fallow-graph 3.22.0

Module graph construction and import resolution for fallow codebase intelligence
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
//! Module dependency graph with re-export chain propagation and reachability analysis.
//!
//! The graph is built from resolved modules and entry points, then used to determine
//! which files are reachable and which exports are referenced.

mod ambiguity;
mod build;
mod cycles;
mod effective_exports;
mod effective_re_exports;
mod fan_io;
mod impact_closure;
mod namespace_aliases;
mod namespace_indexes;
mod namespace_re_exports;
mod narrowing;
mod partition_order;
mod public_exports;
mod re_exports;
mod reachability;
pub mod types;

use std::path::Path;

use fixedbitset::FixedBitSet;
use rustc_hash::{FxHashMap, FxHashSet};

use crate::resolve::{ResolvedModule, ResolvedReplacedModuleTarget};
use fallow_types::discover::{DiscoveredFile, EntryPoint, FileId};
use fallow_types::extract::{ImportedName, ModuleLoadMechanism};
use types::{ReferencePathInterner, ReferencePathNode, ReferenceRouteNodeId, ReferenceRoutes};

pub use ambiguity::{AmbiguityParticipants, AmbiguousStarExport};
pub use effective_exports::{EffectiveExportBinding, EffectiveExportResolution, ExportNamespace};
pub use effective_re_exports::EffectiveReExportRoute;
pub use fan_io::{FocusFileFacts, FocusFileFactsPaths};
pub use impact_closure::{
    CoordinationGap, CoordinationGapPaths, ImpactClosure, ImpactClosurePaths,
};
pub use partition_order::{PartitionOrder, PartitionOrderPaths, ReviewUnit, ReviewUnitPaths};
pub use public_exports::PublicExportOrigin;
pub use re_exports::GraphReExportCycle;
pub use types::{
    ExportSymbol, ModuleNode, ReExportEdge, ReferenceKind, ReferencePathId, SymbolReference,
};

/// Direct declaration selected by one unique effective export binding.
#[derive(Debug, Clone, Copy)]
pub struct EffectiveExportOrigin<'graph> {
    file_id: FileId,
    export: &'graph ExportSymbol,
}

/// One namespace-specific export exposed by a module and its effective binding.
#[derive(Debug, Clone, Copy)]
pub struct EffectiveExportSurface<'graph> {
    binding: EffectiveExportBinding,
    namespace: ExportNamespace,
    export: Option<&'graph ExportSymbol>,
    origin: Option<EffectiveExportOrigin<'graph>>,
    local_export: bool,
}

impl<'graph> EffectiveExportSurface<'graph> {
    /// Canonical binding exposed by the requested module/name/namespace.
    #[must_use]
    pub const fn binding(self) -> EffectiveExportBinding {
        self.binding
    }

    /// Namespace selected for this surface.
    #[must_use]
    pub const fn namespace(self) -> ExportNamespace {
        self.namespace
    }

    /// Reference-bearing graph export selected for this surface.
    ///
    /// Direct declarations use their origin export. Named re-exports use their
    /// single barrel surface while references remain namespace-specific;
    /// namespace objects and implicit SFC defaults have no declaration export.
    #[must_use]
    pub const fn export(self) -> Option<&'graph ExportSymbol> {
        self.export
    }

    /// Direct declaration that owns this binding, when one exists.
    #[must_use]
    pub const fn origin(self) -> Option<EffectiveExportOrigin<'graph>> {
        self.origin
    }

    /// Whether the requested module owns a concrete export surface.
    ///
    /// Named re-exports have a local export-specifier identity. Star-only
    /// surfaces do not, so semantic consumers must use the origin declaration.
    #[must_use]
    pub const fn has_local_export(self) -> bool {
        self.local_export
    }
}

impl<'graph> EffectiveExportOrigin<'graph> {
    /// Module that owns the selected declaration.
    #[must_use]
    pub const fn file_id(self) -> FileId {
        self.file_id
    }

    /// Selected declaration in its owning module.
    #[must_use]
    pub const fn export(self) -> &'graph ExportSymbol {
        self.export
    }
}

/// True when the path's final component looks like a TypeScript declaration
/// file (`.d.ts`, `.d.mts`, `.d.cts`). Used to seed declaration files as
/// overall entry points so ambient `typeof import()` references stay alive.
///
/// Keep in sync with the analysis-layer declaration-file predicate. The graph
/// crate cannot depend on the detector backend, so the predicate is duplicated.
fn is_declaration_file_path(path: &Path) -> bool {
    path.file_name()
        .and_then(|n| n.to_str())
        .is_some_and(|name| {
            name.ends_with(".d.ts") || name.ends_with(".d.mts") || name.ends_with(".d.cts")
        })
}

/// The core module dependency graph.
///
/// Derives `serde` so the whole graph can be persisted to `.fallow/graph-cache.bin`
/// (see `crate::cache`) and skipped on a re-run whose inputs are byte-identical.
/// `namespace_imported` is a derived `FixedBitSet` reconstructed from the edge
/// set on cache load (`reconstruct_namespace_imported`), so it is
/// `#[serde(skip, default)]` rather than persisted.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct ModuleGraph {
    /// All modules indexed by `FileId`.
    ///
    /// Invariant: `modules[file_id.0 as usize].file_id == file_id` for every
    /// `FileId` in the graph. Holds because `discover/walk.rs` assigns FileIds
    /// sequentially via `.enumerate()` after path-sorting, and
    /// `build::populate_edges` pushes one `ModuleNode` per file in iteration
    /// order. Detectors rely on this for O(1) FileId-to-module lookup
    /// (`graph.modules.get(file_id.0 as usize)`) instead of building a
    /// per-call `FxHashMap<FileId, &ModuleNode>`.
    pub modules: Vec<ModuleNode>,
    /// Flat edge storage for cache-friendly iteration.
    edges: Vec<Edge>,
    /// Maps npm package names to the set of `FileId`s that import them.
    pub package_usage: FxHashMap<String, Vec<FileId>>,
    /// Maps npm package names to the set of `FileId`s that import them with type-only imports.
    /// A package appearing here but not in `package_usage` (or only in both) indicates
    /// it's only used for types and could be a devDependency.
    pub type_only_package_usage: FxHashMap<String, Vec<FileId>>,
    /// All entry point `FileId`s.
    pub entry_points: FxHashSet<FileId>,
    /// Runtime/application entry point `FileId`s.
    pub runtime_entry_points: FxHashSet<FileId>,
    /// Test entry point `FileId`s.
    pub test_entry_points: FxHashSet<FileId>,
    /// Compact correlation index for distinct test-root replacement profiles.
    ///
    /// Empty when no test root declares a project-internal replacement. That
    /// preserves the ordinary single-BFS test reachability path.
    test_reachability_index: TestReachabilityIndex,
    /// Flat interned linked paths used by exact export references.
    reference_paths: Vec<ReferencePathNode>,
    /// Compact transition graphs used by namespace-derived references.
    reference_routes: ReferenceRoutes,
    /// Reverse index: for each `FileId`, which files import it.
    pub reverse_deps: Vec<Vec<FileId>>,
    /// Precomputed: which modules have namespace imports (import * as ns).
    ///
    /// Derived entirely from the edge set (a module is namespace-imported iff
    /// some edge to it carries an `ImportedName::Namespace` symbol), so it is
    /// not persisted: on cache load it is rebuilt by
    /// [`ModuleGraph::reconstruct_namespace_imported`], which replicates the
    /// exact insertion logic from `build.rs`.
    #[serde(skip, default)]
    namespace_imported: FixedBitSet,
    /// Re-export cycles and self-loops detected during Phase 4 chain
    /// resolution. Each entry names the participating files (sorted
    /// lexicographically) and a `is_self_loop` flag distinguishing
    /// single-file self-re-exports from multi-node cycles. Populated by
    /// `re_exports::find_re_export_cycles` and consumed by the analysis
    /// backend, which wraps each entry in a typed `ReExportCycleFinding`.
    pub re_export_cycles: Vec<GraphReExportCycle>,
    /// Canonical direct and transitive export binding resolution.
    effective_exports: effective_exports::EffectiveExportIndex,
}

/// An edge in the module graph.
///
/// Public consumers inspect relationships through summary methods such as
/// [`ModuleGraph::direct_importer_summaries`] and
/// [`ModuleGraph::outgoing_edge_summaries`]. Keeping the raw storage private
/// preserves graph invariants and the `Edge == 32` size assertion below.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct Edge {
    /// Source module of this import edge.
    source: FileId,
    /// Target module imported by `source`.
    target: FileId,
    /// Symbols imported across this edge.
    symbols: Vec<ImportedSymbol>,
}

/// A symbol imported across an edge.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct ImportedSymbol {
    /// The name as imported from the target (`Named`, `Default`, `Namespace`,
    /// `SideEffect`).
    pub imported_name: ImportedName,
    /// Local binding name in the importing file.
    pub local_name: String,
    /// Byte span of the import statement in the source file.
    #[serde(with = "crate::cache::span_serde")]
    pub import_span: oxc_span::Span,
    /// Whether this import is type-only (`import type { ... }`).
    /// Used to skip type-only edges in circular dependency detection.
    pub is_type_only: bool,
    /// Whether the ambient star this symbol stands for is spelled
    /// `export type *` (issue #2375), which forwards type meanings only.
    pub is_type_only_star: bool,
    /// Runtime module mechanism that created this symbol edge.
    mechanism: ModuleLoadMechanism,
}

impl ImportedSymbol {
    /// Whether this symbol is the whole-module shape of `export *` or
    /// `export * as ns` inside a `declare module '...'` body (issue #2357):
    /// type-only, bound to no local name, and naming the module namespace or
    /// its `default` member (recorded for the `export * as ns` form).
    ///
    /// The ambient body is erased at runtime, so package usage stays
    /// type-only, but the star forwards every export of the target, so the
    /// graph credits its star surface instead of narrowing to imported names.
    /// Every other type-only symbol, bound (`import type { x }`) or not (an
    /// ambient named re-export, an `import()` type reference), credits the
    /// names it actually imports.
    #[must_use]
    pub(crate) fn is_ambient_star(&self) -> bool {
        self.is_type_only
            && self.local_name.is_empty()
            && matches!(
                self.imported_name,
                ImportedName::Namespace | ImportedName::Default
            )
    }

