bun_standalone_graph 0.1.0

A Rust-native programmable browser runtime built on Servo and SpiderMonkey
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
//! Originally, we tried using LIEF to inject the module graph into a MachO segment
//! But this incurred a fixed 350ms overhead on every build, which is unacceptable
//! so we give up on codesigning support on macOS for now until we can find a better solution

use bun_collections::VecExt;
use core::mem::size_of;
use core::ptr::NonNull;
use std::io::Write as _;
use std::sync::Arc;

use bun_ast::Loader;
use bun_bundler::options::{self, OutputFile};
use bun_collections::StringArrayHashMap;
use bun_core::{Environment, Error as BunError, Output, err};
use bun_core::{String as BunString, StringPointer, ZStr};
use bun_exe_format::{elf as bun_elf, macho as bun_macho, pe as bun_pe};
use bun_options_types::bundle_enums::{Format, WindowsOptions};
#[cfg(not(windows))]
use bun_paths::SEP_STR;
use bun_paths::fs as bun_fs;
use bun_paths::{self as path, PathBuffer, strings};
#[cfg(windows)]
use bun_paths::{OSPathBuffer, WPathBuffer};
use bun_sourcemap as SourceMap;
use bun_sys::{self as Syscall, Fd, FdExt as _, Stat};

// TODO(port): bun_webcore::Blob — `cached_blob` is only ever set from
// `bun_runtime` (higher tier); model as opaque erased pointer here.
bun_opaque::opaque_ffi! {
    /// Opaque stand-in for `bun_webcore::Blob`. Only stored as `NonNull<Blob>`.
    pub struct Blob;
}

pub struct StandaloneModuleGraph {
    /// Raw view over the serialized graph (`[0, offsets.byte_count)`). Stored as a
    /// raw fat pointer — NOT `&'static [u8]` — because `byte_count` covers the
    /// bytecode/module_info subranges that JSC mutates in place via
    /// `File.bytecode`. Holding a `&'static [u8]` over those bytes would freeze
    /// them under Stacked/Tree Borrows and make the later foreign write UB.
    pub bytes: *const [u8],
    pub files: StringArrayHashMap<File>,
    pub entry_point_id: u32,
    pub compile_exec_argv: &'static [u8],
    pub flags: Flags,
}

// We never want to hit the filesystem for these files
// We use the `/$bunfs/` prefix to indicate that it's a virtual path
// It is `/$bunfs/` because:
//
// - `$` makes it unlikely to collide with a real path
// - `/$bunfs/` is 8 characters which is fast to compare for 64-bit CPUs
#[cfg(not(windows))]
pub const BASE_PATH: &str = "/$bunfs/";
// Special case for windows because of file URLs being invalid
// if they do not have a drive letter. B drive because 'bun' but
// also because it's more unlikely to collide with a real path.
#[cfg(windows)]
pub const BASE_PATH: &str = "B:\\~BUN\\";

// TODO(port): Zig version takes `target: Environment.OperatingSystem` + `comptime suffix`
// and concatenates at comptime. Rust cannot const-concat with a runtime enum branch
// nor across a `const fn` boundary. Could expose as a `macro_rules!` over
// `const_format::concatcp!`; for now we materialize the two call-sites directly.
#[cfg(windows)]
pub const BASE_PUBLIC_PATH: &str = "B:/~BUN/";
#[cfg(not(windows))]
pub const BASE_PUBLIC_PATH: &str = "/$bunfs/";

#[cfg(windows)]
pub const BASE_PUBLIC_PATH_WITH_DEFAULT_SUFFIX: &str = const_format::concatcp!("B:/~BUN/", "root/");
#[cfg(not(windows))]
pub const BASE_PUBLIC_PATH_WITH_DEFAULT_SUFFIX: &str = const_format::concatcp!("/$bunfs/", "root/");

// TODO(port): Zig used a nested `Instance` struct holding a static var. Model
// as a process-lifetime `OnceLock` (PORTING.md §Concurrency: never `static mut`).
// `get()` returns a raw `*mut` to mirror Zig's `?*StandaloneModuleGraph`; callers
// mutate `wtf_string` / `cached_blob` / `sourcemap` lazily. TODO(refactor):
// push interior mutability down to those per-`File` fields (`UnsafeCell<…>`) so
// read-only paths (`find`, `entry_point`, `stat`) can take `&self`.
struct Instance(core::cell::UnsafeCell<StandaloneModuleGraph>);
// SAFETY: the graph is populated once at startup before any worker threads;
// post-init mutation is limited to per-`File` lazy fields. NOTE: `INIT_LOCK`
// only guards `LazySourceMap::load`; `File::to_wtf_string` and `cached_blob`
// mutate without any lock and rely on idempotence + JSC's own synchronization.
// (`Send` is auto-derived: `UnsafeCell<T: Send>` is `Send`.)
unsafe impl Sync for Instance {}

static INSTANCE: std::sync::OnceLock<Instance> = std::sync::OnceLock::new();

impl StandaloneModuleGraph {
    pub fn get() -> Option<*mut StandaloneModuleGraph> {
        // Mirrors Zig's `?*StandaloneModuleGraph`: a raw pointer with no
        // uniqueness invariant. Do NOT hand out `&'static mut` here — multiple
        // callers (resolver, sourcemap loader, worker threads) may hold the
        // result concurrently, and overlapping `&mut` is UB regardless of
        // whether either side writes.
        INSTANCE.get().map(|cell| cell.0.get())
    }

    pub fn set(instance: StandaloneModuleGraph) -> *mut StandaloneModuleGraph {
        let _ = INSTANCE.set(Instance(core::cell::UnsafeCell::new(instance)));
        INSTANCE.get().unwrap().0.get()
    }
}

// TODO(port): Zig `targetBasePublicPath(target, comptime suffix: [:0]const u8) [:0]const u8`
// concatenates at comptime via `++`. A runtime `suffix: &[u8]` parameter cannot be
// const-concatenated. All Zig callers pass either `""` or `"root/"`, so the runtime
// variant special-cases those two literals.
pub fn target_base_public_path(
    target: bun_core::Environment::OperatingSystem,
    suffix: &'static [u8],
) -> &'static [u8] {
    match target {
        bun_core::Environment::OperatingSystem::Windows => match suffix {
            b"" => b"B:/~BUN/",
            b"root/" => b"B:/~BUN/root/",
            _ => unreachable!("target_base_public_path: unsupported suffix literal"),
        },
        _ => match suffix {
            b"" => b"/$bunfs/",
            b"root/" => b"/$bunfs/root/",
            _ => unreachable!("target_base_public_path: unsupported suffix literal"),
        },
    }
}

pub(crate) fn is_bun_standalone_file_path_canonicalized(str_: &[u8]) -> bool {
    str_.starts_with(BASE_PATH.as_bytes())
        || (cfg!(windows) && str_.starts_with(BASE_PUBLIC_PATH.as_bytes()))
}

pub fn is_bun_standalone_file_path(str_: &[u8]) -> bool {
    #[cfg(windows)]
    {
        // On Windows, remove NT path prefixes before checking
        let canonicalized = strings::paths::without_nt_prefix::<u8>(str_);
        return is_bun_standalone_file_path_canonicalized(canonicalized);
    }
    #[cfg(not(windows))]
    {
        is_bun_standalone_file_path_canonicalized(str_)
    }
}

impl StandaloneModuleGraph {
    // TODO(port): interior mutability — Zig returns `*File` and callers mutate
    // `wtf_string` / `cached_blob`. Using `&mut self` here may force callers to
    // hold `&mut StandaloneModuleGraph`; could switch to `UnsafeCell` fields.
    pub fn entry_point(&mut self) -> &mut File {
        &mut self.files.values_mut()[self.entry_point_id as usize]
    }

    // by normalized file path
    pub fn find(&mut self, name: &[u8]) -> Option<&mut File> {
        if !is_bun_standalone_file_path(name) {
            return None;
        }
        self.find_assume_standalone_path(name)
    }

    pub fn stat(&mut self, name: &[u8]) -> Option<Stat> {
        let file = self.find(name)?;
        Some(file.stat())
    }

    pub fn find_assume_standalone_path(&mut self, name: &[u8]) -> Option<&mut File> {
        #[cfg(windows)]
        {
            let mut normalized_buf = PathBuffer::uninit();
            let input = strings::paths::without_nt_prefix::<u8>(name);
            let normalized =
                path::resolve_path::platform_to_posix_buf::<u8>(input, &mut normalized_buf);
            return self.files.get_mut(normalized);
        }
        #[cfg(not(windows))]
        {
            self.files.get_mut(name)
        }
    }
}

// SAFETY: the graph is the process-global INSTANCE singleton (set once at
// startup, never freed). The raw-pointer / `Cell` fields it carries are
// `bun_runtime`-owned caches (`cached_blob`, `wtf_string`, source-map state)
// that are only ever touched from the JS main thread under the API lock; the
// resolver-facing read path below touches none of them. Zig stored this as a
// plain `*StandaloneModuleGraph` shared across worker threads with no
// synchronization; mirror that here so the `Send + Sync` supertrait on
// `bun_resolver::StandaloneModuleGraph` is satisfied.
unsafe impl Send for StandaloneModuleGraph {}
// SAFETY: see `Send` impl — post-init mutation is confined to per-`File` lazy caches on the JS thread.
unsafe impl Sync for StandaloneModuleGraph {}

/// Resolver-facing trait object impl. The resolver and VM hold the graph as
/// `&'static dyn bun_resolver::StandaloneModuleGraph` so they stay below
/// `bun_standalone_graph` in the dep graph; this is the sole implementor.
///
/// The trait surface is read-only (`&self`) — the resolver only needs to
/// answer "is `name` an embedded module?" and hand back the canonical name
/// slice; the `&mut`-returning inherent methods above stay for the runtime's
/// blob/sourcemap caching path.
impl bun_resolver::StandaloneModuleGraph for StandaloneModuleGraph {
    fn find_assume_standalone_path(&self, name: &[u8]) -> Option<&[u8]> {
        #[cfg(windows)]
        let file = {
            let mut normalized_buf = PathBuffer::uninit();
            let input = strings::paths::without_nt_prefix::<u8>(name);
            let normalized =
                path::resolve_path::platform_to_posix_buf::<u8>(input, &mut normalized_buf);
            self.files.get(normalized)
        };
        #[cfg(not(windows))]
        let file = self.files.get(name);
        file.map(|f| f.name)
    }

    fn find(&self, name: &[u8]) -> Option<&[u8]> {
        if !is_bun_standalone_file_path(name) {
            return None;
        }
        <Self as bun_resolver::StandaloneModuleGraph>::find_assume_standalone_path(self, name)
    }

    fn base_public_path_with_default_suffix(&self) -> &'static [u8] {
        BASE_PUBLIC_PATH_WITH_DEFAULT_SUFFIX.as_bytes()
    }

    fn compile_exec_argv(&self) -> &[u8] {
        self.compile_exec_argv
    }
}

#[repr(C)]
#[derive(Clone, Copy)]
pub(crate) struct CompiledModuleGraphFile {
    pub name: StringPointer,
    pub contents: StringPointer,
    pub sourcemap: StringPointer,
    pub bytecode: StringPointer,
    pub module_info: StringPointer,
    /// The file path used when generating bytecode (e.g., "B:/~BUN/root/app.js").
    /// Must match exactly at runtime for bytecode cache hits.
    pub bytecode_origin_path: StringPointer,
    pub encoding: Encoding,
    pub loader: Loader,
    pub module_format: ModuleFormat,
    pub side: FileSide,
}

#[repr(u8)]
#[derive(Clone, Copy, PartialEq, Eq, Default)]
pub enum FileSide {
    #[default]
    Server = 0,
    Client = 1,
}

