summaryrefslogtreecommitdiffstats
path: root/devtools/client/debugger/test/mochitest/shared-head.js
blob: 2466957044bac4241924f45d926d6ed2a38c5b21 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at <http://mozilla.org/MPL/2.0/>. */

/**
 * Helper methods to drive with the debugger during mochitests. This file can be safely
 * required from other panel test files.
 */

"use strict";

/* eslint-disable no-unused-vars */

// We can't use "import globals from head.js" because of bug 1395426.
// So workaround by manually importing the few symbols we are using from it.
// (Note that only ./mach eslint devtools/client fails while devtools/client/debugger passes)
/* global EXAMPLE_URL, ContentTask */

// Assume that shared-head is always imported before this file
/* import-globals-from ../../../shared/test/shared-head.js */

/**
 * Helper method to create a "dbg" context for other tools to use
 */
function createDebuggerContext(toolbox) {
  const panel = toolbox.getPanel("jsdebugger");
  const win = panel.panelWin;

  return {
    ...win.dbg,
    commands: toolbox.commands,
    toolbox,
    win,
    panel,
  };
}

var { Toolbox } = require("devtools/client/framework/toolbox");
const asyncStorage = require("devtools/shared/async-storage");

const {
  getSelectedLocation,
} = require("devtools/client/debugger/src/utils/selected-location");
const {
  createLocation,
} = require("devtools/client/debugger/src/utils/location");

const {
  resetSchemaVersion,
} = require("devtools/client/debugger/src/utils/prefs");

const {
  safeDecodeItemName,
} = require("devtools/client/debugger/src/utils/sources-tree/utils");

const {
  isGeneratedId,
} = require("devtools/client/shared/source-map-loader/index");

const DEBUGGER_L10N = new LocalizationHelper(
  "devtools/client/locales/debugger.properties"
);

/**
 * Waits for `predicate()` to be true. `state` is the redux app state.
 *
 * @memberof mochitest/waits
 * @param {Object} dbg
 * @param {Function} predicate
 * @return {Promise}
 * @static
 */
function waitForState(dbg, predicate, msg) {
  return new Promise(resolve => {
    info(`Waiting for state change: ${msg || ""}`);
    if (predicate(dbg.store.getState())) {
      info(`Finished waiting for state change: ${msg || ""}`);
      resolve();
      return;
    }

    const unsubscribe = dbg.store.subscribe(() => {
      const result = predicate(dbg.store.getState());
      if (result) {
        info(`Finished waiting for state change: ${msg || ""}`);
        unsubscribe();
        resolve(result);
      }
    });
  });
}

/**
 * Waits for sources to be loaded.
 *
 * @memberof mochitest/waits
 * @param {Object} dbg
 * @param {Array} sources
 * @return {Promise}
 * @static
 */
async function waitForSources(dbg, ...sources) {
  if (sources.length === 0) {
    return;
  }

  info(`Waiting on sources: ${sources.join(", ")}`);
  await Promise.all(
    sources.map(url => {
      if (!sourceExists(dbg, url)) {
        return waitForState(
          dbg,
          () => sourceExists(dbg, url),
          `source ${url} exists`
        );
      }
      return Promise.resolve();
    })
  );

  info(`Finished waiting on sources: ${sources.join(", ")}`);
}

/**
 * Waits for a source to be loaded.
 *
 * @memberof mochitest/waits
 * @param {Object} dbg
 * @param {String} source
 * @return {Promise}
 * @static
 */
function waitForSource(dbg, url) {
  return waitForState(
    dbg,
    state => findSource(dbg, url, { silent: true }),
    "source exists"
  );
}

async function waitForElement(dbg, name, ...args) {
  await waitUntil(() => findElement(dbg, name, ...args));
  return findElement(dbg, name, ...args);
}

/**
 * Wait for a count of given elements to be rendered on screen.
 *
 * @param {DebuggerPanel} dbg
 * @param {String} name
 * @param {Integer} count: Number of elements to match. Defaults to 1.
 * @param {Boolean} countStrictlyEqual: When set to true, will wait until the exact number
 *                  of elements is displayed on screen. When undefined or false, will wait
 *                  until there's at least `${count}` elements on screen (e.g. if count
 *                  is 1, it will resolve if there are 2 elements rendered).
 */
async function waitForAllElements(
  dbg,
  name,
  count = 1,
  countStrictlyEqual = false
) {
  await waitUntil(() => {
    const elsCount = findAllElements(dbg, name).length;
    return countStrictlyEqual ? elsCount === count : elsCount >= count;
  });
  return findAllElements(dbg, name);
}

async function waitForElementWithSelector(dbg, selector) {
  await waitUntil(() => findElementWithSelector(dbg, selector));
  return findElementWithSelector(dbg, selector);
}

function waitForRequestsToSettle(dbg) {
  return dbg.commands.client.waitForRequestsToSettle();
}

function assertClass(el, className, exists = true) {
  if (exists) {
    ok(el.classList.contains(className), `${className} class exists`);
  } else {
    ok(!el.classList.contains(className), `${className} class does not exist`);
  }
}

function waitForSelectedLocation(dbg, line, column) {
  return waitForState(dbg, state => {
    const location = dbg.selectors.getSelectedLocation();
    return (
      location &&
      (line ? location.line == line : true) &&
      (column ? location.column == column : true)
    );
  });
}

/**
 * Wait for a given source to be selected and ready.
 *
 * @memberof mochitest/waits
 * @param {Object} dbg
 * @param {null|string|Source} sourceOrUrl Optional. Either a source URL (string) or a source object (typically fetched via `findSource`)
 * @return {Promise}
 * @static
 */
function waitForSelectedSource(dbg, sourceOrUrl) {
  const {
    getSelectedSourceTextContent,
    getSymbols,
    getBreakableLines,
    getSourceActorsForSource,
    getSourceActorBreakableLines,
    getFirstSourceActorForGeneratedSource,
  } = dbg.selectors;

  return waitForState(
    dbg,
    state => {
      const location = dbg.selectors.getSelectedLocation() || {};
      const sourceTextContent = getSelectedSourceTextContent();
      if (!sourceTextContent) {
        return false;
      }

      if (sourceOrUrl) {
        // Second argument is either a source URL (string)
        // or a Source object.
        if (typeof sourceOrUrl == "string") {
          const url = location.source.url;
          if (typeof url != "string" || !url.includes(encodeURI(sourceOrUrl))) {
            return false;
          }
        } else if (location.source.id != sourceOrUrl.id) {
          return false;
        }
      }

      // Wait for symbols/AST to be parsed
      if (!getSymbols(location) && !isWasmBinarySource(location.source)) {
        return false;
      }

      // Finaly wait for breakable lines to be set
      if (location.source.isHTML) {
        // For HTML sources we need to wait for each source actor to be processed.
        // getBreakableLines will return the aggregation without being able to know
        // if that's complete, with all the source actors.
        const sourceActors = getSourceActorsForSource(location.source.id);
        const allSourceActorsProcessed = sourceActors.every(
          sourceActor => !!getSourceActorBreakableLines(sourceActor.id)
        );
        return allSourceActorsProcessed;
      }

      if (!getBreakableLines(location.source.id)) {
        return false;
      }

      // Also ensure that CodeMirror updated its content
      return getCM(dbg).getValue() !== DEBUGGER_L10N.getStr("loadingText");
    },
    "selected source"
  );
}

/**
 * The generated source of WASM source are WASM binary file,
 * which have many broken/disabled features in the debugger.
 *
 * They especially have a very special behavior in CodeMirror
 * where line labels aren't line number, but hex addresses.
 */
function isWasmBinarySource(source) {
  return source.isWasm && !source.isOriginal;
}

function getVisibleSelectedFrameLine(dbg) {
  const frame = dbg.selectors.getVisibleSelectedFrame();
  return frame?.location.line;
}

function getVisibleSelectedFrameColumn(dbg) {
  const frame = dbg.selectors.getVisibleSelectedFrame();
  return frame?.location.column;
}

/**
 * Assert that a given line is breakable or not.
 * Verify that CodeMirror gutter is grayed out via the empty line classname if not breakable.
 */
function assertLineIsBreakable(dbg, file, line, shouldBeBreakable) {
  const lineInfo = getCM(dbg).lineInfo(line - 1);
  const lineText = `${line}| ${lineInfo.text.substring(0, 50)}${
    lineInfo.text.length > 50 ? "…" : ""
  } — in ${file}`;
  // When a line is not breakable, the "empty-line" class is added
  // and the line is greyed out
  if (shouldBeBreakable) {
    ok(
      !lineInfo.wrapClass?.includes("empty-line"),
      `${lineText} should be breakable`
    );
  } else {
    ok(
      lineInfo?.wrapClass?.includes("empty-line"),
      `${lineText} should NOT be breakable`
    );
  }
}

/**
 * Assert that the debugger is highlighting the correct location.
 *
 * @memberof mochitest/asserts
 * @param {Object} dbg
 * @param {String} source
 * @param {Number} line
 * @static
 */
function assertHighlightLocation(dbg, source, line) {
  source = findSource(dbg, source);

  // Check the selected source
  is(
    dbg.selectors.getSelectedSource().url,
    source.url,
    "source url is correct"
  );

  // Check the highlight line
  const lineEl = findElement(dbg, "highlightLine");
  ok(lineEl, "Line is highlighted");

  is(
    findAllElements(dbg, "highlightLine").length,
    1,
    "Only 1 line is highlighted"
  );

  ok(isVisibleInEditor(dbg, lineEl), "Highlighted line is visible");

  const cm = getCM(dbg);
  const lineInfo = cm.lineInfo(line - 1);
  ok(lineInfo.wrapClass.includes("highlight-line"), "Line is highlighted");
}

/**
 * Helper function for assertPausedAtSourceAndLine.
 *
 * Assert that CodeMirror reports to be paused at the given line/column.
 */
function _assertDebugLine(dbg, line, column) {
  const source = dbg.selectors.getSelectedSource();
  // WASM lines are hex addresses which have to be mapped to decimal line number
  if (isWasmBinarySource(source)) {
    line = dbg.wasmOffsetToLine(source.id, line) + 1;
  }

  // Check the debug line
  const lineInfo = getCM(dbg).lineInfo(line - 1);
  const sourceTextContent = dbg.selectors.getSelectedSourceTextContent();
  if (source && !sourceTextContent) {
    const url = source.url;
    ok(
      false,
      `Looks like the source ${url} is still loading. Try adding waitForLoadedSource in the test.`
    );
    return;
  }

  // Scroll the line into view to make sure the content
  // on the line is rendered and in the dom.
  getCM(dbg).scrollIntoView({ line, ch: 0 });

  if (!lineInfo.wrapClass) {
    const pauseLine = getVisibleSelectedFrameLine(dbg);
    ok(false, `Expected pause line on line ${line}, it is on ${pauseLine}`);
    return;
  }

  ok(
    lineInfo?.wrapClass.includes("new-debug-line"),
    `Line ${line} is not highlighted as paused`
  );

  const debugLine =
    findElement(dbg, "debugLine") || findElement(dbg, "debugErrorLine");

  is(
    findAllElements(dbg, "debugLine").length +
      findAllElements(dbg, "debugErrorLine").length,
    1,
    "There is only one line"
  );

  ok(isVisibleInEditor(dbg, debugLine), "debug line is visible");

  const markedSpans = lineInfo.handle.markedSpans;
  if (markedSpans && markedSpans.length && !isWasmBinarySource(source)) {
    const hasExpectedDebugLine = markedSpans.some(
      span =>
        span.marker.className?.includes("debug-expression") &&
        // When a precise column is expected, ensure that we have at least
        // one "debug line" for the column we expect.
        // (See the React Component: DebugLine.setDebugLine)
        (!column || span.from == column)
    );
    ok(
      hasExpectedDebugLine,
      "Got the expected DebugLine. i.e. got the right marker in codemirror visualizing the breakpoint"
    );
  }
  info(`Paused on line ${line}`);
}

/**
 * Make sure the debugger is paused at a certain source ID and line.
 *
 * @param {Object} dbg
 * @param {String} expectedSourceId
 * @param {Number} expectedLine
 * @param {Number} [expectedColumn]
 */
