deno_node 0.192.0

Node compatibility for Deno
Documentation
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
// Copyright 2018-2026 the Deno authors. MIT license.

// deno-lint-ignore-file

import { core, internals, primordials } from "ext:core/mod.js";
import {
  op_fs_cwd,
  op_get_env_no_permission_check,
  op_import_sync,
  op_import_sync_with_source,
  op_module_default_resolve,
  op_module_hooks_poll_load,
  op_module_hooks_register,
  op_module_hooks_respond_load,
  op_napi_open,
  op_node_has_child_ipc_pipe,
  op_node_strip_typescript_types,
  op_require_as_file_path,
  op_require_break_on_next_statement,
  op_require_can_parse_as_esm,
  op_require_init_paths,
  op_require_is_deno_dir_package,
  op_require_is_maybe_cjs,
  op_require_is_request_relative,
  op_require_node_module_paths,
  op_require_package_imports_resolve,
  op_require_path_basename,
  op_require_path_dirname,
  op_require_path_is_absolute,
  op_require_path_resolve,
  op_require_proxy_path,
  op_require_read_file,
  op_require_read_package_scope,
  op_require_real_path,
  op_require_resolve_deno_dir,
  op_require_resolve_exports,
  op_require_resolve_lookup_paths,
  op_require_stat,
  op_require_try_self,
} from "ext:core/ops";
const {
  ArrayIsArray,
  ArrayPrototypeIncludes,
  ArrayPrototypeIndexOf,
  ArrayPrototypeJoin,
  ArrayPrototypeMap,
  ArrayPrototypePush,
  ArrayPrototypeSlice,
  ArrayPrototypeSort,
  ArrayPrototypeSplice,
  Error,
  JSONParse,
  ObjectCreate,
  ObjectDefineProperty,
  ObjectEntries,
  ObjectGetOwnPropertyDescriptor,
  ObjectGetPrototypeOf,
  ObjectHasOwn,
  ObjectKeys,
  ObjectPrototype,
  ObjectSetPrototypeOf,
  Proxy,
  ReflectSet,
  RegExpPrototypeExec,
  RegExpPrototypeTest,
  SafeArrayIterator,
  SafeMap,
  SafeSet,
  SafeWeakMap,
  SetPrototypeAdd,
  SetPrototypeDelete,
  SetPrototypeHas,
  String,
  StringPrototypeCharCodeAt,
  StringPrototypeEndsWith,
  StringPrototypeIncludes,
  StringPrototypeIndexOf,
  StringPrototypeLastIndexOf,
  StringPrototypeMatch,
  StringPrototypeReplace,
  StringPrototypeSlice,
  StringPrototypeSplit,
  StringPrototypeStartsWith,
  SyntaxError,
  TypeError,
} = primordials;

const _httpAgent = core.createLazyLoader("node:_http_agent");
const _httpCommon = core.createLazyLoader("node:_http_common");
const _httpOutgoing = core.createLazyLoader("node:_http_outgoing");
const _httpServer = core.createLazyLoader("node:_http_server");
// Heavy stream class definitions. Lazified - only loaded if a script
// actually `require('_stream_*')` or pulls them transitively via
// `node:stream` after our lazy stdio refactor.
// _tls_common, _tls_wrap are lazy-loaded via `lazyNodeModules` below: their
// scripts extend net.Socket at module body, which pulls node:net (and then
// node:stream) into the snapshot.
const { default: assert } = core.loadExtScript("ext:deno_node/assert.ts");
const assertStrict = core.createLazyLoader("node:assert/strict");
const asyncHooks = core.loadExtScript("ext:deno_node/async_hooks.ts").default;
const internalAsyncHooks = core.loadExtScript(
  "ext:deno_node/internal/async_hooks.ts",
);
const {
  emitAfter: internalAsyncHooksEmitAfter,
  emitBefore: internalAsyncHooksEmitBefore,
  emitDestroy: internalAsyncHooksEmitDestroy,
  emitInit: internalAsyncHooksEmitInit,
} = internalAsyncHooks;
const buffer = core.loadExtScript("ext:deno_node/internal/buffer.mjs").default;
// child_process, crypto, dgram are lazy-loaded via `lazyNodeModules` below.
// Their scripts use `createLazyLoader(...)()` patterns to extend classes
// from `node:stream`/`node:net`/etc. at module body time, which pulls the
// whole stream/net subtree into the snapshot if loaded eagerly. cluster
// stays eager because its body reads `NODE_CLUSTER_SCHED_POLICY` from env
// at module evaluation time, which requires Deno env permission at runtime
// but is freely granted at snapshot.
const cluster = core.loadExtScript("ext:deno_node/cluster.ts").default;
import console from "node:console";
const constants = core.loadExtScript("ext:deno_node/constants.ts").default;
const diagnosticsChannel =
  core.loadExtScript("ext:deno_node/diagnostics_channel.js").default;
const dns = core.loadExtScript("ext:deno_node/dns.ts").default;
const dnsPromises = core.loadExtScript(
  "ext:deno_node/dns/promises.ts",
).default;
const domain = core.loadExtScript("ext:deno_node/domain.ts").default;
const events = core.loadExtScript("ext:deno_node/_events.mjs").default;
const fs = core.loadExtScript("ext:deno_node/fs.ts");
// fs/promises is lazy-loaded via `lazyNodeModules` below: its script body
// does `createLazyLoader("node:fs")()` which loads `node:fs` (fs_esm.ts),
// whose body in turn reads the lazy createReadStream/Utf8Stream getters
// off `fs.ts` and pulls the whole internal/fs/streams + node:stream chain
// into the snapshot.
// http/http2/https are lazy-loaded via `lazyNodeModules` below: their script
// bodies eagerly chain into the entire node:_http_* / node:net / node:stream
// graph, so running them at snapshot time defeats lazifying _http_*.
const internalAssertMyersDiff = core.loadExtScript(
  "ext:deno_node/internal/assert/myers_diff.js",
);
// internal/child_process pulls deno_process/40_process.js -> 22_body
// -> 06_streams (208 KB). Lazy-loaded via lazyNodeModules.
const internalCryptoCertificate = core.loadExtScript(
  "ext:deno_node/internal/crypto/certificate.ts",
).default;
// internal/crypto/cipher is lazy-loaded via `lazyNodeModules` below: its
// script does `createLazyLoader("node:stream")()` at body time to extend
// `Transform`, which pulls the whole stream subtree into the snapshot.
const internalCryptoDiffiehellman = core.loadExtScript(
  "ext:deno_node/internal/crypto/diffiehellman.ts",
).default;
const internalCryptoHash = core.loadExtScript(
  "ext:deno_node/internal/crypto/hash.ts",
).default;
const internalCryptoHkdf = core.loadExtScript(
  "ext:deno_node/internal/crypto/hkdf.ts",
).default;
const internalCryptoKeygen = core.loadExtScript(
  "ext:deno_node/internal/crypto/keygen.ts",
).default;
const internalCryptoKeys = core.loadExtScript(
  "ext:deno_node/internal/crypto/keys.ts",
).default;
const internalCryptoPbkdf2 = core.loadExtScript(
  "ext:deno_node/internal/crypto/pbkdf2.ts",
).default;
const internalCryptoRandom = core.loadExtScript(
  "ext:deno_node/internal/crypto/random.ts",
).default;
const internalCryptoScrypt = core.loadExtScript(
  "ext:deno_node/internal/crypto/scrypt.ts",
).default;
const internalCryptoSig = core.loadExtScript(
  "ext:deno_node/internal/crypto/sig.ts",
).default;
const internalCryptoUtil = core.loadExtScript(
  "ext:deno_node/internal/crypto/util.ts",
).default;
const internalCryptoX509 = core.loadExtScript(
  "ext:deno_node/internal/crypto/x509.ts",
).default;
const internalDgram = core.loadExtScript(
  "ext:deno_node/internal/dgram.ts",
).default;
const internalUndici = core.loadExtScript(
  "ext:deno_node/internal/deps/undici/undici.js",
);
const internalDnsPromises = core.loadExtScript(
  "ext:deno_node/internal/dns/promises.ts",
).default;
const internalBuffer = core.loadExtScript("ext:deno_node/internal/buffer.mjs");
const internalErrors = core.loadExtScript("ext:deno_node/internal/errors.ts");
const internalEventTarget = core.createLazyLoader(
  "ext:deno_node/internal/event_target.mjs",
);
const internalFsUtils = core.createLazyLoader(
  "ext:deno_node/internal/fs/utils.mjs",
);
// `internal/fs/promises.ts` evaluates `lazyFs()` at top-level, so triggering
// its load during `setupBuiltinModules()` would re-enter the half-built
// `node:fs` namespace. A Proxy defers evaluation until the first time the
// requiring code reads a property; by then `node:fs` is fully initialized.
const lazyInternalFsPromises = core.createLazyLoader(
  "ext:deno_node/internal/fs/promises.ts",
);
let internalFsPromisesCache;
const internalFsPromisesProxy = new Proxy(ObjectCreate(null), {
  get(_target, prop) {
    return (internalFsPromisesCache ??= lazyInternalFsPromises())[prop];
  },
  has(_target, prop) {
    return prop in (internalFsPromisesCache ??= lazyInternalFsPromises());
  },
});
// internal/http, internal/http2/core, internal/http2/util are lazy-loaded
// via `lazyNodeModules` below. Loading them eagerly here pulls the entire
// http2 ESM chain (node:http2 -> http2.ts -> node:http -> http.ts -> the
// node:_http_* graph) into the snapshot, defeating the http/_http_*
// lazification we set up.
const internalPriorityQueue = core.loadExtScript(
  "ext:deno_node/internal/priority_queue.ts",
);
const internalReadlineUtils = core.loadExtScript(
  "ext:deno_node/internal/readline/utils.mjs",
);
const internalStreamsAddAbortSignal = core.loadExtScript(
  "ext:deno_node/internal/streams/add-abort-signal.js",
).default;
const internalStreamsLazyTransform = core.createLazyLoader(
  "ext:deno_node/internal/streams/lazy_transform.js",
);
const internalStreamsState =
  core.loadExtScript("ext:deno_node/internal/streams/state.js").default;
const internalSocketAddress = core.loadExtScript(
  "ext:deno_node/internal/socketaddress.js",
);
const internalTestBinding = core.loadExtScript(
  "ext:deno_node/internal/test/binding.ts",
);
const internalTimers = core.loadExtScript(
  "ext:deno_node/internal/timers.mjs",
);
const internalUrl = core.loadExtScript("ext:deno_node/internal/url.ts");
const internalUtil = core.loadExtScript("ext:deno_node/internal/util.mjs");
const internalUtilDebuglog = core.loadExtScript(
  "ext:deno_node/internal/util/debuglog.ts",
);
const internalUtilInspect = core.loadExtScript(
  "ext:deno_node/internal/util/inspect.mjs",
);
const internalValidators = core.loadExtScript(
  "ext:deno_node/internal/validators.mjs",
);
const internalConsole = core.loadExtScript(
  "ext:deno_node/internal/console/constructor.mjs",
).default;
const os = core.loadExtScript("ext:deno_node/os.ts").default;
import pathPosix from "node:path/posix";
import pathWin32 from "node:path/win32";
import path from "node:path";
const punycode = core.loadExtScript("ext:deno_node/punycode.ts").default;
// node:process is lazy now (see lib.rs / 98_global_scope_shared.js). 01_require
// only uses `process` inside require-time functions + the builtin map, never at
// module-eval, so resolving it lazily keeps the node process closure out of the
// snapshot for programs that never require()/touch process.
let _processLazy;
const _processMod =
  () => (_processLazy ??= core.createLazyLoader("node:process")().default);
const process = new Proxy({ __proto__: null }, {
  get: (_t, p) => _processMod()[p],
  has: (_t, p) => p in _processMod(),
  set: (_t, p, v) => {
    _processMod()[p] = v;
    return true;
  },
});
const readline = core.createLazyLoader("node:readline");
const readlinePromises = core.createLazyLoader("node:readline/promises");
const repl = core.createLazyLoader("node:repl");
const internalRepl = core.createLazyLoader(
  "ext:deno_node/internal/repl.ts",
);
// node:stream / node:net / node:tty and friends are lazy (see process.ts:
// process.stdout/stderr/stdin are lazy getters now, so nothing forces the
// stream/net/tty closure into the snapshot). stream/web pulls
// ext:deno_web/14_compression.js -> 06_streams (208 KB) too.
const stringDecoder =
  core.loadExtScript("ext:deno_node/string_decoder.ts").default;
const timers = core.loadExtScript("ext:deno_node/timers.ts");
const timersPromises = core.loadExtScript(
  "ext:deno_node/timers/promises.ts",
);
const tls = core.createLazyLoader("node:tls");
const url = core.loadExtScript("ext:deno_node/url.ts");
const util = core.loadExtScript("ext:deno_node/util.ts");
const utilTypes = core.loadExtScript("ext:deno_node/internal/util/types.ts");
const vm = core.loadExtScript("ext:deno_node/vm.js").default;
// worker_threads must stay eager: it registers `internals.__initWorkerThreads`
// / `internals.__isWorkerThread`, which the node process bootstrap calls
// (`__initWorkerThreads` at startup). It also statically imports node:vm, so
// vm stays in the snapshot regardless.
const workerThreads = core.loadExtScript(
  "ext:deno_node/worker_threads.ts",
);
// zlib is lazy-loaded via `lazyNodeModules` below: zlib.js extends
// `Transform` from `node:stream` at module body, so loading it eagerly
// pulls the stream subtree into the snapshot.
const internalOptions = core.loadExtScript(
  "ext:deno_node/internal/options.ts",
);
const { getOptionValue } = internalOptions;

const nativeModuleExports = ObjectCreate(null);
const builtinModules = [];