#[repr(u8)]
#[derive(Clone, Copy, PartialEq, Eq, Default)]
pub enum Encoding {
    Binary = 0,
    #[default]
    Latin1 = 1,
    // Not used yet.
    Utf8 = 2,
}

#[repr(u8)]
#[derive(Clone, Copy, PartialEq, Eq, Default)]
pub enum ModuleFormat {
    #[default]
    None = 0,
    Esm = 1,
    Cjs = 2,
}

#[cfg(target_os = "macos")]
mod macho {
    // TODO(port): move to standalone_graph_sys
    unsafe extern "C" {
        pub(super) fn Bun__getStandaloneModuleGraphMachoLength() -> *mut u64; // align(1) in Zig
    }

    /// Returns `(base, len)` for the embedded `__BUN` section data. Kept as a
    /// raw `*mut u8` so the FFI write-provenance is preserved end-to-end —
    /// collapsing to `&[u8]` here would freeze it to read-only and make the
    /// later `from_bytes` writable subslices UB under Stacked Borrows.
    pub(super) fn get_data() -> Option<(*mut u8, usize)> {
        // SAFETY: FFI call returns pointer to embedded section header or null.
        let length_ptr = unsafe { Bun__getStandaloneModuleGraphMachoLength() };
        if length_ptr.is_null() {
            return None;
        }
        // SAFETY: pointer is valid if non-null; read unaligned u64.
        let length = unsafe { core::ptr::read_unaligned(length_ptr) };
        if length < 8 {
            return None;
        }
        // BlobHeader has 8 bytes size (u64), so data starts at offset 8.
        let data_offset = core::mem::size_of::<u64>();
        let slice_ptr = length_ptr.cast::<u8>();
        // SAFETY: section data is `length` bytes immediately following the u64 header.
        Some((unsafe { slice_ptr.add(data_offset) }, length as usize))
    }
}

#[cfg(windows)]
mod pe {
    use bun_exe_format::pe::{
        Bun__getStandaloneModuleGraphPEData, Bun__getStandaloneModuleGraphPELength,
    };

    /// Returns `(base, len)` for the embedded `.bun` PE section data. Kept as a
    /// raw `*mut u8` so the FFI write-provenance is preserved end-to-end —
    /// collapsing to `&[u8]` here would freeze it to read-only and make the
    /// later `from_bytes` writable subslices UB under Stacked Borrows.
    pub(super) fn get_data() -> Option<(*mut u8, usize)> {
        // SAFETY: FFI calls.
        let length = unsafe { Bun__getStandaloneModuleGraphPELength() };
        if length == 0 {
            return None;
        }
        // SAFETY: FFI call returning a process-lifetime section pointer (or null).
        let data_ptr = unsafe { Bun__getStandaloneModuleGraphPEData() };
        if data_ptr.is_null() {
            return None;
        }
        // data_ptr points to `length` bytes of section data valid for program lifetime.
        Some((data_ptr, length as usize))
    }
}

#[cfg(any(target_os = "linux", target_os = "android", target_os = "freebsd"))]
mod elf {
    // TODO(port): move to standalone_graph_sys
    unsafe extern "C" {
        pub(super) fn Bun__getStandaloneModuleGraphELFVaddr() -> *mut u64; // align(1)
    }

    /// Returns `(base, len)` for the embedded ELF segment data. Kept as a raw
    /// `*mut u8` so write-provenance is preserved end-to-end — collapsing to
    /// `&[u8]` here would freeze it to read-only and make the later
    /// `from_bytes` writable subslices UB under Stacked Borrows.
    pub(super) fn get_data() -> Option<(*mut u8, usize)> {
        // SAFETY: FFI call.
        let vaddr_ptr = unsafe { Bun__getStandaloneModuleGraphELFVaddr() };
        if vaddr_ptr.is_null() {
            return None;
        }
        // SAFETY: read unaligned u64 vaddr.
        let vaddr = unsafe { core::ptr::read_unaligned(vaddr_ptr) };
        if vaddr == 0 {
            return None;
        }
        // BUN_COMPILED.size holds the virtual address of the appended data.
        // The kernel mapped it via PT_LOAD, so we can dereference directly.
        // Format at target: [u64 payload_len][payload bytes]
        // Synthesize a `*mut u8` directly so the provenance carries write
        // permission for the in-place bytecode mutation done by JSC.
        let target = vaddr as *mut u8;
        // SAFETY: target points to 8-byte little-endian length prefix.
        let payload_len =
            u64::from_le_bytes(unsafe { core::ptr::read_unaligned(target.cast::<[u8; 8]>()) });
        if payload_len < 8 {
            return None;
        }
        // SAFETY: payload_len bytes follow the 8-byte header at `target`.
        Some((unsafe { target.add(8) }, payload_len as usize))
    }
}

pub struct File {
    pub name: &'static [u8],
    pub loader: Loader,
    pub contents: &'static ZStr,
    pub sourcemap: LazySourceMap,
    // TODO(port): lifetime — assigned in runtime/api/ (out of crate)
    pub cached_blob: Option<NonNull<Blob>>,
    pub encoding: Encoding,
    pub wtf_string: BunString,
    // TODO(port): Zig type is []u8 (mutable) obtained via @constCast on section bytes.
    // BACKREF into the embedded section; JSC mutates the bytecode buffer in place.
    pub bytecode: *mut [u8],
    pub module_info: *mut [u8],
    /// The file path used when generating bytecode (e.g., "B:/~BUN/root/app.js").
    /// Must match exactly at runtime for bytecode cache hits.
    pub bytecode_origin_path: &'static [u8],
    pub module_format: ModuleFormat,
    pub side: FileSide,
}

impl File {
    pub fn appears_in_embedded_files_array(&self) -> bool {
        self.side == FileSide::Client || !self.loader.is_javascript_like()
    }

    pub fn stat(&self) -> Stat {
        // SAFETY: all-zero is a valid `libc::stat` (POD `#[repr(C)]`).
        let mut result: Stat = unsafe { bun_core::ffi::zeroed_unchecked() };
        result.st_size = self.contents.len() as _;
        // `Stat` is `libc::stat` (POSIX) / `uv_stat_t` (Windows, `st_mode: u64`).
        result.st_mode = (libc::S_IFREG | 0o644) as _;
        result
    }

    pub fn less_than_by_index(ctx: &[File], lhs_i: u32, rhs_i: u32) -> bool {
        let lhs = &ctx[lhs_i as usize];
        let rhs = &ctx[rhs_i as usize];
        strings::cmp_strings_asc((), lhs.name, rhs.name)
    }

    pub fn to_wtf_string(&mut self) -> BunString {
        if self.wtf_string.is_empty() {
            match self.encoding {
                Encoding::Binary | Encoding::Utf8 => {
                    self.wtf_string = BunString::clone_utf8(self.contents.as_bytes());
                }
                Encoding::Latin1 => {
                    self.wtf_string =
                        BunString::create_static_external(self.contents.as_bytes(), true);
                }
            }
        }
        // We don't want this to free.
        self.wtf_string.dupe_ref()
    }

    // TODO(port): move to *_jsc — `pub const blob = @import("../runtime/api/standalone_graph_jsc.zig").fileBlob;`
}

pub enum LazySourceMap {
    Serialized(SerializedSourceMap),
    Parsed(Arc<SourceMap::ParsedSourceMap>),
    None,
}

/// It probably is not possible to run two decoding jobs on the same file
// PORTING.md §Concurrency: `bun_threading::Guarded` for const-init statics.
static INIT_LOCK: bun_threading::Guarded<()> = bun_threading::Guarded::new(());

impl LazySourceMap {
    pub fn load(&mut self) -> Option<Arc<SourceMap::ParsedSourceMap>> {
        let _guard = INIT_LOCK.lock();

        match self {
            LazySourceMap::None => None,
            LazySourceMap::Parsed(map) => Some(Arc::clone(map)),
            LazySourceMap::Serialized(serialized) => {
                let Some(blob) = serialized.mapping_blob() else {
                    *self = LazySourceMap::None;
                    return None;
                };
                if !SourceMap::InternalSourceMap::is_valid_blob(blob) {
                    *self = LazySourceMap::None;
                    return None;
                }
                let ism = SourceMap::InternalSourceMap {
                    data: blob.as_ptr(),
                };
                // PORT NOTE: `from_internal` fills `internal = Some(ism)` +
                // `input_line_count = ism.input_line_count()` and defaults the rest.
                let mut stored = SourceMap::ParsedSourceMap::from_internal(ism);

                let source_files_count = serialized.source_files_count();
                // TODO(port): Zig allocated a single `[]?[]u8` of len*2 and reinterpreted
                // the first half as `[][]const u8` for file_names. Rust splits into two
                // separate Vecs to avoid the punning.
                // PERF(port): `external_source_names` is `Vec<Box<[u8]>>` so we
                // copy the section bytes; Zig held a borrowed slice. Could switch
                // the field to `Vec<&'static [u8]>` for the standalone path.
                let mut file_names: Vec<Box<[u8]>> = Vec::with_capacity(source_files_count);
                let decompressed_contents_slice: Vec<Option<Vec<u8>>> =
                    vec![None; source_files_count];
                for i in 0..source_files_count {
                    // SAFETY: `serialized.bytes` is a 'static read-only sourcemap subrange
                    // (disjoint from bytecode); StringPointer offsets were serialized by
                    // `to_bytes` and are in-bounds.
                    file_names.push(Box::from(unsafe {
                        slice_to(
                            serialized.bytes.as_ptr(),
                            serialized.bytes.len(),
                            serialized.source_file_name(i),
                        )
                    }));
                }

                let data = Box::new(SerializedSourceMapLoaded {
                    map: SerializedSourceMap {
                        bytes: serialized.bytes,
                    },
                    decompressed_files: decompressed_contents_slice.into_boxed_slice(),
                });

                stored.external_source_names = file_names;
                // Zig: `.underlying_provider = .{ .data = @truncate(@intFromPtr(data)) }`
                // (kind = .zig, load_hint = .none implicit). `from_provider` packs the
                // same triple into the `SourceContentPtr` bitfield.
                stored.underlying_provider = SourceMap::SourceContentPtr::from_provider(
                    bun_core::heap::into_raw(data).cast::<SourceMap::SourceProviderMap>(),
                );
                stored.is_standalone_module_graph = true;

                let parsed = Arc::new(stored);
                // PERF(port): Zig did parsed.ref() (intrusive) to never free; Arc clone held in self.
                *self = LazySourceMap::Parsed(Arc::clone(&parsed));
                Some(parsed)
            }
        }
    }
}

#[repr(C)]
#[derive(Clone, Copy, Default)]
pub(crate) struct Offsets {
    pub byte_count: usize,
    pub modules_ptr: StringPointer,
    pub entry_point_id: u32,
    pub compile_exec_argv_ptr: StringPointer,
    pub flags: Flags,
}

bitflags::bitflags! {
    #[repr(transparent)]
    #[derive(Clone, Copy, Default)]
    pub struct Flags: u32 {
        const DISABLE_DEFAULT_ENV_FILES     = 1 << 0;
        const DISABLE_AUTOLOAD_BUNFIG       = 1 << 1;
        const DISABLE_AUTOLOAD_TSCONFIG     = 1 << 2;
        const DISABLE_AUTOLOAD_PACKAGE_JSON = 1 << 3;
        // _padding: u28
    }
}

const TRAILER: &[u8] = b"\n---- Bun! ----\n";

