bun_runtime 0.5.5

Bao runtime integration — JS engine + Bun API + event loop
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
// @trace REQ-ENG-007
use ::std::path::{MAIN_SEPARATOR, Path, PathBuf};
use ::std::ptr::NonNull;
use bun_core::ZBox;

use mozjs::jsapi::*;
use mozjs::jsval::{JSVal, ObjectValue, UndefinedValue};
use mozjs::rooted;
use mozjs::rust::wrappers2 as w2;

// return_string is the crate-wide single source in node_crypto
// (REQ-ARCH-1 duplicate convergence).
use crate::node_crypto::return_string;
use crate::require::cache_builtin;

// ──────────────────────────────────────────────────────────────────────────
// Node.js path algorithm cores — the REAL posix and win32 faces (node ships
// a genuine implementation of BOTH algorithms on every platform, so
// `path.posix` and `path.win32` behave identically everywhere; only the
// separators and root forms differ).
//
// `node_alg` below is a faithful port of node's lib/path.js string
// algorithms (v21.6.1 lineage; cross-verified line-by-line against bun's
// runtime/node/path.zig port and empirically against the node v24.19.0
// oracle for every vector in the trailing-separator / dot-basename /
// win32-separator divergence class). The previous hand-rolled segment
// splitter dropped surviving trailing separators (`normalize('bar/foo../../')`
// answered 'bar' instead of 'bar/'), left '..' unresolved in join outputs,
// mis-answered dot-only basenames in extname ('..') and trailing-separator
// inputs in basename/dirname — all B-class Node-semantics divergences
// (REQ-ENG-007).
// ──────────────────────────────────────────────────────────────────────────

mod node_alg {
    /// node `isPathSeparator` — win32 additionally treats '\' as a separator.
    #[inline]
    fn is_sep(c: u8, windows: bool) -> bool {
        c == b'/' || (windows && c == b'\\')
    }

    /// node `isWindowsDeviceRoot` — 'a'..'z' / 'A'..'Z'.
    #[inline]
    fn is_device_root(c: u8) -> bool {
        c.is_ascii_alphabetic()
    }

    /// node `normalizeString` — resolves `.` / `..` segments. Faithful port
    /// (bun runtime/node/path.zig `normalizeStringT`), including the
    /// trailing-separator preservation semantics: a surviving trailing
    /// separator in the input yields one trailing separator in the output
    /// (`normalize('bar/foo../../') === 'bar/'`), and `..` resolution never
    /// consumes a segment that does not exist (leading `..` survives on
    /// relative paths when `allow_above_root`).
    ///
    /// `sep` is the OUTPUT separator ('/' posix, '\\' win32); on win32 both
    /// separators are recognized in the input.
    /// `..`-segment pop of the normalizeString port: truncate `res` back
    /// to its last output separator and recompute `lastSegmentLength`.
    fn normalize_pop_segment(res: &mut Vec<u8>, last_segment_length: &mut usize, sep: u8) {
        match res.iter().rposition(|&c| c == sep) {
            None => {
                res.clear();
                *last_segment_length = 0;
            }
            Some(idx) => {
                res.truncate(idx);
                // node quirk (see bun's translation note):
                // lastSegmentLength derives from a lastIndexOf over the
                // truncated result.
                *last_segment_length = match res.iter().rposition(|&c| c == sep) {
                    None => res.len(),
                    Some(inner) => res.len() - 1 - inner,
                };
            }
        }
    }

    pub fn normalize_string(path: &str, allow_above_root: bool, sep: u8, windows: bool) -> String {
        let bytes = path.as_bytes();
        let len = bytes.len();
        let mut res: Vec<u8> = Vec::new();
        let mut last_segment_length: usize = 0;
        let mut last_slash: Option<usize> = None;
        // None = "saw a non-dot"; Some(n) = run of n dots since last segment.
        let mut dots: Option<usize> = Some(0);
        let mut byte: u8 = 0;
        let mut i: usize = 0;

        while i <= len {
            if i < len {
                byte = bytes[i];
            } else if is_sep(byte, windows) {
                break;
            } else {
                byte = b'/';
            }

            if is_sep(byte, windows) {
                if (last_slash.is_none() && i == 0)
                    || (i > 0 && last_slash.is_some() && last_slash.unwrap() == i - 1)
                    || dots == Some(1)
                {
                    // Consecutive separators, leading separator, or a '.'
                    // segment — no-op.
                } else if dots == Some(2) {
                    // '..' segment: pop the previous segment unless `res`
                    // already ends with '..'.
                    let ends_with_dotdot = res.len() >= 2
                        && last_segment_length == 2
                        && res[res.len() - 1] == b'.'
                        && res[res.len() - 2] == b'.';
                    if !ends_with_dotdot {
                        if res.len() > 2 {
                            normalize_pop_segment(&mut res, &mut last_segment_length, sep);
                            last_slash = Some(i);
                            dots = Some(0);
                            i += 1;
                            continue;
                        } else if !res.is_empty() {
                            res.clear();
                            last_segment_length = 0;
                            last_slash = Some(i);
                            dots = Some(0);
                            i += 1;
                            continue;
                        }
                    }
                    if allow_above_root {
                        if res.is_empty() {
                            res.extend_from_slice(b"..");
                        } else {
                            res.push(sep);
                            res.extend_from_slice(b"..");
                        }
                        last_segment_length = 2;
                    }
                } else {
                    // Regular segment: append with the output separator.
                    if !res.is_empty() {
                        res.push(sep);
                    }
                    let slice_start = last_slash.map_or(0, |s| s + 1);
                    res.extend_from_slice(&bytes[slice_start..i]);
                    let subtract = last_slash.map_or(2, |s| s + 1);
                    last_segment_length = if i >= subtract { i - subtract } else { 0 };
                }
                last_slash = Some(i);
                dots = Some(0);
                i += 1;
                continue;
            } else if byte == b'.' && dots.is_some() {
                dots = Some(dots.unwrap() + 1);
            } else {
                dots = None;
            }
            i += 1;
        }
        String::from_utf8_lossy(&res).into_owned()
    }

    /// node path.posix.normalize / path.win32.normalize.
    pub fn normalize(path: &str, windows: bool) -> String {
        let bytes = path.as_bytes();
        if bytes.is_empty() {
            return ".".to_string();
        }
        if windows {
            return normalize_windows(path);
        }
        let is_absolute = bytes[0] == b'/';
        let trailing = is_sep(bytes[bytes.len() - 1], false);
        let normalized = normalize_string(path, !is_absolute, b'/', false);
        if normalized.is_empty() {
            return if is_absolute {
                "/".to_string()
            } else if trailing {
                "./".to_string()
            } else {
                ".".to_string()
            };
        }
        let mut out = normalized;
        if trailing {
            out.push('/');
        }
        if is_absolute {
            out.insert(0, '/');
        }
        out
    }

    /// node path.win32.normalize — device / UNC root extraction (bun
    /// `normalizeWindowsT`), with the tail normalized by `normalize_string`.
    fn normalize_windows(path: &str) -> String {
        let bytes = path.as_bytes();
        let len = bytes.len();
        if len == 1 {
            // `path` is a single character: a lone separator normalizes to
            // the win32 root, anything else is itself.
            return if is_sep(bytes[0], true) {
                "\\".to_string()
            } else {
                path.to_string()
            };
        }

        let byte0 = bytes[0];
        let mut root_end: usize = 0;
        let mut device: Option<String> = None;
        let mut is_absolute = false;

        if is_sep(byte0, true) {
            // Possible UNC root.
            is_absolute = true;
            if is_sep(bytes[1], true) {
                let mut j = 2usize;
                let mut last = j;
                while j < len && !is_sep(bytes[j], true) {
                    j += 1;
                }
                if j < len && j != last {
                    let first_part = &path[last..j];
                    last = j;
                    while j < len && is_sep(bytes[j], true) {
                        j += 1;
                    }
                    if j < len && j != last {
                        last = j;
                        while j < len && !is_sep(bytes[j], true) {
                            j += 1;
                        }
                        if j == len {
                            // UNC root only — normalized form keeps the
                            // trailing separator: `\\\\<server>\\<share>\\`.
                            return format!("\\\\{}\\{}\\", first_part, &path[last..]);
                        }
                        if j != last {
                            device = Some(format!("\\\\{}{}", first_part, &path[last..j]));
                            root_end = j;
                        }
                    }
                }
            } else {
                root_end = 1;
            }
        } else if is_device_root(byte0) && bytes[1] == b':' {
            // Possible device root ('C:' / 'c:').
            device = Some(path[0..2].to_string());
            root_end = 2;
            if len > 2 && is_sep(bytes[2], true) {
                is_absolute = true;
                root_end = 3;
            }
        }

        let mut tail = if root_end < len {
            normalize_string(&path[root_end..], !is_absolute, b'\\', true)
        } else {
            String::new()
        };
        if tail.is_empty() && !is_absolute {
            tail.push('.');
        }
        if !tail.is_empty() && is_sep(bytes[len - 1], true) {
            tail.push('\\');
        }
        let mut out = String::with_capacity(
            device.as_ref().map_or(0, |d| d.len()) + is_absolute as usize + tail.len(),
        );
        if let Some(d) = &device {
            out.push_str(d);
        }
        if is_absolute {
            out.push('\\');
        }
        out.push_str(&tail);
        out
    }

    /// node path.posix.join / path.win32.join — concatenate the non-empty
    /// parts with the face separator, then normalize the joined string (this
    /// is why join resolves a trailing '..' the same way normalize does).
    pub fn join(parts: &[&str], windows: bool) -> String {
        let sep: u8 = if windows { b'\\' } else { b'/' };
        if parts.is_empty() {
            return ".".to_string();
        }
        let mut joined = String::new();
        let mut first_part: Option<&str> = None;
        for p in parts {
            if p.is_empty() {
                continue;
            }
            if first_part.is_none() {
                first_part = Some(p);
            }
            if !joined.is_empty() {
                joined.push(sep as char);
            }
            joined.push_str(p);
        }
        if joined.is_empty() {
            return ".".to_string();
        }
        if windows {
            joined = collapse_win32_leading_separators(&joined, first_part.unwrap_or(""));
        }
        normalize(&joined, windows)
    }

    /// node win32.join's pre-normalize step: make sure the joined path does
    /// not start with two separators (normalize would mistake it for a UNC
    /// root) unless the first part explicitly named a UNC share. `first_part`
    /// is the first non-empty argument (node inspects its prefix, not the
    /// joined string's).
    fn collapse_win32_leading_separators(joined: &str, first_part: &str) -> String {
        let bytes = joined.as_bytes();
        let first_bytes = first_part.as_bytes();
        let mut needs_replace = true;
        let mut slash_count = 0usize;
        if is_sep(first_bytes[0], true) {
            slash_count += 1;
            let first_len = first_bytes.len();
            if first_len > 1 && is_sep(first_bytes[1], true) {
                slash_count += 1;
                if first_len > 2 {
                    if is_sep(first_bytes[2], true) {
                        slash_count += 1;
                    } else {
                        // The first part named a UNC server: keep the root.
                        needs_replace = false;
                    }
                }
            }
        }
        if !needs_replace {
            return joined.to_string();
        }
        let len = bytes.len();
        while slash_count < len && is_sep(bytes[slash_count], true) {
            slash_count += 1;
        }
        if slash_count >= 2 {
            format!("\\{}", &joined[slash_count..])
        } else {
            joined.to_string()
        }
    }

