fallow-core 2.40.2

Core analysis engine for the fallow TypeScript/JavaScript codebase analyzer
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
use std::path::{Path, PathBuf};

use super::parse_scripts::extract_script_file_refs;
use super::walk::SOURCE_EXTENSIONS;
use fallow_config::{EntryPointRole, PackageJson, ResolvedConfig};
use fallow_types::discover::{DiscoveredFile, EntryPoint, EntryPointSource};

/// Known output directory names from exports maps.
/// When an entry point path is inside one of these directories, we also try
/// the `src/` equivalent to find the tracked source file.
const OUTPUT_DIRS: &[&str] = &["dist", "build", "out", "esm", "cjs"];

/// Entry points grouped by reachability role.
#[derive(Debug, Clone, Default)]
pub struct CategorizedEntryPoints {
    pub all: Vec<EntryPoint>,
    pub runtime: Vec<EntryPoint>,
    pub test: Vec<EntryPoint>,
}

impl CategorizedEntryPoints {
    pub fn push_runtime(&mut self, entry: EntryPoint) {
        self.runtime.push(entry.clone());
        self.all.push(entry);
    }

    pub fn push_test(&mut self, entry: EntryPoint) {
        self.test.push(entry.clone());
        self.all.push(entry);
    }

    pub fn push_support(&mut self, entry: EntryPoint) {
        self.all.push(entry);
    }

    pub fn extend_runtime<I>(&mut self, entries: I)
    where
        I: IntoIterator<Item = EntryPoint>,
    {
        for entry in entries {
            self.push_runtime(entry);
        }
    }

    pub fn extend_test<I>(&mut self, entries: I)
    where
        I: IntoIterator<Item = EntryPoint>,
    {
        for entry in entries {
            self.push_test(entry);
        }
    }

    pub fn extend_support<I>(&mut self, entries: I)
    where
        I: IntoIterator<Item = EntryPoint>,
    {
        for entry in entries {
            self.push_support(entry);
        }
    }

    pub fn extend(&mut self, other: Self) {
        self.all.extend(other.all);
        self.runtime.extend(other.runtime);
        self.test.extend(other.test);
    }

    #[must_use]
    pub fn dedup(mut self) -> Self {
        dedup_entry_paths(&mut self.all);
        dedup_entry_paths(&mut self.runtime);
        dedup_entry_paths(&mut self.test);
        self
    }
}

fn dedup_entry_paths(entries: &mut Vec<EntryPoint>) {
    entries.sort_by(|a, b| a.path.cmp(&b.path));
    entries.dedup_by(|a, b| a.path == b.path);
}

/// Resolve a path relative to a base directory, with security check and extension fallback.
///
/// Returns `Some(EntryPoint)` if the path resolves to an existing file within `canonical_root`,
/// trying source extensions as fallback when the exact path doesn't exist.
/// Also handles exports map targets in output directories (e.g., `./dist/utils.js`)
/// by trying to map back to the source file (e.g., `./src/utils.ts`).
pub fn resolve_entry_path(
    base: &Path,
    entry: &str,
    canonical_root: &Path,
    source: EntryPointSource,
) -> Option<EntryPoint> {
    // Wildcard exports (e.g., `./src/themes/*.css`) can't be resolved to a single
    // file. Return None and let the caller expand them separately.
    if entry.contains('*') {
        return None;
    }

    let resolved = base.join(entry);
    // Security: ensure resolved path stays within the allowed root
    let canonical_resolved = dunce::canonicalize(&resolved).unwrap_or_else(|_| resolved.clone());
    if !canonical_resolved.starts_with(canonical_root) {
        tracing::warn!(path = %entry, "Skipping entry point outside project root");
        return None;
    }

    // If the path is in an output directory (dist/, build/, etc.), try mapping to src/ first.
    // This handles exports map targets like `./dist/utils.js` → `./src/utils.ts`.
    // We check this BEFORE the exists() check because even if the dist file exists,
    // fallow ignores dist/ by default, so we need the source file instead.
    if let Some(source_path) = try_output_to_source_path(base, entry) {
        // Security: ensure the mapped source path stays within the project root
        if let Ok(canonical_source) = dunce::canonicalize(&source_path)
            && canonical_source.starts_with(canonical_root)
        {
            return Some(EntryPoint {
                path: source_path,
                source,
            });
        }
    }

    // When the entry lives under an output directory but has no direct src/ mirror
    // (e.g. `./dist/esm2022/index.js` where `src/esm2022/index.ts` does not exist),
    // probe the package root for a conventional source index. TypeScript libraries
    // commonly point `main`/`module`/`exports` at compiled output while keeping the
    // canonical source entry at `src/index.ts`. Without this fallback, the dist file
    // becomes the entry point, gets filtered out by the default dist ignore pattern,
    // and leaves the entire src/ tree unreachable. See issue #102.
    if is_entry_in_output_dir(entry)
        && let Some(source_path) = try_source_index_fallback(base)
        && let Ok(canonical_source) = dunce::canonicalize(&source_path)
        && canonical_source.starts_with(canonical_root)
    {
        tracing::info!(
            entry = %entry,
            fallback = %source_path.display(),
            "package.json entry resolves to an ignored output directory; falling back to source index"
        );
        return Some(EntryPoint {
            path: source_path,
            source,
        });
    }

    if resolved.exists() {
        return Some(EntryPoint {
            path: resolved,
            source,
        });
    }
    // Try with source extensions
    for ext in SOURCE_EXTENSIONS {
        let with_ext = resolved.with_extension(ext);
        if with_ext.exists() {
            return Some(EntryPoint {
                path: with_ext,
                source,
            });
        }
    }
    None
}

/// Try to map an entry path from an output directory to its source equivalent.
///
/// Given `base=/project/packages/ui` and `entry=./dist/utils.js`, this tries:
/// - `/project/packages/ui/src/utils.ts`
/// - `/project/packages/ui/src/utils.tsx`
/// - etc. for all source extensions
///
/// Preserves any path prefix between the package root and the output dir,
/// e.g. `./modules/dist/utils.js` → `base/modules/src/utils.ts`.
///
/// Returns `Some(path)` if a source file is found.
fn try_output_to_source_path(base: &Path, entry: &str) -> Option<PathBuf> {
    let entry_path = Path::new(entry);
    let components: Vec<_> = entry_path.components().collect();

    // Find the last output directory component in the entry path
    let output_pos = components.iter().rposition(|c| {
        if let std::path::Component::Normal(s) = c
            && let Some(name) = s.to_str()
        {
            return OUTPUT_DIRS.contains(&name);
        }
        false
    })?;

    // Build the relative prefix before the output dir, filtering out CurDir (".")
    let prefix: PathBuf = components[..output_pos]
        .iter()
        .filter(|c| !matches!(c, std::path::Component::CurDir))
        .collect();

    // Build the relative path after the output dir (e.g., "utils.js")
    let suffix: PathBuf = components[output_pos + 1..].iter().collect();

    // Try base + prefix + "src" + suffix-with-source-extension
    for ext in SOURCE_EXTENSIONS {
        let source_candidate = base
            .join(&prefix)
            .join("src")
            .join(suffix.with_extension(ext));
        if source_candidate.exists() {
            return Some(source_candidate);
        }
    }

    None
}