    /// Whether this ambient star forwards both meanings of every name it
    /// carries.
    ///
    /// `export *` inside the body re-exports the target's value and type
    /// declarations alike, so it credits both namespaces. `export type *`
    /// erases every value meaning (issue #2375), so it credits type space
    /// only, exactly like the ambient named re-exports of issue #2349.
    #[must_use]
    pub(crate) fn is_value_bearing_ambient_star(&self) -> bool {
        self.is_ambient_star() && !self.is_type_only_star
    }
}

/// Flat bitset index mapping files to the test profiles that reach them.
///
/// Each file owns `words_per_file` contiguous reachable-profile words. Masks are
/// target-sparse: only explicit replacement targets own a row, while every row
/// retains dense profile words for constant-time word lookup. Retained storage
/// is `O((files + replaced_targets) * ceil(profiles / 64))`; correlation queries
/// intersect machine words instead of scanning profile file lists.
#[derive(Debug, Default, serde::Serialize, serde::Deserialize)]
struct TestReachabilityIndex {
    profile_count: usize,
    words_per_file: usize,
    reachable_profiles: Vec<u64>,
    masked_profiles: Vec<MaskedTestProfiles>,
}

/// Sparse profile-mask row for one replaced target.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
struct MaskedTestProfiles {
    target: FileId,
    profiles: Vec<u64>,
}

impl TestReachabilityIndex {
    fn new(file_capacity: usize, profile_count: usize) -> Self {
        let words_per_file = profile_count.div_ceil(u64::BITS as usize);
        let storage_len = file_capacity.saturating_mul(words_per_file);
        Self {
            profile_count,
            words_per_file,
            reachable_profiles: vec![0; storage_len],
            masked_profiles: Vec::new(),
        }
    }

    fn set_sparse_masks(&mut self, masks: FxHashMap<FileId, Vec<u64>>) {
        let mut rows: Vec<_> = masks
            .into_iter()
            .map(|(target, profiles)| MaskedTestProfiles { target, profiles })
            .collect();
        rows.sort_unstable_by_key(|row| row.target.0);
        self.masked_profiles = rows;
    }

    fn profiles_for<'a>(&self, storage: &'a [u64], file_id: FileId) -> Option<&'a [u64]> {
        let start = (file_id.0 as usize).checked_mul(self.words_per_file)?;
        let end = start.checked_add(self.words_per_file)?;
        storage.get(start..end)
    }

    fn masked_profiles_for(&self, file_id: FileId) -> Option<&[u64]> {
        self.masked_profiles
            .binary_search_by_key(&file_id.0, |row| row.target.0)
            .ok()
            .map(|index| self.masked_profiles[index].profiles.as_slice())
    }

    fn covers_reference_path(
        &self,
        source: FileId,
        path: types::ReferencePathId,
        paths: &[ReferencePathNode],
        routes: &ReferenceRoutes,
    ) -> bool {
        let Some(source_profiles) = self.profiles_for(&self.reachable_profiles, source) else {
            return false;
        };

        for (word_index, &source_word) in source_profiles.iter().enumerate() {
            let mut active_profiles = source_word;
            if active_profiles == 0 {
                continue;
            }

            let mut next = Some(path);
            while let Some(path_id) = next {
                let Some(path_node) = paths.get(path_id.index()) else {
                    return false;
                };
                next = path_node.parent();
                active_profiles = match *path_node {
                    ReferencePathNode::Hop {
                        target, mechanism, ..
                    } => self.active_hop_profiles(target, mechanism, word_index, active_profiles),
                    ReferencePathNode::Route {
                        graph,
                        start,
                        terminal,
                        start_mechanism,
                        ..
                    } => self.active_route_profiles(
                        routes,
                        graph,
                        start,
                        terminal,
                        start_mechanism,
                        word_index,
                        active_profiles,
                    ),
                };
                if active_profiles == 0 {
                    break;
                }
            }

            if active_profiles != 0 {
                return true;
            }
        }

        false
    }

    #[cfg(test)]
    fn covers_path<I>(&self, source: FileId, hops: &I) -> bool
    where
        I: Iterator<Item = (FileId, ModuleLoadMechanism)> + Clone,
    {
        let Some(source_profiles) = self.profiles_for(&self.reachable_profiles, source) else {
            return false;
        };
        for (word_index, &source_word) in source_profiles.iter().enumerate() {
            let mut active_profiles = source_word;
            for (target, mechanism) in (*hops).clone() {
                active_profiles =
                    self.active_hop_profiles(target, mechanism, word_index, active_profiles);
                if active_profiles == 0 {
                    break;
                }
            }
            if active_profiles != 0 {
                return true;
            }
        }
        false
    }

    fn active_hop_profiles(
        &self,
        target: FileId,
        mechanism: ModuleLoadMechanism,
        word_index: usize,
        mut active_profiles: u64,
    ) -> u64 {
        let Some(target_word) = self
            .profiles_for(&self.reachable_profiles, target)
            .and_then(|profiles| profiles.get(word_index))
        else {
            return 0;
        };
        active_profiles &= target_word;
        if matches!(mechanism, ModuleLoadMechanism::EsModule)
            && let Some(masked_profiles) = self.masked_profiles_for(target)
        {
            let Some(masked_word) = masked_profiles.get(word_index) else {
                return 0;
            };
            active_profiles &= !masked_word;
        }
        active_profiles
    }

    /// Evaluate one compact namespace transition graph with a monotone
    /// profile-bit worklist. Each `(route node, profile bit)` is processed at
    /// most once, including cyclic graphs.
    #[expect(
        clippy::too_many_arguments,
        reason = "the route identity and profile word form one evaluation contract"
    )]
    fn active_route_profiles(
        &self,
        routes: &ReferenceRoutes,
        graph_id: types::ReferenceRouteGraphId,
        start: ReferenceRouteNodeId,
        terminal: ReferenceRouteNodeId,
        start_mechanism: Option<ModuleLoadMechanism>,
        word_index: usize,
        candidate_profiles: u64,
    ) -> u64 {
        let Some(graph) = routes.graphs.get(graph_id.0 as usize) else {
            return 0;
        };
        let node_count = graph.nodes.end.saturating_sub(graph.nodes.start) as usize;
        let start_index = start.0 as usize;
        let terminal_index = terminal.0 as usize;
        if start_index >= node_count || terminal_index >= node_count {
            return 0;
        }

        let mut attempted = vec![0_u64; node_count];
        let mut pending = vec![0_u64; node_count];
        let mut queued = vec![false; node_count];
        let mut queue = std::collections::VecDeque::from([start_index]);
        pending[start_index] = candidate_profiles;
        queued[start_index] = true;
        let mut successful_profiles = 0_u64;

        while let Some(local_index) = queue.pop_front() {
            queued[local_index] = false;
            let incoming = pending[local_index] & !attempted[local_index];
            pending[local_index] = 0;
            attempted[local_index] |= incoming;
            if incoming == 0 {
                continue;
            }

            let Some(node) = routes.nodes.get(graph.nodes.start as usize + local_index) else {
                return 0;
            };
            let active = if local_index == start_index {
                start_mechanism.map_or(incoming, |mechanism| {
                    self.active_hop_profiles(node.target, mechanism, word_index, incoming)
                })
            } else {
                self.active_hop_profiles(node.target, node.mechanism, word_index, incoming)
            };
            if active == 0 {
                continue;
            }
            if local_index == terminal_index {
                successful_profiles |= active;
                continue;
            }

            let Some(successors) = routes
                .edges
                .get(node.successors.start as usize..node.successors.end as usize)
            else {
                return 0;
            };
            for successor in successors {
                let successor_index = successor.0 as usize;
                if successor_index >= node_count {
                    return 0;
                }
                let new_profiles = active & !attempted[successor_index] & !pending[successor_index];
                if new_profiles == 0 {
                    continue;
                }
                pending[successor_index] |= new_profiles;
                if !queued[successor_index] {
                    queued[successor_index] = true;
                    queue.push_back(successor_index);
                }
            }
        }

        successful_profiles
    }

    #[cfg(test)]
    fn profile_contains(&self, storage: &[u64], file_id: FileId, profile: usize) -> bool {
        self.profiles_for(storage, file_id)
            .and_then(|words| words.get(profile / u64::BITS as usize))
            .is_some_and(|word| word & (1_u64 << (profile % u64::BITS as usize)) != 0)
    }

    #[cfg(test)]
    fn profile_reaches(&self, file_id: FileId, profile: usize) -> bool {
        self.profile_contains(&self.reachable_profiles, file_id, profile)
    }

    #[cfg(test)]
    fn profile_masks(&self, file_id: FileId, profile: usize) -> bool {
        self.masked_profiles_for(file_id)
            .and_then(|words| words.get(profile / u64::BITS as usize))
            .is_some_and(|word| word & (1_u64 << (profile % u64::BITS as usize)) != 0)
    }
}

/// Importer details for one file that directly imports a target module.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DirectImporterSummary {
    /// Source file that imports the requested target.
    pub source: FileId,
    /// Symbols imported from the target by this source file.
    pub symbols: Vec<ImportedSymbolSummary>,
}

/// Symbol details for a direct import edge.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ImportedSymbolSummary {
    /// Imported binding name, using `default`, `*`, and `side-effect` for
    /// non-named imports.
    pub imported: String,
    /// Local binding name in the importing file.
    pub local: String,
    /// Whether this symbol came from a type-only import.
    pub type_only: bool,
}

#[cfg(target_pointer_width = "64")]
const _: () = assert!(std::mem::size_of::<Edge>() == 32);
#[cfg(target_pointer_width = "64")]
const _: () = assert!(std::mem::size_of::<ImportedSymbol>() == 64);

#[cold]
#[inline(never)]
fn propagate_namespace_references(
    graph: &mut ModuleGraph,
    module_by_id: &FxHashMap<FileId, &ResolvedModule>,
    features: build::NamespaceFeatures,
    exposed_namespace_targets: &re_exports::ExposedNamespaceTargets,
    reference_paths: &mut ReferencePathInterner,
) {
    let indexes = namespace_indexes::NamespacePropagationIndexes::new(graph, module_by_id);
    if features.has_aliases {
        namespace_aliases::propagate_cross_package_aliases(
            graph,
            module_by_id,
            &indexes,
            reference_paths,
        );
    }
    if features.has_re_exports {
        namespace_re_exports::propagate_namespace_re_exports(
            graph,
            &indexes,
            exposed_namespace_targets,
            reference_paths,
        );
    }
}

