summaryrefslogtreecommitdiffstats
path: root/toolkit/components/extensions/Schemas.sys.mjs
blob: b8a7320c7cd27be3c33d8cd023f667cc79e443f0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* vim: set sts=2 sw=2 et tw=80: */
/* 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/. */

import { AppConstants } from "resource://gre/modules/AppConstants.sys.mjs";
import { XPCOMUtils } from "resource://gre/modules/XPCOMUtils.sys.mjs";

import { ExtensionUtils } from "resource://gre/modules/ExtensionUtils.sys.mjs";

var { DefaultMap, DefaultWeakMap } = ExtensionUtils;

const lazy = {};

ChromeUtils.defineESModuleGetters(lazy, {
  ExtensionParent: "resource://gre/modules/ExtensionParent.sys.mjs",
  ShortcutUtils: "resource://gre/modules/ShortcutUtils.sys.mjs",
});
ChromeUtils.defineModuleGetter(
  lazy,
  "NetUtil",
  "resource://gre/modules/NetUtil.jsm"
);

XPCOMUtils.defineLazyServiceGetter(
  lazy,
  "contentPolicyService",
  "@mozilla.org/addons/content-policy;1",
  "nsIAddonContentPolicy"
);

XPCOMUtils.defineLazyGetter(
  lazy,
  "StartupCache",
  () => lazy.ExtensionParent.StartupCache
);

XPCOMUtils.defineLazyPreferenceGetter(
  lazy,
  "treatWarningsAsErrors",
  "extensions.webextensions.warnings-as-errors",
  false
);

export let Schemas;

const KEY_CONTENT_SCHEMAS = "extensions-framework/schemas/content";
const KEY_PRIVILEGED_SCHEMAS = "extensions-framework/schemas/privileged";

const MIN_MANIFEST_VERSION = 2;
const MAX_MANIFEST_VERSION = 3;

const { DEBUG } = AppConstants;

const isParentProcess =
  Services.appinfo.processType === Services.appinfo.PROCESS_TYPE_DEFAULT;

function readJSON(url) {
  return new Promise((resolve, reject) => {
    lazy.NetUtil.asyncFetch(
      { uri: url, loadUsingSystemPrincipal: true },
      (inputStream, status) => {
        if (!Components.isSuccessCode(status)) {
          // Convert status code to a string
          let e = Components.Exception("", status);
          reject(new Error(`Error while loading '${url}' (${e.name})`));
          return;
        }
        try {
          let text = lazy.NetUtil.readInputStreamToString(
            inputStream,
            inputStream.available()
          );

          // Chrome JSON files include a license comment that we need to
          // strip off for this to be valid JSON. As a hack, we just
          // look for the first '[' character, which signals the start
          // of the JSON content.
          let index = text.indexOf("[");
          text = text.slice(index);

          resolve(JSON.parse(text));
        } catch (e) {
          reject(e);
        }
      }
    );
  });
}

function stripDescriptions(json, stripThis = true) {
  if (Array.isArray(json)) {
    for (let i = 0; i < json.length; i++) {
      if (typeof json[i] === "object" && json[i] !== null) {
        json[i] = stripDescriptions(json[i]);
      }
    }
    return json;
  }

  let result = {};

  // Objects are handled much more efficiently, both in terms of memory and
  // CPU, if they have the same shape as other objects that serve the same
  // purpose. So, normalize the order of properties to increase the chances
  // that the majority of schema objects wind up in large shape groups.
  for (let key of Object.keys(json).sort()) {
    if (stripThis && key === "description" && typeof json[key] === "string") {
      continue;
    }

    if (typeof json[key] === "object" && json[key] !== null) {
      result[key] = stripDescriptions(json[key], key !== "properties");
    } else {
      result[key] = json[key];
    }
  }

  return result;
}

function blobbify(json) {
  // We don't actually use descriptions at runtime, and they make up about a
  // third of the size of our structured clone data, so strip them before
  // blobbifying.
  json = stripDescriptions(json);

  return new StructuredCloneHolder("Schemas/blobbify", null, json);
}

async function readJSONAndBlobbify(url) {
  let json = await readJSON(url);

  return blobbify(json);
}

/**
 * Defines a lazy getter for the given property on the given object. Any
 * security wrappers are waived on the object before the property is
 * defined, and the getter and setter methods are wrapped for the target
 * scope.
 *
 * The given getter function is guaranteed to be called only once, even
 * if the target scope retrieves the wrapped getter from the property
 * descriptor and calls it directly.
 *
 * @param {object} object
 *        The object on which to define the getter.
 * @param {string | symbol} prop
 *        The property name for which to define the getter.
 * @param {Function} getter
 *        The function to call in order to generate the final property
 *        value.
 */
function exportLazyGetter(object, prop, getter) {
  object = ChromeUtils.waiveXrays(object);

  let redefine = value => {
    if (value === undefined) {
      delete object[prop];
    } else {
      Object.defineProperty(object, prop, {
        enumerable: true,
        configurable: true,
        writable: true,
        value,
      });
    }

    getter = null;

    return value;
  };

  Object.defineProperty(object, prop, {
    enumerable: true,
    configurable: true,

    get: Cu.exportFunction(function () {
      return redefine(getter.call(this));
    }, object),

    set: Cu.exportFunction(value => {
      redefine(value);
    }, object),
  });
}

/**
 * Defines a lazily-instantiated property descriptor on the given
 * object. Any security wrappers are waived on the object before the
 * property is defined.
 *
 * The given getter function is guaranteed to be called only once, even
 * if the target scope retrieves the wrapped getter from the property
 * descriptor and calls it directly.
 *
 * @param {object} object
 *        The object on which to define the getter.
 * @param {string | symbol} prop
 *        The property name for which to define the getter.
 * @param {Function} getter
 *        The function to call in order to generate the final property
 *        descriptor object. This will be called, and the property
 *        descriptor installed on the object, the first time the
 *        property is written or read. The function may return
 *        undefined, which will cause the property to be deleted.
 */
function exportLazyProperty(object, prop, getter) {
  object = ChromeUtils.waiveXrays(object);

  let redefine = obj => {
    let desc = getter.call(obj);
    getter = null;

    delete object[prop];
    if (desc) {
      let defaults = {
        configurable: true,
        enumerable: true,
      };

      if (!desc.set && !desc.get) {
        defaults.writable = true;
      }

      Object.defineProperty(object, prop, Object.assign(defaults, desc));
    }
  };

  Object.defineProperty(object, prop, {
    enumerable: true,
    configurable: true,

    get: Cu.exportFunction(function () {
      redefine(this);
      return object[prop];
    }, object),

    set: Cu.exportFunction(function (value) {
      redefine(this);
      object[prop] = value;
    }, object),
  });
}

const POSTPROCESSORS = {
  convertImageDataToURL(imageData, context) {
    let document = context.cloneScope.document;
    let canvas = document.createElementNS(
      "http://www.w3.org/1999/xhtml",
      "canvas"
    );
    canvas.width = imageData.width;
    canvas.height = imageData.height;
    canvas.getContext("2d").putImageData(imageData, 0, 0);

    return canvas.toDataURL("image/png");
  },
  webRequestBlockingPermissionRequired(string, context) {
    if (string === "blocking" && !context.hasPermission("webRequestBlocking")) {
      throw new context.cloneScope.Error(
        "Using webRequest.addListener with the " +
          "blocking option requires the 'webRequestBlocking' permission."
      );
    }

    return string;
  },
  requireBackgroundServiceWorkerEnabled(value, context) {
    if (WebExtensionPolicy.backgroundServiceWorkerEnabled) {
      return value;
    }

    // Add an error to the manifest validations and throw the
    // same error.
    const msg = "background.service_worker is currently disabled";
    context.logError(context.makeError(msg));
    throw new Error(msg);
  },

  manifestVersionCheck(value, context) {
    if (
      value == 2 ||
      (value == 3 &&
        Services.prefs.getBoolPref("extensions.manifestV3.enabled", false))
    ) {
      return value;
    }
    const msg = `Unsupported manifest version: ${value}`;
    context.logError(context.makeError(msg));
    throw new Error(msg);
  },

  webAccessibleMatching(value, context) {
    // Ensure each object has at least one of matches or extension_ids array.
    for (let obj of value) {
      if (!obj.matches && !obj.extension_ids) {
        const msg = `web_accessible_resources requires one of "matches" or "extension_ids"`;
        context.logError(context.makeError(msg));
        throw new Error(msg);
      }
    }
    return value;
  },
};

// Parses a regular expression, with support for the Python extended
// syntax that allows setting flags by including the string (?im)
function parsePattern(pattern) {
  let flags = "";
  let match = /^\(\?([im]*)\)(.*)/.exec(pattern);
  if (match) {
    [, flags, pattern] = match;
  }
  return new RegExp(pattern, flags);
}

function getValueBaseType(value) {
  let type = typeof value;
  switch (type) {
    case "object":
      if (value === null) {
        return "null";
      }
      if (Array.isArray(value)) {
        return "array";
      }
      break;

    case "number":
      if (value % 1 === 0) {
        return "integer";
      }
  }
  return type;
}

// Methods of Context that are used by Schemas.normalize. These methods can be
// overridden at the construction of Context.
const CONTEXT_FOR_VALIDATION = ["checkLoadURL", "hasPermission", "logError"];

// Methods of Context that are used by Schemas.inject.
// Callers of Schemas.inject should implement all of these methods.
const CONTEXT_FOR_INJECTION = [
  ...CONTEXT_FOR_VALIDATION,
  "getImplementation",
  "isPermissionRevokable",
  "shouldInject",
];

// If the message is a function, call it and return the result.
// Otherwise, assume it's a string.
function forceString(msg) {
  if (typeof msg === "function") {
    return msg();
  }
  return msg;
}

/**
 * A context for schema validation and error reporting. This class is only used
 * internally within Schemas.
 */
class Context {
  /**
   * @param {object} params Provides the implementation of this class.
   * @param {Array<string>} overridableMethods
   */
  constructor(params, overridableMethods = CONTEXT_FOR_VALIDATION) {
    this.params = params;

    if (typeof params.manifestVersion !== "number") {
      throw new Error(
        `Unexpected params.manifestVersion value: ${params.manifestVersion}`
      );
    }

    this.path = [];
    this.preprocessors = {
      localize(value, context) {
        return value;
      },
    };
    this.postprocessors = POSTPROCESSORS;
    this.isChromeCompat = false;

    this.currentChoices = new Set();
    this.choicePathIndex = 0;

    for (let method of overridableMethods) {
      if (method in params) {
        this[method] = params[method].bind(params);
      }
    }

    let props = ["isChromeCompat", "manifestVersion", "preprocessors"];
    for (let prop of props) {
      if (prop in params) {
        if (prop in this && typeof this[prop] == "object") {
          Object.assign(this[prop], params[prop]);
        } else {
          this[prop] = params[prop];
        }
      }
    }
  }

  get choicePath() {
    let path = this.path.slice(this.choicePathIndex);
    return path.join(".");
  }

  get cloneScope() {
    return this.params.cloneScope || undefined;
  }

  get url() {
    return this.params.url;
  }

  get principal() {
    return (
      this.params.principal ||
      Services.scriptSecurityManager.createNullPrincipal({})
    );
  }

  /**
   * Checks whether `url` may be loaded by the extension in this context.
   *
   * @param {string} url The URL that the extension wished to load.
   * @returns {boolean} Whether the context may load `url`.
   */
  checkLoadURL(url) {
    let ssm = Services.scriptSecurityManager;
    try {
      ssm.checkLoadURIWithPrincipal(
        this.principal,
        Services.io.newURI(url),
        ssm.DISALLOW_INHERIT_PRINCIPAL
      );
    } catch (e) {
      return false;
    }
    return true;
  }

  /**
   * Checks whether this context has the given permission.
   *
   * @param {string} permission
   *        The name of the permission to check.
   *
   * @returns {boolean} True if the context has the given permission.
   */
  hasPermission(permission) {
    return false;
  }

  /**
   * Checks whether the given permission can be dynamically revoked or
   * granted.
   *
   * @param {string} permission
   *        The name of the permission to check.
   *
   * @returns {boolean} True if the given permission is revokable.
   */
  isPermissionRevokable(permission) {
    return false;
  }