// Modules installed as lazy getters on `nativeModuleExports`. Each value is
// a `() => exports` thunk that's only invoked the first time the require name
// is accessed. Keeping these out of the eager `nodeModules` map means the
// snapshot does not have to compile their bodies (and everything those
// bodies transitively pull in via `loadExtScript`/`op_lazy_load_esm`).
// Use `() => createLazyLoader("...")().default` for `lazy_loaded_esm` entries
// and `() => loadExtScript("...")` for `lazy_loaded_js` entries.
const lazyNodeModules = {
  // Lazy so the WHATWG-streams adapter graph (stream/web -> deno_web
  // 06_streams, ~1.8MB of snapshot heap) is only loaded when something
  // actually requires these internals, not eagerly at node:module init.
  "internal/worker/js_transferable": () =>
    core.loadExtScript("ext:deno_node/internal/worker/js_transferable.js"),
  "internal/webstreams/adapters": () =>
    core.loadExtScript("ext:deno_node/internal/webstreams/adapters.js"),
  "internal/webstreams/readablestream": () =>
    core.loadExtScript("ext:deno_node/internal/webstreams/readablestream.js"),
  "internal/webstreams/util": () =>
    core.loadExtScript("ext:deno_node/internal/webstreams/util.js"),
  "_http_agent": () => _httpAgent().default,
  "_http_common": () => _httpCommon().default,
  "_http_outgoing": () => _httpOutgoing().default,
  "_http_server": () => _httpServer().default,
  "http": () => core.loadExtScript("ext:deno_node/http.ts"),
  "http2": () => core.loadExtScript("ext:deno_node/http2.ts"),
  "https": () => core.loadExtScript("ext:deno_node/https.ts"),
  "internal/http": () =>
    core.loadExtScript("ext:deno_node/internal/http.ts").default,
  "internal/http2/core": () =>
    core.loadExtScript("ext:deno_node/internal/http2/core.ts").default,
  "internal/http2/util": () =>
    core.loadExtScript("ext:deno_node/internal/http2/util.ts").default,
  "internal/streams/lazy_transform": () =>
    internalStreamsLazyTransform().default,
  "child_process": () => core.loadExtScript("ext:deno_node/child_process.ts"),
  "crypto": () => core.loadExtScript("ext:deno_node/crypto.ts").default,
  "dgram": () => core.loadExtScript("ext:deno_node/dgram.ts").default,
  "zlib": () => core.loadExtScript("ext:deno_node/zlib.js"),
  "tls": () => tls().default,
  "internal/crypto/cipher": () =>
    core.loadExtScript("ext:deno_node/internal/crypto/cipher.ts").default,
  "_tls_common": () =>
    core.loadExtScript("ext:deno_node/_tls_common.ts").default,
  "_tls_wrap": () => core.loadExtScript("ext:deno_node/_tls_wrap.js").default,
  "repl": () => repl().default,
  "internal/repl": () => internalRepl().default,
  "fs/promises": () =>
    core.loadExtScript("ext:deno_node/fs/promises.ts").fsPromises,
  "test/reporters": () =>
    core.loadExtScript("ext:deno_node/test/reporters.ts").default,
  "assert/strict": () => assertStrict().default,
  "internal/event_target": () => internalEventTarget().default,
  "internal/fs/utils": () => internalFsUtils().default,
  "readline": () => readline().default,
  "readline/promises": () => readlinePromises().default,
  "internal/child_process": () =>
    core.loadExtScript("ext:deno_node/internal/child_process.ts").default,
  "stream/web": () => core.loadExtScript("ext:deno_node/stream/web.js"),
  "internal/js_stream_socket": () =>
    core.loadExtScript("ext:deno_node/internal/js_stream_socket.js").default,
  "internal/net": () => core.loadExtScript("ext:deno_node/internal/net.ts"),
  "internal/tty": () =>
    core.createLazyLoader("ext:deno_node/internal/tty.js")(),
  "net": () => core.createLazyLoader("node:net")().default,
  // `process` must lazy-resolve to the real `node:process` default export
  // (the proxy at the top of this file is for internal use only). When
  // `getBuiltinModule('process')` is called we want the actual singleton so
  // strict-equality against the global `process` holds.
  "process": () => core.createLazyLoader("node:process")().default,
  // node:stream/net/tty closure - lazy now that process.stdout/stderr/stdin
  // are lazy getters (see process.ts). These are the biggest node snapshot
  // chunk, so keeping them out of the eager heap is the main startup win.
  "stream": () => core.createLazyLoader("node:stream")().default,
  "stream/consumers": () =>
    core.loadExtScript("ext:deno_node/stream/consumers.js"),
  "stream/promises": () =>
    core.createLazyLoader("node:stream/promises")().default,
  "tty": () => core.createLazyLoader("node:tty")().default,
  // Rarely needed on the cold-start path; keeping these out of the eager
  // `nodeModules` map keeps their bodies (and transitive `loadExtScript`
  // closure) out of the snapshot heap, so they aren't deserialized at every
  // startup. Match the previous `.default`/no-`.default` shape exactly.
  "inspector": () => core.loadExtScript("ext:deno_node/inspector.js"),
  "inspector/promises": () =>
    core.loadExtScript("ext:deno_node/inspector/promises.js"),
  "perf_hooks": () => core.loadExtScript("ext:deno_node/perf_hooks.js").default,
  "querystring": () =>
    core.loadExtScript("ext:deno_node/querystring.js").default,
  "sqlite": () => core.loadExtScript("ext:deno_node/sqlite.ts"),
  "test": () => core.loadExtScript("ext:deno_node/testing.ts").default,
  "trace_events": () =>
    core.loadExtScript("ext:deno_node/trace_events.ts").default,
  "v8": () => core.loadExtScript("ext:deno_node/v8.ts"),
  "wasi": () => core.loadExtScript("ext:deno_node/wasi.ts").default,
  "_stream_duplex": () =>
    core.loadExtScript("ext:deno_node/internal/streams/duplex.js").default,
  "_stream_passthrough": () =>
    core.loadExtScript("ext:deno_node/internal/streams/passthrough.js").default,
  "_stream_readable": () =>
    core.loadExtScript("ext:deno_node/internal/streams/readable.js").default,
  "_stream_transform": () =>
    core.loadExtScript("ext:deno_node/internal/streams/transform.js").default,
  "_stream_writable": () =>
    core.loadExtScript("ext:deno_node/internal/streams/writable.js").default,
};

function defineLazyNativeModule(name, loader) {
  ObjectDefineProperty(nativeModuleExports, name, {
    __proto__: null,
    get() {
      const value = loader();
      ObjectDefineProperty(nativeModuleExports, name, {
        __proto__: null,
        value,
        writable: true,
        enumerable: true,
        configurable: true,
      });
      return value;
    },
    enumerable: true,
    configurable: true,
  });
}

// NOTE(bartlomieju): keep this list in sync with `ext/node/lib.rs`
function setupBuiltinModules() {
  const nodeModules = {
    assert,
    "async_hooks": asyncHooks,
    buffer,
    cluster,
    console,
    constants,
    diagnostics_channel: diagnosticsChannel,
    dns,
    "dns/promises": dnsPromises,
    domain,
    events,
    fs,
    "internal/assert/myers_diff": internalAssertMyersDiff.default,
    "internal/async_hooks": internalAsyncHooks,
    "internal/console/constructor": internalConsole,
    "internal/crypto/certificate": internalCryptoCertificate,
    "internal/crypto/diffiehellman": internalCryptoDiffiehellman,
    "internal/crypto/hash": internalCryptoHash,
    "internal/crypto/hkdf": internalCryptoHkdf,
    "internal/crypto/keygen": internalCryptoKeygen,
    "internal/crypto/keys": internalCryptoKeys,
    "internal/crypto/pbkdf2": internalCryptoPbkdf2,
    "internal/crypto/random": internalCryptoRandom,
    "internal/crypto/scrypt": internalCryptoScrypt,
    "internal/crypto/sig": internalCryptoSig,
    "internal/crypto/util": internalCryptoUtil,
    "internal/crypto/x509": internalCryptoX509,
    "internal/dgram": internalDgram,
    "internal/deps/undici/undici": internalUndici.default,
    "internal/dns/promises": internalDnsPromises,
    "internal/buffer": internalBuffer.default,
    "internal/errors": internalErrors,
    "internal/fs/promises": internalFsPromisesProxy,
    "internal/priority_queue": internalPriorityQueue.default,
    "internal/readline/utils": internalReadlineUtils.default,
    "internal/streams/add-abort-signal": internalStreamsAddAbortSignal,
    "internal/streams/state": internalStreamsState,
    "internal/socketaddress": internalSocketAddress,
    "internal/options": internalOptions,
    "internal/test/binding": internalTestBinding,
    "internal/timers": internalTimers,
    "internal/url": internalUrl,
    "internal/util/debuglog": internalUtilDebuglog.default,
    "internal/util/inspect": internalUtilInspect,
    "internal/util": internalUtil,
    "internal/validators": internalValidators,
    module: Module,
    os,
    "path/posix": pathPosix,
    "path/win32": pathWin32,
    path,
    // `process` is registered lazily below (see `lazyNodeModules`) so that
    // `getBuiltinModule('process')` returns the real `node:process` default
    // export rather than the proxy stand-in used elsewhere in this file.
    // NOTE(perf): punycode's deprecation warning previously used `process` in a
    // getter, which ObjectEntries() invoked at module-eval -> loaded node:process
    // into the snapshot. Plain entry now (deprecation warning dropped pending
    // proper lazy wiring).
    punycode,
    string_decoder: stringDecoder,
    sys: util,
    timers,
    "timers/promises": timersPromises,
    url,
    util,
    "util/types": utilTypes,
    vm,
    worker_threads: workerThreads,
  };
  // Match Node's schemelessBlockList: these modules can only be imported
  // via the `node:` scheme (see lib/internal/bootstrap/realm.js), so they
  // appear in `builtinModules` as `node:<name>` rather than `<name>`.
  const schemelessBlockList = new SafeSet([
    "sqlite",
    "test",
    "test/reporters",
  ]);
  function registerName(name) {
    // `internal/*` modules are only exposed under --expose-internals, so
    // they aren't part of the public builtinModules list.
    if (StringPrototypeStartsWith(name, "internal/")) {
      return;
    }
    if (SetPrototypeHas(schemelessBlockList, name)) {
      ArrayPrototypePush(builtinModules, `node:${name}`);
    } else {
      ArrayPrototypePush(builtinModules, name);
    }
  }
  for (const [name, moduleExports] of ObjectEntries(nodeModules)) {
    nativeModuleExports[name] = moduleExports;
    registerName(name);
  }
  for (const [name, loader] of ObjectEntries(lazyNodeModules)) {
    defineLazyNativeModule(name, loader);
    registerName(name);
  }
}
setupBuiltinModules();

function pathDirname(filepath) {
  if (filepath == null) {
    throw new Error("Empty filepath.");
  } else if (filepath === "") {
    return ".";
  }
  return op_require_path_dirname(filepath);
}

function pathResolve(...args) {
  return op_require_path_resolve(args);
}

const nativeModulePolyfill = new SafeMap();

const relativeResolveCache = ObjectCreate(null);
let requireDepth = 0;
let statCache = null;
let mainModule = null;
let hasBrokenOnInspectBrk = false;
let hasInspectBrk = false;
// Are we running with --node-modules-dir flag or byonm?
let usesLocalNodeModulesDir = false;
let patched = false;

// module.registerHooks() infrastructure
const hookEntries = [];
const cjsHookResolvedFilenames = new SafeSet();
let insideResolveHook = false;
let insideLoadHook = false;
let utf8Decoder;
let esmLoadLoopRunning = false;
const requireResolveOptionsMarker = Symbol("require.resolve");
const kSourceURL = Symbol("kSourceURL");

function executeResolveHookChain(specifier, context, parent, isMain, options) {
  // Collect resolve hooks from hookEntries in LIFO order
  const resolveHooks = [];
  for (let i = hookEntries.length - 1; i >= 0; i--) {
    if (hookEntries[i].resolve !== null) {
      ArrayPrototypePush(resolveHooks, hookEntries[i].resolve);
    }
  }
  if (resolveHooks.length === 0) return null;

  let index = 0;
  // Running context accumulates changes across the chain
  let currentContext = context;

  function nextResolve(spec, ctx) {
    // If ctx provided, merge into running context
    if (ctx !== undefined && ctx !== null) {
      currentContext = { ...currentContext, ...ctx };
    }

    if (index >= resolveHooks.length) {
      // Default resolve: use Module._resolveFilename
      insideResolveHook = true;
      try {
        // Handle node: builtins
        if (StringPrototypeStartsWith(spec, "node:")) {
          return { url: spec, shortCircuit: true };
        }
        if (nativeModuleCanBeRequiredByUsers(spec)) {
          return { url: "node:" + spec, shortCircuit: true };
        }
        const resolved = Module._resolveFilename(
          spec,
          parent,
          isMain,
          options,
        );
        let resolvedUrl;
        if (StringPrototypeStartsWith(resolved, "node:")) {
          resolvedUrl = resolved;
        } else {
          resolvedUrl = url.pathToFileURL(resolved).href;
        }
        return { url: resolvedUrl, shortCircuit: true };
      } finally {
        insideResolveHook = false;
      }
    }
    const hook = resolveHooks[index++];
    let nextCalled = false;
    const wrappedNext = (s, c) => {
      nextCalled = true;
      return nextResolve(s, c);
    };
    const result = hook(spec, currentContext, wrappedNext);
    if (!nextCalled && !result?.shortCircuit) {
      throw new internalErrors.ERR_INVALID_RETURN_PROPERTY_VALUE(
        "true",
        "resolve",
        "shortCircuit",
        result?.shortCircuit,
      );
    }
    if (result?.shortCircuit && typeof result?.url !== "string") {
      const err = new TypeError(
        'Expected a URL string to be returned for the "url" from the "resolve" hook',
      );
      err.code = "ERR_INVALID_RETURN_PROPERTY_VALUE";
      throw err;
    }
    return result;
  }

  return nextResolve(specifier, context);
}

