Skip to main content

fallow_core/plugins/registry/
mod.rs

1//! Plugin registry: discovers active plugins, collects patterns, parses configs.
2
3use rustc_hash::{FxHashMap, FxHashSet};
4use std::fmt;
5use std::path::{Path, PathBuf};
6use std::sync::{OnceLock, RwLock};
7
8use fallow_config::{
9    AutoImportRule, EntryPointRole, ExternalPluginDef, JsxImportSourceRule, PackageJson,
10    UsedClassMemberRule,
11};
12
13use crate::scripts;
14
15use super::{PathRule, Plugin, PluginResult, PluginUsedExportRule, ProvidedDependencyRule};
16
17pub(crate) mod builtin;
18mod helpers;
19mod tooling_evidence;
20
21pub(crate) use tooling_evidence::find_config_file;
22
23/// Names of every built-in framework plugin, in registry order.
24///
25/// Derived live from the plugin registry so capability introspection
26/// (`fallow schema`) can list plugins without a hand-maintained mirror.
27#[must_use]
28pub fn builtin_plugin_names() -> Vec<&'static str> {
29    builtin::create_builtin_plugins()
30        .iter()
31        .map(|plugin| plugin.name())
32        .collect()
33}
34
35/// Config file globs that any built-in framework plugin can read, sorted and
36/// without duplicates. A pattern is relative to the directory the plugin
37/// searches, so a caller that matches root-relative paths also tries it
38/// under `**/`.
39#[must_use]
40pub fn builtin_config_patterns() -> Vec<&'static str> {
41    let mut patterns: Vec<&'static str> = builtin::create_builtin_plugins()
42        .iter()
43        .flat_map(|plugin| plugin.config_patterns().iter().copied())
44        .collect();
45    patterns.sort_unstable();
46    patterns.dedup();
47    patterns
48}
49
50/// The config file globs of the named built-in plugins, sorted and without
51/// duplicates. A name that is not a built-in plugin adds no glob. A pattern
52/// is relative to the directory the plugin searches.
53#[must_use]
54pub fn builtin_config_patterns_of(plugin_names: &[String]) -> Vec<&'static str> {
55    let mut patterns: Vec<&'static str> = builtin::create_builtin_plugins()
56        .iter()
57        .filter(|plugin| plugin_names.iter().any(|name| name == plugin.name()))
58        .flat_map(|plugin| plugin.config_patterns().iter().copied())
59        .collect();
60    patterns.sort_unstable();
61    patterns.dedup();
62    patterns
63}
64
65/// The always-used globs of the active built-in plugins, sorted and without
66/// duplicates. Some plugins list their config file here instead of in
67/// `config_patterns`, for example `.vitepress/config.ts`.
68#[must_use]
69pub fn builtin_always_used_patterns_of(plugin_names: &[String]) -> Vec<&'static str> {
70    let mut patterns: Vec<&'static str> = builtin::create_builtin_plugins()
71        .iter()
72        .filter(|plugin| plugin_names.iter().any(|name| name == plugin.name()))
73        .flat_map(|plugin| plugin.always_used().iter().copied())
74        .collect();
75    patterns.sort_unstable();
76    patterns.dedup();
77    patterns
78}
79
80pub use helpers::ConfigCandidateIndex;
81pub use helpers::is_external_plugin_active;
82use helpers::{
83    check_has_config_file, discover_config_files, prepare_config_pattern, process_config_result,
84    process_external_plugins, process_package_json_metadata, process_static_patterns,
85};
86
87fn must_parse_workspace_config_when_root_active(plugin_name: &str) -> bool {
88    matches!(
89        plugin_name,
90        "eslint" | "docusaurus" | "jest" | "storybook" | "tanstack-router" | "vitest"
91    )
92}
93
94fn compile_config_matchers<'a>(
95    active: &[&'a dyn Plugin],
96) -> Vec<(&'a dyn Plugin, Vec<globset::GlobMatcher>)> {
97    active
98        .iter()
99        .filter(|plugin| !plugin.config_patterns().is_empty())
100        .map(|plugin| (*plugin, cached_plugin_config_matchers(*plugin)))
101        .collect()
102}
103
104fn compile_plugin_config_matchers(plugin: &dyn Plugin) -> Vec<globset::GlobMatcher> {
105    plugin
106        .config_patterns()
107        .iter()
108        .filter_map(|pattern| {
109            let prepared = prepare_config_pattern(pattern);
110            globset::Glob::new(&prepared)
111                .ok()
112                .map(|glob| glob.compile_matcher())
113        })
114        .collect()
115}
116
117struct CachedPluginConfigMatchers {
118    patterns: &'static [&'static str],
119    matchers: Vec<globset::GlobMatcher>,
120}
121
122#[derive(Default)]
123struct PluginConfigMatcherCache {
124    by_name: RwLock<FxHashMap<&'static str, Vec<CachedPluginConfigMatchers>>>,
125}
126
127impl PluginConfigMatcherCache {
128    fn get_or_compile(&self, plugin: &dyn Plugin) -> Vec<globset::GlobMatcher> {
129        let patterns = plugin.config_patterns();
130        let cached = self
131            .by_name
132            .read()
133            .unwrap_or_else(std::sync::PoisonError::into_inner)
134            .get(plugin.name())
135            .and_then(|variants| {
136                variants
137                    .iter()
138                    .find(|entry| entry.patterns == patterns)
139                    .map(|entry| entry.matchers.clone())
140            });
141        if let Some(matchers) = cached {
142            return matchers;
143        }
144
145        let matchers = compile_plugin_config_matchers(plugin);
146        {
147            let mut by_name = self
148                .by_name
149                .write()
150                .unwrap_or_else(std::sync::PoisonError::into_inner);
151            let variants = by_name.entry(plugin.name()).or_default();
152            if let Some(entry) = variants.iter().find(|entry| entry.patterns == patterns) {
153                return entry.matchers.clone();
154            }
155            variants.push(CachedPluginConfigMatchers {
156                patterns,
157                matchers: matchers.clone(),
158            });
159            drop(by_name);
160        }
161        matchers
162    }
163}
164
165fn cached_plugin_config_matchers(plugin: &dyn Plugin) -> Vec<globset::GlobMatcher> {
166    static MATCHERS: OnceLock<PluginConfigMatcherCache> = OnceLock::new();
167    MATCHERS
168        .get_or_init(PluginConfigMatcherCache::default)
169        .get_or_compile(plugin)
170}
171
172/// Emit one info-level line naming every active plugin.
173fn log_active_plugins(active: &[&dyn Plugin]) {
174    tracing::info!(
175        plugins = active
176            .iter()
177            .map(|p| p.name())
178            .collect::<Vec<_>>()
179            .join(", "),
180        "active plugins"
181    );
182}
183
184/// Compute `(absolute, root-relative)` file pairs, but only when at least one
185/// active plugin needs config matching or a package.json config key. Returns an
186/// empty vec otherwise to skip the per-file path work.
187fn compute_relative_files(
188    config_matchers: &[(&dyn Plugin, Vec<globset::GlobMatcher>)],
189    active: &[&dyn Plugin],
190    discovered_files: &[PathBuf],
191    root: &Path,
192) -> Vec<(PathBuf, String)> {
193    use rayon::prelude::*;
194    let needs_relative_files =
195        !config_matchers.is_empty() || active.iter().any(|p| p.package_json_config_key().is_some());
196    if !needs_relative_files {
197        return Vec::new();
198    }
199    discovered_files
200        .par_iter()
201        .map(|f| {
202            let rel = f
203                .strip_prefix(root)
204                .unwrap_or(f)
205                .to_string_lossy()
206                .into_owned();
207            (f.clone(), rel)
208        })
209        .collect()
210}
211
212/// Registry of all available plugins (built-in + external).
213pub struct PluginRegistry {
214    plugins: Vec<Box<dyn Plugin>>,
215    external_plugins: Vec<ExternalPluginDef>,
216}
217
218/// Inputs for the workspace-fast plugin path.
219pub(crate) struct WorkspacePluginRunInput<'a> {
220    pub(crate) pkg: &'a PackageJson,
221    pub(crate) root: &'a Path,
222    pub(crate) project_root: &'a Path,
223    pub(crate) precompiled_config_matchers: &'a [(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
224    pub(crate) relative_files: &'a [(PathBuf, String)],
225    pub(crate) skip_config_plugins: &'a FxHashSet<&'a str>,
226    pub(crate) production_mode: bool,
227    pub(crate) candidate_index: Option<&'a ConfigCandidateIndex>,
228}
229
230struct PluginRunContext<'a> {
231    all_deps: Vec<String>,
232    active: Vec<&'a dyn Plugin>,
233}
234
235/// Inputs governing which built-in plugins activate for a project.
236struct PluginActivationInput<'a> {
237    pkg: &'a PackageJson,
238    root: &'a Path,
239    discovered_files: &'a [PathBuf],
240    all_deps: &'a [String],
241    script_packages: &'a FxHashSet<String>,
242    candidate_index: Option<&'a ConfigCandidateIndex>,
243}
244
245/// Invalid user-authored regex extracted from a plugin config file.
246#[derive(Debug, Clone, PartialEq, Eq)]
247pub struct PluginRegexValidationError {
248    plugin_name: String,
249    config_path: Option<PathBuf>,
250    rule_kind: &'static str,
251    field: &'static str,
252    rule_pattern: String,
253    regex_pattern: String,
254    source: String,
255}
256
257impl PluginRegexValidationError {
258    fn new(input: PluginRegexValidationErrorInput<'_>) -> Self {
259        Self {
260            plugin_name: input.plugin_name.to_owned(),
261            config_path: input.config_path.map(Path::to_path_buf),
262            rule_kind: input.rule_kind,
263            field: input.field,
264            rule_pattern: input.rule_pattern.to_owned(),
265            regex_pattern: input.regex_pattern.to_owned(),
266            source: input.source.to_string(),
267        }
268    }
269}
270
271#[derive(Clone, Copy)]
272struct PluginRegexValidationErrorInput<'a> {
273    plugin_name: &'a str,
274    config_path: Option<&'a Path>,
275    rule_kind: &'static str,
276    field: &'static str,
277    rule_pattern: &'a str,
278    regex_pattern: &'a str,
279    source: &'a regex::Error,
280}
281
282impl fmt::Display for PluginRegexValidationError {
283    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
284        let location = self
285            .config_path
286            .as_ref()
287            .map(|path| format!(" in {}", path.display()))
288            .unwrap_or_default();
289        write!(
290            f,
291            "plugin '{}'{}: invalid regex '{}' in {}.{} for path rule '{}': {}",
292            self.plugin_name,
293            location,
294            self.regex_pattern,
295            self.rule_kind,
296            self.field,
297            self.rule_pattern,
298            self.source
299        )
300    }
301}
302
303#[must_use]
304pub(crate) fn format_plugin_regex_errors(errors: &[PluginRegexValidationError]) -> String {
305    let joined = errors
306        .iter()
307        .map(ToString::to_string)
308        .collect::<Vec<_>>()
309        .join("\n  - ");
310    format!(
311        "invalid plugin regex configuration:\n  - {joined}\n\nRewrite the plugin config with Rust-compatible regex syntax, or remove unsupported constructs such as JavaScript lookahead and lookbehind."
312    )
313}
314
315/// The tooling dependencies of one active plugin, plus the evidence that the
316/// project uses the plugin.
317///
318/// The unused devDependency check credits `dependencies` only when the plugin
319/// found a config of its own (`own_config`), or when a package.json script, a
320/// CI workflow or a git hook invokes one of `references`. An active plugin
321/// alone is no evidence: a declared package activates it.
322#[derive(Debug, Clone, Default, PartialEq, Eq)]
323pub struct PluginToolingDependencies {
324    /// The plugin name.
325    pub plugin: String,
326    /// The tooling dependencies the plugin declares.
327    pub dependencies: Vec<String>,
328    /// The package names whose script, CI or hook invocation shows that the
329    /// project runs the plugin's tool: its tooling dependencies and its exact
330    /// enablers.
331    pub references: Vec<String>,
332    /// The config file the plugin found, or the package.json that holds its
333    /// config. Absolute path.
334    pub own_config: Option<PathBuf>,
335}
336
337/// Why a plugin's tooling dependencies are credited.
338#[derive(Debug, Clone, Copy, PartialEq, Eq)]
339pub enum PluginToolingEvidence<'a> {
340    /// The plugin found this config file, or the package.json with its config.
341    OwnConfig(&'a Path),
342    /// A script, CI workflow or git hook invokes this package.
343    Reference(&'a str),
344}
345
346impl PluginToolingDependencies {
347    /// The evidence that the project uses the plugin, given the packages that
348    /// scripts, CI workflows and git hooks invoke. `None` means the plugin's
349    /// tooling dependencies are not credited.
350    #[must_use]
351    pub fn evidence<'a>(
352        &'a self,
353        script_used_packages: &FxHashSet<String>,
354    ) -> Option<PluginToolingEvidence<'a>> {
355        if let Some(config) = &self.own_config {
356            return Some(PluginToolingEvidence::OwnConfig(config));
357        }
358        self.references
359            .iter()
360            .find(|name| script_used_packages.contains(name.as_str()))
361            .map(|name| PluginToolingEvidence::Reference(name))
362    }
363}
364
365/// Aggregated results from all active plugins for a project.
366#[derive(Debug, Clone, Default)]
367pub struct AggregatedPluginResult {
368    /// All entry point patterns from active plugins: (rule, plugin_name).
369    pub entry_patterns: Vec<(PathRule, String)>,
370    /// Plugins whose config already replaced their static entry patterns.
371    /// A later config of a plugin that sets
372    /// `accumulate_config_entry_patterns` adds to the config patterns and does
373    /// not remove them.
374    pub replaced_entry_plugins: FxHashSet<String>,
375    /// The `(plugin, pattern)` pairs that config files added. The first
376    /// replacing config of a plugin that sets
377    /// `accumulate_config_entry_patterns` keeps these patterns.
378    pub config_entry_patterns: FxHashSet<(String, String)>,
379    /// Coverage role for each plugin contributing entry point patterns.
380    pub entry_point_roles: rustc_hash::FxHashMap<String, EntryPointRole>,
381    /// All config file patterns from active plugins.
382    pub config_patterns: Vec<String>,
383    /// All always-used file patterns from active plugins: (pattern, plugin_name).
384    pub always_used: Vec<(String, String)>,
385    /// All used export rules from active plugins.
386    pub used_exports: Vec<PluginUsedExportRule>,
387    /// The config-file export credit of each active plugin: one `default`
388    /// rule for each config pattern minus the plugin's
389    /// `config_default_export_opt_out`, plus the anchored
390    /// `config_file_exports` rules with their own export names, plus the
391    /// entry export credits that config results give. The
392    /// unused-export analysis reads these rules only under
393    /// `includeEntryExports`, so they never change the default output.
394    pub config_export_credits: Vec<PluginUsedExportRule>,
395    /// Class member rules contributed by active plugins that should never be
396    /// flagged as unused. Extends the built-in Angular/React lifecycle allowlist
397    /// with framework-invoked method names, optionally scoped by class heritage.
398    pub used_class_members: Vec<UsedClassMemberRule>,
399    /// Exact framework contracts with plugin and package provenance.
400    pub framework_class_member_contracts: Vec<fallow_types::semantic::SemanticFrameworkContract>,
401    /// Dependencies referenced in config files (should not be flagged unused).
402    pub referenced_dependencies: Vec<String>,
403    /// Dependencies referenced by package.json metadata, scoped to that package.json path.
404    pub package_referenced_dependencies: Vec<(PathBuf, String)>,
405    /// Packages that a config needs installed, with the config location.
406    pub required_dependencies: Vec<super::RequiredDependency>,
407    /// Additional always-used files discovered from config parsing: (pattern, plugin_name).
408    pub discovered_always_used: Vec<(String, String)>,
409    /// Setup files discovered from config parsing: (path, plugin_name).
410    pub setup_files: Vec<(PathBuf, String)>,
411    /// Tooling dependencies of every active plugin, whether or not the plugin
412    /// found evidence that the project uses it. The unlisted-dependency and
413    /// dev-dependency-in-production checks read this list.
414    pub tooling_dependencies: Vec<String>,
415    /// Tooling dependencies grouped by the active plugin that declares them,
416    /// with the evidence that decides whether an unused devDependency check
417    /// credits them. See [`PluginToolingDependencies`].
418    pub plugin_tooling: Vec<PluginToolingDependencies>,
419    /// Package names discovered as used in package.json scripts (binary invocations).
420    pub script_used_packages: FxHashSet<String>,
421    /// The binary names that the declared dependencies provide. Script
422    /// analysis fills it for the root result; workspace results keep the
423    /// default.
424    pub dependency_binaries: crate::scripts::DependencyBinaries,
425    /// The names that the root and workspace manifests declare in
426    /// `devDependencies`. Script analysis fills it for the root result, so
427    /// the trace credits a dependency only where the unused devDependency
428    /// check would.
429    pub dev_dependency_names: FxHashSet<String>,
430    /// Import prefixes for virtual modules provided by active frameworks.
431    /// Imports matching these prefixes should not be flagged as unlisted dependencies.
432    pub virtual_module_prefixes: Vec<String>,
433    /// Package name suffixes that identify virtual or convention-based specifiers.
434    /// Extracted package names ending with any of these suffixes are not flagged as unlisted.
435    pub virtual_package_suffixes: Vec<String>,
436    /// Import suffixes for build-time generated relative imports.
437    /// Unresolved imports ending with these suffixes are suppressed.
438    pub generated_import_patterns: Vec<String>,
439    /// Import prefixes for build-time generated type-only relative imports.
440    /// Unresolved type-only imports starting with these prefixes are suppressed.
441    pub generated_type_import_prefixes: Vec<String>,
442    /// Path alias mappings from active plugins (prefix → replacement directory).
443    /// Used by the resolver to substitute import prefixes before re-resolving.
444    pub path_aliases: Vec<(String, String)>,
445    /// Path alias mappings from the plugins of a workspace package. Each alias
446    /// applies only to the files inside that workspace, so two packages can
447    /// map the same prefix (SvelteKit `$lib`, Nuxt `~/`) to their own
448    /// directories.
449    pub scoped_path_aliases: Vec<fallow_graph::resolve::ScopedPathAlias>,
450    /// Convention-based auto-import rules from active plugins (Nuxt components).
451    /// The resolver matches each file's captured `auto_import_candidates` against
452    /// these and synthesizes a graph edge to the rule's source. See issue #704.
453    pub auto_imports: Vec<AutoImportRule>,
454    /// Names of active plugins.
455    pub active_plugins: Vec<String>,
456    /// Test fixture glob patterns from active plugins: (pattern, plugin_name).
457    pub fixture_patterns: Vec<(String, String)>,
458    /// Absolute directories contributed by plugins that should be searched
459    /// when resolving SCSS/Sass `@import`/`@use` specifiers. Populated from
460    /// Angular's `stylePreprocessorOptions.includePaths` and equivalent
461    /// framework settings. See issue #103.
462    pub scss_include_paths: Vec<PathBuf>,
463    /// Static directory mappings contributed by plugins.
464    pub static_dir_mappings: Vec<(PathBuf, String)>,
465    /// Mounts a framework serves for the whole project, so any HTML document
466    /// reaches them, unlike the tool-scoped mounts above.
467    pub framework_static_dir_mappings: Vec<(PathBuf, String)>,
468    /// File-scoped dependency provider rules from active plugins.
469    pub provided_dependencies: Vec<ProvidedDependencyRule>,
470    /// Advisories about the config files active plugins read. Converted to
471    /// workspace diagnostics once, at the end of the plugin run, where the
472    /// project root is known.
473    pub config_diagnostics: Vec<super::PluginConfigDiagnostic>,
474    /// Where Module Federation configs expose files and declare remote
475    /// aliases, for the trace output.
476    pub federation_sources: Vec<super::FederationSource>,
477    /// JSX import sources that bundler and test configs set, with the files
478    /// each config transforms. The resolver adds the runtime edge to each
479    /// matching module with `jsx_runtime_from_config` set.
480    pub jsx_import_sources: Vec<JsxImportSourceRule>,
481    /// Runtime packages that a JSX transform imports when its config sets no
482    /// import source. The analysis credits a package only when a matching
483    /// module has `jsx_runtime_from_config` set. These rules add no graph
484    /// edge.
485    pub jsx_package_credits: Vec<JsxImportSourceRule>,
486    /// The directories of the tsconfig files that set the JSX runtime of
487    /// TypeScript files, so Vite does not use the default `react` runtime for
488    /// the TypeScript files below them.
489    pub tsconfig_jsx_dirs: Vec<PathBuf>,
490}
491
492/// Append `incoming` string items to `target`, skipping values already present
493/// in `target` or earlier in `incoming`. Matches the deduplication the
494/// workspace merge applied via per-field `seen` sets before #444 centralized
495/// it on [`AggregatedPluginResult::merge_into`].
496fn extend_unique(target: &mut Vec<String>, incoming: Vec<String>) {
497    let mut seen: FxHashSet<String> = target.iter().cloned().collect();
498    for item in incoming {
499        if seen.insert(item.clone()) {
500            target.push(item);
501        }
502    }
503}
504
505/// Append each incoming item that `target` does not hold yet. For the small
506/// lists whose items have no hash.
507fn push_missing<T: PartialEq>(target: &mut Vec<T>, incoming: Vec<T>) {
508    for item in incoming {
509        if !target.contains(&item) {
510            target.push(item);
511        }
512    }
513}
514
515/// Prefix a workspace-relative pattern so it matches from the monorepo root,
516/// unless it is already workspace-prefixed or project-root-relative (leading
517/// `/`, e.g. an angular.json path). Mirrors the pre-#444 inline closure.
518fn prefix_if_needed(pat: &str, ws_prefix: &str) -> String {
519    if pat.starts_with(ws_prefix) || pat.starts_with('/') {
520        pat.to_string()
521    } else {
522        format!("{ws_prefix}/{pat}")
523    }
524}
525
526impl AggregatedPluginResult {
527    /// The entry patterns without exact repeats, in first-seen order.
528    ///
529    /// The project pass, each workspace pass, and each config file of a plugin
530    /// can seed the same rule for the same plugin. A repeat adds no match, so
531    /// the compiled glob set keeps one copy.
532    pub(crate) fn unique_entry_patterns(&self) -> impl Iterator<Item = &(PathRule, String)> {
533        let mut seen: FxHashSet<&(PathRule, String)> = FxHashSet::default();
534        self.entry_patterns
535            .iter()
536            .filter(move |entry| seen.insert(entry))
537    }
538
539    /// Apply a workspace prefix to every path-bearing field in place.
540    ///
541    /// Workspace-package results are collected with patterns relative to the
542    /// package root; to be matchable from the monorepo root they need the
543    /// package's prefix applied. This transform is call-site-specific (it
544    /// depends on `ws_prefix`), so it stays separate from [`Self::merge_into`],
545    /// which is a prefix-agnostic union. The root project's own result is
546    /// never prefixed.
547    ///
548    /// Fields that carry package names, absolute paths, or import-specifier
549    /// boundaries (referenced/tooling deps, setup files, static dir mappings,
550    /// auto-imports, virtual prefixes/suffixes, generated patterns) are left
551    /// untouched, matching the pre-#444 merge loop. `config_diagnostics` is one
552    /// of those: it holds the ABSOLUTE path of the config file a plugin read,
553    /// which needs no prefix to name the right file from the monorepo root.
554    pub(crate) fn apply_workspace_prefix(&mut self, ws_prefix: &str) {
555        for (rule, _) in &mut self.entry_patterns {
556            *rule = rule.prefixed(ws_prefix);
557        }
558        for (pat, _) in &mut self.always_used {
559            *pat = prefix_if_needed(pat, ws_prefix);
560        }
561        for (pat, _) in &mut self.discovered_always_used {
562            *pat = prefix_if_needed(pat, ws_prefix);
563        }
564        for (pat, _) in &mut self.fixture_patterns {
565            *pat = prefix_if_needed(pat, ws_prefix);
566        }
567        for rule in &mut self.used_exports {
568            *rule = rule.prefixed(ws_prefix);
569        }
570        for rule in &mut self.config_export_credits {
571            *rule = rule.prefixed(ws_prefix);
572        }
573        for rule in &mut self.provided_dependencies {
574            *rule = rule.prefixed(ws_prefix);
575        }
576        for source in &mut self.federation_sources {
577            *source = source.prefixed(ws_prefix);
578        }
579        if !ws_prefix.is_empty() {
580            self.scoped_path_aliases
581                .extend(self.path_aliases.drain(..).map(|(prefix, replacement)| {
582                    fallow_graph::resolve::ScopedPathAlias {
583                        scope: ws_prefix.to_string(),
584                        prefix,
585                        replacement: format!("{ws_prefix}/{replacement}"),
586                    }
587                }));
588        }
589    }
590
591    /// Merge `other` into `self`, taking the union of every field.
592    ///
593    /// Exhaustively destructures `Self` so adding a field to
594    /// `AggregatedPluginResult` becomes a `missing field in pattern` compile
595    /// error here instead of a silently-dropped field. See issue #444.
596    ///
597    /// Callers that need the workspace prefix applied must call
598    /// [`Self::apply_workspace_prefix`] on `other` first; this method does not
599    /// transform any path. Dedup-bearing fields (`active_plugins`, the virtual
600    /// prefix/suffix, generated-pattern, and semantic framework-contract lists)
601    /// deduplicate the incoming values against the contents already in `self`,
602    /// matching the pre-#444 `seen`-set behavior. `entry_point_roles` is
603    /// first-writer-wins.
604    pub(crate) fn merge_into(&mut self, other: Self) {
605        let Self {
606            entry_patterns,
607            // Only the config pass of one plugin run reads this field.
608            replaced_entry_plugins: _,
609            config_entry_patterns: _,
610            entry_point_roles,
611            config_patterns,
612            always_used,
613            used_exports,
614            config_export_credits,
615            used_class_members,
616            framework_class_member_contracts,
617            referenced_dependencies,
618            package_referenced_dependencies,
619            required_dependencies,
620            discovered_always_used,
621            setup_files,
622            tooling_dependencies,
623            plugin_tooling,
624            script_used_packages,
625            dependency_binaries: _,
626            dev_dependency_names,
627            virtual_module_prefixes,
628            virtual_package_suffixes,
629            generated_import_patterns,
630            generated_type_import_prefixes,
631            path_aliases,
632            scoped_path_aliases,
633            auto_imports,
634            active_plugins,
635            fixture_patterns,
636            scss_include_paths,
637            static_dir_mappings,
638            framework_static_dir_mappings,
639            provided_dependencies,
640            config_diagnostics,
641            federation_sources,
642            jsx_import_sources,
643            jsx_package_credits,
644            tsconfig_jsx_dirs,
645        } = other;
646
647        self.entry_patterns.extend(entry_patterns);
648        for (plugin_name, role) in entry_point_roles {
649            self.entry_point_roles.entry(plugin_name).or_insert(role);
650        }
651        self.config_patterns.extend(config_patterns);
652        self.always_used.extend(always_used);
653        self.used_exports.extend(used_exports);
654        self.config_export_credits.extend(config_export_credits);
655        self.used_class_members.extend(used_class_members);
656        for contract in framework_class_member_contracts {
657            if !self.framework_class_member_contracts.contains(&contract) {
658                self.framework_class_member_contracts.push(contract);
659            }
660        }
661        self.referenced_dependencies.extend(referenced_dependencies);
662        self.package_referenced_dependencies
663            .extend(package_referenced_dependencies);
664        push_missing(&mut self.required_dependencies, required_dependencies);
665        self.discovered_always_used.extend(discovered_always_used);
666        self.setup_files.extend(setup_files);
667        self.tooling_dependencies.extend(tooling_dependencies);
668        self.plugin_tooling.extend(plugin_tooling);
669        self.dev_dependency_names.extend(dev_dependency_names);
670        self.script_used_packages.extend(script_used_packages);
671        extend_unique(&mut self.virtual_module_prefixes, virtual_module_prefixes);
672        extend_unique(&mut self.virtual_package_suffixes, virtual_package_suffixes);
673        extend_unique(
674            &mut self.generated_import_patterns,
675            generated_import_patterns,
676        );
677        extend_unique(
678            &mut self.generated_type_import_prefixes,
679            generated_type_import_prefixes,
680        );
681        self.path_aliases.extend(path_aliases);
682        self.scoped_path_aliases.extend(scoped_path_aliases);
683        self.auto_imports.extend(auto_imports);
684        extend_unique(&mut self.active_plugins, active_plugins);
685        self.fixture_patterns.extend(fixture_patterns);
686        self.scss_include_paths.extend(scss_include_paths);
687        self.static_dir_mappings.extend(static_dir_mappings);
688        self.framework_static_dir_mappings
689            .extend(framework_static_dir_mappings);
690        self.provided_dependencies.extend(provided_dependencies);
691        self.federation_sources.extend(federation_sources);
692        push_missing(&mut self.jsx_import_sources, jsx_import_sources);
693        push_missing(&mut self.jsx_package_credits, jsx_package_credits);
694        push_missing(&mut self.tsconfig_jsx_dirs, tsconfig_jsx_dirs);
695        push_missing(&mut self.config_diagnostics, config_diagnostics);
696    }
697}
698
699impl PluginRegistry {
700    /// Create a registry with all built-in plugins and optional external plugins.
701    #[must_use]
702    pub fn new(external: Vec<ExternalPluginDef>) -> Self {
703        Self {
704            plugins: builtin::create_builtin_plugins(),
705            external_plugins: external,
706        }
707    }
708
709    /// The preload files of the `bunfig.toml` at `root`, as absolute paths.
710    /// Bun runs them before the tests of each `bun test` run, also when no
711    /// package enables the Bun plugin.
712    #[must_use]
713    pub fn bun_preload_files(root: &Path) -> Vec<PathBuf> {
714        super::bun::preload_files(root)
715    }
716
717    /// Hidden directory names that should be traversed before full plugin execution.
718    ///
719    /// Source discovery runs before plugin config parsing, so this helper only uses
720    /// package-activation checks and static plugin metadata.
721    #[must_use]
722    pub fn discovery_hidden_dirs(&self, pkg: &PackageJson, root: &Path) -> Vec<String> {
723        let all_deps = pkg.all_dependency_names();
724        let mut seen = FxHashSet::default();
725        let mut dirs = Vec::new();
726
727        for plugin in &self.plugins {
728            if !plugin.is_enabled_with_deps(&all_deps, root) {
729                continue;
730            }
731            for dir in plugin.discovery_hidden_dirs() {
732                if seen.insert(*dir) {
733                    dirs.push((*dir).to_string());
734                }
735            }
736        }
737
738        dirs
739    }
740
741    /// Test convenience wrapper for running all plugins against a project.
742    ///
743    /// This discovers which plugins are active, collects their static patterns,
744    /// then parses any config files to extract dynamic information.
745    #[cfg(test)]
746    fn run(
747        &self,
748        pkg: &PackageJson,
749        root: &Path,
750        discovered_files: &[PathBuf],
751    ) -> AggregatedPluginResult {
752        self.try_run(pkg, root, discovered_files)
753            .unwrap_or_else(|errors| panic!("{}", format_plugin_regex_errors(&errors)))
754    }
755
756    /// Run all plugins, returning invalid plugin regexes as hard errors.
757    pub fn try_run(
758        &self,
759        pkg: &PackageJson,
760        root: &Path,
761        discovered_files: &[PathBuf],
762    ) -> Result<AggregatedPluginResult, Vec<PluginRegexValidationError>> {
763        self.try_run_with_search_roots(pkg, root, discovered_files, &[root], false, None)
764    }
765
766    /// Run all plugins against a project with explicit config-file search roots,
767    /// returning invalid plugin regexes as hard errors.
768    #[expect(
769        clippy::too_many_arguments,
770        reason = "public PluginRegistry API; signature is part of the crate surface for embedders"
771    )]
772    pub(crate) fn try_run_with_search_roots(
773        &self,
774        pkg: &PackageJson,
775        root: &Path,
776        discovered_files: &[PathBuf],
777        config_search_roots: &[&Path],
778        production_mode: bool,
779        candidate_index: Option<&ConfigCandidateIndex>,
780    ) -> Result<AggregatedPluginResult, Vec<PluginRegexValidationError>> {
781        let _span = tracing::info_span!("run_plugins").entered();
782        let mut result = AggregatedPluginResult::default();
783        let mut regex_errors = Vec::new();
784
785        let PluginRunContext { all_deps, active } = self.prepare_plugin_run_context(
786            pkg,
787            root,
788            discovered_files,
789            production_mode,
790            candidate_index,
791        );
792
793        self.run_plugin_preflight(&active, &all_deps, root, discovered_files);
794
795        for plugin in &active {
796            process_static_patterns(*plugin, root, &mut result);
797        }
798        process_package_json_metadata(&active, pkg, root, &mut result, &mut regex_errors);
799
800        process_external_plugins(
801            &self.external_plugins,
802            &all_deps,
803            root,
804            discovered_files,
805            &mut result,
806        );
807        tooling_evidence::record_plugin_tooling(
808            &tooling_evidence::ToolingEvidenceInput {
809                active: &active,
810                external_plugins: &self.external_plugins,
811                all_deps: &all_deps,
812                roots: &[root],
813                // Production mode turns the unused devDependency check off, so a
814                // workspace config file credits nothing there and the probe of
815                // every search root is pure cost.
816                extra_roots: if production_mode {
817                    &[]
818                } else {
819                    config_search_roots
820                },
821                candidate_index,
822                discovered_files,
823            },
824            &mut result,
825        );
826
827        let config_matchers = compile_config_matchers(&active);
828        let relative_files =
829            compute_relative_files(&config_matchers, &active, discovered_files, root);
830
831        resolve_plugin_config_files(&mut PluginConfigResolutionInput {
832            config_matchers: &config_matchers,
833            relative_files: &relative_files,
834            config_search_roots,
835            production_mode,
836            candidate_index,
837            root,
838            result: &mut result,
839            regex_errors: &mut regex_errors,
840        });
841
842        process_package_json_inline_configs(
843            &active,
844            &config_matchers,
845            &relative_files,
846            root,
847            &mut result,
848            &mut regex_errors,
849        );
850
851        if regex_errors.is_empty() {
852            Ok(result)
853        } else {
854            Err(regex_errors)
855        }
856    }
857
858    /// Test convenience wrapper for the fast workspace plugin path.
859    ///
860    /// Reuses pre-compiled config matchers and pre-computed relative files from the root
861    /// project run, avoiding repeated glob compilation and path computation per workspace.
862    /// Skips package.json inline config (workspace packages rarely have inline configs).
863    #[cfg(test)]
864    fn run_workspace_fast(&self, input: &WorkspacePluginRunInput<'_>) -> AggregatedPluginResult {
865        self.try_run_workspace_fast(input)
866            .unwrap_or_else(|errors| panic!("{}", format_plugin_regex_errors(&errors)))
867    }
868
869    /// Fast variant of `try_run()` for workspace packages.
870    ///
871    /// Reuses pre-compiled config matchers and pre-computed relative files from the root
872    /// project run, avoiding repeated glob compilation and path computation per workspace.
873    /// Skips package.json inline config (workspace packages rarely have inline configs).
874    pub(crate) fn try_run_workspace_fast(
875        &self,
876        input: &WorkspacePluginRunInput<'_>,
877    ) -> Result<AggregatedPluginResult, Vec<PluginRegexValidationError>> {
878        let _span = tracing::info_span!("run_plugins").entered();
879        let mut result = AggregatedPluginResult::default();
880        let mut regex_errors = Vec::new();
881
882        let all_deps = input.pkg.all_dependency_names();
883        let script_packages =
884            script_activation_packages(input.pkg, input.root, &all_deps, input.production_mode);
885        let workspace_files: Vec<PathBuf> = input
886            .relative_files
887            .iter()
888            .map(|(abs_path, _)| abs_path.clone())
889            .collect();
890
891        let active = self.collect_active_plugins(&PluginActivationInput {
892            pkg: input.pkg,
893            root: input.root,
894            discovered_files: &workspace_files,
895            all_deps: &all_deps,
896            script_packages: &script_packages,
897            candidate_index: input.candidate_index,
898        });
899
900        log_active_plugins(&active);
901
902        self.emit_silent_fail_diagnostics(&active, &all_deps, input.root, &workspace_files);
903
904        process_external_plugins(
905            &self.external_plugins,
906            &all_deps,
907            input.root,
908            &workspace_files,
909            &mut result,
910        );
911
912        if active.is_empty() && result.active_plugins.is_empty() {
913            return Ok(result);
914        }
915
916        process_workspace_active_plugins(&active, input, &mut result, &mut regex_errors);
917        // A config file at the project root applies to a workspace package too.
918        let evidence_roots: &[&Path] = if input.root == input.project_root {
919            &[input.root]
920        } else {
921            &[input.root, input.project_root]
922        };
923        tooling_evidence::record_plugin_tooling(
924            &tooling_evidence::ToolingEvidenceInput {
925                active: &active,
926                external_plugins: &self.external_plugins,
927                all_deps: &all_deps,
928                roots: evidence_roots,
929                extra_roots: &[],
930                candidate_index: input.candidate_index,
931                discovered_files: &workspace_files,
932            },
933            &mut result,
934        );
935        resolve_workspace_plugin_configs(&active, input, &mut result, &mut regex_errors);
936
937        if regex_errors.is_empty() {
938            Ok(result)
939        } else {
940            Err(regex_errors)
941        }
942    }
943
944    /// Pre-compile config pattern glob matchers for all plugins that have config patterns.
945    /// Returns a vec of (plugin, matchers) pairs that can be reused across multiple `run_workspace_fast` calls.
946    #[must_use]
947    pub(crate) fn precompile_config_matchers(
948        &self,
949    ) -> Vec<(&dyn Plugin, Vec<globset::GlobMatcher>)> {
950        self.plugins
951            .iter()
952            .filter(|p| !p.config_patterns().is_empty())
953            .map(|p| (p.as_ref(), cached_plugin_config_matchers(p.as_ref())))
954            .collect()
955    }
956
957    /// Resolve the config files that package scripts pass to a plugin binary
958    /// with `--config` / `-c`.
959    ///
960    /// `package_root` is the directory of the `package.json` that holds the
961    /// scripts, and `ws_prefix` is its path relative to `project_root`
962    /// (empty for the root package). Each file is resolved into its own
963    /// result, so a `test.include` in a script config adds entry patterns
964    /// and does not replace the patterns of the plugin's default config.
965    /// A file in the package root that a `config_patterns()` entry matches is
966    /// skipped, because the normal plugin run resolves it already.
967    pub(crate) fn resolve_script_config_files(
968        &self,
969        config_files: &[scripts::BinaryConfigFile],
970        package_root: &Path,
971        project_root: &Path,
972        ws_prefix: &str,
973    ) -> AggregatedPluginResult {
974        let mut aggregated = AggregatedPluginResult::default();
975        for config_file in config_files {
976            let Some(rel_path) =
977                scripts::normalize_script_entry_pattern(ws_prefix, &config_file.path)
978            else {
979                continue;
980            };
981            let abs_path = package_root.join(config_file.path.trim_start_matches("./"));
982            // The normal plugin run reads a matched config with its own
983            // directory as the directory that the tool runs in. A script runs
984            // the tool in the package root, so a matched config below the
985            // package root is also read here, against the package root.
986            let in_package_root = abs_path.parent() == Some(package_root);
987            for plugin in &self.plugins {
988                let plugin = plugin.as_ref();
989                if !plugin
990                    .script_config_binaries()
991                    .contains(&config_file.binary.as_str())
992                    || (in_package_root
993                        && cached_plugin_config_matchers(plugin)
994                            .iter()
995                            .any(|m| m.is_match(rel_path.as_str())))
996                {
997                    continue;
998                }
999                if !super::config_parser::is_inside_root(&abs_path, project_root) {
1000                    continue;
1001                }
1002                let Ok(source) = std::fs::read_to_string(&abs_path) else {
1003                    continue;
1004                };
1005                let mut file_result = AggregatedPluginResult::default();
1006                file_result
1007                    .entry_point_roles
1008                    .insert(plugin.name().to_string(), plugin.entry_point_role());
1009                let plugin_result =
1010                    plugin.resolve_script_config(&abs_path, &source, package_root, project_root);
1011                if let Err(errors) = process_config_result(
1012                    plugin.name(),
1013                    plugin_result,
1014                    &mut file_result,
1015                    Some(&abs_path),
1016                ) {
1017                    for error in errors {
1018                        tracing::warn!("{error}");
1019                    }
1020                    continue;
1021                }
1022                if !ws_prefix.is_empty() {
1023                    file_result.apply_workspace_prefix(ws_prefix);
1024                }
1025                // The tool loads the config module and reads its default export.
1026                file_result.used_exports.push(PluginUsedExportRule::new(
1027                    plugin.name().to_string(),
1028                    super::UsedExportRule::new(rel_path.clone(), ["default"]),
1029                ));
1030                aggregated.merge_into(file_result);
1031            }
1032        }
1033        aggregated
1034    }
1035}
1036
1037fn process_workspace_active_plugins(
1038    active: &[&dyn Plugin],
1039    input: &WorkspacePluginRunInput<'_>,
1040    result: &mut AggregatedPluginResult,
1041    regex_errors: &mut Vec<PluginRegexValidationError>,
1042) {
1043    for plugin in active {
1044        process_static_patterns(*plugin, input.root, result);
1045    }
1046    process_package_json_metadata(active, input.pkg, input.root, result, regex_errors);
1047}
1048
1049fn resolve_workspace_plugin_configs(
1050    active: &[&dyn Plugin],
1051    input: &WorkspacePluginRunInput<'_>,
1052    result: &mut AggregatedPluginResult,
1053    regex_errors: &mut Vec<PluginRegexValidationError>,
1054) {
1055    let workspace_matchers = select_workspace_matchers(
1056        input.precompiled_config_matchers,
1057        active,
1058        input.skip_config_plugins,
1059    );
1060
1061    let mut resolved_ws_plugins: FxHashSet<&str> = FxHashSet::default();
1062    for (plugin, matchers) in &workspace_matchers {
1063        resolve_plugin_matching_files(&mut PluginMatchingFilesInput {
1064            plugin: *plugin,
1065            matchers,
1066            relative_files: input.relative_files,
1067            root: input.root,
1068            project_root: input.project_root,
1069            result,
1070            regex_errors,
1071            resolved_plugins: &mut resolved_ws_plugins,
1072        });
1073    }
1074
1075    load_workspace_filesystem_configs(&mut WorkspaceFsConfigInput {
1076        workspace_matchers: &workspace_matchers,
1077        resolved_ws_plugins: &resolved_ws_plugins,
1078        root: input.root,
1079        project_root: input.project_root,
1080        production_mode: input.production_mode,
1081        candidate_index: input.candidate_index,
1082        result,
1083        regex_errors,
1084    });
1085}
1086
1087impl Default for PluginRegistry {
1088    fn default() -> Self {
1089        Self::new(vec![])
1090    }
1091}
1092
1093impl PluginRegistry {
1094    fn prepare_plugin_run_context<'a>(
1095        &'a self,
1096        pkg: &PackageJson,
1097        root: &Path,
1098        discovered_files: &[PathBuf],
1099        production_mode: bool,
1100        candidate_index: Option<&ConfigCandidateIndex>,
1101    ) -> PluginRunContext<'a> {
1102        let all_deps = pkg.all_dependency_names();
1103        let script_packages = script_activation_packages(pkg, root, &all_deps, production_mode);
1104        let active = self.collect_active_plugins(&PluginActivationInput {
1105            pkg,
1106            root,
1107            discovered_files,
1108            all_deps: &all_deps,
1109            script_packages: &script_packages,
1110            candidate_index,
1111        });
1112
1113        PluginRunContext { all_deps, active }
1114    }
1115
1116    fn run_plugin_preflight(
1117        &self,
1118        active: &[&dyn Plugin],
1119        all_deps: &[String],
1120        root: &Path,
1121        discovered_files: &[PathBuf],
1122    ) {
1123        log_active_plugins(active);
1124        check_meta_framework_prerequisites(active, root);
1125        self.emit_silent_fail_diagnostics(active, all_deps, root, discovered_files);
1126    }
1127
1128    /// Collect every built-in plugin enabled for this project via files,
1129    /// scripts, or package.json. Shared by the root and workspace-fast paths.
1130    fn collect_active_plugins<'a>(
1131        &'a self,
1132        activation: &PluginActivationInput<'_>,
1133    ) -> Vec<&'a dyn Plugin> {
1134        self.plugins
1135            .iter()
1136            .filter(|p| {
1137                p.is_enabled_with_files(
1138                    activation.all_deps,
1139                    activation.root,
1140                    activation.discovered_files,
1141                    activation.candidate_index,
1142                ) || p.is_enabled_with_scripts(activation.script_packages, activation.root)
1143                    || p.is_enabled_with_package_json(activation.pkg, activation.root)
1144            })
1145            .map(AsRef::as_ref)
1146            .collect()
1147    }
1148
1149    /// Collect the active subset of external plugins, run the silent-fail
1150    /// diagnostics (#479), and emit one `tracing::warn!` per finding (dedup'd
1151    /// across analysis passes via [`plugin_warn_dedupe`]).
1152    ///
1153    /// Called from both `run_with_search_roots` (top-level) and
1154    /// `run_workspace_fast` (per-workspace) so a typo'd enabler or pattern
1155    /// collision surfaces regardless of which entry point dispatched the
1156    /// analysis.
1157    fn emit_silent_fail_diagnostics(
1158        &self,
1159        active: &[&dyn Plugin],
1160        all_deps: &[String],
1161        root: &Path,
1162        discovered_files: &[PathBuf],
1163    ) {
1164        let active_external: Vec<&ExternalPluginDef> = self
1165            .external_plugins
1166            .iter()
1167            .filter(|ext| is_external_plugin_active(ext, all_deps, root, discovered_files))
1168            .collect();
1169        let mut diagnostics = detect_pattern_collisions(active, &active_external);
1170        diagnostics.extend(detect_enabler_typos(&self.external_plugins, all_deps));
1171        emit_plugin_diagnostics(&diagnostics);
1172    }
1173}
1174
1175/// Process-wide dedupe key cache for plugin-system diagnostic warnings.
1176///
1177/// Combined-mode runs `PluginRegistry::run_with_search_roots` three times
1178/// (check + dupes + health) per analysis, so a naive warn would triple-emit
1179/// every diagnostic. Each warn helper builds a unique key, inserts it here,
1180/// and only emits when the key was previously absent.
1181fn plugin_warn_dedupe() -> &'static std::sync::Mutex<FxHashSet<String>> {
1182    static WARNED: std::sync::OnceLock<std::sync::Mutex<FxHashSet<String>>> =
1183        std::sync::OnceLock::new();
1184    WARNED.get_or_init(|| std::sync::Mutex::new(FxHashSet::default()))
1185}
1186
1187struct PluginConfigResolutionInput<'a> {
1188    config_matchers: &'a [(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
1189    relative_files: &'a [(PathBuf, String)],
1190    config_search_roots: &'a [&'a Path],
1191    production_mode: bool,
1192    candidate_index: Option<&'a ConfigCandidateIndex>,
1193    root: &'a Path,
1194    result: &'a mut AggregatedPluginResult,
1195    regex_errors: &'a mut Vec<PluginRegexValidationError>,
1196}
1197
1198/// Filter pre-compiled matchers down to active plugins, keeping a config-skipped
1199/// plugin only when it must still parse its workspace config while root-active.
1200fn select_workspace_matchers<'a>(
1201    precompiled_config_matchers: &[(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
1202    active: &[&dyn Plugin],
1203    skip_config_plugins: &FxHashSet<&str>,
1204) -> Vec<(&'a dyn Plugin, Vec<globset::GlobMatcher>)> {
1205    let active_names: FxHashSet<&str> = active.iter().map(|p| p.name()).collect();
1206    precompiled_config_matchers
1207        .iter()
1208        .filter(|(p, _)| {
1209            active_names.contains(p.name())
1210                && (!skip_config_plugins.contains(p.name())
1211                    || must_parse_workspace_config_when_root_active(p.name()))
1212        })
1213        .map(|(plugin, matchers)| (*plugin, matchers.clone()))
1214        .collect()
1215}
1216
1217struct WorkspaceFsConfigInput<'a> {
1218    workspace_matchers: &'a [(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
1219    resolved_ws_plugins: &'a FxHashSet<&'a str>,
1220    root: &'a Path,
1221    project_root: &'a Path,
1222    production_mode: bool,
1223    candidate_index: Option<&'a ConfigCandidateIndex>,
1224    result: &'a mut AggregatedPluginResult,
1225    regex_errors: &'a mut Vec<PluginRegexValidationError>,
1226}
1227
1228/// Discover and parse workspace config files on disk for plugins not already
1229/// matched against discovered source files (workspace filesystem fallback).
1230fn load_workspace_filesystem_configs(input: &mut WorkspaceFsConfigInput<'_>) {
1231    let search_roots: &[&Path] = if input.root == input.project_root {
1232        &[input.root]
1233    } else {
1234        &[input.root, input.project_root]
1235    };
1236    let ws_json_configs = discover_config_files(
1237        input.workspace_matchers,
1238        input.resolved_ws_plugins,
1239        search_roots,
1240        input.production_mode,
1241        input.candidate_index,
1242    );
1243    for (abs_path, plugin) in &ws_json_configs {
1244        let Ok(source) = std::fs::read_to_string(abs_path) else {
1245            continue;
1246        };
1247        let plugin_result =
1248            plugin.resolve_config_in_project(abs_path, &source, input.root, input.project_root);
1249        if plugin_result.is_empty() {
1250            continue;
1251        }
1252        let rel = abs_path
1253            .strip_prefix(input.project_root)
1254            .map(|p| p.to_string_lossy())
1255            .unwrap_or_default();
1256        tracing::debug!(
1257            plugin = plugin.name(),
1258            config = %rel,
1259            entries = plugin_result.entry_patterns.len(),
1260            deps = plugin_result.referenced_dependencies.len(),
1261            "resolved config (workspace filesystem fallback)"
1262        );
1263        if let Err(mut errors) =
1264            process_config_result(plugin.name(), plugin_result, input.result, Some(abs_path))
1265        {
1266            input.regex_errors.append(&mut errors);
1267        }
1268    }
1269}
1270
1271fn resolve_plugin_config_files(input: &mut PluginConfigResolutionInput<'_>) {
1272    if input.config_matchers.is_empty() {
1273        return;
1274    }
1275
1276    let mut resolved_plugins: FxHashSet<&str> = FxHashSet::default();
1277    for (plugin, matchers) in input.config_matchers {
1278        resolve_plugin_matching_files(&mut PluginMatchingFilesInput {
1279            plugin: *plugin,
1280            matchers,
1281            relative_files: input.relative_files,
1282            root: input.root,
1283            project_root: input.root,
1284            result: input.result,
1285            regex_errors: input.regex_errors,
1286            resolved_plugins: &mut resolved_plugins,
1287        });
1288    }
1289
1290    let json_configs = discover_config_files(
1291        input.config_matchers,
1292        &resolved_plugins,
1293        input.config_search_roots,
1294        input.production_mode,
1295        input.candidate_index,
1296    );
1297    for (abs_path, plugin) in &json_configs {
1298        resolve_plugin_filesystem_config(
1299            *plugin,
1300            abs_path,
1301            input.root,
1302            input.result,
1303            input.regex_errors,
1304        );
1305    }
1306}
1307
1308struct PluginMatchingFilesInput<'plugins, 'data, 'state> {
1309    plugin: &'plugins dyn Plugin,
1310    matchers: &'data [globset::GlobMatcher],
1311    relative_files: &'data [(PathBuf, String)],
1312    root: &'data Path,
1313    project_root: &'data Path,
1314    result: &'state mut AggregatedPluginResult,
1315    regex_errors: &'state mut Vec<PluginRegexValidationError>,
1316    resolved_plugins: &'state mut FxHashSet<&'plugins str>,
1317}
1318
1319fn resolve_plugin_matching_files(input: &mut PluginMatchingFilesInput<'_, '_, '_>) {
1320    use rayon::prelude::*;
1321
1322    let plugin_hits: Vec<&PathBuf> = input
1323        .relative_files
1324        .par_iter()
1325        .filter_map(|(abs_path, rel_path)| {
1326            input
1327                .matchers
1328                .iter()
1329                .any(|m| m.is_match(rel_path.as_str()))
1330                .then_some(abs_path)
1331        })
1332        .collect();
1333    for abs_path in plugin_hits {
1334        let Ok(source) = std::fs::read_to_string(abs_path) else {
1335            continue;
1336        };
1337        let plugin_result = input.plugin.resolve_config_in_project(
1338            abs_path,
1339            &source,
1340            input.root,
1341            input.project_root,
1342        );
1343        if plugin_result.is_empty() {
1344            continue;
1345        }
1346        input.resolved_plugins.insert(input.plugin.name());
1347        process_resolved_plugin_config(ResolvedPluginConfigInput {
1348            plugin: input.plugin,
1349            abs_path,
1350            plugin_result,
1351            result: input.result,
1352            regex_errors: input.regex_errors,
1353            message: "resolved config",
1354            config_display: abs_path.display(),
1355        });
1356    }
1357}
1358
1359fn resolve_plugin_filesystem_config(
1360    plugin: &dyn Plugin,
1361    abs_path: &Path,
1362    root: &Path,
1363    result: &mut AggregatedPluginResult,
1364    regex_errors: &mut Vec<PluginRegexValidationError>,
1365) {
1366    let Ok(source) = std::fs::read_to_string(abs_path) else {
1367        return;
1368    };
1369    let plugin_result = plugin.resolve_config(abs_path, &source, root);
1370    if plugin_result.is_empty() {
1371        return;
1372    }
1373    let rel = abs_path
1374        .strip_prefix(root)
1375        .map(|p| p.to_string_lossy())
1376        .unwrap_or_default();
1377    process_resolved_plugin_config(ResolvedPluginConfigInput {
1378        plugin,
1379        abs_path,
1380        plugin_result,
1381        result,
1382        regex_errors,
1383        message: "resolved config (filesystem fallback)",
1384        config_display: rel,
1385    });
1386}
1387
1388struct ResolvedPluginConfigInput<'a, D> {
1389    plugin: &'a dyn Plugin,
1390    abs_path: &'a Path,
1391    plugin_result: PluginResult,
1392    result: &'a mut AggregatedPluginResult,
1393    regex_errors: &'a mut Vec<PluginRegexValidationError>,
1394    message: &'static str,
1395    config_display: D,
1396}
1397
1398fn process_resolved_plugin_config(input: ResolvedPluginConfigInput<'_, impl std::fmt::Display>) {
1399    tracing::debug!(
1400        plugin = input.plugin.name(),
1401        config = %input.config_display,
1402        entries = input.plugin_result.entry_patterns.len(),
1403        deps = input.plugin_result.referenced_dependencies.len(),
1404        input.message
1405    );
1406    if let Err(mut errors) = process_config_result(
1407        input.plugin.name(),
1408        input.plugin_result,
1409        input.result,
1410        Some(input.abs_path),
1411    ) {
1412        input.regex_errors.append(&mut errors);
1413    }
1414}
1415
1416/// Insert `key` into the dedupe set and return `true` when it was newly
1417/// inserted (caller should emit). Returns `true` on a poisoned mutex so
1418/// over-warning beats swallowing.
1419fn should_warn(key: String) -> bool {
1420    plugin_warn_dedupe()
1421        .lock()
1422        .map_or(true, |mut set| set.insert(key))
1423}
1424
1425/// Structured diagnostic surfaced by the silent-fail plugin checks (#479).
1426///
1427/// Returned by [`detect_pattern_collisions`] and [`detect_enabler_typos`] so
1428/// unit tests can assert on the findings without standing up a tracing
1429/// subscriber. The runtime path calls [`emit_plugin_diagnostics`] to convert
1430/// each variant into one `tracing::warn!` line.
1431#[derive(Debug, Clone, PartialEq, Eq)]
1432enum PluginDiagnostic {
1433    /// Two or more plugins declared an identical `config_patterns` entry.
1434    PatternCollision {
1435        pattern: String,
1436        owners: Vec<String>,
1437    },
1438    /// An external plugin enabler does not match any project dependency, but
1439    /// at least one Levenshtein-close dep name exists.
1440    EnablerTypo {
1441        plugin: String,
1442        enabler: String,
1443        suggestion: String,
1444    },
1445}
1446
1447/// Detect plugins whose `config_patterns` collide byte-for-byte.
1448///
1449/// Detection is byte-equal on the pattern string. Overlapping but non-identical
1450/// globs (e.g. `vite.config.{ts,js}` vs `vite.config.ts`) require pattern
1451/// intersection logic and are intentionally out of scope. The warning's purpose
1452/// is to surface USER-AUTHORED collisions between external plugins or between an
1453/// external plugin and a built-in, so the user can disambiguate by editing one
1454/// side.
1455///
1456/// Built-in-vs-built-in collisions are intentionally NOT reported: they are
1457/// curated and benign (Phase 3a config matching runs every matching plugin's
1458/// `resolve_config` independently, so there is no data loss), and the warning's
1459/// remediation advice ("rename one of the patterns or remove the duplicate
1460/// plugin") is impossible to follow for a built-in. Such a collision exists by
1461/// design, e.g. both `vite` and `tanstack-router` claim
1462/// `vite.config.{ts,js,mts,mjs}` because tanstack-router parses the
1463/// `tanstackRouter({...})` call inside the vite config to find a custom
1464/// `generatedRouteTree` path (#808). A finding is therefore emitted only when
1465/// at least one owner is an external (user-authored) plugin.
1466///
1467/// Precedence rule when two plugins claim the same pattern: the one registered
1468/// first wins. For built-in plugins, registration order is defined in
1469/// [`builtin::create_builtin_plugins`]. External plugins (file-loaded plus
1470/// inline `framework[]`) run AFTER built-ins, so they cannot displace a
1471/// built-in's `resolve_config` result for the same file.
1472fn detect_pattern_collisions(
1473    builtin_active: &[&dyn Plugin],
1474    external_active: &[&ExternalPluginDef],
1475) -> Vec<PluginDiagnostic> {
1476    use rustc_hash::FxHashMap;
1477
1478    let mut pattern_owners: FxHashMap<String, (Vec<String>, FxHashSet<String>)> =
1479        FxHashMap::default();
1480
1481    let record = |pattern_owners: &mut FxHashMap<_, (Vec<String>, FxHashSet<String>)>,
1482                  pattern: String,
1483                  name: String| {
1484        let (list, seen) = pattern_owners.entry(pattern).or_default();
1485        if seen.insert(name.clone()) {
1486            list.push(name);
1487        }
1488    };
1489
1490    for plugin in builtin_active {
1491        for pat in plugin.config_patterns() {
1492            record(
1493                &mut pattern_owners,
1494                (*pat).to_string(),
1495                plugin.name().to_string(),
1496            );
1497        }
1498    }
1499    for ext in external_active {
1500        for pat in &ext.config_patterns {
1501            record(&mut pattern_owners, pat.clone(), ext.name.clone());
1502        }
1503    }
1504
1505    // Names of built-in plugins. Built-in-only collisions are curated + benign
1506    // (every matching plugin runs `resolve_config` independently), so they must
1507    // not surface an un-actionable warning (#808). Keying on the built-in set
1508    // and emitting only when an owner is NOT built-in is robust even if a
1509    // user-authored external plugin happens to share a built-in's name: the
1510    // built-in owner alone never re-enables the warning.
1511    let builtin_names: FxHashSet<&str> = builtin_active.iter().map(|p| p.name()).collect();
1512
1513    let mut findings: Vec<PluginDiagnostic> = pattern_owners
1514        .into_iter()
1515        .filter_map(|(pattern, (owners, _seen))| {
1516            if owners.len() < 2 || owners.iter().all(|o| builtin_names.contains(o.as_str())) {
1517                None
1518            } else {
1519                Some(PluginDiagnostic::PatternCollision { pattern, owners })
1520            }
1521        })
1522        .collect();
1523    findings.sort_unstable_by(|a, b| match (a, b) {
1524        (
1525            PluginDiagnostic::PatternCollision { pattern: ap, .. },
1526            PluginDiagnostic::PatternCollision { pattern: bp, .. },
1527        ) => ap.cmp(bp),
1528        _ => std::cmp::Ordering::Equal,
1529    });
1530    findings
1531}
1532
1533/// Detect external plugins whose enablers do not match any project dependency
1534/// AND at least one enabler is a plausible typo of a real dep.
1535///
1536/// Scope:
1537/// - Only external plugins (file-loaded plus inline `framework[]`). Built-in
1538///   plugins' enablers are hard-coded so cannot be misspelled.
1539/// - Skip plugins with a `detection` block: detection is the rich-logic path
1540///   and false negatives there are not enabler typos.
1541/// - Skip plugins with empty `enablers` (no signal to validate against).
1542/// - Stay silent when no Levenshtein-close dep exists: the plugin may
1543///   legitimately not apply to this project.
1544///
1545/// Matches the established #467 / #510 pattern: tracing-warn with a `did you
1546/// mean` suggestion at the call site. No exit non-zero, no new CLI flag.
1547fn detect_enabler_typos(
1548    external_plugins: &[ExternalPluginDef],
1549    all_deps: &[String],
1550) -> Vec<PluginDiagnostic> {
1551    let mut findings = Vec::new();
1552
1553    for ext in external_plugins {
1554        if ext.detection.is_some() || ext.enablers.is_empty() {
1555            continue;
1556        }
1557
1558        let any_match = ext.enablers.iter().any(|enabler| {
1559            if enabler.ends_with('/') {
1560                all_deps.iter().any(|d| d.starts_with(enabler))
1561            } else {
1562                all_deps.iter().any(|d| d == enabler)
1563            }
1564        });
1565        if any_match {
1566            continue;
1567        }
1568
1569        for enabler in &ext.enablers {
1570            let candidates = all_deps.iter().map(String::as_str);
1571            let Some(suggestion) = fallow_config::levenshtein::closest_match(enabler, candidates)
1572            else {
1573                continue;
1574            };
1575
1576            findings.push(PluginDiagnostic::EnablerTypo {
1577                plugin: ext.name.clone(),
1578                enabler: enabler.clone(),
1579                suggestion: suggestion.to_string(),
1580            });
1581        }
1582    }
1583
1584    findings
1585}
1586
1587/// Emit one `tracing::warn!` per finding, dedup'd against the process-wide
1588/// `plugin_warn_dedupe` set so combined-mode does not triple-warn.
1589fn emit_plugin_diagnostics(findings: &[PluginDiagnostic]) {
1590    for finding in findings {
1591        match finding {
1592            PluginDiagnostic::PatternCollision { pattern, owners } => {
1593                let key = format!("collision::{pattern}::{owners:?}");
1594                if !should_warn(key) {
1595                    continue;
1596                }
1597                let winner = &owners[0];
1598                let others = owners[1..].join(", ");
1599                tracing::warn!(
1600                    "plugin config_patterns collision: identical pattern \
1601                     '{pattern}' is claimed by plugins [{joined}]; '{winner}' \
1602                     runs first (registration order), others ({others}) \
1603                     follow. Rename one of the patterns or remove the \
1604                     duplicate plugin to make resolution explicit. A future \
1605                     release may reject identical-pattern collisions.",
1606                    joined = owners.join(", "),
1607                );
1608            }
1609            PluginDiagnostic::EnablerTypo {
1610                plugin,
1611                enabler,
1612                suggestion,
1613            } => {
1614                let key = format!("enabler::{plugin}::{enabler}");
1615                if !should_warn(key) {
1616                    continue;
1617                }
1618                tracing::warn!(
1619                    "plugin '{plugin}' enabler '{enabler}' does not match any \
1620                     dependency in package.json; did you mean '{suggestion}'? \
1621                     The plugin will not activate. A future release may reject \
1622                     unmatched enablers.",
1623                );
1624            }
1625        }
1626    }
1627}
1628
1629/// Phase 4 of `PluginRegistry::run_with_search_roots`: for any active plugin
1630/// that supports inline package.json configuration via
1631/// [`Plugin::package_json_config_key`], read the root `package.json`, extract
1632/// the relevant key, and feed the result through `resolve_config`.
1633fn process_package_json_inline_configs(
1634    active: &[&dyn Plugin],
1635    config_matchers: &[(&dyn Plugin, Vec<globset::GlobMatcher>)],
1636    relative_files: &[(PathBuf, String)],
1637    root: &Path,
1638    result: &mut AggregatedPluginResult,
1639    regex_errors: &mut Vec<PluginRegexValidationError>,
1640) {
1641    for plugin in active {
1642        let Some(key) = plugin.package_json_config_key() else {
1643            continue;
1644        };
1645        if check_has_config_file(*plugin, config_matchers, relative_files) {
1646            continue;
1647        }
1648        let pkg_path = root.join("package.json");
1649        let Ok(content) = std::fs::read_to_string(&pkg_path) else {
1650            continue;
1651        };
1652        let Ok(json) = serde_json::from_str::<serde_json::Value>(&content) else {
1653            continue;
1654        };
1655        let Some(config_value) = json.get(key) else {
1656            continue;
1657        };
1658        let config_json = serde_json::to_string(config_value).unwrap_or_default();
1659        let fake_path = root.join(format!("{key}.config.json"));
1660        let plugin_result = plugin.resolve_config(&fake_path, &config_json, root);
1661        if plugin_result.is_empty() {
1662            continue;
1663        }
1664        tracing::debug!(
1665            plugin = plugin.name(),
1666            key = key,
1667            "resolved inline package.json config"
1668        );
1669        if let Err(mut errors) =
1670            process_config_result(plugin.name(), plugin_result, result, Some(&pkg_path))
1671        {
1672            regex_errors.append(&mut errors);
1673        }
1674    }
1675}
1676
1677/// A missing meta-framework prerequisite: the per-process dedupe key and the
1678/// warning message to emit.
1679#[derive(Debug)]
1680struct MetaFrameworkWarning {
1681    dedupe_key: &'static str,
1682    message: &'static str,
1683}
1684
1685/// Pure detection: which active meta-frameworks are missing their generated
1686/// config/types directory under `root`. Separated from emission so the
1687/// detection logic is unit-testable without a tracing subscriber or the
1688/// process-wide dedupe set.
1689///
1690/// When adding a framework here, also extend `MATERIALIZED_CONTEXT_DIRS` in
1691/// `fallow-cli`'s `audit.rs` with its generated dir, otherwise `fallow audit`'s
1692/// base worktree will not symlink that dir and the broken-tsconfig-chain bug
1693/// resurfaces on the base pass for the new framework.
1694fn missing_meta_framework_prerequisites(
1695    active_plugins: &[&dyn Plugin],
1696    root: &Path,
1697) -> Vec<MetaFrameworkWarning> {
1698    active_plugins
1699        .iter()
1700        .filter_map(|plugin| match plugin.name() {
1701            "nuxt" if !root.join(".nuxt/tsconfig.json").exists() => Some(MetaFrameworkWarning {
1702                dedupe_key: "meta-prereq::nuxt",
1703                message: "Nuxt project missing .nuxt/tsconfig.json: run `nuxt prepare` \
1704                          before fallow for accurate analysis",
1705            }),
1706            "astro" if !root.join(".astro").exists() => Some(MetaFrameworkWarning {
1707                dedupe_key: "meta-prereq::astro",
1708                message: "Astro project missing .astro/ types: run `astro sync` \
1709                          before fallow for accurate analysis",
1710            }),
1711            _ => None,
1712        })
1713        .collect()
1714}
1715
1716/// Warn when meta-frameworks are active but their generated configs are missing.
1717///
1718/// Meta-frameworks like Nuxt and Astro generate tsconfig/types files during a
1719/// "prepare" step. Without these, the tsconfig extends chain breaks and
1720/// extensionless imports fail wholesale (e.g. 2000+ unresolved imports).
1721///
1722/// Deduped per framework so combined-mode (check + dupes + health through one
1723/// loader) does not re-warn. The advice is generic and does not name the root,
1724/// so one line per process per framework is the right bound (issue #637).
1725fn check_meta_framework_prerequisites(active_plugins: &[&dyn Plugin], root: &Path) {
1726    for warning in missing_meta_framework_prerequisites(active_plugins, root) {
1727        if should_warn(warning.dedupe_key.to_owned()) {
1728            tracing::warn!("{}", warning.message);
1729        }
1730    }
1731}
1732
1733fn script_activation_packages(
1734    pkg: &PackageJson,
1735    root: &Path,
1736    all_deps: &[String],
1737    production_mode: bool,
1738) -> FxHashSet<String> {
1739    let Some(pkg_scripts) = pkg.scripts.as_ref() else {
1740        return FxHashSet::default();
1741    };
1742
1743    let scripts_to_analyze = if production_mode {
1744        scripts::filter_production_scripts(pkg_scripts)
1745    } else {
1746        pkg_scripts.clone()
1747    };
1748
1749    let mut nm_roots = Vec::new();
1750    if root.join("node_modules").is_dir() {
1751        nm_roots.push(root);
1752    }
1753    let bin_map = scripts::build_bin_to_package_map(&nm_roots, all_deps);
1754    let dep_set: FxHashSet<String> = all_deps.iter().cloned().collect();
1755    let catalog =
1756        scripts::ScriptCatalog::from_scripts_with_bodies(pkg_scripts, &scripts_to_analyze);
1757
1758    scripts::analyze_scripts_with_dependency_context(
1759        &scripts_to_analyze,
1760        root,
1761        &bin_map,
1762        &dep_set,
1763        &catalog,
1764        scripts::IgnoredCommandEntries::NONE,
1765    )
1766    .used_packages
1767}
1768
1769#[cfg(test)]
1770mod entry_pattern_tests;
1771#[cfg(test)]
1772mod tests;