fallow-core 3.45.0

Internal detector backend for fallow-engine and fallow-api
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
use std::sync::LazyLock;

use rayon::prelude::*;
use rustc_hash::{FxHashMap, FxHashSet};

use fallow_config::{CompiledIgnoreExportRule, ResolvedConfig, Severity};
use fallow_types::extract::{ExportInfo, ExportName, ModuleInfo};

use crate::discover::FileId;
use crate::graph::{
    AmbiguityParticipants, EffectiveExportResolution, ExportNamespace, ExportSymbol, ModuleGraph,
    ModuleNode,
};
use crate::resolve::{has_react_native_plugin, platform_family_key};
use crate::results::{
    DuplicateExport, DuplicateLocation, ExportUsage, PrivateTypeLeak, ReferenceLocation,
    StaleSuppression, SuppressionOrigin, UnusedExport,
};
use crate::suppress::{IssueKind, SuppressionContext};

use crate::plugins::{ConfigExportCredit, is_export_ignored};

use super::{LineOffsetsMap, byte_offset_to_line_col, read_source};

#[path = "unused_exports_adapter.rs"]
mod adapter;
use adapter::star_re_export_overlays;
#[path = "unused_exports_cjs.rs"]
mod cjs;
#[path = "unused_exports_condition_targets.rs"]
mod condition_targets;
use condition_targets::ConditionTargetFamilies;
#[path = "unused_exports_declaration_siblings.rs"]
mod declaration_siblings;
use declaration_siblings::{
    DeclarationSiblingCredit, declaration_sibling_credit, runtime_sibling_path,
};
#[path = "unused_exports_types.rs"]
mod types;
use types::drop_types_paired_with_schemas;
pub use types::suppress_signature_backing_types;

/// Pre-compiled glob matchers for plugin/framework used_exports rules.
pub(super) type PluginMatchers<'a> = Vec<CompiledUsedExportRule<'a>>;

const TANSTACK_ROUTER_PLUGIN_NAME: &str = "tanstack-router";

type UnusedExportModuleResult = (Vec<UnusedExport>, Vec<UnusedExport>, Vec<StaleSuppression>);

struct UnusedExportModuleContext<'a> {
    graph: &'a ModuleGraph,
    config: &'a ResolvedConfig,
    ignore_matchers: &'a [CompiledIgnoreExportRule],
    plugin_matchers: &'a PluginMatchers<'a>,
    config_export_credit: &'a ConfigExportCredit<'a>,
    module_info_by_id: Option<&'a FxHashMap<FileId, &'a ModuleInfo>>,
    suppressions: &'a SuppressionContext<'a>,
    line_offsets_by_file: &'a LineOffsetsMap<'a>,
    /// Declarations whose export credit is lost to a star-export collision.
    ambiguity: &'a AmbiguityParticipants,
    /// Sorted Effect schema export names per file. `Some` only when
    /// `effect.schemaExportsAsTypes` is on.
    schema_exports: Option<&'a FxHashMap<FileId, Vec<String>>>,
    /// Export names of each declaration file that the importers of its JS
    /// sibling use (`lib.d.mts` next to `lib.mjs`).
    declaration_sibling_credit: &'a DeclarationSiblingCredit,
}

/// Compile plugin-discovered used_exports rules (includes framework preset rules).
pub(super) fn compile_plugin_matchers(
    plugin_result: Option<&crate::plugins::AggregatedPluginResult>,
) -> PluginMatchers<'_> {
    let Some(pr) = plugin_result else {
        return Vec::new();
    };
    pr.used_exports
        .iter()
        .filter_map(compile_used_export_rule)
        .collect()
}

/// Compile TanStack route contract export rules for duplicate-export filtering.
fn compile_tanstack_duplicate_export_matchers(
    plugin_result: Option<&crate::plugins::AggregatedPluginResult>,
) -> PluginMatchers<'_> {
    let Some(pr) = plugin_result else {
        return Vec::new();
    };
    pr.used_exports
        .iter()
        .filter(|rule| rule.plugin_name == TANSTACK_ROUTER_PLUGIN_NAME)
        .filter_map(compile_used_export_rule)
        .collect()
}

fn is_tanstack_router_active(
    plugin_result: Option<&crate::plugins::AggregatedPluginResult>,
) -> bool {
    plugin_result.is_some_and(|pr| {
        pr.active_plugins
            .iter()
            .any(|plugin| plugin == TANSTACK_ROUTER_PLUGIN_NAME)
    })
}

/// Whether Metro platform-extension resolution is in effect, which is the only
/// situation where sibling `<stem>.<platform><ext>` files are one module
/// selected per platform rather than independent duplicates.
fn is_react_native_active(plugin_result: Option<&crate::plugins::AggregatedPluginResult>) -> bool {
    plugin_result.is_some_and(|pr| has_react_native_plugin(&pr.active_plugins))
}

pub(super) struct CompiledUsedExportRule<'a> {
    path: crate::plugins::CompiledPathRule,
    exports: Vec<&'a str>,
}

impl CompiledUsedExportRule<'_> {
    pub(super) fn matches(&self, path: &str) -> bool {
        self.path.matches(path)
    }
}

fn compile_used_export_rule(
    rule: &crate::plugins::PluginUsedExportRule,
) -> Option<CompiledUsedExportRule<'_>> {
    Some(CompiledUsedExportRule {
        path: crate::plugins::CompiledPathRule::for_used_export_rule(
            &rule.rule.path,
            "used_exports pattern",
        )?,
        exports: rule.rule.exports.iter().map(String::as_str).collect(),
    })
}

/// Whether the only export of `module` is the default that an `export = x`
/// forward of an import makes (issue #3392).
///
/// `export = x` sets the whole module object, the same as `module.exports =
/// x`, so it is never an unused export: a module that only assigns
/// `module.exports` is skipped too. The `remove-export` fix also cannot apply
/// to it, because `export =` has no `export` keyword to remove.
fn is_export_assignment_forwarder(module: &ModuleNode) -> bool {
    module.forwards_default_as_module_object()
        && module
            .exports
            .iter()
            .all(|export| matches!(export.name, ExportName::Default))
}

/// Check whether a module should be skipped for unused-export analysis.
fn should_skip_module(
    module: &ModuleNode,
    has_plugin_used_exports: bool,
    include_entry_exports: bool,
) -> bool {
    if module.is_entry_point() && !has_plugin_used_exports && !include_entry_exports {
        return true;
    }
    if !module.is_reachable() {
        return module.exports.iter().all(|e| e.references.is_empty());
    }
    if module.has_cjs_exports() && module.exports.is_empty() {
        return true;
    }
    if is_export_assignment_forwarder(module) {
        return true;
    }
    module.path.extension().is_some_and(|ext| ext == "svelte")
}