    /// node path.posix.dirname / path.win32.dirname — trailing separators
    /// are stripped before the parent is taken ('/a/b/' → '/a').
    pub fn dirname(path: &str, windows: bool) -> String {
        let bytes = path.as_bytes();
        let len = bytes.len();
        if len == 0 {
            return ".".to_string();
        }
        if windows {
            return dirname_windows(path);
        }
        let has_root = bytes[0] == b'/';
        let mut end: Option<usize> = None;
        let mut matched_slash = true;
        let mut i = len - 1;
        while i >= 1 {
            if bytes[i] == b'/' {
                if !matched_slash {
                    end = Some(i);
                    break;
                }
            } else {
                matched_slash = false;
            }
            i -= 1;
        }
        if let Some(e) = end {
            return if has_root && e == 1 {
                "//".to_string()
            } else {
                path[0..e].to_string()
            };
        }
        if has_root {
            "/".to_string()
        } else {
            ".".to_string()
        }
    }

    fn dirname_windows(path: &str) -> String {
        let bytes = path.as_bytes();
        let len = bytes.len();
        let byte0 = bytes[0];
        if len == 1 {
            return if is_sep(byte0, true) {
                path.to_string()
            } else {
                ".".to_string()
            };
        }

        let mut root_end: Option<usize> = None;
        let mut offset = 0usize;

        if is_sep(byte0, true) {
            // Possible UNC root.
            root_end = Some(1);
            offset = 1;
            if is_sep(bytes[1], true) {
                let mut j = 2usize;
                let mut last = j;
                while j < len && !is_sep(bytes[j], true) {
                    j += 1;
                }
                if j < len && j != last {
                    last = j;
                    while j < len && is_sep(bytes[j], true) {
                        j += 1;
                    }
                    if j < len && j != last {
                        last = j;
                        while j < len && !is_sep(bytes[j], true) {
                            j += 1;
                        }
                        if j == len {
                            return path.to_string();
                        }
                        if j != last {
                            offset = j + 1;
                            root_end = Some(offset);
                        }
                    }
                }
            }
        } else if is_device_root(byte0) && bytes[1] == b':' {
            offset = if len > 2 && is_sep(bytes[2], true) { 3 } else { 2 };
            root_end = Some(offset);
        }

        let mut end: Option<usize> = None;
        let mut matched_slash = true;
        let mut i = len as i64 - 1;
        while i >= offset as i64 {
            let iu = i as usize;
            if is_sep(bytes[iu], true) {
                if !matched_slash {
                    end = Some(iu);
                    break;
                }
            } else {
                matched_slash = false;
            }
            i -= 1;
        }
        if let Some(e) = end {
            return path[0..e].to_string();
        }
        match root_end {
            Some(r) => path[0..r].to_string(),
            None => ".".to_string(),
        }
    }

    /// Backward suffix scan shared by `basename` / `basename_windows`
    /// (node path.zig basename port): scans from the tail matching the
    /// suffix while locating the last segment start, then slices the
    /// result the node way (`start == end` falls back to the first
    /// non-slash end). Only reached with a non-empty suffix no longer
    /// than the path; always returns the final answer.
    fn basename_suffix_scan(path: &str, suffix: &str, start: usize, windows: bool) -> String {
        let bytes = path.as_bytes();
        let len = bytes.len();
        let sfx_bytes = suffix.as_bytes();
        let mut start = start;
        let mut end: Option<usize> = None;
        let mut matched_slash = true;
        let mut ext_idx: Option<usize> = Some(sfx_bytes.len() - 1);
        let mut first_non_slash_end: Option<usize> = None;
        let mut i = len as i64 - 1;
        while i >= start as i64 {
            let iu = i as usize;
            let byte = bytes[iu];
            if is_sep(byte, windows) {
                if !matched_slash {
                    start = iu + 1;
                    break;
                }
            } else {
                if first_non_slash_end.is_none() {
                    matched_slash = false;
                    first_non_slash_end = Some(iu + 1);
                }
                if let Some(ei) = ext_idx {
                    if byte == sfx_bytes[ei] {
                        if ei == 0 {
                            end = Some(iu);
                            ext_idx = None;
                        } else {
                            ext_idx = Some(ei - 1);
                        }
                    } else {
                        ext_idx = None;
                        end = first_non_slash_end;
                    }
                }
            }
            i -= 1;
        }
        if let Some(e) = end {
            if start == e {
                return path[start..first_non_slash_end.unwrap_or(len)].to_string();
            }
            return path[start..e].to_string();
        }
        path[start..len].to_string()
    }

    /// node path.posix.basename / path.win32.basename — trailing separators
    /// are stripped before extraction ('/dir/' → 'dir'). `suffix` follows
    /// node's backward scan (the suffix must match the tail of the last
    /// segment; a suffix that spans a separator does not strip).
    pub fn basename(path: &str, suffix: Option<&str>, windows: bool) -> String {
        let bytes = path.as_bytes();
        let len = bytes.len();
        if len == 0 {
            return String::new();
        }
        if windows {
            return basename_windows(path, suffix);
        }

        let mut start = 0usize;
        let mut end: Option<usize> = None;
        let mut matched_slash = true;

        if let Some(sfx) = suffix {
            let sfx_len = sfx.len();
            if sfx_len > 0 && sfx_len <= len {
                if sfx == path {
                    return String::new();
                }
                return basename_suffix_scan(path, sfx, start, windows);
            }
        }

        let mut i = len as i64 - 1;
        while i > -1 {
            let iu = i as usize;
            let byte = bytes[iu];
            if byte == b'/' {
                if !matched_slash {
                    start = iu + 1;
                    break;
                }
            } else if end.is_none() {
                matched_slash = false;
                end = Some(iu + 1);
            }
            i -= 1;
        }
        match end {
            Some(e) => path[start..e].to_string(),
            None => String::new(),
        }
    }

    fn basename_windows(path: &str, suffix: Option<&str>) -> String {
        let bytes = path.as_bytes();
        let len = bytes.len();
        let mut start = 0usize;
        let mut end: Option<usize> = None;
        let mut matched_slash = true;

        // A drive prefix ('C:') is not a separator: skip it so the scan does
        // not treat the separator after the drive as an end-of-path marker.
        if len >= 2 && is_device_root(bytes[0]) && bytes[1] == b':' {
            start = 2;
        }

        if let Some(sfx) = suffix {
            let sfx_len = sfx.len();
            if sfx_len > 0 && sfx_len <= len {
                if sfx == path {
                    return String::new();
                }
                return basename_suffix_scan(path, sfx, start, true);
            }
        }

        let mut i = len as i64 - 1;
        while i >= start as i64 {
            let iu = i as usize;
            let byte = bytes[iu];
            if is_sep(byte, true) {
                if !matched_slash {
                    start = iu + 1;
                    break;
                }
            } else if end.is_none() {
                matched_slash = false;
                end = Some(iu + 1);
            }
            i -= 1;
        }
        match end {
            Some(e) => path[start..e].to_string(),
            None => String::new(),
        }
    }

    /// node path.posix.extname / path.win32.extname — dot-only basenames
    /// have no extension ('..' / '.' / 'a/..' → ''), and trailing separators
    /// are stripped first ('file.ext/' → '.ext', 'file./' → '.').
    ///
    /// Implemented as the observed node rule (validated against the node
    /// v24.19.0 oracle over the full extname edge table incl. '...', '....',
    /// '..file.', trailing separators and mixed '..' segments):
    ///   1. strip trailing separators to get the basename,
    ///   2. a basename of exactly '..' has no extension,
    ///   3. otherwise the substring from the last '.' (empty when the dot
    ///      is the first character or absent).
    pub fn extname(path: &str, windows: bool) -> String {
        let bytes = path.as_bytes();
        let len = bytes.len();
        if len == 0 {
            return String::new();
        }
        // Strip trailing separators, then cut at the last interior one.
        let mut end = len;
        while end > 0 && is_sep(bytes[end - 1], windows) {
            end -= 1;
        }
        if end == 0 {
            return String::new();
        }
        let mut start = 0usize;
        let mut i = end;
        while i > 0 {
            i -= 1;
            if is_sep(bytes[i], windows) {
                start = i + 1;
                break;
            }
        }
        let base = &path[start..end];
        if base == ".." {
            return String::new();
        }
        match base.rfind('.') {
            Some(0) => String::new(),
            Some(idx) => base[idx..].to_string(),
            None => String::new(),
        }
    }

    /// node path.parse result — { root, dir, base, ext, name }.
    pub struct Parsed {
        pub root: String,
        pub dir: String,
        pub base: String,
        pub ext: String,
        pub name: String,
    }

    /// node path.posix.parse / path.win32.parse.
    pub fn parse(path: &str, windows: bool) -> Parsed {
        let bytes = path.as_bytes();
        let len = bytes.len();
        let empty = Parsed {
            root: String::new(),
            dir: String::new(),
            base: String::new(),
            ext: String::new(),
            name: String::new(),
        };
        if len == 0 {
            return empty;
        }
        if windows {
            return parse_windows(path);
        }

        let is_absolute = bytes[0] == b'/';
        let root = if is_absolute { "/".to_string() } else { String::new() };
        let mut start = if is_absolute { 1usize } else { 0usize };

        let mut start_dot: Option<usize> = None;
        let mut start_part = 0usize;
        let mut end: Option<usize> = None;
        let mut matched_slash = true;
        let mut pre_dot_state: Option<usize> = Some(0);

        let mut i = len as i64 - 1;
        while i >= start as i64 {
            let iu = i as usize;
            let byte = bytes[iu];
            if byte == b'/' {
                if !matched_slash {
                    start_part = iu + 1;
                    break;
                }
            } else {
                if end.is_none() {
                    matched_slash = false;
                    end = Some(iu + 1);
                }
                if byte == b'.' {
                    if start_dot.is_none() {
                        start_dot = Some(iu);
                    } else if let Some(p) = pre_dot_state {
                        if p != 1 {
                            pre_dot_state = Some(1);
                        }
                    }
                } else if start_dot.is_some() {
                    pre_dot_state = None;
                }
            }
            i -= 1;
        }

        let mut base = String::new();
        let mut name = String::new();
        let mut ext = String::new();
        if let Some(e) = end {
            start = if start_part == 0 && is_absolute { 1 } else { start_part };
            let no_ext = start_dot.is_none()
                || (pre_dot_state.is_some() && pre_dot_state.unwrap() == 0)
                || (pre_dot_state == Some(1)
                    && start_dot.unwrap() == e - 1
                    && start_dot.unwrap() == start_part + 1);
            if no_ext {
                name = path[start..e].to_string();
                base = name.clone();
            } else {
                name = path[start..start_dot.unwrap()].to_string();
                base = path[start..e].to_string();
                ext = path[start_dot.unwrap()..e].to_string();
            }
        }
        let dir = if start_part > 0 {
            path[0..start_part - 1].to_string()
        } else if is_absolute {
            "/".to_string()
        } else {
            String::new()
        };
        Parsed {
            root,
            dir,
            base,
            ext,
            name,
        }
    }