function executeLoadHookChain(fileUrl, context) {
  // Collect load hooks from hookEntries in LIFO order
  const loadHooks = [];
  for (let i = hookEntries.length - 1; i >= 0; i--) {
    if (hookEntries[i].load !== null) {
      ArrayPrototypePush(loadHooks, hookEntries[i].load);
    }
  }
  if (loadHooks.length === 0) return null;

  let index = 0;
  let currentContext = context;

  function nextLoad(loadUrl, ctx) {
    if (ctx !== undefined && ctx !== null) {
      currentContext = { ...currentContext, ...ctx };
    }

    if (index >= loadHooks.length) {
      // Default load: read file from disk
      // For builtins, return null source
      if (StringPrototypeStartsWith(loadUrl, "node:")) {
        return { source: null, format: "builtin", shortCircuit: true };
      }
      const filePath = StringPrototypeStartsWith(loadUrl, "file://")
        ? url.fileURLToPath(loadUrl)
        : loadUrl;
      const source = op_require_read_file(filePath);
      return {
        source,
        format: currentContext?.format ?? undefined,
        shortCircuit: true,
      };
    }
    const hook = loadHooks[index++];
    let nextCalled = false;
    const wrappedNext = (u, c) => {
      nextCalled = true;
      return nextLoad(u, c);
    };
    const result = hook(loadUrl, currentContext, wrappedNext);
    if (!nextCalled && !result?.shortCircuit) {
      throw new internalErrors.ERR_INVALID_RETURN_PROPERTY_VALUE(
        "true",
        "load",
        "shortCircuit",
        result?.shortCircuit,
      );
    }
    if (
      result?.shortCircuit &&
      !isValidLoadHookSource(result?.source, result?.format)
    ) {
      const err = new TypeError(
        'Expected a string, an ArrayBuffer, or a TypedArray to be returned for the "source" from the "load" hook',
      );
      err.code = "ERR_INVALID_RETURN_PROPERTY_VALUE";
      throw err;
    }
    return result;
  }

  return nextLoad(fileUrl, context);
}

function isValidLoadHookSource(source, format) {
  if (source === null) {
    return format === "builtin";
  }
  return typeof source === "string" ||
    core.isAnyArrayBuffer(source) ||
    core.isArrayBufferView(source);
}

function loadHookSourceToString(source) {
  if (typeof source === "string") {
    return source;
  }
  if (core.isAnyArrayBuffer(source)) {
    return (utf8Decoder ??= new TextDecoder()).decode(new Uint8Array(source));
  }
  return (utf8Decoder ??= new TextDecoder()).decode(
    new Uint8Array(source.buffer, source.byteOffset, source.byteLength),
  );
}

// ESM resolve hook chain: runs hooks in LIFO order.
// Returns { url } if hooks resolved, or null for fallthrough to default.
function executeEsmResolveHookChain(specifier, context) {
  const resolveHooks = [];
  for (let i = hookEntries.length - 1; i >= 0; i--) {
    if (hookEntries[i].resolve !== null) {
      ArrayPrototypePush(resolveHooks, hookEntries[i].resolve);
    }
  }
  if (resolveHooks.length === 0) return null;

  let index = 0;
  let currentContext = context;

  function nextResolve(spec, ctx) {
    if (ctx !== undefined && ctx !== null) {
      currentContext = { ...currentContext, ...ctx };
    }
    if (index >= resolveHooks.length) {
      if (StringPrototypeStartsWith(spec, "node:")) {
        return { url: spec, shortCircuit: true };
      }
      insideResolveHook = true;
      try {
        const resolved = op_module_default_resolve(
          spec,
          currentContext.parentURL ?? "",
        );
        return { url: resolved, shortCircuit: true };
      } catch {
        // Last-ditch fallback so hooks can still observe purely synthetic
        // specifiers that Deno's resolver rejects (e.g. ad-hoc URLs invented
        // by user code).
        try {
          const resolved = new URL(spec, currentContext.parentURL).href;
          return { url: resolved, shortCircuit: true };
        } catch {
          return { url: null, shortCircuit: true };
        }
      } finally {
        insideResolveHook = false;
      }
    }
    const hook = resolveHooks[index++];
    let nextCalled = false;
    const wrappedNext = (s, c) => {
      nextCalled = true;
      return nextResolve(s, c);
    };
    const result = hook(spec, currentContext, wrappedNext);
    if (!nextCalled && !result?.shortCircuit) {
      throw new TypeError(
        "resolve hook must return { shortCircuit: true } or call nextResolve",
      );
    }
    return result;
  }

  return nextResolve(specifier, context);
}

function esmResolveHookCallback(specifier, referrer, importAttributes) {
  const attrs = { __proto__: null };
  if (importAttributes !== null && typeof importAttributes === "object") {
    for (const key in importAttributes) {
      attrs[key] = importAttributes[key];
    }
  }
  const context = {
    parentURL: referrer || undefined,
    conditions: ["node", "import", "module-sync", "node-addons"],
    importAttributes: attrs,
  };
  try {
    const result = executeEsmResolveHookChain(specifier, context);
    return result?.url ?? null;
  } catch (e) {
    return { error: String(e) };
  }
}

// ESM load hook chain: runs hooks in LIFO order.
// Returns `null` when no load hooks are registered, otherwise
// `{ result, effectiveUrl }` where `result` is the hook chain's return value
// and `effectiveUrl` is the URL the chain ultimately delegated to via
// `nextLoad(newUrl)`: used by the load loop when falling through to Rust
// default loading so the source comes from the URL the user redirected to,
// not the original.
function executeEsmLoadHookChain(fileUrl, context) {
  const loadHooks = [];
  for (let i = hookEntries.length - 1; i >= 0; i--) {
    if (hookEntries[i].load !== null) {
      ArrayPrototypePush(loadHooks, hookEntries[i].load);
    }
  }
  if (loadHooks.length === 0) return null;

  let index = 0;
  let currentContext = context;
  let effectiveUrl = fileUrl;

  function nextLoad(loadUrl, ctx) {
    effectiveUrl = loadUrl;
    if (ctx !== undefined && ctx !== null) {
      currentContext = { ...currentContext, ...ctx };
    }
    if (index >= loadHooks.length) {
      // End of chain. Synthesize a default load result so user hooks
      // that call `await nextLoad(...)` observe a real `source` they
      // can transform (matches Node, where `defaultLoad` returns the
      // on-disk source).
      if (StringPrototypeStartsWith(loadUrl, "node:")) {
        return { source: null, format: "builtin", shortCircuit: true };
      }
      if (StringPrototypeStartsWith(loadUrl, "file://")) {
        // `type: "bytes"` modules cannot be faithfully represented as a JS
        // string here; fall through to Rust default loading, which reads the
        // file as bytes and produces a correctly-typed module. (Reading it as
        // a string would otherwise trip "Source code for Bytes module must be
        // provided as bytes".)
        if (currentContext?.importAttributes?.type === "bytes") {
          return { source: null, shortCircuit: true };
        }
        try {
          const source = op_require_read_file(url.fileURLToPath(loadUrl));
          return {
            source,
            format: currentContext?.format,
            shortCircuit: true,
          };
        } catch {
          // Any sync read failure (file absent from disk because it's
          // embedded in a compiled binary's eszip, permission errors,
          // transient IO) falls through to Rust default loading via
          // the load loop, which surfaces a clearer error if the
          // module truly cannot be loaded.
          return { source: null, shortCircuit: true };
        }
      }
      // For other schemes (data:, http(s):, etc.) we cannot synchronously
      // produce source here; fall through to Rust default loading.
      return { source: null, shortCircuit: true };
    }
    const hook = loadHooks[index++];
    let nextCalled = false;
    const wrappedNext = (u, c) => {
      nextCalled = true;
      return nextLoad(u, c);
    };
    const result = hook(loadUrl, currentContext, wrappedNext);
    if (!nextCalled && !result?.shortCircuit) {
      throw new TypeError(
        "load hook must return { shortCircuit: true } or call nextLoad",
      );
    }
    return result;
  }

  const result = nextLoad(fileUrl, context);
  return { result, effectiveUrl };
}

function _startEsmLoadLoop() {
  if (esmLoadLoopRunning) return;
  esmLoadLoopRunning = true;
  (async () => {
    while (true) {
      const pollPromise = op_module_hooks_poll_load();
      core.unrefOpPromise(pollPromise);
      const req = await pollPromise;
      if (req === null) break;
      const [id, fileUrl, rawAttributes] = req;
      const importAttributes = { __proto__: null };
      if (rawAttributes !== null && typeof rawAttributes === "object") {
        for (const key in rawAttributes) {
          importAttributes[key] = rawAttributes[key];
        }
      }
      const context = {
        format: undefined,
        conditions: ["node", "import", "module-sync", "node-addons"],
        importAttributes,
      };
      try {
        const chainResult = executeEsmLoadHookChain(fileUrl, context);
        const result = chainResult?.result ?? null;
        const effectiveUrl = chainResult?.effectiveUrl ?? null;
        if (result?.format === "builtin") {
          op_module_hooks_respond_load(id, null, "builtin", null, null);
        } else if (result !== null && result.source != null) {
          const source = loadHookSourceToString(result.source);
          const format = result.format || null;
          op_module_hooks_respond_load(id, source, format, null, null);
        } else {
          // Fallthrough: tell Rust to use default loading. Pass the URL the
          // hook chain ultimately delegated to (may differ from the original
          // when a hook called `nextLoad(newUrl)`) so source is fetched from
          // there while the module keeps the original URL as its identity.
          op_module_hooks_respond_load(id, null, null, null, effectiveUrl);
        }
      } catch (e) {
        op_module_hooks_respond_load(id, null, null, String(e), null);
      }
    }
  })();
}

function _activateEsmHooks() {
  let hasResolve = false;
  let hasLoad = false;
  for (let i = 0; i < hookEntries.length; i++) {
    if (hookEntries[i].resolve !== null) hasResolve = true;
    if (hookEntries[i].load !== null) hasLoad = true;
  }
  op_module_hooks_register(hasResolve ? esmResolveHookCallback : null, hasLoad);
  if (hasLoad) _startEsmLoadLoop();
}

let internalModuleStat = op_require_stat;

function stat(filename) {
  if (statCache !== null) {
    const result = statCache.get(filename);
    if (result !== undefined) {
      return result;
    }
  }
  const result = internalModuleStat(filename);
  if (statCache !== null && result >= 0) {
    statCache.set(filename, result);
  }

  return result;
}

function updateChildren(parent, child, scan) {
  if (!parent) {
    return;
  }

  const children = parent.children;
  if (children && !(scan && ArrayPrototypeIncludes(children, child))) {
    ArrayPrototypePush(children, child);
  }
}

// Given a path inside a node_modules tree, find the package root by
// locating the last "node_modules" path component and taking the next
// segment (or two for scoped packages). Returns null if no node_modules
// component is found.
function findPackageRootFromNodeModules(filepath) {
  // Find the last occurrence of /node_modules/ or \node_modules\ in the path
  let nmIdx = -1;
  let sep = "/";
  const fwdIdx = StringPrototypeLastIndexOf(filepath, "/node_modules/");
  const bwdIdx = StringPrototypeLastIndexOf(filepath, "\\node_modules\\");
  if (fwdIdx !== -1 && fwdIdx > bwdIdx) {
    nmIdx = fwdIdx;
    sep = "/";
  } else if (bwdIdx !== -1) {
    nmIdx = bwdIdx;
    sep = "\\";
  }
  if (nmIdx === -1) return null;

  const afterNm = nmIdx + sep.length + "node_modules".length + sep.length;
  const rest = StringPrototypeSlice(filepath, afterNm);
  const parts = StringPrototypeSplit(rest, sep);
  if (parts.length === 0 || parts[0] === "") return null;

  if (StringPrototypeStartsWith(parts[0], "@") && parts.length > 1) {
    // Scoped package: @scope/name
    return StringPrototypeSlice(filepath, 0, afterNm) + parts[0] + sep +
      parts[1];
  }
  return StringPrototypeSlice(filepath, 0, afterNm) + parts[0];
}

function tryFile(requestPath, _isMain) {
  const rc = stat(requestPath);
  if (rc !== 0) return;
  return toRealPath(requestPath);
}

function tryPackage(requestPath, exts, isMain, originalPath) {
  const packageJsonPath = pathResolve(
    requestPath,
    "package.json",
  );
  const pkg = op_require_read_package_scope(packageJsonPath)?.main;
  if (!pkg) {
    return tryExtensions(
      pathResolve(requestPath, "index"),
      exts,
      isMain,
    );
  }

  const filename = pathResolve(requestPath, pkg);

  // Find the package root for the path traversal check. For nested
  // package.json files inside node_modules (e.g. pkg/sub/package.json with
  // "main": "../cjs/sub.js"), we allow resolving up to the package root
  // (node_modules/pkg/) rather than restricting to the nested directory.
  const packageRoot = findPackageRootFromNodeModules(requestPath) ??
    requestPath;

  // Ensure the resolved main path doesn't escape the package directory
  // via path traversal (e.g. "main": "../../secret.json")
  if (
    !StringPrototypeStartsWith(filename, packageRoot + "/") &&
    !StringPrototypeStartsWith(filename, packageRoot + "\\") &&
    filename !== packageRoot
  ) {
    const err = new Error(
      `Cannot find module '${filename}'. ` +
        'Please verify that the package.json has a valid "main" entry',
    );
    err.code = "MODULE_NOT_FOUND";
    err.path = pathResolve(requestPath, "package.json");
    err.requestPath = originalPath;
    throw err;
  }
  let actual = tryFile(filename, isMain) ||
    tryExtensions(filename, exts, isMain) ||
    tryExtensions(
      pathResolve(filename, "index"),
      exts,
      isMain,
    );
  if (actual === false) {
    actual = tryExtensions(
      pathResolve(requestPath, "index"),
      exts,
      isMain,
    );
    if (!actual) {
      // eslint-disable-next-line no-restricted-syntax
      const err = new Error(
        `Cannot find module '${filename}'. ` +
          'Please verify that the package.json has a valid "main" entry',
      );
      err.code = "MODULE_NOT_FOUND";
      err.path = pathResolve(
        requestPath,
        "package.json",
      );
      err.requestPath = originalPath;
      throw err;
    } else {
      process.emitWarning(
        `Invalid 'main' field in '${packageJsonPath}' of '${pkg}'. ` +
          "Please either fix that or report it to the module author",
        "DeprecationWarning",
        "DEP0128",
      );
    }
  }
  return actual;
}

const realpathCache = new SafeMap();
function toRealPath(requestPath) {
  const maybeCached = realpathCache.get(requestPath);
  if (maybeCached) {
    return maybeCached;
  }
  const rp = op_require_real_path(requestPath);
  realpathCache.set(requestPath, rp);
  return rp;
}

function tryExtensions(p, exts, isMain) {
  for (let i = 0; i < exts.length; i++) {
    const filename = tryFile(p + exts[i], isMain);

    if (filename) {
      return filename;
    }
  }
  return false;
}

