File: browser-addons.js

package info (click to toggle)
firefox 141.0.3-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 4,550,588 kB
  • sloc: cpp: 7,426,506; javascript: 6,367,238; ansic: 3,707,351; python: 1,369,002; xml: 623,983; asm: 426,918; java: 184,324; sh: 64,488; makefile: 19,203; objc: 13,059; perl: 12,955; yacc: 4,583; cs: 3,846; pascal: 3,352; lex: 1,720; ruby: 1,071; exp: 762; php: 436; lisp: 258; awk: 247; sql: 66; sed: 54; csh: 10
file content (3113 lines) | stat: -rw-r--r-- 104,075 bytes parent folder | download | duplicates (2)
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
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*-
 * 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/. */

// This file is loaded into the browser window scope.
/* eslint-env mozilla/browser-window */

var { XPCOMUtils } = ChromeUtils.importESModule(
  "resource://gre/modules/XPCOMUtils.sys.mjs"
);

const lazy = {};

ChromeUtils.defineESModuleGetters(lazy, {
  AMBrowserExtensionsImport: "resource://gre/modules/AddonManager.sys.mjs",
  AbuseReporter: "resource://gre/modules/AbuseReporter.sys.mjs",
  ExtensionCommon: "resource://gre/modules/ExtensionCommon.sys.mjs",
  ExtensionParent: "resource://gre/modules/ExtensionParent.sys.mjs",
  ExtensionPermissions: "resource://gre/modules/ExtensionPermissions.sys.mjs",
  OriginControls: "resource://gre/modules/ExtensionPermissions.sys.mjs",
  PERMISSION_L10N: "resource://gre/modules/ExtensionPermissionMessages.sys.mjs",
  SITEPERMS_ADDON_TYPE:
    "resource://gre/modules/addons/siteperms-addon-utils.sys.mjs",
});
ChromeUtils.defineLazyGetter(lazy, "l10n", function () {
  return new Localization(
    ["browser/addonNotifications.ftl", "branding/brand.ftl"],
    true
  );
});

/**
 * Mapping of error code -> [error-id, local-error-id]
 *
 * error-id is used for errors in DownloadedAddonInstall,
 * local-error-id for errors in LocalAddonInstall.
 *
 * The error codes are defined in AddonManager's _errors Map.
 * Not all error codes listed there are translated,
 * since errors that are only triggered during updates
 * will never reach this code.
 */
const ERROR_L10N_IDS = new Map([
  [
    -1,
    [
      "addon-install-error-network-failure",
      "addon-local-install-error-network-failure",
    ],
  ],
  [
    -2,
    [
      "addon-install-error-incorrect-hash",
      "addon-local-install-error-incorrect-hash",
    ],
  ],
  [
    -3,
    [
      "addon-install-error-corrupt-file",
      "addon-local-install-error-corrupt-file",
    ],
  ],
  [
    -4,
    [
      "addon-install-error-file-access",
      "addon-local-install-error-file-access",
    ],
  ],
  [
    -5,
    ["addon-install-error-not-signed", "addon-local-install-error-not-signed"],
  ],
  [-8, ["addon-install-error-invalid-domain"]],
  [
    -10,
    ["addon-install-error-hard-blocked", "addon-install-error-hard-blocked"],
  ],
  [
    -11,
    ["addon-install-error-incompatible", "addon-install-error-incompatible"],
  ],
  [
    -13,
    [
      "addon-install-error-admin-install-only",
      "addon-install-error-admin-install-only",
    ],
  ],
  [
    -14,
    ["addon-install-error-soft-blocked", "addon-install-error-soft-blocked"],
  ],
]);

customElements.define(
  "addon-notification-blocklist-url",
  class MozAddonNotificationBlocklistURL extends HTMLAnchorElement {
    connectedCallback() {
      this.addEventListener("click", this);
    }

    disconnectedCallback() {
      this.removeEventListener("click", this);
    }

    handleEvent(e) {
      if (e.type == "click") {
        e.preventDefault();
        window.openTrustedLinkIn(this.href, "tab", {
          // Make sure the newly open tab is going to be focused, independently
          // from general user prefs.
          forceForeground: true,
        });
      }
    }
  },
  { extends: "a" }
);

customElements.define(
  "addon-webext-permissions-notification",
  class MozAddonPermissionsNotification extends customElements.get(
    "popupnotification"
  ) {
    show() {
      super.show();

      if (!this.notification) {
        return;
      }

      if (!this.notification.options?.customElementOptions) {
        throw new Error(
          "Mandatory customElementOptions property missing from notification options"
        );
      }

      this.textEl = this.querySelector("#addon-webext-perm-text");
      this.introEl = this.querySelector("#addon-webext-perm-intro");
      this.permsTitleEl = this.querySelector(
        "#addon-webext-perm-title-required"
      );
      this.permsListEl = this.querySelector("#addon-webext-perm-list-required");
      this.permsTitleDataCollectionEl = this.querySelector(
        "#addon-webext-perm-title-data-collection"
      );
      this.permsListDataCollectionEl = this.querySelector(
        "#addon-webext-perm-list-data-collection"
      );
      this.permsTitleOptionalEl = this.querySelector(
        "#addon-webext-perm-title-optional"
      );
      this.permsListOptionalEl = this.querySelector(
        "#addon-webext-perm-list-optional"
      );

      this.render();
    }

    get hasNoPermissions() {
      const {
        strings,
        showIncognitoCheckbox,
        showTechnicalAndInteractionCheckbox,
      } = this.notification.options.customElementOptions;

      return !(
        strings.msgs.length ||
        this.#dataCollectionPermissions?.msg ||
        showIncognitoCheckbox ||
        showTechnicalAndInteractionCheckbox
      );
    }

    get domainsSet() {
      if (!this.notification?.options?.customElementOptions) {
        return undefined;
      }
      const { strings } = this.notification.options.customElementOptions;
      return strings.fullDomainsList?.domainsSet;
    }

    get hasFullDomainsList() {
      return this.domainsSet?.size;
    }

    #isFullDomainsListEntryIndex(idx) {
      if (!this.hasFullDomainsList) {
        return false;
      }
      const { strings } = this.notification.options.customElementOptions;
      return strings.fullDomainsList.msgIdIndex === idx;
    }

    /**
     * @returns {{idx: number, collectsTechnicalAndInteractionData: boolean}}
     * An object with information about data collection permissions for the UI.
     */
    get #dataCollectionPermissions() {
      if (!this.notification?.options?.customElementOptions) {
        return undefined;
      }
      const { strings } = this.notification.options.customElementOptions;
      return strings.dataCollectionPermissions;
    }

    render() {
      const {
        strings,
        showIncognitoCheckbox,
        showTechnicalAndInteractionCheckbox,
        isUserScriptsRequest,
      } = this.notification.options.customElementOptions;

      const {
        textEl,
        introEl,
        permsTitleEl,
        permsListEl,
        permsTitleDataCollectionEl,
        permsListDataCollectionEl,
        permsTitleOptionalEl,
        permsListOptionalEl,
      } = this;

      const HTML_NS = "http://www.w3.org/1999/xhtml";
      const doc = this.ownerDocument;

      this.#clearChildElements();
      // Re-enable "Allow" button if it was disabled by a previous request with
      // isUserScriptsRequest=true.
      this.#setAllowButtonEnabled(true);

      if (strings.text) {
        textEl.textContent = strings.text;
        // By default, multiline strings don't get formatted properly. These
        // are presently only used in site permission add-ons, so we treat it
        // as a special case to avoid unintended effects on other things.
        if (strings.text.includes("\n\n")) {
          textEl.classList.add("addon-webext-perm-text-multiline");
        }
        textEl.hidden = false;
      }

      if (strings.listIntro) {
        introEl.textContent = strings.listIntro;
        introEl.hidden = false;
      }

      // "sitepermission" add-ons don't have section headers.
      if (strings.sectionHeaders) {
        const { required, dataCollection, optional } = strings.sectionHeaders;

        permsTitleEl.textContent = required;
        permsTitleDataCollectionEl.textContent = dataCollection;
        permsTitleOptionalEl.textContent = optional;
      }

      // Return earlier if there are no permissions to list.
      if (this.hasNoPermissions) {
        return;
      }

      // We only expect a single permission for a userScripts request per
      // https://searchfox.org/mozilla-central/rev/5fb48bf50516ed2529d533e5dfe49b4752efb8b8/browser/modules/ExtensionsUI.sys.mjs#308-313.
      if (isUserScriptsRequest) {
        // The "userScripts" permission cannot be granted until the user has
        // confirmed again in the notification's content, as described at
        // https://bugzilla.mozilla.org/show_bug.cgi?id=1917000#c1

        let { checkboxEl, warningEl } = this.#createUserScriptsPermissionItems(
          // "userScripts" can only be requested with "permissions.request()",
          // which enforces that it is the only permission in the request.
          strings.msgs[0]
        );

        this.#setAllowButtonEnabled(false);

        let item = doc.createElementNS(HTML_NS, "li");
        item.append(checkboxEl, warningEl);
        item.classList.add("webext-perm-optional");
        permsListEl.append(item);

        permsTitleEl.hidden = false;
        permsListEl.hidden = false;
      } else {
        if (strings.msgs.length) {
          for (let [idx, msg] of strings.msgs.entries()) {
            let item = doc.createElementNS(HTML_NS, "li");
            item.classList.add("webext-perm-granted");
            if (
              this.hasFullDomainsList &&
              this.#isFullDomainsListEntryIndex(idx)
            ) {
              item.append(this.#createFullDomainsListFragment(msg));
            } else {
              item.textContent = msg;
            }
            permsListEl.appendChild(item);
          }

          permsTitleEl.hidden = false;
          permsListEl.hidden = false;
        }

        if (this.#dataCollectionPermissions?.msg) {
          let item = doc.createElementNS(HTML_NS, "li");
          item.classList.add(
            "webext-perm-granted",
            "webext-data-collection-perm-granted"
          );
          item.textContent = this.#dataCollectionPermissions.msg;
          permsListDataCollectionEl.appendChild(item);
          permsTitleDataCollectionEl.hidden = false;
          permsListDataCollectionEl.hidden = false;
        }

        // Add a checkbox for the "technicalAndInteraction" optional data
        // collection permission.
        if (showTechnicalAndInteractionCheckbox) {
          let item = doc.createElementNS(HTML_NS, "li");
          item.classList.add(
            "webext-perm-optional",
            "webext-data-collection-perm-optional"
          );
          item.appendChild(this.#createTechnicalAndInteractionDataCheckbox());
          permsListOptionalEl.appendChild(item);
          permsTitleOptionalEl.hidden = false;
          permsListOptionalEl.hidden = false;
        }

        if (showIncognitoCheckbox) {
          let item = doc.createElementNS(HTML_NS, "li");
          item.classList.add(
            "webext-perm-optional",
            "webext-perm-privatebrowsing"
          );
          item.appendChild(this.#createPrivateBrowsingCheckbox());
          permsListOptionalEl.appendChild(item);
          permsTitleOptionalEl.hidden = false;
          permsListOptionalEl.hidden = false;
        }
      }
    }

    #createFullDomainsListFragment(msg) {
      const HTML_NS = "http://www.w3.org/1999/xhtml";
      const doc = this.ownerDocument;
      const label = doc.createXULElement("label");
      label.value = msg;
      const domainsList = doc.createElementNS(HTML_NS, "ul");
      domainsList.classList.add("webext-perm-domains-list");

      // Enforce max-height and ensure the domains list is
      // scrollable when there are more than 5 domains.
      if (this.domainsSet.size > 5) {
        domainsList.classList.add("scrollable-domains-list");
      }

      for (const domain of this.domainsSet) {
        let domainItem = doc.createElementNS(HTML_NS, "li");
        domainItem.textContent = domain;
        domainsList.appendChild(domainItem);
      }
      const { DocumentFragment } = this.ownerGlobal;
      const fragment = new DocumentFragment();
      fragment.append(label);
      fragment.append(domainsList);
      return fragment;
    }

    #clearChildElements() {
      const {
        textEl,
        introEl,
        permsTitleEl,
        permsListEl,
        permsTitleDataCollectionEl,
        permsListDataCollectionEl,
        permsTitleOptionalEl,
        permsListOptionalEl,
      } = this;

      // Clear all changes to the child elements that may have been changed
      // by a previous call of the render method.
      textEl.textContent = "";
      textEl.hidden = true;
      textEl.classList.remove("addon-webext-perm-text-multiline");

      introEl.textContent = "";
      introEl.hidden = true;

      for (const title of [
        permsTitleEl,
        permsTitleOptionalEl,
        permsTitleDataCollectionEl,
      ]) {
        title.hidden = true;
      }

      for (const list of [
        permsListEl,
        permsListDataCollectionEl,
        permsListOptionalEl,
      ]) {
        list.textContent = "";
        list.hidden = true;
      }
    }

    #createUserScriptsPermissionItems(userScriptsPermissionMessage) {
      let checkboxEl = this.ownerDocument.createElement("moz-checkbox");
      checkboxEl.label = userScriptsPermissionMessage;
      checkboxEl.checked = false;
      checkboxEl.addEventListener("change", () => {
        // The main "Allow" button is disabled until the checkbox is checked.
        this.#setAllowButtonEnabled(checkboxEl.checked);
      });

      let warningEl = this.ownerDocument.createElement("moz-message-bar");
      warningEl.setAttribute("type", "warning");
      warningEl.setAttribute(
        "message",
        lazy.PERMISSION_L10N.formatValueSync(
          "webext-perms-extra-warning-userScripts-short"
        )
      );

      return { checkboxEl, warningEl };
    }

    #setAllowButtonEnabled(allowed) {
      let disabled = !allowed;
      // "mainactiondisabled" mirrors the "disabled" boolean attribute of the
      // "Allow" button. toggleAttribute("mainactiondisabled", disabled) cannot
      // be used due to bug 1938481.
      if (disabled) {
        this.setAttribute("mainactiondisabled", "true");
      } else {
        this.removeAttribute("mainactiondisabled");
      }

      // The "mainactiondisabled" attribute may also be toggled by the
      // PopupNotifications._setNotificationUIState() method, which can be
      // called as a side effect of toggling a checkbox within the notification
      // (via PopupNotifications._onCommand).
      //
      // To prevent PopupNotifications._setNotificationUIState() from setting
      // the "mainactiondisabled" attribute to a different state, also set the
      // "invalidselection" attribute, since _setNotificationUIState() mirrors
      // its value to "mainactiondisabled".
      //
      // TODO bug 1938623: Remove this when a better alternative exists.
      this.toggleAttribute("invalidselection", disabled);
    }

    #createPrivateBrowsingCheckbox() {
      const { grantPrivateBrowsingAllowed } =
        this.notification.options.customElementOptions;

      let checkboxEl = this.ownerDocument.createElement("moz-checkbox");
      checkboxEl.checked = grantPrivateBrowsingAllowed;
      checkboxEl.addEventListener("change", () => {
        // NOTE: the popupnotification instances will be reused
        // and so the callback function is destructured here to
        // avoid this custom element to prevent it from being
        // garbage collected.
        const { onPrivateBrowsingAllowedChanged } =
          this.notification.options.customElementOptions;
        onPrivateBrowsingAllowedChanged?.(checkboxEl.checked);
      });
      this.ownerDocument.l10n.setAttributes(
        checkboxEl,
        "popup-notification-addon-privatebrowsing-checkbox2"
      );
      return checkboxEl;
    }

    #createTechnicalAndInteractionDataCheckbox() {
      const { grantTechnicalAndInteractionDataCollection } =
        this.notification.options.customElementOptions;

      const checkboxEl = this.ownerDocument.createElement("moz-checkbox");
      this.ownerDocument.l10n.setAttributes(
        checkboxEl,
        "popup-notification-addon-technical-and-interaction-checkbox"
      );
      checkboxEl.checked = grantTechnicalAndInteractionDataCollection;
      checkboxEl.addEventListener("change", () => {
        // NOTE: the popupnotification instances will be reused
        // and so the callback function is destructured here to
        // avoid this custom element to prevent it from being
        // garbage collected.
        const { onTechnicalAndInteractionDataChanged } =
          this.notification.options.customElementOptions;
        onTechnicalAndInteractionDataChanged?.(checkboxEl.checked);
      });

      return checkboxEl;
    }
  },
  { extends: "popupnotification" }
);