/// Pick up the subset of ignore + plugin matchers whose globs match this module's
/// project-relative path.
fn matchers_for_module<'a>(
    module_path: &std::path::Path,
    config_root: &std::path::Path,
    ignore_matchers: &'a [CompiledIgnoreExportRule],
    plugin_matchers: &'a PluginMatchers<'_>,
) -> (Vec<&'a [String]>, Vec<&'a [&'a str]>) {
    if ignore_matchers.is_empty() && plugin_matchers.is_empty() {
        return (Vec::new(), Vec::new());
    }
    let relative_path = module_path.strip_prefix(config_root).unwrap_or(module_path);
    let file_str = relative_path.to_string_lossy();
    let mi: Vec<&[String]> = ignore_matchers
        .iter()
        .filter(|rule| rule.matcher.is_match(file_str.as_ref()))
        .map(|rule| rule.exports.as_slice())
        .collect();
    let mp: Vec<&[&str]> = plugin_matchers
        .iter()
        .filter(|rule| rule.matches(file_str.as_ref()))
        .map(|rule| rule.exports.as_slice())
        .collect();
    (mi, mp)
}

fn local_export_binding_name(export: &ExportInfo) -> Option<&str> {
    export.local_name.as_deref().or(match &export.name {
        ExportName::Named(name) => Some(name.as_str()),
        ExportName::Default => None,
    })
}

fn is_js_like_source(path: &std::path::Path) -> bool {
    path.extension()
        .and_then(|ext| ext.to_str())
        .is_some_and(|ext| {
            matches!(
                ext,
                "js" | "jsx" | "mjs" | "cjs" | "ts" | "tsx" | "mts" | "cts"
            )
        })
}

fn has_route_path_segment(module_path: &std::path::Path, config_root: &std::path::Path) -> bool {
    let relative_path = module_path.strip_prefix(config_root).unwrap_or(module_path);
    relative_path
        .to_string_lossy()
        .replace('\\', "/")
        .split('/')
        .any(|segment| segment == "routes")
}

fn is_route_tree_generated_file(path: &std::path::Path) -> bool {
    path.file_name()
        .and_then(|name| name.to_str())
        .is_some_and(|name| name.starts_with("routeTree.gen."))
}

fn is_route_referenced_by_tanstack_generated_tree(
    export_name: &str,
    export: &ExportSymbol,
    module: &ModuleNode,
    graph: &ModuleGraph,
    config_root: &std::path::Path,
) -> bool {
    export_name == "Route"
        && has_route_path_segment(&module.path, config_root)
        && export.references.iter().any(|reference| {
            graph
                .modules
                .get(reference.from_file.0 as usize)
                .is_some_and(|from| is_route_tree_generated_file(&from.path))
        })
}

/// Read the program source for the same-file use check. A Vue or Svelte SFC
/// gives its merged inline scripts, so a type that a compiler macro such as
/// `defineProps<T>()` uses counts as a same-file use (issue #3347).
fn same_file_program_source(path: &std::path::Path) -> Option<(String, oxc_span::SourceType)> {
    if fallow_extract::is_sfc_file(path) {
        return fallow_extract::sfc_merged_script_source(&read_source(path));
    }
    if !is_js_like_source(path) {
        return None;
    }
    let source = read_source(path);
    if source.is_empty() {
        return None;
    }
    Some((
        source,
        oxc_span::SourceType::from_path(path).unwrap_or_default(),
    ))
}

fn collect_exports_used_in_file(module: &ModuleInfo, path: &std::path::Path) -> FxHashSet<String> {
    if module.exports.is_empty() {
        return FxHashSet::default();
    }
    let Some((source, source_type)) = same_file_program_source(path) else {
        return FxHashSet::default();
    };

    fallow_extract::parse_bounded_or_default(&source, source_type, |parser_return| {
        let semantic_ret = oxc_semantic::SemanticBuilder::new()
            .with_build_nodes(true)
            .build(&parser_return.program);
        let semantic = semantic_ret.semantic;
        let scoping = semantic.scoping();
        let nodes = semantic.nodes();
        let root_scope = scoping.root_scope_id();

        let mut used = FxHashSet::default();
        for export in module.exports.iter() {
            let Some(local_name) = local_export_binding_name(export) else {
                continue;
            };
            let name = oxc_str::Ident::from(local_name);
            let Some(symbol_id) = scoping.get_binding(root_scope, name) else {
                continue;
            };
            let has_real_use = scoping
                .get_resolved_references(symbol_id)
                .any(|reference| !is_inside_export_specifier(nodes, reference.node_id()));
            if has_real_use {
                used.insert(export.name.to_string());
            }
        }

        used
    })
}

/// Walk ancestors of `node_id` and return `true` if the reference originates
/// from inside an `export { foo }` / `export { foo as bar }` specifier or an
/// `export default foo` declaration. Those identifiers are the export site
/// itself, not a same-file *use*, so they must not satisfy
/// `ignoreExportsUsedInFile` (Knip parity).
fn is_inside_export_specifier(
    nodes: &oxc_semantic::AstNodes<'_>,
    node_id: oxc_syntax::node::NodeId,
) -> bool {
    nodes
        .ancestor_kinds(node_id)
        .any(|kind| matches!(kind, oxc_ast::AstKind::ExportSpecifier(_)))
        || matches!(
            nodes.parent_kind(node_id),
            oxc_ast::AstKind::ExportDefaultDeclaration(_)
        )
}

/// Pick up the subset of ignore matchers whose globs match this module's path.
pub(super) fn ignore_matchers_for_module<'a>(
    module_path: &std::path::Path,
    config_root: &std::path::Path,
    ignore_matchers: &'a [CompiledIgnoreExportRule],
) -> Vec<&'a [String]> {
    if ignore_matchers.is_empty() {
        return Vec::new();
    }
    let relative_path = module_path.strip_prefix(config_root).unwrap_or(module_path);
    let file_str = relative_path.to_string_lossy();
    ignore_matchers
        .iter()
        .filter(|rule| rule.matcher.is_match(file_str.as_ref()))
        .map(|rule| rule.exports.as_slice())
        .collect()
}

fn export_has_reachable_reference(
    graph: &ModuleGraph,
    module: &ModuleNode,
    export: &ExportSymbol,
) -> bool {
    if module.is_reachable() {
        return !export.references.is_empty();
    }
    export.references.iter().any(|r| {
        graph.modules.get(r.from_file.0 as usize).is_some_and(|m| {
            debug_assert_eq!(
                m.file_id, r.from_file,
                "ModuleGraph::modules FileId-as-index invariant broken"
            );
            m.is_reachable()
        })
    })
}

fn stale_expected_unused_suppression(
    module: &ModuleNode,
    export: &ExportSymbol,
    line_offsets_by_file: &LineOffsetsMap<'_>,
) -> StaleSuppression {
    let (line, col) =
        byte_offset_to_line_col(line_offsets_by_file, module.file_id, export.span.start);
    StaleSuppression {
        finding_id: None,
        path: module.path.clone(),
        line,
        col,
        origin: SuppressionOrigin::JsdocTag {
            export_name: export.name.to_string(),
            reason: export.expected_unused_reason.clone(),
        },
        missing_reason: false,
        actions: StaleSuppression::actions_for(false),
        effective_severity: None,
    }
}