function assertPausedAtSourceAndLine(
  dbg,
  expectedSourceId,
  expectedLine,
  expectedColumn
) {
  // Check that the debugger is paused.
  assertPaused(dbg);

  // Check that the paused location is correctly rendered.
  ok(isSelectedFrameSelected(dbg), "top frame's source is selected");

  // Check the pause location
  const pauseLine = getVisibleSelectedFrameLine(dbg);
  is(
    pauseLine,
    expectedLine,
    "Redux state for currently selected frame's line is correct"
  );
  const pauseColumn = getVisibleSelectedFrameColumn(dbg);
  if (expectedColumn) {
    // `pauseColumn` is 0-based, coming from internal state,
    // while `expectedColumn` is manually passed from test scripts and so is 1-based.
    is(
      pauseColumn + 1,
      expectedColumn,
      "Redux state for currently selected frame's column is correct"
    );
  }
  _assertDebugLine(dbg, pauseLine, pauseColumn);

  ok(isVisibleInEditor(dbg, getCM(dbg).display.gutters), "gutter is visible");

  const frames = dbg.selectors.getCurrentThreadFrames();
  const selectedSource = dbg.selectors.getSelectedSource();

  // WASM support is limited when we are on the generated binary source
  if (isWasmBinarySource(selectedSource)) {
    return;
  }

  ok(frames.length >= 1, "Got at least one frame");

  // Lets make sure we can assert both original and generated file locations when needed
  const { source, line, column } = isGeneratedId(expectedSourceId)
    ? frames[0].generatedLocation
    : frames[0].location;
  is(source.id, expectedSourceId, "Frame has correct source");
  is(
    line,
    expectedLine,
    `Frame paused at line ${line}, but expected line ${expectedLine}`
  );

  if (expectedColumn) {
    // `column` is 0-based, coming from internal state,
    // while `expectedColumn` is manually passed from test scripts and so is 1-based.
    is(
      column + 1,
      expectedColumn,
      `Frame paused at column ${
        column + 1
      }, but expected column ${expectedColumn}`
    );
  }
}

async function waitForThreadCount(dbg, count) {
  return waitForState(
    dbg,
    state => dbg.selectors.getThreads(state).length == count
  );
}

async function waitForLoadedScopes(dbg) {
  const scopes = await waitForElement(dbg, "scopes");
  // Since scopes auto-expand, we can assume they are loaded when there is a tree node
  // with the aria-level attribute equal to "2".
  await waitUntil(() => scopes.querySelector('.tree-node[aria-level="2"]'));
}

function waitForBreakpointCount(dbg, count) {
  return waitForState(
    dbg,
    state => dbg.selectors.getBreakpointCount() == count
  );
}

function waitForBreakpoint(dbg, url, line) {
  return waitForState(dbg, () => findBreakpoint(dbg, url, line));
}

function waitForBreakpointRemoved(dbg, url, line) {
  return waitForState(dbg, () => !findBreakpoint(dbg, url, line));
}

/**
 * Returns boolean for whether the debugger is paused.
 *
 * @param {Object} dbg
 */
function isPaused(dbg) {
  return dbg.selectors.getIsCurrentThreadPaused();
}

/**
 * Assert that the debugger is not currently paused.
 *
 * @param {Object} dbg
 * @param {String} msg
 *        Optional assertion message
 */
function assertNotPaused(dbg, msg = "client is not paused") {
  ok(!isPaused(dbg), msg);
}

/**
 * Assert that the debugger is currently paused.
 *
 * @param {Object} dbg
 */
function assertPaused(dbg, msg = "client is paused") {
  ok(isPaused(dbg), msg);
}

/**
 * Waits for the debugger to be fully paused.
 *
 * @param {Object} dbg
 * @param {String} url
 *        Optional URL of the script we should be pausing on.
 * @param {Object} options
 *         {Boolean} shouldWaitForLoadScopes
 *        When paused in original files with original variable mapping disabled, scopes are
 *        not going to exist, lets not wait for it. defaults to true
 */
async function waitForPaused(
  dbg,
  url,
  options = { shouldWaitForLoadedScopes: true }
) {
  info("Waiting for the debugger to pause");
  const { getSelectedScope, getCurrentThread, getCurrentThreadFrames } =
    dbg.selectors;

  await waitForState(
    dbg,
    state => isPaused(dbg) && !!getSelectedScope(getCurrentThread()),
    "paused"
  );

  await waitForState(dbg, getCurrentThreadFrames, "fetched frames");

  if (options.shouldWaitForLoadedScopes) {
    await waitForLoadedScopes(dbg);
  }
  await waitForSelectedSource(dbg, url);
}

/**
 * Waits for the debugger to resume.
 *
 * @param {Objeect} dbg
 */
function waitForResumed(dbg) {
  info("Waiting for the debugger to resume");
  return waitForState(dbg, state => !dbg.selectors.getIsCurrentThreadPaused());
}

function waitForInlinePreviews(dbg) {
  return waitForState(dbg, () => dbg.selectors.getSelectedInlinePreviews());
}

function waitForCondition(dbg, condition) {
  return waitForState(dbg, state =>
    dbg.selectors
      .getBreakpointsList()
      .find(bp => bp.options.condition == condition)
  );
}

function waitForLog(dbg, logValue) {
  return waitForState(dbg, state =>
    dbg.selectors
      .getBreakpointsList()
      .find(bp => bp.options.logValue == logValue)
  );
}

async function waitForPausedThread(dbg, thread) {
  return waitForState(dbg, state => dbg.selectors.getIsPaused(thread));
}

function isSelectedFrameSelected(dbg, state) {
  const frame = dbg.selectors.getVisibleSelectedFrame();

  // Make sure the source text is completely loaded for the
  // source we are paused in.
  const source = dbg.selectors.getSelectedSource();
  const sourceTextContent = dbg.selectors.getSelectedSourceTextContent();

  if (!source || !sourceTextContent) {
    return false;
  }

  return source.id == frame.location.source.id;
}

/**
 * Checks to see if the frame is selected and the title is correct.
 *
 * @param {Object} dbg
 * @param {Integer} index
 * @param {String} title
 */
function isFrameSelected(dbg, index, title) {
  const $frame = findElement(dbg, "frame", index);

  const {
    selectors: { getSelectedFrame, getCurrentThread },
  } = dbg;

  const frame = getSelectedFrame(getCurrentThread());

  const elSelected = $frame.classList.contains("selected");
  const titleSelected = frame.displayName == title;

  return elSelected && titleSelected;
}

/**
 *  Clear all the debugger related preferences.
 */
async function clearDebuggerPreferences(prefs = []) {
  resetSchemaVersion();
  asyncStorage.clear();
  Services.prefs.clearUserPref("devtools.debugger.alphabetize-outline");
  Services.prefs.clearUserPref("devtools.debugger.pause-on-exceptions");
  Services.prefs.clearUserPref("devtools.debugger.pause-on-caught-exceptions");
  Services.prefs.clearUserPref("devtools.debugger.ignore-caught-exceptions");
  Services.prefs.clearUserPref("devtools.debugger.pending-selected-location");
  Services.prefs.clearUserPref("devtools.debugger.expressions");
  Services.prefs.clearUserPref("devtools.debugger.breakpoints-visible");
  Services.prefs.clearUserPref("devtools.debugger.call-stack-visible");
  Services.prefs.clearUserPref("devtools.debugger.scopes-visible");
  Services.prefs.clearUserPref("devtools.debugger.skip-pausing");

  for (const pref of prefs) {
    await pushPref(...pref);
  }
}

/**
 * Intilializes the debugger.
 *
 * @memberof mochitest
 * @param {String} url
 * @return {Promise} dbg
 * @static
 */

async function initDebugger(url, ...sources) {
  // We depend on EXAMPLE_URLs origin to do cross origin/process iframes via
  // EXAMPLE_REMOTE_URL. If the top level document origin changes,
  // we may break this. So be careful if you want to change EXAMPLE_URL.
  return initDebuggerWithAbsoluteURL(EXAMPLE_URL + url, ...sources);
}

async function initDebuggerWithAbsoluteURL(url, ...sources) {
  await clearDebuggerPreferences();
  const toolbox = await openNewTabAndToolbox(url, "jsdebugger");
  const dbg = createDebuggerContext(toolbox);

  await waitForSources(dbg, ...sources);
  return dbg;
}

async function initPane(url, pane, prefs) {
  await clearDebuggerPreferences(prefs);
  return openNewTabAndToolbox(EXAMPLE_URL + url, pane);
}

/**
 * Returns a source that matches a given filename, or a URL.
 * This also accept a source as input argument, in such case it just returns it.
 *
 * @param {Object} dbg
 * @param {String} filenameOrUrlOrSource
 *        The typical case will be to pass only a filename,
 *        but you may also pass a full URL to match sources without filesnames like data: URL
 *        or pass the source itself, which is just returned.
 * @param {Object} options
 * @param {Boolean} options.silent
 *        If true, won't throw if the source is missing.
 * @return {Object} source
 */
function findSource(
  dbg,
  filenameOrUrlOrSource,
  { silent } = { silent: false }
) {
  if (typeof filenameOrUrlOrSource !== "string") {
    // Support passing in a source object itself all APIs that use this
    // function support both styles
    return filenameOrUrlOrSource;
  }

  const sources = dbg.selectors.getSourceList();
  const source = sources.find(s => {
    // Sources don't have a file name attribute, we need to compute it here:
    const sourceFileName = s.url
      ? safeDecodeItemName(s.url.substring(s.url.lastIndexOf("/") + 1))
      : "";

    // The input argument may either be only the filename, or the complete URL
    // This helps match sources whose URL doesn't contain a filename, like data: URLs
    return (
      sourceFileName == filenameOrUrlOrSource || s.url == filenameOrUrlOrSource
    );
  });

  if (!source) {
    if (silent) {
      return false;
    }

    throw new Error(`Unable to find source: ${filenameOrUrlOrSource}`);
  }

  return source;
}

function findSourceContent(dbg, url, opts) {
  const source = findSource(dbg, url, opts);

  if (!source) {
    return null;
  }
  const content = dbg.selectors.getSettledSourceTextContent(
    createLocation({
      source,
    })
  );

  if (!content) {
    return null;
  }

  if (content.state !== "fulfilled") {
    throw new Error(`Expected loaded source, got${content.value}`);
  }

  return content.value;
}

function sourceExists(dbg, url) {
  return !!findSource(dbg, url, { silent: true });
}

function waitForLoadedSource(dbg, url) {
  return waitForState(
    dbg,
    state => {
      const source = findSource(dbg, url, { silent: true });
      return (
        source &&
        dbg.selectors.getSettledSourceTextContent(
          createLocation({
            source,
          })
        )
      );
    },
    "loaded source"
  );
}

/*
 * Selects the source node for a specific source
 * from the source tree.
 *
 * @param {Object} dbg
 * @param {String} filename - The filename for the specific source
 * @param {Number} sourcePosition - The source node postion in the tree
 * @param {String} message - The info message to display
 */
async function selectSourceFromSourceTree(
  dbg,
  fileName,
  sourcePosition,
  message
) {
  info(message);
  await clickElement(dbg, "sourceNode", sourcePosition);
  await waitForSelectedSource(dbg, fileName);
  await waitFor(
    () => getCM(dbg).getValue() !== `Loading…`,
    "Wait for source to completely load"
  );
}

/*
 * Trigger a context menu in the debugger source tree
 *
 * @param {Object} dbg
 * @param {Obejct} sourceTreeNode - The node in the source tree which the context menu
 *                                  item needs to be triggered on.
 * @param {String} contextMenuItem - The id for the context menu item to be selected
 */
async function triggerSourceTreeContextMenu(
  dbg,
  sourceTreeNode,
  contextMenuItem
) {
  const onContextMenu = waitForContextMenu(dbg);
  rightClickEl(dbg, sourceTreeNode);
  const menupopup = await onContextMenu;
  const onHidden = new Promise(resolve => {
    menupopup.addEventListener("popuphidden", resolve, { once: true });
  });
  selectContextMenuItem(dbg, contextMenuItem);
  await onHidden;
}