impl StandaloneModuleGraph {
    fn from_bytes(
        raw_ptr: *mut u8,
        raw_len: usize,
        offsets: Offsets,
    ) -> Result<StandaloneModuleGraph, BunError> {
        if raw_len == 0 {
            return Ok(StandaloneModuleGraph {
                bytes: core::ptr::slice_from_raw_parts(NonNull::<u8>::dangling().as_ptr(), 0),
                files: StringArrayHashMap::new(),
                entry_point_id: 0,
                compile_exec_argv: b"",
                flags: Flags::default(),
            });
        }

        // Zig's `raw_bytes: []u8` aliases freely — this function hands out read-only subslices
        // (name/contents/sourcemap) AND writable subslices (bytecode/module_info, which JSC
        // mutates in place) into the same allocation. In Rust we must not derive the writable
        // ones from a `&[u8]` reborrow (writing through const-derived provenance is UB), and we
        // must not hold a long-lived `&[u8]` that *spans* a writable subrange (a foreign write
        // would invalidate it under Stacked/Tree Borrows). Keep `(raw_ptr, raw_len)` raw and
        // derive every read-only `&'static [u8]` per-call over its own disjoint subrange only;
        // the bytecode/module_info regions never have a shared reference formed over them.
        let raw_const: *const u8 = raw_ptr;

        // SAFETY: modules metadata blob is a read-only subrange of `[0, raw_len)` disjoint
        // from bytecode/module_info, serialized by `to_bytes`.
        let modules_list_bytes = unsafe { slice_to(raw_const, raw_len, offsets.modules_ptr) };
        // PORT NOTE: StandaloneModuleGraph.zig:309 builds `[]align(1) const CompiledModuleGraphFile`
        // because the modules blob sits at an arbitrary byte offset in the section. In Rust,
        // `&[CompiledModuleGraphFile]` would require natural alignment (StringPointer's u32 fields
        // → 4-byte). We instead iterate by index and `read_unaligned` each fixed-size record into a
        // local (`CompiledModuleGraphFile` is `Copy`/POD), so no `&T` ever points at unaligned memory.
        let modules_list_count = modules_list_bytes.len() / size_of::<CompiledModuleGraphFile>();
        let modules_list_base = modules_list_bytes.as_ptr();

        if offsets.entry_point_id as usize > modules_list_count {
            return Err(err!(
                "Corrupted module graph: entry point ID is greater than module list count"
            ));
        }

        let mut modules = StringArrayHashMap::<File>::new();
        modules.reserve(modules_list_count);
        for i in 0..modules_list_count {
            // SAFETY: index < count derived from byte length above; bytes live for 'static.
            let module: CompiledModuleGraphFile = unsafe {
                core::ptr::read_unaligned(
                    modules_list_base
                        .add(i * size_of::<CompiledModuleGraphFile>())
                        .cast::<CompiledModuleGraphFile>(),
                )
            };
            let module = &module;
            // SAFETY: each name/contents/sourcemap/bytecode_origin_path subrange is in-bounds
            // (serialized by `to_bytes`) and disjoint from the writable bytecode/module_info
            // subranges; section bytes are a live 'static allocation.
            let (name, contents, sourcemap_bytes, bytecode_origin) = unsafe {
                (
                    slice_to_z(raw_const, raw_len, module.name),
                    slice_to_z(raw_const, raw_len, module.contents),
                    slice_to(raw_const, raw_len, module.sourcemap),
                    slice_to_z(raw_const, raw_len, module.bytecode_origin_path),
                )
            };
            // PERF(port): was putAssumeCapacity
            let _ = modules.put(
                name.as_bytes(),
                File {
                    name: name.as_bytes(),
                    loader: module.loader,
                    contents,
                    sourcemap: if module.sourcemap.length > 0 {
                        LazySourceMap::Serialized(SerializedSourceMap {
                            // TODO(port): @alignCast — alignment of source map bytes
                            bytes: sourcemap_bytes,
                        })
                    } else {
                        LazySourceMap::None
                    },
                    bytecode: if module.bytecode.length > 0 {
                        // SAFETY: section bytes are a writable 'static allocation; JSC mutates
                        // bytecode in place. Subrange is in-bounds (serialized by to_bytes) and
                        // disjoint from every read-only subslice handed out above — no
                        // `&[u8]` is ever formed over this range.
                        unsafe { slice_to_mut(raw_ptr, raw_len, module.bytecode) }
                    } else {
                        std::ptr::from_mut::<[u8]>(&mut [])
                    },
                    module_info: if module.module_info.length > 0 {
                        // SAFETY: see bytecode above.
                        unsafe { slice_to_mut(raw_ptr, raw_len, module.module_info) }
                    } else {
                        std::ptr::from_mut::<[u8]>(&mut [])
                    },
                    bytecode_origin_path: if module.bytecode_origin_path.length > 0 {
                        bytecode_origin.as_bytes()
                    } else {
                        b""
                    },
                    module_format: module.module_format,
                    side: module.side,
                    cached_blob: None,
                    encoding: Encoding::Binary,
                    wtf_string: BunString::empty(),
                },
            );
        }

        modules.lock_pointers(); // make the pointers stable forever

        Ok(StandaloneModuleGraph {
            // Stored as a raw fat pointer — `byte_count` covers the writable
            // bytecode/module_info regions, so a `&'static [u8]` here would alias them.
            bytes: core::ptr::slice_from_raw_parts(raw_const, offsets.byte_count),
            files: modules,
            entry_point_id: offsets.entry_point_id,
            // SAFETY: read-only argv string subrange, disjoint from writable regions.
            compile_exec_argv: unsafe {
                slice_to_z(raw_const, raw_len, offsets.compile_exec_argv_ptr)
            }
            .as_bytes(),
            flags: offsets.flags,
        })
    }
}

/// Read-only subslice helper. Builds a `&'static [u8]` over the *subrange only* so no
/// shared reference ever spans the writable bytecode/module_info regions of the same
/// allocation (which would be invalidated by JSC's in-place writes).
///
/// SAFETY: caller guarantees `base[..len]` is a live 'static allocation and
/// `[ptr.offset, ptr.offset + ptr.length)` is in-bounds and never written through a
/// `*mut` alias for the lifetime of the returned reference.
unsafe fn slice_to(base: *const u8, len: usize, ptr: StringPointer) -> &'static [u8] {
    if ptr.length == 0 {
        return b"";
    }
    let off = ptr.offset as usize;
    let n = ptr.length as usize;
    debug_assert!(off.checked_add(n).is_some_and(|end| end <= len));
    let _ = len;
    // SAFETY: caller contract — `[off, off+n)` lies within a live 'static read-only allocation.
    unsafe { core::slice::from_raw_parts(base.add(off), n) }
}

/// Mutable-subslice helper for `from_bytes`. Derives a `*mut [u8]` directly from the raw
/// section base so the result carries write provenance — going through `slice_to` (which
/// returns `&[u8]`) and casting `*const [u8] as *mut [u8]` would be UB on write.
///
/// SAFETY: caller guarantees `base[..len]` is a live allocation with write permission and
/// that `[ptr.offset, ptr.offset + ptr.length)` is in-bounds.
unsafe fn slice_to_mut(base: *mut u8, len: usize, ptr: StringPointer) -> *mut [u8] {
    let off = ptr.offset as usize;
    let n = ptr.length as usize;
    debug_assert!(off.checked_add(n).is_some_and(|end| end <= len));
    let _ = len;
    // SAFETY: caller contract — `off` is in-bounds of the writable allocation at `base`.
    core::ptr::slice_from_raw_parts_mut(unsafe { base.add(off) }, n)
}

/// SAFETY: as `slice_to`, plus `base[ptr.offset + ptr.length] == 0` (written by
/// `to_bytes` via `appendCountZ`).
unsafe fn slice_to_z(base: *const u8, len: usize, ptr: StringPointer) -> &'static ZStr {
    if ptr.length == 0 {
        return ZStr::EMPTY;
    }
    let off = ptr.offset as usize;
    let n = ptr.length as usize;
    debug_assert!(off.checked_add(n).is_some_and(|end| end < len));
    let _ = len;
    // SAFETY: caller contract — `[off, off+n]` is in-bounds with a NUL terminator at `base[off+n]`.
    unsafe { ZStr::from_raw(base.add(off), n) }
}

