fallow-core 3.29.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
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
//! Plugin system for framework-aware codebase analysis.
//!
//! Unlike knip's JavaScript plugin system that evaluates config files at runtime,
//! fallow's plugin system uses Oxc's parser to extract configuration values from
//! JS/TS/JSON config files via AST walking, no JavaScript evaluation needed.
//!
//! Each plugin implements the [`Plugin`] trait with:
//! - **Static defaults**: Entry patterns, config file patterns, used exports
//! - **Dynamic resolution**: Parse tool config files to discover additional entries,
//!   referenced dependencies, and setup files

use std::path::{Path, PathBuf};

use fallow_config::{AutoImportRule, EntryPointRole, PackageJson, UsedClassMemberRule};
use fallow_types::semantic::SemanticFrameworkContract;
use regex::Regex;

const TEST_ENTRY_POINT_PLUGINS: &[&str] = &[
    "ava",
    "bun",
    "deno",
    "cucumber",
    "cypress",
    "jest",
    "k6",
    "mocha",
    "playwright",
    "tap",
    "tsd",
    "vitest",
    "webdriverio",
];

const RUNTIME_ENTRY_POINT_PLUGINS: &[&str] = &[
    "adonis",
    "angular",
    "astro",
    "browser-extension",
    "convex",
    "docusaurus",
    "electron",
    "ember",
    "expo",
    "expo-router",
    "gatsby",
    "hardhat",
    "module-federation",
    "nestjs",
    "next-intl",
    "nextjs",
    "nitro",
    "nuxt",
    "obsidian",
    "parcel",
    "qwik",
    "react-native",
    "react-router",
    "redwoodsdk",
    "remix",
    "rolldown",
    "rollup",
    "rsbuild",
    "rspack",
    "sanity",
    "supabase",
    "sveltekit",
    "tanstack-router",
    "tsdown",
    "tsup",
    "vite",
    "vitepress",
    "webpack",
    "wrangler",
    "wxt",
];

#[cfg(test)]
const SUPPORT_ENTRY_POINT_PLUGINS: &[&str] = &[
    "content-collections",
    "contentlayer",
    "danger",
    "drizzle",
    "fumadocs",
    "i18next",
    "knex",
    "kysely",
    "mintlify",
    "msw",
    "opencode",
    "prisma",
    "storybook",
    "stryker",
    "typeorm",
    "velite",
];

/// Which workspace diagnostic kind a plugin-stage advisory becomes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PluginConfigEffect {
    /// The plugin could not read the key in full, so part of what it declares
    /// never reached the analysis.
    Unreadable,
    /// The plugin read the key and does not model its effect, so a modeled
    /// default the run would otherwise have applied stood down.
    NotModeled,
}

/// One advisory about a config file a plugin read, before it becomes a
/// [`fallow_config::WorkspaceDiagnostic`].
///
/// A plugin knows the fact (which config file, which key, why) but not the root
/// the message renders against: in a workspace run its own `root` is the package
/// root, while the diagnostic's path and message are project-root-relative. The
/// conversion therefore happens once, where every plugin result has converged on
/// the project root, and `config_path` is kept ABSOLUTE until then so the
/// registry's canonical dedupe and the serialized root-relative form both work
/// from one value (issue #2736).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PluginConfigDiagnostic {
    /// Absolute path of the config file that was read.
    pub config_path: PathBuf,
    /// The plugin that read it, as it labels itself. Module Federation options
    /// reach four bundler plugins inline, and each names itself rather than the
    /// reader, because the config file the user must edit is the bundler's.
    pub plugin: String,
    /// The config key the advisory is about (`exposes`, `remotes`,
    /// `components`, `imports`).
    pub key: String,
    /// Why, as a kebab-case token from the resulting kind's open set.
    pub reason: String,
    /// Which workspace diagnostic kind this becomes.
    pub effect: PluginConfigEffect,
}

impl PluginConfigDiagnostic {
    /// Build an advisory about a key a plugin could not read in full.
    pub(super) fn unreadable(
        config_path: &Path,
        plugin: &str,
        key: &str,
        reason: &'static str,
    ) -> Self {
        Self {
            config_path: config_path.to_path_buf(),
            plugin: plugin.to_owned(),
            key: key.to_owned(),
            reason: reason.to_owned(),
            effect: PluginConfigEffect::Unreadable,
        }
    }

    /// Build an advisory about a key whose effect the plugin does not model.
    pub(crate) fn not_modeled(
        config_path: &Path,
        plugin: &str,
        key: &str,
        reason: &'static str,
    ) -> Self {
        Self {
            config_path: config_path.to_path_buf(),
            plugin: plugin.to_owned(),
            key: key.to_owned(),
            reason: reason.to_owned(),
            effect: PluginConfigEffect::NotModeled,
        }
    }

    /// Render this advisory against the PROJECT root, which is the root every
    /// consumer's paths are relative to.
    #[must_use]
    pub fn into_workspace_diagnostic(self, root: &Path) -> fallow_config::WorkspaceDiagnostic {
        let Self {
            config_path,
            plugin,
            key,
            reason,
            effect,
        } = self;
        let kind = match effect {
            PluginConfigEffect::Unreadable => {
                fallow_config::WorkspaceDiagnosticKind::PluginConfigUnreadable {
                    plugin,
                    key,
                    reason,
                }
            }
            PluginConfigEffect::NotModeled => {
                fallow_config::WorkspaceDiagnosticKind::PluginEffectNotModeled {
                    plugin,
                    key,
                    reason,
                }
            }
        };
        fallow_config::WorkspaceDiagnostic::new(root, config_path, kind)
    }
}

/// Result of resolving a plugin's config file.
#[derive(Debug, Default)]
pub struct PluginResult {
    /// Additional entry point glob patterns discovered from config.
    entry_patterns: Vec<PathRule>,
    /// When true, `entry_patterns` from config replace the plugin's static
    /// `entry_patterns()` defaults instead of adding to them. Tools like Vitest
    /// and Jest treat their config's include/testMatch as a replacement for built-in
    /// defaults, so when the config is explicit the static patterns must be dropped.
    replace_entry_patterns: bool,
    /// When true, `used_exports` from config replace the plugin's static
    /// `used_export_rules()` defaults instead of adding to them.
    replace_used_export_rules: bool,
    /// Additional export-usage rules discovered from config.
    used_exports: Vec<UsedExportRule>,
    /// Class member rules that should never be flagged as unused. Contributed
    /// by plugins that know their framework invokes these methods at runtime
    /// and may scope suppression via `extends` / `implements` constraints when
    /// the method name is too common to allowlist globally.
    used_class_members: Vec<UsedClassMemberRule>,
    /// Dependencies referenced in config files (should not be flagged as unused).
    referenced_dependencies: Vec<String>,
    /// Dependencies a config credits only to the package that owns it, keyed
    /// by the path of that package's `package.json`.
    package_referenced_dependencies: Vec<(PathBuf, String)>,
    /// Additional files that are always considered used.
    always_used_files: Vec<String>,
    /// Path alias mappings discovered from config (prefix -> replacement directory).
    path_aliases: Vec<(String, String)>,
    /// Setup/helper files referenced from config.
    setup_files: Vec<PathBuf>,
    /// Test fixture glob patterns discovered from config.
    fixture_patterns: Vec<String>,
    /// Absolute directories to include when resolving SCSS/Sass `@import` and
    /// `@use` specifiers. Contributed by framework plugins that read their
    /// tool's equivalent of `includePaths` (e.g. Angular's
    /// `stylePreprocessorOptions.includePaths` from `angular.json` /
    /// `project.json`). Bare SCSS specifiers that fail to resolve relative to
    /// the importing file retry against each include path using the SCSS
    /// partial / directory-index conventions.
    scss_include_paths: Vec<PathBuf>,
    /// URL-to-filesystem static directory mappings discovered from tool config.
    /// Each tuple is `(absolute_source_dir, normalized_url_mount)`.
    static_dir_mappings: Vec<(PathBuf, String)>,
    framework_static_dir_mappings: Vec<(PathBuf, String)>,
    /// File-scoped dependency providers. Matching imports are considered
    /// available from the framework runtime and are not unlisted dependencies.
    provided_dependencies: Vec<ProvidedDependencyRule>,
    /// Advisories about the config file this result was read from. A plugin
    /// records the fact here instead of printing it, so it reaches the report
    /// and every consumer rather than only a stderr line.
    config_diagnostics: Vec<PluginConfigDiagnostic>,
    /// Where a Module Federation config exposes a file or declares a remote
    /// alias, kept so a trace can name the config (issue #2796).
    federation_sources: Vec<FederationSource>,
}

/// What a Module Federation config declares, and where, for the trace output.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FederationSource {
    /// What the config names.
    pub target: FederationSourceTarget,
    /// The absolute path of the config file.
    pub config_path: PathBuf,
    /// The plugin that read the config, as it labels itself.
    pub plugin: String,
    /// The config key that names the target.
    pub key: &'static str,
}

/// The thing a [`FederationSource`] names.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FederationSourceTarget {
    /// An `exposes` target, as the entry-point rule it became.
    Exposed(PathRule),
    /// A `remotes` alias.
    Remote(String),
}

impl FederationSource {
    #[must_use]
    fn prefixed(&self, ws_prefix: &str) -> Self {
        let target = match &self.target {
            FederationSourceTarget::Exposed(rule) => {
                FederationSourceTarget::Exposed(rule.prefixed(ws_prefix))
            }
            FederationSourceTarget::Remote(alias) => FederationSourceTarget::Remote(alias.clone()),
        };
        Self {
            target,
            config_path: self.config_path.clone(),
            plugin: self.plugin.clone(),
            key: self.key,
        }
    }
}