/// Conventional source index file stems probed when a package.json entry lives
/// in an ignored output directory. Ordered by preference.
const SOURCE_INDEX_FALLBACK_STEMS: &[&str] = &["src/index", "src/main", "index", "main"];

/// Return `true` when `entry` contains a known output directory component.
///
/// Matches any segment in `OUTPUT_DIRS`, e.g. `./dist/esm2022/index.js` →
/// `true`, `src/main.ts` → `false`.
fn is_entry_in_output_dir(entry: &str) -> bool {
    Path::new(entry).components().any(|c| {
        matches!(
            c,
            std::path::Component::Normal(s)
                if s.to_str().is_some_and(|name| OUTPUT_DIRS.contains(&name))
        )
    })
}

/// Probe a package root for a conventional source index file.
///
/// Used when `package.json` points at compiled output but the canonical source
/// entry is a standard TypeScript/JavaScript index file. Tries `src/index`,
/// `src/main`, `index`, and `main` with each supported source extension, in
/// that order.
fn try_source_index_fallback(base: &Path) -> Option<PathBuf> {
    for stem in SOURCE_INDEX_FALLBACK_STEMS {
        for ext in SOURCE_EXTENSIONS {
            let candidate = base.join(format!("{stem}.{ext}"));
            if candidate.is_file() {
                return Some(candidate);
            }
        }
    }
    None
}

/// Default index patterns used when no other entry points are found.
const DEFAULT_INDEX_PATTERNS: &[&str] = &[
    "src/index.{ts,tsx,js,jsx}",
    "src/main.{ts,tsx,js,jsx}",
    "index.{ts,tsx,js,jsx}",
    "main.{ts,tsx,js,jsx}",
];

/// Fall back to default index patterns if no entries were found.
///
/// When `ws_filter` is `Some`, only files whose path starts with the given
/// workspace root are considered (used for workspace-scoped discovery).
fn apply_default_fallback(
    files: &[DiscoveredFile],
    root: &Path,
    ws_filter: Option<&Path>,
) -> Vec<EntryPoint> {
    let default_matchers: Vec<globset::GlobMatcher> = DEFAULT_INDEX_PATTERNS
        .iter()
        .filter_map(|p| globset::Glob::new(p).ok().map(|g| g.compile_matcher()))
        .collect();

    let mut entries = Vec::new();
    for file in files {
        // Use strip_prefix instead of canonicalize for workspace filtering
        if let Some(ws_root) = ws_filter
            && file.path.strip_prefix(ws_root).is_err()
        {
            continue;
        }
        let relative = file.path.strip_prefix(root).unwrap_or(&file.path);
        let relative_str = relative.to_string_lossy();
        if default_matchers
            .iter()
            .any(|m| m.is_match(relative_str.as_ref()))
        {
            entries.push(EntryPoint {
                path: file.path.clone(),
                source: EntryPointSource::DefaultIndex,
            });
        }
    }
    entries
}

/// Discover entry points from package.json, framework rules, and defaults.
pub fn discover_entry_points(config: &ResolvedConfig, files: &[DiscoveredFile]) -> Vec<EntryPoint> {
    let _span = tracing::info_span!("discover_entry_points").entered();
    let mut entries = Vec::new();

    // Pre-compute relative paths for all files (once, not per pattern)
    let relative_paths: Vec<String> = files
        .iter()
        .map(|f| {
            f.path
                .strip_prefix(&config.root)
                .unwrap_or(&f.path)
                .to_string_lossy()
                .into_owned()
        })
        .collect();

    // 1. Manual entries from config — batch all patterns into a single GlobSet
    // for O(files) matching instead of O(patterns × files).
    {
        let mut builder = globset::GlobSetBuilder::new();
        for pattern in &config.entry_patterns {
            if let Ok(glob) = globset::Glob::new(pattern) {
                builder.add(glob);
            }
        }
        if let Ok(glob_set) = builder.build()
            && !glob_set.is_empty()
        {
            for (idx, rel) in relative_paths.iter().enumerate() {
                if glob_set.is_match(rel) {
                    entries.push(EntryPoint {
                        path: files[idx].path.clone(),
                        source: EntryPointSource::ManualEntry,
                    });
                }
            }
        }
    }

    // 2. Package.json entries
    // Pre-compute canonical root once for all resolve_entry_path calls
    let canonical_root = dunce::canonicalize(&config.root).unwrap_or_else(|_| config.root.clone());
    let pkg_path = config.root.join("package.json");
    let root_pkg = PackageJson::load(&pkg_path).ok();
    if let Some(pkg) = &root_pkg {
        for entry_path in pkg.entry_points() {
            if let Some(ep) = resolve_entry_path(
                &config.root,
                &entry_path,
                &canonical_root,
                EntryPointSource::PackageJsonMain,
            ) {
                entries.push(ep);
            }
        }

        // 2b. Package.json scripts — extract file references as entry points
        if let Some(scripts) = &pkg.scripts {
            for script_value in scripts.values() {
                for file_ref in extract_script_file_refs(script_value) {
                    if let Some(ep) = resolve_entry_path(
                        &config.root,
                        &file_ref,
                        &canonical_root,
                        EntryPointSource::PackageJsonScript,
                    ) {
                        entries.push(ep);
                    }
                }
            }
        }

        // Framework rules now flow through PluginRegistry via external_plugins.
    }

    // 4. Auto-discover nested package.json entry points
    // For monorepo-like structures without explicit workspace config, scan for
    // package.json files in subdirectories and use their main/exports as entries.
    let exports_dirs = root_pkg
        .map(|pkg| pkg.exports_subdirectories())
        .unwrap_or_default();
    discover_nested_package_entries(
        &config.root,
        files,
        &mut entries,
        &canonical_root,
        &exports_dirs,
    );

    // 5. Default index files (if no other entries found)
    if entries.is_empty() {
        entries = apply_default_fallback(files, &config.root, None);
    }

    // Deduplicate by path
    entries.sort_by(|a, b| a.path.cmp(&b.path));
    entries.dedup_by(|a, b| a.path == b.path);

    entries
}

