Skip to main content

fallow_types/
trace.rs

1//! Shared trace output contracts for analysis and integration surfaces.
2
3use std::path::{Path, PathBuf};
4
5use rustc_hash::{FxHashMap, FxHashSet};
6use serde::Serialize;
7
8use crate::cache_rejection::CacheRejection;
9use crate::duplicates::{CloneInstance, RefactoringSuggestion};
10use crate::semantic::SemanticNamespace;
11use crate::serde_path;
12use crate::trace_chain::StarExportAmbiguity;
13
14/// Result of tracing an export: why it is considered used or unused.
15#[derive(Debug, Serialize)]
16#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
17pub struct ExportTrace {
18    /// The file containing the export.
19    #[serde(serialize_with = "serde_path::serialize")]
20    pub file: PathBuf,
21    /// The export name being traced.
22    pub export_name: String,
23    /// Namespace whose references are listed for the traced export. The
24    /// preferred lane wins whenever it carries a reference: `value` for a
25    /// value export, `type` for a type-only one. When the preferred lane
26    /// carries none and the other lane resolves to the same declaration, the
27    /// other lane's references are listed and this field names it, so a value
28    /// export whose only credit is a bound `import type` reports `type` with
29    /// `is_used: true`. `is_used` and `direct_references` follow the listed
30    /// lane only, and only reachable reference sources can credit it. Legal
31    /// declaration merges share one declaration group across lanes, including
32    /// an `interface` next to a same-name `class` and a `class` next to a
33    /// same-name `namespace`, so references to either lane credit the merged
34    /// declaration. Distinct same-name declarations outside a merge remain
35    /// separate and keep the preferred lane. `semantic.target.namespace`
36    /// names the lane the declaration itself occupies and can therefore differ
37    /// from this field. Producers always emit the field; the schema permits
38    /// omission by payloads created before namespaces were exposed.
39    #[cfg_attr(feature = "schema", schemars(default))]
40    pub namespace: crate::semantic::SemanticNamespace,
41    /// Whether the file is reachable from an entry point.
42    pub file_reachable: bool,
43    /// Whether the file is an entry point.
44    pub is_entry_point: bool,
45    /// Whether the export is considered used.
46    pub is_used: bool,
47    /// Files that reference this export directly.
48    pub direct_references: Vec<ExportReference>,
49    /// Reachable direct references grouped by namespace. This is additive to
50    /// `namespace` and `direct_references`, whose winning-lane meaning remains
51    /// unchanged for backwards compatibility.
52    #[serde(default, skip_serializing_if = "Vec::is_empty")]
53    pub direct_references_by_namespace: Vec<NamespacedExportReferences>,
54    /// A star-export collision that makes the traced name ambiguous. When
55    /// present, `is_used: false` is an abstention rather than an unused-code
56    /// verdict.
57    #[serde(default, skip_serializing_if = "Option::is_none")]
58    pub star_export_ambiguity: Option<StarExportAmbiguity>,
59    /// Re-export chains that pass through this export.
60    pub re_export_chains: Vec<ReExportChain>,
61    /// The framework plugin rules that mark this export as used. The
62    /// framework calls or reads the export, so no import is necessary. A
63    /// credit sets `is_used` when the file is reachable. Absent when no
64    /// plugin credits the export.
65    #[serde(default, skip_serializing_if = "Vec::is_empty")]
66    pub plugin_credits: Vec<PluginExportCredit>,
67    /// The JSDoc visibility tag that keeps an export with no consumer out
68    /// of `unused-export`: `public`, `internal`, `alpha` or `beta`. The
69    /// `keepExportTags` config key selects the tags that do this. Absent
70    /// when the export is used, or when no kept tag is on it.
71    #[serde(default, skip_serializing_if = "Option::is_none")]
72    pub kept_by_tag: Option<String>,
73    /// Human-readable reason summary.
74    pub reason: String,
75    /// Exact checker-backed references when type-aware tracing is enabled.
76    #[serde(default, skip_serializing_if = "Option::is_none")]
77    pub semantic: Option<crate::semantic::SemanticSymbolTrace>,
78}
79
80/// Result of tracing a class / enum / store member: the `--trace FILE:NAME`
81/// fallback when `NAME` is not a top-level export but a member declared on one
82/// (issue #1744). The trace runs on the module graph only, so it reports the
83/// owning export's reachability and usage (the gating precondition for
84/// member-level crediting) plus a pointer to the right `--unused-*-members`
85/// command, rather than per-member crediting provenance.
86#[derive(Debug, Serialize)]
87#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
88pub struct ClassMemberTrace {
89    /// The file containing the member.
90    #[serde(serialize_with = "serde_path::serialize")]
91    pub file: PathBuf,
92    /// The member name being traced.
93    pub member_name: String,
94    /// The member kind: `class-method`, `class-property`, `enum-member`,
95    /// `store-member`, or `namespace-member`.
96    pub member_kind: String,
97    /// The export that declares this member (the class / enum / store name).
98    pub owner_export: String,
99    /// Namespace whose references credit the owning export, mirroring
100    /// [`ExportTrace::namespace`] for the export this member is declared on.
101    /// `owner_is_used` and `owner_direct_references` describe that lane, so a
102    /// member of a value export credited only by a bound `import type` reports
103    /// `type` here. `semantic.target.namespace` names the lane the checker
104    /// proof covers and can therefore differ. Producers always emit the field;
105    /// the schema permits omission by payloads created before the owner
106    /// namespace was exposed.
107    #[cfg_attr(feature = "schema", schemars(default))]
108    pub owner_namespace: crate::semantic::SemanticNamespace,
109    /// Whether the owning export is considered used.
110    pub owner_is_used: bool,
111    /// Whether the file is reachable from an entry point.
112    pub owner_file_reachable: bool,
113    /// Whether the file is an entry point.
114    pub owner_is_entry_point: bool,
115    /// Files that reference the owning export directly. The search visibility
116    /// fields on each entry check the owner export name, not the member name.
117    pub owner_direct_references: Vec<ExportReference>,
118    /// Re-export chains through which the owning export is reachable. Populated
119    /// so a machine consumer can tell "used via a barrel" (empty direct refs but
120    /// non-empty chains) from "genuinely unreferenced".
121    pub owner_re_export_chains: Vec<ReExportChain>,
122    /// Human-readable reason summary plus the follow-up command to inspect the
123    /// member finding.
124    pub reason: String,
125    /// Exact checker-backed member references when type-aware tracing is enabled.
126    #[serde(default, skip_serializing_if = "Option::is_none")]
127    pub semantic: Option<crate::semantic::SemanticSymbolTrace>,
128}
129
130/// A direct reference to an export.
131#[derive(Debug, Clone, Serialize)]
132#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
133pub struct ExportReference {
134    /// File that contains the reference.
135    #[serde(serialize_with = "serde_path::serialize")]
136    pub from_file: PathBuf,
137    /// Reference kind, such as named import, default import, or re-export.
138    pub kind: String,
139    /// 1-based line of the import statement in `from_file`. Absent when the
140    /// graph holds no source position for the reference or the file cannot be
141    /// read.
142    #[serde(default, skip_serializing_if = "Option::is_none")]
143    pub line: Option<u32>,
144    /// Whether a whole-word text search for the export name finds this
145    /// consumer. Absent when no check applies, for example when the consumer
146    /// source cannot be read.
147    #[serde(default, skip_serializing_if = "Option::is_none")]
148    pub search_visibility: Option<SearchVisibility>,
149    /// Why a text search does not find the uses in this consumer. With
150    /// `search_visibility` `found`, only `pass-through` occurs: the consumer
151    /// forwards the export and does not use it.
152    #[serde(default, skip_serializing_if = "Option::is_none")]
153    pub reason: Option<SearchGapReason>,
154    /// The name to search for in this consumer instead of the export name.
155    /// Absent when the export name finds the uses or no single name does.
156    #[serde(default, skip_serializing_if = "Option::is_none")]
157    pub search_as: Option<String>,
158}
159
160impl ExportReference {
161    /// A reference with no source position and no search check.
162    #[must_use]
163    pub const fn new(from_file: PathBuf, kind: String) -> Self {
164        Self {
165            from_file,
166            kind,
167            line: None,
168            search_visibility: None,
169            reason: None,
170            search_as: None,
171        }
172    }
173}
174
175/// Whether a whole-word text search for an export name finds a consumer that
176/// the module graph resolves. The levels sort from best to worst.
177#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
178#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
179#[serde(rename_all = "kebab-case")]
180pub enum SearchVisibility {
181    /// The consumer source contains the export name, and the consumer uses it
182    /// under that name.
183    Found,
184    /// The consumer source contains the export name, but the consumer uses
185    /// the export under another local name.
186    Renamed,
187    /// The consumer source does not contain the export name.
188    Missed,
189}
190
191/// Why a text search for an export name does not find the uses in a consumer,
192/// or why a consumer is not a search target (`pass-through`).
193#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
194#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
195#[serde(rename_all = "kebab-case")]
196pub enum SearchGapReason {
197    /// The consumer imports the export under another local name
198    /// (`import { foo as bar }`).
199    ImportAlias,
200    /// The consumer imports a default export under another local name.
201    DefaultImport,
202    /// A barrel re-exports the export under another name, and the consumer
203    /// imports that name.
204    ReExportAlias,
205    /// The consumer imports the whole module namespace and does not name the
206    /// export.
207    NamespaceUse,
208    /// The consumer loads the module with a dynamic `import()` and does not
209    /// name the export.
210    DynamicImport,
211    /// The consumer only forwards the export and does not use it: a barrel
212    /// (`export * from`, `export { foo } from`), or a file that imports the
213    /// export and only exports it again (`import { foo } from`, then a
214    /// top-level `export { foo }`). A change of the export
215    /// needs no edit there, and the files that import through it are checked
216    /// on their own. Occurs with `found`.
217    PassThrough,
218}
219
220/// Direct references that credit one namespace of an export binding.
221#[derive(Debug, Serialize)]
222#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
223pub struct NamespacedExportReferences {
224    /// Credited namespace.
225    pub namespace: SemanticNamespace,
226    /// Number of reachable references in this namespace.
227    pub reference_count: usize,
228    /// Reachable references in deterministic graph order.
229    pub references: Vec<ExportReference>,
230}
231
232/// A re-export chain showing how an export is propagated.
233#[derive(Debug, Serialize)]
234#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
235pub struct ReExportChain {
236    /// The barrel file that re-exports this symbol.
237    #[serde(serialize_with = "serde_path::serialize")]
238    pub barrel_file: PathBuf,
239    /// The name it is re-exported as.
240    pub exported_as: String,
241    /// Number of references on the barrel's re-exported symbol.
242    pub reference_count: usize,
243}
244
245/// Result of tracing all edges for a file.
246#[derive(Debug, Default, Serialize)]
247#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
248pub struct FileTrace {
249    /// The traced file.
250    #[serde(serialize_with = "serde_path::serialize")]
251    pub file: PathBuf,
252    /// Whether this file is reachable from entry points.
253    pub is_reachable: bool,
254    /// Whether this file is an entry point.
255    pub is_entry_point: bool,
256    /// Exports declared by this file.
257    pub exports: Vec<TracedExport>,
258    /// Files that this file imports from.
259    #[serde(serialize_with = "serde_path::serialize_vec")]
260    pub imports_from: Vec<PathBuf>,
261    /// Files that import from this file.
262    #[serde(serialize_with = "serde_path::serialize_vec")]
263    pub imported_by: Vec<PathBuf>,
264    /// Re-exports declared by this file.
265    pub re_exports: Vec<TracedReExport>,
266    /// The package.json script key that makes this file an entry point, e.g.
267    /// `build`. Absent when no script makes the file an entry point
268    /// (issue #4175).
269    #[serde(default, skip_serializing_if = "Option::is_none")]
270    pub entry_script: Option<String>,
271    /// The configs that make this file an entry point through Module
272    /// Federation `exposes`, one per config. Absent when no Federation config
273    /// exposes the file (issue #2796).
274    #[serde(default, skip_serializing_if = "Vec::is_empty")]
275    pub sources: Vec<TraceSource>,
276}
277
278/// Which configs name which files and which dependency names, collected by one
279/// analysis for the trace output.
280///
281/// It holds plain data, so a trace looks a file up without the rules that
282/// produced it.
283#[derive(Debug, Clone, Default, PartialEq, Eq)]
284pub struct TraceProvenance {
285    /// Root-relative file path and the config that names it.
286    files: Vec<(PathBuf, TraceSource)>,
287    /// Dependency name and the config that names it.
288    dependencies: Vec<(String, TraceSource)>,
289    /// Dependency name and why the unused devDependency check credits it as
290    /// tooling.
291    tooling_credits: Vec<(String, ToolingCredit)>,
292    /// Root-relative file path and an export name that a framework plugin
293    /// reads as configuration, such as the Next.js `dynamic` segment option.
294    config_exports: FxHashMap<PathBuf, FxHashSet<String>>,
295    /// Root-relative file path, export name, and the plugin rule that marks
296    /// the export as used.
297    export_credits: FxHashMap<PathBuf, FxHashMap<String, Vec<PluginExportCredit>>>,
298    /// Root-relative file path of a script entry point and the package.json
299    /// script key that runs the file.
300    entry_scripts: FxHashMap<PathBuf, String>,
301    /// The packages that start the peer-dependency closure in addition to the
302    /// imported packages.
303    peer_seeds: PeerClosureSeeds,
304}
305
306/// The packages that start a peer-dependency closure although no file
307/// imports them: packages that a script runs and packages that a plugin
308/// credits.
309///
310/// The unused-dependency check and the dependency trace read the same seeds,
311/// so the trace names the same hosts that give peer credit.
312#[derive(Debug, Clone, Default, PartialEq, Eq)]
313pub struct PeerClosureSeeds {
314    /// Seeds for every closure.
315    shared: FxHashSet<String>,
316    /// Seeds for the closure of one manifest, keyed by the absolute
317    /// `package.json` path.
318    by_manifest: FxHashMap<PathBuf, FxHashSet<String>>,
319}
320
321impl PeerClosureSeeds {
322    /// Seeds that every closure reads.
323    #[must_use]
324    pub fn from_shared(names: impl IntoIterator<Item = String>) -> Self {
325        Self {
326            shared: names.into_iter().collect(),
327            by_manifest: FxHashMap::default(),
328        }
329    }
330
331    /// Record a seed for the closure of the manifest at `manifest`, an
332    /// absolute `package.json` path.
333    pub fn push_manifest_seed(&mut self, manifest: PathBuf, name: String) {
334        self.by_manifest.entry(manifest).or_default().insert(name);
335    }
336
337    /// The seeds of the closure for the manifest at `manifest`: the shared
338    /// seeds and the seeds of that manifest.
339    pub fn for_manifest<'a>(&'a self, manifest: &Path) -> impl Iterator<Item = &'a str> {
340        self.shared
341            .iter()
342            .chain(self.by_manifest.get(manifest).into_iter().flatten())
343            .map(String::as_str)
344    }
345}
346
347impl TraceProvenance {
348    /// Record that a framework plugin reads the export `name` of the
349    /// root-relative `file` as configuration.
350    pub fn push_config_export(&mut self, file: PathBuf, name: String) {
351        self.config_exports.entry(file).or_default().insert(name);
352    }
353
354    /// Whether a framework plugin reads the export `name` of the
355    /// root-relative `file` as configuration.
356    #[must_use]
357    pub fn is_config_export(&self, file: &Path, name: &str) -> bool {
358        self.config_exports
359            .get(file)
360            .is_some_and(|names| names.contains(name))
361    }
362
363    /// Record the plugin rules that mark exports of the root-relative `file`
364    /// as used, as pairs of an export name and a credit.
365    pub fn push_export_credits(
366        &mut self,
367        file: PathBuf,
368        credits: impl IntoIterator<Item = (String, PluginExportCredit)>,
369    ) {
370        let by_name = self.export_credits.entry(file).or_default();
371        for (name, credit) in credits {
372            let known = by_name.entry(name).or_default();
373            if !known.contains(&credit) {
374                known.push(credit);
375            }
376        }
377    }
378
379    /// The plugin rules that mark the export `name` of the root-relative
380    /// `file` as used.
381    #[must_use]
382    pub fn export_credits(&self, file: &Path, name: &str) -> Vec<PluginExportCredit> {
383        self.export_credits
384            .get(file)
385            .and_then(|by_name| by_name.get(name))
386            .cloned()
387            .unwrap_or_default()
388    }
389
390    /// Record that `source` names the root-relative `file`.
391    pub fn push_file(&mut self, file: PathBuf, source: TraceSource) {
392        if !self
393            .files
394            .iter()
395            .any(|(known, known_source)| *known == file && *known_source == source)
396        {
397            self.files.push((file, source));
398        }
399    }
400
401    /// Record that `source` names the dependency `name`.
402    pub fn push_dependency(&mut self, name: String, source: TraceSource) {
403        if !self
404            .dependencies
405            .iter()
406            .any(|(known, known_source)| *known == name && *known_source == source)
407        {
408            self.dependencies.push((name, source));
409        }
410    }
411
412    /// The configs that name `file`, a root-relative path.
413    #[must_use]
414    pub fn file_sources(&self, file: &std::path::Path) -> Vec<TraceSource> {
415        self.files
416            .iter()
417            .filter(|(known, _)| known == file)
418            .map(|(_, source)| source.clone())
419            .collect()
420    }
421
422    /// The configs that name the dependency `name`.
423    #[must_use]
424    pub fn dependency_sources(&self, name: &str) -> Vec<TraceSource> {
425        self.dependencies
426            .iter()
427            .filter(|(known, _)| known == name)
428            .map(|(_, source)| source.clone())
429            .collect()
430    }
431
432    /// Record the package.json script of each script entry point in
433    /// `entries`, by path relative to `root`.
434    pub fn push_entry_scripts(&mut self, root: &Path, entries: &[crate::discover::EntryPoint]) {
435        for entry in entries {
436            if let Some(script) = entry.source.script() {
437                let file = entry.path.strip_prefix(root).unwrap_or(&entry.path);
438                self.entry_scripts
439                    .entry(file.to_path_buf())
440                    .or_insert_with(|| script.to_string());
441            }
442        }
443    }
444
445    /// The package.json script key that makes the root-relative `file` an
446    /// entry point, if a script does.
447    #[must_use]
448    pub fn entry_script(&self, file: &Path) -> Option<&str> {
449        self.entry_scripts.get(file).map(String::as_str)
450    }
451
452    /// Record why the dependency `name` is credited as tooling. The first
453    /// credit recorded for a name wins.
454    pub fn push_tooling_credit(&mut self, name: String, credit: ToolingCredit) {
455        if !self.tooling_credits.iter().any(|(known, _)| *known == name) {
456            self.tooling_credits.push((name, credit));
457        }
458    }
459
460    /// Why the dependency `name` is credited as tooling, if it is.
461    #[must_use]
462    pub fn tooling_credit(&self, name: &str) -> Option<ToolingCredit> {
463        self.tooling_credits
464            .iter()
465            .find(|(known, _)| known == name)
466            .map(|(_, credit)| credit.clone())
467    }
468
469    /// Set the packages that start the peer-dependency closure in addition to
470    /// the imported packages.
471    #[must_use]
472    pub fn with_peer_seeds(mut self, seeds: PeerClosureSeeds) -> Self {
473        self.peer_seeds = seeds;
474        self
475    }
476
477    /// The packages that start the peer-dependency closure in addition to the
478    /// imported packages.
479    #[must_use]
480    pub const fn peer_seeds(&self) -> &PeerClosureSeeds {
481        &self.peer_seeds
482    }
483}
484
485/// Why the unused devDependency check counts a dependency as used tooling
486/// although no source file imports it.
487#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
488#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
489pub struct ToolingCredit {
490    /// The evidence: `plugin-config` when the plugin that declares the
491    /// dependency found its own config file, `plugin-reference` when a
492    /// package.json script, a CI workflow or a git hook runs one of that
493    /// plugin's packages, `ambient-types` for a type package that declares
494    /// globals, `types-target` when the project declares or imports the
495    /// package that a `@types/` package types, `types-config` when a config
496    /// file, such as a tsconfig `types` entry, names the type package,
497    /// `known-tooling` for a library from the tooling catalogue,
498    /// `known-tooling-config` when a command-line tool from the catalogue has
499    /// its own config file, `own-peer` when the same manifest lists the
500    /// devDependency in `peerDependencies`, and `virtual-module-import` when
501    /// a source file imports a virtual module that the package provides, such
502    /// as the SvelteKit `$app/state`. The set is open.
503    pub reason: String,
504    /// The plugin that declares the dependency as tooling.
505    #[serde(default, skip_serializing_if = "Option::is_none")]
506    pub plugin: Option<String>,
507    /// The config file found, relative to the project root, for
508    /// `plugin-config` and `known-tooling-config`. A `package.json` path when
509    /// the config is a package.json key. For `own-peer`, the manifest that
510    /// lists the dependency. For `virtual-module-import`, the first source
511    /// file in path order that imports one of the virtual modules.
512    #[serde(
513        serialize_with = "serde_path::serialize_option",
514        default,
515        skip_serializing_if = "Option::is_none"
516    )]
517    pub config: Option<PathBuf>,
518    /// The package that a script, CI workflow or git hook runs, for
519    /// `plugin-reference`, or the package that a `@types/` package types,
520    /// for `types-target`. For `virtual-module-import`, the imported
521    /// specifier.
522    #[serde(default, skip_serializing_if = "Option::is_none")]
523    pub reference: Option<String>,
524}
525
526/// A config that names a traced file or a traced dependency, and the key that
527/// names it.
528#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
529#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
530pub struct TraceSource {
531    /// The mechanism that names the file or the dependency:
532    /// `module-federation`. The set is open.
533    pub kind: String,
534    /// The plugin that read the config, as it labels itself:
535    /// `module-federation` for a standalone `module-federation.config.*`,
536    /// or the bundler plugin (`webpack`, `rspack`, `rsbuild`, `vite`,
537    /// `nextjs`) that read the same options inline from its own config.
538    pub plugin: String,
539    /// The file that names the file or the dependency, relative to the
540    /// project root: the config file, or the source file of a Module
541    /// Federation runtime call.
542    #[serde(serialize_with = "serde_path::serialize")]
543    pub config: PathBuf,
544    /// The config key or the runtime function that names the file or the
545    /// dependency: `exposes` for an exposed file, `remotes` for a remote
546    /// alias, and `registerRemotes`, `loadRemote`, `init` or `createInstance`
547    /// for a remote that a runtime call names. The set is open.
548    pub key: String,
549}
550
551/// An export with usage information.
552#[derive(Debug, Serialize)]
553#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
554pub struct TracedExport {
555    /// Export name.
556    pub name: String,
557    /// Whether the export is type-only.
558    pub is_type_only: bool,
559    /// Number of references to this export.
560    pub reference_count: usize,
561    /// Files that reference this export.
562    pub referenced_by: Vec<ExportReference>,
563    /// The framework plugin rules that mark this export as used. Absent when
564    /// no plugin credits the export.
565    #[serde(default, skip_serializing_if = "Vec::is_empty")]
566    pub plugin_credits: Vec<PluginExportCredit>,
567}
568
569/// A framework plugin rule that marks an export as used.
570#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
571#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
572pub struct PluginExportCredit {
573    /// The plugin that gives the rule, for example `nextjs`.
574    pub plugin: String,
575    /// The project-relative file pattern of the rule.
576    pub pattern: String,
577}
578
579impl ExportTrace {
580    /// Add the plugin credits that `provenance` records for the traced export.
581    ///
582    /// The analysis does not report a credited export of a reachable file,
583    /// so the trace then marks the export as used. A star re-export
584    /// collision keeps its abstention.
585    pub fn apply_plugin_credits(&mut self, provenance: &TraceProvenance) {
586        let credits = provenance.export_credits(&self.file, &self.export_name);
587        if credits.is_empty() {
588            return;
589        }
590        if self.file_reachable && !self.is_used && self.star_export_ambiguity.is_none() {
591            let mut plugins: Vec<&str> = Vec::new();
592            for credit in &credits {
593                if !plugins.contains(&credit.plugin.as_str()) {
594                    plugins.push(&credit.plugin);
595                }
596            }
597            self.is_used = true;
598            self.kept_by_tag = None;
599            self.reason = format!(
600                "Used by the framework: the {} plugin marks this export as used",
601                plugins.join(", ")
602            );
603        }
604        self.plugin_credits = credits;
605    }
606}
607
608impl FileTrace {
609    /// Add the plugin credits that `provenance` records for each export.
610    pub fn apply_plugin_credits(&mut self, provenance: &TraceProvenance) {
611        for export in &mut self.exports {
612            export.plugin_credits = provenance.export_credits(&self.file, &export.name);
613        }
614    }
615
616    /// Set the package.json script that `provenance` records for this file
617    /// when the file is an entry point.
618    pub fn apply_entry_script(&mut self, provenance: &TraceProvenance) {
619        self.entry_script = if self.is_entry_point {
620            provenance.entry_script(&self.file).map(str::to_string)
621        } else {
622            None
623        };
624    }
625}
626
627/// A re-export with source information.
628#[derive(Debug, Serialize)]
629#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
630pub struct TracedReExport {
631    /// Source file being re-exported from.
632    #[serde(serialize_with = "serde_path::serialize")]
633    pub source_file: PathBuf,
634    /// Imported symbol name.
635    pub imported_name: String,
636    /// Exported symbol name.
637    pub exported_name: String,
638}
639
640/// Result of tracing a dependency: where it is used.
641#[derive(Debug, Serialize)]
642#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
643pub struct DependencyTrace {
644    /// The dependency name being traced.
645    pub package_name: String,
646    /// Files that import this dependency, each listed once.
647    #[serde(serialize_with = "serde_path::serialize_vec")]
648    pub imported_by: Vec<PathBuf>,
649    /// Files whose every import of this dependency is type-only, each listed
650    /// once.
651    #[serde(serialize_with = "serde_path::serialize_vec")]
652    pub type_only_imported_by: Vec<PathBuf>,
653    /// Whether the dependency is invoked from package.json scripts, CI configs
654    /// or git hooks.
655    pub used_in_scripts: bool,
656    /// Whether the dependency is used at all: imported, invoked from scripts,
657    /// or listed as a peer by a used package (`peer_of`).
658    pub is_used: bool,
659    /// Number of files that import this dependency.
660    pub import_count: usize,
661    /// Used packages that list this dependency in their installed
662    /// `peerDependencies`, required or optional, sorted by name. The
663    /// unused-dependency check credits such a peer, because the package that
664    /// lists it loads it at runtime. Absent when no used package lists it.
665    #[serde(default, skip_serializing_if = "Vec::is_empty")]
666    pub peer_of: Vec<String>,
667    /// The configs that declare this name as a Module Federation remote alias
668    /// under `remotes`, one per config. A remote alias is provided by a
669    /// remote container at runtime, not by an npm package. Absent when no
670    /// Federation config declares the name (issue #2796).
671    #[serde(default, skip_serializing_if = "Vec::is_empty")]
672    pub sources: Vec<TraceSource>,
673    /// Why the unused devDependency check credits the dependency as tooling
674    /// when no file imports it and no script, CI workflow or git hook runs it.
675    /// When present, `is_used` is `true`. Absent otherwise.
676    #[serde(default, skip_serializing_if = "Option::is_none")]
677    pub tooling_credit: Option<ToolingCredit>,
678    /// The manifests that the unused-dependency check flags for this name,
679    /// relative to the project root and sorted. The check reads each
680    /// declaring manifest on its own. An import credits the nearest manifest
681    /// that installs the package, so a name that one workspace uses can still
682    /// be unused in the root manifest or in another workspace. Absent when no
683    /// manifest is flagged.
684    #[serde(
685        default,
686        serialize_with = "serde_path::serialize_vec",
687        skip_serializing_if = "Vec::is_empty"
688    )]
689    pub unused_in: Vec<PathBuf>,
690    /// How the code uses each imported name of the dependency. Present on
691    /// `fallow trace --dependency`, and on the MCP `trace_dependency` tool
692    /// when a usage parameter is set. Absent on
693    /// `fallow dead-code --trace-dependency`. The object has its own
694    /// `schema_version`.
695    #[serde(default, skip_serializing_if = "Option::is_none")]
696    pub usage: Option<crate::trace_usage::DependencyUsage>,
697}
698
699impl DependencyTrace {
700    /// Record the manifests that the unused-dependency report flags for this
701    /// name, so the trace names each declaration that the report lists.
702    pub fn apply_unused_declarations(
703        &mut self,
704        results: &crate::results::AnalysisResults,
705        root: &Path,
706    ) {
707        let flagged = results
708            .unused_dependencies
709            .iter()
710            .map(|finding| &finding.dep)
711            .chain(
712                results
713                    .unused_dev_dependencies
714                    .iter()
715                    .map(|finding| &finding.dep),
716            )
717            .chain(
718                results
719                    .unused_optional_dependencies
720                    .iter()
721                    .map(|finding| &finding.dep),
722            )
723            .filter(|dep| dep.package_name == self.package_name)
724            .map(|dep| {
725                dep.path
726                    .strip_prefix(root)
727                    .unwrap_or(&dep.path)
728                    .to_path_buf()
729            });
730        self.unused_in.extend(flagged);
731        self.unused_in.sort();
732        self.unused_in.dedup();
733    }
734
735    /// Attach the tooling credit of an otherwise unused dependency and count
736    /// the dependency as used, so the trace agrees with the unused-dependency
737    /// report. A dependency that an import or a script already uses keeps no
738    /// credit, because the credit does not decide its status.
739    pub fn apply_tooling_credit(&mut self, credit: Option<ToolingCredit>) {
740        if self.is_used {
741            return;
742        }
743        if let Some(credit) = credit {
744            self.is_used = true;
745            self.tooling_credit = Some(credit);
746        }
747    }
748}
749
750/// Sub-phase attribution inside the entry-point discovery stage.
751///
752/// `PipelineTimings::entry_points_ms` is a single opaque number; these are the
753/// consecutive wall-clock spans that make it up, so a slow discovery stage can
754/// be attributed instead of guessed at. The spans cover the discovery sections
755/// only, so they sum to slightly less than `entry_points_ms`: the summary and
756/// count that follow discovery are not attributed to any span.
757#[derive(Debug, Clone, Copy, Default, Serialize)]
758#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
759pub struct EntryPointSpans {
760    /// Root-package discovery: manual entry globs, root `package.json` fields,
761    /// and the nested `package.json` scan under the conventional monorepo
762    /// directories.
763    pub root_ms: f64,
764    /// Runtime script seed collection plus per-workspace discovery.
765    pub workspaces_ms: f64,
766    /// Plugin entry-point glob compilation and matching.
767    pub plugins_ms: f64,
768    /// The part of `plugins_ms` spent compiling plugin patterns into a glob
769    /// set. Scales with active pattern count, not with project size.
770    pub plugin_glob_build_ms: f64,
771    /// The part of `plugins_ms` spent matching the compiled set against every
772    /// discovered file. Scales with file count times pattern count.
773    pub plugin_glob_match_ms: f64,
774    /// Infrastructure config-file probing at the project root.
775    pub infrastructure_ms: f64,
776    /// Configured `dynamicallyLoaded` glob expansion. Zero when unconfigured.
777    pub dynamic_ms: f64,
778    /// Sorting and deduplicating the merged entry set.
779    pub dedup_ms: f64,
780}
781
782/// Deterministic work counts for one dead-code pipeline run.
783///
784/// Every count is exact for a given project, commit and cache state. It does
785/// not depend on the thread count, the machine or the load, so a regression
786/// test can compare it with exact equality where a millisecond value is too
787/// noisy. A count is zero when its stage did no work, for example the resolver
788/// counts on a run that reused the persisted module graph.
789#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
790#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
791pub struct PipelineCounters {
792    /// Source files whose bytes the parse stage read from disk. A warm cache
793    /// hit on file metadata reads no bytes. `cache_misses` counts the files
794    /// that were parsed.
795    pub files_read: u64,
796    /// Bytes of source read from disk by the parse stage.
797    pub source_bytes_read: u64,
798    /// Bytes of the persisted parse cache read from disk. Zero when the run
799    /// had no parse cache or used `--no-cache`.
800    pub parse_cache_bytes_read: u64,
801    /// Bytes of stylesheet source that the parse stage passed through the CSS
802    /// comment mask. The parse masks each stylesheet once, so this value is
803    /// the size of the parsed stylesheets. A higher value shows a repeated
804    /// mask. Zero when no stylesheet was parsed.
805    pub css_masked_bytes: u64,
806    /// Specifier resolutions that the import sites asked for: one for each
807    /// static import binding, re-export, `require()`, `import()` and module
808    /// mock. Internal retries inside the resolver are not counted here.
809    pub resolve_specifier_calls: u64,
810    /// Distinct `(specifier, from_style)` pairs for each importing file,
811    /// summed over all files. A ratio of `resolve_specifier_calls` to this
812    /// value above 1.0 shows bindings that share a specifier. The resolver
813    /// runs at most once for each of these pairs. A pair that returns before
814    /// the resolver, such as an external URL, makes no resolver call.
815    pub unique_specifiers: u64,
816    /// Calls into the module resolver, including fallback retries.
817    pub oxc_resolve_calls: u64,
818    /// Path canonicalize calls that import resolution needs: each direct call,
819    /// plus one for each distinct path that goes through the canonicalize
820    /// cache. Resolver setup is not counted.
821    pub canonicalize_calls: u64,
822}
823
824/// Pipeline performance timings.
825#[derive(Debug, Clone, Serialize)]
826#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
827pub struct PipelineTimings {
828    /// Time spent discovering files.
829    pub discover_files_ms: f64,
830    /// Number of discovered files.
831    pub file_count: usize,
832    /// Time spent discovering workspaces.
833    pub workspaces_ms: f64,
834    /// Number of discovered workspaces.
835    pub workspace_count: usize,
836    /// Time spent running plugin discovery.
837    pub plugins_ms: f64,
838    /// Time spent analyzing package scripts and CI configuration.
839    pub script_analysis_ms: f64,
840    /// Wall-clock time spent parsing and extracting modules.
841    pub parse_extract_ms: f64,
842    /// Summed parser CPU time across workers.
843    pub parse_cpu_ms: f64,
844    /// The part of `parse_extract_ms` that reads and decodes the persisted
845    /// parse cache. Zero with `--no-cache`.
846    pub parse_cache_load_ms: f64,
847    /// Number of extracted modules.
848    pub module_count: usize,
849    /// Number of files loaded from the parse cache.
850    pub cache_hits: usize,
851    /// Number of files parsed without a cache hit.
852    pub cache_misses: usize,
853    /// Why the persisted parse cache was not reused, when it was not. `None`
854    /// means the cache was loaded; the hit and miss counts then describe how
855    /// much of it applied.
856    #[serde(default, skip_serializing_if = "Option::is_none")]
857    pub cache_rejection: Option<CacheRejection>,
858    /// Why the persisted module-graph cache was not reused, when it was not.
859    #[serde(default, skip_serializing_if = "Option::is_none")]
860    pub graph_cache_rejection: Option<CacheRejection>,
861    /// Time spent updating the parse cache.
862    pub cache_update_ms: f64,
863    /// Time spent categorizing entry points.
864    pub entry_points_ms: f64,
865    /// Sub-phase attribution for `entry_points_ms`.
866    pub entry_point_spans: EntryPointSpans,
867    /// Number of entry points considered.
868    pub entry_point_count: usize,
869    /// Time spent resolving imports.
870    pub resolve_imports_ms: f64,
871    /// Time spent building the module graph.
872    pub build_graph_ms: f64,
873    /// Time spent running analysis.
874    pub analyze_ms: f64,
875    /// Time spent running duplicate-code analysis, when included.
876    #[serde(default, skip_serializing_if = "Option::is_none")]
877    pub duplication_ms: Option<f64>,
878    /// Total pipeline time.
879    pub total_ms: f64,
880    /// Deterministic work counts for this run.
881    pub counters: PipelineCounters,
882}
883
884/// Result of computing the impact closure for a single file as the seed.
885#[derive(Debug, Serialize)]
886#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
887pub struct ImpactClosureTrace {
888    /// The seed file, root-relative.
889    pub seed: String,
890    /// Root-relative paths transitively affected by the seed.
891    pub affected_not_shown: Vec<String>,
892    /// Coordination gaps between the seed and consumers.
893    pub coordination_gap: Vec<ImpactClosureGap>,
894}
895
896/// Wire-version discriminator for [`ImportPathTrace`]. Independent from the
897/// global `SchemaVersion`: the import-path payload versions on its own cadence,
898/// like the other independently-versioned envelopes. Serializes as a string
899/// `const` so JSON consumers can switch on it.
900#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
901#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
902pub enum ImportPathTraceSchemaVersion {
903    /// First release of the `fallow trace --path` shape.
904    #[serde(rename = "1")]
905    V1,
906}
907
908/// Result of asking how one module reaches another: the shortest import path.
909///
910/// `reachable` is the only field that separates "no route exists" from "the
911/// route is empty because both ends are the same module". Both report
912/// `hops: 0`, so a consumer must read `reachable`, never the hop count.
913#[derive(Debug, Serialize)]
914#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
915#[cfg_attr(feature = "schema", schemars(title = "fallow trace --path"))]
916pub struct ImportPathTrace {
917    /// Wire-shape version of this payload.
918    pub schema_version: ImportPathTraceSchemaVersion,
919    /// The module the walk started from, root-relative.
920    pub from: String,
921    /// The module the walk was looking for, root-relative.
922    pub to: String,
923    /// Whether `to` is reachable from `from` by following import edges.
924    pub reachable: bool,
925    /// Number of import edges on the reported route. `0` both when the two ends
926    /// are the same module and when there is no route at all.
927    pub hops: usize,
928    /// The route, in import order. Empty whenever `hops` is `0`.
929    pub path: Vec<ImportPathHop>,
930    /// Human-readable summary of the outcome.
931    pub reason: String,
932}
933
934/// One import edge on an [`ImportPathTrace`].
935#[derive(Debug, Serialize, PartialEq, Eq)]
936#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
937pub struct ImportPathHop {
938    /// The importing module, root-relative.
939    pub from: String,
940    /// The imported module, root-relative.
941    pub to: String,
942    /// Whether every symbol on this edge is type-only, so the hop is erased at
943    /// build time. Type-only hops are reported, never skipped: an `import type`
944    /// chain is a real compile-time coupling.
945    pub type_only: bool,
946    /// Whether the edge carries a runtime value but no static one: the target
947    /// loads only on demand (`import()`, a lazy glob or template pattern) or
948    /// on another thread (a worker URL, a worker loader request,
949    /// `child_process.fork`). False for a
950    /// static hop and for a type-only hop.
951    pub dynamic: bool,
952    /// 1-based line in `from` of the imported binding that creates this edge:
953    /// the first value-carrying symbol on the import, or the first symbol when
954    /// every symbol is type-only. On a multi-line import that is the binding's
955    /// own line, not the `import` keyword's. Absent when the edge carries no
956    /// span or the source could not be read.
957    #[serde(default, skip_serializing_if = "Option::is_none")]
958    pub import_line: Option<u32>,
959}
960
961/// One coordination-gap entry in an [`ImpactClosureTrace`].
962#[derive(Debug, Serialize)]
963#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
964pub struct ImpactClosureGap {
965    /// Root-relative path of the consumer module.
966    pub consumer_file: String,
967    /// Exported symbol names the consumer references.
968    pub consumed_symbols: Vec<String>,
969    /// Scope note for the syntactic trace.
970    pub note: String,
971    /// Whether a whole-word text search for the consumed symbol names finds
972    /// this consumer. When the consumer uses more than one symbol, the worst
973    /// level wins (`missed`, then `renamed`, then `found`). Absent when no
974    /// check applies, for example when the consumer source cannot be read.
975    #[serde(default, skip_serializing_if = "Option::is_none")]
976    pub search_visibility: Option<SearchVisibility>,
977    /// Why a text search does not find the uses of the worst symbol. With
978    /// `search_visibility` `found`, only `pass-through` occurs.
979    #[serde(default, skip_serializing_if = "Option::is_none")]
980    pub reason: Option<SearchGapReason>,
981    /// The name to search for in this consumer instead of the symbol name.
982    #[serde(default, skip_serializing_if = "Option::is_none")]
983    pub search_as: Option<String>,
984    /// The entry of `consumed_symbols` that `search_visibility`, `reason`
985    /// and `search_as` describe: the worst symbol, `default` for a default
986    /// export. Present when `search_visibility` is present.
987    #[serde(default, skip_serializing_if = "Option::is_none")]
988    pub search_symbol: Option<String>,
989}
990
991/// Result of tracing a clone: all groups containing the code at a source
992/// location or addressed by a stable clone fingerprint.
993#[derive(Debug, Serialize)]
994#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
995pub struct CloneTrace {
996    /// File passed to the trace request, root-relative when a group matches.
997    #[serde(serialize_with = "serde_path::serialize")]
998    pub file: PathBuf,
999    /// 1-based line passed to the trace request or representative group line.
1000    pub line: usize,
1001    /// The matched clone instance, if one exists.
1002    pub matched_instance: Option<CloneInstance>,
1003    /// Clone groups matched by the trace request.
1004    pub clone_groups: Vec<TracedCloneGroup>,
1005}
1006
1007/// One clone group returned from a clone trace request.
1008#[derive(Debug, Serialize)]
1009#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1010pub struct TracedCloneGroup {
1011    /// Stable content fingerprint, usually `dup:<8hex>` and widened on rare
1012    /// report collisions.
1013    pub fingerprint: String,
1014    /// Number of tokens in the duplicated block.
1015    pub token_count: usize,
1016    /// Number of lines in the duplicated block.
1017    pub line_count: usize,
1018    /// Maximum directory-tree or same-file line distance between instances.
1019    pub spread: usize,
1020    /// Lowest all-pairs similarity for a near-miss clone group.
1021    #[serde(default, skip_serializing_if = "Option::is_none")]
1022    #[cfg_attr(feature = "schema", schemars(with = "f64"))]
1023    pub similarity: Option<f64>,
1024    /// Root-relative clone instances in this group.
1025    pub instances: Vec<CloneInstance>,
1026    /// Group-level refactoring suggestion.
1027    pub suggestion: RefactoringSuggestion,
1028    /// Best-effort name for the extracted function. Advisory only.
1029    #[serde(default, skip_serializing_if = "Option::is_none")]
1030    pub suggested_name: Option<String>,
1031}
1032
1033#[cfg(test)]
1034mod tests {
1035    use super::*;
1036
1037    fn unreferenced_trace(file_reachable: bool) -> ExportTrace {
1038        ExportTrace {
1039            file: PathBuf::from("app/page.tsx"),
1040            export_name: "default".to_string(),
1041            namespace: SemanticNamespace::Value,
1042            file_reachable,
1043            is_entry_point: true,
1044            is_used: false,
1045            direct_references: Vec::new(),
1046            direct_references_by_namespace: Vec::new(),
1047            star_export_ambiguity: None,
1048            re_export_chains: Vec::new(),
1049            plugin_credits: Vec::new(),
1050            kept_by_tag: None,
1051            reason: "No references".to_string(),
1052            semantic: None,
1053        }
1054    }
1055
1056    fn page_provenance() -> TraceProvenance {
1057        let mut provenance = TraceProvenance::default();
1058        let credit = PluginExportCredit {
1059            plugin: "nextjs".to_string(),
1060            pattern: "app/**/page.tsx".to_string(),
1061        };
1062        provenance.push_export_credits(
1063            PathBuf::from("app/page.tsx"),
1064            [
1065                ("default".to_string(), credit.clone()),
1066                ("default".to_string(), credit),
1067            ],
1068        );
1069        provenance
1070    }
1071
1072    #[test]
1073    fn a_plugin_credit_marks_an_export_of_a_reachable_file_as_used() {
1074        let mut trace = unreferenced_trace(true);
1075        trace.apply_plugin_credits(&page_provenance());
1076        assert!(trace.is_used);
1077        assert_eq!(trace.plugin_credits.len(), 1);
1078        assert!(trace.reason.contains("nextjs"), "{}", trace.reason);
1079    }
1080
1081    #[test]
1082    fn a_plugin_credit_does_not_mark_an_unreachable_file_as_used() {
1083        let mut trace = unreferenced_trace(false);
1084        trace.apply_plugin_credits(&page_provenance());
1085        assert!(!trace.is_used);
1086        assert_eq!(trace.plugin_credits.len(), 1);
1087        assert_eq!(trace.reason, "No references");
1088    }
1089
1090    #[test]
1091    fn a_star_export_collision_keeps_its_abstention() {
1092        let mut trace = unreferenced_trace(true);
1093        trace.star_export_ambiguity = Some(StarExportAmbiguity {
1094            sources: vec![PathBuf::from("a.ts"), PathBuf::from("b.ts")],
1095            namespaces: vec![SemanticNamespace::Value],
1096        });
1097        trace.apply_plugin_credits(&page_provenance());
1098        assert!(!trace.is_used);
1099    }
1100
1101    #[test]
1102    fn an_export_without_a_credit_keeps_its_trace() {
1103        let mut trace = unreferenced_trace(true);
1104        trace.export_name = "helper".to_string();
1105        trace.apply_plugin_credits(&page_provenance());
1106        assert!(!trace.is_used);
1107        assert!(trace.plugin_credits.is_empty());
1108    }
1109
1110    fn file_trace(file: &str, is_entry_point: bool) -> FileTrace {
1111        FileTrace {
1112            file: PathBuf::from(file),
1113            is_reachable: true,
1114            is_entry_point,
1115            exports: Vec::new(),
1116            imports_from: Vec::new(),
1117            imported_by: Vec::new(),
1118            re_exports: Vec::new(),
1119            entry_script: None,
1120            sources: Vec::new(),
1121        }
1122    }
1123
1124    fn script_provenance() -> TraceProvenance {
1125        use crate::discover::{EntryPoint, EntryPointSource};
1126        let mut provenance = TraceProvenance::default();
1127        provenance.push_entry_scripts(
1128            Path::new("/project"),
1129            &[
1130                EntryPoint {
1131                    path: PathBuf::from("/project/scripts/build.js"),
1132                    source: EntryPointSource::PackageJsonScript {
1133                        script: "build".to_string(),
1134                    },
1135                },
1136                EntryPoint {
1137                    path: PathBuf::from("/project/src/index.js"),
1138                    source: EntryPointSource::PackageJsonMain,
1139                },
1140            ],
1141        );
1142        provenance
1143    }
1144
1145    #[test]
1146    fn a_script_entry_point_names_its_script() {
1147        let mut trace = file_trace("scripts/build.js", true);
1148        trace.apply_entry_script(&script_provenance());
1149        assert_eq!(trace.entry_script.as_deref(), Some("build"));
1150    }
1151
1152    #[test]
1153    fn an_entry_point_of_another_source_names_no_script() {
1154        let mut trace = file_trace("src/index.js", true);
1155        trace.apply_entry_script(&script_provenance());
1156        assert_eq!(trace.entry_script, None);
1157    }
1158
1159    #[test]
1160    fn a_file_that_is_not_an_entry_point_names_no_script() {
1161        let mut trace = file_trace("scripts/build.js", false);
1162        trace.apply_entry_script(&script_provenance());
1163        assert_eq!(trace.entry_script, None);
1164    }
1165}