    fn parse_windows(path: &str) -> Parsed {
        let bytes = path.as_bytes();
        let len = bytes.len();
        let byte0 = bytes[0];
        if len == 1 {
            if is_sep(byte0, true) {
                return Parsed {
                    root: path.to_string(),
                    dir: path.to_string(),
                    base: String::new(),
                    ext: String::new(),
                    name: String::new(),
                };
            }
            return Parsed {
                root: String::new(),
                dir: String::new(),
                base: path.to_string(),
                ext: String::new(),
                name: path.to_string(),
            };
        }

        let mut root_end = 0usize;
        if is_sep(byte0, true) {
            root_end = 1;
            if is_sep(bytes[1], true) {
                let mut j = 2usize;
                let mut last = j;
                while j < len && !is_sep(bytes[j], true) {
                    j += 1;
                }
                if j < len && j != last {
                    last = j;
                    while j < len && is_sep(bytes[j], true) {
                        j += 1;
                    }
                    if j < len && j != last {
                        last = j;
                        while j < len && !is_sep(bytes[j], true) {
                            j += 1;
                        }
                        root_end = if j == len { j } else if j != last { j + 1 } else { root_end };
                    }
                }
            }
        } else if is_device_root(byte0) && bytes[1] == b':' {
            if len <= 2 {
                return Parsed {
                    root: path.to_string(),
                    dir: path.to_string(),
                    base: String::new(),
                    ext: String::new(),
                    name: String::new(),
                };
            }
            root_end = 2;
            if is_sep(bytes[2], true) {
                if len == 3 {
                    return Parsed {
                        root: path.to_string(),
                        dir: path.to_string(),
                        base: String::new(),
                        ext: String::new(),
                        name: String::new(),
                    };
                }
                root_end = 3;
            }
        }
        let root = if root_end > 0 {
            path[0..root_end].to_string()
        } else {
            String::new()
        };

        let mut start_dot: Option<usize> = None;
        let mut start_part = root_end;
        let mut end: Option<usize> = None;
        let mut matched_slash = true;
        let mut pre_dot_state: Option<usize> = Some(0);

        let mut i = len as i64 - 1;
        while i >= root_end as i64 {
            let iu = i as usize;
            let byte = bytes[iu];
            if is_sep(byte, true) {
                if !matched_slash {
                    start_part = iu + 1;
                    break;
                }
            } else {
                if end.is_none() {
                    matched_slash = false;
                    end = Some(iu + 1);
                }
                if byte == b'.' {
                    if start_dot.is_none() {
                        start_dot = Some(iu);
                    } else if let Some(p) = pre_dot_state {
                        if p != 1 {
                            pre_dot_state = Some(1);
                        }
                    }
                } else if start_dot.is_some() {
                    pre_dot_state = None;
                }
            }
            i -= 1;
        }

        let mut base = String::new();
        let mut name = String::new();
        let mut ext = String::new();
        if let Some(e) = end {
            let no_ext = start_dot.is_none()
                || (pre_dot_state.is_some() && pre_dot_state.unwrap() == 0)
                || (pre_dot_state == Some(1)
                    && start_dot.unwrap() == e - 1
                    && start_dot.unwrap() == start_part + 1);
            if no_ext {
                name = path[start_part..e].to_string();
                base = name.clone();
            } else {
                name = path[start_part..start_dot.unwrap()].to_string();
                base = path[start_part..e].to_string();
                ext = path[start_dot.unwrap()..e].to_string();
            }
        }
        // The directory is the root itself when the first segment starts at
        // the root end ('C:\abc' → dir 'C:\'); otherwise the trailing
        // separator is stripped ('C:\abc\def' → dir 'C:\abc').
        let dir = if start_part > 0 && start_part != root_end {
            path[0..start_part - 1].to_string()
        } else {
            root.clone()
        };
        Parsed {
            root,
            dir,
            base,
            ext,
            name,
        }
    }

    /// node path.format — `dir || root` + `base || name + formatExt(ext)`,
    /// joined with the face separator unless dir IS the pathObject root.
    pub fn format(p: &Parsed, windows: bool) -> String {
        let sep: char = if windows { '\\' } else { '/' };
        let dir_is_empty = p.dir.is_empty();
        let dir = if dir_is_empty { &p.root } else { &p.dir };
        let dir = dir.as_str();
        let base = if !p.base.is_empty() {
            p.base.clone()
        } else {
            // node formatExt: a missing leading dot is supplied.
            let ext = if p.ext.is_empty() {
                String::new()
            } else if p.ext.starts_with('.') {
                p.ext.clone()
            } else {
                format!(".{}", p.ext)
            };
            format!("{}{}", p.name, ext)
        };
        if dir.is_empty() {
            return base;
        }
        if dir == p.root {
            format!("{}{}", dir, base)
        } else {
            format!("{}{}{}", dir, sep, base)
        }
    }

    /// node path.posix.isAbsolute / path.win32.isAbsolute. On win32 a rooted
    /// path without a drive ('/foo') is absolute, and a bare device ('C:')
    /// is NOT.
    pub fn is_absolute(path: &str, windows: bool) -> bool {
        let bytes = path.as_bytes();
        if bytes.is_empty() {
            return false;
        }
        if windows {
            let c = bytes[0];
            is_sep(c, true)
                || (bytes.len() > 2
                    && is_device_root(c)
                    && bytes[1] == b':'
                    && is_sep(bytes[2], true))
        } else {
            bytes[0] == b'/'
        }
    }

    /// ASCII case-insensitive comparison — the `String.prototype.toLowerCase`
    /// equality node's win32 resolve/relative use for device and root
    /// matching (`C:` === `c:`, `\\SRV\share` === `\\srv\share`). Not
    /// host-gated: the `path.win32` FACE runs it on every platform.
    fn eq_ignore_case(a: &str, b: &str) -> bool {
        a.len() == b.len()
            && a.bytes()
                .zip(b.bytes())
                .all(|(x, y)| x.to_ascii_lowercase() == y.to_ascii_lowercase())
    }

    /// node win32.resolve — the device/UNC-aware resolution the Windows face
    /// runs (`path.resolve` on a Windows host). Iterates the arguments
    /// right-to-left keeping the right-most device + root, then anchors on
    /// the cwd (or the per-drive cwd when a bare device was pinned), so
    /// `resolve('')` answers the drive-qualified `process.cwd()`. Faithful
    /// port of node v22.11.0 lib/path.js win32 `resolve` (cross-verified
    /// against bun's runtime/node/path.zig `resolveWindowsT`).
    /// `drive_env` answers node's `process.env[`=${device}`]` per-drive cwd
    /// lookup; `None` falls through to the process cwd exactly like a
    /// missing environment entry in node. Not host-gated: node ships this
    /// algorithm on every platform (`path.win32.resolve('C:\\a\\b', 'c') ===
    /// Possible UNC root `\\<server>\<share>[tail]` — the `\\\\<server>\\<share>`
    /// device string and the index just past the share, or None when the
    /// bytes do not form one (either `\\`-run is empty or a separator run
    /// trails the share).
    fn parse_unc_root(bytes: &[u8], path: &str) -> Option<(String, usize)> {
        let len = bytes.len();
        let mut j = 2usize;
        let mut last = j;
        while j < len && !is_sep(bytes[j], true) {
            j += 1;
        }
        if j >= len || j == last {
            return None;
        }
        let first_part = &path[last..j];
        last = j;
        while j < len && is_sep(bytes[j], true) {
            j += 1;
        }
        if j >= len || j == last {
            return None;
        }
        last = j;
        while j < len && !is_sep(bytes[j], true) {
            j += 1;
        }
        if j == len || j != last {
            return Some((format!("\\\\{}\\{}", first_part, &path[last..j]), j));
        }
        None
    }

    /// 'C:\\a\\b\\c'` even on Linux — on a posix host the per-drive cwd
    /// lookup simply misses and the process cwd takes its place).
    pub fn resolve_win32(
        parts: &[&str],
        cwd: &str,
        drive_env: &dyn Fn(&str) -> Option<String>,
    ) -> String {
        let mut resolved_device = String::new();
        let mut resolved_tail = String::new();
        let mut resolved_absolute = false;

        // Arguments right-to-left, then the cwd fallback leg (node's
        // `i === -1`).
        for leg in parts.iter().rev().map(Some).chain(::std::iter::once(None)) {
            let path: String = match leg {
                Some(p) => {
                    if p.is_empty() {
                        continue;
                    }
                    (*p).to_string()
                }
                None if resolved_device.is_empty() => cwd.to_string(),
                None => {
                    // Windows keeps a per-drive cwd; node reads it from the
                    // environment and verifies it actually points at the
                    // resolved device, defaulting to the drive's root.
                    let device = resolved_device.clone();
                    let mut candidate = drive_env(&device).unwrap_or_else(|| cwd.to_string());
                    let cb = candidate.as_bytes();
                    if cb.len() > 2
                        && cb[2] == b'\\'
                        && !eq_ignore_case(&candidate[0..2], &device)
                    {
                        candidate = format!("{}\\", device);
                    }
                    candidate
                }
            };

            let bytes = path.as_bytes();
            let len = bytes.len();
            let mut root_end = 0usize;
            let mut device: Option<String> = None;
            let mut is_absolute = false;
            let byte0 = if len > 0 { bytes[0] } else { 0 };

            // Match a root: bare separator, UNC root, or device root.
            if len == 1 {
                if is_sep(byte0, true) {
                    root_end = 1;
                    is_absolute = true;
                }
            } else if is_sep(byte0, true) {
                is_absolute = true;
                if is_sep(bytes[1], true) {
                    // Possible UNC root: \\<server>\<share>[tail].
                    if let Some((unc_device, j)) = parse_unc_root(bytes, &path) {
                        device = Some(unc_device);
                        root_end = j;
                    }
                } else {
                    root_end = 1;
                }
            } else if is_device_root(byte0) && bytes[1] == b':' {
                // Possible device root ('C:' / 'c:').
                device = Some(path[0..2].to_string());
                root_end = 2;
                if len > 2 && is_sep(bytes[2], true) {
                    is_absolute = true;
                    root_end = 3;
                }
            }

            if let Some(d) = &device {
                if !resolved_device.is_empty() {
                    if !eq_ignore_case(d, &resolved_device) {
                        // This path points to another device: not applicable.
                        continue;
                    }
                } else {
                    resolved_device = d.clone();
                }
            }

            if resolved_absolute {
                if !resolved_device.is_empty() {
                    break;
                }
            } else {
                resolved_tail = format!("{}\\{}", &path[root_end..], resolved_tail);
                resolved_absolute = is_absolute;
                if is_absolute && !resolved_device.is_empty() {
                    break;
                }
            }
        }

        if resolved_tail.is_empty() {
            return ".".to_string();
        }
        let tail = normalize_string(&resolved_tail, !resolved_absolute, b'\\', true);
        if resolved_absolute {
            format!("{}\\{}", resolved_device, tail)
        } else {
            let out = format!("{}{}", resolved_device, tail);
            if out.is_empty() {
                ".".to_string()
            } else {
                out
            }
        }
    }

