fallow-core 2.40.2

Core analysis engine for the fallow TypeScript/JavaScript codebase analyzer
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
//! 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::{EntryPointRole, PackageJson, UsedClassMemberRule};
use regex::Regex;

const TEST_ENTRY_POINT_PLUGINS: &[&str] = &[
    "ava",
    "cucumber",
    "cypress",
    "jest",
    "mocha",
    "playwright",
    "vitest",
    "webdriverio",
];

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

#[cfg(test)]
const SUPPORT_ENTRY_POINT_PLUGINS: &[&str] = &[
    "drizzle",
    "i18next",
    "knex",
    "kysely",
    "msw",
    "prisma",
    "storybook",
    "typeorm",
];

/// Result of resolving a plugin's config file.
#[derive(Debug, Default)]
pub struct PluginResult {
    /// Additional entry point glob patterns discovered from config.
    pub 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.
    pub replace_entry_patterns: bool,
    /// When true, `used_exports` from config replace the plugin's static
    /// `used_export_rules()` defaults instead of adding to them.
    pub replace_used_export_rules: bool,
    /// Additional export-usage rules discovered from config.
    pub 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.
    pub used_class_members: Vec<UsedClassMemberRule>,
    /// Dependencies referenced in config files (should not be flagged as unused).
    pub referenced_dependencies: Vec<String>,
    /// Additional files that are always considered used.
    pub always_used_files: Vec<String>,
    /// Path alias mappings discovered from config (prefix -> replacement directory).
    pub path_aliases: Vec<(String, String)>,
    /// Setup/helper files referenced from config.
    pub setup_files: Vec<PathBuf>,
    /// Test fixture glob patterns discovered from config.
    pub 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.
    pub scss_include_paths: Vec<PathBuf>,
}

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

    pub 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(PathRule::new));
    }

    pub 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));
    }

    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.entry_patterns.is_empty()
            && self.used_exports.is_empty()
            && self.used_class_members.is_empty()
            && self.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()
    }
}

/// 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>,
}

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

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

    #[must_use]
    pub 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]
    pub 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]
    pub 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]
    pub fn prefixed(&self, ws_prefix: &str) -> Self {
        Self {
            pattern: prefix_workspace_pattern(&self.pattern, ws_prefix),
            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(),
        }
    }
}

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

impl UsedExportRule {
    #[must_use]
    pub 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]
    pub fn from_static(pattern: &'static str, exports: &'static [&'static str]) -> Self {
        Self::new(pattern, exports.iter().copied())
    }

    #[must_use]
    pub 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]
    pub 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]
    pub 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]
    pub 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 plugin_name: String,
    pub rule: UsedExportRule,
}

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

    #[must_use]
    pub fn prefixed(&self, ws_prefix: &str) -> Self {
        Self {
            plugin_name: self.plugin_name.clone(),
            rule: self.rule.prefixed(ws_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}")
    }
}

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)
            }
        })
    }

    /// 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] {
        &[]
    }

    /// 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] {
        &[]
    }

    /// 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] {
        &[]
    }

    /// 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] {
        &[]
    }

    /// 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![]
    }

    /// 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`, `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 {
    // Variant with `resolve_config: imports_only` — generates a resolve_config method
    // that extracts imports from config files and registers them as referenced dependencies.
    (
        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)?
        $(, virtual_module_prefixes: $virtual: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 virtual_module_prefixes(&self) -> &'static [&'static str] { $virtual } )?

            $(
                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();
                let imports = crate::plugins::config_parser::extract_imports(source, config_path);
                for imp in &imports {
                    let dep = crate::resolve::extract_package_name(imp);
                    result.referenced_dependencies.push(dep);
                }
                result
            }
        }
    };

    // Variant with custom resolve_config body — generates a resolve_config method
    // with the caller-supplied block. Parameter names are caller-controlled (use
    // `_root` for unused params to satisfy clippy).
    (
        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)?
        $(, virtual_module_prefixes: $virtual: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 virtual_module_prefixes(&self) -> &'static [&'static str] { $virtual } )?

            $(
                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
        }
    };

    // Base variant — no resolve_config.
    (
        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)?
        $(, virtual_module_prefixes: $virtual: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 virtual_module_prefixes(&self) -> &'static [&'static str] { $virtual } )?

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

pub mod config_parser;
pub mod registry;
mod tooling;

pub use registry::{AggregatedPluginResult, PluginRegistry};
pub use tooling::is_known_tooling_dependency;