pub(crate) fn to_bytes(
    prefix: &[u8],
    output_files: &[OutputFile],
    output_format: Format,
    compile_exec_argv: &[u8],
    flags: Flags,
) -> Result<Vec<u8>, BunError> {
    // TODO(port): bun_perf::PerfEvent::StandaloneModuleGraph_serialize — generated
    // enum is still a `_Stub` placeholder; restore the trace call once the generator emits
    // real variants.
    // let _serialize_trace = bun_perf::trace(bun_perf::PerfEvent::StandaloneModuleGraph_serialize);

    let mut entry_point_id: Option<usize> = None;
    let mut string_builder = bun_core::StringBuilder::default();
    let mut module_count: usize = 0;
    for output_file in output_files {
        string_builder.count_z(&output_file.dest_path);
        string_builder.count_z(prefix);
        if let options::OutputValue::Buffer { bytes } = &output_file.value {
            if output_file.output_kind == options::OutputKind::Sourcemap {
                // This is an over-estimation to ensure that we allocate
                // enough memory for the source-map contents. Calculating
                // the exact amount is not possible without allocating as it
                // involves a JSON parser.
                string_builder.cap += bytes.len() * 2;
            } else if output_file.output_kind == options::OutputKind::Bytecode {
                // Allocate up to 256 byte alignment for bytecode
                string_builder.cap += bytes.len().div_ceil(256) * 256 + 256;
            } else if output_file.output_kind == options::OutputKind::ModuleInfo {
                string_builder.cap += bytes.len();
            } else {
                if entry_point_id.is_none() {
                    if output_file.side.is_none() || output_file.side == Some(options::Side::Server)
                    {
                        if output_file.output_kind == options::OutputKind::EntryPoint {
                            entry_point_id = Some(module_count);
                        }
                    }
                }

                string_builder.count_z(bytes);
                module_count += 1;
            }
        }
    }

    if module_count == 0 || entry_point_id.is_none() {
        return Ok(Vec::new());
    }

    string_builder.cap += size_of::<CompiledModuleGraphFile>() * output_files.len();
    string_builder.cap += TRAILER.len();
    string_builder.cap += 16;
    string_builder.cap += size_of::<Offsets>();
    string_builder.count_z(compile_exec_argv);

    string_builder.allocate()?;

    let mut modules: Vec<CompiledModuleGraphFile> = Vec::with_capacity(module_count);

    let mut source_map_header_list: Vec<u8> = Vec::new();
    let mut source_map_string_list: Vec<u8> = Vec::new();
    // PERF(port): was arena bulk-free (source_map_arena)

    for output_file in output_files {
        if !output_file.output_kind.is_file_in_standalone_mode() {
            continue;
        }

        let options::OutputValue::Buffer { bytes: buf_bytes } = &output_file.value else {
            continue;
        };

        let dest_path = bun_core::strings::remove_leading_dot_slash(&output_file.dest_path);

        let bytecode: StringPointer = 'brk: {
            if output_file.bytecode_index != u32::MAX {
                // Bytecode alignment for JSC bytecode cache deserialization.
                // Not aligning correctly causes a runtime assertion error or segfault.
                //
                // PLATFORM-SPECIFIC ALIGNMENT:
                // - PE (Windows) and Mach-O (macOS): The module graph data is embedded in
                //   a dedicated section with an 8-byte size header. At runtime, the section
                //   is memory-mapped at a page-aligned address (hence 128-byte aligned).
                //   The data buffer starts 8 bytes after the section start.
                //   For bytecode at offset O to be 128-byte aligned:
                //     (section_va + 8 + O) % 128 == 0
                //     => O % 128 == 120
                //
                // - ELF (Linux): The module graph data is appended to the executable and
                //   read into a heap-allocated buffer at runtime. The allocator provides
                //   natural alignment, and there's no 8-byte section header offset.
                //   However, using target_mod=120 is still safe because:
                //   - If the buffer is 128-aligned: bytecode at offset 120 is at (128n + 120),
                //     which when loaded at a 128-aligned address gives proper alignment.
                //   - The extra 120 bytes of padding is acceptable overhead.
                //
                // This alignment strategy (target_mod=120) works for all platforms because
                // it's the worst-case offset needed for the 8-byte header scenario.
                let bytecode = output_files[output_file.bytecode_index as usize]
                    .value
                    .as_slice();
                let current_offset = string_builder.len;
                // Calculate padding so that (current_offset + padding) % 128 == 120
                // This accounts for the 8-byte section header on PE/Mach-O platforms.
                let target_mod: usize = 128 - size_of::<u64>(); // 120 = accounts for 8-byte header
                let current_mod = current_offset % 128;
                let padding = if current_mod <= target_mod {
                    target_mod - current_mod
                } else {
                    128 - current_mod + target_mod
                };
                // Zero the padding bytes to ensure deterministic output
                let writable = string_builder.writable();
                writable[0..padding].fill(0);
                string_builder.len += padding;
                let aligned_offset = string_builder.len;
                let writable_after_padding = string_builder.writable();
                writable_after_padding[0..bytecode.len()]
                    .copy_from_slice(&bytecode[0..bytecode.len()]);
                let unaligned_space = &writable_after_padding[bytecode.len()..];
                let len = bytecode.len() + unaligned_space.len().min(128);
                string_builder.len += len;
                break 'brk StringPointer {
                    offset: aligned_offset as u32,
                    length: len as u32,
                };
            } else {
                break 'brk StringPointer::default();
            }
        };

        // Embed module_info for ESM bytecode
        let module_info: StringPointer = 'brk: {
            if output_file.module_info_index != u32::MAX {
                let mi_bytes = output_files[output_file.module_info_index as usize]
                    .value
                    .as_slice();
                let offset = string_builder.len;
                let writable = string_builder.writable();
                writable[0..mi_bytes.len()].copy_from_slice(&mi_bytes[0..mi_bytes.len()]);
                string_builder.len += mi_bytes.len();
                break 'brk StringPointer {
                    offset: offset as u32,
                    length: mi_bytes.len() as u32,
                };
            }
            break 'brk StringPointer::default();
        };

        // PORT NOTE: Zig used `bun.sys.File.makeOpen` (open, on-fail mkdir parent +
        // retry). `src/sys/File.rs` is still cfg-gated upstream, so the
        // `make_open` body is inlined here against the live `bun_sys` stub
        // surface (`openat` / `make_path` / `File::write_all`).
        // Zig: `if (comptime bun.Environment.is_canary or bun.Environment.isDebug)`
        if Environment::IS_CANARY || Environment::IS_DEBUG {
            if let Some(dump_code_dir) = bun_core::env_var::BUN_FEATURE_FLAG_DUMP_CODE.get() {
                let mut path_buf = bun_paths::path_buffer_pool::get();
                let dest_z = path::resolve_path::join_abs_string_buf_z::<path::platform::Auto>(
                    dump_code_dir,
                    &mut path_buf[..],
                    &[dest_path],
                );

                // Scoped block to handle dump failures without skipping module emission
                'dump: {
                    let flags = bun_sys::O::WRONLY | bun_sys::O::CREAT | bun_sys::O::TRUNC;
                    // Inline of `bun.sys.File.makeOpen(dest_z, flags, 0o664)`:
                    let file = match Syscall::openat(Fd::cwd(), dest_z, flags, 0o664) {
                        Ok(fd) => bun_sys::File::from_fd(fd),
                        Err(_first_err) => {
                            let dir_path = path::resolve_path::dirname::<path::platform::Auto>(
                                dest_z.as_bytes(),
                            );
                            let _ = bun_sys::Dir::cwd().make_path(dir_path);
                            match Syscall::openat(Fd::cwd(), dest_z, flags, 0o664) {
                                Ok(fd) => bun_sys::File::from_fd(fd),
                                Err(e) => {
                                    Output::pretty_errorln(format_args!(
                                        "<r><red>error<r><d>:<r> failed to open {}: {}",
                                        bstr::BStr::new(dest_path),
                                        e
                                    ));
                                    break 'dump;
                                }
                            }
                        }
                    };
                    if let Err(e) = file.write_all(buf_bytes) {
                        Output::pretty_errorln(format_args!(
                            "<r><red>error<r><d>:<r> failed to write {}: {}",
                            bstr::BStr::new(dest_path),
                            e
                        ));
                        break 'dump;
                    }
                }
            }
        }

        // When there's bytecode, store the bytecode output file's path as bytecode_origin_path.
        // This path was used to generate the bytecode cache and must match at runtime.
        let bytecode_origin_path: StringPointer = if output_file.bytecode_index != u32::MAX {
            string_builder
                .append_count_z(&output_files[output_file.bytecode_index as usize].dest_path)
        } else {
            StringPointer::default()
        };

        let mut module = CompiledModuleGraphFile {
            name: string_builder.fmt_append_count_z(format_args!(
                "{}{}",
                bstr::BStr::new(prefix),
                bstr::BStr::new(dest_path)
            )),
            loader: output_file.loader,
            contents: string_builder.append_count_z(buf_bytes),
            encoding: match output_file.loader {
                Loader::Js | Loader::Jsx | Loader::Ts | Loader::Tsx => Encoding::Latin1,
                _ => Encoding::Binary,
            },
            module_format: if output_file.loader.is_javascript_like() {
                match output_format {
                    Format::Cjs => ModuleFormat::Cjs,
                    Format::Esm => ModuleFormat::Esm,
                    _ => ModuleFormat::None,
                }
            } else {
                ModuleFormat::None
            },
            bytecode,
            module_info,
            bytecode_origin_path,
            side: match output_file.side.unwrap_or(options::Side::Server) {
                options::Side::Server => FileSide::Server,
                options::Side::Client => FileSide::Client,
            },
            sourcemap: StringPointer::default(),
        };

        if output_file.source_map_index != u32::MAX {
            // PERF(port): Zig used defer clearRetainingCapacity + arena.reset(.retain_capacity)
            serialize_json_source_map_for_standalone(
                &mut source_map_header_list,
                &mut source_map_string_list,
                output_files[output_file.source_map_index as usize]
                    .value
                    .as_slice(),
            )?;
            module.sourcemap =
                string_builder.add_concat(&[&source_map_header_list, &source_map_string_list]);
            source_map_header_list.clear();
            source_map_string_list.clear();
        }
        // PERF(port): was appendAssumeCapacity
        modules.push(module);
    }

    // SAFETY: `CompiledModuleGraphFile` is `#[repr(C)]` POD with no padding-dependent
    // invariants; reinterpreting its backing storage as bytes is the same as Zig's
    // `std.mem.sliceAsBytes`.
    let modules_as_bytes: &[u8] = unsafe {
        core::slice::from_raw_parts(
            modules.as_ptr().cast::<u8>(),
            modules.len() * size_of::<CompiledModuleGraphFile>(),
        )
    };
    let offsets = Offsets {
        entry_point_id: entry_point_id.unwrap() as u32,
        modules_ptr: string_builder.append_count(modules_as_bytes),
        compile_exec_argv_ptr: string_builder.append_count_z(compile_exec_argv),
        byte_count: string_builder.len,
        flags,
    };

    // SAFETY: `Offsets` is `#[repr(C)]` POD; same `sliceAsBytes` rationale as above.
    let offsets_as_bytes: &[u8] = unsafe {
        core::slice::from_raw_parts((&raw const offsets).cast::<u8>(), size_of::<Offsets>())
    };
    let _ = string_builder.append(offsets_as_bytes);
    let _ = string_builder.append(TRAILER);

    // SAFETY: string_builder.ptr was set by allocate() above.
    let output_bytes = unsafe {
        core::slice::from_raw_parts_mut(string_builder.ptr.unwrap().as_ptr(), string_builder.len)
    };

    #[cfg(debug_assertions)]
    {
        // An expensive sanity check:
        // TODO(port): from_bytes wants &'static mut; debug-only sanity check elided.
        // let mut graph = StandaloneModuleGraph::from_bytes(output_bytes, offsets)?;
        // debug_assert_eq!(graph.files.count(), modules.len());
    }

    // TODO(port): StringBuilder owns the buffer; return it as Vec<u8>.
    Ok(output_bytes.to_vec())
}

pub(crate) type InjectOptions = WindowsOptions;

pub enum CompileResult {
    Success,
    Err(CompileError),
}

pub enum CompileError {
    Message(Vec<u8>),
    Reason(CompileErrorReason),
}

#[derive(Clone, Copy, strum::IntoStaticStr)]
pub enum CompileErrorReason {
    NoEntryPoint,
    NoOutputFiles,
}

impl CompileErrorReason {
    pub fn message(self) -> &'static [u8] {
        match self {
            CompileErrorReason::NoEntryPoint => b"No entry point found for compilation",
            CompileErrorReason::NoOutputFiles => b"No output files to bundle",
        }
    }
}

impl CompileError {
    pub fn slice(&self) -> &[u8] {
        match self {
            CompileError::Message(m) => m,
            CompileError::Reason(r) => r.message(),
        }
    }
}

impl CompileResult {
    pub fn fail(reason: CompileErrorReason) -> CompileResult {
        CompileResult::Err(CompileError::Reason(reason))
    }

    pub fn fail_fmt(args: core::fmt::Arguments<'_>) -> CompileResult {
        let mut v = Vec::new();
        let _ = write!(&mut v, "{}", args);
        CompileResult::Err(CompileError::Message(v))
    }
}