/// Record stale-suppression entries for an `@expected-unused` export: a missing
/// reason (when required) and/or the export turning out to be referenced.
fn record_expected_unused_stale(
    module: &ModuleNode,
    export: &ExportSymbol,
    ctx: &UnusedExportModuleContext<'_>,
    is_referenced: bool,
    stale_expected_unused: &mut Vec<StaleSuppression>,
) {
    if ctx.config.rules.require_suppression_reason != Severity::Off
        && export.expected_unused_reason.is_none()
    {
        let (line, col) =
            byte_offset_to_line_col(ctx.line_offsets_by_file, module.file_id, export.span.start);
        stale_expected_unused.push(StaleSuppression {
            finding_id: None,
            path: module.path.clone(),
            line,
            col,
            origin: SuppressionOrigin::JsdocTag {
                export_name: export.name.to_string(),
                reason: None,
            },
            missing_reason: true,
            actions: StaleSuppression::actions_for(true),
            effective_severity: None,
        });
    }
    if is_referenced {
        stale_expected_unused.push(stale_expected_unused_suppression(
            module,
            export,
            ctx.line_offsets_by_file,
        ));
    }
}

/// Find exports that are never imported by other files.
pub fn find_unused_exports(
    graph: &ModuleGraph,
    modules: &[ModuleInfo],
    config: &ResolvedConfig,
    plugin_result: Option<&crate::plugins::AggregatedPluginResult>,
    suppressions: &SuppressionContext<'_>,
    line_offsets_by_file: &LineOffsetsMap<'_>,
) -> (Vec<UnusedExport>, Vec<UnusedExport>, Vec<StaleSuppression>) {
    let mut unused_exports = Vec::new();
    let mut unused_types = Vec::new();
    let mut stale_expected_unused = Vec::new();

    let ignore_matchers = config.compiled_ignore_exports.as_slice();
    let plugin_matchers = compile_plugin_matchers(plugin_result);
    let config_export_credit = ConfigExportCredit::new(
        plugin_result,
        config.include_entry_exports || config.workspace_settings.any_include_entry_exports(),
    );
    let module_info_by_id: Option<FxHashMap<FileId, &ModuleInfo>> =
        if config.ignore_exports_used_in_file.is_enabled() {
            Some(modules.iter().map(|m| (m.file_id, m)).collect())
        } else {
            None
        };

    let schema_exports = types::schema_exports_by_file(config, graph, modules);

    let ambiguity = graph.ambiguity_participants();
    let declaration_sibling_credit =
        declaration_sibling_credit(graph, modules, module_info_by_id.as_ref());
    let module_context = UnusedExportModuleContext {
        graph,
        config,
        ignore_matchers,
        plugin_matchers: &plugin_matchers,
        config_export_credit: &config_export_credit,
        module_info_by_id: module_info_by_id.as_ref(),
        suppressions,
        line_offsets_by_file,
        ambiguity: &ambiguity,
        schema_exports: schema_exports.as_ref(),
        declaration_sibling_credit: &declaration_sibling_credit,
    };

    let module_results: Vec<UnusedExportModuleResult> = graph
        .modules
        .par_iter()
        .map(|module| find_unused_exports_for_module(module, &module_context))
        .collect();

    for (exports, types, stale_expected) in module_results {
        unused_exports.extend(exports);
        unused_types.extend(types);
        stale_expected_unused.extend(stale_expected);
    }

    (unused_exports, unused_types, stale_expected_unused)
}

fn find_unused_exports_for_module(
    module: &ModuleNode,
    ctx: &UnusedExportModuleContext<'_>,
) -> UnusedExportModuleResult {
    let mut stale_expected_unused = Vec::new();

    if module.exports.is_empty() && !module.has_cjs_exports() {
        return (Vec::new(), Vec::new(), stale_expected_unused);
    }

    let (matching_ignore, mut matching_plugin) = matchers_for_module(
        &module.path,
        &ctx.config.root,
        ctx.ignore_matchers,
        ctx.plugin_matchers,
    );
    if should_skip_module(
        module,
        !matching_plugin.is_empty(),
        ctx.config.include_entry_exports_for(&module.path),
    ) {
        return (Vec::new(), Vec::new(), stale_expected_unused);
    }
    // A `usedExports` rule on `lib.mjs` also names the exports of `lib.d.mts`,
    // which types the same module.
    if let Some(sibling) = runtime_sibling_path(&module.path) {
        let (_, sibling_plugin) =
            matchers_for_module(&sibling, &ctx.config.root, &[], ctx.plugin_matchers);
        matching_plugin.extend(sibling_plugin);
    }

    let same_file_used_exports = same_file_used_exports(module, ctx);
    let re_export_names: FxHashSet<&str> = module
        .re_exports
        .iter()
        .map(|re| re.exported_name.as_str())
        .collect();

    let config_credited_exports = config_credited_exports(module, ctx);
    let mut match_ctx = UnusedExportMatchContext {
        same_file_used_exports: &same_file_used_exports,
        re_export_names: &re_export_names,
        matching_ignore: &matching_ignore,
        matching_plugin: &matching_plugin,
        config_credited_exports: &config_credited_exports,
        stale_expected_unused: &mut stale_expected_unused,
    };
    let (unused_exports, unused_types) =
        collect_module_unused_export_findings(module, ctx, &mut match_ctx);

    (unused_exports, unused_types, stale_expected_unused)
}

fn collect_module_unused_export_findings(
    module: &ModuleNode,
    ctx: &UnusedExportModuleContext<'_>,
    match_ctx: &mut UnusedExportMatchContext<'_>,
) -> (Vec<UnusedExport>, Vec<UnusedExport>) {
    let mut unused_exports = Vec::new();
    let mut unused_types = Vec::new();

    let schema_exports = ctx
        .schema_exports
        .and_then(|by_file| by_file.get(&module.file_id))
        .map_or(&[][..], Vec::as_slice);

    for export in &module.exports {
        let is_schema = !export.is_type_only
            && schema_exports
                .binary_search_by(|name| name.as_str().cmp(export_name_str(&export.name)))
                .is_ok();
        if let Some(unused) = unused_export_for_module(
            module,
            export,
            is_schema,
            ctx,
            UnusedExportMatchContext {
                same_file_used_exports: match_ctx.same_file_used_exports,
                re_export_names: match_ctx.re_export_names,
                matching_ignore: match_ctx.matching_ignore,
                matching_plugin: match_ctx.matching_plugin,
                config_credited_exports: match_ctx.config_credited_exports,
                stale_expected_unused: &mut *match_ctx.stale_expected_unused,
            },
        ) {
            if export.is_type_only || is_schema {
                unused_types.push(unused);
            } else {
                unused_exports.push(unused);
            }
        }
    }

    drop_types_paired_with_schemas(&mut unused_types);
    (unused_exports, unused_types)
}

/// The export names that a tool reads from `module` as its config file.
fn config_credited_exports<'a>(
    module: &ModuleNode,
    ctx: &UnusedExportModuleContext<'a>,
) -> Vec<&'a [String]> {
    if ctx.config_export_credit.is_empty() || !ctx.config.include_entry_exports_for(&module.path) {
        return Vec::new();
    }
    let relative_path = module.path.strip_prefix(&ctx.config.root);
    let file_str = relative_path.unwrap_or(&module.path).to_string_lossy();
    ctx.config_export_credit.exports_for(file_str.as_ref())
}

fn same_file_used_exports(
    module: &ModuleNode,
    ctx: &UnusedExportModuleContext<'_>,
) -> FxHashSet<String> {
    ctx.module_info_by_id
        .map_or_else(FxHashSet::default, |by_id| {
            by_id
                .get(&module.file_id)
                .map_or_else(FxHashSet::default, |info| {
                    collect_exports_used_in_file(info, &module.path)
                })
        })
}

