Skip to main content

fallow_core/plugins/
mod.rs

1//! Plugin system for framework-aware codebase analysis.
2//!
3//! Plugins read JS, TS and JSON config files with the Oxc parser and walk the
4//! AST. They never run JavaScript. Each plugin implements the [`Plugin`] trait
5//! with static defaults (entry patterns, config file patterns, used exports)
6//! and reads config files for entries, dependencies and setup files.
7
8use std::path::{Path, PathBuf};
9
10use fallow_config::{
11    AutoImportRule, EntryPointRole, JsxImportSourceRule, PackageJson, UsedClassMemberRule,
12};
13use fallow_types::semantic::SemanticFrameworkContract;
14use regex::Regex;
15
16use entry_point_roles::builtin_entry_point_role;
17#[cfg(test)]
18use entry_point_roles::{
19    RUNTIME_ENTRY_POINT_PLUGINS, SUPPORT_ENTRY_POINT_PLUGINS, TEST_ENTRY_POINT_PLUGINS,
20};
21
22/// Whether an entry rule of `result` matches the project-relative `path`, as
23/// entry point discovery compiles and matches the rules.
24#[cfg(test)]
25fn entry_rules_match(result: &PluginResult, path: &str) -> bool {
26    result
27        .entry_patterns
28        .iter()
29        .filter_map(|rule| CompiledPathRule::for_entry_rule(rule, "entry pattern"))
30        .any(|rule| rule.matches(path))
31}
32
33/// Which workspace diagnostic kind a plugin-stage advisory becomes.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum PluginConfigEffect {
36    /// The plugin could not read the key in full, so part of what it declares
37    /// never reached the analysis.
38    Unreadable,
39    /// The plugin read the key and does not model its effect, so a modeled
40    /// default the run would otherwise have applied stood down.
41    NotModeled,
42}
43
44/// One advisory about a config file a plugin read, before it becomes a
45/// [`fallow_config::WorkspaceDiagnostic`].
46///
47/// A plugin knows the fact (which config file, which key, why) but not the root
48/// the message renders against: in a workspace run its own `root` is the package
49/// root, while the diagnostic's path and message are project-root-relative. The
50/// conversion therefore happens once, where every plugin result has converged on
51/// the project root, and `config_path` is kept ABSOLUTE until then so the
52/// registry's canonical dedupe and the serialized root-relative form both work
53/// from one value (issue #2736).
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub struct PluginConfigDiagnostic {
56    /// Absolute path of the config file that was read.
57    pub config_path: PathBuf,
58    /// The plugin that read it, as it labels itself. Module Federation options
59    /// reach four bundler plugins inline, and each names itself rather than the
60    /// reader, because the config file the user must edit is the bundler's.
61    pub plugin: String,
62    /// The config key the advisory is about (`exposes`, `remotes`,
63    /// `components`, `imports`).
64    pub key: String,
65    /// Why, as a kebab-case token from the resulting kind's open set.
66    pub reason: String,
67    /// Which workspace diagnostic kind this becomes.
68    pub effect: PluginConfigEffect,
69}
70
71impl PluginConfigDiagnostic {
72    /// Build an advisory about a key a plugin could not read in full.
73    pub(super) fn unreadable(
74        config_path: &Path,
75        plugin: &str,
76        key: &str,
77        reason: &'static str,
78    ) -> Self {
79        Self {
80            config_path: config_path.to_path_buf(),
81            plugin: plugin.to_owned(),
82            key: key.to_owned(),
83            reason: reason.to_owned(),
84            effect: PluginConfigEffect::Unreadable,
85        }
86    }
87
88    /// Build an advisory about a key whose effect the plugin does not model.
89    pub(crate) fn not_modeled(
90        config_path: &Path,
91        plugin: &str,
92        key: &str,
93        reason: &'static str,
94    ) -> Self {
95        Self {
96            config_path: config_path.to_path_buf(),
97            plugin: plugin.to_owned(),
98            key: key.to_owned(),
99            reason: reason.to_owned(),
100            effect: PluginConfigEffect::NotModeled,
101        }
102    }
103
104    /// Render this advisory against the PROJECT root, which is the root every
105    /// consumer's paths are relative to.
106    #[must_use]
107    pub fn into_workspace_diagnostic(self, root: &Path) -> fallow_config::WorkspaceDiagnostic {
108        let Self {
109            config_path,
110            plugin,
111            key,
112            reason,
113            effect,
114        } = self;
115        let kind = match effect {
116            PluginConfigEffect::Unreadable => {
117                fallow_config::WorkspaceDiagnosticKind::PluginConfigUnreadable {
118                    plugin,
119                    key,
120                    reason,
121                }
122            }
123            PluginConfigEffect::NotModeled => {
124                fallow_config::WorkspaceDiagnosticKind::PluginEffectNotModeled {
125                    plugin,
126                    key,
127                    reason,
128                }
129            }
130        };
131        fallow_config::WorkspaceDiagnostic::new(root, config_path, kind)
132    }
133}
134
135/// Result of resolving a plugin's config file.
136#[derive(Debug, Default)]
137pub struct PluginResult {
138    /// Additional entry point glob patterns discovered from config.
139    entry_patterns: Vec<PathRule>,
140    /// When true, `entry_patterns` from config replace the plugin's static
141    /// `entry_patterns()` defaults instead of adding to them. Tools like Vitest
142    /// and Jest treat their config's include/testMatch as a replacement for built-in
143    /// defaults, so when the config is explicit the static patterns must be dropped.
144    replace_entry_patterns: bool,
145    /// When true, a replacing config removes only the static defaults, and the
146    /// replacing configs of one plugin run add their patterns together. When
147    /// false, the last replacing config of the plugin wins.
148    accumulate_config_entry_patterns: bool,
149    /// When true, `used_exports` from config replace the plugin's static
150    /// `used_export_rules()` defaults instead of adding to them.
151    replace_used_export_rules: bool,
152    /// Additional export-usage rules discovered from config.
153    used_exports: Vec<UsedExportRule>,
154    /// Exports that the tool reads from the files a config names. These rules
155    /// join the config-file export credit, so they count only under
156    /// `includeEntryExports`. Unlike `used_exports`, they never make an entry
157    /// point reportable when `includeEntryExports` is off.
158    entry_export_credits: Vec<UsedExportRule>,
159    /// Class member rules that should never be flagged as unused. Contributed
160    /// by plugins that know their framework invokes these methods at runtime
161    /// and may scope suppression via `extends` / `implements` constraints when
162    /// the method name is too common to allowlist globally.
163    used_class_members: Vec<UsedClassMemberRule>,
164    /// Dependencies referenced in config files (should not be flagged as unused).
165    referenced_dependencies: Vec<String>,
166    /// Dependencies a config credits only to the package that owns it, keyed
167    /// by the path of that package's `package.json`.
168    package_referenced_dependencies: Vec<(PathBuf, String)>,
169    /// Packages that a config needs installed. See [`RequiredDependency`].
170    required_dependencies: Vec<RequiredDependency>,
171    /// Additional files that are always considered used.
172    always_used_files: Vec<String>,
173    /// Path alias mappings discovered from config (prefix -> replacement directory).
174    path_aliases: Vec<(String, String)>,
175    /// Setup/helper files referenced from config.
176    setup_files: Vec<PathBuf>,
177    /// Test fixture glob patterns discovered from config.
178    fixture_patterns: Vec<String>,
179    /// Absolute directories to include when resolving SCSS/Sass `@import` and
180    /// `@use` specifiers. Contributed by framework plugins that read their
181    /// tool's equivalent of `includePaths` (e.g. Angular's
182    /// `stylePreprocessorOptions.includePaths` from `angular.json` /
183    /// `project.json`). Bare SCSS specifiers that fail to resolve relative to
184    /// the importing file retry against each include path using the SCSS
185    /// partial / directory-index conventions.
186    scss_include_paths: Vec<PathBuf>,
187    /// URL-to-filesystem static directory mappings discovered from tool config.
188    /// Each tuple is `(absolute_source_dir, normalized_url_mount)`.
189    static_dir_mappings: Vec<(PathBuf, String)>,
190    framework_static_dir_mappings: Vec<(PathBuf, String)>,
191    /// File-scoped dependency providers. Matching imports are considered
192    /// available from the framework runtime and are not unlisted dependencies.
193    provided_dependencies: Vec<ProvidedDependencyRule>,
194    /// Advisories about the config file this result was read from. A plugin
195    /// records the fact here instead of printing it, so it reaches the report
196    /// and every consumer rather than only a stderr line.
197    config_diagnostics: Vec<PluginConfigDiagnostic>,
198    /// Where a Module Federation config exposes a file or declares a remote
199    /// alias, kept so a trace can name the config (issue #2796).
200    federation_sources: Vec<FederationSource>,
201    /// JSX import sources that the config sets for the files it transforms.
202    /// The resolver adds the runtime edge to each matching file without a
203    /// JSX pragma.
204    jsx_import_sources: Vec<JsxImportSourceRule>,
205    /// Runtime packages that the JSX transform of a config imports when the
206    /// config sets no import source. The analysis credits a package only when
207    /// a matching file has JSX and no pragma. These rules never add a graph
208    /// edge.
209    jsx_package_credits: Vec<JsxImportSourceRule>,
210    /// The directories of the tsconfig files that set the JSX runtime of
211    /// TypeScript files, through `jsxImportSource` or a `jsx` mode that adds
212    /// no automatic runtime import. Vite then does not use the default
213    /// `react` runtime for the TypeScript files below these directories.
214    tsconfig_jsx_dirs: Vec<PathBuf>,
215}
216
217/// What a Module Federation config declares, and where, for the trace output.
218#[derive(Debug, Clone, PartialEq, Eq)]
219pub struct FederationSource {
220    /// What the config names.
221    pub target: FederationSourceTarget,
222    /// The absolute path of the config file.
223    pub config_path: PathBuf,
224    /// The plugin that read the config, as it labels itself.
225    pub plugin: String,
226    /// The config key that names the target.
227    pub key: &'static str,
228}
229
230/// The thing a [`FederationSource`] names.
231#[derive(Debug, Clone, PartialEq, Eq)]
232pub enum FederationSourceTarget {
233    /// An `exposes` target, as the entry-point rule it became.
234    Exposed(PathRule),
235    /// A `remotes` alias.
236    Remote(String),
237}
238
239impl FederationSource {
240    #[must_use]
241    fn prefixed(&self, ws_prefix: &str) -> Self {
242        let target = match &self.target {
243            FederationSourceTarget::Exposed(rule) => {
244                FederationSourceTarget::Exposed(rule.prefixed(ws_prefix))
245            }
246            FederationSourceTarget::Remote(alias) => FederationSourceTarget::Remote(alias.clone()),
247        };
248        Self {
249            target,
250            config_path: self.config_path.clone(),
251            plugin: self.plugin.clone(),
252            key: self.key,
253        }
254    }
255}
256
257/// Match the Module Federation sources of one analysis against the discovered
258/// files, for the trace output.
259///
260/// Only a project with a Federation config pays for the match, and it runs
261/// once per analysis, so a trace reads plain data. A remote that a literal
262/// runtime call (`registerRemotes`, `loadRemote`, `init`, `createInstance`) names traces to the source
263/// file, with the function name as the key.
264#[must_use]
265fn federation_trace_provenance(
266    root: &Path,
267    files: &[crate::discover::DiscoveredFile],
268    sources: &[FederationSource],
269    modules: &[crate::extract::ModuleInfo],
270) -> fallow_types::trace::TraceProvenance {
271    let mut provenance = fallow_types::trace::TraceProvenance::default();
272    push_runtime_remote_sources(&mut provenance, root, files, modules);
273    if sources.is_empty() {
274        return provenance;
275    }
276    let mut exposed = Vec::new();
277    for source in sources {
278        let config = source
279            .config_path
280            .strip_prefix(root)
281            .unwrap_or(&source.config_path)
282            .to_path_buf();
283        let trace_source = fallow_types::trace::TraceSource {
284            kind: "module-federation".to_owned(),
285            plugin: source.plugin.clone(),
286            config,
287            key: source.key.to_owned(),
288        };
289        match &source.target {
290            FederationSourceTarget::Exposed(rule) => {
291                if let Some(compiled) =
292                    CompiledPathRule::for_entry_rule(rule, "Module Federation exposes target")
293                {
294                    exposed.push((compiled, trace_source));
295                }
296            }
297            FederationSourceTarget::Remote(alias) => {
298                provenance.push_dependency(alias.clone(), trace_source);
299            }
300        }
301    }
302    if exposed.is_empty() {
303        return provenance;
304    }
305    for file in files {
306        let Ok(relative) = file.path.strip_prefix(root) else {
307            continue;
308        };
309        let relative_str = relative.to_string_lossy().replace('\\', "/");
310        for (rule, source) in &exposed {
311            if rule.matches(&relative_str) {
312                provenance.push_file(relative.to_path_buf(), source.clone());
313            }
314        }
315    }
316    provenance
317}
318
319/// Export names that frameworks read as configuration, not as code.
320///
321/// A plugin `used_exports` rule can list these names next to real handlers
322/// (Next.js lists `dynamic` next to `GET` and `default`). Only a listed name
323/// with a literal value counts as configuration, so the review brief does not
324/// ask for a test of it. Extend this set when a new plugin adds a
325/// configuration-only export. Never add a name that holds behavior, such as
326/// `generateMetadata`, `loader` or a route handler.
327const CONFIG_ONLY_EXPORT_NAMES: &[&str] = &[
328    "dynamic",
329    "dynamicParams",
330    "revalidate",
331    "fetchCache",
332    "runtime",
333    "preferredRegion",
334    "maxDuration",
335    "prerender",
336    "config",
337    "metadata",
338    "viewport",
339];
340
341/// Record why the unused devDependency check credits each plugin tooling
342/// dependency, so `--trace-dependency` explains the credit instead of calling
343/// the dependency unused.
344fn push_tooling_trace_credits(
345    provenance: &mut fallow_types::trace::TraceProvenance,
346    root: &Path,
347    workspaces: &[fallow_config::WorkspaceInfo],
348    plugin_result: &AggregatedPluginResult,
349) {
350    for entry in &plugin_result.plugin_tooling {
351        let Some(evidence) = entry.evidence(&plugin_result.script_used_packages) else {
352            continue;
353        };
354        let credit = match evidence {
355            PluginToolingEvidence::OwnConfig(config) => fallow_types::trace::ToolingCredit {
356                reason: "plugin-config".to_owned(),
357                plugin: Some(entry.plugin.clone()),
358                config: Some(config.strip_prefix(root).unwrap_or(config).to_path_buf()),
359                reference: None,
360            },
361            PluginToolingEvidence::Reference(name) => fallow_types::trace::ToolingCredit {
362                reason: "plugin-reference".to_owned(),
363                plugin: Some(entry.plugin.clone()),
364                config: None,
365                reference: Some(name.to_owned()),
366            },
367        };
368        for dependency in &entry.dependencies {
369            provenance.push_tooling_credit(dependency.clone(), credit.clone());
370        }
371    }
372    push_types_trace_credits(provenance, plugin_result);
373    push_catalogue_trace_credits(provenance, root, workspaces, plugin_result);
374}
375
376/// Record why the unused devDependency check credits each catalogue entry in
377/// `devDependencies` that the trace would otherwise call unused: a library
378/// entry by name, a command-line tool by its own config file or its
379/// package.json key, and any entry that the same manifest lists in
380/// `peerDependencies`.
381///
382/// The check reads each declaring manifest on its own, so a credit here comes
383/// from a manifest that declares the name. A config in a sibling workspace
384/// gives no credit.
385fn push_catalogue_trace_credits(
386    provenance: &mut fallow_types::trace::TraceProvenance,
387    root: &Path,
388    workspaces: &[fallow_config::WorkspaceInfo],
389    plugin_result: &AggregatedPluginResult,
390) {
391    let manifests = read_trace_manifests(root, workspaces);
392    let mut names: Vec<&String> = plugin_result.dev_dependency_names.iter().collect();
393    names.sort_unstable();
394    for name in names {
395        let declaring: Vec<&(PathBuf, serde_json::Value)> = manifests
396            .iter()
397            .filter(|(_, manifest)| manifest_lists(manifest, "devDependencies", name))
398            .collect();
399        if let Some(credit) = catalogue_credit(name, root, &declaring) {
400            provenance.push_tooling_credit(name.clone(), credit);
401        }
402        if let Some((path, _)) = declaring
403            .iter()
404            .find(|(_, manifest)| manifest_lists(manifest, "peerDependencies", name))
405        {
406            provenance.push_tooling_credit(
407                name.clone(),
408                fallow_types::trace::ToolingCredit {
409                    reason: "own-peer".to_owned(),
410                    plugin: None,
411                    config: Some(path.strip_prefix(root).unwrap_or(path).to_path_buf()),
412                    reference: None,
413                },
414            );
415        }
416    }
417}
418
419/// The root manifest and each workspace manifest, parsed, root first.
420fn read_trace_manifests(
421    root: &Path,
422    workspaces: &[fallow_config::WorkspaceInfo],
423) -> Vec<(PathBuf, serde_json::Value)> {
424    std::iter::once(root)
425        .chain(
426            workspaces
427                .iter()
428                .map(|ws| ws.root.as_path())
429                .filter(|ws_root| *ws_root != root),
430        )
431        .filter_map(|package_root| {
432            let path = package_root.join("package.json");
433            let content = std::fs::read_to_string(&path).ok()?;
434            serde_json::from_str(&content)
435                .ok()
436                .map(|value| (path, value))
437        })
438        .collect()
439}
440
441fn manifest_lists(manifest: &serde_json::Value, section: &str, name: &str) -> bool {
442    manifest
443        .get(section)
444        .and_then(serde_json::Value::as_object)
445        .is_some_and(|deps| deps.contains_key(name))
446}
447
448/// The catalogue credit of `name` from the first declaring manifest that the
449/// unused devDependency check credits.
450fn catalogue_credit(
451    name: &str,
452    root: &Path,
453    declaring: &[&(PathBuf, serde_json::Value)],
454) -> Option<fallow_types::trace::ToolingCredit> {
455    if is_ambient_types_package(name) || types_package_target(name).is_some() {
456        return None;
457    }
458    let Some(patterns) = cli_tooling_config_patterns(name) else {
459        return is_known_tooling_dependency(name).then(|| fallow_types::trace::ToolingCredit {
460            reason: "known-tooling".to_owned(),
461            plugin: None,
462            config: None,
463            reference: None,
464        });
465    };
466    let config = declaring.iter().find_map(|(path, manifest)| {
467        crate::analyze::cli_tool_own_config(name, patterns, root, path, Some(manifest))
468    })?;
469    Some(fallow_types::trace::ToolingCredit {
470        reason: "known-tooling-config".to_owned(),
471        plugin: None,
472        config: Some(config.strip_prefix(root).unwrap_or(&config).to_path_buf()),
473        reference: None,
474    })
475}
476
477/// Record why the unused devDependency check credits each type package in
478/// `devDependencies`: ambient globals, a declared target package, or a
479/// tsconfig `types` entry. A target that the code imports is credited by the trace
480/// itself, which reads the module graph.
481fn push_types_trace_credits(
482    provenance: &mut fallow_types::trace::TraceProvenance,
483    plugin_result: &AggregatedPluginResult,
484) {
485    let declared = plugin_result.dependency_binaries.declared_packages();
486    let mut names: Vec<&String> = plugin_result.dev_dependency_names.iter().collect();
487    names.sort_unstable();
488    for name in names {
489        let credit = if is_ambient_types_package(name) {
490            fallow_types::trace::ToolingCredit {
491                reason: "ambient-types".to_owned(),
492                plugin: None,
493                config: None,
494                reference: None,
495            }
496        } else if let Some(target) = types_package_target(name) {
497            if declared.contains(&target) {
498                fallow_types::trace::ToolingCredit {
499                    reason: "types-target".to_owned(),
500                    plugin: None,
501                    config: None,
502                    reference: Some(target),
503                }
504            } else if plugin_result.referenced_dependencies.contains(name) {
505                fallow_types::trace::ToolingCredit {
506                    reason: "types-config".to_owned(),
507                    plugin: None,
508                    config: None,
509                    reference: None,
510                }
511            } else {
512                continue;
513            }
514        } else {
515            continue;
516        };
517        provenance.push_tooling_credit(name.clone(), credit);
518    }
519}
520
521/// Add a trace source for each remote that a literal runtime call names.
522fn push_runtime_remote_sources(
523    provenance: &mut fallow_types::trace::TraceProvenance,
524    root: &Path,
525    files: &[crate::discover::DiscoveredFile],
526    modules: &[crate::extract::ModuleInfo],
527) {
528    for module in modules {
529        let mut file = None;
530        for fact in module.semantic_facts.iter() {
531            let fallow_types::extract::SemanticFact::FederationRuntimeRemote(fact) = fact else {
532                continue;
533            };
534            let Some(remote) = &fact.remote else {
535                continue;
536            };
537            let Some(path) = file.get_or_insert_with(|| {
538                files.get(module.file_id.0 as usize).map(|file| {
539                    file.path
540                        .strip_prefix(root)
541                        .unwrap_or(&file.path)
542                        .to_path_buf()
543                })
544            }) else {
545                break;
546            };
547            provenance.push_dependency(
548                remote.clone(),
549                fallow_types::trace::TraceSource {
550                    kind: "module-federation".to_owned(),
551                    plugin: "module-federation".to_owned(),
552                    config: path.clone(),
553                    key: fact.call.name().to_owned(),
554                },
555            );
556        }
557    }
558}
559
560impl PluginResult {
561    /// Register `entry` values that a bundler reads relative to the directory
562    /// of its config file. The project root run and the workspace run can read
563    /// the same config, so each value is anchored at the config directory. A
564    /// value with a leading `!` excludes its matches from every other value.
565    fn extend_config_dir_entry_patterns(
566        &mut self,
567        values: Vec<String>,
568        config_path: &Path,
569        root: &Path,
570    ) {
571        let (negated, positive): (Vec<String>, Vec<String>) =
572            values.into_iter().partition(|value| value.starts_with('!'));
573        let excluded: Vec<String> = negated
574            .iter()
575            .filter_map(|value| value.strip_prefix('!'))
576            .filter_map(|value| config_parser::normalize_config_path(value, config_path, root))
577            .collect();
578        self.entry_patterns.extend(
579            positive
580                .iter()
581                .filter_map(|value| config_parser::normalize_config_path(value, config_path, root))
582                .map(|pattern| {
583                    PathRule::new(pattern).with_excluded_globs(excluded.iter().cloned())
584                }),
585        );
586    }
587
588    /// Register an entry pattern whose leading `../` segments are relative to
589    /// the plugin root. The workspace prefix resolves them.
590    fn push_parent_relative_entry_pattern(&mut self, pattern: String) {
591        let mut rule = PathRule::new(pattern);
592        rule.parent_relative = true;
593        self.entry_patterns.push(rule);
594    }
595
596    fn push_entry_pattern(&mut self, pattern: impl Into<String>) {
597        self.entry_patterns
598            .push(PathRule::new(normalize_entry_pattern(pattern.into())));
599    }
600
601    fn extend_entry_patterns<I, S>(&mut self, patterns: I)
602    where
603        I: IntoIterator<Item = S>,
604        S: Into<String>,
605    {
606        self.entry_patterns.extend(
607            patterns
608                .into_iter()
609                .map(|pat| PathRule::new(normalize_entry_pattern(pat.into()))),
610        );
611    }
612
613    /// Route each config value to the surface that can use it: a value naming a
614    /// module request credits its package, every other value becomes an entry
615    /// pattern.
616    ///
617    /// A bundler `entry` accepts a project file and a bare module request such as
618    /// `react-hot-loader/patch` in the same list. A module request names no file,
619    /// so a glob built from it matches nothing while the package still needs
620    /// dependency credit. Module Federation `exposes` targets already split the
621    /// two this way (issue #2706); bundler entries now do too (issue #2739).
622    ///
623    /// `resolve_path` maps a path value to its project-relative form, for
624    /// example against a `context` directory. It runs after the value is
625    /// classified, because a joined path such as `app/main` no longer carries
626    /// the `./` that marks it as a path.
627    fn extend_entry_patterns_or_dependencies<I, S>(
628        &mut self,
629        values: I,
630        resolve_path: impl Fn(String) -> String,
631    ) where
632        I: IntoIterator<Item = S>,
633        S: Into<String>,
634    {
635        for value in values {
636            let value = value.into();
637            if let Some(request) = module_request(&value) {
638                self.referenced_dependencies
639                    .push(crate::resolve::extract_package_name(request));
640                continue;
641            }
642            self.push_entry_path(resolve_path(value));
643        }
644    }
645
646    /// Route each value of a rollup-style `input` to both surfaces when it is
647    /// ambiguous.
648    ///
649    /// Rollup, rolldown and vite resolve an `input` value with no importer: a
650    /// resolve plugin can read it as a module request, and without one it is a
651    /// path relative to the working directory. A value without `./`, `../` or
652    /// `/`, without a source extension and without glob syntax can therefore
653    /// name either one. It keeps the entry pattern, and it credits the package
654    /// unless the value names a file under `root`. A value that names a
655    /// project file is a path, so it must not hide an unused package that has
656    /// the same first segment (issue #2753).
657    fn extend_entry_patterns_and_dependencies<I, S>(&mut self, values: I, root: &Path)
658    where
659        I: IntoIterator<Item = S>,
660        S: Into<String>,
661    {
662        for value in values {
663            let value = value.into();
664            if let Some(request) = module_request(&value)
665                && !names_project_file(root, request)
666            {
667                self.referenced_dependencies
668                    .push(crate::resolve::extract_package_name(request));
669            }
670            self.push_entry_path(value);
671        }
672    }
673
674    /// Register each value as a bundler entry path.
675    fn extend_entry_paths<I, S>(&mut self, values: I)
676    where
677        I: IntoIterator<Item = S>,
678        S: Into<String>,
679    {
680        for value in values {
681            self.push_entry_path(value.into());
682        }
683    }
684
685    /// Register a bundler entry path.
686    ///
687    /// A bundler resolves an entry without a source extension the way it
688    /// resolves an import: first as a file with each extension, then as a
689    /// directory through its index file. `./lib` therefore names
690    /// `lib/index.ts`, and `./src/app` names `src/app.ts`. The value as written
691    /// stays a pattern too, so a file without an extension still matches.
692    fn push_entry_path(&mut self, value: String) {
693        if has_glob_syntax(&value) || has_source_extension(&value) {
694            self.push_entry_pattern(value);
695            return;
696        }
697        let base = value.trim_end_matches('/').to_owned();
698        self.push_entry_pattern(value);
699        self.push_entry_pattern(format!("{base}.{REQUEST_EXTENSIONS}"));
700        self.push_entry_pattern(format!("{base}/index.{REQUEST_EXTENSIONS}"));
701    }
702
703    /// Whether this result contributes nothing, which lets the registry skip a
704    /// config file entirely.
705    ///
706    /// A config that yields only a diagnostic is NOT empty: an unreadable
707    /// `exposes` in a config that declares nothing else is exactly the case the
708    /// advisory exists for, and skipping the result would drop it.
709    #[must_use]
710    const fn is_empty(&self) -> bool {
711        self.config_diagnostics.is_empty()
712            && self.entry_patterns.is_empty()
713            && self.used_exports.is_empty()
714            && self.entry_export_credits.is_empty()
715            && self.used_class_members.is_empty()
716            && self.referenced_dependencies.is_empty()
717            && self.package_referenced_dependencies.is_empty()
718            && self.required_dependencies.is_empty()
719            && self.always_used_files.is_empty()
720            && self.path_aliases.is_empty()
721            && self.setup_files.is_empty()
722            && self.fixture_patterns.is_empty()
723            && self.scss_include_paths.is_empty()
724            && self.static_dir_mappings.is_empty()
725            && self.framework_static_dir_mappings.is_empty()
726            && self.provided_dependencies.is_empty()
727            && self.federation_sources.is_empty()
728            && self.jsx_import_sources.is_empty()
729            && self.jsx_package_credits.is_empty()
730            && self.tsconfig_jsx_dirs.is_empty()
731    }
732}
733
734/// Whether an extensionless value names a file under `root`: the value itself,
735/// the value with a source extension, or the index file of the directory it
736/// names. This is the order in which a bundler resolves a path.
737fn names_project_file(root: &Path, value: &str) -> bool {
738    let base = root.join(value);
739    base.is_file()
740        || crate::discover::SOURCE_EXTENSIONS.iter().any(|extension| {
741            let mut candidate = base.clone().into_os_string();
742            candidate.push(".");
743            candidate.push(extension);
744            Path::new(&candidate).is_file() || base.join(format!("index.{extension}")).is_file()
745        })
746}
747
748/// Brace list of the extensions a bundler tries for a request that names no
749/// extension. Entry patterns are plain globs with no extension expansion, so a
750/// bare `src/Button` would match no file.
751const REQUEST_EXTENSIONS: &str = "{ts,tsx,mts,cts,gts,js,jsx,mjs,cjs,gjs,vue,svelte,astro,mdx}";
752
753fn normalize_entry_pattern(pattern: String) -> String {
754    pattern
755        .strip_prefix("./")
756        .map(str::to_owned)
757        .unwrap_or(pattern)
758}
759
760/// The module request a config value names, or `None` when the value names a
761/// file or a pattern over project files.
762///
763/// A bundler resolves a value without a leading `./`, `../` or `/` and without a
764/// source extension through module resolution, so it names a package. Both
765/// Module Federation `exposes` targets and bundler `entry` values are read this
766/// way. A value carrying glob syntax is a path in every case: no module
767/// resolution accepts a glob, so `src/pages/**` stays an entry pattern. A
768/// resource query is not part of the request, so it is dropped before both
769/// tests and before the package name is taken.
770fn module_request(value: &str) -> Option<&str> {
771    let request = strip_resource_query(value);
772    (config_parser::is_package_specifier(request)
773        && !has_glob_syntax(request)
774        && !has_source_extension(request))
775    .then_some(request)
776}
777
778/// Drop a trailing resource query from a config value.
779///
780/// A bundler hands everything after the first `?` to the loader, so the standard
781/// hot-reload entry `webpack-hot-middleware/client?reload=true` names the
782/// package's `client` module. A `?` is also the single-character glob wildcard,
783/// so what follows it decides: `reload=true` is a query, the `.ts` of
784/// `src/pag?.ts` is not.
785fn strip_resource_query(value: &str) -> &str {
786    match value.split_once('?') {
787        Some((request, query)) if is_resource_query(query) => request,
788        _ => value,
789    }
790}
791
792/// Whether a string is an `&`-separated list of `key` or `key=value` pairs whose
793/// keys read like identifiers.
794fn is_resource_query(query: &str) -> bool {
795    !query.is_empty()
796        && query.split('&').all(|pair| {
797            let key = pair.split_once('=').map_or(pair, |(key, _)| key);
798            key.starts_with(|first: char| first.is_ascii_alphanumeric() || first == '_')
799                && key
800                    .chars()
801                    .all(|char| char.is_ascii_alphanumeric() || matches!(char, '_' | '-' | '.'))
802        })
803}
804
805/// Whether a config value carries glob metacharacters, which makes it a pattern
806/// over project files rather than a single path or module request.
807fn has_glob_syntax(value: &str) -> bool {
808    value.contains('*') || value.contains('?') || value.contains('[') || value.contains('{')
809}
810
811/// Whether a config value carries an extension discovery analyzes. Discovery's
812/// own extension set decides, so a value naming a file type discovery does not
813/// analyze stays a module request.
814fn has_source_extension(value: &str) -> bool {
815    Path::new(value)
816        .extension()
817        .and_then(|ext| ext.to_str())
818        .is_some_and(|ext| {
819            crate::discover::SOURCE_EXTENSIONS.contains(&ext.to_ascii_lowercase().as_str())
820        })
821}
822
823/// A file-pattern rule with optional exclusion globs plus path-level or
824/// segment-level regex filters.
825///
826/// Exclusion regexes are matched against the project-relative path and should be
827/// anchored when generated dynamically so they can be safely workspace-prefixed.
828#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
829pub struct PathRule {
830    pub pattern: String,
831    pub exclude_globs: Vec<String>,
832    pub exclude_regexes: Vec<String>,
833    /// Regexes matched against individual path segments. These are not prefixed
834    /// for workspaces because they intentionally operate on segment names rather
835    /// than the full project-relative path.
836    pub exclude_segment_regexes: Vec<String>,
837    /// Whether the leading `../` segments of `pattern` are relative to the
838    /// plugin root, so the workspace prefix resolves them. Only the Module
839    /// Federation reader sets it, for an `exposes` target in a sibling
840    /// workspace. Other plugins emit patterns relative to a config directory,
841    /// such as the Storybook `../src/**`, which must not climb out of the
842    /// workspace.
843    pub parent_relative: bool,
844}
845
846impl PathRule {
847    #[must_use]
848    pub(crate) fn new(pattern: impl Into<String>) -> Self {
849        Self {
850            pattern: pattern.into(),
851            exclude_globs: Vec::new(),
852            exclude_regexes: Vec::new(),
853            exclude_segment_regexes: Vec::new(),
854            parent_relative: false,
855        }
856    }
857
858    #[must_use]
859    fn from_static(pattern: &'static str) -> Self {
860        Self::new(pattern)
861    }
862
863    /// A rule for a tool glob with extglob groups, such as `!(*.spec)`. The
864    /// rule matches at least the paths that the tool matches. Each negated
865    /// group becomes an excluded glob.
866    #[must_use]
867    fn from_extglob(pattern: &str) -> Self {
868        let rewritten = fallow_config::extglob::rewrite_include(pattern);
869        Self::new(rewritten.include).with_excluded_globs(rewritten.excludes)
870    }
871
872    /// Exclude the paths of tool globs with extglob groups. An excluded glob
873    /// never removes more paths than the tool does, so a glob with a negated
874    /// group excludes nothing.
875    #[must_use]
876    fn with_excluded_extglobs<I, S>(self, patterns: I) -> Self
877    where
878        I: IntoIterator<Item = S>,
879        S: AsRef<str>,
880    {
881        let excluded: Vec<String> = patterns
882            .into_iter()
883            .filter_map(|pattern| fallow_config::extglob::rewrite_exclude(pattern.as_ref()))
884            .collect();
885        self.with_excluded_globs(excluded)
886    }
887
888    #[must_use]
889    pub(crate) fn with_excluded_globs<I, S>(mut self, patterns: I) -> Self
890    where
891        I: IntoIterator<Item = S>,
892        S: Into<String>,
893    {
894        self.exclude_globs
895            .extend(patterns.into_iter().map(Into::into));
896        self
897    }
898
899    #[must_use]
900    fn with_excluded_regexes<I, S>(mut self, patterns: I) -> Self
901    where
902        I: IntoIterator<Item = S>,
903        S: Into<String>,
904    {
905        self.exclude_regexes
906            .extend(patterns.into_iter().map(Into::into));
907        self
908    }
909
910    #[must_use]
911    fn with_excluded_segment_regexes<I, S>(mut self, patterns: I) -> Self
912    where
913        I: IntoIterator<Item = S>,
914        S: Into<String>,
915    {
916        self.exclude_segment_regexes
917            .extend(patterns.into_iter().map(Into::into));
918        self
919    }
920
921    #[must_use]
922    fn prefixed(&self, ws_prefix: &str) -> Self {
923        let prefix = |pattern: &str| {
924            if self.parent_relative && pattern.starts_with("../") {
925                resolve_parent_relative_pattern(pattern, ws_prefix)
926            } else {
927                prefix_workspace_pattern(pattern, ws_prefix)
928            }
929        };
930        Self {
931            pattern: prefix(&self.pattern),
932            exclude_globs: self
933                .exclude_globs
934                .iter()
935                .map(|pattern| prefix(pattern))
936                .collect(),
937            exclude_regexes: self
938                .exclude_regexes
939                .iter()
940                .map(|pattern| prefix_workspace_regex(pattern, ws_prefix))
941                .collect(),
942            exclude_segment_regexes: self.exclude_segment_regexes.clone(),
943            parent_relative: false,
944        }
945    }
946}
947
948/// A file-scoped dependency provider rule contributed by a framework plugin.
949#[derive(Debug, Clone, Default, PartialEq, Eq)]
950pub struct ProvidedDependencyRule {
951    pub(crate) path: PathRule,
952    exact_specifiers: Vec<String>,
953    specifier_prefixes: Vec<String>,
954}
955
956impl ProvidedDependencyRule {
957    #[must_use]
958    fn new(
959        pattern: impl Into<String>,
960        exact_specifiers: impl IntoIterator<Item = impl Into<String>>,
961        specifier_prefixes: impl IntoIterator<Item = impl Into<String>>,
962    ) -> Self {
963        Self {
964            path: PathRule::new(pattern),
965            exact_specifiers: exact_specifiers.into_iter().map(Into::into).collect(),
966            specifier_prefixes: specifier_prefixes.into_iter().map(Into::into).collect(),
967        }
968    }
969
970    #[must_use]
971    fn prefixed(&self, ws_prefix: &str) -> Self {
972        Self {
973            path: self.path.prefixed(ws_prefix),
974            exact_specifiers: self.exact_specifiers.clone(),
975            specifier_prefixes: self.specifier_prefixes.clone(),
976        }
977    }
978
979    #[must_use]
980    pub(crate) fn may_cover_package(&self, package_name: &str) -> bool {
981        self.exact_specifiers
982            .iter()
983            .chain(self.specifier_prefixes.iter())
984            .any(|specifier| crate::resolve::extract_package_name(specifier) == package_name)
985    }
986
987    #[must_use]
988    pub(crate) fn covers_specifier(&self, specifier: &str) -> bool {
989        self.exact_specifiers
990            .iter()
991            .any(|allowed| allowed == specifier)
992            || self
993                .specifier_prefixes
994                .iter()
995                .any(|prefix| specifier.starts_with(prefix))
996    }
997}
998
999/// Compile the include glob of an entry rule. Its `*` stays in one path
1000/// segment, and it accepts an empty alternative, such as `{,m}js`, because
1001/// the rewrite of an extglob `?(m)` group gives one.
1002pub(crate) fn entry_rule_glob(pattern: &str) -> Result<globset::Glob, globset::Error> {
1003    globset::GlobBuilder::new(pattern)
1004        .literal_separator(true)
1005        .empty_alternates(true)
1006        .build()
1007}
1008
1009/// A compiled path rule matcher shared by entry-point and used-export matching.
1010///
1011/// Every glob accepts an empty alternative, such as `{,m}js`, because the
1012/// rewrite of an extglob `?(m)` group gives one.
1013#[derive(Debug, Clone)]
1014pub(crate) struct CompiledPathRule {
1015    include: globset::GlobMatcher,
1016    exclude_globs: Vec<globset::GlobMatcher>,
1017    exclude_regexes: Vec<Regex>,
1018    exclude_segment_regexes: Vec<Regex>,
1019}
1020
1021impl CompiledPathRule {
1022    pub(crate) fn for_entry_rule(rule: &PathRule, rule_kind: &str) -> Option<Self> {
1023        let include = match entry_rule_glob(&rule.pattern) {
1024            Ok(glob) => glob.compile_matcher(),
1025            Err(err) => {
1026                tracing::warn!("invalid {rule_kind} '{}': {err}", rule.pattern);
1027                return None;
1028            }
1029        };
1030        Some(Self {
1031            include,
1032            exclude_globs: compile_excluded_globs(&rule.exclude_globs, rule_kind, &rule.pattern),
1033            exclude_regexes: compile_excluded_regexes(
1034                &rule.exclude_regexes,
1035                rule_kind,
1036                &rule.pattern,
1037            ),
1038            exclude_segment_regexes: compile_excluded_segment_regexes(
1039                &rule.exclude_segment_regexes,
1040                rule_kind,
1041                &rule.pattern,
1042            ),
1043        })
1044    }
1045
1046    pub(crate) fn for_used_export_rule(rule: &PathRule, rule_kind: &str) -> Option<Self> {
1047        Self::for_entry_rule(rule, rule_kind)
1048    }
1049
1050    #[must_use]
1051    pub(crate) fn matches(&self, path: &str) -> bool {
1052        self.include.is_match(path)
1053            && !self.exclude_globs.iter().any(|glob| glob.is_match(path))
1054            && !self
1055                .exclude_regexes
1056                .iter()
1057                .any(|regex| regex.is_match(path))
1058            && !matches_segment_regex(path, &self.exclude_segment_regexes)
1059    }
1060}
1061
1062fn prefix_workspace_pattern(pattern: &str, ws_prefix: &str) -> String {
1063    if pattern.starts_with(ws_prefix) || pattern.starts_with('/') {
1064        pattern.to_string()
1065    } else {
1066        format!("{ws_prefix}/{pattern}")
1067    }
1068}
1069
1070/// Resolve the leading `../` segments of a parent-relative pattern against the
1071/// workspace prefix, so a pattern that names a file in a sibling workspace
1072/// matches from the project root. A pattern that climbs past the project root,
1073/// or a prefix that is not project-relative, keeps the pattern as written,
1074/// which matches no project file.
1075fn resolve_parent_relative_pattern(pattern: &str, ws_prefix: &str) -> String {
1076    if ws_prefix.starts_with('/') || Path::new(ws_prefix).is_absolute() {
1077        return pattern.to_string();
1078    }
1079    // The workspace prefix comes from a native path, so on Windows its
1080    // segments are separated by backslashes.
1081    let mut base: Vec<&str> = ws_prefix
1082        .split(['/', '\\'])
1083        .filter(|segment| !segment.is_empty())
1084        .collect();
1085    let mut rest = pattern;
1086    while let Some(stripped) = rest.strip_prefix("../") {
1087        if base.pop().is_none() {
1088            return pattern.to_string();
1089        }
1090        rest = stripped;
1091    }
1092    if base.is_empty() {
1093        rest.to_string()
1094    } else {
1095        format!("{}/{rest}", base.join("/"))
1096    }
1097}
1098
1099fn prefix_workspace_regex(pattern: &str, ws_prefix: &str) -> String {
1100    if let Some(pattern) = pattern.strip_prefix('^') {
1101        format!("^{}/{}", regex::escape(ws_prefix), pattern)
1102    } else {
1103        format!("^{}/(?:{})", regex::escape(ws_prefix), pattern)
1104    }
1105}
1106
1107fn compile_excluded_globs(
1108    patterns: &[String],
1109    rule_kind: &str,
1110    rule_pattern: &str,
1111) -> Vec<globset::GlobMatcher> {
1112    patterns
1113        .iter()
1114        .filter_map(|pattern| {
1115            match globset::GlobBuilder::new(pattern)
1116                .literal_separator(true)
1117                .empty_alternates(true)
1118                .build()
1119            {
1120                Ok(glob) => Some(glob.compile_matcher()),
1121                Err(err) => {
1122                    tracing::warn!(
1123                        "skipping invalid excluded glob '{}' for {} '{}': {err}",
1124                        pattern,
1125                        rule_kind,
1126                        rule_pattern
1127                    );
1128                    None
1129                }
1130            }
1131        })
1132        .collect()
1133}
1134
1135fn compile_excluded_regexes(
1136    patterns: &[String],
1137    rule_kind: &str,
1138    rule_pattern: &str,
1139) -> Vec<Regex> {
1140    patterns
1141        .iter()
1142        .filter_map(|pattern| match Regex::new(pattern) {
1143            Ok(regex) => Some(regex),
1144            Err(err) => {
1145                tracing::warn!(
1146                    "skipping invalid excluded regex '{}' for {} '{}': {err}",
1147                    pattern,
1148                    rule_kind,
1149                    rule_pattern
1150                );
1151                None
1152            }
1153        })
1154        .collect()
1155}
1156
1157fn compile_excluded_segment_regexes(
1158    patterns: &[String],
1159    rule_kind: &str,
1160    rule_pattern: &str,
1161) -> Vec<Regex> {
1162    patterns
1163        .iter()
1164        .filter_map(|pattern| match Regex::new(pattern) {
1165            Ok(regex) => Some(regex),
1166            Err(err) => {
1167                tracing::warn!(
1168                    "skipping invalid excluded segment regex '{}' for {} '{}': {err}",
1169                    pattern,
1170                    rule_kind,
1171                    rule_pattern
1172                );
1173                None
1174            }
1175        })
1176        .collect()
1177}
1178
1179/// Whether a segment of `path` matches one of `regexes`. The path can use the
1180/// native separator: on Windows a caller can pass `src\pages\x.tsx`.
1181fn matches_segment_regex(path: &str, regexes: &[Regex]) -> bool {
1182    path.split(std::path::is_separator)
1183        .any(|segment| regexes.iter().any(|regex| regex.is_match(segment)))
1184}
1185
1186impl From<String> for PathRule {
1187    fn from(pattern: String) -> Self {
1188        Self::new(pattern)
1189    }
1190}
1191
1192impl From<&str> for PathRule {
1193    fn from(pattern: &str) -> Self {
1194        Self::new(pattern)
1195    }
1196}
1197
1198impl std::ops::Deref for PathRule {
1199    type Target = str;
1200
1201    fn deref(&self) -> &Self::Target {
1202        &self.pattern
1203    }
1204}
1205
1206impl PartialEq<&str> for PathRule {
1207    fn eq(&self, other: &&str) -> bool {
1208        self.pattern == *other
1209    }
1210}
1211
1212impl PartialEq<str> for PathRule {
1213    fn eq(&self, other: &str) -> bool {
1214        self.pattern == other
1215    }
1216}
1217
1218impl PartialEq<String> for PathRule {
1219    fn eq(&self, other: &String) -> bool {
1220        &self.pattern == other
1221    }
1222}
1223
1224/// A framework/tool plugin that contributes to dead code analysis.
1225pub trait Plugin: Send + Sync {
1226    /// Human-readable plugin name.
1227    fn name(&self) -> &'static str;
1228
1229    /// Package names that activate this plugin when found in package.json.
1230    /// Supports exact matches and prefix patterns (ending with `/`).
1231    fn enablers(&self) -> &'static [&'static str] {
1232        &[]
1233    }
1234
1235    /// Calls `is_enabled_with_deps`. The registry does not call this method, so do not override it.
1236    fn is_enabled(&self, pkg: &PackageJson, root: &Path) -> bool {
1237        let deps = pkg.all_dependency_names();
1238        self.is_enabled_with_deps(&deps, root)
1239    }
1240
1241    /// Fast variant of `is_enabled` that accepts a pre-computed deps list.
1242    /// Avoids repeated `all_dependency_names()` allocation when checking many plugins.
1243    fn is_enabled_with_deps(&self, deps: &[String], _root: &Path) -> bool {
1244        let enablers = self.enablers();
1245        if enablers.is_empty() {
1246            return false;
1247        }
1248        enablers.iter().any(|enabler| {
1249            if enabler.ends_with('/') {
1250                // Prefix match (e.g., "@storybook/" matches "@storybook/react")
1251                deps.iter().any(|d| d.starts_with(enabler))
1252            } else {
1253                deps.iter().any(|d| d == enabler)
1254            }
1255        })
1256    }
1257
1258    /// Check whether this plugin should be active with source discovery available.
1259    ///
1260    /// Most plugins only need dependency/config activation. Convention-only tools
1261    /// can override this to activate from discovered source filenames without
1262    /// forcing a separate filesystem walk.
1263    ///
1264    /// `candidate_index` is the discovery walk's in-memory listing of source +
1265    /// non-source config-candidate files (`Some` outside production mode, `None`
1266    /// in production). A plugin that activates on a non-source sentinel file
1267    /// (`manifest.json`, `.env.schema`) can consult it to avoid a per-directory
1268    /// filesystem probe; when it is `None`, the plugin falls back to the
1269    /// filesystem.
1270    fn is_enabled_with_files(
1271        &self,
1272        deps: &[String],
1273        root: &Path,
1274        _discovered_files: &[PathBuf],
1275        _candidate_index: Option<&registry::ConfigCandidateIndex>,
1276    ) -> bool {
1277        self.is_enabled_with_deps(deps, root)
1278    }
1279
1280    /// Package-script binary/package names that can activate this plugin.
1281    fn script_enablers(&self) -> &'static [&'static str] {
1282        &[]
1283    }
1284
1285    /// Check whether this plugin should be active from package.json scripts.
1286    fn is_enabled_with_scripts(
1287        &self,
1288        script_packages: &rustc_hash::FxHashSet<String>,
1289        _root: &Path,
1290    ) -> bool {
1291        let enablers = self.script_enablers();
1292        if enablers.is_empty() {
1293            return false;
1294        }
1295        enablers.iter().any(|enabler| {
1296            if enabler.ends_with('/') {
1297                script_packages
1298                    .iter()
1299                    .any(|package| package.starts_with(enabler))
1300            } else {
1301                script_packages.contains(*enabler)
1302            }
1303        })
1304    }
1305
1306    /// Default glob patterns for entry point files.
1307    fn entry_patterns(&self) -> &'static [&'static str] {
1308        &[]
1309    }
1310
1311    /// Entry point rules with optional exclusions.
1312    fn entry_pattern_rules(&self) -> Vec<PathRule> {
1313        self.entry_patterns()
1314            .iter()
1315            .map(|pattern| PathRule::from_static(pattern))
1316            .collect()
1317    }
1318
1319    /// How this plugin's entry patterns should contribute to coverage reachability.
1320    ///
1321    /// `Support` roots keep files alive for dead-code analysis but do not count
1322    /// as runtime or test reachability for static coverage gaps.
1323    fn entry_point_role(&self) -> EntryPointRole {
1324        builtin_entry_point_role(self.name())
1325    }
1326
1327    /// Glob patterns for config files this plugin can parse.
1328    fn config_patterns(&self) -> &'static [&'static str] {
1329        &[]
1330    }
1331
1332    /// Config patterns whose files do not get the `default` export credit.
1333    ///
1334    /// Under `includeEntryExports`, the `default` export of a file that one of
1335    /// [`Self::config_patterns`] matches counts as used, because the tool loads
1336    /// the config file and reads its default export. List a pattern here when
1337    /// the tool reads named exports instead, or when the pattern also matches
1338    /// ordinary source files. Each entry must be identical to an entry of
1339    /// [`Self::config_patterns`].
1340    fn config_default_export_opt_out(&self) -> &'static [&'static str] {
1341        &[]
1342    }
1343
1344    /// Tool config files and the export names that the tool reads from them.
1345    ///
1346    /// Under `includeEntryExports`, these exports of a matching file count as
1347    /// used. `"*"` credits every export. Use this for a config file that is not
1348    /// in [`Self::config_patterns`], or for a tool that reads named exports.
1349    /// Each pattern is anchored: it gets the workspace prefix but no `**/`
1350    /// prefix, so it matches only at the project or workspace package root.
1351    /// This credit never changes the output without `includeEntryExports`.
1352    fn config_file_exports(&self) -> &'static [(&'static str, &'static [&'static str])] {
1353        &[]
1354    }
1355
1356    /// Files that are always considered "used" when this plugin is active.
1357    fn always_used(&self) -> &'static [&'static str] {
1358        &[]
1359    }
1360
1361    /// Exports that are always considered used for matching file patterns.
1362    fn used_exports(&self) -> Vec<(&'static str, &'static [&'static str])> {
1363        vec![]
1364    }
1365
1366    /// Used-export rules with optional exclusions.
1367    fn used_export_rules(&self) -> Vec<UsedExportRule> {
1368        self.used_exports()
1369            .into_iter()
1370            .map(|(pattern, exports)| UsedExportRule::from_static(pattern, exports))
1371            .collect()
1372    }
1373
1374    /// Class member names the framework invokes at runtime. Matching members
1375    /// are skipped during `unused-class-members` analysis. Intended for
1376    /// interface/contract patterns where the library calls methods on consumer
1377    /// classes (e.g. ag-Grid's `agInit`, Web Components' `connectedCallback`).
1378    fn used_class_members(&self) -> &'static [&'static str] {
1379        &[]
1380    }
1381
1382    /// Heritage-scoped class member rules. Each rule applies only to classes
1383    /// matching its `extends` and/or `implements` clause. Used for frameworks
1384    /// where lifecycle members are runtime-invoked only on classes that extend
1385    /// a known base (e.g. Lit's `render`/`updated` on classes extending
1386    /// `LitElement`, native Web Components' `connectedCallback` on classes
1387    /// extending `HTMLElement`). Default: empty. Plugins override when they
1388    /// need scoping; flat names should still come from `used_class_members`.
1389    fn used_class_member_rules(&self) -> Vec<UsedClassMemberRule> {
1390        Vec::new()
1391    }
1392
1393    /// Exact package-backed framework contracts that type-aware analysis may
1394    /// verify for latent class-member candidates.
1395    fn framework_class_member_contracts(&self) -> Vec<SemanticFrameworkContract> {
1396        Vec::new()
1397    }
1398
1399    /// Glob patterns for test fixture files consumed by this framework.
1400    /// These files are implicitly used by the test runner and should not be
1401    /// flagged as unused. Unlike `always_used()`, this carries semantic intent
1402    /// for reporting purposes.
1403    fn fixture_glob_patterns(&self) -> &'static [&'static str] {
1404        &[]
1405    }
1406
1407    /// Hidden directory names that should be traversed when this plugin is active.
1408    ///
1409    /// These are consulted before normal plugin execution because source discovery
1410    /// runs first. Keep entries static and package-convention scoped.
1411    fn discovery_hidden_dirs(&self) -> &'static [&'static str] {
1412        &[]
1413    }
1414
1415    /// Dependencies that are tooling (used via CLI/config, not source imports).
1416    /// These should not be flagged as unused devDependencies.
1417    fn tooling_dependencies(&self) -> &'static [&'static str] {
1418        &[]
1419    }
1420
1421    /// Import prefixes that are virtual modules provided by this framework at build time.
1422    /// Imports matching these prefixes should not be flagged as unlisted dependencies.
1423    /// Each entry is matched as a prefix against the extracted package name
1424    /// (e.g., `"@theme/"` matches `@theme/Layout`).
1425    fn virtual_module_prefixes(&self) -> &'static [&'static str] {
1426        &[]
1427    }
1428
1429    /// Package name suffixes that are virtual modules provided by this framework
1430    /// at build time (e.g., test runner mock conventions).
1431    /// Imports matching these suffixes should not be flagged as unlisted dependencies.
1432    /// Each entry is matched as a suffix against the extracted package name
1433    /// (e.g., `"/__mocks__"` matches `@aws-sdk/__mocks__` and `some-pkg/__mocks__`).
1434    fn virtual_package_suffixes(&self) -> &'static [&'static str] {
1435        &[]
1436    }
1437
1438    /// Import suffixes for build-time generated relative imports.
1439    ///
1440    /// Unresolved relative imports whose specifier ends with one of these suffixes
1441    /// will not be flagged as unresolved. For example, SvelteKit generates
1442    /// `./$types` imports in route files, returning `"/$types"` suppresses those.
1443    fn generated_import_patterns(&self) -> &'static [&'static str] {
1444        &[]
1445    }
1446
1447    /// Import prefixes for generated type-only relative imports.
1448    ///
1449    /// Unresolved type-only imports whose specifier starts with one of these prefixes
1450    /// will not be flagged as unresolved. Runtime imports are still reported.
1451    fn generated_type_import_prefixes(&self) -> &'static [&'static str] {
1452        &[]
1453    }
1454
1455    /// Path alias mappings provided by this framework at build time.
1456    ///
1457    /// Returns a list of `(prefix, replacement_dir)` tuples. When an import starting
1458    /// with `prefix` fails to resolve, the resolver will substitute the prefix with
1459    /// `replacement_dir` (relative to the project root) and retry.
1460    ///
1461    /// Called once when plugins are activated. The project `root` is provided so
1462    /// plugins can inspect the filesystem (e.g., Nuxt checks whether `app/` exists
1463    /// to determine the `srcDir`).
1464    fn path_aliases(&self, _root: &Path) -> Vec<(&'static str, String)> {
1465        vec![]
1466    }
1467
1468    /// Directories this framework serves at a URL mount by convention, so a
1469    /// root-absolute reference in ANY HTML document in the project names a file
1470    /// inside one.
1471    ///
1472    /// Called once when plugins are activated, with the project `root`, so a
1473    /// plugin can require the directory to exist before claiming it.
1474    ///
1475    /// Distinct from the config-file mounts a tool declares from
1476    /// `resolve_config` (Storybook `staticDirs`), which stay scoped to that
1477    /// tool's own documents. A convention here describes how the whole project
1478    /// is served, so it is not scoped that way.
1479    fn static_dir_mappings(&self, _root: &Path) -> Vec<(std::path::PathBuf, String)> {
1480        vec![]
1481    }
1482
1483    /// Convention-based auto-imports provided by this framework.
1484    ///
1485    /// Returns the names this framework exposes to user code by filesystem
1486    /// convention with no explicit `import` statement (e.g. Nuxt `components/`
1487    /// resolved by `<Card001 />` template tags), each mapped to the source file
1488    /// providing the export. When a file references one of these names without an
1489    /// import, the resolver synthesizes a graph edge to `source`.
1490    ///
1491    /// Called once when plugins are activated. The project `root` is provided so
1492    /// plugins can scan the convention directories on the filesystem. The table is
1493    /// a function of which files exist on disk, so it is rebuilt every run and is
1494    /// never folded into per-file extraction caching. See issue #704.
1495    ///
1496    /// A rule with an empty `scope` is visible to the files under `root` only.
1497    /// A plugin can set `scope` itself to make a rule visible to more roots.
1498    /// After the plugin runs, a shared step links a Nuxt app and each layer
1499    /// outside it in both directions. See issue #2752.
1500    fn auto_imports(&self, _root: &Path) -> Vec<AutoImportRule> {
1501        Vec::new()
1502    }
1503
1504    /// File-scoped dependency providers contributed by this framework.
1505    fn provided_dependencies(&self) -> Vec<ProvidedDependencyRule> {
1506        Vec::new()
1507    }
1508
1509    /// Check whether parsed package.json metadata activates this plugin.
1510    fn is_enabled_with_package_json(&self, _pkg: &PackageJson, _root: &Path) -> bool {
1511        false
1512    }
1513
1514    /// Resolve parsed package.json metadata into dynamic plugin facts.
1515    fn resolve_package_json(&self, _pkg: &PackageJson, _root: &Path) -> PluginResult {
1516        PluginResult::default()
1517    }
1518
1519    /// Dependencies referenced by the package's own package.json metadata.
1520    ///
1521    /// Unlike config-derived dependencies, these credits apply only to the
1522    /// package.json that produced them.
1523    fn package_json_referenced_dependencies(
1524        &self,
1525        _pkg: &PackageJson,
1526        _root: &Path,
1527    ) -> Vec<String> {
1528        Vec::new()
1529    }
1530
1531    /// Parse a config file's AST to discover additional entries, dependencies, etc.
1532    ///
1533    /// Called for each config file matching `config_patterns()`. The source code
1534    /// and parsed AST are provided, use [`config_parser`] utilities to extract values.
1535    fn resolve_config(&self, _config_path: &Path, _source: &str, _root: &Path) -> PluginResult {
1536        PluginResult::default()
1537    }
1538
1539    /// Parse a config file with the project root known.
1540    ///
1541    /// `root` is the package root that [`Plugin::resolve_config`] receives. In
1542    /// a workspace run it is the workspace package directory. `project_root`
1543    /// is the analysis root. A plugin that reads more files from paths that
1544    /// the config names must keep each read inside `project_root`, because the
1545    /// config comes from the analyzed repository. The default ignores
1546    /// `project_root`.
1547    fn resolve_config_in_project(
1548        &self,
1549        config_path: &Path,
1550        source: &str,
1551        root: &Path,
1552        _project_root: &Path,
1553    ) -> PluginResult {
1554        self.resolve_config(config_path, source, root)
1555    }
1556
1557    /// Parse a config file that a package script passes with `--config` or
1558    /// `-c`. The script runs the tool in `root`, also for a config in a
1559    /// subdirectory. The default is [`Plugin::resolve_config_in_project`].
1560    fn resolve_script_config(
1561        &self,
1562        config_path: &Path,
1563        source: &str,
1564        root: &Path,
1565        project_root: &Path,
1566    ) -> PluginResult {
1567        self.resolve_config_in_project(config_path, source, root, project_root)
1568    }
1569
1570    /// Binaries whose `--config` / `-c` argument in a package script names a
1571    /// config file of this plugin.
1572    ///
1573    /// A script such as `vitest run --config vitest.e2e.config.ts` points the
1574    /// tool at a file that no `config_patterns()` entry matches. The plugin
1575    /// system sends that file to `resolve_config` and credits its default
1576    /// export as used.
1577    fn script_config_binaries(&self) -> &'static [&'static str] {
1578        &[]
1579    }
1580
1581    /// The key name in package.json that holds inline configuration for this tool.
1582    /// When set (e.g., `"jest"` for the `"jest"` key in package.json), the plugin
1583    /// system will extract that key's value and call `resolve_config` with its
1584    /// JSON content if no standalone config file was found.
1585    fn package_json_config_key(&self) -> Option<&'static str> {
1586        None
1587    }
1588}
1589
1590/// Macro to eliminate boilerplate in plugin implementations.
1591///
1592/// Generates a struct and a `Plugin` trait impl with the standard static methods
1593/// (`name`, `enablers`, `entry_patterns`, `config_patterns`, `always_used`, `tooling_dependencies`,
1594/// `fixture_glob_patterns`, `virtual_module_prefixes`, `virtual_package_suffixes`,
1595/// `generated_type_import_prefixes`, `used_exports`).
1596///
1597/// For plugins that need custom `resolve_config()` or `is_enabled()`, keep those as
1598/// manual `impl Plugin for ...` blocks instead of using this macro.
1599///
1600/// # Usage
1601///
1602/// ```ignore
1603/// // Simple plugin (most common):
1604/// define_plugin! {
1605///     struct VitePlugin => "vite",
1606///     enablers: ENABLERS,
1607///     entry_patterns: ENTRY_PATTERNS,
1608///     config_patterns: CONFIG_PATTERNS,
1609///     always_used: ALWAYS_USED,
1610///     tooling_dependencies: TOOLING_DEPENDENCIES,
1611/// }
1612///
1613/// // Plugin with used_exports:
1614/// define_plugin! {
1615///     struct RemixPlugin => "remix",
1616///     enablers: ENABLERS,
1617///     entry_patterns: ENTRY_PATTERNS,
1618///     always_used: ALWAYS_USED,
1619///     tooling_dependencies: TOOLING_DEPENDENCIES,
1620///     used_exports: [("app/routes/**/*.{ts,tsx}", ROUTE_EXPORTS)],
1621/// }
1622///
1623/// // Plugin with imports-only resolve_config (extracts imports from config as deps):
1624/// define_plugin! {
1625///     struct CypressPlugin => "cypress",
1626///     enablers: ENABLERS,
1627///     entry_patterns: ENTRY_PATTERNS,
1628///     config_patterns: CONFIG_PATTERNS,
1629///     always_used: ALWAYS_USED,
1630///     tooling_dependencies: TOOLING_DEPENDENCIES,
1631///     resolve_config: imports_only,
1632/// }
1633///
1634/// // Plugin with custom resolve_config body:
1635/// define_plugin! {
1636///     struct RollupPlugin => "rollup",
1637///     enablers: ENABLERS,
1638///     config_patterns: CONFIG_PATTERNS,
1639///     always_used: ALWAYS_USED,
1640///     tooling_dependencies: TOOLING_DEPENDENCIES,
1641///     resolve_config(config_path, source, _root) {
1642///         let mut result = PluginResult::default();
1643///         // custom config parsing...
1644///         result
1645///     }
1646/// }
1647/// ```
1648///
1649/// All fields except `struct` and `enablers` are optional and default to `&[]` / `vec![]`.
1650macro_rules! define_plugin {
1651    (
1652        struct $name:ident => $display:expr,
1653        enablers: $enablers:expr
1654        $(, entry_patterns: $entry:expr)?
1655        $(, config_patterns: $config:expr)?
1656        $(, config_default_export_opt_out: $config_opt_out:expr)?
1657        $(, config_file_exports: $config_exports:expr)?
1658        $(, always_used: $always:expr)?
1659        $(, tooling_dependencies: $tooling:expr)?
1660        $(, fixture_glob_patterns: $fixtures:expr)?
1661        $(, discovery_hidden_dirs: $hidden_dirs:expr)?
1662        $(, virtual_module_prefixes: $virtual:expr)?
1663        $(, virtual_package_suffixes: $virtual_suffixes:expr)?
1664        $(, generated_type_import_prefixes: $generated_type_prefixes:expr)?
1665        $(, provided_dependencies: $provided_dependencies:expr)?
1666        $(, used_exports: [$( ($pat:expr, $exports:expr) ),* $(,)?])?
1667        , resolve_config: imports_only
1668        $(,)?
1669    ) => {
1670        pub struct $name;
1671
1672        impl Plugin for $name {
1673            fn name(&self) -> &'static str {
1674                $display
1675            }
1676
1677            fn enablers(&self) -> &'static [&'static str] {
1678                $enablers
1679            }
1680
1681            $( fn entry_patterns(&self) -> &'static [&'static str] { $entry } )?
1682            $( fn config_patterns(&self) -> &'static [&'static str] { $config } )?
1683            $( fn config_default_export_opt_out(&self) -> &'static [&'static str] { $config_opt_out } )?
1684            $( fn config_file_exports(&self) -> &'static [(&'static str, &'static [&'static str])] { $config_exports } )?
1685            $( fn always_used(&self) -> &'static [&'static str] { $always } )?
1686            $( fn tooling_dependencies(&self) -> &'static [&'static str] { $tooling } )?
1687            $( fn fixture_glob_patterns(&self) -> &'static [&'static str] { $fixtures } )?
1688            $( fn discovery_hidden_dirs(&self) -> &'static [&'static str] { $hidden_dirs } )?
1689            $( fn virtual_module_prefixes(&self) -> &'static [&'static str] { $virtual } )?
1690            $( fn virtual_package_suffixes(&self) -> &'static [&'static str] { $virtual_suffixes } )?
1691            $( fn generated_type_import_prefixes(&self) -> &'static [&'static str] { $generated_type_prefixes } )?
1692            $( fn provided_dependencies(&self) -> Vec<ProvidedDependencyRule> { $provided_dependencies } )?
1693
1694            $(
1695                fn used_exports(&self) -> Vec<(&'static str, &'static [&'static str])> {
1696                    vec![$( ($pat, $exports) ),*]
1697                }
1698            )?
1699
1700            fn resolve_config(
1701                &self,
1702                config_path: &std::path::Path,
1703                source: &str,
1704                _root: &std::path::Path,
1705            ) -> PluginResult {
1706                let mut result = PluginResult::default();
1707                crate::plugins::add_import_referenced_dependencies(
1708                    &mut result,
1709                    source,
1710                    config_path,
1711                );
1712                result
1713            }
1714        }
1715    };
1716
1717    (
1718        struct $name:ident => $display:expr,
1719        enablers: $enablers:expr
1720        $(, entry_patterns: $entry:expr)?
1721        $(, config_patterns: $config:expr)?
1722        $(, config_default_export_opt_out: $config_opt_out:expr)?
1723        $(, config_file_exports: $config_exports:expr)?
1724        $(, always_used: $always:expr)?
1725        $(, tooling_dependencies: $tooling:expr)?
1726        $(, fixture_glob_patterns: $fixtures:expr)?
1727        $(, discovery_hidden_dirs: $hidden_dirs:expr)?
1728        $(, virtual_module_prefixes: $virtual:expr)?
1729        $(, virtual_package_suffixes: $virtual_suffixes:expr)?
1730        $(, generated_type_import_prefixes: $generated_type_prefixes:expr)?
1731        $(, provided_dependencies: $provided_dependencies:expr)?
1732        $(, package_json_config_key: $pkg_key:expr)?
1733        $(, script_config_binaries: $script_binaries:expr)?
1734        $(, used_exports: [$( ($pat:expr, $exports:expr) ),* $(,)?])?
1735        , resolve_config($cp:ident, $src:ident, $root:ident) $body:block
1736        $(, resolve_config_in_project($pcp:ident, $psrc:ident, $proot:ident, $pproj:ident) $pbody:block)?
1737        $(,)?
1738    ) => {
1739        pub struct $name;
1740
1741        impl Plugin for $name {
1742            fn name(&self) -> &'static str {
1743                $display
1744            }
1745
1746            fn enablers(&self) -> &'static [&'static str] {
1747                $enablers
1748            }
1749
1750            $( fn entry_patterns(&self) -> &'static [&'static str] { $entry } )?
1751            $( fn config_patterns(&self) -> &'static [&'static str] { $config } )?
1752            $( fn config_default_export_opt_out(&self) -> &'static [&'static str] { $config_opt_out } )?
1753            $( fn config_file_exports(&self) -> &'static [(&'static str, &'static [&'static str])] { $config_exports } )?
1754            $( fn always_used(&self) -> &'static [&'static str] { $always } )?
1755            $( fn tooling_dependencies(&self) -> &'static [&'static str] { $tooling } )?
1756            $( fn fixture_glob_patterns(&self) -> &'static [&'static str] { $fixtures } )?
1757            $( fn discovery_hidden_dirs(&self) -> &'static [&'static str] { $hidden_dirs } )?
1758            $( fn virtual_module_prefixes(&self) -> &'static [&'static str] { $virtual } )?
1759            $( fn virtual_package_suffixes(&self) -> &'static [&'static str] { $virtual_suffixes } )?
1760            $( fn generated_type_import_prefixes(&self) -> &'static [&'static str] { $generated_type_prefixes } )?
1761            $( fn provided_dependencies(&self) -> Vec<ProvidedDependencyRule> { $provided_dependencies } )?
1762
1763            $(
1764                fn package_json_config_key(&self) -> Option<&'static str> {
1765                    Some($pkg_key)
1766                }
1767            )?
1768
1769            $(
1770                fn used_exports(&self) -> Vec<(&'static str, &'static [&'static str])> {
1771                    vec![$( ($pat, $exports) ),*]
1772                }
1773            )?
1774
1775            $( fn script_config_binaries(&self) -> &'static [&'static str] { $script_binaries } )?
1776
1777            fn resolve_config(
1778                &self,
1779                $cp: &std::path::Path,
1780                $src: &str,
1781                $root: &std::path::Path,
1782            ) -> PluginResult
1783            $body
1784
1785            $(
1786                fn resolve_config_in_project(
1787                    &self,
1788                    $pcp: &std::path::Path,
1789                    $psrc: &str,
1790                    $proot: &std::path::Path,
1791                    $pproj: &std::path::Path,
1792                ) -> PluginResult
1793                $pbody
1794            )?
1795        }
1796    };
1797
1798    (
1799        struct $name:ident => $display:expr,
1800        enablers: $enablers:expr
1801        $(, entry_patterns: $entry:expr)?
1802        $(, config_patterns: $config:expr)?
1803        $(, config_default_export_opt_out: $config_opt_out:expr)?
1804        $(, config_file_exports: $config_exports:expr)?
1805        $(, always_used: $always:expr)?
1806        $(, tooling_dependencies: $tooling:expr)?
1807        $(, fixture_glob_patterns: $fixtures:expr)?
1808        $(, discovery_hidden_dirs: $hidden_dirs:expr)?
1809        $(, virtual_module_prefixes: $virtual:expr)?
1810        $(, virtual_package_suffixes: $virtual_suffixes:expr)?
1811        $(, generated_type_import_prefixes: $generated_type_prefixes:expr)?
1812        $(, provided_dependencies: $provided_dependencies:expr)?
1813        $(, package_json_config_key: $pkg_key:expr)?
1814        $(, used_exports: [$( ($pat:expr, $exports:expr) ),* $(,)?])?
1815        $(,)?
1816    ) => {
1817        pub struct $name;
1818
1819        impl Plugin for $name {
1820            fn name(&self) -> &'static str {
1821                $display
1822            }
1823
1824            fn enablers(&self) -> &'static [&'static str] {
1825                $enablers
1826            }
1827
1828            $( fn entry_patterns(&self) -> &'static [&'static str] { $entry } )?
1829            $( fn config_patterns(&self) -> &'static [&'static str] { $config } )?
1830            $( fn config_default_export_opt_out(&self) -> &'static [&'static str] { $config_opt_out } )?
1831            $( fn config_file_exports(&self) -> &'static [(&'static str, &'static [&'static str])] { $config_exports } )?
1832            $( fn always_used(&self) -> &'static [&'static str] { $always } )?
1833            $( fn tooling_dependencies(&self) -> &'static [&'static str] { $tooling } )?
1834            $( fn fixture_glob_patterns(&self) -> &'static [&'static str] { $fixtures } )?
1835            $( fn discovery_hidden_dirs(&self) -> &'static [&'static str] { $hidden_dirs } )?
1836            $( fn virtual_module_prefixes(&self) -> &'static [&'static str] { $virtual } )?
1837            $( fn virtual_package_suffixes(&self) -> &'static [&'static str] { $virtual_suffixes } )?
1838            $( fn generated_type_import_prefixes(&self) -> &'static [&'static str] { $generated_type_prefixes } )?
1839            $( fn provided_dependencies(&self) -> Vec<ProvidedDependencyRule> { $provided_dependencies } )?
1840
1841            $(
1842                fn package_json_config_key(&self) -> Option<&'static str> {
1843                    Some($pkg_key)
1844                }
1845            )?
1846
1847            $(
1848                fn used_exports(&self) -> Vec<(&'static str, &'static [&'static str])> {
1849                    vec![$( ($pat, $exports) ),*]
1850                }
1851            )?
1852        }
1853    };
1854}
1855
1856mod config_dependencies;
1857pub mod config_parser;
1858mod config_value_credits;
1859mod flue;
1860mod jasmine;
1861mod manifest;
1862pub mod manifest_entries;
1863mod mise;
1864mod osls;
1865mod project_glob;
1866mod railway;
1867pub mod registry;
1868mod rstest;
1869mod serverless_framework;
1870mod textlint;
1871mod tooling;
1872pub(crate) mod trace_provenance;
1873mod used_export_names;
1874mod used_export_rule;
1875
1876pub use config_dependencies::RequiredDependency;
1877use config_dependencies::add_import_referenced_dependencies;
1878pub(crate) use module_federation::runtime_remotes;
1879pub use registry::{
1880    AggregatedPluginResult, PluginRegistry, PluginToolingDependencies, PluginToolingEvidence,
1881};
1882pub use tooling::types_package_target;
1883pub(crate) use tooling::{
1884    cli_tooling_config_patterns, is_ambient_types_package, is_known_tooling_dependency,
1885};
1886pub use trace_provenance::ExportCredits;
1887pub use used_export_names::UsedExportNames;
1888pub(crate) use used_export_rule::{ConfigExportCredit, is_export_ignored};
1889pub use used_export_rule::{PluginUsedExportRule, UsedExportRule};
1890
1891/// Credit the optional peer dependencies a test environment loads at runtime.
1892///
1893/// The rules are data: see the `test-environment-optional-peer` rows in
1894/// `crates/core/data/config_value_credits.toml`. `jsdom` requires its optional
1895/// peer `canvas` lazily when it is installed, so a project installing it for
1896/// real canvas support has no import of it anywhere and would see the
1897/// dependency reported as unused (issue #2005). Environments without such a
1898/// peer, like `happy-dom`, have no row.
1899///
1900/// Only names already declared in the manifest can be credited, so this never
1901/// invents an unlisted dependency.
1902fn credit_environment_optional_peers(environment: &str, result: &mut PluginResult) {
1903    credit_config_value(
1904        config_value_credits::CreditSurface::TestEnvironmentOptionalPeer,
1905        canonical_test_environment(environment),
1906        result,
1907    );
1908}
1909
1910/// Record the catalogue credits for a config value, if any.
1911///
1912/// Returns whether a rule matched, which callers use when the credited packages
1913/// replace the dependencies derived from the value itself.
1914fn credit_config_value(
1915    surface: config_value_credits::CreditSurface,
1916    value: &str,
1917    result: &mut PluginResult,
1918) -> bool {
1919    let Some(packages) = config_value_credits::credited_packages(surface, value) else {
1920        return false;
1921    };
1922    result
1923        .referenced_dependencies
1924        .extend(packages.iter().cloned());
1925    true
1926}
1927
1928/// Strip the runner prefix from a test environment specifier.
1929///
1930/// Both runners accept the bare name and the package it resolves to, so
1931/// `testEnvironment: "jest-environment-jsdom"` and `environment: "jsdom"` select
1932/// the same environment. A match on the short name only missed the fully
1933/// qualified form that the Jest docs use, so that form lost its credit.
1934fn canonical_test_environment(environment: &str) -> &str {
1935    environment
1936        .strip_prefix("jest-environment-")
1937        .or_else(|| environment.strip_prefix("vitest-environment-"))
1938        .unwrap_or(environment)
1939}
1940
1941mod adonis;
1942mod ag_ui;
1943mod alchemy;
1944mod alias_replacement;
1945mod angular;
1946mod astro;
1947mod ava;
1948mod babel;
1949mod biome;
1950mod browser_extension;
1951mod bun;
1952mod c8;
1953mod capacitor;
1954mod changesets;
1955mod commit_and_tag_version;
1956mod commitizen;
1957mod commitlint;
1958mod content_collections;
1959mod contentlayer;
1960mod convex;
1961mod cspell;
1962mod cucumber;
1963mod cypress;
1964mod danger;
1965mod deno;
1966mod dependency_cruiser;
1967mod docusaurus;
1968mod dotenv;
1969mod drizzle;
1970mod dumi;
1971mod egg;
1972mod electron;
1973mod ember;
1974mod entry_point_roles;
1975mod eslint;
1976mod eve;
1977mod expo;
1978mod expo_router;
1979mod firebase;
1980mod fumadocs;
1981mod gatsby;
1982mod github_action;
1983mod graphql_codegen;
1984mod graphql_config;
1985mod gulp;
1986mod hardhat;
1987mod husky;
1988mod i18next;
1989mod ionic;
1990mod jest;
1991mod k6;
1992mod karma;
1993mod kibana;
1994mod knex;
1995mod kysely;
1996mod lefthook;
1997mod lexical;
1998mod lint_staged;
1999mod lit;
2000mod markdownlint;
2001mod mintlify;
2002mod mocha;
2003mod module_federation;
2004mod msw;
2005mod n8n;
2006mod napi_rs;
2007mod nest_commander;
2008mod nestjs;
2009mod nestjs_trpc;
2010mod next_intl;
2011mod nextjs;
2012mod nitro;
2013mod nodemon;
2014pub(crate) mod nuxt;
2015mod nx;
2016mod nyc;
2017mod obsidian;
2018mod openapi_ts;
2019mod opencode;
2020mod opennext_cloudflare;
2021mod opentelemetry;
2022mod oxfmt;
2023mod oxlint;
2024mod pandacss;
2025mod parcel;
2026mod pinia;
2027mod pkg_utils;
2028mod playwright;
2029mod plop;
2030mod pm2;
2031mod pnpm;
2032mod postcss;
2033mod prettier;
2034mod prisma;
2035mod qwik;
2036mod react_compiler;
2037mod react_native;
2038mod react_router;
2039mod redwoodsdk;
2040mod relay;
2041mod release_it;
2042mod remark;
2043mod remix;
2044mod rolldown;
2045mod rollup;
2046mod rsbuild;
2047mod rspack;
2048mod rspress;
2049mod sanity;
2050mod semantic_release;
2051mod sentry;
2052mod simple_git_hooks;
2053mod size_limit;
2054mod solid_start;
2055mod storybook;
2056mod stryker;
2057mod stylelint;
2058mod supabase;
2059mod sveltekit;
2060mod svgo;
2061mod svgr;
2062mod swc;
2063mod syncpack;
2064mod tailwind;
2065mod tanstack_router;
2066mod tap;
2067mod test_alias;
2068#[cfg(test)]
2069mod tests;
2070mod tsd;
2071mod tsdown;
2072mod tsup;
2073mod turborepo;
2074mod typedoc;
2075mod typeorm;
2076mod typescript;
2077mod typescript_content_mapper;
2078mod unocss;
2079pub(crate) mod unplugin_icons;
2080mod varlock;
2081mod velite;
2082mod vercel;
2083mod vite;
2084mod vite_plugin_pages;
2085pub(crate) mod vite_plus;
2086mod vitepress;
2087mod vitest;
2088mod vscode;
2089mod waku;
2090mod webdriverio;
2091mod webpack;
2092mod wrangler;
2093mod wuchale;
2094mod wxt;