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;
20
21pub(crate) use tooling_evidence::find_config_file;
22
23#[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#[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#[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#[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#[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
186fn 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
198fn 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
226pub struct PluginRegistry {
228 plugins: Vec<Box<dyn Plugin>>,
229 external_plugins: Vec<ExternalPluginDef>,
230}
231
232pub(crate) struct RootPluginContext<'a> {
234 pub(crate) active_plugins: FxHashSet<&'a str>,
236 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
249pub(crate) struct WorkspacePluginRunInput<'a> {
251 pub(crate) pkg: &'a PackageJson,
252 pub(crate) root: &'a Path,
253 pub(crate) project_root: &'a Path,
254 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
270struct 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#[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#[derive(Debug, Clone, Default, PartialEq, Eq)]
358pub struct PluginToolingDependencies {
359 pub plugin: String,
361 pub dependencies: Vec<String>,
363 pub references: Vec<String>,
367 pub own_config: Option<PathBuf>,
370}
371
372#[derive(Debug, Clone, Copy, PartialEq, Eq)]
374pub enum PluginToolingEvidence<'a> {
375 OwnConfig(&'a Path),
377 Reference(&'a str),
379}
380
381impl PluginToolingDependencies {
382 #[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#[derive(Debug, Clone, PartialEq, Eq)]
402pub struct CheckedAliasPrefix {
403 pub scope: String,
407 pub prefix: String,
409}
410
411impl CheckedAliasPrefix {
412 #[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#[derive(Debug, Clone, Default)]
422pub struct AggregatedPluginResult {
423 pub entry_patterns: Vec<(PathRule, String)>,
425 pub replaced_entry_plugins: FxHashSet<String>,
430 pub config_entry_patterns: FxHashSet<(String, String)>,
434 pub entry_point_roles: rustc_hash::FxHashMap<String, EntryPointRole>,
436 pub config_patterns: Vec<String>,
438 pub always_used: Vec<(String, String)>,
440 pub used_exports: Vec<PluginUsedExportRule>,
442 pub config_export_credits: Vec<PluginUsedExportRule>,
450 pub used_class_members: Vec<UsedClassMemberRule>,
454 pub framework_class_member_contracts: Vec<fallow_types::semantic::SemanticFrameworkContract>,
456 pub referenced_dependencies: Vec<String>,
458 pub package_referenced_dependencies: Vec<(PathBuf, String)>,
460 pub required_dependencies: Vec<super::RequiredDependency>,
462 pub discovered_always_used: Vec<(String, String)>,
464 pub setup_files: Vec<(PathBuf, String)>,
466 pub tooling_dependencies: Vec<String>,
470 pub plugin_tooling: Vec<PluginToolingDependencies>,
474 pub script_used_packages: FxHashSet<String>,
476 pub dependency_binaries: crate::scripts::DependencyBinaries,
480 pub dev_dependency_names: FxHashSet<String>,
485 pub virtual_module_prefixes: Vec<String>,
488 pub virtual_package_suffixes: Vec<String>,
491 pub generated_import_patterns: Vec<String>,
494 pub generated_type_import_prefixes: Vec<String>,
497 pub path_aliases: Vec<(String, String)>,
500 pub scoped_path_aliases: Vec<fallow_graph::resolve::ScopedPathAlias>,
505 pub checked_alias_prefixes: Vec<CheckedAliasPrefix>,
509 pub auto_imports: Vec<AutoImportRule>,
513 pub active_plugins: Vec<String>,
515 pub active_plugin_scopes: Vec<(String, String)>,
519 pub fixture_patterns: Vec<(String, String)>,
521 pub scss_include_paths: Vec<PathBuf>,
526 pub static_dir_mappings: Vec<(PathBuf, String)>,
528 pub framework_static_dir_mappings: Vec<(PathBuf, String)>,
531 pub provided_dependencies: Vec<ProvidedDependencyRule>,
533 pub config_diagnostics: Vec<super::PluginConfigDiagnostic>,
537 pub federation_sources: Vec<super::FederationSource>,
540 pub jsx_import_sources: Vec<JsxImportSourceRule>,
544 pub jsx_package_credits: Vec<JsxImportSourceRule>,
549 pub tsconfig_jsx_dirs: Vec<PathBuf>,
553}
554
555fn extend_unique(target: &mut Vec<String>, incoming: Vec<String>) {
560 let mut seen: FxHashSet<String> = target.iter().cloned().collect();
561 for item in incoming {
562 if seen.insert(item.clone()) {
563 target.push(item);
564 }
565 }
566}
567
568fn push_missing<T: PartialEq>(target: &mut Vec<T>, incoming: Vec<T>) {
571 for item in incoming {
572 if !target.contains(&item) {
573 target.push(item);
574 }
575 }
576}
577
578fn prefix_if_needed(pat: &str, ws_prefix: &str) -> String {
582 if pat.starts_with(ws_prefix) || pat.starts_with('/') {
583 pat.to_string()
584 } else {
585 format!("{ws_prefix}/{pat}")
586 }
587}
588
589impl AggregatedPluginResult {
590 pub(crate) fn unique_entry_patterns(&self) -> impl Iterator<Item = &(PathRule, String)> {
596 let mut seen: FxHashSet<&(PathRule, String)> = FxHashSet::default();
597 self.entry_patterns
598 .iter()
599 .filter(move |entry| seen.insert(entry))
600 }
601
602 pub(crate) fn apply_workspace_prefix(&mut self, ws_prefix: &str) {
618 for (rule, _) in &mut self.entry_patterns {
619 *rule = rule.prefixed(ws_prefix);
620 }
621 for (pat, _) in &mut self.always_used {
622 *pat = prefix_if_needed(pat, ws_prefix);
623 }
624 for (pat, _) in &mut self.discovered_always_used {
625 *pat = prefix_if_needed(pat, ws_prefix);
626 }
627 for (pat, _) in &mut self.fixture_patterns {
628 *pat = prefix_if_needed(pat, ws_prefix);
629 }
630 for rule in &mut self.used_exports {
631 *rule = rule.prefixed(ws_prefix);
632 }
633 for (_, scope) in &mut self.active_plugin_scopes {
634 *scope = ws_prefix.to_string();
635 }
636 for rule in &mut self.config_export_credits {
637 *rule = rule.prefixed(ws_prefix);
638 }
639 for rule in &mut self.provided_dependencies {
640 *rule = rule.prefixed(ws_prefix);
641 }
642 for source in &mut self.federation_sources {
643 *source = source.prefixed(ws_prefix);
644 }
645 if !ws_prefix.is_empty() {
646 for checked in &mut self.checked_alias_prefixes {
647 checked.scope = ws_prefix.to_string();
648 }
649 self.scoped_path_aliases
650 .extend(self.path_aliases.drain(..).map(|(prefix, replacement)| {
651 fallow_graph::resolve::ScopedPathAlias {
652 scope: ws_prefix.to_string(),
653 prefix,
654 replacement: format!("{ws_prefix}/{replacement}"),
655 }
656 }));
657 }
658 }
659
660 pub(crate) fn merge_into(&mut self, other: Self) {
674 let Self {
675 entry_patterns,
676 replaced_entry_plugins: _,
678 config_entry_patterns: _,
679 entry_point_roles,
680 config_patterns,
681 always_used,
682 used_exports,
683 config_export_credits,
684 used_class_members,
685 framework_class_member_contracts,
686 referenced_dependencies,
687 package_referenced_dependencies,
688 required_dependencies,
689 discovered_always_used,
690 setup_files,
691 tooling_dependencies,
692 plugin_tooling,
693 script_used_packages,
694 dependency_binaries: _,
695 dev_dependency_names,
696 virtual_module_prefixes,
697 virtual_package_suffixes,
698 generated_import_patterns,
699 generated_type_import_prefixes,
700 path_aliases,
701 scoped_path_aliases,
702 checked_alias_prefixes,
703 auto_imports,
704 active_plugins,
705 active_plugin_scopes,
706 fixture_patterns,
707 scss_include_paths,
708 static_dir_mappings,
709 framework_static_dir_mappings,
710 provided_dependencies,
711 config_diagnostics,
712 federation_sources,
713 jsx_import_sources,
714 jsx_package_credits,
715 tsconfig_jsx_dirs,
716 } = other;
717
718 self.entry_patterns.extend(entry_patterns);
719 for (plugin_name, role) in entry_point_roles {
720 self.entry_point_roles.entry(plugin_name).or_insert(role);
721 }
722 self.config_patterns.extend(config_patterns);
723 self.always_used.extend(always_used);
724 self.used_exports.extend(used_exports);
725 self.config_export_credits.extend(config_export_credits);
726 self.used_class_members.extend(used_class_members);
727 for contract in framework_class_member_contracts {
728 if !self.framework_class_member_contracts.contains(&contract) {
729 self.framework_class_member_contracts.push(contract);
730 }
731 }
732 self.referenced_dependencies.extend(referenced_dependencies);
733 self.package_referenced_dependencies
734 .extend(package_referenced_dependencies);
735 push_missing(&mut self.required_dependencies, required_dependencies);
736 self.discovered_always_used.extend(discovered_always_used);
737 self.setup_files.extend(setup_files);
738 self.tooling_dependencies.extend(tooling_dependencies);
739 self.plugin_tooling.extend(plugin_tooling);
740 self.dev_dependency_names.extend(dev_dependency_names);
741 self.script_used_packages.extend(script_used_packages);
742 extend_unique(&mut self.virtual_module_prefixes, virtual_module_prefixes);
743 extend_unique(&mut self.virtual_package_suffixes, virtual_package_suffixes);
744 extend_unique(
745 &mut self.generated_import_patterns,
746 generated_import_patterns,
747 );
748 extend_unique(
749 &mut self.generated_type_import_prefixes,
750 generated_type_import_prefixes,
751 );
752 self.path_aliases.extend(path_aliases);
753 self.scoped_path_aliases.extend(scoped_path_aliases);
754 push_missing(&mut self.checked_alias_prefixes, checked_alias_prefixes);
755 self.auto_imports.extend(auto_imports);
756 extend_unique(&mut self.active_plugins, active_plugins);
757 push_missing(&mut self.active_plugin_scopes, active_plugin_scopes);
758 self.fixture_patterns.extend(fixture_patterns);
759 self.scss_include_paths.extend(scss_include_paths);
760 self.static_dir_mappings.extend(static_dir_mappings);
761 self.framework_static_dir_mappings
762 .extend(framework_static_dir_mappings);
763 self.provided_dependencies.extend(provided_dependencies);
764 self.federation_sources.extend(federation_sources);
765 push_missing(&mut self.jsx_import_sources, jsx_import_sources);
766 push_missing(&mut self.jsx_package_credits, jsx_package_credits);
767 push_missing(&mut self.tsconfig_jsx_dirs, tsconfig_jsx_dirs);
768 push_missing(&mut self.config_diagnostics, config_diagnostics);
769 }
770}
771
772impl PluginRegistry {
773 #[must_use]
775 pub fn new(external: Vec<ExternalPluginDef>) -> Self {
776 Self {
777 plugins: builtin::create_builtin_plugins(),
778 external_plugins: external,
779 }
780 }
781
782 #[must_use]
786 pub fn bun_preload_files(root: &Path) -> Vec<PathBuf> {
787 super::bun::preload_files(root)
788 }
789
790 #[must_use]
795 pub fn discovery_hidden_dirs(&self, pkg: &PackageJson, root: &Path) -> Vec<String> {
796 let all_deps = pkg.all_dependency_names();
797 let mut seen = FxHashSet::default();
798 let mut dirs = Vec::new();
799
800 for plugin in &self.plugins {
801 if !plugin.is_enabled_with_deps(&all_deps, root) {
802 continue;
803 }
804 for dir in plugin.discovery_hidden_dirs() {
805 if seen.insert(*dir) {
806 dirs.push((*dir).to_string());
807 }
808 }
809 }
810
811 dirs
812 }
813
814 #[cfg(test)]
819 fn run(
820 &self,
821 pkg: &PackageJson,
822 root: &Path,
823 discovered_files: &[PathBuf],
824 ) -> AggregatedPluginResult {
825 self.try_run(pkg, root, discovered_files)
826 .unwrap_or_else(|errors| panic!("{}", format_plugin_regex_errors(&errors)))
827 }
828
829 pub fn try_run(
831 &self,
832 pkg: &PackageJson,
833 root: &Path,
834 discovered_files: &[PathBuf],
835 ) -> Result<AggregatedPluginResult, Vec<PluginRegexValidationError>> {
836 self.try_run_with_search_roots(pkg, root, discovered_files, &[root], false, None)
837 }
838
839 #[expect(
842 clippy::too_many_arguments,
843 reason = "public PluginRegistry API; signature is part of the crate surface for embedders"
844 )]
845 pub(crate) fn try_run_with_search_roots(
846 &self,
847 pkg: &PackageJson,
848 root: &Path,
849 discovered_files: &[PathBuf],
850 config_search_roots: &[&Path],
851 production_mode: bool,
852 candidate_index: Option<&ConfigCandidateIndex>,
853 ) -> Result<AggregatedPluginResult, Vec<PluginRegexValidationError>> {
854 let _span = tracing::info_span!("run_plugins").entered();
855 let mut result = AggregatedPluginResult::default();
856 let mut regex_errors = Vec::new();
857
858 let PluginRunContext { all_deps, active } = self.prepare_plugin_run_context(
859 pkg,
860 root,
861 discovered_files,
862 production_mode,
863 candidate_index,
864 );
865
866 self.run_plugin_preflight(&active, &all_deps, root, discovered_files);
867
868 for plugin in &active {
869 process_static_patterns(*plugin, root, &mut result);
870 }
871 process_package_json_metadata(&active, pkg, root, &mut result, &mut regex_errors);
872
873 process_external_plugins(
874 &self.external_plugins,
875 &all_deps,
876 root,
877 discovered_files,
878 &mut result,
879 );
880 tooling_evidence::record_plugin_tooling(
881 &tooling_evidence::ToolingEvidenceInput {
882 active: &active,
883 external_plugins: &self.external_plugins,
884 all_deps: &all_deps,
885 roots: &[root],
886 extra_roots: if production_mode {
890 &[]
891 } else {
892 config_search_roots
893 },
894 candidate_index,
895 discovered_files,
896 },
897 &mut result,
898 );
899
900 let config_matchers = compile_config_matchers(&active);
901 let relative_files =
902 compute_relative_files(&config_matchers, &active, discovered_files, root);
903
904 resolve_plugin_config_files(&mut PluginConfigResolutionInput {
905 config_matchers: &config_matchers,
906 relative_files: &relative_files,
907 config_search_roots,
908 production_mode,
909 candidate_index,
910 root,
911 result: &mut result,
912 regex_errors: &mut regex_errors,
913 });
914
915 process_package_json_inline_configs(
916 &InlineConfigInput {
917 active: &active,
918 config_matchers: &config_matchers,
919 relative_files: &relative_files,
920 pkg,
921 root,
922 project_root: root,
923 },
924 &mut result,
925 &mut regex_errors,
926 );
927
928 if regex_errors.is_empty() {
929 Ok(result)
930 } else {
931 Err(regex_errors)
932 }
933 }
934
935 #[cfg(test)]
940 fn run_workspace_fast(&self, input: &WorkspacePluginRunInput<'_>) -> AggregatedPluginResult {
941 self.try_run_workspace_fast(input)
942 .unwrap_or_else(|errors| panic!("{}", format_plugin_regex_errors(&errors)))
943 }
944
945 pub(crate) fn try_run_workspace_fast(
952 &self,
953 input: &WorkspacePluginRunInput<'_>,
954 ) -> Result<AggregatedPluginResult, Vec<PluginRegexValidationError>> {
955 let _span = tracing::info_span!("run_plugins").entered();
956 let mut result = AggregatedPluginResult::default();
957 let mut regex_errors = Vec::new();
958
959 let (all_deps, script_packages) = workspace_activation_deps(input);
960 let workspace_files: Vec<PathBuf> = input
961 .relative_files
962 .iter()
963 .map(|(abs_path, _)| abs_path.clone())
964 .collect();
965
966 let active = self.collect_active_plugins(&PluginActivationInput {
967 pkg: input.pkg,
968 root: input.root,
969 discovered_files: &workspace_files,
970 all_deps: &all_deps,
971 script_packages: &script_packages,
972 candidate_index: input.candidate_index,
973 });
974
975 log_active_plugins(&active);
976
977 self.emit_silent_fail_diagnostics(&active, &all_deps, input.root, &workspace_files);
978
979 process_external_plugins(
980 &self.external_plugins,
981 &all_deps,
982 input.root,
983 &workspace_files,
984 &mut result,
985 );
986
987 if active.is_empty() && result.active_plugins.is_empty() {
988 return Ok(result);
989 }
990
991 process_workspace_active_plugins(&active, input, &mut result, &mut regex_errors);
992 let evidence_roots: &[&Path] = if input.root == input.project_root {
994 &[input.root]
995 } else {
996 &[input.root, input.project_root]
997 };
998 tooling_evidence::record_plugin_tooling(
999 &tooling_evidence::ToolingEvidenceInput {
1000 active: &active,
1001 external_plugins: &self.external_plugins,
1002 all_deps: &all_deps,
1003 roots: evidence_roots,
1004 extra_roots: &[],
1005 candidate_index: input.candidate_index,
1006 discovered_files: &workspace_files,
1007 },
1008 &mut result,
1009 );
1010 resolve_workspace_plugin_configs(&active, input, &mut result, &mut regex_errors);
1011 if input.root != input.project_root {
1013 process_package_json_inline_configs(
1014 &InlineConfigInput {
1015 active: &active,
1016 config_matchers: input.precompiled_config_matchers,
1017 relative_files: input.relative_files,
1018 pkg: input.pkg,
1019 root: input.root,
1020 project_root: input.project_root,
1021 },
1022 &mut result,
1023 &mut regex_errors,
1024 );
1025 }
1026
1027 if regex_errors.is_empty() {
1028 Ok(result)
1029 } else {
1030 Err(regex_errors)
1031 }
1032 }
1033
1034 #[must_use]
1037 pub(crate) fn precompile_config_matchers(
1038 &self,
1039 ) -> Vec<(&dyn Plugin, Vec<globset::GlobMatcher>)> {
1040 self.plugins
1041 .iter()
1042 .filter(|p| !p.config_patterns().is_empty())
1043 .map(|p| (p.as_ref(), cached_plugin_config_matchers(p.as_ref())))
1044 .collect()
1045 }
1046
1047 pub(crate) fn resolve_script_config_files(
1058 &self,
1059 config_files: &[scripts::BinaryConfigFile],
1060 package_root: &Path,
1061 project_root: &Path,
1062 ws_prefix: &str,
1063 ) -> AggregatedPluginResult {
1064 let mut aggregated = AggregatedPluginResult::default();
1065 for config_file in config_files {
1066 let Some(rel_path) =
1067 scripts::normalize_script_entry_pattern(ws_prefix, &config_file.path)
1068 else {
1069 continue;
1070 };
1071 let abs_path = package_root.join(config_file.path.trim_start_matches("./"));
1072 let in_package_root = abs_path.parent() == Some(package_root);
1077 let binary = config_file
1080 .binary
1081 .rsplit('/')
1082 .next()
1083 .unwrap_or(&config_file.binary);
1084 for plugin in &self.plugins {
1085 let plugin = plugin.as_ref();
1086 if !plugin.script_config_binaries().contains(&binary)
1087 || (in_package_root
1088 && cached_plugin_config_matchers(plugin)
1089 .iter()
1090 .any(|m| m.is_match(rel_path.as_str())))
1091 {
1092 continue;
1093 }
1094 if !super::config_parser::is_inside_root(&abs_path, project_root) {
1095 continue;
1096 }
1097 let Ok(source) = std::fs::read_to_string(&abs_path) else {
1098 continue;
1099 };
1100 let mut file_result = AggregatedPluginResult::default();
1101 file_result
1102 .entry_point_roles
1103 .insert(plugin.name().to_string(), plugin.entry_point_role());
1104 let plugin_result =
1105 plugin.resolve_script_config(&abs_path, &source, package_root, project_root);
1106 if let Err(errors) = process_config_result(
1107 plugin.name(),
1108 plugin_result,
1109 &mut file_result,
1110 Some(&abs_path),
1111 ) {
1112 for error in errors {
1113 tracing::warn!("{error}");
1114 }
1115 continue;
1116 }
1117 if !ws_prefix.is_empty() {
1118 file_result.apply_workspace_prefix(ws_prefix);
1119 }
1120 file_result.used_exports.push(PluginUsedExportRule::new(
1122 plugin.name().to_string(),
1123 super::UsedExportRule::new(rel_path.clone(), ["default"]),
1124 ));
1125 aggregated.merge_into(file_result);
1126 }
1127 }
1128 aggregated
1129 }
1130}
1131
1132fn process_workspace_active_plugins(
1133 active: &[&dyn Plugin],
1134 input: &WorkspacePluginRunInput<'_>,
1135 result: &mut AggregatedPluginResult,
1136 regex_errors: &mut Vec<PluginRegexValidationError>,
1137) {
1138 for plugin in active {
1139 process_static_patterns(*plugin, input.root, result);
1140 }
1141 process_package_json_metadata(active, input.pkg, input.root, result, regex_errors);
1142}
1143
1144fn resolve_workspace_plugin_configs(
1145 active: &[&dyn Plugin],
1146 input: &WorkspacePluginRunInput<'_>,
1147 result: &mut AggregatedPluginResult,
1148 regex_errors: &mut Vec<PluginRegexValidationError>,
1149) {
1150 let workspace_matchers = select_workspace_matchers(
1151 input.precompiled_config_matchers,
1152 active,
1153 input.skip_config_plugins,
1154 );
1155
1156 let mut resolved_ws_plugins: FxHashSet<&str> = FxHashSet::default();
1157 for (plugin, matchers) in &workspace_matchers {
1158 resolve_plugin_matching_files(&mut PluginMatchingFilesInput {
1159 plugin: *plugin,
1160 matchers,
1161 relative_files: input.relative_files,
1162 root: input.root,
1163 project_root: input.project_root,
1164 result,
1165 regex_errors,
1166 resolved_plugins: &mut resolved_ws_plugins,
1167 });
1168 }
1169
1170 load_workspace_filesystem_configs(&mut WorkspaceFsConfigInput {
1171 workspace_matchers: &workspace_matchers,
1172 resolved_ws_plugins: &resolved_ws_plugins,
1173 root: input.root,
1174 project_root: input.project_root,
1175 production_mode: input.production_mode,
1176 candidate_index: input.candidate_index,
1177 result,
1178 regex_errors,
1179 });
1180}
1181
1182impl Default for PluginRegistry {
1183 fn default() -> Self {
1184 Self::new(vec![])
1185 }
1186}
1187
1188impl PluginRegistry {
1189 fn prepare_plugin_run_context<'a>(
1190 &'a self,
1191 pkg: &PackageJson,
1192 root: &Path,
1193 discovered_files: &[PathBuf],
1194 production_mode: bool,
1195 candidate_index: Option<&ConfigCandidateIndex>,
1196 ) -> PluginRunContext<'a> {
1197 let all_deps = pkg.all_dependency_names();
1198 let script_packages =
1199 script_activation_packages(pkg, root, &[root], &all_deps, production_mode);
1200 let active = self.collect_active_plugins(&PluginActivationInput {
1201 pkg,
1202 root,
1203 discovered_files,
1204 all_deps: &all_deps,
1205 script_packages: &script_packages,
1206 candidate_index,
1207 });
1208
1209 PluginRunContext { all_deps, active }
1210 }
1211
1212 fn run_plugin_preflight(
1213 &self,
1214 active: &[&dyn Plugin],
1215 all_deps: &[String],
1216 root: &Path,
1217 discovered_files: &[PathBuf],
1218 ) {
1219 log_active_plugins(active);
1220 check_meta_framework_prerequisites(active, root);
1221 self.emit_silent_fail_diagnostics(active, all_deps, root, discovered_files);
1222 }
1223
1224 fn collect_active_plugins<'a>(
1227 &'a self,
1228 activation: &PluginActivationInput<'_>,
1229 ) -> Vec<&'a dyn Plugin> {
1230 self.plugins
1231 .iter()
1232 .filter(|p| {
1233 p.is_enabled_with_files(
1234 activation.all_deps,
1235 activation.root,
1236 activation.discovered_files,
1237 activation.candidate_index,
1238 ) || p.is_enabled_with_scripts(activation.script_packages, activation.root)
1239 || p.is_enabled_with_package_json(activation.pkg, activation.root)
1240 })
1241 .map(AsRef::as_ref)
1242 .collect()
1243 }
1244
1245 fn emit_silent_fail_diagnostics(
1254 &self,
1255 active: &[&dyn Plugin],
1256 all_deps: &[String],
1257 root: &Path,
1258 discovered_files: &[PathBuf],
1259 ) {
1260 let active_external: Vec<&ExternalPluginDef> = self
1261 .external_plugins
1262 .iter()
1263 .filter(|ext| is_external_plugin_active(ext, all_deps, root, discovered_files))
1264 .collect();
1265 let mut diagnostics = detect_pattern_collisions(active, &active_external);
1266 diagnostics.extend(detect_enabler_typos(&self.external_plugins, all_deps));
1267 emit_plugin_diagnostics(&diagnostics);
1268 }
1269}
1270
1271fn plugin_warn_dedupe() -> &'static std::sync::Mutex<FxHashSet<String>> {
1276 static WARNED: std::sync::OnceLock<std::sync::Mutex<FxHashSet<String>>> =
1277 std::sync::OnceLock::new();
1278 WARNED.get_or_init(|| std::sync::Mutex::new(FxHashSet::default()))
1279}
1280
1281struct PluginConfigResolutionInput<'a> {
1282 config_matchers: &'a [(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
1283 relative_files: &'a [(PathBuf, String)],
1284 config_search_roots: &'a [&'a Path],
1285 production_mode: bool,
1286 candidate_index: Option<&'a ConfigCandidateIndex>,
1287 root: &'a Path,
1288 result: &'a mut AggregatedPluginResult,
1289 regex_errors: &'a mut Vec<PluginRegexValidationError>,
1290}
1291
1292fn select_workspace_matchers<'a>(
1295 precompiled_config_matchers: &[(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
1296 active: &[&dyn Plugin],
1297 skip_config_plugins: &FxHashSet<&str>,
1298) -> Vec<(&'a dyn Plugin, Vec<globset::GlobMatcher>)> {
1299 let active_names: FxHashSet<&str> = active.iter().map(|p| p.name()).collect();
1300 precompiled_config_matchers
1301 .iter()
1302 .filter(|(p, _)| {
1303 active_names.contains(p.name())
1304 && (!skip_config_plugins.contains(p.name())
1305 || must_parse_workspace_config_when_root_active(p.name()))
1306 })
1307 .map(|(plugin, matchers)| (*plugin, matchers.clone()))
1308 .collect()
1309}
1310
1311struct WorkspaceFsConfigInput<'a> {
1312 workspace_matchers: &'a [(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
1313 resolved_ws_plugins: &'a FxHashSet<&'a str>,
1314 root: &'a Path,
1315 project_root: &'a Path,
1316 production_mode: bool,
1317 candidate_index: Option<&'a ConfigCandidateIndex>,
1318 result: &'a mut AggregatedPluginResult,
1319 regex_errors: &'a mut Vec<PluginRegexValidationError>,
1320}
1321
1322fn load_workspace_filesystem_configs(input: &mut WorkspaceFsConfigInput<'_>) {
1325 let search_roots: &[&Path] = if input.root == input.project_root {
1326 &[input.root]
1327 } else {
1328 &[input.root, input.project_root]
1329 };
1330 let ws_json_configs = discover_config_files(
1331 input.workspace_matchers,
1332 input.resolved_ws_plugins,
1333 search_roots,
1334 input.production_mode,
1335 input.candidate_index,
1336 );
1337 for (abs_path, plugin) in &ws_json_configs {
1338 let Ok(source) = std::fs::read_to_string(abs_path) else {
1339 continue;
1340 };
1341 let plugin_result =
1342 plugin.resolve_config_in_project(abs_path, &source, input.root, input.project_root);
1343 if plugin_result.is_empty() {
1344 continue;
1345 }
1346 let rel = abs_path
1347 .strip_prefix(input.project_root)
1348 .map(|p| p.to_string_lossy())
1349 .unwrap_or_default();
1350 tracing::debug!(
1351 plugin = plugin.name(),
1352 config = %rel,
1353 entries = plugin_result.entry_patterns.len(),
1354 deps = plugin_result.referenced_dependencies.len(),
1355 "resolved config (workspace filesystem fallback)"
1356 );
1357 if let Err(mut errors) =
1358 process_config_result(plugin.name(), plugin_result, input.result, Some(abs_path))
1359 {
1360 input.regex_errors.append(&mut errors);
1361 }
1362 }
1363}
1364
1365fn resolve_plugin_config_files(input: &mut PluginConfigResolutionInput<'_>) {
1366 if input.config_matchers.is_empty() {
1367 return;
1368 }
1369
1370 let mut resolved_plugins: FxHashSet<&str> = FxHashSet::default();
1371 for (plugin, matchers) in input.config_matchers {
1372 resolve_plugin_matching_files(&mut PluginMatchingFilesInput {
1373 plugin: *plugin,
1374 matchers,
1375 relative_files: input.relative_files,
1376 root: input.root,
1377 project_root: input.root,
1378 result: input.result,
1379 regex_errors: input.regex_errors,
1380 resolved_plugins: &mut resolved_plugins,
1381 });
1382 }
1383
1384 let json_configs = discover_config_files(
1385 input.config_matchers,
1386 &resolved_plugins,
1387 input.config_search_roots,
1388 input.production_mode,
1389 input.candidate_index,
1390 );
1391 for (abs_path, plugin) in &json_configs {
1392 resolve_plugin_filesystem_config(
1393 *plugin,
1394 abs_path,
1395 input.root,
1396 input.result,
1397 input.regex_errors,
1398 );
1399 }
1400}
1401
1402struct PluginMatchingFilesInput<'plugins, 'data, 'state> {
1403 plugin: &'plugins dyn Plugin,
1404 matchers: &'data [globset::GlobMatcher],
1405 relative_files: &'data [(PathBuf, String)],
1406 root: &'data Path,
1407 project_root: &'data Path,
1408 result: &'state mut AggregatedPluginResult,
1409 regex_errors: &'state mut Vec<PluginRegexValidationError>,
1410 resolved_plugins: &'state mut FxHashSet<&'plugins str>,
1411}
1412
1413fn resolve_plugin_matching_files(input: &mut PluginMatchingFilesInput<'_, '_, '_>) {
1414 use rayon::prelude::*;
1415
1416 let plugin_hits: Vec<&PathBuf> = input
1417 .relative_files
1418 .par_iter()
1419 .filter_map(|(abs_path, rel_path)| {
1420 input
1421 .matchers
1422 .iter()
1423 .any(|m| m.is_match(rel_path.as_str()))
1424 .then_some(abs_path)
1425 })
1426 .collect();
1427 for abs_path in plugin_hits {
1428 let Ok(source) = std::fs::read_to_string(abs_path) else {
1429 continue;
1430 };
1431 let plugin_result = input.plugin.resolve_config_in_project(
1432 abs_path,
1433 &source,
1434 input.root,
1435 input.project_root,
1436 );
1437 if plugin_result.is_empty() {
1438 continue;
1439 }
1440 input.resolved_plugins.insert(input.plugin.name());
1441 process_resolved_plugin_config(ResolvedPluginConfigInput {
1442 plugin: input.plugin,
1443 abs_path,
1444 plugin_result,
1445 result: input.result,
1446 regex_errors: input.regex_errors,
1447 message: "resolved config",
1448 config_display: abs_path.display(),
1449 });
1450 }
1451}
1452
1453fn resolve_plugin_filesystem_config(
1454 plugin: &dyn Plugin,
1455 abs_path: &Path,
1456 root: &Path,
1457 result: &mut AggregatedPluginResult,
1458 regex_errors: &mut Vec<PluginRegexValidationError>,
1459) {
1460 let Ok(source) = std::fs::read_to_string(abs_path) else {
1461 return;
1462 };
1463 let plugin_result = plugin.resolve_config(abs_path, &source, root);
1464 if plugin_result.is_empty() {
1465 return;
1466 }
1467 let rel = abs_path
1468 .strip_prefix(root)
1469 .map(|p| p.to_string_lossy())
1470 .unwrap_or_default();
1471 process_resolved_plugin_config(ResolvedPluginConfigInput {
1472 plugin,
1473 abs_path,
1474 plugin_result,
1475 result,
1476 regex_errors,
1477 message: "resolved config (filesystem fallback)",
1478 config_display: rel,
1479 });
1480}
1481
1482struct ResolvedPluginConfigInput<'a, D> {
1483 plugin: &'a dyn Plugin,
1484 abs_path: &'a Path,
1485 plugin_result: PluginResult,
1486 result: &'a mut AggregatedPluginResult,
1487 regex_errors: &'a mut Vec<PluginRegexValidationError>,
1488 message: &'static str,
1489 config_display: D,
1490}
1491
1492fn process_resolved_plugin_config(input: ResolvedPluginConfigInput<'_, impl std::fmt::Display>) {
1493 tracing::debug!(
1494 plugin = input.plugin.name(),
1495 config = %input.config_display,
1496 entries = input.plugin_result.entry_patterns.len(),
1497 deps = input.plugin_result.referenced_dependencies.len(),
1498 input.message
1499 );
1500 if let Err(mut errors) = process_config_result(
1501 input.plugin.name(),
1502 input.plugin_result,
1503 input.result,
1504 Some(input.abs_path),
1505 ) {
1506 input.regex_errors.append(&mut errors);
1507 }
1508}
1509
1510fn should_warn(key: String) -> bool {
1514 plugin_warn_dedupe()
1515 .lock()
1516 .map_or(true, |mut set| set.insert(key))
1517}
1518
1519#[derive(Debug, Clone, PartialEq, Eq)]
1526enum PluginDiagnostic {
1527 PatternCollision {
1529 pattern: String,
1530 owners: Vec<String>,
1531 },
1532 EnablerTypo {
1535 plugin: String,
1536 enabler: String,
1537 suggestion: String,
1538 },
1539}
1540
1541fn detect_pattern_collisions(
1567 builtin_active: &[&dyn Plugin],
1568 external_active: &[&ExternalPluginDef],
1569) -> Vec<PluginDiagnostic> {
1570 use rustc_hash::FxHashMap;
1571
1572 let mut pattern_owners: FxHashMap<String, (Vec<String>, FxHashSet<String>)> =
1573 FxHashMap::default();
1574
1575 let record = |pattern_owners: &mut FxHashMap<_, (Vec<String>, FxHashSet<String>)>,
1576 pattern: String,
1577 name: String| {
1578 let (list, seen) = pattern_owners.entry(pattern).or_default();
1579 if seen.insert(name.clone()) {
1580 list.push(name);
1581 }
1582 };
1583
1584 for plugin in builtin_active {
1585 for pat in plugin.config_patterns() {
1586 record(
1587 &mut pattern_owners,
1588 (*pat).to_string(),
1589 plugin.name().to_string(),
1590 );
1591 }
1592 }
1593 for ext in external_active {
1594 for pat in &ext.config_patterns {
1595 record(&mut pattern_owners, pat.clone(), ext.name.clone());
1596 }
1597 }
1598
1599 let builtin_names: FxHashSet<&str> = builtin_active.iter().map(|p| p.name()).collect();
1606
1607 let mut findings: Vec<PluginDiagnostic> = pattern_owners
1608 .into_iter()
1609 .filter_map(|(pattern, (owners, _seen))| {
1610 if owners.len() < 2 || owners.iter().all(|o| builtin_names.contains(o.as_str())) {
1611 None
1612 } else {
1613 Some(PluginDiagnostic::PatternCollision { pattern, owners })
1614 }
1615 })
1616 .collect();
1617 findings.sort_unstable_by(|a, b| match (a, b) {
1618 (
1619 PluginDiagnostic::PatternCollision { pattern: ap, .. },
1620 PluginDiagnostic::PatternCollision { pattern: bp, .. },
1621 ) => ap.cmp(bp),
1622 _ => std::cmp::Ordering::Equal,
1623 });
1624 findings
1625}
1626
1627fn detect_enabler_typos(
1642 external_plugins: &[ExternalPluginDef],
1643 all_deps: &[String],
1644) -> Vec<PluginDiagnostic> {
1645 let mut findings = Vec::new();
1646
1647 for ext in external_plugins {
1648 if ext.detection.is_some() || ext.enablers.is_empty() {
1649 continue;
1650 }
1651
1652 let any_match = ext.enablers.iter().any(|enabler| {
1653 if enabler.ends_with('/') {
1654 all_deps.iter().any(|d| d.starts_with(enabler))
1655 } else {
1656 all_deps.iter().any(|d| d == enabler)
1657 }
1658 });
1659 if any_match {
1660 continue;
1661 }
1662
1663 for enabler in &ext.enablers {
1664 let candidates = all_deps.iter().map(String::as_str);
1665 let Some(suggestion) = fallow_config::levenshtein::closest_match(enabler, candidates)
1666 else {
1667 continue;
1668 };
1669
1670 findings.push(PluginDiagnostic::EnablerTypo {
1671 plugin: ext.name.clone(),
1672 enabler: enabler.clone(),
1673 suggestion: suggestion.to_string(),
1674 });
1675 }
1676 }
1677
1678 findings
1679}
1680
1681fn emit_plugin_diagnostics(findings: &[PluginDiagnostic]) {
1684 for finding in findings {
1685 match finding {
1686 PluginDiagnostic::PatternCollision { pattern, owners } => {
1687 let key = format!("collision::{pattern}::{owners:?}");
1688 if !should_warn(key) {
1689 continue;
1690 }
1691 let winner = &owners[0];
1692 let others = owners[1..].join(", ");
1693 tracing::warn!(
1694 "plugin config_patterns collision: identical pattern \
1695 '{pattern}' is claimed by plugins [{joined}]; '{winner}' \
1696 runs first (registration order), others ({others}) \
1697 follow. Rename one of the patterns or remove the \
1698 duplicate plugin to make resolution explicit. A future \
1699 release may reject identical-pattern collisions.",
1700 joined = owners.join(", "),
1701 );
1702 }
1703 PluginDiagnostic::EnablerTypo {
1704 plugin,
1705 enabler,
1706 suggestion,
1707 } => {
1708 let key = format!("enabler::{plugin}::{enabler}");
1709 if !should_warn(key) {
1710 continue;
1711 }
1712 tracing::warn!(
1713 "plugin '{plugin}' enabler '{enabler}' does not match any \
1714 dependency in package.json; did you mean '{suggestion}'? \
1715 The plugin will not activate. A future release may reject \
1716 unmatched enablers.",
1717 );
1718 }
1719 }
1720 }
1721}
1722
1723fn process_package_json_inline_configs(
1735 input: &InlineConfigInput<'_>,
1736 result: &mut AggregatedPluginResult,
1737 regex_errors: &mut Vec<PluginRegexValidationError>,
1738) {
1739 let pkg_path = input.root.join("package.json");
1740 let credited_manifests: Vec<PathBuf> = if input.root == input.project_root {
1741 Vec::new()
1742 } else {
1743 input
1744 .root
1745 .ancestors()
1746 .take_while(|dir| dir.starts_with(input.project_root))
1747 .map(|dir| dir.join("package.json"))
1748 .collect()
1749 };
1750 for plugin in input.active {
1751 let Some(key) = plugin.package_json_config_key() else {
1752 continue;
1753 };
1754 let Some(config_value) = input.pkg.inline_tool_config(key) else {
1755 continue;
1756 };
1757 if check_has_config_file(*plugin, input.config_matchers, input.relative_files) {
1758 continue;
1759 }
1760 let config_json = serde_json::to_string(config_value).unwrap_or_default();
1761 let fake_path = input.root.join(format!("{key}.config.json"));
1762 let mut plugin_result = plugin.resolve_config_in_project(
1763 &fake_path,
1764 &config_json,
1765 input.root,
1766 input.project_root,
1767 );
1768 if plugin_result.is_empty() {
1769 continue;
1770 }
1771 tracing::debug!(
1772 plugin = plugin.name(),
1773 key = key,
1774 "resolved inline package.json config"
1775 );
1776 if !credited_manifests.is_empty() {
1777 for dep in std::mem::take(&mut plugin_result.referenced_dependencies) {
1778 plugin_result.package_referenced_dependencies.extend(
1779 credited_manifests
1780 .iter()
1781 .map(|manifest| (manifest.clone(), dep.clone())),
1782 );
1783 }
1784 }
1785 if let Err(mut errors) =
1786 process_config_result(plugin.name(), plugin_result, result, Some(&pkg_path))
1787 {
1788 regex_errors.append(&mut errors);
1789 }
1790 }
1791}
1792
1793struct InlineConfigInput<'a> {
1795 active: &'a [&'a dyn Plugin],
1796 config_matchers: &'a [(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
1797 relative_files: &'a [(PathBuf, String)],
1798 pkg: &'a PackageJson,
1799 root: &'a Path,
1800 project_root: &'a Path,
1801}
1802
1803#[derive(Debug)]
1806struct MetaFrameworkWarning {
1807 dedupe_key: &'static str,
1808 message: &'static str,
1809}
1810
1811fn missing_meta_framework_prerequisites(
1821 active_plugins: &[&dyn Plugin],
1822 root: &Path,
1823) -> Vec<MetaFrameworkWarning> {
1824 active_plugins
1825 .iter()
1826 .filter_map(|plugin| match plugin.name() {
1827 "nuxt" if !root.join(".nuxt/tsconfig.json").exists() => Some(MetaFrameworkWarning {
1828 dedupe_key: "meta-prereq::nuxt",
1829 message: "Nuxt project missing .nuxt/tsconfig.json: run `nuxt prepare` \
1830 before fallow for accurate analysis",
1831 }),
1832 "astro" if !root.join(".astro").exists() => Some(MetaFrameworkWarning {
1833 dedupe_key: "meta-prereq::astro",
1834 message: "Astro project missing .astro/ types: run `astro sync` \
1835 before fallow for accurate analysis",
1836 }),
1837 _ => None,
1838 })
1839 .collect()
1840}
1841
1842fn check_meta_framework_prerequisites(active_plugins: &[&dyn Plugin], root: &Path) {
1852 for warning in missing_meta_framework_prerequisites(active_plugins, root) {
1853 if should_warn(warning.dedupe_key.to_owned()) {
1854 tracing::warn!("{}", warning.message);
1855 }
1856 }
1857}
1858
1859fn workspace_activation_deps(
1868 input: &WorkspacePluginRunInput<'_>,
1869) -> (Vec<String>, FxHashSet<String>) {
1870 let mut deps = input.pkg.all_dependency_names();
1871 let own: FxHashSet<&str> = deps.iter().map(String::as_str).collect();
1872 let hoisted: Vec<String> = input
1873 .root_dependencies
1874 .iter()
1875 .filter(|dep| !own.contains(dep.as_str()))
1876 .cloned()
1877 .collect();
1878 let mut script_deps = deps.clone();
1879 script_deps.extend(hoisted.iter().cloned());
1880 let script_packages = script_activation_packages(
1881 input.pkg,
1882 input.root,
1883 &[input.root, input.project_root],
1884 &script_deps,
1885 input.production_mode,
1886 );
1887 deps.extend(
1888 hoisted
1889 .into_iter()
1890 .filter(|dep| script_packages.contains(dep)),
1891 );
1892 (deps, script_packages)
1893}
1894
1895fn script_activation_packages(
1898 pkg: &PackageJson,
1899 root: &Path,
1900 node_modules_roots: &[&Path],
1901 all_deps: &[String],
1902 production_mode: bool,
1903) -> FxHashSet<String> {
1904 let Some(pkg_scripts) = pkg.scripts.as_ref() else {
1905 return FxHashSet::default();
1906 };
1907
1908 let scripts_to_analyze = if production_mode {
1909 scripts::filter_production_scripts(pkg_scripts)
1910 } else {
1911 pkg_scripts.clone()
1912 };
1913
1914 let mut nm_roots: Vec<&Path> = Vec::new();
1915 for nm_root in node_modules_roots {
1916 if !nm_roots.contains(nm_root) && nm_root.join("node_modules").is_dir() {
1917 nm_roots.push(nm_root);
1918 }
1919 }
1920 let bin_map = scripts::build_bin_to_package_map(&nm_roots, all_deps);
1921 let dep_set: FxHashSet<String> = all_deps.iter().cloned().collect();
1922 let catalog =
1923 scripts::ScriptCatalog::from_scripts_with_bodies(pkg_scripts, &scripts_to_analyze);
1924
1925 scripts::analyze_scripts_with_dependency_context(
1926 &scripts_to_analyze,
1927 root,
1928 &bin_map,
1929 &dep_set,
1930 &catalog,
1931 scripts::IgnoredCommandEntries::NONE,
1932 )
1933 .used_packages
1934}
1935
1936#[cfg(test)]
1937mod entry_pattern_tests;
1938#[cfg(test)]
1939mod tests;