// Find the longest (possibly multi-dot) extension registered in
// Module._extensions
function findLongestRegisteredExtension(filename) {
  const name = op_require_path_basename(filename);
  let currentExtension;
  let index;
  let startIndex = 0;
  while ((index = StringPrototypeIndexOf(name, ".", startIndex)) !== -1) {
    startIndex = index + 1;
    if (index === 0) continue; // Skip dotfiles like .gitignore
    currentExtension = StringPrototypeSlice(name, index);
    if (Module._extensions[currentExtension]) {
      return currentExtension;
    }
  }
  return ".js";
}

function getExportsForCircularRequire(module) {
  if (
    module.exports &&
    // Skip Proxy module.exports so the warning machinery never invokes the
    // user-visible getPrototypeOf / setPrototypeOf traps. Matches the
    // !isProxy(...) guard in Node's lib/internal/modules/cjs/loader.js.
    !core.isProxy(module.exports) &&
    ObjectGetPrototypeOf(module.exports) === ObjectPrototype &&
    // Exclude transpiled ES6 modules / TypeScript code because those may
    // employ unusual patterns for accessing 'module.exports'. That should
    // be okay because ES6 modules have a different approach to circular
    // dependencies anyway.
    !module.exports.__esModule
  ) {
    // This is later unset once the module is done loading.
    ObjectSetPrototypeOf(
      module.exports,
      CircularRequirePrototypeWarningProxy,
    );
  }

  return module.exports;
}

function emitCircularRequireWarning(prop) {
  process.emitWarning(
    `Accessing non-existent property '${String(prop)}' of module exports ` +
      "inside circular dependency",
  );
}

// A Proxy that can be used as the prototype of a module.exports object and
// warns when non-existent properties are accessed.
const CircularRequirePrototypeWarningProxy = new Proxy({}, {
  get(target, prop) {
    // Allow __esModule access in any case because it is used in the output
    // of transpiled code to determine whether something comes from an
    // ES module, and is not used as a regular key of `module.exports`.
    if (prop in target || prop === "__esModule") return target[prop];
    emitCircularRequireWarning(prop);
    return undefined;
  },

  getOwnPropertyDescriptor(target, prop) {
    if (
      ObjectHasOwn(target, prop) || prop === "__esModule"
    ) {
      return ObjectGetOwnPropertyDescriptor(target, prop);
    }
    emitCircularRequireWarning(prop);
    return undefined;
  },
});

const moduleParentCache = new SafeWeakMap();
function Module(id = "", parent) {
  this.id = id;
  this.path = pathDirname(id);
  // Use ObjectDefineProperty so that user-installed Object.prototype.exports
  // setters/getters are not invoked during module construction. Mirrors
  // setOwnProperty() in Node's lib/internal/util.js.
  ObjectDefineProperty(this, "exports", {
    __proto__: null,
    configurable: true,
    enumerable: true,
    value: {},
    writable: true,
  });
  moduleParentCache.set(this, parent);
  updateChildren(parent, this, false);
  this.filename = null;
  this.loaded = false;
  this.children = [];
}

let parentDeprecationEmitted = false;
function emitParentDeprecation() {
  if (parentDeprecationEmitted) return;
  if (!getOptionValue("--pending-deprecation")) return;
  parentDeprecationEmitted = true;
  process.emitWarning(
    "module.parent is deprecated due to accuracy issues. Please use " +
      "require.main to find program entry point instead.",
    "DeprecationWarning",
    "DEP0144",
  );
}

ObjectDefineProperty(Module.prototype, "parent", {
  __proto__: null,
  configurable: true,
  enumerable: true,
  get() {
    emitParentDeprecation();
    return moduleParentCache.get(this);
  },
  set(value) {
    emitParentDeprecation();
    moduleParentCache.set(this, value);
  },
});

Module.builtinModules = builtinModules;

Module._extensions = ObjectCreate(null);
Module._cache = ObjectCreate(null);
Module._pathCache = ObjectCreate(null);
let modulePaths = [];
Module.globalPaths = modulePaths;

ObjectDefineProperty(Module, "_stat", {
  __proto__: null,
  configurable: true,
  get() {
    return internalModuleStat;
  },
  set(value) {
    internalUtil.emitExperimentalWarning("Module._stat");
    internalModuleStat = value;
    Module.stat = value;
    return true;
  },
});

const CHAR_FORWARD_SLASH = 47;
const TRAILING_SLASH_REGEX = /(?:^|\/)\.?\.$/;

// This only applies to requests of a specific form:
// 1. name/.*
// 2. @scope/name/.*
const EXPORTS_PATTERN = /^((?:@[^/\\%]+\/)?[^./\\%][^/\\%]*)(\/.*)?$/;
function resolveExports(
  modulesPath,
  request,
  parentPath,
  usesLocalNodeModulesDir,
) {
  // The implementation's behavior is meant to mirror resolution in ESM.
  const [, name, expansion = ""] =
    StringPrototypeMatch(request, EXPORTS_PATTERN) || [];
  if (!name) {
    return;
  }

  return op_require_resolve_exports(
    usesLocalNodeModulesDir,
    modulesPath,
    request,
    name,
    expansion,
    parentPath ?? "",
  ) ?? false;
}

Module._findPath = function (request, paths, isMain, parentPath) {
  const absoluteRequest = op_require_path_is_absolute(request);
  if (absoluteRequest) {
    paths = [""];
  } else if (!paths || paths.length === 0) {
    return false;
  }

  const cacheKey = request + "\x00" + ArrayPrototypeJoin(paths, "\x00");
  const entry = Module._pathCache[cacheKey];
  if (entry) {
    return entry;
  }

  let exts;
  let trailingSlash = request.length > 0 &&
    StringPrototypeCharCodeAt(request, request.length - 1) ===
      CHAR_FORWARD_SLASH;
  if (!trailingSlash) {
    trailingSlash = RegExpPrototypeTest(TRAILING_SLASH_REGEX, request);
  }

  // For each path
  for (let i = 0; i < paths.length; i++) {
    // Don't search further if path doesn't exist
    const curPath = paths[i];
    if (curPath && stat(curPath) < 1) continue;

    if (!absoluteRequest) {
      const exportsResolved = resolveExports(
        curPath,
        request,
        parentPath,
        usesLocalNodeModulesDir,
      );
      if (exportsResolved) {
        return exportsResolved;
      }
    }

    let basePath;

    if (usesLocalNodeModulesDir) {
      basePath = pathResolve(curPath, request);
    } else {
      const isDenoDirPackage = op_require_is_deno_dir_package(
        curPath,
      );
      const isRelative = op_require_is_request_relative(
        request,
      );
      basePath = (isDenoDirPackage && !isRelative)
        ? pathResolve(curPath, packageSpecifierSubPath(request))
        : pathResolve(curPath, request);
    }
    let filename;

    const rc = stat(basePath);
    if (!trailingSlash) {
      if (rc === 0) { // File.
        filename = toRealPath(basePath);
      }

      if (!filename) {
        // Try it with each of the extensions
        if (exts === undefined) {
          exts = ObjectKeys(Module._extensions);
        }
        filename = tryExtensions(basePath, exts, isMain);
      }
    }

    if (!filename && rc === 1) { // Directory.
      // try it with each of the extensions at "index"
      if (exts === undefined) {
        exts = ObjectKeys(Module._extensions);
      }
      filename = tryPackage(basePath, exts, isMain, request);
    }

    if (filename) {
      Module._pathCache[cacheKey] = filename;
      return filename;
    }
  }

  return false;
};

/**
 * Get a list of potential module directories
 * @param {string} fromPath The directory name of the module
 * @returns {string[]} List of module directories
 */
Module._nodeModulePaths = function (fromPath) {
  return op_require_node_module_paths(fromPath);
};

Module._resolveLookupPaths = function (request, parent) {
  if (typeof request !== "string") {
    throw new internalErrors.ERR_INVALID_ARG_TYPE(
      "request",
      "string",
      request,
    );
  }

  // Return null for built-in modules, matching Node.js behavior.
  // Libraries like requizzle rely on this to detect native modules.
  const normalizedRequest = StringPrototypeStartsWith(request, "node:")
    ? StringPrototypeSlice(request, 5)
    : request;
  if (
    isBuiltin(request) ||
    normalizedRequest in nativeModuleExports
  ) {
    return null;
  }

  const paths = [];

  if (op_require_is_request_relative(request)) {
    ArrayPrototypePush(
      paths,
      parent?.filename ? op_require_path_dirname(parent.filename) : ".",
    );
    return paths;
  }

  if (
    !usesLocalNodeModulesDir && parent?.filename && parent.filename.length > 0
  ) {
    const denoDirPath = op_require_resolve_deno_dir(
      request,
      parent.filename,
    );
    if (denoDirPath) {
      ArrayPrototypePush(paths, denoDirPath);
    }
  }
  const lookupPathsResult = op_require_resolve_lookup_paths(
    request,
    parent?.paths,
    parent?.filename ?? "",
  );
  if (lookupPathsResult) {
    ArrayPrototypePush(paths, ...new SafeArrayIterator(lookupPathsResult));
  }
  return paths;
};

Module._load = function (request, parent, isMain) {
  // A `node:`-prefixed `require()` of a specifier that isn't a user-requirable
  // builtin throws ERR_UNKNOWN_BUILTIN_MODULE. This covers unknown ids and
  // `internal/*` modules (Node only exposes those under `--expose-internals`).
  // `require.resolve()` goes through `_resolveFilename` directly and instead
  // reports MODULE_NOT_FOUND, so this check lives here rather than there.
  if (
    typeof request === "string" &&
    StringPrototypeStartsWith(request, "node:") &&
    !(hookEntries.length > 0 && !insideResolveHook)
  ) {
    const id = StringPrototypeSlice(request, 5);
    if (
      !(id in nativeModuleExports) ||
      StringPrototypeStartsWith(id, "internal/")
    ) {
      throw new internalErrors.ERR_UNKNOWN_BUILTIN_MODULE(request);
    }
  }

  let relResolveCacheIdentifier;
  if (parent) {
    // Fast path for (lazy loaded) modules in the same directory. The indirect
    // caching is required to allow cache invalidation without changing the old
    // cache key names.
    relResolveCacheIdentifier = `${parent.path}\x00${request}`;
    const filename = relativeResolveCache[relResolveCacheIdentifier];
    if (filename !== undefined) {
      const cachedModule = Module._cache[filename];
      if (cachedModule !== undefined) {
        updateChildren(parent, cachedModule, true);
        if (!cachedModule.loaded) {
          return getExportsForCircularRequire(cachedModule);
        }
        return cachedModule.exports;
      }
      delete relativeResolveCache[relResolveCacheIdentifier];
    }
  }

  const filename = Module._resolveFilename(request, parent, isMain);
  const cachedModule = Module._cache[filename];
  if (
    cachedModule !== undefined &&
    !StringPrototypeStartsWith(filename, "node:")
  ) {
    updateChildren(parent, cachedModule, true);
    if (!cachedModule.loaded) {
      return getExportsForCircularRequire(cachedModule);
    }
    return cachedModule.exports;
  }

  const isBuiltinFilename = StringPrototypeStartsWith(filename, "node:") ||
    nativeModuleCanBeRequiredByUsers(filename);
  if (isBuiltinFilename) {
    const builtinFilename = StringPrototypeStartsWith(filename, "node:")
      ? filename
      : "node:" + filename;
    // Slice 'node:' prefix
    const id = StringPrototypeSlice(builtinFilename, 5);

    // Run load hooks for builtins if registered. Node invokes the load hook
    // chain on every require() of a builtin, so do this before the cache
    // lookup; otherwise the second require would short-circuit and the hook
    // wouldn't fire.
    let builtinHookResult = null;
    if (hookEntries.length > 0 && !insideLoadHook) {
      let hasLoadHook = false;
      for (let i = 0; i < hookEntries.length; i++) {
        if (hookEntries[i].load !== null) {
          hasLoadHook = true;
          break;
        }
      }
      if (hasLoadHook) {
        const context = {
          format: "builtin",
          conditions: ["node", "require"],
          importAttributes: { __proto__: null },
        };
        insideLoadHook = true;
        try {
          builtinHookResult = executeLoadHookChain(builtinFilename, context);
        } finally {
          insideLoadHook = false;
        }
      }
    }

    // Hook-overridden builtins are cached under the `node:`-prefixed key.
    // `require("util")` resolves to a bare name, so the early cache lookup
    // above misses; check the prefixed key here so repeated requires reuse
    // the same module instance.
    const cachedBuiltin = Module._cache[builtinFilename];
    if (cachedBuiltin !== undefined) {
      updateChildren(parent, cachedBuiltin, true);
      if (!cachedBuiltin.loaded) {
        return getExportsForCircularRequire(cachedBuiltin);
      }
      return cachedBuiltin.exports;
    }

    if (builtinHookResult != null) {
      const result = builtinHookResult;
      // If the hook changed the format away from "builtin", use the
      // hook-provided source instead of loading the native module.
      // This matches Node.js behavior where hooks can replace builtins
      // by returning a different format (e.g. "commonjs").
      if (
        result.format && result.format !== "builtin" && result.source != null
      ) {
        const mod = new Module(builtinFilename, parent);
        Module._cache[builtinFilename] = mod;
        const source = loadHookSourceToString(result.source);
        if (result.format === "commonjs") {
          mod._compile(source, builtinFilename, "commonjs");
        } else if (result.format === "json") {
          mod.exports = JSONParse(stripBOM(source));
        } else if (result.format === "module") {
          loadESMFromCJS(mod, builtinFilename, source, true);
        } else {
          mod._compile(source, builtinFilename, undefined, true);
        }
        mod.loaded = true;
        return mod.exports;
      }
      if (result.format === "builtin") {
        const module = loadNativeModule(id, id);
        if (module) {
          return module.exports;
        }
        const mod = new Module(builtinFilename, parent);
        mod.exports = {};
        mod.loaded = true;
        Module._cache[builtinFilename] = mod;
        return mod.exports;
      }
    }

    maybeEmitNativeModuleDeprecation(id);
    const module = loadNativeModule(id, id);
    if (!module) {
      // TODO:
      // throw new ERR_UNKNOWN_BUILTIN_MODULE(filename);
      throw new Error("Unknown built-in module");
    }

    return module.exports;
  }

  if (cachedModule !== undefined) {
    updateChildren(parent, cachedModule, true);
    if (!cachedModule.loaded) {
      return getExportsForCircularRequire(cachedModule);
    }
    return cachedModule.exports;
  }

  // A resolve hook that redirected `require('zlib')` to a file path must
  // not silently fall back to the native module via the original request.
  if (!SetPrototypeHas(cjsHookResolvedFilenames, filename)) {
    maybeEmitNativeModuleDeprecation(filename);
    const mod = loadNativeModule(filename, request);
    if (mod) {
      return mod.exports;
    }
  }
  // Don't call updateChildren(), Module constructor already does.
  const module = cachedModule || new Module(filename, parent);

  if (isMain) {
    process.mainModule = module;
    mainModule = module;
    module.id = ".";
  }

  Module._cache[filename] = module;
  if (parent !== undefined) {
    relativeResolveCache[relResolveCacheIdentifier] = filename;
  }

  let threw = true;
  try {
    try {
      module.load(filename);
      threw = false;
    } finally {
      if (threw) {
        delete Module._cache[filename];
        SetPrototypeDelete(cjsHookResolvedFilenames, filename);
        if (parent !== undefined) {
          delete relativeResolveCache[relResolveCacheIdentifier];
          const children = parent?.children;
          if (ArrayIsArray(children)) {
            const index = ArrayPrototypeIndexOf(children, module);
            if (index !== -1) {
              ArrayPrototypeSplice(children, index, 1);
            }
          }
        }
      } else if (
        module.exports &&
        // Skip Proxy module.exports so the cleanup pass after a circular
        // require doesn't invoke user-visible getPrototypeOf traps. Matches
        // Node's lib/internal/modules/cjs/loader.js behavior.
        !core.isProxy(module.exports) &&
        ObjectGetPrototypeOf(module.exports) ===
          CircularRequirePrototypeWarningProxy
      ) {
        ObjectSetPrototypeOf(module.exports, ObjectPrototype);
      }
    }
  } catch (err) {
    // For a top-level CommonJS throw in the entry module, fire
    // 'uncaughtExceptionMonitor' and 'uncaughtException' synchronously with
    // origin === 'uncaughtException', matching Node.js semantics.
    //
    // Without this, the throw bubbles up to the ESM wrapper that loads the
    // main CJS module, becomes a module evaluation rejection, and is routed
    // through Deno's unhandled-rejection path.
    if (
      isMain &&
      parent === null &&
      typeof process !== "undefined" &&
      typeof process._fatalException === "function"
    ) {
      if (process._fatalException(err)) {
        return module.exports;
      }
      if (err !== null && typeof err === "object") {
        const set = internals._dispatchedFatalErrors;
        if (set !== undefined) set.add(err);
      }
    }
    throw err;
  }

  if (isMain && parent === null) {
    core.processTicksAndRejections();
  }

  return module.exports;
};

