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