/// Discover entry points from nested package.json files in subdirectories.
///
/// Scans two sources for sub-packages:
/// 1. Common monorepo directory patterns (`packages/`, `apps/`, `libs/`, etc.)
/// 2. Directories derived from the root package.json `exports` map keys
///    (e.g., `"./compat": {...}` implies `compat/` may be a sub-package)
///
/// For each discovered sub-package with a `package.json`, the `main`, `module`,
/// `source`, `exports`, and `bin` fields are treated as entry points.
fn discover_nested_package_entries(
    root: &Path,
    _files: &[DiscoveredFile],
    entries: &mut Vec<EntryPoint>,
    canonical_root: &Path,
    exports_subdirectories: &[String],
) {
    let mut visited = rustc_hash::FxHashSet::default();

    // 1. Walk common monorepo patterns
    let search_dirs = [
        "packages", "apps", "libs", "modules", "plugins", "services", "tools", "utils",
    ];
    for dir_name in &search_dirs {
        let search_dir = root.join(dir_name);
        if !search_dir.is_dir() {
            continue;
        }
        let Ok(read_dir) = std::fs::read_dir(&search_dir) else {
            continue;
        };
        for entry in read_dir.flatten() {
            let pkg_dir = entry.path();
            if visited.insert(pkg_dir.clone()) {
                collect_nested_package_entries(&pkg_dir, entries, canonical_root);
            }
        }
    }

    // 2. Scan directories derived from the root exports map
    for dir_name in exports_subdirectories {
        let pkg_dir = root.join(dir_name);
        if pkg_dir.is_dir() && visited.insert(pkg_dir.clone()) {
            collect_nested_package_entries(&pkg_dir, entries, canonical_root);
        }
    }
}

/// Collect entry points from a single sub-package directory.
fn collect_nested_package_entries(
    pkg_dir: &Path,
    entries: &mut Vec<EntryPoint>,
    canonical_root: &Path,
) {
    let pkg_path = pkg_dir.join("package.json");
    if !pkg_path.exists() {
        return;
    }
    let Ok(pkg) = PackageJson::load(&pkg_path) else {
        return;
    };
    for entry_path in pkg.entry_points() {
        if entry_path.contains('*') {
            expand_wildcard_entries(pkg_dir, &entry_path, canonical_root, entries);
        } else if let Some(ep) = resolve_entry_path(
            pkg_dir,
            &entry_path,
            canonical_root,
            EntryPointSource::PackageJsonExports,
        ) {
            entries.push(ep);
        }
    }
    if let Some(scripts) = &pkg.scripts {
        for script_value in scripts.values() {
            for file_ref in extract_script_file_refs(script_value) {
                if let Some(ep) = resolve_entry_path(
                    pkg_dir,
                    &file_ref,
                    canonical_root,
                    EntryPointSource::PackageJsonScript,
                ) {
                    entries.push(ep);
                }
            }
        }
    }
}

/// Expand wildcard subpath exports to matching files on disk.
///
/// Handles patterns like `./src/themes/*.css` from package.json exports maps
/// (`"./themes/*": { "import": "./src/themes/*.css" }`). Expands the `*` to
/// match actual files in the target directory.
fn expand_wildcard_entries(
    base: &Path,
    pattern: &str,
    canonical_root: &Path,
    entries: &mut Vec<EntryPoint>,
) {
    let full_pattern = base.join(pattern).to_string_lossy().to_string();
    let Ok(matches) = glob::glob(&full_pattern) else {
        return;
    };
    for path_result in matches {
        let Ok(path) = path_result else {
            continue;
        };
        if let Ok(canonical) = dunce::canonicalize(&path)
            && canonical.starts_with(canonical_root)
        {
            entries.push(EntryPoint {
                path,
                source: EntryPointSource::PackageJsonExports,
            });
        }
    }
}

/// Discover entry points for a workspace package.
#[must_use]
pub fn discover_workspace_entry_points(
    ws_root: &Path,
    _config: &ResolvedConfig,
    all_files: &[DiscoveredFile],
) -> Vec<EntryPoint> {
    let mut entries = Vec::new();

    let pkg_path = ws_root.join("package.json");
    if let Ok(pkg) = PackageJson::load(&pkg_path) {
        let canonical_ws_root =
            dunce::canonicalize(ws_root).unwrap_or_else(|_| ws_root.to_path_buf());
        for entry_path in pkg.entry_points() {
            if entry_path.contains('*') {
                expand_wildcard_entries(ws_root, &entry_path, &canonical_ws_root, &mut entries);
            } else if let Some(ep) = resolve_entry_path(
                ws_root,
                &entry_path,
                &canonical_ws_root,
                EntryPointSource::PackageJsonMain,
            ) {
                entries.push(ep);
            }
        }

        // Scripts field — extract file references as entry points
        if let Some(scripts) = &pkg.scripts {
            for script_value in scripts.values() {
                for file_ref in extract_script_file_refs(script_value) {
                    if let Some(ep) = resolve_entry_path(
                        ws_root,
                        &file_ref,
                        &canonical_ws_root,
                        EntryPointSource::PackageJsonScript,
                    ) {
                        entries.push(ep);
                    }
                }
            }
        }

        // Framework rules now flow through PluginRegistry via external_plugins.
    }

    // Fall back to default index files if no entry points found for this workspace
    if entries.is_empty() {
        entries = apply_default_fallback(all_files, ws_root, Some(ws_root));
    }

    entries.sort_by(|a, b| a.path.cmp(&b.path));
    entries.dedup_by(|a, b| a.path == b.path);
    entries
}

/// Discover entry points from plugin results (dynamic config parsing).
///
/// Converts plugin-discovered patterns and setup files into concrete entry points
/// by matching them against the discovered file list.
#[must_use]
pub fn discover_plugin_entry_points(
    plugin_result: &crate::plugins::AggregatedPluginResult,
    config: &ResolvedConfig,
    files: &[DiscoveredFile],
) -> Vec<EntryPoint> {
    discover_plugin_entry_point_sets(plugin_result, config, files).all
}

