fallow_core/plugins/registry/mod.rs
1//! Plugin registry: discovers active plugins, collects patterns, parses configs.
2
3use rustc_hash::FxHashSet;
4use std::path::{Path, PathBuf};
5
6use fallow_config::{EntryPointRole, ExternalPluginDef, PackageJson, UsedClassMemberRule};
7
8use super::{PathRule, Plugin, PluginUsedExportRule};
9
10pub(crate) mod builtin;
11mod helpers;
12
13use helpers::{
14 check_has_config_file, discover_config_files, prepare_config_pattern, process_config_result,
15 process_external_plugins, process_static_patterns,
16};
17
18// ESLint is included because each workspace owns its own eslint.config.{mjs,js,...}
19// that may import a shared workspace eslint-config package. Those transitive deps
20// (e.g. eslint-config-next, eslint-plugin-react) are declared in the workspace's
21// devDependencies and will be flagged as unused if we skip config parsing here.
22fn must_parse_workspace_config_when_root_active(plugin_name: &str) -> bool {
23 matches!(
24 plugin_name,
25 "eslint" | "docusaurus" | "jest" | "tanstack-router" | "vitest"
26 )
27}
28
29/// Registry of all available plugins (built-in + external).
30pub struct PluginRegistry {
31 plugins: Vec<Box<dyn Plugin>>,
32 external_plugins: Vec<ExternalPluginDef>,
33}
34
35/// Aggregated results from all active plugins for a project.
36#[derive(Debug, Default)]
37pub struct AggregatedPluginResult {
38 /// All entry point patterns from active plugins: (rule, plugin_name).
39 pub entry_patterns: Vec<(PathRule, String)>,
40 /// Coverage role for each plugin contributing entry point patterns.
41 pub entry_point_roles: rustc_hash::FxHashMap<String, EntryPointRole>,
42 /// All config file patterns from active plugins.
43 pub config_patterns: Vec<String>,
44 /// All always-used file patterns from active plugins: (pattern, plugin_name).
45 pub always_used: Vec<(String, String)>,
46 /// All used export rules from active plugins.
47 pub used_exports: Vec<PluginUsedExportRule>,
48 /// Class member rules contributed by active plugins that should never be
49 /// flagged as unused. Extends the built-in Angular/React lifecycle allowlist
50 /// with framework-invoked method names, optionally scoped by class heritage.
51 pub used_class_members: Vec<UsedClassMemberRule>,
52 /// Dependencies referenced in config files (should not be flagged unused).
53 pub referenced_dependencies: Vec<String>,
54 /// Additional always-used files discovered from config parsing: (pattern, plugin_name).
55 pub discovered_always_used: Vec<(String, String)>,
56 /// Setup files discovered from config parsing: (path, plugin_name).
57 pub setup_files: Vec<(PathBuf, String)>,
58 /// Tooling dependencies (should not be flagged as unused devDeps).
59 pub tooling_dependencies: Vec<String>,
60 /// Package names discovered as used in package.json scripts (binary invocations).
61 pub script_used_packages: FxHashSet<String>,
62 /// Import prefixes for virtual modules provided by active frameworks.
63 /// Imports matching these prefixes should not be flagged as unlisted dependencies.
64 pub virtual_module_prefixes: Vec<String>,
65 /// Package name suffixes that identify virtual or convention-based specifiers.
66 /// Extracted package names ending with any of these suffixes are not flagged as unlisted.
67 pub virtual_package_suffixes: Vec<String>,
68 /// Import suffixes for build-time generated relative imports.
69 /// Unresolved imports ending with these suffixes are suppressed.
70 pub generated_import_patterns: Vec<String>,
71 /// Path alias mappings from active plugins (prefix → replacement directory).
72 /// Used by the resolver to substitute import prefixes before re-resolving.
73 pub path_aliases: Vec<(String, String)>,
74 /// Names of active plugins.
75 pub active_plugins: Vec<String>,
76 /// Test fixture glob patterns from active plugins: (pattern, plugin_name).
77 pub fixture_patterns: Vec<(String, String)>,
78 /// Absolute directories contributed by plugins that should be searched
79 /// when resolving SCSS/Sass `@import`/`@use` specifiers. Populated from
80 /// Angular's `stylePreprocessorOptions.includePaths` and equivalent
81 /// framework settings. See issue #103.
82 pub scss_include_paths: Vec<PathBuf>,
83}
84
85impl PluginRegistry {
86 /// Create a registry with all built-in plugins and optional external plugins.
87 #[must_use]
88 pub fn new(external: Vec<ExternalPluginDef>) -> Self {
89 Self {
90 plugins: builtin::create_builtin_plugins(),
91 external_plugins: external,
92 }
93 }
94
95 /// Run all plugins against a project, returning aggregated results.
96 ///
97 /// This discovers which plugins are active, collects their static patterns,
98 /// then parses any config files to extract dynamic information.
99 pub fn run(
100 &self,
101 pkg: &PackageJson,
102 root: &Path,
103 discovered_files: &[PathBuf],
104 ) -> AggregatedPluginResult {
105 self.run_with_search_roots(pkg, root, discovered_files, &[root], false)
106 }
107
108 /// Run all plugins against a project with explicit config-file search roots.
109 ///
110 /// `config_search_roots` should stay narrowly focused to directories that are
111 /// already known to matter for this project. Broad recursive scans are
112 /// intentionally avoided because they become prohibitively expensive on
113 /// large monorepos with populated `node_modules` trees.
114 ///
115 /// `production_mode` controls the FS fallback for source-extension config
116 /// patterns. In production mode the source walker excludes `*.config.*` so
117 /// the FS walk is required; otherwise Phase 3a's in-memory matcher covers
118 /// them and the walk is skipped.
119 pub fn run_with_search_roots(
120 &self,
121 pkg: &PackageJson,
122 root: &Path,
123 discovered_files: &[PathBuf],
124 config_search_roots: &[&Path],
125 production_mode: bool,
126 ) -> AggregatedPluginResult {
127 let _span = tracing::info_span!("run_plugins").entered();
128 let mut result = AggregatedPluginResult::default();
129
130 // Phase 1: Determine which plugins are active
131 // Compute deps once to avoid repeated Vec<String> allocation per plugin
132 let all_deps = pkg.all_dependency_names();
133 let active: Vec<&dyn Plugin> = self
134 .plugins
135 .iter()
136 .filter(|p| p.is_enabled_with_deps(&all_deps, root))
137 .map(AsRef::as_ref)
138 .collect();
139
140 tracing::info!(
141 plugins = active
142 .iter()
143 .map(|p| p.name())
144 .collect::<Vec<_>>()
145 .join(", "),
146 "active plugins"
147 );
148
149 // Warn when meta-frameworks are active but their generated configs are missing.
150 // Without these, tsconfig extends chains break and import resolution fails.
151 check_meta_framework_prerequisites(&active, root);
152
153 // Phase 2: Collect static patterns from active plugins
154 for plugin in &active {
155 process_static_patterns(*plugin, root, &mut result);
156 }
157
158 // Phase 2b: Process external plugins (includes inline framework definitions)
159 process_external_plugins(
160 &self.external_plugins,
161 &all_deps,
162 root,
163 discovered_files,
164 &mut result,
165 );
166
167 // Phase 3: Find and parse config files for dynamic resolution
168 // Pre-compile all config patterns. Source-extension root-anchored
169 // patterns are wrapped with `**/` so they match nested files via the
170 // discovered file set (Phase 3a), letting Phase 3b skip those plugins
171 // and avoid a per-directory stat storm on large monorepos.
172 let config_matchers: Vec<(&dyn Plugin, Vec<globset::GlobMatcher>)> = active
173 .iter()
174 .filter(|p| !p.config_patterns().is_empty())
175 .map(|p| {
176 let matchers: Vec<globset::GlobMatcher> = p
177 .config_patterns()
178 .iter()
179 .filter_map(|pat| {
180 let prepared = prepare_config_pattern(pat);
181 globset::Glob::new(&prepared)
182 .ok()
183 .map(|g| g.compile_matcher())
184 })
185 .collect();
186 (*p, matchers)
187 })
188 .collect();
189
190 // Build relative paths lazily: only needed when config matchers exist
191 // or plugins have package_json_config_key. Skip entirely for projects
192 // with no config-parsing plugins (e.g., only React), avoiding O(files)
193 // String allocations.
194 let needs_relative_files = !config_matchers.is_empty()
195 || active.iter().any(|p| p.package_json_config_key().is_some());
196 let relative_files: Vec<(PathBuf, String)> = if needs_relative_files {
197 discovered_files
198 .iter()
199 .map(|f| {
200 let rel = f
201 .strip_prefix(root)
202 .unwrap_or(f)
203 .to_string_lossy()
204 .into_owned();
205 (f.clone(), rel)
206 })
207 .collect()
208 } else {
209 Vec::new()
210 };
211
212 if !config_matchers.is_empty() {
213 // Phase 3a: Match config files from discovered source files
214 let mut resolved_plugins: FxHashSet<&str> = FxHashSet::default();
215
216 for (plugin, matchers) in &config_matchers {
217 for (abs_path, rel_path) in &relative_files {
218 if matchers.iter().any(|m| m.is_match(rel_path.as_str()))
219 && let Ok(source) = std::fs::read_to_string(abs_path)
220 {
221 let plugin_result = plugin.resolve_config(abs_path, &source, root);
222 if !plugin_result.is_empty() {
223 resolved_plugins.insert(plugin.name());
224 tracing::debug!(
225 plugin = plugin.name(),
226 config = rel_path.as_str(),
227 entries = plugin_result.entry_patterns.len(),
228 deps = plugin_result.referenced_dependencies.len(),
229 "resolved config"
230 );
231 process_config_result(plugin.name(), plugin_result, &mut result);
232 }
233 }
234 }
235 }
236
237 // Phase 3b: Filesystem fallback for JSON config files.
238 // JSON files (angular.json, project.json) are not in the discovered file set
239 // because fallow only discovers JS/TS/CSS/Vue/etc. files. In production
240 // mode, source-extension configs (`*.config.*`, dotfiles) are also
241 // excluded from the walker, so the FS walk runs for those patterns too.
242 let json_configs = discover_config_files(
243 &config_matchers,
244 &resolved_plugins,
245 config_search_roots,
246 production_mode,
247 );
248 for (abs_path, plugin) in &json_configs {
249 if let Ok(source) = std::fs::read_to_string(abs_path) {
250 let plugin_result = plugin.resolve_config(abs_path, &source, root);
251 if !plugin_result.is_empty() {
252 let rel = abs_path
253 .strip_prefix(root)
254 .map(|p| p.to_string_lossy())
255 .unwrap_or_default();
256 tracing::debug!(
257 plugin = plugin.name(),
258 config = %rel,
259 entries = plugin_result.entry_patterns.len(),
260 deps = plugin_result.referenced_dependencies.len(),
261 "resolved config (filesystem fallback)"
262 );
263 process_config_result(plugin.name(), plugin_result, &mut result);
264 }
265 }
266 }
267 }
268
269 // Phase 4: Package.json inline config fallback
270 // For plugins that define `package_json_config_key()`, check if the root
271 // package.json contains that key and no standalone config file was found.
272 for plugin in &active {
273 if let Some(key) = plugin.package_json_config_key()
274 && !check_has_config_file(*plugin, &config_matchers, &relative_files)
275 {
276 // Try to extract the key from package.json
277 let pkg_path = root.join("package.json");
278 if let Ok(content) = std::fs::read_to_string(&pkg_path)
279 && let Ok(json) = serde_json::from_str::<serde_json::Value>(&content)
280 && let Some(config_value) = json.get(key)
281 {
282 let config_json = serde_json::to_string(config_value).unwrap_or_default();
283 let fake_path = root.join(format!("{key}.config.json"));
284 let plugin_result = plugin.resolve_config(&fake_path, &config_json, root);
285 if !plugin_result.is_empty() {
286 tracing::debug!(
287 plugin = plugin.name(),
288 key = key,
289 "resolved inline package.json config"
290 );
291 process_config_result(plugin.name(), plugin_result, &mut result);
292 }
293 }
294 }
295 }
296
297 result
298 }
299
300 /// Fast variant of `run()` for workspace packages.
301 ///
302 /// Reuses pre-compiled config matchers and pre-computed relative files from the root
303 /// project run, avoiding repeated glob compilation and path computation per workspace.
304 /// Skips package.json inline config (workspace packages rarely have inline configs).
305 #[expect(
306 clippy::too_many_arguments,
307 reason = "Each parameter is a distinct, small value with no natural grouping; \
308 bundling them into a struct hurts call-site readability."
309 )]
310 pub fn run_workspace_fast(
311 &self,
312 pkg: &PackageJson,
313 root: &Path,
314 project_root: &Path,
315 precompiled_config_matchers: &[(&dyn Plugin, Vec<globset::GlobMatcher>)],
316 relative_files: &[(PathBuf, String)],
317 skip_config_plugins: &FxHashSet<&str>,
318 production_mode: bool,
319 ) -> AggregatedPluginResult {
320 let _span = tracing::info_span!("run_plugins").entered();
321 let mut result = AggregatedPluginResult::default();
322
323 // Phase 1: Determine which plugins are active (with pre-computed deps)
324 let all_deps = pkg.all_dependency_names();
325 let active: Vec<&dyn Plugin> = self
326 .plugins
327 .iter()
328 .filter(|p| p.is_enabled_with_deps(&all_deps, root))
329 .map(AsRef::as_ref)
330 .collect();
331
332 let workspace_files: Vec<PathBuf> = relative_files
333 .iter()
334 .map(|(abs_path, _)| abs_path.clone())
335 .collect();
336
337 tracing::info!(
338 plugins = active
339 .iter()
340 .map(|p| p.name())
341 .collect::<Vec<_>>()
342 .join(", "),
343 "active plugins"
344 );
345
346 process_external_plugins(
347 &self.external_plugins,
348 &all_deps,
349 root,
350 &workspace_files,
351 &mut result,
352 );
353
354 // Early exit if no plugins are active (common for leaf workspace packages)
355 if active.is_empty() && result.active_plugins.is_empty() {
356 return result;
357 }
358
359 // Phase 2: Collect static patterns from active plugins
360 for plugin in &active {
361 process_static_patterns(*plugin, root, &mut result);
362 }
363
364 // Phase 3: Find and parse config files using pre-compiled matchers
365 // Only check matchers for plugins that are active in this workspace
366 let active_names: FxHashSet<&str> = active.iter().map(|p| p.name()).collect();
367 let workspace_matchers: Vec<_> = precompiled_config_matchers
368 .iter()
369 .filter(|(p, _)| {
370 active_names.contains(p.name())
371 && (!skip_config_plugins.contains(p.name())
372 || must_parse_workspace_config_when_root_active(p.name()))
373 })
374 .map(|(plugin, matchers)| (*plugin, matchers.clone()))
375 .collect();
376
377 let mut resolved_ws_plugins: FxHashSet<&str> = FxHashSet::default();
378 if !workspace_matchers.is_empty() {
379 for (plugin, matchers) in &workspace_matchers {
380 for (abs_path, rel_path) in relative_files {
381 if matchers.iter().any(|m| m.is_match(rel_path.as_str()))
382 && let Ok(source) = std::fs::read_to_string(abs_path)
383 {
384 let plugin_result = plugin.resolve_config(abs_path, &source, root);
385 if !plugin_result.is_empty() {
386 resolved_ws_plugins.insert(plugin.name());
387 tracing::debug!(
388 plugin = plugin.name(),
389 config = rel_path.as_str(),
390 entries = plugin_result.entry_patterns.len(),
391 deps = plugin_result.referenced_dependencies.len(),
392 "resolved config"
393 );
394 process_config_result(plugin.name(), plugin_result, &mut result);
395 }
396 }
397 }
398 }
399 }
400
401 // Phase 3b: Filesystem fallback for JSON config files at the project root.
402 // Config files like angular.json live at the monorepo root, but Angular is
403 // only active in workspace packages. Check the project root for unresolved
404 // config patterns.
405 let ws_json_configs = if root == project_root {
406 discover_config_files(
407 &workspace_matchers,
408 &resolved_ws_plugins,
409 &[root],
410 production_mode,
411 )
412 } else {
413 discover_config_files(
414 &workspace_matchers,
415 &resolved_ws_plugins,
416 &[root, project_root],
417 production_mode,
418 )
419 };
420 // Parse discovered JSON config files
421 for (abs_path, plugin) in &ws_json_configs {
422 if let Ok(source) = std::fs::read_to_string(abs_path) {
423 let plugin_result = plugin.resolve_config(abs_path, &source, root);
424 if !plugin_result.is_empty() {
425 let rel = abs_path
426 .strip_prefix(project_root)
427 .map(|p| p.to_string_lossy())
428 .unwrap_or_default();
429 tracing::debug!(
430 plugin = plugin.name(),
431 config = %rel,
432 entries = plugin_result.entry_patterns.len(),
433 deps = plugin_result.referenced_dependencies.len(),
434 "resolved config (workspace filesystem fallback)"
435 );
436 process_config_result(plugin.name(), plugin_result, &mut result);
437 }
438 }
439 }
440
441 result
442 }
443
444 /// Pre-compile config pattern glob matchers for all plugins that have config patterns.
445 /// Returns a vec of (plugin, matchers) pairs that can be reused across multiple `run_workspace_fast` calls.
446 #[must_use]
447 pub fn precompile_config_matchers(&self) -> Vec<(&dyn Plugin, Vec<globset::GlobMatcher>)> {
448 self.plugins
449 .iter()
450 .filter(|p| !p.config_patterns().is_empty())
451 .map(|p| {
452 let matchers: Vec<globset::GlobMatcher> = p
453 .config_patterns()
454 .iter()
455 .filter_map(|pat| {
456 let prepared = prepare_config_pattern(pat);
457 globset::Glob::new(&prepared)
458 .ok()
459 .map(|g| g.compile_matcher())
460 })
461 .collect();
462 (p.as_ref(), matchers)
463 })
464 .collect()
465 }
466}
467
468impl Default for PluginRegistry {
469 fn default() -> Self {
470 Self::new(vec![])
471 }
472}
473
474/// Warn when meta-frameworks are active but their generated configs are missing.
475///
476/// Meta-frameworks like Nuxt and Astro generate tsconfig/types files during a
477/// "prepare" step. Without these, the tsconfig extends chain breaks and
478/// extensionless imports fail wholesale (e.g. 2000+ unresolved imports).
479fn check_meta_framework_prerequisites(active_plugins: &[&dyn Plugin], root: &Path) {
480 for plugin in active_plugins {
481 match plugin.name() {
482 "nuxt" if !root.join(".nuxt/tsconfig.json").exists() => {
483 tracing::warn!(
484 "Nuxt project missing .nuxt/tsconfig.json: run `nuxt prepare` \
485 before fallow for accurate analysis"
486 );
487 }
488 "astro" if !root.join(".astro").exists() => {
489 tracing::warn!(
490 "Astro project missing .astro/ types: run `astro sync` \
491 before fallow for accurate analysis"
492 );
493 }
494 _ => {}
495 }
496 }
497}
498
499#[cfg(test)]
500mod tests;