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, and `own-peer` when the same manifest lists the
500    /// devDependency in `peerDependencies`. The set is open.
501    pub reason: String,
502    /// The plugin that declares the dependency as tooling.
503    #[serde(default, skip_serializing_if = "Option::is_none")]
504    pub plugin: Option<String>,
505    /// The config file found, relative to the project root, for
506    /// `plugin-config` and `known-tooling-config`. A `package.json` path when
507    /// the config is a package.json key. For `own-peer`, the manifest that
508    /// lists the dependency.
509    #[serde(
510        serialize_with = "serde_path::serialize_option",
511        default,
512        skip_serializing_if = "Option::is_none"
513    )]
514    pub config: Option<PathBuf>,
515    /// The package that a script, CI workflow or git hook runs, for
516    /// `plugin-reference`, or the package that a `@types/` package types,
517    /// for `types-target`.
518    #[serde(default, skip_serializing_if = "Option::is_none")]
519    pub reference: Option<String>,
520}
521
522/// A config that names a traced file or a traced dependency, and the key that
523/// names it.
524#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
525#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
526pub struct TraceSource {
527    /// The mechanism that names the file or the dependency:
528    /// `module-federation`. The set is open.
529    pub kind: String,
530    /// The plugin that read the config, as it labels itself:
531    /// `module-federation` for a standalone `module-federation.config.*`,
532    /// or the bundler plugin (`webpack`, `rspack`, `rsbuild`, `vite`,
533    /// `nextjs`) that read the same options inline from its own config.
534    pub plugin: String,
535    /// The file that names the file or the dependency, relative to the
536    /// project root: the config file, or the source file of a Module
537    /// Federation runtime call.
538    #[serde(serialize_with = "serde_path::serialize")]
539    pub config: PathBuf,
540    /// The config key or the runtime function that names the file or the
541    /// dependency: `exposes` for an exposed file, `remotes` for a remote
542    /// alias, and `registerRemotes`, `loadRemote`, `init` or `createInstance`
543    /// for a remote that a runtime call names. The set is open.
544    pub key: String,
545}
546
547/// An export with usage information.
548#[derive(Debug, Serialize)]
549#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
550pub struct TracedExport {
551    /// Export name.
552    pub name: String,
553    /// Whether the export is type-only.
554    pub is_type_only: bool,
555    /// Number of references to this export.
556    pub reference_count: usize,
557    /// Files that reference this export.
558    pub referenced_by: Vec<ExportReference>,
559    /// The framework plugin rules that mark this export as used. Absent when
560    /// no plugin credits the export.
561    #[serde(default, skip_serializing_if = "Vec::is_empty")]
562    pub plugin_credits: Vec<PluginExportCredit>,
563}
564
565/// A framework plugin rule that marks an export as used.
566#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
567#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
568pub struct PluginExportCredit {
569    /// The plugin that gives the rule, for example `nextjs`.
570    pub plugin: String,
571    /// The project-relative file pattern of the rule.
572    pub pattern: String,
573}
574
575impl ExportTrace {
576    /// Add the plugin credits that `provenance` records for the traced export.
577    ///
578    /// The analysis does not report a credited export of a reachable file,
579    /// so the trace then marks the export as used. A star re-export
580    /// collision keeps its abstention.
581    pub fn apply_plugin_credits(&mut self, provenance: &TraceProvenance) {
582        let credits = provenance.export_credits(&self.file, &self.export_name);
583        if credits.is_empty() {
584            return;
585        }
586        if self.file_reachable && !self.is_used && self.star_export_ambiguity.is_none() {
587            let mut plugins: Vec<&str> = Vec::new();
588            for credit in &credits {
589                if !plugins.contains(&credit.plugin.as_str()) {
590                    plugins.push(&credit.plugin);
591                }
592            }
593            self.is_used = true;
594            self.kept_by_tag = None;
595            self.reason = format!(
596                "Used by the framework: the {} plugin marks this export as used",
597                plugins.join(", ")
598            );
599        }
600        self.plugin_credits = credits;
601    }
602}
603
604impl FileTrace {
605    /// Add the plugin credits that `provenance` records for each export.
606    pub fn apply_plugin_credits(&mut self, provenance: &TraceProvenance) {
607        for export in &mut self.exports {
608            export.plugin_credits = provenance.export_credits(&self.file, &export.name);
609        }
610    }
611
612    /// Set the package.json script that `provenance` records for this file
613    /// when the file is an entry point.
614    pub fn apply_entry_script(&mut self, provenance: &TraceProvenance) {
615        self.entry_script = if self.is_entry_point {
616            provenance.entry_script(&self.file).map(str::to_string)
617        } else {
618            None
619        };
620    }
621}
622
623/// A re-export with source information.
624#[derive(Debug, Serialize)]
625#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
626pub struct TracedReExport {
627    /// Source file being re-exported from.
628    #[serde(serialize_with = "serde_path::serialize")]
629    pub source_file: PathBuf,
630    /// Imported symbol name.
631    pub imported_name: String,
632    /// Exported symbol name.
633    pub exported_name: String,
634}
635
636/// Result of tracing a dependency: where it is used.
637#[derive(Debug, Serialize)]
638#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
639pub struct DependencyTrace {
640    /// The dependency name being traced.
641    pub package_name: String,
642    /// Files that import this dependency, each listed once.
643    #[serde(serialize_with = "serde_path::serialize_vec")]
644    pub imported_by: Vec<PathBuf>,
645    /// Files whose every import of this dependency is type-only, each listed
646    /// once.
647    #[serde(serialize_with = "serde_path::serialize_vec")]
648    pub type_only_imported_by: Vec<PathBuf>,
649    /// Whether the dependency is invoked from package.json scripts, CI configs
650    /// or git hooks.
651    pub used_in_scripts: bool,
652    /// Whether the dependency is used at all: imported, invoked from scripts,
653    /// or listed as a peer by a used package (`peer_of`).
654    pub is_used: bool,
655    /// Number of files that import this dependency.
656    pub import_count: usize,
657    /// Used packages that list this dependency in their installed
658    /// `peerDependencies`, required or optional, sorted by name. The
659    /// unused-dependency check credits such a peer, because the package that
660    /// lists it loads it at runtime. Absent when no used package lists it.
661    #[serde(default, skip_serializing_if = "Vec::is_empty")]
662    pub peer_of: Vec<String>,
663    /// The configs that declare this name as a Module Federation remote alias
664    /// under `remotes`, one per config. A remote alias is provided by a
665    /// remote container at runtime, not by an npm package. Absent when no
666    /// Federation config declares the name (issue #2796).
667    #[serde(default, skip_serializing_if = "Vec::is_empty")]
668    pub sources: Vec<TraceSource>,
669    /// Why the unused devDependency check credits the dependency as tooling
670    /// when no file imports it and no script, CI workflow or git hook runs it.
671    /// When present, `is_used` is `true`. Absent otherwise.
672    #[serde(default, skip_serializing_if = "Option::is_none")]
673    pub tooling_credit: Option<ToolingCredit>,
674    /// The manifests that the unused-dependency check flags for this name,
675    /// relative to the project root and sorted. The check reads each
676    /// declaring manifest on its own. An import credits the nearest manifest
677    /// that installs the package, so a name that one workspace uses can still
678    /// be unused in the root manifest or in another workspace. Absent when no
679    /// manifest is flagged.
680    #[serde(
681        default,
682        serialize_with = "serde_path::serialize_vec",
683        skip_serializing_if = "Vec::is_empty"
684    )]
685    pub unused_in: Vec<PathBuf>,
686    /// How the code uses each imported name of the dependency. Present on
687    /// `fallow trace --dependency`, and on the MCP `trace_dependency` tool
688    /// when a usage parameter is set. Absent on
689    /// `fallow dead-code --trace-dependency`. The object has its own
690    /// `schema_version`.
691    #[serde(default, skip_serializing_if = "Option::is_none")]
692    pub usage: Option<crate::trace_usage::DependencyUsage>,
693}
694
695impl DependencyTrace {
696    /// Record the manifests that the unused-dependency report flags for this
697    /// name, so the trace names each declaration that the report lists.
698    pub fn apply_unused_declarations(
699        &mut self,
700        results: &crate::results::AnalysisResults,
701        root: &Path,
702    ) {
703        let flagged = results
704            .unused_dependencies
705            .iter()
706            .map(|finding| &finding.dep)
707            .chain(
708                results
709                    .unused_dev_dependencies
710                    .iter()
711                    .map(|finding| &finding.dep),
712            )
713            .chain(
714                results
715                    .unused_optional_dependencies
716                    .iter()
717                    .map(|finding| &finding.dep),
718            )
719            .filter(|dep| dep.package_name == self.package_name)
720            .map(|dep| {
721                dep.path
722                    .strip_prefix(root)
723                    .unwrap_or(&dep.path)
724                    .to_path_buf()
725            });
726        self.unused_in.extend(flagged);
727        self.unused_in.sort();
728        self.unused_in.dedup();
729    }
730
731    /// Attach the tooling credit of an otherwise unused dependency and count
732    /// the dependency as used, so the trace agrees with the unused-dependency
733    /// report. A dependency that an import or a script already uses keeps no
734    /// credit, because the credit does not decide its status.
735    pub fn apply_tooling_credit(&mut self, credit: Option<ToolingCredit>) {
736        if self.is_used {
737            return;
738        }
739        if let Some(credit) = credit {
740            self.is_used = true;
741            self.tooling_credit = Some(credit);
742        }
743    }
744}
745
746/// Sub-phase attribution inside the entry-point discovery stage.
747///
748/// `PipelineTimings::entry_points_ms` is a single opaque number; these are the
749/// consecutive wall-clock spans that make it up, so a slow discovery stage can
750/// be attributed instead of guessed at. The spans cover the discovery sections
751/// only, so they sum to slightly less than `entry_points_ms`: the summary and
752/// count that follow discovery are not attributed to any span.
753#[derive(Debug, Clone, Copy, Default, Serialize)]
754#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
755pub struct EntryPointSpans {
756    /// Root-package discovery: manual entry globs, root `package.json` fields,
757    /// and the nested `package.json` scan under the conventional monorepo
758    /// directories.
759    pub root_ms: f64,
760    /// Runtime script seed collection plus per-workspace discovery.
761    pub workspaces_ms: f64,
762    /// Plugin entry-point glob compilation and matching.
763    pub plugins_ms: f64,
764    /// The part of `plugins_ms` spent compiling plugin patterns into a glob
765    /// set. Scales with active pattern count, not with project size.
766    pub plugin_glob_build_ms: f64,
767    /// The part of `plugins_ms` spent matching the compiled set against every
768    /// discovered file. Scales with file count times pattern count.
769    pub plugin_glob_match_ms: f64,
770    /// Infrastructure config-file probing at the project root.
771    pub infrastructure_ms: f64,
772    /// Configured `dynamicallyLoaded` glob expansion. Zero when unconfigured.
773    pub dynamic_ms: f64,
774    /// Sorting and deduplicating the merged entry set.
775    pub dedup_ms: f64,
776}
777
778/// Deterministic work counts for one dead-code pipeline run.
779///
780/// Every count is exact for a given project, commit and cache state. It does
781/// not depend on the thread count, the machine or the load, so a regression
782/// test can compare it with exact equality where a millisecond value is too
783/// noisy. A count is zero when its stage did no work, for example the resolver
784/// counts on a run that reused the persisted module graph.
785#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
786#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
787pub struct PipelineCounters {
788    /// Source files whose bytes the parse stage read from disk. A warm cache
789    /// hit on file metadata reads no bytes. `cache_misses` counts the files
790    /// that were parsed.
791    pub files_read: u64,
792    /// Bytes of source read from disk by the parse stage.
793    pub source_bytes_read: u64,
794    /// Bytes of the persisted parse cache read from disk. Zero when the run
795    /// had no parse cache or used `--no-cache`.
796    pub parse_cache_bytes_read: u64,
797    /// Bytes of stylesheet source that the parse stage passed through the CSS
798    /// comment mask. The parse masks each stylesheet once, so this value is
799    /// the size of the parsed stylesheets. A higher value shows a repeated
800    /// mask. Zero when no stylesheet was parsed.
801    pub css_masked_bytes: u64,
802    /// Specifier resolutions that the import sites asked for: one for each
803    /// static import binding, re-export, `require()`, `import()` and module
804    /// mock. Internal retries inside the resolver are not counted here.
805    pub resolve_specifier_calls: u64,
806    /// Distinct `(specifier, from_style)` pairs for each importing file,
807    /// summed over all files. A ratio of `resolve_specifier_calls` to this
808    /// value above 1.0 shows bindings that share a specifier. The resolver
809    /// runs at most once for each of these pairs. A pair that returns before
810    /// the resolver, such as an external URL, makes no resolver call.
811    pub unique_specifiers: u64,
812    /// Calls into the module resolver, including fallback retries.
813    pub oxc_resolve_calls: u64,
814    /// Path canonicalize calls that import resolution needs: each direct call,
815    /// plus one for each distinct path that goes through the canonicalize
816    /// cache. Resolver setup is not counted.
817    pub canonicalize_calls: u64,
818}
819
820/// Pipeline performance timings.
821#[derive(Debug, Clone, Serialize)]
822#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
823pub struct PipelineTimings {
824    /// Time spent discovering files.
825    pub discover_files_ms: f64,
826    /// Number of discovered files.
827    pub file_count: usize,
828    /// Time spent discovering workspaces.
829    pub workspaces_ms: f64,
830    /// Number of discovered workspaces.
831    pub workspace_count: usize,
832    /// Time spent running plugin discovery.
833    pub plugins_ms: f64,
834    /// Time spent analyzing package scripts and CI configuration.
835    pub script_analysis_ms: f64,
836    /// Wall-clock time spent parsing and extracting modules.
837    pub parse_extract_ms: f64,
838    /// Summed parser CPU time across workers.
839    pub parse_cpu_ms: f64,
840    /// The part of `parse_extract_ms` that reads and decodes the persisted
841    /// parse cache. Zero with `--no-cache`.
842    pub parse_cache_load_ms: f64,
843    /// Number of extracted modules.
844    pub module_count: usize,
845    /// Number of files loaded from the parse cache.
846    pub cache_hits: usize,
847    /// Number of files parsed without a cache hit.
848    pub cache_misses: usize,
849    /// Why the persisted parse cache was not reused, when it was not. `None`
850    /// means the cache was loaded; the hit and miss counts then describe how
851    /// much of it applied.
852    #[serde(default, skip_serializing_if = "Option::is_none")]
853    pub cache_rejection: Option<CacheRejection>,
854    /// Why the persisted module-graph cache was not reused, when it was not.
855    #[serde(default, skip_serializing_if = "Option::is_none")]
856    pub graph_cache_rejection: Option<CacheRejection>,
857    /// Time spent updating the parse cache.
858    pub cache_update_ms: f64,
859    /// Time spent categorizing entry points.
860    pub entry_points_ms: f64,
861    /// Sub-phase attribution for `entry_points_ms`.
862    pub entry_point_spans: EntryPointSpans,
863    /// Number of entry points considered.
864    pub entry_point_count: usize,
865    /// Time spent resolving imports.
866    pub resolve_imports_ms: f64,
867    /// Time spent building the module graph.
868    pub build_graph_ms: f64,
869    /// Time spent running analysis.
870    pub analyze_ms: f64,
871    /// Time spent running duplicate-code analysis, when included.
872    #[serde(default, skip_serializing_if = "Option::is_none")]
873    pub duplication_ms: Option<f64>,
874    /// Total pipeline time.
875    pub total_ms: f64,
876    /// Deterministic work counts for this run.
877    pub counters: PipelineCounters,
878}
879
880/// Result of computing the impact closure for a single file as the seed.
881#[derive(Debug, Serialize)]
882#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
883pub struct ImpactClosureTrace {
884    /// The seed file, root-relative.
885    pub seed: String,
886    /// Root-relative paths transitively affected by the seed.
887    pub affected_not_shown: Vec<String>,
888    /// Coordination gaps between the seed and consumers.
889    pub coordination_gap: Vec<ImpactClosureGap>,
890}
891
892/// Wire-version discriminator for [`ImportPathTrace`]. Independent from the
893/// global `SchemaVersion`: the import-path payload versions on its own cadence,
894/// like the other independently-versioned envelopes. Serializes as a string
895/// `const` so JSON consumers can switch on it.
896#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
897#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
898pub enum ImportPathTraceSchemaVersion {
899    /// First release of the `fallow trace --path` shape.
900    #[serde(rename = "1")]
901    V1,
902}
903
904/// Result of asking how one module reaches another: the shortest import path.
905///
906/// `reachable` is the only field that separates "no route exists" from "the
907/// route is empty because both ends are the same module". Both report
908/// `hops: 0`, so a consumer must read `reachable`, never the hop count.
909#[derive(Debug, Serialize)]
910#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
911#[cfg_attr(feature = "schema", schemars(title = "fallow trace --path"))]
912pub struct ImportPathTrace {
913    /// Wire-shape version of this payload.
914    pub schema_version: ImportPathTraceSchemaVersion,
915    /// The module the walk started from, root-relative.
916    pub from: String,
917    /// The module the walk was looking for, root-relative.
918    pub to: String,
919    /// Whether `to` is reachable from `from` by following import edges.
920    pub reachable: bool,
921    /// Number of import edges on the reported route. `0` both when the two ends
922    /// are the same module and when there is no route at all.
923    pub hops: usize,
924    /// The route, in import order. Empty whenever `hops` is `0`.
925    pub path: Vec<ImportPathHop>,
926    /// Human-readable summary of the outcome.
927    pub reason: String,
928}
929
930/// One import edge on an [`ImportPathTrace`].
931#[derive(Debug, Serialize, PartialEq, Eq)]
932#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
933pub struct ImportPathHop {
934    /// The importing module, root-relative.
935    pub from: String,
936    /// The imported module, root-relative.
937    pub to: String,
938    /// Whether every symbol on this edge is type-only, so the hop is erased at
939    /// build time. Type-only hops are reported, never skipped: an `import type`
940    /// chain is a real compile-time coupling.
941    pub type_only: bool,
942    /// Whether the edge carries a runtime value but no static one: the target
943    /// loads only on demand (`import()`, a lazy glob or template pattern) or
944    /// on another thread (a worker URL, a worker loader request,
945    /// `child_process.fork`). False for a
946    /// static hop and for a type-only hop.
947    pub dynamic: bool,
948    /// 1-based line in `from` of the imported binding that creates this edge:
949    /// the first value-carrying symbol on the import, or the first symbol when
950    /// every symbol is type-only. On a multi-line import that is the binding's
951    /// own line, not the `import` keyword's. Absent when the edge carries no
952    /// span or the source could not be read.
953    #[serde(default, skip_serializing_if = "Option::is_none")]
954    pub import_line: Option<u32>,
955}
956
957/// One coordination-gap entry in an [`ImpactClosureTrace`].
958#[derive(Debug, Serialize)]
959#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
960pub struct ImpactClosureGap {
961    /// Root-relative path of the consumer module.
962    pub consumer_file: String,
963    /// Exported symbol names the consumer references.
964    pub consumed_symbols: Vec<String>,
965    /// Scope note for the syntactic trace.
966    pub note: String,
967    /// Whether a whole-word text search for the consumed symbol names finds
968    /// this consumer. When the consumer uses more than one symbol, the worst
969    /// level wins (`missed`, then `renamed`, then `found`). Absent when no
970    /// check applies, for example when the consumer source cannot be read.
971    #[serde(default, skip_serializing_if = "Option::is_none")]
972    pub search_visibility: Option<SearchVisibility>,
973    /// Why a text search does not find the uses of the worst symbol. With
974    /// `search_visibility` `found`, only `pass-through` occurs.
975    #[serde(default, skip_serializing_if = "Option::is_none")]
976    pub reason: Option<SearchGapReason>,
977    /// The name to search for in this consumer instead of the symbol name.
978    #[serde(default, skip_serializing_if = "Option::is_none")]
979    pub search_as: Option<String>,
980    /// The entry of `consumed_symbols` that `search_visibility`, `reason`
981    /// and `search_as` describe: the worst symbol, `default` for a default
982    /// export. Present when `search_visibility` is present.
983    #[serde(default, skip_serializing_if = "Option::is_none")]
984    pub search_symbol: Option<String>,
985}
986
987/// Result of tracing a clone: all groups containing the code at a source
988/// location or addressed by a stable clone fingerprint.
989#[derive(Debug, Serialize)]
990#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
991pub struct CloneTrace {
992    /// File passed to the trace request, root-relative when a group matches.
993    #[serde(serialize_with = "serde_path::serialize")]
994    pub file: PathBuf,
995    /// 1-based line passed to the trace request or representative group line.
996    pub line: usize,
997    /// The matched clone instance, if one exists.
998    pub matched_instance: Option<CloneInstance>,
999    /// Clone groups matched by the trace request.
1000    pub clone_groups: Vec<TracedCloneGroup>,
1001}
1002
1003/// One clone group returned from a clone trace request.
1004#[derive(Debug, Serialize)]
1005#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1006pub struct TracedCloneGroup {
1007    /// Stable content fingerprint, usually `dup:<8hex>` and widened on rare
1008    /// report collisions.
1009    pub fingerprint: String,
1010    /// Number of tokens in the duplicated block.
1011    pub token_count: usize,
1012    /// Number of lines in the duplicated block.
1013    pub line_count: usize,
1014    /// Maximum directory-tree or same-file line distance between instances.
1015    pub spread: usize,
1016    /// Lowest all-pairs similarity for a near-miss clone group.
1017    #[serde(default, skip_serializing_if = "Option::is_none")]
1018    #[cfg_attr(feature = "schema", schemars(with = "f64"))]
1019    pub similarity: Option<f64>,
1020    /// Root-relative clone instances in this group.
1021    pub instances: Vec<CloneInstance>,
1022    /// Group-level refactoring suggestion.
1023    pub suggestion: RefactoringSuggestion,
1024    /// Best-effort name for the extracted function. Advisory only.
1025    #[serde(default, skip_serializing_if = "Option::is_none")]
1026    pub suggested_name: Option<String>,
1027}
1028
1029#[cfg(test)]
1030mod tests {
1031    use super::*;
1032
1033    fn unreferenced_trace(file_reachable: bool) -> ExportTrace {
1034        ExportTrace {
1035            file: PathBuf::from("app/page.tsx"),
1036            export_name: "default".to_string(),
1037            namespace: SemanticNamespace::Value,
1038            file_reachable,
1039            is_entry_point: true,
1040            is_used: false,
1041            direct_references: Vec::new(),
1042            direct_references_by_namespace: Vec::new(),
1043            star_export_ambiguity: None,
1044            re_export_chains: Vec::new(),
1045            plugin_credits: Vec::new(),
1046            kept_by_tag: None,
1047            reason: "No references".to_string(),
1048            semantic: None,
1049        }
1050    }
1051
1052    fn page_provenance() -> TraceProvenance {
1053        let mut provenance = TraceProvenance::default();
1054        let credit = PluginExportCredit {
1055            plugin: "nextjs".to_string(),
1056            pattern: "app/**/page.tsx".to_string(),
1057        };
1058        provenance.push_export_credits(
1059            PathBuf::from("app/page.tsx"),
1060            [
1061                ("default".to_string(), credit.clone()),
1062                ("default".to_string(), credit),
1063            ],
1064        );
1065        provenance
1066    }
1067
1068    #[test]
1069    fn a_plugin_credit_marks_an_export_of_a_reachable_file_as_used() {
1070        let mut trace = unreferenced_trace(true);
1071        trace.apply_plugin_credits(&page_provenance());
1072        assert!(trace.is_used);
1073        assert_eq!(trace.plugin_credits.len(), 1);
1074        assert!(trace.reason.contains("nextjs"), "{}", trace.reason);
1075    }
1076
1077    #[test]
1078    fn a_plugin_credit_does_not_mark_an_unreachable_file_as_used() {
1079        let mut trace = unreferenced_trace(false);
1080        trace.apply_plugin_credits(&page_provenance());
1081        assert!(!trace.is_used);
1082        assert_eq!(trace.plugin_credits.len(), 1);
1083        assert_eq!(trace.reason, "No references");
1084    }
1085
1086    #[test]
1087    fn a_star_export_collision_keeps_its_abstention() {
1088        let mut trace = unreferenced_trace(true);
1089        trace.star_export_ambiguity = Some(StarExportAmbiguity {
1090            sources: vec![PathBuf::from("a.ts"), PathBuf::from("b.ts")],
1091            namespaces: vec![SemanticNamespace::Value],
1092        });
1093        trace.apply_plugin_credits(&page_provenance());
1094        assert!(!trace.is_used);
1095    }
1096
1097    #[test]
1098    fn an_export_without_a_credit_keeps_its_trace() {
1099        let mut trace = unreferenced_trace(true);
1100        trace.export_name = "helper".to_string();
1101        trace.apply_plugin_credits(&page_provenance());
1102        assert!(!trace.is_used);
1103        assert!(trace.plugin_credits.is_empty());
1104    }
1105
1106    fn file_trace(file: &str, is_entry_point: bool) -> FileTrace {
1107        FileTrace {
1108            file: PathBuf::from(file),
1109            is_reachable: true,
1110            is_entry_point,
1111            exports: Vec::new(),
1112            imports_from: Vec::new(),
1113            imported_by: Vec::new(),
1114            re_exports: Vec::new(),
1115            entry_script: None,
1116            sources: Vec::new(),
1117        }
1118    }
1119
1120    fn script_provenance() -> TraceProvenance {
1121        use crate::discover::{EntryPoint, EntryPointSource};
1122        let mut provenance = TraceProvenance::default();
1123        provenance.push_entry_scripts(
1124            Path::new("/project"),
1125            &[
1126                EntryPoint {
1127                    path: PathBuf::from("/project/scripts/build.js"),
1128                    source: EntryPointSource::PackageJsonScript {
1129                        script: "build".to_string(),
1130                    },
1131                },
1132                EntryPoint {
1133                    path: PathBuf::from("/project/src/index.js"),
1134                    source: EntryPointSource::PackageJsonMain,
1135                },
1136            ],
1137        );
1138        provenance
1139    }
1140
1141    #[test]
1142    fn a_script_entry_point_names_its_script() {
1143        let mut trace = file_trace("scripts/build.js", true);
1144        trace.apply_entry_script(&script_provenance());
1145        assert_eq!(trace.entry_script.as_deref(), Some("build"));
1146    }
1147
1148    #[test]
1149    fn an_entry_point_of_another_source_names_no_script() {
1150        let mut trace = file_trace("src/index.js", true);
1151        trace.apply_entry_script(&script_provenance());
1152        assert_eq!(trace.entry_script, None);
1153    }
1154
1155    #[test]
1156    fn a_file_that_is_not_an_entry_point_names_no_script() {
1157        let mut trace = file_trace("scripts/build.js", false);
1158        trace.apply_entry_script(&script_provenance());
1159        assert_eq!(trace.entry_script, None);
1160    }
1161}