/// Discover plugin-derived entry points with runtime/test/support roles preserved.
#[must_use]
pub fn discover_plugin_entry_point_sets(
    plugin_result: &crate::plugins::AggregatedPluginResult,
    config: &ResolvedConfig,
    files: &[DiscoveredFile],
) -> CategorizedEntryPoints {
    let mut entries = CategorizedEntryPoints::default();

    // Pre-compute relative paths
    let relative_paths: Vec<String> = files
        .iter()
        .map(|f| {
            f.path
                .strip_prefix(&config.root)
                .unwrap_or(&f.path)
                .to_string_lossy()
                .into_owned()
        })
        .collect();

    // Match plugin entry patterns against files using a single GlobSet for
    // include globs, then filter candidate matches through any exclusions.
    let mut builder = globset::GlobSetBuilder::new();
    let mut glob_meta: Vec<CompiledEntryRule<'_>> = Vec::new();
    for (rule, pname) in &plugin_result.entry_patterns {
        if let Some((include, compiled)) = compile_entry_rule(rule, pname, plugin_result) {
            builder.add(include);
            glob_meta.push(compiled);
        }
    }
    for (pattern, pname) in plugin_result
        .discovered_always_used
        .iter()
        .chain(plugin_result.always_used.iter())
        .chain(plugin_result.fixture_patterns.iter())
    {
        if let Ok(glob) = globset::GlobBuilder::new(pattern)
            .literal_separator(true)
            .build()
        {
            builder.add(glob);
            if let Some(path) = crate::plugins::CompiledPathRule::for_entry_rule(
                &crate::plugins::PathRule::new(pattern.clone()),
                "support entry pattern",
            ) {
                glob_meta.push(CompiledEntryRule {
                    path,
                    plugin_name: pname,
                    role: EntryPointRole::Support,
                });
            }
        }
    }
    if let Ok(glob_set) = builder.build()
        && !glob_set.is_empty()
    {
        for (idx, rel) in relative_paths.iter().enumerate() {
            let matches: Vec<usize> = glob_set
                .matches(rel)
                .into_iter()
                .filter(|match_idx| glob_meta[*match_idx].matches(rel))
                .collect();
            if !matches.is_empty() {
                let name = glob_meta[matches[0]].plugin_name;
                let entry = EntryPoint {
                    path: files[idx].path.clone(),
                    source: EntryPointSource::Plugin {
                        name: name.to_string(),
                    },
                };

                let mut has_runtime = false;
                let mut has_test = false;
                let mut has_support = false;
                for match_idx in matches {
                    match glob_meta[match_idx].role {
                        EntryPointRole::Runtime => has_runtime = true,
                        EntryPointRole::Test => has_test = true,
                        EntryPointRole::Support => has_support = true,
                    }
                }

                if has_runtime {
                    entries.push_runtime(entry.clone());
                }
                if has_test {
                    entries.push_test(entry.clone());
                }
                if has_support || (!has_runtime && !has_test) {
                    entries.push_support(entry);
                }
            }
        }
    }

    // Add setup files (absolute paths from plugin config parsing)
    for (setup_file, pname) in &plugin_result.setup_files {
        let resolved = if setup_file.is_absolute() {
            setup_file.clone()
        } else {
            config.root.join(setup_file)
        };
        if resolved.exists() {
            entries.push_support(EntryPoint {
                path: resolved,
                source: EntryPointSource::Plugin {
                    name: pname.clone(),
                },
            });
        } else {
            // Try with extensions
            for ext in SOURCE_EXTENSIONS {
                let with_ext = resolved.with_extension(ext);
                if with_ext.exists() {
                    entries.push_support(EntryPoint {
                        path: with_ext,
                        source: EntryPointSource::Plugin {
                            name: pname.clone(),
                        },
                    });
                    break;
                }
            }
        }
    }

    entries.dedup()
}

/// Discover entry points from `dynamicallyLoaded` config patterns.
///
/// Matches the configured glob patterns against the discovered file list and
/// marks matching files as entry points so they are never flagged as unused.
#[must_use]
pub fn discover_dynamically_loaded_entry_points(
    config: &ResolvedConfig,
    files: &[DiscoveredFile],
) -> Vec<EntryPoint> {
    if config.dynamically_loaded.is_empty() {
        return Vec::new();
    }

    let mut builder = globset::GlobSetBuilder::new();
    for pattern in &config.dynamically_loaded {
        if let Ok(glob) = globset::Glob::new(pattern) {
            builder.add(glob);
        }
    }
    let Ok(glob_set) = builder.build() else {
        return Vec::new();
    };
    if glob_set.is_empty() {
        return Vec::new();
    }

    let mut entries = Vec::new();
    for file in files {
        let rel = file
            .path
            .strip_prefix(&config.root)
            .unwrap_or(&file.path)
            .to_string_lossy();
        if glob_set.is_match(rel.as_ref()) {
            entries.push(EntryPoint {
                path: file.path.clone(),
                source: EntryPointSource::DynamicallyLoaded,
            });
        }
    }
    entries
}

struct CompiledEntryRule<'a> {
    path: crate::plugins::CompiledPathRule,
    plugin_name: &'a str,
    role: EntryPointRole,
}

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

fn compile_entry_rule<'a>(
    rule: &'a crate::plugins::PathRule,
    plugin_name: &'a str,
    plugin_result: &'a crate::plugins::AggregatedPluginResult,
) -> Option<(globset::Glob, CompiledEntryRule<'a>)> {
    let include = match globset::GlobBuilder::new(&rule.pattern)
        .literal_separator(true)
        .build()
    {
        Ok(glob) => glob,
        Err(err) => {
            tracing::warn!("invalid entry pattern '{}': {err}", rule.pattern);
            return None;
        }
    };
    let role = plugin_result
        .entry_point_roles
        .get(plugin_name)
        .copied()
        .unwrap_or(EntryPointRole::Support);
    Some((
        include,
        CompiledEntryRule {
            path: crate::plugins::CompiledPathRule::for_entry_rule(rule, "entry pattern")?,
            plugin_name,
            role,
        },
    ))
}

/// Pre-compile a set of glob patterns for efficient matching against many paths.
#[must_use]
pub fn compile_glob_set(patterns: &[String]) -> Option<globset::GlobSet> {
    if patterns.is_empty() {
        return None;
    }
    let mut builder = globset::GlobSetBuilder::new();
    for pattern in patterns {
        if let Ok(glob) = globset::GlobBuilder::new(pattern)
            .literal_separator(true)
            .build()
        {
            builder.add(glob);
        }
    }
    builder.build().ok()
}

#[cfg(test)]
mod tests {
    use super::*;
    use fallow_config::{FallowConfig, OutputFormat, RulesConfig};
    use fallow_types::discover::FileId;
    use proptest::prelude::*;