    /// node win32.relative — resolve both sides through `resolve_win32`
    /// first, then strip the (case-insensitively compared) common prefix,
    /// emitting `..` per surviving `from` segment. Faithful port of node
    /// v22.11.0 lib/path.js win32 `relative`. Not host-gated: the
    /// `path.win32` FACE runs it on every platform.
    pub fn relative_win32(
        from: &str,
        to: &str,
        cwd: &str,
        drive_env: &dyn Fn(&str) -> Option<String>,
    ) -> String {
        if from == to {
            return String::new();
        }
        let from_orig = resolve_win32(&[from], cwd, drive_env);
        let to_orig = resolve_win32(&[to], cwd, drive_env);
        if from_orig == to_orig || eq_ignore_case(&from_orig, &to_orig) {
            return String::new();
        }

        // node lowercases both resolved paths for the scan and slices the
        // originals (lengths agree); the per-byte compare below is the same
        // scan.
        let from = from_orig.as_bytes();
        let to = to_orig.as_bytes();

        // Trim leading backslashes.
        let mut from_start = 0usize;
        while from_start < from.len() && from[from_start] == b'\\' {
            from_start += 1;
        }
        // Trim trailing backslashes (applicable to UNC paths only).
        let mut from_end = from.len();
        while from_end > from_start && from[from_end - 1] == b'\\' {
            from_end -= 1;
        }
        let from_len = from_end - from_start;

        let mut to_start = 0usize;
        while to_start < to.len() && to[to_start] == b'\\' {
            to_start += 1;
        }
        let mut to_end = to.len();
        while to_end > to_start && to[to_end - 1] == b'\\' {
            to_end -= 1;
        }
        let to_len = to_end - to_start;

        // Longest common case-insensitive prefix.
        let length = from_len.min(to_len);
        let mut last_common_sep: Option<usize> = None;
        let mut i = 0usize;
        while i < length {
            let fb = from[from_start + i];
            if fb.to_ascii_lowercase() != to[to_start + i].to_ascii_lowercase() {
                break;
            }
            if fb == b'\\' {
                last_common_sep = Some(i);
            }
            i += 1;
        }
        let matched_all = i == length;

        if !matched_all {
            if last_common_sep.is_none() {
                // We found a mismatch before the first common path
                // separator was seen, so return the original `to`.
                return to_orig;
            }
        } else {
            if to_len > length {
                if to[to_start + length] == b'\\' {
                    // `from` is the exact base path for `to`
                    // (from='C:\foo\bar'; to='C:\foo\bar\baz').
                    return to_orig[to_start + length + 1..].to_string();
                }
                if length == 2 {
                    // `from` is the device root
                    // (from='C:\'; to='C:\foo').
                    return to_orig[to_start + length..].to_string();
                }
            }
            if from_len > length {
                if from[from_start + length] == b'\\' {
                    // `to` is the exact base path for `from`
                    // (from='C:\foo\bar'; to='C:\foo').
                    last_common_sep = Some(length);
                } else if length == 2 {
                    // `to` is the device root
                    // (from='C:\foo\bar'; to='C:\').
                    last_common_sep = Some(3);
                }
            }
        }

        // `..` per surviving `from` segment past the common prefix.
        let mut out = String::new();
        let mut i = from_start + last_common_sep.map_or(0, |s| s + 1);
        while i <= from_end {
            if i == from_end || from[i] == b'\\' {
                if out.is_empty() {
                    out.push_str("..");
                } else {
                    out.push_str("\\..");
                }
            }
            i += 1;
        }

        // `last_common_sep` is always resolved by the branches above (node's
        // `-1` is normalized to 0 before the tail).
        let to_start = to_start + last_common_sep.unwrap_or(0);
        if !out.is_empty() {
            return format!("{}{}", out, &to_orig[to_start..to_end]);
        }
        let mut to_start = to_start;
        if to_orig.as_bytes()[to_start] == b'\\' {
            to_start += 1;
        }
        to_orig[to_start..to_end].to_string()
    }

    /// node win32.toNamespacedPath — resolve, then prefix the `\\?\` long
    /// namespace (`\\?\UNC\` for non-long UNC roots); short results come
    /// back verbatim. Not host-gated: the `path.win32` FACE runs it on
    /// every platform.
    pub fn to_namespaced_win32(
        path: &str,
        cwd: &str,
        drive_env: &dyn Fn(&str) -> Option<String>,
    ) -> String {
        if path.is_empty() {
            return path.to_string();
        }
        let resolved = resolve_win32(&[path], cwd, drive_env);
        let b = resolved.as_bytes();
        if b.len() <= 2 {
            return path.to_string();
        }
        if b[0] == b'\\' && b[1] == b'\\' {
            let code = b[2];
            if code != b'?' && code != b'.' {
                // Non-long UNC root → long UNC form.
                return format!("\\\\?\\UNC\\{}", &resolved[2..]);
            }
        } else if is_device_root(b[0]) && b[1] == b':' && b.len() > 2 && b[2] == b'\\' {
            return format!("\\\\?\\{}", resolved);
        }
        resolved
    }
}

mod posix_core {
    /// Split a posix path into segments; keeps a leading-root flag.
    /// (Consumed by `resolve` / `relative` below; the string-algorithm
    /// primitives live in `node_alg`.)
    fn split(p: &str) -> (bool, Vec<&str>) {
        let rooted = p.starts_with('/');
        let segs = p
            .split('/')
            .filter(|s| !s.is_empty() && *s != ".")
            .collect();
        (rooted, segs)
    }

    pub fn normalize(p: &str) -> String {
        super::node_alg::normalize(p, false)
    }

    pub fn join(parts: &[String]) -> String {
        let joined: Vec<&str> = parts.iter().map(|s| s.as_str()).collect();
        super::node_alg::join(&joined, false)
    }

    pub fn is_absolute(p: &str) -> bool {
        super::node_alg::is_absolute(p, false)
    }

    pub fn resolve(parts: &[String], cwd: &str) -> String {
        // Right-most absolute segment wins; otherwise cwd + parts.
        let mut abs_start = 0usize;
        for (i, p) in parts.iter().enumerate() {
            if is_absolute(p) {
                abs_start = i;
            }
        }
        let mut base: Vec<&str> = Vec::new();
        let mut rooted = false;
        if abs_start == 0 && !parts.first().is_some_and(|p| is_absolute(p)) {
            let (r, segs) = split(cwd);
            rooted = r;
            base = segs;
        }
        for p in &parts[abs_start..] {
            let (_r, segs) = split(p);
            rooted = rooted || is_absolute(p);
            for seg in segs {
                if seg == ".." {
                    if !base.is_empty() && *base.last().unwrap() != ".." {
                        base.pop();
                    } else if !rooted {
                        base.push(seg);
                    }
                } else {
                    base.push(seg);
                }
            }
        }
        let joined = base.join("/");
        if rooted {
            format!("/{}", joined)
        } else if joined.is_empty() {
            "/".to_string()
        } else {
            joined
        }
    }

    pub fn dirname(p: &str) -> String {
        super::node_alg::dirname(p, false)
    }

    pub fn basename(p: &str, ext: Option<&str>) -> String {
        super::node_alg::basename(p, ext, false)
    }

    pub fn extname(p: &str) -> String {
        super::node_alg::extname(p, false)
    }

    pub fn relative(from: &str, to: &str) -> String {
        let fa = normalize(from);
        let ta = normalize(to);
        if fa == ta {
            return String::new();
        }
        let (_, fseg) = split(&fa);
        let (_, tseg) = split(&ta);
        let mut i = 0;
        while i < fseg.len() && i < tseg.len() && fseg[i] == tseg[i] {
            i += 1;
        }
        let ups = fseg.len() - i;
        let mut parts: Vec<String> = Vec::new();
        for _ in 0..ups {
            parts.push("..".to_string());
        }
        for seg in &tseg[i..] {
            parts.push(seg.to_string());
        }
        if parts.is_empty() {
            ".".to_string()
        } else {
            parts.join("/")
        }
    }

    /// node posix.parse: { root, dir, base, ext, name }
    pub fn parse(p: &str) -> (String, String, String, String, String) {
        let parsed = super::node_alg::parse(p, false);
        (
            parsed.root,
            parsed.dir,
            parsed.base,
            parsed.ext,
            parsed.name,
        )
    }

    pub fn format(p: &super::node_alg::Parsed) -> String {
        super::node_alg::format(p, false)
    }
}

/// path.win32 — the genuine win32 face (node ships the Windows algorithm on
/// every platform, so `path.win32.normalize('a/b') === 'a\\b'` even on
/// Linux). Pure-string cores from `node_alg`; the cwd-dependent members
/// (`resolve` / `relative` / `toNamespacedPath`) run the `*_win32` cores on
/// every host too — the `=X:` per-drive cwd lookup simply misses on posix
/// hosts and falls through to the process cwd, matching node.
mod win32_core {
    pub fn normalize(p: &str) -> String {
        super::node_alg::normalize(p, true)
    }

    pub fn join(parts: &[String]) -> String {
        let joined: Vec<&str> = parts.iter().map(|s| s.as_str()).collect();
        super::node_alg::join(&joined, true)
    }

    pub fn dirname(p: &str) -> String {
        super::node_alg::dirname(p, true)
    }

    pub fn basename(p: &str, ext: Option<&str>) -> String {
        super::node_alg::basename(p, ext, true)
    }

    pub fn extname(p: &str) -> String {
        super::node_alg::extname(p, true)
    }

    pub fn is_absolute(p: &str) -> bool {
        super::node_alg::is_absolute(p, true)
    }

    pub fn parse(p: &str) -> (String, String, String, String, String) {
        let parsed = super::node_alg::parse(p, true);
        (
            parsed.root,
            parsed.dir,
            parsed.base,
            parsed.ext,
            parsed.name,
        )
    }

    pub fn format(p: &super::node_alg::Parsed) -> String {
        super::node_alg::format(p, true)
    }
}

/// arg_to_string for the posix natives (same contract as the platform fns).
#[allow(unsafe_op_in_unsafe_fn)]
unsafe fn posix_arg(cx: *mut JSContext, v: mozjs::jsval::JSVal) -> Option<String> {
    arg_to_string(cx, v)
}

macro_rules! posix_str_fn {
    ($name:ident, $jsname:literal, $body:expr) => {
        #[allow(unsafe_op_in_unsafe_fn)]
        unsafe extern "C" fn $name(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
            let args = ::mozjs::jsapi::CallArgs::from_vp(vp, argc);
            let out: Option<String> = $body(cx, &args, argc);
            match out {
                Some(s) => return_string(cx, &args, &s),
                None => {
                    ::mozjs::jsapi::JS_ReportErrorUTF8(
                        cx,
                        c"posix path: invalid argument".as_ptr(),
                    );
                    false
                }
            }
        }
    };
}

posix_str_fn!(js_posix_join, "join", |cx: *mut JSContext,
                                    args: &::mozjs::jsapi::CallArgs,
                                    argc: u32|
 -> Option<String> {
    let mut parts = Vec::new();
    for i in 0..argc {
        parts.push(posix_arg(cx, *args.get(i).ptr)?);
    }
    Some(posix_core::join(&parts))
});
posix_str_fn!(js_posix_normalize, "normalize", |cx: *mut JSContext,
                                             args: &::mozjs::jsapi::CallArgs,
                                             _argc: u32|
 -> Option<String> {
    Some(posix_core::normalize(&posix_arg(cx, *args.get(0).ptr)?))
});
posix_str_fn!(js_posix_resolve, "resolve", |cx: *mut JSContext,
                                         args: &::mozjs::jsapi::CallArgs,
                                         argc: u32|
 -> Option<String> {
    let mut parts = Vec::new();
    for i in 0..argc {
        parts.push(posix_arg(cx, *args.get(i).ptr)?);
    }
    // node keeps process.cwd() VERBATIM as the posix-resolve base (on a
    // Windows host: cwd 'C:\Users\x' + resolve('a') === 'C:\Users\x/a' —
    // mixed separators, node-faithful). No separator rewriting.
    let cwd = ::std::env::current_dir().ok()?.to_string_lossy().into_owned();
    Some(posix_core::resolve(&parts, &cwd))
});
posix_str_fn!(js_posix_dirname, "dirname", |cx: *mut JSContext,
                                         args: &::mozjs::jsapi::CallArgs,
                                         _argc: u32|
 -> Option<String> {
    Some(posix_core::dirname(&posix_arg(cx, *args.get(0).ptr)?))
});
posix_str_fn!(js_posix_basename, "basename", |cx: *mut JSContext,
                                           args: &::mozjs::jsapi::CallArgs,
                                           argc: u32|
 -> Option<String> {
    let p = posix_arg(cx, *args.get(0).ptr)?;
    // node: an explicit `undefined` suffix is valid (no strip); anything
    // else non-string is invalid.
    let ext = if argc > 1 && !(*args.get(1).ptr).is_undefined() {
        Some(posix_arg(cx, *args.get(1).ptr)?)
    } else {
        None
    };
    Some(posix_core::basename(&p, ext.as_deref()))
});
posix_str_fn!(js_posix_extname, "extname", |cx: *mut JSContext,
                                         args: &::mozjs::jsapi::CallArgs,
                                         _argc: u32|
 -> Option<String> {
    Some(posix_core::extname(&posix_arg(cx, *args.get(0).ptr)?))
});
posix_str_fn!(js_posix_relative, "relative", |cx: *mut JSContext,
                                           args: &::mozjs::jsapi::CallArgs,
                                           _argc: u32|
 -> Option<String> {
    let from = posix_arg(cx, *args.get(0).ptr)?;
    let to = posix_arg(cx, *args.get(1).ptr)?;
    Some(posix_core::relative(&from, &to))
});
posix_str_fn!(js_posix_format, "format", |cx: *mut JSContext,
                                       args: &::mozjs::jsapi::CallArgs,
                                       _argc: u32|
 -> Option<String> {
    // Accepts the parsed-shape object {root, dir, base, ext, name} (node
    // format: dir || root, base || name + formatExt(ext)).
    let parsed = read_path_object(cx, args)?;
    Some(posix_core::format(&parsed))
});