  /**
   * Returns an error result object with the given message, for return
   * by Type normalization functions.
   *
   * If the context has a `currentTarget` value, this is prepended to
   * the message to indicate the location of the error.
   *
   * @param {string | Function} errorMessage
   *        The error message which will be displayed when this is the
   *        only possible matching schema. If a function is passed, it
   *        will be evaluated when the error string is first needed, and
   *        must return a string.
   * @param {string | Function} choicesMessage
   *        The message describing the valid what constitutes a valid
   *        value for this schema, which will be displayed when multiple
   *        schema choices are available and none match.
   *
   *        A caller may pass `null` to prevent a choice from being
   *        added, but this should *only* be done from code processing a
   *        choices type.
   * @param {boolean} [warning = false]
   *        If true, make message prefixed `Warning`. If false, make message
   *        prefixed `Error`
   * @returns {object}
   */
  error(errorMessage, choicesMessage = undefined, warning = false) {
    if (choicesMessage !== null) {
      let { choicePath } = this;
      if (choicePath) {
        choicesMessage = `.${choicePath} must ${choicesMessage}`;
      }

      this.currentChoices.add(choicesMessage);
    }

    if (this.currentTarget) {
      let { currentTarget } = this;
      return {
        error: () =>
          `${
            warning ? "Warning" : "Error"
          } processing ${currentTarget}: ${forceString(errorMessage)}`,
      };
    }
    return { error: errorMessage };
  }

  /**
   * Creates an `Error` object belonging to the current unprivileged
   * scope. If there is no unprivileged scope associated with this
   * context, the message is returned as a string.
   *
   * If the context has a `currentTarget` value, this is prepended to
   * the message, in the same way as for the `error` method.
   *
   * @param {string} message
   * @param {object} [options]
   * @param {boolean} [options.warning = false]
   * @returns {Error}
   */
  makeError(message, { warning = false } = {}) {
    let error = forceString(this.error(message, null, warning).error);
    if (this.cloneScope) {
      return new this.cloneScope.Error(error);
    }
    return error;
  }

  /**
   * Logs the given error to the console. May be overridden to enable
   * custom logging.
   *
   * @param {Error|string} error
   */
  logError(error) {
    if (this.cloneScope) {
      Cu.reportError(
        // Error objects logged using Cu.reportError are not associated
        // to the related innerWindowID. This results in a leaked docshell
        // since consoleService cannot release the error object when the
        // extension global is destroyed.
        typeof error == "string" ? error : String(error),
        // Report the error with the appropriate stack trace when the
        // is related to an actual extension global (instead of being
        // related to a manifest validation).
        this.principal && ChromeUtils.getCallerLocation(this.principal)
      );
    } else {
      Cu.reportError(error);
    }
  }

  /**
   * Logs a warning. An error might be thrown when we treat warnings as errors.
   *
   * @param {string} warningMessage
   */
  logWarning(warningMessage) {
    let error = this.makeError(warningMessage, { warning: true });
    this.logError(error);

    if (lazy.treatWarningsAsErrors) {
      // This pref is false by default, and true by default in tests to
      // discourage the use of deprecated APIs in our unit tests.
      // If a warning is an expected part of a test, temporarily set the pref
      // to false, e.g. with the ExtensionTestUtils.failOnSchemaWarnings helper.
      Services.console.logStringMessage(
        "Treating warning as error because the preference " +
          "extensions.webextensions.warnings-as-errors is set to true"
      );
      if (typeof error === "string") {
        error = new Error(error);
      }
      throw error;
    }
  }

  /**
   * Returns the name of the value currently being normalized. For a
   * nested object, this is usually approximately equivalent to the
   * JavaScript property accessor for that property. Given:
   *
   *   { foo: { bar: [{ baz: x }] } }
   *
   * When processing the value for `x`, the currentTarget is
   * 'foo.bar.0.baz'
   */
  get currentTarget() {
    return this.path.join(".");
  }

  /**
   * Executes the given callback, and returns an array of choice strings
   * passed to {@see #error} during its execution.
   *
   * @param {Function} callback
   * @returns {object}
   *          An object with a `result` property containing the return
   *          value of the callback, and a `choice` property containing
   *          an array of choices.
   */
  withChoices(callback) {
    let { currentChoices, choicePathIndex } = this;

    let choices = new Set();
    this.currentChoices = choices;
    this.choicePathIndex = this.path.length;

    try {
      let result = callback();

      return { result, choices };
    } finally {
      this.currentChoices = currentChoices;
      this.choicePathIndex = choicePathIndex;

      if (choices.size == 1) {
        for (let choice of choices) {
          currentChoices.add(choice);
        }
      } else if (choices.size) {
        this.error(null, () => {
          let array = Array.from(choices, forceString);
          let n = array.length - 1;
          array[n] = `or ${array[n]}`;

          return `must either [${array.join(", ")}]`;
        });
      }
    }
  }

  /**
   * Appends the given component to the `currentTarget` path to indicate
   * that it is being processed, calls the given callback function, and
   * then restores the original path.
   *
   * This is used to identify the path of the property being processed
   * when reporting type errors.
   *
   * @param {string} component
   * @param {Function} callback
   * @returns {*}
   */
  withPath(component, callback) {
    this.path.push(component);
    try {
      return callback();
    } finally {
      this.path.pop();
    }
  }

  matchManifestVersion(entry) {
    let { manifestVersion } = this;
    return (
      manifestVersion >= entry.min_manifest_version &&
      manifestVersion <= entry.max_manifest_version
    );
  }
}

/**
 * Represents a schema entry to be injected into an object. Handles the
 * injection, revocation, and permissions of said entry.
 *
 * @param {InjectionContext} context
 *        The injection context for the entry.
 * @param {Entry} entry
 *        The entry to inject.
 * @param {object} parentObject
 *        The object into which to inject this entry.
 * @param {string} name
 *        The property name at which to inject this entry.
 * @param {Array<string>} path
 *        The full path from the root entry to this entry.
 * @param {Entry} parentEntry
 *        The parent entry for the injected entry.
 */
class InjectionEntry {
  constructor(context, entry, parentObj, name, path, parentEntry) {
    this.context = context;
    this.entry = entry;
    this.parentObj = parentObj;
    this.name = name;
    this.path = path;
    this.parentEntry = parentEntry;

    this.injected = null;
    this.lazyInjected = null;
  }

  /**
   * @property {Array<string>} allowedContexts
   *        The list of allowed contexts into which the entry may be
   *        injected.
   */
  get allowedContexts() {
    let { allowedContexts } = this.entry;
    if (allowedContexts.length) {
      return allowedContexts;
    }
    return this.parentEntry.defaultContexts;
  }

  /**
   * @property {boolean} isRevokable
   *        Returns true if this entry may be dynamically injected or
   *        revoked based on its permissions.
   */
  get isRevokable() {
    return (
      this.entry.permissions &&
      this.entry.permissions.some(perm =>
        this.context.isPermissionRevokable(perm)
      )
    );
  }

  /**
   * @property {boolean} hasPermission
   *        Returns true if the injection context currently has the
   *        appropriate permissions to access this entry.
   */
  get hasPermission() {
    return (
      !this.entry.permissions ||
      this.entry.permissions.some(perm => this.context.hasPermission(perm))
    );
  }

  /**
   * @property {boolean} shouldInject
   *        Returns true if this entry should be injected in the given
   *        context, without respect to permissions.
   */
  get shouldInject() {
    return (
      this.context.matchManifestVersion(this.entry) &&
      this.context.shouldInject(
        this.path.join("."),
        this.name,
        this.allowedContexts
      )
    );
  }

  /**
   * Revokes this entry, removing its property from its parent object,
   * and invalidating its wrappers.
   */
  revoke() {
    if (this.lazyInjected) {
      this.lazyInjected = false;
    } else if (this.injected) {
      if (this.injected.revoke) {
        this.injected.revoke();
      }

      try {
        let unwrapped = ChromeUtils.waiveXrays(this.parentObj);
        delete unwrapped[this.name];
      } catch (e) {
        Cu.reportError(e);
      }

      let { value } = this.injected.descriptor;
      if (value) {
        this.context.revokeChildren(value);
      }

      this.injected = null;
    }
  }

  /**
   * Returns a property descriptor object for this entry, if it should
   * be injected, or undefined if it should not.
   *
   * @returns {object?}
   *        A property descriptor object, or undefined if the property
   *        should be removed.
   */
  getDescriptor() {
    this.lazyInjected = false;

    if (this.injected) {
      let path = [...this.path, this.name];
      throw new Error(
        `Attempting to re-inject already injected entry: ${path.join(".")}`
      );
    }

    if (!this.shouldInject) {
      return;
    }

    if (this.isRevokable) {
      this.context.pendingEntries.add(this);
    }

    if (!this.hasPermission) {
      return;
    }

    this.injected = this.entry.getDescriptor(this.path, this.context);
    if (!this.injected) {
      return undefined;
    }

    return this.injected.descriptor;
  }

  /**
   * Injects a lazy property descriptor into the parent object which
   * checks permissions and eligibility for injection the first time it
   * is accessed.
   */
  lazyInject() {
    if (this.lazyInjected || this.injected) {
      let path = [...this.path, this.name];
      throw new Error(
        `Attempting to re-lazy-inject already injected entry: ${path.join(".")}`
      );
    }

    this.lazyInjected = true;
    exportLazyProperty(this.parentObj, this.name, () => {
      if (this.lazyInjected) {
        return this.getDescriptor();
      }
    });
  }

  /**
   * Injects or revokes this entry if its current state does not match
   * the context's current permissions.
   */
  permissionsChanged() {
    if (this.injected) {
      this.maybeRevoke();
    } else {
      this.maybeInject();
    }
  }

  maybeInject() {
    if (!this.injected && !this.lazyInjected) {
      this.lazyInject();
    }
  }

  maybeRevoke() {
    if (this.injected && !this.hasPermission) {
      this.revoke();
    }
  }
}

/**
 * Holds methods that run the actual implementation of the extension APIs. These
 * methods are only called if the extension API invocation matches the signature
 * as defined in the schema. Otherwise an error is reported to the context.
 */
class InjectionContext extends Context {
  constructor(params, schemaRoot) {
    super(params, CONTEXT_FOR_INJECTION);

    this.schemaRoot = schemaRoot;

    this.pendingEntries = new Set();
    this.children = new DefaultWeakMap(() => new Map());

    this.injectedRoots = new Set();

    if (params.setPermissionsChangedCallback) {
      params.setPermissionsChangedCallback(this.permissionsChanged.bind(this));
    }
  }

  /**
   * Check whether the API should be injected.
   *
   * @abstract
   * @param {string} namespace The namespace of the API. This may contain dots,
   *     e.g. in the case of "devtools.inspectedWindow".
   * @param {string} [name] The name of the property in the namespace.
   *     `null` if we are checking whether the namespace should be injected.
   * @param {Array<string>} allowedContexts A list of additional contexts in which
   *     this API should be available. May include any of:
   *         "main" - The main chrome browser process.
   *         "addon" - An addon process.
   *         "content" - A content process.
   * @returns {boolean} Whether the API should be injected.
   */
  shouldInject(namespace, name, allowedContexts) {
    throw new Error("Not implemented");
  }

  /**
   * Generate the implementation for `namespace`.`name`.
   *
   * @abstract
   * @param {string} namespace The full path to the namespace of the API, minus
   *     the name of the method or property. E.g. "storage.local".
   * @param {string} name The name of the method, property or event.
   * @returns {SchemaAPIInterface} The implementation of the API.
   */
  getImplementation(namespace, name) {
    throw new Error("Not implemented");
  }

  /**
   * Updates all injection entries which may need to be updated after a
   * permission change, revoking or re-injecting them as necessary.
   */
  permissionsChanged() {
    for (let entry of this.pendingEntries) {
      try {
        entry.permissionsChanged();
      } catch (e) {
        Cu.reportError(e);
      }
    }
  }

  /**
   * Recursively revokes all child injection entries of the given
   * object.
   *
   * @param {object} object
   *        The object for which to invoke children.
   */
  revokeChildren(object) {
    if (!this.children.has(object)) {
      return;
    }

    let children = this.children.get(object);
    for (let [name, entry] of children.entries()) {
      try {
        entry.revoke();
      } catch (e) {
        Cu.reportError(e);
      }
      children.delete(name);

      // When we revoke children for an object, we consider that object
      // dead. If the entry is ever reified again, a new object is
      // created, with new child entries.
      this.pendingEntries.delete(entry);
    }
    this.children.delete(object);
  }

  _getInjectionEntry(entry, dest, name, path, parentEntry) {
    let injection = new InjectionEntry(
      this,
      entry,
      dest,
      name,
      path,
      parentEntry
    );

    this.children.get(dest).set(name, injection);

    return injection;
  }

