1use 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;
20mod virtual_module;
21
22pub(crate) use tooling_evidence::find_config_file;
23pub(crate) use virtual_module::module_specifiers;
24pub use virtual_module::{VirtualModuleMatch, VirtualModuleProviderRule};
25
26#[must_use]
31pub fn builtin_plugin_names() -> Vec<&'static str> {
32 builtin::create_builtin_plugins()
33 .iter()
34 .map(|plugin| plugin.name())
35 .collect()
36}
37
38#[must_use]
43pub fn builtin_config_patterns() -> Vec<&'static str> {
44 let mut patterns: Vec<&'static str> = builtin::create_builtin_plugins()
45 .iter()
46 .flat_map(|plugin| plugin.config_patterns().iter().copied())
47 .collect();
48 patterns.sort_unstable();
49 patterns.dedup();
50 patterns
51}
52
53#[must_use]
57pub fn builtin_config_patterns_of(plugin_names: &[String]) -> Vec<&'static str> {
58 let mut patterns: Vec<&'static str> = builtin::create_builtin_plugins()
59 .iter()
60 .filter(|plugin| plugin_names.iter().any(|name| name == plugin.name()))
61 .flat_map(|plugin| plugin.config_patterns().iter().copied())
62 .collect();
63 patterns.sort_unstable();
64 patterns.dedup();
65 patterns
66}
67
68#[must_use]
73pub fn builtin_config_lookup(
74 plugin_name: &str,
75) -> Option<(&'static [&'static str], &'static [&'static str])> {
76 builtin::create_builtin_plugins()
77 .iter()
78 .find(|plugin| plugin.name() == plugin_name)
79 .map(|plugin| (plugin.config_patterns(), plugin.script_config_binaries()))
80}
81
82#[must_use]
86pub fn builtin_always_used_patterns_of(plugin_names: &[String]) -> Vec<&'static str> {
87 let mut patterns: Vec<&'static str> = builtin::create_builtin_plugins()
88 .iter()
89 .filter(|plugin| plugin_names.iter().any(|name| name == plugin.name()))
90 .flat_map(|plugin| plugin.always_used().iter().copied())
91 .collect();
92 patterns.sort_unstable();
93 patterns.dedup();
94 patterns
95}
96
97pub use helpers::ConfigCandidateIndex;
98pub use helpers::is_external_plugin_active;
99use helpers::{
100 check_has_config_file, discover_config_files, prepare_config_pattern, process_config_result,
101 process_external_plugins, process_package_json_metadata, process_static_patterns,
102};
103
104fn must_parse_workspace_config_when_root_active(plugin_name: &str) -> bool {
105 matches!(
106 plugin_name,
107 "eslint" | "docusaurus" | "jest" | "storybook" | "tanstack-router" | "vitest"
108 )
109}
110
111fn compile_config_matchers<'a>(
112 active: &[&'a dyn Plugin],
113) -> Vec<(&'a dyn Plugin, Vec<globset::GlobMatcher>)> {
114 active
115 .iter()
116 .filter(|plugin| !plugin.config_patterns().is_empty())
117 .map(|plugin| (*plugin, cached_plugin_config_matchers(*plugin)))
118 .collect()
119}
120
121fn compile_plugin_config_matchers(plugin: &dyn Plugin) -> Vec<globset::GlobMatcher> {
122 plugin
123 .config_patterns()
124 .iter()
125 .filter_map(|pattern| {
126 let prepared = prepare_config_pattern(pattern);
127 globset::Glob::new(&prepared)
128 .ok()
129 .map(|glob| glob.compile_matcher())
130 })
131 .collect()
132}
133
134struct CachedPluginConfigMatchers {
135 patterns: &'static [&'static str],
136 matchers: Vec<globset::GlobMatcher>,
137}
138
139#[derive(Default)]
140struct PluginConfigMatcherCache {
141 by_name: RwLock<FxHashMap<&'static str, Vec<CachedPluginConfigMatchers>>>,
142}
143
144impl PluginConfigMatcherCache {
145 fn get_or_compile(&self, plugin: &dyn Plugin) -> Vec<globset::GlobMatcher> {
146 let patterns = plugin.config_patterns();
147 let cached = self
148 .by_name
149 .read()
150 .unwrap_or_else(std::sync::PoisonError::into_inner)
151 .get(plugin.name())
152 .and_then(|variants| {
153 variants
154 .iter()
155 .find(|entry| entry.patterns == patterns)
156 .map(|entry| entry.matchers.clone())
157 });
158 if let Some(matchers) = cached {
159 return matchers;
160 }
161
162 let matchers = compile_plugin_config_matchers(plugin);
163 {
164 let mut by_name = self
165 .by_name
166 .write()
167 .unwrap_or_else(std::sync::PoisonError::into_inner);
168 let variants = by_name.entry(plugin.name()).or_default();
169 if let Some(entry) = variants.iter().find(|entry| entry.patterns == patterns) {
170 return entry.matchers.clone();
171 }
172 variants.push(CachedPluginConfigMatchers {
173 patterns,
174 matchers: matchers.clone(),
175 });
176 drop(by_name);
177 }
178 matchers
179 }
180}
181
182fn cached_plugin_config_matchers(plugin: &dyn Plugin) -> Vec<globset::GlobMatcher> {
183 static MATCHERS: OnceLock<PluginConfigMatcherCache> = OnceLock::new();
184 MATCHERS
185 .get_or_init(PluginConfigMatcherCache::default)
186 .get_or_compile(plugin)
187}
188
189fn log_active_plugins(active: &[&dyn Plugin]) {
191 tracing::info!(
192 plugins = active
193 .iter()
194 .map(|p| p.name())
195 .collect::<Vec<_>>()
196 .join(", "),
197 "active plugins"
198 );
199}
200
201fn compute_relative_files(
205 config_matchers: &[(&dyn Plugin, Vec<globset::GlobMatcher>)],
206 active: &[&dyn Plugin],
207 discovered_files: &[PathBuf],
208 root: &Path,
209) -> Vec<(PathBuf, String)> {
210 use rayon::prelude::*;
211 let needs_relative_files =
212 !config_matchers.is_empty() || active.iter().any(|p| p.package_json_config_key().is_some());
213 if !needs_relative_files {
214 return Vec::new();
215 }
216 discovered_files
217 .par_iter()
218 .map(|f| {
219 let rel = f
220 .strip_prefix(root)
221 .unwrap_or(f)
222 .to_string_lossy()
223 .into_owned();
224 (f.clone(), rel)
225 })
226 .collect()
227}
228
229pub struct PluginRegistry {
231 plugins: Vec<Box<dyn Plugin>>,
232 external_plugins: Vec<ExternalPluginDef>,
233}
234
235pub(crate) struct RootPluginContext<'a> {
237 pub(crate) active_plugins: FxHashSet<&'a str>,
239 pub(crate) dependencies: Vec<String>,
241}
242
243impl<'a> RootPluginContext<'a> {
244 pub(crate) fn new(root_pkg: Option<&PackageJson>, active_plugins: &'a [String]) -> Self {
245 Self {
246 active_plugins: active_plugins.iter().map(String::as_str).collect(),
247 dependencies: root_pkg.map_or_else(Vec::new, PackageJson::all_dependency_names),
248 }
249 }
250}
251
252pub(crate) struct WorkspacePluginRunInput<'a> {
254 pub(crate) pkg: &'a PackageJson,
255 pub(crate) root: &'a Path,
256 pub(crate) project_root: &'a Path,
257 pub(crate) root_dependencies: &'a [String],
261 pub(crate) precompiled_config_matchers: &'a [(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
262 pub(crate) relative_files: &'a [(PathBuf, String)],
263 pub(crate) skip_config_plugins: &'a FxHashSet<&'a str>,
264 pub(crate) production_mode: bool,
265 pub(crate) candidate_index: Option<&'a ConfigCandidateIndex>,
266}
267
268struct PluginRunContext<'a> {
269 all_deps: Vec<String>,
270 active: Vec<&'a dyn Plugin>,
271}
272
273struct PluginActivationInput<'a> {
275 pkg: &'a PackageJson,
276 root: &'a Path,
277 discovered_files: &'a [PathBuf],
278 all_deps: &'a [String],
279 script_packages: &'a FxHashSet<String>,
280 candidate_index: Option<&'a ConfigCandidateIndex>,
281}
282
283#[derive(Debug, Clone, PartialEq, Eq)]
285pub struct PluginRegexValidationError {
286 plugin_name: String,
287 config_path: Option<PathBuf>,
288 rule_kind: &'static str,
289 field: &'static str,
290 rule_pattern: String,
291 regex_pattern: String,
292 source: String,
293}
294
295impl PluginRegexValidationError {
296 fn new(input: PluginRegexValidationErrorInput<'_>) -> Self {
297 Self {
298 plugin_name: input.plugin_name.to_owned(),
299 config_path: input.config_path.map(Path::to_path_buf),
300 rule_kind: input.rule_kind,
301 field: input.field,
302 rule_pattern: input.rule_pattern.to_owned(),
303 regex_pattern: input.regex_pattern.to_owned(),
304 source: input.source.to_string(),
305 }
306 }
307}
308
309#[derive(Clone, Copy)]
310struct PluginRegexValidationErrorInput<'a> {
311 plugin_name: &'a str,
312 config_path: Option<&'a Path>,
313 rule_kind: &'static str,
314 field: &'static str,
315 rule_pattern: &'a str,
316 regex_pattern: &'a str,
317 source: &'a regex::Error,
318}
319
320impl fmt::Display for PluginRegexValidationError {
321 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
322 let location = self
323 .config_path
324 .as_ref()
325 .map(|path| format!(" in {}", path.display()))
326 .unwrap_or_default();
327 write!(
328 f,
329 "plugin '{}'{}: invalid regex '{}' in {}.{} for path rule '{}': {}",
330 self.plugin_name,
331 location,
332 self.regex_pattern,
333 self.rule_kind,
334 self.field,
335 self.rule_pattern,
336 self.source
337 )
338 }
339}
340
341#[must_use]
342pub(crate) fn format_plugin_regex_errors(errors: &[PluginRegexValidationError]) -> String {
343 let joined = errors
344 .iter()
345 .map(ToString::to_string)
346 .collect::<Vec<_>>()
347 .join("\n - ");
348 format!(
349 "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."
350 )
351}
352
353#[derive(Debug, Clone, Default, PartialEq, Eq)]
361pub struct PluginToolingDependencies {
362 pub plugin: String,
364 pub dependencies: Vec<String>,
366 pub references: Vec<String>,
370 pub own_config: Option<PathBuf>,
373}
374
375#[derive(Debug, Clone, Copy, PartialEq, Eq)]
377pub enum PluginToolingEvidence<'a> {
378 OwnConfig(&'a Path),
380 Reference(&'a str),
382}
383
384impl PluginToolingDependencies {
385 #[must_use]
389 pub fn evidence<'a>(
390 &'a self,
391 script_used_packages: &FxHashSet<String>,
392 ) -> Option<PluginToolingEvidence<'a>> {
393 if let Some(config) = &self.own_config {
394 return Some(PluginToolingEvidence::OwnConfig(config));
395 }
396 self.references
397 .iter()
398 .find(|name| script_used_packages.contains(name.as_str()))
399 .map(|name| PluginToolingEvidence::Reference(name))
400 }
401}
402
403#[derive(Debug, Clone, PartialEq, Eq)]
405pub struct CheckedAliasPrefix {
406 pub scope: String,
410 pub prefix: String,
412}
413
414impl CheckedAliasPrefix {
415 #[must_use]
417 pub fn covers(&self, root: &Path, from_file: &Path, specifier: &str) -> bool {
418 specifier.starts_with(&self.prefix)
419 && (self.scope.is_empty() || from_file.starts_with(root.join(&self.scope)))
420 }
421}
422
423#[derive(Debug, Clone, Default)]
425pub struct AggregatedPluginResult {
426 pub entry_patterns: Vec<(PathRule, String)>,
428 pub replaced_entry_plugins: FxHashSet<String>,
433 pub config_entry_patterns: FxHashSet<(String, String)>,
437 pub entry_point_roles: rustc_hash::FxHashMap<String, EntryPointRole>,
439 pub config_patterns: Vec<String>,
441 pub always_used: Vec<(String, String)>,
443 pub used_exports: Vec<PluginUsedExportRule>,
445 pub config_export_credits: Vec<PluginUsedExportRule>,
453 pub used_class_members: Vec<UsedClassMemberRule>,
457 pub framework_class_member_contracts: Vec<fallow_types::semantic::SemanticFrameworkContract>,
459 pub referenced_dependencies: Vec<String>,
461 pub package_referenced_dependencies: Vec<(PathBuf, String)>,
463 pub required_dependencies: Vec<super::RequiredDependency>,
465 pub discovered_always_used: Vec<(String, String)>,
467 pub setup_files: Vec<(PathBuf, String)>,
469 pub tooling_dependencies: Vec<String>,
473 pub plugin_tooling: Vec<PluginToolingDependencies>,
477 pub script_used_packages: FxHashSet<String>,
479 pub dependency_binaries: crate::scripts::DependencyBinaries,
483 pub dev_dependency_names: FxHashSet<String>,
488 pub virtual_module_prefixes: Vec<String>,
491 pub virtual_package_suffixes: Vec<String>,
494 pub generated_import_patterns: Vec<String>,
497 pub generated_type_import_prefixes: Vec<String>,
500 pub virtual_module_providers: Vec<VirtualModuleProviderRule>,
505 pub path_aliases: Vec<(String, String)>,
508 pub scoped_path_aliases: Vec<fallow_graph::resolve::ScopedPathAlias>,
513 pub checked_alias_prefixes: Vec<CheckedAliasPrefix>,
517 pub auto_imports: Vec<AutoImportRule>,
521 pub active_plugins: Vec<String>,
523 pub active_plugin_scopes: Vec<(String, String)>,
527 pub fixture_patterns: Vec<(String, String)>,
529 pub scss_include_paths: Vec<PathBuf>,
534 pub static_dir_mappings: Vec<(PathBuf, String)>,
536 pub framework_static_dir_mappings: Vec<(PathBuf, String)>,
539 pub provided_dependencies: Vec<ProvidedDependencyRule>,
541 pub config_diagnostics: Vec<super::PluginConfigDiagnostic>,
545 pub federation_sources: Vec<super::FederationSource>,
548 pub jsx_import_sources: Vec<JsxImportSourceRule>,
552 pub jsx_package_credits: Vec<JsxImportSourceRule>,
557 pub tsconfig_jsx_dirs: Vec<TsconfigJsxDir>,
560}
561
562#[derive(Debug, Clone, PartialEq, Eq)]
565pub struct TsconfigJsxDir {
566 pub dir: PathBuf,
568 pub automatic_react: bool,
573}
574
575fn extend_unique(target: &mut Vec<String>, incoming: Vec<String>) {
580 let mut seen: FxHashSet<String> = target.iter().cloned().collect();
581 for item in incoming {
582 if seen.insert(item.clone()) {
583 target.push(item);
584 }
585 }
586}
587
588fn push_missing<T: PartialEq>(target: &mut Vec<T>, incoming: Vec<T>) {
591 for item in incoming {
592 if !target.contains(&item) {
593 target.push(item);
594 }
595 }
596}
597
598fn prefix_if_needed(pat: &str, ws_prefix: &str) -> String {
602 if pat.starts_with(ws_prefix) || pat.starts_with('/') {
603 pat.to_string()
604 } else {
605 format!("{ws_prefix}/{pat}")
606 }
607}
608
609impl AggregatedPluginResult {
610 pub(crate) fn unique_entry_patterns(&self) -> impl Iterator<Item = &(PathRule, String)> {
616 let mut seen: FxHashSet<&(PathRule, String)> = FxHashSet::default();
617 self.entry_patterns
618 .iter()
619 .filter(move |entry| seen.insert(entry))
620 }
621
622 pub(crate) fn apply_workspace_prefix(&mut self, ws_prefix: &str) {
638 for (rule, _) in &mut self.entry_patterns {
639 *rule = rule.prefixed(ws_prefix);
640 }
641 for (pat, _) in &mut self.always_used {
642 *pat = prefix_if_needed(pat, ws_prefix);
643 }
644 for (pat, _) in &mut self.discovered_always_used {
645 *pat = prefix_if_needed(pat, ws_prefix);
646 }
647 for (pat, _) in &mut self.fixture_patterns {
648 *pat = prefix_if_needed(pat, ws_prefix);
649 }
650 for rule in &mut self.used_exports {
651 *rule = rule.prefixed(ws_prefix);
652 }
653 for (_, scope) in &mut self.active_plugin_scopes {
654 *scope = ws_prefix.to_string();
655 }
656 for rule in &mut self.virtual_module_providers {
657 rule.scope = ws_prefix.to_string();
658 }
659 for rule in &mut self.config_export_credits {
660 *rule = rule.prefixed(ws_prefix);
661 }
662 for rule in &mut self.provided_dependencies {
663 *rule = rule.prefixed(ws_prefix);
664 }
665 for source in &mut self.federation_sources {
666 *source = source.prefixed(ws_prefix);
667 }
668 if !ws_prefix.is_empty() {
669 for checked in &mut self.checked_alias_prefixes {
670 checked.scope = ws_prefix.to_string();
671 }
672 self.scoped_path_aliases
673 .extend(self.path_aliases.drain(..).map(|(prefix, replacement)| {
674 fallow_graph::resolve::ScopedPathAlias {
675 scope: ws_prefix.to_string(),
676 prefix,
677 replacement: format!("{ws_prefix}/{replacement}"),
678 }
679 }));
680 }
681 }
682
683 pub(crate) fn merge_into(&mut self, other: Self) {
697 let Self {
698 entry_patterns,
699 replaced_entry_plugins: _,
701 config_entry_patterns: _,
702 entry_point_roles,
703 config_patterns,
704 always_used,
705 used_exports,
706 config_export_credits,
707 used_class_members,
708 framework_class_member_contracts,
709 referenced_dependencies,
710 package_referenced_dependencies,
711 required_dependencies,
712 discovered_always_used,
713 setup_files,
714 tooling_dependencies,
715 plugin_tooling,
716 script_used_packages,
717 dependency_binaries: _,
718 dev_dependency_names,
719 virtual_module_prefixes,
720 virtual_package_suffixes,
721 generated_import_patterns,
722 generated_type_import_prefixes,
723 virtual_module_providers,
724 path_aliases,
725 scoped_path_aliases,
726 checked_alias_prefixes,
727 auto_imports,
728 active_plugins,
729 active_plugin_scopes,
730 fixture_patterns,
731 scss_include_paths,
732 static_dir_mappings,
733 framework_static_dir_mappings,
734 provided_dependencies,
735 config_diagnostics,
736 federation_sources,
737 jsx_import_sources,
738 jsx_package_credits,
739 tsconfig_jsx_dirs,
740 } = other;
741
742 self.entry_patterns.extend(entry_patterns);
743 for (plugin_name, role) in entry_point_roles {
744 self.entry_point_roles.entry(plugin_name).or_insert(role);
745 }
746 self.config_patterns.extend(config_patterns);
747 self.always_used.extend(always_used);
748 self.used_exports.extend(used_exports);
749 self.config_export_credits.extend(config_export_credits);
750 self.used_class_members.extend(used_class_members);
751 for contract in framework_class_member_contracts {
752 if !self.framework_class_member_contracts.contains(&contract) {
753 self.framework_class_member_contracts.push(contract);
754 }
755 }
756 self.referenced_dependencies.extend(referenced_dependencies);
757 self.package_referenced_dependencies
758 .extend(package_referenced_dependencies);
759 push_missing(&mut self.required_dependencies, required_dependencies);
760 self.discovered_always_used.extend(discovered_always_used);
761 self.setup_files.extend(setup_files);
762 self.tooling_dependencies.extend(tooling_dependencies);
763 self.plugin_tooling.extend(plugin_tooling);
764 self.dev_dependency_names.extend(dev_dependency_names);
765 self.script_used_packages.extend(script_used_packages);
766 extend_unique(&mut self.virtual_module_prefixes, virtual_module_prefixes);
767 extend_unique(&mut self.virtual_package_suffixes, virtual_package_suffixes);
768 extend_unique(
769 &mut self.generated_import_patterns,
770 generated_import_patterns,
771 );
772 extend_unique(
773 &mut self.generated_type_import_prefixes,
774 generated_type_import_prefixes,
775 );
776 push_missing(&mut self.virtual_module_providers, virtual_module_providers);
777 self.path_aliases.extend(path_aliases);
778 self.scoped_path_aliases.extend(scoped_path_aliases);
779 push_missing(&mut self.checked_alias_prefixes, checked_alias_prefixes);
780 self.auto_imports.extend(auto_imports);
781 extend_unique(&mut self.active_plugins, active_plugins);
782 push_missing(&mut self.active_plugin_scopes, active_plugin_scopes);
783 self.fixture_patterns.extend(fixture_patterns);
784 self.scss_include_paths.extend(scss_include_paths);
785 self.static_dir_mappings.extend(static_dir_mappings);
786 self.framework_static_dir_mappings
787 .extend(framework_static_dir_mappings);
788 self.provided_dependencies.extend(provided_dependencies);
789 self.federation_sources.extend(federation_sources);
790 push_missing(&mut self.jsx_import_sources, jsx_import_sources);
791 push_missing(&mut self.jsx_package_credits, jsx_package_credits);
792 push_missing(&mut self.tsconfig_jsx_dirs, tsconfig_jsx_dirs);
793 push_missing(&mut self.config_diagnostics, config_diagnostics);
794 }
795}
796
797impl PluginRegistry {
798 #[must_use]
800 pub fn new(external: Vec<ExternalPluginDef>) -> Self {
801 Self {
802 plugins: builtin::create_builtin_plugins(),
803 external_plugins: external,
804 }
805 }
806
807 #[must_use]
811 pub fn bun_preload_files(root: &Path) -> Vec<PathBuf> {
812 super::bun::preload_files(root)
813 }
814
815 #[must_use]
820 pub fn discovery_hidden_dirs(&self, pkg: &PackageJson, root: &Path) -> Vec<String> {
821 let all_deps = pkg.all_dependency_names();
822 let mut seen = FxHashSet::default();
823 let mut dirs = Vec::new();
824
825 for plugin in &self.plugins {
826 if !plugin.is_enabled_with_deps(&all_deps, root) {
827 continue;
828 }
829 for dir in plugin.discovery_hidden_dirs() {
830 if seen.insert(*dir) {
831 dirs.push((*dir).to_string());
832 }
833 }
834 }
835
836 dirs
837 }
838
839 #[cfg(test)]
844 fn run(
845 &self,
846 pkg: &PackageJson,
847 root: &Path,
848 discovered_files: &[PathBuf],
849 ) -> AggregatedPluginResult {
850 self.try_run(pkg, root, discovered_files)
851 .unwrap_or_else(|errors| panic!("{}", format_plugin_regex_errors(&errors)))
852 }
853
854 pub fn try_run(
856 &self,
857 pkg: &PackageJson,
858 root: &Path,
859 discovered_files: &[PathBuf],
860 ) -> Result<AggregatedPluginResult, Vec<PluginRegexValidationError>> {
861 self.try_run_with_search_roots(pkg, root, discovered_files, &[root], false, None)
862 }
863
864 #[expect(
867 clippy::too_many_arguments,
868 reason = "public PluginRegistry API; signature is part of the crate surface for embedders"
869 )]
870 pub(crate) fn try_run_with_search_roots(
871 &self,
872 pkg: &PackageJson,
873 root: &Path,
874 discovered_files: &[PathBuf],
875 config_search_roots: &[&Path],
876 production_mode: bool,
877 candidate_index: Option<&ConfigCandidateIndex>,
878 ) -> Result<AggregatedPluginResult, Vec<PluginRegexValidationError>> {
879 let _span = tracing::info_span!("run_plugins").entered();
880 let mut result = AggregatedPluginResult::default();
881 let mut regex_errors = Vec::new();
882
883 let PluginRunContext { all_deps, active } = self.prepare_plugin_run_context(
884 pkg,
885 root,
886 discovered_files,
887 production_mode,
888 candidate_index,
889 );
890
891 self.run_plugin_preflight(&active, &all_deps, root, discovered_files);
892
893 for plugin in &active {
894 process_static_patterns(*plugin, root, &mut result);
895 }
896 process_package_json_metadata(&active, pkg, root, &mut result, &mut regex_errors);
897
898 process_external_plugins(
899 &self.external_plugins,
900 &all_deps,
901 root,
902 discovered_files,
903 &mut result,
904 );
905 tooling_evidence::record_plugin_tooling(
906 &tooling_evidence::ToolingEvidenceInput {
907 active: &active,
908 external_plugins: &self.external_plugins,
909 all_deps: &all_deps,
910 roots: &[root],
911 extra_roots: if production_mode {
915 &[]
916 } else {
917 config_search_roots
918 },
919 candidate_index,
920 discovered_files,
921 },
922 &mut result,
923 );
924
925 let config_matchers = compile_config_matchers(&active);
926 let relative_files =
927 compute_relative_files(&config_matchers, &active, discovered_files, root);
928
929 resolve_plugin_config_files(&mut PluginConfigResolutionInput {
930 config_matchers: &config_matchers,
931 relative_files: &relative_files,
932 config_search_roots,
933 production_mode,
934 candidate_index,
935 root,
936 result: &mut result,
937 regex_errors: &mut regex_errors,
938 });
939
940 process_package_json_inline_configs(
941 &InlineConfigInput {
942 active: &active,
943 config_matchers: &config_matchers,
944 relative_files: &relative_files,
945 pkg,
946 root,
947 project_root: root,
948 },
949 &mut result,
950 &mut regex_errors,
951 );
952
953 if regex_errors.is_empty() {
954 Ok(result)
955 } else {
956 Err(regex_errors)
957 }
958 }
959
960 #[cfg(test)]
965 fn run_workspace_fast(&self, input: &WorkspacePluginRunInput<'_>) -> AggregatedPluginResult {
966 self.try_run_workspace_fast(input)
967 .unwrap_or_else(|errors| panic!("{}", format_plugin_regex_errors(&errors)))
968 }
969
970 pub(crate) fn try_run_workspace_fast(
977 &self,
978 input: &WorkspacePluginRunInput<'_>,
979 ) -> Result<AggregatedPluginResult, Vec<PluginRegexValidationError>> {
980 let _span = tracing::info_span!("run_plugins").entered();
981 let mut result = AggregatedPluginResult::default();
982 let mut regex_errors = Vec::new();
983
984 let (all_deps, script_packages) = workspace_activation_deps(
985 input.pkg,
986 (input.root, input.project_root),
987 input.root_dependencies,
988 input.production_mode,
989 );
990 let workspace_files: Vec<PathBuf> = input
991 .relative_files
992 .iter()
993 .map(|(abs_path, _)| abs_path.clone())
994 .collect();
995
996 let active = self.collect_active_plugins(&PluginActivationInput {
997 pkg: input.pkg,
998 root: input.root,
999 discovered_files: &workspace_files,
1000 all_deps: &all_deps,
1001 script_packages: &script_packages,
1002 candidate_index: input.candidate_index,
1003 });
1004
1005 log_active_plugins(&active);
1006
1007 self.emit_silent_fail_diagnostics(&active, &all_deps, input.root, &workspace_files);
1008
1009 process_external_plugins(
1010 &self.external_plugins,
1011 &all_deps,
1012 input.root,
1013 &workspace_files,
1014 &mut result,
1015 );
1016
1017 if active.is_empty() && result.active_plugins.is_empty() {
1018 return Ok(result);
1019 }
1020
1021 process_workspace_active_plugins(&active, input, &mut result, &mut regex_errors);
1022 let evidence_roots: &[&Path] = if input.root == input.project_root {
1024 &[input.root]
1025 } else {
1026 &[input.root, input.project_root]
1027 };
1028 tooling_evidence::record_plugin_tooling(
1029 &tooling_evidence::ToolingEvidenceInput {
1030 active: &active,
1031 external_plugins: &self.external_plugins,
1032 all_deps: &all_deps,
1033 roots: evidence_roots,
1034 extra_roots: &[],
1035 candidate_index: input.candidate_index,
1036 discovered_files: &workspace_files,
1037 },
1038 &mut result,
1039 );
1040 resolve_workspace_plugin_configs(&active, input, &mut result, &mut regex_errors);
1041 if input.root != input.project_root {
1043 process_package_json_inline_configs(
1044 &InlineConfigInput {
1045 active: &active,
1046 config_matchers: input.precompiled_config_matchers,
1047 relative_files: input.relative_files,
1048 pkg: input.pkg,
1049 root: input.root,
1050 project_root: input.project_root,
1051 },
1052 &mut result,
1053 &mut regex_errors,
1054 );
1055 }
1056
1057 if regex_errors.is_empty() {
1058 Ok(result)
1059 } else {
1060 Err(regex_errors)
1061 }
1062 }
1063
1064 #[must_use]
1067 pub(crate) fn precompile_config_matchers(
1068 &self,
1069 ) -> Vec<(&dyn Plugin, Vec<globset::GlobMatcher>)> {
1070 self.plugins
1071 .iter()
1072 .filter(|p| !p.config_patterns().is_empty())
1073 .map(|p| (p.as_ref(), cached_plugin_config_matchers(p.as_ref())))
1074 .collect()
1075 }
1076
1077 pub(crate) fn resolve_script_config_files(
1088 &self,
1089 config_files: &[scripts::BinaryConfigFile],
1090 package_root: &Path,
1091 project_root: &Path,
1092 ws_prefix: &str,
1093 ) -> AggregatedPluginResult {
1094 let mut aggregated = AggregatedPluginResult::default();
1095 for config_file in config_files {
1096 let Some(rel_path) =
1097 scripts::normalize_script_entry_pattern(ws_prefix, &config_file.path)
1098 else {
1099 continue;
1100 };
1101 let abs_path = package_root.join(config_file.path.trim_start_matches("./"));
1102 let in_package_root = abs_path.parent() == Some(package_root);
1107 let binary = config_file
1110 .binary
1111 .rsplit('/')
1112 .next()
1113 .unwrap_or(&config_file.binary);
1114 for plugin in &self.plugins {
1115 let plugin = plugin.as_ref();
1116 if !plugin.script_config_binaries().contains(&binary)
1117 || (in_package_root
1118 && cached_plugin_config_matchers(plugin)
1119 .iter()
1120 .any(|m| m.is_match(rel_path.as_str())))
1121 {
1122 continue;
1123 }
1124 if !super::config_parser::is_inside_root(&abs_path, project_root) {
1125 continue;
1126 }
1127 let Ok(source) = std::fs::read_to_string(&abs_path) else {
1128 continue;
1129 };
1130 let mut file_result = AggregatedPluginResult::default();
1131 file_result
1132 .entry_point_roles
1133 .insert(plugin.name().to_string(), plugin.entry_point_role());
1134 let plugin_result =
1135 plugin.resolve_script_config(&abs_path, &source, package_root, project_root);
1136 if let Err(errors) = process_config_result(
1137 plugin.name(),
1138 plugin_result,
1139 &mut file_result,
1140 Some(&abs_path),
1141 ) {
1142 for error in errors {
1143 tracing::warn!("{error}");
1144 }
1145 continue;
1146 }
1147 if !ws_prefix.is_empty() {
1148 file_result.apply_workspace_prefix(ws_prefix);
1149 }
1150 file_result.used_exports.push(PluginUsedExportRule::new(
1152 plugin.name().to_string(),
1153 super::UsedExportRule::new(rel_path.clone(), ["default"]),
1154 ));
1155 aggregated.merge_into(file_result);
1156 }
1157 }
1158 aggregated
1159 }
1160}
1161
1162fn process_workspace_active_plugins(
1163 active: &[&dyn Plugin],
1164 input: &WorkspacePluginRunInput<'_>,
1165 result: &mut AggregatedPluginResult,
1166 regex_errors: &mut Vec<PluginRegexValidationError>,
1167) {
1168 for plugin in active {
1169 process_static_patterns(*plugin, input.root, result);
1170 }
1171 process_package_json_metadata(active, input.pkg, input.root, result, regex_errors);
1172}
1173
1174fn resolve_workspace_plugin_configs(
1175 active: &[&dyn Plugin],
1176 input: &WorkspacePluginRunInput<'_>,
1177 result: &mut AggregatedPluginResult,
1178 regex_errors: &mut Vec<PluginRegexValidationError>,
1179) {
1180 let workspace_matchers = select_workspace_matchers(
1181 input.precompiled_config_matchers,
1182 active,
1183 input.skip_config_plugins,
1184 );
1185
1186 let mut resolved_ws_plugins: FxHashSet<&str> = FxHashSet::default();
1187 for (plugin, matchers) in &workspace_matchers {
1188 resolve_plugin_matching_files(&mut PluginMatchingFilesInput {
1189 plugin: *plugin,
1190 matchers,
1191 relative_files: input.relative_files,
1192 root: input.root,
1193 project_root: input.project_root,
1194 result,
1195 regex_errors,
1196 resolved_plugins: &mut resolved_ws_plugins,
1197 });
1198 }
1199
1200 load_workspace_filesystem_configs(&mut WorkspaceFsConfigInput {
1201 workspace_matchers: &workspace_matchers,
1202 resolved_ws_plugins: &resolved_ws_plugins,
1203 root: input.root,
1204 project_root: input.project_root,
1205 production_mode: input.production_mode,
1206 candidate_index: input.candidate_index,
1207 result,
1208 regex_errors,
1209 });
1210}
1211
1212impl Default for PluginRegistry {
1213 fn default() -> Self {
1214 Self::new(vec![])
1215 }
1216}
1217
1218impl PluginRegistry {
1219 fn prepare_plugin_run_context<'a>(
1220 &'a self,
1221 pkg: &PackageJson,
1222 root: &Path,
1223 discovered_files: &[PathBuf],
1224 production_mode: bool,
1225 candidate_index: Option<&ConfigCandidateIndex>,
1226 ) -> PluginRunContext<'a> {
1227 let all_deps = pkg.all_dependency_names();
1228 let script_packages =
1229 script_activation_packages(pkg, root, &[root], &all_deps, production_mode);
1230 let active = self.collect_active_plugins(&PluginActivationInput {
1231 pkg,
1232 root,
1233 discovered_files,
1234 all_deps: &all_deps,
1235 script_packages: &script_packages,
1236 candidate_index,
1237 });
1238
1239 PluginRunContext { all_deps, active }
1240 }
1241
1242 fn run_plugin_preflight(
1243 &self,
1244 active: &[&dyn Plugin],
1245 all_deps: &[String],
1246 root: &Path,
1247 discovered_files: &[PathBuf],
1248 ) {
1249 log_active_plugins(active);
1250 check_meta_framework_prerequisites(active, root);
1251 self.emit_silent_fail_diagnostics(active, all_deps, root, discovered_files);
1252 }
1253
1254 fn collect_active_plugins<'a>(
1257 &'a self,
1258 activation: &PluginActivationInput<'_>,
1259 ) -> Vec<&'a dyn Plugin> {
1260 self.plugins
1261 .iter()
1262 .filter(|p| {
1263 p.is_enabled_with_files(
1264 activation.all_deps,
1265 activation.root,
1266 activation.discovered_files,
1267 activation.candidate_index,
1268 ) || p.is_enabled_with_scripts(activation.script_packages, activation.root)
1269 || p.is_enabled_with_package_json(activation.pkg, activation.root)
1270 })
1271 .map(AsRef::as_ref)
1272 .collect()
1273 }
1274
1275 fn emit_silent_fail_diagnostics(
1284 &self,
1285 active: &[&dyn Plugin],
1286 all_deps: &[String],
1287 root: &Path,
1288 discovered_files: &[PathBuf],
1289 ) {
1290 let active_external: Vec<&ExternalPluginDef> = self
1291 .external_plugins
1292 .iter()
1293 .filter(|ext| is_external_plugin_active(ext, all_deps, root, discovered_files))
1294 .collect();
1295 let mut diagnostics = detect_pattern_collisions(active, &active_external);
1296 diagnostics.extend(detect_enabler_typos(&self.external_plugins, all_deps));
1297 emit_plugin_diagnostics(&diagnostics);
1298 }
1299}
1300
1301fn plugin_warn_dedupe() -> &'static std::sync::Mutex<FxHashSet<String>> {
1306 static WARNED: std::sync::OnceLock<std::sync::Mutex<FxHashSet<String>>> =
1307 std::sync::OnceLock::new();
1308 WARNED.get_or_init(|| std::sync::Mutex::new(FxHashSet::default()))
1309}
1310
1311struct PluginConfigResolutionInput<'a> {
1312 config_matchers: &'a [(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
1313 relative_files: &'a [(PathBuf, String)],
1314 config_search_roots: &'a [&'a Path],
1315 production_mode: bool,
1316 candidate_index: Option<&'a ConfigCandidateIndex>,
1317 root: &'a Path,
1318 result: &'a mut AggregatedPluginResult,
1319 regex_errors: &'a mut Vec<PluginRegexValidationError>,
1320}
1321
1322fn select_workspace_matchers<'a>(
1325 precompiled_config_matchers: &[(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
1326 active: &[&dyn Plugin],
1327 skip_config_plugins: &FxHashSet<&str>,
1328) -> Vec<(&'a dyn Plugin, Vec<globset::GlobMatcher>)> {
1329 let active_names: FxHashSet<&str> = active.iter().map(|p| p.name()).collect();
1330 precompiled_config_matchers
1331 .iter()
1332 .filter(|(p, _)| {
1333 active_names.contains(p.name())
1334 && (!skip_config_plugins.contains(p.name())
1335 || must_parse_workspace_config_when_root_active(p.name()))
1336 })
1337 .map(|(plugin, matchers)| (*plugin, matchers.clone()))
1338 .collect()
1339}
1340
1341struct WorkspaceFsConfigInput<'a> {
1342 workspace_matchers: &'a [(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
1343 resolved_ws_plugins: &'a FxHashSet<&'a str>,
1344 root: &'a Path,
1345 project_root: &'a Path,
1346 production_mode: bool,
1347 candidate_index: Option<&'a ConfigCandidateIndex>,
1348 result: &'a mut AggregatedPluginResult,
1349 regex_errors: &'a mut Vec<PluginRegexValidationError>,
1350}
1351
1352fn load_workspace_filesystem_configs(input: &mut WorkspaceFsConfigInput<'_>) {
1355 let search_roots: &[&Path] = if input.root == input.project_root {
1356 &[input.root]
1357 } else {
1358 &[input.root, input.project_root]
1359 };
1360 let ws_json_configs = discover_config_files(
1361 input.workspace_matchers,
1362 input.resolved_ws_plugins,
1363 search_roots,
1364 input.production_mode,
1365 input.candidate_index,
1366 );
1367 for (abs_path, plugin) in &ws_json_configs {
1368 let Ok(source) = std::fs::read_to_string(abs_path) else {
1369 continue;
1370 };
1371 let plugin_result =
1372 plugin.resolve_config_in_project(abs_path, &source, input.root, input.project_root);
1373 if plugin_result.is_empty() {
1374 continue;
1375 }
1376 let rel = abs_path
1377 .strip_prefix(input.project_root)
1378 .map(|p| p.to_string_lossy())
1379 .unwrap_or_default();
1380 tracing::debug!(
1381 plugin = plugin.name(),
1382 config = %rel,
1383 entries = plugin_result.entry_patterns.len(),
1384 deps = plugin_result.referenced_dependencies.len(),
1385 "resolved config (workspace filesystem fallback)"
1386 );
1387 if let Err(mut errors) =
1388 process_config_result(plugin.name(), plugin_result, input.result, Some(abs_path))
1389 {
1390 input.regex_errors.append(&mut errors);
1391 }
1392 }
1393}
1394
1395fn resolve_plugin_config_files(input: &mut PluginConfigResolutionInput<'_>) {
1396 if input.config_matchers.is_empty() {
1397 return;
1398 }
1399
1400 let mut resolved_plugins: FxHashSet<&str> = FxHashSet::default();
1401 for (plugin, matchers) in input.config_matchers {
1402 resolve_plugin_matching_files(&mut PluginMatchingFilesInput {
1403 plugin: *plugin,
1404 matchers,
1405 relative_files: input.relative_files,
1406 root: input.root,
1407 project_root: input.root,
1408 result: input.result,
1409 regex_errors: input.regex_errors,
1410 resolved_plugins: &mut resolved_plugins,
1411 });
1412 }
1413
1414 let json_configs = discover_config_files(
1415 input.config_matchers,
1416 &resolved_plugins,
1417 input.config_search_roots,
1418 input.production_mode,
1419 input.candidate_index,
1420 );
1421 for (abs_path, plugin) in &json_configs {
1422 resolve_plugin_filesystem_config(
1423 *plugin,
1424 abs_path,
1425 input.root,
1426 input.result,
1427 input.regex_errors,
1428 );
1429 }
1430}
1431
1432struct PluginMatchingFilesInput<'plugins, 'data, 'state> {
1433 plugin: &'plugins dyn Plugin,
1434 matchers: &'data [globset::GlobMatcher],
1435 relative_files: &'data [(PathBuf, String)],
1436 root: &'data Path,
1437 project_root: &'data Path,
1438 result: &'state mut AggregatedPluginResult,
1439 regex_errors: &'state mut Vec<PluginRegexValidationError>,
1440 resolved_plugins: &'state mut FxHashSet<&'plugins str>,
1441}
1442
1443fn resolve_plugin_matching_files(input: &mut PluginMatchingFilesInput<'_, '_, '_>) {
1444 use rayon::prelude::*;
1445
1446 let plugin_hits: Vec<&PathBuf> = input
1447 .relative_files
1448 .par_iter()
1449 .filter_map(|(abs_path, rel_path)| {
1450 input
1451 .matchers
1452 .iter()
1453 .any(|m| m.is_match(rel_path.as_str()))
1454 .then_some(abs_path)
1455 })
1456 .collect();
1457 for abs_path in plugin_hits {
1458 let Ok(source) = std::fs::read_to_string(abs_path) else {
1459 continue;
1460 };
1461 let plugin_result = input.plugin.resolve_config_in_project(
1462 abs_path,
1463 &source,
1464 input.root,
1465 input.project_root,
1466 );
1467 if plugin_result.is_empty() {
1468 continue;
1469 }
1470 input.resolved_plugins.insert(input.plugin.name());
1471 process_resolved_plugin_config(ResolvedPluginConfigInput {
1472 plugin: input.plugin,
1473 abs_path,
1474 plugin_result,
1475 result: input.result,
1476 regex_errors: input.regex_errors,
1477 message: "resolved config",
1478 config_display: abs_path.display(),
1479 });
1480 }
1481}
1482
1483fn resolve_plugin_filesystem_config(
1484 plugin: &dyn Plugin,
1485 abs_path: &Path,
1486 root: &Path,
1487 result: &mut AggregatedPluginResult,
1488 regex_errors: &mut Vec<PluginRegexValidationError>,
1489) {
1490 let Ok(source) = std::fs::read_to_string(abs_path) else {
1491 return;
1492 };
1493 let plugin_result = plugin.resolve_config(abs_path, &source, root);
1494 if plugin_result.is_empty() {
1495 return;
1496 }
1497 let rel = abs_path
1498 .strip_prefix(root)
1499 .map(|p| p.to_string_lossy())
1500 .unwrap_or_default();
1501 process_resolved_plugin_config(ResolvedPluginConfigInput {
1502 plugin,
1503 abs_path,
1504 plugin_result,
1505 result,
1506 regex_errors,
1507 message: "resolved config (filesystem fallback)",
1508 config_display: rel,
1509 });
1510}
1511
1512struct ResolvedPluginConfigInput<'a, D> {
1513 plugin: &'a dyn Plugin,
1514 abs_path: &'a Path,
1515 plugin_result: PluginResult,
1516 result: &'a mut AggregatedPluginResult,
1517 regex_errors: &'a mut Vec<PluginRegexValidationError>,
1518 message: &'static str,
1519 config_display: D,
1520}
1521
1522fn process_resolved_plugin_config(input: ResolvedPluginConfigInput<'_, impl std::fmt::Display>) {
1523 tracing::debug!(
1524 plugin = input.plugin.name(),
1525 config = %input.config_display,
1526 entries = input.plugin_result.entry_patterns.len(),
1527 deps = input.plugin_result.referenced_dependencies.len(),
1528 input.message
1529 );
1530 if let Err(mut errors) = process_config_result(
1531 input.plugin.name(),
1532 input.plugin_result,
1533 input.result,
1534 Some(input.abs_path),
1535 ) {
1536 input.regex_errors.append(&mut errors);
1537 }
1538}
1539
1540fn should_warn(key: String) -> bool {
1544 plugin_warn_dedupe()
1545 .lock()
1546 .map_or(true, |mut set| set.insert(key))
1547}
1548
1549#[derive(Debug, Clone, PartialEq, Eq)]
1556enum PluginDiagnostic {
1557 PatternCollision {
1559 pattern: String,
1560 owners: Vec<String>,
1561 },
1562 EnablerTypo {
1565 plugin: String,
1566 enabler: String,
1567 suggestion: String,
1568 },
1569}
1570
1571fn detect_pattern_collisions(
1597 builtin_active: &[&dyn Plugin],
1598 external_active: &[&ExternalPluginDef],
1599) -> Vec<PluginDiagnostic> {
1600 use rustc_hash::FxHashMap;
1601
1602 let mut pattern_owners: FxHashMap<String, (Vec<String>, FxHashSet<String>)> =
1603 FxHashMap::default();
1604
1605 let record = |pattern_owners: &mut FxHashMap<_, (Vec<String>, FxHashSet<String>)>,
1606 pattern: String,
1607 name: String| {
1608 let (list, seen) = pattern_owners.entry(pattern).or_default();
1609 if seen.insert(name.clone()) {
1610 list.push(name);
1611 }
1612 };
1613
1614 for plugin in builtin_active {
1615 for pat in plugin.config_patterns() {
1616 record(
1617 &mut pattern_owners,
1618 (*pat).to_string(),
1619 plugin.name().to_string(),
1620 );
1621 }
1622 }
1623 for ext in external_active {
1624 for pat in &ext.config_patterns {
1625 record(&mut pattern_owners, pat.clone(), ext.name.clone());
1626 }
1627 }
1628
1629 let builtin_names: FxHashSet<&str> = builtin_active.iter().map(|p| p.name()).collect();
1636
1637 let mut findings: Vec<PluginDiagnostic> = pattern_owners
1638 .into_iter()
1639 .filter_map(|(pattern, (owners, _seen))| {
1640 if owners.len() < 2 || owners.iter().all(|o| builtin_names.contains(o.as_str())) {
1641 None
1642 } else {
1643 Some(PluginDiagnostic::PatternCollision { pattern, owners })
1644 }
1645 })
1646 .collect();
1647 findings.sort_unstable_by(|a, b| match (a, b) {
1648 (
1649 PluginDiagnostic::PatternCollision { pattern: ap, .. },
1650 PluginDiagnostic::PatternCollision { pattern: bp, .. },
1651 ) => ap.cmp(bp),
1652 _ => std::cmp::Ordering::Equal,
1653 });
1654 findings
1655}
1656
1657fn detect_enabler_typos(
1672 external_plugins: &[ExternalPluginDef],
1673 all_deps: &[String],
1674) -> Vec<PluginDiagnostic> {
1675 let mut findings = Vec::new();
1676
1677 for ext in external_plugins {
1678 if ext.detection.is_some() || ext.enablers.is_empty() {
1679 continue;
1680 }
1681
1682 let any_match = ext.enablers.iter().any(|enabler| {
1683 if enabler.ends_with('/') {
1684 all_deps.iter().any(|d| d.starts_with(enabler))
1685 } else {
1686 all_deps.iter().any(|d| d == enabler)
1687 }
1688 });
1689 if any_match {
1690 continue;
1691 }
1692
1693 for enabler in &ext.enablers {
1694 let candidates = all_deps.iter().map(String::as_str);
1695 let Some(suggestion) = fallow_config::levenshtein::closest_match(enabler, candidates)
1696 else {
1697 continue;
1698 };
1699
1700 findings.push(PluginDiagnostic::EnablerTypo {
1701 plugin: ext.name.clone(),
1702 enabler: enabler.clone(),
1703 suggestion: suggestion.to_string(),
1704 });
1705 }
1706 }
1707
1708 findings
1709}
1710
1711fn emit_plugin_diagnostics(findings: &[PluginDiagnostic]) {
1714 for finding in findings {
1715 match finding {
1716 PluginDiagnostic::PatternCollision { pattern, owners } => {
1717 let key = format!("collision::{pattern}::{owners:?}");
1718 if !should_warn(key) {
1719 continue;
1720 }
1721 let winner = &owners[0];
1722 let others = owners[1..].join(", ");
1723 tracing::warn!(
1724 "plugin config_patterns collision: identical pattern \
1725 '{pattern}' is claimed by plugins [{joined}]; '{winner}' \
1726 runs first (registration order), others ({others}) \
1727 follow. Rename one of the patterns or remove the \
1728 duplicate plugin to make resolution explicit. A future \
1729 release may reject identical-pattern collisions.",
1730 joined = owners.join(", "),
1731 );
1732 }
1733 PluginDiagnostic::EnablerTypo {
1734 plugin,
1735 enabler,
1736 suggestion,
1737 } => {
1738 let key = format!("enabler::{plugin}::{enabler}");
1739 if !should_warn(key) {
1740 continue;
1741 }
1742 tracing::warn!(
1743 "plugin '{plugin}' enabler '{enabler}' does not match any \
1744 dependency in package.json; did you mean '{suggestion}'? \
1745 The plugin will not activate. A future release may reject \
1746 unmatched enablers.",
1747 );
1748 }
1749 }
1750 }
1751}
1752
1753fn process_package_json_inline_configs(
1765 input: &InlineConfigInput<'_>,
1766 result: &mut AggregatedPluginResult,
1767 regex_errors: &mut Vec<PluginRegexValidationError>,
1768) {
1769 let pkg_path = input.root.join("package.json");
1770 let credited_manifests: Vec<PathBuf> = if input.root == input.project_root {
1771 Vec::new()
1772 } else {
1773 input
1774 .root
1775 .ancestors()
1776 .take_while(|dir| dir.starts_with(input.project_root))
1777 .map(|dir| dir.join("package.json"))
1778 .collect()
1779 };
1780 for plugin in input.active {
1781 let Some(key) = plugin.package_json_config_key() else {
1782 continue;
1783 };
1784 let Some(config_value) = input.pkg.inline_tool_config(key) else {
1785 continue;
1786 };
1787 if check_has_config_file(*plugin, input.config_matchers, input.relative_files) {
1788 continue;
1789 }
1790 let config_json = serde_json::to_string(config_value).unwrap_or_default();
1791 let fake_path = input.root.join(format!("{key}.config.json"));
1792 let mut plugin_result = plugin.resolve_config_in_project(
1793 &fake_path,
1794 &config_json,
1795 input.root,
1796 input.project_root,
1797 );
1798 if plugin_result.is_empty() {
1799 continue;
1800 }
1801 tracing::debug!(
1802 plugin = plugin.name(),
1803 key = key,
1804 "resolved inline package.json config"
1805 );
1806 if !credited_manifests.is_empty() {
1807 for dep in std::mem::take(&mut plugin_result.referenced_dependencies) {
1808 plugin_result.package_referenced_dependencies.extend(
1809 credited_manifests
1810 .iter()
1811 .map(|manifest| (manifest.clone(), dep.clone())),
1812 );
1813 }
1814 }
1815 if let Err(mut errors) =
1816 process_config_result(plugin.name(), plugin_result, result, Some(&pkg_path))
1817 {
1818 regex_errors.append(&mut errors);
1819 }
1820 }
1821}
1822
1823struct InlineConfigInput<'a> {
1825 active: &'a [&'a dyn Plugin],
1826 config_matchers: &'a [(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
1827 relative_files: &'a [(PathBuf, String)],
1828 pkg: &'a PackageJson,
1829 root: &'a Path,
1830 project_root: &'a Path,
1831}
1832
1833#[derive(Debug)]
1836struct MetaFrameworkWarning {
1837 dedupe_key: &'static str,
1838 message: &'static str,
1839}
1840
1841fn missing_meta_framework_prerequisites(
1851 active_plugins: &[&dyn Plugin],
1852 root: &Path,
1853) -> Vec<MetaFrameworkWarning> {
1854 active_plugins
1855 .iter()
1856 .filter_map(|plugin| match plugin.name() {
1857 "nuxt" if !root.join(".nuxt/tsconfig.json").exists() => Some(MetaFrameworkWarning {
1858 dedupe_key: "meta-prereq::nuxt",
1859 message: "Nuxt project missing .nuxt/tsconfig.json: run `nuxt prepare` \
1860 before fallow for accurate analysis",
1861 }),
1862 "astro" if !root.join(".astro").exists() => Some(MetaFrameworkWarning {
1863 dedupe_key: "meta-prereq::astro",
1864 message: "Astro project missing .astro/ types: run `astro sync` \
1865 before fallow for accurate analysis",
1866 }),
1867 _ => None,
1868 })
1869 .collect()
1870}
1871
1872fn check_meta_framework_prerequisites(active_plugins: &[&dyn Plugin], root: &Path) {
1882 for warning in missing_meta_framework_prerequisites(active_plugins, root) {
1883 if should_warn(warning.dedupe_key.to_owned()) {
1884 tracing::warn!("{}", warning.message);
1885 }
1886 }
1887}
1888
1889fn workspace_activation_deps(
1898 pkg: &PackageJson,
1899 (root, project_root): (&Path, &Path),
1900 root_dependencies: &[String],
1901 production_mode: bool,
1902) -> (Vec<String>, FxHashSet<String>) {
1903 let mut deps = pkg.all_dependency_names();
1904 let own: FxHashSet<&str> = deps.iter().map(String::as_str).collect();
1905 let hoisted: Vec<String> = root_dependencies
1906 .iter()
1907 .filter(|dep| !own.contains(dep.as_str()))
1908 .cloned()
1909 .collect();
1910 let mut script_deps = deps.clone();
1911 script_deps.extend(hoisted.iter().cloned());
1912 let script_packages = script_activation_packages(
1913 pkg,
1914 root,
1915 &[root, project_root],
1916 &script_deps,
1917 production_mode,
1918 );
1919 deps.extend(
1920 hoisted
1921 .into_iter()
1922 .filter(|dep| script_packages.contains(dep)),
1923 );
1924 (deps, script_packages)
1925}
1926
1927#[must_use]
1931pub fn workspace_activation_dependencies(
1932 pkg: &PackageJson,
1933 root: &Path,
1934 project_root: &Path,
1935 root_dependencies: &[String],
1936 production_mode: bool,
1937) -> Vec<String> {
1938 workspace_activation_deps(
1939 pkg,
1940 (root, project_root),
1941 root_dependencies,
1942 production_mode,
1943 )
1944 .0
1945}
1946
1947fn script_activation_packages(
1950 pkg: &PackageJson,
1951 root: &Path,
1952 node_modules_roots: &[&Path],
1953 all_deps: &[String],
1954 production_mode: bool,
1955) -> FxHashSet<String> {
1956 let Some(pkg_scripts) = pkg.scripts.as_ref() else {
1957 return FxHashSet::default();
1958 };
1959
1960 let scripts_to_analyze = if production_mode {
1961 scripts::filter_production_scripts(pkg_scripts)
1962 } else {
1963 pkg_scripts.clone()
1964 };
1965
1966 let mut nm_roots: Vec<&Path> = Vec::new();
1967 for nm_root in node_modules_roots {
1968 if !nm_roots.contains(nm_root) && nm_root.join("node_modules").is_dir() {
1969 nm_roots.push(nm_root);
1970 }
1971 }
1972 let bin_map = scripts::build_bin_to_package_map(&nm_roots, all_deps);
1973 let dep_set: FxHashSet<String> = all_deps.iter().cloned().collect();
1974 let catalog =
1975 scripts::ScriptCatalog::from_scripts_with_bodies(pkg_scripts, &scripts_to_analyze);
1976
1977 scripts::analyze_scripts_with_dependency_context(
1978 &scripts_to_analyze,
1979 root,
1980 &bin_map,
1981 &dep_set,
1982 &catalog,
1983 scripts::IgnoredCommandEntries::NONE,
1984 )
1985 .used_packages
1986}
1987
1988#[cfg(test)]
1989mod entry_pattern_tests;
1990#[cfg(test)]
1991mod tests;