/**
 * Selects the source.
 *
 * @memberof mochitest/actions
 * @param {Object} dbg
 * @param {String} url
 * @param {Number} line
 * @param {Number} column
 * @return {Promise}
 * @static
 */
async function selectSource(dbg, url, line, column) {
  const source = findSource(dbg, url);

  await dbg.actions.selectLocation(createLocation({ source, line, column }), {
    keepContext: false,
  });
  return waitForSelectedSource(dbg, source);
}

async function closeTab(dbg, url) {
  await dbg.actions.closeTab(findSource(dbg, url));
}

function countTabs(dbg) {
  return findElement(dbg, "sourceTabs").children.length;
}

/**
 * Steps over.
 *
 * @memberof mochitest/actions
 * @param {Object} dbg
 * @param {Object} pauseOptions
 * @return {Promise}
 * @static
 */
async function stepOver(dbg, pauseOptions) {
  const pauseLine = getVisibleSelectedFrameLine(dbg);
  info(`Stepping over from ${pauseLine}`);
  await dbg.actions.stepOver();
  return waitForPaused(dbg, null, pauseOptions);
}

/**
 * Steps in.
 *
 * @memberof mochitest/actions
 * @param {Object} dbg
 * @return {Promise}
 * @static
 */
async function stepIn(dbg) {
  const pauseLine = getVisibleSelectedFrameLine(dbg);
  info(`Stepping in from ${pauseLine}`);
  await dbg.actions.stepIn();
  return waitForPaused(dbg);
}

/**
 * Steps out.
 *
 * @memberof mochitest/actions
 * @param {Object} dbg
 * @return {Promise}
 * @static
 */
async function stepOut(dbg) {
  const pauseLine = getVisibleSelectedFrameLine(dbg);
  info(`Stepping out from ${pauseLine}`);
  await dbg.actions.stepOut();
  return waitForPaused(dbg);
}

/**
 * Resumes.
 *
 * @memberof mochitest/actions
 * @param {Object} dbg
 * @return {Promise}
 * @static
 */
async function resume(dbg) {
  const pauseLine = getVisibleSelectedFrameLine(dbg);
  info(`Resuming from ${pauseLine}`);
  const onResumed = waitForResumed(dbg);
  await dbg.actions.resume();
  return onResumed;
}

function deleteExpression(dbg, input) {
  info(`Delete expression "${input}"`);
  return dbg.actions.deleteExpression({ input });
}

/**
 * Reloads the debuggee.
 *
 * @memberof mochitest/actions
 * @param {Object} dbg
 * @param {Array} sources
 * @return {Promise}
 * @static
 */
async function reload(dbg, ...sources) {
  await reloadBrowser();
  return waitForSources(dbg, ...sources);
}

// Only use this method when the page is paused by the debugger
// during page load and we navigate away without resuming.
//
// In this particular scenario, the page will never be "loaded".
// i.e. emit DOCUMENT_EVENT's dom-complete
// And consequently, debugger panel won't emit "reloaded" event.
async function reloadWhenPausedBeforePageLoaded(dbg, ...sources) {
  // But we can at least listen for the next DOCUMENT_EVENT's dom-loading,
  // which should be fired even if the page is pause the earliest.
  const { resourceCommand } = dbg.commands;
  const { onResource: onTopLevelDomLoading } =
    await resourceCommand.waitForNextResource(
      resourceCommand.TYPES.DOCUMENT_EVENT,
      {
        ignoreExistingResources: true,
        predicate: resource =>
          resource.targetFront.isTopLevel && resource.name === "dom-loading",
      }
    );

  gBrowser.reloadTab(gBrowser.selectedTab);

  info("Wait for DOCUMENT_EVENT dom-loading after reload");
  await onTopLevelDomLoading;
  return waitForSources(dbg, ...sources);
}

/**
 * Navigates the debuggee to another url.
 *
 * @memberof mochitest/actions
 * @param {Object} dbg
 * @param {String} url
 * @param {Array} sources
 * @return {Promise}
 * @static
 */
async function navigate(dbg, url, ...sources) {
  return navigateToAbsoluteURL(dbg, EXAMPLE_URL + url, ...sources);
}

/**
 * Navigates the debuggee to another absolute url.
 *
 * @memberof mochitest/actions
 * @param {Object} dbg
 * @param {String} url
 * @param {Array} sources
 * @return {Promise}
 * @static
 */
async function navigateToAbsoluteURL(dbg, url, ...sources) {
  await navigateTo(url);
  return waitForSources(dbg, ...sources);
}

function getFirstBreakpointColumn(dbg, source, line) {
  const position = dbg.selectors.getFirstBreakpointPosition(
    createLocation({
      line,
      source,
    })
  );

  return getSelectedLocation(position, source).column;
}

function isMatchingLocation(location1, location2) {
  return (
    location1?.source.id == location2?.source.id &&
    location1?.line == location2?.line &&
    location1?.column == location2?.column
  );
}

function getBreakpointForLocation(dbg, location) {
  if (!location) {
    return undefined;
  }

  const isGeneratedSource = isGeneratedId(location.source.id);
  return dbg.selectors.getBreakpointsList().find(bp => {
    const loc = isGeneratedSource ? bp.generatedLocation : bp.location;
    return isMatchingLocation(loc, location);
  });
}

/**
 * Adds a breakpoint to a source at line/col.
 *
 * @memberof mochitest/actions
 * @param {Object} dbg
 * @param {String} source
 * @param {Number} line
 * @param {Number} col
 * @return {Promise}
 * @static
 */
async function addBreakpoint(dbg, source, line, column, options) {
  source = findSource(dbg, source);
  const bpCount = dbg.selectors.getBreakpointCount();
  const onBreakpoint = waitForDispatch(dbg.store, "SET_BREAKPOINT");
  await dbg.actions.addBreakpoint(
    // column is 0-based internally, but tests are using 1-based.
    createLocation({ source, line, column: column - 1 }),
    options
  );
  await onBreakpoint;
  is(
    dbg.selectors.getBreakpointCount(),
    bpCount + 1,
    "a new breakpoint was created"
  );
}

/**
 * Similar to `addBreakpoint`, but uses the UI instead or calling
 * the actions directly. This only support breakpoint on lines,
 * not on a specific column.
 */
async function addBreakpointViaGutter(dbg, line) {
  info(`Add breakpoint via the editor on line ${line}`);
  await clickGutter(dbg, line);
  return waitForDispatch(dbg.store, "SET_BREAKPOINT");
}

function disableBreakpoint(dbg, source, line, column) {
  if (column === 0) {
    throw new Error("disableBreakpoint expect a 1-based column argument");
  }
  // `internalColumn` is 0-based internally, while `column` manually defined in test scripts is 1-based.
  const internalColumn = column
    ? column - 1
    : getFirstBreakpointColumn(dbg, source, line);
  const location = createLocation({
    source,
    line,
    column: internalColumn,
  });
  const bp = getBreakpointForLocation(dbg, location);
  return dbg.actions.disableBreakpoint(bp);
}

function findBreakpoint(dbg, url, line) {
  const source = findSource(dbg, url);
  return dbg.selectors.getBreakpointsForSource(source, line)[0];
}

// helper for finding column breakpoints.
function findColumnBreakpoint(dbg, url, line, column) {
  const source = findSource(dbg, url);
  const lineBreakpoints = dbg.selectors.getBreakpointsForSource(source, line);

  return lineBreakpoints.find(bp => {
    return source.isOriginal
      ? bp.location.column === column
      : bp.generatedLocation.column === column;
  });
}

async function loadAndAddBreakpoint(dbg, filename, line, column) {
  const {
    selectors: { getBreakpoint, getBreakpointCount, getBreakpointsMap },
  } = dbg;

  await waitForSources(dbg, filename);

  ok(true, "Original sources exist");
  const source = findSource(dbg, filename);

  await selectSource(dbg, source);

  // Test that breakpoint is not off by a line.
  await addBreakpoint(dbg, source, line, column);

  is(getBreakpointCount(), 1, "One breakpoint exists");
  // column is 0-based internally, but tests are using 1-based.
  if (!getBreakpoint(createLocation({ source, line, column: column - 1 }))) {
    const breakpoints = getBreakpointsMap();
    const id = Object.keys(breakpoints).pop();
    const loc = breakpoints[id].location;
    ok(
      false,
      `Breakpoint has correct line ${line}, column ${column}, but was line ${
        loc.line
      } column ${loc.column + 1}`
    );
  }

  return source;
}

async function invokeWithBreakpoint(
  dbg,
  fnName,
  filename,
  { line, column },
  handler,
  pauseOptions
) {
  const source = await loadAndAddBreakpoint(dbg, filename, line, column);

  const invokeResult = invokeInTab(fnName);

  const invokeFailed = await Promise.race([
    waitForPaused(dbg, null, pauseOptions),
    invokeResult.then(
      () => new Promise(() => {}),
      () => true
    ),
  ]);

  if (invokeFailed) {
    await invokeResult;
    return;
  }

  assertPausedAtSourceAndLine(dbg, findSource(dbg, filename).id, line, column);

  await removeBreakpoint(dbg, source.id, line, column);

  is(dbg.selectors.getBreakpointCount(), 0, "Breakpoint reverted");

  await handler(source);

  await resume(dbg);

  // eslint-disable-next-line max-len
  // If the invoke errored later somehow, capture here so the error is reported nicely.
  await invokeResult;
}

function prettyPrint(dbg) {
  const source = dbg.selectors.getSelectedSource();
  return dbg.actions.prettyPrintAndSelectSource(source);
}

async function expandAllScopes(dbg) {
  const scopes = await waitForElement(dbg, "scopes");
  const scopeElements = scopes.querySelectorAll(
    '.tree-node[aria-level="1"][data-expandable="true"]:not([aria-expanded="true"])'
  );
  const indices = Array.from(scopeElements, el => {
    return Array.prototype.indexOf.call(el.parentNode.childNodes, el);
  }).reverse();

  for (const index of indices) {
    await toggleScopeNode(dbg, index + 1);
  }
}

async function assertScopes(dbg, items) {
  await expandAllScopes(dbg);

  for (const [i, val] of items.entries()) {
    if (Array.isArray(val)) {
      is(getScopeNodeLabel(dbg, i + 1), val[0]);
      is(
        getScopeNodeValue(dbg, i + 1),
        val[1],
        `"${val[0]}" has the expected "${val[1]}" value`
      );
    } else {
      is(getScopeNodeLabel(dbg, i + 1), val);
    }
  }

  is(getScopeNodeLabel(dbg, items.length + 1), "Window");
}

function findSourceTreeThreadByName(dbg, name) {
  return [...findAllElements(dbg, "sourceTreeThreads")].find(el => {
    return el.textContent.includes(name);
  });
}

function findSourceNodeWithText(dbg, text) {
  return [...findAllElements(dbg, "sourceNodes")].find(el => {
    return el.textContent.includes(text);
  });
}

/**
 * Assert the icon type used in the SourceTree for a given source
 *
 * @param {Object} dbg
 * @param {String} sourceName
 *        Name of the source displayed in the source tree
 * @param {String} icon
 *        Expected icon CSS classname
 */
function assertSourceIcon(dbg, sourceName, icon) {
  const sourceItem = findSourceNodeWithText(dbg, sourceName);
  ok(sourceItem, `Found the source item for ${sourceName}`);
  is(
    sourceItem.querySelector(".source-icon").className,
    `img source-icon ${icon}`,
    `The icon for ${sourceName} is correct`
  );
}

async function expandSourceTree(dbg) {
  // Click on expand all context menu for all top level "expandable items".
  // If there is no project root, it will be thread items.
  // But when there is a project root, it can be directory or group items.
  // Select only expandable in order to ignore source items.
  for (const rootNode of dbg.win.document.querySelectorAll(
    ".sources-list > .tree > .tree-node[data-expandable=true]"
  )) {
    await expandAllSourceNodes(dbg, rootNode);
  }
}

