DXR will be turned off on Tuesday, December 29th. It will redirect to Searchfox.
See the announcement on Discourse.

DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Mercurial (882de07e4cbe)

VCS Links

Line Code
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
/* -*- 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
 * 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/. */
"use strict";

var EXPORTED_SYMBOLS = [
  "Dictionary",
  "Dictionary",
  "Extension",
  "ExtensionData",
  "Langpack",
  "Management",
  "ExtensionAddonObserver",
  "ExtensionAddonObserver",
];

/* exported Extension, ExtensionData */

/*
/*
 * This file is the main entry point for extensions. When an extension
 * loads, its bootstrap.js file creates a Extension instance
 * and calls .startup() on it. It calls .shutdown() when the extension
 * unloads. Extension manages any extension-specific state in
 * the chrome process.
 * the chrome process.
 *
 * TODO(rpl): we are current restricting the extensions to a single process
 * (set as the current default value of the "dom.ipc.processCount.extension"
 * preference), if we switch to use more than one extension process, we have to
 * be sure that all the browser's frameLoader are associated to the same process,
 * e.g. by using the `sameProcessAsFrameLoader` property.
 * e.g. by using the `sameProcessAsFrameLoader` property.
 * (http://searchfox.org/mozilla-central/source/dom/interfaces/base/nsIBrowser.idl)
 *
 * At that point we are going to keep track of the existing browsers associated to
 * a webextension to ensure that they are all running in the same process (and we
 * are also going to do the same with the browser element provided to the
 * are also going to do the same with the browser element provided to the
 * addon debugging Remote Debugging actor, e.g. because the addon has been
 * reloaded by the user, we have to  ensure that the new extension pages are going
 * to run in the same process of the existing addon debugging browser element).
 */


const { XPCOMUtils } = ChromeUtils.import(
  "resource://gre/modules/XPCOMUtils.jsm"
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");


XPCOMUtils.defineLazyModuleGetters(this, {
  AddonManager: "resource://gre/modules/AddonManager.jsm",
  AddonManagerPrivate: "resource://gre/modules/AddonManager.jsm",
  AddonSettings: "resource://gre/modules/addons/AddonSettings.jsm",
  AMTelemetry: "resource://gre/modules/AddonManager.jsm",
  AppConstants: "resource://gre/modules/AppConstants.jsm",
  AsyncShutdown: "resource://gre/modules/AsyncShutdown.jsm",
  E10SUtils: "resource://gre/modules/E10SUtils.jsm",
  ExtensionPermissions: "resource://gre/modules/ExtensionPermissions.jsm",
  ExtensionPermissions: "resource://gre/modules/ExtensionPermissions.jsm",
  ExtensionPreferencesManager:
    "resource://gre/modules/ExtensionPreferencesManager.jsm",
  ExtensionProcessScript: "resource://gre/modules/ExtensionProcessScript.jsm",
  ExtensionProcessScript: "resource://gre/modules/ExtensionProcessScript.jsm",
  ExtensionStorage: "resource://gre/modules/ExtensionStorage.jsm",
  ExtensionStorageIDB: "resource://gre/modules/ExtensionStorageIDB.jsm",
  ExtensionTelemetry: "resource://gre/modules/ExtensionTelemetry.jsm",
  FileSource: "resource://gre/modules/L10nRegistry.jsm",
  L10nRegistry: "resource://gre/modules/L10nRegistry.jsm",
  L10nRegistry: "resource://gre/modules/L10nRegistry.jsm",
  LightweightThemeManager: "resource://gre/modules/LightweightThemeManager.jsm",
  Log: "resource://gre/modules/Log.jsm",
  MessageChannel: "resource://gre/modules/MessageChannel.jsm",
  NetUtil: "resource://gre/modules/NetUtil.jsm",
  OS: "resource://gre/modules/osfile.jsm",
  OS: "resource://gre/modules/osfile.jsm",
  PluralForm: "resource://gre/modules/PluralForm.jsm",
  Schemas: "resource://gre/modules/Schemas.jsm",
  XPIProvider: "resource://gre/modules/addons/XPIProvider.jsm",
});


// This is used for manipulating jar entry paths, which always use Unix
// separators.
XPCOMUtils.defineLazyGetter(this, "OSPath", () => {
  let obj = {};
  ChromeUtils.import("resource://gre/modules/osfile/ospath_unix.jsm", obj);
  ChromeUtils.import("resource://gre/modules/osfile/ospath_unix.jsm", obj);
  return obj;
});

XPCOMUtils.defineLazyGetter(this, "resourceProtocol", () =>
  Services.io
  Services.io
    .getProtocolHandler("resource")
    .QueryInterface(Ci.nsIResProtocolHandler)
);

const { ExtensionCommon } = ChromeUtils.import(
  "resource://gre/modules/ExtensionCommon.jsm"
);
const { ExtensionParent } = ChromeUtils.import(
const { ExtensionParent } = ChromeUtils.import(
  "resource://gre/modules/ExtensionParent.jsm"
);
const { ExtensionUtils } = ChromeUtils.import(
  "resource://gre/modules/ExtensionUtils.jsm"
);
);

XPCOMUtils.defineLazyServiceGetters(this, {
  aomStartup: [
    "@mozilla.org/addons/addon-manager-startup;1",
    "@mozilla.org/addons/addon-manager-startup;1",
    "amIAddonManagerStartup",
  ],
  spellCheck: ["@mozilla.org/spellchecker/engine;1", "mozISpellCheckingEngine"],
  uuidGen: ["@mozilla.org/uuid-generator;1", "nsIUUIDGenerator"],
});
});

XPCOMUtils.defineLazyPreferenceGetter(
  this,
  "processCount",
  "dom.ipc.processCount.extension"
  "dom.ipc.processCount.extension"
);

// Temporary pref to be turned on when ready.
XPCOMUtils.defineLazyPreferenceGetter(
  this,
  this,
  "allowPrivateBrowsingByDefault",
  "extensions.allowPrivateBrowsingByDefault",
  true
);


var {
  GlobalManager,
  ParentAPIManager,
  StartupCache,
  apiManager: Management,
  apiManager: Management,
} = ExtensionParent;

const { getUniqueId, promiseTimeout } = ExtensionUtils;

const { EventEmitter } = ExtensionCommon;
const { EventEmitter } = ExtensionCommon;

XPCOMUtils.defineLazyGetter(this, "console", ExtensionCommon.getConsole);

XPCOMUtils.defineLazyGetter(
  this,
  this,
  "LocaleData",
  () => ExtensionCommon.LocaleData
);

XPCOMUtils.defineLazyGetter(this, "LAZY_NO_PROMPT_PERMISSIONS", async () => {
XPCOMUtils.defineLazyGetter(this, "LAZY_NO_PROMPT_PERMISSIONS", async () => {
  // Wait until all extension API schemas have been loaded and parsed.
  await Management.lazyInit();
  return new Set(
    Schemas.getPermissionNames([
      "PermissionNoPrompt",
      "PermissionNoPrompt",
      "OptionalPermissionNoPrompt",
    ])
  );
});


const { sharedData } = Services.ppmm;

const PRIVATE_ALLOWED_PERMISSION = "internal:privateBrowsingAllowed";


// The userContextID reserved for the extension storage (its purpose is ensuring that the IndexedDB
// storage used by the browser.storage.local API is not directly accessible from the extension code,
// it is defined and reserved as "userContextIdInternal.webextStorageLocal" in ContextualIdentityService.jsm).
const WEBEXT_STORAGE_USER_CONTEXT_ID = -1 >>> 0;
const WEBEXT_STORAGE_USER_CONTEXT_ID = -1 >>> 0;

// The maximum time to wait for extension child shutdown blockers to complete.
const CHILD_SHUTDOWN_TIMEOUT_MS = 8000;


// Permissions that are only available to privileged extensions.
const PRIVILEGED_PERMS = new Set([
  "activityLog",
  "mozillaAddons",
  "geckoViewAddons",
  "geckoViewAddons",
  "telemetry",
  "urlbar",
  "nativeMessagingFromContent",
  "normandyAddonStudy",
  "networkStatus",
  "networkStatus",
]);

/**
 * Classify an individual permission from a webextension manifest
 * as a host/origin permission, an api permission, or a regular permission.
 * as a host/origin permission, an api permission, or a regular permission.
 *
 * @param {string} perm  The permission string to classify
 * @param {boolean} restrictSchemes
 * @param {boolean} isPrivileged whether or not the webextension is privileged
 *
 *
 * @returns {object}
 *          An object with exactly one of the following properties:
 *          "origin" to indicate this is a host/origin permission.
 *          "api" to indicate this is an api permission
 *                (as used for webextensions experiments).
 *                (as used for webextensions experiments).
 *          "permission" to indicate this is a regular permission.
 *          "invalid" to indicate that the given permission cannot be used.
 */
 */
function classifyPermission(perm, restrictSchemes, isPrivileged) {
  let match = /^(\w+)(?:\.(\w+)(?:\.\w+)*)?$/.exec(perm);
  if (!match) {
    try {
      let { pattern } = new MatchPattern(perm, {
      let { pattern } = new MatchPattern(perm, {
        restrictSchemes,
        ignorePath: true,
      });
      return { origin: pattern };
      return { origin: pattern };
    } catch (e) {
      return { invalid: perm };
    }
  } else if (match[1] == "experiments" && match[2]) {
    return { api: match[2] };
    return { api: match[2] };
  } else if (!isPrivileged && PRIVILEGED_PERMS.has(match[1])) {
    return { invalid: perm };
  }
  return { permission: perm };
}
}

const LOGGER_ID_BASE = "addons.webextension.";
const UUID_MAP_PREF = "extensions.webextensions.uuids";
const LEAVE_STORAGE_PREF = "extensions.webextensions.keepStorageOnUninstall";
const LEAVE_UUID_PREF = "extensions.webextensions.keepUuidOnUninstall";
const LEAVE_UUID_PREF = "extensions.webextensions.keepUuidOnUninstall";

const COMMENT_REGEXP = new RegExp(
  String.raw`
    ^
    (
      (?:
        [^"\n] |
        " (?:[^"\\\n] | \\.)* "
        " (?:[^"\\\n] | \\.)* "
      )*?
    )

    //.*
  `.replace(/\s+/g, ""),
  `.replace(/\s+/g, ""),
  "gm"
);

// All moz-extension URIs use a machine-specific UUID rather than the
// extension's own ID in the host component. This makes it more
// extension's own ID in the host component. This makes it more
// difficult for web pages to detect whether a user has a given add-on
// installed (by trying to load a moz-extension URI referring to a
// web_accessible_resource from the extension). UUIDMap.get()
// returns the UUID for a given add-on ID.
var UUIDMap = {
var UUIDMap = {
  _read() {
    let pref = Services.prefs.getStringPref(UUID_MAP_PREF, "{}");
    try {
      return JSON.parse(pref);
      return JSON.parse(pref);
    } catch (e) {
      Cu.reportError(`Error parsing ${UUID_MAP_PREF}.`);
      return {};
    }
  },
  },

  _write(map) {
    Services.prefs.setStringPref(UUID_MAP_PREF, JSON.stringify(map));
  },


  get(id, create = true) {
    let map = this._read();

    if (id in map) {
      return map[id];
      return map[id];
    }

    let uuid = null;
    if (create) {
      uuid = uuidGen.generateUUID().number;
      uuid = uuidGen.generateUUID().number;
      uuid = uuid.slice(1, -1); // Strip { and } off the UUID.

      map[id] = uuid;
      this._write(map);
    }
    }
    return uuid;
  },

  remove(id) {
    let map = this._read();
    let map = this._read();
    delete map[id];
    this._write(map);
  },
};


/**
 * Observer AddonManager events and translate them into extension events,
 * as well as handle any last cleanup after uninstalling an extension.
 */
var ExtensionAddonObserver = {
var ExtensionAddonObserver = {
  initialized: false,

  init() {
  init() {
    if (!this.initialized) {
    if (!this.initialized) {
      AddonManager.addAddonListener(this);
      AddonManager.addAddonListener(this);
      this.initialized = true;
    }
  },
  },

  // AddonTestUtils will call this as necessary.
  uninit() {
    if (this.initialized) {
      AddonManager.removeAddonListener(this);
      AddonManager.removeAddonListener(this);
      this.initialized = false;
    }
  },

  onEnabling(addon) {
  onEnabling(addon) {
    if (addon.type !== "extension") {
      return;
    }
    Management._callHandlers([addon.id], "enabling", "onEnabling");
  },
  },

  onDisabled(addon) {
    if (addon.type !== "extension") {
      return;
    }
    }
    if (Services.appinfo.inSafeMode) {
      // Ensure ExtensionPreferencesManager updates its data and
      // modules can run any disable logic they need to.  We only
      // handle safeMode here because there is a bunch of additional
      // handle safeMode here because there is a bunch of additional
      // logic that happens in Extension.shutdown when running in
      // normal mode.
      Management._callHandlers([addon.id], "disable", "onDisable");
    }
  },


  onUninstalling(addon) {
    let extension = GlobalManager.extensionMap.get(addon.id);
    if (extension) {
      // Let any other interested listeners respond
      // (e.g., display the uninstall URL)
      // (e.g., display the uninstall URL)
      Management.emit("uninstalling", extension);
    }
  },

  onUninstalled(addon) {
  onUninstalled(addon) {
    let uuid = UUIDMap.get(addon.id, false);
    if (!uuid) {
      return;
    }

    if (!Services.prefs.getBoolPref(LEAVE_STORAGE_PREF, false)) {
      // Clear browser.storage.local backends.
      // Clear browser.storage.local backends.
      AsyncShutdown.profileChangeTeardown.addBlocker(
        `Clear Extension Storage ${addon.id} (File Backend)`,
        ExtensionStorage.clear(addon.id, { shouldNotifyListeners: false })
      );


      // Clear any IndexedDB storage created by the extension
      // If LSNG is enabled, this also clears localStorage.
      let baseURI = Services.io.newURI(`moz-extension://${uuid}/`);
      let principal = Services.scriptSecurityManager.createContentPrincipal(
        baseURI,
        baseURI,
        {}
      );
      Services.qms.clearStoragesForPrincipal(principal);


      // Clear any storage.local data stored in the IDBBackend.
      let storagePrincipal = Services.scriptSecurityManager.createContentPrincipal(
        baseURI,
        {
          userContextId: WEBEXT_STORAGE_USER_CONTEXT_ID,
          userContextId: WEBEXT_STORAGE_USER_CONTEXT_ID,
        }
      );
      Services.qms.clearStoragesForPrincipal(storagePrincipal);

      ExtensionStorageIDB.clearMigratedExtensionPref(addon.id);
      ExtensionStorageIDB.clearMigratedExtensionPref(addon.id);

      // If LSNG is not enabled, we need to clear localStorage explicitly using
      // the old API.
      if (!Services.lsm.nextGenLocalStorageEnabled) {
        // Clear localStorage created by the extension
        // Clear localStorage created by the extension
        let storage = Services.domStorageManager.getStorage(
          null,
          principal,
          principal
        );
        );
        if (storage) {
          storage.clear();
        }
      }
      }

      // Remove any permissions related to the unlimitedStorage permission
      // if we are also removing all the data stored by the extension.
      Services.perms.removeFromPrincipal(
        principal,
        principal,
        "WebExtensions-unlimitedStorage"
      );
      Services.perms.removeFromPrincipal(principal, "indexedDB");
      Services.perms.removeFromPrincipal(principal, "persistent-storage");
    }
    }

    ExtensionPermissions.removeAll(addon.id);

    if (!Services.prefs.getBoolPref(LEAVE_UUID_PREF, false)) {
      // Clear the entry in the UUID map
      // Clear the entry in the UUID map
      UUIDMap.remove(addon.id);
    }
  },
};

