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 fixture_patterns: Vec<(String, String)>,
517 pub scss_include_paths: Vec<PathBuf>,
522 pub static_dir_mappings: Vec<(PathBuf, String)>,
524 pub framework_static_dir_mappings: Vec<(PathBuf, String)>,
527 pub provided_dependencies: Vec<ProvidedDependencyRule>,
529 pub config_diagnostics: Vec<super::PluginConfigDiagnostic>,
533 pub federation_sources: Vec<super::FederationSource>,
536 pub jsx_import_sources: Vec<JsxImportSourceRule>,
540 pub jsx_package_credits: Vec<JsxImportSourceRule>,
545 pub tsconfig_jsx_dirs: Vec<PathBuf>,
549}
550
551fn extend_unique(target: &mut Vec<String>, incoming: Vec<String>) {
556 let mut seen: FxHashSet<String> = target.iter().cloned().collect();
557 for item in incoming {
558 if seen.insert(item.clone()) {
559 target.push(item);
560 }
561 }
562}
563
564fn push_missing<T: PartialEq>(target: &mut Vec<T>, incoming: Vec<T>) {
567 for item in incoming {
568 if !target.contains(&item) {
569 target.push(item);
570 }
571 }
572}
573
574fn prefix_if_needed(pat: &str, ws_prefix: &str) -> String {
578 if pat.starts_with(ws_prefix) || pat.starts_with('/') {
579 pat.to_string()
580 } else {
581 format!("{ws_prefix}/{pat}")
582 }
583}
584
585impl AggregatedPluginResult {
586 pub(crate) fn unique_entry_patterns(&self) -> impl Iterator<Item = &(PathRule, String)> {
592 let mut seen: FxHashSet<&(PathRule, String)> = FxHashSet::default();
593 self.entry_patterns
594 .iter()
595 .filter(move |entry| seen.insert(entry))
596 }
597
598 pub(crate) fn apply_workspace_prefix(&mut self, ws_prefix: &str) {
614 for (rule, _) in &mut self.entry_patterns {
615 *rule = rule.prefixed(ws_prefix);
616 }
617 for (pat, _) in &mut self.always_used {
618 *pat = prefix_if_needed(pat, ws_prefix);
619 }
620 for (pat, _) in &mut self.discovered_always_used {
621 *pat = prefix_if_needed(pat, ws_prefix);
622 }
623 for (pat, _) in &mut self.fixture_patterns {
624 *pat = prefix_if_needed(pat, ws_prefix);
625 }
626 for rule in &mut self.used_exports {
627 *rule = rule.prefixed(ws_prefix);
628 }
629 for rule in &mut self.config_export_credits {
630 *rule = rule.prefixed(ws_prefix);
631 }
632 for rule in &mut self.provided_dependencies {
633 *rule = rule.prefixed(ws_prefix);
634 }
635 for source in &mut self.federation_sources {
636 *source = source.prefixed(ws_prefix);
637 }
638 if !ws_prefix.is_empty() {
639 for checked in &mut self.checked_alias_prefixes {
640 checked.scope = ws_prefix.to_string();
641 }
642 self.scoped_path_aliases
643 .extend(self.path_aliases.drain(..).map(|(prefix, replacement)| {
644 fallow_graph::resolve::ScopedPathAlias {
645 scope: ws_prefix.to_string(),
646 prefix,
647 replacement: format!("{ws_prefix}/{replacement}"),
648 }
649 }));
650 }
651 }
652
653 pub(crate) fn merge_into(&mut self, other: Self) {
667 let Self {
668 entry_patterns,
669 replaced_entry_plugins: _,
671 config_entry_patterns: _,
672 entry_point_roles,
673 config_patterns,
674 always_used,
675 used_exports,
676 config_export_credits,
677 used_class_members,
678 framework_class_member_contracts,
679 referenced_dependencies,
680 package_referenced_dependencies,
681 required_dependencies,
682 discovered_always_used,
683 setup_files,
684 tooling_dependencies,
685 plugin_tooling,
686 script_used_packages,
687 dependency_binaries: _,
688 dev_dependency_names,
689 virtual_module_prefixes,
690 virtual_package_suffixes,
691 generated_import_patterns,
692 generated_type_import_prefixes,
693 path_aliases,
694 scoped_path_aliases,
695 checked_alias_prefixes,
696 auto_imports,
697 active_plugins,
698 fixture_patterns,
699 scss_include_paths,
700 static_dir_mappings,
701 framework_static_dir_mappings,
702 provided_dependencies,
703 config_diagnostics,
704 federation_sources,
705 jsx_import_sources,
706 jsx_package_credits,
707 tsconfig_jsx_dirs,
708 } = other;
709
710 self.entry_patterns.extend(entry_patterns);
711 for (plugin_name, role) in entry_point_roles {
712 self.entry_point_roles.entry(plugin_name).or_insert(role);
713 }
714 self.config_patterns.extend(config_patterns);
715 self.always_used.extend(always_used);
716 self.used_exports.extend(used_exports);
717 self.config_export_credits.extend(config_export_credits);
718 self.used_class_members.extend(used_class_members);
719 for contract in framework_class_member_contracts {
720 if !self.framework_class_member_contracts.contains(&contract) {
721 self.framework_class_member_contracts.push(contract);
722 }
723 }
724 self.referenced_dependencies.extend(referenced_dependencies);
725 self.package_referenced_dependencies
726 .extend(package_referenced_dependencies);
727 push_missing(&mut self.required_dependencies, required_dependencies);
728 self.discovered_always_used.extend(discovered_always_used);
729 self.setup_files.extend(setup_files);
730 self.tooling_dependencies.extend(tooling_dependencies);
731 self.plugin_tooling.extend(plugin_tooling);
732 self.dev_dependency_names.extend(dev_dependency_names);
733 self.script_used_packages.extend(script_used_packages);
734 extend_unique(&mut self.virtual_module_prefixes, virtual_module_prefixes);
735 extend_unique(&mut self.virtual_package_suffixes, virtual_package_suffixes);
736 extend_unique(
737 &mut self.generated_import_patterns,
738 generated_import_patterns,
739 );
740 extend_unique(
741 &mut self.generated_type_import_prefixes,
742 generated_type_import_prefixes,
743 );
744 self.path_aliases.extend(path_aliases);
745 self.scoped_path_aliases.extend(scoped_path_aliases);
746 push_missing(&mut self.checked_alias_prefixes, checked_alias_prefixes);
747 self.auto_imports.extend(auto_imports);
748 extend_unique(&mut self.active_plugins, active_plugins);
749 self.fixture_patterns.extend(fixture_patterns);
750 self.scss_include_paths.extend(scss_include_paths);
751 self.static_dir_mappings.extend(static_dir_mappings);
752 self.framework_static_dir_mappings
753 .extend(framework_static_dir_mappings);
754 self.provided_dependencies.extend(provided_dependencies);
755 self.federation_sources.extend(federation_sources);
756 push_missing(&mut self.jsx_import_sources, jsx_import_sources);
757 push_missing(&mut self.jsx_package_credits, jsx_package_credits);
758 push_missing(&mut self.tsconfig_jsx_dirs, tsconfig_jsx_dirs);
759 push_missing(&mut self.config_diagnostics, config_diagnostics);
760 }
761}
762
763impl PluginRegistry {
764 #[must_use]
766 pub fn new(external: Vec<ExternalPluginDef>) -> Self {
767 Self {
768 plugins: builtin::create_builtin_plugins(),
769 external_plugins: external,
770 }
771 }
772
773 #[must_use]
777 pub fn bun_preload_files(root: &Path) -> Vec<PathBuf> {
778 super::bun::preload_files(root)
779 }
780
781 #[must_use]
786 pub fn discovery_hidden_dirs(&self, pkg: &PackageJson, root: &Path) -> Vec<String> {
787 let all_deps = pkg.all_dependency_names();
788 let mut seen = FxHashSet::default();
789 let mut dirs = Vec::new();
790
791 for plugin in &self.plugins {
792 if !plugin.is_enabled_with_deps(&all_deps, root) {
793 continue;
794 }
795 for dir in plugin.discovery_hidden_dirs() {
796 if seen.insert(*dir) {
797 dirs.push((*dir).to_string());
798 }
799 }
800 }
801
802 dirs
803 }
804
805 #[cfg(test)]
810 fn run(
811 &self,
812 pkg: &PackageJson,
813 root: &Path,
814 discovered_files: &[PathBuf],
815 ) -> AggregatedPluginResult {
816 self.try_run(pkg, root, discovered_files)
817 .unwrap_or_else(|errors| panic!("{}", format_plugin_regex_errors(&errors)))
818 }
819
820 pub fn try_run(
822 &self,
823 pkg: &PackageJson,
824 root: &Path,
825 discovered_files: &[PathBuf],
826 ) -> Result<AggregatedPluginResult, Vec<PluginRegexValidationError>> {
827 self.try_run_with_search_roots(pkg, root, discovered_files, &[root], false, None)
828 }
829
830 #[expect(
833 clippy::too_many_arguments,
834 reason = "public PluginRegistry API; signature is part of the crate surface for embedders"
835 )]
836 pub(crate) fn try_run_with_search_roots(
837 &self,
838 pkg: &PackageJson,
839 root: &Path,
840 discovered_files: &[PathBuf],
841 config_search_roots: &[&Path],
842 production_mode: bool,
843 candidate_index: Option<&ConfigCandidateIndex>,
844 ) -> Result<AggregatedPluginResult, Vec<PluginRegexValidationError>> {
845 let _span = tracing::info_span!("run_plugins").entered();
846 let mut result = AggregatedPluginResult::default();
847 let mut regex_errors = Vec::new();
848
849 let PluginRunContext { all_deps, active } = self.prepare_plugin_run_context(
850 pkg,
851 root,
852 discovered_files,
853 production_mode,
854 candidate_index,
855 );
856
857 self.run_plugin_preflight(&active, &all_deps, root, discovered_files);
858
859 for plugin in &active {
860 process_static_patterns(*plugin, root, &mut result);
861 }
862 process_package_json_metadata(&active, pkg, root, &mut result, &mut regex_errors);
863
864 process_external_plugins(
865 &self.external_plugins,
866 &all_deps,
867 root,
868 discovered_files,
869 &mut result,
870 );
871 tooling_evidence::record_plugin_tooling(
872 &tooling_evidence::ToolingEvidenceInput {
873 active: &active,
874 external_plugins: &self.external_plugins,
875 all_deps: &all_deps,
876 roots: &[root],
877 extra_roots: if production_mode {
881 &[]
882 } else {
883 config_search_roots
884 },
885 candidate_index,
886 discovered_files,
887 },
888 &mut result,
889 );
890
891 let config_matchers = compile_config_matchers(&active);
892 let relative_files =
893 compute_relative_files(&config_matchers, &active, discovered_files, root);
894
895 resolve_plugin_config_files(&mut PluginConfigResolutionInput {
896 config_matchers: &config_matchers,
897 relative_files: &relative_files,
898 config_search_roots,
899 production_mode,
900 candidate_index,
901 root,
902 result: &mut result,
903 regex_errors: &mut regex_errors,
904 });
905
906 process_package_json_inline_configs(
907 &InlineConfigInput {
908 active: &active,
909 config_matchers: &config_matchers,
910 relative_files: &relative_files,
911 pkg,
912 root,
913 project_root: root,
914 },
915 &mut result,
916 &mut regex_errors,
917 );
918
919 if regex_errors.is_empty() {
920 Ok(result)
921 } else {
922 Err(regex_errors)
923 }
924 }
925
926 #[cfg(test)]
931 fn run_workspace_fast(&self, input: &WorkspacePluginRunInput<'_>) -> AggregatedPluginResult {
932 self.try_run_workspace_fast(input)
933 .unwrap_or_else(|errors| panic!("{}", format_plugin_regex_errors(&errors)))
934 }
935
936 pub(crate) fn try_run_workspace_fast(
943 &self,
944 input: &WorkspacePluginRunInput<'_>,
945 ) -> Result<AggregatedPluginResult, Vec<PluginRegexValidationError>> {
946 let _span = tracing::info_span!("run_plugins").entered();
947 let mut result = AggregatedPluginResult::default();
948 let mut regex_errors = Vec::new();
949
950 let (all_deps, script_packages) = workspace_activation_deps(input);
951 let workspace_files: Vec<PathBuf> = input
952 .relative_files
953 .iter()
954 .map(|(abs_path, _)| abs_path.clone())
955 .collect();
956
957 let active = self.collect_active_plugins(&PluginActivationInput {
958 pkg: input.pkg,
959 root: input.root,
960 discovered_files: &workspace_files,
961 all_deps: &all_deps,
962 script_packages: &script_packages,
963 candidate_index: input.candidate_index,
964 });
965
966 log_active_plugins(&active);
967
968 self.emit_silent_fail_diagnostics(&active, &all_deps, input.root, &workspace_files);
969
970 process_external_plugins(
971 &self.external_plugins,
972 &all_deps,
973 input.root,
974 &workspace_files,
975 &mut result,
976 );
977
978 if active.is_empty() && result.active_plugins.is_empty() {
979 return Ok(result);
980 }
981
982 process_workspace_active_plugins(&active, input, &mut result, &mut regex_errors);
983 let evidence_roots: &[&Path] = if input.root == input.project_root {
985 &[input.root]
986 } else {
987 &[input.root, input.project_root]
988 };
989 tooling_evidence::record_plugin_tooling(
990 &tooling_evidence::ToolingEvidenceInput {
991 active: &active,
992 external_plugins: &self.external_plugins,
993 all_deps: &all_deps,
994 roots: evidence_roots,
995 extra_roots: &[],
996 candidate_index: input.candidate_index,
997 discovered_files: &workspace_files,
998 },
999 &mut result,
1000 );
1001 resolve_workspace_plugin_configs(&active, input, &mut result, &mut regex_errors);
1002 if input.root != input.project_root {
1004 process_package_json_inline_configs(
1005 &InlineConfigInput {
1006 active: &active,
1007 config_matchers: input.precompiled_config_matchers,
1008 relative_files: input.relative_files,
1009 pkg: input.pkg,
1010 root: input.root,
1011 project_root: input.project_root,
1012 },
1013 &mut result,
1014 &mut regex_errors,
1015 );
1016 }
1017
1018 if regex_errors.is_empty() {
1019 Ok(result)
1020 } else {
1021 Err(regex_errors)
1022 }
1023 }
1024
1025 #[must_use]
1028 pub(crate) fn precompile_config_matchers(
1029 &self,
1030 ) -> Vec<(&dyn Plugin, Vec<globset::GlobMatcher>)> {
1031 self.plugins
1032 .iter()
1033 .filter(|p| !p.config_patterns().is_empty())
1034 .map(|p| (p.as_ref(), cached_plugin_config_matchers(p.as_ref())))
1035 .collect()
1036 }
1037
1038 pub(crate) fn resolve_script_config_files(
1049 &self,
1050 config_files: &[scripts::BinaryConfigFile],
1051 package_root: &Path,
1052 project_root: &Path,
1053 ws_prefix: &str,
1054 ) -> AggregatedPluginResult {
1055 let mut aggregated = AggregatedPluginResult::default();
1056 for config_file in config_files {
1057 let Some(rel_path) =
1058 scripts::normalize_script_entry_pattern(ws_prefix, &config_file.path)
1059 else {
1060 continue;
1061 };
1062 let abs_path = package_root.join(config_file.path.trim_start_matches("./"));
1063 let in_package_root = abs_path.parent() == Some(package_root);
1068 let binary = config_file
1071 .binary
1072 .rsplit('/')
1073 .next()
1074 .unwrap_or(&config_file.binary);
1075 for plugin in &self.plugins {
1076 let plugin = plugin.as_ref();
1077 if !plugin.script_config_binaries().contains(&binary)
1078 || (in_package_root
1079 && cached_plugin_config_matchers(plugin)
1080 .iter()
1081 .any(|m| m.is_match(rel_path.as_str())))
1082 {
1083 continue;
1084 }
1085 if !super::config_parser::is_inside_root(&abs_path, project_root) {
1086 continue;
1087 }
1088 let Ok(source) = std::fs::read_to_string(&abs_path) else {
1089 continue;
1090 };
1091 let mut file_result = AggregatedPluginResult::default();
1092 file_result
1093 .entry_point_roles
1094 .insert(plugin.name().to_string(), plugin.entry_point_role());
1095 let plugin_result =
1096 plugin.resolve_script_config(&abs_path, &source, package_root, project_root);
1097 if let Err(errors) = process_config_result(
1098 plugin.name(),
1099 plugin_result,
1100 &mut file_result,
1101 Some(&abs_path),
1102 ) {
1103 for error in errors {
1104 tracing::warn!("{error}");
1105 }
1106 continue;
1107 }
1108 if !ws_prefix.is_empty() {
1109 file_result.apply_workspace_prefix(ws_prefix);
1110 }
1111 file_result.used_exports.push(PluginUsedExportRule::new(
1113 plugin.name().to_string(),
1114 super::UsedExportRule::new(rel_path.clone(), ["default"]),
1115 ));
1116 aggregated.merge_into(file_result);
1117 }
1118 }
1119 aggregated
1120 }
1121}
1122
1123fn process_workspace_active_plugins(
1124 active: &[&dyn Plugin],
1125 input: &WorkspacePluginRunInput<'_>,
1126 result: &mut AggregatedPluginResult,
1127 regex_errors: &mut Vec<PluginRegexValidationError>,
1128) {
1129 for plugin in active {
1130 process_static_patterns(*plugin, input.root, result);
1131 }
1132 process_package_json_metadata(active, input.pkg, input.root, result, regex_errors);
1133}
1134
1135fn resolve_workspace_plugin_configs(
1136 active: &[&dyn Plugin],
1137 input: &WorkspacePluginRunInput<'_>,
1138 result: &mut AggregatedPluginResult,
1139 regex_errors: &mut Vec<PluginRegexValidationError>,
1140) {
1141 let workspace_matchers = select_workspace_matchers(
1142 input.precompiled_config_matchers,
1143 active,
1144 input.skip_config_plugins,
1145 );
1146
1147 let mut resolved_ws_plugins: FxHashSet<&str> = FxHashSet::default();
1148 for (plugin, matchers) in &workspace_matchers {
1149 resolve_plugin_matching_files(&mut PluginMatchingFilesInput {
1150 plugin: *plugin,
1151 matchers,
1152 relative_files: input.relative_files,
1153 root: input.root,
1154 project_root: input.project_root,
1155 result,
1156 regex_errors,
1157 resolved_plugins: &mut resolved_ws_plugins,
1158 });
1159 }
1160
1161 load_workspace_filesystem_configs(&mut WorkspaceFsConfigInput {
1162 workspace_matchers: &workspace_matchers,
1163 resolved_ws_plugins: &resolved_ws_plugins,
1164 root: input.root,
1165 project_root: input.project_root,
1166 production_mode: input.production_mode,
1167 candidate_index: input.candidate_index,
1168 result,
1169 regex_errors,
1170 });
1171}
1172
1173impl Default for PluginRegistry {
1174 fn default() -> Self {
1175 Self::new(vec![])
1176 }
1177}
1178
1179impl PluginRegistry {
1180 fn prepare_plugin_run_context<'a>(
1181 &'a self,
1182 pkg: &PackageJson,
1183 root: &Path,
1184 discovered_files: &[PathBuf],
1185 production_mode: bool,
1186 candidate_index: Option<&ConfigCandidateIndex>,
1187 ) -> PluginRunContext<'a> {
1188 let all_deps = pkg.all_dependency_names();
1189 let script_packages =
1190 script_activation_packages(pkg, root, &[root], &all_deps, production_mode);
1191 let active = self.collect_active_plugins(&PluginActivationInput {
1192 pkg,
1193 root,
1194 discovered_files,
1195 all_deps: &all_deps,
1196 script_packages: &script_packages,
1197 candidate_index,
1198 });
1199
1200 PluginRunContext { all_deps, active }
1201 }
1202
1203 fn run_plugin_preflight(
1204 &self,
1205 active: &[&dyn Plugin],
1206 all_deps: &[String],
1207 root: &Path,
1208 discovered_files: &[PathBuf],
1209 ) {
1210 log_active_plugins(active);
1211 check_meta_framework_prerequisites(active, root);
1212 self.emit_silent_fail_diagnostics(active, all_deps, root, discovered_files);
1213 }
1214
1215 fn collect_active_plugins<'a>(
1218 &'a self,
1219 activation: &PluginActivationInput<'_>,
1220 ) -> Vec<&'a dyn Plugin> {
1221 self.plugins
1222 .iter()
1223 .filter(|p| {
1224 p.is_enabled_with_files(
1225 activation.all_deps,
1226 activation.root,
1227 activation.discovered_files,
1228 activation.candidate_index,
1229 ) || p.is_enabled_with_scripts(activation.script_packages, activation.root)
1230 || p.is_enabled_with_package_json(activation.pkg, activation.root)
1231 })
1232 .map(AsRef::as_ref)
1233 .collect()
1234 }
1235
1236 fn emit_silent_fail_diagnostics(
1245 &self,
1246 active: &[&dyn Plugin],
1247 all_deps: &[String],
1248 root: &Path,
1249 discovered_files: &[PathBuf],
1250 ) {
1251 let active_external: Vec<&ExternalPluginDef> = self
1252 .external_plugins
1253 .iter()
1254 .filter(|ext| is_external_plugin_active(ext, all_deps, root, discovered_files))
1255 .collect();
1256 let mut diagnostics = detect_pattern_collisions(active, &active_external);
1257 diagnostics.extend(detect_enabler_typos(&self.external_plugins, all_deps));
1258 emit_plugin_diagnostics(&diagnostics);
1259 }
1260}
1261
1262fn plugin_warn_dedupe() -> &'static std::sync::Mutex<FxHashSet<String>> {
1269 static WARNED: std::sync::OnceLock<std::sync::Mutex<FxHashSet<String>>> =
1270 std::sync::OnceLock::new();
1271 WARNED.get_or_init(|| std::sync::Mutex::new(FxHashSet::default()))
1272}
1273
1274struct PluginConfigResolutionInput<'a> {
1275 config_matchers: &'a [(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
1276 relative_files: &'a [(PathBuf, String)],
1277 config_search_roots: &'a [&'a Path],
1278 production_mode: bool,
1279 candidate_index: Option<&'a ConfigCandidateIndex>,
1280 root: &'a Path,
1281 result: &'a mut AggregatedPluginResult,
1282 regex_errors: &'a mut Vec<PluginRegexValidationError>,
1283}
1284
1285fn select_workspace_matchers<'a>(
1288 precompiled_config_matchers: &[(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
1289 active: &[&dyn Plugin],
1290 skip_config_plugins: &FxHashSet<&str>,
1291) -> Vec<(&'a dyn Plugin, Vec<globset::GlobMatcher>)> {
1292 let active_names: FxHashSet<&str> = active.iter().map(|p| p.name()).collect();
1293 precompiled_config_matchers
1294 .iter()
1295 .filter(|(p, _)| {
1296 active_names.contains(p.name())
1297 && (!skip_config_plugins.contains(p.name())
1298 || must_parse_workspace_config_when_root_active(p.name()))
1299 })
1300 .map(|(plugin, matchers)| (*plugin, matchers.clone()))
1301 .collect()
1302}
1303
1304struct WorkspaceFsConfigInput<'a> {
1305 workspace_matchers: &'a [(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
1306 resolved_ws_plugins: &'a FxHashSet<&'a str>,
1307 root: &'a Path,
1308 project_root: &'a Path,
1309 production_mode: bool,
1310 candidate_index: Option<&'a ConfigCandidateIndex>,
1311 result: &'a mut AggregatedPluginResult,
1312 regex_errors: &'a mut Vec<PluginRegexValidationError>,
1313}
1314
1315fn load_workspace_filesystem_configs(input: &mut WorkspaceFsConfigInput<'_>) {
1318 let search_roots: &[&Path] = if input.root == input.project_root {
1319 &[input.root]
1320 } else {
1321 &[input.root, input.project_root]
1322 };
1323 let ws_json_configs = discover_config_files(
1324 input.workspace_matchers,
1325 input.resolved_ws_plugins,
1326 search_roots,
1327 input.production_mode,
1328 input.candidate_index,
1329 );
1330 for (abs_path, plugin) in &ws_json_configs {
1331 let Ok(source) = std::fs::read_to_string(abs_path) else {
1332 continue;
1333 };
1334 let plugin_result =
1335 plugin.resolve_config_in_project(abs_path, &source, input.root, input.project_root);
1336 if plugin_result.is_empty() {
1337 continue;
1338 }
1339 let rel = abs_path
1340 .strip_prefix(input.project_root)
1341 .map(|p| p.to_string_lossy())
1342 .unwrap_or_default();
1343 tracing::debug!(
1344 plugin = plugin.name(),
1345 config = %rel,
1346 entries = plugin_result.entry_patterns.len(),
1347 deps = plugin_result.referenced_dependencies.len(),
1348 "resolved config (workspace filesystem fallback)"
1349 );
1350 if let Err(mut errors) =
1351 process_config_result(plugin.name(), plugin_result, input.result, Some(abs_path))
1352 {
1353 input.regex_errors.append(&mut errors);
1354 }
1355 }
1356}
1357
1358fn resolve_plugin_config_files(input: &mut PluginConfigResolutionInput<'_>) {
1359 if input.config_matchers.is_empty() {
1360 return;
1361 }
1362
1363 let mut resolved_plugins: FxHashSet<&str> = FxHashSet::default();
1364 for (plugin, matchers) in input.config_matchers {
1365 resolve_plugin_matching_files(&mut PluginMatchingFilesInput {
1366 plugin: *plugin,
1367 matchers,
1368 relative_files: input.relative_files,
1369 root: input.root,
1370 project_root: input.root,
1371 result: input.result,
1372 regex_errors: input.regex_errors,
1373 resolved_plugins: &mut resolved_plugins,
1374 });
1375 }
1376
1377 let json_configs = discover_config_files(
1378 input.config_matchers,
1379 &resolved_plugins,
1380 input.config_search_roots,
1381 input.production_mode,
1382 input.candidate_index,
1383 );
1384 for (abs_path, plugin) in &json_configs {
1385 resolve_plugin_filesystem_config(
1386 *plugin,
1387 abs_path,
1388 input.root,
1389 input.result,
1390 input.regex_errors,
1391 );
1392 }
1393}
1394
1395struct PluginMatchingFilesInput<'plugins, 'data, 'state> {
1396 plugin: &'plugins dyn Plugin,
1397 matchers: &'data [globset::GlobMatcher],
1398 relative_files: &'data [(PathBuf, String)],
1399 root: &'data Path,
1400 project_root: &'data Path,
1401 result: &'state mut AggregatedPluginResult,
1402 regex_errors: &'state mut Vec<PluginRegexValidationError>,
1403 resolved_plugins: &'state mut FxHashSet<&'plugins str>,
1404}
1405
1406fn resolve_plugin_matching_files(input: &mut PluginMatchingFilesInput<'_, '_, '_>) {
1407 use rayon::prelude::*;
1408
1409 let plugin_hits: Vec<&PathBuf> = input
1410 .relative_files
1411 .par_iter()
1412 .filter_map(|(abs_path, rel_path)| {
1413 input
1414 .matchers
1415 .iter()
1416 .any(|m| m.is_match(rel_path.as_str()))
1417 .then_some(abs_path)
1418 })
1419 .collect();
1420 for abs_path in plugin_hits {
1421 let Ok(source) = std::fs::read_to_string(abs_path) else {
1422 continue;
1423 };
1424 let plugin_result = input.plugin.resolve_config_in_project(
1425 abs_path,
1426 &source,
1427 input.root,
1428 input.project_root,
1429 );
1430 if plugin_result.is_empty() {
1431 continue;
1432 }
1433 input.resolved_plugins.insert(input.plugin.name());
1434 process_resolved_plugin_config(ResolvedPluginConfigInput {
1435 plugin: input.plugin,
1436 abs_path,
1437 plugin_result,
1438 result: input.result,
1439 regex_errors: input.regex_errors,
1440 message: "resolved config",
1441 config_display: abs_path.display(),
1442 });
1443 }
1444}
1445
1446fn resolve_plugin_filesystem_config(
1447 plugin: &dyn Plugin,
1448 abs_path: &Path,
1449 root: &Path,
1450 result: &mut AggregatedPluginResult,
1451 regex_errors: &mut Vec<PluginRegexValidationError>,
1452) {
1453 let Ok(source) = std::fs::read_to_string(abs_path) else {
1454 return;
1455 };
1456 let plugin_result = plugin.resolve_config(abs_path, &source, root);
1457 if plugin_result.is_empty() {
1458 return;
1459 }
1460 let rel = abs_path
1461 .strip_prefix(root)
1462 .map(|p| p.to_string_lossy())
1463 .unwrap_or_default();
1464 process_resolved_plugin_config(ResolvedPluginConfigInput {
1465 plugin,
1466 abs_path,
1467 plugin_result,
1468 result,
1469 regex_errors,
1470 message: "resolved config (filesystem fallback)",
1471 config_display: rel,
1472 });
1473}
1474
1475struct ResolvedPluginConfigInput<'a, D> {
1476 plugin: &'a dyn Plugin,
1477 abs_path: &'a Path,
1478 plugin_result: PluginResult,
1479 result: &'a mut AggregatedPluginResult,
1480 regex_errors: &'a mut Vec<PluginRegexValidationError>,
1481 message: &'static str,
1482 config_display: D,
1483}
1484
1485fn process_resolved_plugin_config(input: ResolvedPluginConfigInput<'_, impl std::fmt::Display>) {
1486 tracing::debug!(
1487 plugin = input.plugin.name(),
1488 config = %input.config_display,
1489 entries = input.plugin_result.entry_patterns.len(),
1490 deps = input.plugin_result.referenced_dependencies.len(),
1491 input.message
1492 );
1493 if let Err(mut errors) = process_config_result(
1494 input.plugin.name(),
1495 input.plugin_result,
1496 input.result,
1497 Some(input.abs_path),
1498 ) {
1499 input.regex_errors.append(&mut errors);
1500 }
1501}
1502
1503fn should_warn(key: String) -> bool {
1507 plugin_warn_dedupe()
1508 .lock()
1509 .map_or(true, |mut set| set.insert(key))
1510}
1511
1512#[derive(Debug, Clone, PartialEq, Eq)]
1519enum PluginDiagnostic {
1520 PatternCollision {
1522 pattern: String,
1523 owners: Vec<String>,
1524 },
1525 EnablerTypo {
1528 plugin: String,
1529 enabler: String,
1530 suggestion: String,
1531 },
1532}
1533
1534fn detect_pattern_collisions(
1560 builtin_active: &[&dyn Plugin],
1561 external_active: &[&ExternalPluginDef],
1562) -> Vec<PluginDiagnostic> {
1563 use rustc_hash::FxHashMap;
1564
1565 let mut pattern_owners: FxHashMap<String, (Vec<String>, FxHashSet<String>)> =
1566 FxHashMap::default();
1567
1568 let record = |pattern_owners: &mut FxHashMap<_, (Vec<String>, FxHashSet<String>)>,
1569 pattern: String,
1570 name: String| {
1571 let (list, seen) = pattern_owners.entry(pattern).or_default();
1572 if seen.insert(name.clone()) {
1573 list.push(name);
1574 }
1575 };
1576
1577 for plugin in builtin_active {
1578 for pat in plugin.config_patterns() {
1579 record(
1580 &mut pattern_owners,
1581 (*pat).to_string(),
1582 plugin.name().to_string(),
1583 );
1584 }
1585 }
1586 for ext in external_active {
1587 for pat in &ext.config_patterns {
1588 record(&mut pattern_owners, pat.clone(), ext.name.clone());
1589 }
1590 }
1591
1592 let builtin_names: FxHashSet<&str> = builtin_active.iter().map(|p| p.name()).collect();
1599
1600 let mut findings: Vec<PluginDiagnostic> = pattern_owners
1601 .into_iter()
1602 .filter_map(|(pattern, (owners, _seen))| {
1603 if owners.len() < 2 || owners.iter().all(|o| builtin_names.contains(o.as_str())) {
1604 None
1605 } else {
1606 Some(PluginDiagnostic::PatternCollision { pattern, owners })
1607 }
1608 })
1609 .collect();
1610 findings.sort_unstable_by(|a, b| match (a, b) {
1611 (
1612 PluginDiagnostic::PatternCollision { pattern: ap, .. },
1613 PluginDiagnostic::PatternCollision { pattern: bp, .. },
1614 ) => ap.cmp(bp),
1615 _ => std::cmp::Ordering::Equal,
1616 });
1617 findings
1618}
1619
1620fn detect_enabler_typos(
1635 external_plugins: &[ExternalPluginDef],
1636 all_deps: &[String],
1637) -> Vec<PluginDiagnostic> {
1638 let mut findings = Vec::new();
1639
1640 for ext in external_plugins {
1641 if ext.detection.is_some() || ext.enablers.is_empty() {
1642 continue;
1643 }
1644
1645 let any_match = ext.enablers.iter().any(|enabler| {
1646 if enabler.ends_with('/') {
1647 all_deps.iter().any(|d| d.starts_with(enabler))
1648 } else {
1649 all_deps.iter().any(|d| d == enabler)
1650 }
1651 });
1652 if any_match {
1653 continue;
1654 }
1655
1656 for enabler in &ext.enablers {
1657 let candidates = all_deps.iter().map(String::as_str);
1658 let Some(suggestion) = fallow_config::levenshtein::closest_match(enabler, candidates)
1659 else {
1660 continue;
1661 };
1662
1663 findings.push(PluginDiagnostic::EnablerTypo {
1664 plugin: ext.name.clone(),
1665 enabler: enabler.clone(),
1666 suggestion: suggestion.to_string(),
1667 });
1668 }
1669 }
1670
1671 findings
1672}
1673
1674fn emit_plugin_diagnostics(findings: &[PluginDiagnostic]) {
1677 for finding in findings {
1678 match finding {
1679 PluginDiagnostic::PatternCollision { pattern, owners } => {
1680 let key = format!("collision::{pattern}::{owners:?}");
1681 if !should_warn(key) {
1682 continue;
1683 }
1684 let winner = &owners[0];
1685 let others = owners[1..].join(", ");
1686 tracing::warn!(
1687 "plugin config_patterns collision: identical pattern \
1688 '{pattern}' is claimed by plugins [{joined}]; '{winner}' \
1689 runs first (registration order), others ({others}) \
1690 follow. Rename one of the patterns or remove the \
1691 duplicate plugin to make resolution explicit. A future \
1692 release may reject identical-pattern collisions.",
1693 joined = owners.join(", "),
1694 );
1695 }
1696 PluginDiagnostic::EnablerTypo {
1697 plugin,
1698 enabler,
1699 suggestion,
1700 } => {
1701 let key = format!("enabler::{plugin}::{enabler}");
1702 if !should_warn(key) {
1703 continue;
1704 }
1705 tracing::warn!(
1706 "plugin '{plugin}' enabler '{enabler}' does not match any \
1707 dependency in package.json; did you mean '{suggestion}'? \
1708 The plugin will not activate. A future release may reject \
1709 unmatched enablers.",
1710 );
1711 }
1712 }
1713 }
1714}
1715
1716fn process_package_json_inline_configs(
1728 input: &InlineConfigInput<'_>,
1729 result: &mut AggregatedPluginResult,
1730 regex_errors: &mut Vec<PluginRegexValidationError>,
1731) {
1732 let pkg_path = input.root.join("package.json");
1733 let credited_manifests: Vec<PathBuf> = if input.root == input.project_root {
1734 Vec::new()
1735 } else {
1736 input
1737 .root
1738 .ancestors()
1739 .take_while(|dir| dir.starts_with(input.project_root))
1740 .map(|dir| dir.join("package.json"))
1741 .collect()
1742 };
1743 for plugin in input.active {
1744 let Some(key) = plugin.package_json_config_key() else {
1745 continue;
1746 };
1747 let Some(config_value) = input.pkg.inline_tool_config(key) else {
1748 continue;
1749 };
1750 if check_has_config_file(*plugin, input.config_matchers, input.relative_files) {
1751 continue;
1752 }
1753 let config_json = serde_json::to_string(config_value).unwrap_or_default();
1754 let fake_path = input.root.join(format!("{key}.config.json"));
1755 let mut plugin_result = plugin.resolve_config_in_project(
1756 &fake_path,
1757 &config_json,
1758 input.root,
1759 input.project_root,
1760 );
1761 if plugin_result.is_empty() {
1762 continue;
1763 }
1764 tracing::debug!(
1765 plugin = plugin.name(),
1766 key = key,
1767 "resolved inline package.json config"
1768 );
1769 if !credited_manifests.is_empty() {
1770 for dep in std::mem::take(&mut plugin_result.referenced_dependencies) {
1771 plugin_result.package_referenced_dependencies.extend(
1772 credited_manifests
1773 .iter()
1774 .map(|manifest| (manifest.clone(), dep.clone())),
1775 );
1776 }
1777 }
1778 if let Err(mut errors) =
1779 process_config_result(plugin.name(), plugin_result, result, Some(&pkg_path))
1780 {
1781 regex_errors.append(&mut errors);
1782 }
1783 }
1784}
1785
1786struct InlineConfigInput<'a> {
1788 active: &'a [&'a dyn Plugin],
1789 config_matchers: &'a [(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
1790 relative_files: &'a [(PathBuf, String)],
1791 pkg: &'a PackageJson,
1792 root: &'a Path,
1793 project_root: &'a Path,
1794}
1795
1796#[derive(Debug)]
1799struct MetaFrameworkWarning {
1800 dedupe_key: &'static str,
1801 message: &'static str,
1802}
1803
1804fn missing_meta_framework_prerequisites(
1814 active_plugins: &[&dyn Plugin],
1815 root: &Path,
1816) -> Vec<MetaFrameworkWarning> {
1817 active_plugins
1818 .iter()
1819 .filter_map(|plugin| match plugin.name() {
1820 "nuxt" if !root.join(".nuxt/tsconfig.json").exists() => Some(MetaFrameworkWarning {
1821 dedupe_key: "meta-prereq::nuxt",
1822 message: "Nuxt project missing .nuxt/tsconfig.json: run `nuxt prepare` \
1823 before fallow for accurate analysis",
1824 }),
1825 "astro" if !root.join(".astro").exists() => Some(MetaFrameworkWarning {
1826 dedupe_key: "meta-prereq::astro",
1827 message: "Astro project missing .astro/ types: run `astro sync` \
1828 before fallow for accurate analysis",
1829 }),
1830 _ => None,
1831 })
1832 .collect()
1833}
1834
1835fn check_meta_framework_prerequisites(active_plugins: &[&dyn Plugin], root: &Path) {
1845 for warning in missing_meta_framework_prerequisites(active_plugins, root) {
1846 if should_warn(warning.dedupe_key.to_owned()) {
1847 tracing::warn!("{}", warning.message);
1848 }
1849 }
1850}
1851
1852fn workspace_activation_deps(
1861 input: &WorkspacePluginRunInput<'_>,
1862) -> (Vec<String>, FxHashSet<String>) {
1863 let mut deps = input.pkg.all_dependency_names();
1864 let own: FxHashSet<&str> = deps.iter().map(String::as_str).collect();
1865 let hoisted: Vec<String> = input
1866 .root_dependencies
1867 .iter()
1868 .filter(|dep| !own.contains(dep.as_str()))
1869 .cloned()
1870 .collect();
1871 let mut script_deps = deps.clone();
1872 script_deps.extend(hoisted.iter().cloned());
1873 let script_packages = script_activation_packages(
1874 input.pkg,
1875 input.root,
1876 &[input.root, input.project_root],
1877 &script_deps,
1878 input.production_mode,
1879 );
1880 deps.extend(
1881 hoisted
1882 .into_iter()
1883 .filter(|dep| script_packages.contains(dep)),
1884 );
1885 (deps, script_packages)
1886}
1887
1888fn script_activation_packages(
1891 pkg: &PackageJson,
1892 root: &Path,
1893 node_modules_roots: &[&Path],
1894 all_deps: &[String],
1895 production_mode: bool,
1896) -> FxHashSet<String> {
1897 let Some(pkg_scripts) = pkg.scripts.as_ref() else {
1898 return FxHashSet::default();
1899 };
1900
1901 let scripts_to_analyze = if production_mode {
1902 scripts::filter_production_scripts(pkg_scripts)
1903 } else {
1904 pkg_scripts.clone()
1905 };
1906
1907 let mut nm_roots: Vec<&Path> = Vec::new();
1908 for nm_root in node_modules_roots {
1909 if !nm_roots.contains(nm_root) && nm_root.join("node_modules").is_dir() {
1910 nm_roots.push(nm_root);
1911 }
1912 }
1913 let bin_map = scripts::build_bin_to_package_map(&nm_roots, all_deps);
1914 let dep_set: FxHashSet<String> = all_deps.iter().cloned().collect();
1915 let catalog =
1916 scripts::ScriptCatalog::from_scripts_with_bodies(pkg_scripts, &scripts_to_analyze);
1917
1918 scripts::analyze_scripts_with_dependency_context(
1919 &scripts_to_analyze,
1920 root,
1921 &bin_map,
1922 &dep_set,
1923 &catalog,
1924 scripts::IgnoredCommandEntries::NONE,
1925 )
1926 .used_packages
1927}
1928
1929#[cfg(test)]
1930mod entry_pattern_tests;
1931#[cfg(test)]
1932mod tests;