/// Read the `{root, dir, base, ext, name}` pathObject shape shared by
/// path.format on both faces. Absent properties coerce to "" (node treats
/// them as falsy).
unsafe fn read_path_object(
    cx: *mut JSContext,
    args: &::mozjs::jsapi::CallArgs,
) -> Option<node_alg::Parsed> {
    let obj = (*args.get(0).ptr).to_object();
    let wrapped_cx = ::mozjs::context::JSContext::from_ptr(::std::ptr::NonNull::new_unchecked(cx));
    rooted!(&in(wrapped_cx) let obj_root = obj);
    let mut root = String::new();
    let mut dir = String::new();
    let mut base = String::new();
    let mut ext = String::new();
    let mut name = String::new();
    if let Some(v) = get_string_prop(cx, obj_root.handle().into(), "root") {
        root = v;
    }
    if let Some(v) = get_string_prop(cx, obj_root.handle().into(), "dir") {
        dir = v;
    }
    if let Some(v) = get_string_prop(cx, obj_root.handle().into(), "base") {
        base = v;
    }
    if let Some(v) = get_string_prop(cx, obj_root.handle().into(), "ext") {
        ext = v;
    }
    if let Some(v) = get_string_prop(cx, obj_root.handle().into(), "name") {
        name = v;
    }
    Some(node_alg::Parsed {
        root,
        dir,
        base,
        ext,
        name,
    })
}

posix_str_fn!(js_win32_join, "join", |cx: *mut JSContext,
                                    args: &::mozjs::jsapi::CallArgs,
                                    argc: u32|
 -> Option<String> {
    let mut parts = Vec::new();
    for i in 0..argc {
        parts.push(posix_arg(cx, *args.get(i).ptr)?);
    }
    Some(win32_core::join(&parts))
});
posix_str_fn!(js_win32_normalize, "normalize", |cx: *mut JSContext,
                                             args: &::mozjs::jsapi::CallArgs,
                                             _argc: u32|
 -> Option<String> {
    Some(win32_core::normalize(&posix_arg(cx, *args.get(0).ptr)?))
});
posix_str_fn!(js_win32_dirname, "dirname", |cx: *mut JSContext,
                                         args: &::mozjs::jsapi::CallArgs,
                                         _argc: u32|
 -> Option<String> {
    Some(win32_core::dirname(&posix_arg(cx, *args.get(0).ptr)?))
});
posix_str_fn!(js_win32_basename, "basename", |cx: *mut JSContext,
                                           args: &::mozjs::jsapi::CallArgs,
                                           argc: u32|
 -> Option<String> {
    let p = posix_arg(cx, *args.get(0).ptr)?;
    // node: an explicit `undefined` suffix is valid (no strip); anything
    // else non-string is invalid.
    let ext = if argc > 1 && !(*args.get(1).ptr).is_undefined() {
        Some(posix_arg(cx, *args.get(1).ptr)?)
    } else {
        None
    };
    Some(win32_core::basename(&p, ext.as_deref()))
});
posix_str_fn!(js_win32_extname, "extname", |cx: *mut JSContext,
                                         args: &::mozjs::jsapi::CallArgs,
                                         _argc: u32|
 -> Option<String> {
    Some(win32_core::extname(&posix_arg(cx, *args.get(0).ptr)?))
});
posix_str_fn!(js_win32_format, "format", |cx: *mut JSContext,
                                       args: &::mozjs::jsapi::CallArgs,
                                       _argc: u32|
 -> Option<String> {
    let parsed = read_path_object(cx, args)?;
    Some(win32_core::format(&parsed))
});

// The win32 face's cwd-dependent members run the SAME win32 cores the
// Windows-host face runs — unconditionally (node's win32 module object is
// the genuine Windows algorithm on every platform, so `path.win32.resolve(
// 'C:\\a\\b', 'c') === 'C:\\a\\b\\c'` on Linux too; the `=X:` per-drive cwd
// lookup just misses on posix hosts and falls through to the process cwd).
posix_str_fn!(js_win32_resolve, "resolve", |cx: *mut JSContext,
                                            args: &::mozjs::jsapi::CallArgs,
                                            argc: u32|
 -> Option<String> {
    let mut parts = Vec::new();
    for i in 0..argc {
        parts.push(posix_arg(cx, *args.get(i).ptr)?);
    }
    let refs: Vec<&str> = parts.iter().map(|s| s.as_str()).collect();
    Some(node_alg::resolve_win32(
        &refs,
        &host_cwd_string(),
        &win32_drive_env,
    ))
});
posix_str_fn!(js_win32_relative, "relative", |cx: *mut JSContext,
                                              args: &::mozjs::jsapi::CallArgs,
                                              _argc: u32|
 -> Option<String> {
    let from = posix_arg(cx, *args.get(0).ptr)?;
    let to = posix_arg(cx, *args.get(1).ptr)?;
    Some(node_alg::relative_win32(
        &from,
        &to,
        &host_cwd_string(),
        &win32_drive_env,
    ))
});

/// path.win32.toNamespacedPath — the win32 core on every host. An absent or
/// non-coercible argument answers `undefined` (same arg contract as the host
/// face's toNamespacedPath; node returns the input verbatim for non-strings).
#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn js_win32_to_namespaced(
    cx: *mut JSContext,
    argc: u32,
    vp: *mut JSVal,
) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    if argc == 0 {
        args.rval().set(UndefinedValue());
        return true;
    }
    let s = match arg_to_string(cx, *args.get(0).ptr) {
        Some(s) => s,
        None => {
            args.rval().set(UndefinedValue());
            return true;
        }
    };
    let result = node_alg::to_namespaced_win32(&s, &host_cwd_string(), &win32_drive_env);
    return_string(cx, &args, &result)
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn win32_is_absolute(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = ::mozjs::jsapi::CallArgs::from_vp(vp, argc);
    if argc == 0 {
        args.rval().set(::mozjs::jsval::BooleanValue(false));
        return true;
    }
    match posix_arg(cx, *args.get(0).ptr) {
        Some(s) => args
            .rval()
            .set(::mozjs::jsval::BooleanValue(win32_core::is_absolute(&s))),
        None => args.rval().set(::mozjs::jsval::BooleanValue(false)),
    }
    true
}