struct UnusedExportMatchContext<'a> {
    same_file_used_exports: &'a FxHashSet<String>,
    re_export_names: &'a FxHashSet<&'a str>,
    matching_ignore: &'a [&'a [String]],
    matching_plugin: &'a [&'a [&'a str]],
    config_credited_exports: &'a [&'a [String]],
    stale_expected_unused: &'a mut Vec<StaleSuppression>,
}

fn export_name_str(name: &ExportName) -> &str {
    match name {
        ExportName::Named(name) => name.as_str(),
        ExportName::Default => "default",
    }
}

/// `is_schema` marks an Effect schema export that `effect.schemaExportsAsTypes`
/// reports as an unused type.
fn unused_export_for_module(
    module: &ModuleNode,
    export: &ExportSymbol,
    is_schema: bool,
    ctx: &UnusedExportModuleContext<'_>,
    match_ctx: UnusedExportMatchContext<'_>,
) -> Option<UnusedExport> {
    let mut match_ctx = match_ctx;
    let export_str = export_name_str(&export.name);

    if unused_export_candidate_is_skipped(module, export, ctx, export_str, &mut match_ctx) {
        return None;
    }

    let (line, col) =
        byte_offset_to_line_col(ctx.line_offsets_by_file, module.file_id, export.span.start);
    let issue_kind = if export.is_type_only || is_schema {
        IssueKind::UnusedType
    } else {
        IssueKind::UnusedExport
    };
    // A schema export keeps the `unused-export` comments written before the
    // option was on, so they do not turn stale.
    let suppressed = ctx
        .suppressions
        .is_suppressed(module.file_id, line, issue_kind)
        || (is_schema
            && ctx
                .suppressions
                .is_suppressed(module.file_id, line, IssueKind::UnusedExport));
    if suppressed {
        return None;
    }

    let is_re_export = match_ctx.re_export_names.contains(export_str);
    Some(build_unused_export(
        module,
        export,
        export_str.to_owned(),
        line,
        col,
        is_re_export,
    ))
}

fn unused_export_candidate_is_skipped(
    module: &ModuleNode,
    export: &ExportSymbol,
    ctx: &UnusedExportModuleContext<'_>,
    export_str: &str,
    match_ctx: &mut UnusedExportMatchContext<'_>,
) -> bool {
    let has_cross_file_ref = export_has_reachable_reference(ctx.graph, module, export)
        || ctx
            .declaration_sibling_credit
            .get(&module.file_id)
            .is_some_and(|names| names.contains(export_str));
    let is_referenced = has_cross_file_ref || (module.is_reachable() && export.is_side_effect_used);
    if matches!(
        export.visibility,
        fallow_types::extract::VisibilityTag::ExpectedUnused
    ) {
        record_expected_unused_stale(
            module,
            export,
            ctx,
            is_referenced,
            match_ctx.stale_expected_unused,
        );
        return true;
    }

    if export.visibility.suppresses_unused() || is_referenced {
        return true;
    }

    // A declaration that lost its credit to a star-export collision is unknown,
    // not dead: the barrel exports nothing under that name, so no importer can
    // credit it. Reporting it would attribute a barrel mistake to a source file
    // that contains none. See issue #2263.
    if ctx
        .ambiguity
        .contains_declaration(module.file_id, export_str, export.is_type_only)
    {
        return true;
    }

    if ctx
        .config
        .ignore_exports_used_in_file
        .suppresses(export.is_type_only)
        && match_ctx.same_file_used_exports.contains(export_str)
    {
        return true;
    }

    cjs::is_credited(module, export_str, match_ctx)
}

fn build_unused_export(
    module: &ModuleNode,
    export: &ExportSymbol,
    export_name: String,
    line: u32,
    col: u32,
    is_re_export: bool,
) -> UnusedExport {
    UnusedExport {
        path: module.path.clone(),
        export_name,
        is_type_only: export.is_type_only,
        line,
        col,
        span_start: export.span.start,
        is_re_export,
        deprecated: export.deprecated,
        deprecated_reason: export.deprecated_reason.as_deref().map(str::to_owned),
    }
}

/// File-name suffixes that idiomatically declare local helper types
/// (`type Story = StoryObj<typeof Component>`) used by virtually every export.
/// Skipping these in private-type-leak detection keeps Storybook codebases
/// from drowning in true-but-unhelpful findings.
const STORYBOOK_SUFFIXES: &[&str] = &[
    ".stories.ts",
    ".stories.tsx",
    ".stories.js",
    ".stories.jsx",
    ".stories.mts",
    ".stories.cts",
    ".stories.mjs",
    ".stories.cjs",
    ".story.ts",
    ".story.tsx",
    ".story.js",
    ".story.jsx",
    ".story.mts",
    ".story.cts",
    ".story.mjs",
    ".story.cjs",
];

fn is_storybook_file(path: &std::path::Path) -> bool {
    path.file_name()
        .and_then(|name| name.to_str())
        .is_some_and(|name| {
            STORYBOOK_SUFFIXES
                .iter()
                .any(|suffix| name.ends_with(suffix))
        })
}

/// File-path globs for framework routing conventions where per-file private types are shared across exports.
const ROUTE_CONVENTION_PATTERNS: &[&str] = &[
    "**/app/**/page.{ts,tsx,js,jsx}",
    "**/app/**/layout.{ts,tsx,js,jsx}",
    "**/app/**/template.{ts,tsx,js,jsx}",
    "**/app/**/loading.{ts,tsx,js,jsx}",
    "**/app/**/error.{ts,tsx,js,jsx}",
    "**/app/**/not-found.{ts,tsx,js,jsx}",
    "**/app/**/route.{ts,tsx,js,jsx}",
    "**/app/**/default.{ts,tsx,js,jsx}",
    "**/app/**/global-error.{ts,tsx,js,jsx}",
    "**/app/**/forbidden.{ts,tsx,js,jsx}",
    "**/app/**/unauthorized.{ts,tsx,js,jsx}",
    "**/app/global-not-found.{ts,tsx,js,jsx}",
    "**/app/page.{ts,tsx,js,jsx}",
    "**/app/layout.{ts,tsx,js,jsx}",
    "**/app/template.{ts,tsx,js,jsx}",
    "**/app/loading.{ts,tsx,js,jsx}",
    "**/app/error.{ts,tsx,js,jsx}",
    "**/app/not-found.{ts,tsx,js,jsx}",
    "**/app/route.{ts,tsx,js,jsx}",
    "**/app/default.{ts,tsx,js,jsx}",
    "**/app/global-error.{ts,tsx,js,jsx}",
    "**/app/**/opengraph-image.{ts,tsx,js,jsx}",
    "**/app/**/twitter-image.{ts,tsx,js,jsx}",
    "**/app/**/icon.{ts,tsx,js,jsx}",
    "**/app/**/apple-icon.{ts,tsx,js,jsx}",
    "**/app/**/manifest.{ts,tsx,js,jsx}",
    "**/app/**/sitemap.{ts,tsx,js,jsx}",
    "**/app/**/robots.{ts,tsx,js,jsx}",
    "**/pages/**/*.{ts,tsx,js,jsx}",
    "**/src/templates/**/*.{ts,tsx,js,jsx}",
    "**/routes/*.{ts,tsx,js,jsx}",
    "**/routes/**/route.{ts,tsx,js,jsx}",
    "**/routes/**/_layout.{ts,tsx,js,jsx}",
    "**/routes/**/_index.{ts,tsx,js,jsx}",
    "**/routes/**/index.{ts,tsx,js,jsx}",
    "**/routes/**/__root.{ts,tsx,js,jsx}",
    "**/app/**/_layout.{ts,tsx,js,jsx}",
    "**/app/**/+*.{ts,tsx,js,jsx}",
];

