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