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

use std::borrow::Cow;
use std::cell::{Cell, OnceCell};
use std::collections::hash_map::Entry;
use std::collections::{HashMap, VecDeque};
use std::ops::Index;
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::thread::JoinHandle;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use std::{mem, ptr};

use base::id::{
    BlobId, BroadcastChannelRouterId, MessagePortId, MessagePortRouterId, PipelineId,
    ServiceWorkerId, ServiceWorkerRegistrationId,
};
use content_security_policy::{CheckResult, CspList, PolicyDisposition};
use crossbeam_channel::Sender;
use devtools_traits::{PageError, ScriptToDevtoolsControlMsg};
use dom_struct::dom_struct;
use embedder_traits::EmbedderMsg;
use ipc_channel::ipc::{self, IpcSender};
use ipc_channel::router::ROUTER;
use js::glue::{IsWrapper, UnwrapObjectDynamic};
use js::jsapi::{
    Compile1, CurrentGlobalOrNull, GetNonCCWObjectGlobal, HandleObject, Heap,
    InstantiateGlobalStencil, InstantiateOptions, JSContext, JSObject, JSScript, RuntimeCode,
    SetScriptPrivate,
};
use js::jsval::{PrivateValue, UndefinedValue};
use js::panic::maybe_resume_unwind;
use js::rust::wrappers::{JS_ExecuteScript, JS_GetScriptPrivate};
use js::rust::{
    describe_scripted_caller, get_object_class, transform_str_to_source_text,
    CompileOptionsWrapper, CustomAutoRooter, CustomAutoRooterGuard, HandleValue,
    MutableHandleValue, ParentRuntime, Runtime,
};
use js::{JSCLASS_IS_DOMJSCLASS, JSCLASS_IS_GLOBAL};
use net_traits::blob_url_store::{get_blob_origin, BlobBuf};
use net_traits::filemanager_thread::{
    FileManagerResult, FileManagerThreadMsg, ReadFileProgress, RelativePos,
};
use net_traits::image_cache::ImageCache;
use net_traits::policy_container::PolicyContainer;
use net_traits::request::{Referrer, RequestBuilder};
use net_traits::response::HttpsState;
use net_traits::{
    fetch_async, CoreResourceMsg, CoreResourceThread, FetchResponseListener, IpcSend,
    ReferrerPolicy, ResourceThreads,
};
use profile_traits::{ipc as profile_ipc, mem as profile_mem, time as profile_time};
use script_traits::serializable::{BlobData, BlobImpl, FileBlob};
use script_traits::transferable::MessagePortImpl;
use script_traits::{
    BroadcastMsg, GamepadEvent, GamepadSupportedHapticEffects, GamepadUpdateType, MessagePortMsg,
    PortMessageTask, ScriptMsg, ScriptToConstellationChan, TimerEvent, TimerEventId,
    TimerSchedulerMsg, TimerSource,
};
use servo_url::{ImmutableOrigin, MutableOrigin, ServoUrl};
use uuid::Uuid;
#[cfg(feature = "webgpu")]
use webgpu::{DeviceLostReason, WebGPUDevice};

use super::bindings::codegen::Bindings::MessagePortBinding::StructuredSerializeOptions;
#[cfg(feature = "webgpu")]
use super::bindings::codegen::Bindings::WebGPUBinding::GPUDeviceLostReason;
use super::bindings::error::Fallible;
use super::bindings::trace::{HashMapTracedValues, RootedTraceableBox};
use crate::dom::bindings::cell::{DomRefCell, RefMut};
use crate::dom::bindings::codegen::Bindings::BroadcastChannelBinding::BroadcastChannelMethods;
use crate::dom::bindings::codegen::Bindings::EventSourceBinding::EventSource_Binding::EventSourceMethods;
use crate::dom::bindings::codegen::Bindings::FunctionBinding::Function;
use crate::dom::bindings::codegen::Bindings::ImageBitmapBinding::{
    ImageBitmapOptions, ImageBitmapSource,
};
use crate::dom::bindings::codegen::Bindings::NavigatorBinding::NavigatorMethods;
use crate::dom::bindings::codegen::Bindings::PerformanceBinding::Performance_Binding::PerformanceMethods;
use crate::dom::bindings::codegen::Bindings::PermissionStatusBinding::PermissionState;
use crate::dom::bindings::codegen::Bindings::VoidFunctionBinding::VoidFunction;
use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use crate::dom::bindings::codegen::Bindings::WorkerGlobalScopeBinding::WorkerGlobalScopeMethods;
use crate::dom::bindings::conversions::{root_from_object, root_from_object_static};
use crate::dom::bindings::error::{report_pending_exception, Error, ErrorInfo};
use crate::dom::bindings::frozenarray::CachedFrozenArray;
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::refcounted::{Trusted, TrustedPromise};
use crate::dom::bindings::reflector::DomObject;
use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
use crate::dom::bindings::settings_stack::{entry_global, incumbent_global, AutoEntryScript};
use crate::dom::bindings::str::DOMString;
use crate::dom::bindings::structuredclone;
use crate::dom::bindings::trace::CustomTraceable;
use crate::dom::bindings::weakref::{DOMTracker, WeakRef};
use crate::dom::blob::Blob;
use crate::dom::broadcastchannel::BroadcastChannel;
use crate::dom::crypto::Crypto;
use crate::dom::dedicatedworkerglobalscope::{
    DedicatedWorkerControlMsg, DedicatedWorkerGlobalScope,
};
use crate::dom::errorevent::ErrorEvent;
use crate::dom::event::{Event, EventBubbles, EventCancelable, EventStatus};
use crate::dom::eventsource::EventSource;
use crate::dom::eventtarget::EventTarget;
use crate::dom::file::File;
use crate::dom::gamepad::{contains_user_gesture, Gamepad};
use crate::dom::gamepadevent::GamepadEventType;
use crate::dom::htmlscriptelement::{ScriptId, SourceCode};
use crate::dom::imagebitmap::ImageBitmap;
use crate::dom::messageevent::MessageEvent;
use crate::dom::messageport::MessagePort;
use crate::dom::paintworkletglobalscope::PaintWorkletGlobalScope;
use crate::dom::performance::Performance;
use crate::dom::performanceobserver::VALID_ENTRY_TYPES;
use crate::dom::promise::Promise;
use crate::dom::readablestream::ReadableStream;
use crate::dom::serviceworker::ServiceWorker;
use crate::dom::serviceworkerregistration::ServiceWorkerRegistration;
use crate::dom::underlyingsourcecontainer::UnderlyingSourceType;
#[cfg(feature = "webgpu")]
use crate::dom::webgpu::gpudevice::GPUDevice;
#[cfg(feature = "webgpu")]
use crate::dom::webgpu::identityhub::IdentityHub;
use crate::dom::window::Window;
use crate::dom::workerglobalscope::WorkerGlobalScope;
use crate::dom::workletglobalscope::WorkletGlobalScope;
use crate::microtask::{Microtask, MicrotaskQueue, UserMicrotask};
use crate::network_listener::{NetworkListener, PreInvoke};
use crate::realms::{enter_realm, AlreadyInRealm, InRealm};
use crate::script_module::{DynamicModuleList, ModuleScript, ModuleTree, ScriptFetchOptions};
use crate::script_runtime::{
    CanGc, CommonScriptMsg, JSContext as SafeJSContext, ScriptChan, ScriptPort, ThreadSafeJSContext,
};
use crate::script_thread::{MainThreadScriptChan, ScriptThread};
use crate::security_manager::CSPViolationReporter;
use crate::task::TaskCanceller;
use crate::task_source::dom_manipulation::DOMManipulationTaskSource;
use crate::task_source::file_reading::FileReadingTaskSource;
use crate::task_source::gamepad::GamepadTaskSource;
use crate::task_source::networking::NetworkingTaskSource;
use crate::task_source::performance_timeline::PerformanceTimelineTaskSource;
use crate::task_source::port_message::PortMessageQueue;
use crate::task_source::remote_event::RemoteEventTaskSource;
use crate::task_source::timer::TimerTaskSource;
use crate::task_source::websocket::WebsocketTaskSource;
use crate::task_source::{TaskSource, TaskSourceName};
use crate::timers::{
    IsInterval, OneshotTimerCallback, OneshotTimerHandle, OneshotTimers, TimerCallback,
};
use crate::unminify::unminified_path;

#[derive(JSTraceable)]
pub struct AutoCloseWorker {
    /// <https://html.spec.whatwg.org/multipage/#dom-workerglobalscope-closing>
    closing: Arc<AtomicBool>,
    /// A handle to join on the worker thread.
    join_handle: Option<JoinHandle<()>>,
    /// A sender of control messages,
    /// currently only used to signal shutdown.
    #[no_trace]
    control_sender: Sender<DedicatedWorkerControlMsg>,
    /// The context to request an interrupt on the worker thread.
    #[no_trace]
    context: ThreadSafeJSContext,
}

impl Drop for AutoCloseWorker {
    /// <https://html.spec.whatwg.org/multipage/#terminate-a-worker>
    fn drop(&mut self) {
        // Step 1.
        self.closing.store(true, Ordering::SeqCst);

        if self
            .control_sender
            .send(DedicatedWorkerControlMsg::Exit)
            .is_err()
        {
            warn!("Couldn't send an exit message to a dedicated worker.");
        }

        self.context.request_interrupt_callback();

        // TODO: step 2 and 3.
        // Step 4 is unnecessary since we don't use actual ports for dedicated workers.
        if self
            .join_handle
            .take()
            .expect("No handle to join on worker.")
            .join()
            .is_err()
        {
            warn!("Failed to join on dedicated worker thread.");
        }
    }
}

#[dom_struct]
pub struct GlobalScope {
    eventtarget: EventTarget,
    crypto: MutNullableDom<Crypto>,

    /// The message-port router id for this global, if it is managing ports.
    message_port_state: DomRefCell<MessagePortState>,

    /// The broadcast channels state this global, if it is managing any.
    broadcast_channel_state: DomRefCell<BroadcastChannelState>,

    /// The blobs managed by this global, if any.
    blob_state: DomRefCell<BlobState>,

    /// <https://w3c.github.io/ServiceWorker/#environment-settings-object-service-worker-registration-object-map>
    registration_map: DomRefCell<
        HashMapTracedValues<ServiceWorkerRegistrationId, Dom<ServiceWorkerRegistration>>,
    >,

    /// <https://w3c.github.io/ServiceWorker/#environment-settings-object-service-worker-object-map>
    worker_map: DomRefCell<HashMapTracedValues<ServiceWorkerId, Dom<ServiceWorker>>>,

    /// Pipeline id associated with this global.
    #[no_trace]
    pipeline_id: PipelineId,

    /// A flag to indicate whether the developer tools has requested
    /// live updates from the worker.
    devtools_wants_updates: Cell<bool>,

    /// Timers (milliseconds) used by the Console API.
    console_timers: DomRefCell<HashMap<DOMString, Instant>>,

    /// module map is used when importing JavaScript modules
    /// <https://html.spec.whatwg.org/multipage/#concept-settings-object-module-map>
    #[ignore_malloc_size_of = "mozjs"]
    module_map: DomRefCell<HashMapTracedValues<ServoUrl, Rc<ModuleTree>>>,

    #[ignore_malloc_size_of = "mozjs"]
    inline_module_map: DomRefCell<HashMap<ScriptId, Rc<ModuleTree>>>,

    /// For providing instructions to an optional devtools server.
    #[ignore_malloc_size_of = "channels are hard"]
    #[no_trace]
    devtools_chan: Option<IpcSender<ScriptToDevtoolsControlMsg>>,

    /// For sending messages to the memory profiler.
    #[ignore_malloc_size_of = "channels are hard"]
    #[no_trace]
    mem_profiler_chan: profile_mem::ProfilerChan,

    /// For sending messages to the time profiler.
    #[ignore_malloc_size_of = "channels are hard"]
    #[no_trace]
    time_profiler_chan: profile_time::ProfilerChan,

    /// A handle for communicating messages to the constellation thread.
    #[ignore_malloc_size_of = "channels are hard"]
    #[no_trace]
    script_to_constellation_chan: ScriptToConstellationChan,

    #[ignore_malloc_size_of = "channels are hard"]
    #[no_trace]
    scheduler_chan: IpcSender<TimerSchedulerMsg>,

    /// <https://html.spec.whatwg.org/multipage/#in-error-reporting-mode>
    in_error_reporting_mode: Cell<bool>,

    /// Associated resource threads for use by DOM objects like XMLHttpRequest,
    /// including resource_thread, filemanager_thread and storage_thread
    #[no_trace]
    resource_threads: ResourceThreads,

    /// The mechanism by which time-outs and intervals are scheduled.
    /// <https://html.spec.whatwg.org/multipage/#timers>
    timers: OneshotTimers,

    /// Have timers been initialized?
    init_timers: Cell<bool>,

    /// The origin of the globalscope
    #[no_trace]
    origin: MutableOrigin,

    /// <https://html.spec.whatwg.org/multipage/#concept-environment-creation-url>
    #[no_trace]
    creation_url: Option<ServoUrl>,

    /// A map for storing the previous permission state read results.
    permission_state_invocation_results: DomRefCell<HashMap<String, PermissionState>>,

    /// The microtask queue associated with this global.
    ///
    /// It is refcounted because windows in the same script thread share the
    /// same microtask queue.
    ///
    /// <https://html.spec.whatwg.org/multipage/#microtask-queue>
    #[ignore_malloc_size_of = "Rc<T> is hard"]
    microtask_queue: Rc<MicrotaskQueue>,

    /// Vector storing closing references of all workers
    #[ignore_malloc_size_of = "Arc"]
    list_auto_close_worker: DomRefCell<Vec<AutoCloseWorker>>,

    /// Vector storing references of all eventsources.
    event_source_tracker: DOMTracker<EventSource>,

    /// Storage for watching rejected promises waiting for some client to
    /// consume their rejection.
    /// Promises in this list have been rejected in the last turn of the
    /// event loop without the rejection being handled.
    /// Note that this can contain nullptrs in place of promises removed because
    /// they're consumed before it'd be reported.
    ///
    /// <https://html.spec.whatwg.org/multipage/#about-to-be-notified-rejected-promises-list>
    #[ignore_malloc_size_of = "mozjs"]
    // `Heap` values must stay boxed, as they need semantics like `Pin`
    // (that is, they cannot be moved).
    #[allow(clippy::vec_box)]
    uncaught_rejections: DomRefCell<Vec<Box<Heap<*mut JSObject>>>>,

    /// Promises in this list have previously been reported as rejected
    /// (because they were in the above list), but the rejection was handled
    /// in the last turn of the event loop.
    ///
    /// <https://html.spec.whatwg.org/multipage/#outstanding-rejected-promises-weak-set>
    #[ignore_malloc_size_of = "mozjs"]
    // `Heap` values must stay boxed, as they need semantics like `Pin`
    // (that is, they cannot be moved).
    #[allow(clippy::vec_box)]
    consumed_rejections: DomRefCell<Vec<Box<Heap<*mut JSObject>>>>,

    /// True if headless mode.
    is_headless: bool,