    proptest! {
        /// Valid glob patterns should never panic when compiled via globset.
        #[test]
        fn glob_patterns_never_panic_on_compile(
            prefix in "[a-zA-Z0-9_]{1,20}",
            ext in prop::sample::select(vec!["ts", "tsx", "js", "jsx", "vue", "svelte", "astro", "mdx"]),
        ) {
            let pattern = format!("**/{prefix}*.{ext}");
            // Should not panic — either compiles or returns Err gracefully
            let result = globset::Glob::new(&pattern);
            prop_assert!(result.is_ok(), "Glob::new should not fail for well-formed patterns");
        }

        /// Non-source extensions should NOT be in the SOURCE_EXTENSIONS list.
        #[test]
        fn non_source_extensions_not_in_list(
            ext in prop::sample::select(vec!["py", "rb", "rs", "go", "java", "xml", "yaml", "toml", "md", "txt", "png", "jpg", "wasm", "lock"]),
        ) {
            prop_assert!(
                !SOURCE_EXTENSIONS.contains(&ext),
                "Extension '{ext}' should NOT be in SOURCE_EXTENSIONS"
            );
        }

        /// compile_glob_set should never panic on arbitrary well-formed glob patterns.
        #[test]
        fn compile_glob_set_no_panic(
            patterns in prop::collection::vec("[a-zA-Z0-9_*/.]{1,30}", 0..10),
        ) {
            // Should not panic regardless of input
            let _ = compile_glob_set(&patterns);
        }
    }

    // compile_glob_set unit tests
    #[test]
    fn compile_glob_set_empty_input() {
        assert!(
            compile_glob_set(&[]).is_none(),
            "empty patterns should return None"
        );
    }

    #[test]
    fn compile_glob_set_valid_patterns() {
        let patterns = vec!["**/*.ts".to_string(), "src/**/*.js".to_string()];
        let set = compile_glob_set(&patterns);
        assert!(set.is_some(), "valid patterns should compile");
        let set = set.unwrap();
        assert!(set.is_match("src/foo.ts"));
        assert!(set.is_match("src/bar.js"));
        assert!(!set.is_match("src/bar.py"));
    }

    #[test]
    fn compile_glob_set_keeps_star_within_a_single_path_segment() {
        let patterns = vec!["composables/*.{ts,js}".to_string()];
        let set = compile_glob_set(&patterns).expect("pattern should compile");

        assert!(set.is_match("composables/useFoo.ts"));
        assert!(!set.is_match("composables/nested/useFoo.ts"));
    }

    #[test]
    fn plugin_entry_point_sets_preserve_runtime_test_and_support_roles() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let root = dir.path();
        std::fs::create_dir_all(root.join("src")).unwrap();
        std::fs::create_dir_all(root.join("tests")).unwrap();
        std::fs::write(root.join("src/runtime.ts"), "export const runtime = 1;").unwrap();
        std::fs::write(root.join("src/setup.ts"), "export const setup = 1;").unwrap();
        std::fs::write(root.join("tests/app.test.ts"), "export const test = 1;").unwrap();

        let config = FallowConfig {
            schema: None,
            extends: vec![],
            entry: vec![],
            ignore_patterns: vec![],
            framework: vec![],
            workspaces: None,
            ignore_dependencies: vec![],
            ignore_exports: vec![],
            used_class_members: vec![],
            duplicates: fallow_config::DuplicatesConfig::default(),
            health: fallow_config::HealthConfig::default(),
            rules: RulesConfig::default(),
            boundaries: fallow_config::BoundaryConfig::default(),
            production: false,
            plugins: vec![],
            dynamically_loaded: vec![],
            overrides: vec![],
            regression: None,
            codeowners: None,
            public_packages: vec![],
            flags: fallow_config::FlagsConfig::default(),
            sealed: false,
        }
        .resolve(root.to_path_buf(), OutputFormat::Human, 4, true, true);

        let files = vec![
            DiscoveredFile {
                id: FileId(0),
                path: root.join("src/runtime.ts"),
                size_bytes: 1,
            },
            DiscoveredFile {
                id: FileId(1),
                path: root.join("src/setup.ts"),
                size_bytes: 1,
            },
            DiscoveredFile {
                id: FileId(2),
                path: root.join("tests/app.test.ts"),
                size_bytes: 1,
            },
        ];

        let mut plugin_result = crate::plugins::AggregatedPluginResult::default();
        plugin_result.entry_patterns.push((
            crate::plugins::PathRule::new("src/runtime.ts"),
            "runtime-plugin".to_string(),
        ));
        plugin_result.entry_patterns.push((
            crate::plugins::PathRule::new("tests/app.test.ts"),
            "test-plugin".to_string(),
        ));
        plugin_result
            .always_used
            .push(("src/setup.ts".to_string(), "support-plugin".to_string()));
        plugin_result
            .entry_point_roles
            .insert("runtime-plugin".to_string(), EntryPointRole::Runtime);
        plugin_result
            .entry_point_roles
            .insert("test-plugin".to_string(), EntryPointRole::Test);
        plugin_result
            .entry_point_roles
            .insert("support-plugin".to_string(), EntryPointRole::Support);

        let entries = discover_plugin_entry_point_sets(&plugin_result, &config, &files);