  /**
   * Returns the property descriptor for the given entry.
   *
   * @param {Entry} entry
   *        The entry instance to return a descriptor for.
   * @param {object} dest
   *        The object into which this entry is being injected.
   * @param {string} name
   *        The property name on the destination object where the entry
   *        will be injected.
   * @param {Array<string>} path
   *        The full path from the root injection object to this entry.
   * @param {Entry} parentEntry
   *        The parent entry for this entry.
   *
   * @returns {object?}
   *        A property descriptor object, or null if the entry should
   *        not be injected.
   */
  getDescriptor(entry, dest, name, path, parentEntry) {
    let injection = this._getInjectionEntry(
      entry,
      dest,
      name,
      path,
      parentEntry
    );

    return injection.getDescriptor();
  }

  /**
   * Lazily injects the given entry into the given object.
   *
   * @param {Entry} entry
   *        The entry instance to lazily inject.
   * @param {object} dest
   *        The object into which to inject this entry.
   * @param {string} name
   *        The property name at which to inject the entry.
   * @param {Array<string>} path
   *        The full path from the root injection object to this entry.
   * @param {Entry} parentEntry
   *        The parent entry for this entry.
   */
  injectInto(entry, dest, name, path, parentEntry) {
    let injection = this._getInjectionEntry(
      entry,
      dest,
      name,
      path,
      parentEntry
    );

    injection.lazyInject();
  }
}

/**
 * The methods in this singleton represent the "format" specifier for
 * JSON Schema string types.
 *
 * Each method either returns a normalized version of the original
 * value, or throws an error if the value is not valid for the given
 * format.
 */
const FORMATS = {
  hostname(string, context) {
    // TODO bug 1797376: Despite the name, this format is NOT a "hostname",
    // but hostname + port and may fail with IPv6. Use canonicalDomain instead.
    let valid = true;

    try {
      valid = new URL(`http://${string}`).host === string;
    } catch (e) {
      valid = false;
    }

    if (!valid) {
      throw new Error(`Invalid hostname ${string}`);
    }

    return string;
  },

  canonicalDomain(string, context) {
    let valid;

    try {
      valid = new URL(`http://${string}`).hostname === string;
    } catch (e) {
      valid = false;
    }

    if (!valid) {
      // Require the input to be a canonical domain.
      // Rejects obvious non-domains such as URLs,
      // but also catches non-IDN (punycode) domains.
      throw new Error(`Invalid domain ${string}`);
    }

    return string;
  },

  url(string, context) {
    let url = new URL(string).href;

    if (!context.checkLoadURL(url)) {
      throw new Error(`Access denied for URL ${url}`);
    }
    return url;
  },

  origin(string, context) {
    let url;
    try {
      url = new URL(string);
    } catch (e) {
      throw new Error(`Invalid origin: ${string}`);
    }
    if (!/^https?:/.test(url.protocol)) {
      throw new Error(`Invalid origin must be http or https for URL ${string}`);
    }
    // url.origin is punycode so a direct check against string wont work.
    // url.href appends a slash even if not in the original string, we we
    // additionally check that string does not end in slash.
    if (string.endsWith("/") || url.href != new URL(url.origin).href) {
      throw new Error(
        `Invalid origin for URL ${string}, replace with origin ${url.origin}`
      );
    }
    if (!context.checkLoadURL(url.origin)) {
      throw new Error(`Access denied for URL ${url}`);
    }
    return url.origin;
  },

  relativeUrl(string, context) {
    if (!context.url) {
      // If there's no context URL, return relative URLs unresolved, and
      // skip security checks for them.
      try {
        new URL(string);
      } catch (e) {
        return string;
      }
    }

    let url = new URL(string, context.url).href;

    if (!context.checkLoadURL(url)) {
      throw new Error(`Access denied for URL ${url}`);
    }
    return url;
  },

  strictRelativeUrl(string, context) {
    void FORMATS.unresolvedRelativeUrl(string, context);
    return FORMATS.relativeUrl(string, context);
  },

  unresolvedRelativeUrl(string, context) {
    if (!string.startsWith("//")) {
      try {
        new URL(string);
      } catch (e) {
        return string;
      }
    }

    throw new SyntaxError(
      `String ${JSON.stringify(string)} must be a relative URL`
    );
  },

  homepageUrl(string, context) {
    // Pipes are used for separating homepages, but we only allow extensions to
    // set a single homepage. Encoding any pipes makes it one URL.
    return FORMATS.relativeUrl(
      string.replace(new RegExp("\\|", "g"), "%7C"),
      context
    );
  },

  imageDataOrStrictRelativeUrl(string, context) {
    // Do not accept a string which resolves as an absolute URL, or any
    // protocol-relative URL, except PNG or JPG data URLs
    if (
      !string.startsWith("data:image/png;base64,") &&
      !string.startsWith("data:image/jpeg;base64,")
    ) {
      try {
        return FORMATS.strictRelativeUrl(string, context);
      } catch (e) {
        throw new SyntaxError(
          `String ${JSON.stringify(
            string
          )} must be a relative or PNG or JPG data:image URL`
        );
      }
    }
    return string;
  },

  contentSecurityPolicy(string, context) {
    // Manifest V3 extension_pages allows WASM.  When sandbox is
    // implemented, or any other V3 or later directive, the flags
    // logic will need to be updated.
    let flags =
      context.manifestVersion < 3
        ? Ci.nsIAddonContentPolicy.CSP_ALLOW_ANY
        : Ci.nsIAddonContentPolicy.CSP_ALLOW_WASM;
    let error = lazy.contentPolicyService.validateAddonCSP(string, flags);
    if (error != null) {
      // The CSP validation error is not reported as part of the "choices" error message,
      // we log the CSP validation error explicitly here to make it easier for the addon developers
      // to see and fix the extension CSP.
      context.logError(`Error processing ${context.currentTarget}: ${error}`);
      return null;
    }
    return string;
  },

  date(string, context) {
    // A valid ISO 8601 timestamp.
    const PATTERN =
      /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d{3})?(Z|([-+]\d{2}:?\d{2})))?$/;
    if (!PATTERN.test(string)) {
      throw new Error(`Invalid date string ${string}`);
    }
    // Our pattern just checks the format, we could still have invalid
    // values (e.g., month=99 or month=02 and day=31).  Let the Date
    // constructor do the dirty work of validating.
    if (isNaN(new Date(string))) {
      throw new Error(`Invalid date string ${string}`);
    }
    return string;
  },

  manifestShortcutKey(string, context) {
    if (lazy.ShortcutUtils.validate(string) == lazy.ShortcutUtils.IS_VALID) {
      return string;
    }
    let errorMessage =
      `Value "${string}" must consist of ` +
      `either a combination of one or two modifiers, including ` +
      `a mandatory primary modifier and a key, separated by '+', ` +
      `or a media key. For details see: ` +
      `https://developer.mozilla.org/en-US/Add-ons/WebExtensions/manifest.json/commands#Key_combinations`;
    throw new Error(errorMessage);
  },

  manifestShortcutKeyOrEmpty(string, context) {
    return string === "" ? "" : FORMATS.manifestShortcutKey(string, context);
  },

  versionString(string, context) {
    const parts = string.split(".");

    if (
      // We accept up to 4 numbers.
      parts.length > 4 ||
      // Non-zero values cannot start with 0 and we allow numbers up to 9 digits.
      parts.some(part => !/^(0|[1-9][0-9]{0,8})$/.test(part))
    ) {
      context.logWarning(
        `version must be a version string consisting of at most 4 integers ` +
          `of at most 9 digits without leading zeros, and separated with dots`
      );
    }

    // The idea is to only emit a warning when the version string does not
    // match the simple format we want to encourage developers to use. Given
    // the version is required, we always accept the value as is.
    return string;
  },
};

// Schema files contain namespaces, and each namespace contains types,
// properties, functions, and events. An Entry is a base class for
// types, properties, functions, and events.
class Entry {
  constructor(schema = {}) {
    /**
     * If set to any value which evaluates as true, this entry is
     * deprecated, and any access to it will result in a deprecation
     * warning being logged to the browser console.
     *
     * If the value is a string, it will be appended to the deprecation
     * message. If it contains the substring "${value}", it will be
     * replaced with a string representation of the value being
     * processed.
     *
     * If the value is any other truthy value, a generic deprecation
     * message will be emitted.
     */
    this.deprecated = false;
    if ("deprecated" in schema) {
      this.deprecated = schema.deprecated;
    }

    /**
     * @property {string} [preprocessor]
     * If set to a string value, and a preprocessor of the same is
     * defined in the validation context, it will be applied to this
     * value prior to any normalization.
     */
    this.preprocessor = schema.preprocess || null;

    /**
     * @property {string} [postprocessor]
     * If set to a string value, and a postprocessor of the same is
     * defined in the validation context, it will be applied to this
     * value after any normalization.
     */
    this.postprocessor = schema.postprocess || null;

    /**
     * @property {Array<string>} allowedContexts A list of allowed contexts
     * to consider before generating the API.
     * These are not parsed by the schema, but passed to `shouldInject`.
     */
    this.allowedContexts = schema.allowedContexts || [];

    this.min_manifest_version =
      schema.min_manifest_version ?? MIN_MANIFEST_VERSION;
    this.max_manifest_version =
      schema.max_manifest_version ?? MAX_MANIFEST_VERSION;
  }

  /**
   * Preprocess the given value with the preprocessor declared in
   * `preprocessor`.
   *
   * @param {*} value
   * @param {Context} context
   * @returns {*}
   */
  preprocess(value, context) {
    if (this.preprocessor) {
      return context.preprocessors[this.preprocessor](value, context);
    }
    return value;
  }

  /**
   * Postprocess the given result with the postprocessor declared in
   * `postprocessor`.
   *
   * @param {object} result
   * @param {Context} context
   * @returns {object}
   */
  postprocess(result, context) {
    if (result.error || !this.postprocessor) {
      return result;
    }

    let value = context.postprocessors[this.postprocessor](
      result.value,
      context
    );
    return { value };
  }

  /**
   * Logs a deprecation warning for this entry, based on the value of
   * its `deprecated` property.
   *
   * @param {Context} context
   * @param {value} [value]
   */
  logDeprecation(context, value = null) {
    let message = "This property is deprecated";
    if (typeof this.deprecated == "string") {
      message = this.deprecated;
      if (message.includes("${value}")) {
        try {
          value = JSON.stringify(value);
        } catch (e) {
          value = String(value);
        }
        message = message.replace(/\$\{value\}/g, () => value);
      }
    }

    context.logWarning(message);
  }

  /**
   * Checks whether the entry is deprecated and, if so, logs a
   * deprecation message.
   *
   * @param {Context} context
   * @param {value} [value]
   */
  checkDeprecated(context, value = null) {
    if (this.deprecated) {
      this.logDeprecation(context, value);
    }
  }

  /**
   * Returns an object containing property descriptor for use when
   * injecting this entry into an API object.
   *
   * @param {Array<string>} path The API path, e.g. `["storage", "local"]`.
   * @param {InjectionContext} context
   *
   * @returns {object?}
   *        An object containing a `descriptor` property, specifying the
   *        entry's property descriptor, and an optional `revoke`
   *        method, to be called when the entry is being revoked.
   */
  getDescriptor(path, context) {
    return undefined;
  }
}

// Corresponds either to a type declared in the "types" section of the
// schema or else to any type object used throughout the schema.
class Type extends Entry {
  /**
   * @property {Array<string>} EXTRA_PROPERTIES
   *        An array of extra properties which may be present for
   *        schemas of this type.
   */
  static get EXTRA_PROPERTIES() {
    return [
      "description",
      "deprecated",
      "preprocess",
      "postprocess",
      "privileged",
      "allowedContexts",
      "min_manifest_version",
      "max_manifest_version",
    ];
  }

  /**
   * Parses the given schema object and returns an instance of this
   * class which corresponds to its properties.
   *
   * @param {SchemaRoot} root
   *        The root schema for this type.
   * @param {object} schema
   *        A JSON schema object which corresponds to a definition of
   *        this type.
   * @param {Array<string>} path
   *        The path to this schema object from the root schema,
   *        corresponding to the property names and array indices
   *        traversed during parsing in order to arrive at this schema
   *        object.
   * @param {Array<string>} [extraProperties]
   *        An array of extra property names which are valid for this
   *        schema in the current context.
   * @returns {Type}
   *        An instance of this type which corresponds to the given
   *        schema object.
   * @static
   */
  static parseSchema(root, schema, path, extraProperties = []) {
    this.checkSchemaProperties(schema, path, extraProperties);

    return new this(schema);
  }