    /// An optional string allowing the user agent to be set for testing.
    user_agent: Cow<'static, str>,

    /// Identity Manager for WebGPU resources
    #[ignore_malloc_size_of = "defined in wgpu"]
    #[no_trace]
    #[cfg(feature = "webgpu")]
    gpu_id_hub: Arc<IdentityHub>,

    /// WebGPU devices
    #[cfg(feature = "webgpu")]
    gpu_devices: DomRefCell<HashMapTracedValues<WebGPUDevice, WeakRef<GPUDevice>>>,

    // https://w3c.github.io/performance-timeline/#supportedentrytypes-attribute
    #[ignore_malloc_size_of = "mozjs"]
    frozen_supported_performance_entry_types: CachedFrozenArray,

    /// currect https state (from previous request)
    #[no_trace]
    https_state: Cell<HttpsState>,

    /// The stack of active group labels for the Console APIs.
    console_group_stack: DomRefCell<Vec<DOMString>>,

    /// The count map for the Console APIs.
    ///
    /// <https://console.spec.whatwg.org/#count>
    console_count_map: DomRefCell<HashMap<DOMString, usize>>,

    /// List of ongoing dynamic module imports.
    dynamic_modules: DomRefCell<DynamicModuleList>,

    /// Is considered in a secure context
    inherited_secure_context: Option<bool>,

    /// Directory to store unminified scripts for this window if unminify-js
    /// opt is enabled.
    unminified_js_dir: Option<String>,

    /// The byte length queuing strategy size function that will be initialized once
    /// `size` getter of `ByteLengthQueuingStrategy` is called.
    ///
    /// <https://streams.spec.whatwg.org/#byte-length-queuing-strategy-size-function>
    #[ignore_malloc_size_of = "Rc<T> is hard"]
    byte_length_queuing_strategy_size_function: OnceCell<Rc<Function>>,

    /// The count queuing strategy size function that will be initialized once
    /// `size` getter of `CountQueuingStrategy` is called.
    ///
    /// <https://streams.spec.whatwg.org/#count-queuing-strategy-size-function>
    #[ignore_malloc_size_of = "Rc<T> is hard"]
    count_queuing_strategy_size_function: OnceCell<Rc<Function>>,
}

/// A wrapper for glue-code between the ipc router and the event-loop.
struct MessageListener {
    canceller: TaskCanceller,
    task_source: PortMessageQueue,
    context: Trusted<GlobalScope>,
}

/// A wrapper for broadcasts coming in over IPC, and the event-loop.
struct BroadcastListener {
    canceller: TaskCanceller,
    task_source: DOMManipulationTaskSource,
    context: Trusted<GlobalScope>,
}

/// A wrapper between timer events coming in over IPC, and the event-loop.
struct TimerListener {
    canceller: TaskCanceller,
    task_source: TimerTaskSource,
    context: Trusted<GlobalScope>,
}

type FileListenerCallback = Box<dyn Fn(Rc<Promise>, Fallible<Vec<u8>>) + Send>;

/// A wrapper for the handling of file data received by the ipc router
struct FileListener {
    /// State should progress as either of:
    /// - Some(Empty) => Some(Receiving) => None
    /// - Some(Empty) => None
    state: Option<FileListenerState>,
    task_source: FileReadingTaskSource,
    task_canceller: TaskCanceller,
}

enum FileListenerTarget {
    Promise(TrustedPromise, FileListenerCallback),
    Stream(Trusted<ReadableStream>),
}

enum FileListenerState {
    Empty(FileListenerTarget),
    Receiving(Vec<u8>, FileListenerTarget),
}

#[derive(JSTraceable, MallocSizeOf)]
/// A holder of a weak reference for a DOM blob or file.
pub enum BlobTracker {
    /// A weak ref to a DOM file.
    File(WeakRef<File>),
    /// A weak ref to a DOM blob.
    Blob(WeakRef<Blob>),
}

#[derive(JSTraceable, MallocSizeOf)]
/// The info pertaining to a blob managed by this global.
pub struct BlobInfo {
    /// The weak ref to the corresponding DOM object.
    tracker: BlobTracker,
    /// The data and logic backing the DOM object.
    #[no_trace]
    blob_impl: BlobImpl,
    /// Whether this blob has an outstanding URL,
    /// <https://w3c.github.io/FileAPI/#url>.
    has_url: bool,
}

/// State representing whether this global is currently managing blobs.
#[derive(JSTraceable, MallocSizeOf)]
pub enum BlobState {
    /// A map of managed blobs.
    Managed(HashMapTracedValues<BlobId, BlobInfo>),
    /// This global is not managing any blobs at this time.
    UnManaged,
}

/// The result of looking-up the data for a Blob,
/// containing either the in-memory bytes,
/// or the file-id.
enum BlobResult {
    Bytes(Vec<u8>),
    File(Uuid, usize),
}

/// Data representing a message-port managed by this global.
#[derive(JSTraceable, MallocSizeOf)]
#[crown::unrooted_must_root_lint::must_root]
pub struct ManagedMessagePort {
    /// The DOM port.
    dom_port: Dom<MessagePort>,
    /// The logic and data backing the DOM port.
    /// The option is needed to take out the port-impl
    /// as part of its transferring steps,
    /// without having to worry about rooting the dom-port.
    #[no_trace]
    port_impl: Option<MessagePortImpl>,
    /// We keep ports pending when they are first transfer-received,
    /// and only add them, and ask the constellation to complete the transfer,
    /// in a subsequent task if the port hasn't been re-transfered.
    pending: bool,
    /// Has the port been closed? If closed, it can be dropped and later GC'ed.
    closed: bool,
}

/// State representing whether this global is currently managing broadcast channels.
#[derive(JSTraceable, MallocSizeOf)]
#[crown::unrooted_must_root_lint::must_root]
pub enum BroadcastChannelState {
    /// The broadcast-channel router id for this global, and a queue of managed channels.
    /// Step 9, "sort destinations"
    /// of <https://html.spec.whatwg.org/multipage/#dom-broadcastchannel-postmessage>
    /// requires keeping track of creation order, hence the queue.
    Managed(
        #[no_trace] BroadcastChannelRouterId,
        /// The map of channel-name to queue of channels, in order of creation.
        HashMap<DOMString, VecDeque<Dom<BroadcastChannel>>>,
    ),
    /// This global is not managing any broadcast channels at this time.
    UnManaged,
}

/// State representing whether this global is currently managing messageports.
#[derive(JSTraceable, MallocSizeOf)]
#[crown::unrooted_must_root_lint::must_root]
pub enum MessagePortState {
    /// The message-port router id for this global, and a map of managed ports.
    Managed(
        #[no_trace] MessagePortRouterId,
        HashMapTracedValues<MessagePortId, ManagedMessagePort>,
    ),
    /// This global is not managing any ports at this time.
    UnManaged,
}

impl BroadcastListener {
    /// Handle a broadcast coming in over IPC,
    /// by queueing the appropriate task on the relevant event-loop.
    fn handle(&self, event: BroadcastMsg) {
        let context = self.context.clone();

        // Note: strictly speaking we should just queue the message event tasks,
        // not queue a task that then queues more tasks.
        // This however seems to be hard to avoid in the light of the IPC.
        // One can imagine queueing tasks directly,
        // for channels that would be in the same script-thread.
        let _ = self.task_source.queue_with_canceller(
            task!(broadcast_message_event: move || {
                let global = context.root();
                // Step 10 of https://html.spec.whatwg.org/multipage/#dom-broadcastchannel-postmessage,
                // For each BroadcastChannel object destination in destinations, queue a task.
                global.broadcast_message_event(event, None);
            }),
            &self.canceller,
        );
    }
}

impl TimerListener {
    /// Handle a timer-event coming-in over IPC,
    /// by queuing the appropriate task on the relevant event-loop.
    fn handle(&self, event: TimerEvent) {
        let context = self.context.clone();
        // Step 18, queue a task,
        // https://html.spec.whatwg.org/multipage/#timer-initialisation-steps
        let _ = self.task_source.queue_with_canceller(
            task!(timer_event: move || {
                let global = context.root();
                let TimerEvent(source, id) = event;
                match source {
                    TimerSource::FromWorker => {
                        global.downcast::<WorkerGlobalScope>().expect("Window timer delivered to worker");
                    },
                    TimerSource::FromWindow(pipeline) => {
                        assert_eq!(pipeline, global.pipeline_id());
                        global.downcast::<Window>().expect("Worker timer delivered to window");
                    },
                };
                // Step 7, substeps run in a task.
                global.fire_timer(id, CanGc::note());
            }),
            &self.canceller,
        );
    }
}

impl MessageListener {
    /// A new message came in, handle it via a task enqueued on the event-loop.
    /// A task is required, since we are using a trusted globalscope,
    /// and we can only access the root from the event-loop.
    fn notify(&self, msg: MessagePortMsg) {
        match msg {
            MessagePortMsg::CompleteTransfer(ports) => {
                let context = self.context.clone();
                let _ = self.task_source.queue_with_canceller(
                    task!(process_complete_transfer: move || {
                        let global = context.root();

                        let router_id = match global.port_router_id() {
                            Some(router_id) => router_id,
                            None => {
                                // If not managing any ports, no transfer can succeed,
                                // so just send back everything.
                                let _ = global.script_to_constellation_chan().send(
                                    ScriptMsg::MessagePortTransferResult(None, vec![], ports),
                                );
                                return;
                            }
                        };

                        let mut succeeded = vec![];
                        let mut failed = HashMap::new();

                        for (id, buffer) in ports.into_iter() {
                            if global.is_managing_port(&id) {
                                succeeded.push(id);
                                global.complete_port_transfer(id, buffer);
                            } else {
                                failed.insert(id, buffer);
                            }
                        }
                        let _ = global.script_to_constellation_chan().send(
                            ScriptMsg::MessagePortTransferResult(Some(router_id), succeeded, failed),
                        );
                    }),
                    &self.canceller,
                );
            },
            MessagePortMsg::CompletePendingTransfer(port_id, buffer) => {
                let context = self.context.clone();
                let _ = self.task_source.queue_with_canceller(
                    task!(complete_pending: move || {
                        let global = context.root();
                        global.complete_port_transfer(port_id, buffer);
                    }),
                    &self.canceller,
                );
            },
            MessagePortMsg::NewTask(port_id, task) => {
                let context = self.context.clone();
                let _ = self.task_source.queue_with_canceller(
                    task!(process_new_task: move || {
                        let global = context.root();
                        global.route_task_to_port(port_id, task, CanGc::note());
                    }),
                    &self.canceller,
                );
            },
            MessagePortMsg::RemoveMessagePort(port_id) => {
                let context = self.context.clone();
                let _ = self.task_source.queue_with_canceller(
                    task!(process_remove_message_port: move || {
                        let global = context.root();
                        global.note_entangled_port_removed(&port_id);
                    }),
                    &self.canceller,
                );
            },
        }
    }
}

/// Callback used to enqueue file chunks to streams as part of FileListener.
fn stream_handle_incoming(stream: &ReadableStream, bytes: Fallible<Vec<u8>>) {
    match bytes {
        Ok(b) => {
            stream.enqueue_native(b);
        },
        Err(e) => {
            stream.error_native(e);
        },
    }
}

/// Callback used to close streams as part of FileListener.
fn stream_handle_eof(stream: &ReadableStream) {
    stream.controller_close_native();
}

impl FileListener {
    fn handle(&mut self, msg: FileManagerResult<ReadFileProgress>) {
        match msg {
            Ok(ReadFileProgress::Meta(blob_buf)) => match self.state.take() {
                Some(FileListenerState::Empty(target)) => {
                    let bytes = if let FileListenerTarget::Stream(ref trusted_stream) = target {
                        let trusted = trusted_stream.clone();

                        let task = task!(enqueue_stream_chunk: move || {
                            let stream = trusted.root();
                            stream_handle_incoming(&stream, Ok(blob_buf.bytes));
                        });

                        let _ = self
                            .task_source
                            .queue_with_canceller(task, &self.task_canceller);
                        Vec::with_capacity(0)
                    } else {
                        blob_buf.bytes
                    };

                    self.state = Some(FileListenerState::Receiving(bytes, target));
                },
                _ => panic!(
                    "Unexpected FileListenerState when receiving ReadFileProgress::Meta msg."
                ),
            },
            Ok(ReadFileProgress::Partial(mut bytes_in)) => match self.state.take() {
                Some(FileListenerState::Receiving(mut bytes, target)) => {
                    if let FileListenerTarget::Stream(ref trusted_stream) = target {
                        let trusted = trusted_stream.clone();

                        let task = task!(enqueue_stream_chunk: move || {
                            let stream = trusted.root();
                            stream_handle_incoming(&stream, Ok(bytes_in));
                        });

                        let _ = self
                            .task_source
                            .queue_with_canceller(task, &self.task_canceller);
                    } else {
                        bytes.append(&mut bytes_in);
                    };

                    self.state = Some(FileListenerState::Receiving(bytes, target));
                },
                _ => panic!(
                    "Unexpected FileListenerState when receiving ReadFileProgress::Partial msg."
                ),
            },
            Ok(ReadFileProgress::EOF) => match self.state.take() {
                Some(FileListenerState::Receiving(bytes, target)) => match target {
                    FileListenerTarget::Promise(trusted_promise, callback) => {
                        let task = task!(resolve_promise: move || {
                            let promise = trusted_promise.root();
                            let _ac = enter_realm(&*promise.global());
                            callback(promise, Ok(bytes));
                        });

                        let _ = self
                            .task_source
                            .queue_with_canceller(task, &self.task_canceller);
                    },
                    FileListenerTarget::Stream(trusted_stream) => {
                        let trusted = trusted_stream.clone();

                        let task = task!(enqueue_stream_chunk: move || {
                            let stream = trusted.root();
                            stream_handle_eof(&stream);
                        });

                        let _ = self
                            .task_source
                            .queue_with_canceller(task, &self.task_canceller);
                    },
                },
                _ => {
                    panic!("Unexpected FileListenerState when receiving ReadFileProgress::EOF msg.")
                },
            },
            Err(_) => match self.state.take() {
                Some(FileListenerState::Receiving(_, target)) |
                Some(FileListenerState::Empty(target)) => {
                    let error = Err(Error::Network);

                    match target {
                        FileListenerTarget::Promise(trusted_promise, callback) => {
                            let _ = self.task_source.queue_with_canceller(
                                task!(reject_promise: move || {
                                    let promise = trusted_promise.root();
                                    let _ac = enter_realm(&*promise.global());
                                    callback(promise, error);
                                }),
                                &self.task_canceller,
                            );
                        },
                        FileListenerTarget::Stream(trusted_stream) => {
                            let _ = self.task_source.queue_with_canceller(
                                task!(error_stream: move || {
                                    let stream = trusted_stream.root();
                                    stream_handle_incoming(&stream, error);
                                }),
                                &self.task_canceller,
                            );
                        },
                    }
                },
                _ => panic!("Unexpected FileListenerState when receiving Err msg."),
            },
        }
    }
}