impl ModuleGraph {
    fn resolve_entry_point_ids(
        entry_points: &[EntryPoint],
        path_to_id: &FxHashMap<&Path, FileId>,
    ) -> FxHashSet<FileId> {
        entry_points
            .iter()
            .filter_map(|ep| {
                path_to_id.get(ep.path.as_path()).copied().or_else(|| {
                    dunce::canonicalize(&ep.path)
                        .ok()
                        .and_then(|path| path_to_id.get(path.as_path()).copied())
                })
            })
            .collect()
    }

    /// Build the module graph from resolved modules and entry points.
    pub fn build(
        resolved_modules: &[ResolvedModule],
        entry_points: &[EntryPoint],
        files: &[DiscoveredFile],
    ) -> Self {
        Self::build_with_reachability_roots(
            resolved_modules,
            entry_points,
            entry_points,
            &[],
            files,
        )
    }

    /// Build the module graph with explicit runtime and test reachability roots.
    pub fn build_with_reachability_roots(
        resolved_modules: &[ResolvedModule],
        entry_points: &[EntryPoint],
        runtime_entry_points: &[EntryPoint],
        test_entry_points: &[EntryPoint],
        files: &[DiscoveredFile],
    ) -> Self {
        Self::build_with_reachability_roots_and_replacements(
            resolved_modules,
            &[],
            entry_points,
            runtime_entry_points,
            test_entry_points,
            files,
        )
    }

    /// Build the module graph with root-specific test-time module replacements.
    pub fn build_with_reachability_roots_and_replacements(
        resolved_modules: &[ResolvedModule],
        replaced_module_targets: &[ResolvedReplacedModuleTarget],
        entry_points: &[EntryPoint],
        runtime_entry_points: &[EntryPoint],
        test_entry_points: &[EntryPoint],
        files: &[DiscoveredFile],
    ) -> Self {
        let _span = tracing::info_span!("build_graph").entered();

        let module_count = files.len();

        let max_file_id = files
            .iter()
            .map(|f| f.id.0 as usize)
            .max()
            .map_or(0, |m| m + 1);
        let total_capacity = max_file_id.max(module_count);

        let path_to_id: FxHashMap<&Path, FileId> =
            files.iter().map(|f| (f.path.as_path(), f.id)).collect();

        let module_by_id: FxHashMap<FileId, &ResolvedModule> =
            resolved_modules.iter().map(|m| (m.file_id, m)).collect();

        let mut entry_point_ids = Self::resolve_entry_point_ids(entry_points, &path_to_id);
        let runtime_entry_point_ids =
            Self::resolve_entry_point_ids(runtime_entry_points, &path_to_id);
        let test_entry_point_ids = Self::resolve_entry_point_ids(test_entry_points, &path_to_id);

        for file in files {
            if is_declaration_file_path(&file.path) {
                entry_point_ids.insert(file.id);
            }
        }

        let (mut graph, namespace_features) = Self::populate_edges(&build::PopulateEdgesInput {
            files,
            module_by_id: &module_by_id,
            entry_point_ids: &entry_point_ids,
            runtime_entry_point_ids: &runtime_entry_point_ids,
            test_entry_point_ids: &test_entry_point_ids,
            module_count,
            total_capacity,
        });
        graph.effective_exports = effective_exports::EffectiveExportIndex::build(resolved_modules);

        let test_reachability_plan = reachability::TestReachabilityPlan::new(
            &test_entry_point_ids,
            replaced_module_targets,
            total_capacity,
        );

        let mut reference_paths =
            ReferencePathInterner::new(test_reachability_plan.requires_reference_provenance());
        let whole_module_targets =
            graph.populate_references(&module_by_id, &entry_point_ids, &mut reference_paths);
        // Entry-point reachability depends on edges alone, so it is available
        // here and is reused verbatim by `mark_reachable` below. The exposed
        // namespace closure needs it to stay off modules the report already
        // calls unused files.
        let entry_reachable = graph.collect_reachable(&entry_point_ids, total_capacity);
        let exposed_namespace_targets = graph.collect_exposed_namespace_targets(
            &whole_module_targets,
            &entry_reachable,
            &module_by_id,
        );

        if namespace_features.has_aliases || namespace_features.has_re_exports {
            propagate_namespace_references(
                &mut graph,
                &module_by_id,
                namespace_features,
                &exposed_namespace_targets,
                &mut reference_paths,
            );
        }

        graph.mark_reachable(
            &entry_reachable,
            &entry_point_ids,
            &runtime_entry_point_ids,
            test_reachability_plan,
            total_capacity,
        );

        graph.re_export_cycles = graph.resolve_re_export_chains(
            &module_by_id,
            &exposed_namespace_targets,
            &mut reference_paths,
        );
        let finalized_paths = reference_paths.finalize(&mut graph.modules);
        graph.reference_paths = finalized_paths.paths;
        graph.reference_routes = finalized_paths.routes;

        graph
    }

    /// Total number of modules.
    #[must_use]
    pub const fn module_count(&self) -> usize {
        self.modules.len()
    }

    /// Total number of edges.
    #[must_use]
    pub const fn edge_count(&self) -> usize {
        self.edges.len()
    }

    /// Return whether any test-root traversal reaches `file_id`.
    #[must_use]
    pub fn is_test_reachable(&self, file_id: FileId) -> bool {
        self.modules
            .get(file_id.0 as usize)
            .is_some_and(ModuleNode::is_test_reachable)
    }

    /// Return whether one test-root traversal covers the export reference at
    /// `reference_index` on `export`.
    ///
    /// Coverage requires one profile that reaches the referencing file and
    /// every target hop. ESM hops also require that profile not to replace the
    /// hop target; CommonJS hops remain active because Vitest replacement mocks
    /// do not intercept `require()`.
    #[must_use]
    pub fn is_test_reference_covered(&self, export: &ExportSymbol, reference_index: usize) -> bool {
        let Some(reference) = export.references.get(reference_index) else {
            return false;
        };
        if self.test_reachability_index.profile_count == 0 {
            return self.is_test_reachable(reference.from_file);
        }

        let Some(path) = export.reference_path(reference_index) else {
            return false;
        };

        self.test_reachability_index.covers_reference_path(
            reference.from_file,
            path,
            &self.reference_paths,
            &self.reference_routes,
        )
    }

    /// Return whether any reference on `export` is covered by a test-root
    /// traversal.
    #[must_use]
    pub fn is_any_test_reference_covered(&self, export: &ExportSymbol) -> bool {
        (0..export.references.len())
            .any(|reference_index| self.is_test_reference_covered(export, reference_index))
    }

    #[cfg(test)]
    fn reference_path_hops(
        &self,
        export: &ExportSymbol,
        reference_index: usize,
    ) -> Vec<(FileId, ModuleLoadMechanism)> {
        let mut hops = Vec::new();
        let mut next = export.reference_path(reference_index);
        while let Some(path_id) = next {
            let Some(node) = self.reference_paths.get(path_id.index()) else {
                return Vec::new();
            };
            next = node.parent();
            match *node {
                ReferencePathNode::Hop {
                    target, mechanism, ..
                } => hops.push((target, mechanism)),
                ReferencePathNode::Route {
                    graph,
                    start,
                    terminal,
                    start_mechanism,
                    ..
                } => hops.extend(self.reference_routes.canonical_hops(
                    graph,
                    start,
                    terminal,
                    start_mechanism,
                )),
            }
        }
        hops
    }

    /// Rebuild the `namespace_imported` bitset from the edge set.
    ///
    /// `namespace_imported` is `#[serde(skip)]`, so a graph loaded from the
    /// persisted cache (`crate::cache`) arrives with an empty default bitset.
    /// This restores it by replicating the EXACT insertion rule from
    /// `build.rs`: a target `FileId` is namespace-imported iff some edge to it
    /// carries an `ImportedName::Namespace` symbol. Both build-time insertion
    /// sites (static / dynamic `import * as ns` in `collect_import_edge`, and
    /// glob dynamic-import patterns in `collect_edges_for_module`) push a
    /// `Namespace` symbol onto the target's edge, so iterating the persisted
    /// edges and checking for a `Namespace` symbol reproduces the original
    /// bitset bit-for-bit. The capacity matches `build.rs`'s
    /// `max_file_id.max(module_count)`, which equals `modules.len()` under the
    /// dense path-sorted FileId invariant.
    pub(crate) fn reconstruct_namespace_imported(&mut self) {
        let capacity = self
            .edges
            .iter()
            .map(|edge| edge.target.0 as usize + 1)
            .max()
            .unwrap_or(0)
            .max(self.modules.len());
        let mut bitset = FixedBitSet::with_capacity(capacity);
        for edge in &self.edges {
            if edge
                .symbols
                .iter()
                .any(|sym| matches!(sym.imported_name, ImportedName::Namespace))
            {
                let idx = edge.target.0 as usize;
                if idx < capacity {
                    bitset.insert(idx);
                }
            }
        }
        self.namespace_imported = bitset;
    }

    /// Resolve the effective declaration exported under `name` in one namespace.
    ///
    /// This is the canonical graph contract for direct exports and every named
    /// or star re-export path. Missing and ambiguous bindings are explicit so
    /// consumers cannot accidentally credit an arbitrary source declaration.
    #[must_use]
    pub fn resolve_export(
        &self,
        file_id: FileId,
        name: &str,
        namespace: ExportNamespace,
    ) -> EffectiveExportResolution {
        self.effective_exports.resolve(file_id, name, namespace)
    }

    /// Whether two effective bindings denote the same declaration surface.
    ///
    /// TypeScript declaration merges occupy separate export slots while
    /// representing one symbol. Consumers that compare type and value lanes
    /// use this instead of raw binding equality so either half can carry the
    /// reference credit for the merged declaration.
    #[must_use]
    pub fn effective_bindings_share_declaration_group(
        &self,
        left: EffectiveExportBinding,
        right: EffectiveExportBinding,
    ) -> bool {
        if left == right || left.origin_file() != right.origin_file() {
            return left == right;
        }
        let Some(right_slot) = right.origin_slot() else {
            return false;
        };
        self.effective_exports
            .declaration_group_slots(left)
            .contains(&right_slot)
    }