  /**
   * Checks that all of the properties present in the given schema
   * object are valid properties for this type, and throws if invalid.
   *
   * @param {object} schema
   *        A JSON schema object.
   * @param {Array<string>} path
   *        The path to this schema object from the root schema,
   *        corresponding to the property names and array indices
   *        traversed during parsing in order to arrive at this schema
   *        object.
   * @param {Array<string>} [extra]
   *        An array of extra property names which are valid for this
   *        schema in the current context.
   * @throws {Error}
   *        An error describing the first invalid property found in the
   *        schema object.
   */
  static checkSchemaProperties(schema, path, extra = []) {
    if (DEBUG) {
      let allowedSet = new Set([...this.EXTRA_PROPERTIES, ...extra]);

      for (let prop of Object.keys(schema)) {
        if (!allowedSet.has(prop)) {
          throw new Error(
            `Internal error: Namespace ${path.join(".")} has ` +
              `invalid type property "${prop}" ` +
              `in type "${schema.id || JSON.stringify(schema)}"`
          );
        }
      }
    }
  }

  // Takes a value, checks that it has the correct type, and returns a
  // "normalized" version of the value. The normalized version will
  // include "nulls" in place of omitted optional properties. The
  // result of this function is either {error: "Some type error"} or
  // {value: <normalized-value>}.
  normalize(value, context) {
    return context.error("invalid type");
  }

  // Unlike normalize, this function does a shallow check to see if
  // |baseType| (one of the possible getValueBaseType results) is
  // valid for this type. It returns true or false. It's used to fill
  // in optional arguments to functions before actually type checking

  checkBaseType(baseType) {
    return false;
  }

  // Helper method that simply relies on checkBaseType to implement
  // normalize. Subclasses can choose to use it or not.
  normalizeBase(type, value, context) {
    if (this.checkBaseType(getValueBaseType(value))) {
      this.checkDeprecated(context, value);
      return { value: this.preprocess(value, context) };
    }

    let choice;
    if ("aeiou".includes(type[0])) {
      choice = `be an ${type} value`;
    } else {
      choice = `be a ${type} value`;
    }

    return context.error(
      () => `Expected ${type} instead of ${JSON.stringify(value)}`,
      choice
    );
  }
}

// Type that allows any value.
class AnyType extends Type {
  normalize(value, context) {
    this.checkDeprecated(context, value);
    return this.postprocess({ value }, context);
  }

  checkBaseType(baseType) {
    return true;
  }
}

// An untagged union type.
class ChoiceType extends Type {
  static get EXTRA_PROPERTIES() {
    return ["choices", ...super.EXTRA_PROPERTIES];
  }

  static parseSchema(root, schema, path, extraProperties = []) {
    this.checkSchemaProperties(schema, path, extraProperties);

    let choices = schema.choices.map(t => root.parseSchema(t, path));
    return new this(schema, choices);
  }

  constructor(schema, choices) {
    super(schema);
    this.choices = choices;
  }

  extend(type) {
    this.choices.push(...type.choices);

    return this;
  }

  normalize(value, context) {
    this.checkDeprecated(context, value);

    let error;
    let { choices, result } = context.withChoices(() => {
      for (let choice of this.choices) {
        // Ignore a possible choice if it is not supported by
        // the manifest version we are normalizing.
        if (!context.matchManifestVersion(choice)) {
          continue;
        }

        let r = choice.normalize(value, context);
        if (!r.error) {
          return r;
        }

        error = r;
      }
    });

    if (result) {
      return result;
    }
    if (choices.size <= 1) {
      return error;
    }

    choices = Array.from(choices, forceString);
    let n = choices.length - 1;
    choices[n] = `or ${choices[n]}`;

    let message;
    if (typeof value === "object") {
      message = () => `Value must either: ${choices.join(", ")}`;
    } else {
      message = () =>
        `Value ${JSON.stringify(value)} must either: ${choices.join(", ")}`;
    }

    return context.error(message, null);
  }

  checkBaseType(baseType) {
    return this.choices.some(t => t.checkBaseType(baseType));
  }

  getDescriptor(path, context) {
    // In StringType.getDescriptor, unlike any other Type, a descriptor is returned if
    // it is an enumeration.  Since we need versioned choices in some cases, here we
    // build a list of valid enumerations that will work for a given manifest version.
    if (
      !this.choices.length ||
      !this.choices.every(t => t.checkBaseType("string") && t.enumeration)
    ) {
      return;
    }

    let obj = Cu.createObjectIn(context.cloneScope);
    let descriptor = { value: obj };
    for (let choice of this.choices) {
      // Ignore a possible choice if it is not supported by
      // the manifest version we are normalizing.
      if (!context.matchManifestVersion(choice)) {
        continue;
      }
      let d = choice.getDescriptor(path, context);
      if (d) {
        Object.assign(obj, d.descriptor.value);
      }
    }

    return { descriptor };
  }
}

// This is a reference to another type--essentially a typedef.
class RefType extends Type {
  static get EXTRA_PROPERTIES() {
    return ["$ref", ...super.EXTRA_PROPERTIES];
  }

  static parseSchema(root, schema, path, extraProperties = []) {
    this.checkSchemaProperties(schema, path, extraProperties);

    let ref = schema.$ref;
    let ns = path.join(".");
    if (ref.includes(".")) {
      [, ns, ref] = /^(.*)\.(.*?)$/.exec(ref);
    }
    return new this(root, schema, ns, ref);
  }

  // For a reference to a type named T declared in namespace NS,
  // namespaceName will be NS and reference will be T.
  constructor(root, schema, namespaceName, reference) {
    super(schema);
    this.root = root;
    this.namespaceName = namespaceName;
    this.reference = reference;
  }

  get targetType() {
    let ns = this.root.getNamespace(this.namespaceName);
    let type = ns.get(this.reference);
    if (!type) {
      throw new Error(`Internal error: Type ${this.reference} not found`);
    }
    return type;
  }

  normalize(value, context) {
    this.checkDeprecated(context, value);
    return this.targetType.normalize(value, context);
  }

  checkBaseType(baseType) {
    return this.targetType.checkBaseType(baseType);
  }
}

class StringType extends Type {
  static get EXTRA_PROPERTIES() {
    return [
      "enum",
      "minLength",
      "maxLength",
      "pattern",
      "format",
      ...super.EXTRA_PROPERTIES,
    ];
  }

  static parseSchema(root, schema, path, extraProperties = []) {
    this.checkSchemaProperties(schema, path, extraProperties);

    let enumeration = schema.enum || null;
    if (enumeration) {
      // The "enum" property is either a list of strings that are
      // valid values or else a list of {name, description} objects,
      // where the .name values are the valid values.
      enumeration = enumeration.map(e => {
        if (typeof e == "object") {
          return e.name;
        }
        return e;
      });
    }

    let pattern = null;
    if (schema.pattern) {
      try {
        pattern = parsePattern(schema.pattern);
      } catch (e) {
        throw new Error(
          `Internal error: Invalid pattern ${JSON.stringify(schema.pattern)}`
        );
      }
    }

    let format = null;
    if (schema.format) {
      if (!(schema.format in FORMATS)) {
        throw new Error(
          `Internal error: Invalid string format ${schema.format}`
        );
      }
      format = FORMATS[schema.format];
    }
    return new this(
      schema,
      schema.id || undefined,
      enumeration,
      schema.minLength || 0,
      schema.maxLength || Infinity,
      pattern,
      format
    );
  }

  constructor(
    schema,
    name,
    enumeration,
    minLength,
    maxLength,
    pattern,
    format
  ) {
    super(schema);
    this.name = name;
    this.enumeration = enumeration;
    this.minLength = minLength;
    this.maxLength = maxLength;
    this.pattern = pattern;
    this.format = format;
  }

  normalize(value, context) {
    let r = this.normalizeBase("string", value, context);
    if (r.error) {
      return r;
    }
    value = r.value;

    if (this.enumeration) {
      if (this.enumeration.includes(value)) {
        return this.postprocess({ value }, context);
      }

      let choices = this.enumeration.map(JSON.stringify).join(", ");

      return context.error(
        () => `Invalid enumeration value ${JSON.stringify(value)}`,
        `be one of [${choices}]`
      );
    }

    if (value.length < this.minLength) {
      return context.error(
        () =>
          `String ${JSON.stringify(value)} is too short (must be ${
            this.minLength
          })`,
        `be longer than ${this.minLength}`
      );
    }
    if (value.length > this.maxLength) {
      return context.error(
        () =>
          `String ${JSON.stringify(value)} is too long (must be ${
            this.maxLength
          })`,
        `be shorter than ${this.maxLength}`
      );
    }

    if (this.pattern && !this.pattern.test(value)) {
      return context.error(
        () => `String ${JSON.stringify(value)} must match ${this.pattern}`,
        `match the pattern ${this.pattern.toSource()}`
      );
    }

    if (this.format) {
      try {
        r.value = this.format(r.value, context);
      } catch (e) {
        return context.error(
          String(e),
          `match the format "${this.format.name}"`
        );
      }
    }

    return r;
  }

  checkBaseType(baseType) {
    return baseType == "string";
  }

  getDescriptor(path, context) {
    if (this.enumeration) {
      let obj = Cu.createObjectIn(context.cloneScope);

      for (let e of this.enumeration) {
        obj[e.toUpperCase()] = e;
      }

      return {
        descriptor: { value: obj },
      };
    }
  }
}

class NullType extends Type {
  normalize(value, context) {
    return this.normalizeBase("null", value, context);
  }

  checkBaseType(baseType) {
    return baseType == "null";
  }
}

let FunctionEntry;
let Event;
let SubModuleType;

class ObjectType extends Type {
  static get EXTRA_PROPERTIES() {
    return [
      "properties",
      "patternProperties",
      "$import",
      ...super.EXTRA_PROPERTIES,
    ];
  }

  static parseSchema(root, schema, path, extraProperties = []) {
    if ("functions" in schema) {
      return SubModuleType.parseSchema(root, schema, path, extraProperties);
    }

    if (DEBUG && !("$extend" in schema)) {
      // Only allow extending "properties" and "patternProperties".
      extraProperties = [
        "additionalProperties",
        "isInstanceOf",
        ...extraProperties,
      ];
    }
    this.checkSchemaProperties(schema, path, extraProperties);

    let imported = null;
    if ("$import" in schema) {
      let importPath = schema.$import;
      let idx = importPath.indexOf(".");
      if (idx === -1) {
        imported = [path[0], importPath];
      } else {
        imported = [importPath.slice(0, idx), importPath.slice(idx + 1)];
      }
    }

    let parseProperty = (schema, extraProps = []) => {
      return {
        type: root.parseSchema(
          schema,
          path,
          DEBUG && [
            "unsupported",
            "onError",
            "permissions",
            "default",
            ...extraProps,
          ]
        ),
        optional: schema.optional || false,
        unsupported: schema.unsupported || false,
        onError: schema.onError || null,
        default: schema.default === undefined ? null : schema.default,
      };
    };

    // Parse explicit "properties" object.
    let properties = Object.create(null);
    for (let propName of Object.keys(schema.properties || {})) {
      properties[propName] = parseProperty(schema.properties[propName], [
        "optional",
      ]);
    }

    // Parse regexp properties from "patternProperties" object.
    let patternProperties = [];
    for (let propName of Object.keys(schema.patternProperties || {})) {
      let pattern;
      try {
        pattern = parsePattern(propName);
      } catch (e) {
        throw new Error(
          `Internal error: Invalid property pattern ${JSON.stringify(propName)}`
        );
      }

      patternProperties.push({
        pattern,
        type: parseProperty(schema.patternProperties[propName]),
      });
    }

    // Parse "additionalProperties" schema.
    let additionalProperties = null;
    if (schema.additionalProperties) {
      let type = schema.additionalProperties;
      if (type === true) {
        type = { type: "any" };
      }

      additionalProperties = root.parseSchema(type, path);
    }

    return new this(
      schema,
      properties,
      additionalProperties,
      patternProperties,
      schema.isInstanceOf || null,
      imported
    );
  }

  constructor(
    schema,
    properties,
    additionalProperties,
    patternProperties,
    isInstanceOf,
    imported
  ) {
    super(schema);
    this.properties = properties;
    this.additionalProperties = additionalProperties;
    this.patternProperties = patternProperties;
    this.isInstanceOf = isInstanceOf;

    if (imported) {
      let [ns, path] = imported;
      ns = Schemas.getNamespace(ns);
      let importedType = ns.get(path);
      if (!importedType) {
        throw new Error(`Internal error: imported type ${path} not found`);
      }

      if (DEBUG && !(importedType instanceof ObjectType)) {
        throw new Error(
          `Internal error: cannot import non-object type ${path}`
        );
      }

      this.properties = Object.assign(
        {},
        importedType.properties,
        this.properties
      );
      this.patternProperties = [
        ...importedType.patternProperties,
        ...this.patternProperties,
      ];
      this.additionalProperties =
        importedType.additionalProperties || this.additionalProperties;
    }
  }

