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]
69pub fn builtin_always_used_patterns_of(plugin_names: &[String]) -> Vec<&'static str> {
70 let mut patterns: Vec<&'static str> = builtin::create_builtin_plugins()
71 .iter()
72 .filter(|plugin| plugin_names.iter().any(|name| name == plugin.name()))
73 .flat_map(|plugin| plugin.always_used().iter().copied())
74 .collect();
75 patterns.sort_unstable();
76 patterns.dedup();
77 patterns
78}
79
80pub use helpers::ConfigCandidateIndex;
81pub use helpers::is_external_plugin_active;
82use helpers::{
83 check_has_config_file, discover_config_files, prepare_config_pattern, process_config_result,
84 process_external_plugins, process_package_json_metadata, process_static_patterns,
85};
86
87fn must_parse_workspace_config_when_root_active(plugin_name: &str) -> bool {
88 matches!(
89 plugin_name,
90 "eslint" | "docusaurus" | "jest" | "storybook" | "tanstack-router" | "vitest"
91 )
92}
93
94fn compile_config_matchers<'a>(
95 active: &[&'a dyn Plugin],
96) -> Vec<(&'a dyn Plugin, Vec<globset::GlobMatcher>)> {
97 active
98 .iter()
99 .filter(|plugin| !plugin.config_patterns().is_empty())
100 .map(|plugin| (*plugin, cached_plugin_config_matchers(*plugin)))
101 .collect()
102}
103
104fn compile_plugin_config_matchers(plugin: &dyn Plugin) -> Vec<globset::GlobMatcher> {
105 plugin
106 .config_patterns()
107 .iter()
108 .filter_map(|pattern| {
109 let prepared = prepare_config_pattern(pattern);
110 globset::Glob::new(&prepared)
111 .ok()
112 .map(|glob| glob.compile_matcher())
113 })
114 .collect()
115}
116
117struct CachedPluginConfigMatchers {
118 patterns: &'static [&'static str],
119 matchers: Vec<globset::GlobMatcher>,
120}
121
122#[derive(Default)]
123struct PluginConfigMatcherCache {
124 by_name: RwLock<FxHashMap<&'static str, Vec<CachedPluginConfigMatchers>>>,
125}
126
127impl PluginConfigMatcherCache {
128 fn get_or_compile(&self, plugin: &dyn Plugin) -> Vec<globset::GlobMatcher> {
129 let patterns = plugin.config_patterns();
130 let cached = self
131 .by_name
132 .read()
133 .unwrap_or_else(std::sync::PoisonError::into_inner)
134 .get(plugin.name())
135 .and_then(|variants| {
136 variants
137 .iter()
138 .find(|entry| entry.patterns == patterns)
139 .map(|entry| entry.matchers.clone())
140 });
141 if let Some(matchers) = cached {
142 return matchers;
143 }
144
145 let matchers = compile_plugin_config_matchers(plugin);
146 {
147 let mut by_name = self
148 .by_name
149 .write()
150 .unwrap_or_else(std::sync::PoisonError::into_inner);
151 let variants = by_name.entry(plugin.name()).or_default();
152 if let Some(entry) = variants.iter().find(|entry| entry.patterns == patterns) {
153 return entry.matchers.clone();
154 }
155 variants.push(CachedPluginConfigMatchers {
156 patterns,
157 matchers: matchers.clone(),
158 });
159 drop(by_name);
160 }
161 matchers
162 }
163}
164
165fn cached_plugin_config_matchers(plugin: &dyn Plugin) -> Vec<globset::GlobMatcher> {
166 static MATCHERS: OnceLock<PluginConfigMatcherCache> = OnceLock::new();
167 MATCHERS
168 .get_or_init(PluginConfigMatcherCache::default)
169 .get_or_compile(plugin)
170}
171
172fn log_active_plugins(active: &[&dyn Plugin]) {
174 tracing::info!(
175 plugins = active
176 .iter()
177 .map(|p| p.name())
178 .collect::<Vec<_>>()
179 .join(", "),
180 "active plugins"
181 );
182}
183
184fn compute_relative_files(
188 config_matchers: &[(&dyn Plugin, Vec<globset::GlobMatcher>)],
189 active: &[&dyn Plugin],
190 discovered_files: &[PathBuf],
191 root: &Path,
192) -> Vec<(PathBuf, String)> {
193 use rayon::prelude::*;
194 let needs_relative_files =
195 !config_matchers.is_empty() || active.iter().any(|p| p.package_json_config_key().is_some());
196 if !needs_relative_files {
197 return Vec::new();
198 }
199 discovered_files
200 .par_iter()
201 .map(|f| {
202 let rel = f
203 .strip_prefix(root)
204 .unwrap_or(f)
205 .to_string_lossy()
206 .into_owned();
207 (f.clone(), rel)
208 })
209 .collect()
210}
211
212pub struct PluginRegistry {
214 plugins: Vec<Box<dyn Plugin>>,
215 external_plugins: Vec<ExternalPluginDef>,
216}
217
218pub(crate) struct RootPluginContext<'a> {
220 pub(crate) active_plugins: FxHashSet<&'a str>,
222 pub(crate) dependencies: Vec<String>,
224}
225
226impl<'a> RootPluginContext<'a> {
227 pub(crate) fn new(root_pkg: Option<&PackageJson>, active_plugins: &'a [String]) -> Self {
228 Self {
229 active_plugins: active_plugins.iter().map(String::as_str).collect(),
230 dependencies: root_pkg.map_or_else(Vec::new, PackageJson::all_dependency_names),
231 }
232 }
233}
234
235pub(crate) struct WorkspacePluginRunInput<'a> {
237 pub(crate) pkg: &'a PackageJson,
238 pub(crate) root: &'a Path,
239 pub(crate) project_root: &'a Path,
240 pub(crate) root_dependencies: &'a [String],
244 pub(crate) precompiled_config_matchers: &'a [(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
245 pub(crate) relative_files: &'a [(PathBuf, String)],
246 pub(crate) skip_config_plugins: &'a FxHashSet<&'a str>,
247 pub(crate) production_mode: bool,
248 pub(crate) candidate_index: Option<&'a ConfigCandidateIndex>,
249}
250
251struct PluginRunContext<'a> {
252 all_deps: Vec<String>,
253 active: Vec<&'a dyn Plugin>,
254}
255
256struct PluginActivationInput<'a> {
258 pkg: &'a PackageJson,
259 root: &'a Path,
260 discovered_files: &'a [PathBuf],
261 all_deps: &'a [String],
262 script_packages: &'a FxHashSet<String>,
263 candidate_index: Option<&'a ConfigCandidateIndex>,
264}
265
266#[derive(Debug, Clone, PartialEq, Eq)]
268pub struct PluginRegexValidationError {
269 plugin_name: String,
270 config_path: Option<PathBuf>,
271 rule_kind: &'static str,
272 field: &'static str,
273 rule_pattern: String,
274 regex_pattern: String,
275 source: String,
276}
277
278impl PluginRegexValidationError {
279 fn new(input: PluginRegexValidationErrorInput<'_>) -> Self {
280 Self {
281 plugin_name: input.plugin_name.to_owned(),
282 config_path: input.config_path.map(Path::to_path_buf),
283 rule_kind: input.rule_kind,
284 field: input.field,
285 rule_pattern: input.rule_pattern.to_owned(),
286 regex_pattern: input.regex_pattern.to_owned(),
287 source: input.source.to_string(),
288 }
289 }
290}
291
292#[derive(Clone, Copy)]
293struct PluginRegexValidationErrorInput<'a> {
294 plugin_name: &'a str,
295 config_path: Option<&'a Path>,
296 rule_kind: &'static str,
297 field: &'static str,
298 rule_pattern: &'a str,
299 regex_pattern: &'a str,
300 source: &'a regex::Error,
301}
302
303impl fmt::Display for PluginRegexValidationError {
304 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
305 let location = self
306 .config_path
307 .as_ref()
308 .map(|path| format!(" in {}", path.display()))
309 .unwrap_or_default();
310 write!(
311 f,
312 "plugin '{}'{}: invalid regex '{}' in {}.{} for path rule '{}': {}",
313 self.plugin_name,
314 location,
315 self.regex_pattern,
316 self.rule_kind,
317 self.field,
318 self.rule_pattern,
319 self.source
320 )
321 }
322}
323
324#[must_use]
325pub(crate) fn format_plugin_regex_errors(errors: &[PluginRegexValidationError]) -> String {
326 let joined = errors
327 .iter()
328 .map(ToString::to_string)
329 .collect::<Vec<_>>()
330 .join("\n - ");
331 format!(
332 "invalid plugin regex configuration:\n - {joined}\n\nRewrite the plugin config with Rust-compatible regex syntax, or remove unsupported constructs such as JavaScript lookahead and lookbehind."
333 )
334}
335
336#[derive(Debug, Clone, Default, PartialEq, Eq)]
344pub struct PluginToolingDependencies {
345 pub plugin: String,
347 pub dependencies: Vec<String>,
349 pub references: Vec<String>,
353 pub own_config: Option<PathBuf>,
356}
357
358#[derive(Debug, Clone, Copy, PartialEq, Eq)]
360pub enum PluginToolingEvidence<'a> {
361 OwnConfig(&'a Path),
363 Reference(&'a str),
365}
366
367impl PluginToolingDependencies {
368 #[must_use]
372 pub fn evidence<'a>(
373 &'a self,
374 script_used_packages: &FxHashSet<String>,
375 ) -> Option<PluginToolingEvidence<'a>> {
376 if let Some(config) = &self.own_config {
377 return Some(PluginToolingEvidence::OwnConfig(config));
378 }
379 self.references
380 .iter()
381 .find(|name| script_used_packages.contains(name.as_str()))
382 .map(|name| PluginToolingEvidence::Reference(name))
383 }
384}
385
386#[derive(Debug, Clone, PartialEq, Eq)]
388pub struct CheckedAliasPrefix {
389 pub scope: String,
393 pub prefix: String,
395}
396
397impl CheckedAliasPrefix {
398 #[must_use]
400 pub fn covers(&self, root: &Path, from_file: &Path, specifier: &str) -> bool {
401 specifier.starts_with(&self.prefix)
402 && (self.scope.is_empty() || from_file.starts_with(root.join(&self.scope)))
403 }
404}
405
406#[derive(Debug, Clone, Default)]
408pub struct AggregatedPluginResult {
409 pub entry_patterns: Vec<(PathRule, String)>,
411 pub replaced_entry_plugins: FxHashSet<String>,
416 pub config_entry_patterns: FxHashSet<(String, String)>,
420 pub entry_point_roles: rustc_hash::FxHashMap<String, EntryPointRole>,
422 pub config_patterns: Vec<String>,
424 pub always_used: Vec<(String, String)>,
426 pub used_exports: Vec<PluginUsedExportRule>,
428 pub config_export_credits: Vec<PluginUsedExportRule>,
436 pub used_class_members: Vec<UsedClassMemberRule>,
440 pub framework_class_member_contracts: Vec<fallow_types::semantic::SemanticFrameworkContract>,
442 pub referenced_dependencies: Vec<String>,
444 pub package_referenced_dependencies: Vec<(PathBuf, String)>,
446 pub required_dependencies: Vec<super::RequiredDependency>,
448 pub discovered_always_used: Vec<(String, String)>,
450 pub setup_files: Vec<(PathBuf, String)>,
452 pub tooling_dependencies: Vec<String>,
456 pub plugin_tooling: Vec<PluginToolingDependencies>,
460 pub script_used_packages: FxHashSet<String>,
462 pub dependency_binaries: crate::scripts::DependencyBinaries,
466 pub dev_dependency_names: FxHashSet<String>,
471 pub virtual_module_prefixes: Vec<String>,
474 pub virtual_package_suffixes: Vec<String>,
477 pub generated_import_patterns: Vec<String>,
480 pub generated_type_import_prefixes: Vec<String>,
483 pub path_aliases: Vec<(String, String)>,
486 pub scoped_path_aliases: Vec<fallow_graph::resolve::ScopedPathAlias>,
491 pub checked_alias_prefixes: Vec<CheckedAliasPrefix>,
495 pub auto_imports: Vec<AutoImportRule>,
499 pub active_plugins: Vec<String>,
501 pub fixture_patterns: Vec<(String, String)>,
503 pub scss_include_paths: Vec<PathBuf>,
508 pub static_dir_mappings: Vec<(PathBuf, String)>,
510 pub framework_static_dir_mappings: Vec<(PathBuf, String)>,
513 pub provided_dependencies: Vec<ProvidedDependencyRule>,
515 pub config_diagnostics: Vec<super::PluginConfigDiagnostic>,
519 pub federation_sources: Vec<super::FederationSource>,
522 pub jsx_import_sources: Vec<JsxImportSourceRule>,
526 pub jsx_package_credits: Vec<JsxImportSourceRule>,
531 pub tsconfig_jsx_dirs: Vec<PathBuf>,
535}
536
537fn extend_unique(target: &mut Vec<String>, incoming: Vec<String>) {
542 let mut seen: FxHashSet<String> = target.iter().cloned().collect();
543 for item in incoming {
544 if seen.insert(item.clone()) {
545 target.push(item);
546 }
547 }
548}
549
550fn push_missing<T: PartialEq>(target: &mut Vec<T>, incoming: Vec<T>) {
553 for item in incoming {
554 if !target.contains(&item) {
555 target.push(item);
556 }
557 }
558}
559
560fn prefix_if_needed(pat: &str, ws_prefix: &str) -> String {
564 if pat.starts_with(ws_prefix) || pat.starts_with('/') {
565 pat.to_string()
566 } else {
567 format!("{ws_prefix}/{pat}")
568 }
569}
570
571impl AggregatedPluginResult {
572 pub(crate) fn unique_entry_patterns(&self) -> impl Iterator<Item = &(PathRule, String)> {
578 let mut seen: FxHashSet<&(PathRule, String)> = FxHashSet::default();
579 self.entry_patterns
580 .iter()
581 .filter(move |entry| seen.insert(entry))
582 }
583
584 pub(crate) fn apply_workspace_prefix(&mut self, ws_prefix: &str) {
600 for (rule, _) in &mut self.entry_patterns {
601 *rule = rule.prefixed(ws_prefix);
602 }
603 for (pat, _) in &mut self.always_used {
604 *pat = prefix_if_needed(pat, ws_prefix);
605 }
606 for (pat, _) in &mut self.discovered_always_used {
607 *pat = prefix_if_needed(pat, ws_prefix);
608 }
609 for (pat, _) in &mut self.fixture_patterns {
610 *pat = prefix_if_needed(pat, ws_prefix);
611 }
612 for rule in &mut self.used_exports {
613 *rule = rule.prefixed(ws_prefix);
614 }
615 for rule in &mut self.config_export_credits {
616 *rule = rule.prefixed(ws_prefix);
617 }
618 for rule in &mut self.provided_dependencies {
619 *rule = rule.prefixed(ws_prefix);
620 }
621 for source in &mut self.federation_sources {
622 *source = source.prefixed(ws_prefix);
623 }
624 if !ws_prefix.is_empty() {
625 for checked in &mut self.checked_alias_prefixes {
626 checked.scope = ws_prefix.to_string();
627 }
628 self.scoped_path_aliases
629 .extend(self.path_aliases.drain(..).map(|(prefix, replacement)| {
630 fallow_graph::resolve::ScopedPathAlias {
631 scope: ws_prefix.to_string(),
632 prefix,
633 replacement: format!("{ws_prefix}/{replacement}"),
634 }
635 }));
636 }
637 }
638
639 pub(crate) fn merge_into(&mut self, other: Self) {
653 let Self {
654 entry_patterns,
655 replaced_entry_plugins: _,
657 config_entry_patterns: _,
658 entry_point_roles,
659 config_patterns,
660 always_used,
661 used_exports,
662 config_export_credits,
663 used_class_members,
664 framework_class_member_contracts,
665 referenced_dependencies,
666 package_referenced_dependencies,
667 required_dependencies,
668 discovered_always_used,
669 setup_files,
670 tooling_dependencies,
671 plugin_tooling,
672 script_used_packages,
673 dependency_binaries: _,
674 dev_dependency_names,
675 virtual_module_prefixes,
676 virtual_package_suffixes,
677 generated_import_patterns,
678 generated_type_import_prefixes,
679 path_aliases,
680 scoped_path_aliases,
681 checked_alias_prefixes,
682 auto_imports,
683 active_plugins,
684 fixture_patterns,
685 scss_include_paths,
686 static_dir_mappings,
687 framework_static_dir_mappings,
688 provided_dependencies,
689 config_diagnostics,
690 federation_sources,
691 jsx_import_sources,
692 jsx_package_credits,
693 tsconfig_jsx_dirs,
694 } = other;
695
696 self.entry_patterns.extend(entry_patterns);
697 for (plugin_name, role) in entry_point_roles {
698 self.entry_point_roles.entry(plugin_name).or_insert(role);
699 }
700 self.config_patterns.extend(config_patterns);
701 self.always_used.extend(always_used);
702 self.used_exports.extend(used_exports);
703 self.config_export_credits.extend(config_export_credits);
704 self.used_class_members.extend(used_class_members);
705 for contract in framework_class_member_contracts {
706 if !self.framework_class_member_contracts.contains(&contract) {
707 self.framework_class_member_contracts.push(contract);
708 }
709 }
710 self.referenced_dependencies.extend(referenced_dependencies);
711 self.package_referenced_dependencies
712 .extend(package_referenced_dependencies);
713 push_missing(&mut self.required_dependencies, required_dependencies);
714 self.discovered_always_used.extend(discovered_always_used);
715 self.setup_files.extend(setup_files);
716 self.tooling_dependencies.extend(tooling_dependencies);
717 self.plugin_tooling.extend(plugin_tooling);
718 self.dev_dependency_names.extend(dev_dependency_names);
719 self.script_used_packages.extend(script_used_packages);
720 extend_unique(&mut self.virtual_module_prefixes, virtual_module_prefixes);
721 extend_unique(&mut self.virtual_package_suffixes, virtual_package_suffixes);
722 extend_unique(
723 &mut self.generated_import_patterns,
724 generated_import_patterns,
725 );
726 extend_unique(
727 &mut self.generated_type_import_prefixes,
728 generated_type_import_prefixes,
729 );
730 self.path_aliases.extend(path_aliases);
731 self.scoped_path_aliases.extend(scoped_path_aliases);
732 push_missing(&mut self.checked_alias_prefixes, checked_alias_prefixes);
733 self.auto_imports.extend(auto_imports);
734 extend_unique(&mut self.active_plugins, active_plugins);
735 self.fixture_patterns.extend(fixture_patterns);
736 self.scss_include_paths.extend(scss_include_paths);
737 self.static_dir_mappings.extend(static_dir_mappings);
738 self.framework_static_dir_mappings
739 .extend(framework_static_dir_mappings);
740 self.provided_dependencies.extend(provided_dependencies);
741 self.federation_sources.extend(federation_sources);
742 push_missing(&mut self.jsx_import_sources, jsx_import_sources);
743 push_missing(&mut self.jsx_package_credits, jsx_package_credits);
744 push_missing(&mut self.tsconfig_jsx_dirs, tsconfig_jsx_dirs);
745 push_missing(&mut self.config_diagnostics, config_diagnostics);
746 }
747}
748
749impl PluginRegistry {
750 #[must_use]
752 pub fn new(external: Vec<ExternalPluginDef>) -> Self {
753 Self {
754 plugins: builtin::create_builtin_plugins(),
755 external_plugins: external,
756 }
757 }
758
759 #[must_use]
763 pub fn bun_preload_files(root: &Path) -> Vec<PathBuf> {
764 super::bun::preload_files(root)
765 }
766
767 #[must_use]
772 pub fn discovery_hidden_dirs(&self, pkg: &PackageJson, root: &Path) -> Vec<String> {
773 let all_deps = pkg.all_dependency_names();
774 let mut seen = FxHashSet::default();
775 let mut dirs = Vec::new();
776
777 for plugin in &self.plugins {
778 if !plugin.is_enabled_with_deps(&all_deps, root) {
779 continue;
780 }
781 for dir in plugin.discovery_hidden_dirs() {
782 if seen.insert(*dir) {
783 dirs.push((*dir).to_string());
784 }
785 }
786 }
787
788 dirs
789 }
790
791 #[cfg(test)]
796 fn run(
797 &self,
798 pkg: &PackageJson,
799 root: &Path,
800 discovered_files: &[PathBuf],
801 ) -> AggregatedPluginResult {
802 self.try_run(pkg, root, discovered_files)
803 .unwrap_or_else(|errors| panic!("{}", format_plugin_regex_errors(&errors)))
804 }
805
806 pub fn try_run(
808 &self,
809 pkg: &PackageJson,
810 root: &Path,
811 discovered_files: &[PathBuf],
812 ) -> Result<AggregatedPluginResult, Vec<PluginRegexValidationError>> {
813 self.try_run_with_search_roots(pkg, root, discovered_files, &[root], false, None)
814 }
815
816 #[expect(
819 clippy::too_many_arguments,
820 reason = "public PluginRegistry API; signature is part of the crate surface for embedders"
821 )]
822 pub(crate) fn try_run_with_search_roots(
823 &self,
824 pkg: &PackageJson,
825 root: &Path,
826 discovered_files: &[PathBuf],
827 config_search_roots: &[&Path],
828 production_mode: bool,
829 candidate_index: Option<&ConfigCandidateIndex>,
830 ) -> Result<AggregatedPluginResult, Vec<PluginRegexValidationError>> {
831 let _span = tracing::info_span!("run_plugins").entered();
832 let mut result = AggregatedPluginResult::default();
833 let mut regex_errors = Vec::new();
834
835 let PluginRunContext { all_deps, active } = self.prepare_plugin_run_context(
836 pkg,
837 root,
838 discovered_files,
839 production_mode,
840 candidate_index,
841 );
842
843 self.run_plugin_preflight(&active, &all_deps, root, discovered_files);
844
845 for plugin in &active {
846 process_static_patterns(*plugin, root, &mut result);
847 }
848 process_package_json_metadata(&active, pkg, root, &mut result, &mut regex_errors);
849
850 process_external_plugins(
851 &self.external_plugins,
852 &all_deps,
853 root,
854 discovered_files,
855 &mut result,
856 );
857 tooling_evidence::record_plugin_tooling(
858 &tooling_evidence::ToolingEvidenceInput {
859 active: &active,
860 external_plugins: &self.external_plugins,
861 all_deps: &all_deps,
862 roots: &[root],
863 extra_roots: if production_mode {
867 &[]
868 } else {
869 config_search_roots
870 },
871 candidate_index,
872 discovered_files,
873 },
874 &mut result,
875 );
876
877 let config_matchers = compile_config_matchers(&active);
878 let relative_files =
879 compute_relative_files(&config_matchers, &active, discovered_files, root);
880
881 resolve_plugin_config_files(&mut PluginConfigResolutionInput {
882 config_matchers: &config_matchers,
883 relative_files: &relative_files,
884 config_search_roots,
885 production_mode,
886 candidate_index,
887 root,
888 result: &mut result,
889 regex_errors: &mut regex_errors,
890 });
891
892 process_package_json_inline_configs(
893 &InlineConfigInput {
894 active: &active,
895 config_matchers: &config_matchers,
896 relative_files: &relative_files,
897 pkg,
898 root,
899 project_root: root,
900 },
901 &mut result,
902 &mut regex_errors,
903 );
904
905 if regex_errors.is_empty() {
906 Ok(result)
907 } else {
908 Err(regex_errors)
909 }
910 }
911
912 #[cfg(test)]
917 fn run_workspace_fast(&self, input: &WorkspacePluginRunInput<'_>) -> AggregatedPluginResult {
918 self.try_run_workspace_fast(input)
919 .unwrap_or_else(|errors| panic!("{}", format_plugin_regex_errors(&errors)))
920 }
921
922 pub(crate) fn try_run_workspace_fast(
929 &self,
930 input: &WorkspacePluginRunInput<'_>,
931 ) -> Result<AggregatedPluginResult, Vec<PluginRegexValidationError>> {
932 let _span = tracing::info_span!("run_plugins").entered();
933 let mut result = AggregatedPluginResult::default();
934 let mut regex_errors = Vec::new();
935
936 let (all_deps, script_packages) = workspace_activation_deps(input);
937 let workspace_files: Vec<PathBuf> = input
938 .relative_files
939 .iter()
940 .map(|(abs_path, _)| abs_path.clone())
941 .collect();
942
943 let active = self.collect_active_plugins(&PluginActivationInput {
944 pkg: input.pkg,
945 root: input.root,
946 discovered_files: &workspace_files,
947 all_deps: &all_deps,
948 script_packages: &script_packages,
949 candidate_index: input.candidate_index,
950 });
951
952 log_active_plugins(&active);
953
954 self.emit_silent_fail_diagnostics(&active, &all_deps, input.root, &workspace_files);
955
956 process_external_plugins(
957 &self.external_plugins,
958 &all_deps,
959 input.root,
960 &workspace_files,
961 &mut result,
962 );
963
964 if active.is_empty() && result.active_plugins.is_empty() {
965 return Ok(result);
966 }
967
968 process_workspace_active_plugins(&active, input, &mut result, &mut regex_errors);
969 let evidence_roots: &[&Path] = if input.root == input.project_root {
971 &[input.root]
972 } else {
973 &[input.root, input.project_root]
974 };
975 tooling_evidence::record_plugin_tooling(
976 &tooling_evidence::ToolingEvidenceInput {
977 active: &active,
978 external_plugins: &self.external_plugins,
979 all_deps: &all_deps,
980 roots: evidence_roots,
981 extra_roots: &[],
982 candidate_index: input.candidate_index,
983 discovered_files: &workspace_files,
984 },
985 &mut result,
986 );
987 resolve_workspace_plugin_configs(&active, input, &mut result, &mut regex_errors);
988 if input.root != input.project_root {
990 process_package_json_inline_configs(
991 &InlineConfigInput {
992 active: &active,
993 config_matchers: input.precompiled_config_matchers,
994 relative_files: input.relative_files,
995 pkg: input.pkg,
996 root: input.root,
997 project_root: input.project_root,
998 },
999 &mut result,
1000 &mut regex_errors,
1001 );
1002 }
1003
1004 if regex_errors.is_empty() {
1005 Ok(result)
1006 } else {
1007 Err(regex_errors)
1008 }
1009 }
1010
1011 #[must_use]
1014 pub(crate) fn precompile_config_matchers(
1015 &self,
1016 ) -> Vec<(&dyn Plugin, Vec<globset::GlobMatcher>)> {
1017 self.plugins
1018 .iter()
1019 .filter(|p| !p.config_patterns().is_empty())
1020 .map(|p| (p.as_ref(), cached_plugin_config_matchers(p.as_ref())))
1021 .collect()
1022 }
1023
1024 pub(crate) fn resolve_script_config_files(
1035 &self,
1036 config_files: &[scripts::BinaryConfigFile],
1037 package_root: &Path,
1038 project_root: &Path,
1039 ws_prefix: &str,
1040 ) -> AggregatedPluginResult {
1041 let mut aggregated = AggregatedPluginResult::default();
1042 for config_file in config_files {
1043 let Some(rel_path) =
1044 scripts::normalize_script_entry_pattern(ws_prefix, &config_file.path)
1045 else {
1046 continue;
1047 };
1048 let abs_path = package_root.join(config_file.path.trim_start_matches("./"));
1049 let in_package_root = abs_path.parent() == Some(package_root);
1054 for plugin in &self.plugins {
1055 let plugin = plugin.as_ref();
1056 if !plugin
1057 .script_config_binaries()
1058 .contains(&config_file.binary.as_str())
1059 || (in_package_root
1060 && cached_plugin_config_matchers(plugin)
1061 .iter()
1062 .any(|m| m.is_match(rel_path.as_str())))
1063 {
1064 continue;
1065 }
1066 if !super::config_parser::is_inside_root(&abs_path, project_root) {
1067 continue;
1068 }
1069 let Ok(source) = std::fs::read_to_string(&abs_path) else {
1070 continue;
1071 };
1072 let mut file_result = AggregatedPluginResult::default();
1073 file_result
1074 .entry_point_roles
1075 .insert(plugin.name().to_string(), plugin.entry_point_role());
1076 let plugin_result =
1077 plugin.resolve_script_config(&abs_path, &source, package_root, project_root);
1078 if let Err(errors) = process_config_result(
1079 plugin.name(),
1080 plugin_result,
1081 &mut file_result,
1082 Some(&abs_path),
1083 ) {
1084 for error in errors {
1085 tracing::warn!("{error}");
1086 }
1087 continue;
1088 }
1089 if !ws_prefix.is_empty() {
1090 file_result.apply_workspace_prefix(ws_prefix);
1091 }
1092 file_result.used_exports.push(PluginUsedExportRule::new(
1094 plugin.name().to_string(),
1095 super::UsedExportRule::new(rel_path.clone(), ["default"]),
1096 ));
1097 aggregated.merge_into(file_result);
1098 }
1099 }
1100 aggregated
1101 }
1102}
1103
1104fn process_workspace_active_plugins(
1105 active: &[&dyn Plugin],
1106 input: &WorkspacePluginRunInput<'_>,
1107 result: &mut AggregatedPluginResult,
1108 regex_errors: &mut Vec<PluginRegexValidationError>,
1109) {
1110 for plugin in active {
1111 process_static_patterns(*plugin, input.root, result);
1112 }
1113 process_package_json_metadata(active, input.pkg, input.root, result, regex_errors);
1114}
1115
1116fn resolve_workspace_plugin_configs(
1117 active: &[&dyn Plugin],
1118 input: &WorkspacePluginRunInput<'_>,
1119 result: &mut AggregatedPluginResult,
1120 regex_errors: &mut Vec<PluginRegexValidationError>,
1121) {
1122 let workspace_matchers = select_workspace_matchers(
1123 input.precompiled_config_matchers,
1124 active,
1125 input.skip_config_plugins,
1126 );
1127
1128 let mut resolved_ws_plugins: FxHashSet<&str> = FxHashSet::default();
1129 for (plugin, matchers) in &workspace_matchers {
1130 resolve_plugin_matching_files(&mut PluginMatchingFilesInput {
1131 plugin: *plugin,
1132 matchers,
1133 relative_files: input.relative_files,
1134 root: input.root,
1135 project_root: input.project_root,
1136 result,
1137 regex_errors,
1138 resolved_plugins: &mut resolved_ws_plugins,
1139 });
1140 }
1141
1142 load_workspace_filesystem_configs(&mut WorkspaceFsConfigInput {
1143 workspace_matchers: &workspace_matchers,
1144 resolved_ws_plugins: &resolved_ws_plugins,
1145 root: input.root,
1146 project_root: input.project_root,
1147 production_mode: input.production_mode,
1148 candidate_index: input.candidate_index,
1149 result,
1150 regex_errors,
1151 });
1152}
1153
1154impl Default for PluginRegistry {
1155 fn default() -> Self {
1156 Self::new(vec![])
1157 }
1158}
1159
1160impl PluginRegistry {
1161 fn prepare_plugin_run_context<'a>(
1162 &'a self,
1163 pkg: &PackageJson,
1164 root: &Path,
1165 discovered_files: &[PathBuf],
1166 production_mode: bool,
1167 candidate_index: Option<&ConfigCandidateIndex>,
1168 ) -> PluginRunContext<'a> {
1169 let all_deps = pkg.all_dependency_names();
1170 let script_packages =
1171 script_activation_packages(pkg, root, &[root], &all_deps, production_mode);
1172 let active = self.collect_active_plugins(&PluginActivationInput {
1173 pkg,
1174 root,
1175 discovered_files,
1176 all_deps: &all_deps,
1177 script_packages: &script_packages,
1178 candidate_index,
1179 });
1180
1181 PluginRunContext { all_deps, active }
1182 }
1183
1184 fn run_plugin_preflight(
1185 &self,
1186 active: &[&dyn Plugin],
1187 all_deps: &[String],
1188 root: &Path,
1189 discovered_files: &[PathBuf],
1190 ) {
1191 log_active_plugins(active);
1192 check_meta_framework_prerequisites(active, root);
1193 self.emit_silent_fail_diagnostics(active, all_deps, root, discovered_files);
1194 }
1195
1196 fn collect_active_plugins<'a>(
1199 &'a self,
1200 activation: &PluginActivationInput<'_>,
1201 ) -> Vec<&'a dyn Plugin> {
1202 self.plugins
1203 .iter()
1204 .filter(|p| {
1205 p.is_enabled_with_files(
1206 activation.all_deps,
1207 activation.root,
1208 activation.discovered_files,
1209 activation.candidate_index,
1210 ) || p.is_enabled_with_scripts(activation.script_packages, activation.root)
1211 || p.is_enabled_with_package_json(activation.pkg, activation.root)
1212 })
1213 .map(AsRef::as_ref)
1214 .collect()
1215 }
1216
1217 fn emit_silent_fail_diagnostics(
1226 &self,
1227 active: &[&dyn Plugin],
1228 all_deps: &[String],
1229 root: &Path,
1230 discovered_files: &[PathBuf],
1231 ) {
1232 let active_external: Vec<&ExternalPluginDef> = self
1233 .external_plugins
1234 .iter()
1235 .filter(|ext| is_external_plugin_active(ext, all_deps, root, discovered_files))
1236 .collect();
1237 let mut diagnostics = detect_pattern_collisions(active, &active_external);
1238 diagnostics.extend(detect_enabler_typos(&self.external_plugins, all_deps));
1239 emit_plugin_diagnostics(&diagnostics);
1240 }
1241}
1242
1243fn plugin_warn_dedupe() -> &'static std::sync::Mutex<FxHashSet<String>> {
1250 static WARNED: std::sync::OnceLock<std::sync::Mutex<FxHashSet<String>>> =
1251 std::sync::OnceLock::new();
1252 WARNED.get_or_init(|| std::sync::Mutex::new(FxHashSet::default()))
1253}
1254
1255struct PluginConfigResolutionInput<'a> {
1256 config_matchers: &'a [(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
1257 relative_files: &'a [(PathBuf, String)],
1258 config_search_roots: &'a [&'a Path],
1259 production_mode: bool,
1260 candidate_index: Option<&'a ConfigCandidateIndex>,
1261 root: &'a Path,
1262 result: &'a mut AggregatedPluginResult,
1263 regex_errors: &'a mut Vec<PluginRegexValidationError>,
1264}
1265
1266fn select_workspace_matchers<'a>(
1269 precompiled_config_matchers: &[(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
1270 active: &[&dyn Plugin],
1271 skip_config_plugins: &FxHashSet<&str>,
1272) -> Vec<(&'a dyn Plugin, Vec<globset::GlobMatcher>)> {
1273 let active_names: FxHashSet<&str> = active.iter().map(|p| p.name()).collect();
1274 precompiled_config_matchers
1275 .iter()
1276 .filter(|(p, _)| {
1277 active_names.contains(p.name())
1278 && (!skip_config_plugins.contains(p.name())
1279 || must_parse_workspace_config_when_root_active(p.name()))
1280 })
1281 .map(|(plugin, matchers)| (*plugin, matchers.clone()))
1282 .collect()
1283}
1284
1285struct WorkspaceFsConfigInput<'a> {
1286 workspace_matchers: &'a [(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
1287 resolved_ws_plugins: &'a FxHashSet<&'a str>,
1288 root: &'a Path,
1289 project_root: &'a Path,
1290 production_mode: bool,
1291 candidate_index: Option<&'a ConfigCandidateIndex>,
1292 result: &'a mut AggregatedPluginResult,
1293 regex_errors: &'a mut Vec<PluginRegexValidationError>,
1294}
1295
1296fn load_workspace_filesystem_configs(input: &mut WorkspaceFsConfigInput<'_>) {
1299 let search_roots: &[&Path] = if input.root == input.project_root {
1300 &[input.root]
1301 } else {
1302 &[input.root, input.project_root]
1303 };
1304 let ws_json_configs = discover_config_files(
1305 input.workspace_matchers,
1306 input.resolved_ws_plugins,
1307 search_roots,
1308 input.production_mode,
1309 input.candidate_index,
1310 );
1311 for (abs_path, plugin) in &ws_json_configs {
1312 let Ok(source) = std::fs::read_to_string(abs_path) else {
1313 continue;
1314 };
1315 let plugin_result =
1316 plugin.resolve_config_in_project(abs_path, &source, input.root, input.project_root);
1317 if plugin_result.is_empty() {
1318 continue;
1319 }
1320 let rel = abs_path
1321 .strip_prefix(input.project_root)
1322 .map(|p| p.to_string_lossy())
1323 .unwrap_or_default();
1324 tracing::debug!(
1325 plugin = plugin.name(),
1326 config = %rel,
1327 entries = plugin_result.entry_patterns.len(),
1328 deps = plugin_result.referenced_dependencies.len(),
1329 "resolved config (workspace filesystem fallback)"
1330 );
1331 if let Err(mut errors) =
1332 process_config_result(plugin.name(), plugin_result, input.result, Some(abs_path))
1333 {
1334 input.regex_errors.append(&mut errors);
1335 }
1336 }
1337}
1338
1339fn resolve_plugin_config_files(input: &mut PluginConfigResolutionInput<'_>) {
1340 if input.config_matchers.is_empty() {
1341 return;
1342 }
1343
1344 let mut resolved_plugins: FxHashSet<&str> = FxHashSet::default();
1345 for (plugin, matchers) in input.config_matchers {
1346 resolve_plugin_matching_files(&mut PluginMatchingFilesInput {
1347 plugin: *plugin,
1348 matchers,
1349 relative_files: input.relative_files,
1350 root: input.root,
1351 project_root: input.root,
1352 result: input.result,
1353 regex_errors: input.regex_errors,
1354 resolved_plugins: &mut resolved_plugins,
1355 });
1356 }
1357
1358 let json_configs = discover_config_files(
1359 input.config_matchers,
1360 &resolved_plugins,
1361 input.config_search_roots,
1362 input.production_mode,
1363 input.candidate_index,
1364 );
1365 for (abs_path, plugin) in &json_configs {
1366 resolve_plugin_filesystem_config(
1367 *plugin,
1368 abs_path,
1369 input.root,
1370 input.result,
1371 input.regex_errors,
1372 );
1373 }
1374}
1375
1376struct PluginMatchingFilesInput<'plugins, 'data, 'state> {
1377 plugin: &'plugins dyn Plugin,
1378 matchers: &'data [globset::GlobMatcher],
1379 relative_files: &'data [(PathBuf, String)],
1380 root: &'data Path,
1381 project_root: &'data Path,
1382 result: &'state mut AggregatedPluginResult,
1383 regex_errors: &'state mut Vec<PluginRegexValidationError>,
1384 resolved_plugins: &'state mut FxHashSet<&'plugins str>,
1385}
1386
1387fn resolve_plugin_matching_files(input: &mut PluginMatchingFilesInput<'_, '_, '_>) {
1388 use rayon::prelude::*;
1389
1390 let plugin_hits: Vec<&PathBuf> = input
1391 .relative_files
1392 .par_iter()
1393 .filter_map(|(abs_path, rel_path)| {
1394 input
1395 .matchers
1396 .iter()
1397 .any(|m| m.is_match(rel_path.as_str()))
1398 .then_some(abs_path)
1399 })
1400 .collect();
1401 for abs_path in plugin_hits {
1402 let Ok(source) = std::fs::read_to_string(abs_path) else {
1403 continue;
1404 };
1405 let plugin_result = input.plugin.resolve_config_in_project(
1406 abs_path,
1407 &source,
1408 input.root,
1409 input.project_root,
1410 );
1411 if plugin_result.is_empty() {
1412 continue;
1413 }
1414 input.resolved_plugins.insert(input.plugin.name());
1415 process_resolved_plugin_config(ResolvedPluginConfigInput {
1416 plugin: input.plugin,
1417 abs_path,
1418 plugin_result,
1419 result: input.result,
1420 regex_errors: input.regex_errors,
1421 message: "resolved config",
1422 config_display: abs_path.display(),
1423 });
1424 }
1425}
1426
1427fn resolve_plugin_filesystem_config(
1428 plugin: &dyn Plugin,
1429 abs_path: &Path,
1430 root: &Path,
1431 result: &mut AggregatedPluginResult,
1432 regex_errors: &mut Vec<PluginRegexValidationError>,
1433) {
1434 let Ok(source) = std::fs::read_to_string(abs_path) else {
1435 return;
1436 };
1437 let plugin_result = plugin.resolve_config(abs_path, &source, root);
1438 if plugin_result.is_empty() {
1439 return;
1440 }
1441 let rel = abs_path
1442 .strip_prefix(root)
1443 .map(|p| p.to_string_lossy())
1444 .unwrap_or_default();
1445 process_resolved_plugin_config(ResolvedPluginConfigInput {
1446 plugin,
1447 abs_path,
1448 plugin_result,
1449 result,
1450 regex_errors,
1451 message: "resolved config (filesystem fallback)",
1452 config_display: rel,
1453 });
1454}
1455
1456struct ResolvedPluginConfigInput<'a, D> {
1457 plugin: &'a dyn Plugin,
1458 abs_path: &'a Path,
1459 plugin_result: PluginResult,
1460 result: &'a mut AggregatedPluginResult,
1461 regex_errors: &'a mut Vec<PluginRegexValidationError>,
1462 message: &'static str,
1463 config_display: D,
1464}
1465
1466fn process_resolved_plugin_config(input: ResolvedPluginConfigInput<'_, impl std::fmt::Display>) {
1467 tracing::debug!(
1468 plugin = input.plugin.name(),
1469 config = %input.config_display,
1470 entries = input.plugin_result.entry_patterns.len(),
1471 deps = input.plugin_result.referenced_dependencies.len(),
1472 input.message
1473 );
1474 if let Err(mut errors) = process_config_result(
1475 input.plugin.name(),
1476 input.plugin_result,
1477 input.result,
1478 Some(input.abs_path),
1479 ) {
1480 input.regex_errors.append(&mut errors);
1481 }
1482}
1483
1484fn should_warn(key: String) -> bool {
1488 plugin_warn_dedupe()
1489 .lock()
1490 .map_or(true, |mut set| set.insert(key))
1491}
1492
1493#[derive(Debug, Clone, PartialEq, Eq)]
1500enum PluginDiagnostic {
1501 PatternCollision {
1503 pattern: String,
1504 owners: Vec<String>,
1505 },
1506 EnablerTypo {
1509 plugin: String,
1510 enabler: String,
1511 suggestion: String,
1512 },
1513}
1514
1515fn detect_pattern_collisions(
1541 builtin_active: &[&dyn Plugin],
1542 external_active: &[&ExternalPluginDef],
1543) -> Vec<PluginDiagnostic> {
1544 use rustc_hash::FxHashMap;
1545
1546 let mut pattern_owners: FxHashMap<String, (Vec<String>, FxHashSet<String>)> =
1547 FxHashMap::default();
1548
1549 let record = |pattern_owners: &mut FxHashMap<_, (Vec<String>, FxHashSet<String>)>,
1550 pattern: String,
1551 name: String| {
1552 let (list, seen) = pattern_owners.entry(pattern).or_default();
1553 if seen.insert(name.clone()) {
1554 list.push(name);
1555 }
1556 };
1557
1558 for plugin in builtin_active {
1559 for pat in plugin.config_patterns() {
1560 record(
1561 &mut pattern_owners,
1562 (*pat).to_string(),
1563 plugin.name().to_string(),
1564 );
1565 }
1566 }
1567 for ext in external_active {
1568 for pat in &ext.config_patterns {
1569 record(&mut pattern_owners, pat.clone(), ext.name.clone());
1570 }
1571 }
1572
1573 let builtin_names: FxHashSet<&str> = builtin_active.iter().map(|p| p.name()).collect();
1580
1581 let mut findings: Vec<PluginDiagnostic> = pattern_owners
1582 .into_iter()
1583 .filter_map(|(pattern, (owners, _seen))| {
1584 if owners.len() < 2 || owners.iter().all(|o| builtin_names.contains(o.as_str())) {
1585 None
1586 } else {
1587 Some(PluginDiagnostic::PatternCollision { pattern, owners })
1588 }
1589 })
1590 .collect();
1591 findings.sort_unstable_by(|a, b| match (a, b) {
1592 (
1593 PluginDiagnostic::PatternCollision { pattern: ap, .. },
1594 PluginDiagnostic::PatternCollision { pattern: bp, .. },
1595 ) => ap.cmp(bp),
1596 _ => std::cmp::Ordering::Equal,
1597 });
1598 findings
1599}
1600
1601fn detect_enabler_typos(
1616 external_plugins: &[ExternalPluginDef],
1617 all_deps: &[String],
1618) -> Vec<PluginDiagnostic> {
1619 let mut findings = Vec::new();
1620
1621 for ext in external_plugins {
1622 if ext.detection.is_some() || ext.enablers.is_empty() {
1623 continue;
1624 }
1625
1626 let any_match = ext.enablers.iter().any(|enabler| {
1627 if enabler.ends_with('/') {
1628 all_deps.iter().any(|d| d.starts_with(enabler))
1629 } else {
1630 all_deps.iter().any(|d| d == enabler)
1631 }
1632 });
1633 if any_match {
1634 continue;
1635 }
1636
1637 for enabler in &ext.enablers {
1638 let candidates = all_deps.iter().map(String::as_str);
1639 let Some(suggestion) = fallow_config::levenshtein::closest_match(enabler, candidates)
1640 else {
1641 continue;
1642 };
1643
1644 findings.push(PluginDiagnostic::EnablerTypo {
1645 plugin: ext.name.clone(),
1646 enabler: enabler.clone(),
1647 suggestion: suggestion.to_string(),
1648 });
1649 }
1650 }
1651
1652 findings
1653}
1654
1655fn emit_plugin_diagnostics(findings: &[PluginDiagnostic]) {
1658 for finding in findings {
1659 match finding {
1660 PluginDiagnostic::PatternCollision { pattern, owners } => {
1661 let key = format!("collision::{pattern}::{owners:?}");
1662 if !should_warn(key) {
1663 continue;
1664 }
1665 let winner = &owners[0];
1666 let others = owners[1..].join(", ");
1667 tracing::warn!(
1668 "plugin config_patterns collision: identical pattern \
1669 '{pattern}' is claimed by plugins [{joined}]; '{winner}' \
1670 runs first (registration order), others ({others}) \
1671 follow. Rename one of the patterns or remove the \
1672 duplicate plugin to make resolution explicit. A future \
1673 release may reject identical-pattern collisions.",
1674 joined = owners.join(", "),
1675 );
1676 }
1677 PluginDiagnostic::EnablerTypo {
1678 plugin,
1679 enabler,
1680 suggestion,
1681 } => {
1682 let key = format!("enabler::{plugin}::{enabler}");
1683 if !should_warn(key) {
1684 continue;
1685 }
1686 tracing::warn!(
1687 "plugin '{plugin}' enabler '{enabler}' does not match any \
1688 dependency in package.json; did you mean '{suggestion}'? \
1689 The plugin will not activate. A future release may reject \
1690 unmatched enablers.",
1691 );
1692 }
1693 }
1694 }
1695}
1696
1697fn process_package_json_inline_configs(
1709 input: &InlineConfigInput<'_>,
1710 result: &mut AggregatedPluginResult,
1711 regex_errors: &mut Vec<PluginRegexValidationError>,
1712) {
1713 let pkg_path = input.root.join("package.json");
1714 let credited_manifests: Vec<PathBuf> = if input.root == input.project_root {
1715 Vec::new()
1716 } else {
1717 input
1718 .root
1719 .ancestors()
1720 .take_while(|dir| dir.starts_with(input.project_root))
1721 .map(|dir| dir.join("package.json"))
1722 .collect()
1723 };
1724 for plugin in input.active {
1725 let Some(key) = plugin.package_json_config_key() else {
1726 continue;
1727 };
1728 let Some(config_value) = input.pkg.inline_tool_config(key) else {
1729 continue;
1730 };
1731 if check_has_config_file(*plugin, input.config_matchers, input.relative_files) {
1732 continue;
1733 }
1734 let config_json = serde_json::to_string(config_value).unwrap_or_default();
1735 let fake_path = input.root.join(format!("{key}.config.json"));
1736 let mut plugin_result = plugin.resolve_config_in_project(
1737 &fake_path,
1738 &config_json,
1739 input.root,
1740 input.project_root,
1741 );
1742 if plugin_result.is_empty() {
1743 continue;
1744 }
1745 tracing::debug!(
1746 plugin = plugin.name(),
1747 key = key,
1748 "resolved inline package.json config"
1749 );
1750 if !credited_manifests.is_empty() {
1751 for dep in std::mem::take(&mut plugin_result.referenced_dependencies) {
1752 plugin_result.package_referenced_dependencies.extend(
1753 credited_manifests
1754 .iter()
1755 .map(|manifest| (manifest.clone(), dep.clone())),
1756 );
1757 }
1758 }
1759 if let Err(mut errors) =
1760 process_config_result(plugin.name(), plugin_result, result, Some(&pkg_path))
1761 {
1762 regex_errors.append(&mut errors);
1763 }
1764 }
1765}
1766
1767struct InlineConfigInput<'a> {
1769 active: &'a [&'a dyn Plugin],
1770 config_matchers: &'a [(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
1771 relative_files: &'a [(PathBuf, String)],
1772 pkg: &'a PackageJson,
1773 root: &'a Path,
1774 project_root: &'a Path,
1775}
1776
1777#[derive(Debug)]
1780struct MetaFrameworkWarning {
1781 dedupe_key: &'static str,
1782 message: &'static str,
1783}
1784
1785fn missing_meta_framework_prerequisites(
1795 active_plugins: &[&dyn Plugin],
1796 root: &Path,
1797) -> Vec<MetaFrameworkWarning> {
1798 active_plugins
1799 .iter()
1800 .filter_map(|plugin| match plugin.name() {
1801 "nuxt" if !root.join(".nuxt/tsconfig.json").exists() => Some(MetaFrameworkWarning {
1802 dedupe_key: "meta-prereq::nuxt",
1803 message: "Nuxt project missing .nuxt/tsconfig.json: run `nuxt prepare` \
1804 before fallow for accurate analysis",
1805 }),
1806 "astro" if !root.join(".astro").exists() => Some(MetaFrameworkWarning {
1807 dedupe_key: "meta-prereq::astro",
1808 message: "Astro project missing .astro/ types: run `astro sync` \
1809 before fallow for accurate analysis",
1810 }),
1811 _ => None,
1812 })
1813 .collect()
1814}
1815
1816fn check_meta_framework_prerequisites(active_plugins: &[&dyn Plugin], root: &Path) {
1826 for warning in missing_meta_framework_prerequisites(active_plugins, root) {
1827 if should_warn(warning.dedupe_key.to_owned()) {
1828 tracing::warn!("{}", warning.message);
1829 }
1830 }
1831}
1832
1833fn workspace_activation_deps(
1842 input: &WorkspacePluginRunInput<'_>,
1843) -> (Vec<String>, FxHashSet<String>) {
1844 let mut deps = input.pkg.all_dependency_names();
1845 let own: FxHashSet<&str> = deps.iter().map(String::as_str).collect();
1846 let hoisted: Vec<String> = input
1847 .root_dependencies
1848 .iter()
1849 .filter(|dep| !own.contains(dep.as_str()))
1850 .cloned()
1851 .collect();
1852 let mut script_deps = deps.clone();
1853 script_deps.extend(hoisted.iter().cloned());
1854 let script_packages = script_activation_packages(
1855 input.pkg,
1856 input.root,
1857 &[input.root, input.project_root],
1858 &script_deps,
1859 input.production_mode,
1860 );
1861 deps.extend(
1862 hoisted
1863 .into_iter()
1864 .filter(|dep| script_packages.contains(dep)),
1865 );
1866 (deps, script_packages)
1867}
1868
1869fn script_activation_packages(
1872 pkg: &PackageJson,
1873 root: &Path,
1874 node_modules_roots: &[&Path],
1875 all_deps: &[String],
1876 production_mode: bool,
1877) -> FxHashSet<String> {
1878 let Some(pkg_scripts) = pkg.scripts.as_ref() else {
1879 return FxHashSet::default();
1880 };
1881
1882 let scripts_to_analyze = if production_mode {
1883 scripts::filter_production_scripts(pkg_scripts)
1884 } else {
1885 pkg_scripts.clone()
1886 };
1887
1888 let mut nm_roots: Vec<&Path> = Vec::new();
1889 for nm_root in node_modules_roots {
1890 if !nm_roots.contains(nm_root) && nm_root.join("node_modules").is_dir() {
1891 nm_roots.push(nm_root);
1892 }
1893 }
1894 let bin_map = scripts::build_bin_to_package_map(&nm_roots, all_deps);
1895 let dep_set: FxHashSet<String> = all_deps.iter().cloned().collect();
1896 let catalog =
1897 scripts::ScriptCatalog::from_scripts_with_bodies(pkg_scripts, &scripts_to_analyze);
1898
1899 scripts::analyze_scripts_with_dependency_context(
1900 &scripts_to_analyze,
1901 root,
1902 &bin_map,
1903 &dep_set,
1904 &catalog,
1905 scripts::IgnoredCommandEntries::NONE,
1906 )
1907 .used_packages
1908}
1909
1910#[cfg(test)]
1911mod entry_pattern_tests;
1912#[cfg(test)]
1913mod tests;