pub(crate) fn inject(
    bytes: &[u8],
    self_exe: &ZStr,
    inject_options: &InjectOptions,
    target: &CompileTarget,
) -> Fd {
    let _ = inject_options;
    let mut buf = PathBuffer::uninit();
    // PORT NOTE: `tmpname` borrows `buf` mutably for the &ZStr it returns. The
    // tmpdir-fallback retry below may need to repoint `zname` at a heap-owned
    // buffer instead, so hoist that owner here so it outlives the loop.
    let mut zname_owned: Option<Box<[u8]>> = None;
    let mut zname: &ZStr = match bun_fs::FileSystem::tmpname(
        b"bun-build",
        &mut buf[..],
        // i64 → u64 bitcast (Zig: `@bitCast`).
        bun_core::time::milli_timestamp() as u64,
    ) {
        Ok(n) => n,
        Err(e) => {
            Output::pretty_errorln(format_args!(
                "<r><red>error<r><d>:<r> failed to get temporary file name: {}",
                bstr::BStr::new(e.name())
            ));
            return Fd::INVALID;
        }
    };

    let cleanup = |name: &ZStr, fd: Fd| {
        // Ensure we own the file
        #[cfg(unix)]
        {
            // Make the file writable so we can delete it
            let _ = Syscall::fchmod(fd, 0o700);
        }
        fd.close();
        let _ = Syscall::unlink(name);
    };

    let cloned_executable_fd: Fd = 'brk: {
        #[cfg(windows)]
        {
            // copy self and then open it for writing

            let mut in_buf = WPathBuffer::uninit();
            strings::copy_u8_into_u16(&mut in_buf, self_exe.as_bytes());
            in_buf[self_exe.len()] = 0;
            let mut out_buf = WPathBuffer::uninit();
            strings::copy_u8_into_u16(&mut out_buf, zname.as_bytes());
            out_buf[zname.len()] = 0;

            use bun_sys::windows as w;
            use bun_sys::windows::Win32ErrorExt as _;
            // SAFETY: both buffers NUL-terminated above; `CopyFileW` does not
            // retain the pointers past return.
            if unsafe { w::CopyFileW(in_buf.as_ptr(), out_buf.as_ptr(), w::FALSE) } == w::FALSE {
                let e = w::Win32Error::get();
                // Zig prints `@errorName(err)` (e.g. `AccessDenied`); map the
                // Win32 code through the errno table so users see a name, not
                // a raw integer.
                Output::pretty_errorln(format_args!(
                    "<r><red>error<r><d>:<r> failed to copy bun executable into temporary file: {:?}",
                    e.to_system_errno()
                        .unwrap_or(bun_sys::SystemErrno::EUNKNOWN)
                ));
                return Fd::invalid();
            }
            let out = &out_buf[..zname.len()];
            let file = match Syscall::open_file_at_windows(
                Fd::invalid(),
                out,
                Syscall::NtCreateFileOptions {
                    access_mask: w::SYNCHRONIZE | w::GENERIC_WRITE | w::GENERIC_READ | w::DELETE,
                    disposition: w::FILE_OPEN,
                    options: w::FILE_SYNCHRONOUS_IO_NONALERT | w::FILE_OPEN_REPARSE_POINT,
                    ..Default::default()
                },
            ) {
                Ok(f) => f,
                Err(e) => {
                    Output::pretty_errorln(format_args!(
                        "<r><red>error<r><d>:<r> failed to open temporary file to copy bun into\n{}",
                        e
                    ));
                    return Fd::invalid();
                }
            };

            break 'brk file;
        }

        #[cfg(target_os = "macos")]
        {
            // if we're on a mac, use clonefile() if we can
            // failure is okay, clonefile is just a fast path.
            if let bun_sys::Result::Ok(()) = Syscall::clonefile(self_exe, zname) {
                if let bun_sys::Result::Ok(res) =
                    Syscall::open(zname, bun_sys::O::RDWR | bun_sys::O::CLOEXEC, 0)
                {
                    break 'brk res;
                }
            }
        }

        // otherwise, just copy the file

        #[cfg(not(windows))]
        let fd: Fd = 'brk2: {
            let mut tried_changing_abs_dir = false;
            for retry in 0..3 {
                match Syscall::open(
                    zname,
                    bun_sys::O::CLOEXEC | bun_sys::O::RDWR | bun_sys::O::CREAT | bun_sys::O::EXCL,
                    0,
                ) {
                    Ok(res) => break 'brk2 res,
                    Err(err) => {
                        if retry < 2 {
                            // they may not have write access to the present working directory
                            //
                            // but we want to default to it since it's the
                            // least likely to need to be copied due to
                            // renameat() across filesystems
                            //
                            // so in the event of a failure, we try to
                            // we retry using the tmp dir
                            //
                            // but we only do that once because otherwise it's just silly
                            if !tried_changing_abs_dir {
                                tried_changing_abs_dir = true;
                                // `RealFS::tmpdir_path` lives in `bun_resolver::fs` (T6);
                                // reached via `bun_bundler`'s public re-export so this
                                // crate doesn't take a direct `bun_resolver` edge.
                                {
                                    let zname_z = bun_core::strings::concat(&[
                                        bun_bundler::bun_fs::RealFS::tmpdir_path(),
                                        SEP_STR.as_bytes(),
                                        zname.as_bytes(),
                                        &[0],
                                    ]);
                                    // PORT NOTE: Zig leaked the concat buffer here. PORTING.md
                                    // §Forbidden bans `mem::forget`; the buffer is parked in
                                    // `zname_owned` (declared at fn entry) so it outlives the
                                    // loop and drops at fn exit.
                                    let len = zname_z.len().saturating_sub(1);
                                    zname_owned = Some(zname_z);
                                    // SAFETY: trailing 0 byte appended above; `zname_owned`
                                    // keeps the allocation alive for the rest of the fn.
                                    zname = unsafe {
                                        ZStr::from_raw(zname_owned.as_ref().unwrap().as_ptr(), len)
                                    };
                                    continue;
                                }
                            }
                            match err.get_errno() {
                                // try again
                                bun_sys::E::EPERM | bun_sys::E::EAGAIN | bun_sys::E::EBUSY => {
                                    continue;
                                }
                                _ => break,
                            }
                        }
                        // PORT NOTE: Zig falls through to `unreachable` on retry == 2; the
                        // print+return above is dead code in Zig too (kept for diff parity).
                    }
                }
            }
            unreachable!()
        };
        #[cfg(not(windows))]
        let self_fd: Fd = 'brk2: {
            for retry in 0..3 {
                match Syscall::open(self_exe, bun_sys::O::CLOEXEC | bun_sys::O::RDONLY, 0) {
                    Ok(res) => break 'brk2 res,
                    Err(err) => {
                        if retry < 2 {
                            match err.get_errno() {
                                // try again
                                bun_sys::E::EPERM | bun_sys::E::EAGAIN | bun_sys::E::EBUSY => {
                                    continue;
                                }
                                _ => {}
                            }
                        }

                        Output::pretty_errorln(format_args!(
                            "<r><red>error<r><d>:<r> failed to open bun executable to copy from as read-only\n{}",
                            err
                        ));
                        cleanup(zname, fd);
                        return Fd::INVALID;
                    }
                }
            }
            unreachable!()
        };

        #[cfg(not(windows))]
        {
            // defer self_fd.close()
            let _self_fd_guard = Syscall::CloseOnDrop::new(self_fd);

            if let Err(e) = bun_sys::copy_file(self_fd, fd) {
                Output::pretty_errorln(format_args!(
                    "<r><red>error<r><d>:<r> failed to copy bun executable into temporary file: {}",
                    e
                ));
                cleanup(zname, fd);
                return Fd::INVALID;
            }

            break 'brk fd;
        }
    };
    let _ = (&mut zname_owned, &mut zname);

    match target.os {
        CompileTargetOs::Mac => {
            let input_bytes = match bun_sys::File::borrow(&cloned_executable_fd).read_to_end() {
                Ok(b) => b,
                Err(err) => {
                    Output::pretty_errorln(format_args!(
                        "Error reading standalone module graph: {}",
                        err
                    ));
                    cleanup(zname, cloned_executable_fd);
                    return Fd::INVALID;
                }
            };
            let mut macho_file = match bun_macho::MachoFile::init(&input_bytes, bytes.len()) {
                Ok(f) => f,
                Err(e) => {
                    Output::pretty_errorln(format_args!(
                        "Error initializing standalone module graph: {}",
                        e
                    ));
                    cleanup(zname, cloned_executable_fd);
                    return Fd::INVALID;
                }
            };
            if let Err(e) = macho_file.write_section(bytes) {
                Output::pretty_errorln(format_args!(
                    "Error writing standalone module graph: {}",
                    e
                ));
                cleanup(zname, cloned_executable_fd);
                return Fd::INVALID;
            }
            drop(input_bytes);

            if let Err(err) = Syscall::set_file_offset(cloned_executable_fd, 0) {
                Output::pretty_errorln(format_args!(
                    "Error seeking to start of temporary file: {}",
                    err
                ));
                cleanup(zname, cloned_executable_fd);
                return Fd::INVALID;
            }

            // PERF(port): Zig used writer.adaptToNewApi(&buffer) with a 512KB stack
            // buffer. `std::io::BufWriter` heap-allocates the buffer instead.
            let mut buffered_writer = std::io::BufWriter::with_capacity(
                512 * 1024,
                bun_sys::FileWriter(cloned_executable_fd),
            );
            if let Err(e) = macho_file.build_and_sign(&mut buffered_writer) {
                Output::pretty_errorln(format_args!(
                    "Error writing standalone module graph: {}",
                    bstr::BStr::new(e.name())
                ));
                cleanup(zname, cloned_executable_fd);
                return Fd::INVALID;
            }
            if let Err(e) = std::io::Write::flush(&mut buffered_writer) {
                Output::pretty_errorln(format_args!(
                    "Error flushing standalone module graph: {}",
                    e
                ));
                cleanup(zname, cloned_executable_fd);
                return Fd::INVALID;
            }
            #[cfg(not(windows))]
            {
                // SAFETY: libc fchmod on a valid native fd.
                unsafe { bun_sys::c::fchmod(cloned_executable_fd.native(), 0o755) };
            }
            return cloned_executable_fd;
        }
        CompileTargetOs::Windows => {
            let input_bytes = match bun_sys::File::borrow(&cloned_executable_fd).read_to_end() {
                Ok(b) => b,
                Err(err) => {
                    Output::pretty_errorln(format_args!(
                        "Error reading standalone module graph: {}",
                        err
                    ));
                    cleanup(zname, cloned_executable_fd);
                    return Fd::INVALID;
                }
            };
            let mut pe_file = match bun_pe::PEFile::init(&input_bytes) {
                Ok(f) => f,
                Err(e) => {
                    Output::pretty_errorln(format_args!("Error initializing PE file: {}", e));
                    cleanup(zname, cloned_executable_fd);
                    return Fd::INVALID;
                }
            };
            // Always strip authenticode when adding .bun section for --compile
            if let Err(e) = pe_file.add_bun_section(bytes, bun_pe::StripMode::StripAlways) {
                Output::pretty_errorln(format_args!("Error adding Bun section to PE file: {}", e));
                cleanup(zname, cloned_executable_fd);
                return Fd::INVALID;
            }
            drop(input_bytes);

            if let Err(err) = Syscall::set_file_offset(cloned_executable_fd, 0) {
                Output::pretty_errorln(format_args!(
                    "Error seeking to start of temporary file: {}",
                    err
                ));
                cleanup(zname, cloned_executable_fd);
                return Fd::INVALID;
            }

            let mut writer = bun_sys::FileWriter(cloned_executable_fd);
            if let Err(e) = pe_file.write(&mut writer) {
                Output::pretty_errorln(format_args!(
                    "Error writing PE file: {}",
                    bstr::BStr::new(e.name())
                ));
                cleanup(zname, cloned_executable_fd);
                return Fd::INVALID;
            }
            // Set executable permissions when running on POSIX hosts, even for Windows targets
            #[cfg(not(windows))]
            {
                // SAFETY: libc fchmod on a valid native fd.
                unsafe { bun_sys::c::fchmod(cloned_executable_fd.native(), 0o755) };
            }
            return cloned_executable_fd;
        }
        CompileTargetOs::Linux | CompileTargetOs::Freebsd => {
            // ELF section approach: find .bun section and expand it
            let input_bytes = match bun_sys::File::borrow(&cloned_executable_fd).read_to_end() {
                Ok(b) => b,
                Err(err) => {
                    Output::pretty_errorln(format_args!("Error reading executable: {}", err));
                    cleanup(zname, cloned_executable_fd);
                    return Fd::INVALID;
                }
            };

            let mut elf_file = match bun_elf::ElfFile::init(input_bytes) {
                Ok(f) => f,
                Err(e) => {
                    Output::pretty_errorln(format_args!("Error initializing ELF file: {}", e));
                    cleanup(zname, cloned_executable_fd);
                    return Fd::INVALID;
                }
            };

            elf_file.normalize_interpreter();

            if let Err(e) = elf_file.write_bun_section(bytes) {
                Output::pretty_errorln(format_args!("Error writing .bun section to ELF: {}", e));
                cleanup(zname, cloned_executable_fd);
                return Fd::INVALID;
            }

            if let Err(err) = Syscall::set_file_offset(cloned_executable_fd, 0) {
                Output::pretty_errorln(format_args!(
                    "Error seeking to start of temporary file: {}",
                    err
                ));
                cleanup(zname, cloned_executable_fd);
                return Fd::INVALID;
            }

            // Write the modified ELF data back to the file
            let write_file = bun_sys::File::borrow(&cloned_executable_fd);
            if let Err(err) = write_file.write_all(&elf_file.data) {
                Output::pretty_errorln(format_args!("Error writing ELF file: {}", err));
                cleanup(zname, cloned_executable_fd);
                return Fd::INVALID;
            }
            // Truncate the file to the exact size of the modified ELF
            let _ = Syscall::ftruncate(
                cloned_executable_fd,
                i64::try_from(elf_file.data.len()).expect("int cast"),
            );

            #[cfg(not(windows))]
            {
                // SAFETY: libc fchmod on a valid native fd.
                unsafe { bun_sys::c::fchmod(cloned_executable_fd.native(), 0o755) };
            }
            return cloned_executable_fd;
        }
        _ => {
            let total_byte_count: usize;
            #[cfg(windows)]
            {
                total_byte_count = bytes.len()
                    + 8
                    + match Syscall::set_file_offset_to_end_windows(cloned_executable_fd) {
                        Ok(v) => v,
                        Err(e) => {
                            Output::pretty_errorln(format_args!(
                                "<r><red>error<r><d>:<r> failed to seek to end of temporary file\n{}",
                                e
                            ));
                            cleanup(zname, cloned_executable_fd);
                            return Fd::invalid();
                        }
                    };
            }
            #[cfg(not(windows))]
            {
                let seek_position: u64 = u64::try_from('brk: {
                    let fstat = match Syscall::fstat(cloned_executable_fd) {
                        Ok(res) => res,
                        Err(err) => {
                            Output::pretty_errorln(format_args!("{}", err));
                            cleanup(zname, cloned_executable_fd);
                            return Fd::INVALID;
                        }
                    };
                    break 'brk fstat.st_size.max(0);
                })
                .unwrap();

                total_byte_count = seek_position as usize + bytes.len() + 8;

                // From https://man7.org/linux/man-pages/man2/lseek.2.html
                //
                //  lseek() allows the file offset to be set beyond the end of the
                //  file (but this does not change the size of the file).  If data is
                //  later written at this point, subsequent reads of the data in the
                //  gap (a "hole") return null bytes ('\0') until data is actually
                //  written into the gap.
                //
                if let Err(err) = Syscall::set_file_offset(cloned_executable_fd, seek_position) {
                    Output::pretty_errorln(format_args!(
                        "{}\nwhile seeking to end of temporary file (pos: {})",
                        err, seek_position
                    ));
                    cleanup(zname, cloned_executable_fd);
                    return Fd::INVALID;
                }
            }

            let mut remain = bytes;
            while !remain.is_empty() {
                match Syscall::write(cloned_executable_fd, remain) {
                    Ok(written) => remain = &remain[written..],
                    Err(err) => {
                        Output::pretty_errorln(format_args!(
                            "<r><red>error<r><d>:<r> failed to write to temporary file\n{}",
                            err
                        ));
                        cleanup(zname, cloned_executable_fd);
                        return Fd::INVALID;
                    }
                }
            }

            // the final 8 bytes in the file are the length of the module graph with padding, excluding the trailer and offsets
            let _ = Syscall::write(cloned_executable_fd, &total_byte_count.to_ne_bytes());
            #[cfg(not(windows))]
            {
                // SAFETY: libc fchmod on a valid native fd.
                unsafe { bun_sys::c::fchmod(cloned_executable_fd.native(), 0o755) };
            }

            return cloned_executable_fd;
        }
    }
}