    /// Resolve one exported name to its unique direct declaration.
    ///
    /// Missing and ambiguous bindings return `None`. Namespace-object exports
    /// are bindings in their own right rather than direct declarations, so
    /// they also have no declaration origin.
    #[must_use]
    pub fn resolve_export_origin(
        &self,
        file_id: FileId,
        name: &str,
        namespace: ExportNamespace,
    ) -> Option<EffectiveExportOrigin<'_>> {
        let EffectiveExportResolution::Unique(binding) =
            self.resolve_export(file_id, name, namespace)
        else {
            return None;
        };
        self.export_binding_origin(binding)
    }

    /// Resolve one module surface to its canonical binding and reference-bearing
    /// graph export. Value and type namespaces are selected independently.
    #[must_use]
    pub fn effective_export_surface(
        &self,
        file_id: FileId,
        name: &str,
        namespace: ExportNamespace,
    ) -> Option<EffectiveExportSurface<'_>> {
        let EffectiveExportResolution::Unique(binding) =
            self.resolve_export(file_id, name, namespace)
        else {
            return None;
        };
        let module = self.modules.get(file_id.0 as usize)?;
        let exact_surface = module.exports.iter().find(|export| {
            export.name.matches_str(name)
                && match namespace {
                    ExportNamespace::Type => export.is_type_only,
                    ExportNamespace::Value => !export.is_type_only,
                }
        });
        let surface_export = exact_surface.or_else(|| {
            module
                .exports
                .iter()
                .find(|export| export.name.matches_str(name))
        });
        let origin = self.export_binding_origin(binding);
        let export = surface_export.or_else(|| origin.map(|o| o.export));
        Some(EffectiveExportSurface {
            binding,
            namespace,
            export,
            origin,
            local_export: surface_export.is_some(),
        })
    }

    /// Local re-export specifier that owns one effective module surface.
    ///
    /// Direct declarations and star-only forwarded surfaces return `None`.
    /// Named and namespace re-exports return the namespace-compatible edge
    /// whose source resolves to the same canonical binding.
    #[must_use]
    pub fn effective_export_surface_re_export(
        &self,
        file_id: FileId,
        name: &str,
        namespace: ExportNamespace,
    ) -> Option<&ReExportEdge> {
        let EffectiveExportResolution::Unique(binding) =
            self.resolve_export(file_id, name, namespace)
        else {
            return None;
        };
        self.modules
            .get(file_id.0 as usize)?
            .re_exports
            .iter()
            .find(|re_export| {
                re_export.exported_name == name
                    && (namespace == ExportNamespace::Type || !re_export.is_type_only)
                    && if re_export.imported_name == "*" {
                        binding.namespace_source() == Some(re_export.source_file)
                    } else {
                        self.resolve_export(
                            re_export.source_file,
                            &re_export.imported_name,
                            namespace,
                        ) == EffectiveExportResolution::Unique(binding)
                    }
            })
    }

    /// References that reach one exact module export surface.
    ///
    /// Star-only surfaces share their declaration with other barrels, so their
    /// origin references are filtered by recorded provenance instead of being
    /// borrowed wholesale from the declaration.
    #[must_use]
    pub fn effective_export_surface_references(
        &self,
        file_id: FileId,
        name: &str,
        namespace: ExportNamespace,
    ) -> Vec<&SymbolReference> {
        let Some(surface) = self.effective_export_surface(file_id, name, namespace) else {
            return Vec::new();
        };
        let Some(export) = surface.export() else {
            return Vec::new();
        };
        if surface.local_export
            || surface
                .origin()
                .is_none_or(|origin| origin.file_id() == file_id)
        {
            return export.references_in(namespace).collect();
        }
        let mut exposed: FxHashMap<FileId, FxHashSet<String>> = FxHashMap::default();
        exposed.entry(file_id).or_default().insert(name.to_string());
        for route in self.effective_re_export_routes(file_id, name, namespace) {
            exposed
                .entry(route.barrel_file())
                .or_default()
                .insert(route.exported_name().to_string());
        }
        export
            .references
            .iter()
            .filter(|reference| {
                reference.namespace == namespace
                    && self.reference_reaches_surface(reference, &exposed, namespace)
            })
            .collect()
    }

    fn reference_reaches_surface(
        &self,
        reference: &SymbolReference,
        exposed: &FxHashMap<FileId, FxHashSet<String>>,
        namespace: ExportNamespace,
    ) -> bool {
        if reference.kind == ReferenceKind::ReExport && exposed.contains_key(&reference.from_file) {
            return true;
        }
        self.outgoing_symbol_edges(reference.from_file)
            .any(|(target, symbols)| {
                let Some(names) = exposed.get(&target) else {
                    return false;
                };
                symbols.iter().any(|symbol| {
                    symbol.import_span == reference.import_span
                        && (namespace == ExportNamespace::Type
                            || !symbol.is_type_only
                            || symbol.is_value_bearing_ambient_star())
                        && match &symbol.imported_name {
                            ImportedName::Named(imported) => names.contains(imported.as_str()),
                            ImportedName::Default => names.contains("default"),
                            ImportedName::Namespace => true,
                            ImportedName::SideEffect => false,
                        }
                })
            })
    }

    /// Resolve a unique binding to its direct declaration, when it has one.
    #[must_use]
    pub fn export_binding_origin(
        &self,
        binding: EffectiveExportBinding,
    ) -> Option<EffectiveExportOrigin<'_>> {
        let origin_file = binding.origin_file();
        let export = self
            .modules
            .get(origin_file.0 as usize)?
            .exports
            .get(binding.origin_slot()?)?;
        Some(EffectiveExportOrigin {
            file_id: origin_file,
            export,
        })
    }

    /// Unique bindings exposed by a module in one namespace.
    ///
    /// Multiple names that resolve to the same declaration are deduplicated;
    /// missing and ambiguous exports are excluded.
    #[must_use]
    pub fn unique_export_bindings(
        &self,
        file_id: FileId,
        namespace: ExportNamespace,
    ) -> FxHashSet<EffectiveExportBinding> {
        self.effective_exports.unique_bindings(file_id, namespace)
    }

    /// Whether `importer` connects to `source` as an origin of `name`.
    ///
    /// Any direct import connects the two modules for duplicate-export
    /// grouping, even when it imports a different symbol. A re-export-only edge
    /// connects them only when it contributes this binding, including each
    /// contributor to an ambiguous star export and excluding star bindings
    /// shadowed by an explicit export.
    #[must_use]
    pub fn importer_connects_export_origin(
        &self,
        importer: FileId,
        source: FileId,
        name: &str,
        namespace: ExportNamespace,
    ) -> bool {
        let Some(importer_module) = self.modules.get(importer.0 as usize) else {
            return false;
        };
        let re_export_count = importer_module
            .re_exports
            .iter()
            .filter(|re_export| re_export.source_file == source)
            .count();
        if self.edges[importer_module.edge_range.clone()]
            .iter()
            .any(|edge| edge.target == source && edge.symbols.len() > re_export_count)
        {
            return true;
        }

        importer_module.re_exports.iter().any(|re_export| {
            if re_export.source_file != source
                || (namespace == ExportNamespace::Value && re_export.is_type_only)
            {
                return false;
            }
            let exported_name = if re_export.imported_name == "*" {
                if re_export.exported_name != "*" || name == "default" {
                    return false;
                }
                name
            } else {
                if re_export.imported_name != name {
                    return false;
                }
                &re_export.exported_name
            };
            self.effective_exports.contributes_through(
                importer,
                exported_name,
                source,
                name,
                namespace,
            )
        })
    }

    /// Check if any importer uses `import * as ns` for this module.
    /// Uses precomputed bitset, O(1) lookup.
    #[must_use]
    pub fn has_namespace_import(&self, file_id: FileId) -> bool {
        let idx = file_id.0 as usize;
        if idx >= self.namespace_imported.len() {
            return false;
        }
        self.namespace_imported.contains(idx)
    }

    /// Get the target `FileId`s of all outgoing edges for a module.
    #[must_use]
    pub fn edges_for(&self, file_id: FileId) -> Vec<FileId> {
        let idx = file_id.0 as usize;
        if idx >= self.modules.len() {
            return Vec::new();
        }
        let range = &self.modules[idx].edge_range;
        self.edges[range.clone()].iter().map(|e| e.target).collect()
    }

    /// Iterate the outgoing edges of `file_id` with full per-symbol data.
    ///
    /// `fallow trace` needs the raw `ImportedSymbol` set on each edge in
    /// both directions, which the flattened summary structs cannot express.
    /// Returns an empty iterator for out-of-range file ids.
    pub fn outgoing_symbol_edges(
        &self,
        file_id: FileId,
    ) -> impl Iterator<Item = (FileId, &[ImportedSymbol])> + '_ {
        let idx = file_id.0 as usize;
        let range = if idx < self.modules.len() {
            self.modules[idx].edge_range.clone()
        } else {
            0..0
        };
        self.edges[range]
            .iter()
            .map(|edge| (edge.target, edge.symbols.as_slice()))
    }

    /// The importer `FileId`s that directly import `target` (reverse-dep view).
    ///
    /// Returns an empty slice when `target` is out of range.
    #[must_use]
    pub fn importers_of(&self, target: FileId) -> &[FileId] {
        self.reverse_deps
            .get(target.0 as usize)
            .map_or(&[], Vec::as_slice)
    }

    /// Summarize files that directly import `target`.
    ///
    /// Uses existing reverse dependency and edge indexes. Returns an empty
    /// list when the target is out of range or has no importers.
    #[must_use]
    pub fn direct_importer_summaries(&self, target: FileId) -> Vec<DirectImporterSummary> {
        let Some(importers) = self.reverse_deps.get(target.0 as usize) else {
            return Vec::new();
        };

        let mut summaries = Vec::new();
        for &source in importers {
            let idx = source.0 as usize;
            let Some(source_node) = self.modules.get(idx) else {
                continue;
            };
            let mut symbols = Vec::new();
            for edge in &self.edges[source_node.edge_range.clone()] {
                if edge.target != target {
                    continue;
                }
                symbols.extend(edge.symbols.iter().map(|symbol| ImportedSymbolSummary {
                    imported: imported_name_label(&symbol.imported_name),
                    local: symbol.local_name.clone(),
                    type_only: symbol.is_type_only,
                }));
            }
            symbols.sort_by(|a, b| {
                a.imported
                    .cmp(&b.imported)
                    .then_with(|| a.local.cmp(&b.local))
                    .then_with(|| a.type_only.cmp(&b.type_only))
            });
            symbols.dedup();
            summaries.push(DirectImporterSummary { source, symbols });
        }
        summaries.sort_by_key(|summary| summary.source.0);
        summaries
    }

    /// Find the byte offset of the import statement from `source` to `target`.
    ///
    /// Mixed type/value imports to the same target are stored as one edge. Prefer
    /// the first value-carrying import so runtime-cycle diagnostics and line
    /// suppressions anchor on the import that actually participates in the cycle.
    /// Returns `None` if no edge exists or the edge has no symbols.
    #[must_use]
    pub fn find_import_span_start(&self, source: FileId, target: FileId) -> Option<u32> {
        let idx = source.0 as usize;
        if idx >= self.modules.len() {
            return None;
        }
        let range = &self.modules[idx].edge_range;
        for edge in &self.edges[range.clone()] {
            if edge.target == target {
                return edge
                    .symbols
                    .iter()
                    .find(|s| !s.is_type_only)
                    .or_else(|| edge.symbols.first())
                    .map(|s| s.import_span.start);
            }
        }
        None
    }

    /// Iterate outgoing edges with the data the boundary detector needs in a
    /// single pass: target file id, whether every symbol on the edge is
    /// type-only (matches the predicate used by cycle detection), and the
    /// span start of the first value-carrying symbol (or the first symbol
    /// when every symbol is type-only).
    ///
    /// When `featureB` has both `import type { Foo } from './x'` and
    /// `import { bar } from './x'`, fallow groups them into ONE edge with the
    /// type-only symbol first and the value symbol second. Consumers need the
    /// value span so findings anchor on the runtime import line; otherwise a
    /// `// fallow-ignore-next-line` above the type-only line would silently
    /// suppress the real violation.
    ///
    /// Returns an empty iterator for out-of-range file ids.
    pub fn outgoing_edge_summaries(
        &self,
        file_id: FileId,
    ) -> impl Iterator<Item = (FileId, bool, Option<u32>)> + '_ {
        let idx = file_id.0 as usize;
        let range = if idx < self.modules.len() {
            self.modules[idx].edge_range.clone()
        } else {
            0..0
        };
        self.edges[range].iter().map(|edge| {
            let all_type_only =
                !edge.symbols.is_empty() && edge.symbols.iter().all(|s| s.is_type_only);
            let span = edge
                .symbols
                .iter()
                .find(|s| !s.is_type_only)
                .or_else(|| edge.symbols.first())
                .map(|s| s.import_span.start);
            (edge.target, all_type_only, span)
        })
    }

    /// Like [`Self::outgoing_edge_summaries`] but additionally reports, as a
    /// fourth boolean, whether EVERY non-type-only symbol on the edge has an
    /// `import_span` start in `excluded_span_starts` (`all_client_only`). The
    /// security `client-server-leak` BFS passes the `next/dynamic ssr:false`
    /// dynamic-import span starts so it can skip an edge reached ONLY through the
    /// client-only escape hatch. An edge with no non-type-only symbols, or with at
    /// least one non-type-only symbol whose span is not excluded, reports `false`
    /// (so a target also reached via a real static import stays in the cone).
    ///
    /// Returns an empty iterator for out-of-range file ids.
    pub fn outgoing_edge_summaries_with_exclusions<'a>(
        &'a self,
        file_id: FileId,
        excluded_span_starts: &'a FxHashSet<u32>,
    ) -> impl Iterator<Item = (FileId, bool, Option<u32>, bool)> + 'a {
        let idx = file_id.0 as usize;
        let range = if idx < self.modules.len() {
            self.modules[idx].edge_range.clone()
        } else {
            0..0
        };
        self.edges[range].iter().map(move |edge| {
            let all_type_only =
                !edge.symbols.is_empty() && edge.symbols.iter().all(|s| s.is_type_only);
            let span = edge
                .symbols
                .iter()
                .find(|s| !s.is_type_only)
                .or_else(|| edge.symbols.first())
                .map(|s| s.import_span.start);
            // `all_client_only`: there is at least one non-type-only symbol and
            // every such symbol's import span is in the excluded set. A
            // non-excluded value symbol keeps the edge live.
            let mut value_symbols = edge.symbols.iter().filter(|s| !s.is_type_only).peekable();
            let all_client_only = value_symbols.peek().is_some()
                && value_symbols.all(|s| excluded_span_starts.contains(&s.import_span.start));
            (edge.target, all_type_only, span, all_client_only)
        })
    }
}