customElements.define(
  "addon-progress-notification",
  class MozAddonProgressNotification extends customElements.get(
    "popupnotification"
  ) {
    show() {
      super.show();
      this.progressmeter = document.getElementById(
        "addon-progress-notification-progressmeter"
      );

      this.progresstext = document.getElementById(
        "addon-progress-notification-progresstext"
      );

      if (!this.notification) {
        return;
      }

      this.notification.options.installs.forEach(function (aInstall) {
        aInstall.addListener(this);
      }, this);

      // Calling updateProgress can sometimes cause this notification to be
      // removed in the middle of refreshing the notification panel which
      // makes the panel get refreshed again. Just initialise to the
      // undetermined state and then schedule a proper check at the next
      // opportunity
      this.setProgress(0, -1);
      this._updateProgressTimeout = setTimeout(
        this.updateProgress.bind(this),
        0
      );
    }

    disconnectedCallback() {
      this.destroy();
    }

    destroy() {
      if (!this.notification) {
        return;
      }
      this.notification.options.installs.forEach(function (aInstall) {
        aInstall.removeListener(this);
      }, this);

      clearTimeout(this._updateProgressTimeout);
    }

    setProgress(aProgress, aMaxProgress) {
      if (aMaxProgress == -1) {
        this.progressmeter.removeAttribute("value");
      } else {
        this.progressmeter.setAttribute(
          "value",
          (aProgress * 100) / aMaxProgress
        );
      }

      let now = Date.now();

      if (!this.notification.lastUpdate) {
        this.notification.lastUpdate = now;
        this.notification.lastProgress = aProgress;
        return;
      }

      let delta = now - this.notification.lastUpdate;
      if (delta < 400 && aProgress < aMaxProgress) {
        return;
      }

      // Set min. time delta to avoid division by zero in the upcoming speed calculation
      delta = Math.max(delta, 400);
      delta /= 1000;

      // This algorithm is the same used by the downloads code.
      let speed = (aProgress - this.notification.lastProgress) / delta;
      if (this.notification.speed) {
        speed = speed * 0.9 + this.notification.speed * 0.1;
      }

      this.notification.lastUpdate = now;
      this.notification.lastProgress = aProgress;
      this.notification.speed = speed;

      let status = null;
      [status, this.notification.last] = DownloadUtils.getDownloadStatus(
        aProgress,
        aMaxProgress,
        speed,
        this.notification.last
      );
      this.progresstext.setAttribute("value", status);
      this.progresstext.setAttribute("tooltiptext", status);
    }

    cancel() {
      let installs = this.notification.options.installs;
      installs.forEach(function (aInstall) {
        try {
          aInstall.cancel();
        } catch (e) {
          // Cancel will throw if the download has already failed
        }
      }, this);

      PopupNotifications.remove(this.notification);
    }

    updateProgress() {
      if (!this.notification) {
        return;
      }

      let downloadingCount = 0;
      let progress = 0;
      let maxProgress = 0;

      this.notification.options.installs.forEach(function (aInstall) {
        if (aInstall.maxProgress == -1) {
          maxProgress = -1;
        }
        progress += aInstall.progress;
        if (maxProgress >= 0) {
          maxProgress += aInstall.maxProgress;
        }
        if (aInstall.state < AddonManager.STATE_DOWNLOADED) {
          downloadingCount++;
        }
      });

      if (downloadingCount == 0) {
        this.destroy();
        this.progressmeter.removeAttribute("value");
        const status = lazy.l10n.formatValueSync("addon-download-verifying");
        this.progresstext.setAttribute("value", status);
        this.progresstext.setAttribute("tooltiptext", status);
      } else {
        this.setProgress(progress, maxProgress);
      }
    }

    onDownloadProgress() {
      this.updateProgress();
    }

    onDownloadFailed() {
      this.updateProgress();
    }

    onDownloadCancelled() {
      this.updateProgress();
    }

    onDownloadEnded() {
      this.updateProgress();
    }
  },
  { extends: "popupnotification" }
);

// This custom element wraps the messagebar shown in the extensions panel
// and used in both ext-browserAction.js and browser-unified-extensions.js
customElements.define(
  "unified-extensions-item-messagebar-wrapper",
  class extends HTMLElement {
    get extensionPolicy() {
      return WebExtensionPolicy.getByID(this.extensionId);
    }

    get extensionName() {
      return this.extensionPolicy?.name;
    }

    get isSoftBlocked() {
      return this.extensionPolicy?.extension?.isSoftBlocked;
    }

    connectedCallback() {
      this.messagebar = document.createElement("moz-message-bar");
      this.messagebar.classList.add("unified-extensions-item-messagebar");
      this.append(this.messagebar);
      this.refresh();
    }

    disconnectedCallback() {
      this.messagebar?.remove();
    }

    async refresh() {
      if (!this.messagebar) {
        // Nothing to refresh, the custom element has not been
        // connected to the DOM yet.
        return;
      }
      if (!customElements.get("moz-message-bar")) {
        document.createElement("moz-message-bar");
        await customElements.whenDefined("moz-message-bar");
      }
      const { messagebar } = this;
      if (this.isSoftBlocked) {
        const SOFTBLOCK_FLUENTID =
          "unified-extensions-item-messagebar-softblocked";
        if (
          messagebar.messageL10nId === SOFTBLOCK_FLUENTID &&
          messagebar.messageL10nArgs?.extensionName === this.extensionName
        ) {
          // nothing to refresh.
          return;
        }
        messagebar.removeAttribute("hidden");
        messagebar.setAttribute("type", "warning");
        messagebar.messageL10nId = SOFTBLOCK_FLUENTID;
        messagebar.messageL10nArgs = {
          extensionName: this.extensionName,
        };
      } else {
        if (messagebar.hasAttribute("hidden")) {
          // nothing to refresh.
          return;
        }
        messagebar.setAttribute("hidden", "true");
        messagebar.messageL10nId = null;
        messagebar.messageL10nArgs = null;
      }
      messagebar.requestUpdate();
    }
  }
);

class BrowserActionWidgetObserver {
  #connected = false;
  /**
   * @param {string} addonId The ID of the extension
   * @param {function()} onButtonAreaChanged Callback that is called whenever
   *   the observer detects the presence, absence or relocation of the browser
   *   action button for the given extension.
   */
  constructor(addonId, onButtonAreaChanged) {
    this.addonId = addonId;
    // The expected ID of the browserAction widget. Keep in sync with
    // actionWidgetId logic in ext-browserAction.js.
    this.widgetId = `${lazy.ExtensionCommon.makeWidgetId(addonId)}-browser-action`;
    this.onButtonAreaChanged = onButtonAreaChanged;
  }

  startObserving() {
    if (this.#connected) {
      return;
    }
    this.#connected = true;
    CustomizableUI.addListener(this);
    window.addEventListener("unload", this);
  }

  stopObserving() {
    if (!this.#connected) {
      return;
    }
    this.#connected = false;
    CustomizableUI.removeListener(this);
    window.removeEventListener("unload", this);
  }

  hasBrowserActionUI() {
    const policy = WebExtensionPolicy.getByID(this.addonId);
    if (!policy?.canAccessWindow(window)) {
      // Add-on is not an extension, or extension has not started yet. Or it
      // was uninstalled/disabled. Or disabled in current (private) window.
      return false;
    }
    if (!gUnifiedExtensions.browserActionFor(policy)) {
      // Does not have a browser action button.
      return false;
    }
    return true;
  }

  onWidgetCreated(aWidgetId) {
    // This is triggered as soon as ext-browserAction registers the button,
    // shortly after hasBrowserActionUI() above can return true for the first
    // time since add-on installation.
    if (aWidgetId === this.widgetId) {
      this.onButtonAreaChanged();
    }
  }

  onWidgetAdded(aWidgetId) {
    if (aWidgetId === this.widgetId) {
      this.onButtonAreaChanged();
    }
  }

  onWidgetMoved(aWidgetId) {
    if (aWidgetId === this.widgetId) {
      this.onButtonAreaChanged();
    }
  }

