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, PackageJson, UsedClassMemberRule,
10};
11
12use crate::scripts;
13
14use super::{PathRule, Plugin, PluginResult, PluginUsedExportRule, ProvidedDependencyRule};
15
16pub(crate) mod builtin;
17mod helpers;
18
19#[must_use]
24pub fn builtin_plugin_names() -> Vec<&'static str> {
25 builtin::create_builtin_plugins()
26 .iter()
27 .map(|plugin| plugin.name())
28 .collect()
29}
30
31#[must_use]
36pub fn builtin_plugin_config_candidate_basenames() -> Vec<String> {
37 let mut set: FxHashSet<String> = FxHashSet::default();
38 for plugin in builtin::create_builtin_plugins() {
39 for pattern in plugin.config_patterns() {
40 let basename = pattern.rsplit('/').next().unwrap_or(pattern);
41 set.insert(basename.to_string());
42 }
43 }
44 let mut basenames = set.into_iter().collect::<Vec<_>>();
45 basenames.sort_unstable();
46 basenames
47}
48
49pub use helpers::ConfigCandidateIndex;
50pub use helpers::is_external_plugin_active;
51use helpers::{
52 check_has_config_file, discover_config_files, prepare_config_pattern, process_config_result,
53 process_external_plugins, process_package_json_metadata, process_static_patterns,
54};
55
56fn must_parse_workspace_config_when_root_active(plugin_name: &str) -> bool {
57 matches!(
58 plugin_name,
59 "eslint" | "docusaurus" | "jest" | "tanstack-router" | "vitest"
60 )
61}
62
63fn compile_config_matchers<'a>(
64 active: &[&'a dyn Plugin],
65) -> Vec<(&'a dyn Plugin, Vec<globset::GlobMatcher>)> {
66 active
67 .iter()
68 .filter(|plugin| !plugin.config_patterns().is_empty())
69 .map(|plugin| (*plugin, cached_plugin_config_matchers(*plugin)))
70 .collect()
71}
72
73fn compile_plugin_config_matchers(plugin: &dyn Plugin) -> Vec<globset::GlobMatcher> {
74 plugin
75 .config_patterns()
76 .iter()
77 .filter_map(|pattern| {
78 let prepared = prepare_config_pattern(pattern);
79 globset::Glob::new(&prepared)
80 .ok()
81 .map(|glob| glob.compile_matcher())
82 })
83 .collect()
84}
85
86struct CachedPluginConfigMatchers {
87 patterns: &'static [&'static str],
88 matchers: Vec<globset::GlobMatcher>,
89}
90
91#[derive(Default)]
92struct PluginConfigMatcherCache {
93 by_name: RwLock<FxHashMap<&'static str, Vec<CachedPluginConfigMatchers>>>,
94}
95
96impl PluginConfigMatcherCache {
97 fn get_or_compile(&self, plugin: &dyn Plugin) -> Vec<globset::GlobMatcher> {
98 let patterns = plugin.config_patterns();
99 let cached = self
100 .by_name
101 .read()
102 .unwrap_or_else(std::sync::PoisonError::into_inner)
103 .get(plugin.name())
104 .and_then(|variants| {
105 variants
106 .iter()
107 .find(|entry| entry.patterns == patterns)
108 .map(|entry| entry.matchers.clone())
109 });
110 if let Some(matchers) = cached {
111 return matchers;
112 }
113
114 let matchers = compile_plugin_config_matchers(plugin);
115 {
116 let mut by_name = self
117 .by_name
118 .write()
119 .unwrap_or_else(std::sync::PoisonError::into_inner);
120 let variants = by_name.entry(plugin.name()).or_default();
121 if let Some(entry) = variants.iter().find(|entry| entry.patterns == patterns) {
122 return entry.matchers.clone();
123 }
124 variants.push(CachedPluginConfigMatchers {
125 patterns,
126 matchers: matchers.clone(),
127 });
128 drop(by_name);
129 }
130 matchers
131 }
132}
133
134fn cached_plugin_config_matchers(plugin: &dyn Plugin) -> Vec<globset::GlobMatcher> {
135 static MATCHERS: OnceLock<PluginConfigMatcherCache> = OnceLock::new();
136 MATCHERS
137 .get_or_init(PluginConfigMatcherCache::default)
138 .get_or_compile(plugin)
139}
140
141fn log_active_plugins(active: &[&dyn Plugin]) {
143 tracing::info!(
144 plugins = active
145 .iter()
146 .map(|p| p.name())
147 .collect::<Vec<_>>()
148 .join(", "),
149 "active plugins"
150 );
151}
152
153fn compute_relative_files(
157 config_matchers: &[(&dyn Plugin, Vec<globset::GlobMatcher>)],
158 active: &[&dyn Plugin],
159 discovered_files: &[PathBuf],
160 root: &Path,
161) -> Vec<(PathBuf, String)> {
162 use rayon::prelude::*;
163 let needs_relative_files =
164 !config_matchers.is_empty() || active.iter().any(|p| p.package_json_config_key().is_some());
165 if !needs_relative_files {
166 return Vec::new();
167 }
168 discovered_files
169 .par_iter()
170 .map(|f| {
171 let rel = f
172 .strip_prefix(root)
173 .unwrap_or(f)
174 .to_string_lossy()
175 .into_owned();
176 (f.clone(), rel)
177 })
178 .collect()
179}
180
181pub struct PluginRegistry {
183 plugins: Vec<Box<dyn Plugin>>,
184 external_plugins: Vec<ExternalPluginDef>,
185}
186
187pub(crate) struct WorkspacePluginRunInput<'a> {
189 pub(crate) pkg: &'a PackageJson,
190 pub(crate) root: &'a Path,
191 pub(crate) project_root: &'a Path,
192 pub(crate) precompiled_config_matchers: &'a [(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
193 pub(crate) relative_files: &'a [(PathBuf, String)],
194 pub(crate) skip_config_plugins: &'a FxHashSet<&'a str>,
195 pub(crate) production_mode: bool,
196 pub(crate) candidate_index: Option<&'a ConfigCandidateIndex>,
197}
198
199struct PluginRunContext<'a> {
200 all_deps: Vec<String>,
201 active: Vec<&'a dyn Plugin>,
202}
203
204struct PluginActivationInput<'a> {
206 pkg: &'a PackageJson,
207 root: &'a Path,
208 discovered_files: &'a [PathBuf],
209 all_deps: &'a [String],
210 script_packages: &'a FxHashSet<String>,
211 candidate_index: Option<&'a ConfigCandidateIndex>,
212}
213
214#[derive(Debug, Clone, PartialEq, Eq)]
216pub struct PluginRegexValidationError {
217 plugin_name: String,
218 config_path: Option<PathBuf>,
219 rule_kind: &'static str,
220 field: &'static str,
221 rule_pattern: String,
222 regex_pattern: String,
223 source: String,
224}
225
226impl PluginRegexValidationError {
227 fn new(input: PluginRegexValidationErrorInput<'_>) -> Self {
228 Self {
229 plugin_name: input.plugin_name.to_owned(),
230 config_path: input.config_path.map(Path::to_path_buf),
231 rule_kind: input.rule_kind,
232 field: input.field,
233 rule_pattern: input.rule_pattern.to_owned(),
234 regex_pattern: input.regex_pattern.to_owned(),
235 source: input.source.to_string(),
236 }
237 }
238}
239
240#[derive(Clone, Copy)]
241pub(crate) struct PluginRegexValidationErrorInput<'a> {
242 plugin_name: &'a str,
243 config_path: Option<&'a Path>,
244 rule_kind: &'static str,
245 field: &'static str,
246 rule_pattern: &'a str,
247 regex_pattern: &'a str,
248 source: &'a regex::Error,
249}
250
251impl fmt::Display for PluginRegexValidationError {
252 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
253 let location = self
254 .config_path
255 .as_ref()
256 .map(|path| format!(" in {}", path.display()))
257 .unwrap_or_default();
258 write!(
259 f,
260 "plugin '{}'{}: invalid regex '{}' in {}.{} for path rule '{}': {}",
261 self.plugin_name,
262 location,
263 self.regex_pattern,
264 self.rule_kind,
265 self.field,
266 self.rule_pattern,
267 self.source
268 )
269 }
270}
271
272#[must_use]
273pub(crate) fn format_plugin_regex_errors(errors: &[PluginRegexValidationError]) -> String {
274 let joined = errors
275 .iter()
276 .map(ToString::to_string)
277 .collect::<Vec<_>>()
278 .join("\n - ");
279 format!(
280 "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."
281 )
282}
283
284#[derive(Debug, Clone, Default)]
286pub struct AggregatedPluginResult {
287 pub entry_patterns: Vec<(PathRule, String)>,
289 pub entry_point_roles: rustc_hash::FxHashMap<String, EntryPointRole>,
291 pub config_patterns: Vec<String>,
293 pub always_used: Vec<(String, String)>,
295 pub used_exports: Vec<PluginUsedExportRule>,
297 pub used_class_members: Vec<UsedClassMemberRule>,
301 pub framework_class_member_contracts: Vec<fallow_types::semantic::SemanticFrameworkContract>,
303 pub referenced_dependencies: Vec<String>,
305 pub package_referenced_dependencies: Vec<(PathBuf, String)>,
307 pub discovered_always_used: Vec<(String, String)>,
309 pub setup_files: Vec<(PathBuf, String)>,
311 pub tooling_dependencies: Vec<String>,
313 pub script_used_packages: FxHashSet<String>,
315 pub virtual_module_prefixes: Vec<String>,
318 pub virtual_package_suffixes: Vec<String>,
321 pub generated_import_patterns: Vec<String>,
324 pub generated_type_import_prefixes: Vec<String>,
327 pub path_aliases: Vec<(String, String)>,
330 pub auto_imports: Vec<AutoImportRule>,
334 pub active_plugins: Vec<String>,
336 pub fixture_patterns: Vec<(String, String)>,
338 pub scss_include_paths: Vec<PathBuf>,
343 pub static_dir_mappings: Vec<(PathBuf, String)>,
345 pub framework_static_dir_mappings: Vec<(PathBuf, String)>,
348 pub provided_dependencies: Vec<ProvidedDependencyRule>,
350}
351
352fn extend_unique(target: &mut Vec<String>, incoming: Vec<String>) {
357 let mut seen: FxHashSet<String> = target.iter().cloned().collect();
358 for item in incoming {
359 if seen.insert(item.clone()) {
360 target.push(item);
361 }
362 }
363}
364
365fn prefix_if_needed(pat: &str, ws_prefix: &str) -> String {
369 if pat.starts_with(ws_prefix) || pat.starts_with('/') {
370 pat.to_string()
371 } else {
372 format!("{ws_prefix}/{pat}")
373 }
374}
375
376impl AggregatedPluginResult {
377 pub(crate) fn apply_workspace_prefix(&mut self, ws_prefix: &str) {
391 for (rule, _) in &mut self.entry_patterns {
392 *rule = rule.prefixed(ws_prefix);
393 }
394 for (pat, _) in &mut self.always_used {
395 *pat = prefix_if_needed(pat, ws_prefix);
396 }
397 for (pat, _) in &mut self.discovered_always_used {
398 *pat = prefix_if_needed(pat, ws_prefix);
399 }
400 for (pat, _) in &mut self.fixture_patterns {
401 *pat = prefix_if_needed(pat, ws_prefix);
402 }
403 for rule in &mut self.used_exports {
404 *rule = rule.prefixed(ws_prefix);
405 }
406 for rule in &mut self.provided_dependencies {
407 *rule = rule.prefixed(ws_prefix);
408 }
409 for (_, replacement) in &mut self.path_aliases {
410 *replacement = format!("{ws_prefix}/{replacement}");
411 }
412 }
413
414 pub(crate) fn merge_into(&mut self, other: Self) {
428 let Self {
429 entry_patterns,
430 entry_point_roles,
431 config_patterns,
432 always_used,
433 used_exports,
434 used_class_members,
435 framework_class_member_contracts,
436 referenced_dependencies,
437 package_referenced_dependencies,
438 discovered_always_used,
439 setup_files,
440 tooling_dependencies,
441 script_used_packages,
442 virtual_module_prefixes,
443 virtual_package_suffixes,
444 generated_import_patterns,
445 generated_type_import_prefixes,
446 path_aliases,
447 auto_imports,
448 active_plugins,
449 fixture_patterns,
450 scss_include_paths,
451 static_dir_mappings,
452 framework_static_dir_mappings,
453 provided_dependencies,
454 } = other;
455
456 self.entry_patterns.extend(entry_patterns);
457 for (plugin_name, role) in entry_point_roles {
458 self.entry_point_roles.entry(plugin_name).or_insert(role);
459 }
460 self.config_patterns.extend(config_patterns);
461 self.always_used.extend(always_used);
462 self.used_exports.extend(used_exports);
463 self.used_class_members.extend(used_class_members);
464 for contract in framework_class_member_contracts {
465 if !self.framework_class_member_contracts.contains(&contract) {
466 self.framework_class_member_contracts.push(contract);
467 }
468 }
469 self.referenced_dependencies.extend(referenced_dependencies);
470 self.package_referenced_dependencies
471 .extend(package_referenced_dependencies);
472 self.discovered_always_used.extend(discovered_always_used);
473 self.setup_files.extend(setup_files);
474 self.tooling_dependencies.extend(tooling_dependencies);
475 self.script_used_packages.extend(script_used_packages);
476 extend_unique(&mut self.virtual_module_prefixes, virtual_module_prefixes);
477 extend_unique(&mut self.virtual_package_suffixes, virtual_package_suffixes);
478 extend_unique(
479 &mut self.generated_import_patterns,
480 generated_import_patterns,
481 );
482 extend_unique(
483 &mut self.generated_type_import_prefixes,
484 generated_type_import_prefixes,
485 );
486 self.path_aliases.extend(path_aliases);
487 self.auto_imports.extend(auto_imports);
488 extend_unique(&mut self.active_plugins, active_plugins);
489 self.fixture_patterns.extend(fixture_patterns);
490 self.scss_include_paths.extend(scss_include_paths);
491 self.static_dir_mappings.extend(static_dir_mappings);
492 self.framework_static_dir_mappings
493 .extend(framework_static_dir_mappings);
494 self.provided_dependencies.extend(provided_dependencies);
495 }
496}
497
498impl PluginRegistry {
499 #[must_use]
501 pub fn new(external: Vec<ExternalPluginDef>) -> Self {
502 Self {
503 plugins: builtin::create_builtin_plugins(),
504 external_plugins: external,
505 }
506 }
507
508 #[must_use]
513 pub fn discovery_hidden_dirs(&self, pkg: &PackageJson, root: &Path) -> Vec<String> {
514 let all_deps = pkg.all_dependency_names();
515 let mut seen = FxHashSet::default();
516 let mut dirs = Vec::new();
517
518 for plugin in &self.plugins {
519 if !plugin.is_enabled_with_deps(&all_deps, root) {
520 continue;
521 }
522 for dir in plugin.discovery_hidden_dirs() {
523 if seen.insert(*dir) {
524 dirs.push((*dir).to_string());
525 }
526 }
527 }
528
529 dirs
530 }
531
532 #[cfg(test)]
537 fn run(
538 &self,
539 pkg: &PackageJson,
540 root: &Path,
541 discovered_files: &[PathBuf],
542 ) -> AggregatedPluginResult {
543 self.try_run(pkg, root, discovered_files)
544 .unwrap_or_else(|errors| panic!("{}", format_plugin_regex_errors(&errors)))
545 }
546
547 pub fn try_run(
549 &self,
550 pkg: &PackageJson,
551 root: &Path,
552 discovered_files: &[PathBuf],
553 ) -> Result<AggregatedPluginResult, Vec<PluginRegexValidationError>> {
554 self.try_run_with_search_roots(pkg, root, discovered_files, &[root], false, None)
555 }
556
557 #[expect(
560 clippy::too_many_arguments,
561 reason = "public PluginRegistry API; signature is part of the crate surface for embedders"
562 )]
563 pub(crate) fn try_run_with_search_roots(
564 &self,
565 pkg: &PackageJson,
566 root: &Path,
567 discovered_files: &[PathBuf],
568 config_search_roots: &[&Path],
569 production_mode: bool,
570 candidate_index: Option<&ConfigCandidateIndex>,
571 ) -> Result<AggregatedPluginResult, Vec<PluginRegexValidationError>> {
572 let _span = tracing::info_span!("run_plugins").entered();
573 let mut result = AggregatedPluginResult::default();
574 let mut regex_errors = Vec::new();
575
576 let PluginRunContext { all_deps, active } = self.prepare_plugin_run_context(
577 pkg,
578 root,
579 discovered_files,
580 production_mode,
581 candidate_index,
582 );
583
584 self.run_plugin_preflight(&active, &all_deps, root, discovered_files);
585
586 for plugin in &active {
587 process_static_patterns(*plugin, root, &mut result);
588 }
589 process_package_json_metadata(&active, pkg, root, &mut result, &mut regex_errors);
590
591 process_external_plugins(
592 &self.external_plugins,
593 &all_deps,
594 root,
595 discovered_files,
596 &mut result,
597 );
598
599 let config_matchers = compile_config_matchers(&active);
600 let relative_files =
601 compute_relative_files(&config_matchers, &active, discovered_files, root);
602
603 resolve_plugin_config_files(&mut PluginConfigResolutionInput {
604 config_matchers: &config_matchers,
605 relative_files: &relative_files,
606 config_search_roots,
607 production_mode,
608 candidate_index,
609 root,
610 result: &mut result,
611 regex_errors: &mut regex_errors,
612 });
613
614 process_package_json_inline_configs(
615 &active,
616 &config_matchers,
617 &relative_files,
618 root,
619 &mut result,
620 &mut regex_errors,
621 );
622
623 if regex_errors.is_empty() {
624 Ok(result)
625 } else {
626 Err(regex_errors)
627 }
628 }
629
630 #[cfg(test)]
636 fn run_workspace_fast(&self, input: &WorkspacePluginRunInput<'_>) -> AggregatedPluginResult {
637 self.try_run_workspace_fast(input)
638 .unwrap_or_else(|errors| panic!("{}", format_plugin_regex_errors(&errors)))
639 }
640
641 pub(crate) fn try_run_workspace_fast(
647 &self,
648 input: &WorkspacePluginRunInput<'_>,
649 ) -> Result<AggregatedPluginResult, Vec<PluginRegexValidationError>> {
650 let _span = tracing::info_span!("run_plugins").entered();
651 let mut result = AggregatedPluginResult::default();
652 let mut regex_errors = Vec::new();
653
654 let all_deps = input.pkg.all_dependency_names();
655 let script_packages =
656 script_activation_packages(input.pkg, input.root, &all_deps, input.production_mode);
657 let workspace_files: Vec<PathBuf> = input
658 .relative_files
659 .iter()
660 .map(|(abs_path, _)| abs_path.clone())
661 .collect();
662
663 let active = self.collect_active_plugins(&PluginActivationInput {
664 pkg: input.pkg,
665 root: input.root,
666 discovered_files: &workspace_files,
667 all_deps: &all_deps,
668 script_packages: &script_packages,
669 candidate_index: input.candidate_index,
670 });
671
672 log_active_plugins(&active);
673
674 self.emit_silent_fail_diagnostics(&active, &all_deps, input.root, &workspace_files);
675
676 process_external_plugins(
677 &self.external_plugins,
678 &all_deps,
679 input.root,
680 &workspace_files,
681 &mut result,
682 );
683
684 if active.is_empty() && result.active_plugins.is_empty() {
685 return Ok(result);
686 }
687
688 process_workspace_active_plugins(&active, input, &mut result, &mut regex_errors);
689 resolve_workspace_plugin_configs(&active, input, &mut result, &mut regex_errors);
690
691 if regex_errors.is_empty() {
692 Ok(result)
693 } else {
694 Err(regex_errors)
695 }
696 }
697
698 #[must_use]
701 pub(crate) fn precompile_config_matchers(
702 &self,
703 ) -> Vec<(&dyn Plugin, Vec<globset::GlobMatcher>)> {
704 self.plugins
705 .iter()
706 .filter(|p| !p.config_patterns().is_empty())
707 .map(|p| (p.as_ref(), cached_plugin_config_matchers(p.as_ref())))
708 .collect()
709 }
710}
711
712fn process_workspace_active_plugins(
713 active: &[&dyn Plugin],
714 input: &WorkspacePluginRunInput<'_>,
715 result: &mut AggregatedPluginResult,
716 regex_errors: &mut Vec<PluginRegexValidationError>,
717) {
718 for plugin in active {
719 process_static_patterns(*plugin, input.root, result);
720 }
721 process_package_json_metadata(active, input.pkg, input.root, result, regex_errors);
722}
723
724fn resolve_workspace_plugin_configs(
725 active: &[&dyn Plugin],
726 input: &WorkspacePluginRunInput<'_>,
727 result: &mut AggregatedPluginResult,
728 regex_errors: &mut Vec<PluginRegexValidationError>,
729) {
730 let workspace_matchers = select_workspace_matchers(
731 input.precompiled_config_matchers,
732 active,
733 input.skip_config_plugins,
734 );
735
736 let mut resolved_ws_plugins: FxHashSet<&str> = FxHashSet::default();
737 for (plugin, matchers) in &workspace_matchers {
738 resolve_plugin_matching_files(&mut PluginMatchingFilesInput {
739 plugin: *plugin,
740 matchers,
741 relative_files: input.relative_files,
742 root: input.root,
743 result,
744 regex_errors,
745 resolved_plugins: &mut resolved_ws_plugins,
746 });
747 }
748
749 load_workspace_filesystem_configs(&mut WorkspaceFsConfigInput {
750 workspace_matchers: &workspace_matchers,
751 resolved_ws_plugins: &resolved_ws_plugins,
752 root: input.root,
753 project_root: input.project_root,
754 production_mode: input.production_mode,
755 candidate_index: input.candidate_index,
756 result,
757 regex_errors,
758 });
759}
760
761impl Default for PluginRegistry {
762 fn default() -> Self {
763 Self::new(vec![])
764 }
765}
766
767impl PluginRegistry {
768 fn prepare_plugin_run_context<'a>(
769 &'a self,
770 pkg: &PackageJson,
771 root: &Path,
772 discovered_files: &[PathBuf],
773 production_mode: bool,
774 candidate_index: Option<&ConfigCandidateIndex>,
775 ) -> PluginRunContext<'a> {
776 let all_deps = pkg.all_dependency_names();
777 let script_packages = script_activation_packages(pkg, root, &all_deps, production_mode);
778 let active = self.collect_active_plugins(&PluginActivationInput {
779 pkg,
780 root,
781 discovered_files,
782 all_deps: &all_deps,
783 script_packages: &script_packages,
784 candidate_index,
785 });
786
787 PluginRunContext { all_deps, active }
788 }
789
790 fn run_plugin_preflight(
791 &self,
792 active: &[&dyn Plugin],
793 all_deps: &[String],
794 root: &Path,
795 discovered_files: &[PathBuf],
796 ) {
797 log_active_plugins(active);
798 check_meta_framework_prerequisites(active, root);
799 self.emit_silent_fail_diagnostics(active, all_deps, root, discovered_files);
800 }
801
802 fn collect_active_plugins<'a>(
805 &'a self,
806 activation: &PluginActivationInput<'_>,
807 ) -> Vec<&'a dyn Plugin> {
808 self.plugins
809 .iter()
810 .filter(|p| {
811 p.is_enabled_with_files(
812 activation.all_deps,
813 activation.root,
814 activation.discovered_files,
815 activation.candidate_index,
816 ) || p.is_enabled_with_scripts(activation.script_packages, activation.root)
817 || p.is_enabled_with_package_json(activation.pkg, activation.root)
818 })
819 .map(AsRef::as_ref)
820 .collect()
821 }
822
823 fn emit_silent_fail_diagnostics(
832 &self,
833 active: &[&dyn Plugin],
834 all_deps: &[String],
835 root: &Path,
836 discovered_files: &[PathBuf],
837 ) {
838 let active_external: Vec<&ExternalPluginDef> = self
839 .external_plugins
840 .iter()
841 .filter(|ext| is_external_plugin_active(ext, all_deps, root, discovered_files))
842 .collect();
843 let mut diagnostics = detect_pattern_collisions(active, &active_external);
844 diagnostics.extend(detect_enabler_typos(&self.external_plugins, all_deps));
845 emit_plugin_diagnostics(&diagnostics);
846 }
847}
848
849fn plugin_warn_dedupe() -> &'static std::sync::Mutex<FxHashSet<String>> {
856 static WARNED: std::sync::OnceLock<std::sync::Mutex<FxHashSet<String>>> =
857 std::sync::OnceLock::new();
858 WARNED.get_or_init(|| std::sync::Mutex::new(FxHashSet::default()))
859}
860
861struct PluginConfigResolutionInput<'a> {
862 config_matchers: &'a [(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
863 relative_files: &'a [(PathBuf, String)],
864 config_search_roots: &'a [&'a Path],
865 production_mode: bool,
866 candidate_index: Option<&'a ConfigCandidateIndex>,
867 root: &'a Path,
868 result: &'a mut AggregatedPluginResult,
869 regex_errors: &'a mut Vec<PluginRegexValidationError>,
870}
871
872fn select_workspace_matchers<'a>(
875 precompiled_config_matchers: &[(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
876 active: &[&dyn Plugin],
877 skip_config_plugins: &FxHashSet<&str>,
878) -> Vec<(&'a dyn Plugin, Vec<globset::GlobMatcher>)> {
879 let active_names: FxHashSet<&str> = active.iter().map(|p| p.name()).collect();
880 precompiled_config_matchers
881 .iter()
882 .filter(|(p, _)| {
883 active_names.contains(p.name())
884 && (!skip_config_plugins.contains(p.name())
885 || must_parse_workspace_config_when_root_active(p.name()))
886 })
887 .map(|(plugin, matchers)| (*plugin, matchers.clone()))
888 .collect()
889}
890
891struct WorkspaceFsConfigInput<'a> {
892 workspace_matchers: &'a [(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
893 resolved_ws_plugins: &'a FxHashSet<&'a str>,
894 root: &'a Path,
895 project_root: &'a Path,
896 production_mode: bool,
897 candidate_index: Option<&'a ConfigCandidateIndex>,
898 result: &'a mut AggregatedPluginResult,
899 regex_errors: &'a mut Vec<PluginRegexValidationError>,
900}
901
902fn load_workspace_filesystem_configs(input: &mut WorkspaceFsConfigInput<'_>) {
905 let search_roots: &[&Path] = if input.root == input.project_root {
906 &[input.root]
907 } else {
908 &[input.root, input.project_root]
909 };
910 let ws_json_configs = discover_config_files(
911 input.workspace_matchers,
912 input.resolved_ws_plugins,
913 search_roots,
914 input.production_mode,
915 input.candidate_index,
916 );
917 for (abs_path, plugin) in &ws_json_configs {
918 let Ok(source) = std::fs::read_to_string(abs_path) else {
919 continue;
920 };
921 let plugin_result = plugin.resolve_config(abs_path, &source, input.root);
922 if plugin_result.is_empty() {
923 continue;
924 }
925 let rel = abs_path
926 .strip_prefix(input.project_root)
927 .map(|p| p.to_string_lossy())
928 .unwrap_or_default();
929 tracing::debug!(
930 plugin = plugin.name(),
931 config = %rel,
932 entries = plugin_result.entry_patterns.len(),
933 deps = plugin_result.referenced_dependencies.len(),
934 "resolved config (workspace filesystem fallback)"
935 );
936 if let Err(mut errors) =
937 process_config_result(plugin.name(), plugin_result, input.result, Some(abs_path))
938 {
939 input.regex_errors.append(&mut errors);
940 }
941 }
942}
943
944fn resolve_plugin_config_files(input: &mut PluginConfigResolutionInput<'_>) {
945 if input.config_matchers.is_empty() {
946 return;
947 }
948
949 let mut resolved_plugins: FxHashSet<&str> = FxHashSet::default();
950 for (plugin, matchers) in input.config_matchers {
951 resolve_plugin_matching_files(&mut PluginMatchingFilesInput {
952 plugin: *plugin,
953 matchers,
954 relative_files: input.relative_files,
955 root: input.root,
956 result: input.result,
957 regex_errors: input.regex_errors,
958 resolved_plugins: &mut resolved_plugins,
959 });
960 }
961
962 let json_configs = discover_config_files(
963 input.config_matchers,
964 &resolved_plugins,
965 input.config_search_roots,
966 input.production_mode,
967 input.candidate_index,
968 );
969 for (abs_path, plugin) in &json_configs {
970 resolve_plugin_filesystem_config(
971 *plugin,
972 abs_path,
973 input.root,
974 input.result,
975 input.regex_errors,
976 );
977 }
978}
979
980struct PluginMatchingFilesInput<'plugins, 'data, 'state> {
981 plugin: &'plugins dyn Plugin,
982 matchers: &'data [globset::GlobMatcher],
983 relative_files: &'data [(PathBuf, String)],
984 root: &'data Path,
985 result: &'state mut AggregatedPluginResult,
986 regex_errors: &'state mut Vec<PluginRegexValidationError>,
987 resolved_plugins: &'state mut FxHashSet<&'plugins str>,
988}
989
990fn resolve_plugin_matching_files(input: &mut PluginMatchingFilesInput<'_, '_, '_>) {
991 use rayon::prelude::*;
992
993 let plugin_hits: Vec<&PathBuf> = input
994 .relative_files
995 .par_iter()
996 .filter_map(|(abs_path, rel_path)| {
997 input
998 .matchers
999 .iter()
1000 .any(|m| m.is_match(rel_path.as_str()))
1001 .then_some(abs_path)
1002 })
1003 .collect();
1004 for abs_path in plugin_hits {
1005 let Ok(source) = std::fs::read_to_string(abs_path) else {
1006 continue;
1007 };
1008 let plugin_result = input.plugin.resolve_config(abs_path, &source, input.root);
1009 if plugin_result.is_empty() {
1010 continue;
1011 }
1012 input.resolved_plugins.insert(input.plugin.name());
1013 process_resolved_plugin_config(ResolvedPluginConfigInput {
1014 plugin: input.plugin,
1015 abs_path,
1016 plugin_result,
1017 result: input.result,
1018 regex_errors: input.regex_errors,
1019 message: "resolved config",
1020 config_display: abs_path.display(),
1021 });
1022 }
1023}
1024
1025fn resolve_plugin_filesystem_config(
1026 plugin: &dyn Plugin,
1027 abs_path: &Path,
1028 root: &Path,
1029 result: &mut AggregatedPluginResult,
1030 regex_errors: &mut Vec<PluginRegexValidationError>,
1031) {
1032 let Ok(source) = std::fs::read_to_string(abs_path) else {
1033 return;
1034 };
1035 let plugin_result = plugin.resolve_config(abs_path, &source, root);
1036 if plugin_result.is_empty() {
1037 return;
1038 }
1039 let rel = abs_path
1040 .strip_prefix(root)
1041 .map(|p| p.to_string_lossy())
1042 .unwrap_or_default();
1043 process_resolved_plugin_config(ResolvedPluginConfigInput {
1044 plugin,
1045 abs_path,
1046 plugin_result,
1047 result,
1048 regex_errors,
1049 message: "resolved config (filesystem fallback)",
1050 config_display: rel,
1051 });
1052}
1053
1054struct ResolvedPluginConfigInput<'a, D> {
1055 plugin: &'a dyn Plugin,
1056 abs_path: &'a Path,
1057 plugin_result: PluginResult,
1058 result: &'a mut AggregatedPluginResult,
1059 regex_errors: &'a mut Vec<PluginRegexValidationError>,
1060 message: &'static str,
1061 config_display: D,
1062}
1063
1064fn process_resolved_plugin_config(input: ResolvedPluginConfigInput<'_, impl std::fmt::Display>) {
1065 tracing::debug!(
1066 plugin = input.plugin.name(),
1067 config = %input.config_display,
1068 entries = input.plugin_result.entry_patterns.len(),
1069 deps = input.plugin_result.referenced_dependencies.len(),
1070 input.message
1071 );
1072 if let Err(mut errors) = process_config_result(
1073 input.plugin.name(),
1074 input.plugin_result,
1075 input.result,
1076 Some(input.abs_path),
1077 ) {
1078 input.regex_errors.append(&mut errors);
1079 }
1080}
1081
1082fn should_warn(key: String) -> bool {
1086 plugin_warn_dedupe()
1087 .lock()
1088 .map_or(true, |mut set| set.insert(key))
1089}
1090
1091#[derive(Debug, Clone, PartialEq, Eq)]
1098pub(crate) enum PluginDiagnostic {
1099 PatternCollision {
1101 pattern: String,
1102 owners: Vec<String>,
1103 },
1104 EnablerTypo {
1107 plugin: String,
1108 enabler: String,
1109 suggestion: String,
1110 },
1111}
1112
1113fn detect_pattern_collisions(
1139 builtin_active: &[&dyn Plugin],
1140 external_active: &[&ExternalPluginDef],
1141) -> Vec<PluginDiagnostic> {
1142 use rustc_hash::FxHashMap;
1143
1144 let mut pattern_owners: FxHashMap<String, (Vec<String>, FxHashSet<String>)> =
1145 FxHashMap::default();
1146
1147 let record = |pattern_owners: &mut FxHashMap<_, (Vec<String>, FxHashSet<String>)>,
1148 pattern: String,
1149 name: String| {
1150 let (list, seen) = pattern_owners.entry(pattern).or_default();
1151 if seen.insert(name.clone()) {
1152 list.push(name);
1153 }
1154 };
1155
1156 for plugin in builtin_active {
1157 for pat in plugin.config_patterns() {
1158 record(
1159 &mut pattern_owners,
1160 (*pat).to_string(),
1161 plugin.name().to_string(),
1162 );
1163 }
1164 }
1165 for ext in external_active {
1166 for pat in &ext.config_patterns {
1167 record(&mut pattern_owners, pat.clone(), ext.name.clone());
1168 }
1169 }
1170
1171 let builtin_names: FxHashSet<&str> = builtin_active.iter().map(|p| p.name()).collect();
1178
1179 let mut findings: Vec<PluginDiagnostic> = pattern_owners
1180 .into_iter()
1181 .filter_map(|(pattern, (owners, _seen))| {
1182 if owners.len() < 2 || owners.iter().all(|o| builtin_names.contains(o.as_str())) {
1183 None
1184 } else {
1185 Some(PluginDiagnostic::PatternCollision { pattern, owners })
1186 }
1187 })
1188 .collect();
1189 findings.sort_unstable_by(|a, b| match (a, b) {
1190 (
1191 PluginDiagnostic::PatternCollision { pattern: ap, .. },
1192 PluginDiagnostic::PatternCollision { pattern: bp, .. },
1193 ) => ap.cmp(bp),
1194 _ => std::cmp::Ordering::Equal,
1195 });
1196 findings
1197}
1198
1199fn detect_enabler_typos(
1214 external_plugins: &[ExternalPluginDef],
1215 all_deps: &[String],
1216) -> Vec<PluginDiagnostic> {
1217 let mut findings = Vec::new();
1218
1219 for ext in external_plugins {
1220 if ext.detection.is_some() || ext.enablers.is_empty() {
1221 continue;
1222 }
1223
1224 let any_match = ext.enablers.iter().any(|enabler| {
1225 if enabler.ends_with('/') {
1226 all_deps.iter().any(|d| d.starts_with(enabler))
1227 } else {
1228 all_deps.iter().any(|d| d == enabler)
1229 }
1230 });
1231 if any_match {
1232 continue;
1233 }
1234
1235 for enabler in &ext.enablers {
1236 let candidates = all_deps.iter().map(String::as_str);
1237 let Some(suggestion) = fallow_config::levenshtein::closest_match(enabler, candidates)
1238 else {
1239 continue;
1240 };
1241
1242 findings.push(PluginDiagnostic::EnablerTypo {
1243 plugin: ext.name.clone(),
1244 enabler: enabler.clone(),
1245 suggestion: suggestion.to_string(),
1246 });
1247 }
1248 }
1249
1250 findings
1251}
1252
1253fn emit_plugin_diagnostics(findings: &[PluginDiagnostic]) {
1256 for finding in findings {
1257 match finding {
1258 PluginDiagnostic::PatternCollision { pattern, owners } => {
1259 let key = format!("collision::{pattern}::{owners:?}");
1260 if !should_warn(key) {
1261 continue;
1262 }
1263 let winner = &owners[0];
1264 let others = owners[1..].join(", ");
1265 tracing::warn!(
1266 "plugin config_patterns collision: identical pattern \
1267 '{pattern}' is claimed by plugins [{joined}]; '{winner}' \
1268 runs first (registration order), others ({others}) \
1269 follow. Rename one of the patterns or remove the \
1270 duplicate plugin to make resolution explicit. A future \
1271 release may reject identical-pattern collisions.",
1272 joined = owners.join(", "),
1273 );
1274 }
1275 PluginDiagnostic::EnablerTypo {
1276 plugin,
1277 enabler,
1278 suggestion,
1279 } => {
1280 let key = format!("enabler::{plugin}::{enabler}");
1281 if !should_warn(key) {
1282 continue;
1283 }
1284 tracing::warn!(
1285 "plugin '{plugin}' enabler '{enabler}' does not match any \
1286 dependency in package.json; did you mean '{suggestion}'? \
1287 The plugin will not activate. A future release may reject \
1288 unmatched enablers.",
1289 );
1290 }
1291 }
1292 }
1293}
1294
1295fn process_package_json_inline_configs(
1300 active: &[&dyn Plugin],
1301 config_matchers: &[(&dyn Plugin, Vec<globset::GlobMatcher>)],
1302 relative_files: &[(PathBuf, String)],
1303 root: &Path,
1304 result: &mut AggregatedPluginResult,
1305 regex_errors: &mut Vec<PluginRegexValidationError>,
1306) {
1307 for plugin in active {
1308 let Some(key) = plugin.package_json_config_key() else {
1309 continue;
1310 };
1311 if check_has_config_file(*plugin, config_matchers, relative_files) {
1312 continue;
1313 }
1314 let pkg_path = root.join("package.json");
1315 let Ok(content) = std::fs::read_to_string(&pkg_path) else {
1316 continue;
1317 };
1318 let Ok(json) = serde_json::from_str::<serde_json::Value>(&content) else {
1319 continue;
1320 };
1321 let Some(config_value) = json.get(key) else {
1322 continue;
1323 };
1324 let config_json = serde_json::to_string(config_value).unwrap_or_default();
1325 let fake_path = root.join(format!("{key}.config.json"));
1326 let plugin_result = plugin.resolve_config(&fake_path, &config_json, root);
1327 if plugin_result.is_empty() {
1328 continue;
1329 }
1330 tracing::debug!(
1331 plugin = plugin.name(),
1332 key = key,
1333 "resolved inline package.json config"
1334 );
1335 if let Err(mut errors) =
1336 process_config_result(plugin.name(), plugin_result, result, Some(&pkg_path))
1337 {
1338 regex_errors.append(&mut errors);
1339 }
1340 }
1341}
1342
1343#[derive(Debug)]
1346struct MetaFrameworkWarning {
1347 dedupe_key: &'static str,
1348 message: &'static str,
1349}
1350
1351fn missing_meta_framework_prerequisites(
1361 active_plugins: &[&dyn Plugin],
1362 root: &Path,
1363) -> Vec<MetaFrameworkWarning> {
1364 active_plugins
1365 .iter()
1366 .filter_map(|plugin| match plugin.name() {
1367 "nuxt" if !root.join(".nuxt/tsconfig.json").exists() => Some(MetaFrameworkWarning {
1368 dedupe_key: "meta-prereq::nuxt",
1369 message: "Nuxt project missing .nuxt/tsconfig.json: run `nuxt prepare` \
1370 before fallow for accurate analysis",
1371 }),
1372 "astro" if !root.join(".astro").exists() => Some(MetaFrameworkWarning {
1373 dedupe_key: "meta-prereq::astro",
1374 message: "Astro project missing .astro/ types: run `astro sync` \
1375 before fallow for accurate analysis",
1376 }),
1377 _ => None,
1378 })
1379 .collect()
1380}
1381
1382fn check_meta_framework_prerequisites(active_plugins: &[&dyn Plugin], root: &Path) {
1392 for warning in missing_meta_framework_prerequisites(active_plugins, root) {
1393 if should_warn(warning.dedupe_key.to_owned()) {
1394 tracing::warn!("{}", warning.message);
1395 }
1396 }
1397}
1398
1399fn script_activation_packages(
1400 pkg: &PackageJson,
1401 root: &Path,
1402 all_deps: &[String],
1403 production_mode: bool,
1404) -> FxHashSet<String> {
1405 let Some(pkg_scripts) = pkg.scripts.as_ref() else {
1406 return FxHashSet::default();
1407 };
1408
1409 let scripts_to_analyze = if production_mode {
1410 scripts::filter_production_scripts(pkg_scripts)
1411 } else {
1412 pkg_scripts.clone()
1413 };
1414
1415 let mut nm_roots = Vec::new();
1416 if root.join("node_modules").is_dir() {
1417 nm_roots.push(root);
1418 }
1419 let bin_map = scripts::build_bin_to_package_map(&nm_roots, all_deps);
1420 let dep_set: FxHashSet<String> = all_deps.iter().cloned().collect();
1421 let catalog =
1422 scripts::ScriptCatalog::from_scripts_with_bodies(pkg_scripts, &scripts_to_analyze);
1423
1424 scripts::analyze_scripts_with_dependency_context(
1425 &scripts_to_analyze,
1426 root,
1427 &bin_map,
1428 &dep_set,
1429 &catalog,
1430 )
1431 .used_packages
1432}
1433
1434#[cfg(test)]
1435mod tests;