  extend(type) {
    for (let key of Object.keys(type.properties)) {
      if (key in this.properties) {
        throw new Error(
          `InternalError: Attempt to extend an object with conflicting property "${key}"`
        );
      }
      this.properties[key] = type.properties[key];
    }

    this.patternProperties.push(...type.patternProperties);

    return this;
  }

  checkBaseType(baseType) {
    return baseType == "object";
  }

  /**
   * Extracts the enumerable properties of the given object, including
   * function properties which would normally be omitted by X-ray
   * wrappers.
   *
   * @param {object} value
   * @param {Context} context
   *        The current parse context.
   * @returns {object}
   *        An object with an `error` or `value` property.
   */
  extractProperties(value, context) {
    // |value| should be a JS Xray wrapping an object in the
    // extension compartment. This works well except when we need to
    // access callable properties on |value| since JS Xrays don't
    // support those. To work around the problem, we verify that
    // |value| is a plain JS object (i.e., not anything scary like a
    // Proxy). Then we copy the properties out of it into a normal
    // object using a waiver wrapper.

    let klass = ChromeUtils.getClassName(value, true);
    if (klass != "Object") {
      throw context.error(
        `Expected a plain JavaScript object, got a ${klass}`,
        `be a plain JavaScript object`
      );
    }

    return ChromeUtils.shallowClone(value);
  }

  checkProperty(context, prop, propType, result, properties, remainingProps) {
    let { type, optional, unsupported, onError } = propType;
    let error = null;

    if (!context.matchManifestVersion(type)) {
      if (prop in properties) {
        error = context.error(
          `Property "${prop}" is unsupported in Manifest Version ${context.manifestVersion}`,
          `not contain an unsupported "${prop}" property`
        );

        context.logWarning(forceString(error.error));
        if (this.additionalProperties) {
          // When `additionalProperties` is set to UnrecognizedProperty, the
          // caller (i.e. ObjectType's normalize method) assigns the original
          // value to `result[prop]`. Erase the property now to prevent
          // `result[prop]` from becoming anything other than `undefined.
          //
          // A warning was already logged above, so we do not need to also log
          // "An unexpected property was found in the WebExtension manifest."
          remainingProps.delete(prop);
        }
        // When `additionalProperties` is not set, ObjectType's normalize method
        // will return an error because prop is still in remainingProps.
        return;
      }
    } else if (unsupported) {
      if (prop in properties) {
        error = context.error(
          `Property "${prop}" is unsupported by Firefox`,
          `not contain an unsupported "${prop}" property`
        );
      }
    } else if (prop in properties) {
      if (
        optional &&
        (properties[prop] === null || properties[prop] === undefined)
      ) {
        result[prop] = propType.default;
      } else {
        let r = context.withPath(prop, () =>
          type.normalize(properties[prop], context)
        );
        if (r.error) {
          error = r;
        } else {
          result[prop] = r.value;
          properties[prop] = r.value;
        }
      }
      remainingProps.delete(prop);
    } else if (!optional) {
      error = context.error(
        `Property "${prop}" is required`,
        `contain the required "${prop}" property`
      );
    } else if (optional !== "omit-key-if-missing") {
      result[prop] = propType.default;
    }

    if (error) {
      if (onError == "warn") {
        context.logWarning(forceString(error.error));
      } else if (onError != "ignore") {
        throw error;
      }

      result[prop] = propType.default;
    }
  }

  normalize(value, context) {
    try {
      let v = this.normalizeBase("object", value, context);
      if (v.error) {
        return v;
      }
      value = v.value;

      if (this.isInstanceOf) {
        if (DEBUG) {
          if (
            Object.keys(this.properties).length ||
            this.patternProperties.length ||
            !(this.additionalProperties instanceof AnyType)
          ) {
            throw new Error(
              "InternalError: isInstanceOf can only be used " +
                "with objects that are otherwise unrestricted"
            );
          }
        }

        if (
          ChromeUtils.getClassName(value) !== this.isInstanceOf &&
          (this.isInstanceOf !== "Element" || value.nodeType !== 1)
        ) {
          return context.error(
            `Object must be an instance of ${this.isInstanceOf}`,
            `be an instance of ${this.isInstanceOf}`
          );
        }

        // This is kind of a hack, but we can't normalize things that
        // aren't JSON, so we just return them.
        return this.postprocess({ value }, context);
      }

      let properties = this.extractProperties(value, context);
      let remainingProps = new Set(Object.keys(properties));

      let result = {};
      for (let prop of Object.keys(this.properties)) {
        this.checkProperty(
          context,
          prop,
          this.properties[prop],
          result,
          properties,
          remainingProps
        );
      }

      for (let prop of Object.keys(properties)) {
        for (let { pattern, type } of this.patternProperties) {
          if (pattern.test(prop)) {
            this.checkProperty(
              context,
              prop,
              type,
              result,
              properties,
              remainingProps
            );
          }
        }
      }

      if (this.additionalProperties) {
        for (let prop of remainingProps) {
          let r = context.withPath(prop, () =>
            this.additionalProperties.normalize(properties[prop], context)
          );
          if (r.error) {
            return r;
          }
          result[prop] = r.value;
        }
      } else if (remainingProps.size == 1) {
        return context.error(
          `Unexpected property "${[...remainingProps]}"`,
          `not contain an unexpected "${[...remainingProps]}" property`
        );
      } else if (remainingProps.size) {
        let props = [...remainingProps].sort().join(", ");
        return context.error(
          `Unexpected properties: ${props}`,
          `not contain the unexpected properties [${props}]`
        );
      }

      return this.postprocess({ value: result }, context);
    } catch (e) {
      if (e.error) {
        return e;
      }
      throw e;
    }
  }
}

// This type is just a placeholder to be referred to by
// SubModuleProperty. No value is ever expected to have this type.
SubModuleType = class SubModuleType extends Type {
  static get EXTRA_PROPERTIES() {
    return ["functions", "events", "properties", ...super.EXTRA_PROPERTIES];
  }

  static parseSchema(root, schema, path, extraProperties = []) {
    this.checkSchemaProperties(schema, path, extraProperties);

    // The path we pass in here is only used for error messages.
    path = [...path, schema.id];
    let functions = schema.functions
      .filter(fun => !fun.unsupported)
      .map(fun => FunctionEntry.parseSchema(root, fun, path));

    let events = [];

    if (schema.events) {
      events = schema.events
        .filter(event => !event.unsupported)
        .map(event => Event.parseSchema(root, event, path));
    }

    return new this(schema, functions, events);
  }

  constructor(schema, functions, events) {
    // schema contains properties such as min/max_manifest_version needed
    // in the base class so that the Context class can version compare
    // any entries against the manifest version.
    super(schema);
    this.functions = functions;
    this.events = events;
  }
};

class NumberType extends Type {
  normalize(value, context) {
    let r = this.normalizeBase("number", value, context);
    if (r.error) {
      return r;
    }

    if (isNaN(r.value) || !Number.isFinite(r.value)) {
      return context.error(
        "NaN and infinity are not valid",
        "be a finite number"
      );
    }

    return r;
  }

  checkBaseType(baseType) {
    return baseType == "number" || baseType == "integer";
  }
}

class IntegerType extends Type {
  static get EXTRA_PROPERTIES() {
    return ["minimum", "maximum", ...super.EXTRA_PROPERTIES];
  }

  static parseSchema(root, schema, path, extraProperties = []) {
    this.checkSchemaProperties(schema, path, extraProperties);

    let { minimum = -Infinity, maximum = Infinity } = schema;
    return new this(schema, minimum, maximum);
  }

  constructor(schema, minimum, maximum) {
    super(schema);
    this.minimum = minimum;
    this.maximum = maximum;
  }

  normalize(value, context) {
    let r = this.normalizeBase("integer", value, context);
    if (r.error) {
      return r;
    }
    value = r.value;

    // Ensure it's between -2**31 and 2**31-1
    if (!Number.isSafeInteger(value)) {
      return context.error(
        "Integer is out of range",
        "be a valid 32 bit signed integer"
      );
    }

    if (value < this.minimum) {
      return context.error(
        `Integer ${value} is too small (must be at least ${this.minimum})`,
        `be at least ${this.minimum}`
      );
    }
    if (value > this.maximum) {
      return context.error(
        `Integer ${value} is too big (must be at most ${this.maximum})`,
        `be no greater than ${this.maximum}`
      );
    }

    return this.postprocess(r, context);
  }

  checkBaseType(baseType) {
    return baseType == "integer";
  }
}

class BooleanType extends Type {
  static get EXTRA_PROPERTIES() {
    return ["enum", ...super.EXTRA_PROPERTIES];
  }

  static parseSchema(root, schema, path, extraProperties = []) {
    this.checkSchemaProperties(schema, path, extraProperties);
    let enumeration = schema.enum || null;
    return new this(schema, enumeration);
  }

  constructor(schema, enumeration) {
    super(schema);
    this.enumeration = enumeration;
  }

  normalize(value, context) {
    if (!this.checkBaseType(getValueBaseType(value))) {
      return context.error(
        () => `Expected boolean instead of ${JSON.stringify(value)}`,
        `be a boolean`
      );
    }
    value = this.preprocess(value, context);
    if (this.enumeration && !this.enumeration.includes(value)) {
      return context.error(
        () => `Invalid value ${JSON.stringify(value)}`,
        `be ${this.enumeration}`
      );
    }
    this.checkDeprecated(context, value);
    return { value };
  }

  checkBaseType(baseType) {
    return baseType == "boolean";
  }
}

class ArrayType extends Type {
  static get EXTRA_PROPERTIES() {
    return ["items", "minItems", "maxItems", ...super.EXTRA_PROPERTIES];
  }

  static parseSchema(root, schema, path, extraProperties = []) {
    this.checkSchemaProperties(schema, path, extraProperties);

    let items = root.parseSchema(schema.items, path, ["onError"]);

    return new this(
      schema,
      items,
      schema.minItems || 0,
      schema.maxItems || Infinity
    );
  }

  constructor(schema, itemType, minItems, maxItems) {
    super(schema);
    this.itemType = itemType;
    this.minItems = minItems;
    this.maxItems = maxItems;
    this.onError = schema.items.onError || null;
  }

  normalize(value, context) {
    let v = this.normalizeBase("array", value, context);
    if (v.error) {
      return v;
    }
    value = v.value;

    let result = [];
    for (let [i, element] of value.entries()) {
      element = context.withPath(String(i), () =>
        this.itemType.normalize(element, context)
      );
      if (element.error) {
        if (this.onError == "warn") {
          context.logWarning(forceString(element.error));
        } else if (this.onError != "ignore") {
          return element;
        }
        continue;
      }
      result.push(element.value);
    }

    if (result.length < this.minItems) {
      return context.error(
        `Array requires at least ${this.minItems} items; you have ${result.length}`,
        `have at least ${this.minItems} items`
      );
    }

    if (result.length > this.maxItems) {
      return context.error(
        `Array requires at most ${this.maxItems} items; you have ${result.length}`,
        `have at most ${this.maxItems} items`
      );
    }

    return this.postprocess({ value: result }, context);
  }

  checkBaseType(baseType) {
    return baseType == "array";
  }
}

class FunctionType extends Type {
  static get EXTRA_PROPERTIES() {
    return [
      "parameters",
      "async",
      "returns",
      "requireUserInput",
      ...super.EXTRA_PROPERTIES,
    ];
  }

