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, Default)]
388pub struct AggregatedPluginResult {
389 pub entry_patterns: Vec<(PathRule, String)>,
391 pub replaced_entry_plugins: FxHashSet<String>,
396 pub config_entry_patterns: FxHashSet<(String, String)>,
400 pub entry_point_roles: rustc_hash::FxHashMap<String, EntryPointRole>,
402 pub config_patterns: Vec<String>,
404 pub always_used: Vec<(String, String)>,
406 pub used_exports: Vec<PluginUsedExportRule>,
408 pub config_export_credits: Vec<PluginUsedExportRule>,
416 pub used_class_members: Vec<UsedClassMemberRule>,
420 pub framework_class_member_contracts: Vec<fallow_types::semantic::SemanticFrameworkContract>,
422 pub referenced_dependencies: Vec<String>,
424 pub package_referenced_dependencies: Vec<(PathBuf, String)>,
426 pub required_dependencies: Vec<super::RequiredDependency>,
428 pub discovered_always_used: Vec<(String, String)>,
430 pub setup_files: Vec<(PathBuf, String)>,
432 pub tooling_dependencies: Vec<String>,
436 pub plugin_tooling: Vec<PluginToolingDependencies>,
440 pub script_used_packages: FxHashSet<String>,
442 pub dependency_binaries: crate::scripts::DependencyBinaries,
446 pub dev_dependency_names: FxHashSet<String>,
451 pub virtual_module_prefixes: Vec<String>,
454 pub virtual_package_suffixes: Vec<String>,
457 pub generated_import_patterns: Vec<String>,
460 pub generated_type_import_prefixes: Vec<String>,
463 pub path_aliases: Vec<(String, String)>,
466 pub scoped_path_aliases: Vec<fallow_graph::resolve::ScopedPathAlias>,
471 pub auto_imports: Vec<AutoImportRule>,
475 pub active_plugins: Vec<String>,
477 pub fixture_patterns: Vec<(String, String)>,
479 pub scss_include_paths: Vec<PathBuf>,
484 pub static_dir_mappings: Vec<(PathBuf, String)>,
486 pub framework_static_dir_mappings: Vec<(PathBuf, String)>,
489 pub provided_dependencies: Vec<ProvidedDependencyRule>,
491 pub config_diagnostics: Vec<super::PluginConfigDiagnostic>,
495 pub federation_sources: Vec<super::FederationSource>,
498 pub jsx_import_sources: Vec<JsxImportSourceRule>,
502 pub jsx_package_credits: Vec<JsxImportSourceRule>,
507 pub tsconfig_jsx_dirs: Vec<PathBuf>,
511}
512
513fn extend_unique(target: &mut Vec<String>, incoming: Vec<String>) {
518 let mut seen: FxHashSet<String> = target.iter().cloned().collect();
519 for item in incoming {
520 if seen.insert(item.clone()) {
521 target.push(item);
522 }
523 }
524}
525
526fn push_missing<T: PartialEq>(target: &mut Vec<T>, incoming: Vec<T>) {
529 for item in incoming {
530 if !target.contains(&item) {
531 target.push(item);
532 }
533 }
534}
535
536fn prefix_if_needed(pat: &str, ws_prefix: &str) -> String {
540 if pat.starts_with(ws_prefix) || pat.starts_with('/') {
541 pat.to_string()
542 } else {
543 format!("{ws_prefix}/{pat}")
544 }
545}
546
547impl AggregatedPluginResult {
548 pub(crate) fn unique_entry_patterns(&self) -> impl Iterator<Item = &(PathRule, String)> {
554 let mut seen: FxHashSet<&(PathRule, String)> = FxHashSet::default();
555 self.entry_patterns
556 .iter()
557 .filter(move |entry| seen.insert(entry))
558 }
559
560 pub(crate) fn apply_workspace_prefix(&mut self, ws_prefix: &str) {
576 for (rule, _) in &mut self.entry_patterns {
577 *rule = rule.prefixed(ws_prefix);
578 }
579 for (pat, _) in &mut self.always_used {
580 *pat = prefix_if_needed(pat, ws_prefix);
581 }
582 for (pat, _) in &mut self.discovered_always_used {
583 *pat = prefix_if_needed(pat, ws_prefix);
584 }
585 for (pat, _) in &mut self.fixture_patterns {
586 *pat = prefix_if_needed(pat, ws_prefix);
587 }
588 for rule in &mut self.used_exports {
589 *rule = rule.prefixed(ws_prefix);
590 }
591 for rule in &mut self.config_export_credits {
592 *rule = rule.prefixed(ws_prefix);
593 }
594 for rule in &mut self.provided_dependencies {
595 *rule = rule.prefixed(ws_prefix);
596 }
597 for source in &mut self.federation_sources {
598 *source = source.prefixed(ws_prefix);
599 }
600 if !ws_prefix.is_empty() {
601 self.scoped_path_aliases
602 .extend(self.path_aliases.drain(..).map(|(prefix, replacement)| {
603 fallow_graph::resolve::ScopedPathAlias {
604 scope: ws_prefix.to_string(),
605 prefix,
606 replacement: format!("{ws_prefix}/{replacement}"),
607 }
608 }));
609 }
610 }
611
612 pub(crate) fn merge_into(&mut self, other: Self) {
626 let Self {
627 entry_patterns,
628 replaced_entry_plugins: _,
630 config_entry_patterns: _,
631 entry_point_roles,
632 config_patterns,
633 always_used,
634 used_exports,
635 config_export_credits,
636 used_class_members,
637 framework_class_member_contracts,
638 referenced_dependencies,
639 package_referenced_dependencies,
640 required_dependencies,
641 discovered_always_used,
642 setup_files,
643 tooling_dependencies,
644 plugin_tooling,
645 script_used_packages,
646 dependency_binaries: _,
647 dev_dependency_names,
648 virtual_module_prefixes,
649 virtual_package_suffixes,
650 generated_import_patterns,
651 generated_type_import_prefixes,
652 path_aliases,
653 scoped_path_aliases,
654 auto_imports,
655 active_plugins,
656 fixture_patterns,
657 scss_include_paths,
658 static_dir_mappings,
659 framework_static_dir_mappings,
660 provided_dependencies,
661 config_diagnostics,
662 federation_sources,
663 jsx_import_sources,
664 jsx_package_credits,
665 tsconfig_jsx_dirs,
666 } = other;
667
668 self.entry_patterns.extend(entry_patterns);
669 for (plugin_name, role) in entry_point_roles {
670 self.entry_point_roles.entry(plugin_name).or_insert(role);
671 }
672 self.config_patterns.extend(config_patterns);
673 self.always_used.extend(always_used);
674 self.used_exports.extend(used_exports);
675 self.config_export_credits.extend(config_export_credits);
676 self.used_class_members.extend(used_class_members);
677 for contract in framework_class_member_contracts {
678 if !self.framework_class_member_contracts.contains(&contract) {
679 self.framework_class_member_contracts.push(contract);
680 }
681 }
682 self.referenced_dependencies.extend(referenced_dependencies);
683 self.package_referenced_dependencies
684 .extend(package_referenced_dependencies);
685 push_missing(&mut self.required_dependencies, required_dependencies);
686 self.discovered_always_used.extend(discovered_always_used);
687 self.setup_files.extend(setup_files);
688 self.tooling_dependencies.extend(tooling_dependencies);
689 self.plugin_tooling.extend(plugin_tooling);
690 self.dev_dependency_names.extend(dev_dependency_names);
691 self.script_used_packages.extend(script_used_packages);
692 extend_unique(&mut self.virtual_module_prefixes, virtual_module_prefixes);
693 extend_unique(&mut self.virtual_package_suffixes, virtual_package_suffixes);
694 extend_unique(
695 &mut self.generated_import_patterns,
696 generated_import_patterns,
697 );
698 extend_unique(
699 &mut self.generated_type_import_prefixes,
700 generated_type_import_prefixes,
701 );
702 self.path_aliases.extend(path_aliases);
703 self.scoped_path_aliases.extend(scoped_path_aliases);
704 self.auto_imports.extend(auto_imports);
705 extend_unique(&mut self.active_plugins, active_plugins);
706 self.fixture_patterns.extend(fixture_patterns);
707 self.scss_include_paths.extend(scss_include_paths);
708 self.static_dir_mappings.extend(static_dir_mappings);
709 self.framework_static_dir_mappings
710 .extend(framework_static_dir_mappings);
711 self.provided_dependencies.extend(provided_dependencies);
712 self.federation_sources.extend(federation_sources);
713 push_missing(&mut self.jsx_import_sources, jsx_import_sources);
714 push_missing(&mut self.jsx_package_credits, jsx_package_credits);
715 push_missing(&mut self.tsconfig_jsx_dirs, tsconfig_jsx_dirs);
716 push_missing(&mut self.config_diagnostics, config_diagnostics);
717 }
718}
719
720impl PluginRegistry {
721 #[must_use]
723 pub fn new(external: Vec<ExternalPluginDef>) -> Self {
724 Self {
725 plugins: builtin::create_builtin_plugins(),
726 external_plugins: external,
727 }
728 }
729
730 #[must_use]
734 pub fn bun_preload_files(root: &Path) -> Vec<PathBuf> {
735 super::bun::preload_files(root)
736 }
737
738 #[must_use]
743 pub fn discovery_hidden_dirs(&self, pkg: &PackageJson, root: &Path) -> Vec<String> {
744 let all_deps = pkg.all_dependency_names();
745 let mut seen = FxHashSet::default();
746 let mut dirs = Vec::new();
747
748 for plugin in &self.plugins {
749 if !plugin.is_enabled_with_deps(&all_deps, root) {
750 continue;
751 }
752 for dir in plugin.discovery_hidden_dirs() {
753 if seen.insert(*dir) {
754 dirs.push((*dir).to_string());
755 }
756 }
757 }
758
759 dirs
760 }
761
762 #[cfg(test)]
767 fn run(
768 &self,
769 pkg: &PackageJson,
770 root: &Path,
771 discovered_files: &[PathBuf],
772 ) -> AggregatedPluginResult {
773 self.try_run(pkg, root, discovered_files)
774 .unwrap_or_else(|errors| panic!("{}", format_plugin_regex_errors(&errors)))
775 }
776
777 pub fn try_run(
779 &self,
780 pkg: &PackageJson,
781 root: &Path,
782 discovered_files: &[PathBuf],
783 ) -> Result<AggregatedPluginResult, Vec<PluginRegexValidationError>> {
784 self.try_run_with_search_roots(pkg, root, discovered_files, &[root], false, None)
785 }
786
787 #[expect(
790 clippy::too_many_arguments,
791 reason = "public PluginRegistry API; signature is part of the crate surface for embedders"
792 )]
793 pub(crate) fn try_run_with_search_roots(
794 &self,
795 pkg: &PackageJson,
796 root: &Path,
797 discovered_files: &[PathBuf],
798 config_search_roots: &[&Path],
799 production_mode: bool,
800 candidate_index: Option<&ConfigCandidateIndex>,
801 ) -> Result<AggregatedPluginResult, Vec<PluginRegexValidationError>> {
802 let _span = tracing::info_span!("run_plugins").entered();
803 let mut result = AggregatedPluginResult::default();
804 let mut regex_errors = Vec::new();
805
806 let PluginRunContext { all_deps, active } = self.prepare_plugin_run_context(
807 pkg,
808 root,
809 discovered_files,
810 production_mode,
811 candidate_index,
812 );
813
814 self.run_plugin_preflight(&active, &all_deps, root, discovered_files);
815
816 for plugin in &active {
817 process_static_patterns(*plugin, root, &mut result);
818 }
819 process_package_json_metadata(&active, pkg, root, &mut result, &mut regex_errors);
820
821 process_external_plugins(
822 &self.external_plugins,
823 &all_deps,
824 root,
825 discovered_files,
826 &mut result,
827 );
828 tooling_evidence::record_plugin_tooling(
829 &tooling_evidence::ToolingEvidenceInput {
830 active: &active,
831 external_plugins: &self.external_plugins,
832 all_deps: &all_deps,
833 roots: &[root],
834 extra_roots: if production_mode {
838 &[]
839 } else {
840 config_search_roots
841 },
842 candidate_index,
843 discovered_files,
844 },
845 &mut result,
846 );
847
848 let config_matchers = compile_config_matchers(&active);
849 let relative_files =
850 compute_relative_files(&config_matchers, &active, discovered_files, root);
851
852 resolve_plugin_config_files(&mut PluginConfigResolutionInput {
853 config_matchers: &config_matchers,
854 relative_files: &relative_files,
855 config_search_roots,
856 production_mode,
857 candidate_index,
858 root,
859 result: &mut result,
860 regex_errors: &mut regex_errors,
861 });
862
863 process_package_json_inline_configs(
864 &active,
865 &config_matchers,
866 &relative_files,
867 root,
868 &mut result,
869 &mut regex_errors,
870 );
871
872 if regex_errors.is_empty() {
873 Ok(result)
874 } else {
875 Err(regex_errors)
876 }
877 }
878
879 #[cfg(test)]
885 fn run_workspace_fast(&self, input: &WorkspacePluginRunInput<'_>) -> AggregatedPluginResult {
886 self.try_run_workspace_fast(input)
887 .unwrap_or_else(|errors| panic!("{}", format_plugin_regex_errors(&errors)))
888 }
889
890 pub(crate) fn try_run_workspace_fast(
896 &self,
897 input: &WorkspacePluginRunInput<'_>,
898 ) -> Result<AggregatedPluginResult, Vec<PluginRegexValidationError>> {
899 let _span = tracing::info_span!("run_plugins").entered();
900 let mut result = AggregatedPluginResult::default();
901 let mut regex_errors = Vec::new();
902
903 let (all_deps, script_packages) = workspace_activation_deps(input);
904 let workspace_files: Vec<PathBuf> = input
905 .relative_files
906 .iter()
907 .map(|(abs_path, _)| abs_path.clone())
908 .collect();
909
910 let active = self.collect_active_plugins(&PluginActivationInput {
911 pkg: input.pkg,
912 root: input.root,
913 discovered_files: &workspace_files,
914 all_deps: &all_deps,
915 script_packages: &script_packages,
916 candidate_index: input.candidate_index,
917 });
918
919 log_active_plugins(&active);
920
921 self.emit_silent_fail_diagnostics(&active, &all_deps, input.root, &workspace_files);
922
923 process_external_plugins(
924 &self.external_plugins,
925 &all_deps,
926 input.root,
927 &workspace_files,
928 &mut result,
929 );
930
931 if active.is_empty() && result.active_plugins.is_empty() {
932 return Ok(result);
933 }
934
935 process_workspace_active_plugins(&active, input, &mut result, &mut regex_errors);
936 let evidence_roots: &[&Path] = if input.root == input.project_root {
938 &[input.root]
939 } else {
940 &[input.root, input.project_root]
941 };
942 tooling_evidence::record_plugin_tooling(
943 &tooling_evidence::ToolingEvidenceInput {
944 active: &active,
945 external_plugins: &self.external_plugins,
946 all_deps: &all_deps,
947 roots: evidence_roots,
948 extra_roots: &[],
949 candidate_index: input.candidate_index,
950 discovered_files: &workspace_files,
951 },
952 &mut result,
953 );
954 resolve_workspace_plugin_configs(&active, input, &mut result, &mut regex_errors);
955
956 if regex_errors.is_empty() {
957 Ok(result)
958 } else {
959 Err(regex_errors)
960 }
961 }
962
963 #[must_use]
966 pub(crate) fn precompile_config_matchers(
967 &self,
968 ) -> Vec<(&dyn Plugin, Vec<globset::GlobMatcher>)> {
969 self.plugins
970 .iter()
971 .filter(|p| !p.config_patterns().is_empty())
972 .map(|p| (p.as_ref(), cached_plugin_config_matchers(p.as_ref())))
973 .collect()
974 }
975
976 pub(crate) fn resolve_script_config_files(
987 &self,
988 config_files: &[scripts::BinaryConfigFile],
989 package_root: &Path,
990 project_root: &Path,
991 ws_prefix: &str,
992 ) -> AggregatedPluginResult {
993 let mut aggregated = AggregatedPluginResult::default();
994 for config_file in config_files {
995 let Some(rel_path) =
996 scripts::normalize_script_entry_pattern(ws_prefix, &config_file.path)
997 else {
998 continue;
999 };
1000 let abs_path = package_root.join(config_file.path.trim_start_matches("./"));
1001 let in_package_root = abs_path.parent() == Some(package_root);
1006 for plugin in &self.plugins {
1007 let plugin = plugin.as_ref();
1008 if !plugin
1009 .script_config_binaries()
1010 .contains(&config_file.binary.as_str())
1011 || (in_package_root
1012 && cached_plugin_config_matchers(plugin)
1013 .iter()
1014 .any(|m| m.is_match(rel_path.as_str())))
1015 {
1016 continue;
1017 }
1018 if !super::config_parser::is_inside_root(&abs_path, project_root) {
1019 continue;
1020 }
1021 let Ok(source) = std::fs::read_to_string(&abs_path) else {
1022 continue;
1023 };
1024 let mut file_result = AggregatedPluginResult::default();
1025 file_result
1026 .entry_point_roles
1027 .insert(plugin.name().to_string(), plugin.entry_point_role());
1028 let plugin_result =
1029 plugin.resolve_script_config(&abs_path, &source, package_root, project_root);
1030 if let Err(errors) = process_config_result(
1031 plugin.name(),
1032 plugin_result,
1033 &mut file_result,
1034 Some(&abs_path),
1035 ) {
1036 for error in errors {
1037 tracing::warn!("{error}");
1038 }
1039 continue;
1040 }
1041 if !ws_prefix.is_empty() {
1042 file_result.apply_workspace_prefix(ws_prefix);
1043 }
1044 file_result.used_exports.push(PluginUsedExportRule::new(
1046 plugin.name().to_string(),
1047 super::UsedExportRule::new(rel_path.clone(), ["default"]),
1048 ));
1049 aggregated.merge_into(file_result);
1050 }
1051 }
1052 aggregated
1053 }
1054}
1055
1056fn process_workspace_active_plugins(
1057 active: &[&dyn Plugin],
1058 input: &WorkspacePluginRunInput<'_>,
1059 result: &mut AggregatedPluginResult,
1060 regex_errors: &mut Vec<PluginRegexValidationError>,
1061) {
1062 for plugin in active {
1063 process_static_patterns(*plugin, input.root, result);
1064 }
1065 process_package_json_metadata(active, input.pkg, input.root, result, regex_errors);
1066}
1067
1068fn resolve_workspace_plugin_configs(
1069 active: &[&dyn Plugin],
1070 input: &WorkspacePluginRunInput<'_>,
1071 result: &mut AggregatedPluginResult,
1072 regex_errors: &mut Vec<PluginRegexValidationError>,
1073) {
1074 let workspace_matchers = select_workspace_matchers(
1075 input.precompiled_config_matchers,
1076 active,
1077 input.skip_config_plugins,
1078 );
1079
1080 let mut resolved_ws_plugins: FxHashSet<&str> = FxHashSet::default();
1081 for (plugin, matchers) in &workspace_matchers {
1082 resolve_plugin_matching_files(&mut PluginMatchingFilesInput {
1083 plugin: *plugin,
1084 matchers,
1085 relative_files: input.relative_files,
1086 root: input.root,
1087 project_root: input.project_root,
1088 result,
1089 regex_errors,
1090 resolved_plugins: &mut resolved_ws_plugins,
1091 });
1092 }
1093
1094 load_workspace_filesystem_configs(&mut WorkspaceFsConfigInput {
1095 workspace_matchers: &workspace_matchers,
1096 resolved_ws_plugins: &resolved_ws_plugins,
1097 root: input.root,
1098 project_root: input.project_root,
1099 production_mode: input.production_mode,
1100 candidate_index: input.candidate_index,
1101 result,
1102 regex_errors,
1103 });
1104}
1105
1106impl Default for PluginRegistry {
1107 fn default() -> Self {
1108 Self::new(vec![])
1109 }
1110}
1111
1112impl PluginRegistry {
1113 fn prepare_plugin_run_context<'a>(
1114 &'a self,
1115 pkg: &PackageJson,
1116 root: &Path,
1117 discovered_files: &[PathBuf],
1118 production_mode: bool,
1119 candidate_index: Option<&ConfigCandidateIndex>,
1120 ) -> PluginRunContext<'a> {
1121 let all_deps = pkg.all_dependency_names();
1122 let script_packages =
1123 script_activation_packages(pkg, root, &[root], &all_deps, production_mode);
1124 let active = self.collect_active_plugins(&PluginActivationInput {
1125 pkg,
1126 root,
1127 discovered_files,
1128 all_deps: &all_deps,
1129 script_packages: &script_packages,
1130 candidate_index,
1131 });
1132
1133 PluginRunContext { all_deps, active }
1134 }
1135
1136 fn run_plugin_preflight(
1137 &self,
1138 active: &[&dyn Plugin],
1139 all_deps: &[String],
1140 root: &Path,
1141 discovered_files: &[PathBuf],
1142 ) {
1143 log_active_plugins(active);
1144 check_meta_framework_prerequisites(active, root);
1145 self.emit_silent_fail_diagnostics(active, all_deps, root, discovered_files);
1146 }
1147
1148 fn collect_active_plugins<'a>(
1151 &'a self,
1152 activation: &PluginActivationInput<'_>,
1153 ) -> Vec<&'a dyn Plugin> {
1154 self.plugins
1155 .iter()
1156 .filter(|p| {
1157 p.is_enabled_with_files(
1158 activation.all_deps,
1159 activation.root,
1160 activation.discovered_files,
1161 activation.candidate_index,
1162 ) || p.is_enabled_with_scripts(activation.script_packages, activation.root)
1163 || p.is_enabled_with_package_json(activation.pkg, activation.root)
1164 })
1165 .map(AsRef::as_ref)
1166 .collect()
1167 }
1168
1169 fn emit_silent_fail_diagnostics(
1178 &self,
1179 active: &[&dyn Plugin],
1180 all_deps: &[String],
1181 root: &Path,
1182 discovered_files: &[PathBuf],
1183 ) {
1184 let active_external: Vec<&ExternalPluginDef> = self
1185 .external_plugins
1186 .iter()
1187 .filter(|ext| is_external_plugin_active(ext, all_deps, root, discovered_files))
1188 .collect();
1189 let mut diagnostics = detect_pattern_collisions(active, &active_external);
1190 diagnostics.extend(detect_enabler_typos(&self.external_plugins, all_deps));
1191 emit_plugin_diagnostics(&diagnostics);
1192 }
1193}
1194
1195fn plugin_warn_dedupe() -> &'static std::sync::Mutex<FxHashSet<String>> {
1202 static WARNED: std::sync::OnceLock<std::sync::Mutex<FxHashSet<String>>> =
1203 std::sync::OnceLock::new();
1204 WARNED.get_or_init(|| std::sync::Mutex::new(FxHashSet::default()))
1205}
1206
1207struct PluginConfigResolutionInput<'a> {
1208 config_matchers: &'a [(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
1209 relative_files: &'a [(PathBuf, String)],
1210 config_search_roots: &'a [&'a Path],
1211 production_mode: bool,
1212 candidate_index: Option<&'a ConfigCandidateIndex>,
1213 root: &'a Path,
1214 result: &'a mut AggregatedPluginResult,
1215 regex_errors: &'a mut Vec<PluginRegexValidationError>,
1216}
1217
1218fn select_workspace_matchers<'a>(
1221 precompiled_config_matchers: &[(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
1222 active: &[&dyn Plugin],
1223 skip_config_plugins: &FxHashSet<&str>,
1224) -> Vec<(&'a dyn Plugin, Vec<globset::GlobMatcher>)> {
1225 let active_names: FxHashSet<&str> = active.iter().map(|p| p.name()).collect();
1226 precompiled_config_matchers
1227 .iter()
1228 .filter(|(p, _)| {
1229 active_names.contains(p.name())
1230 && (!skip_config_plugins.contains(p.name())
1231 || must_parse_workspace_config_when_root_active(p.name()))
1232 })
1233 .map(|(plugin, matchers)| (*plugin, matchers.clone()))
1234 .collect()
1235}
1236
1237struct WorkspaceFsConfigInput<'a> {
1238 workspace_matchers: &'a [(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
1239 resolved_ws_plugins: &'a FxHashSet<&'a str>,
1240 root: &'a Path,
1241 project_root: &'a Path,
1242 production_mode: bool,
1243 candidate_index: Option<&'a ConfigCandidateIndex>,
1244 result: &'a mut AggregatedPluginResult,
1245 regex_errors: &'a mut Vec<PluginRegexValidationError>,
1246}
1247
1248fn load_workspace_filesystem_configs(input: &mut WorkspaceFsConfigInput<'_>) {
1251 let search_roots: &[&Path] = if input.root == input.project_root {
1252 &[input.root]
1253 } else {
1254 &[input.root, input.project_root]
1255 };
1256 let ws_json_configs = discover_config_files(
1257 input.workspace_matchers,
1258 input.resolved_ws_plugins,
1259 search_roots,
1260 input.production_mode,
1261 input.candidate_index,
1262 );
1263 for (abs_path, plugin) in &ws_json_configs {
1264 let Ok(source) = std::fs::read_to_string(abs_path) else {
1265 continue;
1266 };
1267 let plugin_result =
1268 plugin.resolve_config_in_project(abs_path, &source, input.root, input.project_root);
1269 if plugin_result.is_empty() {
1270 continue;
1271 }
1272 let rel = abs_path
1273 .strip_prefix(input.project_root)
1274 .map(|p| p.to_string_lossy())
1275 .unwrap_or_default();
1276 tracing::debug!(
1277 plugin = plugin.name(),
1278 config = %rel,
1279 entries = plugin_result.entry_patterns.len(),
1280 deps = plugin_result.referenced_dependencies.len(),
1281 "resolved config (workspace filesystem fallback)"
1282 );
1283 if let Err(mut errors) =
1284 process_config_result(plugin.name(), plugin_result, input.result, Some(abs_path))
1285 {
1286 input.regex_errors.append(&mut errors);
1287 }
1288 }
1289}
1290
1291fn resolve_plugin_config_files(input: &mut PluginConfigResolutionInput<'_>) {
1292 if input.config_matchers.is_empty() {
1293 return;
1294 }
1295
1296 let mut resolved_plugins: FxHashSet<&str> = FxHashSet::default();
1297 for (plugin, matchers) in input.config_matchers {
1298 resolve_plugin_matching_files(&mut PluginMatchingFilesInput {
1299 plugin: *plugin,
1300 matchers,
1301 relative_files: input.relative_files,
1302 root: input.root,
1303 project_root: input.root,
1304 result: input.result,
1305 regex_errors: input.regex_errors,
1306 resolved_plugins: &mut resolved_plugins,
1307 });
1308 }
1309
1310 let json_configs = discover_config_files(
1311 input.config_matchers,
1312 &resolved_plugins,
1313 input.config_search_roots,
1314 input.production_mode,
1315 input.candidate_index,
1316 );
1317 for (abs_path, plugin) in &json_configs {
1318 resolve_plugin_filesystem_config(
1319 *plugin,
1320 abs_path,
1321 input.root,
1322 input.result,
1323 input.regex_errors,
1324 );
1325 }
1326}
1327
1328struct PluginMatchingFilesInput<'plugins, 'data, 'state> {
1329 plugin: &'plugins dyn Plugin,
1330 matchers: &'data [globset::GlobMatcher],
1331 relative_files: &'data [(PathBuf, String)],
1332 root: &'data Path,
1333 project_root: &'data Path,
1334 result: &'state mut AggregatedPluginResult,
1335 regex_errors: &'state mut Vec<PluginRegexValidationError>,
1336 resolved_plugins: &'state mut FxHashSet<&'plugins str>,
1337}
1338
1339fn resolve_plugin_matching_files(input: &mut PluginMatchingFilesInput<'_, '_, '_>) {
1340 use rayon::prelude::*;
1341
1342 let plugin_hits: Vec<&PathBuf> = input
1343 .relative_files
1344 .par_iter()
1345 .filter_map(|(abs_path, rel_path)| {
1346 input
1347 .matchers
1348 .iter()
1349 .any(|m| m.is_match(rel_path.as_str()))
1350 .then_some(abs_path)
1351 })
1352 .collect();
1353 for abs_path in plugin_hits {
1354 let Ok(source) = std::fs::read_to_string(abs_path) else {
1355 continue;
1356 };
1357 let plugin_result = input.plugin.resolve_config_in_project(
1358 abs_path,
1359 &source,
1360 input.root,
1361 input.project_root,
1362 );
1363 if plugin_result.is_empty() {
1364 continue;
1365 }
1366 input.resolved_plugins.insert(input.plugin.name());
1367 process_resolved_plugin_config(ResolvedPluginConfigInput {
1368 plugin: input.plugin,
1369 abs_path,
1370 plugin_result,
1371 result: input.result,
1372 regex_errors: input.regex_errors,
1373 message: "resolved config",
1374 config_display: abs_path.display(),
1375 });
1376 }
1377}
1378
1379fn resolve_plugin_filesystem_config(
1380 plugin: &dyn Plugin,
1381 abs_path: &Path,
1382 root: &Path,
1383 result: &mut AggregatedPluginResult,
1384 regex_errors: &mut Vec<PluginRegexValidationError>,
1385) {
1386 let Ok(source) = std::fs::read_to_string(abs_path) else {
1387 return;
1388 };
1389 let plugin_result = plugin.resolve_config(abs_path, &source, root);
1390 if plugin_result.is_empty() {
1391 return;
1392 }
1393 let rel = abs_path
1394 .strip_prefix(root)
1395 .map(|p| p.to_string_lossy())
1396 .unwrap_or_default();
1397 process_resolved_plugin_config(ResolvedPluginConfigInput {
1398 plugin,
1399 abs_path,
1400 plugin_result,
1401 result,
1402 regex_errors,
1403 message: "resolved config (filesystem fallback)",
1404 config_display: rel,
1405 });
1406}
1407
1408struct ResolvedPluginConfigInput<'a, D> {
1409 plugin: &'a dyn Plugin,
1410 abs_path: &'a Path,
1411 plugin_result: PluginResult,
1412 result: &'a mut AggregatedPluginResult,
1413 regex_errors: &'a mut Vec<PluginRegexValidationError>,
1414 message: &'static str,
1415 config_display: D,
1416}
1417
1418fn process_resolved_plugin_config(input: ResolvedPluginConfigInput<'_, impl std::fmt::Display>) {
1419 tracing::debug!(
1420 plugin = input.plugin.name(),
1421 config = %input.config_display,
1422 entries = input.plugin_result.entry_patterns.len(),
1423 deps = input.plugin_result.referenced_dependencies.len(),
1424 input.message
1425 );
1426 if let Err(mut errors) = process_config_result(
1427 input.plugin.name(),
1428 input.plugin_result,
1429 input.result,
1430 Some(input.abs_path),
1431 ) {
1432 input.regex_errors.append(&mut errors);
1433 }
1434}
1435
1436fn should_warn(key: String) -> bool {
1440 plugin_warn_dedupe()
1441 .lock()
1442 .map_or(true, |mut set| set.insert(key))
1443}
1444
1445#[derive(Debug, Clone, PartialEq, Eq)]
1452enum PluginDiagnostic {
1453 PatternCollision {
1455 pattern: String,
1456 owners: Vec<String>,
1457 },
1458 EnablerTypo {
1461 plugin: String,
1462 enabler: String,
1463 suggestion: String,
1464 },
1465}
1466
1467fn detect_pattern_collisions(
1493 builtin_active: &[&dyn Plugin],
1494 external_active: &[&ExternalPluginDef],
1495) -> Vec<PluginDiagnostic> {
1496 use rustc_hash::FxHashMap;
1497
1498 let mut pattern_owners: FxHashMap<String, (Vec<String>, FxHashSet<String>)> =
1499 FxHashMap::default();
1500
1501 let record = |pattern_owners: &mut FxHashMap<_, (Vec<String>, FxHashSet<String>)>,
1502 pattern: String,
1503 name: String| {
1504 let (list, seen) = pattern_owners.entry(pattern).or_default();
1505 if seen.insert(name.clone()) {
1506 list.push(name);
1507 }
1508 };
1509
1510 for plugin in builtin_active {
1511 for pat in plugin.config_patterns() {
1512 record(
1513 &mut pattern_owners,
1514 (*pat).to_string(),
1515 plugin.name().to_string(),
1516 );
1517 }
1518 }
1519 for ext in external_active {
1520 for pat in &ext.config_patterns {
1521 record(&mut pattern_owners, pat.clone(), ext.name.clone());
1522 }
1523 }
1524
1525 let builtin_names: FxHashSet<&str> = builtin_active.iter().map(|p| p.name()).collect();
1532
1533 let mut findings: Vec<PluginDiagnostic> = pattern_owners
1534 .into_iter()
1535 .filter_map(|(pattern, (owners, _seen))| {
1536 if owners.len() < 2 || owners.iter().all(|o| builtin_names.contains(o.as_str())) {
1537 None
1538 } else {
1539 Some(PluginDiagnostic::PatternCollision { pattern, owners })
1540 }
1541 })
1542 .collect();
1543 findings.sort_unstable_by(|a, b| match (a, b) {
1544 (
1545 PluginDiagnostic::PatternCollision { pattern: ap, .. },
1546 PluginDiagnostic::PatternCollision { pattern: bp, .. },
1547 ) => ap.cmp(bp),
1548 _ => std::cmp::Ordering::Equal,
1549 });
1550 findings
1551}
1552
1553fn detect_enabler_typos(
1568 external_plugins: &[ExternalPluginDef],
1569 all_deps: &[String],
1570) -> Vec<PluginDiagnostic> {
1571 let mut findings = Vec::new();
1572
1573 for ext in external_plugins {
1574 if ext.detection.is_some() || ext.enablers.is_empty() {
1575 continue;
1576 }
1577
1578 let any_match = ext.enablers.iter().any(|enabler| {
1579 if enabler.ends_with('/') {
1580 all_deps.iter().any(|d| d.starts_with(enabler))
1581 } else {
1582 all_deps.iter().any(|d| d == enabler)
1583 }
1584 });
1585 if any_match {
1586 continue;
1587 }
1588
1589 for enabler in &ext.enablers {
1590 let candidates = all_deps.iter().map(String::as_str);
1591 let Some(suggestion) = fallow_config::levenshtein::closest_match(enabler, candidates)
1592 else {
1593 continue;
1594 };
1595
1596 findings.push(PluginDiagnostic::EnablerTypo {
1597 plugin: ext.name.clone(),
1598 enabler: enabler.clone(),
1599 suggestion: suggestion.to_string(),
1600 });
1601 }
1602 }
1603
1604 findings
1605}
1606
1607fn emit_plugin_diagnostics(findings: &[PluginDiagnostic]) {
1610 for finding in findings {
1611 match finding {
1612 PluginDiagnostic::PatternCollision { pattern, owners } => {
1613 let key = format!("collision::{pattern}::{owners:?}");
1614 if !should_warn(key) {
1615 continue;
1616 }
1617 let winner = &owners[0];
1618 let others = owners[1..].join(", ");
1619 tracing::warn!(
1620 "plugin config_patterns collision: identical pattern \
1621 '{pattern}' is claimed by plugins [{joined}]; '{winner}' \
1622 runs first (registration order), others ({others}) \
1623 follow. Rename one of the patterns or remove the \
1624 duplicate plugin to make resolution explicit. A future \
1625 release may reject identical-pattern collisions.",
1626 joined = owners.join(", "),
1627 );
1628 }
1629 PluginDiagnostic::EnablerTypo {
1630 plugin,
1631 enabler,
1632 suggestion,
1633 } => {
1634 let key = format!("enabler::{plugin}::{enabler}");
1635 if !should_warn(key) {
1636 continue;
1637 }
1638 tracing::warn!(
1639 "plugin '{plugin}' enabler '{enabler}' does not match any \
1640 dependency in package.json; did you mean '{suggestion}'? \
1641 The plugin will not activate. A future release may reject \
1642 unmatched enablers.",
1643 );
1644 }
1645 }
1646 }
1647}
1648
1649fn process_package_json_inline_configs(
1654 active: &[&dyn Plugin],
1655 config_matchers: &[(&dyn Plugin, Vec<globset::GlobMatcher>)],
1656 relative_files: &[(PathBuf, String)],
1657 root: &Path,
1658 result: &mut AggregatedPluginResult,
1659 regex_errors: &mut Vec<PluginRegexValidationError>,
1660) {
1661 for plugin in active {
1662 let Some(key) = plugin.package_json_config_key() else {
1663 continue;
1664 };
1665 if check_has_config_file(*plugin, config_matchers, relative_files) {
1666 continue;
1667 }
1668 let pkg_path = root.join("package.json");
1669 let Ok(content) = std::fs::read_to_string(&pkg_path) else {
1670 continue;
1671 };
1672 let Ok(json) = serde_json::from_str::<serde_json::Value>(&content) else {
1673 continue;
1674 };
1675 let Some(config_value) = json.get(key) else {
1676 continue;
1677 };
1678 let config_json = serde_json::to_string(config_value).unwrap_or_default();
1679 let fake_path = root.join(format!("{key}.config.json"));
1680 let plugin_result = plugin.resolve_config(&fake_path, &config_json, root);
1681 if plugin_result.is_empty() {
1682 continue;
1683 }
1684 tracing::debug!(
1685 plugin = plugin.name(),
1686 key = key,
1687 "resolved inline package.json config"
1688 );
1689 if let Err(mut errors) =
1690 process_config_result(plugin.name(), plugin_result, result, Some(&pkg_path))
1691 {
1692 regex_errors.append(&mut errors);
1693 }
1694 }
1695}
1696
1697#[derive(Debug)]
1700struct MetaFrameworkWarning {
1701 dedupe_key: &'static str,
1702 message: &'static str,
1703}
1704
1705fn missing_meta_framework_prerequisites(
1715 active_plugins: &[&dyn Plugin],
1716 root: &Path,
1717) -> Vec<MetaFrameworkWarning> {
1718 active_plugins
1719 .iter()
1720 .filter_map(|plugin| match plugin.name() {
1721 "nuxt" if !root.join(".nuxt/tsconfig.json").exists() => Some(MetaFrameworkWarning {
1722 dedupe_key: "meta-prereq::nuxt",
1723 message: "Nuxt project missing .nuxt/tsconfig.json: run `nuxt prepare` \
1724 before fallow for accurate analysis",
1725 }),
1726 "astro" if !root.join(".astro").exists() => Some(MetaFrameworkWarning {
1727 dedupe_key: "meta-prereq::astro",
1728 message: "Astro project missing .astro/ types: run `astro sync` \
1729 before fallow for accurate analysis",
1730 }),
1731 _ => None,
1732 })
1733 .collect()
1734}
1735
1736fn check_meta_framework_prerequisites(active_plugins: &[&dyn Plugin], root: &Path) {
1746 for warning in missing_meta_framework_prerequisites(active_plugins, root) {
1747 if should_warn(warning.dedupe_key.to_owned()) {
1748 tracing::warn!("{}", warning.message);
1749 }
1750 }
1751}
1752
1753fn workspace_activation_deps(
1762 input: &WorkspacePluginRunInput<'_>,
1763) -> (Vec<String>, FxHashSet<String>) {
1764 let mut deps = input.pkg.all_dependency_names();
1765 let own: FxHashSet<&str> = deps.iter().map(String::as_str).collect();
1766 let hoisted: Vec<String> = input
1767 .root_dependencies
1768 .iter()
1769 .filter(|dep| !own.contains(dep.as_str()))
1770 .cloned()
1771 .collect();
1772 let mut script_deps = deps.clone();
1773 script_deps.extend(hoisted.iter().cloned());
1774 let script_packages = script_activation_packages(
1775 input.pkg,
1776 input.root,
1777 &[input.root, input.project_root],
1778 &script_deps,
1779 input.production_mode,
1780 );
1781 deps.extend(
1782 hoisted
1783 .into_iter()
1784 .filter(|dep| script_packages.contains(dep)),
1785 );
1786 (deps, script_packages)
1787}
1788
1789fn script_activation_packages(
1792 pkg: &PackageJson,
1793 root: &Path,
1794 node_modules_roots: &[&Path],
1795 all_deps: &[String],
1796 production_mode: bool,
1797) -> FxHashSet<String> {
1798 let Some(pkg_scripts) = pkg.scripts.as_ref() else {
1799 return FxHashSet::default();
1800 };
1801
1802 let scripts_to_analyze = if production_mode {
1803 scripts::filter_production_scripts(pkg_scripts)
1804 } else {
1805 pkg_scripts.clone()
1806 };
1807
1808 let mut nm_roots: Vec<&Path> = Vec::new();
1809 for nm_root in node_modules_roots {
1810 if !nm_roots.contains(nm_root) && nm_root.join("node_modules").is_dir() {
1811 nm_roots.push(nm_root);
1812 }
1813 }
1814 let bin_map = scripts::build_bin_to_package_map(&nm_roots, all_deps);
1815 let dep_set: FxHashSet<String> = all_deps.iter().cloned().collect();
1816 let catalog =
1817 scripts::ScriptCatalog::from_scripts_with_bodies(pkg_scripts, &scripts_to_analyze);
1818
1819 scripts::analyze_scripts_with_dependency_context(
1820 &scripts_to_analyze,
1821 root,
1822 &bin_map,
1823 &dep_set,
1824 &catalog,
1825 scripts::IgnoredCommandEntries::NONE,
1826 )
1827 .used_packages
1828}
1829
1830#[cfg(test)]
1831mod entry_pattern_tests;
1832#[cfg(test)]
1833mod tests;