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