  static parseSchema(root, schema, path, extraProperties = []) {
    this.checkSchemaProperties(schema, path, extraProperties);

    let isAsync = !!schema.async;
    let isExpectingCallback = typeof schema.async === "string";
    let parameters = null;
    if ("parameters" in schema) {
      parameters = [];
      for (let param of schema.parameters) {
        // Callbacks default to optional for now, because of promise
        // handling.
        let isCallback = isAsync && param.name == schema.async;
        if (isCallback) {
          isExpectingCallback = false;
        }

        parameters.push({
          type: root.parseSchema(param, path, ["name", "optional", "default"]),
          name: param.name,
          optional: param.optional == null ? isCallback : param.optional,
          default: param.default == undefined ? null : param.default,
        });
      }
    }
    let hasAsyncCallback = false;
    if (isAsync) {
      hasAsyncCallback =
        parameters &&
        parameters.length &&
        parameters[parameters.length - 1].name == schema.async;
    }

    if (DEBUG) {
      if (isExpectingCallback) {
        throw new Error(
          `Internal error: Expected a callback parameter ` +
            `with name ${schema.async}`
        );
      }

      if (isAsync && schema.returns) {
        throw new Error(
          "Internal error: Async functions must not have return values."
        );
      }
      if (
        isAsync &&
        schema.allowAmbiguousOptionalArguments &&
        !hasAsyncCallback
      ) {
        throw new Error(
          "Internal error: Async functions with ambiguous " +
            "arguments must declare the callback as the last parameter"
        );
      }
    }

    return new this(
      schema,
      parameters,
      isAsync,
      hasAsyncCallback,
      !!schema.requireUserInput
    );
  }

  constructor(schema, parameters, isAsync, hasAsyncCallback, requireUserInput) {
    super(schema);
    this.parameters = parameters;
    this.isAsync = isAsync;
    this.hasAsyncCallback = hasAsyncCallback;
    this.requireUserInput = requireUserInput;
  }

  normalize(value, context) {
    return this.normalizeBase("function", value, context);
  }

  checkBaseType(baseType) {
    return baseType == "function";
  }
}

// Represents a "property" defined in a schema namespace with a
// particular value. Essentially this is a constant.
class ValueProperty extends Entry {
  constructor(schema, name, value) {
    super(schema);
    this.name = name;
    this.value = value;
  }

  getDescriptor(path, context) {
    // Prevent injection if not a supported version.
    if (!context.matchManifestVersion(this)) {
      return;
    }

    return {
      descriptor: { value: this.value },
    };
  }
}

// Represents a "property" defined in a schema namespace that is not a
// constant.
class TypeProperty extends Entry {
  constructor(schema, path, name, type, writable, permissions) {
    super(schema);
    this.path = path;
    this.name = name;
    this.type = type;
    this.writable = writable;
    this.permissions = permissions;
  }

  throwError(context, msg) {
    throw context.makeError(`${msg} for ${this.path.join(".")}.${this.name}.`);
  }

  getDescriptor(path, context) {
    if (this.unsupported || !context.matchManifestVersion(this)) {
      return;
    }

    let apiImpl = context.getImplementation(path.join("."), this.name);

    let getStub = () => {
      this.checkDeprecated(context);
      return apiImpl.getProperty();
    };

    let descriptor = {
      get: Cu.exportFunction(getStub, context.cloneScope),
    };

    if (this.writable) {
      let setStub = value => {
        let normalized = this.type.normalize(value, context);
        if (normalized.error) {
          this.throwError(context, forceString(normalized.error));
        }

        apiImpl.setProperty(normalized.value);
      };

      descriptor.set = Cu.exportFunction(setStub, context.cloneScope);
    }

    return {
      descriptor,
      revoke() {
        apiImpl.revoke();
        apiImpl = null;
      },
    };
  }
}

class SubModuleProperty extends Entry {
  // A SubModuleProperty represents a tree of objects and properties
  // to expose to an extension. Currently we support only a limited
  // form of sub-module properties, where "$ref" points to a
  // SubModuleType containing a list of functions and "properties" is
  // a list of additional simple properties.
  //
  // name: Name of the property stuff is being added to.
  // namespaceName: Namespace in which the property lives.
  // reference: Name of the type defining the functions to add to the property.
  // properties: Additional properties to add to the module (unsupported).
  constructor(root, schema, path, name, reference, properties, permissions) {
    super(schema);
    this.root = root;
    this.name = name;
    this.path = path;
    this.namespaceName = path.join(".");
    this.reference = reference;
    this.properties = properties;
    this.permissions = permissions;
  }

  get targetType() {
    let ns = this.root.getNamespace(this.namespaceName);
    let type = ns.get(this.reference);
    if (!type && this.reference.includes(".")) {
      let [namespaceName, ref] = this.reference.split(".");
      ns = this.root.getNamespace(namespaceName);
      type = ns.get(ref);
    }
    return type;
  }

  getDescriptor(path, context) {
    let obj = Cu.createObjectIn(context.cloneScope);

    let ns = this.root.getNamespace(this.namespaceName);
    let type = this.targetType;

    // Prevent injection if not a supported version.
    if (!context.matchManifestVersion(type)) {
      return;
    }

    if (DEBUG) {
      if (!type || !(type instanceof SubModuleType)) {
        throw new Error(
          `Internal error: ${this.namespaceName}.${this.reference} ` +
            `is not a sub-module`
        );
      }
    }
    let subpath = [...path, this.name];

    let functions = type.functions;
    for (let fun of functions) {
      context.injectInto(fun, obj, fun.name, subpath, ns);
    }

    let events = type.events;
    for (let event of events) {
      context.injectInto(event, obj, event.name, subpath, ns);
    }

    // TODO: Inject this.properties.

    return {
      descriptor: { value: obj },
      revoke() {
        let unwrapped = ChromeUtils.waiveXrays(obj);
        for (let fun of functions) {
          try {
            delete unwrapped[fun.name];
          } catch (e) {
            Cu.reportError(e);
          }
        }
      },
    };
  }
}

// This class is a base class for FunctionEntrys and Events. It takes
// care of validating parameter lists (i.e., handling of optional
// parameters and parameter type checking).
class CallEntry extends Entry {
  constructor(schema, path, name, parameters, allowAmbiguousOptionalArguments) {
    super(schema);
    this.path = path;
    this.name = name;
    this.parameters = parameters;
    this.allowAmbiguousOptionalArguments = allowAmbiguousOptionalArguments;
  }

  throwError(context, msg) {
    throw context.makeError(`${msg} for ${this.path.join(".")}.${this.name}.`);
  }

  checkParameters(args, context) {
    let fixedArgs = [];

    // First we create a new array, fixedArgs, that is the same as
    // |args| but with default values in place of omitted optional parameters.
    let check = (parameterIndex, argIndex) => {
      if (parameterIndex == this.parameters.length) {
        if (argIndex == args.length) {
          return true;
        }
        return false;
      }

      let parameter = this.parameters[parameterIndex];
      if (parameter.optional) {
        // Try skipping it.
        fixedArgs[parameterIndex] = parameter.default;
        if (check(parameterIndex + 1, argIndex)) {
          return true;
        }
      }

      if (argIndex == args.length) {
        return false;
      }

      let arg = args[argIndex];
      if (!parameter.type.checkBaseType(getValueBaseType(arg))) {
        // For Chrome compatibility, use the default value if null or undefined
        // is explicitly passed but is not a valid argument in this position.
        if (parameter.optional && (arg === null || arg === undefined)) {
          fixedArgs[parameterIndex] = Cu.cloneInto(parameter.default, {});
        } else {
          return false;
        }
      } else {
        fixedArgs[parameterIndex] = arg;
      }

      return check(parameterIndex + 1, argIndex + 1);
    };

    if (this.allowAmbiguousOptionalArguments) {
      // When this option is set, it's up to the implementation to
      // parse arguments.
      // The last argument for asynchronous methods is either a function or null.
      // This is specifically done for runtime.sendMessage.
      if (this.hasAsyncCallback && typeof args[args.length - 1] != "function") {
        args.push(null);
      }
      return args;
    }
    let success = check(0, 0);
    if (!success) {
      this.throwError(context, "Incorrect argument types");
    }

    // Now we normalize (and fully type check) all non-omitted arguments.
    fixedArgs = fixedArgs.map((arg, parameterIndex) => {
      if (arg === null) {
        return null;
      }
      let parameter = this.parameters[parameterIndex];
      let r = parameter.type.normalize(arg, context);
      if (r.error) {
        this.throwError(
          context,
          `Type error for parameter ${parameter.name} (${forceString(r.error)})`
        );
      }
      return r.value;
    });

    return fixedArgs;
  }
}

// Represents a "function" defined in a schema namespace.
FunctionEntry = class FunctionEntry extends CallEntry {
  static parseSchema(root, schema, path) {
    // When not in DEBUG mode, we just need to know *if* this returns.
    let returns = !!schema.returns;
    if (DEBUG && "returns" in schema) {
      returns = {
        type: root.parseSchema(schema.returns, path, ["optional", "name"]),
        optional: schema.returns.optional || false,
        name: "result",
      };
    }

    return new this(
      schema,
      path,
      schema.name,
      root.parseSchema(schema, path, [
        "name",
        "unsupported",
        "returns",
        "permissions",
        "allowAmbiguousOptionalArguments",
        "allowCrossOriginArguments",
      ]),
      schema.unsupported || false,
      schema.allowAmbiguousOptionalArguments || false,
      schema.allowCrossOriginArguments || false,
      returns,
      schema.permissions || null
    );
  }

  constructor(
    schema,
    path,
    name,
    type,
    unsupported,
    allowAmbiguousOptionalArguments,
    allowCrossOriginArguments,
    returns,
    permissions
  ) {
    super(schema, path, name, type.parameters, allowAmbiguousOptionalArguments);
    this.unsupported = unsupported;
    this.returns = returns;
    this.permissions = permissions;
    this.allowCrossOriginArguments = allowCrossOriginArguments;

    this.isAsync = type.isAsync;
    this.hasAsyncCallback = type.hasAsyncCallback;
    this.requireUserInput = type.requireUserInput;
  }

  checkValue({ type, optional, name }, value, context) {
    if (optional && value == null) {
      return;
    }
    if (
      type.reference === "ExtensionPanel" ||
      type.reference === "ExtensionSidebarPane" ||
      type.reference === "Port"
    ) {
      // TODO: We currently treat objects with functions as SubModuleType,
      // which is just wrong, and a bigger yak.  Skipping for now.
      return;
    }
    const { error } = type.normalize(value, context);
    if (error) {
      this.throwError(
        context,
        `Type error for ${name} value (${forceString(error)})`
      );
    }
  }

  checkCallback(args, context) {
    const callback = this.parameters[this.parameters.length - 1];
    for (const [i, param] of callback.type.parameters.entries()) {
      this.checkValue(param, args[i], context);
    }
  }

  getDescriptor(path, context) {
    let apiImpl = context.getImplementation(path.join("."), this.name);

    let stub;
    if (this.isAsync) {
      stub = (...args) => {
        this.checkDeprecated(context);
        let actuals = this.checkParameters(args, context);
        let callback = null;
        if (this.hasAsyncCallback) {
          callback = actuals.pop();
        }
        if (callback === null && context.isChromeCompat) {
          // We pass an empty stub function as a default callback for
          // the `chrome` API, so promise objects are not returned,
          // and lastError values are reported immediately.
          callback = () => {};
        }
        if (DEBUG && this.hasAsyncCallback && callback) {
          let original = callback;
          callback = (...args) => {
            this.checkCallback(args, context);
            original(...args);
          };
        }
        let result = apiImpl.callAsyncFunction(
          actuals,
          callback,
          this.requireUserInput
        );
        if (DEBUG && this.hasAsyncCallback && !callback) {
          return result.then(result => {
            this.checkCallback([result], context);
            return result;
          });
        }
        return result;
      };
    } else if (!this.returns) {
      stub = (...args) => {
        this.checkDeprecated(context);
        let actuals = this.checkParameters(args, context);
        return apiImpl.callFunctionNoReturn(actuals);
      };
    } else {
      stub = (...args) => {
        this.checkDeprecated(context);
        let actuals = this.checkParameters(args, context);
        let result = apiImpl.callFunction(actuals);
        if (DEBUG && this.returns) {
          this.checkValue(this.returns, result, context);
        }
        return result;
      };
    }

    return {
      descriptor: {
        value: Cu.exportFunction(stub, context.cloneScope, {
          allowCrossOriginArguments: this.allowCrossOriginArguments,
        }),
      },
      revoke() {
        apiImpl.revoke();
        apiImpl = null;
      },
    };
  }
};

