Skip to main content

fallow_types/
trace.rs

1//! Shared trace output contracts for analysis and integration surfaces.
2
3use std::path::PathBuf;
4
5use serde::Serialize;
6
7use crate::cache_rejection::CacheRejection;
8use crate::duplicates::{CloneInstance, RefactoringSuggestion};
9use crate::semantic::SemanticNamespace;
10use crate::serde_path;
11use crate::trace_chain::StarExportAmbiguity;
12
13/// Result of tracing an export: why it is considered used or unused.
14#[derive(Debug, Serialize)]
15#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
16pub struct ExportTrace {
17    /// The file containing the export.
18    #[serde(serialize_with = "serde_path::serialize")]
19    pub file: PathBuf,
20    /// The export name being traced.
21    pub export_name: String,
22    /// Namespace whose references are listed for the traced export. The
23    /// preferred lane wins whenever it carries a reference: `value` for a
24    /// value export, `type` for a type-only one. When the preferred lane
25    /// carries none and the other lane resolves to the same declaration, the
26    /// other lane's references are listed and this field names it, so a value
27    /// export whose only credit is a bound `import type` reports `type` with
28    /// `is_used: true`. `is_used` and `direct_references` follow the listed
29    /// lane only, and only reachable reference sources can credit it. Legal
30    /// declaration merges share one declaration group across lanes, including
31    /// an `interface` next to a same-name `class` and a `class` next to a
32    /// same-name `namespace`, so references to either lane credit the merged
33    /// declaration. Distinct same-name declarations outside a merge remain
34    /// separate and keep the preferred lane. `semantic.target.namespace`
35    /// names the lane the declaration itself occupies and can therefore differ
36    /// from this field. Producers always emit the field; the schema permits
37    /// omission by payloads created before namespaces were exposed.
38    #[cfg_attr(feature = "schema", schemars(default))]
39    pub namespace: crate::semantic::SemanticNamespace,
40    /// Whether the file is reachable from an entry point.
41    pub file_reachable: bool,
42    /// Whether the file is an entry point.
43    pub is_entry_point: bool,
44    /// Whether the export is considered used.
45    pub is_used: bool,
46    /// Files that reference this export directly.
47    pub direct_references: Vec<ExportReference>,
48    /// Reachable direct references grouped by namespace. This is additive to
49    /// `namespace` and `direct_references`, whose winning-lane meaning remains
50    /// unchanged for backwards compatibility.
51    #[serde(default, skip_serializing_if = "Vec::is_empty")]
52    pub direct_references_by_namespace: Vec<NamespacedExportReferences>,
53    /// A star-export collision that makes the traced name ambiguous. When
54    /// present, `is_used: false` is an abstention rather than an unused-code
55    /// verdict.
56    #[serde(default, skip_serializing_if = "Option::is_none")]
57    pub star_export_ambiguity: Option<StarExportAmbiguity>,
58    /// Re-export chains that pass through this export.
59    pub re_export_chains: Vec<ReExportChain>,
60    /// Human-readable reason summary.
61    pub reason: String,
62    /// Exact checker-backed references when type-aware tracing is enabled.
63    #[serde(default, skip_serializing_if = "Option::is_none")]
64    pub semantic: Option<crate::semantic::SemanticSymbolTrace>,
65}
66
67/// Result of tracing a class / enum / store MEMBER: the `--trace FILE:NAME`
68/// fallback when `NAME` is not a top-level export but a member declared on one
69/// (issue #1744). The trace runs on the module graph only, so it reports the
70/// OWNING export's reachability and usage (the gating precondition for
71/// member-level crediting) plus a pointer to the right `--unused-*-members`
72/// command, rather than per-member crediting provenance.
73#[derive(Debug, Serialize)]
74#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
75pub struct ClassMemberTrace {
76    /// The file containing the member.
77    #[serde(serialize_with = "serde_path::serialize")]
78    pub file: PathBuf,
79    /// The member name being traced.
80    pub member_name: String,
81    /// The member kind: `class-method`, `class-property`, `enum-member`,
82    /// `store-member`, or `namespace-member`.
83    pub member_kind: String,
84    /// The export that declares this member (the class / enum / store name).
85    pub owner_export: String,
86    /// Namespace whose references credit the owning export, mirroring
87    /// [`ExportTrace::namespace`] for the export this member is declared on.
88    /// `owner_is_used` and `owner_direct_references` describe that lane, so a
89    /// member of a value export credited only by a bound `import type` reports
90    /// `type` here. `semantic.target.namespace` names the lane the checker
91    /// proof covers and can therefore differ. Producers always emit the field;
92    /// the schema permits omission by payloads created before the owner
93    /// namespace was exposed.
94    #[cfg_attr(feature = "schema", schemars(default))]
95    pub owner_namespace: crate::semantic::SemanticNamespace,
96    /// Whether the owning export is considered used.
97    pub owner_is_used: bool,
98    /// Whether the file is reachable from an entry point.
99    pub owner_file_reachable: bool,
100    /// Whether the file is an entry point.
101    pub owner_is_entry_point: bool,
102    /// Files that reference the owning export directly.
103    pub owner_direct_references: Vec<ExportReference>,
104    /// Re-export chains through which the owning export is reachable. Populated
105    /// so a machine consumer can tell "used via a barrel" (empty direct refs but
106    /// non-empty chains) from "genuinely unreferenced".
107    pub owner_re_export_chains: Vec<ReExportChain>,
108    /// Human-readable reason summary plus the follow-up command to inspect the
109    /// member finding.
110    pub reason: String,
111    /// Exact checker-backed member references when type-aware tracing is enabled.
112    #[serde(default, skip_serializing_if = "Option::is_none")]
113    pub semantic: Option<crate::semantic::SemanticSymbolTrace>,
114}
115
116/// A direct reference to an export.
117#[derive(Debug, Clone, Serialize)]
118#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
119pub struct ExportReference {
120    /// File that contains the reference.
121    #[serde(serialize_with = "serde_path::serialize")]
122    pub from_file: PathBuf,
123    /// Reference kind, such as named import, default import, or re-export.
124    pub kind: String,
125}
126
127/// Direct references that credit one namespace of an export binding.
128#[derive(Debug, Serialize)]
129#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
130pub struct NamespacedExportReferences {
131    /// Credited namespace.
132    pub namespace: SemanticNamespace,
133    /// Number of reachable references in this namespace.
134    pub reference_count: usize,
135    /// Reachable references in deterministic graph order.
136    pub references: Vec<ExportReference>,
137}
138
139/// A re-export chain showing how an export is propagated.
140#[derive(Debug, Serialize)]
141#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
142pub struct ReExportChain {
143    /// The barrel file that re-exports this symbol.
144    #[serde(serialize_with = "serde_path::serialize")]
145    pub barrel_file: PathBuf,
146    /// The name it is re-exported as.
147    pub exported_as: String,
148    /// Number of references on the barrel's re-exported symbol.
149    pub reference_count: usize,
150}
151
152/// Result of tracing all edges for a file.
153#[derive(Debug, Serialize)]
154#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
155pub struct FileTrace {
156    /// The traced file.
157    #[serde(serialize_with = "serde_path::serialize")]
158    pub file: PathBuf,
159    /// Whether this file is reachable from entry points.
160    pub is_reachable: bool,
161    /// Whether this file is an entry point.
162    pub is_entry_point: bool,
163    /// Exports declared by this file.
164    pub exports: Vec<TracedExport>,
165    /// Files that this file imports from.
166    #[serde(serialize_with = "serde_path::serialize_vec")]
167    pub imports_from: Vec<PathBuf>,
168    /// Files that import from this file.
169    #[serde(serialize_with = "serde_path::serialize_vec")]
170    pub imported_by: Vec<PathBuf>,
171    /// Re-exports declared by this file.
172    pub re_exports: Vec<TracedReExport>,
173    /// The configs that make this file an entry point through Module
174    /// Federation `exposes`, one per config. Absent when no Federation config
175    /// exposes the file (issue #2796).
176    #[serde(default, skip_serializing_if = "Vec::is_empty")]
177    pub sources: Vec<TraceSource>,
178}
179
180/// Which configs name which files and which dependency names, collected by one
181/// analysis for the trace output.
182///
183/// It holds plain data, so a trace looks a file up without the rules that
184/// produced it.
185#[derive(Debug, Clone, Default, PartialEq, Eq)]
186pub struct TraceProvenance {
187    /// Root-relative file path and the config that names it.
188    files: Vec<(PathBuf, TraceSource)>,
189    /// Dependency name and the config that names it.
190    dependencies: Vec<(String, TraceSource)>,
191}
192
193impl TraceProvenance {
194    /// Record that `source` names the root-relative `file`.
195    pub fn push_file(&mut self, file: PathBuf, source: TraceSource) {
196        if !self
197            .files
198            .iter()
199            .any(|(known, known_source)| *known == file && *known_source == source)
200        {
201            self.files.push((file, source));
202        }
203    }
204
205    /// Record that `source` names the dependency `name`.
206    pub fn push_dependency(&mut self, name: String, source: TraceSource) {
207        if !self
208            .dependencies
209            .iter()
210            .any(|(known, known_source)| *known == name && *known_source == source)
211        {
212            self.dependencies.push((name, source));
213        }
214    }
215
216    /// The configs that name `file`, a root-relative path.
217    #[must_use]
218    pub fn file_sources(&self, file: &std::path::Path) -> Vec<TraceSource> {
219        self.files
220            .iter()
221            .filter(|(known, _)| known == file)
222            .map(|(_, source)| source.clone())
223            .collect()
224    }
225
226    /// The configs that name the dependency `name`.
227    #[must_use]
228    pub fn dependency_sources(&self, name: &str) -> Vec<TraceSource> {
229        self.dependencies
230            .iter()
231            .filter(|(known, _)| known == name)
232            .map(|(_, source)| source.clone())
233            .collect()
234    }
235}
236
237/// A config that names a traced file or a traced dependency, and the key that
238/// names it.
239#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
240#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
241pub struct TraceSource {
242    /// The mechanism that names the file or the dependency:
243    /// `module-federation`. The set is open.
244    pub kind: String,
245    /// The plugin that read the config, as it labels itself:
246    /// `module-federation` for a standalone `module-federation.config.*`,
247    /// or the bundler plugin (`webpack`, `rspack`, `rsbuild`, `vite`,
248    /// `nextjs`) that read the same options inline from its own config.
249    pub plugin: String,
250    /// The file that names the file or the dependency, relative to the
251    /// project root: the config file, or the source file of a Module
252    /// Federation runtime call.
253    #[serde(serialize_with = "serde_path::serialize")]
254    pub config: PathBuf,
255    /// The config key or the runtime function that names the file or the
256    /// dependency: `exposes` for an exposed file, `remotes` for a remote
257    /// alias, and `registerRemotes`, `loadRemote`, `init` or `createInstance`
258    /// for a remote that a runtime call names. The set is open.
259    pub key: String,
260}
261
262/// An export with usage information.
263#[derive(Debug, Serialize)]
264#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
265pub struct TracedExport {
266    /// Export name.
267    pub name: String,
268    /// Whether the export is type-only.
269    pub is_type_only: bool,
270    /// Number of references to this export.
271    pub reference_count: usize,
272    /// Files that reference this export.
273    pub referenced_by: Vec<ExportReference>,
274}
275
276/// A re-export with source information.
277#[derive(Debug, Serialize)]
278#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
279pub struct TracedReExport {
280    /// Source file being re-exported from.
281    #[serde(serialize_with = "serde_path::serialize")]
282    pub source_file: PathBuf,
283    /// Imported symbol name.
284    pub imported_name: String,
285    /// Exported symbol name.
286    pub exported_name: String,
287}
288
289/// Result of tracing a dependency: where it is used.
290#[derive(Debug, Serialize)]
291#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
292pub struct DependencyTrace {
293    /// The dependency name being traced.
294    pub package_name: String,
295    /// Files that import this dependency.
296    #[serde(serialize_with = "serde_path::serialize_vec")]
297    pub imported_by: Vec<PathBuf>,
298    /// Files that import this dependency with type-only imports.
299    #[serde(serialize_with = "serde_path::serialize_vec")]
300    pub type_only_imported_by: Vec<PathBuf>,
301    /// Whether the dependency is invoked from package.json scripts or CI configs.
302    pub used_in_scripts: bool,
303    /// Whether the dependency is used at all.
304    pub is_used: bool,
305    /// Total import count.
306    pub import_count: usize,
307    /// The configs that declare this name as a Module Federation remote alias
308    /// under `remotes`, one per config. A remote alias is provided by a
309    /// remote container at runtime, not by an npm package. Absent when no
310    /// Federation config declares the name (issue #2796).
311    #[serde(default, skip_serializing_if = "Vec::is_empty")]
312    pub sources: Vec<TraceSource>,
313}
314
315/// Sub-phase attribution inside the entry-point discovery stage.
316///
317/// `PipelineTimings::entry_points_ms` is a single opaque number; these are the
318/// consecutive wall-clock spans that make it up, so a slow discovery stage can
319/// be attributed instead of guessed at. The spans cover the discovery sections
320/// only, so they sum to slightly less than `entry_points_ms`: the summary and
321/// count that follow discovery are not attributed to any span.
322#[derive(Debug, Clone, Copy, Default, Serialize)]
323#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
324pub struct EntryPointSpans {
325    /// Root-package discovery: manual entry globs, root `package.json` fields,
326    /// and the nested `package.json` scan under the conventional monorepo
327    /// directories.
328    pub root_ms: f64,
329    /// Runtime script seed collection plus per-workspace discovery.
330    pub workspaces_ms: f64,
331    /// Plugin entry-point glob compilation and matching.
332    pub plugins_ms: f64,
333    /// The part of `plugins_ms` spent compiling plugin patterns into a glob
334    /// set. Scales with active pattern count, not with project size.
335    pub plugin_glob_build_ms: f64,
336    /// The part of `plugins_ms` spent matching the compiled set against every
337    /// discovered file. Scales with file count times pattern count.
338    pub plugin_glob_match_ms: f64,
339    /// Infrastructure config-file probing at the project root.
340    pub infrastructure_ms: f64,
341    /// Configured `dynamicallyLoaded` glob expansion. Zero when unconfigured.
342    pub dynamic_ms: f64,
343    /// Sorting and deduplicating the merged entry set.
344    pub dedup_ms: f64,
345}
346
347/// Pipeline performance timings.
348#[derive(Debug, Clone, Serialize)]
349#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
350pub struct PipelineTimings {
351    /// Time spent discovering files.
352    pub discover_files_ms: f64,
353    /// Number of discovered files.
354    pub file_count: usize,
355    /// Time spent discovering workspaces.
356    pub workspaces_ms: f64,
357    /// Number of discovered workspaces.
358    pub workspace_count: usize,
359    /// Time spent running plugin discovery.
360    pub plugins_ms: f64,
361    /// Time spent analyzing package scripts and CI configuration.
362    pub script_analysis_ms: f64,
363    /// Wall-clock time spent parsing and extracting modules.
364    pub parse_extract_ms: f64,
365    /// Summed parser CPU time across workers.
366    pub parse_cpu_ms: f64,
367    /// Number of extracted modules.
368    pub module_count: usize,
369    /// Number of files loaded from the parse cache.
370    pub cache_hits: usize,
371    /// Number of files parsed without a cache hit.
372    pub cache_misses: usize,
373    /// Why the persisted parse cache was not reused, when it was not. `None`
374    /// means the cache was loaded; the hit and miss counts then describe how
375    /// much of it applied.
376    #[serde(default, skip_serializing_if = "Option::is_none")]
377    pub cache_rejection: Option<CacheRejection>,
378    /// Why the persisted module-graph cache was not reused, when it was not.
379    #[serde(default, skip_serializing_if = "Option::is_none")]
380    pub graph_cache_rejection: Option<CacheRejection>,
381    /// Time spent updating the parse cache.
382    pub cache_update_ms: f64,
383    /// Time spent categorizing entry points.
384    pub entry_points_ms: f64,
385    /// Sub-phase attribution for `entry_points_ms`.
386    pub entry_point_spans: EntryPointSpans,
387    /// Number of entry points considered.
388    pub entry_point_count: usize,
389    /// Time spent resolving imports.
390    pub resolve_imports_ms: f64,
391    /// Time spent building the module graph.
392    pub build_graph_ms: f64,
393    /// Time spent running analysis.
394    pub analyze_ms: f64,
395    /// Time spent running duplicate-code analysis, when included.
396    #[serde(default, skip_serializing_if = "Option::is_none")]
397    pub duplication_ms: Option<f64>,
398    /// Total pipeline time.
399    pub total_ms: f64,
400}
401
402/// Result of computing the impact closure for a single file as the seed.
403#[derive(Debug, Serialize)]
404#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
405pub struct ImpactClosureTrace {
406    /// The seed file, root-relative.
407    pub seed: String,
408    /// Root-relative paths transitively affected by the seed.
409    pub affected_not_shown: Vec<String>,
410    /// Coordination gaps between the seed and consumers.
411    pub coordination_gap: Vec<ImpactClosureGap>,
412}
413
414/// Wire-version discriminator for [`ImportPathTrace`]. Independent from the
415/// global `SchemaVersion`: the import-path payload versions on its own cadence,
416/// like the other independently-versioned envelopes. Serializes as a string
417/// `const` so JSON consumers can switch on it.
418#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
419#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
420pub enum ImportPathTraceSchemaVersion {
421    /// First release of the `fallow trace --path` shape.
422    #[serde(rename = "1")]
423    V1,
424}
425
426/// Result of asking how one module reaches another: the shortest import path.
427///
428/// `reachable` is the only field that separates "no route exists" from "the
429/// route is empty because both ends are the same module". Both report
430/// `hops: 0`, so a consumer must read `reachable`, never the hop count.
431#[derive(Debug, Serialize)]
432#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
433#[cfg_attr(feature = "schema", schemars(title = "fallow trace --path"))]
434pub struct ImportPathTrace {
435    /// Wire-shape version of this payload.
436    pub schema_version: ImportPathTraceSchemaVersion,
437    /// The module the walk started from, root-relative.
438    pub from: String,
439    /// The module the walk was looking for, root-relative.
440    pub to: String,
441    /// Whether `to` is reachable from `from` by following import edges.
442    pub reachable: bool,
443    /// Number of import edges on the reported route. `0` both when the two ends
444    /// are the same module and when there is no route at all.
445    pub hops: usize,
446    /// The route, in import order. Empty whenever `hops` is `0`.
447    pub path: Vec<ImportPathHop>,
448    /// Human-readable summary of the outcome.
449    pub reason: String,
450}
451
452/// One import edge on an [`ImportPathTrace`].
453#[derive(Debug, Serialize, PartialEq, Eq)]
454#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
455pub struct ImportPathHop {
456    /// The importing module, root-relative.
457    pub from: String,
458    /// The imported module, root-relative.
459    pub to: String,
460    /// Whether every symbol on this edge is type-only, so the hop is erased at
461    /// build time. Type-only hops are reported, never skipped: an `import type`
462    /// chain is a real compile-time coupling.
463    pub type_only: bool,
464    /// 1-based line in `from` of the imported binding that creates this edge:
465    /// the first value-carrying symbol on the import, or the first symbol when
466    /// every symbol is type-only. On a multi-line import that is the binding's
467    /// own line, not the `import` keyword's. Absent when the edge carries no
468    /// span or the source could not be read.
469    #[serde(default, skip_serializing_if = "Option::is_none")]
470    pub import_line: Option<u32>,
471}
472
473/// One coordination-gap entry in an [`ImpactClosureTrace`].
474#[derive(Debug, Serialize)]
475#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
476pub struct ImpactClosureGap {
477    /// Root-relative path of the consumer module.
478    pub consumer_file: String,
479    /// Exported symbol names the consumer references.
480    pub consumed_symbols: Vec<String>,
481    /// Scope note for the syntactic trace.
482    pub note: String,
483}
484
485/// Result of tracing a clone: all groups containing the code at a source
486/// location or addressed by a stable clone fingerprint.
487#[derive(Debug, Serialize)]
488#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
489pub struct CloneTrace {
490    /// File passed to the trace request, root-relative when a group matches.
491    #[serde(serialize_with = "serde_path::serialize")]
492    pub file: PathBuf,
493    /// 1-based line passed to the trace request or representative group line.
494    pub line: usize,
495    /// The matched clone instance, if one exists.
496    pub matched_instance: Option<CloneInstance>,
497    /// Clone groups matched by the trace request.
498    pub clone_groups: Vec<TracedCloneGroup>,
499}
500
501/// One clone group returned from a clone trace request.
502#[derive(Debug, Serialize)]
503#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
504pub struct TracedCloneGroup {
505    /// Stable content fingerprint, usually `dup:<8hex>` and widened on rare
506    /// report collisions.
507    pub fingerprint: String,
508    /// Number of tokens in the duplicated block.
509    pub token_count: usize,
510    /// Number of lines in the duplicated block.
511    pub line_count: usize,
512    /// Maximum directory-tree or same-file line distance between instances.
513    pub spread: usize,
514    /// Lowest all-pairs similarity for a near-miss clone group.
515    #[serde(default, skip_serializing_if = "Option::is_none")]
516    #[cfg_attr(feature = "schema", schemars(with = "f64"))]
517    pub similarity: Option<f64>,
518    /// Root-relative clone instances in this group.
519    pub instances: Vec<CloneInstance>,
520    /// Group-level refactoring suggestion.
521    pub suggestion: RefactoringSuggestion,
522    /// Best-effort name for the extracted function. Advisory only.
523    #[serde(default, skip_serializing_if = "Option::is_none")]
524    pub suggested_name: Option<String>,
525}