  handleEvent(event) {
    if (event.type === "unload") {
      this.stopObserving();
    }
  }
}

customElements.define(
  "addon-installed-notification",
  class MozAddonInstalledNotification extends customElements.get(
    "popupnotification"
  ) {
    #shouldIgnoreCheckboxStateChangeEvent = false;
    #browserActionWidgetObserver;
    connectedCallback() {
      this.descriptionEl = this.querySelector("#addon-install-description");
      this.pinExtensionEl = this.querySelector(
        "#addon-pin-toolbarbutton-checkbox"
      );

      this.addEventListener("click", this);
      this.pinExtensionEl.addEventListener("CheckboxStateChange", this);
      this.#browserActionWidgetObserver?.startObserving();
    }

    disconnectedCallback() {
      this.removeEventListener("click", this);
      this.pinExtensionEl.removeEventListener("CheckboxStateChange", this);
      this.#browserActionWidgetObserver?.stopObserving();
    }

    get #settingsLinkId() {
      return "addon-install-settings-link";
    }

    handleEvent(event) {
      const { target } = event;

      switch (event.type) {
        case "click": {
          if (target.id === this.#settingsLinkId) {
            const { addonId } = this.notification.options.customElementOptions;
            BrowserAddonUI.openAddonsMgr(
              "addons://detail/" + encodeURIComponent(addonId)
            );
          }
          break;
        }
        case "CheckboxStateChange":
          // CheckboxStateChange fires whenever the checked value changes.
          // Ignore the event if triggered by us instead of the user.
          if (!this.#shouldIgnoreCheckboxStateChangeEvent) {
            this.#handlePinnedCheckboxStateChange();
          }
          break;
      }
    }

    show() {
      super.show();

      if (!this.notification) {
        return;
      }

      if (!this.notification.options?.customElementOptions) {
        throw new Error(
          "Mandatory customElementOptions property missing from notification options"
        );
      }

      this.#browserActionWidgetObserver?.stopObserving();
      this.#browserActionWidgetObserver = new BrowserActionWidgetObserver(
        this.notification.options.customElementOptions.addonId,
        () => this.#renderPinToolbarButtonCheckbox()
      );

      this.render();
      if (this.isConnected) {
        this.#browserActionWidgetObserver.startObserving();
      }
    }

    render() {
      let fluentId = "appmenu-addon-post-install-message3";

      this.ownerDocument.l10n.setAttributes(this.descriptionEl, null);
      this.querySelector(`#${this.#settingsLinkId}`)?.remove();

      if (this.#dataCollectionPermissionsEnabled) {
        const HTML_NS = "http://www.w3.org/1999/xhtml";
        const link = document.createElementNS(HTML_NS, "a");
        link.setAttribute("id", this.#settingsLinkId);
        link.setAttribute("data-l10n-name", "settings-link");
        // Make the link both accessible and keyboard-friendly.
        link.href = "#";
        this.descriptionEl.append(link);

        fluentId = "appmenu-addon-post-install-message-with-data-collection";
      }

      this.ownerDocument.l10n.setAttributes(this.descriptionEl, fluentId);
      this.#renderPinToolbarButtonCheckbox();
    }

    get #dataCollectionPermissionsEnabled() {
      return Services.prefs.getBoolPref(
        "extensions.dataCollectionPermissions.enabled",
        false
      );
    }

    #renderPinToolbarButtonCheckbox() {
      // If the extension has a browser action, show the checkbox to allow the
      // user to customize its location. Hide by default until we know for
      // certain that the conditions have been met.
      this.pinExtensionEl.hidden = true;

      if (!this.#browserActionWidgetObserver.hasBrowserActionUI()) {
        return;
      }
      const widgetId = this.#browserActionWidgetObserver.widgetId;

      // Extension buttons appear in AREA_ADDONS by default. There are several
      // ways for the default to differ for a specific add-on, including the
      // extension specifying default_area in its manifest.json file, an
      // enterprise policy having been configured, or the user having moved the
      // button someplace else. We only show the checkbox if it is either in
      // AREA_ADDONS or in the toolbar. This covers almost all common cases.
      const area = CustomizableUI.getPlacementOfWidget(widgetId)?.area;
      let shouldPinToToolbar = area !== CustomizableUI.AREA_ADDONS;
      if (shouldPinToToolbar && area !== CustomizableUI.AREA_NAVBAR) {
        // We only support AREA_ADDONS and AREA_NAVBAR for now.
        return;
      }
      this.#shouldIgnoreCheckboxStateChangeEvent = true;
      this.pinExtensionEl.checked = shouldPinToToolbar;
      this.#shouldIgnoreCheckboxStateChangeEvent = false;
      this.pinExtensionEl.hidden = false;
    }

    #handlePinnedCheckboxStateChange() {
      if (!this.#browserActionWidgetObserver.hasBrowserActionUI()) {
        // Unexpected. #renderPinToolbarButtonCheckbox() should have hidden
        // the checkbox if there is no widget.
        const { addonId } = this.notification.options.customElementOptions;
        throw new Error(`No browser action widget found for ${addonId}!`);
      }
      const widgetId = this.#browserActionWidgetObserver.widgetId;
      const shouldPinToToolbar = this.pinExtensionEl.checked;
      if (shouldPinToToolbar) {
        gUnifiedExtensions._maybeMoveWidgetNodeBack(widgetId);
      }
      gUnifiedExtensions.pinToToolbar(widgetId, shouldPinToToolbar);
    }
  },
  { extends: "popupnotification" }
);

// Removes a doorhanger notification if all of the installs it was notifying
// about have ended in some way.
function removeNotificationOnEnd(notification, installs) {
  let count = installs.length;

  function maybeRemove(install) {
    install.removeListener(this);

    if (--count == 0) {
      // Check that the notification is still showing
      let current = PopupNotifications.getNotification(
        notification.id,
        notification.browser
      );
      if (current === notification) {
        notification.remove();
      }
    }
  }

  for (let install of installs) {
    install.addListener({
      onDownloadCancelled: maybeRemove,
      onDownloadFailed: maybeRemove,
      onInstallFailed: maybeRemove,
      onInstallEnded: maybeRemove,
    });
  }
}

function buildNotificationAction(msg, callback) {
  let label = "";
  let accessKey = "";
  for (let { name, value } of msg.attributes) {
    switch (name) {
      case "label":
        label = value;
        break;
      case "accesskey":
        accessKey = value;
        break;
    }
  }
  return { label, accessKey, callback };
}