#[expect(
    clippy::expect_used,
    reason = "route convention globs are hard-coded and covered by entry point tests"
)]
fn build_route_convention_globset() -> globset::GlobSet {
    let mut builder = globset::GlobSetBuilder::new();
    for pattern in ROUTE_CONVENTION_PATTERNS {
        let glob = globset::GlobBuilder::new(pattern)
            .literal_separator(true)
            .build()
            .expect("static route-convention glob pattern must be valid");
        builder.add(glob);
    }
    builder
        .build()
        .expect("static route-convention globset must build")
}

fn is_route_convention_file(absolute_path: &std::path::Path, root: &std::path::Path) -> bool {
    let relative = absolute_path.strip_prefix(root).unwrap_or(absolute_path);
    let normalized = relative.to_string_lossy().replace('\\', "/");
    ROUTE_CONVENTION_GLOBSET.is_match(normalized.as_str())
}

static ROUTE_CONVENTION_GLOBSET: LazyLock<globset::GlobSet> =
    LazyLock::new(build_route_convention_globset);

/// Find exported signatures that reference same-file type declarations that
/// are not exported by that same name.
pub fn find_private_type_leaks(
    graph: &ModuleGraph,
    modules: &[fallow_types::extract::ModuleInfo],
    config: &ResolvedConfig,
    suppressions: &SuppressionContext<'_>,
    line_offsets_by_file: &LineOffsetsMap<'_>,
) -> Vec<PrivateTypeLeak> {
    let mut leaks = Vec::new();
    for module_info in modules {
        if module_info.public_signature_type_references.is_empty()
            || module_info.local_type_declarations.is_empty()
        {
            continue;
        }
        let Some(module) = graph.modules.get(module_info.file_id.0 as usize) else {
            continue;
        };
        debug_assert_eq!(
            module.file_id, module_info.file_id,
            "ModuleGraph::modules FileId-as-index invariant broken"
        );
        if is_storybook_file(&module.path) || is_route_convention_file(&module.path, &config.root) {
            continue;
        }
        collect_module_private_type_leaks(
            module,
            module_info,
            suppressions,
            line_offsets_by_file,
            &mut leaks,
        );
    }

    leaks
}

/// Collect private-type-leak findings for a single module: every public
/// signature reference to a same-file type declaration not exported by name.
fn collect_module_private_type_leaks(
    module: &ModuleNode,
    module_info: &fallow_types::extract::ModuleInfo,
    suppressions: &SuppressionContext<'_>,
    line_offsets_by_file: &LineOffsetsMap<'_>,
    leaks: &mut Vec<PrivateTypeLeak>,
) {
    let local_types: FxHashSet<&str> = module_info
        .local_type_declarations
        .iter()
        .map(|decl| decl.name.as_str())
        .collect();
    let exported_names: FxHashSet<String> = module
        .exports
        .iter()
        .map(|export| export.name.to_string())
        .collect();

    let mut seen: FxHashSet<(&str, &str)> = FxHashSet::default();
    for reference in &module_info.public_signature_type_references {
        // A `satisfies` clause checks the value but does not change the
        // exported type, so its type cannot leak through the export.
        if reference.from_satisfies {
            continue;
        }
        if !local_types.contains(reference.type_name.as_str())
            || exported_names.contains(&reference.type_name)
        {
            continue;
        }
        if !seen.insert((reference.export_name.as_str(), reference.type_name.as_str())) {
            continue;
        }
        let (line, col) = byte_offset_to_line_col(
            line_offsets_by_file,
            module_info.file_id,
            reference.span.start,
        );
        if suppressions.is_suppressed(module_info.file_id, line, IssueKind::PrivateTypeLeak) {
            continue;
        }
        leaks.push(PrivateTypeLeak {
            path: module.path.clone(),
            export_name: reference.export_name.clone(),
            type_name: reference.type_name.clone(),
            line,
            col,
            span_start: reference.span.start,
            semantic: None,
        });
    }
}

type DynamicReExportSources = FxHashMap<usize, FxHashMap<String, FxHashSet<usize>>>;

/// Record dynamic-import edges that act as named re-exports. A dynamic import
/// counts only when the wrapper module exports the same name, mirroring a
/// static `export { X } from` shape without conflating unrelated names.
fn collect_dynamic_reexport_sources(
    resolved_modules: &[crate::resolve::ResolvedModule],
    graph: &ModuleGraph,
    re_export_sources: &mut DynamicReExportSources,
) {
    use crate::extract::ExportName;
    use fallow_types::extract::ImportedName;

    for resolved in resolved_modules {
        let wrapper_idx = resolved.file_id.0 as usize;
        let Some(wrapper) = graph.modules.get(wrapper_idx) else {
            continue;
        };
        debug_assert_eq!(
            wrapper.file_id, resolved.file_id,
            "ModuleGraph::modules FileId-as-index invariant broken"
        );
        let wrapper_exports = &wrapper.exports;

        for dynamic_import in &resolved.resolved_dynamic_imports {
            let Some(source_file_id) = dynamic_import.target.internal_file_id() else {
                continue;
            };

            let ImportedName::Named(name) = &dynamic_import.info.imported_name else {
                continue;
            };
            if !wrapper_exports
                .iter()
                .any(|export| matches!(&export.name, ExportName::Named(n) if n == name))
            {
                continue;
            }

            let source_idx = source_file_id.0 as usize;
            if source_idx >= graph.modules.len() {
                continue;
            }
            re_export_sources
                .entry(wrapper_idx)
                .or_default()
                .entry(name.clone())
                .or_default()
                .insert(source_idx);
        }
    }
}

/// An export name occurrence in a single module, collected before deduplication.
struct ExportEntry {
    module_idx: usize,
    path: std::path::PathBuf,
    file_id: FileId,
    span_start: u32,
    is_type_only: bool,
}

impl ExportEntry {
    const fn namespaces(&self) -> &'static [ExportNamespace] {
        if self.is_type_only {
            &[ExportNamespace::Type]
        } else {
            &[ExportNamespace::Type, ExportNamespace::Value]
        }
    }

    fn connects_importer(&self, graph: &ModuleGraph, importer: FileId, export_name: &str) -> bool {
        self.namespaces().iter().any(|&namespace| {
            graph.importer_connects_export_origin(importer, self.file_id, export_name, namespace)
        })
    }
}