mod angular;
mod astro;
mod ava;
mod babel;
mod biome;
mod bun;
mod c8;
mod capacitor;
mod changesets;
mod commitizen;
mod commitlint;
mod convex;
mod cspell;
mod cucumber;
mod cypress;
mod dependency_cruiser;
mod docusaurus;
mod drizzle;
mod electron;
mod eslint;
mod expo;
mod expo_router;
mod gatsby;
mod graphql_codegen;
mod hardhat;
mod husky;
mod i18next;
mod jest;
mod karma;
mod knex;
mod kysely;
mod lefthook;
mod lint_staged;
mod markdownlint;
mod mocha;
mod msw;
mod nestjs;
mod next_intl;
mod nextjs;
mod nitro;
mod nodemon;
mod nuxt;
mod nx;
mod nyc;
mod openapi_ts;
mod oxlint;
mod parcel;
mod playwright;
mod plop;
mod pm2;
mod pnpm;
mod postcss;
mod prettier;
mod prisma;
mod qwik;
mod react_native;
mod react_router;
mod relay;
mod remark;
mod remix;
mod rolldown;
mod rollup;
mod rsbuild;
mod rspack;
mod sanity;
mod semantic_release;
mod sentry;
mod simple_git_hooks;
mod storybook;
mod stylelint;
mod sveltekit;
mod svgo;
mod svgr;
mod swc;
mod syncpack;
mod tailwind;
mod tanstack_router;
mod tsdown;
mod tsup;
mod turborepo;
mod typedoc;
mod typeorm;
mod typescript;
mod unocss;
mod vite;
mod vitepress;
mod vitest;
mod webdriverio;
mod webpack;
mod wrangler;

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

    // ── is_enabled_with_deps edge cases ──────────────────────────

    #[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 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!(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()
            );
        }
    }

    // ── PluginResult::is_empty ───────────────────────────────────

    #[test]
    fn plugin_result_is_empty_when_default() {
        let r = PluginResult::default();
        assert!(r.is_empty());
    }

    #[test]
    fn plugin_result_not_empty_with_entry_patterns() {
        let r = PluginResult {
            entry_patterns: vec!["*.ts".into()],
            ..Default::default()
        };
        assert!(!r.is_empty());
    }

    #[test]
    fn plugin_result_not_empty_with_referenced_deps() {
        let r = PluginResult {
            referenced_dependencies: vec!["lodash".to_string()],
            ..Default::default()
        };
        assert!(!r.is_empty());
    }

    #[test]
    fn plugin_result_not_empty_with_setup_files() {
        let r = PluginResult {
            setup_files: vec![PathBuf::from("/setup.ts")],
            ..Default::default()
        };
        assert!(!r.is_empty());
    }

    #[test]
    fn plugin_result_not_empty_with_always_used_files() {
        let r = PluginResult {
            always_used_files: vec!["**/*.stories.tsx".to_string()],
            ..Default::default()
        };
        assert!(!r.is_empty());
    }

    #[test]
    fn plugin_result_not_empty_with_fixture_patterns() {
        let r = PluginResult {
            fixture_patterns: vec!["**/__fixtures__/**/*".to_string()],
            ..Default::default()
        };
        assert!(!r.is_empty());
    }

    // ── is_enabled_with_deps prefix matching ─────────────────────

    #[test]
    fn is_enabled_with_deps_prefix_match() {
        // Storybook plugin uses prefix enabler "@storybook/"
        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() {
        // "@storybook/" prefix should NOT match "@storybookish" (different package)
        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() {
        // Vitest plugin has 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")));
    }

    // ── Plugin trait default implementations ─────────────────────

    #[test]
    fn plugin_default_methods_return_empty() {
        // Use a simple plugin to test default trait methods
        let plugin = commitizen::CommitizenPlugin;
        assert!(
            plugin.tooling_dependencies().is_empty() || !plugin.tooling_dependencies().is_empty()
        );
        assert!(plugin.virtual_module_prefixes().is_empty());
        assert!(plugin.path_aliases(Path::new("/project")).is_empty());
        assert!(
            plugin.package_json_config_key().is_none()
                || plugin.package_json_config_key().is_some()
        );
    }

    #[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());
    }

    // ── is_enabled_with_deps exact and prefix ────────────────────

    #[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")));
    }

    // ── Plugin trait default implementations ──────────────────────

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

    #[test]
    fn default_enablers_is_empty() {
        assert!(MinimalPlugin.enablers().is_empty());
    }

    #[test]
    fn default_entry_patterns_is_empty() {
        assert!(MinimalPlugin.entry_patterns().is_empty());
    }

    #[test]
    fn default_config_patterns_is_empty() {
        assert!(MinimalPlugin.config_patterns().is_empty());
    }

    #[test]
    fn default_always_used_is_empty() {
        assert!(MinimalPlugin.always_used().is_empty());
    }

    #[test]
    fn default_used_exports_is_empty() {
        assert!(MinimalPlugin.used_exports().is_empty());
    }

    #[test]
    fn default_tooling_dependencies_is_empty() {
        assert!(MinimalPlugin.tooling_dependencies().is_empty());
    }

    #[test]
    fn default_fixture_glob_patterns_is_empty() {
        assert!(MinimalPlugin.fixture_glob_patterns().is_empty());
    }

    #[test]
    fn default_virtual_module_prefixes_is_empty() {
        assert!(MinimalPlugin.virtual_module_prefixes().is_empty());
    }

    #[test]
    fn default_path_aliases_is_empty() {
        assert!(MinimalPlugin.path_aliases(Path::new("/")).is_empty());
    }

    #[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_config_key_is_none() {
        assert!(MinimalPlugin.package_json_config_key().is_none());
    }

    #[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("/")));
    }

    // ── All built-in plugins have unique names ───────────────────

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

    #[test]
    fn all_builtin_plugins_have_enablers() {
        let plugins = registry::builtin::create_builtin_plugins();
        for p in &plugins {
            assert!(
                !p.enablers().is_empty(),
                "plugin '{}' has no enablers",
                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()
                );
            }
        }
    }

    // ── Enabler patterns for all categories ──────────────────────

    #[test]
    fn framework_plugins_enablers() {
        let cases: Vec<(&dyn Plugin, &[&str])> = vec![
            (&nextjs::NextJsPlugin, &["next"]),
            (&nuxt::NuxtPlugin, &["nuxt"]),
            (&angular::AngularPlugin, &["@angular/core"]),
            (&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"),
        ];
        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![
            &jest::JestPlugin,
            &vitest::VitestPlugin,
            &mocha::MochaPlugin,
        ];
        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,
            &rollup::RollupPlugin,
            &sveltekit::SvelteKitPlugin,
            &prettier::PrettierPlugin,
        ];
        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,
        ];
        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 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_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() >= 80,
            "expected at least 80 built-in plugins, got {}",
            plugins.len()
        );
    }
}