var gXPInstallObserver = {
  pendingInstalls: new WeakMap(),

  showInstallConfirmation(browser, installInfo, height = undefined) {
    // If the confirmation notification is already open cache the installInfo
    // and the new confirmation will be shown later
    if (
      PopupNotifications.getNotification("addon-install-confirmation", browser)
    ) {
      let pending = this.pendingInstalls.get(browser);
      if (pending) {
        pending.push(installInfo);
      } else {
        this.pendingInstalls.set(browser, [installInfo]);
      }
      return;
    }

    let showNextConfirmation = () => {
      // Make sure the browser is still alive.
      if (!gBrowser.browsers.includes(browser)) {
        return;
      }

      let pending = this.pendingInstalls.get(browser);
      if (pending && pending.length) {
        this.showInstallConfirmation(browser, pending.shift());
      }
    };

    // If all installs have already been cancelled in some way then just show
    // the next confirmation
    if (
      installInfo.installs.every(i => i.state != AddonManager.STATE_DOWNLOADED)
    ) {
      showNextConfirmation();
      return;
    }

    // Make notifications persistent
    var options = {
      displayURI: installInfo.originatingURI,
      persistent: true,
      hideClose: true,
      popupOptions: {
        position: "bottomright topright",
      },
    };

    let acceptInstallation = () => {
      for (let install of installInfo.installs) {
        install.install();
      }
      installInfo = null;

      Glean.securityUi.events.accumulateSingleSample(
        Ci.nsISecurityUITelemetry.WARNING_CONFIRM_ADDON_INSTALL_CLICK_THROUGH
      );
    };

    let cancelInstallation = () => {
      if (installInfo) {
        for (let install of installInfo.installs) {
          // The notification may have been closed because the add-ons got
          // cancelled elsewhere, only try to cancel those that are still
          // pending install.
          if (install.state != AddonManager.STATE_CANCELLED) {
            install.cancel();
          }
        }
      }

      showNextConfirmation();
    };

    let unsigned = installInfo.installs.filter(
      i => i.addon.signedState <= AddonManager.SIGNEDSTATE_MISSING
    );
    let someUnsigned =
      !!unsigned.length && unsigned.length < installInfo.installs.length;

    options.eventCallback = aEvent => {
      switch (aEvent) {
        case "removed":
          cancelInstallation();
          break;
        case "shown":
          let addonList = document.getElementById(
            "addon-install-confirmation-content"
          );
          while (addonList.firstChild) {
            addonList.firstChild.remove();
          }

          for (let install of installInfo.installs) {
            let container = document.createXULElement("hbox");

            let name = document.createXULElement("label");
            name.setAttribute("value", install.addon.name);
            name.setAttribute("class", "addon-install-confirmation-name");
            container.appendChild(name);

            if (
              someUnsigned &&
              install.addon.signedState <= AddonManager.SIGNEDSTATE_MISSING
            ) {
              let unsignedLabel = document.createXULElement("label");
              document.l10n.setAttributes(
                unsignedLabel,
                "popup-notification-addon-install-unsigned"
              );
              unsignedLabel.setAttribute(
                "class",
                "addon-install-confirmation-unsigned"
              );
              container.appendChild(unsignedLabel);
            }

            addonList.appendChild(container);
          }
          break;
      }
    };

    options.learnMoreURL = Services.urlFormatter.formatURLPref(
      "app.support.baseURL"
    );

    let msgId;
    let notification = document.getElementById(
      "addon-install-confirmation-notification"
    );
    if (unsigned.length == installInfo.installs.length) {
      // None of the add-ons are verified
      msgId = "addon-confirm-install-unsigned-message";
      notification.setAttribute("warning", "true");
      options.learnMoreURL += "unsigned-addons";
    } else if (!unsigned.length) {
      // All add-ons are verified or don't need to be verified
      msgId = "addon-confirm-install-message";
      notification.removeAttribute("warning");
      options.learnMoreURL += "find-and-install-add-ons";
    } else {
      // Some of the add-ons are unverified, the list of names will indicate
      // which
      msgId = "addon-confirm-install-some-unsigned-message";
      notification.setAttribute("warning", "true");
      options.learnMoreURL += "unsigned-addons";
    }
    const addonCount = installInfo.installs.length;
    const messageString = lazy.l10n.formatValueSync(msgId, { addonCount });

    const [acceptMsg, cancelMsg] = lazy.l10n.formatMessagesSync([
      "addon-install-accept-button",
      "addon-install-cancel-button",
    ]);
    const action = buildNotificationAction(acceptMsg, acceptInstallation);
    const secondaryAction = buildNotificationAction(cancelMsg, () => {});

    if (height) {
      notification.style.minHeight = height + "px";
    }

    let tab = gBrowser.getTabForBrowser(browser);
    if (tab) {
      gBrowser.selectedTab = tab;
    }

    let popup = PopupNotifications.show(
      browser,
      "addon-install-confirmation",
      messageString,
      gUnifiedExtensions.getPopupAnchorID(browser, window),
      action,
      [secondaryAction],
      options
    );

    removeNotificationOnEnd(popup, installInfo.installs);

    Glean.securityUi.events.accumulateSingleSample(
      Ci.nsISecurityUITelemetry.WARNING_CONFIRM_ADDON_INSTALL
    );
  },

  // IDs of addon install related notifications, passed by this file
  // (browser-addons.js) to PopupNotifications.show(). The only exception is
  // "addon-webext-permissions" (from browser/modules/ExtensionsUI.sys.mjs),
  // which can not only be triggered during add-on installation, but also
  // later, when the extension uses the browser.permissions.request() API.
  NOTIFICATION_IDS: [
    "addon-install-blocked",
    "addon-install-confirmation",
    "addon-install-failed",
    "addon-install-origin-blocked",
    "addon-install-webapi-blocked",
    "addon-install-policy-blocked",
    "addon-progress",
    "addon-webext-permissions",
    "xpinstall-disabled",
  ],

  /**
   * Remove all opened addon installation notifications
   *
   * @param {*} browser - Browser to remove notifications for
   * @returns {boolean} - true if notifications have been removed.
   */
  removeAllNotifications(browser) {
    let notifications = this.NOTIFICATION_IDS.map(id =>
      PopupNotifications.getNotification(id, browser)
    ).filter(notification => notification != null);

    PopupNotifications.remove(notifications, true);

    return !!notifications.length;
  },

  logWarningFullScreenInstallBlocked() {
    // If notifications have been removed, log a warning to the website console
    let consoleMsg = Cc["@mozilla.org/scripterror;1"].createInstance(
      Ci.nsIScriptError
    );
    const message = lazy.l10n.formatValueSync(
      "addon-install-full-screen-blocked"
    );
    consoleMsg.initWithWindowID(
      message,
      gBrowser.currentURI.spec,
      0,
      0,
      Ci.nsIScriptError.warningFlag,
      "FullScreen",
      gBrowser.selectedBrowser.innerWindowID
    );
    Services.console.logMessage(consoleMsg);
  },

  async observe(aSubject, aTopic) {
    var installInfo = aSubject.wrappedJSObject;
    var browser = installInfo.browser;

    // Make sure the browser is still alive.
    if (!browser || !gBrowser.browsers.includes(browser)) {
      return;
    }

    // Make notifications persistent
    var options = {
      displayURI: installInfo.originatingURI,
      persistent: true,
      hideClose: true,
      timeout: Date.now() + 30000,
      popupOptions: {
        position: "bottomright topright",
      },
    };

    switch (aTopic) {
      case "addon-install-disabled": {
        let msgId, action, secondaryActions;
        if (Services.prefs.prefIsLocked("xpinstall.enabled")) {
          msgId = "xpinstall-disabled-by-policy";
          action = null;
          secondaryActions = null;
        } else {
          msgId = "xpinstall-disabled";
          const [disabledMsg, cancelMsg] = await lazy.l10n.formatMessages([
            "xpinstall-disabled-button",
            "addon-install-cancel-button",
          ]);
          action = buildNotificationAction(disabledMsg, () => {
            Services.prefs.setBoolPref("xpinstall.enabled", true);
          });
          secondaryActions = [buildNotificationAction(cancelMsg, () => {})];
        }

        PopupNotifications.show(
          browser,
          "xpinstall-disabled",
          await lazy.l10n.formatValue(msgId),
          gUnifiedExtensions.getPopupAnchorID(browser, window),
          action,
          secondaryActions,
          options
        );
        break;
      }
      case "addon-install-fullscreen-blocked": {
        // AddonManager denied installation because we are in DOM fullscreen
        this.logWarningFullScreenInstallBlocked();
        break;
      }
      case "addon-install-webapi-blocked":
      case "addon-install-policy-blocked":
      case "addon-install-origin-blocked": {
        const msgId =
          aTopic == "addon-install-policy-blocked"
            ? "addon-install-domain-blocked-by-policy"
            : "xpinstall-prompt";
        let messageString = await lazy.l10n.formatValue(msgId);
        if (Services.policies) {
          let extensionSettings = Services.policies.getExtensionSettings("*");
          if (
            extensionSettings &&
            "blocked_install_message" in extensionSettings
          ) {
            messageString += " " + extensionSettings.blocked_install_message;
          }
        }

        options.removeOnDismissal = true;
        options.persistent = false;
        Glean.securityUi.events.accumulateSingleSample(
          Ci.nsISecurityUITelemetry.WARNING_ADDON_ASKING_PREVENTED
        );
        let popup = PopupNotifications.show(
          browser,
          aTopic,
          messageString,
          gUnifiedExtensions.getPopupAnchorID(browser, window),
          null,
          null,
          options
        );
        removeNotificationOnEnd(popup, installInfo.installs);
        break;
      }
      case "addon-install-blocked": {
        // Dismiss the progress notification.  Note that this is bad if
        // there are multiple simultaneous installs happening, see
        // bug 1329884 for a longer explanation.
        let progressNotification = PopupNotifications.getNotification(
          "addon-progress",
          browser
        );
        if (progressNotification) {
          progressNotification.remove();
        }

        // The informational content differs somewhat for site permission
        // add-ons. AOM no longer supports installing multiple addons,
        // so the array handling here is vestigial.
        let isSitePermissionAddon = installInfo.installs.every(
          ({ addon }) => addon?.type === lazy.SITEPERMS_ADDON_TYPE
        );
        let hasHost = false;
        let headerId, msgId;
        if (isSitePermissionAddon) {
          // At present, WebMIDI is the only consumer of the site permission
          // add-on infrastructure, and so we can hard-code a midi string here.
          // If and when we use it for other things, we'll need to plumb that
          // information through. See bug 1826747.
          headerId = "site-permission-install-first-prompt-midi-header";
          msgId = "site-permission-install-first-prompt-midi-message";
        } else if (options.displayURI) {
          // PopupNotifications.show replaces <> with options.name.
          headerId = { id: "xpinstall-prompt-header", args: { host: "<>" } };
          // BrowserUIUtils.getLocalizedFragment replaces %1$S with options.name.
          msgId = { id: "xpinstall-prompt-message", args: { host: "%1$S" } };
          options.name = options.displayURI.displayHost;
          hasHost = true;
        } else {
          headerId = "xpinstall-prompt-header-unknown";
          msgId = "xpinstall-prompt-message-unknown";
        }
        const [headerString, msgString] = await lazy.l10n.formatValues([
          headerId,
          msgId,
        ]);

        // displayURI becomes it's own label, so we unset it for this panel. It will become part of the
        // messageString above.
        let displayURI = options.displayURI;
        options.displayURI = undefined;

        options.eventCallback = topic => {
          if (topic !== "showing") {
            return;
          }
          let doc = browser.ownerDocument;
          let message = doc.getElementById("addon-install-blocked-message");
          // We must remove any prior use of this panel message in this window.
          while (message.firstChild) {
            message.firstChild.remove();
          }

          if (!hasHost) {
            message.textContent = msgString;
          } else {
            let b = doc.createElementNS("http://www.w3.org/1999/xhtml", "b");
            b.textContent = options.name;
            let fragment = BrowserUIUtils.getLocalizedFragment(
              doc,
              msgString,
              b
            );
            message.appendChild(fragment);
          }

          let article = isSitePermissionAddon
            ? "site-permission-addons"
            : "unlisted-extensions-risks";
          let learnMore = doc.getElementById("addon-install-blocked-info");
          learnMore.setAttribute("support-page", article);
        };
        Glean.securityUi.events.accumulateSingleSample(
          Ci.nsISecurityUITelemetry.WARNING_ADDON_ASKING_PREVENTED
        );

        const [
          installMsg,
          dontAllowMsg,
          neverAllowMsg,
          neverAllowAndReportMsg,
        ] = await lazy.l10n.formatMessages([
          "xpinstall-prompt-install",
          "xpinstall-prompt-dont-allow",
          "xpinstall-prompt-never-allow",
          "xpinstall-prompt-never-allow-and-report",
        ]);

        const action = buildNotificationAction(installMsg, () => {
          Glean.securityUi.events.accumulateSingleSample(
            Ci.nsISecurityUITelemetry
              .WARNING_ADDON_ASKING_PREVENTED_CLICK_THROUGH
          );
          installInfo.install();
        });

        const neverAllowCallback = () => {
          SitePermissions.setForPrincipal(
            browser.contentPrincipal,
            "install",
            SitePermissions.BLOCK
          );
          for (let install of installInfo.installs) {
            if (install.state != AddonManager.STATE_CANCELLED) {
              install.cancel();
            }
          }
          if (installInfo.cancel) {
            installInfo.cancel();
          }
        };

        const declineActions = [
          buildNotificationAction(dontAllowMsg, () => {
            for (let install of installInfo.installs) {
              if (install.state != AddonManager.STATE_CANCELLED) {
                install.cancel();
              }
            }
            if (installInfo.cancel) {
              installInfo.cancel();
            }
          }),
          buildNotificationAction(neverAllowMsg, neverAllowCallback),
        ];

        if (isSitePermissionAddon) {
          // Restrict this to site permission add-ons for now pending a decision
          // from product about how to approach this for extensions.
          declineActions.push(
            buildNotificationAction(neverAllowAndReportMsg, () => {
              AMTelemetry.recordSuspiciousSiteEvent({ displayURI });
              neverAllowCallback();
            })
          );
        }

        let popup = PopupNotifications.show(
          browser,
          aTopic,
          headerString,
          gUnifiedExtensions.getPopupAnchorID(browser, window),
          action,
          declineActions,
          options
        );
        removeNotificationOnEnd(popup, installInfo.installs);
        break;
      }
      case "addon-install-started": {
        // If all installs have already been downloaded then there is no need to
        // show the download progress
        if (
          installInfo.installs.every(
            aInstall => aInstall.state == AddonManager.STATE_DOWNLOADED
          )
        ) {
          return;
        }

        const messageString = lazy.l10n.formatValueSync(
          "addon-downloading-and-verifying",
          { addonCount: installInfo.installs.length }
        );
        options.installs = installInfo.installs;
        options.contentWindow = browser.contentWindow;
        options.sourceURI = browser.currentURI;
        options.eventCallback = function (aEvent) {
          switch (aEvent) {
            case "removed":
              options.contentWindow = null;
              options.sourceURI = null;
              break;
          }
        };

        const [acceptMsg, cancelMsg] = lazy.l10n.formatMessagesSync([
          "addon-install-accept-button",
          "addon-install-cancel-button",
        ]);

        const action = buildNotificationAction(acceptMsg, () => {});
        action.disabled = true;

        const secondaryAction = buildNotificationAction(cancelMsg, () => {
          for (let install of installInfo.installs) {
            if (install.state != AddonManager.STATE_CANCELLED) {
              install.cancel();
            }
          }
        });

        let notification = PopupNotifications.show(
          browser,
          "addon-progress",
          messageString,
          gUnifiedExtensions.getPopupAnchorID(browser, window),
          action,
          [secondaryAction],
          options
        );
        notification._startTime = Date.now();

        break;
      }
      case "addon-install-failed": {
        options.removeOnDismissal = true;
        options.persistent = false;

        // TODO This isn't terribly ideal for the multiple failure case
        for (let install of installInfo.installs) {
          let host;
          try {
            host = options.displayURI.host;
          } catch (e) {
            // displayURI might be missing or 'host' might throw for non-nsStandardURL nsIURIs.
          }

          if (!host) {
            host =
              install.sourceURI instanceof Ci.nsIStandardURL &&
              install.sourceURI.host;
          }

          let messageString;
          if (
            install.addon &&
            !Services.policies.mayInstallAddon(install.addon)
          ) {
            messageString = lazy.l10n.formatValueSync(
              "addon-installation-blocked-by-policy",
              { addonName: install.name, addonId: install.addon.id }
            );
            let extensionSettings = Services.policies.getExtensionSettings(
              install.addon.id
            );
            if (
              extensionSettings &&
              "blocked_install_message" in extensionSettings
            ) {
              messageString += " " + extensionSettings.blocked_install_message;
            }
          } else {
            // TODO bug 1834484: simplify computation of isLocal.
            const isLocal = !host;
            let errorId = ERROR_L10N_IDS.get(install.error)?.[isLocal ? 1 : 0];
            const args = {
              addonName: install.name,
              appVersion: Services.appinfo.version,
            };
            // TODO: Bug 1846725 - when there is no error ID (which shouldn't
            // happen but... we never know) we use the "incompatible" error
            // message for now but we should have a better error message
            // instead.
            if (!errorId) {
              errorId = "addon-install-error-incompatible";
            }
            messageString = lazy.l10n.formatValueSync(errorId, args);
          }

          // Add Learn More link when refusing to install an unsigned add-on
          if (install.error == AddonManager.ERROR_SIGNEDSTATE_REQUIRED) {
            options.learnMoreURL =
              Services.urlFormatter.formatURLPref("app.support.baseURL") +
              "unsigned-addons";
          }

          let notificationId = aTopic;

          const isBlocklistError = [
            AddonManager.ERROR_BLOCKLISTED,
            AddonManager.ERROR_SOFT_BLOCKED,
          ].includes(install.error);

          // On blocklist-related install failures:
          // - use "addon-install-failed-blocklist" as the notificationId
          //   (which will use the popupnotification with id
          //   "addon-install-failed-blocklist-notification" defined
          //   in popup-notification.inc)
          // - add an eventCallback that will take care of filling in the
          //   blocklistURL into the href attribute of the link element
          //   with id "addon-install-failed-blocklist-info"
          if (isBlocklistError) {
            const blocklistURL = await install.addon?.getBlocklistURL();
            notificationId = `${aTopic}-blocklist`;
            options.eventCallback = topic => {
              if (topic !== "showing") {
                return;
              }
              let doc = browser.ownerDocument;
              let blocklistURLEl = doc.getElementById(
                "addon-install-failed-blocklist-info"
              );
              if (blocklistURL) {
                blocklistURLEl.setAttribute("href", blocklistURL);
              } else {
                blocklistURLEl.removeAttribute("href");
              }
            };
          }

          PopupNotifications.show(
            browser,
            notificationId,
            messageString,
            gUnifiedExtensions.getPopupAnchorID(browser, window),
            null,
            null,
            options
          );

          // Can't have multiple notifications with the same ID, so stop here.
          break;
        }
        this._removeProgressNotification(browser);
        break;
      }
      case "addon-install-confirmation": {
        let showNotification = () => {
          let height = undefined;

          if (PopupNotifications.isPanelOpen) {
            let rect = window.windowUtils.getBoundsWithoutFlushing(
              document.getElementById("addon-progress-notification")
            );
            height = rect.height;
          }

          this._removeProgressNotification(browser);
          this.showInstallConfirmation(browser, installInfo, height);
        };

        let progressNotification = PopupNotifications.getNotification(
          "addon-progress",
          browser
        );
        if (progressNotification) {
          let downloadDuration = Date.now() - progressNotification._startTime;
          let securityDelay =
            Services.prefs.getIntPref("security.dialog_enable_delay") -
            downloadDuration;
          if (securityDelay > 0) {
            setTimeout(() => {
              // The download may have been cancelled during the security delay
              if (
                PopupNotifications.getNotification("addon-progress", browser)
              ) {
                showNotification();
              }
            }, securityDelay);
            break;
          }
        }
        showNotification();
        break;
      }
    }
  },
  _removeProgressNotification(aBrowser) {
    let notification = PopupNotifications.getNotification(
      "addon-progress",
      aBrowser
    );
    if (notification) {
      notification.remove();
    }
  },
};