/// Partition `entries` into connected components where two entries are connected
/// when they share at least one common importer in `graph`, or one directly
/// imports the other.
///
/// Returns index sets into `entries`; each inner vec is one component.
/// Singleton components (no shared importer with any sibling) are included so
/// the caller can drop them as unrelated leaf modules.
fn partition_by_common_importer(
    entries: &[ExportEntry],
    export_name: &str,
    graph: &ModuleGraph,
) -> Vec<Vec<usize>> {
    let n = entries.len();
    let mut union_find = UnionFind::new(n);

    // Build importer -> [entry index] map so we can union all entries that share
    // a common importer.
    let mut importer_to_entries: FxHashMap<FileId, Vec<usize>> = FxHashMap::default();
    for (i, entry) in entries.iter().enumerate() {
        let idx = entry.file_id.0 as usize;
        if idx >= graph.reverse_deps.len() {
            continue;
        }
        for &importer in &graph.reverse_deps[idx] {
            if !entry.connects_importer(graph, importer, export_name) {
                continue;
            }
            importer_to_entries.entry(importer).or_default().push(i);
        }
    }

    // Union all entries that share a common importer.
    for members in importer_to_entries.values() {
        if let Some((&first, rest)) = members.split_first() {
            for &other in rest {
                union_find.union(first, other);
            }
        }
    }

    // Also union entries where one directly imports the other (i.e. the importer
    // itself is a member of the duplicate set). Build a `file_id -> first index`
    // map once (first index wins, mirroring `position()`), so the importer lookup
    // is O(1) instead of a linear `position()` scan over the growing entries vec
    // nested inside the per-entry x per-importer loops (issue #1843 follow-up).
    let mut entry_index_by_file_id: FxHashMap<FileId, usize> = FxHashMap::default();
    for (i, entry) in entries.iter().enumerate() {
        entry_index_by_file_id.entry(entry.file_id).or_insert(i);
    }
    for (i, entry) in entries.iter().enumerate() {
        let idx = entry.file_id.0 as usize;
        if idx >= graph.reverse_deps.len() {
            continue;
        }
        for &importer in &graph.reverse_deps[idx] {
            if !entry.connects_importer(graph, importer, export_name) {
                continue;
            }
            if let Some(&j) = entry_index_by_file_id.get(&importer) {
                union_find.union(i, j);
            }
        }
    }

    union_find.components()
}

/// Union-Find with path compression for duplicate-export component grouping.
struct UnionFind {
    parent: Vec<usize>,
}

impl UnionFind {
    fn new(len: usize) -> Self {
        Self {
            parent: (0..len).collect(),
        }
    }

    fn find(&mut self, mut x: usize) -> usize {
        while self.parent[x] != x {
            self.parent[x] = self.parent[self.parent[x]];
            x = self.parent[x];
        }
        x
    }

    fn union(&mut self, a: usize, b: usize) {
        let root_a = self.find(a);
        let root_b = self.find(b);
        if root_a != root_b {
            self.parent[root_a] = root_b;
        }
    }

    fn components(mut self) -> Vec<Vec<usize>> {
        // Group entry indices by their union-find root.
        let mut components: FxHashMap<usize, Vec<usize>> = FxHashMap::default();
        for i in 0..self.parent.len() {
            let root = self.find(i);
            components.entry(root).or_default().push(i);
        }

        components.into_values().collect()
    }
}

/// Find exports that appear with the same name in multiple files (potential duplicates).
///
/// Barrel re-exports (files that only re-export from other modules via `export { X } from './source'`)
/// are excluded. Having an index.ts re-export the same name as the source module is the normal
/// barrel file pattern, not a true duplicate.
///
/// `resolved_modules` is the set of modules with their resolved dynamic imports.
/// Pass `&[]` to opt out of dynamic-import re-export detection (existing static
/// `export { X } from '...'` re-exports are still recognized).
pub fn find_duplicate_exports(
    graph: &ModuleGraph,
    config: &ResolvedConfig,
    suppressions: &SuppressionContext<'_>,
    line_offsets_by_file: &LineOffsetsMap<'_>,
    resolved_modules: &[crate::resolve::ResolvedModule],
) -> Vec<DuplicateExport> {
    find_duplicate_exports_with_plugins(
        graph,
        config,
        suppressions,
        line_offsets_by_file,
        None,
        resolved_modules,
    )
}

pub(super) fn find_duplicate_exports_with_plugins(
    graph: &ModuleGraph,
    config: &ResolvedConfig,
    suppressions: &SuppressionContext<'_>,
    line_offsets_by_file: &LineOffsetsMap<'_>,
    plugin_result: Option<&crate::plugins::AggregatedPluginResult>,
    resolved_modules: &[crate::resolve::ResolvedModule],
) -> Vec<DuplicateExport> {
    let dynamic_re_export_sources = build_dynamic_re_export_source_map(graph, resolved_modules);
    let export_locations =
        collect_duplicate_export_locations(graph, config, suppressions, plugin_result);
    let condition_families = ConditionTargetFamilies::build(resolved_modules);
    let collapse = AlternativeFiles {
        platform_families: is_react_native_active(plugin_result),
        condition_families: &condition_families,
    };

    let mut sorted_locations: Vec<_> = export_locations.into_iter().collect();
    sorted_locations.sort_by(|a, b| a.0.cmp(&b.0));

    sorted_locations
        .into_iter()
        .filter_map(|(name, locations)| {
            evaluate_duplicate_export_group(
                name,
                locations,
                &dynamic_re_export_sources,
                graph,
                line_offsets_by_file,
                &collapse,
            )
        })
        .collect()
}

/// Map each wrapper module and exported name to the dynamic-import modules that
/// supply it. Static exports are resolved by the graph's canonical effective
/// export index instead of maintaining a second source map here.
fn build_dynamic_re_export_source_map(
    graph: &ModuleGraph,
    resolved_modules: &[crate::resolve::ResolvedModule],
) -> DynamicReExportSources {
    let mut re_export_sources = DynamicReExportSources::default();
    collect_dynamic_reexport_sources(resolved_modules, graph, &mut re_export_sources);
    re_export_sources
}

/// Collect every non-default, non-ignored named export across reachable,
/// non-entry-point modules, keyed by export name. The resulting groups feed
/// duplicate detection.
fn collect_duplicate_export_locations(
    graph: &ModuleGraph,
    config: &ResolvedConfig,
    suppressions: &SuppressionContext<'_>,
    plugin_result: Option<&crate::plugins::AggregatedPluginResult>,
) -> FxHashMap<String, Vec<ExportEntry>> {
    let ignore_matchers = config.compiled_ignore_exports.as_slice();
    let tanstack_duplicate_matchers = compile_tanstack_duplicate_export_matchers(plugin_result);
    let has_tanstack_router = is_tanstack_router_active(plugin_result);

    let mut export_locations: FxHashMap<String, Vec<ExportEntry>> = FxHashMap::default();

    for (idx, module) in graph.modules.iter().enumerate() {
        collect_module_duplicate_export_locations(
            &mut export_locations,
            DuplicateExportModuleInput {
                graph,
                config,
                suppressions,
                ignore_matchers,
                tanstack_duplicate_matchers: &tanstack_duplicate_matchers,
                has_tanstack_router,
                module_idx: idx,
                module,
            },
        );
    }

    export_locations
}

#[derive(Clone, Copy)]
struct DuplicateExportModuleInput<'a> {
    graph: &'a ModuleGraph,
    config: &'a ResolvedConfig,
    suppressions: &'a SuppressionContext<'a>,
    ignore_matchers: &'a [CompiledIgnoreExportRule],
    tanstack_duplicate_matchers: &'a PluginMatchers<'a>,
    has_tanstack_router: bool,
    module_idx: usize,
    module: &'a ModuleNode,
}

