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