Module._resolveFilename = function (
  request,
  parent,
  isMain,
  options,
) {
  if (typeof request !== "string") {
    throw new internalErrors.ERR_INVALID_ARG_TYPE(
      "request",
      "string",
      request,
    );
  }

  // Run resolve hooks if registered (and not already inside a hook)
  if (
    hookEntries.length > 0 && !insideResolveHook &&
    // Dynamic import of CJS goes through an internal self-require to execute
    // the CommonJS module. That is not a user resolve operation and Node's
    // registerHooks tests expect only the original import specifier to be
    // observable.
    request !== parent?.filename
  ) {
    const parentURL = parent?.[kSourceURL] ??
      (parent?.filename ? url.pathToFileURL(parent.filename).href : undefined);
    const context = {
      conditions: ["node", "require"],
      importAttributes: { __proto__: null },
      parentURL,
    };
    const result = executeResolveHookChain(
      request,
      context,
      parent,
      isMain,
      options,
    );
    if (result != null && result.url != null) {
      if (
        options?.[requireResolveOptionsMarker] &&
        StringPrototypeStartsWith(result.url, "node:")
      ) {
        return StringPrototypeSlice(result.url, 5);
      }
      if (StringPrototypeStartsWith(result.url, "file://")) {
        try {
          const filename = url.fileURLToPath(result.url);
          SetPrototypeAdd(cjsHookResolvedFilenames, filename);
          return filename;
        } catch {
          // Virtual file:// URLs may not have valid OS paths (e.g.
          // file:///virtual.js on Windows). Return the URL as-is and
          // let the load hook handle it.
          SetPrototypeAdd(cjsHookResolvedFilenames, result.url);
          return result.url;
        }
      }
      // node: and other schemes returned as-is
      SetPrototypeAdd(cjsHookResolvedFilenames, result.url);
      return result.url;
    }
  }

  if (nativeModuleCanBeRequiredByUsers(request)) {
    return request;
  }

  if (StringPrototypeStartsWith(request, "node:")) {
    const id = StringPrototypeSlice(request, 5);
    if (id in nativeModuleExports) {
      return request;
    }
    if (hookEntries.length > 0 && !insideResolveHook) {
      return request;
    }
    // `require.resolve("node:unknown")` reports MODULE_NOT_FOUND, unlike
    // `require("node:unknown")` which throws ERR_UNKNOWN_BUILTIN_MODULE from
    // `Module._load`.
    const err = new Error(`Cannot find module '${request}'`);
    err.code = "MODULE_NOT_FOUND";
    throw err;
  }

  let paths;

  if (typeof options === "object" && options !== null) {
    if (ArrayIsArray(options.paths)) {
      // Validate all path entries are strings before using them.
      for (let i = 0; i < options.paths.length; i++) {
        if (typeof options.paths[i] !== "string") {
          throw new internalErrors.ERR_INVALID_ARG_TYPE(
            "options.paths",
            "string",
            options.paths[i],
          );
        }
      }

      const isRelative = op_require_is_request_relative(request);

      if (isRelative) {
        // Resolve relative entries to absolute paths so _findPath can
        // stat them correctly.
        paths = [];
        for (let i = 0; i < options.paths.length; i++) {
          ArrayPrototypePush(
            paths,
            pathResolve(process.cwd(), options.paths[i]),
          );
        }
      } else {
        const fakeParent = new Module("", null);
        paths = [];

        for (let i = 0; i < options.paths.length; i++) {
          const path = options.paths[i];
          fakeParent.paths = Module._nodeModulePaths(path);
          const lookupPaths = Module._resolveLookupPaths(request, fakeParent);

          for (let j = 0; j < lookupPaths.length; j++) {
            if (!ArrayPrototypeIncludes(paths, lookupPaths[j])) {
              ArrayPrototypePush(paths, lookupPaths[j]);
            }
          }
        }
      }
    } else if (options.paths === undefined) {
      paths = Module._resolveLookupPaths(request, parent);
    } else {
      throw new internalErrors.ERR_INVALID_ARG_VALUE(
        "options.paths",
        options.paths,
      );
    }
  } else {
    paths = Module._resolveLookupPaths(request, parent);
  }

  if (parent?.filename) {
    if (request[0] === "#") {
      const maybeResolved = op_require_package_imports_resolve(
        parent.filename,
        request,
      );
      if (maybeResolved) {
        return maybeResolved;
      }
    }
  }

  // Try module self resolution first
  const parentPath = trySelfParentPath(parent);
  const selfResolved = parentPath != null
    ? op_require_try_self(parentPath, request)
    : undefined;
  if (selfResolved) {
    const cacheKey = request + "\x00" +
      (paths.length === 1 ? paths[0] : ArrayPrototypeJoin(paths, "\x00"));
    Module._pathCache[cacheKey] = selfResolved;
    return selfResolved;
  }

  // Look up the filename first, since that's the cache key.
  const filename = Module._findPath(
    request,
    paths,
    isMain,
    parentPath,
  );
  if (filename) {
    return op_require_real_path(filename);
  }
  // fallback and attempt to resolve bare specifiers using
  // the global cache when not using --node-modules-dir
  if (
    !usesLocalNodeModulesDir &&
    ArrayIsArray(options?.paths) &&
    request[0] !== "." &&
    request[0] !== "#" &&
    !request.startsWith("file:///") &&
    !op_require_is_request_relative(request) &&
    !op_require_path_is_absolute(request)
  ) {
    try {
      return Module._resolveFilename(request, parent, isMain, {
        ...options,
        paths: undefined,
      });
    } catch {
      // ignore
    }
  }

  if (
    typeof request === "string" &&
    (StringPrototypeEndsWith(request, "$deno$eval.cjs") ||
      StringPrototypeEndsWith(request, "$deno$eval.cts") ||
      StringPrototypeEndsWith(request, "$deno$stdin.cjs") ||
      StringPrototypeEndsWith(request, "$deno$stdin.cts"))
  ) {
    return request;
  }

  const requireStack = [];
  for (let cursor = parent; cursor; cursor = moduleParentCache.get(cursor)) {
    ArrayPrototypePush(requireStack, cursor.filename || cursor.id);
  }
  let message = `Cannot find module '${request}'`;
  if (requireStack.length > 0) {
    message = message + "\nRequire stack:\n- " +
      ArrayPrototypeJoin(requireStack, "\n- ");
  }
  // eslint-disable-next-line no-restricted-syntax
  const err = new Error(message);
  err.code = "MODULE_NOT_FOUND";
  err.requireStack = requireStack;
  throw err;
};

function trySelfParentPath(parent) {
  if (parent == null) {
    return undefined;
  }
  if (typeof parent.filename === "string") {
    return parent.filename;
  }
  if (parent.id === "<repl>" || parent.id === "internal/preload") {
    return op_fs_cwd();
  }
  return undefined;
}

/**
 * Internal CommonJS API to always require modules before requiring the actual
 * one when calling `require("my-module")`. This is used by require hooks such
 * as `ts-node/register`.
 * @param {string[]} requests List of modules to preload
 */
Module._preloadModules = function (requests) {
  if (!ArrayIsArray(requests) || requests.length === 0) {
    return;
  }

  const parent = new Module("internal/preload", null);
  // All requested files must be resolved against cwd
  parent.paths = Module._nodeModulePaths(process.cwd());
  for (let i = 0; i < requests.length; i++) {
    parent.require(requests[i]);
  }
};

Module.prototype.load = function (filename) {
  if (this.loaded) {
    throw new Error("Module already loaded");
  }

  // Canonicalize the path so it's not pointing to the symlinked directory
  // in `node_modules` directory of the referrer.
  // When load hooks are active, the file may not exist on disk (virtual
  // modules), so we fall back to the original filename.
  let hasLoadHooks = false;
  if (hookEntries.length > 0 && !insideLoadHook) {
    for (let i = 0; i < hookEntries.length; i++) {
      if (hookEntries[i].load !== null) {
        hasLoadHooks = true;
        break;
      }
    }
  }
  if (hasLoadHooks) {
    try {
      this.filename = op_require_real_path(filename);
    } catch {
      this.filename = filename;
    }
  } else {
    this.filename = op_require_real_path(filename);
  }
  this.paths = Module._nodeModulePaths(pathDirname(this.filename));

  // Run load hooks if registered
  if (hasLoadHooks) {
    {
      let fileUrl;
      if (StringPrototypeStartsWith(this.filename, "node:")) {
        fileUrl = this.filename;
      } else if (
        StringPrototypeStartsWith(this.filename, "file://") ||
        StringPrototypeIncludes(this.filename, "://")
      ) {
        // Already a URL (e.g. from a resolve hook returning a virtual URL)
        fileUrl = this.filename;
      } else {
        fileUrl = url.pathToFileURL(this.filename).href;
      }
      const context = {
        format: undefined,
        conditions: ["node", "require"],
        importAttributes: { __proto__: null },
      };
      insideLoadHook = true;
      let result;
      try {
        result = executeLoadHookChain(fileUrl, context);
      } finally {
        insideLoadHook = false;
      }
      if (result != null && result.source != null) {
        const format = result.format;
        const source = loadHookSourceToString(result.source);
        if (format === "module") {
          loadESMFromCJS(this, this.filename, source, true);
        } else if (format === "commonjs") {
          this._compile(source, this.filename, "commonjs");
        } else if (format === "json") {
          try {
            this.exports = JSONParse(stripBOM(source));
          } catch (err) {
            err.message = this.filename + ": " + err.message;
            throw err;
          }
        } else {
          // Default to CJS when format is unspecified
          this._compile(source, this.filename, undefined, true);
        }
        this.loaded = true;
        return;
      }
    }
  }

  const extension = findLongestRegisteredExtension(filename);
  Module._extensions[extension](this, this.filename);
  this.loaded = true;

  // TODO: do caching
};

// Loads a module at the given file path. Returns that module's
// `exports` property.
const moduleRequireDc = diagnosticsChannel.tracingChannel("module.require");

Module.prototype.require = function (id) {
  if (typeof id !== "string") {
    throw new internalErrors.ERR_INVALID_ARG_TYPE("id", "string", id);
  }

  if (id === "") {
    throw new internalErrors.ERR_INVALID_ARG_VALUE(
      "id",
      id,
      "must be a non-empty string",
    );
  }
  requireDepth++;
  // `tracingChannel('module.require').traceSync` publishes:
  //   start: { parentFilename, id } before the load
  //   end:   { parentFilename, id, result } on success (in finally)
  //   error: { parentFilename, id, error } when require throws; end still
  //          fires in finally with the error context, matching Node.
  const parentFilename = this.filename;
  try {
    if (moduleRequireDc.hasSubscribers) {
      return moduleRequireDc.traceSync(
        Module._load,
        { parentFilename, id },
        // deno-lint-ignore no-undef
        Module,
        id,
        this,
        /* isMain */ false,
      );
    }
    return Module._load(id, this, /* isMain */ false);
  } finally {
    requireDepth--;
  }
};

const wrapper = [
  "(function (exports, require, module, __filename, __dirname) { ",
  "\n});",
];