async function expandAllSourceNodes(dbg, treeNode) {
  return triggerSourceTreeContextMenu(dbg, treeNode, "#node-menu-expand-all");
}

/**
 * Removes a breakpoint from a source at line/col.
 *
 * @memberof mochitest/actions
 * @param {Object} dbg
 * @param {String} source
 * @param {Number} line
 * @param {Number} col
 * @return {Promise}
 * @static
 */
function removeBreakpoint(dbg, sourceId, line, column) {
  const source = dbg.selectors.getSource(sourceId);
  // column is 0-based internally, but tests are using 1-based.
  column = column ? column - 1 : getFirstBreakpointColumn(dbg, source, line);
  const location = createLocation({
    source,
    line,
    column,
  });
  const bp = getBreakpointForLocation(dbg, location);
  return dbg.actions.removeBreakpoint(bp);
}

/**
 * Toggles the Pause on exceptions feature in the debugger.
 *
 * @memberof mochitest/actions
 * @param {Object} dbg
 * @param {Boolean} pauseOnExceptions
 * @param {Boolean} pauseOnCaughtExceptions
 * @return {Promise}
 * @static
 */
async function togglePauseOnExceptions(
  dbg,
  pauseOnExceptions,
  pauseOnCaughtExceptions
) {
  return dbg.actions.pauseOnExceptions(
    pauseOnExceptions,
    pauseOnCaughtExceptions
  );
}

// Helpers

/**
 * Invokes a global function in the debuggee tab.
 *
 * @memberof mochitest/helpers
 * @param {String} fnc The name of a global function on the content window to
 *                     call. This is applied to structured clones of the
 *                     remaining arguments to invokeInTab.
 * @param {Any} ...args Remaining args to serialize and pass to fnc.
 * @return {Promise}
 * @static
 */
function invokeInTab(fnc, ...args) {
  info(`Invoking in tab: ${fnc}(${args.map(uneval).join(",")})`);
  return ContentTask.spawn(gBrowser.selectedBrowser, { fnc, args }, options =>
    content.wrappedJSObject[options.fnc](...options.args)
  );
}

function clickElementInTab(selector) {
  info(`click element ${selector} in tab`);

  return SpecialPowers.spawn(
    gBrowser.selectedBrowser,
    [selector],
    function (_selector) {
      const element = content.document.querySelector(_selector);
      // Run the click in another event loop in order to immediately resolve spawn's promise.
      // Otherwise if we pause on click and navigate, the JSWindowActor used by spawn will
      // be destroyed while its query is still pending. And this would reject the promise.
      content.setTimeout(() => {
        element.click();
      });
    }
  );
}

const isLinux = Services.appinfo.OS === "Linux";
const isMac = Services.appinfo.OS === "Darwin";
const cmdOrCtrl = isMac ? { metaKey: true } : { ctrlKey: true };
const shiftOrAlt = isMac
  ? { accelKey: true, shiftKey: true }
  : { accelKey: true, altKey: true };

const cmdShift = isMac
  ? { accelKey: true, shiftKey: true, metaKey: true }
  : { accelKey: true, shiftKey: true, ctrlKey: true };

// On Mac, going to beginning/end only works with meta+left/right.  On
// Windows, it only works with home/end.  On Linux, apparently, either
// ctrl+left/right or home/end work.
const endKey = isMac
  ? { code: "VK_RIGHT", modifiers: cmdOrCtrl }
  : { code: "VK_END" };
const startKey = isMac
  ? { code: "VK_LEFT", modifiers: cmdOrCtrl }
  : { code: "VK_HOME" };

const keyMappings = {
  close: { code: "w", modifiers: cmdOrCtrl },
  commandKeyDown: { code: "VK_META", modifiers: { type: "keydown" } },
  commandKeyUp: { code: "VK_META", modifiers: { type: "keyup" } },
  debugger: { code: "s", modifiers: shiftOrAlt },
  // test conditional panel shortcut
  toggleCondPanel: { code: "b", modifiers: cmdShift },
  inspector: { code: "c", modifiers: shiftOrAlt },
  quickOpen: { code: "p", modifiers: cmdOrCtrl },
  quickOpenFunc: { code: "o", modifiers: cmdShift },
  quickOpenLine: { code: ":", modifiers: cmdOrCtrl },
  fileSearch: { code: "f", modifiers: cmdOrCtrl },
  projectSearch: { code: "f", modifiers: cmdShift },
  fileSearchNext: { code: "g", modifiers: { metaKey: true } },
  fileSearchPrev: { code: "g", modifiers: cmdShift },
  goToLine: { code: "g", modifiers: { ctrlKey: true } },
  Enter: { code: "VK_RETURN" },
  ShiftEnter: { code: "VK_RETURN", modifiers: { shiftKey: true } },
  AltEnter: {
    code: "VK_RETURN",
    modifiers: { altKey: true },
  },
  Up: { code: "VK_UP" },
  Down: { code: "VK_DOWN" },
  Right: { code: "VK_RIGHT" },
  Left: { code: "VK_LEFT" },
  End: endKey,
  Start: startKey,
  Tab: { code: "VK_TAB" },
  Escape: { code: "VK_ESCAPE" },
  Delete: { code: "VK_DELETE" },
  pauseKey: { code: "VK_F8" },
  resumeKey: { code: "VK_F8" },
  stepOverKey: { code: "VK_F10" },
  stepInKey: { code: "VK_F11" },
  stepOutKey: {
    code: "VK_F11",
    modifiers: { shiftKey: true },
  },
  Backspace: { code: "VK_BACK_SPACE" },
};

/**
 * Simulates a key press in the debugger window.
 *
 * @memberof mochitest/helpers
 * @param {Object} dbg
 * @param {String} keyName
 * @return {Promise}
 * @static
 */
function pressKey(dbg, keyName) {
  const keyEvent = keyMappings[keyName];
  const { code, modifiers } = keyEvent;
  info(`The ${keyName} key is pressed`);
  return EventUtils.synthesizeKey(code, modifiers || {}, dbg.win);
}

function type(dbg, string) {
  string.split("").forEach(char => EventUtils.synthesizeKey(char, {}, dbg.win));
}

/*
 * Checks to see if the inner element is visible inside the editor.
 *
 * @memberof mochitest/helpers
 * @param {Object} dbg
 * @param {HTMLElement} inner element
 * @return {boolean}
 * @static
 */

function isVisibleInEditor(dbg, element) {
  return isVisible(findElement(dbg, "codeMirror"), element);
}

/*
 * Checks to see if the inner element is visible inside the
 * outer element.
 *
 * Note, the inner element does not need to be entirely visible,
 * it is possible for it to be somewhat clipped by the outer element's
 * bounding element or for it to span the entire length, starting before the
 * outer element and ending after.
 *
 * @memberof mochitest/helpers
 * @param {HTMLElement} outer element
 * @param {HTMLElement} inner element
 * @return {boolean}
 * @static
 */
function isVisible(outerEl, innerEl) {
  if (!innerEl || !outerEl) {
    return false;
  }

  const innerRect = innerEl.getBoundingClientRect();
  const outerRect = outerEl.getBoundingClientRect();

  const verticallyVisible =
    innerRect.top >= outerRect.top ||
    innerRect.bottom <= outerRect.bottom ||
    (innerRect.top < outerRect.top && innerRect.bottom > outerRect.bottom);

  const horizontallyVisible =
    innerRect.left >= outerRect.left ||
    innerRect.right <= outerRect.right ||
    (innerRect.left < outerRect.left && innerRect.right > outerRect.right);

  const visible = verticallyVisible && horizontallyVisible;
  return visible;
}

async function getEditorLineGutter(dbg, line) {
  const lineEl = await getEditorLineEl(dbg, line);
  return lineEl.firstChild;
}

async function getEditorLineEl(dbg, line) {
  let el = await codeMirrorGutterElement(dbg, line);
  while (el && !el.matches(".CodeMirror-code > div")) {
    el = el.parentElement;
  }

  return el;
}

/**
 * Opens the debugger editor context menu in either codemirror or the
 * the debugger gutter.
 * @param {Object} dbg
 * @param {String} elementName
 *                  The element to select
 * @param {Number} line
 *                  The line to open the context menu on.
 */
async function openContextMenuInDebugger(dbg, elementName, line) {
  const waitForOpen = waitForContextMenu(dbg);
  info(`Open ${elementName} context menu on line ${line || ""}`);
  rightClickElement(dbg, elementName, line);
  return waitForOpen;
}

/**
 * Select a range of lines in the editor and open the contextmenu
 * @param {Object} dbg
 * @param {Object} lines
 * @returns
 */
async function selectEditorLinesAndOpenContextMenu(dbg, lines) {
  const { startLine, endLine } = lines;
  const elementName = "line";
  if (!endLine) {
    await clickElement(dbg, elementName, startLine);
  } else {
    getCM(dbg).setSelection(
      { line: startLine - 1, ch: 0 },
      { line: endLine, ch: 0 }
    );
  }
  return openContextMenuInDebugger(dbg, elementName, startLine);
}

/**
 * Asserts that the styling for ignored lines are applied
 * @param {Object} dbg
 * @param {Object} options
 *                 lines {null | Number[]} [lines] Line(s) to assert.
 *                   - If null is passed, the assertion is on all the blackboxed lines
 *                   - If an array of one item (start line) is passed, the assertion is on the specified line
 *                   - If an array (start and end lines) is passed, the assertion is on the multiple lines seelected
 *                 hasBlackboxedLinesClass
 *                   If `true` assert that style exist, else assert that style does not exist
 */
function assertIgnoredStyleInSourceLines(
  dbg,
  { lines, hasBlackboxedLinesClass }
) {
  if (lines) {
    let currentLine = lines[0];
    do {
      const element = findElement(dbg, "line", currentLine);
      const hasStyle = hasBlackboxedLinesClass
        ? element.parentNode.classList.contains("blackboxed-line")
        : !element.parentNode.classList.contains("blackboxed-line");
      ok(
        hasStyle,
        `Line ${currentLine} ${
          hasBlackboxedLinesClass ? "does not have" : "has"
        } ignored styling`
      );
      currentLine = currentLine + 1;
    } while (currentLine <= lines[1]);
  } else {
    const codeLines = findAllElementsWithSelector(
      dbg,
      ".CodeMirror-code .CodeMirror-line"
    );
    const blackboxedLines = findAllElementsWithSelector(
      dbg,
      ".CodeMirror-code .blackboxed-line"
    );
    is(
      hasBlackboxedLinesClass ? codeLines.length : 0,
      blackboxedLines.length,
      `${blackboxedLines.length} of ${codeLines.length} lines are blackboxed`
    );
  }
}

/**
 * Assert the text content on the line matches what is
 * expected.
 *
 * @param {Object} dbg
 * @param {Number} line
 * @param {String} expectedTextContent
 */
function assertTextContentOnLine(dbg, line, expectedTextContent) {
  const lineInfo = getCM(dbg).lineInfo(line - 1);
  const textContent = lineInfo.text.trim();
  is(textContent, expectedTextContent, `Expected text content on line ${line}`);
}

/*
 * Assert that no breakpoint is set on a given line of
 * the currently selected source in the editor.
 *
 * @memberof mochitest/helpers
 * @param {Object} dbg
 * @param {Number} line Line where to check for a breakpoint in the editor
 * @static
 */
async function assertNoBreakpoint(dbg, line) {
  const el = await getEditorLineEl(dbg, line);

  const exists = !!el.querySelector(".new-breakpoint");
  ok(!exists, `Breakpoint doesn't exists on line ${line}`);
}

/*
 * Assert that a regular breakpoint is set in the currently
 * selected source in the editor. (no conditional, nor log breakpoint)
 *
 * @memberof mochitest/helpers
 * @param {Object} dbg
 * @param {Number} line Line where to check for a breakpoint
 * @static
 */
async function assertBreakpoint(dbg, line) {
  const el = await getEditorLineEl(dbg, line);

  const exists = !!el.querySelector(".new-breakpoint");
  ok(exists, `Breakpoint exists on line ${line}`);

  const hasConditionClass = el.classList.contains("has-condition");

  ok(
    !hasConditionClass,
    `Regular breakpoint doesn't have condition on line ${line}`
  );

  const hasLogClass = el.classList.contains("has-log");

  ok(!hasLogClass, `Regular breakpoint doesn't have log on line ${line}`);
}

