Skip to main content

fallow_core/plugins/registry/
helpers.rs

1//! Helper functions for plugin registry orchestration.
2//!
3//! Contains pattern aggregation, external plugin processing, config file discovery,
4//! config result merging, and plugin detection logic.
5
6use std::borrow::Cow;
7use std::ffi::{OsStr, OsString};
8use std::path::{Path, PathBuf};
9
10use rustc_hash::{FxHashMap, FxHashSet};
11
12use fallow_config::{ExternalPluginDef, PackageJson, PluginDetection, UsedClassMemberRule};
13
14use crate::discover::SOURCE_EXTENSIONS;
15
16use super::super::{PathRule, Plugin, PluginResult, PluginUsedExportRule, UsedExportRule};
17use super::{AggregatedPluginResult, PluginRegexValidationError, PluginRegexValidationErrorInput};
18
19/// True when a config pattern names a source-extension config file living
20/// directly in some directory (no path separator, no leading dot, all expanded
21/// extensions are in `SOURCE_EXTENSIONS`).
22///
23/// Such patterns describe files that are already in the discovered file set, so
24/// Phase 3a's in-memory matchers can find them after a `**/` prefix is added.
25/// Callers use this to skip the corresponding filesystem fallback walk in
26/// `discover_config_files`, which is the dominant cost on large monorepos.
27#[must_use]
28pub fn is_source_ext_root_pattern(pat: &str) -> bool {
29    if pat.is_empty() || pat.contains('/') {
30        return false;
31    }
32    for expanded in expand_brace_pattern(pat) {
33        if expanded.starts_with('.') {
34            return false;
35        }
36        let Some(ext) = std::path::Path::new(&expanded).extension() else {
37            return false;
38        };
39        let Some(ext_str) = ext.to_str() else {
40            return false;
41        };
42        if !SOURCE_EXTENSIONS.contains(&ext_str) {
43            return false;
44        }
45    }
46    true
47}
48
49/// Prepare a config pattern for `globset::Glob`.
50#[must_use]
51pub fn prepare_config_pattern(pat: &str) -> Cow<'_, str> {
52    if is_source_ext_root_pattern(pat) {
53        Cow::Owned(format!("**/{pat}"))
54    } else {
55        Cow::Borrowed(pat)
56    }
57}
58
59/// Credit the `default` export of each config file that `patterns` match.
60///
61/// The tool loads its config file and reads the default export, so the export
62/// counts as used under `includeEntryExports`. The patterns get the same
63/// `**/` prefix that config discovery adds, so a config file in a nested
64/// directory gets the credit too.
65fn push_config_default_exports<'a>(
66    pname: &str,
67    patterns: impl Iterator<Item = &'a str>,
68    result: &mut AggregatedPluginResult,
69) {
70    for pat in patterns {
71        result.config_export_credits.push(PluginUsedExportRule::new(
72            pname,
73            UsedExportRule::new(prepare_config_pattern(pat), ["default"]),
74        ));
75    }
76}
77
78/// Collect static patterns from a single plugin into the aggregated result.
79pub fn process_static_patterns(
80    plugin: &dyn Plugin,
81    root: &Path,
82    result: &mut AggregatedPluginResult,
83) {
84    let pname = plugin.name().to_string();
85    result.active_plugins.push(pname.clone());
86    result
87        .entry_point_roles
88        .insert(pname.clone(), plugin.entry_point_role());
89
90    collect_static_plugin_rules(plugin, &pname, result);
91    collect_static_plugin_metadata(plugin, root, result);
92}
93
94/// Collect a plugin's entry/used-export/class-member/config/always-used rules
95/// into the aggregate, all scoped under `pname`.
96fn collect_static_plugin_rules(
97    plugin: &dyn Plugin,
98    pname: &str,
99    result: &mut AggregatedPluginResult,
100) {
101    for rule in plugin.entry_pattern_rules() {
102        result.entry_patterns.push((rule, pname.to_string()));
103    }
104    for pat in plugin.config_patterns() {
105        result.config_patterns.push((*pat).to_string());
106    }
107    let opt_out = plugin.config_default_export_opt_out();
108    push_config_default_exports(
109        pname,
110        plugin
111            .config_patterns()
112            .iter()
113            .copied()
114            .filter(|pat| !opt_out.contains(pat)),
115        result,
116    );
117    for (pat, exports) in plugin.config_file_exports() {
118        result.config_export_credits.push(PluginUsedExportRule::new(
119            pname,
120            UsedExportRule::from_static(pat, exports),
121        ));
122    }
123    for pat in plugin.always_used() {
124        result
125            .always_used
126            .push(((*pat).to_string(), pname.to_string()));
127    }
128    for rule in plugin.used_export_rules() {
129        result
130            .used_exports
131            .push(PluginUsedExportRule::new(pname.to_string(), rule));
132    }
133    for member in plugin.used_class_members() {
134        result
135            .used_class_members
136            .push(UsedClassMemberRule::from(*member));
137    }
138    for rule in plugin.used_class_member_rules() {
139        result.used_class_members.push(rule);
140    }
141    result
142        .framework_class_member_contracts
143        .extend(plugin.framework_class_member_contracts());
144    for pat in plugin.fixture_glob_patterns() {
145        result
146            .fixture_patterns
147            .push(((*pat).to_string(), pname.to_string()));
148    }
149}
150
151/// Collect a plugin's dependency/virtual-module/alias/auto-import metadata into
152/// the aggregate.
153fn collect_static_plugin_metadata(
154    plugin: &dyn Plugin,
155    root: &Path,
156    result: &mut AggregatedPluginResult,
157) {
158    for dep in plugin.tooling_dependencies() {
159        result.tooling_dependencies.push((*dep).to_string());
160    }
161    for prefix in plugin.virtual_module_prefixes() {
162        result.virtual_module_prefixes.push((*prefix).to_string());
163    }
164    for suffix in plugin.virtual_package_suffixes() {
165        result.virtual_package_suffixes.push((*suffix).to_string());
166    }
167    for pattern in plugin.generated_import_patterns() {
168        result
169            .generated_import_patterns
170            .push((*pattern).to_string());
171    }
172    for prefix in plugin.generated_type_import_prefixes() {
173        result
174            .generated_type_import_prefixes
175            .push((*prefix).to_string());
176    }
177    for (prefix, replacement) in plugin.path_aliases(root) {
178        result.path_aliases.push((prefix.to_string(), replacement));
179    }
180    result
181        .framework_static_dir_mappings
182        .extend(plugin.static_dir_mappings(root));
183    result
184        .auto_imports
185        .extend(plugin.auto_imports(root).into_iter().map(|mut rule| {
186            if rule.scope.is_empty() {
187                rule.scope.push(root.to_path_buf());
188            }
189            rule
190        }));
191    result
192        .provided_dependencies
193        .extend(plugin.provided_dependencies());
194}
195
196/// Resolve package.json metadata hooks for active plugins.
197pub fn process_package_json_metadata(
198    active: &[&dyn Plugin],
199    pkg: &PackageJson,
200    root: &Path,
201    result: &mut AggregatedPluginResult,
202    regex_errors: &mut Vec<PluginRegexValidationError>,
203) {
204    for plugin in active {
205        let package_referenced = plugin.package_json_referenced_dependencies(pkg, root);
206        if !package_referenced.is_empty() {
207            let pkg_path = root.join("package.json");
208            result.package_referenced_dependencies.extend(
209                package_referenced
210                    .into_iter()
211                    .map(|dep| (pkg_path.clone(), dep)),
212            );
213        }
214        let plugin_result = plugin.resolve_package_json(pkg, root);
215        if plugin_result.is_empty() {
216            continue;
217        }
218        tracing::debug!(
219            plugin = plugin.name(),
220            deps = plugin_result.referenced_dependencies.len(),
221            "resolved package.json metadata"
222        );
223        if let Err(mut errors) = process_config_result(plugin.name(), plugin_result, result, None) {
224            regex_errors.append(&mut errors);
225        }
226    }
227}
228
229/// Determine whether an external plugin activates against the given project.
230///
231/// Shared between `process_external_plugins` and the collision-warning
232/// helper in `registry::mod` so both paths agree on activation semantics.
233pub fn is_external_plugin_active(
234    ext: &ExternalPluginDef,
235    all_deps: &[String],
236    root: &Path,
237    discovered_files: &[PathBuf],
238) -> bool {
239    if !ext.has_activation_condition() {
240        return false;
241    }
242    if let Some(detection) = &ext.detection {
243        let all_dep_refs: Vec<&str> = all_deps.iter().map(String::as_str).collect();
244        return check_plugin_detection(detection, &all_dep_refs, root, discovered_files);
245    }
246    ext.enablers.iter().any(|enabler| {
247        if enabler.ends_with('/') {
248            all_deps.iter().any(|d| d.starts_with(enabler))
249        } else {
250            all_deps.iter().any(|d| d == enabler)
251        }
252    })
253}
254
255/// Process external plugin definitions, checking activation and aggregating patterns.
256pub fn process_external_plugins(
257    external_plugins: &[ExternalPluginDef],
258    all_deps: &[String],
259    root: &Path,
260    discovered_files: &[PathBuf],
261    result: &mut AggregatedPluginResult,
262) {
263    for ext in external_plugins {
264        let is_active = is_external_plugin_active(ext, all_deps, root, discovered_files);
265        if is_active {
266            result.active_plugins.push(ext.name.clone());
267            result
268                .entry_point_roles
269                .insert(ext.name.clone(), ext.effective_entry_point_role());
270            result.entry_patterns.extend(
271                ext.entry_points
272                    .iter()
273                    .map(|p| (PathRule::new(p.clone()), ext.name.clone())),
274            );
275            if !ext.manifest_entries.is_empty() {
276                result.entry_patterns.extend(
277                    crate::plugins::manifest_entries::evaluate_manifest_entries(ext, root)
278                        .into_iter()
279                        .map(|rule| (rule, ext.name.clone())),
280                );
281            }
282            result.config_patterns.extend(ext.config_patterns.clone());
283            push_config_default_exports(
284                &ext.name,
285                ext.config_patterns
286                    .iter()
287                    .filter(|pat| !ext.config_default_export_opt_out.contains(pat))
288                    .map(String::as_str),
289                result,
290            );
291            result.always_used.extend(
292                ext.config_patterns
293                    .iter()
294                    .chain(ext.always_used.iter())
295                    .map(|p| (p.clone(), ext.name.clone())),
296            );
297            result
298                .tooling_dependencies
299                .extend(ext.tooling_dependencies.clone());
300            for ue in &ext.used_exports {
301                result.used_exports.push(PluginUsedExportRule::new(
302                    ext.name.clone(),
303                    UsedExportRule::new(ue.pattern.clone(), ue.exports.clone()),
304                ));
305            }
306            result
307                .used_class_members
308                .extend(ext.used_class_members.iter().cloned());
309        }
310    }
311}
312
313/// In-memory directory listing of config-candidate files (and discovered source
314/// files), keyed by absolute directory, used to resolve plugin config patterns
315/// without re-walking the filesystem.
316///
317/// Built once from the files the discovery walk already collected, so a
318/// `discover_config_files` lookup that previously cost one filesystem stat per
319/// `(plugin, ancestor-directory, pattern)` becomes an in-memory set lookup. The
320/// walk respects `.gitignore` / `ignorePatterns` / the hidden-directory
321/// allowlist, so config discovery via this index follows the same traversal
322/// rules as source discovery (the raw filesystem path used in production mode
323/// does not); see the crate docs / CHANGELOG for that deliberate refinement.
324pub struct ConfigCandidateIndex {
325    dirs: FxHashMap<PathBuf, FxHashSet<OsString>>,
326}
327
328impl ConfigCandidateIndex {
329    /// Build the index from absolute file paths (discovered source files unioned
330    /// with non-source config candidates). Files with no parent or no file name
331    /// are skipped.
332    #[must_use]
333    pub(crate) fn build<'a>(paths: impl IntoIterator<Item = &'a Path>) -> Self {
334        let mut dirs: FxHashMap<PathBuf, FxHashSet<OsString>> = FxHashMap::default();
335        for path in paths {
336            if let (Some(parent), Some(name)) = (path.parent(), path.file_name()) {
337                dirs.entry(parent.to_path_buf())
338                    .or_default()
339                    .insert(name.to_os_string());
340            }
341        }
342        Self { dirs }
343    }
344
345    /// Whether the discovery walk collected the file at `path`.
346    #[must_use]
347    pub(crate) fn contains_file(&self, path: &Path) -> bool {
348        match (path.parent(), path.file_name()) {
349            (Some(dir), Some(name)) => self.dir_contains(dir, name),
350            _ => false,
351        }
352    }
353
354    /// Whether the directory `dir` contains a file named `name`, per the files
355    /// the discovery walk collected. Used by file-based plugin activation to
356    /// avoid a per-directory filesystem `read` probe.
357    #[must_use]
358    pub(crate) fn dir_contains(&self, dir: &Path, name: &OsStr) -> bool {
359        self.dirs.get(dir).is_some_and(|names| names.contains(name))
360    }
361
362    /// Whether any directory at or below `root` contains a file named `name`,
363    /// per the files the discovery walk collected. Lets a plugin activate from
364    /// a sentinel file nested anywhere under `root` (e.g. a `.env.schema` in a
365    /// workspace subdirectory) without a recursive filesystem walk.
366    #[must_use]
367    pub(crate) fn any_descendant_contains(&self, root: &Path, name: &OsStr) -> bool {
368        self.dirs
369            .iter()
370            .any(|(dir, names)| dir.starts_with(root) && names.contains(name))
371    }
372
373    /// Whether any directory at or below `root` contains a file whose name
374    /// matches `matcher`, per the files the discovery walk collected. The glob
375    /// analogue of [`Self::any_descendant_contains`], used to activate a plugin
376    /// from a wildcard config filename (e.g. `tsconfig.*.json`) nested anywhere
377    /// under `root` without a recursive filesystem walk.
378    #[must_use]
379    pub(crate) fn any_descendant_matches(
380        &self,
381        root: &Path,
382        matcher: &globset::GlobMatcher,
383    ) -> bool {
384        self.dirs.iter().any(|(dir, names)| {
385            dir.starts_with(root) && names.iter().any(|name| matcher.is_match(Path::new(name)))
386        })
387    }
388
389    /// The file names that the discovery walk collected in the directory `dir`.
390    pub(super) fn names_in_dir(&self, dir: &Path) -> Option<&FxHashSet<OsString>> {
391        self.dirs.get(dir)
392    }
393
394    pub(super) fn glob_matches_in_dir(
395        &self,
396        dir: &Path,
397        matcher: &globset::GlobMatcher,
398    ) -> Vec<PathBuf> {
399        self.dirs.get(dir).map_or_else(Vec::new, |names| {
400            names
401                .iter()
402                .filter(|name| matcher.is_match(Path::new(name)))
403                .map(|name| dir.join(name))
404                .collect()
405        })
406    }
407}
408
409/// Discover config files for plugins that were not matched against the
410/// discovered source set.
411///
412/// This intentionally probes only known search roots instead of recursively
413/// globbing the whole repository tree. Large monorepos often contain enormous
414/// `node_modules` directories, and a full `**/project.json` walk becomes
415/// pathological there. Callers should therefore pass a focused root list such
416/// as the repo root, workspace roots, and ancestors of discovered source files.
417///
418/// When `candidate_index` is `Some` (the non-production fast path), patterns are
419/// resolved against the in-memory directory index the discovery walk already
420/// built, avoiding one filesystem stat per `(plugin, root, pattern)`. When it is
421/// `None` (production mode), the filesystem is probed directly.
422///
423/// When `production_mode` is `false`, source-extension root-anchored patterns
424/// (e.g., `webpack.config.{ts,js,mjs,cjs}`) are skipped because Phase 3a's
425/// `**/`-prefixed matcher already finds them in the discovered source file
426/// set. In production mode, the file walker excludes `*.config.*` and dotfile
427/// configs, so the FS walk is still required to keep the discovery correct.
428pub fn discover_config_files<'a>(
429    config_matchers: &[(&'a dyn Plugin, Vec<globset::GlobMatcher>)],
430    resolved_plugins: &FxHashSet<&str>,
431    roots: &[&Path],
432    production_mode: bool,
433    candidate_index: Option<&ConfigCandidateIndex>,
434) -> Vec<(PathBuf, &'a dyn Plugin)> {
435    use rayon::prelude::*;
436    let mut pending: Vec<(&'a dyn Plugin, &Path, String, bool)> = Vec::new();
437    for (plugin, _) in config_matchers {
438        // A resolved plugin still probes the patterns that Phase 3a cannot
439        // read: files under a directory that source discovery does not index,
440        // such as `build/webpack.prod.js`, and non-source files, such as a
441        // root `.eslintrc.json` next to a workspace `eslint.config.mjs`. A
442        // source config that Phase 3a read does not cover those files.
443        let resolved = resolved_plugins.contains(plugin.name());
444        for root in roots {
445            for pat in plugin.config_patterns() {
446                if !production_mode && is_source_ext_root_pattern(pat) {
447                    continue;
448                }
449                if resolved
450                    && !pattern_needs_filesystem(pat)
451                    && pattern_names_only_source_files(pat)
452                {
453                    continue;
454                }
455                pending.push((*plugin, *root, pat.to_string(), resolved));
456            }
457        }
458    }
459
460    let hits: Vec<(PathBuf, &'a dyn Plugin)> = pending
461        .par_iter()
462        .flat_map_iter(|(plugin, root, pat, resolved)| {
463            expand_brace_pattern(pat)
464                .into_iter()
465                .flat_map(|expanded| {
466                    let needs_fs = pattern_needs_filesystem(&expanded);
467                    let paths = match candidate_index {
468                        // A pattern under a non-allowlisted hidden directory
469                        // (e.g. `.config/prisma.ts`) is never descended by the
470                        // discovery walk, so it cannot be in the in-memory
471                        // index; probe the filesystem for those few patterns
472                        // even on the fast path so they stay discoverable.
473                        Some(index) if !needs_fs => match_pattern_in_index(root, &expanded, index),
474                        _ => discover_pattern_matches(root, &expanded),
475                    };
476                    paths
477                        .into_iter()
478                        .filter(move |path| {
479                            !*resolved || !phase_3a_read_file(path, needs_fs, candidate_index)
480                        })
481                        .map(move |path| (path, *plugin))
482                })
483                .collect::<Vec<_>>()
484        })
485        .collect();
486
487    let mut seen: FxHashSet<(PathBuf, &'a str)> = FxHashSet::default();
488    let mut config_files: Vec<(PathBuf, &'a dyn Plugin)> = Vec::with_capacity(hits.len());
489    for (path, plugin) in hits {
490        if seen.insert((path.clone(), plugin.name())) {
491            config_files.push((path, plugin));
492        }
493    }
494    config_files
495}
496
497/// True when every brace alternative of `pattern` names a file with a source
498/// extension. Phase 3a reads only discovered source files, so a resolved plugin
499/// still needs the filesystem fallback for a pattern such as
500/// `.eslintrc.{js,json}`.
501fn pattern_names_only_source_files(pattern: &str) -> bool {
502    expand_brace_pattern(pattern)
503        .iter()
504        .all(|expanded| has_source_extension(Path::new(expanded)))
505}
506
507fn has_source_extension(path: &Path) -> bool {
508    path.extension()
509        .and_then(|ext| ext.to_str())
510        .is_some_and(|ext| SOURCE_EXTENSIONS.contains(&ext))
511}
512
513/// True when Phase 3a already read `path` for a resolved plugin. Phase 3a
514/// reads discovered source files only. A file that only a filesystem probe
515/// finds (`needs_fs`) was read when the discovery walk indexed it, for example
516/// a config in an allowlisted hidden directory.
517fn phase_3a_read_file(
518    path: &Path,
519    needs_fs: bool,
520    candidate_index: Option<&ConfigCandidateIndex>,
521) -> bool {
522    if needs_fs {
523        return candidate_index.is_some_and(|index| index.contains_file(path));
524    }
525    has_source_extension(path)
526}
527
528fn pattern_has_glob(pattern: &str) -> bool {
529    pattern.contains('*') || pattern.contains('?') || pattern.contains('[')
530}
531
532/// True when `pattern` has a directory component (any component before the
533/// basename) that the discovery walk does not index: a hidden directory NOT on
534/// the walk's traversal allowlist, or a directory that a built-in ignore
535/// pattern excludes, such as `build`. The in-memory candidate index cannot
536/// contain files under them, so the filesystem probe is required to keep those
537/// configs (e.g. `.config/prisma.ts`, `build/webpack.prod.js`) discoverable.
538pub(super) fn pattern_needs_filesystem(pattern: &str) -> bool {
539    let mut components = pattern.split('/').peekable();
540    let mut needs_fs = false;
541    while let Some(component) = components.next() {
542        if components.peek().is_none() {
543            break; // the basename is not a directory component
544        }
545        if component.starts_with('.')
546            && component != "."
547            && component != ".."
548            && !crate::discover::is_allowed_hidden_dir(OsStr::new(component))
549        {
550            needs_fs = true;
551            break;
552        }
553        if is_default_ignored_directory(component) {
554            needs_fs = true;
555            break;
556        }
557    }
558    needs_fs
559}
560
561/// Whether a built-in ignore pattern of the form `**/<name>/**` excludes a
562/// directory of this name from source discovery.
563fn is_default_ignored_directory(name: &str) -> bool {
564    fallow_config::DEFAULT_IGNORE_PATTERNS
565        .iter()
566        .any(|pattern| {
567            pattern
568                .strip_prefix("**/")
569                .and_then(|rest| rest.strip_suffix("/**"))
570                .is_some_and(|directory| directory == name)
571        })
572}
573
574/// In-memory equivalent of [`discover_pattern_matches`], resolving `pattern`
575/// against `index` instead of the filesystem. Mirrors that function's structure
576/// arm-for-arm (plain path, `**/` strip, parent/glob split) so the two produce
577/// identical hits for any file the index contains.
578fn match_pattern_in_index(
579    root: &Path,
580    pattern: &str,
581    index: &ConfigCandidateIndex,
582) -> Vec<PathBuf> {
583    if !pattern_has_glob(pattern) {
584        let path = root.join(pattern);
585        return match (path.parent(), path.file_name()) {
586            (Some(dir), Some(name)) if index.dir_contains(dir, name) => vec![path],
587            _ => Vec::new(),
588        };
589    }
590
591    if let Some(stripped) = pattern.strip_prefix("**/") {
592        return match_pattern_in_index(root, stripped, index);
593    }
594
595    let (dir, file_pattern) = match pattern.rsplit_once('/') {
596        Some((parent, file_pattern)) if !pattern_has_glob(parent) => {
597            (root.join(parent), file_pattern)
598        }
599        Some(_) => return Vec::new(),
600        None => (root.to_path_buf(), pattern),
601    };
602
603    let Ok(matcher) = globset::Glob::new(file_pattern).map(|g| g.compile_matcher()) else {
604        return Vec::new();
605    };
606    index.glob_matches_in_dir(&dir, &matcher)
607}
608
609fn discover_pattern_matches(root: &Path, pattern: &str) -> Vec<PathBuf> {
610    if !pattern_has_glob(pattern) {
611        let path = root.join(pattern);
612        return if path.is_file() {
613            vec![path]
614        } else {
615            Vec::new()
616        };
617    }
618
619    if let Some(stripped) = pattern.strip_prefix("**/") {
620        return discover_pattern_matches(root, stripped);
621    }
622
623    let (dir, file_pattern) = match pattern.rsplit_once('/') {
624        Some((parent, file_pattern)) if !pattern_has_glob(parent) => {
625            (root.join(parent), file_pattern)
626        }
627        Some(_) => return Vec::new(),
628        None => (root.to_path_buf(), pattern),
629    };
630
631    scan_dir_for_pattern(&dir, file_pattern)
632}
633
634fn scan_dir_for_pattern(dir: &Path, file_pattern: &str) -> Vec<PathBuf> {
635    let Ok(matcher) = globset::Glob::new(file_pattern).map(|g| g.compile_matcher()) else {
636        return Vec::new();
637    };
638    let Ok(entries) = std::fs::read_dir(dir) else {
639        return Vec::new();
640    };
641
642    entries
643        .filter_map(Result::ok)
644        .map(|entry| entry.path())
645        .filter(|path| path.is_file())
646        .filter(|path| {
647            path.file_name()
648                .is_some_and(|name| matcher.is_match(std::path::Path::new(name)))
649        })
650        .collect()
651}
652
653pub(super) fn expand_brace_pattern(pattern: &str) -> Vec<String> {
654    let Some(open) = pattern.find('{') else {
655        return vec![pattern.to_string()];
656    };
657    let Some(close_rel) = pattern[open + 1..].find('}') else {
658        return vec![pattern.to_string()];
659    };
660    let close = open + 1 + close_rel;
661
662    let prefix = &pattern[..open];
663    let suffix = &pattern[close + 1..];
664    let inner = &pattern[open + 1..close];
665    let mut expanded = Vec::new();
666    for option in inner.split(',') {
667        for tail in expand_brace_pattern(suffix) {
668            expanded.push(format!("{prefix}{option}{tail}"));
669        }
670    }
671    expanded
672}
673
674/// Validate the user-supplied exclude regexes attached to a `PathRule`.
675///
676/// The originating plugin and source config file are surfaced so users can
677/// locate every typo in one config-load error.
678fn collect_path_rule_regex_errors(
679    rule: &crate::plugins::PathRule,
680    plugin_name: &str,
681    config_path: Option<&Path>,
682    rule_kind: &'static str,
683    errors: &mut Vec<PluginRegexValidationError>,
684) {
685    for pattern in &rule.exclude_regexes {
686        if let Err(source) = regex::Regex::new(pattern) {
687            errors.push(PluginRegexValidationError::new(
688                PluginRegexValidationErrorInput {
689                    plugin_name,
690                    config_path,
691                    rule_kind,
692                    field: "exclude_regexes",
693                    rule_pattern: &rule.pattern,
694                    regex_pattern: pattern,
695                    source: &source,
696                },
697            ));
698        }
699    }
700    for pattern in &rule.exclude_segment_regexes {
701        if let Err(source) = regex::Regex::new(pattern) {
702            errors.push(PluginRegexValidationError::new(
703                PluginRegexValidationErrorInput {
704                    plugin_name,
705                    config_path,
706                    rule_kind,
707                    field: "exclude_segment_regexes",
708                    rule_pattern: &rule.pattern,
709                    regex_pattern: pattern,
710                    source: &source,
711                },
712            ));
713        }
714    }
715}
716
717/// Merge a `PluginResult` from config parsing into the aggregated result.
718///
719/// `config_path` is the source config file the plugin parsed (when known).
720/// It is only used to enrich config-load errors so users can find their typo.
721/// Tests and inline package.json fallbacks may pass `None`.
722pub fn process_config_result(
723    plugin_name: &str,
724    plugin_result: PluginResult,
725    result: &mut AggregatedPluginResult,
726    config_path: Option<&Path>,
727) -> Result<(), Vec<PluginRegexValidationError>> {
728    let mut regex_errors = Vec::new();
729
730    for rule in &plugin_result.entry_patterns {
731        collect_path_rule_regex_errors(
732            rule,
733            plugin_name,
734            config_path,
735            "entry_patterns[]",
736            &mut regex_errors,
737        );
738    }
739    for rule in &plugin_result.used_exports {
740        collect_path_rule_regex_errors(
741            &rule.path,
742            plugin_name,
743            config_path,
744            "used_exports[].path",
745            &mut regex_errors,
746        );
747    }
748    if !regex_errors.is_empty() {
749        return Err(regex_errors);
750    }
751    merge_plugin_result_fields(plugin_name, plugin_result, result);
752    Ok(())
753}
754
755/// Merge the entry patterns of one config result, with the replace and
756/// accumulate semantics of the plugin.
757fn merge_entry_patterns(
758    pname: &str,
759    plugin_result: &mut PluginResult,
760    result: &mut AggregatedPluginResult,
761) {
762    if plugin_result.replace_entry_patterns && !plugin_result.entry_patterns.is_empty() {
763        let first_replacement = result.replaced_entry_plugins.insert(pname.to_string());
764        if !plugin_result.accumulate_config_entry_patterns {
765            result.entry_patterns.retain(|(_, name)| name != pname);
766        } else if first_replacement {
767            // An earlier config of the plugin that did not replace (a Vitest
768            // config below the root) keeps its patterns. Only the static
769            // defaults go.
770            let config_patterns = &result.config_entry_patterns;
771            result.entry_patterns.retain(|(rule, name)| {
772                name != pname || config_patterns.contains(&(name.clone(), rule.pattern.clone()))
773            });
774        }
775    }
776    if plugin_result.accumulate_config_entry_patterns {
777        result.config_entry_patterns.extend(
778            plugin_result
779                .entry_patterns
780                .iter()
781                .map(|rule| (pname.to_string(), rule.pattern.clone())),
782        );
783    }
784    result.entry_patterns.extend(
785        std::mem::take(&mut plugin_result.entry_patterns)
786            .into_iter()
787            .map(|rule| (rule, pname.to_string())),
788    );
789}
790
791/// Merge a validated `PluginResult`'s payload fields into the aggregate, applying
792/// the per-plugin `replace_*` semantics for entry patterns, used-export rules,
793/// and path aliases.
794fn merge_plugin_result_fields(
795    pname: &str,
796    mut plugin_result: PluginResult,
797    result: &mut AggregatedPluginResult,
798) {
799    merge_entry_patterns(pname, &mut plugin_result, result);
800    if plugin_result.replace_used_export_rules && !plugin_result.used_exports.is_empty() {
801        result.used_exports.retain(|rule| rule.plugin_name != pname);
802    }
803    result.used_exports.extend(
804        plugin_result
805            .used_exports
806            .into_iter()
807            .map(|rule| PluginUsedExportRule::new(pname.to_string(), rule)),
808    );
809    result.config_export_credits.extend(
810        plugin_result
811            .entry_export_credits
812            .into_iter()
813            .map(|rule| PluginUsedExportRule::new(pname.to_string(), rule)),
814    );
815    result
816        .used_class_members
817        .extend(plugin_result.used_class_members);
818    result
819        .referenced_dependencies
820        .extend(plugin_result.referenced_dependencies);
821    result
822        .package_referenced_dependencies
823        .extend(plugin_result.package_referenced_dependencies);
824    super::push_missing(
825        &mut result.required_dependencies,
826        plugin_result.required_dependencies,
827    );
828    result.discovered_always_used.extend(
829        plugin_result
830            .always_used_files
831            .into_iter()
832            .map(|p| (p, pname.to_string())),
833    );
834    for (prefix, replacement) in plugin_result.path_aliases {
835        result
836            .path_aliases
837            .retain(|(existing_prefix, _)| existing_prefix != &prefix);
838        result.path_aliases.push((prefix, replacement));
839    }
840    result.setup_files.extend(
841        plugin_result
842            .setup_files
843            .into_iter()
844            .map(|p| (p, pname.to_string())),
845    );
846    result.fixture_patterns.extend(
847        plugin_result
848            .fixture_patterns
849            .into_iter()
850            .map(|p| (p, pname.to_string())),
851    );
852    result
853        .scss_include_paths
854        .extend(plugin_result.scss_include_paths);
855    result
856        .static_dir_mappings
857        .extend(plugin_result.static_dir_mappings);
858    result
859        .framework_static_dir_mappings
860        .extend(plugin_result.framework_static_dir_mappings);
861    result
862        .provided_dependencies
863        .extend(plugin_result.provided_dependencies);
864    result
865        .federation_sources
866        .extend(plugin_result.federation_sources);
867    for rule in plugin_result.jsx_import_sources {
868        if !result.jsx_import_sources.contains(&rule) {
869            result.jsx_import_sources.push(rule);
870        }
871    }
872    for rule in plugin_result.jsx_package_credits {
873        if !result.jsx_package_credits.contains(&rule) {
874            result.jsx_package_credits.push(rule);
875        }
876    }
877    for dir in plugin_result.tsconfig_jsx_dirs {
878        if !result.tsconfig_jsx_dirs.contains(&dir) {
879            result.tsconfig_jsx_dirs.push(dir);
880        }
881    }
882    for diagnostic in plugin_result.config_diagnostics {
883        if !result.config_diagnostics.contains(&diagnostic) {
884            result.config_diagnostics.push(diagnostic);
885        }
886    }
887}
888
889/// Check if a plugin already has a config file matched against discovered files.
890pub fn check_has_config_file(
891    plugin: &dyn Plugin,
892    config_matchers: &[(&dyn Plugin, Vec<globset::GlobMatcher>)],
893    relative_files: &[(PathBuf, String)],
894) -> bool {
895    !plugin.config_patterns().is_empty()
896        && config_matchers.iter().any(|(p, matchers)| {
897            p.name() == plugin.name()
898                && relative_files
899                    .iter()
900                    .any(|(_, rel)| matchers.iter().any(|m| m.is_match(rel.as_str())))
901        })
902}
903
904/// Check if a `PluginDetection` condition is satisfied.
905pub fn check_plugin_detection(
906    detection: &PluginDetection,
907    all_deps: &[&str],
908    root: &Path,
909    discovered_files: &[PathBuf],
910) -> bool {
911    match detection {
912        PluginDetection::Dependency { package } => all_deps.iter().any(|d| *d == package),
913        PluginDetection::FileExists { pattern } => {
914            if let Ok(matcher) =
915                fallow_config::compile_path_glob(pattern).map(|g| g.compile_matcher())
916            {
917                for file in discovered_files {
918                    let relative = file.strip_prefix(root).unwrap_or(file);
919                    if matcher.is_match(relative) {
920                        return true;
921                    }
922                }
923            }
924            fallow_config::glob_validation::expand_disk_glob(root, pattern)
925                .is_some_and(|mut paths| paths.next().is_some())
926        }
927        PluginDetection::All { conditions } => conditions
928            .iter()
929            .all(|c| check_plugin_detection(c, all_deps, root, discovered_files)),
930        PluginDetection::Any { conditions } => conditions
931            .iter()
932            .any(|c| check_plugin_detection(c, all_deps, root, discovered_files)),
933    }
934}
935
936#[cfg(test)]
937mod tests {
938    use super::*;
939
940    #[test]
941    fn pattern_needs_filesystem_only_for_non_allowlisted_hidden_dirs() {
942        // `.config` is a hidden directory not on the walk's allowlist, so a
943        // config under it is never in the in-memory index and must be probed.
944        assert!(pattern_needs_filesystem(".config/prisma.ts"));
945        // Plain, nested-non-hidden, dotfile-basename, `**/`, and allowlisted
946        // hidden-dir (`.storybook`) patterns all resolve from the index.
947        assert!(!pattern_needs_filesystem("tsconfig.json"));
948        assert!(!pattern_needs_filesystem("prisma/schema.prisma"));
949        assert!(!pattern_needs_filesystem(".eslintrc.json"));
950        assert!(!pattern_needs_filesystem("**/project.json"));
951        assert!(!pattern_needs_filesystem(".storybook/main.ts"));
952        assert!(!pattern_needs_filesystem("a/b/c.json"));
953        // A directory that a built-in ignore pattern excludes is not indexed.
954        assert!(pattern_needs_filesystem("build/webpack.prod.js"));
955        assert!(!pattern_needs_filesystem("config/webpack.prod.js"));
956    }
957
958    #[test]
959    fn config_candidate_index_matches_plain_nested_and_glob_shapes() {
960        let root = Path::new("/project");
961        let index = ConfigCandidateIndex::build([
962            Path::new("/project/tsconfig.json"),
963            Path::new("/project/packages/a/tsconfig.json"),
964            Path::new("/project/prisma/schema.prisma"),
965            Path::new("/project/src/main.ts"),
966        ]);
967
968        // Plain basename resolved at the project root and at a nested root.
969        assert_eq!(
970            match_pattern_in_index(root, "tsconfig.json", &index),
971            vec![PathBuf::from("/project/tsconfig.json")]
972        );
973        assert_eq!(
974            match_pattern_in_index(Path::new("/project/packages/a"), "tsconfig.json", &index),
975            vec![PathBuf::from("/project/packages/a/tsconfig.json")]
976        );
977        // Nested non-glob, `**/` strip, and a basename glob.
978        assert_eq!(
979            match_pattern_in_index(root, "prisma/schema.prisma", &index),
980            vec![PathBuf::from("/project/prisma/schema.prisma")]
981        );
982        assert_eq!(
983            match_pattern_in_index(root, "**/tsconfig.json", &index),
984            vec![PathBuf::from("/project/tsconfig.json")]
985        );
986        assert_eq!(
987            match_pattern_in_index(Path::new("/project/prisma"), "*.prisma", &index),
988            vec![PathBuf::from("/project/prisma/schema.prisma")]
989        );
990        // A pattern present in no indexed directory yields nothing.
991        assert!(match_pattern_in_index(root, "missing.json", &index).is_empty());
992    }
993
994    #[test]
995    fn file_exists_detection_never_matches_outside_root() {
996        let base = tempfile::tempdir().expect("create temp dir");
997        let root = base.path().join("project");
998        std::fs::create_dir_all(root.join(".config")).expect("create project dirs");
999        std::fs::write(base.path().join("outside-marker.json"), "{}").expect("write marker");
1000
1001        // `.*` names hidden directories. The `glob` crate also lets it match
1002        // `..`, so this pattern found the marker in the parent directory.
1003        for pattern in [".*/outside-marker.json", "..*/outside-marker.json"] {
1004            let detection = PluginDetection::FileExists {
1005                pattern: pattern.to_string(),
1006            };
1007            assert!(
1008                !check_plugin_detection(&detection, &[], &root, &[]),
1009                "{pattern} matched a file outside the project root"
1010            );
1011        }
1012
1013        std::fs::write(root.join(".config").join("outside-marker.json"), "{}")
1014            .expect("write marker inside root");
1015        let detection = PluginDetection::FileExists {
1016            pattern: ".*/outside-marker.json".to_string(),
1017        };
1018        assert!(check_plugin_detection(&detection, &[], &root, &[]));
1019    }
1020
1021    #[test]
1022    fn file_exists_detection_works_under_a_root_with_glob_characters() {
1023        let base = tempfile::tempdir().expect("create temp dir");
1024        let root = base.path().join("app [1]");
1025        std::fs::create_dir_all(root.join(".config")).expect("create project dirs");
1026        std::fs::write(root.join(".config").join("tool.json"), "{}").expect("write config");
1027
1028        let detection = PluginDetection::FileExists {
1029            pattern: ".config/*.json".to_string(),
1030        };
1031        assert!(check_plugin_detection(&detection, &[], &root, &[]));
1032    }
1033}