/// Shared `path.parse` core: identical arg handling + result object shape;
/// the win32/posix faces differ only in the algorithm core consulted
/// (REQ-ARCH-1 duplicate convergence).
#[allow(unsafe_op_in_unsafe_fn)]
unsafe fn path_parse_impl(
    cx: *mut JSContext,
    argc: u32,
    vp: *mut JSVal,
    parse: fn(&str) -> (String, String, String, String, String),
) -> bool {
    let args = ::mozjs::jsapi::CallArgs::from_vp(vp, argc);
    if argc == 0 {
        ::mozjs::jsapi::JS_ReportErrorUTF8(
            cx,
            ::std::ffi::CStr::from_bytes_with_nul(b"path.parse requires a path\0")
                .unwrap()
                .as_ptr(),
        );
        return false;
    }
    let Some(p) = posix_arg(cx, *args.get(0).ptr) else {
        args.rval().set(::mozjs::jsval::UndefinedValue());
        return true;
    };
    let (root, dir, base, ext, name) = parse(&p);
    let raw_cx = cx;
    let mut wrapped = ::mozjs::context::JSContext::from_ptr(
        ::std::ptr::NonNull::new_unchecked(raw_cx),
    );
    let cx_ref = &mut wrapped;
    ::mozjs::rooted!(&in(cx_ref) let obj = ::mozjs::rust::wrappers2::JS_NewPlainObject(cx_ref));
    if obj.get().is_null() {
        args.rval().set(::mozjs::jsval::UndefinedValue());
        return true;
    }
    let h = obj.handle().into();
    macro_rules! def_str {
        ($name:literal, $val:expr) => {{
            let cs = ZBox::from_bytes($val.as_bytes());
            let js = JS_NewStringCopyZ(raw_cx, cs.as_ptr());
            if !js.is_null() {
                ::mozjs::rooted!(&in(cx_ref) let sv = ::mozjs::jsval::StringValue(&*js));
                ::mozjs::jsapi::JS_DefineProperty(
                    raw_cx,
                    h,
                    ::std::ffi::CStr::from_bytes_with_nul(::std::concat!($name, "\0").as_bytes())
                        .unwrap()
                        .as_ptr(),
                    sv.handle().into(),
                    JSPROP_ENUMERATE as u32,
                );
            }
        }};
    }
    def_str!("root", root);
    def_str!("dir", dir);
    def_str!("base", base);
    def_str!("ext", ext);
    def_str!("name", name);
    args.rval().set(::mozjs::jsval::ObjectValue(obj.get()));
    true
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn win32_parse_fn(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    path_parse_impl(cx, argc, vp, win32_core::parse)
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn posix_is_absolute(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = ::mozjs::jsapi::CallArgs::from_vp(vp, argc);
    if argc == 0 {
        args.rval().set(::mozjs::jsval::BooleanValue(false));
        return true;
    }
    match posix_arg(cx, *args.get(0).ptr) {
        Some(s) => args.rval().set(::mozjs::jsval::BooleanValue(posix_core::is_absolute(&s))),
        None => args.rval().set(::mozjs::jsval::BooleanValue(false)),
    }
    true
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn posix_parse_fn(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    path_parse_impl(cx, argc, vp, posix_core::parse)
}

pub fn install(cx: &mut mozjs::context::JSContext) {
    rooted!(&in(cx) let path_obj = unsafe { w2::JS_NewPlainObject(cx) });
    if path_obj.get().is_null() {
        return;
    }

    unsafe {
        w2::JS_DefineFunction(
            cx,
            path_obj.handle(),
            c"join".as_ptr(),
            Some(path_join),
            1,
            JSPROP_ENUMERATE as u32,
        );
        w2::JS_DefineFunction(
            cx,
            path_obj.handle(),
            c"resolve".as_ptr(),
            Some(path_resolve),
            0,
            JSPROP_ENUMERATE as u32,
        );
        w2::JS_DefineFunction(
            cx,
            path_obj.handle(),
            c"dirname".as_ptr(),
            Some(path_dirname),
            1,
            JSPROP_ENUMERATE as u32,
        );
        w2::JS_DefineFunction(
            cx,
            path_obj.handle(),
            c"basename".as_ptr(),
            Some(path_basename),
            1,
            JSPROP_ENUMERATE as u32,
        );
        w2::JS_DefineFunction(
            cx,
            path_obj.handle(),
            c"extname".as_ptr(),
            Some(path_extname),
            1,
            JSPROP_ENUMERATE as u32,
        );
        w2::JS_DefineFunction(
            cx,
            path_obj.handle(),
            c"normalize".as_ptr(),
            Some(path_normalize),
            1,
            JSPROP_ENUMERATE as u32,
        );
        w2::JS_DefineFunction(
            cx,
            path_obj.handle(),
            c"isAbsolute".as_ptr(),
            Some(path_is_absolute),
            1,
            JSPROP_ENUMERATE as u32,
        );
        w2::JS_DefineFunction(
            cx,
            path_obj.handle(),
            c"relative".as_ptr(),
            Some(path_relative),
            2,
            JSPROP_ENUMERATE as u32,
        );
        w2::JS_DefineFunction(
            cx,
            path_obj.handle(),
            c"parse".as_ptr(),
            Some(path_parse),
            1,
            JSPROP_ENUMERATE as u32,
        );
        w2::JS_DefineFunction(
            cx,
            path_obj.handle(),
            c"format".as_ptr(),
            Some(path_format),
            1,
            JSPROP_ENUMERATE as u32,
        );
        w2::JS_DefineFunction(
            cx,
            path_obj.handle(),
            c"toNamespacedPath".as_ptr(),
            Some(path_to_namespaced),
            1,
            JSPROP_ENUMERATE as u32,
        );

        let sep_cstr = ZBox::from_bytes(if MAIN_SEPARATOR == '/' { "/" } else { "\\" }.as_bytes());
        let sep_str = JS_NewStringCopyZ(cx.raw_cx(), sep_cstr.as_ptr());
        if !sep_str.is_null() {
            let sep_val = mozjs::jsval::StringValue(&*sep_str);
            rooted!(&in(cx) let sep_root = sep_val);
            JS_DefineProperty(
                cx.raw_cx(),
                path_obj.handle().into(),
                c"sep".as_ptr(),
                sep_root.handle().into(),
                JSPROP_ENUMERATE as u32,
            );
        }

        // path.platform — mirrors process.platform / os.platform() so code
        // branching on `path.platform === "win32"` behaves like Node's
        // platform-tagged path modules. Audit item: was entirely missing
        // (typeof path.platform === 'undefined').
        let platform_bytes: &[u8] = if cfg!(target_os = "linux") {
            b"linux"
        } else if cfg!(target_os = "macos") {
            b"darwin"
        } else if cfg!(target_os = "windows") {
            b"win32"
        } else {
            b"unknown"
        };
        let platform_cstr = ZBox::from_bytes(platform_bytes);
        let platform_str = JS_NewStringCopyZ(cx.raw_cx(), platform_cstr.as_ptr());
        if !platform_str.is_null() {
            let platform_val = mozjs::jsval::StringValue(&*platform_str);
            rooted!(&in(cx) let platform_root = platform_val);
            JS_DefineProperty(
                cx.raw_cx(),
                path_obj.handle().into(),
                c"platform".as_ptr(),
                platform_root.handle().into(),
                JSPROP_ENUMERATE as u32,
            );
        }

        let delim_cstr = ZBox::from_bytes(if cfg!(windows) { b";" } else { b":" });
        let delim_str = JS_NewStringCopyZ(cx.raw_cx(), delim_cstr.as_ptr());
        if !delim_str.is_null() {
            let delim_val = mozjs::jsval::StringValue(&*delim_str);
            rooted!(&in(cx) let delim_root = delim_val);
            JS_DefineProperty(
                cx.raw_cx(),
                path_obj.handle().into(),
                c"delimiter".as_ptr(),
                delim_root.handle().into(),
                JSPROP_ENUMERATE as u32,
            );
        }
    }

    // path.posix — node ships a genuine posix face on every platform, and on
    // posix hosts the platform face IS the posix face (`path === path.posix`:
    // module.exports is the posix module object, which also carries the win32
    // face). The host face above now runs the same `windows=false` node_alg
    // cores as `posix_core`, so on posix platforms `path.posix` is defined as
    // a SELF-REFERENCE on the host object (identity, not a copy) and no
    // separate module object is built. On windows the host face runs the
    // win32 cores, so the pure posix face is a separate object there.
    unsafe {
        if cfg!(windows) {
            rooted!(&in(cx) let posix_obj = w2::JS_NewPlainObject(cx));
            if !posix_obj.get().is_null() {
                let fns: &[(&str, ::std::option::Option<
                    unsafe extern "C" fn(*mut JSContext, u32, *mut JSVal) -> bool,
                >)] = &[
                    ("join", Some(js_posix_join)),
                    ("normalize", Some(js_posix_normalize)),
                    ("resolve", Some(js_posix_resolve)),
                    ("dirname", Some(js_posix_dirname)),
                    ("basename", Some(js_posix_basename)),
                    ("extname", Some(js_posix_extname)),
                    ("isAbsolute", Some(posix_is_absolute)),
                    ("relative", Some(js_posix_relative)),
                    ("parse", Some(posix_parse_fn)),
                    ("format", Some(js_posix_format)),
                ];
                for (name, fp) in fns {
                    let c_name = ZBox::from_bytes(name.as_bytes());
                    let f = ::mozjs::jsapi::JS_NewFunction(
                        cx.raw_cx(),
                        *fp,
                        2,
                        0,
                        c_name.as_ptr(),
                    );
                    if !f.is_null() {
                        let fobj = ::mozjs::jsapi::JS_GetFunctionObject(f);
                        ::mozjs::rooted!(&in(cx) let fv = ::mozjs::jsval::ObjectValue(fobj));
                        ::mozjs::jsapi::JS_DefineProperty(
                            cx.raw_cx(),
                            posix_obj.handle().into(),
                            c_name.as_ptr(),
                            fv.handle().into(),
                            JSPROP_ENUMERATE as u32,
                        );
                    }
                }
                // posix.sep = "/" / posix.delimiter = ":"
                let sep_cstr = ZBox::from_bytes(b"/");
                let sep_str = JS_NewStringCopyZ(cx.raw_cx(), sep_cstr.as_ptr());
                if !sep_str.is_null() {
                    let v = ::mozjs::jsval::StringValue(&*sep_str);
                    ::mozjs::rooted!(&in(cx) let vr = v);
                    JS_DefineProperty(
                        cx.raw_cx(),
                        posix_obj.handle().into(),
                        c"sep".as_ptr(),
                        vr.handle().into(),
                        JSPROP_ENUMERATE as u32,
                    );
                }
                let dlm_cstr = ZBox::from_bytes(b":");
                let dlm_str = JS_NewStringCopyZ(cx.raw_cx(), dlm_cstr.as_ptr());
                if !dlm_str.is_null() {
                    let v = ::mozjs::jsval::StringValue(&*dlm_str);
                    ::mozjs::rooted!(&in(cx) let vr = v);
                    JS_DefineProperty(
                        cx.raw_cx(),
                        posix_obj.handle().into(),
                        c"delimiter".as_ptr(),
                        vr.handle().into(),
                        JSPROP_ENUMERATE as u32,
                    );
                }
                // posix.posix self-ref (node shape)
                w2::JS_DefineProperty3(
                    cx,
                    posix_obj.handle(),
                    c"posix".as_ptr(),
                    posix_obj.handle(),
                    JSPROP_ENUMERATE as u32,
                );
                // Attach the real posix face to the module:
                w2::JS_DefineProperty3(
                    cx,
                    path_obj.handle(),
                    c"posix".as_ptr(),
                    posix_obj.handle(),
                    JSPROP_ENUMERATE as u32,
                );
            }
        } else {
            // Posix host: `path === path.posix` by reference (node shape) —
            // the win32 face below re-reads this property for its own
            // `win32.posix` alias.
            w2::JS_DefineProperty3(
                cx,
                path_obj.handle(),
                c"posix".as_ptr(),
                path_obj.handle(),
                JSPROP_ENUMERATE as u32,
            );
        }
    }

    // path.win32 — Node.js ships a real Windows-flavoured path object on all
    // platforms: `path.win32.sep === "\\"`, `path.win32.normalize('a/b') ===
    // 'a\\b'`, `path.win32.basename('C:\\dir\\f') === 'f'`,
    // `path.win32.resolve('C:\\a\\b', 'c') === 'C:\\a\\b\\c'` — on Linux too.
    // Every member therefore gets genuine win32 cores (win32_core / node_alg,
    // ported from node lib/path.js), including the cwd-dependent
    // `resolve` / `relative` / `toNamespacedPath` — no host-face forwarding.
    // (See ~/code/rust/bun/src/runtime/node/path.zig — Bun likewise ships a
    // real win32 face on every platform.)
    unsafe {
        rooted!(&in(cx) let win32_obj = w2::JS_NewPlainObject(cx));
        if !win32_obj.get().is_null() {
            let win_fns: &[(&str, ::std::option::Option<
                unsafe extern "C" fn(*mut JSContext, u32, *mut JSVal) -> bool,
            >)] = &[
                ("join", Some(js_win32_join)),
                ("normalize", Some(js_win32_normalize)),
                ("dirname", Some(js_win32_dirname)),
                ("basename", Some(js_win32_basename)),
                ("extname", Some(js_win32_extname)),
                ("isAbsolute", Some(win32_is_absolute)),
                ("parse", Some(win32_parse_fn)),
                ("format", Some(js_win32_format)),
                ("resolve", Some(js_win32_resolve)),
                ("relative", Some(js_win32_relative)),
                ("toNamespacedPath", Some(js_win32_to_namespaced)),
            ];
            for (name, fp) in win_fns {
                let c_name = ZBox::from_bytes(name.as_bytes());
                let f = ::mozjs::jsapi::JS_NewFunction(
                    cx.raw_cx(),
                    *fp,
                    2,
                    0,
                    c_name.as_ptr(),
                );
                if !f.is_null() {
                    let fobj = ::mozjs::jsapi::JS_GetFunctionObject(f);
                    ::mozjs::rooted!(&in(cx) let fv = ::mozjs::jsval::ObjectValue(fobj));
                    ::mozjs::jsapi::JS_DefineProperty(
                        cx.raw_cx(),
                        win32_obj.handle().into(),
                        c_name.as_ptr(),
                        fv.handle().into(),
                        JSPROP_ENUMERATE as u32,
                    );
                }
            }
            // win32.sep = "\\" / win32.delimiter = ";"
            let winsep_cstr = ZBox::from_bytes(b"\\");
            let winsep_str = JS_NewStringCopyZ(cx.raw_cx(), winsep_cstr.as_ptr());
            if !winsep_str.is_null() {
                let v = mozjs::jsval::StringValue(&*winsep_str);
                rooted!(&in(cx) let vr = v);
                JS_DefineProperty(
                    cx.raw_cx(),
                    win32_obj.handle().into(),
                    c"sep".as_ptr(),
                    vr.handle().into(),
                    JSPROP_ENUMERATE as u32,
                );
            }
            let wdlm_cstr = ZBox::from_bytes(b";");
            let wdlm_str = JS_NewStringCopyZ(cx.raw_cx(), wdlm_cstr.as_ptr());
            if !wdlm_str.is_null() {
                let v = mozjs::jsval::StringValue(&*wdlm_str);
                rooted!(&in(cx) let vr = v);
                JS_DefineProperty(
                    cx.raw_cx(),
                    win32_obj.handle().into(),
                    c"delimiter".as_ptr(),
                    vr.handle().into(),
                    JSPROP_ENUMERATE as u32,
                );
            }
            // win32.win32 self-ref + win32.posix alias (matches Node.js
            // shape: `path.win32.posix === path.posix` — the posix face,
            // which on posix hosts is the host object itself).
            w2::JS_DefineProperty3(
                cx,
                win32_obj.handle(),
                c"win32".as_ptr(),
                win32_obj.handle(),
                JSPROP_ENUMERATE as u32,
            );
            let mut posix_face_val = UndefinedValue();
            JS_GetProperty(
                cx.raw_cx(),
                path_obj.handle().into(),
                c"posix".as_ptr(),
                MutableHandle::<Value> {
                    _phantom_0: ::std::marker::PhantomData,
                    ptr: &mut posix_face_val,
                },
            );
            if posix_face_val.is_object() {
                rooted!(&in(cx) let pfv = posix_face_val);
                let pv = ::mozjs::jsval::ObjectValue(pfv.get().to_object());
                rooted!(&in(cx) let pvr = pv);
                JS_DefineProperty(
                    cx.raw_cx(),
                    win32_obj.handle().into(),
                    c"posix".as_ptr(),
                    pvr.handle().into(),
                    JSPROP_ENUMERATE as u32,
                );
            }

            w2::JS_DefineProperty3(
                cx,
                path_obj.handle(),
                c"win32".as_ptr(),
                win32_obj.handle(),
                JSPROP_ENUMERATE as u32,
            );
        }
    }

    // path.matchesGlob(path, pattern) — pure JS glob matcher. Bun's
    // implementation (~/code/rust/bun/src/js/node/path.ts:matchesGlob) uses
    // `Bun.Glob` (native); here we express the same boolean result with a
    // minimal regex-based glob translator covering the standard wildcard
    // syntax (`*`, `?`, `**`, character classes) so behaviour matches Node.
    unsafe {
        let matches_src = r#"(function(p){
  function globToRegExp(pattern) {
    // Anchor the pattern; translate `**` → `.*`, `*` → `.*`, `?` → `.`,
    // and escape regex metacharacters in literals. Mirrors Bun.Glob's
    // full-path glob semantics (a single `*` matches across path segments),
    // which is what Node.js' path.matchesGlob surfaces.
    var s = '^';
    for (var i = 0; i < pattern.length; i++) {
      var c = pattern.charAt(i);
      if (c === '*') {
        if (pattern.charAt(i + 1) === '*') {
          s += '.*';
          i++;
        } else {
          s += '.*';
        }
      } else if (c === '?') {
        s += '.';
      } else if ('.+^${}()|[]\\'.indexOf(c) >= 0) {
        s += '\\' + c;
      } else {
        s += c;
      }
    }
    return new RegExp(s + '$');
  }
  p.matchesGlob = function matchesGlob(path, pattern) {
    if (typeof path !== 'string') {
      throw new TypeError('The "path" argument must be of type string.');
    }
    if (typeof pattern !== 'string') {
      throw new TypeError('The "pattern" argument must be of type string.');
    }
    return globToRegExp(pattern).test(path);
  };
})"#;
        let mut msrc = mozjs::rust::transform_str_to_source_text(matches_src);
        let mut mval = UndefinedValue();
        let mh = MutableHandle::<Value> {
            _phantom_0: ::std::marker::PhantomData,
            ptr: &mut mval,
        };
        let mopts = mozjs::glue::NewCompileOptions(cx.raw_cx(), c"<path-matchesGlob>".as_ptr(), 1);
        if !mopts.is_null() {
            let global = CurrentGlobalOrNull(cx.raw_cx());
            if !global.is_null()
                && JS::Evaluate2(cx.raw_cx(), mopts, &mut msrc, mh)
                && mval.is_object()
            {
                let wrapped_cx =
                    mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx.raw_cx()));
                rooted!(&in(wrapped_cx) let global_root = global);
                rooted!(&in(wrapped_cx) let path_val_root = ObjectValue(path_obj.get()));
                let args_arr = HandleValueArray {
                    length_: 1,
                    elements_: &path_val_root.get() as *const Value,
                };
                let mut call_rval = UndefinedValue();
                let call_rval_h = MutableHandle::<Value> {
                    _phantom_0: ::std::marker::PhantomData,
                    ptr: &mut call_rval,
                };
                rooted!(&in(wrapped_cx) let factory_obj = mval.to_object());
                rooted!(&in(wrapped_cx) let factory_obj_h = ObjectValue(factory_obj.get()));
                JS_CallFunctionValue(
                    cx.raw_cx(),
                    global_root.handle().into(),
                    factory_obj_h.handle().into(),
                    &args_arr,
                    call_rval_h,
                );
            }
            mozjs::glue::DeleteCompileOptions(mopts);
        }
    }

    cache_builtin(cx, "path", path_obj.get());
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe fn arg_to_string(
    cx: *mut JSContext,
    val: JSVal,
) -> ::std::option::Option<::std::string::String> {
    if val.is_undefined() || val.is_null() {
        return ::std::option::Option::None;
    }
    let mut wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    rooted!(&in(wrapped_cx) let val_root = val);
    let s = mozjs::rust::ToString(&mut wrapped_cx, val_root.handle().into());
    if s.is_null() {
        return ::std::option::Option::None;
    }
    let rust_str = crate::jsstr_to_rust_string(cx, s);
    ::std::option::Option::Some(rust_str)
}