/// Match the Module Federation sources of one analysis against the discovered
/// files, for the trace output.
///
/// Only a project with a Federation config pays for the match, and it runs
/// once per analysis, so a trace reads plain data. A remote that a literal
/// runtime call (`registerRemotes`, `loadRemote`, `init`, `createInstance`) names traces to the source
/// file, with the function name as the key.
#[must_use]
pub fn federation_trace_provenance(
    root: &Path,
    files: &[crate::discover::DiscoveredFile],
    sources: &[FederationSource],
    modules: &[crate::extract::ModuleInfo],
) -> fallow_types::trace::TraceProvenance {
    let mut provenance = fallow_types::trace::TraceProvenance::default();
    push_runtime_remote_sources(&mut provenance, root, files, modules);
    if sources.is_empty() {
        return provenance;
    }
    let mut exposed = Vec::new();
    for source in sources {
        let config = source
            .config_path
            .strip_prefix(root)
            .unwrap_or(&source.config_path)
            .to_path_buf();
        let trace_source = fallow_types::trace::TraceSource {
            kind: "module-federation".to_owned(),
            plugin: source.plugin.clone(),
            config,
            key: source.key.to_owned(),
        };
        match &source.target {
            FederationSourceTarget::Exposed(rule) => {
                if let Some(compiled) =
                    CompiledPathRule::for_entry_rule(rule, "Module Federation exposes target")
                {
                    exposed.push((compiled, trace_source));
                }
            }
            FederationSourceTarget::Remote(alias) => {
                provenance.push_dependency(alias.clone(), trace_source);
            }
        }
    }
    if exposed.is_empty() {
        return provenance;
    }
    for file in files {
        let Ok(relative) = file.path.strip_prefix(root) else {
            continue;
        };
        let relative_str = relative.to_string_lossy().replace('\\', "/");
        for (rule, source) in &exposed {
            if rule.matches(&relative_str) {
                provenance.push_file(relative.to_path_buf(), source.clone());
            }
        }
    }
    provenance
}

/// Add a trace source for each remote that a literal runtime call names.
fn push_runtime_remote_sources(
    provenance: &mut fallow_types::trace::TraceProvenance,
    root: &Path,
    files: &[crate::discover::DiscoveredFile],
    modules: &[crate::extract::ModuleInfo],
) {
    for module in modules {
        let mut file = None;
        for fact in module.semantic_facts.iter() {
            let fallow_types::extract::SemanticFact::FederationRuntimeRemote(fact) = fact else {
                continue;
            };
            let Some(remote) = &fact.remote else {
                continue;
            };
            let Some(path) = file.get_or_insert_with(|| {
                files.get(module.file_id.0 as usize).map(|file| {
                    file.path
                        .strip_prefix(root)
                        .unwrap_or(&file.path)
                        .to_path_buf()
                })
            }) else {
                break;
            };
            provenance.push_dependency(
                remote.clone(),
                fallow_types::trace::TraceSource {
                    kind: "module-federation".to_owned(),
                    plugin: "module-federation".to_owned(),
                    config: path.clone(),
                    key: fact.call.name().to_owned(),
                },
            );
        }
    }
}

impl PluginResult {
    /// Register an entry pattern whose leading `../` segments are relative to
    /// the plugin root. The workspace prefix resolves them.
    fn push_parent_relative_entry_pattern(&mut self, pattern: String) {
        let mut rule = PathRule::new(pattern);
        rule.parent_relative = true;
        self.entry_patterns.push(rule);
    }

    fn push_entry_pattern(&mut self, pattern: impl Into<String>) {
        self.entry_patterns
            .push(PathRule::new(normalize_entry_pattern(pattern.into())));
    }

    fn extend_entry_patterns<I, S>(&mut self, patterns: I)
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.entry_patterns.extend(
            patterns
                .into_iter()
                .map(|pat| PathRule::new(normalize_entry_pattern(pat.into()))),
        );
    }

    /// Route each config value to the surface that can use it: a value naming a
    /// module request credits its package, every other value becomes an entry
    /// pattern.
    ///
    /// A bundler `entry` accepts a project file and a bare module request such as
    /// `react-hot-loader/patch` in the same list. A module request names no file,
    /// so a glob built from it matches nothing while the package still needs
    /// dependency credit. Module Federation `exposes` targets already split the
    /// two this way (issue #2706); bundler entries now do too (issue #2739).
    ///
    /// `resolve_path` maps a path value to its project-relative form, for
    /// example against a `context` directory. It runs after the value is
    /// classified, because a joined path such as `app/main` no longer carries
    /// the `./` that marks it as a path.
    fn extend_entry_patterns_or_dependencies<I, S>(
        &mut self,
        values: I,
        resolve_path: impl Fn(String) -> String,
    ) where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        for value in values {
            let value = value.into();
            if let Some(request) = module_request(&value) {
                self.referenced_dependencies
                    .push(crate::resolve::extract_package_name(request));
                continue;
            }
            self.push_entry_path(resolve_path(value));
        }
    }

    /// Route each value of a rollup-style `input` to both surfaces when it is
    /// ambiguous.
    ///
    /// Rollup, rolldown and vite resolve an `input` value with no importer: a
    /// resolve plugin can read it as a module request, and without one it is a
    /// path relative to the working directory. A value without `./`, `../` or
    /// `/`, without a source extension and without glob syntax can therefore
    /// name either one. It keeps the entry pattern, and it credits the package
    /// unless the value names a file under `root`. A value that names a
    /// project file is a path, so it must not hide an unused package that has
    /// the same first segment (issue #2753).
    fn extend_entry_patterns_and_dependencies<I, S>(&mut self, values: I, root: &Path)
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        for value in values {
            let value = value.into();
            if let Some(request) = module_request(&value)
                && !names_project_file(root, request)
            {
                self.referenced_dependencies
                    .push(crate::resolve::extract_package_name(request));
            }
            self.push_entry_path(value);
        }
    }

    /// Register each value as a bundler entry path.
    fn extend_entry_paths<I, S>(&mut self, values: I)
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        for value in values {
            self.push_entry_path(value.into());
        }
    }

    /// Register a bundler entry path.
    ///
    /// A bundler resolves an entry without a source extension the way it
    /// resolves an import: first as a file with each extension, then as a
    /// directory through its index file. `./lib` therefore names
    /// `lib/index.ts`, and `./src/app` names `src/app.ts`. The value as written
    /// stays a pattern too, so a file without an extension still matches.
    fn push_entry_path(&mut self, value: String) {
        if has_glob_syntax(&value) || has_source_extension(&value) {
            self.push_entry_pattern(value);
            return;
        }
        let base = value.trim_end_matches('/').to_owned();
        self.push_entry_pattern(value);
        self.push_entry_pattern(format!("{base}.{REQUEST_EXTENSIONS}"));
        self.push_entry_pattern(format!("{base}/index.{REQUEST_EXTENSIONS}"));
    }

    fn push_used_export_rule(
        &mut self,
        pattern: impl Into<String>,
        exports: impl IntoIterator<Item = impl Into<String>>,
    ) {
        self.used_exports
            .push(UsedExportRule::new(pattern, exports));
    }

    /// Whether this result contributes nothing, which lets the registry skip a
    /// config file entirely.
    ///
    /// A config that yields only a diagnostic is NOT empty: an unreadable
    /// `exposes` in a config that declares nothing else is exactly the case the
    /// advisory exists for, and skipping the result would drop it.
    #[must_use]
    const fn is_empty(&self) -> bool {
        self.config_diagnostics.is_empty()
            && self.entry_patterns.is_empty()
            && self.used_exports.is_empty()
            && self.used_class_members.is_empty()
            && self.referenced_dependencies.is_empty()
            && self.package_referenced_dependencies.is_empty()
            && self.always_used_files.is_empty()
            && self.path_aliases.is_empty()
            && self.setup_files.is_empty()
            && self.fixture_patterns.is_empty()
            && self.scss_include_paths.is_empty()
            && self.static_dir_mappings.is_empty()
            && self.framework_static_dir_mappings.is_empty()
            && self.provided_dependencies.is_empty()
            && self.federation_sources.is_empty()
    }
}

/// Whether an extensionless value names a file under `root`: the value itself,
/// the value with a source extension, or the index file of the directory it
/// names. This is the order in which a bundler resolves a path.
fn names_project_file(root: &Path, value: &str) -> bool {
    let base = root.join(value);
    base.is_file()
        || crate::discover::SOURCE_EXTENSIONS.iter().any(|extension| {
            let mut candidate = base.clone().into_os_string();
            candidate.push(".");
            candidate.push(extension);
            Path::new(&candidate).is_file() || base.join(format!("index.{extension}")).is_file()
        })
}

/// Brace list of the extensions a bundler tries for a request that names no
/// extension. Entry patterns are plain globs with no extension expansion, so a
/// bare `src/Button` would match no file.
const REQUEST_EXTENSIONS: &str = "{ts,tsx,mts,cts,gts,js,jsx,mjs,cjs,gjs,vue,svelte,astro,mdx}";

fn normalize_entry_pattern(pattern: String) -> String {
    pattern
        .strip_prefix("./")
        .map(str::to_owned)
        .unwrap_or(pattern)
}

/// The module request a config value names, or `None` when the value names a
/// file or a pattern over project files.
///
/// A bundler resolves a value without a leading `./`, `../` or `/` and without a
/// source extension through module resolution, so it names a package. Both
/// Module Federation `exposes` targets and bundler `entry` values are read this
/// way. A value carrying glob syntax is a path in every case: no module
/// resolution accepts a glob, so `src/pages/**` stays an entry pattern. A
/// resource query is not part of the request, so it is dropped before both
/// tests and before the package name is taken.
fn module_request(value: &str) -> Option<&str> {
    let request = strip_resource_query(value);
    (config_parser::is_package_specifier(request)
        && !has_glob_syntax(request)
        && !has_source_extension(request))
    .then_some(request)
}

/// Drop a trailing resource query from a config value.
///
/// A bundler hands everything after the first `?` to the loader, so the standard
/// hot-reload entry `webpack-hot-middleware/client?reload=true` names the
/// package's `client` module. A `?` is also the single-character glob wildcard,
/// so what follows it decides: `reload=true` is a query, the `.ts` of
/// `src/pag?.ts` is not.
fn strip_resource_query(value: &str) -> &str {
    match value.split_once('?') {
        Some((request, query)) if is_resource_query(query) => request,
        _ => value,
    }
}

/// Whether a string is an `&`-separated list of `key` or `key=value` pairs whose
/// keys read like identifiers.
fn is_resource_query(query: &str) -> bool {
    !query.is_empty()
        && query.split('&').all(|pair| {
            let key = pair.split_once('=').map_or(pair, |(key, _)| key);
            key.starts_with(|first: char| first.is_ascii_alphanumeric() || first == '_')
                && key
                    .chars()
                    .all(|char| char.is_ascii_alphanumeric() || matches!(char, '_' | '-' | '.'))
        })
}

/// Whether a config value carries glob metacharacters, which makes it a pattern
/// over project files rather than a single path or module request.
fn has_glob_syntax(value: &str) -> bool {
    value.contains('*') || value.contains('?') || value.contains('[') || value.contains('{')
}