/*
 * Assert that a conditionnal breakpoint is set.
 *
 * @memberof mochitest/helpers
 * @param {Object} dbg
 * @param {Number} line Line where to check for a breakpoint
 * @static
 */
async function assertConditionBreakpoint(dbg, line) {
  const el = await getEditorLineEl(dbg, line);

  const exists = !!el.querySelector(".new-breakpoint");
  ok(exists, `Breakpoint exists on line ${line}`);

  const hasConditionClass = el.classList.contains("has-condition");

  ok(hasConditionClass, `Conditional breakpoint on line ${line}`);

  const hasLogClass = el.classList.contains("has-log");

  ok(
    !hasLogClass,
    `Conditional breakpoint doesn't have log breakpoint on line ${line}`
  );
}

/*
 * Assert that a log breakpoint is set.
 *
 * @memberof mochitest/helpers
 * @param {Object} dbg
 * @param {Number} line Line where to check for a breakpoint
 * @static
 */
async function assertLogBreakpoint(dbg, line) {
  const el = await getEditorLineEl(dbg, line);

  const exists = !!el.querySelector(".new-breakpoint");
  ok(exists, `Breakpoint exists on line ${line}`);

  const hasConditionClass = el.classList.contains("has-condition");

  ok(
    !hasConditionClass,
    `Log breakpoint doesn't have condition on line ${line}`
  );

  const hasLogClass = el.classList.contains("has-log");

  ok(hasLogClass, `Log breakpoint on line ${line}`);
}

function assertBreakpointSnippet(dbg, index, expectedSnippet) {
  const actualSnippet = findElement(dbg, "breakpointLabel", 2).innerText;
  is(actualSnippet, expectedSnippet, `Breakpoint ${index} snippet`);
}

const selectors = {
  callStackHeader: ".call-stack-pane ._header .header-label",
  callStackBody: ".call-stack-pane .pane",
  domMutationItem: ".dom-mutation-list li",
  expressionNode: i =>
    `.expressions-list .expression-container:nth-child(${i}) .object-label`,
  expressionValue: i =>
    // eslint-disable-next-line max-len
    `.expressions-list .expression-container:nth-child(${i}) .object-delimiter + *`,
  expressionClose: i =>
    `.expressions-list .expression-container:nth-child(${i}) .close`,
  expressionInput: ".watch-expressions-pane input.input-expression",
  expressionNodes: ".expressions-list .tree-node",
  expressionPlus: ".watch-expressions-pane button.plus",
  expressionRefresh: ".watch-expressions-pane button.refresh",
  expressionsHeader: ".watch-expressions-pane ._header .header-label",
  scopesHeader: ".scopes-pane ._header .header-label",
  breakpointItem: i => `.breakpoints-list div:nth-of-type(${i})`,
  breakpointLabel: i => `${selectors.breakpointItem(i)} .breakpoint-label`,
  breakpointHeadings: ".breakpoints-list .breakpoint-heading",
  breakpointItems: ".breakpoints-list .breakpoint",
  breakpointContextMenu: {
    disableSelf: "#node-menu-disable-self",
    disableAll: "#node-menu-disable-all",
    disableOthers: "#node-menu-disable-others",
    enableSelf: "#node-menu-enable-self",
    enableOthers: "#node-menu-enable-others",
    disableDbgStatement: "#node-menu-disable-dbgStatement",
    enableDbgStatement: "#node-menu-enable-dbgStatement",
    remove: "#node-menu-delete-self",
    removeOthers: "#node-menu-delete-other",
    removeCondition: "#node-menu-remove-condition",
  },
  editorContextMenu: {
    continueToHere: "#node-menu-continue-to-here",
  },
  columnBreakpoints: ".column-breakpoint",
  scopes: ".scopes-list",
  scopeNodes: ".scopes-list .object-label",
  scopeNode: i => `.scopes-list .tree-node:nth-child(${i}) .object-label`,
  scopeValue: i =>
    `.scopes-list .tree-node:nth-child(${i}) .object-delimiter + *`,
  mapScopesCheckbox: ".map-scopes-header input",
  frame: i => `.frames [role="list"] [role="listitem"]:nth-child(${i})`,
  frames: '.frames [role="list"] [role="listitem"]',
  gutter: i => `.CodeMirror-code *:nth-child(${i}) .CodeMirror-linenumber`,
  line: i => `.CodeMirror-code div:nth-child(${i}) .CodeMirror-line`,
  addConditionItem:
    "#node-menu-add-condition, #node-menu-add-conditional-breakpoint",
  editConditionItem:
    "#node-menu-edit-condition, #node-menu-edit-conditional-breakpoint",
  addLogItem: "#node-menu-add-log-point",
  editLogItem: "#node-menu-edit-log-point",
  disableItem: "#node-menu-disable-breakpoint",
  menuitem: i => `menupopup menuitem:nth-child(${i})`,
  pauseOnExceptions: ".pause-exceptions",
  breakpoint: ".CodeMirror-code > .new-breakpoint",
  highlightLine: ".CodeMirror-code > .highlight-line",
  debugLine: ".new-debug-line",
  debugErrorLine: ".new-debug-line-error",
  codeMirror: ".CodeMirror",
  resume: ".resume.active",
  pause: ".pause.active",
  sourceTabs: ".source-tabs",
  activeTab: ".source-tab.active",
  stepOver: ".stepOver.active",
  stepOut: ".stepOut.active",
  stepIn: ".stepIn.active",
  trace: ".debugger-trace-menu-button",
  prettyPrintButton: ".source-footer .prettyPrint",
  mappedSourceLink: ".source-footer .mapped-source",
  sourcesFooter: ".sources-panel .source-footer",
  editorFooter: ".editor-pane .source-footer",
  sourceNode: i => `.sources-list .tree-node:nth-child(${i}) .node`,
  sourceNodes: ".sources-list .tree-node",
  sourceTreeThreads: '.sources-list .tree-node[aria-level="1"]',
  sourceTreeThreadsNodes:
    '.sources-list .tree-node[aria-level="1"] > .node > span:nth-child(1)',
  sourceTreeFiles: ".sources-list .tree-node[data-expandable=false]",
  threadSourceTree: i => `.threads-list .sources-pane:nth-child(${i})`,
  threadSourceTreeSourceNode: (i, j) =>
    `${selectors.threadSourceTree(i)} .tree-node:nth-child(${j}) .node`,
  sourceDirectoryLabel: i => `.sources-list .tree-node:nth-child(${i}) .label`,
  resultItems: ".result-list .result-item",
  resultItemName: (name, i) =>
    `${selectors.resultItems}:nth-child(${i})[title$="${name}"]`,
  fileMatch: ".project-text-search .line-value",
  popup: ".popover",
  previewPopup: ".preview-popup",
  openInspector: "button.open-inspector",
  outlineItem: i =>
    `.outline-list__element:nth-child(${i}) .function-signature`,
  outlineItems: ".outline-list__element",
  conditionalPanel: ".conditional-breakpoint-panel",
  conditionalPanelInput: ".conditional-breakpoint-panel textarea",
  conditionalBreakpointInSecPane: ".breakpoint.is-conditional",
  logPointPanel: ".conditional-breakpoint-panel.log-point",
  logPointInSecPane: ".breakpoint.is-log",
  searchField: ".search-field",
  blackbox: ".action.black-box",
  projectSearchSearchInput: ".project-text-search .search-field input",
  projectSearchCollapsed: ".project-text-search .arrow:not(.expanded)",
  projectSearchExpandedResults: ".project-text-search .result",
  projectSearchFileResults: ".project-text-search .file-result",
  projectSearchModifiersCaseSensitive:
    ".project-text-search button.case-sensitive-btn",
  projectSearchModifiersRegexMatch:
    ".project-text-search button.regex-match-btn",
  projectSearchModifiersWholeWordMatch:
    ".project-text-search button.whole-word-btn",
  projectSearchRefreshButton: ".project-text-search button.refresh-btn",
  threadsPaneItems: ".threads-pane .thread",
  threadsPaneItem: i => `.threads-pane .thread:nth-child(${i})`,
  threadsPaneItemPause: i => `${selectors.threadsPaneItem(i)}.paused`,
  CodeMirrorLines: ".CodeMirror-lines",
  inlinePreviewLabels: ".inline-preview .inline-preview-label",
  inlinePreviewValues: ".inline-preview .inline-preview-value",
  inlinePreviewOpenInspector: ".inline-preview-value button.open-inspector",
  watchpointsSubmenu: "#node-menu-watchpoints",
  addGetWatchpoint: "#node-menu-add-get-watchpoint",
  addSetWatchpoint: "#node-menu-add-set-watchpoint",
  removeWatchpoint: "#node-menu-remove-watchpoint",
  logEventsCheckbox: ".events-header input",
  previewPopupInvokeGetterButton: ".preview-popup .invoke-getter",
  previewPopupObjectNumber: ".preview-popup .objectBox-number",
  previewPopupObjectObject: ".preview-popup .objectBox-object",
  sourceTreeRootNode: ".sources-panel .node .window",
  sourceTreeFolderNode: ".sources-panel .node .folder",
  excludePatternsInput: ".project-text-search .exclude-patterns-field input",
  fileSearchInput: ".search-bar input",
  watchExpressionsHeader: ".watch-expressions-pane ._header .header-label",
  watchExpressionsAddButton: ".watch-expressions-pane ._header .plus",
  editorNotificationFooter: ".editor-notification-footer",
};

function getSelector(elementName, ...args) {
  let selector = selectors[elementName];
  if (!selector) {
    throw new Error(`The selector ${elementName} is not defined`);
  }

  if (typeof selector == "function") {
    selector = selector(...args);
  }

  return selector;
}

function findElement(dbg, elementName, ...args) {
  const selector = getSelector(elementName, ...args);
  return findElementWithSelector(dbg, selector);
}

function findElementWithSelector(dbg, selector) {
  return dbg.win.document.querySelector(selector);
}

function findAllElements(dbg, elementName, ...args) {
  const selector = getSelector(elementName, ...args);
  return findAllElementsWithSelector(dbg, selector);
}

function findAllElementsWithSelector(dbg, selector) {
  return dbg.win.document.querySelectorAll(selector);
}

function getSourceNodeLabel(dbg, index) {
  return findElement(dbg, "sourceNode", index)
    .textContent.trim()
    .replace(/^[\s\u200b]*/g, "");
}

/**
 * Simulates a mouse click in the debugger DOM.
 *
 * @memberof mochitest/helpers
 * @param {Object} dbg
 * @param {String} elementName
 * @param {Array} args
 * @return {Promise}
 * @static
 */
async function clickElement(dbg, elementName, ...args) {
  const selector = getSelector(elementName, ...args);
  const el = await waitForElementWithSelector(dbg, selector);

  el.scrollIntoView();

  return clickElementWithSelector(dbg, selector);
}

function clickElementWithSelector(dbg, selector) {
  clickDOMElement(dbg, findElementWithSelector(dbg, selector));
}

function clickDOMElement(dbg, element, options = {}) {
  EventUtils.synthesizeMouseAtCenter(element, options, dbg.win);
}

function dblClickElement(dbg, elementName, ...args) {
  const selector = getSelector(elementName, ...args);

  return EventUtils.synthesizeMouseAtCenter(
    findElementWithSelector(dbg, selector),
    { clickCount: 2 },
    dbg.win
  );
}

function clickElementWithOptions(dbg, elementName, options, ...args) {
  const selector = getSelector(elementName, ...args);
  const el = findElementWithSelector(dbg, selector);
  el.scrollIntoView();

  return EventUtils.synthesizeMouseAtCenter(el, options, dbg.win);
}

function altClickElement(dbg, elementName, ...args) {
  return clickElementWithOptions(dbg, elementName, { altKey: true }, ...args);
}

function shiftClickElement(dbg, elementName, ...args) {
  return clickElementWithOptions(dbg, elementName, { shiftKey: true }, ...args);
}

