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 WorkspacePluginRunInput<'a> {
220 pub(crate) pkg: &'a PackageJson,
221 pub(crate) root: &'a Path,
222 pub(crate) project_root: &'a Path,
223 pub(crate) precompiled_config_matchers: &'a [(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
224 pub(crate) relative_files: &'a [(PathBuf, String)],
225 pub(crate) skip_config_plugins: &'a FxHashSet<&'a str>,
226 pub(crate) production_mode: bool,
227 pub(crate) candidate_index: Option<&'a ConfigCandidateIndex>,
228}
229
230struct PluginRunContext<'a> {
231 all_deps: Vec<String>,
232 active: Vec<&'a dyn Plugin>,
233}
234
235struct PluginActivationInput<'a> {
237 pkg: &'a PackageJson,
238 root: &'a Path,
239 discovered_files: &'a [PathBuf],
240 all_deps: &'a [String],
241 script_packages: &'a FxHashSet<String>,
242 candidate_index: Option<&'a ConfigCandidateIndex>,
243}
244
245#[derive(Debug, Clone, PartialEq, Eq)]
247pub struct PluginRegexValidationError {
248 plugin_name: String,
249 config_path: Option<PathBuf>,
250 rule_kind: &'static str,
251 field: &'static str,
252 rule_pattern: String,
253 regex_pattern: String,
254 source: String,
255}
256
257impl PluginRegexValidationError {
258 fn new(input: PluginRegexValidationErrorInput<'_>) -> Self {
259 Self {
260 plugin_name: input.plugin_name.to_owned(),
261 config_path: input.config_path.map(Path::to_path_buf),
262 rule_kind: input.rule_kind,
263 field: input.field,
264 rule_pattern: input.rule_pattern.to_owned(),
265 regex_pattern: input.regex_pattern.to_owned(),
266 source: input.source.to_string(),
267 }
268 }
269}
270
271#[derive(Clone, Copy)]
272struct PluginRegexValidationErrorInput<'a> {
273 plugin_name: &'a str,
274 config_path: Option<&'a Path>,
275 rule_kind: &'static str,
276 field: &'static str,
277 rule_pattern: &'a str,
278 regex_pattern: &'a str,
279 source: &'a regex::Error,
280}
281
282impl fmt::Display for PluginRegexValidationError {
283 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
284 let location = self
285 .config_path
286 .as_ref()
287 .map(|path| format!(" in {}", path.display()))
288 .unwrap_or_default();
289 write!(
290 f,
291 "plugin '{}'{}: invalid regex '{}' in {}.{} for path rule '{}': {}",
292 self.plugin_name,
293 location,
294 self.regex_pattern,
295 self.rule_kind,
296 self.field,
297 self.rule_pattern,
298 self.source
299 )
300 }
301}
302
303#[must_use]
304pub(crate) fn format_plugin_regex_errors(errors: &[PluginRegexValidationError]) -> String {
305 let joined = errors
306 .iter()
307 .map(ToString::to_string)
308 .collect::<Vec<_>>()
309 .join("\n - ");
310 format!(
311 "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."
312 )
313}
314
315#[derive(Debug, Clone, Default, PartialEq, Eq)]
323pub struct PluginToolingDependencies {
324 pub plugin: String,
326 pub dependencies: Vec<String>,
328 pub references: Vec<String>,
332 pub own_config: Option<PathBuf>,
335}
336
337#[derive(Debug, Clone, Copy, PartialEq, Eq)]
339pub enum PluginToolingEvidence<'a> {
340 OwnConfig(&'a Path),
342 Reference(&'a str),
344}
345
346impl PluginToolingDependencies {
347 #[must_use]
351 pub fn evidence<'a>(
352 &'a self,
353 script_used_packages: &FxHashSet<String>,
354 ) -> Option<PluginToolingEvidence<'a>> {
355 if let Some(config) = &self.own_config {
356 return Some(PluginToolingEvidence::OwnConfig(config));
357 }
358 self.references
359 .iter()
360 .find(|name| script_used_packages.contains(name.as_str()))
361 .map(|name| PluginToolingEvidence::Reference(name))
362 }
363}
364
365#[derive(Debug, Clone, Default)]
367pub struct AggregatedPluginResult {
368 pub entry_patterns: Vec<(PathRule, String)>,
370 pub replaced_entry_plugins: FxHashSet<String>,
375 pub config_entry_patterns: FxHashSet<(String, String)>,
379 pub entry_point_roles: rustc_hash::FxHashMap<String, EntryPointRole>,
381 pub config_patterns: Vec<String>,
383 pub always_used: Vec<(String, String)>,
385 pub used_exports: Vec<PluginUsedExportRule>,
387 pub config_export_credits: Vec<PluginUsedExportRule>,
395 pub used_class_members: Vec<UsedClassMemberRule>,
399 pub framework_class_member_contracts: Vec<fallow_types::semantic::SemanticFrameworkContract>,
401 pub referenced_dependencies: Vec<String>,
403 pub package_referenced_dependencies: Vec<(PathBuf, String)>,
405 pub required_dependencies: Vec<super::RequiredDependency>,
407 pub discovered_always_used: Vec<(String, String)>,
409 pub setup_files: Vec<(PathBuf, String)>,
411 pub tooling_dependencies: Vec<String>,
415 pub plugin_tooling: Vec<PluginToolingDependencies>,
419 pub script_used_packages: FxHashSet<String>,
421 pub dependency_binaries: crate::scripts::DependencyBinaries,
425 pub dev_dependency_names: FxHashSet<String>,
430 pub virtual_module_prefixes: Vec<String>,
433 pub virtual_package_suffixes: Vec<String>,
436 pub generated_import_patterns: Vec<String>,
439 pub generated_type_import_prefixes: Vec<String>,
442 pub path_aliases: Vec<(String, String)>,
445 pub auto_imports: Vec<AutoImportRule>,
449 pub active_plugins: Vec<String>,
451 pub fixture_patterns: Vec<(String, String)>,
453 pub scss_include_paths: Vec<PathBuf>,
458 pub static_dir_mappings: Vec<(PathBuf, String)>,
460 pub framework_static_dir_mappings: Vec<(PathBuf, String)>,
463 pub provided_dependencies: Vec<ProvidedDependencyRule>,
465 pub config_diagnostics: Vec<super::PluginConfigDiagnostic>,
469 pub federation_sources: Vec<super::FederationSource>,
472 pub jsx_import_sources: Vec<JsxImportSourceRule>,
476 pub jsx_package_credits: Vec<JsxImportSourceRule>,
481 pub tsconfig_jsx_dirs: Vec<PathBuf>,
485}
486
487fn extend_unique(target: &mut Vec<String>, incoming: Vec<String>) {
492 let mut seen: FxHashSet<String> = target.iter().cloned().collect();
493 for item in incoming {
494 if seen.insert(item.clone()) {
495 target.push(item);
496 }
497 }
498}
499
500fn push_missing<T: PartialEq>(target: &mut Vec<T>, incoming: Vec<T>) {
503 for item in incoming {
504 if !target.contains(&item) {
505 target.push(item);
506 }
507 }
508}
509
510fn prefix_if_needed(pat: &str, ws_prefix: &str) -> String {
514 if pat.starts_with(ws_prefix) || pat.starts_with('/') {
515 pat.to_string()
516 } else {
517 format!("{ws_prefix}/{pat}")
518 }
519}
520
521impl AggregatedPluginResult {
522 pub(crate) fn unique_entry_patterns(&self) -> impl Iterator<Item = &(PathRule, String)> {
528 let mut seen: FxHashSet<&(PathRule, String)> = FxHashSet::default();
529 self.entry_patterns
530 .iter()
531 .filter(move |entry| seen.insert(entry))
532 }
533
534 pub(crate) fn apply_workspace_prefix(&mut self, ws_prefix: &str) {
550 for (rule, _) in &mut self.entry_patterns {
551 *rule = rule.prefixed(ws_prefix);
552 }
553 for (pat, _) in &mut self.always_used {
554 *pat = prefix_if_needed(pat, ws_prefix);
555 }
556 for (pat, _) in &mut self.discovered_always_used {
557 *pat = prefix_if_needed(pat, ws_prefix);
558 }
559 for (pat, _) in &mut self.fixture_patterns {
560 *pat = prefix_if_needed(pat, ws_prefix);
561 }
562 for rule in &mut self.used_exports {
563 *rule = rule.prefixed(ws_prefix);
564 }
565 for rule in &mut self.config_export_credits {
566 *rule = rule.prefixed(ws_prefix);
567 }
568 for rule in &mut self.provided_dependencies {
569 *rule = rule.prefixed(ws_prefix);
570 }
571 for source in &mut self.federation_sources {
572 *source = source.prefixed(ws_prefix);
573 }
574 for (_, replacement) in &mut self.path_aliases {
575 *replacement = format!("{ws_prefix}/{replacement}");
576 }
577 }
578
579 pub(crate) fn merge_into(&mut self, other: Self) {
593 let Self {
594 entry_patterns,
595 replaced_entry_plugins: _,
597 config_entry_patterns: _,
598 entry_point_roles,
599 config_patterns,
600 always_used,
601 used_exports,
602 config_export_credits,
603 used_class_members,
604 framework_class_member_contracts,
605 referenced_dependencies,
606 package_referenced_dependencies,
607 required_dependencies,
608 discovered_always_used,
609 setup_files,
610 tooling_dependencies,
611 plugin_tooling,
612 script_used_packages,
613 dependency_binaries: _,
614 dev_dependency_names,
615 virtual_module_prefixes,
616 virtual_package_suffixes,
617 generated_import_patterns,
618 generated_type_import_prefixes,
619 path_aliases,
620 auto_imports,
621 active_plugins,
622 fixture_patterns,
623 scss_include_paths,
624 static_dir_mappings,
625 framework_static_dir_mappings,
626 provided_dependencies,
627 config_diagnostics,
628 federation_sources,
629 jsx_import_sources,
630 jsx_package_credits,
631 tsconfig_jsx_dirs,
632 } = other;
633
634 self.entry_patterns.extend(entry_patterns);
635 for (plugin_name, role) in entry_point_roles {
636 self.entry_point_roles.entry(plugin_name).or_insert(role);
637 }
638 self.config_patterns.extend(config_patterns);
639 self.always_used.extend(always_used);
640 self.used_exports.extend(used_exports);
641 self.config_export_credits.extend(config_export_credits);
642 self.used_class_members.extend(used_class_members);
643 for contract in framework_class_member_contracts {
644 if !self.framework_class_member_contracts.contains(&contract) {
645 self.framework_class_member_contracts.push(contract);
646 }
647 }
648 self.referenced_dependencies.extend(referenced_dependencies);
649 self.package_referenced_dependencies
650 .extend(package_referenced_dependencies);
651 push_missing(&mut self.required_dependencies, required_dependencies);
652 self.discovered_always_used.extend(discovered_always_used);
653 self.setup_files.extend(setup_files);
654 self.tooling_dependencies.extend(tooling_dependencies);
655 self.plugin_tooling.extend(plugin_tooling);
656 self.dev_dependency_names.extend(dev_dependency_names);
657 self.script_used_packages.extend(script_used_packages);
658 extend_unique(&mut self.virtual_module_prefixes, virtual_module_prefixes);
659 extend_unique(&mut self.virtual_package_suffixes, virtual_package_suffixes);
660 extend_unique(
661 &mut self.generated_import_patterns,
662 generated_import_patterns,
663 );
664 extend_unique(
665 &mut self.generated_type_import_prefixes,
666 generated_type_import_prefixes,
667 );
668 self.path_aliases.extend(path_aliases);
669 self.auto_imports.extend(auto_imports);
670 extend_unique(&mut self.active_plugins, active_plugins);
671 self.fixture_patterns.extend(fixture_patterns);
672 self.scss_include_paths.extend(scss_include_paths);
673 self.static_dir_mappings.extend(static_dir_mappings);
674 self.framework_static_dir_mappings
675 .extend(framework_static_dir_mappings);
676 self.provided_dependencies.extend(provided_dependencies);
677 self.federation_sources.extend(federation_sources);
678 push_missing(&mut self.jsx_import_sources, jsx_import_sources);
679 push_missing(&mut self.jsx_package_credits, jsx_package_credits);
680 push_missing(&mut self.tsconfig_jsx_dirs, tsconfig_jsx_dirs);
681 push_missing(&mut self.config_diagnostics, config_diagnostics);
682 }
683}
684
685impl PluginRegistry {
686 #[must_use]
688 pub fn new(external: Vec<ExternalPluginDef>) -> Self {
689 Self {
690 plugins: builtin::create_builtin_plugins(),
691 external_plugins: external,
692 }
693 }
694
695 #[must_use]
700 pub fn discovery_hidden_dirs(&self, pkg: &PackageJson, root: &Path) -> Vec<String> {
701 let all_deps = pkg.all_dependency_names();
702 let mut seen = FxHashSet::default();
703 let mut dirs = Vec::new();
704
705 for plugin in &self.plugins {
706 if !plugin.is_enabled_with_deps(&all_deps, root) {
707 continue;
708 }
709 for dir in plugin.discovery_hidden_dirs() {
710 if seen.insert(*dir) {
711 dirs.push((*dir).to_string());
712 }
713 }
714 }
715
716 dirs
717 }
718
719 #[cfg(test)]
724 fn run(
725 &self,
726 pkg: &PackageJson,
727 root: &Path,
728 discovered_files: &[PathBuf],
729 ) -> AggregatedPluginResult {
730 self.try_run(pkg, root, discovered_files)
731 .unwrap_or_else(|errors| panic!("{}", format_plugin_regex_errors(&errors)))
732 }
733
734 pub fn try_run(
736 &self,
737 pkg: &PackageJson,
738 root: &Path,
739 discovered_files: &[PathBuf],
740 ) -> Result<AggregatedPluginResult, Vec<PluginRegexValidationError>> {
741 self.try_run_with_search_roots(pkg, root, discovered_files, &[root], false, None)
742 }
743
744 #[expect(
747 clippy::too_many_arguments,
748 reason = "public PluginRegistry API; signature is part of the crate surface for embedders"
749 )]
750 pub(crate) fn try_run_with_search_roots(
751 &self,
752 pkg: &PackageJson,
753 root: &Path,
754 discovered_files: &[PathBuf],
755 config_search_roots: &[&Path],
756 production_mode: bool,
757 candidate_index: Option<&ConfigCandidateIndex>,
758 ) -> Result<AggregatedPluginResult, Vec<PluginRegexValidationError>> {
759 let _span = tracing::info_span!("run_plugins").entered();
760 let mut result = AggregatedPluginResult::default();
761 let mut regex_errors = Vec::new();
762
763 let PluginRunContext { all_deps, active } = self.prepare_plugin_run_context(
764 pkg,
765 root,
766 discovered_files,
767 production_mode,
768 candidate_index,
769 );
770
771 self.run_plugin_preflight(&active, &all_deps, root, discovered_files);
772
773 for plugin in &active {
774 process_static_patterns(*plugin, root, &mut result);
775 }
776 process_package_json_metadata(&active, pkg, root, &mut result, &mut regex_errors);
777
778 process_external_plugins(
779 &self.external_plugins,
780 &all_deps,
781 root,
782 discovered_files,
783 &mut result,
784 );
785 tooling_evidence::record_plugin_tooling(
786 &tooling_evidence::ToolingEvidenceInput {
787 active: &active,
788 external_plugins: &self.external_plugins,
789 all_deps: &all_deps,
790 roots: &[root],
791 extra_roots: if production_mode {
795 &[]
796 } else {
797 config_search_roots
798 },
799 candidate_index,
800 discovered_files,
801 },
802 &mut result,
803 );
804
805 let config_matchers = compile_config_matchers(&active);
806 let relative_files =
807 compute_relative_files(&config_matchers, &active, discovered_files, root);
808
809 resolve_plugin_config_files(&mut PluginConfigResolutionInput {
810 config_matchers: &config_matchers,
811 relative_files: &relative_files,
812 config_search_roots,
813 production_mode,
814 candidate_index,
815 root,
816 result: &mut result,
817 regex_errors: &mut regex_errors,
818 });
819
820 process_package_json_inline_configs(
821 &active,
822 &config_matchers,
823 &relative_files,
824 root,
825 &mut result,
826 &mut regex_errors,
827 );
828
829 if regex_errors.is_empty() {
830 Ok(result)
831 } else {
832 Err(regex_errors)
833 }
834 }
835
836 #[cfg(test)]
842 fn run_workspace_fast(&self, input: &WorkspacePluginRunInput<'_>) -> AggregatedPluginResult {
843 self.try_run_workspace_fast(input)
844 .unwrap_or_else(|errors| panic!("{}", format_plugin_regex_errors(&errors)))
845 }
846
847 pub(crate) fn try_run_workspace_fast(
853 &self,
854 input: &WorkspacePluginRunInput<'_>,
855 ) -> Result<AggregatedPluginResult, Vec<PluginRegexValidationError>> {
856 let _span = tracing::info_span!("run_plugins").entered();
857 let mut result = AggregatedPluginResult::default();
858 let mut regex_errors = Vec::new();
859
860 let all_deps = input.pkg.all_dependency_names();
861 let script_packages =
862 script_activation_packages(input.pkg, input.root, &all_deps, input.production_mode);
863 let workspace_files: Vec<PathBuf> = input
864 .relative_files
865 .iter()
866 .map(|(abs_path, _)| abs_path.clone())
867 .collect();
868
869 let active = self.collect_active_plugins(&PluginActivationInput {
870 pkg: input.pkg,
871 root: input.root,
872 discovered_files: &workspace_files,
873 all_deps: &all_deps,
874 script_packages: &script_packages,
875 candidate_index: input.candidate_index,
876 });
877
878 log_active_plugins(&active);
879
880 self.emit_silent_fail_diagnostics(&active, &all_deps, input.root, &workspace_files);
881
882 process_external_plugins(
883 &self.external_plugins,
884 &all_deps,
885 input.root,
886 &workspace_files,
887 &mut result,
888 );
889
890 if active.is_empty() && result.active_plugins.is_empty() {
891 return Ok(result);
892 }
893
894 process_workspace_active_plugins(&active, input, &mut result, &mut regex_errors);
895 let evidence_roots: &[&Path] = if input.root == input.project_root {
897 &[input.root]
898 } else {
899 &[input.root, input.project_root]
900 };
901 tooling_evidence::record_plugin_tooling(
902 &tooling_evidence::ToolingEvidenceInput {
903 active: &active,
904 external_plugins: &self.external_plugins,
905 all_deps: &all_deps,
906 roots: evidence_roots,
907 extra_roots: &[],
908 candidate_index: input.candidate_index,
909 discovered_files: &workspace_files,
910 },
911 &mut result,
912 );
913 resolve_workspace_plugin_configs(&active, input, &mut result, &mut regex_errors);
914
915 if regex_errors.is_empty() {
916 Ok(result)
917 } else {
918 Err(regex_errors)
919 }
920 }
921
922 #[must_use]
925 pub(crate) fn precompile_config_matchers(
926 &self,
927 ) -> Vec<(&dyn Plugin, Vec<globset::GlobMatcher>)> {
928 self.plugins
929 .iter()
930 .filter(|p| !p.config_patterns().is_empty())
931 .map(|p| (p.as_ref(), cached_plugin_config_matchers(p.as_ref())))
932 .collect()
933 }
934
935 pub(crate) fn resolve_script_config_files(
946 &self,
947 config_files: &[scripts::BinaryConfigFile],
948 package_root: &Path,
949 project_root: &Path,
950 ws_prefix: &str,
951 ) -> AggregatedPluginResult {
952 let mut aggregated = AggregatedPluginResult::default();
953 for config_file in config_files {
954 let Some(rel_path) =
955 scripts::normalize_script_entry_pattern(ws_prefix, &config_file.path)
956 else {
957 continue;
958 };
959 let abs_path = package_root.join(config_file.path.trim_start_matches("./"));
960 let in_package_root = abs_path.parent() == Some(package_root);
965 for plugin in &self.plugins {
966 let plugin = plugin.as_ref();
967 if !plugin
968 .script_config_binaries()
969 .contains(&config_file.binary.as_str())
970 || (in_package_root
971 && cached_plugin_config_matchers(plugin)
972 .iter()
973 .any(|m| m.is_match(rel_path.as_str())))
974 {
975 continue;
976 }
977 if !super::config_parser::is_inside_root(&abs_path, project_root) {
978 continue;
979 }
980 let Ok(source) = std::fs::read_to_string(&abs_path) else {
981 continue;
982 };
983 let mut file_result = AggregatedPluginResult::default();
984 file_result
985 .entry_point_roles
986 .insert(plugin.name().to_string(), plugin.entry_point_role());
987 let plugin_result =
988 plugin.resolve_script_config(&abs_path, &source, package_root, project_root);
989 if let Err(errors) = process_config_result(
990 plugin.name(),
991 plugin_result,
992 &mut file_result,
993 Some(&abs_path),
994 ) {
995 for error in errors {
996 tracing::warn!("{error}");
997 }
998 continue;
999 }
1000 if !ws_prefix.is_empty() {
1001 file_result.apply_workspace_prefix(ws_prefix);
1002 }
1003 file_result.used_exports.push(PluginUsedExportRule::new(
1005 plugin.name().to_string(),
1006 super::UsedExportRule::new(rel_path.clone(), ["default"]),
1007 ));
1008 aggregated.merge_into(file_result);
1009 }
1010 }
1011 aggregated
1012 }
1013}
1014
1015fn process_workspace_active_plugins(
1016 active: &[&dyn Plugin],
1017 input: &WorkspacePluginRunInput<'_>,
1018 result: &mut AggregatedPluginResult,
1019 regex_errors: &mut Vec<PluginRegexValidationError>,
1020) {
1021 for plugin in active {
1022 process_static_patterns(*plugin, input.root, result);
1023 }
1024 process_package_json_metadata(active, input.pkg, input.root, result, regex_errors);
1025}
1026
1027fn resolve_workspace_plugin_configs(
1028 active: &[&dyn Plugin],
1029 input: &WorkspacePluginRunInput<'_>,
1030 result: &mut AggregatedPluginResult,
1031 regex_errors: &mut Vec<PluginRegexValidationError>,
1032) {
1033 let workspace_matchers = select_workspace_matchers(
1034 input.precompiled_config_matchers,
1035 active,
1036 input.skip_config_plugins,
1037 );
1038
1039 let mut resolved_ws_plugins: FxHashSet<&str> = FxHashSet::default();
1040 for (plugin, matchers) in &workspace_matchers {
1041 resolve_plugin_matching_files(&mut PluginMatchingFilesInput {
1042 plugin: *plugin,
1043 matchers,
1044 relative_files: input.relative_files,
1045 root: input.root,
1046 project_root: input.project_root,
1047 result,
1048 regex_errors,
1049 resolved_plugins: &mut resolved_ws_plugins,
1050 });
1051 }
1052
1053 load_workspace_filesystem_configs(&mut WorkspaceFsConfigInput {
1054 workspace_matchers: &workspace_matchers,
1055 resolved_ws_plugins: &resolved_ws_plugins,
1056 root: input.root,
1057 project_root: input.project_root,
1058 production_mode: input.production_mode,
1059 candidate_index: input.candidate_index,
1060 result,
1061 regex_errors,
1062 });
1063}
1064
1065impl Default for PluginRegistry {
1066 fn default() -> Self {
1067 Self::new(vec![])
1068 }
1069}
1070
1071impl PluginRegistry {
1072 fn prepare_plugin_run_context<'a>(
1073 &'a self,
1074 pkg: &PackageJson,
1075 root: &Path,
1076 discovered_files: &[PathBuf],
1077 production_mode: bool,
1078 candidate_index: Option<&ConfigCandidateIndex>,
1079 ) -> PluginRunContext<'a> {
1080 let all_deps = pkg.all_dependency_names();
1081 let script_packages = script_activation_packages(pkg, root, &all_deps, production_mode);
1082 let active = self.collect_active_plugins(&PluginActivationInput {
1083 pkg,
1084 root,
1085 discovered_files,
1086 all_deps: &all_deps,
1087 script_packages: &script_packages,
1088 candidate_index,
1089 });
1090
1091 PluginRunContext { all_deps, active }
1092 }
1093
1094 fn run_plugin_preflight(
1095 &self,
1096 active: &[&dyn Plugin],
1097 all_deps: &[String],
1098 root: &Path,
1099 discovered_files: &[PathBuf],
1100 ) {
1101 log_active_plugins(active);
1102 check_meta_framework_prerequisites(active, root);
1103 self.emit_silent_fail_diagnostics(active, all_deps, root, discovered_files);
1104 }
1105
1106 fn collect_active_plugins<'a>(
1109 &'a self,
1110 activation: &PluginActivationInput<'_>,
1111 ) -> Vec<&'a dyn Plugin> {
1112 self.plugins
1113 .iter()
1114 .filter(|p| {
1115 p.is_enabled_with_files(
1116 activation.all_deps,
1117 activation.root,
1118 activation.discovered_files,
1119 activation.candidate_index,
1120 ) || p.is_enabled_with_scripts(activation.script_packages, activation.root)
1121 || p.is_enabled_with_package_json(activation.pkg, activation.root)
1122 })
1123 .map(AsRef::as_ref)
1124 .collect()
1125 }
1126
1127 fn emit_silent_fail_diagnostics(
1136 &self,
1137 active: &[&dyn Plugin],
1138 all_deps: &[String],
1139 root: &Path,
1140 discovered_files: &[PathBuf],
1141 ) {
1142 let active_external: Vec<&ExternalPluginDef> = self
1143 .external_plugins
1144 .iter()
1145 .filter(|ext| is_external_plugin_active(ext, all_deps, root, discovered_files))
1146 .collect();
1147 let mut diagnostics = detect_pattern_collisions(active, &active_external);
1148 diagnostics.extend(detect_enabler_typos(&self.external_plugins, all_deps));
1149 emit_plugin_diagnostics(&diagnostics);
1150 }
1151}
1152
1153fn plugin_warn_dedupe() -> &'static std::sync::Mutex<FxHashSet<String>> {
1160 static WARNED: std::sync::OnceLock<std::sync::Mutex<FxHashSet<String>>> =
1161 std::sync::OnceLock::new();
1162 WARNED.get_or_init(|| std::sync::Mutex::new(FxHashSet::default()))
1163}
1164
1165struct PluginConfigResolutionInput<'a> {
1166 config_matchers: &'a [(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
1167 relative_files: &'a [(PathBuf, String)],
1168 config_search_roots: &'a [&'a Path],
1169 production_mode: bool,
1170 candidate_index: Option<&'a ConfigCandidateIndex>,
1171 root: &'a Path,
1172 result: &'a mut AggregatedPluginResult,
1173 regex_errors: &'a mut Vec<PluginRegexValidationError>,
1174}
1175
1176fn select_workspace_matchers<'a>(
1179 precompiled_config_matchers: &[(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
1180 active: &[&dyn Plugin],
1181 skip_config_plugins: &FxHashSet<&str>,
1182) -> Vec<(&'a dyn Plugin, Vec<globset::GlobMatcher>)> {
1183 let active_names: FxHashSet<&str> = active.iter().map(|p| p.name()).collect();
1184 precompiled_config_matchers
1185 .iter()
1186 .filter(|(p, _)| {
1187 active_names.contains(p.name())
1188 && (!skip_config_plugins.contains(p.name())
1189 || must_parse_workspace_config_when_root_active(p.name()))
1190 })
1191 .map(|(plugin, matchers)| (*plugin, matchers.clone()))
1192 .collect()
1193}
1194
1195struct WorkspaceFsConfigInput<'a> {
1196 workspace_matchers: &'a [(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
1197 resolved_ws_plugins: &'a FxHashSet<&'a str>,
1198 root: &'a Path,
1199 project_root: &'a Path,
1200 production_mode: bool,
1201 candidate_index: Option<&'a ConfigCandidateIndex>,
1202 result: &'a mut AggregatedPluginResult,
1203 regex_errors: &'a mut Vec<PluginRegexValidationError>,
1204}
1205
1206fn load_workspace_filesystem_configs(input: &mut WorkspaceFsConfigInput<'_>) {
1209 let search_roots: &[&Path] = if input.root == input.project_root {
1210 &[input.root]
1211 } else {
1212 &[input.root, input.project_root]
1213 };
1214 let ws_json_configs = discover_config_files(
1215 input.workspace_matchers,
1216 input.resolved_ws_plugins,
1217 search_roots,
1218 input.production_mode,
1219 input.candidate_index,
1220 );
1221 for (abs_path, plugin) in &ws_json_configs {
1222 let Ok(source) = std::fs::read_to_string(abs_path) else {
1223 continue;
1224 };
1225 let plugin_result =
1226 plugin.resolve_config_in_project(abs_path, &source, input.root, input.project_root);
1227 if plugin_result.is_empty() {
1228 continue;
1229 }
1230 let rel = abs_path
1231 .strip_prefix(input.project_root)
1232 .map(|p| p.to_string_lossy())
1233 .unwrap_or_default();
1234 tracing::debug!(
1235 plugin = plugin.name(),
1236 config = %rel,
1237 entries = plugin_result.entry_patterns.len(),
1238 deps = plugin_result.referenced_dependencies.len(),
1239 "resolved config (workspace filesystem fallback)"
1240 );
1241 if let Err(mut errors) =
1242 process_config_result(plugin.name(), plugin_result, input.result, Some(abs_path))
1243 {
1244 input.regex_errors.append(&mut errors);
1245 }
1246 }
1247}
1248
1249fn resolve_plugin_config_files(input: &mut PluginConfigResolutionInput<'_>) {
1250 if input.config_matchers.is_empty() {
1251 return;
1252 }
1253
1254 let mut resolved_plugins: FxHashSet<&str> = FxHashSet::default();
1255 for (plugin, matchers) in input.config_matchers {
1256 resolve_plugin_matching_files(&mut PluginMatchingFilesInput {
1257 plugin: *plugin,
1258 matchers,
1259 relative_files: input.relative_files,
1260 root: input.root,
1261 project_root: input.root,
1262 result: input.result,
1263 regex_errors: input.regex_errors,
1264 resolved_plugins: &mut resolved_plugins,
1265 });
1266 }
1267
1268 let json_configs = discover_config_files(
1269 input.config_matchers,
1270 &resolved_plugins,
1271 input.config_search_roots,
1272 input.production_mode,
1273 input.candidate_index,
1274 );
1275 for (abs_path, plugin) in &json_configs {
1276 resolve_plugin_filesystem_config(
1277 *plugin,
1278 abs_path,
1279 input.root,
1280 input.result,
1281 input.regex_errors,
1282 );
1283 }
1284}
1285
1286struct PluginMatchingFilesInput<'plugins, 'data, 'state> {
1287 plugin: &'plugins dyn Plugin,
1288 matchers: &'data [globset::GlobMatcher],
1289 relative_files: &'data [(PathBuf, String)],
1290 root: &'data Path,
1291 project_root: &'data Path,
1292 result: &'state mut AggregatedPluginResult,
1293 regex_errors: &'state mut Vec<PluginRegexValidationError>,
1294 resolved_plugins: &'state mut FxHashSet<&'plugins str>,
1295}
1296
1297fn resolve_plugin_matching_files(input: &mut PluginMatchingFilesInput<'_, '_, '_>) {
1298 use rayon::prelude::*;
1299
1300 let plugin_hits: Vec<&PathBuf> = input
1301 .relative_files
1302 .par_iter()
1303 .filter_map(|(abs_path, rel_path)| {
1304 input
1305 .matchers
1306 .iter()
1307 .any(|m| m.is_match(rel_path.as_str()))
1308 .then_some(abs_path)
1309 })
1310 .collect();
1311 for abs_path in plugin_hits {
1312 let Ok(source) = std::fs::read_to_string(abs_path) else {
1313 continue;
1314 };
1315 let plugin_result = input.plugin.resolve_config_in_project(
1316 abs_path,
1317 &source,
1318 input.root,
1319 input.project_root,
1320 );
1321 if plugin_result.is_empty() {
1322 continue;
1323 }
1324 input.resolved_plugins.insert(input.plugin.name());
1325 process_resolved_plugin_config(ResolvedPluginConfigInput {
1326 plugin: input.plugin,
1327 abs_path,
1328 plugin_result,
1329 result: input.result,
1330 regex_errors: input.regex_errors,
1331 message: "resolved config",
1332 config_display: abs_path.display(),
1333 });
1334 }
1335}
1336
1337fn resolve_plugin_filesystem_config(
1338 plugin: &dyn Plugin,
1339 abs_path: &Path,
1340 root: &Path,
1341 result: &mut AggregatedPluginResult,
1342 regex_errors: &mut Vec<PluginRegexValidationError>,
1343) {
1344 let Ok(source) = std::fs::read_to_string(abs_path) else {
1345 return;
1346 };
1347 let plugin_result = plugin.resolve_config(abs_path, &source, root);
1348 if plugin_result.is_empty() {
1349 return;
1350 }
1351 let rel = abs_path
1352 .strip_prefix(root)
1353 .map(|p| p.to_string_lossy())
1354 .unwrap_or_default();
1355 process_resolved_plugin_config(ResolvedPluginConfigInput {
1356 plugin,
1357 abs_path,
1358 plugin_result,
1359 result,
1360 regex_errors,
1361 message: "resolved config (filesystem fallback)",
1362 config_display: rel,
1363 });
1364}
1365
1366struct ResolvedPluginConfigInput<'a, D> {
1367 plugin: &'a dyn Plugin,
1368 abs_path: &'a Path,
1369 plugin_result: PluginResult,
1370 result: &'a mut AggregatedPluginResult,
1371 regex_errors: &'a mut Vec<PluginRegexValidationError>,
1372 message: &'static str,
1373 config_display: D,
1374}
1375
1376fn process_resolved_plugin_config(input: ResolvedPluginConfigInput<'_, impl std::fmt::Display>) {
1377 tracing::debug!(
1378 plugin = input.plugin.name(),
1379 config = %input.config_display,
1380 entries = input.plugin_result.entry_patterns.len(),
1381 deps = input.plugin_result.referenced_dependencies.len(),
1382 input.message
1383 );
1384 if let Err(mut errors) = process_config_result(
1385 input.plugin.name(),
1386 input.plugin_result,
1387 input.result,
1388 Some(input.abs_path),
1389 ) {
1390 input.regex_errors.append(&mut errors);
1391 }
1392}
1393
1394fn should_warn(key: String) -> bool {
1398 plugin_warn_dedupe()
1399 .lock()
1400 .map_or(true, |mut set| set.insert(key))
1401}
1402
1403#[derive(Debug, Clone, PartialEq, Eq)]
1410enum PluginDiagnostic {
1411 PatternCollision {
1413 pattern: String,
1414 owners: Vec<String>,
1415 },
1416 EnablerTypo {
1419 plugin: String,
1420 enabler: String,
1421 suggestion: String,
1422 },
1423}
1424
1425fn detect_pattern_collisions(
1451 builtin_active: &[&dyn Plugin],
1452 external_active: &[&ExternalPluginDef],
1453) -> Vec<PluginDiagnostic> {
1454 use rustc_hash::FxHashMap;
1455
1456 let mut pattern_owners: FxHashMap<String, (Vec<String>, FxHashSet<String>)> =
1457 FxHashMap::default();
1458
1459 let record = |pattern_owners: &mut FxHashMap<_, (Vec<String>, FxHashSet<String>)>,
1460 pattern: String,
1461 name: String| {
1462 let (list, seen) = pattern_owners.entry(pattern).or_default();
1463 if seen.insert(name.clone()) {
1464 list.push(name);
1465 }
1466 };
1467
1468 for plugin in builtin_active {
1469 for pat in plugin.config_patterns() {
1470 record(
1471 &mut pattern_owners,
1472 (*pat).to_string(),
1473 plugin.name().to_string(),
1474 );
1475 }
1476 }
1477 for ext in external_active {
1478 for pat in &ext.config_patterns {
1479 record(&mut pattern_owners, pat.clone(), ext.name.clone());
1480 }
1481 }
1482
1483 let builtin_names: FxHashSet<&str> = builtin_active.iter().map(|p| p.name()).collect();
1490
1491 let mut findings: Vec<PluginDiagnostic> = pattern_owners
1492 .into_iter()
1493 .filter_map(|(pattern, (owners, _seen))| {
1494 if owners.len() < 2 || owners.iter().all(|o| builtin_names.contains(o.as_str())) {
1495 None
1496 } else {
1497 Some(PluginDiagnostic::PatternCollision { pattern, owners })
1498 }
1499 })
1500 .collect();
1501 findings.sort_unstable_by(|a, b| match (a, b) {
1502 (
1503 PluginDiagnostic::PatternCollision { pattern: ap, .. },
1504 PluginDiagnostic::PatternCollision { pattern: bp, .. },
1505 ) => ap.cmp(bp),
1506 _ => std::cmp::Ordering::Equal,
1507 });
1508 findings
1509}
1510
1511fn detect_enabler_typos(
1526 external_plugins: &[ExternalPluginDef],
1527 all_deps: &[String],
1528) -> Vec<PluginDiagnostic> {
1529 let mut findings = Vec::new();
1530
1531 for ext in external_plugins {
1532 if ext.detection.is_some() || ext.enablers.is_empty() {
1533 continue;
1534 }
1535
1536 let any_match = ext.enablers.iter().any(|enabler| {
1537 if enabler.ends_with('/') {
1538 all_deps.iter().any(|d| d.starts_with(enabler))
1539 } else {
1540 all_deps.iter().any(|d| d == enabler)
1541 }
1542 });
1543 if any_match {
1544 continue;
1545 }
1546
1547 for enabler in &ext.enablers {
1548 let candidates = all_deps.iter().map(String::as_str);
1549 let Some(suggestion) = fallow_config::levenshtein::closest_match(enabler, candidates)
1550 else {
1551 continue;
1552 };
1553
1554 findings.push(PluginDiagnostic::EnablerTypo {
1555 plugin: ext.name.clone(),
1556 enabler: enabler.clone(),
1557 suggestion: suggestion.to_string(),
1558 });
1559 }
1560 }
1561
1562 findings
1563}
1564
1565fn emit_plugin_diagnostics(findings: &[PluginDiagnostic]) {
1568 for finding in findings {
1569 match finding {
1570 PluginDiagnostic::PatternCollision { pattern, owners } => {
1571 let key = format!("collision::{pattern}::{owners:?}");
1572 if !should_warn(key) {
1573 continue;
1574 }
1575 let winner = &owners[0];
1576 let others = owners[1..].join(", ");
1577 tracing::warn!(
1578 "plugin config_patterns collision: identical pattern \
1579 '{pattern}' is claimed by plugins [{joined}]; '{winner}' \
1580 runs first (registration order), others ({others}) \
1581 follow. Rename one of the patterns or remove the \
1582 duplicate plugin to make resolution explicit. A future \
1583 release may reject identical-pattern collisions.",
1584 joined = owners.join(", "),
1585 );
1586 }
1587 PluginDiagnostic::EnablerTypo {
1588 plugin,
1589 enabler,
1590 suggestion,
1591 } => {
1592 let key = format!("enabler::{plugin}::{enabler}");
1593 if !should_warn(key) {
1594 continue;
1595 }
1596 tracing::warn!(
1597 "plugin '{plugin}' enabler '{enabler}' does not match any \
1598 dependency in package.json; did you mean '{suggestion}'? \
1599 The plugin will not activate. A future release may reject \
1600 unmatched enablers.",
1601 );
1602 }
1603 }
1604 }
1605}
1606
1607fn process_package_json_inline_configs(
1612 active: &[&dyn Plugin],
1613 config_matchers: &[(&dyn Plugin, Vec<globset::GlobMatcher>)],
1614 relative_files: &[(PathBuf, String)],
1615 root: &Path,
1616 result: &mut AggregatedPluginResult,
1617 regex_errors: &mut Vec<PluginRegexValidationError>,
1618) {
1619 for plugin in active {
1620 let Some(key) = plugin.package_json_config_key() else {
1621 continue;
1622 };
1623 if check_has_config_file(*plugin, config_matchers, relative_files) {
1624 continue;
1625 }
1626 let pkg_path = root.join("package.json");
1627 let Ok(content) = std::fs::read_to_string(&pkg_path) else {
1628 continue;
1629 };
1630 let Ok(json) = serde_json::from_str::<serde_json::Value>(&content) else {
1631 continue;
1632 };
1633 let Some(config_value) = json.get(key) else {
1634 continue;
1635 };
1636 let config_json = serde_json::to_string(config_value).unwrap_or_default();
1637 let fake_path = root.join(format!("{key}.config.json"));
1638 let plugin_result = plugin.resolve_config(&fake_path, &config_json, root);
1639 if plugin_result.is_empty() {
1640 continue;
1641 }
1642 tracing::debug!(
1643 plugin = plugin.name(),
1644 key = key,
1645 "resolved inline package.json config"
1646 );
1647 if let Err(mut errors) =
1648 process_config_result(plugin.name(), plugin_result, result, Some(&pkg_path))
1649 {
1650 regex_errors.append(&mut errors);
1651 }
1652 }
1653}
1654
1655#[derive(Debug)]
1658struct MetaFrameworkWarning {
1659 dedupe_key: &'static str,
1660 message: &'static str,
1661}
1662
1663fn missing_meta_framework_prerequisites(
1673 active_plugins: &[&dyn Plugin],
1674 root: &Path,
1675) -> Vec<MetaFrameworkWarning> {
1676 active_plugins
1677 .iter()
1678 .filter_map(|plugin| match plugin.name() {
1679 "nuxt" if !root.join(".nuxt/tsconfig.json").exists() => Some(MetaFrameworkWarning {
1680 dedupe_key: "meta-prereq::nuxt",
1681 message: "Nuxt project missing .nuxt/tsconfig.json: run `nuxt prepare` \
1682 before fallow for accurate analysis",
1683 }),
1684 "astro" if !root.join(".astro").exists() => Some(MetaFrameworkWarning {
1685 dedupe_key: "meta-prereq::astro",
1686 message: "Astro project missing .astro/ types: run `astro sync` \
1687 before fallow for accurate analysis",
1688 }),
1689 _ => None,
1690 })
1691 .collect()
1692}
1693
1694fn check_meta_framework_prerequisites(active_plugins: &[&dyn Plugin], root: &Path) {
1704 for warning in missing_meta_framework_prerequisites(active_plugins, root) {
1705 if should_warn(warning.dedupe_key.to_owned()) {
1706 tracing::warn!("{}", warning.message);
1707 }
1708 }
1709}
1710
1711fn script_activation_packages(
1712 pkg: &PackageJson,
1713 root: &Path,
1714 all_deps: &[String],
1715 production_mode: bool,
1716) -> FxHashSet<String> {
1717 let Some(pkg_scripts) = pkg.scripts.as_ref() else {
1718 return FxHashSet::default();
1719 };
1720
1721 let scripts_to_analyze = if production_mode {
1722 scripts::filter_production_scripts(pkg_scripts)
1723 } else {
1724 pkg_scripts.clone()
1725 };
1726
1727 let mut nm_roots = Vec::new();
1728 if root.join("node_modules").is_dir() {
1729 nm_roots.push(root);
1730 }
1731 let bin_map = scripts::build_bin_to_package_map(&nm_roots, all_deps);
1732 let dep_set: FxHashSet<String> = all_deps.iter().cloned().collect();
1733 let catalog =
1734 scripts::ScriptCatalog::from_scripts_with_bodies(pkg_scripts, &scripts_to_analyze);
1735
1736 scripts::analyze_scripts_with_dependency_context(
1737 &scripts_to_analyze,
1738 root,
1739 &bin_map,
1740 &dep_set,
1741 &catalog,
1742 scripts::IgnoredCommandEntries::NONE,
1743 )
1744 .used_packages
1745}
1746
1747#[cfg(test)]
1748mod entry_pattern_tests;
1749#[cfg(test)]
1750mod tests;