/// Whether a config value carries an extension discovery analyzes. Discovery's
/// own extension set decides, so a value naming a file type discovery does not
/// analyze stays a module request.
fn has_source_extension(value: &str) -> bool {
    Path::new(value)
        .extension()
        .and_then(|ext| ext.to_str())
        .is_some_and(|ext| {
            crate::discover::SOURCE_EXTENSIONS.contains(&ext.to_ascii_lowercase().as_str())
        })
}

/// A file-pattern rule with optional exclusion globs plus path-level or
/// segment-level regex filters.
///
/// Exclusion regexes are matched against the project-relative path and should be
/// anchored when generated dynamically so they can be safely workspace-prefixed.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct PathRule {
    pub pattern: String,
    pub exclude_globs: Vec<String>,
    pub exclude_regexes: Vec<String>,
    /// Regexes matched against individual path segments. These are not prefixed
    /// for workspaces because they intentionally operate on segment names rather
    /// than the full project-relative path.
    pub exclude_segment_regexes: Vec<String>,
    /// Whether the leading `../` segments of `pattern` are relative to the
    /// plugin root, so the workspace prefix resolves them. Only the Module
    /// Federation reader sets it, for an `exposes` target in a sibling
    /// workspace. Other plugins emit patterns relative to a config directory,
    /// such as the Storybook `../src/**`, which must not climb out of the
    /// workspace.
    pub parent_relative: bool,
}

impl PathRule {
    #[must_use]
    pub(crate) fn new(pattern: impl Into<String>) -> Self {
        Self {
            pattern: pattern.into(),
            exclude_globs: Vec::new(),
            exclude_regexes: Vec::new(),
            exclude_segment_regexes: Vec::new(),
            parent_relative: false,
        }
    }

    #[must_use]
    fn from_static(pattern: &'static str) -> Self {
        Self::new(pattern)
    }

    #[must_use]
    pub(crate) fn with_excluded_globs<I, S>(mut self, patterns: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.exclude_globs
            .extend(patterns.into_iter().map(Into::into));
        self
    }

    #[must_use]
    fn with_excluded_regexes<I, S>(mut self, patterns: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.exclude_regexes
            .extend(patterns.into_iter().map(Into::into));
        self
    }

    #[must_use]
    fn with_excluded_segment_regexes<I, S>(mut self, patterns: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.exclude_segment_regexes
            .extend(patterns.into_iter().map(Into::into));
        self
    }

    #[must_use]
    fn prefixed(&self, ws_prefix: &str) -> Self {
        let pattern = if self.parent_relative && self.pattern.starts_with("../") {
            resolve_parent_relative_pattern(&self.pattern, ws_prefix)
        } else {
            prefix_workspace_pattern(&self.pattern, ws_prefix)
        };
        Self {
            pattern,
            exclude_globs: self
                .exclude_globs
                .iter()
                .map(|pattern| prefix_workspace_pattern(pattern, ws_prefix))
                .collect(),
            exclude_regexes: self
                .exclude_regexes
                .iter()
                .map(|pattern| prefix_workspace_regex(pattern, ws_prefix))
                .collect(),
            exclude_segment_regexes: self.exclude_segment_regexes.clone(),
            parent_relative: false,
        }
    }
}

/// A used-export rule bound to a file-pattern rule.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct UsedExportRule {
    pub(crate) path: PathRule,
    pub(crate) exports: Vec<String>,
}

impl UsedExportRule {
    #[must_use]
    pub(crate) fn new(
        pattern: impl Into<String>,
        exports: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        Self {
            path: PathRule::new(pattern),
            exports: exports.into_iter().map(Into::into).collect(),
        }
    }

    #[must_use]
    fn from_static(pattern: &'static str, exports: &'static [&'static str]) -> Self {
        Self::new(pattern, exports.iter().copied())
    }

    #[must_use]
    fn with_excluded_globs<I, S>(mut self, patterns: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.path = self.path.with_excluded_globs(patterns);
        self
    }

    #[must_use]
    fn with_excluded_regexes<I, S>(mut self, patterns: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.path = self.path.with_excluded_regexes(patterns);
        self
    }

    #[must_use]
    fn with_excluded_segment_regexes<I, S>(mut self, patterns: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.path = self.path.with_excluded_segment_regexes(patterns);
        self
    }

    #[must_use]
    fn prefixed(&self, ws_prefix: &str) -> Self {
        Self {
            path: self.path.prefixed(ws_prefix),
            exports: self.exports.clone(),
        }
    }
}

/// A used-export rule tagged with the plugin that contributed it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PluginUsedExportRule {
    pub(crate) plugin_name: String,
    pub(crate) rule: UsedExportRule,
}

impl PluginUsedExportRule {
    #[must_use]
    pub(crate) fn new(plugin_name: impl Into<String>, rule: UsedExportRule) -> Self {
        Self {
            plugin_name: plugin_name.into(),
            rule,
        }
    }

    #[must_use]
    fn prefixed(&self, ws_prefix: &str) -> Self {
        Self {
            plugin_name: self.plugin_name.clone(),
            rule: self.rule.prefixed(ws_prefix),
        }
    }
}

/// A file-scoped dependency provider rule contributed by a framework plugin.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ProvidedDependencyRule {
    pub(crate) path: PathRule,
    exact_specifiers: Vec<String>,
    specifier_prefixes: Vec<String>,
}

impl ProvidedDependencyRule {
    #[must_use]
    fn new(
        pattern: impl Into<String>,
        exact_specifiers: impl IntoIterator<Item = impl Into<String>>,
        specifier_prefixes: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        Self {
            path: PathRule::new(pattern),
            exact_specifiers: exact_specifiers.into_iter().map(Into::into).collect(),
            specifier_prefixes: specifier_prefixes.into_iter().map(Into::into).collect(),
        }
    }

    #[must_use]
    fn prefixed(&self, ws_prefix: &str) -> Self {
        Self {
            path: self.path.prefixed(ws_prefix),
            exact_specifiers: self.exact_specifiers.clone(),
            specifier_prefixes: self.specifier_prefixes.clone(),
        }
    }

    #[must_use]
    pub(crate) fn may_cover_package(&self, package_name: &str) -> bool {
        self.exact_specifiers
            .iter()
            .chain(self.specifier_prefixes.iter())
            .any(|specifier| crate::resolve::extract_package_name(specifier) == package_name)
    }

    #[must_use]
    pub(crate) fn covers_specifier(&self, specifier: &str) -> bool {
        self.exact_specifiers
            .iter()
            .any(|allowed| allowed == specifier)
            || self
                .specifier_prefixes
                .iter()
                .any(|prefix| specifier.starts_with(prefix))
    }
}

/// A compiled path rule matcher shared by entry-point and used-export matching.
#[derive(Debug, Clone)]
pub(crate) struct CompiledPathRule {
    include: globset::GlobMatcher,
    exclude_globs: Vec<globset::GlobMatcher>,
    exclude_regexes: Vec<Regex>,
    exclude_segment_regexes: Vec<Regex>,
}

impl CompiledPathRule {
    pub(crate) fn for_entry_rule(rule: &PathRule, rule_kind: &str) -> Option<Self> {
        let include = match globset::GlobBuilder::new(&rule.pattern)
            .literal_separator(true)
            .build()
        {
            Ok(glob) => glob.compile_matcher(),
            Err(err) => {
                tracing::warn!("invalid {rule_kind} '{}': {err}", rule.pattern);
                return None;
            }
        };
        Some(Self {
            include,
            exclude_globs: compile_excluded_globs(&rule.exclude_globs, rule_kind, &rule.pattern),
            exclude_regexes: compile_excluded_regexes(
                &rule.exclude_regexes,
                rule_kind,
                &rule.pattern,
            ),
            exclude_segment_regexes: compile_excluded_segment_regexes(
                &rule.exclude_segment_regexes,
                rule_kind,
                &rule.pattern,
            ),
        })
    }

    pub(crate) fn for_used_export_rule(rule: &PathRule, rule_kind: &str) -> Option<Self> {
        let include = match globset::Glob::new(&rule.pattern) {
            Ok(glob) => glob.compile_matcher(),
            Err(err) => {
                tracing::warn!("invalid {rule_kind} '{}': {err}", rule.pattern);
                return None;
            }
        };
        Some(Self {
            include,
            exclude_globs: compile_excluded_globs(&rule.exclude_globs, rule_kind, &rule.pattern),
            exclude_regexes: compile_excluded_regexes(
                &rule.exclude_regexes,
                rule_kind,
                &rule.pattern,
            ),
            exclude_segment_regexes: compile_excluded_segment_regexes(
                &rule.exclude_segment_regexes,
                rule_kind,
                &rule.pattern,
            ),
        })
    }

    #[must_use]
    pub(crate) fn matches(&self, path: &str) -> bool {
        self.include.is_match(path)
            && !self.exclude_globs.iter().any(|glob| glob.is_match(path))
            && !self
                .exclude_regexes
                .iter()
                .any(|regex| regex.is_match(path))
            && !matches_segment_regex(path, &self.exclude_segment_regexes)
    }
}

fn prefix_workspace_pattern(pattern: &str, ws_prefix: &str) -> String {
    if pattern.starts_with(ws_prefix) || pattern.starts_with('/') {
        pattern.to_string()
    } else {
        format!("{ws_prefix}/{pattern}")
    }
}

/// Resolve the leading `../` segments of a parent-relative pattern against the
/// workspace prefix, so a pattern that names a file in a sibling workspace
/// matches from the project root. A pattern that climbs past the project root,
/// or a prefix that is not project-relative, keeps the pattern as written,
/// which matches no project file.
fn resolve_parent_relative_pattern(pattern: &str, ws_prefix: &str) -> String {
    if ws_prefix.starts_with('/') || Path::new(ws_prefix).is_absolute() {
        return pattern.to_string();
    }
    // The workspace prefix comes from a native path, so on Windows its
    // segments are separated by backslashes.
    let mut base: Vec<&str> = ws_prefix
        .split(['/', '\\'])
        .filter(|segment| !segment.is_empty())
        .collect();
    let mut rest = pattern;
    while let Some(stripped) = rest.strip_prefix("../") {
        if base.pop().is_none() {
            return pattern.to_string();
        }
        rest = stripped;
    }
    if base.is_empty() {
        rest.to_string()
    } else {
        format!("{}/{rest}", base.join("/"))
    }
}