function rightClickElement(dbg, elementName, ...args) {
  const selector = getSelector(elementName, ...args);
  const doc = dbg.win.document;
  return rightClickEl(dbg, doc.querySelector(selector));
}

function rightClickEl(dbg, el) {
  const doc = dbg.win.document;
  el.scrollIntoView();
  EventUtils.synthesizeMouseAtCenter(el, { type: "contextmenu" }, dbg.win);
}

async function clearElement(dbg, elementName) {
  await clickElement(dbg, elementName);
  await pressKey(dbg, "End");
  const selector = getSelector(elementName);
  const el = findElementWithSelector(dbg, getSelector(elementName));
  let len = el.value.length;
  while (len) {
    pressKey(dbg, "Backspace");
    len--;
  }
}

async function clickGutter(dbg, line) {
  const el = await codeMirrorGutterElement(dbg, line);
  clickDOMElement(dbg, el);
}

async function cmdClickGutter(dbg, line) {
  const el = await codeMirrorGutterElement(dbg, line);
  clickDOMElement(dbg, el, cmdOrCtrl);
}

function findContextMenu(dbg, selector) {
  // the context menu is in the toolbox window
  const doc = dbg.toolbox.topDoc;

  // there are several context menus, we want the one with the menu-api
  const popup = doc.querySelector('menupopup[menu-api="true"]');

  return popup.querySelector(selector);
}

// Waits for the context menu to exist and to fully open. Once this function
// completes, selectContextMenuItem can be called.
// waitForContextMenu must be called after menu opening has been triggered, e.g.
// after synthesizing a right click / contextmenu event.
async function waitForContextMenu(dbg) {
  // the context menu is in the toolbox window
  const doc = dbg.toolbox.topDoc;

  // there are several context menus, we want the one with the menu-api
  const popup = await waitFor(() =>
    doc.querySelector('menupopup[menu-api="true"]')
  );

  if (popup.state == "open") {
    return popup;
  }

  await new Promise(resolve => {
    popup.addEventListener("popupshown", () => resolve(), { once: true });
  });

  return popup;
}

/**
 * Closes and open context menu popup.
 *
 * @memberof mochitest/helpers
 * @param {Object} dbg
 * @param {String} popup - The currently opened popup returned by
 *                         `waitForContextMenu`.
 * @return {Promise}
 */

async function closeContextMenu(dbg, popup) {
  const onHidden = new Promise(resolve => {
    popup.addEventListener("popuphidden", resolve, { once: true });
  });
  popup.hidePopup();
  return onHidden;
}

function selectContextMenuItem(dbg, selector) {
  const item = findContextMenu(dbg, selector);
  item.closest("menupopup").activateItem(item);
}

async function openContextMenuSubmenu(dbg, selector) {
  const item = findContextMenu(dbg, selector);
  const popup = item.menupopup;
  const popupshown = new Promise(resolve => {
    popup.addEventListener("popupshown", () => resolve(), { once: true });
  });
  item.openMenu(true);
  await popupshown;
  return popup;
}

async function assertContextMenuLabel(dbg, selector, expectedLabel) {
  const item = await waitFor(() => findContextMenu(dbg, selector));
  is(
    item.label,
    expectedLabel,
    "The label of the context menu item shown to the user"
  );
}

async function typeInPanel(dbg, text) {
  await waitForElement(dbg, "conditionalPanelInput");
  // Position cursor reliably at the end of the text.
  pressKey(dbg, "End");
  type(dbg, text);
  pressKey(dbg, "Enter");
}

async function toggleMapScopes(dbg) {
  info("Turn on original variable mapping");
  const scopesLoaded = waitForLoadedScopes(dbg);
  const onDispatch = waitForDispatch(dbg.store, "TOGGLE_MAP_SCOPES");
  clickElement(dbg, "mapScopesCheckbox");
  return Promise.all([onDispatch, scopesLoaded]);
}

async function waitForPausedInOriginalFileAndToggleMapScopes(
  dbg,
  expectedSelectedSource = null
) {
  // Original variable mapping is not switched on, so do not wait for any loaded scopes
  await waitForPaused(dbg, expectedSelectedSource, {
    shouldWaitForLoadedScopes: false,
  });
  await toggleMapScopes(dbg);
}

function toggleExpressions(dbg) {
  return findElement(dbg, "expressionsHeader").click();
}

function toggleScopes(dbg) {
  return findElement(dbg, "scopesHeader").click();
}

function toggleExpressionNode(dbg, index) {
  return toggleObjectInspectorNode(findElement(dbg, "expressionNode", index));
}

function toggleScopeNode(dbg, index) {
  return toggleObjectInspectorNode(findElement(dbg, "scopeNode", index));
}

function rightClickScopeNode(dbg, index) {
  rightClickObjectInspectorNode(dbg, findElement(dbg, "scopeNode", index));
}

function getScopeNodeLabel(dbg, index) {
  return findElement(dbg, "scopeNode", index).innerText;
}

function getScopeNodeValue(dbg, index) {
  return findElement(dbg, "scopeValue", index).innerText;
}

function toggleObjectInspectorNode(node) {
  const objectInspector = node.closest(".object-inspector");
  const properties = objectInspector.querySelectorAll(".node").length;

  info(`Toggling node ${node.innerText}`);
  node.click();
  return waitUntil(
    () => objectInspector.querySelectorAll(".node").length !== properties
  );
}

function rightClickObjectInspectorNode(dbg, node) {
  const objectInspector = node.closest(".object-inspector");
  const properties = objectInspector.querySelectorAll(".node").length;

  info(`Right clicking node ${node.innerText}`);
  rightClickEl(dbg, node);

  return waitUntil(
    () => objectInspector.querySelectorAll(".node").length !== properties
  );
}

function getCM(dbg) {
  const el = dbg.win.document.querySelector(".CodeMirror");
  return el.CodeMirror;
}

function getCoordsFromPosition(cm, { line, ch }) {
  return cm.charCoords({ line: ~~line, ch: ~~ch });
}

async function getTokenFromPosition(dbg, { line, column = 0 }) {
  info(`Get token at ${line}:${column}`);
  const cm = getCM(dbg);

  // CodeMirror is 0-based while line and column arguments are 1-based.
  // Pass "ch=-1" when there is no column argument passed.
  const cmPosition = { line: line - 1, ch: column - 1 };

  const onScrolled = waitForScrolling(cm);
  cm.scrollIntoView(cmPosition, 0);

  // Ensure the line is visible with margin because the bar at the bottom of
  // the editor overlaps into what the editor thinks is its own space, blocking
  // the click event below.
  await onScrolled;

  const { left, top } = getCoordsFromPosition(cm, cmPosition);

  // Adds a vertical offset due to increased line height
  // https://github.com/firefox-devtools/debugger/pull/7934
  const lineHeightOffset = 3;

  // Note that we might end up retrieving any popup if one is still shown over the expected token
  return dbg.win.document.elementFromPoint(left, top + lineHeightOffset);
}

async function waitForScrolling(codeMirror) {
  return new Promise(resolve => {
    codeMirror.on("scroll", resolve);
    setTimeout(resolve, 500);
  });
}

async function codeMirrorGutterElement(dbg, line) {
  info(`CodeMirror line ${line}`);
  const cm = getCM(dbg);

  const position = { line: line - 1, ch: 0 };
  cm.scrollIntoView(position, 0);
  await waitForScrolling(cm);

  const coords = getCoordsFromPosition(cm, position);

  const { left, top } = coords;

  // Adds a vertical offset due to increased line height
  // https://github.com/firefox-devtools/debugger/pull/7934
  const lineHeightOffset = 3;

  // Click in the center of the line/breakpoint
  const leftOffset = 10;

  const tokenEl = dbg.win.document.elementFromPoint(
    left - leftOffset,
    top + lineHeightOffset
  );

  if (!tokenEl) {
    throw new Error(`Failed to find element for line ${line}`);
  }
  return tokenEl;
}

async function clickAtPos(dbg, pos) {
  const tokenEl = await getTokenFromPosition(dbg, pos);

  if (!tokenEl) {
    return;
  }

  const { top, left } = tokenEl.getBoundingClientRect();
  info(
    `Clicking on token ${tokenEl.innerText} in line ${tokenEl.parentNode.innerText}`
  );
  tokenEl.dispatchEvent(
    new MouseEvent("click", {
      bubbles: true,
      cancelable: true,
      view: dbg.win,
      clientX: left,
      clientY: top,
    })
  );
}

async function rightClickAtPos(dbg, pos) {
  const el = await getTokenFromPosition(dbg, pos);
  if (!el) {
    return;
  }

  EventUtils.synthesizeMouseAtCenter(el, { type: "contextmenu" }, dbg.win);
}

async function hoverAtPos(dbg, pos) {
  const tokenEl = await getTokenFromPosition(dbg, pos);

  if (!tokenEl) {
    return;
  }

  hoverToken(tokenEl);
}

function hoverToken(tokenEl) {
  info(`Hovering on token <${tokenEl.innerText}>`);

  // We can't use synthesizeMouse(AtCenter) as it's using the element bounding client rect.
  // But here, we might have a token that wraps on multiple line and the center of the
  // bounding client rect won't actually hover the token.
  // +───────────────────────+
  // │      myLongVariableNa│
  // │me         +          │
  // +───────────────────────+

  // Instead, we need to get the first quad.
  const { p1, p2, p3 } = tokenEl.getBoxQuads()[0];
  const x = p1.x + (p2.x - p1.x) / 2;
  const y = p1.y + (p3.y - p1.y) / 2;

  // This first event helps utils/editor/tokens.js to receive the right mouseover event
  EventUtils.synthesizeMouseAtPoint(
    x,
    y,
    {
      type: "mouseover",
    },
    tokenEl.ownerGlobal
  );

  // This second event helps Popover to have :hover pseudoclass set on the token element
  EventUtils.synthesizeMouseAtPoint(
    x,
    y,
    {
      type: "mousemove",
    },
    tokenEl.ownerGlobal
  );
}

/**
 * Helper to close a variable preview popup.
 *
 * @param {Object} dbg
 * @param {DOM Element} tokenEl
 *        The DOM element on which we hovered to display the popup.
 * @param {String} previewType
 *        Based on the actual JS value being hovered we may have two different kinds
 *        of popups: popup (for js objects) or previewPopup (for primitives)
 */
async function closePreviewForToken(
  dbg,
  tokenEl,
  previewType = "previewPopup"
) {
  ok(
    findElement(dbg, previewType),
    "A preview was opened before trying to close it"
  );

  // Force "mousing out" from all elements.
  //
  // This helps utils/editor/tokens.js to receive the right mouseleave event.
  // This is super important as it will then allow re-emitting a tokenenter event if you try to re-preview the same token!
  // We can't use synthesizeMouse(AtCenter) as it's using the element bounding client rect.
  // But here, we might have a token that wraps on multiple line and the center of the
  // bounding client rect won't actually hover the token.
  // +───────────────────────+
  // │      myLongVariableNa│
  // │me         +          │
  // +───────────────────────+

  // Instead, we need to get the first quad.
  const { p1, p2, p3 } = tokenEl.getBoxQuads()[0];
  const x = p1.x + (p2.x - p1.x) / 2;
  const y = p1.y + (p3.y - p1.y) / 2;
  EventUtils.synthesizeMouseAtPoint(
    tokenEl,
    x,
    y,
    {
      type: "mouseout",
    },
    tokenEl.ownerGlobal
  );

  // This second event helps Popover to have :hover pseudoclass removed on the token element
  //
  // For some unexplained reason, the precise element onto which we emit mousemove is actually important.
  // Emitting it on documentElement, or random other element within CodeMirror would cause
  // a "mousemove" event to be emitted on preview-popup element instead and wouldn't cause :hover
  // pseudoclass to be dropped.
  const element = tokenEl.ownerDocument.querySelector(
    ".debugger-settings-menu-button"
  );
  EventUtils.synthesizeMouseAtCenter(
    element,
    {
      type: "mousemove",
    },
    element.ownerGlobal
  );

  await waitUntil(() => findElement(dbg, previewType) == null);
  info("Preview closed");
}