// Represents an "event" defined in a schema namespace.
//
// TODO Bug 1369722: we should be able to remove the eslint-disable-line that follows
// once Bug 1369722 has been fixed.
// eslint-disable-next-line no-global-assign
Event = class Event extends CallEntry {
  static parseSchema(root, event, path) {
    let extraParameters = Array.from(event.extraParameters || [], param => ({
      type: root.parseSchema(param, path, ["name", "optional", "default"]),
      name: param.name,
      optional: param.optional || false,
      default: param.default == undefined ? null : param.default,
    }));

    let extraProperties = [
      "name",
      "unsupported",
      "permissions",
      "extraParameters",
      // We ignore these properties for now.
      "returns",
      "filters",
    ];

    return new this(
      event,
      path,
      event.name,
      root.parseSchema(event, path, extraProperties),
      extraParameters,
      event.unsupported || false,
      event.permissions || null
    );
  }

  constructor(
    schema,
    path,
    name,
    type,
    extraParameters,
    unsupported,
    permissions
  ) {
    super(schema, path, name, extraParameters);
    this.type = type;
    this.unsupported = unsupported;
    this.permissions = permissions;
  }

  checkListener(listener, context) {
    let r = this.type.normalize(listener, context);
    if (r.error) {
      this.throwError(context, "Invalid listener");
    }
    return r.value;
  }

  getDescriptor(path, context) {
    let apiImpl = context.getImplementation(path.join("."), this.name);

    let addStub = (listener, ...args) => {
      listener = this.checkListener(listener, context);
      let actuals = this.checkParameters(args, context);
      apiImpl.addListener(listener, actuals);
    };

    let removeStub = listener => {
      listener = this.checkListener(listener, context);
      apiImpl.removeListener(listener);
    };

    let hasStub = listener => {
      listener = this.checkListener(listener, context);
      return apiImpl.hasListener(listener);
    };

    let obj = Cu.createObjectIn(context.cloneScope);

    Cu.exportFunction(addStub, obj, { defineAs: "addListener" });
    Cu.exportFunction(removeStub, obj, { defineAs: "removeListener" });
    Cu.exportFunction(hasStub, obj, { defineAs: "hasListener" });

    return {
      descriptor: { value: obj },
      revoke() {
        apiImpl.revoke();
        apiImpl = null;

        let unwrapped = ChromeUtils.waiveXrays(obj);
        delete unwrapped.addListener;
        delete unwrapped.removeListener;
        delete unwrapped.hasListener;
      },
    };
  }
};

const TYPES = Object.freeze(
  Object.assign(Object.create(null), {
    any: AnyType,
    array: ArrayType,
    boolean: BooleanType,
    function: FunctionType,
    integer: IntegerType,
    null: NullType,
    number: NumberType,
    object: ObjectType,
    string: StringType,
  })
);

const LOADERS = {
  events: "loadEvent",
  functions: "loadFunction",
  properties: "loadProperty",
  types: "loadType",
};

class Namespace extends Map {
  constructor(root, name, path) {
    super();

    this.root = root;

    this._lazySchemas = [];
    this.initialized = false;

    this.name = name;
    this.path = name ? [...path, name] : [...path];

    this.superNamespace = null;

    this.min_manifest_version = MIN_MANIFEST_VERSION;
    this.max_manifest_version = MAX_MANIFEST_VERSION;

    this.permissions = null;
    this.allowedContexts = [];
    this.defaultContexts = [];
  }

  /**
   * Adds a JSON Schema object to the set of schemas that represent this
   * namespace.
   *
   * @param {object} schema
   *        A JSON schema object which partially describes this
   *        namespace.
   */
  addSchema(schema) {
    this._lazySchemas.push(schema);

    for (let prop of [
      "permissions",
      "allowedContexts",
      "defaultContexts",
      "min_manifest_version",
      "max_manifest_version",
    ]) {
      if (schema[prop]) {
        this[prop] = schema[prop];
      }
    }

    if (schema.$import) {
      this.superNamespace = this.root.getNamespace(schema.$import);
    }
  }

  /**
   * Initializes the keys of this namespace based on the schema objects
   * added via previous `addSchema` calls.
   */
  init() {
    if (this.initialized) {
      return;
    }

    if (this.superNamespace) {
      this._lazySchemas.unshift(...this.superNamespace._lazySchemas);
    }

    for (let type of Object.keys(LOADERS)) {
      this[type] = new DefaultMap(() => []);
    }

    for (let schema of this._lazySchemas) {
      for (let type of schema.types || []) {
        if (!type.unsupported) {
          this.types.get(type.$extend || type.id).push(type);
        }
      }

      for (let [name, prop] of Object.entries(schema.properties || {})) {
        if (!prop.unsupported) {
          this.properties.get(name).push(prop);
        }
      }

      for (let fun of schema.functions || []) {
        if (!fun.unsupported) {
          this.functions.get(fun.name).push(fun);
        }
      }

      for (let event of schema.events || []) {
        if (!event.unsupported) {
          this.events.get(event.name).push(event);
        }
      }
    }

    // For each type of top-level property in the schema object, iterate
    // over all properties of that type, and create a temporary key for
    // each property pointing to its type. Those temporary properties
    // are later used to instantiate an Entry object based on the actual
    // schema object.
    for (let type of Object.keys(LOADERS)) {
      for (let key of this[type].keys()) {
        this.set(key, type);
      }
    }

    this.initialized = true;

    if (DEBUG) {
      for (let key of this.keys()) {
        this.get(key);
      }
    }
  }

  /**
   * Initializes the value of a given key, by parsing the schema object
   * associated with it and replacing its temporary value with an `Entry`
   * instance.
   *
   * @param {string} key
   *        The name of the property to initialize.
   * @param {string} type
   *        The type of property the key represents. Must have a
   *        corresponding entry in the `LOADERS` object, pointing to the
   *        initialization method for that type.
   *
   * @returns {Entry}
   */
  initKey(key, type) {
    let loader = LOADERS[type];

    for (let schema of this[type].get(key)) {
      this.set(key, this[loader](key, schema));
    }

    return this.get(key);
  }

  loadType(name, type) {
    if ("$extend" in type) {
      return this.extendType(type);
    }
    return this.root.parseSchema(type, this.path, ["id"]);
  }

  extendType(type) {
    let targetType = this.get(type.$extend);

    // Only allow extending object and choices types for now.
    if (targetType instanceof ObjectType) {
      type.type = "object";
    } else if (DEBUG) {
      if (!targetType) {
        throw new Error(
          `Internal error: Attempt to extend a nonexistent type ${type.$extend}`
        );
      } else if (!(targetType instanceof ChoiceType)) {
        throw new Error(
          `Internal error: Attempt to extend a non-extensible type ${type.$extend}`
        );
      }
    }

    let parsed = this.root.parseSchema(type, this.path, ["$extend"]);

    if (DEBUG && parsed.constructor !== targetType.constructor) {
      throw new Error(`Internal error: Bad attempt to extend ${type.$extend}`);
    }

    targetType.extend(parsed);

    return targetType;
  }

  loadProperty(name, prop) {
    if ("$ref" in prop) {
      if (!prop.unsupported) {
        return new SubModuleProperty(
          this.root,
          prop,
          this.path,
          name,
          prop.$ref,
          prop.properties || {},
          prop.permissions || null
        );
      }
    } else if ("value" in prop) {
      return new ValueProperty(prop, name, prop.value);
    } else {
      // We ignore the "optional" attribute on properties since we
      // don't inject anything here anyway.
      let type = this.root.parseSchema(
        prop,
        [this.name],
        ["optional", "permissions", "writable"]
      );
      return new TypeProperty(
        prop,
        this.path,
        name,
        type,
        prop.writable || false,
        prop.permissions || null
      );
    }
  }

  loadFunction(name, fun) {
    return FunctionEntry.parseSchema(this.root, fun, this.path);
  }

  loadEvent(name, event) {
    return Event.parseSchema(this.root, event, this.path);
  }

  /**
   * Injects the properties of this namespace into the given object.
   *
   * @param {object} dest
   *        The object into which to inject the namespace properties.
   * @param {InjectionContext} context
   *        The injection context with which to inject the properties.
   */
  injectInto(dest, context) {
    for (let name of this.keys()) {
      // If the entry does not match the manifest version do not
      // inject the property.  This prevents the item from being
      // enumerable in the namespace object.  We cannot accomplish
      // this inside exportLazyProperty, it specifically injects
      // an enumerable object.
      let entry = this.get(name);
      if (!context.matchManifestVersion(entry)) {
        continue;
      }
      exportLazyProperty(dest, name, () => {
        let entry = this.get(name);

        return context.getDescriptor(entry, dest, name, this.path, this);
      });
    }
  }

  getDescriptor(path, context) {
    let obj = Cu.createObjectIn(context.cloneScope);

    let ns = context.schemaRoot.getNamespace(this.path.join("."));
    ns.injectInto(obj, context);

    // Only inject the namespace object if it isn't empty.
    if (Object.keys(obj).length) {
      return {
        descriptor: { value: obj },
      };
    }
  }

  keys() {
    this.init();
    return super.keys();
  }

  *entries() {
    for (let key of this.keys()) {
      yield [key, this.get(key)];
    }
  }

  get(key) {
    this.init();
    let value = super.get(key);

    // The initial values of lazily-initialized schema properties are
    // strings, pointing to the type of property, corresponding to one
    // of the entries in the `LOADERS` object.
    if (typeof value === "string") {
      value = this.initKey(key, value);
    }

    return value;
  }

  /**
   * Returns a Namespace object for the given namespace name. If a
   * namespace object with this name does not already exist, it is
   * created. If the name contains any '.' characters, namespaces are
   * recursively created, for each dot-separated component.
   *
   * @param {string} name
   *        The name of the sub-namespace to retrieve.
   * @param {boolean} [create = true]
   *        If true, create any intermediate namespaces which don't
   *        exist.
   *
   * @returns {Namespace}
   */
  getNamespace(name, create = true) {
    let subName;

    let idx = name.indexOf(".");
    if (idx > 0) {
      subName = name.slice(idx + 1);
      name = name.slice(0, idx);
    }

    let ns = super.get(name);
    if (!ns) {
      if (!create) {
        return null;
      }
      ns = new Namespace(this.root, name, this.path);
      this.set(name, ns);
    }

    if (subName) {
      return ns.getNamespace(subName);
    }
    return ns;
  }

  getOwnNamespace(name) {
    return this.getNamespace(name);
  }

  has(key) {
    this.init();
    return super.has(key);
  }
}

/**
 * A namespace which combines the children of an arbitrary number of
 * sub-namespaces.
 */
class Namespaces extends Namespace {
  constructor(root, name, path, namespaces) {
    super(root, name, path);

    this.namespaces = namespaces;
  }

  injectInto(obj, context) {
    for (let ns of this.namespaces) {
      ns.injectInto(obj, context);
    }
  }
}

/**
 * A root schema which combines the contents of an arbitrary number of base
 * schema roots.
 */
class SchemaRoots extends Namespaces {
  constructor(root, bases) {
    bases = bases.map(base => base.rootSchema || base);

    super(null, "", [], bases);

    this.root = root;
    this.bases = bases;
    this._namespaces = new Map();
  }

  _getNamespace(name, create) {
    let results = [];
    for (let root of this.bases) {
      let ns = root.getNamespace(name, create);
      if (ns) {
        results.push(ns);
      }
    }

    if (results.length == 1) {
      return results[0];
    }

    if (results.length) {
      return new Namespaces(this.root, name, name.split("."), results);
    }
    return null;
  }

  getNamespace(name, create) {
    let ns = this._namespaces.get(name);
    if (!ns) {
      ns = this._getNamespace(name, create);
      if (ns) {
        this._namespaces.set(name, ns);
      }
    }
    return ns;
  }

  *getNamespaces(name) {
    for (let root of this.bases) {
      yield* root.getNamespaces(name);
    }
  }
}

/**
 * A root schema namespace containing schema data which is isolated from data in
 * other schema roots. May extend a base namespace, in which case schemas in
 * this root may refer to types in a base, but not vice versa.
 *
 * @param {SchemaRoot|Array<SchemaRoot>|null} base
 *        A base schema root (or roots) from which to derive, or null.
 * @param {Map<string, Array|StructuredCloneHolder>} schemaJSON
 *        A map of schema URLs and corresponding JSON blobs from which to
 *        populate this root namespace.
 */
export class SchemaRoot extends Namespace {
  constructor(base, schemaJSON) {
    super(null, "", []);

    if (Array.isArray(base)) {
      base = new SchemaRoots(this, base);
    }

    this.root = this;
    this.base = base;
    this.schemaJSON = schemaJSON;
  }

  *getNamespaces(path) {
    let name = path.join(".");

    let ns = this.getNamespace(name, false);
    if (ns) {
      yield ns;
    }

    if (this.base) {
      yield* this.base.getNamespaces(name);
    }
  }