fn prefix_workspace_regex(pattern: &str, ws_prefix: &str) -> String {
    if let Some(pattern) = pattern.strip_prefix('^') {
        format!("^{}/{}", regex::escape(ws_prefix), pattern)
    } else {
        format!("^{}/(?:{})", regex::escape(ws_prefix), pattern)
    }
}

fn compile_excluded_globs(
    patterns: &[String],
    rule_kind: &str,
    rule_pattern: &str,
) -> Vec<globset::GlobMatcher> {
    patterns
        .iter()
        .filter_map(|pattern| {
            match globset::GlobBuilder::new(pattern)
                .literal_separator(true)
                .build()
            {
                Ok(glob) => Some(glob.compile_matcher()),
                Err(err) => {
                    tracing::warn!(
                        "skipping invalid excluded glob '{}' for {} '{}': {err}",
                        pattern,
                        rule_kind,
                        rule_pattern
                    );
                    None
                }
            }
        })
        .collect()
}

fn compile_excluded_regexes(
    patterns: &[String],
    rule_kind: &str,
    rule_pattern: &str,
) -> Vec<Regex> {
    patterns
        .iter()
        .filter_map(|pattern| match Regex::new(pattern) {
            Ok(regex) => Some(regex),
            Err(err) => {
                tracing::warn!(
                    "skipping invalid excluded regex '{}' for {} '{}': {err}",
                    pattern,
                    rule_kind,
                    rule_pattern
                );
                None
            }
        })
        .collect()
}

fn compile_excluded_segment_regexes(
    patterns: &[String],
    rule_kind: &str,
    rule_pattern: &str,
) -> Vec<Regex> {
    patterns
        .iter()
        .filter_map(|pattern| match Regex::new(pattern) {
            Ok(regex) => Some(regex),
            Err(err) => {
                tracing::warn!(
                    "skipping invalid excluded segment regex '{}' for {} '{}': {err}",
                    pattern,
                    rule_kind,
                    rule_pattern
                );
                None
            }
        })
        .collect()
}

fn matches_segment_regex(path: &str, regexes: &[Regex]) -> bool {
    path.split('/')
        .any(|segment| regexes.iter().any(|regex| regex.is_match(segment)))
}

impl From<String> for PathRule {
    fn from(pattern: String) -> Self {
        Self::new(pattern)
    }
}

impl From<&str> for PathRule {
    fn from(pattern: &str) -> Self {
        Self::new(pattern)
    }
}

impl std::ops::Deref for PathRule {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        &self.pattern
    }
}

impl PartialEq<&str> for PathRule {
    fn eq(&self, other: &&str) -> bool {
        self.pattern == *other
    }
}

impl PartialEq<str> for PathRule {
    fn eq(&self, other: &str) -> bool {
        self.pattern == other
    }
}

impl PartialEq<String> for PathRule {
    fn eq(&self, other: &String) -> bool {
        &self.pattern == other
    }
}

/// A framework/tool plugin that contributes to dead code analysis.
pub trait Plugin: Send + Sync {
    /// Human-readable plugin name.
    fn name(&self) -> &'static str;

    /// Package names that activate this plugin when found in package.json.
    /// Supports exact matches and prefix patterns (ending with `/`).
    fn enablers(&self) -> &'static [&'static str] {
        &[]
    }

    /// Check if this plugin should be active for the given project.
    /// Default implementation checks `enablers()` against package.json dependencies.
    fn is_enabled(&self, pkg: &PackageJson, root: &Path) -> bool {
        let deps = pkg.all_dependency_names();
        self.is_enabled_with_deps(&deps, root)
    }

    /// Fast variant of `is_enabled` that accepts a pre-computed deps list.
    /// Avoids repeated `all_dependency_names()` allocation when checking many plugins.
    fn is_enabled_with_deps(&self, deps: &[String], _root: &Path) -> bool {
        let enablers = self.enablers();
        if enablers.is_empty() {
            return false;
        }
        enablers.iter().any(|enabler| {
            if enabler.ends_with('/') {
                // Prefix match (e.g., "@storybook/" matches "@storybook/react")
                deps.iter().any(|d| d.starts_with(enabler))
            } else {
                deps.iter().any(|d| d == enabler)
            }
        })
    }

    /// Check whether this plugin should be active with source discovery available.
    ///
    /// Most plugins only need dependency/config activation. Convention-only tools
    /// can override this to activate from discovered source filenames without
    /// forcing a separate filesystem walk.
    ///
    /// `candidate_index` is the discovery walk's in-memory listing of source +
    /// non-source config-candidate files (`Some` outside production mode, `None`
    /// in production). A plugin that activates on a non-source sentinel file
    /// (`manifest.json`, `.env.schema`) can consult it to avoid a per-directory
    /// filesystem probe; when it is `None`, the plugin falls back to the
    /// filesystem.
    fn is_enabled_with_files(
        &self,
        deps: &[String],
        root: &Path,
        _discovered_files: &[PathBuf],
        _candidate_index: Option<&registry::ConfigCandidateIndex>,
    ) -> bool {
        self.is_enabled_with_deps(deps, root)
    }

    /// Package-script binary/package names that can activate this plugin.
    fn script_enablers(&self) -> &'static [&'static str] {
        &[]
    }

    /// Check whether this plugin should be active from package.json scripts.
    fn is_enabled_with_scripts(
        &self,
        script_packages: &rustc_hash::FxHashSet<String>,
        _root: &Path,
    ) -> bool {
        let enablers = self.script_enablers();
        if enablers.is_empty() {
            return false;
        }
        enablers.iter().any(|enabler| {
            if enabler.ends_with('/') {
                script_packages
                    .iter()
                    .any(|package| package.starts_with(enabler))
            } else {
                script_packages.contains(*enabler)
            }
        })
    }

    /// Default glob patterns for entry point files.
    fn entry_patterns(&self) -> &'static [&'static str] {
        &[]
    }

    /// Entry point rules with optional exclusions.
    fn entry_pattern_rules(&self) -> Vec<PathRule> {
        self.entry_patterns()
            .iter()
            .map(|pattern| PathRule::from_static(pattern))
            .collect()
    }

    /// How this plugin's entry patterns should contribute to coverage reachability.
    ///
    /// `Support` roots keep files alive for dead-code analysis but do not count
    /// as runtime or test reachability for static coverage gaps.
    fn entry_point_role(&self) -> EntryPointRole {
        builtin_entry_point_role(self.name())
    }

    /// Glob patterns for config files this plugin can parse.
    fn config_patterns(&self) -> &'static [&'static str] {
        &[]
    }

    /// Files that are always considered "used" when this plugin is active.
    fn always_used(&self) -> &'static [&'static str] {
        &[]
    }

    /// Exports that are always considered used for matching file patterns.
    fn used_exports(&self) -> Vec<(&'static str, &'static [&'static str])> {
        vec![]
    }

    /// Used-export rules with optional exclusions.
    fn used_export_rules(&self) -> Vec<UsedExportRule> {
        self.used_exports()
            .into_iter()
            .map(|(pattern, exports)| UsedExportRule::from_static(pattern, exports))
            .collect()
    }

    /// Class member names the framework invokes at runtime. Matching members
    /// are skipped during `unused-class-members` analysis. Intended for
    /// interface/contract patterns where the library calls methods on consumer
    /// classes (e.g. ag-Grid's `agInit`, Web Components' `connectedCallback`).
    fn used_class_members(&self) -> &'static [&'static str] {
        &[]
    }

    /// Heritage-scoped class member rules. Each rule applies only to classes
    /// matching its `extends` and/or `implements` clause. Used for frameworks
    /// where lifecycle members are runtime-invoked only on classes that extend
    /// a known base (e.g. Lit's `render`/`updated` on classes extending
    /// `LitElement`, native Web Components' `connectedCallback` on classes
    /// extending `HTMLElement`). Default: empty. Plugins override when they
    /// need scoping; flat names should still come from `used_class_members`.
    fn used_class_member_rules(&self) -> Vec<UsedClassMemberRule> {
        Vec::new()
    }

    /// Exact package-backed framework contracts that type-aware analysis may
    /// verify for latent class-member candidates.
    fn framework_class_member_contracts(&self) -> Vec<SemanticFrameworkContract> {
        Vec::new()
    }

    /// Glob patterns for test fixture files consumed by this framework.
    /// These files are implicitly used by the test runner and should not be
    /// flagged as unused. Unlike `always_used()`, this carries semantic intent
    /// for reporting purposes.
    fn fixture_glob_patterns(&self) -> &'static [&'static str] {
        &[]
    }

    /// Hidden directory names that should be traversed when this plugin is active.
    ///
    /// These are consulted before normal plugin execution because source discovery
    /// runs first. Keep entries static and package-convention scoped.
    fn discovery_hidden_dirs(&self) -> &'static [&'static str] {
        &[]
    }

    /// Dependencies that are tooling (used via CLI/config, not source imports).
    /// These should not be flagged as unused devDependencies.
    fn tooling_dependencies(&self) -> &'static [&'static str] {
        &[]
    }

    /// Import prefixes that are virtual modules provided by this framework at build time.
    /// Imports matching these prefixes should not be flagged as unlisted dependencies.
    /// Each entry is matched as a prefix against the extracted package name
    /// (e.g., `"@theme/"` matches `@theme/Layout`).
    fn virtual_module_prefixes(&self) -> &'static [&'static str] {
        &[]
    }

    /// Package name suffixes that are virtual modules provided by this framework
    /// at build time (e.g., test runner mock conventions).
    /// Imports matching these suffixes should not be flagged as unlisted dependencies.
    /// Each entry is matched as a suffix against the extracted package name
    /// (e.g., `"/__mocks__"` matches `@aws-sdk/__mocks__` and `some-pkg/__mocks__`).
    fn virtual_package_suffixes(&self) -> &'static [&'static str] {
        &[]
    }

    /// Import suffixes for build-time generated relative imports.
    ///
    /// Unresolved relative imports whose specifier ends with one of these suffixes
    /// will not be flagged as unresolved. For example, SvelteKit generates
    /// `./$types` imports in route files, returning `"/$types"` suppresses those.
    fn generated_import_patterns(&self) -> &'static [&'static str] {
        &[]
    }

    /// Import prefixes for generated type-only relative imports.
    ///
    /// Unresolved type-only imports whose specifier starts with one of these prefixes
    /// will not be flagged as unresolved. Runtime imports are still reported.
    fn generated_type_import_prefixes(&self) -> &'static [&'static str] {
        &[]
    }

    /// Path alias mappings provided by this framework at build time.
    ///
    /// Returns a list of `(prefix, replacement_dir)` tuples. When an import starting
    /// with `prefix` fails to resolve, the resolver will substitute the prefix with
    /// `replacement_dir` (relative to the project root) and retry.
    ///
    /// Called once when plugins are activated. The project `root` is provided so
    /// plugins can inspect the filesystem (e.g., Nuxt checks whether `app/` exists
    /// to determine the `srcDir`).
    fn path_aliases(&self, _root: &Path) -> Vec<(&'static str, String)> {
        vec![]
    }

    /// Directories this framework serves at a URL mount by convention, so a
    /// root-absolute reference in ANY HTML document in the project names a file
    /// inside one.
    ///
    /// Called once when plugins are activated, with the project `root`, so a
    /// plugin can require the directory to exist before claiming it.
    ///
    /// Distinct from the config-file mounts a tool declares from
    /// `resolve_config` (Storybook `staticDirs`), which stay scoped to that
    /// tool's own documents. A convention here describes how the whole project
    /// is served, so it is not scoped that way.
    fn static_dir_mappings(&self, _root: &Path) -> Vec<(std::path::PathBuf, String)> {
        vec![]
    }

    /// Convention-based auto-imports provided by this framework.
    ///
    /// Returns the names this framework exposes to user code by filesystem
    /// convention with no explicit `import` statement (e.g. Nuxt `components/`
    /// resolved by `<Card001 />` template tags), each mapped to the source file
    /// providing the export. When a file references one of these names without an
    /// import, the resolver synthesizes a graph edge to `source`.
    ///
    /// Called once when plugins are activated. The project `root` is provided so
    /// plugins can scan the convention directories on the filesystem. The table is
    /// a function of which files exist on disk, so it is rebuilt every run and is
    /// never folded into per-file extraction caching. See issue #704.
    ///
    /// A rule with an empty `scope` is visible to the files under `root` only.
    /// A plugin can set `scope` itself to make a rule visible to more roots.
    /// After the plugin runs, a shared step links a Nuxt app and each layer
    /// outside it in both directions. See issue #2752.
    fn auto_imports(&self, _root: &Path) -> Vec<AutoImportRule> {
        Vec::new()
    }

    /// File-scoped dependency providers contributed by this framework.
    fn provided_dependencies(&self) -> Vec<ProvidedDependencyRule> {
        Vec::new()
    }

    /// Check whether parsed package.json metadata activates this plugin.
    fn is_enabled_with_package_json(&self, _pkg: &PackageJson, _root: &Path) -> bool {
        false
    }

    /// Resolve parsed package.json metadata into dynamic plugin facts.
    fn resolve_package_json(&self, _pkg: &PackageJson, _root: &Path) -> PluginResult {
        PluginResult::default()
    }

    /// Dependencies referenced by the package's own package.json metadata.
    ///
    /// Unlike config-derived dependencies, these credits apply only to the
    /// package.json that produced them.
    fn package_json_referenced_dependencies(
        &self,
        _pkg: &PackageJson,
        _root: &Path,
    ) -> Vec<String> {
        Vec::new()
    }

    /// Parse a config file's AST to discover additional entries, dependencies, etc.
    ///
    /// Called for each config file matching `config_patterns()`. The source code
    /// and parsed AST are provided, use [`config_parser`] utilities to extract values.
    fn resolve_config(&self, _config_path: &Path, _source: &str, _root: &Path) -> PluginResult {
        PluginResult::default()
    }

    /// The key name in package.json that holds inline configuration for this tool.
    /// When set (e.g., `"jest"` for the `"jest"` key in package.json), the plugin
    /// system will extract that key's value and call `resolve_config` with its
    /// JSON content if no standalone config file was found.
    fn package_json_config_key(&self) -> Option<&'static str> {
        None
    }
}