use bun_core::Environment::OperatingSystem as CompileTargetOs;
pub use bun_options_types::compile_target::CompileTarget;

/// Port of `CompileTarget.downloadToPath` (CompileTarget.zig). Moved up from
/// `bun_options_types` (T3) so it can name `bun_http::AsyncHTTP` directly
/// instead of routing through `extern "Rust"` shims; the only callers are the
/// two `download*` fns below in this crate.
pub(crate) fn download_to_path(
    target: &CompileTarget,
    env: &mut bun_dotenv::Loader<'_>,
    dest_z: &ZStr,
) -> Result<(), BunError> {
    bun_http::http_thread::init(&Default::default());
    let mut refresher = bun_core::Progress::Progress::default();

    {
        refresher.refresh();

        // TODO: This is way too much code necessary to send a single HTTP request...
        let mut compressed_archive_bytes =
            Box::new(bun_core::MutableString::init(24 * 1024 * 1024)?);
        let mut url_buffer = [0u8; 2048];
        let url_str = match target.to_npm_registry_url(&mut url_buffer) {
            Ok(s) => s,
            Err(err) => {
                // Return error without printing - let caller decide how to handle
                return Err(err);
            }
        };
        let url_str_copy: Box<[u8]> = Box::from(url_str);
        let url = bun_url::URL::parse(&url_str_copy);
        {
            // TODO(port): errdefer progress.end() — `start` returns `&mut Node`
            // borrowing `refresher`, so a scopeguard capturing it would alias.
            // Could reshape with a guard that re-borrows on drop.
            // PORT NOTE: reshaped for borrowck — `get_http_proxy_for` borrows
            // `env` for the proxy URL lifetime; read the bool first.
            let reject_unauthorized = env.get_tls_reject_unauthorized();
            let http_proxy: Option<bun_url::URL<'_>> = env.get_http_proxy_for(&url);
            let progress = refresher.start(b"Downloading", 0);

            let mut async_http = Box::new(bun_http::AsyncHTTP::init_sync(
                bun_http::Method::GET,
                url,
                Default::default(),
                b"",
                &raw mut *compressed_archive_bytes,
                b"",
                http_proxy,
                None,
                bun_http::FetchRedirect::Follow,
            ));
            async_http.client.progress_node =
                core::ptr::NonNull::new(core::ptr::from_mut(progress));
            async_http.client.flags.reject_unauthorized = reject_unauthorized;
            let send_result = async_http.send_sync();

            progress.end();
            let status_code = send_result?.status_code as u16;

            match status_code {
                404 => {
                    // Return error without printing - let caller handle the messaging
                    return Err(err!("TargetNotFound"));
                }
                403 | 429 | 499..=599 => {
                    // Return error without printing - let caller handle the messaging
                    return Err(err!("NetworkError"));
                }
                200 => {}
                _ => return Err(err!("NetworkError")),
            }
        }

        let mut tarball_bytes: Vec<u8> = Vec::new();
        {
            refresher.refresh();
            // defer compressed_archive_bytes.list.deinit(allocator) — handled by Drop

            if compressed_archive_bytes.list.is_empty() {
                // Return error without printing - let caller handle the messaging
                return Err(err!("InvalidResponse"));
            }

            {
                // PORT NOTE: reshaped for borrowck — `refresher.start` borrows
                // `refresher` mutably; do gunzip work first, drive progress around it.
                refresher.start(b"Decompressing", 0);
                let gunzip_result = (|| -> Result<(), BunError> {
                    let mut gunzip = bun_zlib::ZlibReaderArrayList::init(
                        compressed_archive_bytes.list.as_slice(),
                        &mut tarball_bytes,
                    )
                    .map_err(|_| err!("InvalidResponse"))?;
                    gunzip.read_all(true).map_err(|_| err!("InvalidResponse"))?;
                    Ok(())
                })();
                refresher.root.end();
                gunzip_result?;
            }
            refresher.refresh();

            {
                refresher.start(b"Extracting", 0);
                // defer node.end() — see explicit calls below

                let mut tmpname_buf = [0u8; 1024];
                let tempdir_name: &ZStr =
                    bun_fs::FileSystem::tmpname(b"tmp", &mut tmpname_buf, bun_core::fast_random())?;
                let tmpdir = bun_sys::Dir::cwd()
                    .make_open_path(tempdir_name.as_bytes(), Default::default())?;
                scopeguard::defer! {
                    let _ = bun_sys::Dir::cwd().delete_tree(tempdir_name.as_bytes());
                }
                let extract_res = bun_libarchive::Archiver::extract_to_dir(
                    tarball_bytes.as_slice(),
                    tmpdir.fd(),
                    None,
                    &mut (),
                    bun_libarchive::ExtractOptions {
                        // "package/bin"
                        depth_to_skip: 2,
                        ..Default::default()
                    },
                );
                if extract_res.is_err() {
                    refresher.root.end();
                    // Return error without printing - let caller handle the messaging
                    return Err(err!("ExtractionFailed"));
                }

                let mut did_retry = false;
                loop {
                    let src_name: &ZStr = if target.os == CompileTargetOs::Windows {
                        bun_core::zstr!("bun.exe")
                    } else {
                        bun_core::zstr!("bun")
                    };
                    let mv = bun_sys::move_file_z(tmpdir.fd(), src_name, Fd::INVALID, dest_z);
                    if mv.is_err() {
                        if !did_retry {
                            did_retry = true;
                            let dirname = path::dirname_simple(dest_z.as_bytes());
                            if !dirname.is_empty() {
                                let _ = bun_sys::Dir::cwd().make_path(dirname);
                                continue;
                            }

                            // fallthrough, failed for another reason
                        }
                        refresher.root.end();
                        // Return error without printing - let caller handle the messaging
                        return Err(err!("ExtractionFailed"));
                    }
                    break;
                }
                tmpdir.close();
                refresher.root.end();
            }
            refresher.refresh();
        }
    }
    Ok(())
}

