Skip to main content

fallow_core/plugins/
mod.rs

1//! Plugin system for framework-aware codebase analysis.
2//!
3//! Unlike knip's JavaScript plugin system that evaluates config files at runtime,
4//! fallow's plugin system uses Oxc's parser to extract configuration values from
5//! JS/TS/JSON config files via AST walking — no JavaScript evaluation needed.
6//!
7//! Each plugin implements the [`Plugin`] trait with:
8//! - **Static defaults**: Entry patterns, config file patterns, used exports
9//! - **Dynamic resolution**: Parse tool config files to discover additional entries,
10//!   referenced dependencies, and setup files
11
12use std::path::{Path, PathBuf};
13
14use fallow_config::{AutoImportRule, EntryPointRole, PackageJson, UsedClassMemberRule};
15use regex::Regex;
16
17const TEST_ENTRY_POINT_PLUGINS: &[&str] = &[
18    "ava",
19    "bun",
20    "cucumber",
21    "cypress",
22    "jest",
23    "k6",
24    "mocha",
25    "playwright",
26    "tap",
27    "tsd",
28    "vitest",
29    "webdriverio",
30];
31
32const RUNTIME_ENTRY_POINT_PLUGINS: &[&str] = &[
33    "adonis",
34    "angular",
35    "astro",
36    "browser-extension",
37    "convex",
38    "docusaurus",
39    "electron",
40    "ember",
41    "expo",
42    "expo-router",
43    "gatsby",
44    "hardhat",
45    "nestjs",
46    "next-intl",
47    "nextjs",
48    "nitro",
49    "nuxt",
50    "obsidian",
51    "parcel",
52    "qwik",
53    "react-native",
54    "react-router",
55    "redwoodsdk",
56    "remix",
57    "rolldown",
58    "rollup",
59    "rsbuild",
60    "rspack",
61    "sanity",
62    "supabase",
63    "sveltekit",
64    "tanstack-router",
65    "tsdown",
66    "tsup",
67    "vite",
68    "vitepress",
69    "webpack",
70    "wrangler",
71    "wxt",
72];
73
74#[cfg(test)]
75const SUPPORT_ENTRY_POINT_PLUGINS: &[&str] = &[
76    "content-collections",
77    "contentlayer",
78    "danger",
79    "drizzle",
80    "fumadocs",
81    "i18next",
82    "knex",
83    "kysely",
84    "mintlify",
85    "msw",
86    "opencode",
87    "prisma",
88    "storybook",
89    "stryker",
90    "typeorm",
91    "velite",
92];
93
94/// Result of resolving a plugin's config file.
95#[derive(Debug, Default)]
96pub struct PluginResult {
97    /// Additional entry point glob patterns discovered from config.
98    pub entry_patterns: Vec<PathRule>,
99    /// When true, `entry_patterns` from config replace the plugin's static
100    /// `entry_patterns()` defaults instead of adding to them. Tools like Vitest
101    /// and Jest treat their config's include/testMatch as a replacement for built-in
102    /// defaults, so when the config is explicit the static patterns must be dropped.
103    pub replace_entry_patterns: bool,
104    /// When true, `used_exports` from config replace the plugin's static
105    /// `used_export_rules()` defaults instead of adding to them.
106    pub replace_used_export_rules: bool,
107    /// Additional export-usage rules discovered from config.
108    pub used_exports: Vec<UsedExportRule>,
109    /// Class member rules that should never be flagged as unused. Contributed
110    /// by plugins that know their framework invokes these methods at runtime
111    /// and may scope suppression via `extends` / `implements` constraints when
112    /// the method name is too common to allowlist globally.
113    pub used_class_members: Vec<UsedClassMemberRule>,
114    /// Dependencies referenced in config files (should not be flagged as unused).
115    pub referenced_dependencies: Vec<String>,
116    /// Additional files that are always considered used.
117    pub always_used_files: Vec<String>,
118    /// Path alias mappings discovered from config (prefix -> replacement directory).
119    pub path_aliases: Vec<(String, String)>,
120    /// Setup/helper files referenced from config.
121    pub setup_files: Vec<PathBuf>,
122    /// Test fixture glob patterns discovered from config.
123    pub fixture_patterns: Vec<String>,
124    /// Absolute directories to include when resolving SCSS/Sass `@import` and
125    /// `@use` specifiers. Contributed by framework plugins that read their
126    /// tool's equivalent of `includePaths` (e.g. Angular's
127    /// `stylePreprocessorOptions.includePaths` from `angular.json` /
128    /// `project.json`). Bare SCSS specifiers that fail to resolve relative to
129    /// the importing file retry against each include path using the SCSS
130    /// partial / directory-index conventions.
131    pub scss_include_paths: Vec<PathBuf>,
132    /// URL-to-filesystem static directory mappings discovered from tool config.
133    /// Each tuple is `(absolute_source_dir, normalized_url_mount)`.
134    pub static_dir_mappings: Vec<(PathBuf, String)>,
135    /// File-scoped dependency providers. Matching imports are considered
136    /// available from the framework runtime and are not unlisted dependencies.
137    pub provided_dependencies: Vec<ProvidedDependencyRule>,
138}
139
140impl PluginResult {
141    pub fn push_entry_pattern(&mut self, pattern: impl Into<String>) {
142        self.entry_patterns
143            .push(PathRule::new(normalize_entry_pattern(pattern.into())));
144    }
145
146    pub fn extend_entry_patterns<I, S>(&mut self, patterns: I)
147    where
148        I: IntoIterator<Item = S>,
149        S: Into<String>,
150    {
151        self.entry_patterns.extend(
152            patterns
153                .into_iter()
154                .map(|pat| PathRule::new(normalize_entry_pattern(pat.into()))),
155        );
156    }
157
158    pub fn push_used_export_rule(
159        &mut self,
160        pattern: impl Into<String>,
161        exports: impl IntoIterator<Item = impl Into<String>>,
162    ) {
163        self.used_exports
164            .push(UsedExportRule::new(pattern, exports));
165    }
166
167    #[must_use]
168    pub const fn is_empty(&self) -> bool {
169        self.entry_patterns.is_empty()
170            && self.used_exports.is_empty()
171            && self.used_class_members.is_empty()
172            && self.referenced_dependencies.is_empty()
173            && self.always_used_files.is_empty()
174            && self.path_aliases.is_empty()
175            && self.setup_files.is_empty()
176            && self.fixture_patterns.is_empty()
177            && self.scss_include_paths.is_empty()
178            && self.static_dir_mappings.is_empty()
179            && self.provided_dependencies.is_empty()
180    }
181}
182
183fn normalize_entry_pattern(pattern: String) -> String {
184    pattern
185        .strip_prefix("./")
186        .map(str::to_owned)
187        .unwrap_or(pattern)
188}
189
190/// A file-pattern rule with optional exclusion globs plus path-level or
191/// segment-level regex filters.
192///
193/// Exclusion regexes are matched against the project-relative path and should be
194/// anchored when generated dynamically so they can be safely workspace-prefixed.
195#[derive(Debug, Clone, Default, PartialEq, Eq)]
196pub struct PathRule {
197    pub pattern: String,
198    pub exclude_globs: Vec<String>,
199    pub exclude_regexes: Vec<String>,
200    /// Regexes matched against individual path segments. These are not prefixed
201    /// for workspaces because they intentionally operate on segment names rather
202    /// than the full project-relative path.
203    pub exclude_segment_regexes: Vec<String>,
204}
205
206impl PathRule {
207    #[must_use]
208    pub fn new(pattern: impl Into<String>) -> Self {
209        Self {
210            pattern: pattern.into(),
211            exclude_globs: Vec::new(),
212            exclude_regexes: Vec::new(),
213            exclude_segment_regexes: Vec::new(),
214        }
215    }
216
217    #[must_use]
218    pub fn from_static(pattern: &'static str) -> Self {
219        Self::new(pattern)
220    }
221
222    #[must_use]
223    pub fn with_excluded_globs<I, S>(mut self, patterns: I) -> Self
224    where
225        I: IntoIterator<Item = S>,
226        S: Into<String>,
227    {
228        self.exclude_globs
229            .extend(patterns.into_iter().map(Into::into));
230        self
231    }
232
233    #[must_use]
234    pub fn with_excluded_regexes<I, S>(mut self, patterns: I) -> Self
235    where
236        I: IntoIterator<Item = S>,
237        S: Into<String>,
238    {
239        self.exclude_regexes
240            .extend(patterns.into_iter().map(Into::into));
241        self
242    }
243
244    #[must_use]
245    pub fn with_excluded_segment_regexes<I, S>(mut self, patterns: I) -> Self
246    where
247        I: IntoIterator<Item = S>,
248        S: Into<String>,
249    {
250        self.exclude_segment_regexes
251            .extend(patterns.into_iter().map(Into::into));
252        self
253    }
254
255    #[must_use]
256    pub fn prefixed(&self, ws_prefix: &str) -> Self {
257        Self {
258            pattern: prefix_workspace_pattern(&self.pattern, ws_prefix),
259            exclude_globs: self
260                .exclude_globs
261                .iter()
262                .map(|pattern| prefix_workspace_pattern(pattern, ws_prefix))
263                .collect(),
264            exclude_regexes: self
265                .exclude_regexes
266                .iter()
267                .map(|pattern| prefix_workspace_regex(pattern, ws_prefix))
268                .collect(),
269            exclude_segment_regexes: self.exclude_segment_regexes.clone(),
270        }
271    }
272}
273
274/// A used-export rule bound to a file-pattern rule.
275#[derive(Debug, Clone, Default, PartialEq, Eq)]
276pub struct UsedExportRule {
277    pub path: PathRule,
278    pub exports: Vec<String>,
279}
280
281impl UsedExportRule {
282    #[must_use]
283    pub fn new(
284        pattern: impl Into<String>,
285        exports: impl IntoIterator<Item = impl Into<String>>,
286    ) -> Self {
287        Self {
288            path: PathRule::new(pattern),
289            exports: exports.into_iter().map(Into::into).collect(),
290        }
291    }
292
293    #[must_use]
294    pub fn from_static(pattern: &'static str, exports: &'static [&'static str]) -> Self {
295        Self::new(pattern, exports.iter().copied())
296    }
297
298    #[must_use]
299    pub fn with_excluded_globs<I, S>(mut self, patterns: I) -> Self
300    where
301        I: IntoIterator<Item = S>,
302        S: Into<String>,
303    {
304        self.path = self.path.with_excluded_globs(patterns);
305        self
306    }
307
308    #[must_use]
309    pub fn with_excluded_regexes<I, S>(mut self, patterns: I) -> Self
310    where
311        I: IntoIterator<Item = S>,
312        S: Into<String>,
313    {
314        self.path = self.path.with_excluded_regexes(patterns);
315        self
316    }
317
318    #[must_use]
319    pub fn with_excluded_segment_regexes<I, S>(mut self, patterns: I) -> Self
320    where
321        I: IntoIterator<Item = S>,
322        S: Into<String>,
323    {
324        self.path = self.path.with_excluded_segment_regexes(patterns);
325        self
326    }
327
328    #[must_use]
329    pub fn prefixed(&self, ws_prefix: &str) -> Self {
330        Self {
331            path: self.path.prefixed(ws_prefix),
332            exports: self.exports.clone(),
333        }
334    }
335}
336
337/// A used-export rule tagged with the plugin that contributed it.
338#[derive(Debug, Clone, PartialEq, Eq)]
339pub struct PluginUsedExportRule {
340    pub plugin_name: String,
341    pub rule: UsedExportRule,
342}
343
344impl PluginUsedExportRule {
345    #[must_use]
346    pub fn new(plugin_name: impl Into<String>, rule: UsedExportRule) -> Self {
347        Self {
348            plugin_name: plugin_name.into(),
349            rule,
350        }
351    }
352
353    #[must_use]
354    pub fn prefixed(&self, ws_prefix: &str) -> Self {
355        Self {
356            plugin_name: self.plugin_name.clone(),
357            rule: self.rule.prefixed(ws_prefix),
358        }
359    }
360}
361
362/// A file-scoped dependency provider rule contributed by a framework plugin.
363#[derive(Debug, Clone, Default, PartialEq, Eq)]
364pub struct ProvidedDependencyRule {
365    pub path: PathRule,
366    pub exact_specifiers: Vec<String>,
367    pub specifier_prefixes: Vec<String>,
368}
369
370impl ProvidedDependencyRule {
371    #[must_use]
372    pub fn new(
373        pattern: impl Into<String>,
374        exact_specifiers: impl IntoIterator<Item = impl Into<String>>,
375        specifier_prefixes: impl IntoIterator<Item = impl Into<String>>,
376    ) -> Self {
377        Self {
378            path: PathRule::new(pattern),
379            exact_specifiers: exact_specifiers.into_iter().map(Into::into).collect(),
380            specifier_prefixes: specifier_prefixes.into_iter().map(Into::into).collect(),
381        }
382    }
383
384    #[must_use]
385    pub fn prefixed(&self, ws_prefix: &str) -> Self {
386        Self {
387            path: self.path.prefixed(ws_prefix),
388            exact_specifiers: self.exact_specifiers.clone(),
389            specifier_prefixes: self.specifier_prefixes.clone(),
390        }
391    }
392
393    #[must_use]
394    pub fn may_cover_package(&self, package_name: &str) -> bool {
395        self.exact_specifiers
396            .iter()
397            .chain(self.specifier_prefixes.iter())
398            .any(|specifier| crate::resolve::extract_package_name(specifier) == package_name)
399    }
400
401    #[must_use]
402    pub fn covers_specifier(&self, specifier: &str) -> bool {
403        self.exact_specifiers
404            .iter()
405            .any(|allowed| allowed == specifier)
406            || self
407                .specifier_prefixes
408                .iter()
409                .any(|prefix| specifier.starts_with(prefix))
410    }
411}
412
413/// A compiled path rule matcher shared by entry-point and used-export matching.
414#[derive(Debug, Clone)]
415pub(crate) struct CompiledPathRule {
416    include: globset::GlobMatcher,
417    exclude_globs: Vec<globset::GlobMatcher>,
418    exclude_regexes: Vec<Regex>,
419    exclude_segment_regexes: Vec<Regex>,
420}
421
422impl CompiledPathRule {
423    pub(crate) fn for_entry_rule(rule: &PathRule, rule_kind: &str) -> Option<Self> {
424        let include = match globset::GlobBuilder::new(&rule.pattern)
425            .literal_separator(true)
426            .build()
427        {
428            Ok(glob) => glob.compile_matcher(),
429            Err(err) => {
430                tracing::warn!("invalid {rule_kind} '{}': {err}", rule.pattern);
431                return None;
432            }
433        };
434        Some(Self {
435            include,
436            exclude_globs: compile_excluded_globs(&rule.exclude_globs, rule_kind, &rule.pattern),
437            exclude_regexes: compile_excluded_regexes(
438                &rule.exclude_regexes,
439                rule_kind,
440                &rule.pattern,
441            ),
442            exclude_segment_regexes: compile_excluded_segment_regexes(
443                &rule.exclude_segment_regexes,
444                rule_kind,
445                &rule.pattern,
446            ),
447        })
448    }
449
450    pub(crate) fn for_used_export_rule(rule: &PathRule, rule_kind: &str) -> Option<Self> {
451        let include = match globset::Glob::new(&rule.pattern) {
452            Ok(glob) => glob.compile_matcher(),
453            Err(err) => {
454                tracing::warn!("invalid {rule_kind} '{}': {err}", rule.pattern);
455                return None;
456            }
457        };
458        Some(Self {
459            include,
460            exclude_globs: compile_excluded_globs(&rule.exclude_globs, rule_kind, &rule.pattern),
461            exclude_regexes: compile_excluded_regexes(
462                &rule.exclude_regexes,
463                rule_kind,
464                &rule.pattern,
465            ),
466            exclude_segment_regexes: compile_excluded_segment_regexes(
467                &rule.exclude_segment_regexes,
468                rule_kind,
469                &rule.pattern,
470            ),
471        })
472    }
473
474    #[must_use]
475    pub(crate) fn matches(&self, path: &str) -> bool {
476        self.include.is_match(path)
477            && !self.exclude_globs.iter().any(|glob| glob.is_match(path))
478            && !self
479                .exclude_regexes
480                .iter()
481                .any(|regex| regex.is_match(path))
482            && !matches_segment_regex(path, &self.exclude_segment_regexes)
483    }
484}
485
486fn prefix_workspace_pattern(pattern: &str, ws_prefix: &str) -> String {
487    if pattern.starts_with(ws_prefix) || pattern.starts_with('/') {
488        pattern.to_string()
489    } else {
490        format!("{ws_prefix}/{pattern}")
491    }
492}
493
494fn prefix_workspace_regex(pattern: &str, ws_prefix: &str) -> String {
495    if let Some(pattern) = pattern.strip_prefix('^') {
496        format!("^{}/{}", regex::escape(ws_prefix), pattern)
497    } else {
498        format!("^{}/(?:{})", regex::escape(ws_prefix), pattern)
499    }
500}
501
502fn compile_excluded_globs(
503    patterns: &[String],
504    rule_kind: &str,
505    rule_pattern: &str,
506) -> Vec<globset::GlobMatcher> {
507    patterns
508        .iter()
509        .filter_map(|pattern| {
510            match globset::GlobBuilder::new(pattern)
511                .literal_separator(true)
512                .build()
513            {
514                Ok(glob) => Some(glob.compile_matcher()),
515                Err(err) => {
516                    tracing::warn!(
517                        "skipping invalid excluded glob '{}' for {} '{}': {err}",
518                        pattern,
519                        rule_kind,
520                        rule_pattern
521                    );
522                    None
523                }
524            }
525        })
526        .collect()
527}
528
529fn compile_excluded_regexes(
530    patterns: &[String],
531    rule_kind: &str,
532    rule_pattern: &str,
533) -> Vec<Regex> {
534    patterns
535        .iter()
536        .filter_map(|pattern| match Regex::new(pattern) {
537            Ok(regex) => Some(regex),
538            Err(err) => {
539                tracing::warn!(
540                    "skipping invalid excluded regex '{}' for {} '{}': {err}",
541                    pattern,
542                    rule_kind,
543                    rule_pattern
544                );
545                None
546            }
547        })
548        .collect()
549}
550
551fn compile_excluded_segment_regexes(
552    patterns: &[String],
553    rule_kind: &str,
554    rule_pattern: &str,
555) -> Vec<Regex> {
556    patterns
557        .iter()
558        .filter_map(|pattern| match Regex::new(pattern) {
559            Ok(regex) => Some(regex),
560            Err(err) => {
561                tracing::warn!(
562                    "skipping invalid excluded segment regex '{}' for {} '{}': {err}",
563                    pattern,
564                    rule_kind,
565                    rule_pattern
566                );
567                None
568            }
569        })
570        .collect()
571}
572
573fn matches_segment_regex(path: &str, regexes: &[Regex]) -> bool {
574    path.split('/')
575        .any(|segment| regexes.iter().any(|regex| regex.is_match(segment)))
576}
577
578impl From<String> for PathRule {
579    fn from(pattern: String) -> Self {
580        Self::new(pattern)
581    }
582}
583
584impl From<&str> for PathRule {
585    fn from(pattern: &str) -> Self {
586        Self::new(pattern)
587    }
588}
589
590impl std::ops::Deref for PathRule {
591    type Target = str;
592
593    fn deref(&self) -> &Self::Target {
594        &self.pattern
595    }
596}
597
598impl PartialEq<&str> for PathRule {
599    fn eq(&self, other: &&str) -> bool {
600        self.pattern == *other
601    }
602}
603
604impl PartialEq<str> for PathRule {
605    fn eq(&self, other: &str) -> bool {
606        self.pattern == other
607    }
608}
609
610impl PartialEq<String> for PathRule {
611    fn eq(&self, other: &String) -> bool {
612        &self.pattern == other
613    }
614}
615
616/// A framework/tool plugin that contributes to dead code analysis.
617pub trait Plugin: Send + Sync {
618    /// Human-readable plugin name.
619    fn name(&self) -> &'static str;
620
621    /// Package names that activate this plugin when found in package.json.
622    /// Supports exact matches and prefix patterns (ending with `/`).
623    fn enablers(&self) -> &'static [&'static str] {
624        &[]
625    }
626
627    /// Check if this plugin should be active for the given project.
628    /// Default implementation checks `enablers()` against package.json dependencies.
629    fn is_enabled(&self, pkg: &PackageJson, root: &Path) -> bool {
630        let deps = pkg.all_dependency_names();
631        self.is_enabled_with_deps(&deps, root)
632    }
633
634    /// Fast variant of `is_enabled` that accepts a pre-computed deps list.
635    /// Avoids repeated `all_dependency_names()` allocation when checking many plugins.
636    fn is_enabled_with_deps(&self, deps: &[String], _root: &Path) -> bool {
637        let enablers = self.enablers();
638        if enablers.is_empty() {
639            return false;
640        }
641        enablers.iter().any(|enabler| {
642            if enabler.ends_with('/') {
643                // Prefix match (e.g., "@storybook/" matches "@storybook/react")
644                deps.iter().any(|d| d.starts_with(enabler))
645            } else {
646                deps.iter().any(|d| d == enabler)
647            }
648        })
649    }
650
651    /// Check whether this plugin should be active with source discovery available.
652    ///
653    /// Most plugins only need dependency/config activation. Convention-only tools
654    /// can override this to activate from discovered source filenames without
655    /// forcing a separate filesystem walk.
656    fn is_enabled_with_files(
657        &self,
658        deps: &[String],
659        root: &Path,
660        _discovered_files: &[PathBuf],
661    ) -> bool {
662        self.is_enabled_with_deps(deps, root)
663    }
664
665    /// Package-script binary/package names that can activate this plugin.
666    fn script_enablers(&self) -> &'static [&'static str] {
667        &[]
668    }
669
670    /// Check whether this plugin should be active from package.json scripts.
671    fn is_enabled_with_scripts(
672        &self,
673        script_packages: &rustc_hash::FxHashSet<String>,
674        _root: &Path,
675    ) -> bool {
676        let enablers = self.script_enablers();
677        if enablers.is_empty() {
678            return false;
679        }
680        enablers.iter().any(|enabler| {
681            if enabler.ends_with('/') {
682                script_packages
683                    .iter()
684                    .any(|package| package.starts_with(enabler))
685            } else {
686                script_packages.contains(*enabler)
687            }
688        })
689    }
690
691    /// Default glob patterns for entry point files.
692    fn entry_patterns(&self) -> &'static [&'static str] {
693        &[]
694    }
695
696    /// Entry point rules with optional exclusions.
697    fn entry_pattern_rules(&self) -> Vec<PathRule> {
698        self.entry_patterns()
699            .iter()
700            .map(|pattern| PathRule::from_static(pattern))
701            .collect()
702    }
703
704    /// How this plugin's entry patterns should contribute to coverage reachability.
705    ///
706    /// `Support` roots keep files alive for dead-code analysis but do not count
707    /// as runtime or test reachability for static coverage gaps.
708    fn entry_point_role(&self) -> EntryPointRole {
709        builtin_entry_point_role(self.name())
710    }
711
712    /// Glob patterns for config files this plugin can parse.
713    fn config_patterns(&self) -> &'static [&'static str] {
714        &[]
715    }
716
717    /// Files that are always considered "used" when this plugin is active.
718    fn always_used(&self) -> &'static [&'static str] {
719        &[]
720    }
721
722    /// Exports that are always considered used for matching file patterns.
723    fn used_exports(&self) -> Vec<(&'static str, &'static [&'static str])> {
724        vec![]
725    }
726
727    /// Used-export rules with optional exclusions.
728    fn used_export_rules(&self) -> Vec<UsedExportRule> {
729        self.used_exports()
730            .into_iter()
731            .map(|(pattern, exports)| UsedExportRule::from_static(pattern, exports))
732            .collect()
733    }
734
735    /// Class member names the framework invokes at runtime. Matching members
736    /// are skipped during `unused-class-members` analysis. Intended for
737    /// interface/contract patterns where the library calls methods on consumer
738    /// classes (e.g. ag-Grid's `agInit`, Web Components' `connectedCallback`).
739    fn used_class_members(&self) -> &'static [&'static str] {
740        &[]
741    }
742
743    /// Heritage-scoped class member rules. Each rule applies only to classes
744    /// matching its `extends` and/or `implements` clause. Used for frameworks
745    /// where lifecycle members are runtime-invoked only on classes that extend
746    /// a known base (e.g. Lit's `render`/`updated` on classes extending
747    /// `LitElement`, native Web Components' `connectedCallback` on classes
748    /// extending `HTMLElement`). Default: empty. Plugins override when they
749    /// need scoping; flat names should still come from `used_class_members`.
750    fn used_class_member_rules(&self) -> Vec<UsedClassMemberRule> {
751        Vec::new()
752    }
753
754    /// Glob patterns for test fixture files consumed by this framework.
755    /// These files are implicitly used by the test runner and should not be
756    /// flagged as unused. Unlike `always_used()`, this carries semantic intent
757    /// for reporting purposes.
758    fn fixture_glob_patterns(&self) -> &'static [&'static str] {
759        &[]
760    }
761
762    /// Hidden directory names that should be traversed when this plugin is active.
763    ///
764    /// These are consulted before normal plugin execution because source discovery
765    /// runs first. Keep entries static and package-convention scoped.
766    fn discovery_hidden_dirs(&self) -> &'static [&'static str] {
767        &[]
768    }
769
770    /// Dependencies that are tooling (used via CLI/config, not source imports).
771    /// These should not be flagged as unused devDependencies.
772    fn tooling_dependencies(&self) -> &'static [&'static str] {
773        &[]
774    }
775
776    /// Import prefixes that are virtual modules provided by this framework at build time.
777    /// Imports matching these prefixes should not be flagged as unlisted dependencies.
778    /// Each entry is matched as a prefix against the extracted package name
779    /// (e.g., `"@theme/"` matches `@theme/Layout`).
780    fn virtual_module_prefixes(&self) -> &'static [&'static str] {
781        &[]
782    }
783
784    /// Package name suffixes that are virtual modules provided by this framework
785    /// at build time (e.g., test runner mock conventions).
786    /// Imports matching these suffixes should not be flagged as unlisted dependencies.
787    /// Each entry is matched as a suffix against the extracted package name
788    /// (e.g., `"/__mocks__"` matches `@aws-sdk/__mocks__` and `some-pkg/__mocks__`).
789    fn virtual_package_suffixes(&self) -> &'static [&'static str] {
790        &[]
791    }
792
793    /// Import suffixes for build-time generated relative imports.
794    ///
795    /// Unresolved relative imports whose specifier ends with one of these suffixes
796    /// will not be flagged as unresolved. For example, SvelteKit generates
797    /// `./$types` imports in route files — returning `"/$types"` suppresses those.
798    fn generated_import_patterns(&self) -> &'static [&'static str] {
799        &[]
800    }
801
802    /// Import prefixes for generated type-only relative imports.
803    ///
804    /// Unresolved type-only imports whose specifier starts with one of these prefixes
805    /// will not be flagged as unresolved. Runtime imports are still reported.
806    fn generated_type_import_prefixes(&self) -> &'static [&'static str] {
807        &[]
808    }
809
810    /// Path alias mappings provided by this framework at build time.
811    ///
812    /// Returns a list of `(prefix, replacement_dir)` tuples. When an import starting
813    /// with `prefix` fails to resolve, the resolver will substitute the prefix with
814    /// `replacement_dir` (relative to the project root) and retry.
815    ///
816    /// Called once when plugins are activated. The project `root` is provided so
817    /// plugins can inspect the filesystem (e.g., Nuxt checks whether `app/` exists
818    /// to determine the `srcDir`).
819    fn path_aliases(&self, _root: &Path) -> Vec<(&'static str, String)> {
820        vec![]
821    }
822
823    /// Convention-based auto-imports provided by this framework.
824    ///
825    /// Returns the names this framework exposes to user code by filesystem
826    /// convention with no explicit `import` statement (e.g. Nuxt `components/`
827    /// resolved by `<Card001 />` template tags), each mapped to the source file
828    /// providing the export. When a file references one of these names without an
829    /// import, the resolver synthesizes a graph edge to `source`.
830    ///
831    /// Called once when plugins are activated. The project `root` is provided so
832    /// plugins can scan the convention directories on the filesystem. The table is
833    /// a function of which files exist on disk, so it is rebuilt every run and is
834    /// never folded into per-file extraction caching. See issue #704.
835    fn auto_imports(&self, _root: &Path) -> Vec<AutoImportRule> {
836        Vec::new()
837    }
838
839    /// File-scoped dependency providers contributed by this framework.
840    fn provided_dependencies(&self) -> Vec<ProvidedDependencyRule> {
841        Vec::new()
842    }
843
844    /// Check whether parsed package.json metadata activates this plugin.
845    fn is_enabled_with_package_json(&self, _pkg: &PackageJson, _root: &Path) -> bool {
846        false
847    }
848
849    /// Resolve parsed package.json metadata into dynamic plugin facts.
850    fn resolve_package_json(&self, _pkg: &PackageJson, _root: &Path) -> PluginResult {
851        PluginResult::default()
852    }
853
854    /// Dependencies referenced by the package's own package.json metadata.
855    ///
856    /// Unlike config-derived dependencies, these credits apply only to the
857    /// package.json that produced them.
858    fn package_json_referenced_dependencies(
859        &self,
860        _pkg: &PackageJson,
861        _root: &Path,
862    ) -> Vec<String> {
863        Vec::new()
864    }
865
866    /// Parse a config file's AST to discover additional entries, dependencies, etc.
867    ///
868    /// Called for each config file matching `config_patterns()`. The source code
869    /// and parsed AST are provided — use [`config_parser`] utilities to extract values.
870    fn resolve_config(&self, _config_path: &Path, _source: &str, _root: &Path) -> PluginResult {
871        PluginResult::default()
872    }
873
874    /// The key name in package.json that holds inline configuration for this tool.
875    /// When set (e.g., `"jest"` for the `"jest"` key in package.json), the plugin
876    /// system will extract that key's value and call `resolve_config` with its
877    /// JSON content if no standalone config file was found.
878    fn package_json_config_key(&self) -> Option<&'static str> {
879        None
880    }
881}
882
883fn builtin_entry_point_role(name: &str) -> EntryPointRole {
884    if TEST_ENTRY_POINT_PLUGINS.contains(&name) {
885        EntryPointRole::Test
886    } else if RUNTIME_ENTRY_POINT_PLUGINS.contains(&name) {
887        EntryPointRole::Runtime
888    } else {
889        EntryPointRole::Support
890    }
891}
892
893/// Macro to eliminate boilerplate in plugin implementations.
894///
895/// Generates a struct and a `Plugin` trait impl with the standard static methods
896/// (`name`, `enablers`, `entry_patterns`, `config_patterns`, `always_used`, `tooling_dependencies`,
897/// `fixture_glob_patterns`, `virtual_module_prefixes`, `virtual_package_suffixes`,
898/// `generated_type_import_prefixes`, `used_exports`).
899///
900/// For plugins that need custom `resolve_config()` or `is_enabled()`, keep those as
901/// manual `impl Plugin for ...` blocks instead of using this macro.
902///
903/// # Usage
904///
905/// ```ignore
906/// // Simple plugin (most common):
907/// define_plugin! {
908///     struct VitePlugin => "vite",
909///     enablers: ENABLERS,
910///     entry_patterns: ENTRY_PATTERNS,
911///     config_patterns: CONFIG_PATTERNS,
912///     always_used: ALWAYS_USED,
913///     tooling_dependencies: TOOLING_DEPENDENCIES,
914/// }
915///
916/// // Plugin with used_exports:
917/// define_plugin! {
918///     struct RemixPlugin => "remix",
919///     enablers: ENABLERS,
920///     entry_patterns: ENTRY_PATTERNS,
921///     always_used: ALWAYS_USED,
922///     tooling_dependencies: TOOLING_DEPENDENCIES,
923///     used_exports: [("app/routes/**/*.{ts,tsx}", ROUTE_EXPORTS)],
924/// }
925///
926/// // Plugin with imports-only resolve_config (extracts imports from config as deps):
927/// define_plugin! {
928///     struct CypressPlugin => "cypress",
929///     enablers: ENABLERS,
930///     entry_patterns: ENTRY_PATTERNS,
931///     config_patterns: CONFIG_PATTERNS,
932///     always_used: ALWAYS_USED,
933///     tooling_dependencies: TOOLING_DEPENDENCIES,
934///     resolve_config: imports_only,
935/// }
936///
937/// // Plugin with custom resolve_config body:
938/// define_plugin! {
939///     struct RollupPlugin => "rollup",
940///     enablers: ENABLERS,
941///     config_patterns: CONFIG_PATTERNS,
942///     always_used: ALWAYS_USED,
943///     tooling_dependencies: TOOLING_DEPENDENCIES,
944///     resolve_config(config_path, source, _root) {
945///         let mut result = PluginResult::default();
946///         // custom config parsing...
947///         result
948///     }
949/// }
950/// ```
951///
952/// All fields except `struct` and `enablers` are optional and default to `&[]` / `vec![]`.
953macro_rules! define_plugin {
954    (
955        struct $name:ident => $display:expr,
956        enablers: $enablers:expr
957        $(, entry_patterns: $entry:expr)?
958        $(, config_patterns: $config:expr)?
959        $(, always_used: $always:expr)?
960        $(, tooling_dependencies: $tooling:expr)?
961        $(, fixture_glob_patterns: $fixtures:expr)?
962        $(, discovery_hidden_dirs: $hidden_dirs:expr)?
963        $(, virtual_module_prefixes: $virtual:expr)?
964        $(, virtual_package_suffixes: $virtual_suffixes:expr)?
965        $(, generated_type_import_prefixes: $generated_type_prefixes:expr)?
966        $(, provided_dependencies: $provided_dependencies:expr)?
967        $(, used_exports: [$( ($pat:expr, $exports:expr) ),* $(,)?])?
968        , resolve_config: imports_only
969        $(,)?
970    ) => {
971        pub struct $name;
972
973        impl Plugin for $name {
974            fn name(&self) -> &'static str {
975                $display
976            }
977
978            fn enablers(&self) -> &'static [&'static str] {
979                $enablers
980            }
981
982            $( fn entry_patterns(&self) -> &'static [&'static str] { $entry } )?
983            $( fn config_patterns(&self) -> &'static [&'static str] { $config } )?
984            $( fn always_used(&self) -> &'static [&'static str] { $always } )?
985            $( fn tooling_dependencies(&self) -> &'static [&'static str] { $tooling } )?
986            $( fn fixture_glob_patterns(&self) -> &'static [&'static str] { $fixtures } )?
987            $( fn discovery_hidden_dirs(&self) -> &'static [&'static str] { $hidden_dirs } )?
988            $( fn virtual_module_prefixes(&self) -> &'static [&'static str] { $virtual } )?
989            $( fn virtual_package_suffixes(&self) -> &'static [&'static str] { $virtual_suffixes } )?
990            $( fn generated_type_import_prefixes(&self) -> &'static [&'static str] { $generated_type_prefixes } )?
991            $( fn provided_dependencies(&self) -> Vec<ProvidedDependencyRule> { $provided_dependencies } )?
992
993            $(
994                fn used_exports(&self) -> Vec<(&'static str, &'static [&'static str])> {
995                    vec![$( ($pat, $exports) ),*]
996                }
997            )?
998
999            fn resolve_config(
1000                &self,
1001                config_path: &std::path::Path,
1002                source: &str,
1003                _root: &std::path::Path,
1004            ) -> PluginResult {
1005                let mut result = PluginResult::default();
1006                let imports = crate::plugins::config_parser::extract_imports(source, config_path);
1007                for imp in &imports {
1008                    let dep = crate::resolve::extract_package_name(imp);
1009                    result.referenced_dependencies.push(dep);
1010                }
1011                result
1012            }
1013        }
1014    };
1015
1016    (
1017        struct $name:ident => $display:expr,
1018        enablers: $enablers:expr
1019        $(, entry_patterns: $entry:expr)?
1020        $(, config_patterns: $config:expr)?
1021        $(, always_used: $always:expr)?
1022        $(, tooling_dependencies: $tooling:expr)?
1023        $(, fixture_glob_patterns: $fixtures:expr)?
1024        $(, discovery_hidden_dirs: $hidden_dirs:expr)?
1025        $(, virtual_module_prefixes: $virtual:expr)?
1026        $(, virtual_package_suffixes: $virtual_suffixes:expr)?
1027        $(, generated_type_import_prefixes: $generated_type_prefixes:expr)?
1028        $(, provided_dependencies: $provided_dependencies:expr)?
1029        $(, package_json_config_key: $pkg_key:expr)?
1030        $(, used_exports: [$( ($pat:expr, $exports:expr) ),* $(,)?])?
1031        , resolve_config($cp:ident, $src:ident, $root:ident) $body:block
1032        $(,)?
1033    ) => {
1034        pub struct $name;
1035
1036        impl Plugin for $name {
1037            fn name(&self) -> &'static str {
1038                $display
1039            }
1040
1041            fn enablers(&self) -> &'static [&'static str] {
1042                $enablers
1043            }
1044
1045            $( fn entry_patterns(&self) -> &'static [&'static str] { $entry } )?
1046            $( fn config_patterns(&self) -> &'static [&'static str] { $config } )?
1047            $( fn always_used(&self) -> &'static [&'static str] { $always } )?
1048            $( fn tooling_dependencies(&self) -> &'static [&'static str] { $tooling } )?
1049            $( fn fixture_glob_patterns(&self) -> &'static [&'static str] { $fixtures } )?
1050            $( fn discovery_hidden_dirs(&self) -> &'static [&'static str] { $hidden_dirs } )?
1051            $( fn virtual_module_prefixes(&self) -> &'static [&'static str] { $virtual } )?
1052            $( fn virtual_package_suffixes(&self) -> &'static [&'static str] { $virtual_suffixes } )?
1053            $( fn generated_type_import_prefixes(&self) -> &'static [&'static str] { $generated_type_prefixes } )?
1054            $( fn provided_dependencies(&self) -> Vec<ProvidedDependencyRule> { $provided_dependencies } )?
1055
1056            $(
1057                fn package_json_config_key(&self) -> Option<&'static str> {
1058                    Some($pkg_key)
1059                }
1060            )?
1061
1062            $(
1063                fn used_exports(&self) -> Vec<(&'static str, &'static [&'static str])> {
1064                    vec![$( ($pat, $exports) ),*]
1065                }
1066            )?
1067
1068            fn resolve_config(
1069                &self,
1070                $cp: &std::path::Path,
1071                $src: &str,
1072                $root: &std::path::Path,
1073            ) -> PluginResult
1074            $body
1075        }
1076    };
1077
1078    (
1079        struct $name:ident => $display:expr,
1080        enablers: $enablers:expr
1081        $(, entry_patterns: $entry:expr)?
1082        $(, config_patterns: $config:expr)?
1083        $(, always_used: $always:expr)?
1084        $(, tooling_dependencies: $tooling:expr)?
1085        $(, fixture_glob_patterns: $fixtures:expr)?
1086        $(, discovery_hidden_dirs: $hidden_dirs:expr)?
1087        $(, virtual_module_prefixes: $virtual:expr)?
1088        $(, virtual_package_suffixes: $virtual_suffixes:expr)?
1089        $(, generated_type_import_prefixes: $generated_type_prefixes:expr)?
1090        $(, provided_dependencies: $provided_dependencies:expr)?
1091        $(, used_exports: [$( ($pat:expr, $exports:expr) ),* $(,)?])?
1092        $(,)?
1093    ) => {
1094        pub struct $name;
1095
1096        impl Plugin for $name {
1097            fn name(&self) -> &'static str {
1098                $display
1099            }
1100
1101            fn enablers(&self) -> &'static [&'static str] {
1102                $enablers
1103            }
1104
1105            $( fn entry_patterns(&self) -> &'static [&'static str] { $entry } )?
1106            $( fn config_patterns(&self) -> &'static [&'static str] { $config } )?
1107            $( fn always_used(&self) -> &'static [&'static str] { $always } )?
1108            $( fn tooling_dependencies(&self) -> &'static [&'static str] { $tooling } )?
1109            $( fn fixture_glob_patterns(&self) -> &'static [&'static str] { $fixtures } )?
1110            $( fn discovery_hidden_dirs(&self) -> &'static [&'static str] { $hidden_dirs } )?
1111            $( fn virtual_module_prefixes(&self) -> &'static [&'static str] { $virtual } )?
1112            $( fn virtual_package_suffixes(&self) -> &'static [&'static str] { $virtual_suffixes } )?
1113            $( fn generated_type_import_prefixes(&self) -> &'static [&'static str] { $generated_type_prefixes } )?
1114            $( fn provided_dependencies(&self) -> Vec<ProvidedDependencyRule> { $provided_dependencies } )?
1115
1116            $(
1117                fn used_exports(&self) -> Vec<(&'static str, &'static [&'static str])> {
1118                    vec![$( ($pat, $exports) ),*]
1119                }
1120            )?
1121        }
1122    };
1123}
1124
1125pub mod config_parser;
1126pub mod registry;
1127mod tooling;
1128
1129pub use registry::{AggregatedPluginResult, PluginRegistry};
1130pub use tooling::is_known_tooling_dependency;
1131
1132mod adonis;
1133mod angular;
1134mod astro;
1135mod ava;
1136mod babel;
1137mod biome;
1138mod browser_extension;
1139mod bun;
1140mod c8;
1141mod capacitor;
1142mod changesets;
1143mod commitizen;
1144mod commitlint;
1145mod content_collections;
1146mod contentlayer;
1147mod convex;
1148mod cspell;
1149mod cucumber;
1150mod cypress;
1151mod danger;
1152mod dependency_cruiser;
1153mod docusaurus;
1154mod drizzle;
1155mod electron;
1156mod ember;
1157mod eslint;
1158mod expo;
1159mod expo_router;
1160mod firebase;
1161mod fumadocs;
1162mod gatsby;
1163mod graphql_codegen;
1164mod hardhat;
1165mod husky;
1166mod i18next;
1167mod ionic;
1168mod jest;
1169mod k6;
1170mod karma;
1171mod knex;
1172mod kysely;
1173mod lefthook;
1174mod lexical;
1175mod lint_staged;
1176mod lit;
1177mod markdownlint;
1178mod mintlify;
1179mod mocha;
1180mod msw;
1181mod napi_rs;
1182mod nestjs;
1183mod next_intl;
1184mod nextjs;
1185mod nitro;
1186mod nodemon;
1187pub(crate) mod nuxt;
1188mod nx;
1189mod nyc;
1190mod obsidian;
1191mod openapi_ts;
1192mod opencode;
1193mod opennext_cloudflare;
1194mod oxlint;
1195mod pandacss;
1196mod parcel;
1197mod pinia;
1198mod pkg_utils;
1199mod playwright;
1200mod plop;
1201mod pm2;
1202mod pnpm;
1203mod postcss;
1204mod prettier;
1205mod prisma;
1206mod qwik;
1207mod react_compiler;
1208mod react_native;
1209mod react_router;
1210mod redwoodsdk;
1211mod relay;
1212mod remark;
1213mod remix;
1214mod rolldown;
1215mod rollup;
1216mod rsbuild;
1217mod rspack;
1218mod rspress;
1219mod sanity;
1220mod semantic_release;
1221mod sentry;
1222mod simple_git_hooks;
1223mod storybook;
1224mod stryker;
1225mod stylelint;
1226mod supabase;
1227mod sveltekit;
1228mod svgo;
1229mod svgr;
1230mod swc;
1231mod syncpack;
1232mod tailwind;
1233mod tanstack_router;
1234mod tap;
1235mod test_alias;
1236mod tsd;
1237mod tsdown;
1238mod tsup;
1239mod turborepo;
1240mod typedoc;
1241mod typeorm;
1242mod typescript;
1243mod unocss;
1244mod varlock;
1245mod velite;
1246mod vercel;
1247mod vite;
1248mod vitepress;
1249mod vitest;
1250mod vscode;
1251mod webdriverio;
1252mod webpack;
1253mod wrangler;
1254mod wuchale;
1255mod wxt;
1256
1257#[cfg(test)]
1258mod tests {
1259    use super::*;
1260    use std::path::Path;
1261
1262    #[test]
1263    fn is_enabled_with_deps_exact_match() {
1264        let plugin = nextjs::NextJsPlugin;
1265        let deps = vec!["next".to_string()];
1266        assert!(plugin.is_enabled_with_deps(&deps, Path::new("/project")));
1267    }
1268
1269    #[test]
1270    fn is_enabled_with_deps_no_match() {
1271        let plugin = nextjs::NextJsPlugin;
1272        let deps = vec!["react".to_string()];
1273        assert!(!plugin.is_enabled_with_deps(&deps, Path::new("/project")));
1274    }
1275
1276    #[test]
1277    fn is_enabled_with_deps_empty_deps() {
1278        let plugin = nextjs::NextJsPlugin;
1279        let deps: Vec<String> = vec![];
1280        assert!(!plugin.is_enabled_with_deps(&deps, Path::new("/project")));
1281    }
1282
1283    #[test]
1284    fn entry_point_role_defaults_are_centralized() {
1285        assert_eq!(vite::VitePlugin.entry_point_role(), EntryPointRole::Runtime);
1286        assert_eq!(
1287            vitest::VitestPlugin.entry_point_role(),
1288            EntryPointRole::Test
1289        );
1290        assert_eq!(
1291            storybook::StorybookPlugin.entry_point_role(),
1292            EntryPointRole::Support
1293        );
1294        assert_eq!(
1295            obsidian::ObsidianPlugin.entry_point_role(),
1296            EntryPointRole::Runtime
1297        );
1298        assert_eq!(knex::KnexPlugin.entry_point_role(), EntryPointRole::Support);
1299    }
1300
1301    #[test]
1302    fn plugins_with_entry_patterns_have_explicit_role_intent() {
1303        let runtime_or_test_or_support: rustc_hash::FxHashSet<&'static str> =
1304            TEST_ENTRY_POINT_PLUGINS
1305                .iter()
1306                .chain(RUNTIME_ENTRY_POINT_PLUGINS.iter())
1307                .chain(SUPPORT_ENTRY_POINT_PLUGINS.iter())
1308                .copied()
1309                .collect();
1310
1311        for plugin in crate::plugins::registry::builtin::create_builtin_plugins() {
1312            if plugin.entry_patterns().is_empty() {
1313                continue;
1314            }
1315            assert!(
1316                runtime_or_test_or_support.contains(plugin.name()),
1317                "plugin '{}' exposes entry patterns but is missing from the entry-point role map",
1318                plugin.name()
1319            );
1320        }
1321    }
1322
1323    #[test]
1324    fn plugin_result_is_empty_when_default() {
1325        let r = PluginResult::default();
1326        assert!(r.is_empty());
1327    }
1328
1329    #[test]
1330    fn plugin_result_not_empty_with_entry_patterns() {
1331        let r = PluginResult {
1332            entry_patterns: vec!["*.ts".into()],
1333            ..Default::default()
1334        };
1335        assert!(!r.is_empty());
1336    }
1337
1338    #[test]
1339    fn plugin_result_not_empty_with_referenced_deps() {
1340        let r = PluginResult {
1341            referenced_dependencies: vec!["lodash".to_string()],
1342            ..Default::default()
1343        };
1344        assert!(!r.is_empty());
1345    }
1346
1347    #[test]
1348    fn plugin_result_not_empty_with_setup_files() {
1349        let r = PluginResult {
1350            setup_files: vec![PathBuf::from("/setup.ts")],
1351            ..Default::default()
1352        };
1353        assert!(!r.is_empty());
1354    }
1355
1356    #[test]
1357    fn plugin_result_not_empty_with_always_used_files() {
1358        let r = PluginResult {
1359            always_used_files: vec!["**/*.stories.tsx".to_string()],
1360            ..Default::default()
1361        };
1362        assert!(!r.is_empty());
1363    }
1364
1365    #[test]
1366    fn plugin_result_not_empty_with_fixture_patterns() {
1367        let r = PluginResult {
1368            fixture_patterns: vec!["**/__fixtures__/**/*".to_string()],
1369            ..Default::default()
1370        };
1371        assert!(!r.is_empty());
1372    }
1373
1374    #[test]
1375    fn is_enabled_with_deps_prefix_match() {
1376        let plugin = storybook::StorybookPlugin;
1377        let deps = vec!["@storybook/react".to_string()];
1378        assert!(plugin.is_enabled_with_deps(&deps, Path::new("/project")));
1379    }
1380
1381    #[test]
1382    fn is_enabled_with_deps_prefix_no_match_without_slash() {
1383        let plugin = storybook::StorybookPlugin;
1384        let deps = vec!["@storybookish".to_string()];
1385        assert!(!plugin.is_enabled_with_deps(&deps, Path::new("/project")));
1386    }
1387
1388    #[test]
1389    fn is_enabled_with_deps_multiple_enablers() {
1390        let plugin = vitest::VitestPlugin;
1391        let deps_vitest = vec!["vitest".to_string()];
1392        let deps_none = vec!["mocha".to_string()];
1393        assert!(plugin.is_enabled_with_deps(&deps_vitest, Path::new("/project")));
1394        assert!(!plugin.is_enabled_with_deps(&deps_none, Path::new("/project")));
1395    }
1396
1397    #[test]
1398    fn plugin_default_methods_return_empty() {
1399        let plugin = commitizen::CommitizenPlugin;
1400        assert!(
1401            plugin.tooling_dependencies().is_empty() || !plugin.tooling_dependencies().is_empty()
1402        );
1403        assert!(plugin.virtual_module_prefixes().is_empty());
1404        assert!(plugin.virtual_package_suffixes().is_empty());
1405        assert!(plugin.path_aliases(Path::new("/project")).is_empty());
1406        assert!(
1407            plugin.package_json_config_key().is_none()
1408                || plugin.package_json_config_key().is_some()
1409        );
1410    }
1411
1412    #[test]
1413    fn plugin_resolve_config_default_returns_empty() {
1414        let plugin = commitizen::CommitizenPlugin;
1415        let result = plugin.resolve_config(
1416            Path::new("/project/config.js"),
1417            "const x = 1;",
1418            Path::new("/project"),
1419        );
1420        assert!(result.is_empty());
1421    }
1422
1423    #[test]
1424    fn is_enabled_with_deps_exact_and_prefix_both_work() {
1425        let plugin = storybook::StorybookPlugin;
1426        let deps_exact = vec!["storybook".to_string()];
1427        assert!(plugin.is_enabled_with_deps(&deps_exact, Path::new("/project")));
1428        let deps_prefix = vec!["@storybook/vue3".to_string()];
1429        assert!(plugin.is_enabled_with_deps(&deps_prefix, Path::new("/project")));
1430    }
1431
1432    #[test]
1433    fn is_enabled_with_deps_multiple_enablers_remix() {
1434        let plugin = remix::RemixPlugin;
1435        let deps_node = vec!["@remix-run/node".to_string()];
1436        assert!(plugin.is_enabled_with_deps(&deps_node, Path::new("/project")));
1437        let deps_react = vec!["@remix-run/react".to_string()];
1438        assert!(plugin.is_enabled_with_deps(&deps_react, Path::new("/project")));
1439        let deps_cf = vec!["@remix-run/cloudflare".to_string()];
1440        assert!(plugin.is_enabled_with_deps(&deps_cf, Path::new("/project")));
1441    }
1442
1443    struct MinimalPlugin;
1444    impl Plugin for MinimalPlugin {
1445        fn name(&self) -> &'static str {
1446            "minimal"
1447        }
1448    }
1449
1450    #[test]
1451    fn default_enablers_is_empty() {
1452        assert!(MinimalPlugin.enablers().is_empty());
1453    }
1454
1455    #[test]
1456    fn default_entry_patterns_is_empty() {
1457        assert!(MinimalPlugin.entry_patterns().is_empty());
1458    }
1459
1460    #[test]
1461    fn default_config_patterns_is_empty() {
1462        assert!(MinimalPlugin.config_patterns().is_empty());
1463    }
1464
1465    #[test]
1466    fn default_always_used_is_empty() {
1467        assert!(MinimalPlugin.always_used().is_empty());
1468    }
1469
1470    #[test]
1471    fn default_used_exports_is_empty() {
1472        assert!(MinimalPlugin.used_exports().is_empty());
1473    }
1474
1475    #[test]
1476    fn default_tooling_dependencies_is_empty() {
1477        assert!(MinimalPlugin.tooling_dependencies().is_empty());
1478    }
1479
1480    #[test]
1481    fn default_fixture_glob_patterns_is_empty() {
1482        assert!(MinimalPlugin.fixture_glob_patterns().is_empty());
1483    }
1484
1485    #[test]
1486    fn default_virtual_module_prefixes_is_empty() {
1487        assert!(MinimalPlugin.virtual_module_prefixes().is_empty());
1488    }
1489
1490    #[test]
1491    fn default_virtual_package_suffixes_is_empty() {
1492        assert!(MinimalPlugin.virtual_package_suffixes().is_empty());
1493    }
1494
1495    #[test]
1496    fn default_path_aliases_is_empty() {
1497        assert!(MinimalPlugin.path_aliases(Path::new("/")).is_empty());
1498    }
1499
1500    #[test]
1501    fn default_resolve_config_returns_empty() {
1502        let r = MinimalPlugin.resolve_config(
1503            Path::new("config.js"),
1504            "export default {}",
1505            Path::new("/"),
1506        );
1507        assert!(r.is_empty());
1508    }
1509
1510    #[test]
1511    fn default_package_json_metadata_hooks_are_empty() {
1512        let pkg = PackageJson::default();
1513        assert!(!MinimalPlugin.is_enabled_with_package_json(&pkg, Path::new("/")));
1514        assert!(
1515            MinimalPlugin
1516                .resolve_package_json(&pkg, Path::new("/"))
1517                .is_empty()
1518        );
1519    }
1520
1521    #[test]
1522    fn default_package_json_config_key_is_none() {
1523        assert!(MinimalPlugin.package_json_config_key().is_none());
1524    }
1525
1526    #[test]
1527    fn default_is_enabled_returns_false_when_no_enablers() {
1528        let deps = vec!["anything".to_string()];
1529        assert!(!MinimalPlugin.is_enabled_with_deps(&deps, Path::new("/")));
1530    }
1531
1532    #[test]
1533    fn all_builtin_plugin_names_are_unique() {
1534        let plugins = registry::builtin::create_builtin_plugins();
1535        let mut seen = std::collections::BTreeSet::new();
1536        for p in &plugins {
1537            let name = p.name();
1538            assert!(seen.insert(name), "duplicate plugin name: {name}");
1539        }
1540    }
1541
1542    #[test]
1543    fn all_builtin_plugins_have_activation_signals() {
1544        const PACKAGE_JSON_METADATA_PLUGINS: &[&str] = &["napi-rs"];
1545        let plugins = registry::builtin::create_builtin_plugins();
1546        for p in &plugins {
1547            assert!(
1548                !p.enablers().is_empty()
1549                    || !p.script_enablers().is_empty()
1550                    || PACKAGE_JSON_METADATA_PLUGINS.contains(&p.name()),
1551                "plugin '{}' has no activation signal",
1552                p.name()
1553            );
1554        }
1555    }
1556
1557    #[test]
1558    fn plugins_with_config_patterns_have_always_used() {
1559        let plugins = registry::builtin::create_builtin_plugins();
1560        for p in &plugins {
1561            if !p.config_patterns().is_empty() {
1562                assert!(
1563                    !p.always_used().is_empty(),
1564                    "plugin '{}' has config_patterns but no always_used",
1565                    p.name()
1566                );
1567            }
1568        }
1569    }
1570
1571    #[test]
1572    fn framework_plugins_enablers() {
1573        let cases: Vec<(&dyn Plugin, &[&str])> = vec![
1574            (&nextjs::NextJsPlugin, &["next"]),
1575            (&nuxt::NuxtPlugin, &["nuxt"]),
1576            (&angular::AngularPlugin, &["@angular/core"]),
1577            (&ionic::IonicPlugin, &["@ionic/angular"]),
1578            (&sveltekit::SvelteKitPlugin, &["@sveltejs/kit"]),
1579            (&gatsby::GatsbyPlugin, &["gatsby"]),
1580        ];
1581        for (plugin, expected_enablers) in cases {
1582            let enablers = plugin.enablers();
1583            for expected in expected_enablers {
1584                assert!(
1585                    enablers.contains(expected),
1586                    "plugin '{}' should have '{}'",
1587                    plugin.name(),
1588                    expected
1589                );
1590            }
1591        }
1592    }
1593
1594    #[test]
1595    fn testing_plugins_enablers() {
1596        let cases: Vec<(&dyn Plugin, &str)> = vec![
1597            (&jest::JestPlugin, "jest"),
1598            (&vitest::VitestPlugin, "vitest"),
1599            (&playwright::PlaywrightPlugin, "@playwright/test"),
1600            (&cypress::CypressPlugin, "cypress"),
1601            (&mocha::MochaPlugin, "mocha"),
1602            (&stryker::StrykerPlugin, "@stryker-mutator/core"),
1603        ];
1604        for (plugin, enabler) in cases {
1605            assert!(
1606                plugin.enablers().contains(&enabler),
1607                "plugin '{}' should have '{}'",
1608                plugin.name(),
1609                enabler
1610            );
1611        }
1612    }
1613
1614    #[test]
1615    fn bundler_plugins_enablers() {
1616        let cases: Vec<(&dyn Plugin, &str)> = vec![
1617            (&vite::VitePlugin, "vite"),
1618            (&webpack::WebpackPlugin, "webpack"),
1619            (&rollup::RollupPlugin, "rollup"),
1620        ];
1621        for (plugin, enabler) in cases {
1622            assert!(
1623                plugin.enablers().contains(&enabler),
1624                "plugin '{}' should have '{}'",
1625                plugin.name(),
1626                enabler
1627            );
1628        }
1629    }
1630
1631    #[test]
1632    fn test_plugins_have_test_entry_patterns() {
1633        let test_plugins: Vec<&dyn Plugin> = vec![
1634            &bun::BunPlugin,
1635            &jest::JestPlugin,
1636            &vitest::VitestPlugin,
1637            &mocha::MochaPlugin,
1638            &tap::TapPlugin,
1639            &tsd::TsdPlugin,
1640        ];
1641        for plugin in test_plugins {
1642            let patterns = plugin.entry_patterns();
1643            assert!(
1644                !patterns.is_empty(),
1645                "test plugin '{}' should have entry patterns",
1646                plugin.name()
1647            );
1648            assert!(
1649                patterns
1650                    .iter()
1651                    .any(|p| p.contains("test") || p.contains("spec") || p.contains("__tests__")),
1652                "test plugin '{}' should have test/spec patterns",
1653                plugin.name()
1654            );
1655        }
1656    }
1657
1658    #[test]
1659    fn framework_plugins_have_entry_patterns() {
1660        let plugins: Vec<&dyn Plugin> = vec![
1661            &nextjs::NextJsPlugin,
1662            &nuxt::NuxtPlugin,
1663            &angular::AngularPlugin,
1664            &sveltekit::SvelteKitPlugin,
1665        ];
1666        for plugin in plugins {
1667            assert!(
1668                !plugin.entry_patterns().is_empty(),
1669                "framework plugin '{}' should have entry patterns",
1670                plugin.name()
1671            );
1672        }
1673    }
1674
1675    #[test]
1676    fn plugins_with_resolve_config_have_config_patterns() {
1677        let plugins: Vec<&dyn Plugin> = vec![
1678            &jest::JestPlugin,
1679            &vitest::VitestPlugin,
1680            &babel::BabelPlugin,
1681            &eslint::EslintPlugin,
1682            &webpack::WebpackPlugin,
1683            &storybook::StorybookPlugin,
1684            &typescript::TypeScriptPlugin,
1685            &postcss::PostCssPlugin,
1686            &nextjs::NextJsPlugin,
1687            &nuxt::NuxtPlugin,
1688            &angular::AngularPlugin,
1689            &nx::NxPlugin,
1690            &stryker::StrykerPlugin,
1691            &wuchale::WuchalePlugin,
1692            &rollup::RollupPlugin,
1693            &sveltekit::SvelteKitPlugin,
1694            &prettier::PrettierPlugin,
1695            &contentlayer::ContentlayerPlugin,
1696        ];
1697        for plugin in plugins {
1698            assert!(
1699                !plugin.config_patterns().is_empty(),
1700                "plugin '{}' with resolve_config should have config_patterns",
1701                plugin.name()
1702            );
1703        }
1704    }
1705
1706    #[test]
1707    fn plugin_tooling_deps_include_enabler_package() {
1708        let plugins: Vec<&dyn Plugin> = vec![
1709            &jest::JestPlugin,
1710            &vitest::VitestPlugin,
1711            &webpack::WebpackPlugin,
1712            &typescript::TypeScriptPlugin,
1713            &eslint::EslintPlugin,
1714            &prettier::PrettierPlugin,
1715            &danger::DangerPlugin,
1716            &stryker::StrykerPlugin,
1717            &wuchale::WuchalePlugin,
1718            &contentlayer::ContentlayerPlugin,
1719        ];
1720        for plugin in plugins {
1721            let tooling = plugin.tooling_dependencies();
1722            let enablers = plugin.enablers();
1723            assert!(
1724                enablers
1725                    .iter()
1726                    .any(|e| !e.ends_with('/') && tooling.contains(e)),
1727                "plugin '{}': at least one non-prefix enabler should be in tooling_dependencies",
1728                plugin.name()
1729            );
1730        }
1731    }
1732
1733    #[test]
1734    fn nextjs_has_used_exports_for_pages() {
1735        let plugin = nextjs::NextJsPlugin;
1736        let exports = plugin.used_exports();
1737        assert!(!exports.is_empty());
1738        assert!(exports.iter().any(|(_, names)| names.contains(&"default")));
1739    }
1740
1741    #[test]
1742    fn remix_has_used_exports_for_routes() {
1743        let plugin = remix::RemixPlugin;
1744        let exports = plugin.used_exports();
1745        assert!(!exports.is_empty());
1746        let route_entry = exports.iter().find(|(pat, _)| pat.contains("routes"));
1747        assert!(route_entry.is_some());
1748        let (_, names) = route_entry.unwrap();
1749        assert!(names.contains(&"loader"));
1750        assert!(names.contains(&"action"));
1751        assert!(names.contains(&"default"));
1752    }
1753
1754    #[test]
1755    fn sveltekit_has_used_exports_for_routes() {
1756        let plugin = sveltekit::SvelteKitPlugin;
1757        let exports = plugin.used_exports();
1758        assert!(!exports.is_empty());
1759        assert!(exports.iter().any(|(_, names)| names.contains(&"GET")));
1760    }
1761
1762    #[test]
1763    fn nuxt_has_hash_virtual_prefix() {
1764        assert!(nuxt::NuxtPlugin.virtual_module_prefixes().contains(&"#"));
1765    }
1766
1767    #[test]
1768    fn sveltekit_has_dollar_virtual_prefixes() {
1769        let prefixes = sveltekit::SvelteKitPlugin.virtual_module_prefixes();
1770        assert!(prefixes.contains(&"$app/"));
1771        assert!(prefixes.contains(&"$env/"));
1772        assert!(prefixes.contains(&"$lib/"));
1773    }
1774
1775    #[test]
1776    fn sveltekit_has_lib_path_alias() {
1777        let aliases = sveltekit::SvelteKitPlugin.path_aliases(Path::new("/project"));
1778        assert!(aliases.iter().any(|(prefix, _)| *prefix == "$lib/"));
1779    }
1780
1781    #[test]
1782    fn nuxt_has_tilde_path_alias() {
1783        let aliases = nuxt::NuxtPlugin.path_aliases(Path::new("/nonexistent"));
1784        assert!(aliases.iter().any(|(prefix, _)| *prefix == "~/"));
1785        assert!(aliases.iter().any(|(prefix, _)| *prefix == "~~/"));
1786    }
1787
1788    #[test]
1789    fn jest_has_package_json_config_key() {
1790        assert_eq!(jest::JestPlugin.package_json_config_key(), Some("jest"));
1791    }
1792
1793    #[test]
1794    fn tsd_has_package_json_config_key() {
1795        assert_eq!(tsd::TsdPlugin.package_json_config_key(), Some("tsd"));
1796    }
1797
1798    #[test]
1799    fn babel_has_package_json_config_key() {
1800        assert_eq!(babel::BabelPlugin.package_json_config_key(), Some("babel"));
1801    }
1802
1803    #[test]
1804    fn eslint_has_package_json_config_key() {
1805        assert_eq!(
1806            eslint::EslintPlugin.package_json_config_key(),
1807            Some("eslintConfig")
1808        );
1809    }
1810
1811    #[test]
1812    fn prettier_has_package_json_config_key() {
1813        assert_eq!(
1814            prettier::PrettierPlugin.package_json_config_key(),
1815            Some("prettier")
1816        );
1817    }
1818
1819    #[test]
1820    fn macro_generated_plugin_basic_properties() {
1821        let plugin = msw::MswPlugin;
1822        assert_eq!(plugin.name(), "msw");
1823        assert!(plugin.enablers().contains(&"msw"));
1824        assert!(!plugin.entry_patterns().is_empty());
1825        assert!(plugin.config_patterns().is_empty());
1826        assert!(!plugin.always_used().is_empty());
1827        assert!(!plugin.tooling_dependencies().is_empty());
1828    }
1829
1830    #[test]
1831    fn macro_generated_plugin_with_used_exports() {
1832        let plugin = remix::RemixPlugin;
1833        assert_eq!(plugin.name(), "remix");
1834        assert!(!plugin.used_exports().is_empty());
1835    }
1836
1837    #[test]
1838    fn macro_passes_through_virtual_package_suffixes() {
1839        define_plugin! {
1840            struct MacroSuffixSmokePlugin => "macro-suffix-smoke",
1841            enablers: &["macro-suffix-smoke"],
1842            virtual_package_suffixes: &["/__macro_smoke__"],
1843        }
1844
1845        let plugin = MacroSuffixSmokePlugin;
1846        assert_eq!(
1847            plugin.virtual_package_suffixes(),
1848            &["/__macro_smoke__"],
1849            "macro-declared virtual_package_suffixes must propagate to the trait method"
1850        );
1851    }
1852
1853    #[test]
1854    fn macro_generated_plugin_imports_only_resolve_config() {
1855        let plugin = cypress::CypressPlugin;
1856        let source = r"
1857            import { defineConfig } from 'cypress';
1858            import coveragePlugin from '@cypress/code-coverage';
1859            export default defineConfig({});
1860        ";
1861        let result = plugin.resolve_config(
1862            Path::new("cypress.config.ts"),
1863            source,
1864            Path::new("/project"),
1865        );
1866        assert!(
1867            result
1868                .referenced_dependencies
1869                .contains(&"cypress".to_string())
1870        );
1871        assert!(
1872            result
1873                .referenced_dependencies
1874                .contains(&"@cypress/code-coverage".to_string())
1875        );
1876    }
1877
1878    #[test]
1879    fn builtin_plugin_count_is_expected() {
1880        let plugins = registry::builtin::create_builtin_plugins();
1881        assert!(
1882            plugins.len() >= 110,
1883            "expected at least 110 built-in plugins, got {}",
1884            plugins.len()
1885        );
1886    }
1887}