// ── Host/platform face ────────────────────────────────────────────────────
// Every pure-string native below is the SAME `node_alg` core the posix/win32
// faces use, with `windows = cfg!(windows)` — node builds the platform face
// out of one of the two shipped algorithms (`path === path.posix` on posix
// hosts), so the host face must not carry a third (std::path-flavoured)
// behavior. The B-class divergences this removes: `normalize('bar/foo../../')`
// answered 'bar' instead of 'bar/' (surviving trailing separator dropped),
// `join('a','..','..')` answered '../..' instead of '..' (leading '..' above a
// relative root mishandled), `format({name,ext})` dropped formatExt's dot, and
// `parse` answered std::path shapes for dot-leading basenames.
//
// The cwd-bound natives (resolve / relative / toNamespacedPath) run the
// matching node cores per host: `resolve_win32` / `relative_win32` /
// `to_namespaced_win32` on Windows hosts (drive-qualified absolute output —
// the prior std::path legs re-rooted to '/' and dropped the drive, answering
// `resolve('') === '/Users\putao\...'` instead of `C:\Users\putao\...`), and
// `posix_core::resolve` / `relative` on posix hosts.

/// The cwd as a forward-slash string for the platform face's cwd-bound
/// natives (resolve / relative / toNamespacedPath), falling back to ".".
fn host_cwd_string() -> String {
    let mut buf = bun_paths::path_buffer_pool::get();
    match bun_core::getcwd(&mut buf) {
        Ok(z) => String::from_utf8_lossy(z.as_bytes()).into_owned(),
        Err(_) => ".".to_string(),
    }
}