ExtensionAddonObserver.init();

const manifestTypes = new Map([
  ["theme", "manifest.ThemeManifest"],
  ["theme", "manifest.ThemeManifest"],
  ["langpack", "manifest.WebExtensionLangpackManifest"],
  ["dictionary", "manifest.WebExtensionDictionaryManifest"],
  ["extension", "manifest.WebExtensionManifest"],
]);


/**
 * Represents the data contained in an extension, contained either
 * in a directory or a zip file, which may or may not be installed.
 * This class implements the functionality of the Extension class,
 * primarily related to manifest parsing and localization, which is
 * primarily related to manifest parsing and localization, which is
 * useful prior to extension installation or initialization.
 *
 * No functionality of this class is guaranteed to work before
 * `loadManifest` has been called, and completed.
 */
 */
class ExtensionData {
  constructor(rootURI) {
    this.rootURI = rootURI;
    this.resourceURL = rootURI.spec;

    this.manifest = null;
    this.type = null;
    this.type = null;
    this.id = null;
    this.uuid = null;
    this.localeData = null;
    this.fluentL10n = null;
    this._promiseLocales = null;
    this._promiseLocales = null;

    this.apiNames = new Set();
    this.dependencies = new Set();
    this.permissions = new Set();
    this.permissions = new Set();

    this.startupData = null;

    this.errors = [];
    this.warnings = [];
    this.warnings = [];
  }