/**
 * Hover at a position until we see a preview element (popup, tooltip) appear.
 * ⚠️ Note that this is using CodeMirror method to retrieve the token element
 * and that could be subject to CodeMirror bugs / outdated internal state
 *
 * @param {Debugger} dbg
 * @param {Integer} line: The line we want to hover over
 * @param {Integer} column: The column we want to hover over
 * @param {String} elementName: "Selector" string that will be passed to waitForElement,
 *                              describing the element that should be displayed on hover.
 * @returns Promise<{element, tokenEl}>
 *          element is the DOM element matching the passed elementName
 *          tokenEl is the DOM element for the token we hovered
 */
async function tryHovering(dbg, line, column, elementName) {
  ok(
    !findElement(dbg, elementName),
    "The expected preview element on hover should not exist beforehand"
  );

  const tokenEl = await getTokenFromPosition(dbg, { line, column });
  return tryHoverToken(dbg, tokenEl, elementName);
}

/**
 * Retrieve the token element matching `expression` at line `line` and hover it.
 * This is retrieving the token from the DOM, contrary to `tryHovering`, which calls
 * CodeMirror internal method for this (and which might suffer from bugs / outdated internal state)
 *
 * @param {Debugger} dbg
 * @param {String} expression: The text of the token we want to hover
 * @param {Integer} line: The line the token should be at
 * @param {Integer} column: The column the token should be at
 * @param {String} elementName: "Selector" string that will be passed to waitForElement,
 *                              describing the element that should be displayed on hover.
 * @returns Promise<{element, tokenEl}>
 *          element is the DOM element matching the passed elementName
 *          tokenEl is the DOM element for the token we hovered
 */
async function tryHoverTokenAtLine(dbg, expression, line, column, elementName) {
  info("Scroll codeMirror to make the token visible");
  const cm = getCM(dbg);
  const onScrolled = waitForScrolling(cm);
  cm.scrollIntoView({ line: line - 1, ch: 0 }, 0);
  await onScrolled;

  // Lookup for the token matching the passed expression
  const tokenEl = getTokenElAtLine(dbg, expression, line, column);
  if (!tokenEl) {
    throw new Error(
      `Couldn't find token <${expression}> on ${line}:${column}\n`
    );
  }

  ok(true, `Found token <${expression}> on ${line}:${column}`);

  return tryHoverToken(dbg, tokenEl, elementName);
}

async function tryHoverToken(dbg, tokenEl, elementName) {
  hoverToken(tokenEl);

  // Wait for the preview element to be created
  const element = await waitForElement(dbg, elementName);
  return { element, tokenEl };
}

/**
 * Retrieve the token element matching `expression` at line `line`, from the DOM.
 *
 * @param {Debugger} dbg
 * @param {String} expression: The text of the token we want to hover
 * @param {Integer} line: The line the token should be at
 * @param {Integer} column: The column the token should be at
 * @returns {Element} the token element, or null if not found
 */
function getTokenElAtLine(dbg, expression, line, column = 0) {
  info(`Search for <${expression}> token on ${line}:${column}`);
  // Get the line gutter element matching the passed line
  const lineGutterEl = [
    ...dbg.win.document.querySelectorAll(".CodeMirror-linenumber"),
  ].find(el => el.textContent === `${line}`);

  // Get the related editor line
  const editorLineEl = lineGutterEl
    .closest(".CodeMirror-gutter-wrapper")
    .parentElement.querySelector(".CodeMirror-line");

  // Lookup for the token matching the passed expression
  let currentColumn = 1;
  return Array.from(editorLineEl.childNodes[0].childNodes).find(child => {
    const childText = child.textContent;
    currentColumn += childText.length;

    // Only consider elements that are after the passed column
    if (currentColumn < column) {
      return false;
    }
    return childText === expression;
  });
}

/**
 * Wait for a few ms and assert that a tooltip preview was not displayed.
 * @param {*} dbg
 */
async function assertNoTooltip(dbg) {
  await wait(200);
  const el = findElement(dbg, "previewPopup");
  is(el, null, "Tooltip should not exist");
}

/**
 * Hovers and asserts tooltip previews with simple text expressions (i.e numbers and strings)
 * @param {*} dbg
 * @param {Number} line
 * @param {Number} column
 * @param {Object} options
 * @param {String}  options.result - Expected text shown in the preview
 * @param {String}  options.expression - The expression hovered over
 * @param {Boolean} options.doNotClose - Set to true to not close the tooltip
 */
async function assertPreviewTextValue(
  dbg,
  line,
  column,
  { result, expression, doNotClose = false }
) {
  // CodeMirror refreshes after inline previews are displayed, so wait until they're rendered.
  await waitForInlinePreviews(dbg);

  const { element: previewEl, tokenEl } = await tryHoverTokenAtLine(
    dbg,
    expression,
    line,
    column,
    "previewPopup"
  );

  ok(
    previewEl.innerText.includes(result),
    "Popup preview text shown to user. Got: " +
      previewEl.innerText +
      " Expected: " +
      result
  );

  if (!doNotClose) {
    await closePreviewForToken(dbg, tokenEl);
  }
}

/**
 * Asserts multiple previews
 * @param {*} dbg
 * @param {Array} previews
 */
async function assertPreviews(dbg, previews) {
  // Move the cursor to the top left corner to have a clean state
  EventUtils.synthesizeMouse(
    findElement(dbg, "codeMirror"),
    0,
    0,
    {
      type: "mousemove",
    },
    dbg.win
  );

  // CodeMirror refreshes after inline previews are displayed, so wait until they're rendered.
  await waitForInlinePreviews(dbg);

  for (const { line, column, expression, result, header, fields } of previews) {
    info(" # Assert preview on " + line + ":" + column);

    if (result) {
      await assertPreviewTextValue(dbg, line, column, {
        expression,
        result,
      });
    }

    if (fields) {
      const { element: popupEl, tokenEl } = expression
        ? await tryHoverTokenAtLine(dbg, expression, line, column, "popup")
        : await tryHovering(dbg, line, column, "popup");

      info("Wait for child nodes to load");
      await waitUntil(
        () => popupEl.querySelectorAll(".preview-popup .node").length > 1
      );
      ok(true, "child nodes loaded");

      const oiNodes = Array.from(
        popupEl.querySelectorAll(".preview-popup .node")
      );

      if (header) {
        is(
          oiNodes[0].querySelector(".objectBox").textContent,
          header,
          "popup has expected value"
        );
      }

      for (const [field, value] of fields) {
        const node = oiNodes.find(
          oiNode => oiNode.querySelector(".object-label")?.textContent === field
        );
        if (!node) {
          ok(false, `The "${field}" property is not displayed in the popup`);
        } else {
          is(
            node.querySelector(".object-label").textContent,
            field,
            `The "${field}" property is displayed in the popup`
          );
          if (value !== undefined) {
            is(
              node.querySelector(".objectBox").textContent,
              value,
              `The "${field}" property has the expected value`
            );
          }
        }
      }

      await closePreviewForToken(dbg, tokenEl, "popup");
    }
  }
}

/**
 * Asserts the inline expression preview value
 * @param {*} dbg
 * @param {Number} line
 * @param {Number} column
 * @param {Object} options
 * @param {String}  options.result - Expected text shown in the preview
 * @param {String}  options.expression - The expression hovered over
 * @param {Array}  options.fields - The expected stacktrace information
 */
async function assertInlineExceptionPreview(
  dbg,
  line,
  column,
  { expression, result, fields }
) {
  info(" # Assert preview on " + line + ":" + column);
  const { element: popupEl, tokenEl } = await tryHovering(
    dbg,
    line,
    column,
    "previewPopup"
  );

  info("Wait for top level node to expand and child nodes to load");
  await waitForElementWithSelector(
    dbg,
    ".exception-popup .exception-message .arrow.expanded"
  );

  is(
    popupEl.querySelector(".preview-popup .exception-message .objectBox")
      .textContent,
    result,
    "The correct result is not displayed in the popup"
  );

  await waitFor(() =>
    popupEl.querySelectorAll(".preview-popup .exception-stacktrace .frame")
  );
  const stackFrameNodes = Array.from(
    popupEl.querySelectorAll(".preview-popup .exception-stacktrace .frame")
  );

  for (const [field, value] of fields) {
    const node = stackFrameNodes.find(
      frameNode => frameNode.querySelector(".title")?.textContent === field
    );
    if (!node) {
      ok(false, `The "${field}" property is not displayed in the popup`);
    } else {
      is(
        node.querySelector(".location").textContent,
        value,
        `The "${field}" property has the expected value`
      );
    }
  }

  await closePreviewForToken(dbg, tokenEl, "previewPopup");
}

async function waitForBreakableLine(dbg, source, lineNumber) {
  await waitForState(
    dbg,
    state => {
      const currentSource = findSource(dbg, source);

      const breakableLines =
        currentSource && dbg.selectors.getBreakableLines(currentSource.id);

      return breakableLines && breakableLines.includes(lineNumber);
    },
    `waiting for breakable line ${lineNumber}`
  );
}

async function waitForSourceTreeThreadsCount(dbg, i) {
  info(`waiting for ${i} threads in the source tree`);
  await waitUntil(() => {
    return findAllElements(dbg, "sourceTreeThreads").length === i;
  });
}

async function waitForSourcesInSourceTree(
  dbg,
  sources,
  { noExpand = false } = {}
) {
  info(`waiting for ${sources.length} files in the source tree`);
  function getDisplayedSources() {
    // Replace some non visible space characters that prevents Array.includes from working correctly
    return [...findAllElements(dbg, "sourceTreeFiles")].map(e => {
      return e.textContent.trim().replace(/^[\s\u200b]*/g, "");
    });
  }
  try {
    // Use custom timeout and retry count for waitFor as the test method is slow to resolve
    // and default value makes the timeout unecessarily long
    await waitFor(
      async () => {
        if (!noExpand) {
          await expandSourceTree(dbg);
        }
        const displayedSources = getDisplayedSources();
        return (
          displayedSources.length == sources.length &&
          sources.every(source => displayedSources.includes(source))
        );
      },
      null,
      100,
      50
    );
  } catch (e) {
    // Craft a custom error message to help understand what's wrong with the Source Tree content
    const displayedSources = getDisplayedSources();
    let msg = "Invalid Source Tree Content.\n";
    const missingElements = [];
    for (const source of sources) {
      const idx = displayedSources.indexOf(source);
      if (idx != -1) {
        displayedSources.splice(idx, 1);
      } else {
        missingElements.push(source);
      }
    }
    if (missingElements.length) {
      msg += "Missing elements: " + missingElements.join(", ") + "\n";
    }
    if (displayedSources.length) {
      msg += "Unexpected elements: " + displayedSources.join(", ");
    }
    throw new Error(msg);
  }
}

async function waitForNodeToGainFocus(dbg, index) {
  await waitUntil(() => {
    const element = findElement(dbg, "sourceNode", index);

    if (element) {
      return element.classList.contains("focused");
    }

    return false;
  }, `waiting for source node ${index} to be focused`);
}

async function assertNodeIsFocused(dbg, index) {
  await waitForNodeToGainFocus(dbg, index);
  const node = findElement(dbg, "sourceNode", index);
  ok(node.classList.contains("focused"), `node ${index} is focused`);
}

/**
 * Asserts that the debugger is paused and the debugger tab is
 * highlighted.
 * @param {*} toolbox
 * @returns
 */
async function assertDebuggerIsHighlightedAndPaused(toolbox) {
  info("Wait for the debugger to be automatically selected on pause");
  await waitUntil(() => toolbox.currentToolId == "jsdebugger");
  ok(true, "Debugger selected");

  // Wait for the debugger to finish loading.
  await toolbox.getPanelWhenReady("jsdebugger");

  // And to be fully paused
  const dbg = createDebuggerContext(toolbox);
  await waitForPaused(dbg);

  ok(toolbox.isHighlighted("jsdebugger"), "Debugger is highlighted");

  return dbg;
}