var gExtensionsNotifications = {
  initialized: false,
  init() {
    this.updateAlerts();
    this.boundUpdate = this.updateAlerts.bind(this);
    ExtensionsUI.on("change", this.boundUpdate);
    this.initialized = true;
  },

  uninit() {
    // uninit() can race ahead of init() in some cases, if that happens,
    // we have no handler to remove.
    if (!this.initialized) {
      return;
    }
    ExtensionsUI.off("change", this.boundUpdate);
  },

  _createAddonButton(l10nId, addon, callback) {
    let text = addon
      ? lazy.l10n.formatValueSync(l10nId, { addonName: addon.name })
      : lazy.l10n.formatValueSync(l10nId);
    let button = document.createXULElement("toolbarbutton");
    button.setAttribute("id", l10nId);
    button.setAttribute("wrap", "true");
    button.setAttribute("label", text);
    button.setAttribute("tooltiptext", text);
    const DEFAULT_EXTENSION_ICON =
      "chrome://mozapps/skin/extensions/extensionGeneric.svg";
    button.setAttribute("image", addon?.iconURL || DEFAULT_EXTENSION_ICON);
    button.className = "addon-banner-item subviewbutton";

    button.addEventListener("command", callback);
    PanelUI.addonNotificationContainer.appendChild(button);
  },

  updateAlerts() {
    let sideloaded = ExtensionsUI.sideloaded;
    let updates = ExtensionsUI.updates;

    let container = PanelUI.addonNotificationContainer;

    while (container.firstChild) {
      container.firstChild.remove();
    }

    let items = 0;
    if (lazy.AMBrowserExtensionsImport.canCompleteOrCancelInstalls) {
      this._createAddonButton("webext-imported-addons", null, () => {
        lazy.AMBrowserExtensionsImport.completeInstalls();
      });
      items++;
    }

    for (let update of updates) {
      if (++items > 4) {
        break;
      }
      this._createAddonButton(
        "webext-perms-update-menu-item",
        update.addon,
        () => {
          ExtensionsUI.showUpdate(gBrowser, update);
        }
      );
    }

    for (let addon of sideloaded) {
      if (++items > 4) {
        break;
      }
      this._createAddonButton("webext-perms-sideload-menu-item", addon, () => {
        // We need to hide the main menu manually because the toolbarbutton is
        // removed immediately while processing this event, and PanelUI is
        // unable to identify which panel should be closed automatically.
        PanelUI.hide();
        ExtensionsUI.showSideloaded(gBrowser, addon);
      });
    }
  },
};

var BrowserAddonUI = {
  async promptRemoveExtension(addon) {
    let { name } = addon;
    let [title, btnTitle] = await lazy.l10n.formatValues([
      { id: "addon-removal-title", args: { name } },
      { id: "addon-removal-button" },
    ]);

    let {
      BUTTON_TITLE_IS_STRING: titleString,
      BUTTON_TITLE_CANCEL: titleCancel,
      BUTTON_POS_0,
      BUTTON_POS_1,
      confirmEx,
    } = Services.prompt;
    let btnFlags = BUTTON_POS_0 * titleString + BUTTON_POS_1 * titleCancel;

    // Enable abuse report checkbox in the remove extension dialog,
    // if enabled by the about:config prefs and the addon type
    // is currently supported.
    let checkboxMessage = null;
    if (
      gAddonAbuseReportEnabled &&
      ["extension", "theme"].includes(addon.type)
    ) {
      checkboxMessage = await lazy.l10n.formatValue(
        "addon-removal-abuse-report-checkbox"
      );
    }

    // If the prompt is being used for ML model removal, use a body message
    let body = null;
    if (addon.type === "mlmodel") {
      body = await lazy.l10n.formatValue("addon-mlmodel-removal-body");
    }

    let checkboxState = { value: false };
    let result = confirmEx(
      window,
      title,
      body,
      btnFlags,
      btnTitle,
      /* button1 */ null,
      /* button2 */ null,
      checkboxMessage,
      checkboxState
    );

    return { remove: result === 0, report: checkboxState.value };
  },

  async reportAddon(addonId, _reportEntryPoint) {
    let addon = addonId && (await AddonManager.getAddonByID(addonId));
    if (!addon) {
      return;
    }

    const amoUrl = lazy.AbuseReporter.getAMOFormURL({ addonId });
    window.openTrustedLinkIn(amoUrl, "tab", {
      // Make sure the newly open tab is going to be focused, independently
      // from general user prefs.
      forceForeground: true,
    });
  },

  async removeAddon(addonId) {
    let addon = addonId && (await AddonManager.getAddonByID(addonId));
    if (!addon || !(addon.permissions & AddonManager.PERM_CAN_UNINSTALL)) {
      return;
    }

    let { remove, report } = await this.promptRemoveExtension(addon);

    if (remove) {
      // Leave the extension in pending uninstall if we are also reporting the
      // add-on.
      await addon.uninstall(report);

      if (report) {
        await this.reportAddon(addon.id, "uninstall");
      }
    }
  },

  async manageAddon(addonId) {
    let addon = addonId && (await AddonManager.getAddonByID(addonId));
    if (!addon) {
      return;
    }

    this.openAddonsMgr("addons://detail/" + encodeURIComponent(addon.id));
  },

  /**
   * Open about:addons page by given view id.
   * @param {String} aView
   *                 View id of page that will open.
   *                 e.g. "addons://discover/"
   * @param {Object} options
   *        {
   *          selectTabByViewId: If true, if there is the tab opening page having
   *                             same view id, select the tab. Else if the current
   *                             page is blank, load on it. Otherwise, open a new
   *                             tab, then load on it.
   *                             If false, if there is the tab opening
   *                             about:addoons page, select the tab and load page
   *                             for view id on it. Otherwise, leave the loading
   *                             behavior to switchToTabHavingURI().
   *                             If no options, handles as false.
   *        }
   * @returns {Promise} When the Promise resolves, returns window object loaded the
   *                    view id.
   */
  openAddonsMgr(aView, { selectTabByViewId = false } = {}) {
    return new Promise(resolve => {
      let emWindow;
      let browserWindow;

      const receivePong = function (aSubject) {
        const browserWin = aSubject.browsingContext.topChromeWindow;
        if (!emWindow || browserWin == window /* favor the current window */) {
          if (
            selectTabByViewId &&
            aSubject.gViewController.currentViewId !== aView
          ) {
            return;
          }

          emWindow = aSubject;
          browserWindow = browserWin;
        }
      };
      Services.obs.addObserver(receivePong, "EM-pong");
      Services.obs.notifyObservers(null, "EM-ping");
      Services.obs.removeObserver(receivePong, "EM-pong");

      if (emWindow) {
        if (aView && !selectTabByViewId) {
          emWindow.loadView(aView);
        }
        let tab = browserWindow.gBrowser.getTabForBrowser(
          emWindow.docShell.chromeEventHandler
        );
        browserWindow.gBrowser.selectedTab = tab;
        emWindow.focus();
        resolve(emWindow);
        return;
      }

      if (selectTabByViewId) {
        const target = isBlankPageURL(gBrowser.currentURI.spec)
          ? "current"
          : "tab";
        openTrustedLinkIn("about:addons", target);
      } else {
        // This must be a new load, else the ping/pong would have
        // found the window above.
        switchToTabHavingURI("about:addons", true);
      }

      Services.obs.addObserver(function observer(aSubject, aTopic) {
        Services.obs.removeObserver(observer, aTopic);
        if (aView) {
          aSubject.loadView(aView);
        }
        aSubject.focus();
        resolve(aSubject);
      }, "EM-loaded");
    });
  },
};