export let wrap = function (script) {
  script = script.replace(/^#!.*?\n/, "");
  return `${Module.wrapper[0]}${script}${Module.wrapper[1]}`;
};

let wrapperProxy = new Proxy(wrapper, {
  set(target, property, value, receiver) {
    patched = true;
    return ReflectSet(target, property, value, receiver);
  },

  defineProperty(target, property, descriptor) {
    patched = true;
    return ObjectDefineProperty(target, property, descriptor);
  },
});

ObjectDefineProperty(Module, "wrap", {
  get() {
    return wrap;
  },

  set(value) {
    patched = true;
    wrap = value;
  },
});

ObjectDefineProperty(Module, "wrapper", {
  get() {
    return wrapperProxy;
  },

  set(value) {
    patched = true;
    wrapperProxy = value;
  },
});

function isEsmSyntaxError(error) {
  return error instanceof SyntaxError && (
    StringPrototypeIncludes(
      error.message,
      "Cannot use import statement outside a module",
    ) ||
    StringPrototypeIncludes(error.message, "Unexpected token 'export'")
  );
}

function enrichCJSError(error) {
  if (isEsmSyntaxError(error)) {
    console.error(
      'To load an ES module, set "type": "module" in the package.json or use ' +
        "the .mjs extension.",
    );
  }
}

function wrapSafe(
  filename,
  content,
  cjsModuleInstance,
  format,
) {
  let f;
  let err;

  if (patched) {
    [f, err] = core.evalContext(
      Module.wrap(content),
      url.pathToFileURL(filename).toString(),
      [format !== "module"],
    );
  } else {
    [f, err] = core.compileFunction(
      content,
      url.pathToFileURL(filename).toString(),
      [format !== "module"],
      [
        "exports",
        "require",
        "module",
        "__filename",
        "__dirname",
      ],
    );
  }
  if (err) {
    if (process.mainModule === cjsModuleInstance) {
      enrichCJSError(err.thrown);
    }
    throw err.thrown;
  }
  return f;
}

Module.prototype._compile = function (
  content,
  filename,
  format,
  sourceFromHook = false,
) {
  const useSourceImport = sourceFromHook ||
    SetPrototypeDelete(cjsHookResolvedFilenames, filename);
  if (format === "module") {
    return loadESMFromCJS(this, filename, content, useSourceImport);
  }

  let compiledWrapper;
  try {
    compiledWrapper = wrapSafe(filename, content, this, format);
  } catch (err) {
    if (
      format !== "commonjs" && err instanceof SyntaxError &&
      (op_require_can_parse_as_esm(content) || isEsmSyntaxError(err))
    ) {
      return loadESMFromCJS(this, filename, content, useSourceImport);
    }
    throw err;
  }

  const dirname = pathDirname(filename);
  const require = makeRequireFunction(this);
  const exports = this.exports;
  const thisValue = exports;
  if (requireDepth === 0) {
    statCache = new SafeMap();
  }

  if (hasInspectBrk && !hasBrokenOnInspectBrk) {
    hasBrokenOnInspectBrk = true;
    op_require_break_on_next_statement();
  }

  const result = compiledWrapper.call(
    thisValue,
    exports,
    require,
    this,
    filename,
    dirname,
  );
  if (requireDepth === 0) {
    statCache = null;
  }
  return result;
};

Module._extensions[".js"] = function (module, filename) {
  // We don't define everything on Module.extensions in
  // order to prevent probing for these files
  if (
    StringPrototypeEndsWith(filename, ".js") ||
    StringPrototypeEndsWith(filename, ".ts") ||
    StringPrototypeEndsWith(filename, ".jsx") ||
    StringPrototypeEndsWith(filename, ".tsx")
  ) {
    return loadMaybeCjs(module, filename);
  } else if (StringPrototypeEndsWith(filename, ".mts")) {
    return loadESMFromCJS(module, filename);
  } else if (StringPrototypeEndsWith(filename, ".cts")) {
    return loadCjs(module, filename);
  } else {
    return loadMaybeCjs(module, filename);
  }
};

Module._extensions[".cjs"] = loadCjs;
Module._extensions[".mjs"] = loadESMFromCJS;
Module._extensions[".wasm"] = loadESMFromCJS;

function loadMaybeCjs(module, filename) {
  const content = op_require_read_file(filename);
  const format = op_require_is_maybe_cjs(filename) ? undefined : "module";
  module._compile(content, filename, format);
}

function loadCjs(module, filename) {
  const content = op_require_read_file(filename);
  module._compile(content, filename, "commonjs");
}

function _throwRequireAsyncModule(specifier, module) {
  // Use moduleParentCache directly to avoid triggering the module.parent
  // deprecation getter when --pending-deprecation is set.
  const parentModule = module ? moduleParentCache.get(module) : undefined;
  const parent = parentModule?.filename ?? "<unknown>";
  throw new internalErrors.ERR_REQUIRE_ASYNC_MODULE(specifier, parent);
}

function loadESMFromCJS(module, filename, code, sourceFromHook = false) {
  const specifier = url.pathToFileURL(filename).toString();
  let namespace;
  try {
    namespace = sourceFromHook && code !== undefined
      ? op_import_sync_with_source(specifier, code)
      : op_import_sync(specifier);
  } catch (e) {
    if (
      e instanceof Error &&
      StringPrototypeIncludes(
        e.message,
        "Top-level await is not allowed in synchronous evaluation",
      )
    ) {
      _throwRequireAsyncModule(specifier, module);
    }
    throw e;
  }
  if (ObjectHasOwn(namespace, "module.exports")) {
    module.exports = namespace["module.exports"];
  } else {
    module.exports = namespace;
  }
}

function stripBOM(content) {
  if (StringPrototypeCharCodeAt(content, 0) === 0xfeff) {
    content = StringPrototypeSlice(content, 1);
  }
  return content;
}

// Native extension for .json
Module._extensions[".json"] = function (module, filename) {
  const content = op_require_read_file(filename);

  try {
    module.exports = JSONParse(stripBOM(content));
  } catch (err) {
    err.message = filename + ": " + err.message;
    throw err;
  }
};

// Async hooks wrappers for NAPI - called from Rust via V8 function calls.
function napiAsyncHooksEmitInit(asyncId, type, triggerAsyncId, resource) {
  internalAsyncHooksEmitInit(asyncId, type, triggerAsyncId, resource);
}
function napiAsyncHooksEmitBefore(asyncId) {
  internalAsyncHooksEmitBefore(asyncId);
}
function napiAsyncHooksEmitAfter(asyncId) {
  internalAsyncHooksEmitAfter(asyncId);
}
function napiAsyncHooksEmitDestroy(asyncId) {
  internalAsyncHooksEmitDestroy(asyncId);
}

// Native extension for .node
Module._extensions[".node"] = function (module, filename) {
  if (filename.endsWith("cpufeatures.node")) {
    throw new Error("Using cpu-features module is currently not supported");
  }
  module.exports = op_napi_open(
    filename,
    globalThis,
    buffer.Buffer.from,
    reportError,
    napiAsyncHooksEmitInit,
    napiAsyncHooksEmitBefore,
    napiAsyncHooksEmitAfter,
    napiAsyncHooksEmitDestroy,
  );
};

function createRequireFromPath(filename, sourceURL) {
  const proxyPath = op_require_proxy_path(filename) ?? filename;
  const mod = new Module(proxyPath);
  mod.filename = proxyPath;
  mod.paths = Module._nodeModulePaths(mod.path);
  if (sourceURL !== undefined) {
    // Preserve the original URL (with query/hash) for resolve hooks'
    // `context.parentURL`, which would otherwise lose those parts via
    // pathToFileURL(filename).
    mod[kSourceURL] = sourceURL;
  }
  return makeRequireFunction(mod);
}

function makeRequireFunction(mod) {
  const require = function require(path) {
    return mod.require(path);
  };

  function resolve(request, options) {
    options = options == null ? {} : { __proto__: null, ...options };
    options[requireResolveOptionsMarker] = true;
    return Module._resolveFilename(request, mod, false, options);
  }

  require.resolve = resolve;

  function paths(request) {
    return Module._resolveLookupPaths(request, mod);
  }

  resolve.paths = paths;
  // Use ObjectDefineProperty so user-installed Object.prototype.main setters
  // are not invoked when require() is constructed. Mirrors setOwnProperty()
  // in Node's lib/internal/modules/helpers.js.
  ObjectDefineProperty(require, "main", {
    __proto__: null,
    configurable: true,
    enumerable: true,
    value: mainModule,
    writable: true,
  });
  // Enable support to add extra extension types.
  require.extensions = Module._extensions;
  require.cache = Module._cache;

  return require;
}

// Matches to:
// - /foo/...
// - \foo\...
// - C:/foo/...
// - C:\foo\...
const RE_START_OF_ABS_PATH = /^([/\\]|[a-zA-Z]:[/\\])/;
const RE_URL_SCHEME = /^[a-zA-Z][a-zA-Z\d+\-.]*:/;

function isAbsolute(filenameOrUrl) {
  return RE_START_OF_ABS_PATH.test(filenameOrUrl);
}

// Match Node's error reason (see lib/internal/modules/cjs/loader.js).
const kCreateRequireError =
  "must be a file URL object, file URL string, or absolute path string";

function createRequire(filenameOrUrl) {
  let fileUrlStr;
  if (filenameOrUrl instanceof URL) {
    if (filenameOrUrl.protocol !== "file:") {
      throw new internalErrors.ERR_INVALID_ARG_VALUE(
        "filename",
        filenameOrUrl,
        kCreateRequireError,
      );
    }
    fileUrlStr = filenameOrUrl.toString();
  } else if (typeof filenameOrUrl === "string") {
    if (!filenameOrUrl.startsWith("file:") && !isAbsolute(filenameOrUrl)) {
      throw new internalErrors.ERR_INVALID_ARG_VALUE(
        "filename",
        filenameOrUrl,
        kCreateRequireError,
      );
    }
    fileUrlStr = filenameOrUrl;
  } else {
    throw new internalErrors.ERR_INVALID_ARG_VALUE(
      "filename",
      filenameOrUrl,
      kCreateRequireError,
    );
  }
  const filename = op_require_as_file_path(fileUrlStr) ?? fileUrlStr;
  return createRequireFromPath(filename, fileUrlStr);
}

function isBuiltin(moduleName) {
  if (typeof moduleName !== "string") {
    return false;
  }

  if (StringPrototypeStartsWith(moduleName, "node:")) {
    moduleName = StringPrototypeSlice(moduleName, 5);
  } else if (moduleName === "test" || moduleName === "test/reporters") {
    // test is only a builtin if it has the "node:" scheme
    // see https://github.com/nodejs/node/blob/73025c4dec042e344eeea7912ed39f7b7c4a3991/test/parallel/test-module-isBuiltin.js#L14
    return false;
  }

  return moduleName in nativeModuleExports &&
    !StringPrototypeStartsWith(moduleName, "internal/");
}

function getBuiltinModule(id) {
  if (typeof id !== "string") {
    throw new internalErrors.ERR_INVALID_ARG_TYPE("id", "string", id);
  }
  if (!isBuiltin(id)) {
    return undefined;
  }

  if (StringPrototypeStartsWith(id, "node:")) {
    // Slice 'node:' prefix
    id = StringPrototypeSlice(id, 5);
  }

  const mod = loadNativeModule(id, id);
  if (mod) {
    return mod.exports;
  }

  return undefined;
}

Module.isBuiltin = isBuiltin;

Module.createRequire = createRequire;

function packageNameFromBareSpecifier(specifier) {
  if (
    op_require_is_request_relative(specifier) ||
    isAbsolute(specifier) ||
    RegExpPrototypeTest(RE_URL_SCHEME, specifier)
  ) {
    return null;
  }

  const parts = StringPrototypeSplit(specifier, "/");
  if (parts[0] === "") {
    return null;
  }
  if (StringPrototypeStartsWith(parts[0], "@")) {
    if (parts.length < 2 || parts[1] === "") {
      return specifier;
    }
    return `${parts[0]}/${parts[1]}`;
  }
  return parts[0];
}

function findClosestPackageJSON(filePath) {
  let currentPath = stat(filePath) === 1 ? filePath : pathDirname(filePath);

  while (true) {
    const packageJsonPath = pathResolve(currentPath, "package.json");
    if (op_require_read_package_scope(packageJsonPath)) {
      return toRealPath(packageJsonPath);
    }

    const parentPath = pathDirname(currentPath);
    if (parentPath === currentPath) {
      return undefined;
    }
    currentPath = parentPath;
  }
}

function basePathFromFileURLOrPath(base) {
  if (base instanceof URL) {
    if (base.protocol !== "file:") {
      throw new internalErrors.ERR_INVALID_URL_SCHEME("file");
    }
    return op_require_as_file_path(base.href);
  }
  if (typeof base !== "string") {
    throw new internalErrors.ERR_INVALID_ARG_TYPE("base", "string", base);
  }
  if (StringPrototypeStartsWith(base, "file:")) {
    return op_require_as_file_path(base);
  }
  return base;
}

function findPackageJSONForBareSpecifier(packageName, base) {
  if (base === undefined) {
    return undefined;
  }

  const basePath = basePathFromFileURLOrPath(base);
  const baseDir = stat(basePath) === 1 ? basePath : pathDirname(basePath);
  const parent = new Module("", null);
  parent.filename = pathResolve(baseDir, "$deno$find_package_json.js");
  parent.paths = Module._nodeModulePaths(baseDir);
  const lookupPaths = Module._resolveLookupPaths(packageName, parent);

  if (lookupPaths === null) {
    return undefined;
  }

  for (let i = 0; i < lookupPaths.length; i++) {
    const lookupPath = lookupPaths[i];
    const candidatePackageJsonPaths = [
      pathResolve(lookupPath, packageName, "package.json"),
      pathResolve(lookupPath, "package.json"),
    ];
    for (let j = 0; j < candidatePackageJsonPaths.length; j++) {
      const packageJsonPath = candidatePackageJsonPaths[j];
      if (op_require_read_package_scope(packageJsonPath)) {
        return toRealPath(packageJsonPath);
      }
    }
  }
  return undefined;
}

function pathFromResolvedFileUrl(resolved) {
  if (!StringPrototypeStartsWith(resolved, "file:")) {
    throw new internalErrors.ERR_INVALID_URL_SCHEME("file");
  }
  return op_require_as_file_path(resolved);
}

function resolveSpecifierForPackageJSON(specifier, base) {
  if (specifier instanceof URL) {
    return specifier.href;
  }
  specifier = String(specifier);
  if (StringPrototypeStartsWith(specifier, "file:")) {
    return specifier;
  }
  if (RegExpPrototypeTest(RE_URL_SCHEME, specifier)) {
    return specifier;
  }

  let parentURL = "data:";
  if (base !== undefined) {
    if (base instanceof URL) {
      parentURL = base.href;
    } else if (typeof base === "string") {
      parentURL = base;
    } else {
      throw new internalErrors.ERR_INVALID_ARG_TYPE("base", "string", base);
    }
  }
  return op_module_default_resolve(specifier, parentURL);
}

function findPackageJSON(specifier, base = undefined) {
  const specifierString = specifier instanceof URL
    ? specifier.href
    : String(specifier);
  const packageName = packageNameFromBareSpecifier(specifierString);
  if (packageName !== null) {
    const packageJsonPath = findPackageJSONForBareSpecifier(packageName, base);
    if (packageJsonPath !== undefined) {
      return packageJsonPath;
    }
  }

  const resolved = resolveSpecifierForPackageJSON(specifier, base);
  const filePath = pathFromResolvedFileUrl(resolved);
  return findClosestPackageJSON(filePath);
}

Module.findPackageJSON = findPackageJSON;

Module._initPaths = function () {
  const paths = op_require_init_paths();
  modulePaths = paths;
  Module.globalPaths = ArrayPrototypeSlice(modulePaths);
};

function syncBuiltinESMExports() {}

Module.syncBuiltinESMExports = syncBuiltinESMExports;

// Mostly used by tools like ts-node.
Module.runMain = function () {
  Module._load(process.argv[1], null, true);
};

Module.Module = Module;

nativeModuleExports.module = Module;

// Modules that emit a deprecation warning the first time they are required via
// the CJS loader (`require('_stream_readable')` etc.). Maps the module name to
// [message, code]. Matches Node's `BuiltinModule#compileForPublicLoader` --
// `process.getBuiltinModule()` does NOT trigger these warnings.
const deprecatedNativeModules = ObjectCreate(null);
deprecatedNativeModules._tls_common = [
  "The _tls_common module is deprecated. Use `node:tls` instead.",
  "DEP0192",
];
deprecatedNativeModules._tls_wrap = [
  "The _tls_wrap module is deprecated. Use `node:tls` instead.",
  "DEP0192",
];
deprecatedNativeModules._stream_duplex = [
  "The _stream_duplex module is deprecated. Use `node:stream` instead.",
  "DEP0193",
];
deprecatedNativeModules._stream_passthrough = [
  "The _stream_passthrough module is deprecated. Use `node:stream` instead.",
  "DEP0193",
];
deprecatedNativeModules._stream_readable = [
  "The _stream_readable module is deprecated. Use `node:stream` instead.",
  "DEP0193",
];
deprecatedNativeModules._stream_transform = [
  "The _stream_transform module is deprecated. Use `node:stream` instead.",
  "DEP0193",
];
deprecatedNativeModules._stream_writable = [
  "The _stream_writable module is deprecated. Use `node:stream` instead.",
  "DEP0193",
];
deprecatedNativeModules.punycode = [
  "The `punycode` module is deprecated. Please use a userland " +
  "alternative instead.",
  "DEP0040",
];

const emittedNativeModuleDeprecations = new SafeSet();
function maybeEmitNativeModuleDeprecation(request) {
  const deprecation = deprecatedNativeModules[request];
  if (deprecation === undefined) return;
  if (SetPrototypeHas(emittedNativeModuleDeprecations, request)) return;
  SetPrototypeAdd(emittedNativeModuleDeprecations, request);
  process.emitWarning(
    deprecation[0],
    "DeprecationWarning",
    deprecation[1],
  );
}

function loadNativeModule(_id, request) {
  if (nativeModulePolyfill.has(request)) {
    return nativeModulePolyfill.get(request);
  }
  const modExports = nativeModuleExports[request];
  if (modExports) {
    const nodeMod = new Module(request);
    nodeMod.exports = modExports;
    nodeMod.loaded = true;
    nativeModulePolyfill.set(request, nodeMod);
    return nodeMod;
  }
  return undefined;
}

function nativeModuleCanBeRequiredByUsers(request) {
  // `in` rather than bracket access avoids triggering the lazy getters
  // installed by `defineLazyNativeModule`.
  return request in nativeModuleExports;
}

/** @param specifier {string} */
function packageSpecifierSubPath(specifier) {
  let parts = StringPrototypeSplit(specifier, "/");
  if (StringPrototypeStartsWith(parts[0], "@")) {
    parts = ArrayPrototypeSlice(parts, 2);
  } else {
    parts = ArrayPrototypeSlice(parts, 1);
  }
  return ArrayPrototypeJoin(parts, "/");
}

// VLQ Base64 decoding for source maps
const BASE64_CHARS =
  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const BASE64_LOOKUP = new Int32Array(128);
for (let i = 0; i < 128; i++) BASE64_LOOKUP[i] = -1;
for (let i = 0; i < BASE64_CHARS.length; i++) {
  BASE64_LOOKUP[StringPrototypeCharCodeAt(BASE64_CHARS, i)] = i;
}

const VLQ_BASE_SHIFT = 5;
const VLQ_BASE = 1 << VLQ_BASE_SHIFT; // 32
const VLQ_BASE_MASK = VLQ_BASE - 1; // 31
const VLQ_CONTINUATION_BIT = VLQ_BASE; // 32

/**
 * Decode a single VLQ value from a string iterator.
 * @param {string} str
 * @param {{ pos: number }} iter
 * @returns {number}
 */
function decodeVLQ(str, iter) {
  let result = 0;
  let shift = 0;
  let digit;
  do {
    if (iter.pos >= str.length) {
      return 0;
    }
    const charCode = StringPrototypeCharCodeAt(str, iter.pos++);
    digit = BASE64_LOOKUP[charCode];
    if (digit === -1) {
      return 0;
    }
    result += (digit & VLQ_BASE_MASK) << shift;
    shift += VLQ_BASE_SHIFT;
  } while (digit & VLQ_CONTINUATION_BIT);

  // The sign is encoded in the least significant bit
  const negative = result & 1;
  // Use unsigned right shift, so that the 32nd bit is properly shifted
  // to the 31st, and the 32nd becomes unset.
  result >>>= 1;
  if (!negative) {
    return result;
  }
  // We need to OR here to ensure the 32nd bit (the sign bit in an Int32) is
  // always set for negative numbers. If `result` were 1, (meaning `negative`
  // is true and all other bits were zeros), `result` would now be 0. But -0
  // doesn't flip the 32nd bit as intended.
  return -result | (1 << 31);
}

/**
 * Parse VLQ-encoded source map mappings string into an array of mapping entries.
 * @param {string} mappings
 * @param {string[]} sources
 * @param {string} sourceRoot
 * @returns {Array<{generatedLine: number, generatedColumn: number, originalSource: string, originalLine: number, originalColumn: number, name?: string}>}
 */
function parseMappings(mappings, sources, names, sourceRoot) {
  const entries = [];
  if (!mappings) return entries;

  let generatedLine = 0;
  let previousGeneratedColumn = 0;
  let previousOriginalLine = 0;
  let previousOriginalColumn = 0;
  let previousSource = 0;
  let previousName = 0;
  const iter = { pos: 0 };

  while (iter.pos < mappings.length) {
    const ch = mappings[iter.pos];
    if (ch === ";") {
      generatedLine++;
      previousGeneratedColumn = 0;
      iter.pos++;
      continue;
    }
    if (ch === ",") {
      iter.pos++;
      continue;
    }

    // Decode segment: generatedColumn, [sourceIndex, originalLine, originalColumn, [nameIndex]]
    const generatedColumn = previousGeneratedColumn + decodeVLQ(mappings, iter);
    previousGeneratedColumn = generatedColumn;

    // Check if there are more fields (source mapping)
    if (iter.pos < mappings.length) {
      const next = mappings[iter.pos];
      if (next !== "," && next !== ";") {
        const sourceIndex = previousSource + decodeVLQ(mappings, iter);
        previousSource = sourceIndex;

        const originalLine = previousOriginalLine +
          decodeVLQ(mappings, iter);
        previousOriginalLine = originalLine;

        const originalColumn = previousOriginalColumn +
          decodeVLQ(mappings, iter);
        previousOriginalColumn = originalColumn;

        let source = sources[sourceIndex] || "";
        if (
          sourceRoot && !StringPrototypeStartsWith(source, "/") &&
          !RegExpPrototypeTest(/^\w+:\/\//, source)
        ) {
          source = sourceRoot + source;
        }

        let name;
        // Check for optional name index
        if (
          iter.pos < mappings.length &&
          mappings[iter.pos] !== "," &&
          mappings[iter.pos] !== ";"
        ) {
          const nameIndex = previousName + decodeVLQ(mappings, iter);
          previousName = nameIndex;
          name = names ? names[nameIndex] : undefined;
        }

        ArrayPrototypePush(entries, {
          generatedLine,
          generatedColumn,
          originalSource: source,
          originalLine,
          originalColumn,
          name,
        });
      }
    }

    // Segments with only generated column (no source mapping) are skipped,
    // matching Node.js behavior - only full mapping entries are included.
  }

  return entries;
}

/**
 * Compare two source map entries for sorting/binary search.
 */
function compareEntries(a, b) {
  if (a.generatedLine !== b.generatedLine) {
    return a.generatedLine - b.generatedLine;
  }
  return a.generatedColumn - b.generatedColumn;
}

/**
 * Binary search for the entry that contains the given generated position.
 */
function findEntryInMappings(entries, line, column) {
  let low = 0;
  let high = entries.length - 1;
  let best = -1;

  while (low <= high) {
    const mid = (low + high) >> 1;
    const entry = entries[mid];
    const cmp = entry.generatedLine - line ||
      entry.generatedColumn - column;

    if (cmp === 0) {
      return entry;
    } else if (cmp < 0) {
      best = mid;
      low = mid + 1;
    } else {
      high = mid - 1;
    }
  }

  if (best >= 0) {
    const entry = entries[best];
    if (entry.generatedLine === line) {
      return entry;
    }
  }

  return null;
}

/**
 * Deep clone an object (simple JSON-safe objects).
 */
function deepClone(obj) {
  if (obj === null || typeof obj !== "object") return obj;
  if (ArrayIsArray(obj)) return ArrayPrototypeMap(obj, deepClone);
  const clone = {};
  const keys = ObjectKeys(obj);
  for (let i = 0; i < keys.length; i++) {
    clone[keys[i]] = deepClone(obj[keys[i]]);
  }
  return clone;
}

/**
 * SourceMap class implementing Node.js's module.SourceMap API.
 * @see https://nodejs.org/api/module.html#class-modulesourcemap
 */
class SourceMap {
  #payload;
  #lineLengths;
  #mappings;

  /**
   * @param {object} payload - Source Map V3 payload object
   * @param {{ lineLengths?: number[] }} [options]
   */
  constructor(payload, options) {
    if (
      typeof payload !== "object" || payload === null ||
      ArrayIsArray(payload)
    ) {
      let received;
      if (payload === null) {
        received = " Received null";
      } else if (typeof payload === "object") {
        const proto = ObjectGetPrototypeOf(payload);
        const name = proto?.constructor?.name;
        received = name
          ? ` Received an instance of ${name}`
          : ` Received ${typeof payload}`;
      } else {
        let inspected = String(payload);
        if (inspected.length > 28) {
          inspected = StringPrototypeSlice(inspected, 0, 25) + "...";
        }
        received = ` Received type ${typeof payload} (${inspected})`;
      }
      const err = new TypeError(
        `The "payload" argument must be of type object.${received}`,
      );
      err.code = "ERR_INVALID_ARG_TYPE";
      throw err;
    }

    this.#payload = deepClone(payload);
    this.#lineLengths = options?.lineLengths
      ? ArrayPrototypeSlice(options.lineLengths)
      : undefined;

    // Parse mappings - handle both regular and index source maps
    this.#mappings = this.#parseMap(payload);
    // Sort entries by generated position
    ArrayPrototypeSort(this.#mappings, compareEntries);
  }

  /**
   * Parse source map payload into mapping entries.
   * Handles both regular source maps and index source maps (with sections).
   */
  #parseMap(payload) {
    if (payload.sections) {
      // Index Source Map V3
      const entries = [];
      const sections = payload.sections;
      for (let i = 0; i < sections.length; i++) {
        const section = sections[i];
        const offset = section.offset || { line: 0, column: 0 };
        const map = section.map;
        const sectionEntries = parseMappings(
          map.mappings,
          map.sources || [],
          map.names || [],
          map.sourceRoot || "",
        );
        // Apply section offset
        for (let j = 0; j < sectionEntries.length; j++) {
          const entry = sectionEntries[j];
          entry.generatedLine += offset.line;
          if (entry.generatedLine === offset.line) {
            entry.generatedColumn += offset.column;
          }
          ArrayPrototypePush(entries, entry);
        }
      }
      // For index maps, flatten the sources and mappings into the payload clone
      if (!this.#payload.sources) {
        this.#payload.sources = [];
      }
      if (!this.#payload.mappings) {
        this.#payload.mappings = payload.mappings || undefined;
      }
      return entries;
    }

    return parseMappings(
      payload.mappings,
      payload.sources || [],
      payload.names || [],
      payload.sourceRoot || "",
    );
  }

  /**
   * Getter for the payload used to construct the SourceMap instance.
   * Returns a clone of the original payload.
   */
  get payload() {
    return this.#payload;
  }

  /**
   * Getter for line lengths, if provided in the constructor options.
   */
  get lineLengths() {
    return this.#lineLengths;
  }

  /**
   * Given a 0-indexed line offset and column offset in the generated source,
   * returns an object representing the SourceMap range in the original file
   * if found, or an empty object if not.
   *
   * @param {number} lineOffset - Zero-indexed line number in generated source
   * @param {number} columnOffset - Zero-indexed column number in generated source
   * @returns {{ generatedLine: number, generatedColumn: number, originalSource: string, originalLine: number, originalColumn: number } | {}}
   */
  findEntry(lineOffset, columnOffset) {
    if (this.#mappings.length === 0) return {};
    const entry = findEntryInMappings(this.#mappings, lineOffset, columnOffset);
    if (!entry) return {};
    return {
      generatedLine: entry.generatedLine,
      generatedColumn: entry.generatedColumn,
      originalSource: entry.originalSource,
      originalLine: entry.originalLine,
      originalColumn: entry.originalColumn,
    };
  }

  /**
   * Given 1-indexed lineNumber and columnNumber from a call site in the generated
   * source, find the corresponding call site location in the original source.
   *
   * @param {number} lineNumber - 1-indexed line number
   * @param {number} columnNumber - 1-indexed column number
   * @returns {{ name?: string, fileName: string, lineNumber: number, columnNumber: number } | {}}
   */
  findOrigin(lineNumber, columnNumber) {
    const entry = this.findEntry(lineNumber - 1, columnNumber - 1);
    if (
      entry.originalSource === undefined ||
      entry.originalLine === undefined ||
      entry.originalColumn === undefined ||
      entry.generatedLine === undefined ||
      entry.generatedColumn === undefined
    ) {
      return {};
    }
    const lineOffset = lineNumber - entry.generatedLine;
    const columnOffset = columnNumber - entry.generatedColumn;
    const result = {
      fileName: entry.originalSource,
      lineNumber: entry.originalLine + lineOffset,
      columnNumber: entry.originalColumn + columnOffset,
    };
    if (entry.name !== undefined) {
      result.name = entry.name;
    }
    return result;
  }
}

// Cache for findSourceMap: path -> SourceMap | null (null means checked but not found)
const sourceMapCache = new SafeMap();

// Regex to match //# sourceMappingURL=<url> or //@ sourceMappingURL=<url>
const SOURCE_MAP_URL_RE =
  /\/\/[#@]\s*sourceMappingURL\s*=\s*(\S+)\s*(?:\n|\r\n?)?$/;

/**
 * Extract the sourceMappingURL from the last non-empty line of content.
 * @param {string} content
 * @returns {string | null}
 */
function extractSourceMapUrl(content) {
  // Search backwards from the end for the sourceMappingURL comment.
  // The comment must appear in the last non-empty line.
  const match = RegExpPrototypeExec(SOURCE_MAP_URL_RE, content);
  return match ? match[1] : null;
}

/**
 * Resolve a source map from a sourceMappingURL.
 * Handles both inline data URIs and external file references.
 * @param {string} url - The sourceMappingURL value
 * @param {string} filePath - The path of the file containing the reference
 * @returns {object | null} - Parsed source map payload or null
 */
function resolveSourceMapPayload(url, filePath) {
  // Handle inline base64 data URIs
  if (StringPrototypeStartsWith(url, "data:")) {
    const dataUrlMatch = StringPrototypeMatch(
      url,
      /^data:application\/json;(?:charset=utf-?8;)?base64,(.+)$/,
    );
    if (dataUrlMatch) {
      try {
        const decoded = atob(dataUrlMatch[1]);
        return JSONParse(decoded);
      } catch {
        return null;
      }
    }
    return null;
  }

  // Handle external source map files
  try {
    let mapPath;
    if (
      StringPrototypeStartsWith(url, "/") ||
      RegExpPrototypeTest(/^[a-zA-Z]:\\/, url)
    ) {
      // Absolute path
      mapPath = url;
    } else {
      // Relative path - resolve against the source file's directory
      const dir = op_require_path_dirname(filePath);
      mapPath = op_require_path_resolve([dir, url]);
    }
    const mapContent = op_require_read_file(mapPath);
    if (mapContent) {
      return JSONParse(mapContent);
    }
  } catch {
    // File not found or invalid JSON - return null
  }
  return null;
}

/**
 * @param {string} path
 * @returns {SourceMap | undefined}
 */
export function findSourceMap(path) {
  // Normalize the path to avoid duplicate cache entries for equivalent paths
  // (e.g. "/foo/bar.js" vs "/foo/./bar.js")
  path = op_require_path_resolve([path]);

  if (sourceMapCache.has(path)) {
    const cached = sourceMapCache.get(path);
    return cached === null ? undefined : cached;
  }

  try {
    const content = op_require_read_file(path);
    if (!content) {
      sourceMapCache.set(path, null);
      return undefined;
    }

    const url = extractSourceMapUrl(content);
    if (!url) {
      sourceMapCache.set(path, null);
      return undefined;
    }

    const payload = resolveSourceMapPayload(url, path);
    if (!payload) {
      sourceMapCache.set(path, null);
      return undefined;
    }

    // Compute lineLengths from the source file content
    const lines = StringPrototypeSplit(
      StringPrototypeReplace(content, /\n$/, ""),
      "\n",
    );
    const lineLengths = [];
    for (let i = 0; i < lines.length; i++) {
      ArrayPrototypePush(lineLengths, lines[i].length);
    }

    const sourceMap = new SourceMap(payload, { lineLengths });
    sourceMapCache.set(path, sourceMap);
    return sourceMap;
  } catch {
    sourceMapCache.set(path, null);
    return undefined;
  }
}

Module.findSourceMap = findSourceMap;
Module.SourceMap = SourceMap;

/**
 * @param {string} code
 * @param {{ mode?: "strip" | "transform", sourceMap?: boolean, sourceUrl?: string }} [options]
 * @returns {string}
 */
export function stripTypeScriptTypes(code, options = undefined) {
  if (typeof code !== "string") {
    throw new internalErrors.ERR_INVALID_ARG_TYPE("code", "string", code);
  }
  if (
    options !== undefined &&
    (typeof options !== "object" || options === null)
  ) {
    throw new internalErrors.ERR_INVALID_ARG_TYPE("options", "object", options);
  }

  const mode = options?.mode ?? "strip";
  if (mode !== "strip" && mode !== "transform") {
    throw new internalErrors.ERR_INVALID_ARG_VALUE(
      "options.mode",
      mode,
      "must be one of: 'strip', 'transform'",
    );
  }

  if (
    options?.sourceMap !== undefined &&
    typeof options.sourceMap !== "boolean"
  ) {
    throw new internalErrors.ERR_INVALID_ARG_TYPE(
      "options.sourceMap",
      "boolean",
      options.sourceMap,
    );
  }
  if (
    options?.sourceUrl !== undefined &&
    typeof options.sourceUrl !== "string"
  ) {
    throw new internalErrors.ERR_INVALID_ARG_TYPE(
      "options.sourceUrl",
      "string",
      options.sourceUrl,
    );
  }

  const sourceMap = options?.sourceMap === true;
  if (mode === "strip" && sourceMap) {
    throw new internalErrors.ERR_INVALID_ARG_VALUE(
      "options.sourceMap",
      sourceMap,
      "must be one of: false, undefined",
    );
  }

  let result;
  try {
    result = op_node_strip_typescript_types(code, mode, sourceMap);
  } catch (err) {
    if (mode === "strip") {
      const syntaxError = new SyntaxError(err.message);
      syntaxError.code = "ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX";
      throw syntaxError;
    }
    throw err;
  }

  if (!sourceMap && options?.sourceUrl !== undefined) {
    result += `\n\n//# sourceURL=${options.sourceUrl}`;
  }
  return result;
}

Module.stripTypeScriptTypes = stripTypeScriptTypes;

/**
 * @param {string | URL} _specifier
 * @param {string | URL} _parentUrl
 * @param {{ parentURL: string | URL, data: any, transferList: any[] }} [_options]
 */
export function register(_specifier, _parentUrl, _options) {
  // TODO(@marvinhagemeister): Stub implementation for programs registering
  // TypeScript loaders. We don't support registering loaders for file
  // types that Deno itself doesn't support at the moment.

  return undefined;
}

/**
 * Register synchronous module loader hooks.
 * @param {{ resolve?: Function, load?: Function }} hooks
 * @returns {{ deregister: () => void }}
 */
export function registerHooks(hooks) {
  const { resolve, load } = hooks;
  if (resolve) {
    internalValidators.validateFunction(resolve, "hooks.resolve");
  }
  if (load) {
    internalValidators.validateFunction(load, "hooks.load");
  }
  const entry = {
    resolve: typeof resolve === "function" ? resolve : null,
    load: typeof load === "function" ? load : null,
  };
  ArrayPrototypePush(hookEntries, entry);

  // Activate ESM hooks in Rust module loader
  _activateEsmHooks();

  return {
    deregister() {
      const idx = ArrayPrototypeIndexOf(hookEntries, entry);
      if (idx !== -1) {
        ArrayPrototypeSplice(hookEntries, idx, 1);
      }
      // Update Rust-side active flags
      _activateEsmHooks();
    },
  };
}

Module.registerHooks = registerHooks;

let initialized = false;

function initialize(args) {
  const {
    usesLocalNodeModulesDir: usesLocalNodeModulesDirArg,
    argv0,
    runningOnMainThread,
    workerId,
    maybeWorkerMetadata,
    nodeDebug,
    nodeClusterUniqueId,
    nodeClusterSchedPolicy,
    warmup = false,
    moduleSpecifier = null,
  } = args;
  if (!warmup) {
    if (initialized) {
      throw new Error("Node runtime already initialized");
    }
    initialized = true;
    if (usesLocalNodeModulesDirArg) {
      usesLocalNodeModulesDir = true;
    }

    internals.__bootstrapNodeProcess(
      argv0,
      Deno.args,
      Deno.version,
      nodeDebug ?? "",
      false,
      runningOnMainThread,
    );
    internals.__initWorkerThreads(
      runningOnMainThread,
      workerId,
      maybeWorkerMetadata,
      moduleSpecifier,
    );
    // `child_process.ts` is in `lazy_loaded_js` (see ext/node/lib.rs), so its
    // module body - which registers `internals.__setupChildProcessIpcChannel`
    // - only runs once `loadExtScript` is called. Skip both when there is no
    // IPC pipe configured. (NOTE: under node-defer this `initialize` does not
    // auto-run, so a forked IPC child does not yet get this setup -- known
    // follow-up; see process.ts bootstrap trigger.)
    if (op_node_has_child_ipc_pipe()) {
      core.loadExtScript("ext:deno_node/child_process.ts");
      internals.__setupChildProcessIpcChannel();
    }
    if (nodeClusterUniqueId) {
      core.loadExtScript("ext:deno_node/cluster.ts");
      internals.__initCluster(nodeClusterUniqueId, nodeClusterSchedPolicy);
    }
    // (stream-wrap GothamState registration moved to process.ts's
    // __bootstrapNodeProcess, which this calls above at 3090 -- single
    // registration point that also covers the node-defer path.)
    nativeModuleExports["internal/console/constructor"].bindStreamsLazy(
      nativeModuleExports["console"],
      nativeModuleExports["process"],
    );
    nativeModuleExports["internal/console/constructor"].bindStreamsLazy(
      globalThis.console,
      nativeModuleExports["process"],
    );
  } else {
    internals.__bootstrapNodeProcess(
      undefined,
      undefined,
      undefined,
      undefined,
      true,
    );
  }
}

globalThis.nodeBootstrap = initialize;

// node-defer: `initialize()` is the only place that sets
// `usesLocalNodeModulesDir`, but it does not auto-run when node:module is
// loaded lazily (see below). Apply the node_modules-dir mode from the stashed
// bootstrap args at module-eval so `require.resolve(x, { paths })` and the
// bare-specifier resolution fallback behave the same as in the eager path.
if (!initialized && internals.__nodeBootstrapArgs?.usesLocalNodeModulesDir) {
  usesLocalNodeModulesDir = true;
}

// Pre-enable any trace event categories requested via the spawning process's
// --trace-event-categories flag (propagated as an env var by child_process).
// Runs at module-eval (not inside `initialize`, which doesn't auto-run under
// node-defer) so node.async_hooks tracing works in every isolate, including
// worker threads. No-ops unless tracing was explicitly requested, so it never
// forces node:process to load for ordinary programs.
let traceEventsPreEnabled = false;
function preEnableTraceEvents() {
  if (traceEventsPreEnabled) {
    return;
  }
  traceEventsPreEnabled = true;
  const traceCategoriesEnv = op_get_env_no_permission_check(
    "DENO_NODE_TRACE_EVENT_CATEGORIES",
  );
  if (!traceCategoriesEnv) {
    return;
  }
  const categories = traceCategoriesEnv.split(",").filter((c) => c.length > 0);
  if (categories.length === 0) {
    return;
  }
  const traceEvents = core.loadExtScript("ext:deno_node/trace_events.ts");
  // Surface the flag through process.execArgv so test fixtures that probe it
  // (e.g. node's test-trace-events-api) see the same shape they would in Node.
  const proc = nativeModuleExports["process"];
  if (proc && Array.isArray(proc.execArgv)) {
    proc.execArgv.push("--trace-event-categories", traceCategoriesEnv);
  }
  try {
    traceEvents.createTracing({ categories }).enable();
  } catch {
    // Invalid categories must not block startup.
  }
}
preEnableTraceEvents();

// node-defer: node:process's own deferred trigger runs the process half of
// the bootstrap (`__bootstrapNodeProcess`) on first node:* use. The other
// half of `initialize` (worker_threads alias, IPC, cluster, trace_events) used
// to run unconditionally; under node-defer each
// piece is now handled where it belongs:
// - worker_threads MessageChannel/MessagePort alias: at the bottom of
//   ext/node/polyfills/worker_threads.ts module body, so importing
//   node:worker_threads is enough to install the globals.
// - IPC fork bootstrap: 99_main.js runs the full eager bootstrap when
//   `op_node_has_child_ipc_pipe()` is true (forked child path).
// - cluster init / trace_events env-var pre-enable:
//   still pending; only matter when those features are actively used and
//   are tracked as follow-ups, not regressions for ordinary programs.

function closeIdleConnections() {
  try {
    const http = nativeModuleExports["http"];
    if (http?.globalAgent) {
      http.globalAgent.destroy();
    }
  } catch {
    // Ignore
  }
  try {
    const https = nativeModuleExports["https"];
    if (https?.globalAgent) {
      https.globalAgent.destroy();
    }
  } catch {
    // Ignore
  }
}

internals.closeIdleConnections = closeIdleConnections;

export {
  builtinModules,
  createRequire,
  findPackageJSON,
  getBuiltinModule,
  isBuiltin,
  Module,
  SourceMap,
  syncBuiltinESMExports,
};
export const _cache = Module._cache;
export const _extensions = Module._extensions;
export const _findPath = Module._findPath;
export const _initPaths = Module._initPaths;
export const _load = Module._load;
export const _nodeModulePaths = Module._nodeModulePaths;
export const _pathCache = Module._pathCache;
export const _preloadModules = Module._preloadModules;
export const _resolveFilename = Module._resolveFilename;
export const _resolveLookupPaths = Module._resolveLookupPaths;
export const _stat = Module._stat;
export const globalPaths = Module.globalPaths;
export const runMain = Module.runMain;

export default Module;