fn builtin_entry_point_role(name: &str) -> EntryPointRole {
    if TEST_ENTRY_POINT_PLUGINS.contains(&name) {
        EntryPointRole::Test
    } else if RUNTIME_ENTRY_POINT_PLUGINS.contains(&name) {
        EntryPointRole::Runtime
    } else {
        EntryPointRole::Support
    }
}

/// Macro to eliminate boilerplate in plugin implementations.
///
/// Generates a struct and a `Plugin` trait impl with the standard static methods
/// (`name`, `enablers`, `entry_patterns`, `config_patterns`, `always_used`, `tooling_dependencies`,
/// `fixture_glob_patterns`, `virtual_module_prefixes`, `virtual_package_suffixes`,
/// `generated_type_import_prefixes`, `used_exports`).
///
/// For plugins that need custom `resolve_config()` or `is_enabled()`, keep those as
/// manual `impl Plugin for ...` blocks instead of using this macro.
///
/// # Usage
///
/// ```ignore
/// // Simple plugin (most common):
/// define_plugin! {
///     struct VitePlugin => "vite",
///     enablers: ENABLERS,
///     entry_patterns: ENTRY_PATTERNS,
///     config_patterns: CONFIG_PATTERNS,
///     always_used: ALWAYS_USED,
///     tooling_dependencies: TOOLING_DEPENDENCIES,
/// }
///
/// // Plugin with used_exports:
/// define_plugin! {
///     struct RemixPlugin => "remix",
///     enablers: ENABLERS,
///     entry_patterns: ENTRY_PATTERNS,
///     always_used: ALWAYS_USED,
///     tooling_dependencies: TOOLING_DEPENDENCIES,
///     used_exports: [("app/routes/**/*.{ts,tsx}", ROUTE_EXPORTS)],
/// }
///
/// // Plugin with imports-only resolve_config (extracts imports from config as deps):
/// define_plugin! {
///     struct CypressPlugin => "cypress",
///     enablers: ENABLERS,
///     entry_patterns: ENTRY_PATTERNS,
///     config_patterns: CONFIG_PATTERNS,
///     always_used: ALWAYS_USED,
///     tooling_dependencies: TOOLING_DEPENDENCIES,
///     resolve_config: imports_only,
/// }
///
/// // Plugin with custom resolve_config body:
/// define_plugin! {
///     struct RollupPlugin => "rollup",
///     enablers: ENABLERS,
///     config_patterns: CONFIG_PATTERNS,
///     always_used: ALWAYS_USED,
///     tooling_dependencies: TOOLING_DEPENDENCIES,
///     resolve_config(config_path, source, _root) {
///         let mut result = PluginResult::default();
///         // custom config parsing...
///         result
///     }
/// }
/// ```
///
/// All fields except `struct` and `enablers` are optional and default to `&[]` / `vec![]`.
macro_rules! define_plugin {
    (
        struct $name:ident => $display:expr,
        enablers: $enablers:expr
        $(, entry_patterns: $entry:expr)?
        $(, config_patterns: $config:expr)?
        $(, always_used: $always:expr)?
        $(, tooling_dependencies: $tooling:expr)?
        $(, fixture_glob_patterns: $fixtures:expr)?
        $(, discovery_hidden_dirs: $hidden_dirs:expr)?
        $(, virtual_module_prefixes: $virtual:expr)?
        $(, virtual_package_suffixes: $virtual_suffixes:expr)?
        $(, generated_type_import_prefixes: $generated_type_prefixes:expr)?
        $(, provided_dependencies: $provided_dependencies:expr)?
        $(, used_exports: [$( ($pat:expr, $exports:expr) ),* $(,)?])?
        , resolve_config: imports_only
        $(,)?
    ) => {
        pub struct $name;

        impl Plugin for $name {
            fn name(&self) -> &'static str {
                $display
            }

            fn enablers(&self) -> &'static [&'static str] {
                $enablers
            }

            $( fn entry_patterns(&self) -> &'static [&'static str] { $entry } )?
            $( fn config_patterns(&self) -> &'static [&'static str] { $config } )?
            $( fn always_used(&self) -> &'static [&'static str] { $always } )?
            $( fn tooling_dependencies(&self) -> &'static [&'static str] { $tooling } )?
            $( fn fixture_glob_patterns(&self) -> &'static [&'static str] { $fixtures } )?
            $( fn discovery_hidden_dirs(&self) -> &'static [&'static str] { $hidden_dirs } )?
            $( fn virtual_module_prefixes(&self) -> &'static [&'static str] { $virtual } )?
            $( fn virtual_package_suffixes(&self) -> &'static [&'static str] { $virtual_suffixes } )?
            $( fn generated_type_import_prefixes(&self) -> &'static [&'static str] { $generated_type_prefixes } )?
            $( fn provided_dependencies(&self) -> Vec<ProvidedDependencyRule> { $provided_dependencies } )?

            $(
                fn used_exports(&self) -> Vec<(&'static str, &'static [&'static str])> {
                    vec![$( ($pat, $exports) ),*]
                }
            )?

            fn resolve_config(
                &self,
                config_path: &std::path::Path,
                source: &str,
                _root: &std::path::Path,
            ) -> PluginResult {
                let mut result = PluginResult::default();
                crate::plugins::add_import_referenced_dependencies(
                    &mut result,
                    source,
                    config_path,
                );
                result
            }
        }
    };

    (
        struct $name:ident => $display:expr,
        enablers: $enablers:expr
        $(, entry_patterns: $entry:expr)?
        $(, config_patterns: $config:expr)?
        $(, always_used: $always:expr)?
        $(, tooling_dependencies: $tooling:expr)?
        $(, fixture_glob_patterns: $fixtures:expr)?
        $(, discovery_hidden_dirs: $hidden_dirs:expr)?
        $(, virtual_module_prefixes: $virtual:expr)?
        $(, virtual_package_suffixes: $virtual_suffixes:expr)?
        $(, generated_type_import_prefixes: $generated_type_prefixes:expr)?
        $(, provided_dependencies: $provided_dependencies:expr)?
        $(, package_json_config_key: $pkg_key:expr)?
        $(, used_exports: [$( ($pat:expr, $exports:expr) ),* $(,)?])?
        , resolve_config($cp:ident, $src:ident, $root:ident) $body:block
        $(,)?
    ) => {
        pub struct $name;

        impl Plugin for $name {
            fn name(&self) -> &'static str {
                $display
            }

            fn enablers(&self) -> &'static [&'static str] {
                $enablers
            }

            $( fn entry_patterns(&self) -> &'static [&'static str] { $entry } )?
            $( fn config_patterns(&self) -> &'static [&'static str] { $config } )?
            $( fn always_used(&self) -> &'static [&'static str] { $always } )?
            $( fn tooling_dependencies(&self) -> &'static [&'static str] { $tooling } )?
            $( fn fixture_glob_patterns(&self) -> &'static [&'static str] { $fixtures } )?
            $( fn discovery_hidden_dirs(&self) -> &'static [&'static str] { $hidden_dirs } )?
            $( fn virtual_module_prefixes(&self) -> &'static [&'static str] { $virtual } )?
            $( fn virtual_package_suffixes(&self) -> &'static [&'static str] { $virtual_suffixes } )?
            $( fn generated_type_import_prefixes(&self) -> &'static [&'static str] { $generated_type_prefixes } )?
            $( fn provided_dependencies(&self) -> Vec<ProvidedDependencyRule> { $provided_dependencies } )?

            $(
                fn package_json_config_key(&self) -> Option<&'static str> {
                    Some($pkg_key)
                }
            )?

            $(
                fn used_exports(&self) -> Vec<(&'static str, &'static [&'static str])> {
                    vec![$( ($pat, $exports) ),*]
                }
            )?

            fn resolve_config(
                &self,
                $cp: &std::path::Path,
                $src: &str,
                $root: &std::path::Path,
            ) -> PluginResult
            $body
        }
    };

    (
        struct $name:ident => $display:expr,
        enablers: $enablers:expr
        $(, entry_patterns: $entry:expr)?
        $(, config_patterns: $config:expr)?
        $(, always_used: $always:expr)?
        $(, tooling_dependencies: $tooling:expr)?
        $(, fixture_glob_patterns: $fixtures:expr)?
        $(, discovery_hidden_dirs: $hidden_dirs:expr)?
        $(, virtual_module_prefixes: $virtual:expr)?
        $(, virtual_package_suffixes: $virtual_suffixes:expr)?
        $(, generated_type_import_prefixes: $generated_type_prefixes:expr)?
        $(, provided_dependencies: $provided_dependencies:expr)?
        $(, used_exports: [$( ($pat:expr, $exports:expr) ),* $(,)?])?
        $(,)?
    ) => {
        pub struct $name;

        impl Plugin for $name {
            fn name(&self) -> &'static str {
                $display
            }

            fn enablers(&self) -> &'static [&'static str] {
                $enablers
            }

            $( fn entry_patterns(&self) -> &'static [&'static str] { $entry } )?
            $( fn config_patterns(&self) -> &'static [&'static str] { $config } )?
            $( fn always_used(&self) -> &'static [&'static str] { $always } )?
            $( fn tooling_dependencies(&self) -> &'static [&'static str] { $tooling } )?
            $( fn fixture_glob_patterns(&self) -> &'static [&'static str] { $fixtures } )?
            $( fn discovery_hidden_dirs(&self) -> &'static [&'static str] { $hidden_dirs } )?
            $( fn virtual_module_prefixes(&self) -> &'static [&'static str] { $virtual } )?
            $( fn virtual_package_suffixes(&self) -> &'static [&'static str] { $virtual_suffixes } )?
            $( fn generated_type_import_prefixes(&self) -> &'static [&'static str] { $generated_type_prefixes } )?
            $( fn provided_dependencies(&self) -> Vec<ProvidedDependencyRule> { $provided_dependencies } )?

            $(
                fn used_exports(&self) -> Vec<(&'static str, &'static [&'static str])> {
                    vec![$( ($pat, $exports) ),*]
                }
            )?
        }
    };
}