// We must declare `gUnifiedExtensions` using `var` below to avoid a
// "redeclaration" syntax error.
var gUnifiedExtensions = {
  _initialized: false,
  // buttonAlwaysVisible: true, -- based on pref, declared later.
  _buttonShownBeforeButtonOpen: null,
  _buttonBarHasMouse: false,

  // We use a `<deck>` in the extension items to show/hide messages below each
  // extension name. We have a default message for origin controls, and
  // optionally a second message shown on hover, which describes the action
  // (when clicking on the action button). We have another message shown when
  // the menu button is hovered/focused. The constants below define the indexes
  // of each message in the `<deck>`.
  MESSAGE_DECK_INDEX_DEFAULT: 0,
  MESSAGE_DECK_INDEX_HOVER: 1,
  MESSAGE_DECK_INDEX_MENU_HOVER: 2,

  init() {
    if (this._initialized) {
      return;
    }

    // Button is hidden by default, declared in navigator-toolbox.inc.xhtml.
    this._button = document.getElementById("unified-extensions-button");
    this._navbar = document.getElementById("nav-bar");
    this.updateButtonVisibility();
    this._buttonAttrObs = new MutationObserver(() => this.onButtonOpenChange());
    this._buttonAttrObs.observe(this._button, { attributeFilter: ["open"] });
    this._button.addEventListener("PopupNotificationsBeforeAnchor", this);
    this._navbar.addEventListener("mouseenter", this);
    this._navbar.addEventListener("mouseleave", this);

    gBrowser.addTabsProgressListener(this);
    window.addEventListener("TabSelect", () => this.updateAttention());
    window.addEventListener("toolbarvisibilitychange", this);

    this.permListener = () => this.updateAttention();
    lazy.ExtensionPermissions.addListener(this.permListener);

    this.onAppMenuShowing = this.onAppMenuShowing.bind(this);
    PanelUI.mainView.addEventListener("ViewShowing", this.onAppMenuShowing);
    gNavToolbox.addEventListener("customizationstarting", this);
    gNavToolbox.addEventListener("aftercustomization", this);
    CustomizableUI.addListener(this);
    AddonManager.addManagerListener(this);

    Glean.extensionsButton.prefersHiddenButton.set(!this.buttonAlwaysVisible);

    this._initialized = true;
  },

  uninit() {
    if (!this._initialized) {
      return;
    }

    this._buttonAttrObs.disconnect();
    this._button.removeEventListener("PopupNotificationsBeforeAnchor", this);

    window.removeEventListener("toolbarvisibilitychange", this);

    lazy.ExtensionPermissions.removeListener(this.permListener);
    this.permListener = null;

    PanelUI.mainView.removeEventListener("ViewShowing", this.onAppMenuShowing);
    gNavToolbox.removeEventListener("customizationstarting", this);
    gNavToolbox.removeEventListener("aftercustomization", this);
    CustomizableUI.removeListener(this);
    AddonManager.removeManagerListener(this);
  },

  onBlocklistAttentionUpdated() {
    this.updateAttention();
  },

  onAppMenuShowing() {
    document.getElementById("appMenu-extensions-themes-button").hidden =
      !this.buttonAlwaysVisible;
    document.getElementById("appMenu-unified-extensions-button").hidden =
      this.buttonAlwaysVisible;
  },

  onLocationChange(browser, webProgress, _request, _uri, flags) {
    // Only update on top-level cross-document navigations in the selected tab.
    if (
      webProgress.isTopLevel &&
      browser === gBrowser.selectedBrowser &&
      !(flags & Ci.nsIWebProgressListener.LOCATION_CHANGE_SAME_DOCUMENT)
    ) {
      this.updateAttention();
    }
  },

  updateButtonVisibility() {
    // TODO: Bug 1778684 - Auto-hide button when there is no active extension.
    let shouldShowButton =
      this.buttonAlwaysVisible ||
      // If anything is anchored to the button, keep it visible.
      this._button.open ||
      // Button will be open soon - see ensureButtonShownBeforeAttachingPanel.
      this._buttonShownBeforeButtonOpen ||
      // Items in the toolbar shift when the button hides. To prevent the user
      // from clicking on something different than they intended, never hide an
      // already-visible button while the mouse is still in the toolbar.
      (!this.button.hidden && this._buttonBarHasMouse) ||
      // Attention dot - see comment at buttonIgnoresAttention.
      (!this.buttonIgnoresAttention && this.button.hasAttribute("attention")) ||
      // Always show when customizing, because even if the button should mostly
      // be hidden, the user should be able to specify the desired location for
      // cases where the button is forcibly shown.
      CustomizationHandler.isCustomizing();

    if (shouldShowButton) {
      this._button.hidden = false;
      this._navbar.setAttribute("unifiedextensionsbuttonshown", true);
    } else {
      this._button.hidden = true;
      this._navbar.removeAttribute("unifiedextensionsbuttonshown");
    }
  },

  ensureButtonShownBeforeAttachingPanel(panel) {
    if (!this.buttonAlwaysVisible && !this._button.open) {
      // When the panel is anchored to the button, its "open" attribute will be
      // set, which visually renders as a "button pressed". Until we get there,
      // we need to make sure that the button is visible so that it can serve
      // as anchor.
      this._buttonShownBeforeButtonOpen = panel;
      this.updateButtonVisibility();
    }
  },

  onButtonOpenChange() {
    if (this._button.open) {
      this._buttonShownBeforeButtonOpen = false;
    }
    if (!this.buttonAlwaysVisible && !this._button.open) {
      this.updateButtonVisibility();
    }
  },

  // Update the attention indicator for the whole unified extensions button.
  updateAttention() {
    let permissionsAttention = false;
    let quarantinedAttention = false;
    let blocklistAttention = AddonManager.shouldShowBlocklistAttention();

    // Computing the OriginControls state for all active extensions is potentially
    // more expensive, and so we don't compute it if we have already determined that
    // there is a blocklist attention to be shown.
    if (!blocklistAttention) {
      for (let policy of this.getActivePolicies()) {
        let widget = this.browserActionFor(policy)?.widget;

        // Only show for extensions which are not already visible in the toolbar.
        if (!widget || widget.areaType !== CustomizableUI.TYPE_TOOLBAR) {
          if (lazy.OriginControls.getAttentionState(policy, window).attention) {
            permissionsAttention = true;
            break;
          }
        }
      }

      // If the domain is quarantined and we have extensions not allowed, we'll
      // show a notification in the panel so we want to let the user know about
      // it.
      quarantinedAttention = this._shouldShowQuarantinedNotification();
    }

    this.button.toggleAttribute(
      "attention",
      quarantinedAttention || permissionsAttention || blocklistAttention
    );
    let msgId = permissionsAttention
      ? "unified-extensions-button-permissions-needed"
      : "unified-extensions-button";
    // Quarantined state takes precedence over anything else.
    if (quarantinedAttention) {
      msgId = "unified-extensions-button-quarantined";
    }
    // blocklistAttention state takes precedence over the other ones
    // because it is dismissible and, once dismissed, the tooltip will
    // show one of the other messages if appropriate.
    if (blocklistAttention) {
      msgId = "unified-extensions-button-blocklisted";
    }
    this.button.ownerDocument.l10n.setAttributes(this.button, msgId);
    if (!this.buttonAlwaysVisible && !this.buttonIgnoresAttention) {
      if (blocklistAttention) {
        this.recordButtonTelemetry("attention_blocklist");
      } else if (permissionsAttention || quarantinedAttention) {
        this.recordButtonTelemetry("attention_permission_denied");
      }
      this.updateButtonVisibility();
    }
  },

  // Get the anchor to use with PopupNotifications.show(). If you add a new use
  // of this method, make sure to update gXPInstallObserver.NOTIFICATION_IDS!
  // If the new ID is not added in NOTIFICATION_IDS, consider handling the case
  // in the "PopupNotificationsBeforeAnchor" handler elsewhere in this file.
  getPopupAnchorID(aBrowser, aWindow) {
    const anchorID = "unified-extensions-button";
    const attr = anchorID + "popupnotificationanchor";

    if (!aBrowser[attr]) {
      // A hacky way of setting the popup anchor outside the usual url bar
      // icon box, similar to how it was done for CFR.
      // See: https://searchfox.org/mozilla-central/rev/c5c002f81f08a73e04868e0c2bf0eb113f200b03/toolkit/modules/PopupNotifications.sys.mjs#40
      aBrowser[attr] = aWindow.document.getElementById(
        anchorID
        // Anchor on the toolbar icon to position the popup right below the
        // button.
      ).firstElementChild;
    }

    return anchorID;
  },

  get button() {
    return this._button;
  },

  /**
   * Gets a list of active WebExtensionPolicy instances of type "extension",
   * sorted alphabetically based on add-on's names. Optionally, filter out
   * extensions with browser action.
   *
   * @param {bool} all When set to true (the default), return the list of all
   *                   active policies, including the ones that have a
   *                   browser action. Otherwise, extensions with browser
   *                   action are filtered out.
   * @returns {Array<WebExtensionPolicy>} An array of active policies.
   */
  getActivePolicies(all = true) {
    let policies = WebExtensionPolicy.getActiveExtensions();
    policies = policies.filter(policy => {
      let { extension } = policy;
      if (!policy.active || extension?.type !== "extension") {
        return false;
      }

      // Ignore hidden and extensions that cannot access the current window
      // (because of PB mode when we are in a private window), since users
      // cannot do anything with those extensions anyway.
      if (extension.isHidden || !policy.canAccessWindow(window)) {
        return false;
      }

      return all || !extension.hasBrowserActionUI;
    });

    policies.sort((a, b) => a.name.localeCompare(b.name));
    return policies;
  },

  /**
   * Returns true when there are active extensions listed/shown in the unified
   * extensions panel, and false otherwise (e.g. when extensions are pinned in
   * the toolbar OR there are 0 active extensions).
   *
   * @returns {boolean} Whether there are extensions listed in the panel.
   */
  hasExtensionsInPanel() {
    const policies = this.getActivePolicies();

    return !!policies
      .map(policy => this.browserActionFor(policy)?.widget)
      .filter(widget => {
        return (
          !widget ||
          widget?.areaType !== CustomizableUI.TYPE_TOOLBAR ||
          widget?.forWindow(window).overflowed
        );
      }).length;
  },

  handleEvent(event) {
    switch (event.type) {
      case "ViewShowing":
        this.onPanelViewShowing(event.target);
        break;

      case "ViewHiding":
        this.onPanelViewHiding(event.target);
        break;

      case "PopupNotificationsBeforeAnchor":
        {
          const popupnotification = PopupNotifications.panel.firstElementChild;
          const popupid = popupnotification?.getAttribute("popupid");
          if (popupid === "addon-webext-permissions") {
            // "addon-webext-permissions" is also in NOTIFICATION_IDS, but to
            // distinguish it from other cases, give it a separate reason.
            this.recordButtonTelemetry("extension_permission_prompt");
          } else if (gXPInstallObserver.NOTIFICATION_IDS.includes(popupid)) {
            this.recordButtonTelemetry("addon_install_doorhanger");
          } else {
            console.error(`Unrecognized notification ID: ${popupid}`);
          }
          this.ensureButtonShownBeforeAttachingPanel(PopupNotifications.panel);
        }
        break;

      case "mouseenter":
        this._buttonBarHasMouse = true;
        break;

      case "mouseleave":
        this._buttonBarHasMouse = false;
        this.updateButtonVisibility();
        break;

      case "customizationstarting":
        this.panel.hidePopup();
        this.recordButtonTelemetry("customize");
        this.updateButtonVisibility();
        break;

      case "aftercustomization":
        this.updateButtonVisibility();
        break;

      case "toolbarvisibilitychange":
        this.onToolbarVisibilityChange(event.target.id, event.detail.visible);
        break;
    }
  },

  onPanelViewShowing(panelview) {
    const list = panelview.querySelector(".unified-extensions-list");
    // Only add extensions that do not have a browser action in this list since
    // the extensions with browser action have CUI widgets and will appear in
    // the panel (or toolbar) via the CUI mechanism.
    for (const policy of this.getActivePolicies(/* all */ false)) {
      const item = document.createElement("unified-extensions-item");
      item.setExtension(policy.extension);
      list.appendChild(item);
    }

    const container = panelview.querySelector(
      "#unified-extensions-messages-container"
    );

    if (this.blocklistAttentionInfo?.shouldShow) {
      this._messageBarBlocklist = this._createBlocklistMessageBar(container);
    } else {
      this._messageBarBlocklist?.remove();
      this._messageBarBlocklist = null;
    }

    const shouldShowQuarantinedNotification =
      this._shouldShowQuarantinedNotification();
    if (shouldShowQuarantinedNotification) {
      if (!this._messageBarQuarantinedDomain) {
        this._messageBarQuarantinedDomain = this._makeMessageBar({
          messageBarFluentId:
            "unified-extensions-mb-quarantined-domain-message-3",
          supportPage: "quarantined-domains",
          dismissible: false,
        });
        this._messageBarQuarantinedDomain
          .querySelector("a")
          .addEventListener("click", () => {
            this.togglePanel();
          });
      }

      container.appendChild(this._messageBarQuarantinedDomain);
    } else if (
      !shouldShowQuarantinedNotification &&
      this._messageBarQuarantinedDomain &&
      container.contains(this._messageBarQuarantinedDomain)
    ) {
      container.removeChild(this._messageBarQuarantinedDomain);
      this._messageBarQuarantinedDomain = null;
    }
  },

  onPanelViewHiding(panelview) {
    if (window.closed) {
      return;
    }
    const list = panelview.querySelector(".unified-extensions-list");
    while (list.lastChild) {
      list.lastChild.remove();
    }
    // If temporary access was granted, (maybe) clear attention indicator.
    requestAnimationFrame(() => this.updateAttention());
  },

  onToolbarVisibilityChange(toolbarId, isVisible) {
    // A list of extension widget IDs (possibly empty).
    let widgetIDs;

    try {
      widgetIDs = CustomizableUI.getWidgetIdsInArea(toolbarId).filter(
        CustomizableUI.isWebExtensionWidget
      );
    } catch {
      // Do nothing if the area does not exist for some reason.
      return;
    }

    // The list of overflowed extensions in the extensions panel.
    const overflowedExtensionsList = this.panel.querySelector(
      "#overflowed-extensions-list"
    );

    // We are going to move all the extension widgets via DOM manipulation
    // *only* so that it looks like these widgets have moved (and users will
    // see that) but CUI still thinks the widgets haven't been moved.
    //
    // We can move the extension widgets either from the toolbar to the
    // extensions panel OR the other way around (when the toolbar becomes
    // visible again).
    for (const widgetID of widgetIDs) {
      const widget = CustomizableUI.getWidget(widgetID);
      if (!widget) {
        continue;
      }

      if (isVisible) {
        this._maybeMoveWidgetNodeBack(widget.id);
      } else {
        const { node } = widget.forWindow(window);
        // Artificially overflow the extension widget in the extensions panel
        // when the toolbar is hidden.
        node.setAttribute("overflowedItem", true);
        node.setAttribute("artificallyOverflowed", true);
        // This attribute forces browser action popups to be anchored to the
        // extensions button.
        node.setAttribute("cui-anchorid", "unified-extensions-button");
        overflowedExtensionsList.appendChild(node);

        this._updateWidgetClassName(widgetID, /* inPanel */ true);
      }
    }
  },

  _maybeMoveWidgetNodeBack(widgetID) {
    const widget = CustomizableUI.getWidget(widgetID);
    if (!widget) {
      return;
    }

    // We only want to move back widget nodes that have been manually moved
    // previously via `onToolbarVisibilityChange()`.
    const { node } = widget.forWindow(window);
    if (!node.hasAttribute("artificallyOverflowed")) {
      return;
    }

    const { area, position } = CustomizableUI.getPlacementOfWidget(widgetID);

    // This is where we are going to re-insert the extension widgets (DOM
    // nodes) but we need to account for some hidden DOM nodes already present
    // in this container when determining where to put the nodes back.
    const container = CustomizableUI.getCustomizationTarget(
      document.getElementById(area)
    );

    let moved = false;
    let currentPosition = 0;

    for (const child of container.childNodes) {
      const isSkipToolbarset = child.getAttribute("skipintoolbarset") == "true";
      if (isSkipToolbarset && child !== container.lastChild) {
        continue;
      }

      if (currentPosition === position) {
        child.before(node);
        moved = true;
        break;
      }

      if (child === container.lastChild) {
        child.after(node);
        moved = true;
        break;
      }

      currentPosition++;
    }

    if (moved) {
      // Remove the attribute set when we artificially overflow the widget.
      node.removeAttribute("overflowedItem");
      node.removeAttribute("artificallyOverflowed");
      node.removeAttribute("cui-anchorid");

      this._updateWidgetClassName(widgetID, /* inPanel */ false);
    }
  },

  _panel: null,
  get panel() {
    // Lazy load the unified-extensions-panel panel the first time we need to
    // display it.
    if (!this._panel) {
      let template = document.getElementById(
        "unified-extensions-panel-template"
      );
      template.replaceWith(template.content);
      this._panel = document.getElementById("unified-extensions-panel");
      let customizationArea = this._panel.querySelector(
        "#unified-extensions-area"
      );
      CustomizableUI.registerPanelNode(
        customizationArea,
        CustomizableUI.AREA_ADDONS
      );
      CustomizableUI.addPanelCloseListeners(this._panel);

      this._panel
        .querySelector("#unified-extensions-manage-extensions")
        .addEventListener("command", () => {
          BrowserAddonUI.openAddonsMgr("addons://list/extension");
        });

      // Lazy-load the l10n strings. Those strings are used for the CUI and
      // non-CUI extensions in the unified extensions panel.
      document
        .getElementById("unified-extensions-context-menu")
        .querySelectorAll("[data-lazy-l10n-id]")
        .forEach(el => {
          el.setAttribute("data-l10n-id", el.getAttribute("data-lazy-l10n-id"));
          el.removeAttribute("data-lazy-l10n-id");
        });
    }
    return this._panel;
  },

  // `aEvent` and `reason` are optional. If `reason` is specified, it should be
  // a valid argument to gUnifiedExtensions.recordButtonTelemetry().
  async togglePanel(aEvent, reason) {
    if (!CustomizationHandler.isCustomizing()) {
      if (aEvent) {
        if (
          // On MacOS, ctrl-click will send a context menu event from the
          // widget, so we don't want to bring up the panel when ctrl key is
          // pressed.
          (aEvent.type == "mousedown" &&
            (aEvent.button !== 0 ||
              (AppConstants.platform === "macosx" && aEvent.ctrlKey))) ||
          (aEvent.type === "keypress" &&
            aEvent.charCode !== KeyEvent.DOM_VK_SPACE &&
            aEvent.keyCode !== KeyEvent.DOM_VK_RETURN)
        ) {
          return;
        }

        // The button should directly open `about:addons` when the user does not
        // have any active extensions listed in the unified extensions panel.
        if (!this.hasExtensionsInPanel()) {
          let viewID;
          if (
            Services.prefs.getBoolPref("extensions.getAddons.showPane", true) &&
            // Unconditionally show the list of extensions if the blocklist
            // attention flag has been shown on the extension panel button.
            !AddonManager.shouldShowBlocklistAttention()
          ) {
            viewID = "addons://discover/";
          } else {
            viewID = "addons://list/extension";
          }
          await BrowserAddonUI.openAddonsMgr(viewID);
          return;
        }
      }

      this.blocklistAttentionInfo =
        await AddonManager.getBlocklistAttentionInfo();

      let panel = this.panel;

      if (!this._listView) {
        this._listView = PanelMultiView.getViewNode(
          document,
          "unified-extensions-view"
        );
        this._listView.addEventListener("ViewShowing", this);
        this._listView.addEventListener("ViewHiding", this);
      }

      if (this._button.open) {
        PanelMultiView.hidePopup(panel);
        this._button.open = false;
      } else {
        // Overflow extensions placed in collapsed toolbars, if any.
        for (const toolbarId of CustomizableUI.getCollapsedToolbarIds(window)) {
          // We pass `false` because all these toolbars are collapsed.
          this.onToolbarVisibilityChange(toolbarId, /* isVisible */ false);
        }

        panel.hidden = false;
        this.recordButtonTelemetry(reason || "extensions_panel_showing");
        this.ensureButtonShownBeforeAttachingPanel(panel);
        PanelMultiView.openPopup(panel, this._button, {
          position: "bottomright topright",
          triggerEvent: aEvent,
        });
      }
    }

    // We always dispatch an event (useful for testing purposes).
    window.dispatchEvent(new CustomEvent("UnifiedExtensionsTogglePanel"));
  },

  async openPanel(event, reason) {
    if (this._button.open) {
      throw new Error("Tried to open panel whilst a panel was already open!");
    }
    if (CustomizationHandler.isCustomizing()) {
      throw new Error("Cannot open panel while in Customize mode!");
    }

    if (event?.sourceEvent?.target.id === "appMenu-unified-extensions-button") {
      Glean.extensionsButton.openViaAppMenu.record({
        is_extensions_panel_empty: !this.hasExtensionsInPanel(),
        is_extensions_button_visible: !this._button.hidden,
      });
    }

    await this.togglePanel(event, reason);
  },

  updateContextMenu(menu, event) {
    // When the context menu is open, `onpopupshowing` is called when menu
    // items open sub-menus. We don't want to update the context menu in this
    // case.
    if (event.target.id !== "unified-extensions-context-menu") {
      return;
    }

    const id = this._getExtensionId(menu);
    const widgetId = this._getWidgetId(menu);
    const forBrowserAction = !!widgetId;

    const pinButton = menu.querySelector(
      ".unified-extensions-context-menu-pin-to-toolbar"
    );
    const removeButton = menu.querySelector(
      ".unified-extensions-context-menu-remove-extension"
    );
    const reportButton = menu.querySelector(
      ".unified-extensions-context-menu-report-extension"
    );
    const menuSeparator = menu.querySelector(
      ".unified-extensions-context-menu-management-separator"
    );
    const moveUp = menu.querySelector(
      ".unified-extensions-context-menu-move-widget-up"
    );
    const moveDown = menu.querySelector(
      ".unified-extensions-context-menu-move-widget-down"
    );

    for (const element of [menuSeparator, pinButton, moveUp, moveDown]) {
      element.hidden = !forBrowserAction;
    }

    reportButton.hidden = !gAddonAbuseReportEnabled;
    // We use this syntax instead of async/await to not block this method that
    // updates the context menu. This avoids the context menu to be out of sync
    // on macOS.
    AddonManager.getAddonByID(id).then(addon => {
      removeButton.disabled = !(
        addon.permissions & AddonManager.PERM_CAN_UNINSTALL
      );
    });

    if (forBrowserAction) {
      let area = CustomizableUI.getPlacementOfWidget(widgetId).area;
      let inToolbar = area != CustomizableUI.AREA_ADDONS;
      pinButton.setAttribute("checked", inToolbar);

      const placement = CustomizableUI.getPlacementOfWidget(widgetId);
      const notInPanel = placement?.area !== CustomizableUI.AREA_ADDONS;
      // We rely on the DOM nodes because CUI widgets will always exist but
      // not necessarily with DOM nodes created depending on the window. For
      // example, in PB mode, not all extensions will be listed in the panel
      // but the CUI widgets may be all created.
      if (
        notInPanel ||
        document.querySelector("#unified-extensions-area > :first-child")
          ?.id === widgetId
      ) {
        moveUp.hidden = true;
      }

      if (
        notInPanel ||
        document.querySelector("#unified-extensions-area > :last-child")?.id ===
          widgetId
      ) {
        moveDown.hidden = true;
      }
    }

    ExtensionsUI.originControlsMenu(menu, id);

    const browserAction = this.browserActionFor(WebExtensionPolicy.getByID(id));
    if (browserAction) {
      browserAction.updateContextMenu(menu);
    }
  },

  // This is registered on the top-level unified extensions context menu.
  onContextMenuCommand(menu, event) {
    // Do not close the extensions panel automatically when we move extension
    // widgets.
    const { classList } = event.target;
    if (
      classList.contains("unified-extensions-context-menu-move-widget-up") ||
      classList.contains("unified-extensions-context-menu-move-widget-down")
    ) {
      return;
    }

    this.togglePanel();
  },

  browserActionFor(policy) {
    // Ideally, we wouldn't do that because `browserActionFor()` will only be
    // defined in `global` when at least one extension has required loading the
    // `ext-browserAction` code.
    let method = lazy.ExtensionParent.apiManager.global.browserActionFor;
    return method?.(policy?.extension);
  },

  async manageExtension(menu) {
    const id = this._getExtensionId(menu);

    await BrowserAddonUI.manageAddon(id, "unifiedExtensions");
  },

  async removeExtension(menu) {
    const id = this._getExtensionId(menu);

    await BrowserAddonUI.removeAddon(id, "unifiedExtensions");
  },

  async reportExtension(menu) {
    const id = this._getExtensionId(menu);

    await BrowserAddonUI.reportAddon(id, "unified_context_menu");
  },

  _getExtensionId(menu) {
    const { triggerNode } = menu;
    return triggerNode
      .closest(".unified-extensions-item")
      ?.querySelector("toolbarbutton")?.dataset.extensionid;
  },

  _getWidgetId(menu) {
    const { triggerNode } = menu;
    return triggerNode.closest(".unified-extensions-item")?.id;
  },

  async onPinToToolbarChange(menu, event) {
    let shouldPinToToolbar = event.target.getAttribute("checked") == "true";
    // Revert the checkbox back to its original state. This is because the
    // addon context menu handlers are asynchronous, and there seems to be
    // a race where the checkbox state won't get set in time to show the
    // right state. So we err on the side of caution, and presume that future
    // attempts to open this context menu on an extension button will show
    // the same checked state that we started in.
    event.target.setAttribute("checked", !shouldPinToToolbar);

    let widgetId = this._getWidgetId(menu);
    if (!widgetId) {
      return;
    }

    // We artificially overflow extension widgets that are placed in collapsed
    // toolbars and CUI does not know about it. For end users, these widgets
    // appear in the list of overflowed extensions in the panel. When we unpin
    // and then pin one of these extensions to the toolbar, we need to first
    // move the DOM node back to where it was (i.e.  in the collapsed toolbar)
    // so that CUI can retrieve the DOM node and do the pinning correctly.
    if (shouldPinToToolbar) {
      this._maybeMoveWidgetNodeBack(widgetId);
    }

    this.pinToToolbar(widgetId, shouldPinToToolbar);
  },

  pinToToolbar(widgetId, shouldPinToToolbar) {
    let newArea = shouldPinToToolbar
      ? CustomizableUI.AREA_NAVBAR
      : CustomizableUI.AREA_ADDONS;
    let newPosition = shouldPinToToolbar ? undefined : 0;

    CustomizableUI.addWidgetToArea(widgetId, newArea, newPosition);
    // addWidgetToArea() will trigger onWidgetAdded or onWidgetMoved as needed,
    // and our handlers will call updateAttention() as needed.
  },

  async moveWidget(menu, direction) {
    // We'll move the widgets based on the DOM node positions. This is because
    // in PB mode (for example), we might not have the same extensions listed
    // in the panel but CUI does not know that. As far as CUI is concerned, all
    // extensions will likely have widgets.
    const node = menu.triggerNode.closest(".unified-extensions-item");

    // Find the element that is before or after the current widget/node to
    // move. `element` might be `null`, e.g. if the current node is the first
    // one listed in the panel (though it shouldn't be possible to call this
    // method in this case).
    let element;
    if (direction === "up" && node.previousElementSibling) {
      element = node.previousElementSibling;
    } else if (direction === "down" && node.nextElementSibling) {
      element = node.nextElementSibling;
    }

    // Now we need to retrieve the position of the CUI placement.
    const placement = CustomizableUI.getPlacementOfWidget(element?.id);
    if (placement) {
      let newPosition = placement.position;
      // That, I am not sure why this is required but it looks like we need to
      // always add one to the current position if we want to move a widget
      // down in the list.
      if (direction === "down") {
        newPosition += 1;
      }

      CustomizableUI.moveWidgetWithinArea(node.id, newPosition);
    }
  },

  onWidgetAdded(aWidgetId, aArea) {
    if (CustomizableUI.isWebExtensionWidget(aWidgetId)) {
      this.updateAttention();
    }

    // When we pin a widget to the toolbar from a narrow window, the widget
    // will be overflowed directly. In this case, we do not want to change the
    // class name since it is going to be changed by `onWidgetOverflow()`
    // below.
    if (CustomizableUI.getWidget(aWidgetId)?.forWindow(window)?.overflowed) {
      return;
    }

    const inPanel =
      CustomizableUI.getAreaType(aArea) !== CustomizableUI.TYPE_TOOLBAR;

    this._updateWidgetClassName(aWidgetId, inPanel);
  },

  onWidgetMoved(aWidgetId) {
    if (CustomizableUI.isWebExtensionWidget(aWidgetId)) {
      this.updateAttention();
    }
  },

  onWidgetOverflow(aNode) {
    // We register a CUI listener for each window so we make sure that we
    // handle the event for the right window here.
    if (window !== aNode.ownerGlobal) {
      return;
    }

    this._updateWidgetClassName(aNode.getAttribute("widget-id"), true);
  },

  onWidgetUnderflow(aNode) {
    // We register a CUI listener for each window so we make sure that we
    // handle the event for the right window here.
    if (window !== aNode.ownerGlobal) {
      return;
    }

    this._updateWidgetClassName(aNode.getAttribute("widget-id"), false);
  },

  onAreaNodeRegistered(aArea, aContainer) {
    // We register a CUI listener for each window so we make sure that we
    // handle the event for the right window here.
    if (window !== aContainer.ownerGlobal) {
      return;
    }

    const inPanel =
      CustomizableUI.getAreaType(aArea) !== CustomizableUI.TYPE_TOOLBAR;

    for (const widgetId of CustomizableUI.getWidgetIdsInArea(aArea)) {
      this._updateWidgetClassName(widgetId, inPanel);
    }
  },

  // This internal method is used to change some CSS classnames on the action
  // and menu buttons of an extension (CUI) widget. When the widget is placed
  // in the panel, the action and menu buttons should have the `.subviewbutton`
  // class and not the `.toolbarbutton-1` one. When NOT placed in the panel,
  // it is the other way around.
  _updateWidgetClassName(aWidgetId, inPanel) {
    if (!CustomizableUI.isWebExtensionWidget(aWidgetId)) {
      return;
    }

    const node = CustomizableUI.getWidget(aWidgetId)?.forWindow(window)?.node;
    const actionButton = node?.querySelector(
      ".unified-extensions-item-action-button"
    );
    if (actionButton) {
      actionButton.classList.toggle("subviewbutton", inPanel);
      actionButton.classList.toggle("subviewbutton-iconic", inPanel);
      actionButton.classList.toggle("toolbarbutton-1", !inPanel);
    }
    const menuButton = node?.querySelector(
      ".unified-extensions-item-menu-button"
    );
    if (menuButton) {
      menuButton.classList.toggle("subviewbutton", inPanel);
      menuButton.classList.toggle("subviewbutton-iconic", inPanel);
      menuButton.classList.toggle("toolbarbutton-1", !inPanel);
    }
  },

  _createBlocklistMessageBar(container) {
    if (!this.blocklistAttentionInfo) {
      return null;
    }

    const { addons, extensionsCount, hasHardBlocked } =
      this.blocklistAttentionInfo;
    const type = hasHardBlocked ? "error" : "warning";

    let messageBarFluentId;
    let extensionName;
    if (extensionsCount === 1) {
      extensionName = addons[0].name;
      messageBarFluentId = hasHardBlocked
        ? "unified-extensions-mb-blocklist-error-single"
        : "unified-extensions-mb-blocklist-warning-single";
    } else {
      messageBarFluentId = hasHardBlocked
        ? "unified-extensions-mb-blocklist-error-multiple"
        : "unified-extensions-mb-blocklist-warning-multiple";
    }

    const messageBarBlocklist = this._makeMessageBar({
      dismissible: true,
      linkToAboutAddons: true,
      messageBarFluentId,
      messageBarFluentArgs: {
        extensionsCount,
        extensionName,
      },
      type,
    });

    messageBarBlocklist.addEventListener(
      "message-bar:user-dismissed",
      () => {
        if (messageBarBlocklist === this._messageBarBlocklist) {
          this._messageBarBlocklist = null;
        }
        this.blocklistAttentionInfo?.dismiss();
      },
      { once: true }
    );

    if (
      this._messageBarBlocklist &&
      container.contains(this._messageBarBlocklist)
    ) {
      container.replaceChild(messageBarBlocklist, this._messageBarBlocklist);
    } else if (container.contains(this._messageBarQuarantinedDomain)) {
      container.insertBefore(
        messageBarBlocklist,
        this._messageBarQuarantinedDomain
      );
    } else {
      container.appendChild(messageBarBlocklist);
    }

    return messageBarBlocklist;
  },

  _makeMessageBar({
    dismissible = false,
    messageBarFluentId,
    messageBarFluentArgs,
    supportPage = null,
    linkToAboutAddons = false,
    type = "warning",
  }) {
    const messageBar = document.createElement("moz-message-bar");
    messageBar.setAttribute("type", type);
    messageBar.classList.add("unified-extensions-message-bar");

    if (dismissible) {
      // NOTE: the moz-message-bar is currently expected to be called `dismissable`.
      messageBar.setAttribute("dismissable", dismissible);
    }

    if (linkToAboutAddons) {
      const linkToAboutAddonsEl = document.createElement("a");
      linkToAboutAddonsEl.setAttribute(
        "class",
        "unified-extensions-link-to-aboutaddons"
      );
      linkToAboutAddonsEl.setAttribute("slot", "support-link");
      linkToAboutAddonsEl.addEventListener("click", () => {
        BrowserAddonUI.openAddonsMgr("addons://list/extension");
        this.togglePanel();
      });
      document.l10n.setAttributes(
        linkToAboutAddonsEl,
        "unified-extensions-mb-about-addons-link"
      );
      messageBar.append(linkToAboutAddonsEl);
    }

    document.l10n.setAttributes(
      messageBar,
      messageBarFluentId,
      messageBarFluentArgs
    );

    if (supportPage) {
      const supportUrl = document.createElement("a", {
        is: "moz-support-link",
      });
      supportUrl.setAttribute("support-page", supportPage);
      document.l10n.setAttributes(
        supportUrl,
        "unified-extensions-mb-quarantined-domain-learn-more"
      );
      supportUrl.setAttribute("data-l10n-attrs", "aria-label");
      supportUrl.setAttribute("slot", "support-link");

      messageBar.append(supportUrl);
    }

    return messageBar;
  },

  _shouldShowQuarantinedNotification() {
    const { currentURI, selectedTab } = window.gBrowser;
    // We should show the quarantined notification when the domain is in the
    // list of quarantined domains and we have at least one extension
    // quarantined. In addition, we check that we have extensions in the panel
    // until Bug 1778684 is resolved.
    return (
      WebExtensionPolicy.isQuarantinedURI(currentURI) &&
      this.hasExtensionsInPanel() &&
      this.getActivePolicies().some(
        policy => lazy.OriginControls.getState(policy, selectedTab).quarantined
      )
    );
  },

  // Records telemetry when the button is about to temporarily be shown,
  // provided that the button is hidden at the time of invocation.
  //
  // `reason` is one of the labels in extensions_button.temporarily_unhidden
  // in browser/components/extensions/metrics.yaml.
  //
  // This is usually immediately before a updateButtonVisibility() call,
  // sometimes a bit earlier (if the updateButtonVisibility() call is indirect).
  recordButtonTelemetry(reason) {
    if (!this.buttonAlwaysVisible && this._button.hidden) {
      Glean.extensionsButton.temporarilyUnhidden[reason].add();
    }
  },

  hideExtensionsButtonFromToolbar() {
    // All browser windows will observe this and call updateButtonVisibility().
    Services.prefs.setBoolPref(
      "extensions.unifiedExtensions.button.always_visible",
      false
    );
    ConfirmationHint.show(
      document.getElementById("PanelUI-menu-button"),
      "confirmation-hint-extensions-button-hidden"
    );
    Glean.extensionsButton.toggleVisibility.record({
      is_customizing: CustomizationHandler.isCustomizing(),
      is_extensions_panel_empty: !this.hasExtensionsInPanel(),
      // After setting the above pref to false, the button should hide
      // immediately. If this was not the case, then something caused the
      // button to be shown temporarily.
      is_temporarily_shown: !this._button.hidden,
      should_hide: true,
    });
  },

  showExtensionsButtonInToolbar() {
    let wasShownBefore = !this.buttonAlwaysVisible && !this._button.hidden;
    // All browser windows will observe this and call updateButtonVisibility().
    Services.prefs.setBoolPref(
      "extensions.unifiedExtensions.button.always_visible",
      true
    );
    Glean.extensionsButton.toggleVisibility.record({
      is_customizing: CustomizationHandler.isCustomizing(),
      is_extensions_panel_empty: !this.hasExtensionsInPanel(),
      is_temporarily_shown: wasShownBefore,
      should_hide: false,
    });
  },
};
XPCOMUtils.defineLazyPreferenceGetter(
  gUnifiedExtensions,
  "buttonAlwaysVisible",
  "extensions.unifiedExtensions.button.always_visible",
  true,
  (prefName, oldValue, newValue) => {
    if (gUnifiedExtensions._initialized) {
      gUnifiedExtensions.updateButtonVisibility();
      Glean.extensionsButton.prefersHiddenButton.set(!newValue);
    }
  }
);
// With button.always_visible is false, we still show the button in specific
// cases when needed. The user is always empowered to dismiss the specific
// trigger that causes the button to be shown. The attention dot is the
// exception, where the button cannot easily be hidden. Users who willingly
// want to ignore the attention dot can set this preference to keep the button
// hidden even if attention is requested.
XPCOMUtils.defineLazyPreferenceGetter(
  gUnifiedExtensions,
  "buttonIgnoresAttention",
  "extensions.unifiedExtensions.button.ignore_attention",
  false,
  () => {
    if (
      gUnifiedExtensions._initialized &&
      gUnifiedExtensions.buttonAlwaysVisible
    ) {
      gUnifiedExtensions.updateButtonVisibility();
    }
  }
);