pub fn to_executable(
    target: &CompileTarget,
    output_files: &[OutputFile],
    root_dir: Fd, // TODO(port): was std.fs.Dir
    module_prefix: &[u8],
    outfile: &[u8],
    env: &mut bun_dotenv::Loader,
    output_format: Format,
    windows_options: &WindowsOptions,
    compile_exec_argv: &[u8],
    self_exe_path: Option<&[u8]>,
    flags: Flags,
) -> Result<CompileResult, BunError> {
    #[cfg(windows)]
    let _ = root_dir;
    // TODO(port): narrow error set
    let bytes = match to_bytes(
        module_prefix,
        output_files,
        output_format,
        compile_exec_argv,
        flags,
    ) {
        Ok(b) => b,
        Err(e) => {
            return Ok(CompileResult::fail_fmt(format_args!(
                "failed to generate module graph bytes: {}",
                bstr::BStr::new(e.name())
            )));
        }
    };
    if bytes.is_empty() {
        return Ok(CompileResult::fail(CompileErrorReason::NoOutputFiles));
    }
    // bytes drops at end of scope

    // PORT NOTE: Zig tracked `free_self_exe` to decide whether the slice was
    // allocator-owned. `ZBox` always owns its bytes and drops on scope exit,
    // so the flag is unnecessary.
    let self_exe: bun_core::ZBox = if let Some(path) = self_exe_path {
        bun_core::ZBox::from_vec_with_nul(path.to_vec())
    } else if target.is_default() {
        match bun_core::self_exe_path() {
            Ok(p) => bun_core::ZBox::from_vec_with_nul(p.as_bytes().to_vec()),
            Err(e) => {
                return Ok(CompileResult::fail_fmt(format_args!(
                    "failed to get self executable path: {}",
                    bstr::BStr::new(e.name())
                )));
            }
        }
    } else {
        let mut exe_path_buf = PathBuffer::uninit();
        // TODO(port): std.fmt.allocPrintSentinel — build NUL-terminated owned string.
        let mut version_str: Vec<u8> = Vec::new();
        let _ = write!(&mut version_str, "{}", target);
        version_str.push(0);
        // SAFETY: trailing 0 byte appended above.
        let version_zstr = ZStr::from_slice_with_nul(&version_str[..]);

        let mut needs_download: bool = true;
        let dest_z = target.exe_path(&mut exe_path_buf, version_zstr, env, &mut needs_download);

        if needs_download {
            if let Err(e) = download_to_path(target, env, dest_z) {
                return Ok(if e == err!("TargetNotFound") {
                    CompileResult::fail_fmt(format_args!(
                        "Target platform '{}' is not available for download. Check if this version of Bun supports this target.",
                        target
                    ))
                } else if e == err!("NetworkError") {
                    CompileResult::fail_fmt(format_args!(
                        "Network error downloading executable for '{}'. Check your internet connection and proxy settings.",
                        target
                    ))
                } else if e == err!("InvalidResponse") {
                    CompileResult::fail_fmt(format_args!(
                        "Downloaded file for '{}' appears to be corrupted. Please try again.",
                        target
                    ))
                } else if e == err!("ExtractionFailed") {
                    CompileResult::fail_fmt(format_args!(
                        "Failed to extract executable for '{}'. The download may be incomplete.",
                        target
                    ))
                } else if e == err!("UnsupportedTarget") {
                    CompileResult::fail_fmt(format_args!("Target '{}' is not supported", target))
                } else {
                    CompileResult::fail_fmt(format_args!(
                        "Failed to download '{}': {}",
                        target,
                        bstr::BStr::new(e.name())
                    ))
                });
            }
        }

        bun_core::ZBox::from_vec_with_nul(dest_z.as_bytes().to_vec())
    };

    let fd = inject(&bytes, &self_exe, windows_options, target);
    // PORT NOTE: Zig's `defer if (fd != invalid) fd.close()` reads `fd` at scope exit
    // after later reassignments. A scopeguard closure capturing `fd` by value would not
    // observe those writes; capturing by `&mut` conflicts with later uses. Explicit
    // `if fd != Fd::INVALID { fd.close(); }` calls are inserted at every return below
    // (both error and success paths) to match Zig behavior.
    debug_assert!(fd.kind() == bun_sys::FdKind::System);

    #[cfg(unix)]
    {
        // Set executable permissions (0o755 = rwxr-xr-x) - makes it executable for owner, readable/executable for group and others
        let _ = Syscall::fchmod(fd, 0o755);
    }

    #[cfg(windows)]
    {
        // Get the current path of the temp file
        let mut temp_buf = PathBuffer::uninit();
        let temp_path = match bun_sys::get_fd_path(fd, &mut temp_buf) {
            Ok(p) => p,
            Err(e) => {
                if fd != Fd::INVALID {
                    fd.close();
                }
                return Ok(CompileResult::fail_fmt(format_args!(
                    "Failed to get temp file path: {}",
                    bstr::BStr::new(e.name())
                )));
            }
        };

        // Build the absolute destination path
        // On Windows, we need an absolute path for MoveFileExW
        // Get the current working directory and join with outfile
        let mut cwd_buf = PathBuffer::uninit();
        let cwd_path: &[u8] = match bun_sys::getcwd(&mut cwd_buf) {
            Ok(len) => &cwd_buf[..len],
            Err(e) => {
                if fd != Fd::INVALID {
                    fd.close();
                }
                return Ok(CompileResult::fail_fmt(format_args!(
                    "Failed to get current directory: {}",
                    bstr::BStr::new(e.name())
                )));
            }
        };
        let dest_path = if bun_paths::is_absolute(outfile) {
            outfile
        } else {
            path::resolve_path::join_abs_string::<path::platform::Auto>(cwd_path, &[outfile])
        };

        // Convert paths to Windows UTF-16
        let mut temp_buf_w = OSPathBuffer::uninit();
        let mut dest_buf_w = OSPathBuffer::uninit();
        let temp_w_len = strings::paths::to_w_path_normalized(&mut temp_buf_w, temp_path).len();
        let dest_w_len = strings::paths::to_w_path_normalized(&mut dest_buf_w, dest_path).len();

        // `to_w_path_normalized` already NUL-terminates (`buf[len] = 0`); the
        // explicit re-slice below is just to derive the wide-string pointers.
        let temp_buf_u16: &mut [u16] = &mut temp_buf_w;
        let dest_buf_u16: &mut [u16] = &mut dest_buf_w;
        temp_buf_u16[temp_w_len] = 0;
        dest_buf_u16[dest_w_len] = 0;

        // Close the file handle before moving (Windows requires this)
        fd.close();

        use bun_sys::windows::{self, Win32ErrorExt as _};
        // Move the file using MoveFileExW
        // SAFETY: NUL-terminated wide strings constructed above. Pass the
        // full-buffer pointer (not a `[..len]` sub-slice) so the pointer's
        // provenance covers the trailing NUL at index `len` that the W-suffix
        // API will read — matches Zig's `buf[0..len :0].ptr` sentinel slice.
        if unsafe {
            windows::kernel32::MoveFileExW(
                temp_buf_u16.as_ptr(),
                dest_buf_u16.as_ptr(),
                windows::MOVEFILE_COPY_ALLOWED
                    | windows::MOVEFILE_REPLACE_EXISTING
                    | windows::MOVEFILE_WRITE_THROUGH,
            )
        } == windows::FALSE
        {
            let werr = windows::Win32Error::get();
            if let Some(sys_err) = werr.to_system_errno() {
                if sys_err == bun_sys::SystemErrno::EISDIR {
                    return Ok(CompileResult::fail_fmt(format_args!(
                        "{} is a directory. Please choose a different --outfile or delete the directory",
                        bstr::BStr::new(outfile)
                    )));
                } else {
                    return Ok(CompileResult::fail_fmt(format_args!(
                        "failed to move executable to {}: {}",
                        bstr::BStr::new(dest_path),
                        <&'static str>::from(sys_err)
                    )));
                }
            } else {
                return Ok(CompileResult::fail_fmt(format_args!(
                    "failed to move executable to {}",
                    bstr::BStr::new(dest_path)
                )));
            }
        }

        // Set Windows icon and/or metadata using unified function
        if windows_options.icon.is_some()
            || windows_options.title.is_some()
            || windows_options.publisher.is_some()
            || windows_options.version.is_some()
            || windows_options.description.is_some()
            || windows_options.copyright.is_some()
        {
            // The file has been moved to dest_path
            // SAFETY: full-buffer pointer so provenance includes the NUL at
            // `dest_buf_u16[dest_w_len]` (FFI reads it as a C wide string).
            if let Err(e) = windows::rescle::set_windows_metadata(
                dest_buf_u16.as_ptr(),
                windows_options.icon.as_deref(),
                windows_options.title.as_deref(),
                windows_options.publisher.as_deref(),
                windows_options.version.as_deref(),
                windows_options.description.as_deref(),
                windows_options.copyright.as_deref(),
            ) {
                return Ok(CompileResult::fail_fmt(format_args!(
                    "Failed to set Windows metadata: {}",
                    e.name()
                )));
            }
        }
        return Ok(CompileResult::Success);
    }

    #[cfg(not(windows))]
    {
        let mut buf2 = PathBuffer::uninit();
        // PORT NOTE: borrowck — `get_fd_path` returns `&mut [u8]` borrowing `buf2`;
        // copy it into an owned buffer so `temp_posix_buf` can also borrow `buf2`'s
        // sibling without overlap.
        let temp_location: Vec<u8> = match bun_sys::get_fd_path(fd, &mut buf2) {
            Ok(p) => p.to_vec(),
            Err(e) => {
                if fd != Fd::INVALID {
                    fd.close();
                }
                return Ok(CompileResult::fail_fmt(format_args!(
                    "failed to get path for fd: {}",
                    e
                )));
            }
        };
        // TODO(port): std.posix.toPosixPath — copy into NUL-terminated fixed buffer.
        // `resolve_path::z` does the same (copy + NUL) and yields `&ZStr`.
        let mut temp_posix_buf = PathBuffer::uninit();
        let temp_posix = path::resolve_path::z(&temp_location, &mut temp_posix_buf);
        let outfile_basename = bun_paths::basename(outfile);
        let mut outfile_posix_buf = PathBuffer::uninit();
        let outfile_posix = path::resolve_path::z(outfile_basename, &mut outfile_posix_buf);

        if let Err(e) =
            bun_sys::move_file_z_with_handle(fd, Fd::cwd(), temp_posix, root_dir, outfile_posix)
        {
            fd.close();

            let _ = Syscall::unlink(temp_posix);

            if e == err!("IsDir") || e == err!("EISDIR") {
                return Ok(CompileResult::fail_fmt(format_args!(
                    "{} is a directory. Please choose a different --outfile or delete the directory",
                    bstr::BStr::new(outfile)
                )));
            } else {
                return Ok(CompileResult::fail_fmt(format_args!(
                    "failed to rename {} to {}: {}",
                    bstr::BStr::new(&temp_location),
                    bstr::BStr::new(outfile),
                    bstr::BStr::new(e.name())
                )));
            }
        }

        if fd != Fd::INVALID {
            fd.close();
        }
        Ok(CompileResult::Success)
    }
}