impl GlobalScope {
    #[allow(clippy::too_many_arguments)]
    pub fn new_inherited(
        pipeline_id: PipelineId,
        devtools_chan: Option<IpcSender<ScriptToDevtoolsControlMsg>>,
        mem_profiler_chan: profile_mem::ProfilerChan,
        time_profiler_chan: profile_time::ProfilerChan,
        script_to_constellation_chan: ScriptToConstellationChan,
        scheduler_chan: IpcSender<TimerSchedulerMsg>,
        resource_threads: ResourceThreads,
        origin: MutableOrigin,
        creation_url: Option<ServoUrl>,
        microtask_queue: Rc<MicrotaskQueue>,
        is_headless: bool,
        user_agent: Cow<'static, str>,
        #[cfg(feature = "webgpu")] gpu_id_hub: Arc<IdentityHub>,
        inherited_secure_context: Option<bool>,
        unminify_js: bool,
    ) -> Self {
        Self {
            message_port_state: DomRefCell::new(MessagePortState::UnManaged),
            broadcast_channel_state: DomRefCell::new(BroadcastChannelState::UnManaged),
            blob_state: DomRefCell::new(BlobState::UnManaged),
            eventtarget: EventTarget::new_inherited(),
            crypto: Default::default(),
            registration_map: DomRefCell::new(HashMapTracedValues::new()),
            worker_map: DomRefCell::new(HashMapTracedValues::new()),
            pipeline_id,
            devtools_wants_updates: Default::default(),
            console_timers: DomRefCell::new(Default::default()),
            module_map: DomRefCell::new(Default::default()),
            inline_module_map: DomRefCell::new(Default::default()),
            devtools_chan,
            mem_profiler_chan,
            time_profiler_chan,
            script_to_constellation_chan,
            scheduler_chan: scheduler_chan.clone(),
            in_error_reporting_mode: Default::default(),
            resource_threads,
            timers: OneshotTimers::new(scheduler_chan),
            init_timers: Default::default(),
            origin,
            creation_url,
            permission_state_invocation_results: Default::default(),
            microtask_queue,
            list_auto_close_worker: Default::default(),
            event_source_tracker: DOMTracker::new(),
            uncaught_rejections: Default::default(),
            consumed_rejections: Default::default(),
            is_headless,
            user_agent,
            #[cfg(feature = "webgpu")]
            gpu_id_hub,
            #[cfg(feature = "webgpu")]
            gpu_devices: DomRefCell::new(HashMapTracedValues::new()),
            frozen_supported_performance_entry_types: CachedFrozenArray::new(),
            https_state: Cell::new(HttpsState::None),
            console_group_stack: DomRefCell::new(Vec::new()),
            console_count_map: Default::default(),
            dynamic_modules: DomRefCell::new(DynamicModuleList::new()),
            inherited_secure_context,
            unminified_js_dir: unminify_js.then(|| unminified_path("unminified-js")),
            byte_length_queuing_strategy_size_function: OnceCell::new(),
            count_queuing_strategy_size_function: OnceCell::new(),
        }
    }

    /// The message-port router Id of the global, if any
    fn port_router_id(&self) -> Option<MessagePortRouterId> {
        if let MessagePortState::Managed(id, _message_ports) = &*self.message_port_state.borrow() {
            Some(*id)
        } else {
            None
        }
    }

    /// Is this global managing a given port?
    fn is_managing_port(&self, port_id: &MessagePortId) -> bool {
        if let MessagePortState::Managed(_router_id, message_ports) =
            &*self.message_port_state.borrow()
        {
            return message_ports.contains_key(port_id);
        }
        false
    }

    /// Setup the IPC-to-event-loop glue for timers to schedule themselves.
    fn setup_timers(&self) {
        if self.init_timers.get() {
            return;
        }
        self.init_timers.set(true);

        let (timer_ipc_chan, timer_ipc_port) = ipc::channel().unwrap();
        self.timers.setup_scheduling(timer_ipc_chan);

        // Setup route from IPC to task-queue for the timer-task-source.
        let context = Trusted::new(self);
        let (task_source, canceller) = (
            self.timer_task_source(),
            self.task_canceller(TaskSourceName::Timer),
        );
        let timer_listener = TimerListener {
            context,
            task_source,
            canceller,
        };
        ROUTER.add_typed_route(
            timer_ipc_port,
            Box::new(move |message| {
                let event = message.unwrap();
                timer_listener.handle(event);
            }),
        );
    }

    /// <https://w3c.github.io/ServiceWorker/#get-the-service-worker-registration-object>
    pub fn get_serviceworker_registration(
        &self,
        script_url: &ServoUrl,
        scope: &ServoUrl,
        registration_id: ServiceWorkerRegistrationId,
        installing_worker: Option<ServiceWorkerId>,
        _waiting_worker: Option<ServiceWorkerId>,
        _active_worker: Option<ServiceWorkerId>,
    ) -> DomRoot<ServiceWorkerRegistration> {
        // Step 1
        let mut registrations = self.registration_map.borrow_mut();

        if let Some(registration) = registrations.get(&registration_id) {
            // Step 3
            return DomRoot::from_ref(&**registration);
        }

        // Step 2.1 -> 2.5
        let new_registration = ServiceWorkerRegistration::new(self, scope.clone(), registration_id);

        // Step 2.6
        if let Some(worker_id) = installing_worker {
            let worker = self.get_serviceworker(script_url, scope, worker_id);
            new_registration.set_installing(&worker);
        }

        // TODO: 2.7 (waiting worker)

        // TODO: 2.8 (active worker)

        // Step 2.9
        registrations.insert(registration_id, Dom::from_ref(&*new_registration));

        // Step 3
        new_registration
    }

    /// <https://w3c.github.io/ServiceWorker/#get-the-service-worker-object>
    pub fn get_serviceworker(
        &self,
        script_url: &ServoUrl,
        scope: &ServoUrl,
        worker_id: ServiceWorkerId,
    ) -> DomRoot<ServiceWorker> {
        // Step 1
        let mut workers = self.worker_map.borrow_mut();

        if let Some(worker) = workers.get(&worker_id) {
            // Step 3
            DomRoot::from_ref(&**worker)
        } else {
            // Step 2.1
            // TODO: step 2.2, worker state.
            let new_worker = ServiceWorker::new(self, script_url.clone(), scope.clone(), worker_id);

            // Step 2.3
            workers.insert(worker_id, Dom::from_ref(&*new_worker));

            // Step 3
            new_worker
        }
    }

    /// Complete the transfer of a message-port.
    fn complete_port_transfer(&self, port_id: MessagePortId, tasks: VecDeque<PortMessageTask>) {
        let should_start = if let MessagePortState::Managed(_id, message_ports) =
            &mut *self.message_port_state.borrow_mut()
        {
            match message_ports.get_mut(&port_id) {
                None => {
                    panic!("complete_port_transfer called for an unknown port.");
                },
                Some(managed_port) => {
                    if managed_port.pending {
                        panic!("CompleteTransfer msg received for a pending port.");
                    }
                    if let Some(port_impl) = managed_port.port_impl.as_mut() {
                        port_impl.complete_transfer(tasks);
                        port_impl.enabled()
                    } else {
                        panic!("managed-port has no port-impl.");
                    }
                },
            }
        } else {
            panic!("complete_port_transfer called for an unknown port.");
        };
        if should_start {
            self.start_message_port(&port_id);
        }
    }

    /// Clean-up DOM related resources
    pub fn perform_a_dom_garbage_collection_checkpoint(&self) {
        self.perform_a_message_port_garbage_collection_checkpoint();
        self.perform_a_blob_garbage_collection_checkpoint();
        self.perform_a_broadcast_channel_garbage_collection_checkpoint();
    }

    /// Remove the routers for ports and broadcast-channels.
    /// Drain the list of workers.
    pub fn remove_web_messaging_and_dedicated_workers_infra(&self) {
        self.remove_message_ports_router();
        self.remove_broadcast_channel_router();

        // Drop each ref to a worker explicitly now,
        // which will send a shutdown signal,
        // and join on the worker thread.
        self.list_auto_close_worker
            .borrow_mut()
            .drain(0..)
            .for_each(drop);
    }

    /// Update our state to un-managed,
    /// and tell the constellation to drop the sender to our message-port router.
    fn remove_message_ports_router(&self) {
        if let MessagePortState::Managed(router_id, _message_ports) =
            &*self.message_port_state.borrow()
        {
            let _ = self
                .script_to_constellation_chan()
                .send(ScriptMsg::RemoveMessagePortRouter(*router_id));
        }
        *self.message_port_state.borrow_mut() = MessagePortState::UnManaged;
    }

    /// Update our state to un-managed,
    /// and tell the constellation to drop the sender to our broadcast router.
    fn remove_broadcast_channel_router(&self) {
        if let BroadcastChannelState::Managed(router_id, _channels) =
            &*self.broadcast_channel_state.borrow()
        {
            let _ =
                self.script_to_constellation_chan()
                    .send(ScriptMsg::RemoveBroadcastChannelRouter(
                        *router_id,
                        self.origin().immutable().clone(),
                    ));
        }
        *self.broadcast_channel_state.borrow_mut() = BroadcastChannelState::UnManaged;
    }

    /// <https://html.spec.whatwg.org/multipage/#entangle>
    pub fn entangle_ports(&self, port1: MessagePortId, port2: MessagePortId) {
        if let MessagePortState::Managed(_id, message_ports) =
            &mut *self.message_port_state.borrow_mut()
        {
            for (port_id, entangled_id) in &[(port1, port2), (port2, port1)] {
                match message_ports.get_mut(port_id) {
                    None => {
                        return warn!("entangled_ports called on a global not managing the port.");
                    },
                    Some(managed_port) => {
                        if let Some(port_impl) = managed_port.port_impl.as_mut() {
                            managed_port.dom_port.entangle(*entangled_id);
                            port_impl.entangle(*entangled_id);
                        } else {
                            panic!("managed-port has no port-impl.");
                        }
                    },
                }
            }
        } else {
            panic!("entangled_ports called on a global not managing any ports.");
        }

        let _ = self
            .script_to_constellation_chan()
            .send(ScriptMsg::EntanglePorts(port1, port2));
    }

    /// Note that the entangled port of `port_id` has been removed in another global.
    pub fn note_entangled_port_removed(&self, port_id: &MessagePortId) {
        // Note: currently this is a no-op,
        // as we only use the `close` method to manage the local lifecyle of a port.
        // This could be used as part of lifecyle management to determine a port can be GC'ed.
        // See https://github.com/servo/servo/issues/25772
        warn!(
            "Entangled port of {:?} has been removed in another global",
            port_id
        );
    }

    /// Handle the transfer of a port in the current task.
    pub fn mark_port_as_transferred(&self, port_id: &MessagePortId) -> MessagePortImpl {
        if let MessagePortState::Managed(_id, message_ports) =
            &mut *self.message_port_state.borrow_mut()
        {
            let mut port_impl = message_ports
                .remove(port_id)
                .map(|ref mut managed_port| {
                    managed_port
                        .port_impl
                        .take()
                        .expect("Managed port doesn't have a port-impl.")
                })
                .expect("mark_port_as_transferred called on a global not managing the port.");
            port_impl.set_has_been_shipped();
            let _ = self
                .script_to_constellation_chan()
                .send(ScriptMsg::MessagePortShipped(*port_id));
            port_impl
        } else {
            panic!("mark_port_as_transferred called on a global not managing any ports.");
        }
    }

    /// <https://html.spec.whatwg.org/multipage/#dom-messageport-start>
    pub fn start_message_port(&self, port_id: &MessagePortId) {
        if let MessagePortState::Managed(_id, message_ports) =
            &mut *self.message_port_state.borrow_mut()
        {
            let message_buffer = match message_ports.get_mut(port_id) {
                None => panic!("start_message_port called on a unknown port."),
                Some(managed_port) => {
                    if let Some(port_impl) = managed_port.port_impl.as_mut() {
                        port_impl.start()
                    } else {
                        panic!("managed-port has no port-impl.");
                    }
                },
            };
            if let Some(message_buffer) = message_buffer {
                for task in message_buffer {
                    let port_id = *port_id;
                    let this = Trusted::new(self);
                    let _ = self.port_message_queue().queue(
                        task!(process_pending_port_messages: move || {
                            let target_global = this.root();
                            target_global.route_task_to_port(port_id, task, CanGc::note());
                        }),
                        self,
                    );
                }
            }
        } else {
            warn!("start_message_port called on a global not managing any ports.")
        }
    }

    /// <https://html.spec.whatwg.org/multipage/#dom-messageport-close>
    pub fn close_message_port(&self, port_id: &MessagePortId) {
        if let MessagePortState::Managed(_id, message_ports) =
            &mut *self.message_port_state.borrow_mut()
        {
            match message_ports.get_mut(port_id) {
                None => panic!("close_message_port called on an unknown port."),
                Some(managed_port) => {
                    if let Some(port_impl) = managed_port.port_impl.as_mut() {
                        port_impl.close();
                        managed_port.closed = true;
                    } else {
                        panic!("managed-port has no port-impl.");
                    }
                },
            };
        } else {
            warn!("close_message_port called on a global not managing any ports.")
        }
    }

    /// <https://html.spec.whatwg.org/multipage/#message-port-post-message-steps>
    // Steps 6 and 7
    pub fn post_messageport_msg(&self, port_id: MessagePortId, task: PortMessageTask) {
        if let MessagePortState::Managed(_id, message_ports) =
            &mut *self.message_port_state.borrow_mut()
        {
            let entangled_port = match message_ports.get_mut(&port_id) {
                None => panic!("post_messageport_msg called on an unknown port."),
                Some(managed_port) => {
                    if let Some(port_impl) = managed_port.port_impl.as_mut() {
                        port_impl.entangled_port_id()
                    } else {
                        panic!("managed-port has no port-impl.");
                    }
                },
            };
            if let Some(entangled_id) = entangled_port {
                // Step 7
                let this = Trusted::new(self);
                let _ = self.port_message_queue().queue(
                    task!(post_message: move || {
                        let global = this.root();
                        // Note: we do this in a task, as this will ensure the global and constellation
                        // are aware of any transfer that might still take place in the current task.
                        global.route_task_to_port(entangled_id, task, CanGc::note());
                    }),
                    self,
                );
            }
        } else {
            warn!("post_messageport_msg called on a global not managing any ports.");
        }
    }

    /// If we don't know about the port,
    /// send the message to the constellation for routing.
    fn re_route_port_task(&self, port_id: MessagePortId, task: PortMessageTask) {
        let _ = self
            .script_to_constellation_chan()
            .send(ScriptMsg::RerouteMessagePort(port_id, task));
    }

    /// <https://html.spec.whatwg.org/multipage/#dom-broadcastchannel-postmessage>
    /// Step 7 and following steps.
    pub fn schedule_broadcast(&self, msg: BroadcastMsg, channel_id: &Uuid) {
        // First, broadcast locally.
        self.broadcast_message_event(msg.clone(), Some(channel_id));

        if let BroadcastChannelState::Managed(router_id, _) =
            &*self.broadcast_channel_state.borrow()
        {
            // Second, broadcast to other globals via the constellation.
            //
            // Note: for globals in the same script-thread,
            // we could skip the hop to the constellation.
            let _ = self
                .script_to_constellation_chan()
                .send(ScriptMsg::ScheduleBroadcast(*router_id, msg));
        } else {
            panic!("Attemps to broadcast a message via global not managing any channels.");
        }
    }