fn collect_module_duplicate_export_locations(
    export_locations: &mut FxHashMap<String, Vec<ExportEntry>>,
    input: DuplicateExportModuleInput<'_>,
) {
    if !input.module.is_reachable()
        || input.module.is_entry_point()
        || is_css_module_path(&input.module.path)
    {
        return;
    }
    if input
        .suppressions
        .is_file_suppressed(input.module.file_id, IssueKind::DuplicateExport)
    {
        return;
    }

    let matching_ignore = ignore_matchers_for_module(
        &input.module.path,
        &input.config.root,
        input.ignore_matchers,
    );
    let (_, matching_tanstack_contracts) = matchers_for_module(
        &input.module.path,
        &input.config.root,
        &[],
        input.tanstack_duplicate_matchers,
    );

    for export in &input.module.exports {
        let Some((name, entry)) = duplicate_export_entry(
            export,
            &input,
            &matching_ignore,
            &matching_tanstack_contracts,
        ) else {
            continue;
        };
        export_locations.entry(name).or_default().push(entry);
    }
}

fn duplicate_export_entry(
    export: &ExportSymbol,
    input: &DuplicateExportModuleInput<'_>,
    matching_ignore: &[&[String]],
    matching_tanstack_contracts: &[&[&str]],
) -> Option<(String, ExportEntry)> {
    if matches!(export.name, crate::extract::ExportName::Default)
        || matches!(&export.name, crate::extract::ExportName::Named(name) if name == "default")
    {
        return None;
    }
    if export.span.start == 0 && export.span.end == 0 {
        return None;
    }
    let name = export.name.to_string();
    if is_export_ignored(&name, matching_ignore, matching_tanstack_contracts) {
        return None;
    }
    if input.has_tanstack_router
        && is_route_referenced_by_tanstack_generated_tree(
            &name,
            export,
            input.module,
            input.graph,
            &input.config.root,
        )
    {
        return None;
    }

    Some((
        name,
        ExportEntry {
            module_idx: input.module_idx,
            path: input.module.path.clone(),
            file_id: input.module.file_id,
            span_start: export.span.start,
            is_type_only: export.is_type_only,
        },
    ))
}

fn is_css_module_path(path: &std::path::Path) -> bool {
    let Some(file_name) = path.file_name().and_then(|name| name.to_str()) else {
        return false;
    };
    let Some((stem, extension)) = file_name.rsplit_once('.') else {
        return false;
    };
    stem.ends_with(".module") && matches!(extension, "css" | "scss" | "sass" | "less")
}

/// Files that load in place of each other, so their same-name exports are one
/// origin: Metro platform-extension families when the React Native or Expo
/// plugin is active, and the condition targets of a package `imports` entry.
struct AlternativeFiles<'a> {
    platform_families: bool,
    condition_families: &'a ConditionTargetFamilies,
}

/// Evaluate one same-name export group into an optional duplicate finding:
/// strip re-export chain members, collapse Metro platform-extension families
/// and the targets of each package `imports` entry (see [`AlternativeFiles`]),
/// partition the remaining origins into importer-connected components, and
/// collect the surviving locations.
fn evaluate_duplicate_export_group(
    name: String,
    locations: Vec<ExportEntry>,
    dynamic_re_export_sources: &DynamicReExportSources,
    graph: &ModuleGraph,
    line_offsets_by_file: &LineOffsetsMap<'_>,
    collapse: &AlternativeFiles<'_>,
) -> Option<DuplicateExport> {
    // One module that exports a name twice holds a TypeScript declaration
    // merge (`class C` plus `namespace C`), not a second origin.
    let mut seen_modules: FxHashSet<usize> = FxHashSet::default();
    let locations: Vec<ExportEntry> = locations
        .into_iter()
        .filter(|entry| seen_modules.insert(entry.module_idx))
        .collect();
    if locations.len() <= 1 {
        return None;
    }

    // Strip re-export chain members and star re-export overlays: a module
    // that re-exports the export of another group member, or star re-exports
    // that member and replaces one binding, is not an independent origin.
    let module_indices: FxHashSet<usize> = locations.iter().map(|e| e.module_idx).collect();
    let overlays = star_re_export_overlays(&locations, &name, graph);
    let independent_entries: Vec<ExportEntry> = locations
        .into_iter()
        .filter(|entry| {
            !is_re_export_chain_member(
                entry,
                &name,
                &module_indices,
                dynamic_re_export_sources,
                graph,
            ) && !overlays.contains(&entry.file_id)
        })
        .collect();

    // Collapse after the re-export strip so a barrel that re-exports from the
    // platform winner is still recognized as a chain member of the family.
    let independent_entries = if collapse.platform_families {
        collapse_platform_family_entries(independent_entries)
    } else {
        independent_entries
    };
    let independent_entries = collapse.condition_families.collapse(independent_entries);

    if independent_entries.len() <= 1 {
        return None;
    }

    // Partition independent entries into connected components where two
    // entries are connected when they share a common importer. This prevents
    // a cross-package member (e.g. a backend `class Label` that no frontend
    // module imports) from inflating `value_modules` and defeating the
    // value+type self-suppression check that should apply only to the
    // frontend component.
    let components = partition_by_common_importer(&independent_entries, &name, graph);

    let mut surviving_locations: Vec<DuplicateLocation> = Vec::new();
    for component_indices in components {
        surviving_locations.extend(component_duplicate_locations(
            &component_indices,
            &independent_entries,
            line_offsets_by_file,
        ));
    }

    if surviving_locations.len() <= 1 {
        return None;
    }

    Some(DuplicateExport {
        export_name: name,
        locations: surviving_locations,
    })
}

/// Keep one member per Metro platform-extension family in `entries`.
///
/// With the React Native or Expo plugin active the resolver credits an import
/// of `./UserMenu` to every family member, so `UserMenu.tsx` and
/// `UserMenu.ios.tsx` share each importer and would otherwise partition into
/// one duplicate component. The variants are one module selected per
/// platform, not independent origins. The base file stands in for the family
/// when present (it is Metro's fallback on every other platform), otherwise
/// the lowest path, so a genuine duplicate elsewhere is still reported
/// against a stable member. Entry order is preserved.
fn collapse_platform_family_entries(entries: Vec<ExportEntry>) -> Vec<ExportEntry> {
    let keep = platform_family_keep_mask(&entries);
    entries
        .into_iter()
        .zip(keep)
        .filter_map(|(entry, keep)| keep.then_some(entry))
        .collect()
}

/// Mark which of `entries` survive family collapsing: every entry outside a
/// family, and every entry of each family's representative file.
fn platform_family_keep_mask(entries: &[ExportEntry]) -> Vec<bool> {
    let mut families: FxHashMap<(&std::path::Path, &str), Vec<(usize, bool)>> =
        FxHashMap::default();
    for (i, entry) in entries.iter().enumerate() {
        let Some(key) = platform_family_key(&entry.path) else {
            continue;
        };
        families
            .entry((key.parent, key.base))
            .or_default()
            .push((i, key.is_platform_variant));
    }

    let mut keep = vec![true; entries.len()];
    for members in families.into_values() {
        let Some(representative) = platform_family_representative(entries, &members) else {
            continue;
        };
        for &(i, _) in &members {
            if entries[i].file_id != representative {
                keep[i] = false;
            }
        }
    }
    keep
}