/// node's per-drive cwd lookup for the win32 resolve/relative cores —
/// `process.env[`=${device}`]` (Windows keeps a per-drive cwd in its
/// environment block as the `=C:` pseudo-entry). A miss (or a non-drive
/// shaped value) answers `None`, which node treats exactly the same way:
/// the process cwd is used and the drive-root default applies when it
/// points at another device. Not host-gated: on posix hosts the `=X:`
/// entries simply do not exist, so the lookup misses and falls through to
/// the process cwd — the same control flow node's win32 face takes there.
fn win32_drive_env(device: &str) -> Option<String> {
    let val = ::std::env::var_os(format!("={}", device))?;
    let s = val.to_string_lossy().into_owned();
    // Only a drive-shaped cwd ('X:\...') is a usable per-drive cwd.
    let b = s.as_bytes();
    if b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':' {
        Some(s)
    } else {
        None
    }
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn path_join(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let mut parts: Vec<::std::string::String> = Vec::new();
    for val in ::std::slice::from_raw_parts(args.argv_, argc as usize) {
        match arg_to_string(cx, *val) {
            Some(s) => parts.push(s),
            None => {
                JS_ReportErrorUTF8(cx, c"The \"path\" argument must be of type string".as_ptr());
                return false;
            }
        }
    }
    let refs: Vec<&str> = parts.iter().map(|s| s.as_str()).collect();
    let joined = node_alg::join(&refs, cfg!(windows));
    return_string(cx, &args, &joined)
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn path_resolve(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    let mut parts: Vec<::std::string::String> = Vec::new();
    for val in ::std::slice::from_raw_parts(args.argv_, argc as usize) {
        match arg_to_string(cx, *val) {
            Some(s) => parts.push(s),
            None => {
                JS_ReportErrorUTF8(cx, c"The \"path\" argument must be of type string".as_ptr());
                return false;
            }
        }
    }
    #[cfg(windows)]
    {
        // Windows host face: node's win32 resolve — device/UNC-aware, and
        // cwd-qualified with the DRIVE LETTER RETAINED (resolve('') ===
        // process.cwd() === 'C:\...'). The previous std::path leg answered
        // posix-flavored output (`normalize_path` re-roots to '/' and drops
        // the device): `resolve('')` → '/Users\putao\...' on a real Windows
        // host (B-class, node oracle: 'C:\Users\putao\...').
        let refs: Vec<&str> = parts.iter().map(|s| s.as_str()).collect();
        let cwd = host_cwd_string();
        let result = node_alg::resolve_win32(&refs, &cwd, &win32_drive_env);
        return return_string(cx, &args, &result);
    }
    // Posix host: the exact `path.posix.resolve` core (right-most absolute
    // segment wins, `..` clamps at the root).
    #[cfg(not(windows))]
    {
        let cwd = host_cwd_string();
        let result = posix_core::resolve(&parts, &cwd);
        return_string(cx, &args, &result)
    }
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn path_dirname(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    if argc == 0 {
        JS_ReportErrorUTF8(cx, c"The \"path\" argument must be of type string".as_ptr());
        return false;
    }
    let val = *args.get(0).ptr;
    let s = match arg_to_string(cx, val) {
        Some(s) => s,
        None => {
            JS_ReportErrorUTF8(cx, c"The \"path\" argument must be of type string".as_ptr());
            return false;
        }
    };
    let result = node_alg::dirname(&s, cfg!(windows));
    return_string(cx, &args, &result)
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn path_basename(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    if argc == 0 {
        JS_ReportErrorUTF8(cx, c"The \"path\" argument must be of type string".as_ptr());
        return false;
    }
    let val = *args.get(0).ptr;
    let s = match arg_to_string(cx, val) {
        Some(s) => s,
        None => {
            JS_ReportErrorUTF8(cx, c"The \"path\" argument must be of type string".as_ptr());
            return false;
        }
    };
    // node: an explicit `undefined` suffix is valid (no strip); anything
    // else non-string is invalid.
    let ext = if argc >= 2 && !(*args.get(1).ptr).is_undefined() {
        match arg_to_string(cx, *args.get(1).ptr) {
            Some(e) => Some(e),
            None => {
                JS_ReportErrorUTF8(cx, c"The \"path\" argument must be of type string".as_ptr());
                return false;
            }
        }
    } else {
        None
    };
    let base = node_alg::basename(&s, ext.as_deref(), cfg!(windows));
    return_string(cx, &args, &base)
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn path_extname(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    if argc == 0 {
        JS_ReportErrorUTF8(cx, c"The \"path\" argument must be of type string".as_ptr());
        return false;
    }
    let val = *args.get(0).ptr;
    let s = match arg_to_string(cx, val) {
        Some(s) => s,
        None => {
            JS_ReportErrorUTF8(cx, c"The \"path\" argument must be of type string".as_ptr());
            return false;
        }
    };
    let ext = node_alg::extname(&s, cfg!(windows));
    return_string(cx, &args, &ext)
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn path_normalize(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    if argc == 0 {
        JS_ReportErrorUTF8(cx, c"The \"path\" argument must be of type string".as_ptr());
        return false;
    }
    let val = *args.get(0).ptr;
    let s = match arg_to_string(cx, val) {
        Some(s) => s,
        None => {
            JS_ReportErrorUTF8(cx, c"The \"path\" argument must be of type string".as_ptr());
            return false;
        }
    };
    let normalized = node_alg::normalize(&s, cfg!(windows));
    return_string(cx, &args, &normalized)
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn path_is_absolute(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    if argc == 0 {
        args.rval().set(mozjs::jsval::BooleanValue(false));
        return true;
    }
    let val = *args.get(0).ptr;
    let s = match arg_to_string(cx, val) {
        Some(s) => s,
        None => {
            args.rval().set(mozjs::jsval::BooleanValue(false));
            return true;
        }
    };
    let absolute = node_alg::is_absolute(&s, cfg!(windows));
    args.rval().set(mozjs::jsval::BooleanValue(absolute));
    true
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn path_relative(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    if argc < 2 {
        JS_ReportErrorUTF8(
            cx,
            c"The \"from\" and \"to\" arguments must be of type string".as_ptr(),
        );
        return false;
    }
    let from_val = *args.get(0).ptr;
    let to_val = *args.get(1).ptr;
    let from_str = match arg_to_string(cx, from_val) {
        Some(s) => s,
        None => return return_string(cx, &args, ""),
    };
    let to_str = match arg_to_string(cx, to_val) {
        Some(s) => s,
        None => return return_string(cx, &args, ""),
    };

    #[cfg(windows)]
    {
        // Windows host face: node's win32 relative — both sides resolved
        // through the win32 resolve (device-qualified) first, then the
        // common prefix stripped case-insensitively. The previous leg ran
        // bun_paths' POSIX relative (same drive-prefix-loss class as
        // resolve).
        let cwd = host_cwd_string();
        let result = node_alg::relative_win32(&from_str, &to_str, &cwd, &win32_drive_env);
        return return_string(cx, &args, &result);
    }
    // Posix host: node resolves both args against the cwd first, then runs the
    // posix relative algorithm (the exact `path.posix.relative` core).
    #[cfg(not(windows))]
    {
        let cwd = host_cwd_string();
        let from_abs = posix_core::resolve(&[from_str], &cwd);
        let to_abs = posix_core::resolve(&[to_str], &cwd);
        let result = posix_core::relative(&from_abs, &to_abs);
        return_string(cx, &args, &result)
    }
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn path_parse(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    if argc == 0 {
        JS_ReportErrorUTF8(cx, c"The \"path\" argument must be of type string".as_ptr());
        return false;
    }
    let val = *args.get(0).ptr;
    let s = match arg_to_string(cx, val) {
        Some(s) => s,
        None => {
            JS_ReportErrorUTF8(cx, c"The \"path\" argument must be of type string".as_ptr());
            return false;
        }
    };

    let parsed_shape = node_alg::parse(&s, cfg!(windows));

    let parsed = JS_NewPlainObject(cx);
    if parsed.is_null() {
        args.rval().set(UndefinedValue());
        return true;
    }
    let wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
    rooted!(&in(wrapped_cx) let parsed_root = parsed);

    define_string_prop(cx, parsed_root.handle().into(), "root", &parsed_shape.root);
    define_string_prop(cx, parsed_root.handle().into(), "dir", &parsed_shape.dir);
    define_string_prop(cx, parsed_root.handle().into(), "base", &parsed_shape.base);
    define_string_prop(cx, parsed_root.handle().into(), "ext", &parsed_shape.ext);
    define_string_prop(cx, parsed_root.handle().into(), "name", &parsed_shape.name);

    args.rval().set(mozjs::jsval::ObjectValue(parsed));
    true
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn path_format(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    if argc == 0 {
        JS_ReportErrorUTF8(
            cx,
            c"The \"pathObject\" argument must be of type object".as_ptr(),
        );
        return false;
    }
    let val = *args.get(0).ptr;
    if !val.is_object() {
        JS_ReportErrorUTF8(
            cx,
            c"The \"pathObject\" argument must be of type object".as_ptr(),
        );
        return false;
    }
    // node format: dir || root, base || name + formatExt(ext) — the same
    // core both faces use (`formatExt` supplies a missing leading dot, so
    // format({name:'b',ext:'txt'}) === 'b.txt').
    let parsed = match read_path_object(cx, &args) {
        Some(p) => p,
        None => {
            args.rval().set(UndefinedValue());
            return true;
        }
    };
    let result = node_alg::format(&parsed, cfg!(windows));
    return_string(cx, &args, &result)
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe extern "C" fn path_to_namespaced(cx: *mut JSContext, argc: u32, vp: *mut JSVal) -> bool {
    let args = CallArgs::from_vp(vp, argc);
    if argc == 0 {
        args.rval().set(UndefinedValue());
        return true;
    }
    let val = *args.get(0).ptr;
    let s = match arg_to_string(cx, val) {
        Some(s) => s,
        None => {
            args.rval().set(UndefinedValue());
            return true;
        }
    };
    #[cfg(windows)]
    {
        // Windows host face: node's win32 toNamespacedPath — `\\?\`-prefix
        // the win32-resolved path (`\\?\UNC\...` for non-long UNC roots).
        // The previous leg answered the same drive-prefix-loss shape as the
        // old resolve (e.g. '/Users\putao\...' instead of 'C:\...\').
        let cwd = host_cwd_string();
        let result = node_alg::to_namespaced_win32(&s, &cwd, &win32_drive_env);
        return return_string(cx, &args, &result);
    }
    // node posix.toNamespacedPath returns the input verbatim (there are no
    // namespaces to prefix on posix).
    #[cfg(not(windows))]
    {
        return_string(cx, &args, &s)
    }
}

// --- Pure logic helpers ---
// @trace REQ-ENG-007 [api:path] — the cwd-dependent Windows-host legs
// (resolve / relative / toNamespacedPath on cfg!(windows)) run the node
// win32 cores in `node_alg` (`resolve_win32` / `relative_win32` /
// `to_namespaced_win32`); the posix legs run the node cores in `posix_core`.
// The `path.win32` FACE runs those same win32 cores on EVERY host
// (unconditional — the cores are pure string algorithms plus the `=X:`
// per-drive cwd lookup, which simply misses on posix hosts), and the
// `path.posix` FACE's resolve keeps the host cwd verbatim (no separator
// rewriting, so `cwd + '/' + arg` on a Windows host is node's mixed-separator
// shape).
// The former bun_paths-based helpers (`make_absolute` / `pathdiff` /
// `cwd_bytes`) are deleted: they were POSIX-leg ports consumed only by the
// Windows legs, which re-rooted output to '/' and dropped the drive prefix
// (`resolve('')` → '/Users\putao\...' on a real Windows host).
//
// The Node.js-specific `.`/`..` collapse for `normalize_path` stays in Rust
// here because Node's `path.posix.normalize` deliberately preserves leading
// `..` above the root (e.g. `/a/../../b` → `/../b`) while Zig std's
// `normalizeString` clamps at the root (`/b`). The bundler/resolver consume
// the Zig semantics; the Node compatibility layer keeps its own.
// `normalize_path` additionally serves bun_api's real-path resolution
// (REQ-ENG-007).

// NOTE: the old hand-rolled `posix_join` (B-class: `join('a','..','..')`
// answered '../..', trailing-separator preservation wrong) is deleted — the
// host join native delegates to `node_alg::join` like both faces do.

pub(crate) fn normalize_path(path: &::std::path::Path) -> PathBuf {
    let mut components = Vec::new();
    let has_root = path.is_absolute();
    for comp in path.components() {
        match comp {
            ::std::path::Component::CurDir => {}
            ::std::path::Component::ParentDir => {
                if let Some(last) = components.last()
                    && last != &".."
                {
                    components.pop();
                    continue;
                }
                components.push("..");
            }
            ::std::path::Component::Normal(s) => {
                components.push(s.to_string_lossy().into_owned().leak() as &'static str);
            }
            _ => {}
        }
    }
    let mut result = PathBuf::new();
    if has_root {
        result.push("/");
    }
    for seg in &components {
        result.push(*seg);
    }
    if result.as_os_str().is_empty() {
        PathBuf::from(".")
    } else {
        result
    }
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe fn define_string_prop(
    cx: *mut JSContext,
    obj: Handle<*mut JSObject>,
    name: &str,
    value: &str,
) {
    let c_name = ZBox::from_bytes(name.as_bytes());
    let c_val = ZBox::from_bytes(value.as_bytes());
    let js_str = JS_NewStringCopyZ(cx, c_val.as_ptr());
    if !js_str.is_null() {
        let val = mozjs::jsval::StringValue(&*js_str);
        let wrapped_cx = mozjs::context::JSContext::from_ptr(NonNull::new_unchecked(cx));
        rooted!(&in(wrapped_cx) let val_root = val);
        JS_DefineProperty(
            cx,
            obj,
            c_name.as_ptr(),
            val_root.handle().into(),
            JSPROP_ENUMERATE as u32,
        );
    }
}

#[allow(unsafe_op_in_unsafe_fn)]
unsafe fn get_string_prop(
    cx: *mut JSContext,
    obj: Handle<*mut JSObject>,
    name: &str,
) -> ::std::option::Option<::std::string::String> {
    let c_name = ZBox::from_bytes(name.as_bytes());
    let mut val = UndefinedValue();
    let handle = MutableHandle::<Value> {
        _phantom_0: ::std::marker::PhantomData,
        ptr: &mut val,
    };
    JS_GetProperty(cx, obj, c_name.as_ptr(), handle);
    arg_to_string(cx, val)
}

#[cfg(test)]
mod tests {
    use super::*;

    // --- normalize_path (Path-based) ---

    // POSIX-path-form assertions (leading-/ anchors): on windows the per-OS
    // path semantics are correct product behavior, these tests hold the posix form.
    #[cfg(unix)]
    #[test]
    fn test_normalize_path_dot_dot() {
        assert_eq!(
            normalize_path(::std::path::Path::new("/a/b/../c")),
            PathBuf::from("/a/c")
        );
    }

    // POSIX-path-form assertions (leading-/ anchors): on windows the per-OS
    // path semantics are correct product behavior, these tests hold the posix form.
    #[cfg(unix)]
    #[test]
    fn test_normalize_path_dot() {
        assert_eq!(
            normalize_path(::std::path::Path::new("/a/./b")),
            PathBuf::from("/a/b")
        );
    }

    // POSIX-path-form assertions (leading-/ anchors): on windows the per-OS
    // path semantics are correct product behavior, these tests hold the posix form.
    #[cfg(unix)]
    #[test]
    fn test_normalize_path_root() {
        assert_eq!(
            normalize_path(::std::path::Path::new("/")),
            PathBuf::from("/")
        );
    }

    #[test]
    fn test_normalize_path_relative() {
        assert_eq!(
            normalize_path(::std::path::Path::new("a/b/../c")),
            PathBuf::from("a/c")
        );
    }

    // POSIX-path-form assertions (leading-/ anchors): on windows the per-OS
    // path semantics are correct product behavior, these tests hold the posix form.
    #[cfg(unix)]
    #[test]
    fn test_normalize_path_double_dot_beyond_root() {
        // Implementation preserves .. beyond root as /../b
        assert_eq!(
            normalize_path(::std::path::Path::new("/a/../../b")),
            PathBuf::from("/../b")
        );
    }

    #[test]
    fn test_normalize_path_empty_relative() {
        assert_eq!(
            normalize_path(::std::path::Path::new(".")),
            PathBuf::from(".")
        );
    }

    // POSIX-path-form assertions (leading-/ anchors): on windows the per-OS
    // path semantics are correct product behavior, these tests hold the posix form.
    #[cfg(unix)]
    #[test]
    fn test_normalize_path_multiple_dots() {
        assert_eq!(
            normalize_path(::std::path::Path::new("/a/b/c/../../d")),
            PathBuf::from("/a/d")
        );
    }

    // --- make_absolute / pathdiff tests deleted with their implementations:
    // the Windows-host cwd-dependent legs now run the node win32 cores
    // (`resolve_win32` / `relative_win32`), and nothing else consumed the
    // bun_paths POSIX-leg helpers.
}