pub mod config_parser;
mod config_value_credits;
mod manifest;
pub mod manifest_entries;
pub mod registry;
mod tooling;

pub(crate) use module_federation::runtime_remotes;
pub use registry::{AggregatedPluginResult, PluginRegistry};
pub(crate) use tooling::is_known_tooling_dependency;

fn add_import_referenced_dependencies(result: &mut PluginResult, source: &str, config_path: &Path) {
    let imports = config_parser::extract_imports(source, config_path);
    for import in &imports {
        result
            .referenced_dependencies
            .push(crate::resolve::extract_package_name(import));
    }
}

/// Credit the optional peer dependencies a test environment loads at runtime.
///
/// The rules are data: see the `test-environment-optional-peer` rows in
/// `crates/core/data/config_value_credits.toml`. `jsdom` requires its optional
/// peer `canvas` lazily when it is installed, so a project installing it for
/// real canvas support has no import of it anywhere and would see the
/// dependency reported as unused (issue #2005). Environments without such a
/// peer, like `happy-dom`, have no row.
///
/// Only names already declared in the manifest can be credited, so this never
/// invents an unlisted dependency.
fn credit_environment_optional_peers(environment: &str, result: &mut PluginResult) {
    credit_config_value(
        config_value_credits::CreditSurface::TestEnvironmentOptionalPeer,
        canonical_test_environment(environment),
        result,
    );
}

/// Record the catalogue credits for a config value, if any.
///
/// Returns whether a rule matched, which callers use when the credited packages
/// replace the dependencies derived from the value itself.
fn credit_config_value(
    surface: config_value_credits::CreditSurface,
    value: &str,
    result: &mut PluginResult,
) -> bool {
    let Some(packages) = config_value_credits::credited_packages(surface, value) else {
        return false;
    };
    result
        .referenced_dependencies
        .extend(packages.iter().cloned());
    true
}

/// Strip the runner prefix from a test environment specifier.
///
/// Both runners accept the bare name and the package it resolves to, so
/// `testEnvironment: "jest-environment-jsdom"` and `environment: "jsdom"` select
/// the same environment. Matching the literal short name only meant the fully
/// qualified form, which the Jest docs use and projects copy, was treated as a
/// third-party environment and missed its optional-peer credit.
fn canonical_test_environment(environment: &str) -> &str {
    environment
        .strip_prefix("jest-environment-")
        .or_else(|| environment.strip_prefix("vitest-environment-"))
        .unwrap_or(environment)
}