/// Pick the file that stands in for one family, or `None` when `members` do
/// not form a family: a single file (possibly with both a value and a type
/// entry), or same-stem files without any platform variant, which Metro never
/// treats as a family.
fn platform_family_representative(
    entries: &[ExportEntry],
    members: &[(usize, bool)],
) -> Option<FileId> {
    let distinct_files: FxHashSet<FileId> =
        members.iter().map(|&(i, _)| entries[i].file_id).collect();
    if distinct_files.len() < 2 || !members.iter().any(|&(_, is_variant)| is_variant) {
        return None;
    }
    let base_members = members
        .iter()
        .filter(|&&(_, is_variant)| !is_variant)
        .map(|&(i, _)| &entries[i]);
    let representative = match base_members.min_by_key(|entry| &entry.path) {
        Some(base) => base,
        None => members
            .iter()
            .map(|&(i, _)| &entries[i])
            .min_by_key(|entry| &entry.path)?,
    };
    Some(representative.file_id)
}

fn is_re_export_chain_member(
    entry: &ExportEntry,
    export_name: &str,
    group_modules: &FxHashSet<usize>,
    dynamic_re_export_sources: &DynamicReExportSources,
    graph: &ModuleGraph,
) -> bool {
    let is_static_re_export = entry.namespaces().iter().any(|&namespace| {
        matches!(
            graph.resolve_export(entry.file_id, export_name, namespace),
            EffectiveExportResolution::Unique(binding)
                if binding.origin_file() != entry.file_id
                    && group_modules.contains(&(binding.origin_file().0 as usize))
        )
    });
    if is_static_re_export {
        return true;
    }

    dynamic_re_export_sources
        .get(&entry.module_idx)
        .and_then(|exports| exports.get(export_name))
        .is_some_and(|sources| sources.iter().any(|source| group_modules.contains(source)))
}

/// Resolve one importer-connected component into the duplicate locations it
/// contributes, dropping unrelated singletons and the TypeScript value+type
/// self-pair (a runtime value re-declared alongside its type alias).
fn component_duplicate_locations(
    component_indices: &[usize],
    independent_entries: &[ExportEntry],
    line_offsets_by_file: &LineOffsetsMap<'_>,
) -> Vec<DuplicateLocation> {
    if component_indices.len() <= 1 {
        // A singleton component shares no importer with any sibling; it is an
        // unrelated leaf and must be dropped.
        return Vec::new();
    }

    // Value+type self-suppression: a single value export paired with a single
    // type export in the same importer-connected component is the TypeScript
    // pattern of re-declaring a runtime value alongside its type alias, not a
    // genuine duplicate.
    let value_count = component_indices
        .iter()
        .filter(|&&i| !independent_entries[i].is_type_only)
        .count();
    let type_count = component_indices
        .iter()
        .filter(|&&i| independent_entries[i].is_type_only)
        .count();
    if value_count == 1 && type_count == 1 {
        return Vec::new();
    }

    component_indices
        .iter()
        .map(|&i| {
            let e = &independent_entries[i];
            let (line, col) =
                byte_offset_to_line_col(line_offsets_by_file, e.file_id, e.span_start);
            DuplicateLocation {
                path: e.path.clone(),
                line,
                col,
            }
        })
        .collect()
}

/// Collect usage counts for all exports in the module graph.
///
/// Iterates every module and every export, producing an `ExportUsage` entry with the
/// number of importing files and the import locations. The LSP server uses this data
/// to show Code Lens annotations (e.g., "imported by 3 files") above export
/// declarations, with click-to-navigate support via `editor.action.showReferences`.
pub fn collect_export_usages(
    graph: &ModuleGraph,
    line_offsets_by_file: &LineOffsetsMap<'_>,
) -> Vec<ExportUsage> {
    let mut usages = Vec::new();

    let file_paths: FxHashMap<FileId, &std::path::Path> = graph
        .modules
        .iter()
        .map(|m| (m.file_id, m.path.as_path()))
        .collect();

    let mut source_cache: FxHashMap<FileId, (String, Vec<u32>)> = FxHashMap::default();

    for module in &graph.modules {
        if !module.is_reachable() {
            continue;
        }

        for export in &module.exports {
            if export.span.start == 0 && export.span.end == 0 {
                continue;
            }

            let (line, col) =
                byte_offset_to_line_col(line_offsets_by_file, module.file_id, export.span.start);

            let (reference_count, reference_locations) = export_reference_locations(
                export,
                &file_paths,
                line_offsets_by_file,
                &mut source_cache,
            );

            usages.push(ExportUsage {
                path: module.path.clone(),
                export_name: export.name.to_string(),
                line,
                col,
                reference_count,
                reference_locations,
            });
        }
    }

    usages
}

/// Resolve each reference on `export` to a `(path, line, col)` location,
/// falling back to an on-disk source read (cached) for files without
/// precomputed line offsets.
fn export_reference_locations(
    export: &ExportSymbol,
    file_paths: &FxHashMap<FileId, &std::path::Path>,
    line_offsets_by_file: &LineOffsetsMap<'_>,
    source_cache: &mut FxHashMap<FileId, (String, Vec<u32>)>,
) -> (usize, Vec<ReferenceLocation>) {
    // The count and the location list use different units on purpose. The
    // count is the number of distinct importing files, the unit that the Code
    // Lens title and the hover show. The list keeps one entry per physical
    // import site, so a file with two imports of the export gives two entries.
    // A reference without an import span (0..0) still counts its file, but it
    // has no position to go to, so it gives no entry in the list.
    let mut importing_files: FxHashSet<FileId> = FxHashSet::default();
    let locations = export
        .physical_references()
        .filter_map(|r| {
            importing_files.insert(r.from_file);
            reference_location(r, file_paths, line_offsets_by_file, source_cache)
        })
        .collect();
    (importing_files.len(), locations)
}

/// Resolve one reference to the `(path, line, col)` of its import statement.
/// `None` when the reference carries no span or its file is unknown.
pub(super) fn reference_location(
    reference: &crate::graph::SymbolReference,
    file_paths: &FxHashMap<FileId, &std::path::Path>,
    line_offsets_by_file: &LineOffsetsMap<'_>,
    source_cache: &mut FxHashMap<FileId, (String, Vec<u32>)>,
) -> Option<ReferenceLocation> {
    if reference.import_span.start == 0 && reference.import_span.end == 0 {
        return None;
    }
    let ref_path = file_paths.get(&reference.from_file)?;
    let (line, col) = if line_offsets_by_file.contains_key(&reference.from_file) {
        byte_offset_to_line_col(
            line_offsets_by_file,
            reference.from_file,
            reference.import_span.start,
        )
    } else {
        let (_, offsets) = source_cache.entry(reference.from_file).or_insert_with(|| {
            let src = read_source(ref_path);
            let ofs = fallow_types::extract::compute_line_offsets(&src);
            (src, ofs)
        });
        fallow_types::extract::byte_offset_to_line_col(offsets, reference.import_span.start)
    };
    Some(ReferenceLocation {
        path: ref_path.to_path_buf(),
        line,
        col,
    })
}

#[cfg(test)]
#[path = "unused_exports_adapter_tests.rs"]
mod adapter_tests;

#[cfg(test)]
#[path = "unused_exports_tests.rs"]
mod tests;