async function addExpression(dbg, input) {
  info("Adding an expression");

  const plusIcon = findElementWithSelector(dbg, selectors.expressionPlus);
  if (plusIcon) {
    plusIcon.click();
  }
  findElementWithSelector(dbg, selectors.expressionInput).focus();
  type(dbg, input);
  const evaluated = waitForDispatch(dbg.store, "EVALUATE_EXPRESSION");
  const clearAutocomplete = waitForDispatch(dbg.store, "CLEAR_AUTOCOMPLETE");
  pressKey(dbg, "Enter");
  await evaluated;
  await clearAutocomplete;
}

async function editExpression(dbg, input) {
  info("Updating the expression");
  dblClickElement(dbg, "expressionNode", 1);
  // Position cursor reliably at the end of the text.
  pressKey(dbg, "End");
  type(dbg, input);
  const evaluated = waitForDispatch(dbg.store, "EVALUATE_EXPRESSIONS");
  pressKey(dbg, "Enter");
  await evaluated;
}

/**
 * Get the text representation of a watch expression label given its position in the panel
 *
 * @param {Object} dbg
 * @param {Number} index: Position in the panel of the expression we want the label of
 * @returns {String}
 */
function getWatchExpressionLabel(dbg, index) {
  return findElement(dbg, "expressionNode", index).innerText;
}

/**
 * Get the text representation of a watch expression value given its position in the panel
 *
 * @param {Object} dbg
 * @param {Number} index: Position in the panel of the expression we want the value of
 * @returns {String}
 */
function getWatchExpressionValue(dbg, index) {
  return findElement(dbg, "expressionValue", index).innerText;
}

// Return a promise with a reference to jsterm, opening the split
// console if necessary.  This cleans up the split console pref so
// it won't pollute other tests.
async function getDebuggerSplitConsole(dbg) {
  let { toolbox, win } = dbg;

  if (!win) {
    win = toolbox.win;
  }

  if (!toolbox.splitConsole) {
    pressKey(dbg, "Escape");
  }

  await toolbox.openSplitConsole();
  return toolbox.getPanel("webconsole");
}

// Return a promise that resolves with the result of a thread evaluating a
// string in the topmost frame.
async function evaluateInTopFrame(dbg, text) {
  const threadFront = dbg.toolbox.target.threadFront;
  const { frames } = await threadFront.getFrames(0, 1);
  ok(frames.length == 1, "Got one frame");
  const response = await dbg.commands.scriptCommand.execute(text, {
    frameActor: frames[0].actorID,
  });
  return response.result.type == "undefined" ? undefined : response.result;
}

// Return a promise that resolves when a thread evaluates a string in the
// topmost frame, ensuring the result matches the expected value.
async function checkEvaluateInTopFrame(dbg, text, expected) {
  const rval = await evaluateInTopFrame(dbg, text);
  ok(rval == expected, `Eval returned ${expected}`);
}

async function findConsoleMessage({ toolbox }, query) {
  const [message] = await findConsoleMessages(toolbox, query);
  const value = message.querySelector(".message-body").innerText;
  // There are console messages which might not have a link e.g Error messages
  const link = message.querySelector(".frame-link-source")?.innerText;
  return { value, link };
}

async function findConsoleMessages(toolbox, query) {
  const webConsole = await toolbox.getPanel("webconsole");
  const win = webConsole._frameWindow;
  return Array.prototype.filter.call(
    win.document.querySelectorAll(".message"),
    e => e.innerText.includes(query)
  );
}

async function hasConsoleMessage({ toolbox }, msg) {
  return waitFor(async () => {
    const messages = await findConsoleMessages(toolbox, msg);
    return !!messages.length;
  });
}

function evaluateExpressionInConsole(
  hud,
  expression,
  expectedClassName = "result"
) {
  const seenMessages = new Set(
    JSON.parse(
      hud.ui.outputNode
        .querySelector("[data-visible-messages]")
        .getAttribute("data-visible-messages")
    )
  );
  const onResult = new Promise(res => {
    const onNewMessage = messages => {
      for (const message of messages) {
        if (
          message.node.classList.contains(expectedClassName) &&
          !seenMessages.has(message.node.getAttribute("data-message-id"))
        ) {
          hud.ui.off("new-messages", onNewMessage);
          res(message.node);
        }
      }
    };
    hud.ui.on("new-messages", onNewMessage);
  });
  hud.ui.wrapper.dispatchEvaluateExpression(expression);
  return onResult;
}

function waitForInspectorPanelChange(dbg) {
  return dbg.toolbox.getPanelWhenReady("inspector");
}

function getEagerEvaluationElement(hud) {
  return hud.ui.outputNode.querySelector(".eager-evaluation-result");
}

async function waitForEagerEvaluationResult(hud, text) {
  await waitUntil(() => {
    const elem = getEagerEvaluationElement(hud);
    if (elem) {
      if (text instanceof RegExp) {
        return text.test(elem.innerText);
      }
      return elem.innerText == text;
    }
    return false;
  });
  ok(true, `Got eager evaluation result ${text}`);
}

function setInputValue(hud, value) {
  const onValueSet = hud.jsterm.once("set-input-value");
  hud.jsterm._setValue(value);
  return onValueSet;
}

function assertMenuItemChecked(menuItem, isChecked) {
  is(
    !!menuItem.getAttribute("aria-checked"),
    isChecked,
    `Item has expected state: ${isChecked ? "checked" : "unchecked"}`
  );
}

async function toggleDebbuggerSettingsMenuItem(dbg, { className, isChecked }) {
  const menuButton = findElementWithSelector(
    dbg,
    ".debugger-settings-menu-button"
  );
  const { parent } = dbg.panel.panelWin;
  const { document } = parent;

  menuButton.click();
  // Waits for the debugger settings panel to appear.
  await waitFor(() => {
    const menuListEl = document.querySelector("#debugger-settings-menu-list");
    // Lets check the offsetParent property to make sure the menu list is actually visible
    // by its parents display property being no longer "none".
    return menuListEl && menuListEl.offsetParent !== null;
  });

  const menuItem = document.querySelector(className);

  assertMenuItemChecked(menuItem, isChecked);

  menuItem.click();

  // Waits for the debugger settings panel to disappear.
  await waitFor(() => menuButton.getAttribute("aria-expanded") === "false");
}

async function setLogPoint(dbg, index, value) {
  rightClickElement(dbg, "gutter", index);
  await waitForContextMenu(dbg);
  selectContextMenuItem(
    dbg,
    `${selectors.addLogItem},${selectors.editLogItem}`
  );
  const onBreakpointSet = waitForDispatch(dbg.store, "SET_BREAKPOINT");
  await typeInPanel(dbg, value);
  await onBreakpointSet;
}
/**
 * Opens the project search panel
 *
 * @param {Object} dbg
 * @return {Boolean} The project search is open
 */
function openProjectSearch(dbg) {
  info("Opening the project search panel");
  synthesizeKeyShortcut("CmdOrCtrl+Shift+F");
  return waitForState(
    dbg,
    state => dbg.selectors.getActiveSearch() === "project"
  );
}

/**
 * Starts a project search based on the specified search term
 *
 * @param {Object} dbg
 * @param {String} searchTerm - The test to search for
 * @param {Number} expectedResults - The expected no of results to wait for.
 *                                   This is the number of file results and not the numer of matches in all files.
 *                                   When falsy value is passed, expects no match.
 * @return {Array} List of search results element nodes
 */
async function doProjectSearch(dbg, searchTerm, expectedResults) {
  await clearElement(dbg, "projectSearchSearchInput");
  type(dbg, searchTerm);
  pressKey(dbg, "Enter");
  return waitForSearchResults(dbg, expectedResults);
}

/**
 * Waits for the search resluts node to render
 *
 * @param {Object} dbg
 * @param {Number} expectedResults - The expected no of results to wait for
 *                                   This is the number of file results and not the numer of matches in all files.
 * @return (Array) List of search result element nodes
 */
async function waitForSearchResults(dbg, expectedResults) {
  if (expectedResults) {
    info(`Wait for ${expectedResults} project search results`);
    await waitUntil(
      () =>
        findAllElements(dbg, "projectSearchFileResults").length ==
        expectedResults
    );
  } else {
    // If no results are expected, wait for the "no results" message to be displayed.
    info("Wait for project search to complete with no results");
    await waitUntil(() => {
      const projectSearchResult = findElementWithSelector(
        dbg,
        ".no-result-msg"
      );
      return projectSearchResult
        ? projectSearchResult.textContent ==
            DEBUGGER_L10N.getStr("projectTextSearch.noResults")
        : false;
    });
  }
  return findAllElements(dbg, "projectSearchFileResults");
}

/**
 * Get the no of expanded search results
 *
 * @param {Object} dbg
 * @return {Number} No of expanded results
 */
function getExpandedResultsCount(dbg) {
  return findAllElements(dbg, "projectSearchExpandedResults").length;
}

// This module is also loaded for Browser Toolbox tests, within the browser toolbox process
// which doesn't contain mochitests resource://testing-common URL.
// This isn't important to allow rejections in the context of the browser toolbox tests.
const protocolHandler = Services.io
  .getProtocolHandler("resource")
  .QueryInterface(Ci.nsIResProtocolHandler);
if (protocolHandler.hasSubstitution("testing-common")) {
  const { PromiseTestUtils } = ChromeUtils.importESModule(
    "resource://testing-common/PromiseTestUtils.sys.mjs"
  );
  PromiseTestUtils.allowMatchingRejectionsGlobally(/Connection closed/);
  this.PromiseTestUtils = PromiseTestUtils;

  // Debugger operations that are canceled because they were rendered obsolete by
  // a navigation or pause/resume end up as uncaught rejections. These never
  // indicate errors and are allowed in all debugger tests.
  // All the following are related to context middleware throwing on obsolete async actions:
  PromiseTestUtils.allowMatchingRejectionsGlobally(/DebuggerContextError/);
}

/**
 * Selects the specific black box context menu item
 * @param {Object} dbg
 * @param {String} itemName
 *                  The name of the context menu item.
 */
async function selectBlackBoxContextMenuItem(dbg, itemName) {
  let wait = null;
  if (itemName == "blackbox-line" || itemName == "blackbox-lines") {
    wait = Promise.any([
      waitForDispatch(dbg.store, "BLACKBOX_SOURCE_RANGES"),
      waitForDispatch(dbg.store, "UNBLACKBOX_SOURCE_RANGES"),
    ]);
  } else if (itemName == "blackbox") {
    wait = Promise.any([
      waitForDispatch(dbg.store, "BLACKBOX_WHOLE_SOURCES"),
      waitForDispatch(dbg.store, "UNBLACKBOX_WHOLE_SOURCES"),
    ]);
  }

  info(`Select the ${itemName} context menu item`);
  selectContextMenuItem(dbg, `#node-menu-${itemName}`);
  return wait;
}

function openOutlinePanel(dbg, waitForOutlineList = true) {
  const outlineTab = findElementWithSelector(dbg, ".outline-tab a");
  EventUtils.synthesizeMouseAtCenter(outlineTab, {}, outlineTab.ownerGlobal);

  if (!waitForOutlineList) {
    return Promise.resolve();
  }

  return waitForElementWithSelector(dbg, ".outline-list");
}

// Test empty panel when source has not function or class symbols
// Test that anonymous functions do not show in the outline panel
function assertOutlineItems(dbg, expectedItems) {
  const outlineItems = Array.from(
    findAllElementsWithSelector(
      dbg,
      ".outline-list h2, .outline-list .outline-list__element"
    )
  );
  SimpleTest.isDeeply(
    outlineItems.map(i => i.innerText.trim()),
    expectedItems,
    "The expected items are displayed in the outline panel"
  );
}

async function checkAdditionalThreadCount(dbg, count) {
  await waitForState(
    dbg,
    state => {
      return dbg.selectors.getThreads().length == count;
    },
    "Have the expected number of additional threads"
  );
  ok(true, `Have ${count} threads`);
}

/**
 * Retrieve the text displayed as warning under the editor.
 */
function findFooterNotificationMessage(dbg) {
  return findElement(dbg, "editorNotificationFooter")?.innerText;
}