  /**
   * Returns the sub-namespace with the given name. If the given namespace
   * doesn't already exist, attempts to find it in the base SchemaRoot before
   * creating a new empty namespace.
   *
   * @param {string} name
   *        The namespace to retrieve.
   * @param {boolean} [create = true]
   *        If true, an empty namespace should be created if one does not
   *        already exist.
   * @returns {Namespace|null}
   */
  getNamespace(name, create = true) {
    let ns = super.getNamespace(name, false);
    if (ns) {
      return ns;
    }

    ns = this.base && this.base.getNamespace(name, false);
    if (ns) {
      return ns;
    }
    return create && super.getNamespace(name, create);
  }

  /**
   * Like getNamespace, but does not take the base SchemaRoot into account.
   *
   * @param {string} name
   *        The namespace to retrieve.
   * @returns {Namespace}
   */
  getOwnNamespace(name) {
    return super.getNamespace(name);
  }

  parseSchema(schema, path, extraProperties = []) {
    let allowedProperties = DEBUG && new Set(extraProperties);

    if ("choices" in schema) {
      return ChoiceType.parseSchema(this, schema, path, allowedProperties);
    } else if ("$ref" in schema) {
      return RefType.parseSchema(this, schema, path, allowedProperties);
    }

    let type = TYPES[schema.type];

    if (DEBUG) {
      allowedProperties.add("type");

      if (!("type" in schema)) {
        throw new Error(`Unexpected value for type: ${JSON.stringify(schema)}`);
      }

      if (!type) {
        throw new Error(`Unexpected type ${schema.type}`);
      }
    }

    return type.parseSchema(this, schema, path, allowedProperties);
  }

  parseSchemas() {
    for (let [key, schema] of this.schemaJSON.entries()) {
      try {
        if (typeof schema.deserialize === "function") {
          schema = schema.deserialize(globalThis, isParentProcess);

          // If we're in the parent process, we need to keep the
          // StructuredCloneHolder blob around in order to send to future child
          // processes. If we're in a child, we have no further use for it, so
          // just store the deserialized schema data in its place.
          if (!isParentProcess) {
            this.schemaJSON.set(key, schema);
          }
        }

        this.loadSchema(schema);
      } catch (e) {
        Cu.reportError(e);
      }
    }
  }

  loadSchema(json) {
    for (let namespace of json) {
      this.getOwnNamespace(namespace.namespace).addSchema(namespace);
    }
  }

  /**
   * Checks whether a given object has the necessary permissions to
   * expose the given namespace.
   *
   * @param {string} namespace
   *        The top-level namespace to check permissions for.
   * @param {object} wrapperFuncs
   *        Wrapper functions for the given context.
   * @param {Function} wrapperFuncs.hasPermission
   *        A function which, when given a string argument, returns true
   *        if the context has the given permission.
   * @returns {boolean}
   *        True if the context has permission for the given namespace.
   */
  checkPermissions(namespace, wrapperFuncs) {
    let ns = this.getNamespace(namespace);
    if (ns && ns.permissions) {
      return ns.permissions.some(perm => wrapperFuncs.hasPermission(perm));
    }
    return true;
  }

  /**
   * Inject registered extension APIs into `dest`.
   *
   * @param {object} dest The root namespace for the APIs.
   *     This object is usually exposed to extensions as "chrome" or "browser".
   * @param {object} wrapperFuncs An implementation of the InjectionContext
   *     interface, which runs the actual functionality of the generated API.
   */
  inject(dest, wrapperFuncs) {
    let context = new InjectionContext(wrapperFuncs, this);

    this.injectInto(dest, context);
  }

  injectInto(dest, context) {
    // For schema graphs where multiple schema roots have the same base, don't
    // inject it more than once.

    if (!context.injectedRoots.has(this)) {
      context.injectedRoots.add(this);
      if (this.base) {
        this.base.injectInto(dest, context);
      }
      super.injectInto(dest, context);
    }
  }

  /**
   * Normalize `obj` according to the loaded schema for `typeName`.
   *
   * @param {object} obj The object to normalize against the schema.
   * @param {string} typeName The name in the format namespace.propertyname
   * @param {object} context An implementation of Context. Any validation errors
   *     are reported to the given context.
   * @returns {object} The normalized object.
   */
  normalize(obj, typeName, context) {
    let [namespaceName, prop] = typeName.split(".");
    let ns = this.getNamespace(namespaceName);
    let type = ns.get(prop);

    let result = type.normalize(obj, new Context(context));
    if (result.error) {
      return { error: forceString(result.error) };
    }
    return result;
  }
}

Schemas = {
  initialized: false,

  REVOKE: Symbol("@@revoke"),

  // Maps a schema URL to the JSON contained in that schema file. This
  // is useful for sending the JSON across processes.
  schemaJSON: new Map(),

  // A map of schema JSON which should be available in all content processes.
  contentSchemaJSON: new Map(),

  // A map of schema JSON which should only be available to extension processes.
  privilegedSchemaJSON: new Map(),

  _rootSchema: null,

  // A weakmap for the validation Context class instances given an extension
  // context (keyed by the extensin context instance).
  // This is used instead of the InjectionContext for webIDL API validation
  // and normalization (see Schemas.checkParameters).
  paramsValidationContexts: new DefaultWeakMap(
    extContext => new Context(extContext)
  ),

  get rootSchema() {
    if (!this.initialized) {
      this.init();
    }
    if (!this._rootSchema) {
      this._rootSchema = new SchemaRoot(null, this.schemaJSON);
      this._rootSchema.parseSchemas();
    }
    return this._rootSchema;
  },

  getNamespace(name) {
    return this.rootSchema.getNamespace(name);
  },

  init() {
    if (this.initialized) {
      return;
    }
    this.initialized = true;

    if (Services.appinfo.processType == Services.appinfo.PROCESS_TYPE_CONTENT) {
      let addSchemas = schemas => {
        for (let [key, value] of schemas.entries()) {
          this.schemaJSON.set(key, value);
        }
      };

      if (WebExtensionPolicy.isExtensionProcess || DEBUG) {
        addSchemas(Services.cpmm.sharedData.get(KEY_PRIVILEGED_SCHEMAS));
      }

      let schemas = Services.cpmm.sharedData.get(KEY_CONTENT_SCHEMAS);
      if (schemas) {
        addSchemas(schemas);
      }
    }
  },

  _loadCachedSchemasPromise: null,
  loadCachedSchemas() {
    if (!this._loadCachedSchemasPromise) {
      this._loadCachedSchemasPromise = lazy.StartupCache.schemas
        .getAll()
        .then(results => {
          return results;
        });
    }

    return this._loadCachedSchemasPromise;
  },

  addSchema(url, schema, content = false) {
    this.schemaJSON.set(url, schema);

    if (content) {
      this.contentSchemaJSON.set(url, schema);
    } else {
      this.privilegedSchemaJSON.set(url, schema);
    }

    if (this._rootSchema) {
      throw new Error("Schema loaded after root schema populated");
    }
  },

  updateSharedSchemas() {
    let { sharedData } = Services.ppmm;

    sharedData.set(KEY_CONTENT_SCHEMAS, this.contentSchemaJSON);
    sharedData.set(KEY_PRIVILEGED_SCHEMAS, this.privilegedSchemaJSON);
  },

  fetch(url) {
    return readJSONAndBlobbify(url);
  },

  processSchema(json) {
    return blobbify(json);
  },

  async load(url, content = false) {
    if (!isParentProcess) {
      return;
    }

    const startTime = Cu.now();
    let schemaCache = await this.loadCachedSchemas();
    const fromCache = schemaCache.has(url);

    let blob =
      schemaCache.get(url) ||
      (await lazy.StartupCache.schemas.get(url, readJSONAndBlobbify));

    if (!this.schemaJSON.has(url)) {
      this.addSchema(url, blob, content);
    }

    ChromeUtils.addProfilerMarker(
      "ExtensionSchemas",
      { startTime },
      `load ${url}, from cache: ${fromCache}`
    );
  },

  /**
   * Checks whether a given object has the necessary permissions to
   * expose the given namespace.
   *
   * @param {string} namespace
   *        The top-level namespace to check permissions for.
   * @param {object} wrapperFuncs
   *        Wrapper functions for the given context.
   * @param {Function} wrapperFuncs.hasPermission
   *        A function which, when given a string argument, returns true
   *        if the context has the given permission.
   * @returns {boolean}
   *        True if the context has permission for the given namespace.
   */
  checkPermissions(namespace, wrapperFuncs) {
    return this.rootSchema.checkPermissions(namespace, wrapperFuncs);
  },

  /**
   * Returns a sorted array of permission names for the given permission types.
   *
   * @param {Array} types An array of permission types, defaults to all permissions.
   * @returns {Array} sorted array of permission names
   */
  getPermissionNames(
    types = [
      "Permission",
      "OptionalPermission",
      "PermissionNoPrompt",
      "OptionalPermissionNoPrompt",
      "PermissionPrivileged",
    ]
  ) {
    const ns = this.getNamespace("manifest");
    let names = [];
    for (let typeName of types) {
      for (let choice of ns
        .get(typeName)
        .choices.filter(choice => choice.enumeration)) {
        names = names.concat(choice.enumeration);
      }
    }
    return names.sort();
  },

  exportLazyGetter,

  /**
   * Inject registered extension APIs into `dest`.
   *
   * @param {object} dest The root namespace for the APIs.
   *     This object is usually exposed to extensions as "chrome" or "browser".
   * @param {object} wrapperFuncs An implementation of the InjectionContext
   *     interface, which runs the actual functionality of the generated API.
   */
  inject(dest, wrapperFuncs) {
    this.rootSchema.inject(dest, wrapperFuncs);
  },

  /**
   * Normalize `obj` according to the loaded schema for `typeName`.
   *
   * @param {object} obj The object to normalize against the schema.
   * @param {string} typeName The name in the format namespace.propertyname
   * @param {object} context An implementation of Context. Any validation errors
   *     are reported to the given context.
   * @returns {object} The normalized object.
   */
  normalize(obj, typeName, context) {
    return this.rootSchema.normalize(obj, typeName, context);
  },

  /**
   * Validate and normalize the arguments for an API request originated
   * from the webIDL API bindings.
   *
   * This provides for calls originating through WebIDL the parameters
   * validation and normalization guarantees that the ext-APINAMESPACE.js
   * scripts expects (what InjectionContext does for the regular bindings).
   *
   * @param {object}                   extContext
   * @param {mozIExtensionAPIRequest } apiRequest
   *
   * @returns {Array<any>} Normalized arguments array.
   */
  checkWebIDLRequestParameters(extContext, apiRequest) {
    const getSchemaForProperty = (schemaObj, propName, schemaPath) => {
      if (schemaObj instanceof Namespace) {
        return schemaObj?.get(propName);
      } else if (schemaObj instanceof SubModuleProperty) {
        for (const fun of schemaObj.targetType.functions) {
          if (fun.name === propName) {
            return fun;
          }
        }

        for (const fun of schemaObj.targetType.events) {
          if (fun.name === propName) {
            return fun;
          }
        }
      } else if (schemaObj instanceof Event) {
        return schemaObj;
      }

      const schemaPathType = schemaObj?.constructor.name;
      throw new Error(
        `API Schema for "${propName}" not found in ${schemaPath} (${schemaPath} type is ${schemaPathType})`
      );
    };
    const { requestType, apiNamespace, apiName } = apiRequest;

    let [ns, ...rest] = (
      ["addListener", "removeListener"].includes(requestType)
        ? `${apiNamespace}.${apiName}.${requestType}`
        : `${apiNamespace}.${apiName}`
    ).split(".");
    let apiSchema = this.getNamespace(ns);

    // Keep track of the current schema path, populated while navigating the nested API schema
    // data and then used to include the full path to the API schema that is hitting unexpected
    // errors due to schema data not found or an unexpected schema type.
    let schemaPath = [ns];

    while (rest.length) {
      // Nested property as namespace (e.g. used for proxy.settings requests).
      if (!apiSchema) {
        throw new Error(`API Schema not found for ${schemaPath.join(".")}`);
      }

      let [propName, ...newRest] = rest;
      rest = newRest;

      apiSchema = getSchemaForProperty(
        apiSchema,
        propName,
        schemaPath.join(".")
      );
      schemaPath.push(propName);
    }

    if (!apiSchema) {
      throw new Error(`API Schema not found for ${schemaPath.join(".")}`);
    }

    if (!apiSchema.checkParameters) {
      throw new Error(
        `Unexpected API Schema type for ${schemaPath.join(
          "."
        )} (${schemaPath.join(".")} type is ${apiSchema.constructor.name})`
      );
    }

    return apiSchema.checkParameters(
      apiRequest.args,
      this.paramsValidationContexts.get(extContext)
    );
  },
};