    /// <https://html.spec.whatwg.org/multipage/#dom-broadcastchannel-postmessage>
    /// Step 7 and following steps.
    pub fn broadcast_message_event(&self, event: BroadcastMsg, channel_id: Option<&Uuid>) {
        if let BroadcastChannelState::Managed(_, channels) = &*self.broadcast_channel_state.borrow()
        {
            let BroadcastMsg {
                data,
                origin,
                channel_name,
            } = event;

            // Step 7, a few preliminary steps.

            // - Check the worker is not closing.
            if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
                if worker.is_closing() {
                    return;
                }
            }

            // - Check the associated document is fully-active.
            if let Some(window) = self.downcast::<Window>() {
                if !window.Document().is_fully_active() {
                    return;
                }
            }

            // - Check for a case-sensitive match for the name of the channel.
            let channel_name = DOMString::from_string(channel_name);

            if let Some(channels) = channels.get(&channel_name) {
                channels
                    .iter()
                    .filter(|channel| {
                        // Step 8.
                        // Filter out the sender.
                        if let Some(id) = channel_id {
                            channel.id() != id
                        } else {
                            true
                        }
                    })
                    .map(|channel| DomRoot::from_ref(&**channel))
                    // Step 9, sort by creation order,
                    // done by using a queue to store channels in creation order.
                    .for_each(|channel| {
                        let data = data.clone_for_broadcast();
                        let origin = origin.clone();

                        // Step 10: Queue a task on the DOM manipulation task-source,
                        // to fire the message event
                        let channel = Trusted::new(&*channel);
                        let global = Trusted::new(self);
                        let _ = self.dom_manipulation_task_source().queue(
                            task!(process_pending_port_messages: move || {
                                let destination = channel.root();
                                let global = global.root();

                                // 10.1 Check for closed flag.
                                if destination.closed() {
                                    return;
                                }

                                rooted!(in(*GlobalScope::get_cx()) let mut message = UndefinedValue());

                                // Step 10.3 StructuredDeserialize(serialized, targetRealm).
                                if let Ok(ports) = structuredclone::read(&global, data, message.handle_mut()) {
                                    // Step 10.4, Fire an event named message at destination.
                                    MessageEvent::dispatch_jsval(
                                        destination.upcast(),
                                        &global,
                                        message.handle(),
                                        Some(&origin.ascii_serialization()),
                                        None,
                                        ports,
                                        CanGc::note()
                                    );
                                } else {
                                    // Step 10.3, fire an event named messageerror at destination.
                                    MessageEvent::dispatch_error(destination.upcast(), &global, CanGc::note());
                                }
                            }),
                            self,
                        );
                    });
            }
        }
    }

    /// Route the task to be handled by the relevant port.
    pub fn route_task_to_port(&self, port_id: MessagePortId, task: PortMessageTask, can_gc: CanGc) {
        let should_dispatch = if let MessagePortState::Managed(_id, message_ports) =
            &mut *self.message_port_state.borrow_mut()
        {
            if !message_ports.contains_key(&port_id) {
                self.re_route_port_task(port_id, task);
                return;
            }
            match message_ports.get_mut(&port_id) {
                None => panic!("route_task_to_port called for an unknown port."),
                Some(managed_port) => {
                    // If the port is not enabled yet, or if is awaiting the completion of it's transfer,
                    // the task will be buffered and dispatched upon enablement or completion of the transfer.
                    if let Some(port_impl) = managed_port.port_impl.as_mut() {
                        port_impl.handle_incoming(task).map(|to_dispatch| {
                            (DomRoot::from_ref(&*managed_port.dom_port), to_dispatch)
                        })
                    } else {
                        panic!("managed-port has no port-impl.");
                    }
                },
            }
        } else {
            self.re_route_port_task(port_id, task);
            return;
        };
        if let Some((dom_port, PortMessageTask { origin, data })) = should_dispatch {
            // Substep 3-4
            rooted!(in(*GlobalScope::get_cx()) let mut message_clone = UndefinedValue());
            if let Ok(ports) = structuredclone::read(self, data, message_clone.handle_mut()) {
                // Substep 6
                // Dispatch the event, using the dom message-port.
                MessageEvent::dispatch_jsval(
                    dom_port.upcast(),
                    self,
                    message_clone.handle(),
                    Some(&origin.ascii_serialization()),
                    None,
                    ports,
                    can_gc,
                );
            } else {
                // Step 4, fire messageerror event.
                MessageEvent::dispatch_error(dom_port.upcast(), self, can_gc);
            }
        }
    }

    /// Check all ports that have been transfer-received in the previous task,
    /// and complete their transfer if they haven't been re-transferred.
    pub fn maybe_add_pending_ports(&self) {
        if let MessagePortState::Managed(router_id, message_ports) =
            &mut *self.message_port_state.borrow_mut()
        {
            let to_be_added: Vec<MessagePortId> = message_ports
                .iter()
                .filter_map(|(id, managed_port)| {
                    if managed_port.pending {
                        Some(*id)
                    } else {
                        None
                    }
                })
                .collect();
            for id in to_be_added.iter() {
                let managed_port = message_ports
                    .get_mut(id)
                    .expect("Collected port-id to match an entry");
                if !managed_port.pending {
                    panic!("Only pending ports should be found in to_be_added")
                }
                managed_port.pending = false;
            }
            let _ =
                self.script_to_constellation_chan()
                    .send(ScriptMsg::CompleteMessagePortTransfer(
                        *router_id,
                        to_be_added,
                    ));
        } else {
            warn!("maybe_add_pending_ports called on a global not managing any ports.");
        }
    }

    /// <https://html.spec.whatwg.org/multipage/#ports-and-garbage-collection>
    pub fn perform_a_message_port_garbage_collection_checkpoint(&self) {
        let is_empty = if let MessagePortState::Managed(_id, message_ports) =
            &mut *self.message_port_state.borrow_mut()
        {
            let to_be_removed: Vec<MessagePortId> = message_ports
                .iter()
                .filter_map(|(id, managed_port)| {
                    if managed_port.closed {
                        // Let the constellation know to drop this port and the one it is entangled with,
                        // and to forward this message to the script-process where the entangled is found.
                        let _ = self
                            .script_to_constellation_chan()
                            .send(ScriptMsg::RemoveMessagePort(*id));
                        Some(*id)
                    } else {
                        None
                    }
                })
                .collect();
            for id in to_be_removed {
                message_ports.remove(&id);
            }
            message_ports.is_empty()
        } else {
            false
        };
        if is_empty {
            self.remove_message_ports_router();
        }
    }

    /// Remove broadcast-channels that are closed.
    /// TODO: Also remove them if they do not have an event-listener.
    /// see <https://github.com/servo/servo/issues/25772>
    pub fn perform_a_broadcast_channel_garbage_collection_checkpoint(&self) {
        let is_empty = if let BroadcastChannelState::Managed(router_id, ref mut channels) =
            &mut *self.broadcast_channel_state.borrow_mut()
        {
            channels.retain(|name, ref mut channels| {
                channels.retain(|chan| !chan.closed());
                if channels.is_empty() {
                    let _ = self.script_to_constellation_chan().send(
                        ScriptMsg::RemoveBroadcastChannelNameInRouter(
                            *router_id,
                            name.to_string(),
                            self.origin().immutable().clone(),
                        ),
                    );
                    false
                } else {
                    true
                }
            });
            channels.is_empty()
        } else {
            false
        };
        if is_empty {
            self.remove_broadcast_channel_router();
        }
    }

    /// Start tracking a broadcast-channel.
    pub fn track_broadcast_channel(&self, dom_channel: &BroadcastChannel) {
        let mut current_state = self.broadcast_channel_state.borrow_mut();

        if let BroadcastChannelState::UnManaged = &*current_state {
            // Setup a route for IPC, for broadcasts from the constellation to our channels.
            let (broadcast_control_sender, broadcast_control_receiver) =
                ipc::channel().expect("ipc channel failure");
            let context = Trusted::new(self);
            let (task_source, canceller) = (
                self.dom_manipulation_task_source(),
                self.task_canceller(TaskSourceName::DOMManipulation),
            );
            let listener = BroadcastListener {
                canceller,
                task_source,
                context,
            };
            ROUTER.add_typed_route(
                broadcast_control_receiver,
                Box::new(move |message| match message {
                    Ok(msg) => listener.handle(msg),
                    Err(err) => warn!("Error receiving a BroadcastMsg: {:?}", err),
                }),
            );
            let router_id = BroadcastChannelRouterId::new();
            *current_state = BroadcastChannelState::Managed(router_id, HashMap::new());
            let _ = self
                .script_to_constellation_chan()
                .send(ScriptMsg::NewBroadcastChannelRouter(
                    router_id,
                    broadcast_control_sender,
                    self.origin().immutable().clone(),
                ));
        }

        if let BroadcastChannelState::Managed(router_id, channels) = &mut *current_state {
            let entry = channels.entry(dom_channel.Name()).or_insert_with(|| {
                let _ = self.script_to_constellation_chan().send(
                    ScriptMsg::NewBroadcastChannelNameInRouter(
                        *router_id,
                        dom_channel.Name().to_string(),
                        self.origin().immutable().clone(),
                    ),
                );
                VecDeque::new()
            });
            entry.push_back(Dom::from_ref(dom_channel));
        } else {
            panic!("track_broadcast_channel should have first switched the state to managed.");
        }
    }

    /// Start tracking a message-port
    pub fn track_message_port(&self, dom_port: &MessagePort, port_impl: Option<MessagePortImpl>) {
        let mut current_state = self.message_port_state.borrow_mut();

        if let MessagePortState::UnManaged = &*current_state {
            // Setup a route for IPC, for messages from the constellation to our ports.
            let (port_control_sender, port_control_receiver) =
                ipc::channel().expect("ipc channel failure");
            let context = Trusted::new(self);
            let (task_source, canceller) = (
                self.port_message_queue(),
                self.task_canceller(TaskSourceName::PortMessage),
            );
            let listener = MessageListener {
                canceller,
                task_source,
                context,
            };
            ROUTER.add_typed_route(
                port_control_receiver,
                Box::new(move |message| match message {
                    Ok(msg) => listener.notify(msg),
                    Err(err) => warn!("Error receiving a MessagePortMsg: {:?}", err),
                }),
            );
            let router_id = MessagePortRouterId::new();
            *current_state = MessagePortState::Managed(router_id, HashMapTracedValues::new());
            let _ = self
                .script_to_constellation_chan()
                .send(ScriptMsg::NewMessagePortRouter(
                    router_id,
                    port_control_sender,
                ));
        }

        if let MessagePortState::Managed(router_id, message_ports) = &mut *current_state {
            if let Some(port_impl) = port_impl {
                // We keep transfer-received ports as "pending",
                // and only ask the constellation to complete the transfer
                // if they're not re-shipped in the current task.
                message_ports.insert(
                    *dom_port.message_port_id(),
                    ManagedMessagePort {
                        port_impl: Some(port_impl),
                        dom_port: Dom::from_ref(dom_port),
                        pending: true,
                        closed: false,
                    },
                );

                // Queue a task to complete the transfer,
                // unless the port is re-transferred in the current task.
                let this = Trusted::new(self);
                let _ = self.port_message_queue().queue(
                    task!(process_pending_port_messages: move || {
                        let target_global = this.root();
                        target_global.maybe_add_pending_ports();
                    }),
                    self,
                );
            } else {
                // If this is a newly-created port, let the constellation immediately know.
                let port_impl = MessagePortImpl::new(*dom_port.message_port_id());
                message_ports.insert(
                    *dom_port.message_port_id(),
                    ManagedMessagePort {
                        port_impl: Some(port_impl),
                        dom_port: Dom::from_ref(dom_port),
                        pending: false,
                        closed: false,
                    },
                );
                let _ = self
                    .script_to_constellation_chan()
                    .send(ScriptMsg::NewMessagePort(
                        *router_id,
                        *dom_port.message_port_id(),
                    ));
            };
        } else {
            panic!("track_message_port should have first switched the state to managed.");
        }
    }

    /// <https://html.spec.whatwg.org/multipage/#serialization-steps>
    /// defined at <https://w3c.github.io/FileAPI/#blob-section>.
    /// Get the snapshot state and underlying bytes of the blob.
    pub fn serialize_blob(&self, blob_id: &BlobId) -> BlobImpl {
        // Note: we combine the snapshot state and underlying bytes into one call,
        // which seems spec compliant.
        // See https://w3c.github.io/FileAPI/#snapshot-state
        let bytes = self
            .get_blob_bytes(blob_id)
            .expect("Could not read bytes from blob as part of serialization steps.");
        let type_string = self.get_blob_type_string(blob_id);

        // Note: the new BlobImpl is a clone, but with it's own BlobId.
        BlobImpl::new_from_bytes(bytes, type_string)
    }

    fn track_blob_info(&self, blob_info: BlobInfo, blob_id: BlobId) {
        let mut blob_state = self.blob_state.borrow_mut();

        match &mut *blob_state {
            BlobState::UnManaged => {
                let mut blobs_map = HashMapTracedValues::new();
                blobs_map.insert(blob_id, blob_info);
                *blob_state = BlobState::Managed(blobs_map);
            },
            BlobState::Managed(blobs_map) => {
                blobs_map.insert(blob_id, blob_info);
            },
        }
    }

    /// Start tracking a blob
    pub fn track_blob(&self, dom_blob: &Blob, blob_impl: BlobImpl) {
        let blob_id = blob_impl.blob_id();

        let blob_info = BlobInfo {
            blob_impl,
            tracker: BlobTracker::Blob(WeakRef::new(dom_blob)),
            has_url: false,
        };

        self.track_blob_info(blob_info, blob_id);
    }

    /// Start tracking a file
    pub fn track_file(&self, file: &File, blob_impl: BlobImpl) {
        let blob_id = blob_impl.blob_id();

        let blob_info = BlobInfo {
            blob_impl,
            tracker: BlobTracker::File(WeakRef::new(file)),
            has_url: false,
        };

        self.track_blob_info(blob_info, blob_id);
    }

    /// Clean-up any file or blob that is unreachable from script,
    /// unless it has an oustanding blob url.
    /// <https://w3c.github.io/FileAPI/#lifeTime>
    fn perform_a_blob_garbage_collection_checkpoint(&self) {
        let mut blob_state = self.blob_state.borrow_mut();
        if let BlobState::Managed(blobs_map) = &mut *blob_state {
            blobs_map.0.retain(|_id, blob_info| {
                let garbage_collected = match &blob_info.tracker {
                    BlobTracker::File(weak) => weak.root().is_none(),
                    BlobTracker::Blob(weak) => weak.root().is_none(),
                };
                if garbage_collected && !blob_info.has_url {
                    if let BlobData::File(ref f) = blob_info.blob_impl.blob_data() {
                        self.decrement_file_ref(f.get_id());
                    }
                    false
                } else {
                    true
                }
            });
            if blobs_map.is_empty() {
                *blob_state = BlobState::UnManaged;
            }
        }
    }

    /// Clean-up all file related resources on document unload.
    /// <https://w3c.github.io/FileAPI/#lifeTime>
    pub fn clean_up_all_file_resources(&self) {
        let mut blob_state = self.blob_state.borrow_mut();
        if let BlobState::Managed(blobs_map) = &mut *blob_state {
            blobs_map.drain().for_each(|(_id, blob_info)| {
                if let BlobData::File(ref f) = blob_info.blob_impl.blob_data() {
                    self.decrement_file_ref(f.get_id());
                }
            });
        }
        *blob_state = BlobState::UnManaged;
    }

    fn decrement_file_ref(&self, id: Uuid) {
        let origin = get_blob_origin(&self.get_url());

        let (tx, rx) = profile_ipc::channel(self.time_profiler_chan().clone()).unwrap();

        let msg = FileManagerThreadMsg::DecRef(id, origin, tx);
        self.send_to_file_manager(msg);
        let _ = rx.recv();
    }

    /// Get a slice to the inner data of a Blob,
    /// In the case of a File-backed blob, this might incur synchronous read and caching.
    pub fn get_blob_bytes(&self, blob_id: &BlobId) -> Result<Vec<u8>, ()> {
        let parent = {
            let blob_state = self.blob_state.borrow();
            if let BlobState::Managed(blobs_map) = &*blob_state {
                let blob_info = blobs_map
                    .get(blob_id)
                    .expect("get_blob_bytes for an unknown blob.");
                match blob_info.blob_impl.blob_data() {
                    BlobData::Sliced(ref parent, ref rel_pos) => Some((*parent, rel_pos.clone())),
                    _ => None,
                }
            } else {
                panic!("get_blob_bytes called on a global not managing any blobs.");
            }
        };

        match parent {
            Some((parent_id, rel_pos)) => self.get_blob_bytes_non_sliced(&parent_id).map(|v| {
                let range = rel_pos.to_abs_range(v.len());
                v.index(range).to_vec()
            }),
            None => self.get_blob_bytes_non_sliced(blob_id),
        }
    }

    /// Get bytes from a non-sliced blob
    fn get_blob_bytes_non_sliced(&self, blob_id: &BlobId) -> Result<Vec<u8>, ()> {
        let blob_state = self.blob_state.borrow();
        if let BlobState::Managed(blobs_map) = &*blob_state {
            let blob_info = blobs_map
                .get(blob_id)
                .expect("get_blob_bytes_non_sliced called for a unknown blob.");
            match blob_info.blob_impl.blob_data() {
                BlobData::File(ref f) => {
                    let (buffer, is_new_buffer) = match f.get_cache() {
                        Some(bytes) => (bytes, false),
                        None => {
                            let bytes = self.read_file(f.get_id())?;
                            (bytes, true)
                        },
                    };

                    // Cache
                    if is_new_buffer {
                        f.cache_bytes(buffer.clone());
                    }

                    Ok(buffer)
                },
                BlobData::Memory(ref s) => Ok(s.clone()),
                BlobData::Sliced(_, _) => panic!("This blob doesn't have a parent."),
            }
        } else {
            panic!("get_blob_bytes_non_sliced called on a global not managing any blobs.");
        }
    }

    /// Get a slice to the inner data of a Blob,
    /// if it's a memory blob, or it's file-id and file-size otherwise.
    ///
    /// Note: this is almost a duplicate of `get_blob_bytes`,
    /// tweaked for integration with streams.
    /// TODO: merge with `get_blob_bytes` by way of broader integration with blob streams.
    fn get_blob_bytes_or_file_id(&self, blob_id: &BlobId) -> BlobResult {
        let parent = {
            let blob_state = self.blob_state.borrow();
            if let BlobState::Managed(blobs_map) = &*blob_state {
                let blob_info = blobs_map
                    .get(blob_id)
                    .expect("get_blob_bytes_or_file_id for an unknown blob.");
                match blob_info.blob_impl.blob_data() {
                    BlobData::Sliced(ref parent, ref rel_pos) => Some((*parent, rel_pos.clone())),
                    _ => None,
                }
            } else {
                panic!("get_blob_bytes_or_file_id called on a global not managing any blobs.");
            }
        };

        match parent {
            Some((parent_id, rel_pos)) => {
                match self.get_blob_bytes_non_sliced_or_file_id(&parent_id) {
                    BlobResult::Bytes(bytes) => {
                        let range = rel_pos.to_abs_range(bytes.len());
                        BlobResult::Bytes(bytes.index(range).to_vec())
                    },
                    res => res,
                }
            },
            None => self.get_blob_bytes_non_sliced_or_file_id(blob_id),
        }
    }

    /// Get bytes from a non-sliced blob if in memory, or it's file-id and file-size.
    ///
    /// Note: this is almost a duplicate of `get_blob_bytes_non_sliced`,
    /// tweaked for integration with streams.
    /// TODO: merge with `get_blob_bytes` by way of broader integration with blob streams.
    fn get_blob_bytes_non_sliced_or_file_id(&self, blob_id: &BlobId) -> BlobResult {
        let blob_state = self.blob_state.borrow();
        if let BlobState::Managed(blobs_map) = &*blob_state {
            let blob_info = blobs_map
                .get(blob_id)
                .expect("get_blob_bytes_non_sliced_or_file_id called for a unknown blob.");
            match blob_info.blob_impl.blob_data() {
                BlobData::File(ref f) => match f.get_cache() {
                    Some(bytes) => BlobResult::Bytes(bytes.clone()),
                    None => BlobResult::File(f.get_id(), f.get_size() as usize),
                },
                BlobData::Memory(ref s) => BlobResult::Bytes(s.clone()),
                BlobData::Sliced(_, _) => panic!("This blob doesn't have a parent."),
            }
        } else {
            panic!(
                "get_blob_bytes_non_sliced_or_file_id called on a global not managing any blobs."
            );
        }
    }

    /// Get a copy of the type_string of a blob.
    pub fn get_blob_type_string(&self, blob_id: &BlobId) -> String {
        let blob_state = self.blob_state.borrow();
        if let BlobState::Managed(blobs_map) = &*blob_state {
            let blob_info = blobs_map
                .get(blob_id)
                .expect("get_blob_type_string called for a unknown blob.");
            blob_info.blob_impl.type_string()
        } else {
            panic!("get_blob_type_string called on a global not managing any blobs.");
        }
    }

    /// <https://w3c.github.io/FileAPI/#dfn-size>
    pub fn get_blob_size(&self, blob_id: &BlobId) -> u64 {
        let blob_state = self.blob_state.borrow();
        if let BlobState::Managed(blobs_map) = &*blob_state {
            let parent = {
                let blob_info = blobs_map
                    .get(blob_id)
                    .expect("get_blob_size called for a unknown blob.");
                match blob_info.blob_impl.blob_data() {
                    BlobData::Sliced(ref parent, ref rel_pos) => Some((*parent, rel_pos.clone())),
                    _ => None,
                }
            };
            match parent {
                Some((parent_id, rel_pos)) => {
                    let parent_info = blobs_map
                        .get(&parent_id)
                        .expect("Parent of blob whose size is unknown.");
                    let parent_size = match parent_info.blob_impl.blob_data() {
                        BlobData::File(ref f) => f.get_size(),
                        BlobData::Memory(ref v) => v.len() as u64,
                        BlobData::Sliced(_, _) => panic!("Blob ancestry should be only one level."),
                    };
                    rel_pos.to_abs_range(parent_size as usize).len() as u64
                },
                None => {
                    let blob_info = blobs_map.get(blob_id).expect("Blob whose size is unknown.");
                    match blob_info.blob_impl.blob_data() {
                        BlobData::File(ref f) => f.get_size(),
                        BlobData::Memory(ref v) => v.len() as u64,
                        BlobData::Sliced(_, _) => panic!(
                            "It was previously checked that this blob does not have a parent."
                        ),
                    }
                },
            }
        } else {
            panic!("get_blob_size called on a global not managing any blobs.");
        }
    }

    pub fn get_blob_url_id(&self, blob_id: &BlobId) -> Uuid {
        let mut blob_state = self.blob_state.borrow_mut();
        if let BlobState::Managed(blobs_map) = &mut *blob_state {
            let parent = {
                let blob_info = blobs_map
                    .get_mut(blob_id)
                    .expect("get_blob_url_id called for a unknown blob.");

                // Keep track of blobs with outstanding URLs.
                blob_info.has_url = true;

                match blob_info.blob_impl.blob_data() {
                    BlobData::Sliced(ref parent, ref rel_pos) => Some((*parent, rel_pos.clone())),
                    _ => None,
                }
            };
            match parent {
                Some((parent_id, rel_pos)) => {
                    let parent_info = blobs_map
                        .get_mut(&parent_id)
                        .expect("Parent of blob whose url is requested is unknown.");
                    let parent_file_id = self.promote(parent_info, /* set_valid is */ false);
                    let parent_size = match parent_info.blob_impl.blob_data() {
                        BlobData::File(ref f) => f.get_size(),
                        BlobData::Memory(ref v) => v.len() as u64,
                        BlobData::Sliced(_, _) => panic!("Blob ancestry should be only one level."),
                    };
                    let parent_size = rel_pos.to_abs_range(parent_size as usize).len() as u64;
                    let blob_info = blobs_map
                        .get_mut(blob_id)
                        .expect("Blob whose url is requested is unknown.");
                    self.create_sliced_url_id(blob_info, &parent_file_id, &rel_pos, parent_size)
                },
                None => {
                    let blob_info = blobs_map
                        .get_mut(blob_id)
                        .expect("Blob whose url is requested is unknown.");
                    self.promote(blob_info, /* set_valid is */ true)
                },
            }
        } else {
            panic!("get_blob_url_id called on a global not managing any blobs.");
        }
    }

    /// Get a FileID representing sliced parent-blob content
    fn create_sliced_url_id(
        &self,
        blob_info: &mut BlobInfo,
        parent_file_id: &Uuid,
        rel_pos: &RelativePos,
        parent_len: u64,
    ) -> Uuid {
        let origin = get_blob_origin(&self.get_url());

        let (tx, rx) = profile_ipc::channel(self.time_profiler_chan().clone()).unwrap();
        let msg = FileManagerThreadMsg::AddSlicedURLEntry(
            *parent_file_id,
            rel_pos.clone(),
            tx,
            origin.clone(),
        );
        self.send_to_file_manager(msg);
        match rx.recv().expect("File manager thread is down.") {
            Ok(new_id) => {
                *blob_info.blob_impl.blob_data_mut() = BlobData::File(FileBlob::new(
                    new_id,
                    None,
                    None,
                    rel_pos.to_abs_range(parent_len as usize).len() as u64,
                ));

                // Return the indirect id reference
                new_id
            },
            Err(_) => {
                // Return dummy id
                Uuid::new_v4()
            },
        }
    }

    /// Promote non-Slice blob:
    /// 1. Memory-based: The bytes in data slice will be transferred to file manager thread.
    /// 2. File-based: If set_valid, then activate the FileID so it can serve as URL
    ///     Depending on set_valid, the returned FileID can be part of
    ///     valid or invalid Blob URL.
    pub fn promote(&self, blob_info: &mut BlobInfo, set_valid: bool) -> Uuid {
        let mut bytes = vec![];
        let global_url = self.get_url();

        match blob_info.blob_impl.blob_data_mut() {
            BlobData::Sliced(_, _) => {
                panic!("Sliced blobs should use create_sliced_url_id instead of promote.");
            },
            BlobData::File(ref f) => {
                if set_valid {
                    let origin = get_blob_origin(&global_url);
                    let (tx, rx) = profile_ipc::channel(self.time_profiler_chan().clone()).unwrap();

                    let msg = FileManagerThreadMsg::ActivateBlobURL(f.get_id(), tx, origin.clone());
                    self.send_to_file_manager(msg);

                    match rx.recv().unwrap() {
                        Ok(_) => return f.get_id(),
                        // Return a dummy id on error
                        Err(_) => return Uuid::new_v4(),
                    }
                } else {
                    // no need to activate
                    return f.get_id();
                }
            },
            BlobData::Memory(ref mut bytes_in) => mem::swap(bytes_in, &mut bytes),
        };

        let origin = get_blob_origin(&global_url);

        let blob_buf = BlobBuf {
            filename: None,
            type_string: blob_info.blob_impl.type_string(),
            size: bytes.len() as u64,
            bytes: bytes.to_vec(),
        };

        let id = Uuid::new_v4();
        let msg = FileManagerThreadMsg::PromoteMemory(id, blob_buf, set_valid, origin.clone());
        self.send_to_file_manager(msg);

        *blob_info.blob_impl.blob_data_mut() = BlobData::File(FileBlob::new(
            id,
            None,
            Some(bytes.to_vec()),
            bytes.len() as u64,
        ));

        id
    }

    fn send_to_file_manager(&self, msg: FileManagerThreadMsg) {
        let resource_threads = self.resource_threads();
        let _ = resource_threads.send(CoreResourceMsg::ToFileManager(msg));
    }

    fn read_file(&self, id: Uuid) -> Result<Vec<u8>, ()> {
        let recv = self.send_msg(id);
        GlobalScope::read_msg(recv)
    }

    /// <https://w3c.github.io/FileAPI/#blob-get-stream>
    pub fn get_blob_stream(&self, blob_id: &BlobId, can_gc: CanGc) -> DomRoot<ReadableStream> {
        let (file_id, size) = match self.get_blob_bytes_or_file_id(blob_id) {
            BlobResult::Bytes(bytes) => {
                // If we have all the bytes in memory, queue them and close the stream.
                let stream = ReadableStream::new_from_bytes(self, bytes, can_gc);
                return stream;
            },
            BlobResult::File(id, size) => (id, size),
        };

        let stream = ReadableStream::new_with_external_underlying_source(
            self,
            UnderlyingSourceType::Blob(size),
            can_gc,
        );

        let recv = self.send_msg(file_id);

        let trusted_stream = Trusted::new(&*stream.clone());
        let task_canceller = self.task_canceller(TaskSourceName::FileReading);
        let task_source = self.file_reading_task_source();

        let mut file_listener = FileListener {
            state: Some(FileListenerState::Empty(FileListenerTarget::Stream(
                trusted_stream,
            ))),
            task_source,
            task_canceller,
        };

        ROUTER.add_typed_route(
            recv.to_ipc_receiver(),
            Box::new(move |msg| {
                file_listener.handle(msg.expect("Deserialization of file listener msg failed."));
            }),
        );

        stream
    }

    pub fn read_file_async(&self, id: Uuid, promise: Rc<Promise>, callback: FileListenerCallback) {
        let recv = self.send_msg(id);

        let trusted_promise = TrustedPromise::new(promise);
        let task_canceller = self.task_canceller(TaskSourceName::FileReading);
        let task_source = self.file_reading_task_source();

        let mut file_listener = FileListener {
            state: Some(FileListenerState::Empty(FileListenerTarget::Promise(
                trusted_promise,
                callback,
            ))),
            task_source,
            task_canceller,
        };

        ROUTER.add_typed_route(
            recv.to_ipc_receiver(),
            Box::new(move |msg| {
                file_listener.handle(msg.expect("Deserialization of file listener msg failed."));
            }),
        );
    }

    fn send_msg(&self, id: Uuid) -> profile_ipc::IpcReceiver<FileManagerResult<ReadFileProgress>> {
        let resource_threads = self.resource_threads();
        let (chan, recv) = profile_ipc::channel(self.time_profiler_chan().clone()).unwrap();
        let origin = get_blob_origin(&self.get_url());
        let msg = FileManagerThreadMsg::ReadFile(chan, id, origin);
        let _ = resource_threads.send(CoreResourceMsg::ToFileManager(msg));
        recv
    }

    fn read_msg(
        receiver: profile_ipc::IpcReceiver<FileManagerResult<ReadFileProgress>>,
    ) -> Result<Vec<u8>, ()> {
        let mut bytes = vec![];

        loop {
            match receiver.recv().unwrap() {
                Ok(ReadFileProgress::Meta(mut blob_buf)) => {
                    bytes.append(&mut blob_buf.bytes);
                },
                Ok(ReadFileProgress::Partial(mut bytes_in)) => {
                    bytes.append(&mut bytes_in);
                },
                Ok(ReadFileProgress::EOF) => {
                    return Ok(bytes);
                },
                Err(_) => return Err(()),
            }
        }
    }

    pub fn permission_state_invocation_results(
        &self,
    ) -> &DomRefCell<HashMap<String, PermissionState>> {
        &self.permission_state_invocation_results
    }

    pub fn track_worker(
        &self,
        closing: Arc<AtomicBool>,
        join_handle: JoinHandle<()>,
        control_sender: Sender<DedicatedWorkerControlMsg>,
        context: ThreadSafeJSContext,
    ) {
        self.list_auto_close_worker
            .borrow_mut()
            .push(AutoCloseWorker {
                closing,
                join_handle: Some(join_handle),
                control_sender,
                context,
            });
    }

    pub fn track_event_source(&self, event_source: &EventSource) {
        self.event_source_tracker.track(event_source);
    }

    pub fn close_event_sources(&self) -> bool {
        let mut canceled_any_fetch = false;
        self.event_source_tracker
            .for_each(
                |event_source: DomRoot<EventSource>| match event_source.ReadyState() {
                    2 => {},
                    _ => {
                        event_source.cancel();
                        canceled_any_fetch = true;
                    },
                },
            );
        canceled_any_fetch
    }

    /// Returns the global scope of the realm that the given DOM object's reflector
    /// was created in.
    #[allow(unsafe_code)]
    pub fn from_reflector<T: DomObject>(reflector: &T, _realm: &AlreadyInRealm) -> DomRoot<Self> {
        unsafe { GlobalScope::from_object(*reflector.reflector().get_jsobject()) }
    }

    /// Returns the global scope of the realm that the given JS object was created in.
    #[allow(unsafe_code)]
    pub unsafe fn from_object(obj: *mut JSObject) -> DomRoot<Self> {
        assert!(!obj.is_null());
        let global = GetNonCCWObjectGlobal(obj);
        global_scope_from_global_static(global)
    }

    /// Returns the global scope for the given JSContext
    #[allow(unsafe_code)]
    pub unsafe fn from_context(cx: *mut JSContext, _realm: InRealm) -> DomRoot<Self> {
        let global = CurrentGlobalOrNull(cx);
        assert!(!global.is_null());
        global_scope_from_global(global, cx)
    }

    /// Returns the global scope for the given SafeJSContext
    #[allow(unsafe_code)]
    pub fn from_safe_context(cx: SafeJSContext, realm: InRealm) -> DomRoot<Self> {
        unsafe { Self::from_context(*cx, realm) }
    }

    /// Returns the global object of the realm that the given JS object
    /// was created in, after unwrapping any wrappers.
    #[allow(unsafe_code)]
    pub unsafe fn from_object_maybe_wrapped(
        mut obj: *mut JSObject,
        cx: *mut JSContext,
    ) -> DomRoot<Self> {
        if IsWrapper(obj) {
            obj = UnwrapObjectDynamic(obj, cx, /* stopAtWindowProxy = */ false);
            assert!(!obj.is_null());
        }
        GlobalScope::from_object(obj)
    }

    pub fn add_uncaught_rejection(&self, rejection: HandleObject) {
        self.uncaught_rejections
            .borrow_mut()
            .push(Heap::boxed(rejection.get()));
    }

    pub fn remove_uncaught_rejection(&self, rejection: HandleObject) {
        let mut uncaught_rejections = self.uncaught_rejections.borrow_mut();

        if let Some(index) = uncaught_rejections
            .iter()
            .position(|promise| *promise == Heap::boxed(rejection.get()))
        {
            uncaught_rejections.remove(index);
        }
    }

    // `Heap` values must stay boxed, as they need semantics like `Pin`
    // (that is, they cannot be moved).
    #[allow(clippy::vec_box)]
    pub fn get_uncaught_rejections(&self) -> &DomRefCell<Vec<Box<Heap<*mut JSObject>>>> {
        &self.uncaught_rejections
    }

    pub fn add_consumed_rejection(&self, rejection: HandleObject) {
        self.consumed_rejections
            .borrow_mut()
            .push(Heap::boxed(rejection.get()));
    }

    pub fn remove_consumed_rejection(&self, rejection: HandleObject) {
        let mut consumed_rejections = self.consumed_rejections.borrow_mut();

        if let Some(index) = consumed_rejections
            .iter()
            .position(|promise| *promise == Heap::boxed(rejection.get()))
        {
            consumed_rejections.remove(index);
        }
    }

    // `Heap` values must stay boxed, as they need semantics like `Pin`
    // (that is, they cannot be moved).
    #[allow(clippy::vec_box)]
    pub fn get_consumed_rejections(&self) -> &DomRefCell<Vec<Box<Heap<*mut JSObject>>>> {
        &self.consumed_rejections
    }

    pub fn set_module_map(&self, url: ServoUrl, module: ModuleTree) {
        self.module_map.borrow_mut().insert(url, Rc::new(module));
    }

    pub fn get_module_map(&self) -> &DomRefCell<HashMapTracedValues<ServoUrl, Rc<ModuleTree>>> {
        &self.module_map
    }

    pub fn set_inline_module_map(&self, script_id: ScriptId, module: ModuleTree) {
        self.inline_module_map
            .borrow_mut()
            .insert(script_id, Rc::new(module));
    }

    pub fn get_inline_module_map(&self) -> &DomRefCell<HashMap<ScriptId, Rc<ModuleTree>>> {
        &self.inline_module_map
    }

    #[allow(unsafe_code)]
    pub fn get_cx() -> SafeJSContext {
        unsafe { SafeJSContext::from_ptr(Runtime::get()) }
    }

    pub fn crypto(&self) -> DomRoot<Crypto> {
        self.crypto.or_init(|| Crypto::new(self))
    }

    pub fn live_devtools_updates(&self) -> bool {
        self.devtools_wants_updates.get()
    }

    pub fn set_devtools_wants_updates(&self, value: bool) {
        self.devtools_wants_updates.set(value);
    }

    pub fn time(&self, label: DOMString) -> Result<(), ()> {
        let mut timers = self.console_timers.borrow_mut();
        if timers.len() >= 10000 {
            return Err(());
        }
        match timers.entry(label) {
            Entry::Vacant(entry) => {
                entry.insert(Instant::now());
                Ok(())
            },
            Entry::Occupied(_) => Err(()),
        }
    }

    /// Computes the delta time since a label has been created
    ///
    /// Returns an error if the label does not exist.
    pub fn time_log(&self, label: &str) -> Result<u64, ()> {
        self.console_timers
            .borrow()
            .get(label)
            .ok_or(())
            .map(|&start| (Instant::now() - start).as_millis() as u64)
    }

    /// Computes the delta time since a label has been created and stops
    /// tracking the label.
    ///
    /// Returns an error if the label does not exist.
    pub fn time_end(&self, label: &str) -> Result<u64, ()> {
        self.console_timers
            .borrow_mut()
            .remove(label)
            .ok_or(())
            .map(|start| (Instant::now() - start).as_millis() as u64)
    }

    /// Get an `&IpcSender<ScriptToDevtoolsControlMsg>` to send messages
    /// to the devtools thread when available.
    pub fn devtools_chan(&self) -> Option<&IpcSender<ScriptToDevtoolsControlMsg>> {
        self.devtools_chan.as_ref()
    }

    pub fn issue_page_warning(&self, warning: &str) {
        if let Some(ref chan) = self.devtools_chan {
            let _ = chan.send(ScriptToDevtoolsControlMsg::ReportPageError(
                self.pipeline_id,
                PageError {
                    type_: "PageError".to_string(),
                    error_message: warning.to_string(),
                    source_name: self.get_url().to_string(),
                    line_text: "".to_string(),
                    line_number: 0,
                    column_number: 0,
                    category: "script".to_string(),
                    time_stamp: SystemTime::now()
                        .duration_since(UNIX_EPOCH)
                        .unwrap_or_default()
                        .as_millis() as u64,
                    error: false,
                    warning: true,
                    exception: true,
                    strict: false,
                    private: false,
                },
            ));
        }
    }

    /// Get a sender to the memory profiler thread.
    pub fn mem_profiler_chan(&self) -> &profile_mem::ProfilerChan {
        &self.mem_profiler_chan
    }

    /// Get a sender to the time profiler thread.
    pub fn time_profiler_chan(&self) -> &profile_time::ProfilerChan {
        &self.time_profiler_chan
    }

    /// Get a sender to the constellation thread.
    pub fn script_to_constellation_chan(&self) -> &ScriptToConstellationChan {
        &self.script_to_constellation_chan
    }

    pub fn send_to_embedder(&self, msg: EmbedderMsg) {
        self.send_to_constellation(ScriptMsg::ForwardToEmbedder(msg));
    }

    pub fn send_to_constellation(&self, msg: ScriptMsg) {
        self.script_to_constellation_chan().send(msg).unwrap();
    }

    pub fn scheduler_chan(&self) -> &IpcSender<TimerSchedulerMsg> {
        &self.scheduler_chan
    }

    /// Get the `PipelineId` for this global scope.
    pub fn pipeline_id(&self) -> PipelineId {
        self.pipeline_id
    }

    /// Get the origin for this global scope
    pub fn origin(&self) -> &MutableOrigin {
        &self.origin
    }

    /// Get the creation_url for this global scope
    pub fn creation_url(&self) -> &Option<ServoUrl> {
        &self.creation_url
    }

    pub fn image_cache(&self) -> Arc<dyn ImageCache> {
        if let Some(window) = self.downcast::<Window>() {
            return window.image_cache();
        }
        if let Some(worker) = self.downcast::<DedicatedWorkerGlobalScope>() {
            return worker.image_cache();
        }
        if let Some(worker) = self.downcast::<PaintWorkletGlobalScope>() {
            return worker.image_cache();
        }
        unreachable!();
    }

    /// <https://html.spec.whatwg.org/multipage/#concept-settings-object-policy-container>
    pub fn policy_container(&self) -> PolicyContainer {
        if let Some(window) = self.downcast::<Window>() {
            return window.Document().policy_container().to_owned();
        }
        if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
            return worker.policy_container().to_owned();
        }
        unreachable!();
    }

    /// Get the [base url](https://html.spec.whatwg.org/multipage/#api-base-url)
    /// for this global scope.
    pub fn api_base_url(&self) -> ServoUrl {
        if let Some(window) = self.downcast::<Window>() {
            // https://html.spec.whatwg.org/multipage/#script-settings-for-browsing-contexts:api-base-url
            return window.Document().base_url();
        }
        if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
            // https://html.spec.whatwg.org/multipage/#script-settings-for-workers:api-base-url
            return worker.get_url().clone();
        }
        if let Some(worklet) = self.downcast::<WorkletGlobalScope>() {
            // https://drafts.css-houdini.org/worklets/#script-settings-for-worklets
            return worklet.base_url();
        }
        unreachable!();
    }

    /// Get the URL for this global scope.
    pub fn get_url(&self) -> ServoUrl {
        if let Some(window) = self.downcast::<Window>() {
            return window.get_url();
        }
        if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
            return worker.get_url().clone();
        }
        if let Some(worklet) = self.downcast::<WorkletGlobalScope>() {
            // TODO: is this the right URL to return?
            return worklet.base_url();
        }
        unreachable!();
    }

    /// Get the Referrer Policy for this global scope.
    pub fn get_referrer_policy(&self) -> ReferrerPolicy {
        if let Some(window) = self.downcast::<Window>() {
            let document = window.Document();

            return document.get_referrer_policy();
        }
        if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
            let policy_container = worker.policy_container().to_owned();

            return policy_container.get_referrer_policy();
        }
        unreachable!();
    }

    /// Determine the Referrer for a request whose Referrer is "client"
    pub fn get_referrer(&self) -> Referrer {
        // Step 3 of https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer
        if let Some(window) = self.downcast::<Window>() {
            // Substep 3.1

            // Substep 3.1.1
            let mut document = window.Document();

            // Substep 3.1.2
            if let ImmutableOrigin::Opaque(_) = document.origin().immutable() {
                return Referrer::NoReferrer;
            }

            let mut url = document.url();

            // Substep 3.1.3
            while url.as_str() == "about:srcdoc" {
                // Return early if we cannot get a parent document. This might happen if
                // this iframe was already removed from the parent page.
                let Some(parent_document) =
                    document.browsing_context().and_then(|browsing_context| {
                        browsing_context
                            .parent()
                            .and_then(|parent| parent.document())
                    })
                else {
                    return Referrer::NoReferrer;
                };
                document = parent_document;
                url = document.url();
            }

            // Substep 3.1.4
            Referrer::Client(url)
        } else {
            // Substep 3.2
            Referrer::Client(self.get_url())
        }
    }

    /// Extract a `Window`, panic if the global object is not a `Window`.
    pub fn as_window(&self) -> &Window {
        self.downcast::<Window>().expect("expected a Window scope")
    }

    /// <https://html.spec.whatwg.org/multipage/#report-the-error>
    pub fn report_an_error(&self, error_info: ErrorInfo, value: HandleValue, can_gc: CanGc) {
        // Step 1.
        if self.in_error_reporting_mode.get() {
            return;
        }

        // Step 2.
        self.in_error_reporting_mode.set(true);

        // Steps 3-6.
        // FIXME(#13195): muted errors.
        let event = ErrorEvent::new(
            self,
            atom!("error"),
            EventBubbles::DoesNotBubble,
            EventCancelable::Cancelable,
            error_info.message.as_str().into(),
            error_info.filename.as_str().into(),
            error_info.lineno,
            error_info.column,
            value,
            can_gc,
        );

        // Step 7.
        let event_status = event
            .upcast::<Event>()
            .fire(self.upcast::<EventTarget>(), can_gc);

        // Step 8.
        self.in_error_reporting_mode.set(false);

        // Step 9.
        if event_status == EventStatus::NotCanceled {
            // https://html.spec.whatwg.org/multipage/#runtime-script-errors-2
            if let Some(dedicated) = self.downcast::<DedicatedWorkerGlobalScope>() {
                dedicated.forward_error_to_worker_object(error_info);
            } else if self.is::<Window>() {
                if let Some(ref chan) = self.devtools_chan {
                    let _ = chan.send(ScriptToDevtoolsControlMsg::ReportPageError(
                        self.pipeline_id,
                        PageError {
                            type_: "PageError".to_string(),
                            error_message: error_info.message.clone(),
                            source_name: error_info.filename.clone(),
                            line_text: "".to_string(), //TODO
                            line_number: error_info.lineno,
                            column_number: error_info.column,
                            category: "script".to_string(),
                            time_stamp: SystemTime::now()
                                .duration_since(UNIX_EPOCH)
                                .unwrap_or_default()
                                .as_millis() as u64,
                            error: true,
                            warning: false,
                            exception: true,
                            strict: false,
                            private: false,
                        },
                    ));
                }
            }
        }
    }

    /// Get the `&ResourceThreads` for this global scope.
    pub fn resource_threads(&self) -> &ResourceThreads {
        &self.resource_threads
    }

    /// Get the `CoreResourceThread` for this global scope.
    pub fn core_resource_thread(&self) -> CoreResourceThread {
        self.resource_threads().sender()
    }

    /// `ScriptChan` to send messages to the event loop of this global scope.
    pub fn script_chan(&self) -> Box<dyn ScriptChan + Send> {
        if let Some(window) = self.downcast::<Window>() {
            return MainThreadScriptChan(window.main_thread_script_chan().clone()).clone();
        }
        if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
            return worker.script_chan();
        }
        unreachable!();
    }

    /// `TaskSource` to send messages to the gamepad task source of
    /// this global scope.
    /// <https://w3c.github.io/gamepad/#dfn-gamepad-task-source>
    pub fn gamepad_task_source(&self) -> GamepadTaskSource {
        if let Some(window) = self.downcast::<Window>() {
            return window.task_manager().gamepad_task_source();
        }
        unreachable!();
    }

    /// `TaskSource` to send messages to the networking task source of
    /// this global scope.
    pub fn networking_task_source(&self) -> NetworkingTaskSource {
        if let Some(window) = self.downcast::<Window>() {
            return window.task_manager().networking_task_source();
        }
        if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
            return worker.networking_task_source();
        }
        unreachable!();
    }

    /// `TaskSource` to send messages to the port message queue of
    /// this global scope.
    pub fn port_message_queue(&self) -> PortMessageQueue {
        if let Some(window) = self.downcast::<Window>() {
            return window.task_manager().port_message_queue();
        }
        if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
            return worker.port_message_queue();
        }
        unreachable!();
    }

    /// `TaskSource` to send messages to the timer queue of
    /// this global scope.
    pub fn timer_task_source(&self) -> TimerTaskSource {
        if let Some(window) = self.downcast::<Window>() {
            return window.task_manager().timer_task_source();
        }
        if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
            return worker.timer_task_source();
        }
        unreachable!();
    }

    /// `TaskSource` to send messages to the remote-event task source of
    /// this global scope.
    pub fn remote_event_task_source(&self) -> RemoteEventTaskSource {
        if let Some(window) = self.downcast::<Window>() {
            return window.task_manager().remote_event_task_source();
        }
        if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
            return worker.remote_event_task_source();
        }
        unreachable!();
    }

    /// `TaskSource` to send messages to the websocket task source of
    /// this global scope.
    pub fn websocket_task_source(&self) -> WebsocketTaskSource {
        if let Some(window) = self.downcast::<Window>() {
            return window.task_manager().websocket_task_source();
        }
        if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
            return worker.websocket_task_source();
        }
        unreachable!();
    }

    /// Evaluate JS code on this global scope.
    pub fn evaluate_js_on_global_with_result(
        &self,
        code: &str,
        rval: MutableHandleValue,
        fetch_options: ScriptFetchOptions,
        script_base_url: ServoUrl,
        can_gc: CanGc,
    ) -> bool {
        let source_code = SourceCode::Text(Rc::new(DOMString::from_string((*code).to_string())));
        self.evaluate_script_on_global_with_result(
            &source_code,
            "",
            rval,
            1,
            fetch_options,
            script_base_url,
            can_gc,
        )
    }

    /// Evaluate a JS script on this global scope.
    #[allow(unsafe_code)]
    #[allow(clippy::too_many_arguments)]
    pub fn evaluate_script_on_global_with_result(
        &self,
        code: &SourceCode,
        filename: &str,
        rval: MutableHandleValue,
        line_number: u32,
        fetch_options: ScriptFetchOptions,
        script_base_url: ServoUrl,
        can_gc: CanGc,
    ) -> bool {
        let cx = GlobalScope::get_cx();

        let ar = enter_realm(self);

        let _aes = AutoEntryScript::new(self);

        unsafe {
            rooted!(in(*cx) let mut compiled_script = std::ptr::null_mut::<JSScript>());
            match code {
                SourceCode::Text(text_code) => {
                    let options = CompileOptionsWrapper::new(*cx, filename, line_number);

                    debug!("compiling dom string");
                    compiled_script.set(Compile1(
                        *cx,
                        options.ptr,
                        &mut transform_str_to_source_text(text_code),
                    ));

                    if compiled_script.is_null() {
                        debug!("error compiling Dom string");
                        report_pending_exception(*cx, true, InRealm::Entered(&ar), can_gc);
                        return false;
                    }
                },
                SourceCode::Compiled(pre_compiled_script) => {
                    let options = InstantiateOptions {
                        skipFilenameValidation: false,
                        hideScriptFromDebugger: false,
                        deferDebugMetadata: false,
                    };
                    let script = InstantiateGlobalStencil(
                        *cx,
                        &options,
                        *pre_compiled_script.source_code,
                        ptr::null_mut(),
                    );
                    compiled_script.set(script);
                },
            };

            assert!(!compiled_script.is_null());

            rooted!(in(*cx) let mut script_private = UndefinedValue());
            JS_GetScriptPrivate(*compiled_script, script_private.handle_mut());

            // When `ScriptPrivate` for the compiled script is undefined,
            // we need to set it so that it can be used in dynamic import context.
            if script_private.is_undefined() {
                debug!("Set script private for {}", script_base_url);

                let module_script_data = Rc::new(ModuleScript::new(
                    script_base_url,
                    fetch_options,
                    // We can't initialize an module owner here because
                    // the executing context of script might be different
                    // from the dynamic import script's executing context.
                    None,
                ));

                SetScriptPrivate(
                    *compiled_script,
                    &PrivateValue(Rc::into_raw(module_script_data) as *const _),
                );
            }

            let result = JS_ExecuteScript(*cx, compiled_script.handle(), rval);

            if !result {
                debug!("error evaluating Dom string");
                report_pending_exception(*cx, true, InRealm::Entered(&ar), can_gc);
            }

            maybe_resume_unwind();
            result
        }
    }

    /// <https://html.spec.whatwg.org/multipage/#timer-initialisation-steps>
    pub fn schedule_callback(
        &self,
        callback: OneshotTimerCallback,
        duration: Duration,
    ) -> OneshotTimerHandle {
        self.setup_timers();
        self.timers
            .schedule_callback(callback, duration, self.timer_source())
    }

    pub fn unschedule_callback(&self, handle: OneshotTimerHandle) {
        self.timers.unschedule_callback(handle);
    }

    /// <https://html.spec.whatwg.org/multipage/#timer-initialisation-steps>
    pub fn set_timeout_or_interval(
        &self,
        callback: TimerCallback,
        arguments: Vec<HandleValue>,
        timeout: Duration,
        is_interval: IsInterval,
    ) -> i32 {
        self.setup_timers();
        self.timers.set_timeout_or_interval(
            self,
            callback,
            arguments,
            timeout,
            is_interval,
            self.timer_source(),
        )
    }

    pub fn clear_timeout_or_interval(&self, handle: i32) {
        self.timers.clear_timeout_or_interval(self, handle);
    }

    pub fn queue_function_as_microtask(&self, callback: Rc<VoidFunction>) {
        self.enqueue_microtask(Microtask::User(UserMicrotask {
            callback,
            pipeline: self.pipeline_id(),
        }))
    }

    #[allow(unsafe_code)]
    pub fn is_js_evaluation_allowed(&self, cx: SafeJSContext) -> bool {
        let Some(csp_list) = self.get_csp_list() else {
            return true;
        };

        let scripted_caller = unsafe { describe_scripted_caller(*cx) }.unwrap_or_default();
        let is_js_evaluation_allowed = csp_list.is_js_evaluation_allowed() == CheckResult::Allowed;

        if !is_js_evaluation_allowed {
            // FIXME: Don't fire event if `script-src` and `default-src`
            // were not passed.
            for policy in csp_list.0 {
                let task = CSPViolationReporter::new(
                    self,
                    None,
                    policy.disposition == PolicyDisposition::Report,
                    RuntimeCode::JS,
                    scripted_caller.filename.clone(),
                    scripted_caller.line,
                    scripted_caller.col,
                );
                self.dom_manipulation_task_source()
                    .queue(task, self)
                    .unwrap();
            }
        }

        is_js_evaluation_allowed
    }

    pub fn create_image_bitmap(
        &self,
        image: ImageBitmapSource,
        options: &ImageBitmapOptions,
        can_gc: CanGc,
    ) -> Rc<Promise> {
        let in_realm_proof = AlreadyInRealm::assert();
        let p = Promise::new_in_current_realm(InRealm::Already(&in_realm_proof), can_gc);
        if options.resizeWidth.is_some_and(|w| w == 0) {
            p.reject_error(Error::InvalidState);
            return p;
        }

        if options.resizeHeight.is_some_and(|w| w == 0) {
            p.reject_error(Error::InvalidState);
            return p;
        }

        match image {
            ImageBitmapSource::HTMLCanvasElement(ref canvas) => {
                // https://html.spec.whatwg.org/multipage/#check-the-usability-of-the-image-argument
                if !canvas.is_valid() {
                    p.reject_error(Error::InvalidState);
                    return p;
                }

                if let Some((data, size)) = canvas.fetch_all_data() {
                    let data = data
                        .map(|data| data.to_vec())
                        .unwrap_or_else(|| vec![0; size.area() as usize * 4]);

                    let image_bitmap = ImageBitmap::new(self, size.width, size.height).unwrap();

                    image_bitmap.set_bitmap_data(data);
                    image_bitmap.set_origin_clean(canvas.origin_is_clean());
                    p.resolve_native(&(image_bitmap));
                }
                p
            },
            ImageBitmapSource::OffscreenCanvas(ref canvas) => {
                // https://html.spec.whatwg.org/multipage/#check-the-usability-of-the-image-argument
                if !canvas.is_valid() {
                    p.reject_error(Error::InvalidState);
                    return p;
                }

                if let Some((data, size)) = canvas.fetch_all_data() {
                    let data = data
                        .map(|data| data.to_vec())
                        .unwrap_or_else(|| vec![0; size.area() as usize * 4]);

                    let image_bitmap = ImageBitmap::new(self, size.width, size.height).unwrap();
                    image_bitmap.set_bitmap_data(data);
                    image_bitmap.set_origin_clean(canvas.origin_is_clean());
                    p.resolve_native(&(image_bitmap));
                }
                p
            },
            _ => {
                p.reject_error(Error::NotSupported);
                p
            },
        }
    }

    pub fn fire_timer(&self, handle: TimerEventId, can_gc: CanGc) {
        self.timers.fire_timer(handle, self, can_gc);
    }

    pub fn resume(&self) {
        self.timers.resume();
    }

    pub fn suspend(&self) {
        self.timers.suspend();
    }

    pub fn slow_down_timers(&self) {
        self.timers.slow_down();
    }

    pub fn speed_up_timers(&self) {
        self.timers.speed_up();
    }

    fn timer_source(&self) -> TimerSource {
        if self.is::<Window>() {
            return TimerSource::FromWindow(self.pipeline_id());
        }
        if self.is::<WorkerGlobalScope>() {
            return TimerSource::FromWorker;
        }
        unreachable!();
    }

    /// Returns a boolean indicating whether the event-loop
    /// where this global is running on can continue running JS.
    pub fn can_continue_running(&self) -> bool {
        if self.is::<Window>() {
            return ScriptThread::can_continue_running();
        }
        if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
            return !worker.is_closing();
        }

        // TODO: plug worklets into this.
        true
    }

    /// Returns the task canceller of this global to ensure that everything is
    /// properly cancelled when the global scope is destroyed.
    pub fn task_canceller(&self, name: TaskSourceName) -> TaskCanceller {
        if let Some(window) = self.downcast::<Window>() {
            return window.task_manager().task_canceller(name);
        }
        if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
            // Note: the "name" is not passed to the worker,
            // because 'closing' it only requires one task canceller for all task sources.
            // https://html.spec.whatwg.org/multipage/#dom-workerglobalscope-closing
            return worker.task_canceller();
        }
        unreachable!();
    }

    /// Perform a microtask checkpoint.
    pub fn perform_a_microtask_checkpoint(&self, can_gc: CanGc) {
        // Only perform the checkpoint if we're not shutting down.
        if self.can_continue_running() {
            self.microtask_queue.checkpoint(
                GlobalScope::get_cx(),
                |_| Some(DomRoot::from_ref(self)),
                vec![DomRoot::from_ref(self)],
                can_gc,
            );
        }
    }

    /// Enqueue a microtask for subsequent execution.
    pub fn enqueue_microtask(&self, job: Microtask) {
        self.microtask_queue.enqueue(job, GlobalScope::get_cx());
    }

    /// Create a new sender/receiver pair that can be used to implement an on-demand
    /// event loop. Used for implementing web APIs that require blocking semantics
    /// without resorting to nested event loops.
    pub fn new_script_pair(&self) -> (Box<dyn ScriptChan + Send>, Box<dyn ScriptPort + Send>) {
        if let Some(window) = self.downcast::<Window>() {
            return window.new_script_pair();
        }
        if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
            return worker.new_script_pair();
        }
        unreachable!();
    }

    /// Returns the microtask queue of this global.
    pub fn microtask_queue(&self) -> &Rc<MicrotaskQueue> {
        &self.microtask_queue
    }

    /// Process a single event as if it were the next event
    /// in the queue for the event-loop where this global scope is running on.
    /// Returns a boolean indicating whether further events should be processed.
    pub fn process_event(&self, msg: CommonScriptMsg) -> bool {
        if self.is::<Window>() {
            return ScriptThread::process_event(msg);
        }
        if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
            return worker.process_event(msg);
        }
        unreachable!();
    }

    pub fn dom_manipulation_task_source(&self) -> DOMManipulationTaskSource {
        if let Some(window) = self.downcast::<Window>() {
            return window.task_manager().dom_manipulation_task_source();
        }
        if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
            return worker.dom_manipulation_task_source();
        }
        unreachable!();
    }

    /// Channel to send messages to the file reading task source of
    /// this of this global scope.
    pub fn file_reading_task_source(&self) -> FileReadingTaskSource {
        if let Some(window) = self.downcast::<Window>() {
            return window.task_manager().file_reading_task_source();
        }
        if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
            return worker.file_reading_task_source();
        }
        unreachable!();
    }

    pub fn runtime_handle(&self) -> ParentRuntime {
        if self.is::<Window>() {
            ScriptThread::runtime_handle()
        } else if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
            worker.runtime_handle()
        } else {
            unreachable!()
        }
    }

    /// Returns the ["current"] global object.
    ///
    /// ["current"]: https://html.spec.whatwg.org/multipage/#current
    #[allow(unsafe_code)]
    pub fn current() -> Option<DomRoot<Self>> {
        unsafe {
            let cx = Runtime::get();
            assert!(!cx.is_null());
            let global = CurrentGlobalOrNull(cx);
            if global.is_null() {
                None
            } else {
                Some(global_scope_from_global(global, cx))
            }
        }
    }

    /// Returns the ["entry"] global object.
    ///
    /// ["entry"]: https://html.spec.whatwg.org/multipage/#entry
    pub fn entry() -> DomRoot<Self> {
        entry_global()
    }

    /// Returns the ["incumbent"] global object.
    ///
    /// ["incumbent"]: https://html.spec.whatwg.org/multipage/#incumbent
    pub fn incumbent() -> Option<DomRoot<Self>> {
        incumbent_global()
    }

    pub fn performance(&self) -> DomRoot<Performance> {
        if let Some(window) = self.downcast::<Window>() {
            return window.Performance();
        }
        if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
            return worker.Performance();
        }
        unreachable!();
    }

    /// Channel to send messages to the performance timeline task source
    /// of this global scope.
    pub fn performance_timeline_task_source(&self) -> PerformanceTimelineTaskSource {
        if let Some(window) = self.downcast::<Window>() {
            return window.task_manager().performance_timeline_task_source();
        }
        if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
            return worker.performance_timeline_task_source();
        }
        unreachable!();
    }

    /// <https://w3c.github.io/performance-timeline/#supportedentrytypes-attribute>
    pub fn supported_performance_entry_types(&self, cx: SafeJSContext, retval: MutableHandleValue) {
        self.frozen_supported_performance_entry_types.get_or_init(
            || {
                VALID_ENTRY_TYPES
                    .iter()
                    .map(|t| DOMString::from(t.to_string()))
                    .collect()
            },
            cx,
            retval,
        );
    }

    pub fn is_headless(&self) -> bool {
        self.is_headless
    }

    pub fn get_user_agent(&self) -> Cow<'static, str> {
        self.user_agent.clone()
    }

    pub fn get_https_state(&self) -> HttpsState {
        self.https_state.get()
    }

    pub fn set_https_state(&self, https_state: HttpsState) {
        self.https_state.set(https_state);
    }

    pub fn is_secure_context(&self) -> bool {
        if Some(false) == self.inherited_secure_context {
            return false;
        }
        if let Some(creation_url) = self.creation_url() {
            if creation_url.scheme() == "blob" && Some(true) == self.inherited_secure_context {
                return true;
            }
            return creation_url.is_potentially_trustworthy();
        }
        false
    }

    /// <https://www.w3.org/TR/CSP/#get-csp-of-object>
    pub fn get_csp_list(&self) -> Option<CspList> {
        if self.downcast::<Window>().is_some() {
            return self.policy_container().csp_list;
        }
        // TODO: Worker and Worklet global scopes.
        None
    }

    pub fn status_code(&self) -> Option<u16> {
        if let Some(window) = self.downcast::<Window>() {
            return window.Document().status_code();
        }
        None
    }

    #[cfg(feature = "webgpu")]
    pub fn wgpu_id_hub(&self) -> Arc<IdentityHub> {
        self.gpu_id_hub.clone()
    }

    #[cfg(feature = "webgpu")]
    pub fn add_gpu_device(&self, device: &GPUDevice) {
        self.gpu_devices
            .borrow_mut()
            .insert(device.id(), WeakRef::new(device));
    }

    #[cfg(feature = "webgpu")]
    pub fn remove_gpu_device(&self, device: WebGPUDevice) {
        let device = self
            .gpu_devices
            .borrow_mut()
            .remove(&device)
            .expect("GPUDevice should still be in devices hashmap");
        assert!(device.root().is_none())
    }

    #[cfg(feature = "webgpu")]
    pub fn gpu_device_lost(&self, device: WebGPUDevice, reason: DeviceLostReason, msg: String) {
        let reason = match reason {
            DeviceLostReason::Unknown => GPUDeviceLostReason::Unknown,
            DeviceLostReason::Destroyed => GPUDeviceLostReason::Destroyed,
        };
        let _ac = enter_realm(self);
        if let Some(device) = self
            .gpu_devices
            .borrow_mut()
            .get_mut(&device)
            .expect("GPUDevice should still be in devices hashmap")
            .root()
        {
            device.lose(reason, msg);
        }
    }

    #[cfg(feature = "webgpu")]
    pub fn handle_uncaptured_gpu_error(
        &self,
        device: WebGPUDevice,
        error: webgpu::Error,
        can_gc: CanGc,
    ) {
        if let Some(gpu_device) = self
            .gpu_devices
            .borrow()
            .get(&device)
            .and_then(|device| device.root())
        {
            gpu_device.fire_uncaptured_error(error, can_gc);
        } else {
            warn!("Recived error for lost GPUDevice!")
        }
    }

    pub fn handle_gamepad_event(&self, gamepad_event: GamepadEvent) {
        match gamepad_event {
            GamepadEvent::Connected(index, name, bounds, supported_haptic_effects) => {
                self.handle_gamepad_connect(
                    index.0,
                    name,
                    bounds.axis_bounds,
                    bounds.button_bounds,
                    supported_haptic_effects,
                );
            },
            GamepadEvent::Disconnected(index) => {
                self.handle_gamepad_disconnect(index.0);
            },
            GamepadEvent::Updated(index, update_type) => {
                self.receive_new_gamepad_button_or_axis(index.0, update_type);
            },
        };
    }

    /// <https://www.w3.org/TR/gamepad/#dfn-gamepadconnected>
    fn handle_gamepad_connect(
        &self,
        // As the spec actually defines how to set the gamepad index, the GilRs index
        // is currently unused, though in practice it will almost always be the same.
        // More infra is currently needed to track gamepads across windows.
        _index: usize,
        name: String,
        axis_bounds: (f64, f64),
        button_bounds: (f64, f64),
        supported_haptic_effects: GamepadSupportedHapticEffects,
    ) {
        // TODO: 2. If document is not null and is not allowed to use the "gamepad" permission,
        //          then abort these steps.
        let this = Trusted::new(self);
        self.gamepad_task_source()
            .queue_with_canceller(
                task!(gamepad_connected: move || {
                    let global = this.root();

                    if let Some(window) = global.downcast::<Window>() {
                        let navigator = window.Navigator();
                        let selected_index = navigator.select_gamepad_index();
                        let gamepad = Gamepad::new(
                            &global,
                            selected_index,
                            name,
                            "standard".into(),
                            axis_bounds,
                            button_bounds,
                            supported_haptic_effects,
                            false,
                            CanGc::note(),
                        );
                        navigator.set_gamepad(selected_index as usize, &gamepad, CanGc::note());
                    }
                }),
                &self.task_canceller(TaskSourceName::Gamepad),
            )
            .expect("Failed to queue gamepad connected task.");
    }

    /// <https://www.w3.org/TR/gamepad/#dfn-gamepaddisconnected>
    pub fn handle_gamepad_disconnect(&self, index: usize) {
        let this = Trusted::new(self);
        self.gamepad_task_source()
            .queue_with_canceller(
                task!(gamepad_disconnected: move || {
                    let global = this.root();
                    if let Some(window) = global.downcast::<Window>() {
                        let navigator = window.Navigator();
                        if let Some(gamepad) = navigator.get_gamepad(index) {
                            if window.Document().is_fully_active() {
                                gamepad.update_connected(false, gamepad.exposed(), CanGc::note());
                                navigator.remove_gamepad(index);
                            }
                        }
                    }
                }),
                &self.task_canceller(TaskSourceName::Gamepad),
            )
            .expect("Failed to queue gamepad disconnected task.");
    }

    /// <https://www.w3.org/TR/gamepad/#receiving-inputs>
    pub fn receive_new_gamepad_button_or_axis(&self, index: usize, update_type: GamepadUpdateType) {
        let this = Trusted::new(self);

        // <https://w3c.github.io/gamepad/#dfn-update-gamepad-state>
        self.gamepad_task_source()
            .queue_with_canceller(
                task!(update_gamepad_state: move || {
                    let global = this.root();
                    if let Some(window) = global.downcast::<Window>() {
                        let navigator = window.Navigator();
                        if let Some(gamepad) = navigator.get_gamepad(index) {
                            let current_time = global.performance().Now();
                            gamepad.update_timestamp(*current_time);
                            match update_type {
                                GamepadUpdateType::Axis(index, value) => {
                                    gamepad.map_and_normalize_axes(index, value);
                                },
                                GamepadUpdateType::Button(index, value) => {
                                    gamepad.map_and_normalize_buttons(index, value);
                                }
                            };
                            if !navigator.has_gamepad_gesture() && contains_user_gesture(update_type) {
                                navigator.set_has_gamepad_gesture(true);
                                navigator.GetGamepads()
                                    .iter()
                                    .filter_map(|g| g.as_ref())
                                    .for_each(|gamepad| {
                                        gamepad.set_exposed(true);
                                        gamepad.update_timestamp(*current_time);
                                        let new_gamepad = Trusted::new(&**gamepad);
                                        if window.Document().is_fully_active() {
                                            window.task_manager().gamepad_task_source().queue_with_canceller(
                                                task!(update_gamepad_connect: move || {
                                                    let gamepad = new_gamepad.root();
                                                    gamepad.notify_event(GamepadEventType::Connected, CanGc::note());
                                                }),
                                                &window.upcast::<GlobalScope>()
                                                    .task_canceller(TaskSourceName::Gamepad),
                                            )
                                            .expect("Failed to queue update gamepad connect task.");
                                        }
                                });
                            }
                        }
                    }
                }),
                &self.task_canceller(TaskSourceName::Gamepad),
            )
            .expect("Failed to queue update gamepad state task.");
    }

    pub(crate) fn current_group_label(&self) -> Option<DOMString> {
        self.console_group_stack
            .borrow()
            .last()
            .map(|label| DOMString::from(format!("[{}]", label)))
    }

    pub(crate) fn push_console_group(&self, group: DOMString) {
        self.console_group_stack.borrow_mut().push(group);
    }

    pub(crate) fn pop_console_group(&self) {
        let _ = self.console_group_stack.borrow_mut().pop();
    }

    pub(crate) fn increment_console_count(&self, label: &DOMString) -> usize {
        *self
            .console_count_map
            .borrow_mut()
            .entry(label.clone())
            .and_modify(|e| *e += 1)
            .or_insert(1)
    }

    pub(crate) fn reset_console_count(&self, label: &DOMString) -> Result<(), ()> {
        match self.console_count_map.borrow_mut().get_mut(label) {
            Some(value) => {
                *value = 0;
                Ok(())
            },
            None => Err(()),
        }
    }

    pub(crate) fn dynamic_module_list(&self) -> RefMut<DynamicModuleList> {
        self.dynamic_modules.borrow_mut()
    }

    pub(crate) fn structured_clone(
        &self,
        cx: SafeJSContext,
        value: HandleValue,
        options: RootedTraceableBox<StructuredSerializeOptions>,
        retval: MutableHandleValue,
    ) -> Fallible<()> {
        let mut rooted = CustomAutoRooter::new(
            options
                .transfer
                .iter()
                .map(|js: &RootedTraceableBox<Heap<*mut JSObject>>| js.get())
                .collect(),
        );
        let guard = CustomAutoRooterGuard::new(*cx, &mut rooted);

        let data = structuredclone::write(cx, value, Some(guard))?;

        structuredclone::read(self, data, retval).map_err(|_| Error::DataClone)?;

        Ok(())
    }

    pub(crate) fn fetch<Listener: FetchResponseListener + PreInvoke + Send + 'static>(
        &self,
        request_builder: RequestBuilder,
        context: Arc<Mutex<Listener>>,
        task_source: NetworkingTaskSource,
        cancellation_sender: Option<ipc::IpcReceiver<()>>,
    ) {
        let canceller = Some(self.task_canceller(TaskSourceName::Networking));
        let network_listener = NetworkListener {
            context,
            task_source,
            canceller,
        };
        self.fetch_with_network_listener(request_builder, network_listener, cancellation_sender);
    }

    pub(crate) fn fetch_with_network_listener<
        Listener: FetchResponseListener + PreInvoke + Send + 'static,
    >(
        &self,
        request_builder: RequestBuilder,
        network_listener: NetworkListener<Listener>,
        cancellation_receiver: Option<ipc::IpcReceiver<()>>,
    ) {
        fetch_async(
            &self.core_resource_thread(),
            request_builder,
            cancellation_receiver,
            network_listener.into_callback(),
        );
    }

    pub fn unminified_js_dir(&self) -> Option<String> {
        self.unminified_js_dir.clone()
    }

    pub(crate) fn set_byte_length_queuing_strategy_size(&self, function: Rc<Function>) {
        if self
            .byte_length_queuing_strategy_size_function
            .set(function)
            .is_err()
        {
            warn!("byte length queuing strategy size function is set twice.");
        };
    }

    pub(crate) fn get_byte_length_queuing_strategy_size(&self) -> Option<Rc<Function>> {
        self.byte_length_queuing_strategy_size_function
            .get()
            .cloned()
    }

    pub(crate) fn set_count_queuing_strategy_size(&self, function: Rc<Function>) {
        if self
            .count_queuing_strategy_size_function
            .set(function)
            .is_err()
        {
            warn!("count queuing strategy size function is set twice.");
        };
    }

    pub(crate) fn get_count_queuing_strategy_size(&self) -> Option<Rc<Function>> {
        self.count_queuing_strategy_size_function.get().cloned()
    }
}

/// Returns the Rust global scope from a JS global object.
#[allow(unsafe_code)]
unsafe fn global_scope_from_global(
    global: *mut JSObject,
    cx: *mut JSContext,
) -> DomRoot<GlobalScope> {
    assert!(!global.is_null());
    let clasp = get_object_class(global);
    assert_ne!(
        ((*clasp).flags & (JSCLASS_IS_DOMJSCLASS | JSCLASS_IS_GLOBAL)),
        0
    );
    root_from_object(global, cx).unwrap()
}

/// Returns the Rust global scope from a JS global object.
#[allow(unsafe_code)]
unsafe fn global_scope_from_global_static(global: *mut JSObject) -> DomRoot<GlobalScope> {
    assert!(!global.is_null());
    let clasp = get_object_class(global);
    assert_ne!(
        ((*clasp).flags & (JSCLASS_IS_DOMJSCLASS | JSCLASS_IS_GLOBAL)),
        0
    );
    root_from_object_static(global).unwrap()
}