        assert_eq!(entries.runtime.len(), 1, "expected one runtime entry");
        assert!(
            entries.runtime[0].path.ends_with("src/runtime.ts"),
            "runtime entry should stay runtime-only"
        );
        assert_eq!(entries.test.len(), 1, "expected one test entry");
        assert!(
            entries.test[0].path.ends_with("tests/app.test.ts"),
            "test entry should stay test-only"
        );
        assert_eq!(
            entries.all.len(),
            3,
            "support entries should stay in all entries"
        );
        assert!(
            entries
                .all
                .iter()
                .any(|entry| entry.path.ends_with("src/setup.ts")),
            "support entries should remain in the overall entry-point set"
        );
        assert!(
            !entries
                .runtime
                .iter()
                .any(|entry| entry.path.ends_with("src/setup.ts")),
            "support entries should not bleed into runtime reachability"
        );
        assert!(
            !entries
                .test
                .iter()
                .any(|entry| entry.path.ends_with("src/setup.ts")),
            "support entries should not bleed into test reachability"
        );
    }

    #[test]
    fn plugin_entry_point_rules_respect_exclusions() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let root = dir.path();
        std::fs::create_dir_all(root.join("app/pages")).unwrap();
        std::fs::write(
            root.join("app/pages/index.tsx"),
            "export default function Page() { return null; }",
        )
        .unwrap();
        std::fs::write(
            root.join("app/pages/-helper.ts"),
            "export const helper = 1;",
        )
        .unwrap();

        let config = FallowConfig {
            schema: None,
            extends: vec![],
            entry: vec![],
            ignore_patterns: vec![],
            framework: vec![],
            workspaces: None,
            ignore_dependencies: vec![],
            ignore_exports: vec![],
            used_class_members: vec![],
            duplicates: fallow_config::DuplicatesConfig::default(),
            health: fallow_config::HealthConfig::default(),
            rules: RulesConfig::default(),
            boundaries: fallow_config::BoundaryConfig::default(),
            production: false,
            plugins: vec![],
            dynamically_loaded: vec![],
            overrides: vec![],
            regression: None,
            codeowners: None,
            public_packages: vec![],
            flags: fallow_config::FlagsConfig::default(),
            sealed: false,
        }
        .resolve(root.to_path_buf(), OutputFormat::Human, 4, true, true);

        let files = vec![
            DiscoveredFile {
                id: FileId(0),
                path: root.join("app/pages/index.tsx"),
                size_bytes: 1,
            },
            DiscoveredFile {
                id: FileId(1),
                path: root.join("app/pages/-helper.ts"),
                size_bytes: 1,
            },
        ];

        let mut plugin_result = crate::plugins::AggregatedPluginResult::default();
        plugin_result.entry_patterns.push((
            crate::plugins::PathRule::new("app/pages/**/*.{ts,tsx,js,jsx}")
                .with_excluded_globs(["app/pages/**/-*", "app/pages/**/-*/**/*"]),
            "tanstack-router".to_string(),
        ));
        plugin_result
            .entry_point_roles
            .insert("tanstack-router".to_string(), EntryPointRole::Runtime);

        let entries = discover_plugin_entry_point_sets(&plugin_result, &config, &files);
        let entry_paths: Vec<_> = entries
            .all
            .iter()
            .map(|entry| {
                entry
                    .path
                    .strip_prefix(root)
                    .unwrap()
                    .to_string_lossy()
                    .into_owned()
            })
            .collect();

        assert!(entry_paths.contains(&"app/pages/index.tsx".to_string()));
        assert!(!entry_paths.contains(&"app/pages/-helper.ts".to_string()));
    }

    // resolve_entry_path unit tests
    mod resolve_entry_path_tests {
        use super::*;

        #[test]
        fn resolves_existing_file() {
            let dir = tempfile::tempdir().expect("create temp dir");
            let src = dir.path().join("src");
            std::fs::create_dir_all(&src).unwrap();
            std::fs::write(src.join("index.ts"), "export const a = 1;").unwrap();

            let canonical = dunce::canonicalize(dir.path()).unwrap();
            let result = resolve_entry_path(
                dir.path(),
                "src/index.ts",
                &canonical,
                EntryPointSource::PackageJsonMain,
            );
            assert!(result.is_some(), "should resolve an existing file");
            assert!(result.unwrap().path.ends_with("src/index.ts"));
        }

        #[test]
        fn resolves_with_extension_fallback() {
            let dir = tempfile::tempdir().expect("create temp dir");
            // Use canonical base to avoid macOS /var → /private/var symlink mismatch
            let canonical = dunce::canonicalize(dir.path()).unwrap();
            let src = canonical.join("src");
            std::fs::create_dir_all(&src).unwrap();
            std::fs::write(src.join("index.ts"), "export const a = 1;").unwrap();

            // Provide path without extension — should try adding .ts, .tsx, etc.
            let result = resolve_entry_path(
                &canonical,
                "src/index",
                &canonical,
                EntryPointSource::PackageJsonMain,
            );
            assert!(
                result.is_some(),
                "should resolve via extension fallback when exact path doesn't exist"
            );
            let ep = result.unwrap();
            assert!(
                ep.path.to_string_lossy().contains("index.ts"),
                "should find index.ts via extension fallback"
            );
        }

        #[test]
        fn returns_none_for_nonexistent_file() {
            let dir = tempfile::tempdir().expect("create temp dir");
            let canonical = dunce::canonicalize(dir.path()).unwrap();
            let result = resolve_entry_path(
                dir.path(),
                "does/not/exist.ts",
                &canonical,
                EntryPointSource::PackageJsonMain,
            );
            assert!(result.is_none(), "should return None for nonexistent files");
        }

        #[test]
        fn maps_dist_output_to_src() {
            let dir = tempfile::tempdir().expect("create temp dir");
            let src = dir.path().join("src");
            std::fs::create_dir_all(&src).unwrap();
            std::fs::write(src.join("utils.ts"), "export const u = 1;").unwrap();

            // Also create the dist/ file to make sure it prefers src/
            let dist = dir.path().join("dist");
            std::fs::create_dir_all(&dist).unwrap();
            std::fs::write(dist.join("utils.js"), "// compiled").unwrap();

            let canonical = dunce::canonicalize(dir.path()).unwrap();
            let result = resolve_entry_path(
                dir.path(),
                "./dist/utils.js",
                &canonical,
                EntryPointSource::PackageJsonExports,
            );
            assert!(result.is_some(), "should resolve dist/ path to src/");
            let ep = result.unwrap();
            assert!(
                ep.path
                    .to_string_lossy()
                    .replace('\\', "/")
                    .contains("src/utils.ts"),
                "should map ./dist/utils.js to src/utils.ts"
            );
        }

        #[test]
        fn maps_build_output_to_src() {
            let dir = tempfile::tempdir().expect("create temp dir");
            // Use canonical base to avoid macOS /var → /private/var symlink mismatch
            let canonical = dunce::canonicalize(dir.path()).unwrap();
            let src = canonical.join("src");
            std::fs::create_dir_all(&src).unwrap();
            std::fs::write(src.join("index.tsx"), "export default () => {};").unwrap();

            let result = resolve_entry_path(
                &canonical,
                "./build/index.js",
                &canonical,
                EntryPointSource::PackageJsonExports,
            );
            assert!(result.is_some(), "should map build/ output to src/");
            let ep = result.unwrap();
            assert!(
                ep.path
                    .to_string_lossy()
                    .replace('\\', "/")
                    .contains("src/index.tsx"),
                "should map ./build/index.js to src/index.tsx"
            );
        }

        #[test]
        fn preserves_entry_point_source() {
            let dir = tempfile::tempdir().expect("create temp dir");
            std::fs::write(dir.path().join("index.ts"), "export const a = 1;").unwrap();

            let canonical = dunce::canonicalize(dir.path()).unwrap();
            let result = resolve_entry_path(
                dir.path(),
                "index.ts",
                &canonical,
                EntryPointSource::PackageJsonScript,
            );
            assert!(result.is_some());
            assert!(
                matches!(result.unwrap().source, EntryPointSource::PackageJsonScript),
                "should preserve the source kind"
            );
        }
    }

    // try_output_to_source_path unit tests
    mod output_to_source_tests {
        use super::*;

        #[test]
        fn maps_dist_to_src_with_ts_extension() {
            let dir = tempfile::tempdir().expect("create temp dir");
            let src = dir.path().join("src");
            std::fs::create_dir_all(&src).unwrap();
            std::fs::write(src.join("utils.ts"), "export const u = 1;").unwrap();

            let result = try_output_to_source_path(dir.path(), "./dist/utils.js");
            assert!(result.is_some());
            assert!(
                result
                    .unwrap()
                    .to_string_lossy()
                    .replace('\\', "/")
                    .contains("src/utils.ts")
            );
        }

        #[test]
        fn returns_none_when_no_source_file_exists() {
            let dir = tempfile::tempdir().expect("create temp dir");
            // No src/ directory at all
            let result = try_output_to_source_path(dir.path(), "./dist/missing.js");
            assert!(result.is_none());
        }

        #[test]
        fn ignores_non_output_directories() {
            let dir = tempfile::tempdir().expect("create temp dir");
            let src = dir.path().join("src");
            std::fs::create_dir_all(&src).unwrap();
            std::fs::write(src.join("foo.ts"), "export const f = 1;").unwrap();

            // "lib" is not in OUTPUT_DIRS, so no mapping should occur
            let result = try_output_to_source_path(dir.path(), "./lib/foo.js");
            assert!(result.is_none());
        }

        #[test]
        fn maps_nested_output_path_preserving_prefix() {
            let dir = tempfile::tempdir().expect("create temp dir");
            let modules_src = dir.path().join("modules").join("src");
            std::fs::create_dir_all(&modules_src).unwrap();
            std::fs::write(modules_src.join("helper.ts"), "export const h = 1;").unwrap();

            let result = try_output_to_source_path(dir.path(), "./modules/dist/helper.js");
            assert!(result.is_some());
            assert!(
                result
                    .unwrap()
                    .to_string_lossy()
                    .replace('\\', "/")
                    .contains("modules/src/helper.ts")
            );
        }
    }

    // Source index fallback unit tests (issue #102)
    mod source_index_fallback_tests {
        use super::*;

        #[test]
        fn detects_dist_entry_in_output_dir() {
            assert!(is_entry_in_output_dir("./dist/esm2022/index.js"));
            assert!(is_entry_in_output_dir("dist/index.js"));
            assert!(is_entry_in_output_dir("./build/index.js"));
            assert!(is_entry_in_output_dir("./out/main.js"));
            assert!(is_entry_in_output_dir("./esm/index.js"));
            assert!(is_entry_in_output_dir("./cjs/index.js"));
        }

        #[test]
        fn rejects_non_output_entry_paths() {
            assert!(!is_entry_in_output_dir("./src/index.ts"));
            assert!(!is_entry_in_output_dir("src/main.ts"));
            assert!(!is_entry_in_output_dir("./index.js"));
            assert!(!is_entry_in_output_dir(""));
        }

        #[test]
        fn rejects_substring_match_for_output_dir() {
            // "distro" contains "dist" as a substring but is not an output dir
            assert!(!is_entry_in_output_dir("./distro/index.js"));
            assert!(!is_entry_in_output_dir("./build-scripts/run.js"));
        }

        #[test]
        fn finds_src_index_ts() {
            let dir = tempfile::tempdir().expect("create temp dir");
            let src = dir.path().join("src");
            std::fs::create_dir_all(&src).unwrap();
            let index_path = src.join("index.ts");
            std::fs::write(&index_path, "export const a = 1;").unwrap();

            let result = try_source_index_fallback(dir.path());
            assert_eq!(result.as_deref(), Some(index_path.as_path()));
        }

        #[test]
        fn finds_src_index_tsx_when_ts_missing() {
            let dir = tempfile::tempdir().expect("create temp dir");
            let src = dir.path().join("src");
            std::fs::create_dir_all(&src).unwrap();
            let index_path = src.join("index.tsx");
            std::fs::write(&index_path, "export default 1;").unwrap();

            let result = try_source_index_fallback(dir.path());
            assert_eq!(result.as_deref(), Some(index_path.as_path()));
        }

        #[test]
        fn prefers_src_index_over_root_index() {
            // Source index fallback must prefer `src/index.*` over root-level `index.*`
            // because library conventions keep source under `src/`.
            let dir = tempfile::tempdir().expect("create temp dir");
            let src = dir.path().join("src");
            std::fs::create_dir_all(&src).unwrap();
            let src_index = src.join("index.ts");
            std::fs::write(&src_index, "export const a = 1;").unwrap();
            let root_index = dir.path().join("index.ts");
            std::fs::write(&root_index, "export const b = 2;").unwrap();

            let result = try_source_index_fallback(dir.path());
            assert_eq!(result.as_deref(), Some(src_index.as_path()));
        }

        #[test]
        fn falls_back_to_src_main() {
            let dir = tempfile::tempdir().expect("create temp dir");
            let src = dir.path().join("src");
            std::fs::create_dir_all(&src).unwrap();
            let main_path = src.join("main.ts");
            std::fs::write(&main_path, "export const a = 1;").unwrap();

            let result = try_source_index_fallback(dir.path());
            assert_eq!(result.as_deref(), Some(main_path.as_path()));
        }

        #[test]
        fn falls_back_to_root_index_when_no_src() {
            let dir = tempfile::tempdir().expect("create temp dir");
            let index_path = dir.path().join("index.js");
            std::fs::write(&index_path, "module.exports = {};").unwrap();

            let result = try_source_index_fallback(dir.path());
            assert_eq!(result.as_deref(), Some(index_path.as_path()));
        }

        #[test]
        fn returns_none_when_nothing_matches() {
            let dir = tempfile::tempdir().expect("create temp dir");
            let result = try_source_index_fallback(dir.path());
            assert!(result.is_none());
        }

        #[test]
        fn resolve_entry_path_falls_back_to_src_index_for_dist_entry() {
            let dir = tempfile::tempdir().expect("create temp dir");
            let canonical = dunce::canonicalize(dir.path()).unwrap();

            // dist/esm2022/index.js exists but there's no src/esm2022/ mirror —
            // only src/index.ts. Without the fallback, resolve_entry_path would
            // return the dist file, which then gets filtered out by the ignore
            // pattern.
            let dist_dir = canonical.join("dist").join("esm2022");
            std::fs::create_dir_all(&dist_dir).unwrap();
            std::fs::write(dist_dir.join("index.js"), "export const x = 1;").unwrap();

            let src = canonical.join("src");
            std::fs::create_dir_all(&src).unwrap();
            let src_index = src.join("index.ts");
            std::fs::write(&src_index, "export const x = 1;").unwrap();

            let result = resolve_entry_path(
                &canonical,
                "./dist/esm2022/index.js",
                &canonical,
                EntryPointSource::PackageJsonMain,
            );
            assert!(result.is_some());
            let entry = result.unwrap();
            assert_eq!(entry.path, src_index);
        }

        #[test]
        fn resolve_entry_path_uses_direct_src_mirror_when_available() {
            // When `src/esm2022/index.ts` exists, the existing mirror logic wins
            // and the fallback should not fire.
            let dir = tempfile::tempdir().expect("create temp dir");
            let canonical = dunce::canonicalize(dir.path()).unwrap();

            let src_mirror = canonical.join("src").join("esm2022");
            std::fs::create_dir_all(&src_mirror).unwrap();
            let mirror_index = src_mirror.join("index.ts");
            std::fs::write(&mirror_index, "export const x = 1;").unwrap();

            // Also create src/index.ts to confirm the mirror wins over the fallback.
            let src_index = canonical.join("src").join("index.ts");
            std::fs::write(&src_index, "export const y = 2;").unwrap();

            let result = resolve_entry_path(
                &canonical,
                "./dist/esm2022/index.js",
                &canonical,
                EntryPointSource::PackageJsonMain,
            );
            assert_eq!(result.map(|e| e.path), Some(mirror_index));
        }
    }

    // apply_default_fallback unit tests
    mod default_fallback_tests {
        use super::*;

        #[test]
        fn finds_src_index_ts_as_fallback() {
            let dir = tempfile::tempdir().expect("create temp dir");
            let src = dir.path().join("src");
            std::fs::create_dir_all(&src).unwrap();
            let index_path = src.join("index.ts");
            std::fs::write(&index_path, "export const a = 1;").unwrap();

            let files = vec![DiscoveredFile {
                id: FileId(0),
                path: index_path.clone(),
                size_bytes: 20,
            }];

            let entries = apply_default_fallback(&files, dir.path(), None);
            assert_eq!(entries.len(), 1);
            assert_eq!(entries[0].path, index_path);
            assert!(matches!(entries[0].source, EntryPointSource::DefaultIndex));
        }

        #[test]
        fn finds_root_index_js_as_fallback() {
            let dir = tempfile::tempdir().expect("create temp dir");
            let index_path = dir.path().join("index.js");
            std::fs::write(&index_path, "module.exports = {};").unwrap();

            let files = vec![DiscoveredFile {
                id: FileId(0),
                path: index_path.clone(),
                size_bytes: 21,
            }];

            let entries = apply_default_fallback(&files, dir.path(), None);
            assert_eq!(entries.len(), 1);
            assert_eq!(entries[0].path, index_path);
        }

        #[test]
        fn returns_empty_when_no_index_file() {
            let dir = tempfile::tempdir().expect("create temp dir");
            let other_path = dir.path().join("src").join("utils.ts");

            let files = vec![DiscoveredFile {
                id: FileId(0),
                path: other_path,
                size_bytes: 10,
            }];

            let entries = apply_default_fallback(&files, dir.path(), None);
            assert!(
                entries.is_empty(),
                "non-index files should not match default fallback"
            );
        }

        #[test]
        fn workspace_filter_restricts_scope() {
            let dir = tempfile::tempdir().expect("create temp dir");
            let ws_a = dir.path().join("packages").join("a").join("src");
            std::fs::create_dir_all(&ws_a).unwrap();
            let ws_b = dir.path().join("packages").join("b").join("src");
            std::fs::create_dir_all(&ws_b).unwrap();

            let index_a = ws_a.join("index.ts");
            let index_b = ws_b.join("index.ts");

            let files = vec![
                DiscoveredFile {
                    id: FileId(0),
                    path: index_a.clone(),
                    size_bytes: 10,
                },
                DiscoveredFile {
                    id: FileId(1),
                    path: index_b,
                    size_bytes: 10,
                },
            ];

            // Filter to workspace A only
            let ws_root = dir.path().join("packages").join("a");
            let entries = apply_default_fallback(&files, &ws_root, Some(&ws_root));
            assert_eq!(entries.len(), 1);
            assert_eq!(entries[0].path, index_a);
        }
    }

    // expand_wildcard_entries unit tests
    mod wildcard_entry_tests {
        use super::*;

        #[test]
        fn expands_wildcard_css_entries() {
            // Wildcard subpath exports like `"./themes/*": { "import": "./src/themes/*.css" }`
            // should expand to actual CSS files on disk.
            let dir = tempfile::tempdir().expect("create temp dir");
            let themes = dir.path().join("src").join("themes");
            std::fs::create_dir_all(&themes).unwrap();
            std::fs::write(themes.join("dark.css"), ":root { --bg: #000; }").unwrap();
            std::fs::write(themes.join("light.css"), ":root { --bg: #fff; }").unwrap();

            let canonical = dunce::canonicalize(dir.path()).unwrap();
            let mut entries = Vec::new();
            expand_wildcard_entries(dir.path(), "./src/themes/*.css", &canonical, &mut entries);

            assert_eq!(entries.len(), 2, "should expand wildcard to 2 CSS files");
            let paths: Vec<String> = entries
                .iter()
                .map(|ep| ep.path.file_name().unwrap().to_string_lossy().to_string())
                .collect();
            assert!(paths.contains(&"dark.css".to_string()));
            assert!(paths.contains(&"light.css".to_string()));
            assert!(
                entries
                    .iter()
                    .all(|ep| matches!(ep.source, EntryPointSource::PackageJsonExports))
            );
        }

        #[test]
        fn wildcard_does_not_match_nonexistent_files() {
            let dir = tempfile::tempdir().expect("create temp dir");
            // No files matching the pattern
            std::fs::create_dir_all(dir.path().join("src/themes")).unwrap();

            let canonical = dunce::canonicalize(dir.path()).unwrap();
            let mut entries = Vec::new();
            expand_wildcard_entries(dir.path(), "./src/themes/*.css", &canonical, &mut entries);

            assert!(
                entries.is_empty(),
                "should return empty when no files match the wildcard"
            );
        }

        #[test]
        fn wildcard_only_matches_specified_extension() {
            // Wildcard pattern `*.css` should not match `.ts` files
            let dir = tempfile::tempdir().expect("create temp dir");
            let themes = dir.path().join("src").join("themes");
            std::fs::create_dir_all(&themes).unwrap();
            std::fs::write(themes.join("dark.css"), ":root {}").unwrap();
            std::fs::write(themes.join("index.ts"), "export {};").unwrap();

            let canonical = dunce::canonicalize(dir.path()).unwrap();
            let mut entries = Vec::new();
            expand_wildcard_entries(dir.path(), "./src/themes/*.css", &canonical, &mut entries);

            assert_eq!(entries.len(), 1, "should only match CSS files");
            assert!(
                entries[0]
                    .path
                    .file_name()
                    .unwrap()
                    .to_string_lossy()
                    .ends_with(".css")
            );
        }
    }
}