impl StandaloneModuleGraph {
    /// Loads the standalone module graph from the executable, allocates it on the heap,
    /// sets it globally, and returns the pointer.
    pub fn from_executable() -> Result<Option<*mut StandaloneModuleGraph>, BunError> {
        #[cfg(target_os = "macos")]
        {
            let Some((base, len)) = macho::get_data() else {
                return Ok(None);
            };
            if len < size_of::<Offsets>() + TRAILER.len() {
                Output::debug_warn(format_args!(
                    "bun standalone module graph is too small to be valid"
                ));
                return Ok(None);
            }
            // SAFETY: `[len - Offsets - TRAILER, len)` is in-bounds (checked above) and
            // read-only; build short-lived views via raw `read_unaligned` so no `&[u8]`
            // ever spans the writable bytecode region carried in `base`'s provenance.
            let offsets_ptr = unsafe { base.add(len - size_of::<Offsets>() - TRAILER.len()) };
            // SAFETY: `[len - TRAILER.len(), len)` is in-bounds (length checked above) and read-only.
            let trailer_bytes = unsafe {
                core::slice::from_raw_parts(base.add(len - TRAILER.len()), TRAILER.len())
            };
            if trailer_bytes != TRAILER {
                Output::debug_warn(format_args!(
                    "bun standalone module graph has invalid trailer"
                ));
                return Ok(None);
            }
            // SAFETY: offsets_ptr has at least size_of::<Offsets>() bytes.
            let offsets: Offsets =
                unsafe { core::ptr::read_unaligned(offsets_ptr.cast::<Offsets>()) };
            return from_bytes_alloc(base, len, offsets).map(Some);
        }

        #[cfg(windows)]
        {
            let Some((base, len)) = pe::get_data() else {
                return Ok(None);
            };
            if len < size_of::<Offsets>() + TRAILER.len() {
                Output::debug_warn(format_args!(
                    "bun standalone module graph is too small to be valid"
                ));
                return Ok(None);
            }
            // SAFETY: `[len - Offsets - TRAILER, len)` is in-bounds (checked above) and
            // read-only; build short-lived views via raw `read_unaligned` so no `&[u8]`
            // ever spans the writable bytecode region carried in `base`'s provenance.
            let offsets_ptr = unsafe { base.add(len - size_of::<Offsets>() - TRAILER.len()) };
            // SAFETY: `[len - TRAILER.len(), len)` is in-bounds (length checked above) and read-only.
            let trailer_bytes = unsafe {
                core::slice::from_raw_parts(base.add(len - TRAILER.len()), TRAILER.len())
            };
            if trailer_bytes != TRAILER {
                Output::debug_warn(format_args!(
                    "bun standalone module graph has invalid trailer"
                ));
                return Ok(None);
            }
            // SAFETY: offsets_ptr has at least size_of::<Offsets>() bytes.
            let offsets: Offsets =
                unsafe { core::ptr::read_unaligned(offsets_ptr.cast::<Offsets>()) };
            return from_bytes_alloc(base, len, offsets).map(Some);
        }

        #[cfg(any(target_os = "linux", target_os = "android", target_os = "freebsd"))]
        {
            let Some((base, len)) = elf::get_data() else {
                return Ok(None);
            };
            if len < size_of::<Offsets>() + TRAILER.len() {
                Output::debug_warn(format_args!(
                    "bun standalone module graph is too small to be valid"
                ));
                return Ok(None);
            }
            // SAFETY: `[len - Offsets - TRAILER, len)` is in-bounds (checked above) and
            // read-only; build short-lived views via raw `read_unaligned` so no `&[u8]`
            // ever spans the writable bytecode region carried in `base`'s provenance.
            let offsets_ptr = unsafe { base.add(len - size_of::<Offsets>() - TRAILER.len()) };
            // SAFETY: `[len - TRAILER.len(), len)` is in-bounds (length checked above) and read-only.
            let trailer_bytes = unsafe {
                core::slice::from_raw_parts(base.add(len - TRAILER.len()), TRAILER.len())
            };
            if trailer_bytes != TRAILER {
                Output::debug_warn(format_args!(
                    "bun standalone module graph has invalid trailer"
                ));
                return Ok(None);
            }
            // SAFETY: offsets_ptr has at least size_of::<Offsets>() bytes.
            let offsets: Offsets =
                unsafe { core::ptr::read_unaligned(offsets_ptr.cast::<Offsets>()) };
            return from_bytes_alloc(base, len, offsets).map(Some);
        }

        #[cfg(not(any(
            target_os = "macos",
            windows,
            target_os = "linux",
            target_os = "android",
            target_os = "freebsd"
        )))]
        {
            unreachable!()
        }
    }

    /// Hint to the kernel that the embedded `__BUN`/`.bun` source pages are
    /// unlikely to be accessed again after the entrypoint has been parsed.
    /// The pages are clean file-backed COW, so any later read (lazy require,
    /// stack-trace source lookup) faults back in transparently from the
    /// executable on disk. Only applies when running as a compiled
    /// standalone binary.
    pub fn hint_source_pages_dont_need() {
        #[cfg(windows)]
        {
            return;
        }

        #[cfg(not(windows))]
        {
            let (base, len): (*mut u8, usize) = {
                #[cfg(target_os = "macos")]
                {
                    match macho::get_data() {
                        Some(b) => b,
                        None => return,
                    }
                }
                #[cfg(any(target_os = "linux", target_os = "android"))]
                {
                    match elf::get_data() {
                        Some(b) => b,
                        None => return,
                    }
                }
                #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "android")))]
                {
                    return;
                }
            };

            #[cfg(any(target_os = "macos", target_os = "linux", target_os = "android"))]
            {
                if len == 0 {
                    return;
                }

                let page: usize = bun_alloc::page_size();
                let start = (base as usize) & !(page - 1);
                let end_unaligned = base as usize + len;
                let end = (end_unaligned + page - 1) & !(page - 1);

                // std.posix.madvise hits `unreachable` on unexpected errnos; this is a
                // best-effort hint, so call libc directly and just log on failure.
                // SAFETY: start..end covers a mapped range of the executable image.
                let rc = unsafe {
                    libc::madvise(
                        start as *mut core::ffi::c_void,
                        end - start,
                        libc::MADV_DONTNEED,
                    )
                };
                if rc != 0 {
                    Output::debug_warn(format_args!(
                        "hintSourcePagesDontNeed: madvise failed errno={}",
                        bun_sys::last_errno()
                    ));
                    return;
                }
                Output::debug_warn(format_args!(
                    "hintSourcePagesDontNeed: MADV_DONTNEED {} bytes",
                    end - start
                ));
            }
        }
    }
}

/// Allocates a StandaloneModuleGraph in the process-static `INSTANCE`,
/// populates it from bytes, sets it globally, and returns the pointer.
fn from_bytes_alloc(
    raw_ptr: *mut u8,
    raw_len: usize,
    offsets: Offsets,
) -> Result<*mut StandaloneModuleGraph, BunError> {
    let graph = StandaloneModuleGraph::from_bytes(raw_ptr, raw_len, offsets)?;
    Ok(StandaloneModuleGraph::set(graph))
}

/// Source map serialization in the bundler is specially designed to be
/// loaded in memory as is. Source contents are compressed with ZSTD to
/// reduce the file size, and mappings are stored as an InternalSourceMap
/// blob (varint deltas + sync points) so lookups need no decode pass.
#[derive(Clone, Copy)]
pub struct SerializedSourceMap {
    pub bytes: &'static [u8],
}

/// Following the header bytes:
/// - source_files_count number of StringPointer, file names
/// - source_files_count number of StringPointer, zstd compressed contents
/// - the InternalSourceMap blob, `map_bytes_length` bytes
/// - all the StringPointer contents
#[repr(C)]
#[derive(Clone, Copy)]
pub(crate) struct SerializedSourceMapHeader {
    pub source_files_count: u32,
    pub map_bytes_length: u32,
}

impl SerializedSourceMap {
    pub(crate) fn header(self) -> SerializedSourceMapHeader {
        // SAFETY: bytes.len() >= size_of::<Header>() must hold (caller checked); align(1) read.
        unsafe {
            core::ptr::read_unaligned(self.bytes.as_ptr().cast::<SerializedSourceMapHeader>())
        }
    }

    pub(crate) fn mapping_blob(self) -> Option<&'static [u8]> {
        if self.bytes.len() < size_of::<SerializedSourceMapHeader>() {
            return None;
        }
        let head = self.header();
        let start = size_of::<SerializedSourceMapHeader>()
            + head.source_files_count as usize * size_of::<StringPointer>() * 2;
        if start > self.bytes.len() || head.map_bytes_length as usize > self.bytes.len() - start {
            return None;
        }
        Some(&self.bytes[start..][..head.map_bytes_length as usize])
    }

    // PORT NOTE: Zig types these arrays as `[]align(1) const StringPointer` because the
    // serialized byte buffer carries no alignment guarantee. Materializing a Rust
    // `&[StringPointer]` would require `align_of::<StringPointer>() == 4` alignment
    // (UB otherwise), so expose count + indexed unaligned reads instead.

    pub(crate) fn source_files_count(self) -> usize {
        self.header().source_files_count as usize
    }

    fn string_pointers_base(self) -> *const StringPointer {
        self.bytes[size_of::<SerializedSourceMapHeader>()..]
            .as_ptr()
            .cast()
    }

    pub(crate) fn source_file_name(self, index: usize) -> StringPointer {
        debug_assert!(index < self.source_files_count());
        // SAFETY: index bounds-checked; layout per Header doc; pointer may be misaligned.
        unsafe { core::ptr::read_unaligned(self.string_pointers_base().add(index)) }
    }
}

/// Once loaded, this map stores additional data for keeping track of source code.
pub struct SerializedSourceMapLoaded {
    pub map: SerializedSourceMap,

    /// Only decompress source code once! Once a file is decompressed,
    /// it is stored here. Decompression failures are stored as an empty
    /// string, which will be treated as "no contents".
    pub decompressed_files: Box<[Option<Vec<u8>>]>,
}

pub(crate) fn serialize_json_source_map_for_standalone(
    header_list: &mut Vec<u8>,
    string_payload: &mut Vec<u8>,
    json_source: &[u8],
) -> Result<(), BunError> {
    use bun_ast::ExprData as AstData;

    // PERF(port): Zig threaded an arena allocator through; here we own a local
    // bump arena and drop it on return (matches `defer arena.free`).
    let arena = bun_alloc::Arena::new();

    let json_src = bun_ast::Source::init_path_string_owned("sourcemap.json", json_source.to_vec());
    let mut log = bun_ast::Log::init();

    // the allocator given to the JS parser is not respected for all parts
    // of the parse, so we need to remember to reset the ast store
    let _reset_guard = bun_ast::StoreResetGuard::new();

    let json = bun_parsers::json::parse::<false>(&json_src, &mut log, &arena)
        .map_err(|_| err!("InvalidSourceMap"))?;

    let mappings_str = json
        .get(b"mappings")
        .ok_or_else(|| err!("InvalidSourceMap"))?;
    if !matches!(mappings_str.data, AstData::EString(_)) {
        return Err(err!("InvalidSourceMap"));
    }
    let sources_content = match json
        .get(b"sourcesContent")
        .ok_or_else(|| err!("InvalidSourceMap"))?
        .data
    {
        AstData::EArray(arr) => arr,
        _ => return Err(err!("InvalidSourceMap")),
    };
    let sources_paths = match json
        .get(b"sources")
        .ok_or_else(|| err!("InvalidSourceMap"))?
        .data
    {
        AstData::EArray(arr) => arr,
        _ => return Err(err!("InvalidSourceMap")),
    };
    if sources_content.items.len_u32() != sources_paths.items.len_u32() {
        return Err(err!("InvalidSourceMap"));
    }

    // SAFETY: matched `EString` above; `StoreRef` derefs `&mut` into the arena node.
    let mut mappings_e_string = mappings_str
        .data
        .e_string()
        .expect("infallible: variant checked");
    let map_vlq: &[u8] = mappings_e_string.slice(&arena);
    let map_blob =
        SourceMap::InternalSourceMap::from_vlq(map_vlq, 0).map_err(|_| err!("InvalidSourceMap"))?;

    header_list.extend_from_slice(&u32::to_le_bytes(sources_paths.items.len_u32()));
    header_list.extend_from_slice(
        &u32::try_from(map_blob.len())
            .expect("int cast")
            .to_le_bytes(),
    );

    let string_payload_start_location = size_of::<u32>()
        + size_of::<u32>()
        + size_of::<StringPointer>() * (sources_content.items.len_u32() as usize) * 2 // path + source
        + map_blob.len();

    for item in sources_paths.items.slice() {
        let AstData::EString(s) = item.data else {
            return Err(err!("InvalidSourceMap"));
        };

        let decoded = s.string_cloned(&arena).map_err(|_| err!("OutOfMemory"))?;

        let offset = string_payload.len();
        string_payload.extend_from_slice(decoded);

        let slice = StringPointer {
            offset: u32::try_from(offset + string_payload_start_location).expect("int cast"),
            length: u32::try_from(string_payload.len() - offset).expect("int cast"),
        };
        header_list.extend_from_slice(&slice.offset.to_le_bytes());
        header_list.extend_from_slice(&slice.length.to_le_bytes());
    }

    for item in sources_content.items.slice() {
        let AstData::EString(s) = item.data else {
            return Err(err!("InvalidSourceMap"));
        };

        let utf8 = s.string_cloned(&arena).map_err(|_| err!("OutOfMemory"))?;

        let offset = string_payload.len();

        let bound = bun_zstd::compress_bound(utf8.len());
        // SAFETY: zstd writes only into the spare slice and reports the byte
        // count on success; on error we commit 0 and `Output::panic` diverges.
        unsafe {
            bun_core::vec::fill_spare(string_payload, bound, |spare| {
                match bun_zstd::compress(spare, utf8, Some(1)) {
                    bun_zstd::Result::Err(err_msg) => {
                        Output::panic(format_args!(
                            "Unexpected error compressing sourcemap: {}",
                            bstr::BStr::new(err_msg.as_bytes())
                        ));
                    }
                    bun_zstd::Result::Success(n) => (n, ()),
                }
            })
        };

        let slice = StringPointer {
            offset: u32::try_from(offset + string_payload_start_location).expect("int cast"),
            length: u32::try_from(string_payload.len() - offset).expect("int cast"),
        };
        header_list.extend_from_slice(&slice.offset.to_le_bytes());
        header_list.extend_from_slice(&slice.length.to_le_bytes());
    }

    header_list.extend_from_slice(&map_blob);

    debug_assert!(header_list.len() == string_payload_start_location);
    Ok(())
}

// ported from: src/standalone_graph/StandaloneModuleGraph.zig