fn imported_name_label(name: &ImportedName) -> String {
    match name {
        ImportedName::Named(name) => name.clone(),
        ImportedName::Default => "default".to_string(),
        ImportedName::Namespace => "*".to_string(),
        ImportedName::SideEffect => "side-effect".to_string(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::resolve::{ResolveResult, ResolvedImport, ResolvedModule};
    use fallow_types::discover::{DiscoveredFile, EntryPoint, EntryPointSource, FileId};
    use fallow_types::extract::{ExportName, ImportInfo, ImportedName, VisibilityTag};
    use std::path::PathBuf;

    fn build_simple_graph() -> ModuleGraph {
        let files = vec![
            DiscoveredFile {
                id: FileId(0),
                path: PathBuf::from("/project/src/entry.ts"),
                size_bytes: 100,
            },
            DiscoveredFile {
                id: FileId(1),
                path: PathBuf::from("/project/src/utils.ts"),
                size_bytes: 50,
            },
        ];

        let entry_points = vec![EntryPoint {
            path: PathBuf::from("/project/src/entry.ts"),
            source: EntryPointSource::PackageJsonMain,
        }];

        let resolved_modules = vec![
            ResolvedModule {
                file_id: FileId(0),
                path: PathBuf::from("/project/src/entry.ts"),
                resolved_imports: vec![ResolvedImport {
                    info: ImportInfo {
                        source: "./utils".to_string(),
                        imported_name: ImportedName::Named("foo".to_string()),
                        local_name: "foo".to_string(),
                        is_type_only: false,
                        is_type_only_star: false,
                        from_style: false,
                        span: oxc_span::Span::new(0, 10),
                        source_span: oxc_span::Span::default(),
                    },
                    target: ResolveResult::InternalModule(FileId(1)),
                }],
                ..Default::default()
            },
            ResolvedModule {
                file_id: FileId(1),
                path: PathBuf::from("/project/src/utils.ts"),
                exports: vec![
                    fallow_types::extract::ExportInfo {
                        name: ExportName::Named("foo".to_string()),
                        local_name: Some("foo".to_string()),
                        is_type_only: false,
                        visibility: VisibilityTag::None,
                        expected_unused_reason: None,
                        span: oxc_span::Span::new(0, 20),
                        members: vec![],
                        is_side_effect_used: false,
                        super_class: None,
                    },
                    fallow_types::extract::ExportInfo {
                        name: ExportName::Named("bar".to_string()),
                        local_name: Some("bar".to_string()),
                        is_type_only: false,
                        visibility: VisibilityTag::None,
                        expected_unused_reason: None,
                        span: oxc_span::Span::new(25, 45),
                        members: vec![],
                        is_side_effect_used: false,
                        super_class: None,
                    },
                ]
                .into(),
                ..Default::default()
            },
        ];

        ModuleGraph::build(&resolved_modules, &entry_points, &files)
    }

    #[test]
    fn graph_module_count() {
        let graph = build_simple_graph();
        assert_eq!(graph.module_count(), 2);
    }

    #[test]
    fn graph_edge_count() {
        let graph = build_simple_graph();
        assert_eq!(graph.edge_count(), 1);
    }

    #[test]
    fn graph_entry_point_is_reachable() {
        let graph = build_simple_graph();
        assert!(graph.modules[0].is_entry_point());
        assert!(graph.modules[0].is_reachable());
    }

    #[test]
    fn graph_imported_module_is_reachable() {
        let graph = build_simple_graph();
        assert!(!graph.modules[1].is_entry_point());
        assert!(graph.modules[1].is_reachable());
    }

    #[test]
    #[expect(
        clippy::too_many_lines,
        reason = "this test fixture exercises four reachability roles end-to-end; splitting it \
                  would obscure the cross-role assertions"
    )]
    fn graph_distinguishes_runtime_test_and_support_reachability() {
        let files = vec![
            DiscoveredFile {
                id: FileId(0),
                path: PathBuf::from("/project/src/main.ts"),
                size_bytes: 100,
            },
            DiscoveredFile {
                id: FileId(1),
                path: PathBuf::from("/project/src/runtime-only.ts"),
                size_bytes: 50,
            },
            DiscoveredFile {
                id: FileId(2),
                path: PathBuf::from("/project/tests/app.test.ts"),
                size_bytes: 50,
            },
            DiscoveredFile {
                id: FileId(3),
                path: PathBuf::from("/project/tests/setup.ts"),
                size_bytes: 50,
            },
            DiscoveredFile {
                id: FileId(4),
                path: PathBuf::from("/project/src/covered.ts"),
                size_bytes: 50,
            },
        ];

        let all_entry_points = vec![
            EntryPoint {
                path: PathBuf::from("/project/src/main.ts"),
                source: EntryPointSource::PackageJsonMain,
            },
            EntryPoint {
                path: PathBuf::from("/project/tests/app.test.ts"),
                source: EntryPointSource::TestFile,
            },
            EntryPoint {
                path: PathBuf::from("/project/tests/setup.ts"),
                source: EntryPointSource::Plugin {
                    name: "vitest".to_string(),
                },
            },
        ];
        let runtime_entry_points = vec![EntryPoint {
            path: PathBuf::from("/project/src/main.ts"),
            source: EntryPointSource::PackageJsonMain,
        }];
        let test_entry_points = vec![EntryPoint {
            path: PathBuf::from("/project/tests/app.test.ts"),
            source: EntryPointSource::TestFile,
        }];

        let resolved_modules = vec![
            ResolvedModule {
                file_id: FileId(0),
                path: PathBuf::from("/project/src/main.ts"),
                resolved_imports: vec![ResolvedImport {
                    info: ImportInfo {
                        source: "./runtime-only".to_string(),
                        imported_name: ImportedName::Named("runtimeOnly".to_string()),
                        local_name: "runtimeOnly".to_string(),
                        is_type_only: false,
                        is_type_only_star: false,
                        from_style: false,
                        span: oxc_span::Span::new(0, 10),
                        source_span: oxc_span::Span::default(),
                    },
                    target: ResolveResult::InternalModule(FileId(1)),
                }],
                ..Default::default()
            },
            ResolvedModule {
                file_id: FileId(1),
                path: PathBuf::from("/project/src/runtime-only.ts"),
                exports: vec![fallow_types::extract::ExportInfo {
                    name: ExportName::Named("runtimeOnly".to_string()),
                    local_name: Some("runtimeOnly".to_string()),
                    is_type_only: false,
                    visibility: VisibilityTag::None,
                    expected_unused_reason: None,
                    span: oxc_span::Span::new(0, 20),
                    members: vec![],
                    is_side_effect_used: false,
                    super_class: None,
                }]
                .into(),
                ..Default::default()
            },
            ResolvedModule {
                file_id: FileId(2),
                path: PathBuf::from("/project/tests/app.test.ts"),
                resolved_imports: vec![ResolvedImport {
                    info: ImportInfo {
                        source: "../src/covered".to_string(),
                        imported_name: ImportedName::Named("covered".to_string()),
                        local_name: "covered".to_string(),
                        is_type_only: false,
                        is_type_only_star: false,
                        from_style: false,
                        span: oxc_span::Span::new(0, 10),
                        source_span: oxc_span::Span::default(),
                    },
                    target: ResolveResult::InternalModule(FileId(4)),
                }],
                ..Default::default()
            },
            ResolvedModule {
                file_id: FileId(3),
                path: PathBuf::from("/project/tests/setup.ts"),
                resolved_imports: vec![ResolvedImport {
                    info: ImportInfo {
                        source: "../src/runtime-only".to_string(),
                        imported_name: ImportedName::Named("runtimeOnly".to_string()),
                        local_name: "runtimeOnly".to_string(),
                        is_type_only: false,
                        is_type_only_star: false,
                        from_style: false,
                        span: oxc_span::Span::new(0, 10),
                        source_span: oxc_span::Span::default(),
                    },
                    target: ResolveResult::InternalModule(FileId(1)),
                }],
                ..Default::default()
            },
            ResolvedModule {
                file_id: FileId(4),
                path: PathBuf::from("/project/src/covered.ts"),
                exports: vec![fallow_types::extract::ExportInfo {
                    name: ExportName::Named("covered".to_string()),
                    local_name: Some("covered".to_string()),
                    is_type_only: false,
                    visibility: VisibilityTag::None,
                    expected_unused_reason: None,
                    span: oxc_span::Span::new(0, 20),
                    members: vec![],
                    is_side_effect_used: false,
                    super_class: None,
                }]
                .into(),
                ..Default::default()
            },
        ];

        let graph = ModuleGraph::build_with_reachability_roots(
            &resolved_modules,
            &all_entry_points,
            &runtime_entry_points,
            &test_entry_points,
            &files,
        );

        assert!(graph.modules[1].is_reachable());
        assert!(graph.modules[1].is_runtime_reachable());
        assert!(
            !graph.modules[1].is_test_reachable(),
            "support roots should not make runtime-only modules test reachable"
        );

        assert!(graph.modules[4].is_reachable());
        assert!(graph.modules[4].is_test_reachable());
        assert!(
            !graph.modules[4].is_runtime_reachable(),
            "test-only reachability should stay separate from runtime roots"
        );
    }

    #[test]
    fn graph_export_has_reference() {
        let graph = build_simple_graph();
        let utils = &graph.modules[1];
        let foo_export = utils
            .exports
            .iter()
            .find(|e| e.name.to_string() == "foo")
            .unwrap();
        assert!(
            !foo_export.references.is_empty(),
            "foo should have references"
        );
    }

    #[test]
    fn graph_unused_export_no_reference() {
        let graph = build_simple_graph();
        let utils = &graph.modules[1];
        let bar_export = utils
            .exports
            .iter()
            .find(|e| e.name.to_string() == "bar")
            .unwrap();
        assert!(
            bar_export.references.is_empty(),
            "bar should have no references"
        );
    }

    #[test]
    fn graph_no_namespace_import() {
        let graph = build_simple_graph();
        assert!(!graph.has_namespace_import(FileId(0)));
        assert!(!graph.has_namespace_import(FileId(1)));
    }

    #[test]
    fn graph_has_namespace_import() {
        let files = vec![
            DiscoveredFile {
                id: FileId(0),
                path: PathBuf::from("/project/entry.ts"),
                size_bytes: 100,
            },
            DiscoveredFile {
                id: FileId(1),
                path: PathBuf::from("/project/utils.ts"),
                size_bytes: 50,
            },
        ];

        let entry_points = vec![EntryPoint {
            path: PathBuf::from("/project/entry.ts"),
            source: EntryPointSource::PackageJsonMain,
        }];

        let resolved_modules = vec![
            ResolvedModule {
                file_id: FileId(0),
                path: PathBuf::from("/project/entry.ts"),
                resolved_imports: vec![ResolvedImport {
                    info: ImportInfo {
                        source: "./utils".to_string(),
                        imported_name: ImportedName::Namespace,
                        local_name: "utils".to_string(),
                        is_type_only: false,
                        is_type_only_star: false,
                        from_style: false,
                        span: oxc_span::Span::new(0, 10),
                        source_span: oxc_span::Span::default(),
                    },
                    target: ResolveResult::InternalModule(FileId(1)),
                }],
                ..Default::default()
            },
            ResolvedModule {
                file_id: FileId(1),
                path: PathBuf::from("/project/utils.ts"),
                exports: vec![fallow_types::extract::ExportInfo {
                    name: ExportName::Named("foo".to_string()),
                    local_name: Some("foo".to_string()),
                    is_type_only: false,
                    visibility: VisibilityTag::None,
                    expected_unused_reason: None,
                    span: oxc_span::Span::new(0, 20),
                    members: vec![],
                    is_side_effect_used: false,
                    super_class: None,
                }]
                .into(),
                ..Default::default()
            },
        ];

        let graph = ModuleGraph::build(&resolved_modules, &entry_points, &files);
        assert!(
            graph.has_namespace_import(FileId(1)),
            "utils should have namespace import"
        );
    }

    #[test]
    fn graph_has_namespace_import_out_of_bounds() {
        let graph = build_simple_graph();
        assert!(!graph.has_namespace_import(FileId(999)));
    }

    /// The persisted graph cache skips `namespace_imported` and rebuilds it from
    /// the edge set on load. This asserts the reconstruction reproduces the
    /// fresh-built bitset BIT-FOR-BIT on a graph that exercises `import * as ns`,
    /// matching what `build.rs` records at build time.
    #[test]
    fn reconstruct_namespace_imported_matches_fresh_build() {
        let files = vec![
            DiscoveredFile {
                id: FileId(0),
                path: PathBuf::from("/project/entry.ts"),
                size_bytes: 100,
            },
            DiscoveredFile {
                id: FileId(1),
                path: PathBuf::from("/project/utils.ts"),
                size_bytes: 50,
            },
            DiscoveredFile {
                id: FileId(2),
                path: PathBuf::from("/project/named-only.ts"),
                size_bytes: 50,
            },
        ];
        let entry_points = vec![EntryPoint {
            path: PathBuf::from("/project/entry.ts"),
            source: EntryPointSource::PackageJsonMain,
        }];
        let resolved_modules = vec![
            ResolvedModule {
                file_id: FileId(0),
                path: PathBuf::from("/project/entry.ts"),
                resolved_imports: vec![
                    ResolvedImport {
                        info: ImportInfo {
                            source: "./utils".to_string(),
                            imported_name: ImportedName::Namespace,
                            local_name: "utils".to_string(),
                            is_type_only: false,
                            is_type_only_star: false,
                            from_style: false,
                            span: oxc_span::Span::new(0, 10),
                            source_span: oxc_span::Span::default(),
                        },
                        target: ResolveResult::InternalModule(FileId(1)),
                    },
                    ResolvedImport {
                        info: ImportInfo {
                            source: "./named-only".to_string(),
                            imported_name: ImportedName::Named("foo".to_string()),
                            local_name: "foo".to_string(),
                            is_type_only: false,
                            is_type_only_star: false,
                            from_style: false,
                            span: oxc_span::Span::new(11, 20),
                            source_span: oxc_span::Span::default(),
                        },
                        target: ResolveResult::InternalModule(FileId(2)),
                    },
                ],
                ..Default::default()
            },
            ResolvedModule {
                file_id: FileId(1),
                path: PathBuf::from("/project/utils.ts"),
                ..Default::default()
            },
            ResolvedModule {
                file_id: FileId(2),
                path: PathBuf::from("/project/named-only.ts"),
                exports: vec![fallow_types::extract::ExportInfo {
                    name: ExportName::Named("foo".to_string()),
                    local_name: Some("foo".to_string()),
                    is_type_only: false,
                    visibility: VisibilityTag::None,
                    expected_unused_reason: None,
                    span: oxc_span::Span::new(0, 20),
                    members: vec![],
                    is_side_effect_used: false,
                    super_class: None,
                }]
                .into(),
                ..Default::default()
            },
        ];

        let mut graph = ModuleGraph::build(&resolved_modules, &entry_points, &files);
        let fresh = graph.namespace_imported.clone();

        // Sanity: the namespace target is set, the named-only target is not.
        assert!(graph.has_namespace_import(FileId(1)));
        assert!(!graph.has_namespace_import(FileId(2)));

        // Simulate the cache load: the bitset arrives empty (serde-skipped), then
        // the loader reconstructs it from the persisted edges.
        graph.namespace_imported = FixedBitSet::default();
        graph.reconstruct_namespace_imported();

        assert_eq!(
            graph.namespace_imported, fresh,
            "reconstructed namespace_imported must equal the fresh-built bitset"
        );
        assert!(graph.has_namespace_import(FileId(1)));
        assert!(!graph.has_namespace_import(FileId(2)));
    }

    #[test]
    fn graph_unreachable_module() {
        let files = vec![
            DiscoveredFile {
                id: FileId(0),
                path: PathBuf::from("/project/entry.ts"),
                size_bytes: 100,
            },
            DiscoveredFile {
                id: FileId(1),
                path: PathBuf::from("/project/utils.ts"),
                size_bytes: 50,
            },
            DiscoveredFile {
                id: FileId(2),
                path: PathBuf::from("/project/orphan.ts"),
                size_bytes: 30,
            },
        ];

        let entry_points = vec![EntryPoint {
            path: PathBuf::from("/project/entry.ts"),
            source: EntryPointSource::PackageJsonMain,
        }];

        let resolved_modules = vec![
            ResolvedModule {
                file_id: FileId(0),
                path: PathBuf::from("/project/entry.ts"),
                resolved_imports: vec![ResolvedImport {
                    info: ImportInfo {
                        source: "./utils".to_string(),
                        imported_name: ImportedName::Named("foo".to_string()),
                        local_name: "foo".to_string(),
                        is_type_only: false,
                        is_type_only_star: false,
                        from_style: false,
                        span: oxc_span::Span::new(0, 10),
                        source_span: oxc_span::Span::default(),
                    },
                    target: ResolveResult::InternalModule(FileId(1)),
                }],
                ..Default::default()
            },
            ResolvedModule {
                file_id: FileId(1),
                path: PathBuf::from("/project/utils.ts"),
                exports: vec![fallow_types::extract::ExportInfo {
                    name: ExportName::Named("foo".to_string()),
                    local_name: Some("foo".to_string()),
                    is_type_only: false,
                    visibility: VisibilityTag::None,
                    expected_unused_reason: None,
                    span: oxc_span::Span::new(0, 20),
                    members: vec![],
                    is_side_effect_used: false,
                    super_class: None,
                }]
                .into(),
                ..Default::default()
            },
            ResolvedModule {
                file_id: FileId(2),
                path: PathBuf::from("/project/orphan.ts"),
                exports: vec![fallow_types::extract::ExportInfo {
                    name: ExportName::Named("orphan".to_string()),
                    local_name: Some("orphan".to_string()),
                    is_type_only: false,
                    visibility: VisibilityTag::None,
                    expected_unused_reason: None,
                    span: oxc_span::Span::new(0, 20),
                    members: vec![],
                    is_side_effect_used: false,
                    super_class: None,
                }]
                .into(),
                ..Default::default()
            },
        ];

        let graph = ModuleGraph::build(&resolved_modules, &entry_points, &files);

        assert!(graph.modules[0].is_reachable(), "entry should be reachable");
        assert!(graph.modules[1].is_reachable(), "utils should be reachable");
        assert!(
            !graph.modules[2].is_reachable(),
            "orphan should NOT be reachable"
        );
    }

    #[test]
    fn graph_package_usage_tracked() {
        let files = vec![DiscoveredFile {
            id: FileId(0),
            path: PathBuf::from("/project/entry.ts"),
            size_bytes: 100,
        }];

        let entry_points = vec![EntryPoint {
            path: PathBuf::from("/project/entry.ts"),
            source: EntryPointSource::PackageJsonMain,
        }];

        let resolved_modules = vec![ResolvedModule {
            file_id: FileId(0),
            path: PathBuf::from("/project/entry.ts"),
            exports: vec![].into(),
            re_exports: vec![],
            resolved_imports: vec![
                ResolvedImport {
                    info: ImportInfo {
                        source: "react".to_string(),
                        imported_name: ImportedName::Default,
                        local_name: "React".to_string(),
                        is_type_only: false,
                        is_type_only_star: false,
                        from_style: false,
                        span: oxc_span::Span::new(0, 10),
                        source_span: oxc_span::Span::default(),
                    },
                    target: ResolveResult::NpmPackage("react".to_string()),
                },
                ResolvedImport {
                    info: ImportInfo {
                        source: "lodash".to_string(),
                        imported_name: ImportedName::Named("merge".to_string()),
                        local_name: "merge".to_string(),
                        is_type_only: false,
                        is_type_only_star: false,
                        from_style: false,
                        span: oxc_span::Span::new(15, 30),
                        source_span: oxc_span::Span::default(),
                    },
                    target: ResolveResult::NpmPackage("lodash".to_string()),
                },
            ],
            ..Default::default()
        }];

        let graph = ModuleGraph::build(&resolved_modules, &entry_points, &files);
        assert!(graph.package_usage.contains_key("react"));
        assert!(graph.package_usage.contains_key("lodash"));
        assert!(!graph.package_usage.contains_key("express"));
    }

    #[test]
    fn graph_empty() {
        let graph = ModuleGraph::build(&[], &[], &[]);
        assert_eq!(graph.module_count(), 0);
        assert_eq!(graph.edge_count(), 0);
    }

    /// The persisted graph cache postcard-encodes the whole `ModuleGraph` and
    /// decodes it on a warm run. This proves the serde round-trip is lossless
    /// for the structural surface analysis reads: module / edge / export /
    /// reference counts and the `namespace_imported` bitset (reconstructed on
    /// load) all survive.
    #[test]
    fn graph_postcard_round_trip_is_lossless() {
        let graph = build_simple_graph();

        let encoded = postcard::to_allocvec(&graph).expect("encode graph");
        let mut decoded: ModuleGraph = postcard::from_bytes(&encoded).expect("decode graph");
        // The store does this on load; do it here so the bitset is restored.
        decoded.reconstruct_namespace_imported();

        assert_eq!(decoded.module_count(), graph.module_count());
        assert_eq!(decoded.edge_count(), graph.edge_count());
        assert_eq!(decoded.namespace_imported, graph.namespace_imported);

        // Export + reference + member surface survives byte-for-byte.
        let utils = &decoded.modules[1];
        let foo = utils
            .exports
            .iter()
            .find(|e| e.name.to_string() == "foo")
            .expect("foo export survives round-trip");
        assert!(!foo.references.is_empty());
        let bar = utils
            .exports
            .iter()
            .find(|e| e.name.to_string() == "bar")
            .expect("bar export survives round-trip");
        assert!(bar.references.is_empty());

        // Reachability flags and entry-point sets survive.
        assert!(decoded.modules[0].is_entry_point());
        assert!(decoded.modules[0].is_reachable());
        assert!(decoded.modules[1].is_reachable());
        assert_eq!(decoded.entry_points, graph.entry_points);
    }

    #[test]
    fn graph_cjs_exports_tracked() {
        let files = vec![DiscoveredFile {
            id: FileId(0),
            path: PathBuf::from("/project/entry.ts"),
            size_bytes: 100,
        }];

        let entry_points = vec![EntryPoint {
            path: PathBuf::from("/project/entry.ts"),
            source: EntryPointSource::PackageJsonMain,
        }];

        let resolved_modules = vec![ResolvedModule {
            file_id: FileId(0),
            path: PathBuf::from("/project/entry.ts"),
            has_cjs_exports: true,
            has_angular_component_template_url: false,
            ..Default::default()
        }];

        let graph = ModuleGraph::build(&resolved_modules, &entry_points, &files);
        assert!(graph.modules[0].has_cjs_exports());
    }

    #[test]
    fn graph_edges_for_returns_targets() {
        let graph = build_simple_graph();
        let targets = graph.edges_for(FileId(0));
        assert_eq!(targets, vec![FileId(1)]);
    }

    #[test]
    fn graph_edges_for_no_imports() {
        let graph = build_simple_graph();
        let targets = graph.edges_for(FileId(1));
        assert!(targets.is_empty());
    }

    #[test]
    fn graph_edges_for_out_of_bounds() {
        let graph = build_simple_graph();
        let targets = graph.edges_for(FileId(999));
        assert!(targets.is_empty());
    }

    #[test]
    fn graph_direct_importer_summaries_include_symbols() {
        let graph = build_simple_graph();
        let summaries = graph.direct_importer_summaries(FileId(1));

        assert_eq!(
            summaries,
            vec![DirectImporterSummary {
                source: FileId(0),
                symbols: vec![ImportedSymbolSummary {
                    imported: "foo".to_string(),
                    local: "foo".to_string(),
                    type_only: false,
                }],
            }]
        );
    }

    #[test]
    fn graph_find_import_span_start_found() {
        let graph = build_simple_graph();
        let span_start = graph.find_import_span_start(FileId(0), FileId(1));
        assert!(span_start.is_some());
        assert_eq!(span_start.unwrap(), 0);
    }

    #[test]
    fn graph_find_import_span_start_prefers_value_import_on_mixed_edge() {
        let files = vec![
            DiscoveredFile {
                id: FileId(0),
                path: PathBuf::from("/project/entry.ts"),
                size_bytes: 100,
            },
            DiscoveredFile {
                id: FileId(1),
                path: PathBuf::from("/project/utils.ts"),
                size_bytes: 50,
            },
        ];
        let entry_points = vec![EntryPoint {
            path: PathBuf::from("/project/entry.ts"),
            source: EntryPointSource::PackageJsonMain,
        }];
        let resolved_modules = vec![
            ResolvedModule {
                file_id: FileId(0),
                path: PathBuf::from("/project/entry.ts"),
                resolved_imports: vec![
                    ResolvedImport {
                        info: ImportInfo {
                            source: "./utils".to_string(),
                            imported_name: ImportedName::Named("Foo".to_string()),
                            local_name: "Foo".to_string(),
                            is_type_only: true,
                            is_type_only_star: false,
                            from_style: false,
                            span: oxc_span::Span::new(10, 20),
                            source_span: oxc_span::Span::default(),
                        },
                        target: ResolveResult::InternalModule(FileId(1)),
                    },
                    ResolvedImport {
                        info: ImportInfo {
                            source: "./utils".to_string(),
                            imported_name: ImportedName::Named("foo".to_string()),
                            local_name: "foo".to_string(),
                            is_type_only: false,
                            is_type_only_star: false,
                            from_style: false,
                            span: oxc_span::Span::new(50, 60),
                            source_span: oxc_span::Span::default(),
                        },
                        target: ResolveResult::InternalModule(FileId(1)),
                    },
                ],
                ..Default::default()
            },
            ResolvedModule {
                file_id: FileId(1),
                path: PathBuf::from("/project/utils.ts"),
                ..Default::default()
            },
        ];

        let graph = ModuleGraph::build(&resolved_modules, &entry_points, &files);
        assert_eq!(graph.find_import_span_start(FileId(0), FileId(1)), Some(50));
    }

    #[test]
    fn graph_find_import_span_start_wrong_target() {
        let graph = build_simple_graph();
        let span_start = graph.find_import_span_start(FileId(0), FileId(0));
        assert!(span_start.is_none());
    }

    #[test]
    fn graph_find_import_span_start_source_out_of_bounds() {
        let graph = build_simple_graph();
        let span_start = graph.find_import_span_start(FileId(999), FileId(1));
        assert!(span_start.is_none());
    }

    #[test]
    fn graph_find_import_span_start_no_edges() {
        let graph = build_simple_graph();
        let span_start = graph.find_import_span_start(FileId(1), FileId(0));
        assert!(span_start.is_none());
    }

    #[test]
    fn graph_reverse_deps_populated() {
        let graph = build_simple_graph();
        assert!(graph.reverse_deps[1].contains(&FileId(0)));
        assert!(graph.reverse_deps[0].is_empty());
    }

    #[test]
    fn graph_type_only_package_usage_tracked() {
        let files = vec![DiscoveredFile {
            id: FileId(0),
            path: PathBuf::from("/project/entry.ts"),
            size_bytes: 100,
        }];
        let entry_points = vec![EntryPoint {
            path: PathBuf::from("/project/entry.ts"),
            source: EntryPointSource::PackageJsonMain,
        }];
        let resolved_modules = vec![ResolvedModule {
            file_id: FileId(0),
            path: PathBuf::from("/project/entry.ts"),
            resolved_imports: vec![
                ResolvedImport {
                    info: ImportInfo {
                        source: "react".to_string(),
                        imported_name: ImportedName::Named("FC".to_string()),
                        local_name: "FC".to_string(),
                        is_type_only: true,
                        is_type_only_star: false,
                        from_style: false,
                        span: oxc_span::Span::new(0, 10),
                        source_span: oxc_span::Span::default(),
                    },
                    target: ResolveResult::NpmPackage("react".to_string()),
                },
                ResolvedImport {
                    info: ImportInfo {
                        source: "react".to_string(),
                        imported_name: ImportedName::Named("useState".to_string()),
                        local_name: "useState".to_string(),
                        is_type_only: false,
                        is_type_only_star: false,
                        from_style: false,
                        span: oxc_span::Span::new(15, 30),
                        source_span: oxc_span::Span::default(),
                    },
                    target: ResolveResult::NpmPackage("react".to_string()),
                },
            ],
            ..Default::default()
        }];

        let graph = ModuleGraph::build(&resolved_modules, &entry_points, &files);
        assert!(graph.package_usage.contains_key("react"));
        assert!(graph.type_only_package_usage.contains_key("react"));
    }

    #[test]
    fn graph_default_import_reference() {
        let files = vec![
            DiscoveredFile {
                id: FileId(0),
                path: PathBuf::from("/project/entry.ts"),
                size_bytes: 100,
            },
            DiscoveredFile {
                id: FileId(1),
                path: PathBuf::from("/project/utils.ts"),
                size_bytes: 50,
            },
        ];
        let entry_points = vec![EntryPoint {
            path: PathBuf::from("/project/entry.ts"),
            source: EntryPointSource::PackageJsonMain,
        }];
        let resolved_modules = vec![
            ResolvedModule {
                file_id: FileId(0),
                path: PathBuf::from("/project/entry.ts"),
                resolved_imports: vec![ResolvedImport {
                    info: ImportInfo {
                        source: "./utils".to_string(),
                        imported_name: ImportedName::Default,
                        local_name: "Utils".to_string(),
                        is_type_only: false,
                        is_type_only_star: false,
                        from_style: false,
                        span: oxc_span::Span::new(0, 10),
                        source_span: oxc_span::Span::default(),
                    },
                    target: ResolveResult::InternalModule(FileId(1)),
                }],
                ..Default::default()
            },
            ResolvedModule {
                file_id: FileId(1),
                path: PathBuf::from("/project/utils.ts"),
                exports: vec![fallow_types::extract::ExportInfo {
                    name: ExportName::Default,
                    local_name: None,
                    is_type_only: false,
                    visibility: VisibilityTag::None,
                    expected_unused_reason: None,
                    span: oxc_span::Span::new(0, 20),
                    members: vec![],
                    is_side_effect_used: false,
                    super_class: None,
                }]
                .into(),
                ..Default::default()
            },
        ];

        let graph = ModuleGraph::build(&resolved_modules, &entry_points, &files);
        let utils = &graph.modules[1];
        let default_export = utils
            .exports
            .iter()
            .find(|e| matches!(e.name, ExportName::Default))
            .unwrap();
        assert!(!default_export.references.is_empty());
        assert_eq!(
            default_export.references[0].kind,
            ReferenceKind::DefaultImport
        );
    }

    #[test]
    fn graph_side_effect_import_no_export_reference() {
        let files = vec![
            DiscoveredFile {
                id: FileId(0),
                path: PathBuf::from("/project/entry.ts"),
                size_bytes: 100,
            },
            DiscoveredFile {
                id: FileId(1),
                path: PathBuf::from("/project/styles.ts"),
                size_bytes: 50,
            },
        ];
        let entry_points = vec![EntryPoint {
            path: PathBuf::from("/project/entry.ts"),
            source: EntryPointSource::PackageJsonMain,
        }];
        let resolved_modules = vec![
            ResolvedModule {
                file_id: FileId(0),
                path: PathBuf::from("/project/entry.ts"),
                resolved_imports: vec![ResolvedImport {
                    info: ImportInfo {
                        source: "./styles".to_string(),
                        imported_name: ImportedName::SideEffect,
                        local_name: String::new(),
                        is_type_only: false,
                        is_type_only_star: false,
                        from_style: false,
                        span: oxc_span::Span::new(0, 10),
                        source_span: oxc_span::Span::default(),
                    },
                    target: ResolveResult::InternalModule(FileId(1)),
                }],
                ..Default::default()
            },
            ResolvedModule {
                file_id: FileId(1),
                path: PathBuf::from("/project/styles.ts"),
                exports: vec![fallow_types::extract::ExportInfo {
                    name: ExportName::Named("primaryColor".to_string()),
                    local_name: Some("primaryColor".to_string()),
                    is_type_only: false,
                    visibility: VisibilityTag::None,
                    expected_unused_reason: None,
                    span: oxc_span::Span::new(0, 20),
                    members: vec![],
                    is_side_effect_used: false,
                    super_class: None,
                }]
                .into(),
                ..Default::default()
            },
        ];

        let graph = ModuleGraph::build(&resolved_modules, &entry_points, &files);
        assert_eq!(graph.edge_count(), 1);
        let styles = &graph.modules[1];
        assert!(styles.is_reachable());
        let export = &styles.exports[0];
        assert!(
            export.references.is_empty(),
            "side-effect import should not reference named exports"
        );

        let encoded = postcard::to_allocvec(&graph).expect("encode graph");
        let decoded: ModuleGraph = postcard::from_bytes(&encoded).expect("decode graph");
        assert_eq!(decoded.edge_count(), 1);
        assert!(decoded.modules[1].is_reachable());
        assert!(decoded.modules[1].exports[0].references.is_empty());
    }

    #[test]
    fn graph_multiple_entry_points() {
        let files = vec![
            DiscoveredFile {
                id: FileId(0),
                path: PathBuf::from("/project/main.ts"),
                size_bytes: 100,
            },
            DiscoveredFile {
                id: FileId(1),
                path: PathBuf::from("/project/worker.ts"),
                size_bytes: 100,
            },
            DiscoveredFile {
                id: FileId(2),
                path: PathBuf::from("/project/shared.ts"),
                size_bytes: 50,
            },
        ];
        let entry_points = vec![
            EntryPoint {
                path: PathBuf::from("/project/main.ts"),
                source: EntryPointSource::PackageJsonMain,
            },
            EntryPoint {
                path: PathBuf::from("/project/worker.ts"),
                source: EntryPointSource::PackageJsonMain,
            },
        ];
        let resolved_modules = vec![
            ResolvedModule {
                file_id: FileId(0),
                path: PathBuf::from("/project/main.ts"),
                resolved_imports: vec![ResolvedImport {
                    info: ImportInfo {
                        source: "./shared".to_string(),
                        imported_name: ImportedName::Named("helper".to_string()),
                        local_name: "helper".to_string(),
                        is_type_only: false,
                        is_type_only_star: false,
                        from_style: false,
                        span: oxc_span::Span::new(0, 10),
                        source_span: oxc_span::Span::default(),
                    },
                    target: ResolveResult::InternalModule(FileId(2)),
                }],
                ..Default::default()
            },
            ResolvedModule {
                file_id: FileId(1),
                path: PathBuf::from("/project/worker.ts"),
                ..Default::default()
            },
            ResolvedModule {
                file_id: FileId(2),
                path: PathBuf::from("/project/shared.ts"),
                exports: vec![fallow_types::extract::ExportInfo {
                    name: ExportName::Named("helper".to_string()),
                    local_name: Some("helper".to_string()),
                    is_type_only: false,
                    visibility: VisibilityTag::None,
                    expected_unused_reason: None,
                    span: oxc_span::Span::new(0, 20),
                    members: vec![],
                    is_side_effect_used: false,
                    super_class: None,
                }]
                .into(),
                ..Default::default()
            },
        ];

        let graph = ModuleGraph::build(&resolved_modules, &entry_points, &files);
        assert!(graph.modules[0].is_entry_point());
        assert!(graph.modules[1].is_entry_point());
        assert!(!graph.modules[2].is_entry_point());
        assert!(graph.modules[0].is_reachable());
        assert!(graph.modules[1].is_reachable());
        assert!(graph.modules[2].is_reachable());
    }
}