mod adonis;
mod angular;
mod astro;
mod ava;
mod babel;
mod biome;
mod browser_extension;
mod bun;
mod c8;
mod capacitor;
mod changesets;
mod commit_and_tag_version;
mod commitizen;
mod commitlint;
mod content_collections;
mod contentlayer;
mod convex;
mod cspell;
mod cucumber;
mod cypress;
mod danger;
mod deno;
mod dependency_cruiser;
mod docusaurus;
mod drizzle;
mod electron;
mod ember;
mod eslint;
mod expo;
mod expo_router;
mod firebase;
mod fumadocs;
mod gatsby;
mod graphql_codegen;
mod hardhat;
mod husky;
mod i18next;
mod ionic;
mod jest;
mod k6;
mod karma;
mod knex;
mod kysely;
mod lefthook;
mod lexical;
mod lint_staged;
mod lit;
mod markdownlint;
mod mintlify;
mod mocha;
mod module_federation;
mod msw;
mod napi_rs;
mod nestjs;
mod next_intl;
mod nextjs;
mod nitro;
mod nodemon;
pub(crate) mod nuxt;
mod nx;
mod nyc;
mod obsidian;
mod openapi_ts;
mod opencode;
mod opennext_cloudflare;
mod oxfmt;
mod oxlint;
mod pandacss;
mod parcel;
mod pinia;
mod pkg_utils;
mod playwright;
mod plop;
mod pm2;
mod pnpm;
mod postcss;
mod prettier;
mod prisma;
mod qwik;
mod react_compiler;
mod react_native;
mod react_router;
mod redwoodsdk;
mod relay;
mod remark;
mod remix;
mod rolldown;
mod rollup;
mod rsbuild;
mod rspack;
mod rspress;
mod sanity;
mod semantic_release;
mod sentry;
mod simple_git_hooks;
mod size_limit;
mod storybook;
mod stryker;
mod stylelint;
mod supabase;
mod sveltekit;
mod svgo;
mod svgr;
mod swc;
mod syncpack;
mod tailwind;
mod tanstack_router;
mod tap;
mod test_alias;
mod tsd;
mod tsdown;
mod tsup;
mod turborepo;
mod typedoc;
mod typeorm;
mod typescript;
mod unocss;
mod varlock;
mod velite;
mod vercel;
mod vite;
mod vitepress;
mod vitest;
mod vscode;
mod webdriverio;
mod webpack;
mod wrangler;
mod wuchale;
mod wxt;

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

    #[test]
    fn is_enabled_with_deps_exact_match() {
        let plugin = nextjs::NextJsPlugin;
        let deps = vec!["next".to_string()];
        assert!(plugin.is_enabled_with_deps(&deps, Path::new("/project")));
    }

    #[test]
    fn is_enabled_with_deps_no_match() {
        let plugin = nextjs::NextJsPlugin;
        let deps = vec!["react".to_string()];
        assert!(!plugin.is_enabled_with_deps(&deps, Path::new("/project")));
    }

    #[test]
    fn is_enabled_with_deps_empty_deps() {
        let plugin = nextjs::NextJsPlugin;
        let deps: Vec<String> = vec![];
        assert!(!plugin.is_enabled_with_deps(&deps, Path::new("/project")));
    }

    #[test]
    fn environment_optional_peers_come_from_the_credit_catalogue() {
        for environment in [
            "jsdom",
            "jest-environment-jsdom",
            "vitest-environment-jsdom",
        ] {
            let mut result = PluginResult::default();
            credit_environment_optional_peers(environment, &mut result);
            assert_eq!(
                result.referenced_dependencies,
                vec!["canvas".to_string()],
                "expected the catalogue credit for {environment}"
            );
        }
    }

    #[test]
    fn environment_without_a_catalogue_row_credits_nothing() {
        let mut result = PluginResult::default();
        credit_environment_optional_peers("happy-dom", &mut result);
        assert!(result.referenced_dependencies.is_empty());
    }

    #[test]
    fn entry_point_role_defaults_are_centralized() {
        assert_eq!(vite::VitePlugin.entry_point_role(), EntryPointRole::Runtime);
        assert_eq!(
            vitest::VitestPlugin.entry_point_role(),
            EntryPointRole::Test
        );
        assert_eq!(
            storybook::StorybookPlugin.entry_point_role(),
            EntryPointRole::Support
        );
        assert_eq!(
            obsidian::ObsidianPlugin.entry_point_role(),
            EntryPointRole::Runtime
        );
        assert_eq!(knex::KnexPlugin.entry_point_role(), EntryPointRole::Support);
    }

    #[test]
    fn plugins_with_entry_patterns_have_explicit_role_intent() {
        let runtime_or_test_or_support: rustc_hash::FxHashSet<&'static str> =
            TEST_ENTRY_POINT_PLUGINS
                .iter()
                .chain(RUNTIME_ENTRY_POINT_PLUGINS.iter())
                .chain(SUPPORT_ENTRY_POINT_PLUGINS.iter())
                .copied()
                .collect();

        for plugin in crate::plugins::registry::builtin::create_builtin_plugins() {
            if plugin.entry_patterns().is_empty() {
                continue;
            }
            assert!(
                runtime_or_test_or_support.contains(plugin.name()),
                "plugin '{}' exposes entry patterns but is missing from the entry-point role map",
                plugin.name()
            );
        }
    }

    /// The registry skips a config whose result `is_empty`, so every field that
    /// carries a contribution must make the result non-empty on its own.
    #[test]
    fn plugin_result_is_empty_only_when_every_field_is_empty() {
        type Fill = fn(&mut PluginResult);

        assert!(PluginResult::default().is_empty());

        let rows: [(&str, Fill); 15] = [
            ("entry_patterns", |r| {
                r.entry_patterns.push(PathRule::new("src/*.ts"));
            }),
            ("used_exports", |r| {
                r.used_exports
                    .push(UsedExportRule::new("src/*.ts", ["default"]));
            }),
            ("used_class_members", |r| {
                r.used_class_members
                    .push(UsedClassMemberRule::from("render"));
            }),
            ("referenced_dependencies", |r| {
                r.referenced_dependencies.push("lodash".to_string());
            }),
            ("package_referenced_dependencies", |r| {
                r.package_referenced_dependencies
                    .push((PathBuf::from("/project/pkg"), "lodash".to_string()));
            }),
            ("always_used_files", |r| {
                r.always_used_files.push("**/*.stories.tsx".to_string());
            }),
            ("path_aliases", |r| {
                r.path_aliases.push(("@".to_string(), "src".to_string()));
            }),
            ("setup_files", |r| {
                r.setup_files.push(PathBuf::from("/setup.ts"));
            }),
            ("fixture_patterns", |r| {
                r.fixture_patterns.push("**/__fixtures__/**/*".to_string());
            }),
            ("scss_include_paths", |r| {
                r.scss_include_paths.push(PathBuf::from("/project/styles"));
            }),
            ("static_dir_mappings", |r| {
                r.static_dir_mappings
                    .push((PathBuf::from("/project/public"), "/".to_string()));
            }),
            ("framework_static_dir_mappings", |r| {
                r.framework_static_dir_mappings
                    .push((PathBuf::from("/project/static"), "/".to_string()));
            }),
            ("provided_dependencies", |r| {
                r.provided_dependencies.push(ProvidedDependencyRule::new(
                    "**/*.stories.tsx",
                    ["react"],
                    Vec::<String>::new(),
                ));
            }),
            ("config_diagnostics", |r| {
                r.config_diagnostics
                    .push(PluginConfigDiagnostic::unreadable(
                        Path::new("/project/webpack.config.js"),
                        "webpack",
                        "exposes",
                        "dynamic-value",
                    ));
            }),
            ("federation_sources", |r| {
                r.federation_sources.push(FederationSource {
                    target: FederationSourceTarget::Remote("app".to_string()),
                    config_path: PathBuf::from("/project/webpack.config.js"),
                    plugin: "webpack".to_string(),
                    key: "remotes",
                });
            }),
        ];

        for (field, fill) in rows {
            let mut result = PluginResult::default();
            fill(&mut result);
            assert!(
                !result.is_empty(),
                "a result with only {field} set must not be empty"
            );
        }
    }

    #[test]
    fn is_enabled_with_deps_prefix_match() {
        let plugin = storybook::StorybookPlugin;
        let deps = vec!["@storybook/react".to_string()];
        assert!(plugin.is_enabled_with_deps(&deps, Path::new("/project")));
    }

    #[test]
    fn is_enabled_with_deps_prefix_no_match_without_slash() {
        let plugin = storybook::StorybookPlugin;
        let deps = vec!["@storybookish".to_string()];
        assert!(!plugin.is_enabled_with_deps(&deps, Path::new("/project")));
    }

    #[test]
    fn is_enabled_with_deps_multiple_enablers() {
        let plugin = vitest::VitestPlugin;
        let deps_vitest = vec!["vitest".to_string()];
        let deps_none = vec!["mocha".to_string()];
        assert!(plugin.is_enabled_with_deps(&deps_vitest, Path::new("/project")));
        assert!(!plugin.is_enabled_with_deps(&deps_none, Path::new("/project")));
    }

    #[test]
    fn plugin_resolve_config_default_returns_empty() {
        let plugin = commitizen::CommitizenPlugin;
        let result = plugin.resolve_config(
            Path::new("/project/config.js"),
            "const x = 1;",
            Path::new("/project"),
        );
        assert!(result.is_empty());
    }

    #[test]
    fn is_enabled_with_deps_exact_and_prefix_both_work() {
        let plugin = storybook::StorybookPlugin;
        let deps_exact = vec!["storybook".to_string()];
        assert!(plugin.is_enabled_with_deps(&deps_exact, Path::new("/project")));
        let deps_prefix = vec!["@storybook/vue3".to_string()];
        assert!(plugin.is_enabled_with_deps(&deps_prefix, Path::new("/project")));
    }

    #[test]
    fn is_enabled_with_deps_multiple_enablers_remix() {
        let plugin = remix::RemixPlugin;
        let deps_node = vec!["@remix-run/node".to_string()];
        assert!(plugin.is_enabled_with_deps(&deps_node, Path::new("/project")));
        let deps_react = vec!["@remix-run/react".to_string()];
        assert!(plugin.is_enabled_with_deps(&deps_react, Path::new("/project")));
        let deps_cf = vec!["@remix-run/cloudflare".to_string()];
        assert!(plugin.is_enabled_with_deps(&deps_cf, Path::new("/project")));
    }

    struct MinimalPlugin;
    impl Plugin for MinimalPlugin {
        fn name(&self) -> &'static str {
            "minimal"
        }
    }

    #[test]
    fn default_resolve_config_returns_empty() {
        let r = MinimalPlugin.resolve_config(
            Path::new("config.js"),
            "export default {}",
            Path::new("/"),
        );
        assert!(r.is_empty());
    }

    #[test]
    fn default_package_json_metadata_hooks_are_empty() {
        let pkg = PackageJson::default();
        assert!(!MinimalPlugin.is_enabled_with_package_json(&pkg, Path::new("/")));
        assert!(
            MinimalPlugin
                .resolve_package_json(&pkg, Path::new("/"))
                .is_empty()
        );
    }

    #[test]
    fn default_is_enabled_returns_false_when_no_enablers() {
        let deps = vec!["anything".to_string()];
        assert!(!MinimalPlugin.is_enabled_with_deps(&deps, Path::new("/")));
    }

    #[test]
    fn all_builtin_plugin_names_are_non_empty_and_unique() {
        let plugins = registry::builtin::create_builtin_plugins();
        let mut seen = std::collections::BTreeSet::new();
        for p in &plugins {
            let name = p.name();
            assert!(
                !name.is_empty(),
                "builtin plugins must have a non-empty name"
            );
            assert!(seen.insert(name), "duplicate plugin name: {name}");
        }
    }

    #[test]
    fn all_builtin_plugins_have_activation_signals() {
        // Plugins activated from package metadata or filesystem sentinels rather
        // than dependency enablers (napi binary name; deno.json presence).
        const NON_DEPENDENCY_ACTIVATED_PLUGINS: &[&str] = &["napi-rs", "deno"];
        let plugins = registry::builtin::create_builtin_plugins();
        for p in &plugins {
            assert!(
                !p.enablers().is_empty()
                    || !p.script_enablers().is_empty()
                    || NON_DEPENDENCY_ACTIVATED_PLUGINS.contains(&p.name()),
                "plugin '{}' has no activation signal",
                p.name()
            );
        }
    }

    #[test]
    fn plugins_with_config_patterns_have_always_used() {
        let plugins = registry::builtin::create_builtin_plugins();
        for p in &plugins {
            if !p.config_patterns().is_empty() {
                assert!(
                    !p.always_used().is_empty(),
                    "plugin '{}' has config_patterns but no always_used",
                    p.name()
                );
            }
        }
    }

    #[test]
    fn framework_plugins_enablers() {
        let cases: Vec<(&dyn Plugin, &[&str])> = vec![
            (&nextjs::NextJsPlugin, &["next"]),
            (&nuxt::NuxtPlugin, &["nuxt"]),
            (&angular::AngularPlugin, &["@angular/core"]),
            (&ionic::IonicPlugin, &["@ionic/angular"]),
            (&sveltekit::SvelteKitPlugin, &["@sveltejs/kit"]),
            (&gatsby::GatsbyPlugin, &["gatsby"]),
        ];
        for (plugin, expected_enablers) in cases {
            let enablers = plugin.enablers();
            for expected in expected_enablers {
                assert!(
                    enablers.contains(expected),
                    "plugin '{}' should have '{}'",
                    plugin.name(),
                    expected
                );
            }
        }
    }

    #[test]
    fn testing_plugins_enablers() {
        let cases: Vec<(&dyn Plugin, &str)> = vec![
            (&jest::JestPlugin, "jest"),
            (&vitest::VitestPlugin, "vitest"),
            (&playwright::PlaywrightPlugin, "@playwright/test"),
            (&cypress::CypressPlugin, "cypress"),
            (&mocha::MochaPlugin, "mocha"),
            (&stryker::StrykerPlugin, "@stryker-mutator/core"),
        ];
        for (plugin, enabler) in cases {
            assert!(
                plugin.enablers().contains(&enabler),
                "plugin '{}' should have '{}'",
                plugin.name(),
                enabler
            );
        }
    }

    #[test]
    fn bundler_plugins_enablers() {
        let cases: Vec<(&dyn Plugin, &str)> = vec![
            (&vite::VitePlugin, "vite"),
            (&webpack::WebpackPlugin, "webpack"),
            (&rollup::RollupPlugin, "rollup"),
        ];
        for (plugin, enabler) in cases {
            assert!(
                plugin.enablers().contains(&enabler),
                "plugin '{}' should have '{}'",
                plugin.name(),
                enabler
            );
        }
    }

    #[test]
    fn test_plugins_have_test_entry_patterns() {
        let test_plugins: Vec<&dyn Plugin> = vec![
            &bun::BunPlugin,
            &deno::DenoPlugin,
            &jest::JestPlugin,
            &vitest::VitestPlugin,
            &mocha::MochaPlugin,
            &tap::TapPlugin,
            &tsd::TsdPlugin,
        ];
        for plugin in test_plugins {
            let patterns = plugin.entry_patterns();
            assert!(
                !patterns.is_empty(),
                "test plugin '{}' should have entry patterns",
                plugin.name()
            );
            assert!(
                patterns
                    .iter()
                    .any(|p| p.contains("test") || p.contains("spec") || p.contains("__tests__")),
                "test plugin '{}' should have test/spec patterns",
                plugin.name()
            );
        }
    }

    #[test]
    fn framework_plugins_have_entry_patterns() {
        let plugins: Vec<&dyn Plugin> = vec![
            &nextjs::NextJsPlugin,
            &nuxt::NuxtPlugin,
            &angular::AngularPlugin,
            &sveltekit::SvelteKitPlugin,
        ];
        for plugin in plugins {
            assert!(
                !plugin.entry_patterns().is_empty(),
                "framework plugin '{}' should have entry patterns",
                plugin.name()
            );
        }
    }

    #[test]
    fn plugins_with_resolve_config_have_config_patterns() {
        let plugins: Vec<&dyn Plugin> = vec![
            &jest::JestPlugin,
            &vitest::VitestPlugin,
            &babel::BabelPlugin,
            &eslint::EslintPlugin,
            &webpack::WebpackPlugin,
            &storybook::StorybookPlugin,
            &typescript::TypeScriptPlugin,
            &postcss::PostCssPlugin,
            &nextjs::NextJsPlugin,
            &nuxt::NuxtPlugin,
            &angular::AngularPlugin,
            &nx::NxPlugin,
            &stryker::StrykerPlugin,
            &wuchale::WuchalePlugin,
            &rollup::RollupPlugin,
            &sveltekit::SvelteKitPlugin,
            &prettier::PrettierPlugin,
            &contentlayer::ContentlayerPlugin,
        ];
        for plugin in plugins {
            assert!(
                !plugin.config_patterns().is_empty(),
                "plugin '{}' with resolve_config should have config_patterns",
                plugin.name()
            );
        }
    }

    #[test]
    fn plugin_tooling_deps_include_enabler_package() {
        let plugins: Vec<&dyn Plugin> = vec![
            &jest::JestPlugin,
            &vitest::VitestPlugin,
            &webpack::WebpackPlugin,
            &typescript::TypeScriptPlugin,
            &eslint::EslintPlugin,
            &prettier::PrettierPlugin,
            &danger::DangerPlugin,
            &stryker::StrykerPlugin,
            &wuchale::WuchalePlugin,
            &contentlayer::ContentlayerPlugin,
        ];
        for plugin in plugins {
            let tooling = plugin.tooling_dependencies();
            let enablers = plugin.enablers();
            assert!(
                enablers
                    .iter()
                    .any(|e| !e.ends_with('/') && tooling.contains(e)),
                "plugin '{}': at least one non-prefix enabler should be in tooling_dependencies",
                plugin.name()
            );
        }
    }

    #[test]
    fn nextjs_has_used_exports_for_pages() {
        let plugin = nextjs::NextJsPlugin;
        let exports = plugin.used_exports();
        assert!(!exports.is_empty());
        assert!(exports.iter().any(|(_, names)| names.contains(&"default")));
    }

    #[test]
    fn remix_has_used_exports_for_routes() {
        let plugin = remix::RemixPlugin;
        let exports = plugin.used_exports();
        assert!(!exports.is_empty());
        let route_entry = exports.iter().find(|(pat, _)| pat.contains("routes"));
        assert!(route_entry.is_some());
        let (_, names) = route_entry.unwrap();
        assert!(names.contains(&"loader"));
        assert!(names.contains(&"action"));
        assert!(names.contains(&"default"));
    }

    #[test]
    fn sveltekit_has_used_exports_for_routes() {
        let plugin = sveltekit::SvelteKitPlugin;
        let exports = plugin.used_exports();
        assert!(!exports.is_empty());
        assert!(exports.iter().any(|(_, names)| names.contains(&"GET")));
    }

    #[test]
    fn nuxt_has_hash_virtual_prefix() {
        assert!(nuxt::NuxtPlugin.virtual_module_prefixes().contains(&"#"));
    }

    #[test]
    fn sveltekit_has_dollar_virtual_prefixes() {
        let prefixes = sveltekit::SvelteKitPlugin.virtual_module_prefixes();
        assert!(prefixes.contains(&"$app/"));
        assert!(prefixes.contains(&"$env/"));
        assert!(prefixes.contains(&"$lib/"));
    }

    #[test]
    fn sveltekit_has_lib_path_alias() {
        let aliases = sveltekit::SvelteKitPlugin.path_aliases(Path::new("/project"));
        assert!(aliases.iter().any(|(prefix, _)| *prefix == "$lib/"));
    }

    #[test]
    fn nuxt_has_tilde_path_alias() {
        let aliases = nuxt::NuxtPlugin.path_aliases(Path::new("/nonexistent"));
        assert!(aliases.iter().any(|(prefix, _)| *prefix == "~/"));
        assert!(aliases.iter().any(|(prefix, _)| *prefix == "~~/"));
    }

    #[test]
    fn jest_has_package_json_config_key() {
        assert_eq!(jest::JestPlugin.package_json_config_key(), Some("jest"));
    }

    #[test]
    fn tsd_has_package_json_config_key() {
        assert_eq!(tsd::TsdPlugin.package_json_config_key(), Some("tsd"));
    }

    #[test]
    fn babel_has_package_json_config_key() {
        assert_eq!(babel::BabelPlugin.package_json_config_key(), Some("babel"));
    }

    #[test]
    fn eslint_has_package_json_config_key() {
        assert_eq!(
            eslint::EslintPlugin.package_json_config_key(),
            Some("eslintConfig")
        );
    }

    #[test]
    fn prettier_has_package_json_config_key() {
        assert_eq!(
            prettier::PrettierPlugin.package_json_config_key(),
            Some("prettier")
        );
    }

    #[test]
    fn macro_generated_plugin_basic_properties() {
        let plugin = msw::MswPlugin;
        assert_eq!(plugin.name(), "msw");
        assert!(plugin.enablers().contains(&"msw"));
        assert!(!plugin.entry_patterns().is_empty());
        assert!(plugin.config_patterns().is_empty());
        assert!(!plugin.always_used().is_empty());
        assert!(!plugin.tooling_dependencies().is_empty());
    }

    #[test]
    fn macro_generated_plugin_with_used_exports() {
        let plugin = remix::RemixPlugin;
        assert_eq!(plugin.name(), "remix");
        assert!(!plugin.used_exports().is_empty());
    }

    #[test]
    fn macro_passes_through_virtual_package_suffixes() {
        define_plugin! {
            struct MacroSuffixSmokePlugin => "macro-suffix-smoke",
            enablers: &["macro-suffix-smoke"],
            virtual_package_suffixes: &["/__macro_smoke__"],
        }

        let plugin = MacroSuffixSmokePlugin;
        assert_eq!(
            plugin.virtual_package_suffixes(),
            &["/__macro_smoke__"],
            "macro-declared virtual_package_suffixes must propagate to the trait method"
        );
    }

    #[test]
    fn macro_generated_plugin_imports_only_resolve_config() {
        let plugin = cypress::CypressPlugin;
        let source = r"
            import { defineConfig } from 'cypress';
            import coveragePlugin from '@cypress/code-coverage';
            export default defineConfig({});
        ";
        let result = plugin.resolve_config(
            Path::new("cypress.config.ts"),
            source,
            Path::new("/project"),
        );
        assert!(
            result
                .referenced_dependencies
                .contains(&"cypress".to_string())
        );
        assert!(
            result
                .referenced_dependencies
                .contains(&"@cypress/code-coverage".to_string())
        );
    }

    #[test]
    fn builtin_plugin_count_is_expected() {
        let plugins = registry::builtin::create_builtin_plugins();
        assert!(
            plugins.len() >= 110,
            "expected at least 110 built-in plugins, got {}",
            plugins.len()
        );
    }

    /// A pattern that climbs out of its workspace with `../` resolves against
    /// the workspace prefix, so it names a file in a sibling workspace. A climb
    /// past the project root stays unresolved and matches no project file.
    #[test]
    fn a_parent_relative_pattern_resolves_against_the_workspace_prefix() {
        let parent_relative = |pattern: &str| {
            let mut rule = PathRule::new(pattern);
            rule.parent_relative = true;
            rule
        };
        assert_eq!(
            parent_relative("../shared/src/Thing.tsx")
                .prefixed("packages/app")
                .pattern,
            "packages/shared/src/Thing.tsx"
        );
        assert_eq!(
            parent_relative("../../lib/index.{ts,js}")
                .prefixed("apps/web/client")
                .pattern,
            "apps/lib/index.{ts,js}"
        );
        assert!(
            parent_relative("../../../outside/Thing.tsx")
                .prefixed("packages/app")
                .pattern
                .starts_with("../"),
            "a climb past the project root matches no project file"
        );
        assert_eq!(
            parent_relative("src/index.ts")
                .prefixed("packages/app")
                .pattern,
            "packages/app/src/index.ts"
        );
    }

    /// On Windows the workspace prefix uses backslashes, so a sibling-workspace
    /// pattern must climb the same segments as with forward slashes.
    #[test]
    fn a_parent_relative_pattern_resolves_against_a_backslash_prefix() {
        let mut rule = PathRule::new("../../packages/ui/src/**/*.mdx");
        rule.parent_relative = true;
        assert_eq!(
            rule.prefixed("apps\\docs").pattern,
            "packages/ui/src/**/*.mdx"
        );
    }

    /// Any other pattern keeps the plain prefix, so a config-directory-relative
    /// `../src/**` does not climb out of its workspace.
    #[test]
    fn a_plain_parent_pattern_is_not_resolved() {
        assert_eq!(
            PathRule::new("../src/**/*.stories.tsx")
                .prefixed("packages/ui")
                .pattern,
            "packages/ui/../src/**/*.stories.tsx"
        );
    }
}