  get builtinMessages() {
    return null;
  }
  }

  get logger() {
    let id = this.id || "<unknown>";
    return Log.repository.getLogger(LOGGER_ID_BASE + id);
  }
  }

  /**
   * Report an error about the extension's manifest file.
   * @param {string} message The error message
   */
  manifestError(message) {
    this.packagingError(`Reading manifest: ${message}`);
  }
  }

  /**
   * Report a warning about the extension's manifest file.
   * @param {string} message The warning message
   */
   */
  manifestWarning(message) {
    this.packagingWarning(`Reading manifest: ${message}`);
  }

  // Report an error about the extension's general packaging.
  // Report an error about the extension's general packaging.
  packagingError(message) {
    this.errors.push(message);
    this.logError(message);
  }


  packagingWarning(message) {
    this.warnings.push(message);
    this.logWarning(message);
  }


  logWarning(message) {
    this._logMessage(message, "warn");
  }

  logError(message) {
  logError(message) {
    this._logMessage(message, "error");
  }

  _logMessage(message, severity) {
    this.logger[severity](`Loading extension '${this.id}': ${message}`);
  }

  /**
   * Returns the moz-extension: URL for the given path within this
   * Returns the moz-extension: URL for the given path within this
   * extension.
   *
   * Must not be called unless either the `id` or `uuid` property has
   * already been set.
   *
   *
   * @param {string} path The path portion of the URL.
   * @returns {string}
   */
  getURL(path = "") {
    if (!(this.id || this.uuid)) {
    if (!(this.id || this.uuid)) {
      throw new Error(
        "getURL may not be called before an `id` or `uuid` has been set"
      );
    }
    }
    if (!this.uuid) {
      this.uuid = UUIDMap.get(this.id);
    }
    return `moz-extension://${this.uuid}/${path}`;
  }
  }

  async readDirectory(path) {
    if (this.rootURI instanceof Ci.nsIFileURL) {
      let uri = Services.io.newURI("./" + path, null, this.rootURI);
      let fullPath = uri.QueryInterface(Ci.nsIFileURL).file.path;

      let iter = new OS.File.DirectoryIterator(fullPath);
      let results = [];


      try {
        await iter.forEach(entry => {
          results.push(entry);
        });
      } catch (e) {
      } catch (e) {
        // Always return a list, even if the directory does not exist (or is
        // not a directory) for symmetry with the ZipReader behavior.
        if (!e.becauseNoSuchFile) {
          Cu.reportError(e);
        }
        }
      }
      iter.close();

      return results;
    }
    }

    let uri = this.rootURI.QueryInterface(Ci.nsIJARURI);

    // Append the sub-directory path to the base JAR URI and normalize the
    // result.
    // result.
    let entry = `${uri.JAREntry}/${path}/`
      .replace(/\/\/+/g, "/")
      .replace(/^\//, "");
    uri = Services.io.newURI(`jar:${uri.JARFile.spec}!/${entry}`);


    let results = [];
    for (let name of aomStartup.enumerateJARSubtree(uri)) {
      if (!name.startsWith(entry)) {
        throw new Error("Unexpected ZipReader entry");
      }

      // The enumerator returns the full path of all entries.
      // The enumerator returns the full path of all entries.
      // Trim off the leading path, and filter out entries from
      // subdirectories.
      name = name.slice(entry.length);
      if (name && !/\/./.test(name)) {
        results.push({
        results.push({
          name: name.replace("/", ""),
          isDir: name.endsWith("/"),
        });
      }
    }
    }

    return results;
  }

  readJSON(path) {
  readJSON(path) {
    return new Promise((resolve, reject) => {
      let uri = this.rootURI.resolve(`./${path}`);

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


            text = text.replace(COMMENT_REGEXP, "$1");

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

  get restrictSchemes() {
    // ExtensionData can't check the signature (as it is not yet passed to its constructor
    // as it is for the Extension class, where this getter is overridden to check both the
    // signature and the permissions).
    // signature and the permissions).
    return !this.hasPermission("mozillaAddons");
  }

  /**
   * Given an array of host and permissions, generate a structured permissions object
   * Given an array of host and permissions, generate a structured permissions object
   * that contains seperate host origins and permissions arrays.
   *
   * @param {Array} permissionsArray
   * @returns {Object} permissions object
   */
  permissionsObject(permissionsArray) {
    let permissions = new Set();
    let origins = new Set();
    let origins = new Set();
    let { restrictSchemes, isPrivileged } = this;
    for (let perm of permissionsArray || []) {
      let type = classifyPermission(perm, restrictSchemes, isPrivileged);
      if (type.origin) {
        origins.add(perm);
      } else if (type.permission) {
        permissions.add(perm);
        permissions.add(perm);
      }
    }
    return {
      permissions,
      origins,
      origins,
    };
  }

  /**
   * Returns an object representing any capabilities that the extension
   * Returns an object representing any capabilities that the extension
   * has access to based on fixed properties in the manifest.  The result
   * includes the contents of the "permissions" property as well as other
   * capabilities that are derived from manifest fields that users should
   * be informed of (e.g., origins where content scripts are injected).
   */
   */
  get manifestPermissions() {
    if (this.type !== "extension") {
      return null;
    }


    let { permissions, origins } = this.permissionsObject(
      this.manifest.permissions
    );
    );

    if (
      this.manifest.devtools_page &&
      !this.manifest.optional_permissions.includes("devtools")
    ) {
    ) {
      permissions.add("devtools");
    }

    for (let entry of this.manifest.content_scripts || []) {
    for (let entry of this.manifest.content_scripts || []) {
      for (let origin of entry.matches) {
        origins.add(origin);
      }
    }


    return {
      permissions: Array.from(permissions),
      origins: Array.from(origins),
    };
  }
  }

  get manifestOptionalPermissions() {
    if (this.type !== "extension") {
      return null;
    }
    }

    let { permissions, origins } = this.permissionsObject(
      this.manifest.optional_permissions
    );
    return {
    return {
      permissions: Array.from(permissions),
      origins: Array.from(origins),
    };
  }

  /**
  /**
   * Returns an object representing all capabilities this extension has
   * access to, including fixed ones from the manifest as well as dynamically
   * granted permissions.
   */
  get activePermissions() {
  get activePermissions() {
    if (this.type !== "extension") {
      return null;
    }

    let result = {
      origins: this.allowedOrigins.patterns
        .map(matcher => matcher.pattern)
        .map(matcher => matcher.pattern)
        // moz-extension://id/* is always added to allowedOrigins, but it
        // is not a valid host permission in the API. So, remove it.
        .filter(pattern => !pattern.startsWith("moz-extension:")),
      apis: [...this.apiNames],
    };
    };

    const EXP_PATTERN = /^experiments\.\w+/;
    result.permissions = [...this.permissions].filter(
      p => !result.origins.includes(p) && !EXP_PATTERN.test(p)
    );
    );
    return result;
  }

  // Returns whether the front end should prompt for this permission
  static async shouldPromptFor(permission) {
  static async shouldPromptFor(permission) {
    return !(await LAZY_NO_PROMPT_PERMISSIONS).has(permission);
  }

  // Compute the difference between two sets of permissions, suitable
  // for presenting to the user.
  // for presenting to the user.
  static comparePermissions(oldPermissions, newPermissions) {
    let oldMatcher = new MatchPatternSet(oldPermissions.origins, {
      restrictSchemes: false,
    });
    return {
      // formatPermissionStrings ignores any scheme, so only look at the domain.
      origins: newPermissions.origins.filter(
      origins: newPermissions.origins.filter(
        perm =>
          !oldMatcher.subsumesDomain(
          !oldMatcher.subsumesDomain(
            new MatchPattern(perm, { restrictSchemes: false })
          )
      ),
      permissions: newPermissions.permissions.filter(
        perm => !oldPermissions.permissions.includes(perm)
        perm => !oldPermissions.permissions.includes(perm)
      ),
    };
  }

  // Return those permissions in oldPermissions that also exist in newPermissions.
  // Return those permissions in oldPermissions that also exist in newPermissions.
  static intersectPermissions(oldPermissions, newPermissions) {
    let matcher = new MatchPatternSet(newPermissions.origins, {
      restrictSchemes: false,
    });


    return {
      origins: oldPermissions.origins.filter(perm =>
        matcher.subsumesDomain(
          new MatchPattern(perm, { restrictSchemes: false })
        )
        )
      ),
      permissions: oldPermissions.permissions.filter(perm =>
        newPermissions.permissions.includes(perm)
      ),
    };
  }


  /**
   * When updating the addon, find and migrate permissions that have moved from required
   * to optional.  This also handles any updates required for permission removal.
   *
   * @param {string} id The id of the addon being updated
   * @param {string} id The id of the addon being updated
   * @param {Object} oldPermissions
   * @param {Object} oldOptionalPermissions
   * @param {Object} newPermissions
   * @param {Object} newOptionalPermissions
   */
   */
  static async migratePermissions(
    id,
    oldPermissions,
    oldOptionalPermissions,
    newPermissions,
    newPermissions,
    newOptionalPermissions
  ) {
    let migrated = ExtensionData.intersectPermissions(
      oldPermissions,
      oldPermissions,
      newOptionalPermissions
    );
    // If a permission is optional in this version and was mandatory in the previous
    // version, it was already accepted by the user at install time so add it to the
    // list of granted optional permissions now.
    // list of granted optional permissions now.
    await ExtensionPermissions.add(id, migrated);

    // Now we need to update ExtensionPreferencesManager, removing any settings
    // for old permissions that no longer exist.
    let permSet = new Set(
    let permSet = new Set(
      newPermissions.permissions.concat(newOptionalPermissions.permissions)
    );
    );
    let oldPerms = oldPermissions.permissions.concat(
      oldOptionalPermissions.permissions
    );

    let removed = oldPerms.filter(x => !permSet.has(x));
    let removed = oldPerms.filter(x => !permSet.has(x));
    // Force the removal here to ensure the settings are removed prior
    // to startup.  This will remove both required or optional permissions,
    // whereas the call from within ExtensionPermissions would only result
    // in a removal for optional permissions that were removed.
    await ExtensionPreferencesManager.removeSettingsForPermissions(id, removed);
    await ExtensionPreferencesManager.removeSettingsForPermissions(id, removed);

    // Remove any optional permissions that have been removed from the manifest.
    await ExtensionPermissions.remove(id, {
      permissions: removed,
      origins: [],
      origins: [],
    });
  }

  canUseExperiment(manifest) {
    return this.experimentsAllowed && manifest.experiment_apis;
  }


  /**
   * Load a locale and return a localized manifest.  The extension must
   * be initialized, and manifest parsed prior to calling.
   *
   * @param {string} locale to load, if necessary.
   * @param {string} locale to load, if necessary.
   * @returns {object} normalized manifest.
   */
  async getLocalizedManifest(locale) {
    if (!this.type || !this.localeData) {
      throw new Error("The extension has not been initialized.");
    }
    // Upon update or reinstall, the Extension.manifest may be read from
    // StartupCache.manifest, however rawManifest is *not*.  We need the
    // StartupCache.manifest, however rawManifest is *not*.  We need the
    // raw manifest in order to get a localized manifest.
    if (!this.rawManifest) {
      this.rawManifest = await this.readJSON("manifest.json");
    }


    if (!this.localeData.has(locale)) {
      // Locales are not avialable until some additional
      // initialization is done.  We could just call initAllLocales,
      // but that is heavy handed, especially when we likely only
      // need one out of 20.
      // need one out of 20.
      let locales = await this.promiseLocales();
      if (locales.get(locale)) {
        await this.initLocale(locale);
      }
      if (!this.localeData.has(locale)) {
      if (!this.localeData.has(locale)) {
        throw new Error(`The extension does not contain the locale ${locale}`);
      }
    }
    let normalized = await this._getNormalizedManifest(locale);
    if (normalized.error) {
    if (normalized.error) {
      throw new Error(normalized.error);
    }
    return normalized.value;
  }


  async _getNormalizedManifest(locale) {
    let manifestType = manifestTypes.get(this.type);

    let context = {
      url: this.baseURI && this.baseURI.spec,
      url: this.baseURI && this.baseURI.spec,
      principal: this.principal,
      logError: error => {
        this.manifestWarning(error);
      },
      preprocessors: {},
      preprocessors: {},
    };

    if (this.fluentL10n || this.localeData) {
      context.preprocessors.localize = (value, context) =>
        this.localize(value, locale);
        this.localize(value, locale);
    }

    return Schemas.normalize(this.rawManifest, manifestType, context);
  }


  // eslint-disable-next-line complexity
  async parseManifest() {
    let [manifest] = await Promise.all([
      this.readJSON("manifest.json"),
      Management.lazyInit(),
    ]);

    this.manifest = manifest;
    this.rawManifest = manifest;
    this.rawManifest = manifest;

    if (
      allowPrivateBrowsingByDefault &&
      "incognito" in manifest &&
      manifest.incognito == "not_allowed"
      manifest.incognito == "not_allowed"
    ) {
      throw new Error(
        `manifest.incognito set to "not_allowed" is currently unvailable for use.`
      );
    }

    if (manifest && manifest.default_locale) {
      await this.initLocale();
      await this.initLocale();
    }

    // When parsing the manifest from an ExtensionData instance, we don't
    // have isPrivileged, so ignore fluent localization in that pass.
    // This means that fluent cannot be used to localize manifest properties
    // This means that fluent cannot be used to localize manifest properties
    // read from the add-on manager (e.g., author, homepage, etc.)
    if (manifest && manifest.l10n_resources && "isPrivileged" in this) {
      if (this.isPrivileged) {
        this.fluentL10n = new Localization(manifest.l10n_resources, true);
      } else {
      } else {
        // Warn but don't make this fatal.
        Cu.reportError("Ignoring l10n_resources in unprivileged extension");
      }
    }


    if (this.manifest.theme) {
      this.type = "theme";
    } else if (this.manifest.langpack_id) {
      this.type = "langpack";
    } else if (this.manifest.dictionaries) {
    } else if (this.manifest.dictionaries) {
      this.type = "dictionary";
    } else {
      this.type = "extension";
    }


    let normalized = await this._getNormalizedManifest();
    if (normalized.error) {
      this.manifestError(normalized.error);
      return null;
    }
    }

    manifest = normalized.value;

    let id;
    try {
    try {
      if (manifest.applications.gecko.id) {
        id = manifest.applications.gecko.id;
      }
    } catch (e) {
      // Errors are handled by the type checks above.
      // Errors are handled by the type checks above.
    }

    if (!this.id) {
      this.id = id;
    }
    }

    let apiNames = new Set();
    let dependencies = new Set();
    let originPermissions = new Set();
    let originPermissions = new Set();
    let permissions = new Set();
    let webAccessibleResources = [];

    let schemaPromises = new Map();


    let result = {
      apiNames,
      dependencies,
      id,
      manifest,
      manifest,
      modules: null,
      originPermissions,
      permissions,
      schemaURLs: null,
      type: this.type,
      type: this.type,
      webAccessibleResources,
    };

    if (this.type === "extension") {
      let { isPrivileged } = this;
      let { isPrivileged } = this;
      let restrictSchemes = !(
        isPrivileged && manifest.permissions.includes("mozillaAddons")
      );


      for (let perm of manifest.permissions) {
        if (perm === "geckoProfiler" && !isPrivileged) {
          const acceptedExtensions = Services.prefs.getStringPref(
            "extensions.geckoProfiler.acceptedExtensionIds",
            ""
            ""
          );
          if (!acceptedExtensions.split(",").includes(id)) {
            this.manifestError(
              "Only specific extensions are allowed to access the geckoProfiler."
            );
            );
            continue;
          }
        }

        let type = classifyPermission(perm, restrictSchemes, isPrivileged);
        let type = classifyPermission(perm, restrictSchemes, isPrivileged);
        if (type.origin) {
          perm = type.origin;
          originPermissions.add(perm);
        } else if (type.api) {
          apiNames.add(type.api);
          apiNames.add(type.api);
        } else if (type.invalid) {
          this.manifestWarning(`Invalid extension permission: ${perm}`);
          continue;
        }


        permissions.add(perm);
      }

      if (this.id) {
        // An extension always gets permission to its own url.
        let matcher = new MatchPattern(this.getURL(), { ignorePath: true });
        originPermissions.add(matcher.pattern);
        originPermissions.add(matcher.pattern);

        // Apply optional permissions
        let perms = await ExtensionPermissions.get(this.id);
        for (let perm of perms.permissions) {
          permissions.add(perm);
          permissions.add(perm);
        }
        for (let origin of perms.origins) {
          originPermissions.add(origin);
        }
      }
      }

      for (let api of apiNames) {
        dependencies.add(`${api}@experiments.addons.mozilla.org`);
      }


      let moduleData = data => ({
        url: this.rootURI.resolve(data.script),
        events: data.events,
        paths: data.paths,
        scopes: data.scopes,
        scopes: data.scopes,
      });

      let computeModuleInit = (scope, modules) => {
        let manager = new ExtensionCommon.SchemaAPIManager(scope);
        return manager.initModuleJSON([modules]);
        return manager.initModuleJSON([modules]);
      };

      result.contentScripts = [];
      for (let options of manifest.content_scripts || []) {
        result.contentScripts.push({
          allFrames: options.all_frames,
          matchAboutBlank: options.match_about_blank,
          matchAboutBlank: options.match_about_blank,
          frameID: options.frame_id,
          runAt: options.run_at,

          matches: options.matches,
          excludeMatches: options.exclude_matches || [],
          excludeMatches: options.exclude_matches || [],
          includeGlobs: options.include_globs,
          excludeGlobs: options.exclude_globs,

          jsPaths: options.js || [],
          cssPaths: options.css || [],
          cssPaths: options.css || [],
        });
      }

      if (this.canUseExperiment(manifest)) {
        let parentModules = {};
        let parentModules = {};
        let childModules = {};

        for (let [name, data] of Object.entries(manifest.experiment_apis)) {
          let schema = this.getURL(data.schema);
          let schema = this.getURL(data.schema);

          if (!schemaPromises.has(schema)) {
            schemaPromises.set(
              schema,
              this.readJSON(data.schema).then(json =>
              this.readJSON(data.schema).then(json =>
                Schemas.processSchema(json)
              )
            );
            );
          }
          }

          if (data.parent) {
            parentModules[name] = moduleData(data.parent);
            parentModules[name] = moduleData(data.parent);
          }

          if (data.child) {
            childModules[name] = moduleData(data.child);
          }
          }
        }

        result.modules = {
          child: computeModuleInit("addon_child", childModules),
          parent: computeModuleInit("addon_parent", parentModules),
          parent: computeModuleInit("addon_parent", parentModules),
        };
      }

      // Normalize all patterns to contain a single leading /
      if (manifest.web_accessible_resources) {
      if (manifest.web_accessible_resources) {
        webAccessibleResources.push(
          ...manifest.web_accessible_resources.map(path =>
            path.replace(/^\/*/, "/")
          )
        );
        );
      }
    } else if (this.type == "langpack") {
      // Langpack startup is performance critical, so we want to compute as much
      // Langpack startup is performance critical, so we want to compute as much
      // as possible here to make startup not trigger async DB reads.
      // We'll store the four items below in the startupData.

      // 1. Compute the chrome resources to be registered for this langpack.
      const platform = AppConstants.platform;
      const platform = AppConstants.platform;
      const chromeEntries = [];
      for (const [language, entry] of Object.entries(manifest.languages)) {
        for (const [alias, path] of Object.entries(
          entry.chrome_resources || {}
        )) {
        )) {
          if (typeof path === "string") {
            chromeEntries.push(["locale", alias, language, path]);
          } else if (platform in path) {
            // If the path is not a string, it's an object with path per
            // platform where the keys are taken from AppConstants.platform
            // platform where the keys are taken from AppConstants.platform
            chromeEntries.push(["locale", alias, language, path[platform]]);
          }
        }
      }


      // 2. Compute langpack ID.
      const productCodeName = AppConstants.MOZ_BUILD_APP.replace("/", "-");

      // The result path looks like this:
      // The result path looks like this:
      //   Firefox - `langpack-pl-browser`
      //   Fennec - `langpack-pl-mobile-android`
      const langpackId = `langpack-${manifest.langpack_id}-${productCodeName}`;

      // 3. Compute L10nRegistry sources for this langpack.
      const l10nRegistrySources = {};

      // Check if there's a root directory `/localization` in the langpack.
      // Check if there's a root directory `/localization` in the langpack.
      // If there is one, add it with the name `toolkit` as a FileSource.
      const entries = await this.readDirectory("localization");
      if (entries.length) {
        l10nRegistrySources.toolkit = "";
      }
      }

      // Add any additional sources listed in the manifest
      if (manifest.sources) {
        for (const [sourceName, { base_path }] of Object.entries(
          manifest.sources
          manifest.sources
        )) {
          l10nRegistrySources[sourceName] = base_path;
        }
      }


      // 4. Save the list of languages handled by this langpack.
      const languages = Object.keys(manifest.languages);

      this.startupData = {
        chromeEntries,
        chromeEntries,
        langpackId,
        l10nRegistrySources,
        languages,
      };
    } else if (this.type == "dictionary") {
    } else if (this.type == "dictionary") {
      let dictionaries = {};
      for (let [lang, path] of Object.entries(manifest.dictionaries)) {
        path = path.replace(/^\/+/, "");

        let dir = OSPath.dirname(path);
        if (dir === ".") {
        if (dir === ".") {
          dir = "";
        }
        let leafName = OSPath.basename(path);
        let affixPath = leafName.slice(0, -3) + "aff";


        let entries = Array.from(
          await this.readDirectory(dir),
          entry => entry.name
        );
        if (!entries.includes(leafName)) {
          this.manifestError(
            `Invalid dictionary path specified for '${lang}': ${path}`
          );
        }
        }
        if (!entries.includes(affixPath)) {
          this.manifestError(
            `Invalid dictionary path specified for '${lang}': Missing affix file: ${path}`
          );
        }
        }

        dictionaries[lang] = path;
      }

      this.startupData = { dictionaries };
      this.startupData = { dictionaries };
    }

    if (schemaPromises.size) {
      let schemas = new Map();
      for (let [url, promise] of schemaPromises) {
      for (let [url, promise] of schemaPromises) {
        schemas.set(url, await promise);
      }
      result.schemaURLs = schemas;
    }


    return result;
  }

  // Reads the extension's |manifest.json| file, and stores its
  // Reads the extension's |manifest.json| file, and stores its
  // parsed contents in |this.manifest|.
  async loadManifest() {
    let [manifestData] = await Promise.all([
      this.parseManifest(),
      Management.lazyInit(),
      Management.lazyInit(),
    ]);

    if (!manifestData) {
      return;
    }
    }

    // Do not override the add-on id that has been already assigned.
    if (!this.id) {
      this.id = manifestData.id;
    }
    }

    this.manifest = manifestData.manifest;
    this.apiNames = manifestData.apiNames;
    this.contentScripts = manifestData.contentScripts;
    this.dependencies = manifestData.dependencies;
    this.dependencies = manifestData.dependencies;
    this.permissions = manifestData.permissions;
    this.schemaURLs = manifestData.schemaURLs;
    this.type = manifestData.type;

    this.modules = manifestData.modules;

    this.apiManager = this.getAPIManager();
    await this.apiManager.lazyInit();
    await this.apiManager.lazyInit();

    this.webAccessibleResources = manifestData.webAccessibleResources.map(
      res => new MatchGlob(res)
    );
    );
    this.allowedOrigins = new MatchPatternSet(manifestData.originPermissions, {
      restrictSchemes: this.restrictSchemes,
    });

      }
    return this.manifest;
  }

  hasPermission(perm, includeOptional = false) {
    // If the permission is a "manifest property" permission, we check if the extension

    // does have the required property in its manifest.
    let manifest_ = "manifest:";
    if (perm.startsWith(manifest_)) {
      // Handle nested "manifest property" permission (e.g. as in "manifest:property.nested").
      let value = this.manifest;
      for (let prop of perm.substr(manifest_.length).split(".")) {
    if (perm.startsWith(manifest_)) {
        if (!value) {
          break;
        }
        value = value[prop];
      }
          break;

      return value != null;
    }

    if (this.permissions.has(perm)) {
      return true;
    }
    }

    if (includeOptional && this.manifest.optional_permissions.includes(perm)) {
      return true;
    }


    return false;
  }

  getAPIManager() {
    return false;
    let apiManagers = [Management];

    for (let id of this.dependencies) {
      let policy = WebExtensionPolicy.getByID(id);
      if (policy) {

        if (policy.extension.experimentAPIManager) {
          apiManagers.push(policy.extension.experimentAPIManager);
        } else if (AppConstants.DEBUG) {
          Cu.reportError(`Cannot find experimental API exported from ${id}`);
        }
          apiManagers.push(policy.extension.experimentAPIManager);
      }
    }

    if (this.modules) {
      this.experimentAPIManager = new ExtensionCommon.LazyAPIManager(
    }
        "main",
        this.modules.parent,
        this.schemaURLs
      );

        this.modules.parent,
      apiManagers.push(this.experimentAPIManager);
    }
      );

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

    if (apiManagers.length == 1) {
    return new ExtensionCommon.MultiAPIManager("main", apiManagers.reverse());
  }

    return new ExtensionCommon.MultiAPIManager("main", apiManagers.reverse());
  localizeMessage(...args) {
    return this.localeData.localizeMessage(...args);
  }

  localize(str, locale) {
  }
    // If the extension declares fluent resources in the manifest, try
    // first to localize with fluent.  Also use the original webextension
    // method (_locales/xx.json) so extensions can migrate bit by bit.
    // Note also that fluent keys typically use hyphense, so hyphens are
    // allowed in the __MSG_foo__ keys used by fluent, though they are
    // method (_locales/xx.json) so extensions can migrate bit by bit.
    // not allowed in the keys used for json translations.
    if (this.fluentL10n) {
      str = str.replace(/__MSG_([-A-Za-z0-9@_]+?)__/g, (matched, message) => {
        let translation = this.fluentL10n.formatValueSync(message);
        return translation !== undefined ? translation : matched;
      str = str.replace(/__MSG_([-A-Za-z0-9@_]+?)__/g, (matched, message) => {
      });
    }
    if (this.localeData) {
      str = this.localeData.localize(str, locale);
    }
    if (this.localeData) {
    return str;
  }

  // If a "default_locale" is specified in that manifest, returns it
  // as a Gecko-compatible locale string. Otherwise, returns null.
  get defaultLocale() {

    if (this.manifest.default_locale != null) {
      return this.normalizeLocaleCode(this.manifest.default_locale);
    }

    return null;
      return this.normalizeLocaleCode(this.manifest.default_locale);
  }

  // Normalizes a Chrome-compatible locale code to the appropriate
  // Gecko-compatible variant. Currently, this means simply
  // replacing underscores with hyphens.

  normalizeLocaleCode(locale) {
    return locale.replace(/_/g, "-");
  }

  // Reads the locale file for the given Gecko-compatible locale code, and
  // stores its parsed contents in |this.localeMessages.get(locale)|.

  async readLocaleFile(locale) {
    let locales = await this.promiseLocales();
    let dir = locales.get(locale) || locale;
    let file = `_locales/${dir}/messages.json`;

    let dir = locales.get(locale) || locale;
    try {
      let messages = await this.readJSON(file);
      return this.localeData.addLocale(locale, messages, this);
    } catch (e) {
      this.packagingError(`Loading locale file ${file}: ${e}`);
      return this.localeData.addLocale(locale, messages, this);
      return new Map();
    }
      this.packagingError(`Loading locale file ${file}: ${e}`);
  }

  async _promiseLocaleMap() {
    let locales = new Map();

  async _promiseLocaleMap() {
    let entries = await this.readDirectory("_locales");
    for (let file of entries) {
      if (file.isDir) {
        let locale = this.normalizeLocaleCode(file.name);
        locales.set(locale, file.name);
      if (file.isDir) {
      }
    }

    return locales;
  }


  _setupLocaleData(locales) {
    if (this.localeData) {
      return this.localeData.locales;
    }
    if (this.localeData) {

    this.localeData = new LocaleData({
      defaultLocale: this.defaultLocale,
      locales,
      builtinMessages: this.builtinMessages,
      defaultLocale: this.defaultLocale,
    });

    return locales;
  }

    return locales;
  // Reads the list of locales available in the extension, and returns a
  // Promise which resolves to a Map upon completion.
  // Each map key is a Gecko-compatible locale code, and each value is the
  // "_locales" subdirectory containing that locale:
  //
  // Each map key is a Gecko-compatible locale code, and each value is the
  // Map(gecko-locale-code -> locale-directory-name)
  promiseLocales() {
    if (!this._promiseLocales) {
      this._promiseLocales = (async () => {
        let locales = this._promiseLocaleMap();
        return this._setupLocaleData(locales);
      })();
    }
        let locales = this._promiseLocaleMap();

    return this._promiseLocales;
  }

  // Reads the locale messages for all locales, and returns a promise which
    return this._promiseLocales;
  // resolves to a Map of locale messages upon completion. Each key in the map
  // is a Gecko-compatible locale code, and each value is a locale data object
  // as returned by |readLocaleFile|.
  async initAllLocales() {
    let locales = await this.promiseLocales();
  // is a Gecko-compatible locale code, and each value is a locale data object

    await Promise.all(
      Array.from(locales.keys(), locale => this.readLocaleFile(locale))
    );
    await Promise.all(

    let defaultLocale = this.defaultLocale;
    if (defaultLocale) {
      if (!locales.has(defaultLocale)) {
        this.manifestError(
    if (defaultLocale) {
          'Value for "default_locale" property must correspond to ' +
            'a directory in "_locales/". Not found: ' +
            JSON.stringify(`_locales/${this.manifest.default_locale}/`)
        );
      }
    } else if (locales.size) {
        );
      this.manifestError(
        'The "default_locale" property is required when a ' +
          '"_locales/" directory is present.'
      );
    }
          '"_locales/" directory is present.'

    return this.localeData.messages;
  }

  // Reads the locale file for the given Gecko-compatible locale code, or the
  }
  // default locale if no locale code is given, and sets it as the currently
  // selected locale on success.
  //
  // Pre-loads the default locale for fallback message processing, regardless
  // of the locale specified.
  //
  //
  // If no locales are unavailable, resolves to |null|.
  async initLocale(locale = this.defaultLocale) {
    if (locale == null) {
      return null;
  async initLocale(locale = this.defaultLocale) {
    }

    let promises = [this.readLocaleFile(locale)];

    let { defaultLocale } = this;
    let promises = [this.readLocaleFile(locale)];
    if (locale != defaultLocale && !this.localeData.has(defaultLocale)) {
      promises.push(this.readLocaleFile(defaultLocale));
    }
    let { defaultLocale } = this;

    let results = await Promise.all(promises);

    this.localeData.selectedLocale = locale;
    return results[0];
  }
    this.localeData.selectedLocale = locale;

  /**
   * Formats all the strings for a permissions dialog/notification.
   *
   * @param {object} info Information about the permissions being requested.
   * Formats all the strings for a permissions dialog/notification.
   *
   * @param {array<string>} info.permissions.origins
   *                        Origin permissions requested.
   * @param {array<string>} info.permissions.permissions
   *                        Regular (non-origin) permissions requested.
   *                        Origin permissions requested.
   * @param {boolean} info.unsigned
   *                  True if the prompt is for installing an unsigned addon.
   * @param {string} info.type
   *                 The type of prompt being shown.  May be one of "update",
   *                 "sideload", "optional", or omitted for a regular
   * @param {string} info.type
   *                 install prompt.
   * @param {string} info.appName
   *                 The localized name of the application, to be substituted
   *                 in computed strings as needed.
   * @param {nsIStringBundle} bundle
   *                 The localized name of the application, to be substituted
   *                          The string bundle to use for l10n.
   * @param {object} options
   * @param {boolean} options.collapseOrigins
   *                  Wether to limit the number of displayed host permissions.
   *                  Default is false.
   * @param {object} options
   *
   * @returns {object} An object with properties containing localized strings
   *                   for various elements of a permission dialog. The "header"
   *                   property on this object is the notification header text
   *                   and it has the string "<>" as a placeholder for the
   * @returns {object} An object with properties containing localized strings
   *                   addon name.
   */
  static formatPermissionStrings(
    info,
    bundle,
   */
    { collapseOrigins = false } = {}
  ) {
    let result = {};

    let perms = info.permissions || { origins: [], permissions: [] };
  ) {

    // First classify our host permissions
    let allUrls = false,
      wildcards = new Set(),

      sites = new Set();
    for (let permission of perms.origins) {
      if (permission == "<all_urls>") {
        allUrls = true;
        break;
    for (let permission of perms.origins) {
      }

      // Privileged extensions may request access to "about:"-URLs, such as
      // about:reader.
      let match = /^[a-z*]+:\/\/([^/]*)\/|^about:/.exec(permission);

      // Privileged extensions may request access to "about:"-URLs, such as
      if (!match) {
        throw new Error(`Unparseable host permission ${permission}`);
      }
      // Note: the scheme is ignored in the permission warnings. If this ever
      // changes, update the comparePermissions method as needed.
      }
      if (!match[1] || match[1] == "*") {
        allUrls = true;
      } else if (match[1].startsWith("*.")) {
        wildcards.add(match[1].slice(2));
      } else {
      } else if (match[1].startsWith("*.")) {
        sites.add(match[1]);
      }
    }

    // Format the host permissions.  If we have a wildcard for all urls,
    }
    // a single string will suffice.  Otherwise, show domain wildcards
    // first, then individual host permissions.
    result.msgs = [];
    if (allUrls) {
      result.msgs.push(
        bundle.GetStringFromName("webextPerms.hostDescription.allUrls")
    result.msgs = [];
      );
    } else {
      // Formats a list of host permissions.  If we have 4 or fewer, display
      // them all, otherwise display the first 3 followed by an item that
      // says "...plus N others"
      let format = (list, itemKey, moreKey) => {
      // them all, otherwise display the first 3 followed by an item that
        function formatItems(items) {
          result.msgs.push(
            ...items.map(item => bundle.formatStringFromName(itemKey, [item]))
          );
        function formatItems(items) {
        }
        if (list.length < 5 || !collapseOrigins) {
          formatItems(list);
        } else {
          formatItems(list.slice(0, 3));

        } else {
          let remaining = list.length - 3;
          result.msgs.push(
            PluralForm.get(
              remaining,
              bundle.GetStringFromName(moreKey)
            PluralForm.get(
            ).replace("#1", remaining)
          );
        }
      };

        }
      format(
        Array.from(wildcards),
        "webextPerms.hostDescription.wildcard",
        "webextPerms.hostDescription.tooManyWildcards"
      );
        "webextPerms.hostDescription.wildcard",
      format(
        Array.from(sites),
        "webextPerms.hostDescription.oneSite",
        "webextPerms.hostDescription.tooManySites"
      );
        "webextPerms.hostDescription.oneSite",
    }

    let permissionKey = perm => `webextPerms.description.${perm}`;

    // Next, show the native messaging permission if it is present.
    let permissionKey = perm => `webextPerms.description.${perm}`;
    const NATIVE_MSG_PERM = "nativeMessaging";
    if (perms.permissions.includes(NATIVE_MSG_PERM)) {
      result.msgs.push(
        bundle.formatStringFromName(permissionKey(NATIVE_MSG_PERM), [
          info.appName,
        ])
      result.msgs.push(
      );
    }

    // Finally, show remaining permissions, in the same order as AMO.
    // The permissions are sorted alphabetically by the permission
    }
    // string to match AMO.
    let permissionsCopy = perms.permissions.slice(0);
    for (let permission of permissionsCopy.sort()) {
      // Handled above
      if (permission == "nativeMessaging") {
    let permissionsCopy = perms.permissions.slice(0);
        continue;
      }
      try {
        result.msgs.push(bundle.GetStringFromName(permissionKey(permission)));
        continue;
      } catch (err) {
        // We deliberately do not include all permissions in the prompt.
        // So if we don't find one then just skip it.
      }
    }
        // We deliberately do not include all permissions in the prompt.

    const haveAccessKeys = AppConstants.platform !== "android";

    result.header = bundle.formatStringFromName("webextPerms.header", ["<>"]);
    result.text = info.unsigned
    const haveAccessKeys = AppConstants.platform !== "android";
      ? bundle.GetStringFromName("webextPerms.unsignedWarning")
      : "";
    result.listIntro = bundle.GetStringFromName("webextPerms.listIntro");

      : "";
    result.acceptText = bundle.GetStringFromName("webextPerms.add.label");
    result.cancelText = bundle.GetStringFromName("webextPerms.cancel.label");
    if (haveAccessKeys) {
    result.acceptText = bundle.GetStringFromName("webextPerms.add.label");
      result.acceptKey = bundle.GetStringFromName("webextPerms.add.accessKey");
      result.cancelKey = bundle.GetStringFromName(
        "webextPerms.cancel.accessKey"
      );
    }
        "webextPerms.cancel.accessKey"

    if (info.type == "sideload") {
      result.header = bundle.formatStringFromName(
        "webextPerms.sideloadHeader",
        ["<>"]
      result.header = bundle.formatStringFromName(
      );
      let key = !result.msgs.length
        ? "webextPerms.sideloadTextNoPerms"
        : "webextPerms.sideloadText2";
      result.text = bundle.GetStringFromName(key);
        ? "webextPerms.sideloadTextNoPerms"
      result.acceptText = bundle.GetStringFromName(
        "webextPerms.sideloadEnable.label"
      );
      result.cancelText = bundle.GetStringFromName(
        "webextPerms.sideloadCancel.label"
      );
      );
      if (haveAccessKeys) {
        result.acceptKey = bundle.GetStringFromName(
          "webextPerms.sideloadEnable.accessKey"
        );
        result.acceptKey = bundle.GetStringFromName(
        result.cancelKey = bundle.GetStringFromName(
          "webextPerms.sideloadCancel.accessKey"
        );
      }
    } else if (info.type == "update") {
      result.header = bundle.formatStringFromName("webextPerms.updateText", [
        "<>",
      ]);
      result.text = "";
      result.acceptText = bundle.GetStringFromName(
        "webextPerms.updateAccept.label"
      ]);
      );
      if (haveAccessKeys) {
        result.acceptKey = bundle.GetStringFromName(
          "webextPerms.updateAccept.accessKey"
        );
      if (haveAccessKeys) {
      }
    } else if (info.type == "optional") {
      result.header = bundle.formatStringFromName(
        "webextPerms.optionalPermsHeader",
        ["<>"]
    } else if (info.type == "optional") {
      );
      result.text = "";
      result.listIntro = bundle.GetStringFromName(
        "webextPerms.optionalPermsListIntro"
      );
      result.acceptText = bundle.GetStringFromName(
        "webextPerms.optionalPermsListIntro"
        "webextPerms.optionalPermsAllow.label"
      );
      result.cancelText = bundle.GetStringFromName(
        "webextPerms.optionalPermsDeny.label"
      );
      result.cancelText = bundle.GetStringFromName(
      if (haveAccessKeys) {
        result.acceptKey = bundle.GetStringFromName(
          "webextPerms.optionalPermsAllow.accessKey"
        );
        result.cancelKey = bundle.GetStringFromName(
          "webextPerms.optionalPermsAllow.accessKey"
          "webextPerms.optionalPermsDeny.accessKey"
        );
        result.cancelKey = bundle.GetStringFromName(
      }
    }

    return result;
  }

}

const PROXIED_EVENTS = new Set([
  "test-harness-message",
  "add-permissions",
const PROXIED_EVENTS = new Set([
  "remove-permissions",
]);

class BootstrapScope {
  install(data, reason) {}

  uninstall(data, reason) {
    AsyncShutdown.profileChangeTeardown.addBlocker(
      `Uninstalling add-on: ${data.id}`,
      Management.emit("uninstall", { id: data.id }).then(() => {
        Management.emit("uninstall-complete", { id: data.id });
      `Uninstalling add-on: ${data.id}`,
      })
    );
  }

  fetchState() {
  }
    if (this.extension) {
      return { state: this.extension.state };
    }
    return null;
      return { state: this.extension.state };
  }

  async update(data, reason) {
    // Retain any previously granted permissions that may have migrated
    // into the optional list.
    if (data.oldPermissions) {
  async update(data, reason) {
      // New permissions may be null, ensure we have an empty
    // into the optional list.
      // permission set in that case.
      let emptyPermissions = { permissions: [], origins: [] };
      await ExtensionData.migratePermissions(
        data.id,
        data.oldPermissions,
      await ExtensionData.migratePermissions(
        data.oldOptionalPermissions,
        data.userPermissions || emptyPermissions,
        data.optionalPermissions || emptyPermissions
      );
    }
        data.optionalPermissions || emptyPermissions

    return Management.emit("update", {
      id: data.id,
      resourceURI: data.resourceURI,
    });
      id: data.id,
  }

  startup(data, reason) {
    // eslint-disable-next-line no-use-before-define
    this.extension = new Extension(
  startup(data, reason) {
      data,
      this.BOOTSTRAP_REASON_TO_STRING_MAP[reason]
    );
    return this.extension.startup();
  }

  async shutdown(data, reason) {
    let result = await this.extension.shutdown(
      this.BOOTSTRAP_REASON_TO_STRING_MAP[reason]
    );
    this.extension = null;
    return result;
      this.BOOTSTRAP_REASON_TO_STRING_MAP[reason]
  }
}

  }
XPCOMUtils.defineLazyGetter(
  BootstrapScope.prototype,
  "BOOTSTRAP_REASON_TO_STRING_MAP",
  () => {
    const { BOOTSTRAP_REASONS } = AddonManagerPrivate;
  "BOOTSTRAP_REASON_TO_STRING_MAP",

    return Object.freeze({
      [BOOTSTRAP_REASONS.APP_STARTUP]: "APP_STARTUP",
      [BOOTSTRAP_REASONS.APP_SHUTDOWN]: "APP_SHUTDOWN",
      [BOOTSTRAP_REASONS.ADDON_ENABLE]: "ADDON_ENABLE",
      [BOOTSTRAP_REASONS.APP_STARTUP]: "APP_STARTUP",
      [BOOTSTRAP_REASONS.ADDON_DISABLE]: "ADDON_DISABLE",
      [BOOTSTRAP_REASONS.ADDON_INSTALL]: "ADDON_INSTALL",
      [BOOTSTRAP_REASONS.ADDON_UNINSTALL]: "ADDON_UNINSTALL",
      [BOOTSTRAP_REASONS.ADDON_UPGRADE]: "ADDON_UPGRADE",
      [BOOTSTRAP_REASONS.ADDON_DOWNGRADE]: "ADDON_DOWNGRADE",
      [BOOTSTRAP_REASONS.ADDON_UNINSTALL]: "ADDON_UNINSTALL",
    });
  }
);

class DictionaryBootstrapScope extends BootstrapScope {
);
  install(data, reason) {}
  uninstall(data, reason) {}

  startup(data, reason) {
    // eslint-disable-next-line no-use-before-define

    this.dictionary = new Dictionary(data);
    return this.dictionary.startup(this.BOOTSTRAP_REASON_TO_STRING_MAP[reason]);
  }

  shutdown(data, reason) {
    this.dictionary.shutdown(this.BOOTSTRAP_REASON_TO_STRING_MAP[reason]);
  }
    this.dictionary = null;
  }
}

class LangpackBootstrapScope {
  }
  install(data, reason) {}
  uninstall(data, reason) {}

  startup(data, reason) {
    // eslint-disable-next-line no-use-before-define
  uninstall(data, reason) {}
    this.langpack = new Langpack(data);
    return this.langpack.startup();
  }

  shutdown(data, reason) {
    this.langpack.shutdown();

    this.langpack = null;
  }
}

let activeExtensionIDs = new Set();
}

let pendingExtensions = new Map();

/**
 * This class is the main representation of an active WebExtension

 * in the main process.
 * @extends ExtensionData
 */
class Extension extends ExtensionData {
  constructor(addonData, startupReason) {
 */
    super(addonData.resourceURI);

    this.startupStates = new Set();
    this.state = "Not started";

    this.sharedDataKeys = new Set();

    this.uuid = UUIDMap.get(addonData.id);
    this.instanceId = getUniqueId();


    this.MESSAGE_EMIT_EVENT = `Extension:EmitEvent:${this.instanceId}`;
    Services.ppmm.addMessageListener(this.MESSAGE_EMIT_EVENT, this);

    if (addonData.cleanupFile) {
      Services.obs.addObserver(this, "xpcom-shutdown");
    Services.ppmm.addMessageListener(this.MESSAGE_EMIT_EVENT, this);
      this.cleanupFile = addonData.cleanupFile || null;
      delete addonData.cleanupFile;
    }

    if (addonData.TEST_NO_ADDON_MANAGER) {
      delete addonData.cleanupFile;
      this.dontSaveStartupData = true;
    }

    this.addonData = addonData;
    this.startupData = addonData.startupData || {};
    }
    this.startupReason = startupReason;

    if (["ADDON_UPGRADE", "ADDON_DOWNGRADE"].includes(startupReason)) {
      StartupCache.clearAddonData(addonData.id);
    }


    this.remote = !WebExtensionPolicy.isExtensionProcess;
    this.remoteType = this.remote ? E10SUtils.EXTENSION_REMOTE_TYPE : null;


    if (this.remote && processCount !== 1) {
      throw new Error(
        "Out-of-process WebExtensions are not supported with multiple child processes"
    if (this.remote && processCount !== 1) {
      );
    }

    // This is filled in the first time an extension child is created.
    this.parentMessageManager = null;


    this.id = addonData.id;
    this.version = addonData.version;
    this.baseURL = this.getURL("");
    this.baseURI = Services.io.newURI(this.baseURL).QueryInterface(Ci.nsIURL);
    this.principal = this.createPrincipal();
    this.version = addonData.version;

    this.views = new Set();
    this._backgroundPageFrameLoader = null;

    this.onStartup = null;

    this.hasShutdown = false;
    this.onShutdown = new Set();


    this.uninstallURL = null;

    this.allowedOrigins = null;
    this._optionalOrigins = null;

    this.webAccessibleResources = null;

    this.registeredContentScripts = new Map();

    this.emitter = new EventEmitter();

    if (this.startupData.lwtData && this.startupReason == "APP_STARTUP") {
      LightweightThemeManager.fallbackThemeData = this.startupData.lwtData;
    }

      LightweightThemeManager.fallbackThemeData = this.startupData.lwtData;
    /* eslint-disable mozilla/balanced-listeners */
    this.on("add-permissions", (ignoreEvent, permissions) => {
      for (let perm of permissions.permissions) {
        this.permissions.add(perm);
      }
      for (let perm of permissions.permissions) {

      if (permissions.origins.length) {
        let patterns = this.allowedOrigins.patterns.map(host => host.pattern);

        this.allowedOrigins = new MatchPatternSet(
        let patterns = this.whiteListedHosts.patterns.map(host => host.pattern);
          new Set([...patterns, ...permissions.origins]),
          {
            restrictSchemes: this.restrictSchemes,
            ignorePath: true,
          }
            restrictSchemes: this.restrictSchemes,
        );
      }

      this.policy.permissions = Array.from(this.permissions);
      this.policy.allowedOrigins = this.allowedOrigins;


      this.cachePermissions();
      this.updatePermissions();
    });

    this.on("remove-permissions", (ignoreEvent, permissions) => {
      for (let perm of permissions.permissions) {

        this.permissions.delete(perm);
      }

      let origins = permissions.origins.map(
        origin => new MatchPattern(origin, { ignorePath: true }).pattern
      }
      );

      this.allowedOrigins = new MatchPatternSet(
        this.allowedOrigins.patterns.filter(
          host => !origins.includes(host.pattern)

        )
      );

      this.policy.permissions = Array.from(this.permissions);
      this.policy.allowedOrigins = this.allowedOrigins;
      );

      this.cachePermissions();
      this.updatePermissions();
    });
    /* eslint-enable mozilla/balanced-listeners */
      this.cachePermissions();
  }

  set state(startupState) {
    this.startupStates.clear();

    this.startupStates.add(startupState);
  }

  get state() {
    return `${Array.from(this.startupStates).join(", ")}`;
  }


  async addStartupStatePromise(name, fn) {
    this.startupStates.add(name);
    try {
      await fn();
    } finally {
    this.startupStates.add(name);
      this.startupStates.delete(name);
    }
  }

    }
  get restrictSchemes() {
    return !(this.isPrivileged && this.hasPermission("mozillaAddons"));
  }

  // Some helpful properties added elsewhere:
  }
  /**
   * An object used to map between extension-visible tab ids and
   * native Tab object
   * @property {TabManager} tabManager
   */
   * native Tab object

  static getBootstrapScope() {
    return new BootstrapScope();
  }


  static getBootstrapScope() {
  get groupFrameLoader() {
    let frameLoader = this._backgroundPageFrameLoader;

    for (let view of this.views) {
      if (view.viewType === "background" && view.xulBrowser) {
        return view.xulBrowser.frameLoader;
      }
      if (!frameLoader && view.xulBrowser) {
        frameLoader = view.xulBrowser.frameLoader;
        return view.xulBrowser.frameLoader;
      }
      if (!frameLoader && view.xulBrowser) {
    }
    return frameLoader || ExtensionParent.DebugUtils.getFrameLoader(this.id);
  }

  on(hook, f) {
  }
    return this.emitter.on(hook, f);
  }

  off(hook, f) {
    return this.emitter.off(hook, f);
  }


  once(hook, f) {
    return this.emitter.once(hook, f);
  }

  once(hook, f) {
  emit(event, ...args) {
    if (PROXIED_EVENTS.has(event)) {
      Services.ppmm.broadcastAsyncMessage(this.MESSAGE_EMIT_EVENT, {
        event,
        args,
    if (PROXIED_EVENTS.has(event)) {
      });
    }

    return this.emitter.emit(event, ...args);
  }
    }

  receiveMessage({ name, data }) {
    if (name === this.MESSAGE_EMIT_EVENT) {
      this.emitter.emit(data.event, ...data.args);
    }
  receiveMessage({ name, data }) {
  }

  testMessage(...args) {
    this.emit("test-harness-message", ...args);
  }

  testMessage(...args) {
  createPrincipal(uri = this.baseURI, originAttributes = {}) {
    return Services.scriptSecurityManager.createContentPrincipal(
      uri,
      originAttributes
    );
    return Services.scriptSecurityManager.createContentPrincipal(
  }

  // Checks that the given URL is a child of our baseURI.
  isExtensionURL(url) {
    let uri = Services.io.newURI(url);


    let common = this.baseURI.getCommonBaseSpec(uri);
    return common == this.baseURL;

  }

  checkLoadURL(url, options = {}) {
    // As an optimization, f the URL starts with the extension's base URL,
    // don't do any further checks. It's always allowed to load it.
    if (url.startsWith(this.baseURL)) {
  checkLoadURL(url, options = {}) {
      return true;
    }

    return ExtensionCommon.checkLoadURL(url, this.principal, options);
  }
    }

  async promiseLocales(locale) {
    let locales = await StartupCache.locales.get(
      [this.id, "@@all_locales"],
      () => this._promiseLocaleMap()
  async promiseLocales(locale) {
    );

    return this._setupLocaleData(locales);
  }


  readLocaleFile(locale) {
    return StartupCache.locales
      .get([this.id, this.version, locale], () => super.readLocaleFile(locale))
      .then(result => {
        this.localeData.messages.set(locale, result);
      });
      .then(result => {
  }

  get manifestCacheKey() {
    return [this.id, this.version, Services.locale.appLocaleAsBCP47];
  }
  get manifestCacheKey() {

  get isPrivileged() {
    return (
      this.addonData.signedState === AddonManager.SIGNEDSTATE_PRIVILEGED ||
      this.addonData.signedState === AddonManager.SIGNEDSTATE_SYSTEM ||
    return (
      this.addonData.builtIn ||
      (AddonSettings.EXPERIMENTS_ENABLED && this.addonData.temporarilyInstalled)
    );
  }

    );
  get experimentsAllowed() {
    return AddonSettings.EXPERIMENTS_ENABLED || this.isPrivileged;
  }

  saveStartupData() {
  }
    if (this.dontSaveStartupData) {
      return;
    }
    XPIProvider.setStartupData(this.id, this.startupData);
  }

  parseManifest() {
    return StartupCache.manifests.get(this.manifestCacheKey, () =>
      super.parseManifest()
    );
  }
    return StartupCache.manifests.get(this.manifestCacheKey, () =>

  async cachePermissions() {
    let manifestData = await this.parseManifest();

    manifestData.originPermissions = this.allowedOrigins.patterns.map(
  async cachePermissions() {
      pat => pat.pattern
    );
    manifestData.permissions = this.permissions;
    return StartupCache.manifests.set(this.manifestCacheKey, manifestData);
    );
  }

  async loadManifest() {
    let manifest = await super.loadManifest();

  async loadManifest() {
    if (this.errors.length) {
      return Promise.reject({ errors: this.errors });
    }

    return manifest;
    }
  }

  get extensionPageCSP() {
    const { content_security_policy } = this.manifest;
    if (
      content_security_policy &&
      typeof content_security_policy === "object"
    if (
    ) {
      return content_security_policy.extension_pages;
    }
    return content_security_policy;
  }

    return content_security_policy;
  get contentScriptCSP() {
    let { content_security_policy } = this.manifest;
    if (
      content_security_policy &&
      typeof content_security_policy === "object"
    if (
    ) {
      return (
        content_security_policy.content_scripts ||
        content_security_policy.isolated_world
      );
    }
  }

      );
  get backgroundScripts() {
    return this.manifest.background && this.manifest.background.scripts;
  }

  get optionalPermissions() {
    return this.manifest.background && this.manifest.background.scripts;
    return this.manifest.optional_permissions;
  }

  get privateBrowsingAllowed() {
    return this.policy.privateBrowsingAllowed;
  }
  }

  canAccessWindow(window) {
    return this.policy.canAccessWindow(window);
  }


  // Representation of the extension to send to content
  // processes. This should include anything the content process might
  // need.
  serialize() {
  // Representation of the extension to send to content
    return {
      id: this.id,
      uuid: this.uuid,
      name: this.name,
      extensionPageCSP: this.extensionPageCSP,
      id: this.id,
      contentScriptCSP: this.contentScriptCSP,
      instanceId: this.instanceId,
      resourceURL: this.resourceURL,
      contentScripts: this.contentScripts,
      webAccessibleResources: this.webAccessibleResources.map(res => res.glob),
      instanceId: this.instanceId,
      allowedOrigins: this.allowedOrigins.patterns.map(pat => pat.pattern),
      permissions: this.permissions,
      optionalPermissions: this.optionalPermissions,
      isPrivileged: this.isPrivileged,
    };
      permissions: this.permissions,
  }

  // Extended serialized data which is only needed in the extensions process,
  // and is never deserialized in web content processes.
  serializeExtended() {

    return {
      backgroundScripts: this.backgroundScripts,
      childModules: this.modules && this.modules.child,
      dependencies: this.dependencies,
      schemaURLs: this.schemaURLs,
      backgroundScripts: this.backgroundScripts,
    };
  }

  broadcast(msg, data) {
    return new Promise(resolve => {
  }
      let { ppmm } = Services;
      let children = new Set();
      for (let i = 0; i < ppmm.childCount; i++) {
        children.add(ppmm.getChildAt(i));
      }

      for (let i = 0; i < ppmm.childCount; i++) {
      let maybeResolve;
      function listener(data) {
        children.delete(data.target);
        maybeResolve();
      }
      function listener(data) {
      function observer(subject, topic, data) {
        children.delete(subject);
        maybeResolve();
      }

        children.delete(subject);
      maybeResolve = () => {
        if (children.size === 0) {
          ppmm.removeMessageListener(msg + "Complete", listener);
          Services.obs.removeObserver(observer, "message-manager-close");
          Services.obs.removeObserver(observer, "message-manager-disconnect");
        if (children.size === 0) {
          resolve();
        }
          Services.obs.removeObserver(observer, "message-manager-disconnect");
      };
          resolve();
      ppmm.addMessageListener(msg + "Complete", listener, true);
      Services.obs.addObserver(observer, "message-manager-close");
      Services.obs.addObserver(observer, "message-manager-disconnect");
      ppmm.addMessageListener(msg + "Complete", listener, true);

      ppmm.broadcastAsyncMessage(msg, data);
    });
  }

    });
  setSharedData(key, value) {
    key = `extension/${this.id}/${key}`;
    this.sharedDataKeys.add(key);

  setSharedData(key, value) {
    sharedData.set(key, value);
  }

  getSharedData(key, value) {
    key = `extension/${this.id}/${key}`;
  }
    return sharedData.get(key);
  }

    return sharedData.get(key);
  initSharedData() {
    this.setSharedData("", this.serialize());
    this.setSharedData("extendedData", this.serializeExtended());
    this.setSharedData("locales", this.localeData.serialize());
    this.setSharedData("manifest", this.manifest);
    this.setSharedData("extendedData", this.serializeExtended());
    this.updateContentScripts();
  }

  updateContentScripts() {
    this.setSharedData("contentScripts", this.registeredContentScripts);

  }

  runManifest(manifest) {
    let promises = [];
    let addPromise = (name, fn) => {
  runManifest(manifest) {
      promises.push(this.addStartupStatePromise(name, fn));
    };

    for (let directive in manifest) {
      if (manifest[directive] !== null) {

        addPromise(`asyncEmitManifestEntry("${directive}")`, () =>
          Management.asyncEmitManifestEntry(this, directive)
        );
        addPromise(`asyncEmitManifestEntry("${directive}")`, () =>
      }
    }

    activeExtensionIDs.add(this.id);
    sharedData.set("extensions/activeIDs", activeExtensionIDs);


    pendingExtensions.delete(this.id);
    sharedData.set("extensions/pending", pendingExtensions);

    Services.ppmm.sharedData.flush();
    sharedData.set("extensions/pending", pendingExtensions);
    this.broadcast("Extension:Startup", this.id);

    return Promise.all(promises);
  }

  /**
   * Call the close() method on the given object when this extension
   * is shut down.  This can happen during browser shutdown, or when

   * an extension is manually disabled or uninstalled.
   *
   * @param {object} obj
   *        An object on which to call the close() method when this
   *        extension is shut down.
   *
   */
  callOnClose(obj) {
    this.onShutdown.add(obj);
  }
  callOnClose(obj) {

  forgetOnClose(obj) {
    this.onShutdown.delete(obj);
  }

  get builtinMessages() {
    return new Map([["@@extension_id", this.uuid]]);
  }


  // Reads the locale file for the given Gecko-compatible locale code, or if
  // no locale is given, the available locale closest to the UI locale.
  // Sets the currently selected locale on success.
  async initLocale(locale = undefined) {
  // Reads the locale file for the given Gecko-compatible locale code, or if
    if (locale === undefined) {
      let locales = await this.promiseLocales();

      let matches = Services.locale.negotiateLanguages(
        Services.locale.appLocalesAsBCP47,
      let locales = await this.promiseLocales();
        Array.from(locales.keys()),
        this.defaultLocale
      );

      locale = matches[0];
        this.defaultLocale
    }

    return super.initLocale(locale);
  }


  /**
   * Update site permissions as necessary.
   *
   * @param {string|undefined} reason
   * Update site permissions as necessary.
   *        If provided, this is a BOOTSTRAP_REASON string.  If reason is undefined,
   *        addon permissions are being added or removed that may effect the site permissions.
   */
  updatePermissions(reason) {
    const { principal } = this;

  updatePermissions(reason) {
    const testPermission = perm =>
      Services.perms.testPermissionFromPrincipal(principal, perm);

    const addUnlimitedStoragePermissions = () => {
      // Set the indexedDB permission and a custom "WebExtensions-unlimitedStorage" to

      // remember that the permission hasn't been selected manually by the user.
      Services.perms.addFromPrincipal(
        principal,
        "WebExtensions-unlimitedStorage",
      Services.perms.addFromPrincipal(
        Services.perms.ALLOW_ACTION
      );
      Services.perms.addFromPrincipal(
        principal,
        "indexedDB",
      Services.perms.addFromPrincipal(
        Services.perms.ALLOW_ACTION
      );
      Services.perms.addFromPrincipal(
        principal,
        "persistent-storage",
      Services.perms.addFromPrincipal(
        Services.perms.ALLOW_ACTION
      );
    };

    // Only update storage permissions when the extension changes in
    };
    // some way.
    if (reason !== "APP_STARTUP" && reason !== "APP_SHUTDOWN") {
      if (this.hasPermission("unlimitedStorage")) {
        addUnlimitedStoragePermissions();
      } else {
        // Remove the indexedDB permission if it has been enabled using the
      if (this.hasPermission("unlimitedStorage")) {
        // unlimitedStorage WebExtensions permissions.
      } else {
        Services.perms.removeFromPrincipal(
          principal,
          "WebExtensions-unlimitedStorage"
        );
        Services.perms.removeFromPrincipal(principal, "indexedDB");
          "WebExtensions-unlimitedStorage"
        Services.perms.removeFromPrincipal(principal, "persistent-storage");
      }
    } else if (
      reason === "APP_STARTUP" &&
      this.hasPermission("unlimitedStorage") &&
    } else if (
      (testPermission("indexedDB") !== Services.perms.ALLOW_ACTION ||
        testPermission("persistent-storage") !== Services.perms.ALLOW_ACTION)
    ) {
      // If the extension does have the unlimitedStorage permission, but the
      // expected site permissions are missing during the app startup, then
    ) {
      // add them back (See Bug 1454192).
      addUnlimitedStoragePermissions();
    }

    // Never change geolocation permissions at shutdown, since it uses a
    // session-only permission.
    if (reason !== "APP_SHUTDOWN") {
    // Never change geolocation permissions at shutdown, since it uses a
      if (this.hasPermission("geolocation")) {
        if (testPermission("geo") === Services.perms.UNKNOWN_ACTION) {
          Services.perms.addFromPrincipal(
            principal,
            "geo",
            Services.perms.ALLOW_ACTION,
          Services.perms.addFromPrincipal(
            Services.perms.EXPIRE_SESSION
          );
        }
      } else if (
          );
        reason !== "APP_STARTUP" &&
        testPermission("geo") === Services.perms.ALLOW_ACTION
      ) {
        Services.perms.removeFromPrincipal(principal, "geo");
      }
      ) {
    }
  }

  static async migratePrivateBrowsing(addonData) {
    if (addonData.incognito !== "not_allowed") {

      ExtensionPermissions.add(addonData.id, {
        permissions: [PRIVATE_ALLOWED_PERMISSION],
        origins: [],
      });
      await StartupCache.clearAddonData(addonData.id);
        origins: [],

      // Record a telemetry event for the extension automatically allowed on private browsing as
      // part of the Firefox upgrade.
      AMTelemetry.recordActionEvent({
        extra: { addonId: addonData.id },
      // part of the Firefox upgrade.
        object: "appUpgrade",
        action: "privateBrowsingAllowed",
        value: "on",
        object: "appUpgrade",
      });
        action: "privateBrowsingAllowed",
    }
  }

    }
  async startup() {
    this.state = "Startup";

    let resolveReadyPromise;
    let readyPromise = new Promise(resolve => {

      resolveReadyPromise = resolve;
    });

    // Create a temporary policy object for the devtools and add-on
      resolveReadyPromise = resolve;
    // manager callers that depend on it being available early.
    this.policy = new WebExtensionPolicy({
      id: this.id,
      mozExtensionHostname: this.uuid,
      baseURL: this.resourceURL,
    this.policy = new WebExtensionPolicy({
      isPrivileged: this.isPrivileged,
      allowedOrigins: new MatchPatternSet([]),
      localizeCallback() {},
      readyPromise,
    });
      allowedOrigins: new MatchPatternSet([]),

    this.policy.extension = this;
    if (!WebExtensionPolicy.getByID(this.id)) {
      this.policy.active = true;
    }
    this.policy.extension = this;

    pendingExtensions.set(this.id, {
      mozExtensionHostname: this.uuid,
      baseURL: this.resourceURL,
    pendingExtensions.set(this.id, {
      isPrivileged: this.isPrivileged,
    });
    sharedData.set("extensions/pending", pendingExtensions);

    ExtensionTelemetry.extensionStartup.stopwatchStart(this);
    });
    try {
      this.state = "Startup: Loading manifest";
      await this.loadManifest();
      this.state = "Startup: Loaded manifest";

      this.state = "Startup: Loading manifest";
      if (!this.hasShutdown) {
      await this.loadManifest();
        this.state = "Startup: Init locale";
        await this.initLocale();
        this.state = "Startup: Initted locale";
      }

        await this.initLocale();
      if (this.errors.length) {
        return Promise.reject({ errors: this.errors });
      }

      if (this.hasShutdown) {
        return Promise.reject({ errors: this.errors });
        return;
      }

      // We automatically add permissions to system/built-in extensions.
      // Extensions expliticy stating not_allowed will never get permission.
      }
      if (!allowPrivateBrowsingByDefault) {
        let isAllowed = this.permissions.has(PRIVATE_ALLOWED_PERMISSION);
        if (this.manifest.incognito === "not_allowed") {
          // If an extension previously had permission, but upgrades/downgrades to
        let isAllowed = this.permissions.has(PRIVATE_ALLOWED_PERMISSION);
          // a version that specifies "not_allowed" in manifest, remove the
          // permission.
          if (isAllowed) {
          // a version that specifies "not_allowed" in manifest, remove the
            ExtensionPermissions.remove(this.id, {
          // permission.
              permissions: [PRIVATE_ALLOWED_PERMISSION],
              origins: [],
            });
            this.permissions.delete(PRIVATE_ALLOWED_PERMISSION);
              permissions: [PRIVATE_ALLOWED_PERMISSION],
          }
        } else if (
          !isAllowed &&
          this.isPrivileged &&
          }
          !this.addonData.temporarilyInstalled
        ) {
          // Add to EP so it is preserved after ADDON_INSTALL.  We don't wait on the add here
          // since we are pushing the value into this.permissions.  EP will eventually save.
          ExtensionPermissions.add(this.id, {
        ) {
            permissions: [PRIVATE_ALLOWED_PERMISSION],
            origins: [],
          });
          this.permissions.add(PRIVATE_ALLOWED_PERMISSION);
            origins: [],
        }
      }

      // Ensure devtools permission is set
      }
      if (
        this.manifest.devtools_page &&
        !this.manifest.optional_permissions.includes("devtools")
      ) {
        ExtensionPermissions.add(this.id, {
        !this.manifest.optional_permissions.includes("devtools")
          permissions: ["devtools"],
          origins: [],
        });
        this.permissions.add("devtools");
      }
        });

      GlobalManager.init(this);

      this.initSharedData();


      this.policy.active = false;
      this.policy = ExtensionProcessScript.initExtension(this);
      this.policy.extension = this;

      this.updatePermissions(this.startupReason);


      // Select the storage.local backend if it is already known,
      // and start the data migration if needed.
      if (this.hasPermission("storage")) {
        if (!ExtensionStorageIDB.isBackendEnabled) {
          this.setSharedData("storageIDBBackend", false);
      if (this.hasPermission("storage")) {
        } else if (ExtensionStorageIDB.isMigratedExtension(this)) {
          this.setSharedData("storageIDBBackend", true);
          this.setSharedData(
            "storageIDBPrincipal",
            ExtensionStorageIDB.getStoragePrincipal(this)
          this.setSharedData(
          );
        } else if (
          this.startupReason === "ADDON_INSTALL" &&
          !Services.prefs.getBoolPref(LEAVE_STORAGE_PREF, false)
        ) {
          this.startupReason === "ADDON_INSTALL" &&
          // If the extension has been just installed, set it as migrated,
          // because there will not be any data to migrate.
          ExtensionStorageIDB.setMigratedExtensionPref(this, true);
          this.setSharedData("storageIDBBackend", true);
          this.setSharedData(
            "storageIDBPrincipal",
            ExtensionStorageIDB.getStoragePrincipal(this)
          );
        }
            ExtensionStorageIDB.getStoragePrincipal(this)
      }

      resolveReadyPromise(this.policy);

      // The "startup" Management event sent on the extension instance itself

      // is emitted just before the Management "startup" event,
      // and it is used to run code that needs to be executed before
      // any of the "startup" listeners.
      this.emit("startup", this);

      // and it is used to run code that needs to be executed before
      this.startupStates.clear();
      await Promise.all([
        this.addStartupStatePromise("Startup: Emit startup", () =>
          Management.emit("startup", this)
        ),
      await Promise.all([
        this.addStartupStatePromise("Startup: Run manifest", () =>
          this.runManifest(this.manifest)
        ),
      ]);
      this.state = "Startup: Ran manifest";
          this.runManifest(this.manifest)

      Management.emit("ready", this);
      this.emit("ready");

      this.state = "Startup: Complete";
      Management.emit("ready", this);
    } catch (errors) {
      this.state = `Startup: Error: ${errors}`;

      for (let e of [].concat(errors)) {
        dump(
      this.state = `Startup: Error: ${errors}`;
          `Extension error: ${e.message || e} ${e.filename || e.fileName}:${
            e.lineNumber
        dump(
          } :: ${e.stack || new Error().stack}\n`
        );
        Cu.reportError(e);
      }

        Cu.reportError(e);
      if (this.policy) {
        this.policy.active = false;
      }

      this.cleanupGeneratedFile();
      }

      throw errors;
    } finally {
      ExtensionTelemetry.extensionStartup.stopwatchFinish(this);
    }
    } finally {
  }

  cleanupGeneratedFile() {
    if (!this.cleanupFile) {
      return;
    }

    let file = this.cleanupFile;
    this.cleanupFile = null;


    Services.obs.removeObserver(this, "xpcom-shutdown");

    return this.broadcast("Extension:FlushJarCache", { path: file.path })
      .then(() => {

        // We can't delete this file until everyone using it has
        // closed it (because Windows is dumb). So we wait for all the
        // child processes (including the parent) to flush their JAR
        // caches. These caches may keep the file open.
        // We can't delete this file until everyone using it has
        file.remove(false);
      })
      .catch(Cu.reportError);
  }

      })
  async shutdown(reason) {
    this.state = "Shutdown";

    this.hasShutdown = true;

    this.state = "Shutdown";
    if (!this.policy) {
      return;
    }

    if (
      return;
      this.hasPermission("storage") &&
      ExtensionStorageIDB.selectedBackendPromises.has(this)
    ) {
      this.state = "Shutdown: Storage";

      ExtensionStorageIDB.selectedBackendPromises.has(this)
      // Wait the data migration to complete.
      try {
        await ExtensionStorageIDB.selectedBackendPromises.get(this);
      } catch (err) {
        Cu.reportError(
          `Error while waiting for extension data migration on shutdown: ${this.policy.debugName} - ${err.message}::${err.stack}`
        );
      } catch (err) {
      }
      this.state = "Shutdown: Storage complete";
    }

    if (this.rootURI instanceof Ci.nsIJARURI) {
    }
      this.state = "Shutdown: Flush jar cache";
      let file = this.rootURI.JARFile.QueryInterface(Ci.nsIFileURL).file;
      Services.ppmm.broadcastAsyncMessage("Extension:FlushJarCache", {
        path: file.path,
      });
      this.state = "Shutdown: Flushed jar cache";
    }

      });
    const isAppShutdown = reason === "APP_SHUTDOWN";
    if (this.cleanupFile || !isAppShutdown) {
      StartupCache.clearAddonData(this.id);
    }

    if (this.cleanupFile || !isAppShutdown) {
    activeExtensionIDs.delete(this.id);
    sharedData.set("extensions/activeIDs", activeExtensionIDs);

    for (let key of this.sharedDataKeys) {
      sharedData.delete(key);
    sharedData.set("extensions/activeIDs", activeExtensionIDs);
    }

    Services.ppmm.removeMessageListener(this.MESSAGE_EMIT_EVENT, this);

    this.updatePermissions(reason);


    if (!this.manifest) {
      this.state = "Shutdown: Complete: No manifest";
      this.policy.active = false;

    if (!this.manifest) {
      return this.cleanupGeneratedFile();
    }

    GlobalManager.uninit(this);

    for (let obj of this.onShutdown) {
    GlobalManager.uninit(this);
      obj.close();
    }

    ParentAPIManager.shutdownExtension(this.id, reason);


    Management.emit("shutdown", this);
    this.emit("shutdown", isAppShutdown);

    const TIMED_OUT = Symbol();

    this.state = "Shutdown: Emit shutdown";

    let result = await Promise.race([
      this.broadcast("Extension:Shutdown", { id: this.id }),
      promiseTimeout(CHILD_SHUTDOWN_TIMEOUT_MS).then(() => TIMED_OUT),
    ]);
    this.state = `Shutdown: Emitted shutdown: ${result === TIMED_OUT}`;
      this.broadcast("Extension:Shutdown", { id: this.id }),
    if (result === TIMED_OUT) {
      Cu.reportError(
        `Timeout while waiting for extension child to shutdown: ${this.policy.debugName}`
      );
    }
      Cu.reportError(

    MessageChannel.abortResponses({ extensionId: this.id });

    this.policy.active = false;



    this.state = `Shutdown: Complete (${this.cleanupFile})`;
    return this.cleanupGeneratedFile();
  }

  observe(subject, topic, data) {
  }
    if (topic === "xpcom-shutdown") {
      this.cleanupGeneratedFile();
    }
  }

    }
  get name() {
    return this.manifest.name;
  }

  get optionalOrigins() {
  }
    if (this._optionalOrigins == null) {
      let { restrictSchemes, isPrivileged } = this;
      let origins = this.manifest.optional_permissions.filter(
        perm => classifyPermission(perm, restrictSchemes, isPrivileged).origin
      );
      let origins = this.manifest.optional_permissions.filter(
      this._optionalOrigins = new MatchPatternSet(origins, {
        restrictSchemes,
        ignorePath: true,
      });
        restrictSchemes,
    }
    return this._optionalOrigins;
  }
}

  }
class Dictionary extends ExtensionData {
  constructor(addonData, startupReason) {
    super(addonData.resourceURI);
    this.id = addonData.id;
    this.startupData = addonData.startupData;
  }

  static getBootstrapScope() {
    return new DictionaryBootstrapScope();
  }

  static getBootstrapScope() {
  async startup(reason) {
    this.dictionaries = {};
    for (let [lang, path] of Object.entries(this.startupData.dictionaries)) {
      let uri = Services.io.newURI(
        path.slice(0, -4) + ".aff",
    this.dictionaries = {};
        null,
        this.rootURI
      );
      this.dictionaries[lang] = uri;

        this.rootURI
      spellCheck.addDictionary(lang, uri);
    }

    Management.emit("ready", this);
  }
    }

  async shutdown(reason) {
    if (reason !== "APP_SHUTDOWN") {
      XPIProvider.unregisterDictionaries(this.dictionaries);
    }
  async shutdown(reason) {
  }
}

class Langpack extends ExtensionData {
  }
  constructor(addonData, startupReason) {
    super(addonData.resourceURI);
    this.startupData = addonData.startupData;
    this.manifestCacheKey = [addonData.id, addonData.version];
  }

  static getBootstrapScope() {
    return new LangpackBootstrapScope();

  }

  async promiseLocales(locale) {
    let locales = await StartupCache.locales.get(
      [this.id, "@@all_locales"],
  async promiseLocales(locale) {
      () => this._promiseLocaleMap()
    );

    return this._setupLocaleData(locales);
  }


  parseManifest() {
    return StartupCache.manifests.get(this.manifestCacheKey, () =>
      super.parseManifest()
    );
    return StartupCache.manifests.get(this.manifestCacheKey, () =>
  }

  async startup(reason) {
    this.chromeRegistryHandle = null;
    if (this.startupData.chromeEntries.length) {
  async startup(reason) {
      const manifestURI = Services.io.newURI(
        "manifest.json",
        null,
        this.rootURI
        "manifest.json",
      );
      this.chromeRegistryHandle = aomStartup.registerChrome(
        manifestURI,
        this.startupData.chromeEntries
      );
    }

    const langpackId = this.startupData.langpackId;
    }
    const l10nRegistrySources = this.startupData.l10nRegistrySources;

    resourceProtocol.setSubstitution(langpackId, this.rootURI);

    for (const [sourceName, basePath] of Object.entries(l10nRegistrySources)) {
    resourceProtocol.setSubstitution(langpackId, this.rootURI);
      L10nRegistry.registerSource(
        new FileSource(
          `${sourceName}-${langpackId}`,
          this.startupData.languages,
          `resource://${langpackId}/${basePath}localization/{locale}/`
          `${sourceName}-${langpackId}`,
        )
      );
    }

    Services.obs.notifyObservers(
    }
      { wrappedJSObject: { langpack: this } },
      "webextension-langpack-startup"
    );
  }
      "webextension-langpack-startup"

  async shutdown(reason) {
    if (reason === "APP_SHUTDOWN") {
      // If we're shutting down, let's not bother updating the state of each
      // system.
    if (reason === "APP_SHUTDOWN") {
      return;
    }
    for (const sourceName of Object.keys(
      this.startupData.l10nRegistrySources
    )) {
    for (const sourceName of Object.keys(
      L10nRegistry.removeSource(`${sourceName}-${this.startupData.langpackId}`);
    }
    if (this.chromeRegistryHandle) {
      this.chromeRegistryHandle.destruct();
      this.chromeRegistryHandle = null;
    if (this.chromeRegistryHandle) {
    }

    resourceProtocol.setSubstitution(this.startupData.langpackId, null);
  }
}
    resourceProtocol.setSubstitution(this.startupData.langpackId, null);