Skip to main content

fallow_engine/
trace_impl.rs

1use std::path::{Path, PathBuf};
2
3use fallow_types::discover::FileId;
4use fallow_types::trace::{
5    ClassMemberTrace, CloneTrace, DependencyTrace, ExportReference, ExportTrace, FileTrace,
6    ImpactClosureGap, ImpactClosureTrace, ImportPathHop, ImportPathTrace,
7    ImportPathTraceSchemaVersion, PeerClosureSeeds, ReExportChain, SearchGapReason, ToolingCredit,
8    TracedCloneGroup, TracedExport, TracedReExport,
9};
10use rustc_hash::{FxHashMap, FxHashSet};
11
12use super::trace_export_references::{crediting_export_references, implicit_default_references};
13use crate::duplicates::{
14    CloneFingerprintSet, CloneGroup, CloneInstance, DuplicationReport, dominant_identifier,
15    group_refactoring_suggestion,
16};
17use crate::graph::{
18    ExportNamespace, ImportPathHop as GraphImportPathHop, ModuleGraph, ModuleNode, ReferenceKind,
19};
20use crate::search_visibility::{SearchCheck, SearchTarget, SourceCache};
21
22/// Match exact module paths before considering abbreviated suffixes.
23///
24/// A root-relative `src/a.ts` must not select `packages/x/src/a.ts` merely
25/// because discovery listed that module first. Suffix matches remain useful
26/// for abbreviated requests, but callers must preserve their ambiguity.
27pub fn matching_module_indexes(graph: &ModuleGraph, root: &Path, user_path: &str) -> Vec<usize> {
28    let normalized = user_path.replace('\\', "/");
29    // The root-relative forms are joined once, so each module costs a path
30    // comparison instead of a `strip_prefix` component walk.
31    let exact_targets: Vec<PathBuf> = [
32        Some(root.join(&normalized)),
33        dunce::canonicalize(root)
34            .ok()
35            .map(|canonical_root| canonical_root.join(&normalized)),
36        dunce::canonicalize(root.join(&normalized)).ok(),
37    ]
38    .into_iter()
39    .flatten()
40    .collect();
41    let mut exact = Vec::new();
42    let mut suffix = Vec::new();
43    let suffix_pattern = format!("/{normalized}");
44    for (index, module) in graph.modules().iter().enumerate() {
45        let module_path = forward_slash_path(&module.path);
46        let is_exact = module_path == normalized || exact_targets.contains(&module.path);
47        if is_exact {
48            exact.push(index);
49        } else if module_path.ends_with(&suffix_pattern) {
50            suffix.push(index);
51        }
52    }
53    if exact.is_empty() { suffix } else { exact }
54}
55
56/// Render a path with forward slashes. Borrows when no rewrite is needed, so
57/// the per-module comparison in a lookup does not allocate on Unix.
58fn forward_slash_path(path: &Path) -> std::borrow::Cow<'_, str> {
59    let lossy = path.to_string_lossy();
60    if lossy.contains('\\') {
61        std::borrow::Cow::Owned(lossy.replace('\\', "/"))
62    } else {
63        lossy
64    }
65}
66
67/// Module paths indexed once for callers that resolve many user paths
68/// against one graph.
69///
70/// [`ModulePathLookup::matching`] returns the same indexes, in graph order, as
71/// [`matching_module_indexes`]. A single lookup does not need this index; a
72/// loop over many references would otherwise scan every module per reference.
73struct ModulePathLookup<'g> {
74    graph: &'g ModuleGraph,
75    root: &'g Path,
76    canonical_root: Option<PathBuf>,
77    /// Component-normalized, forward-slash module path to module indexes.
78    by_path: FxHashMap<String, Vec<usize>>,
79    /// Last path segment to module indexes, for suffix matches.
80    by_file_name: FxHashMap<String, Vec<usize>>,
81}
82
83impl<'g> ModulePathLookup<'g> {
84    fn new(graph: &'g ModuleGraph, root: &'g Path) -> Self {
85        let mut by_path: FxHashMap<String, Vec<usize>> = FxHashMap::default();
86        let mut by_file_name: FxHashMap<String, Vec<usize>> = FxHashMap::default();
87        for (index, module) in graph.modules().iter().enumerate() {
88            by_path
89                .entry(path_key(&module.path))
90                .or_default()
91                .push(index);
92            let module_path = forward_slash_path(&module.path);
93            let file_name = module_path.rsplit('/').next().unwrap_or_default();
94            by_file_name
95                .entry(file_name.to_owned())
96                .or_default()
97                .push(index);
98        }
99        Self {
100            graph,
101            root,
102            canonical_root: dunce::canonicalize(root).ok(),
103            by_path,
104            by_file_name,
105        }
106    }
107
108    fn matching(&self, user_path: &str) -> Vec<usize> {
109        let normalized = user_path.replace('\\', "/");
110        let joined = self.root.join(&normalized);
111        let mut targets = vec![path_key(Path::new(&normalized)), path_key(&joined)];
112        if let Some(canonical_root) = &self.canonical_root {
113            targets.push(path_key(&canonical_root.join(&normalized)));
114        }
115        if let Ok(canonical_target) = dunce::canonicalize(&joined) {
116            targets.push(path_key(&canonical_target));
117        }
118        let mut exact: Vec<usize> = targets
119            .iter()
120            .filter_map(|target| self.by_path.get(target))
121            .flatten()
122            .copied()
123            .collect();
124        if !exact.is_empty() {
125            exact.sort_unstable();
126            exact.dedup();
127            return exact;
128        }
129        let suffix_pattern = format!("/{normalized}");
130        let file_name = normalized.rsplit('/').next().unwrap_or_default();
131        self.by_file_name
132            .get(file_name)
133            .into_iter()
134            .flatten()
135            .copied()
136            .filter(|&index| {
137                forward_slash_path(&self.graph.modules()[index].path).ends_with(&suffix_pattern)
138            })
139            .collect()
140    }
141}
142
143/// A path rendered from its components with forward slashes, so paths that
144/// `Path` equality treats as equal get the same key.
145fn path_key(path: &Path) -> String {
146    forward_slash_path(&path.components().collect::<PathBuf>()).into_owned()
147}
148
149/// Find the module for a user path.
150///
151/// An exact match wins. Otherwise the first suffix match in graph order wins,
152/// so an abbreviated path keeps its earlier behaviour.
153pub fn find_module<'a>(
154    graph: &'a ModuleGraph,
155    root: &Path,
156    user_path: &str,
157) -> Option<&'a ModuleNode> {
158    matching_module_indexes(graph, root, user_path)
159        .first()
160        .map(|&index| &graph.modules()[index])
161}
162
163/// Reconcile checker-backed reference evidence with the retained graph's
164/// entry-point reachability. Evidence from unreachable files remains visible,
165/// but cannot produce a complete `references-found` assertion.
166pub fn reconcile_semantic_trace_reachability(
167    graph: &ModuleGraph,
168    root: &Path,
169    target_reachable: bool,
170    trace: &mut fallow_types::semantic::SemanticSymbolTrace,
171) {
172    if trace.assertion != "references-found" || trace.references.is_empty() {
173        return;
174    }
175    let has_reachable_reference = target_reachable && {
176        let lookup = ModulePathLookup::new(graph, root);
177        trace.references.iter().any(|reference| {
178            lookup
179                .matching(&reference.path.to_string_lossy())
180                .iter()
181                .any(|&index| graph.modules()[index].is_reachable())
182        })
183    };
184    if has_reachable_reference {
185        return;
186    }
187
188    trace.assertion = "references-only-in-unreachable-files".to_string();
189    trace.status = fallow_types::semantic::SemanticCompleteness::Partial;
190    trace.identity.completeness = fallow_types::semantic::SemanticCompleteness::Partial;
191    let action =
192        "Review the unreachable consumer files before removing this declaration.".to_string();
193    if !trace.actions.contains(&action) {
194        trace.actions.push(action);
195    }
196}
197
198/// Map a reference's `from_file` id to a root-relative [`ExportReference`].
199pub(super) fn reference_to_export_reference(
200    graph: &ModuleGraph,
201    root: &Path,
202    r: &crate::graph::SymbolReference,
203) -> ExportReference {
204    let from_path = graph.module(r.from_file).map_or_else(
205        || PathBuf::from(format!("<unknown:{}>", r.from_file.0)),
206        |m| m.path.strip_prefix(root).unwrap_or(&m.path).to_path_buf(),
207    );
208    ExportReference::new(from_path, format_reference_kind(r.kind))
209}
210
211/// Project graph-owned effective routes into the public trace contract.
212fn collect_re_export_chains(
213    graph: &ModuleGraph,
214    root: &Path,
215    target_file_id: crate::discover::FileId,
216    export_name: &str,
217    namespace: ExportNamespace,
218) -> Vec<ReExportChain> {
219    graph
220        .effective_re_export_routes(target_file_id, export_name, namespace)
221        .into_iter()
222        .filter_map(|route| {
223            let module = graph.module(route.barrel_file())?;
224            Some(ReExportChain {
225                barrel_file: relative_module_path(&module.path, root),
226                exported_as: route.exported_name().to_string(),
227                reference_count: graph
228                    .effective_export_surface_references(
229                        route.barrel_file(),
230                        route.exported_name(),
231                        namespace,
232                    )
233                    .into_iter()
234                    .filter(|reference| {
235                        graph
236                            .modules()
237                            .get(reference.from_file.0 as usize)
238                            .is_some_and(crate::graph::ModuleNode::is_reachable)
239                    })
240                    .count(),
241            })
242        })
243        .collect()
244}
245
246/// Trace why an export is considered used or unused.
247#[must_use]
248pub fn trace_export(
249    graph: &ModuleGraph,
250    root: &Path,
251    file_path: &str,
252    export_name: &str,
253) -> Option<ExportTrace> {
254    let module = find_module(graph, root, file_path)?;
255
256    let star_export_ambiguity = super::trace_export_reason::trace_star_export_ambiguity(
257        graph,
258        root,
259        module.file_id,
260        export_name,
261    );
262    let Some(surface) = select_export(graph, module, export_name) else {
263        let ambiguity = star_export_ambiguity?;
264        let namespace = ambiguity.namespaces.first().copied().unwrap_or_default();
265        return Some(ExportTrace {
266            file: relative_module_path(&module.path, root),
267            export_name: export_name.to_string(),
268            namespace,
269            file_reachable: module.is_reachable(),
270            is_entry_point: module.is_entry_point(),
271            is_used: false,
272            direct_references: Vec::new(),
273            direct_references_by_namespace: Vec::new(),
274            star_export_ambiguity: Some(ambiguity),
275            re_export_chains: Vec::new(),
276            plugin_credits: Vec::new(),
277            kept_by_tag: None,
278            kept_by_signature: None,
279            reason: "Star re-export collision makes this name ambiguous".to_string(),
280            semantic: None,
281        });
282    };
283    let implicit_component_default = surface.export().is_none()
284        && surface.binding().is_implicit_default()
285        && surface.binding().origin_file() == module.file_id;
286    let (namespace, direct_references, direct_references_by_namespace) =
287        if implicit_component_default {
288            (
289                ExportNamespace::Value,
290                implicit_default_references(graph, root, module.file_id),
291                Vec::new(),
292            )
293        } else {
294            crediting_export_references(graph, root, module.file_id, export_name, surface)
295        };
296
297    let re_export_chains =
298        collect_re_export_chains(graph, root, module.file_id, export_name, namespace);
299
300    let verdict = super::trace_export_reason::export_verdict(
301        module,
302        (export_name, namespace),
303        super::trace_export_reason::ExportCredit {
304            reference_count: direct_references.len(),
305            implicit_component_default,
306        },
307        &re_export_chains,
308        star_export_ambiguity.is_some(),
309    );
310    let (is_used, kept_by_tag, reason) = (verdict.is_used, verdict.kept_by_tag, verdict.reason);
311
312    Some(ExportTrace {
313        file: relative_module_path(&module.path, root),
314        export_name: export_name.to_string(),
315        namespace: match namespace {
316            ExportNamespace::Type => fallow_types::semantic::SemanticNamespace::Type,
317            ExportNamespace::Value => fallow_types::semantic::SemanticNamespace::Value,
318        },
319        file_reachable: module.is_reachable(),
320        is_entry_point: module.is_entry_point(),
321        is_used,
322        direct_references,
323        direct_references_by_namespace,
324        star_export_ambiguity,
325        re_export_chains,
326        plugin_credits: Vec::new(),
327        kept_by_tag: kept_by_tag.map(str::to_owned),
328        kept_by_signature: None,
329        reason,
330        semantic: None,
331    })
332}
333
334/// The root-relative path of a module, or the path as it is outside `root`.
335pub(super) fn relative_module_path(path: &Path, root: &Path) -> PathBuf {
336    path.strip_prefix(root).unwrap_or(path).to_path_buf()
337}
338
339/// Resolve the exact source identity required by the semantic sidecar for a
340/// graph export. This does not perform semantic analysis itself.
341#[must_use]
342pub fn semantic_symbol_for_export(
343    graph: &ModuleGraph,
344    root: &Path,
345    file_path: &str,
346    export_name: &str,
347) -> Option<fallow_types::semantic::SemanticSymbol> {
348    use fallow_types::semantic::{SemanticNamespace, SemanticSymbol};
349
350    let module = find_module(graph, root, file_path)?;
351    let surface = select_export(graph, module, export_name)?;
352    let namespace = surface.namespace();
353    let (identity_module, span, identity_exported_name, local_name) = if let Some(re_export) =
354        graph.effective_export_surface_re_export(module.file_id, export_name, namespace)
355    {
356        let local_name = if re_export.imported_name == "*" {
357            export_name
358        } else {
359            re_export.imported_name.as_str()
360        };
361        (module, re_export.span, export_name, local_name)
362    } else {
363        let origin = surface.origin()?;
364        let origin_module = graph.module(origin.file_id())?;
365        let origin_export = origin.export();
366        let origin_name = match &origin_export.name {
367            fallow_types::extract::ExportName::Named(name) => name.as_str(),
368            fallow_types::extract::ExportName::Default => "default",
369        };
370        (origin_module, origin_export.span, origin_name, origin_name)
371    };
372    let source = std::fs::read_to_string(&identity_module.path).ok()?;
373    let offsets = fallow_types::extract::compute_line_offsets(&source);
374    let (line, col) = fallow_types::extract::byte_offset_to_line_col(&offsets, span.start);
375    Some(SemanticSymbol {
376        path: identity_module
377            .path
378            .strip_prefix(root)
379            .unwrap_or(&identity_module.path)
380            .to_path_buf(),
381        namespace: match namespace {
382            ExportNamespace::Type => SemanticNamespace::Type,
383            ExportNamespace::Value => SemanticNamespace::Value,
384        },
385        declaration_kind: "export".to_string(),
386        exported_name: identity_exported_name.to_string(),
387        local_name: local_name.to_string(),
388        owner: None,
389        line,
390        col,
391    })
392}
393
394/// Resolve the source identity for a public class member semantic query.
395#[must_use]
396pub fn semantic_symbol_for_class_member(
397    graph: &ModuleGraph,
398    root: &Path,
399    file_path: &str,
400    member_name: &str,
401) -> Option<fallow_types::semantic::SemanticSymbol> {
402    use fallow_types::extract::MemberKind;
403    use fallow_types::semantic::{SemanticNamespace, SemanticSymbol};
404
405    let module = find_module(graph, root, file_path)?;
406    let (owner, member) = module
407        .exports
408        .iter()
409        .filter_map(|export| {
410            export
411                .members
412                .iter()
413                .find(|member| member.name == member_name)
414                .map(|member| (export, member))
415        })
416        .max_by_key(|(export, _)| (!export.references.is_empty(), !export.is_type_only))?;
417    let declaration_kind = match member.kind {
418        MemberKind::ClassMethod => "class_method",
419        MemberKind::ClassProperty => "class_property",
420        _ => return None,
421    };
422    let source = std::fs::read_to_string(&module.path).ok()?;
423    let offsets = fallow_types::extract::compute_line_offsets(&source);
424    let (line, col) = fallow_types::extract::byte_offset_to_line_col(&offsets, member.span.start);
425    Some(SemanticSymbol {
426        path: relative_module_path(&module.path, root),
427        namespace: SemanticNamespace::Value,
428        declaration_kind: declaration_kind.to_string(),
429        exported_name: member_name.to_string(),
430        local_name: member_name.to_string(),
431        owner: Some(owner.name.to_string()),
432        line,
433        col,
434    })
435}
436
437/// Stable reason why an exact class-method target cannot be resolved.
438#[derive(Debug, Clone, Copy, PartialEq, Eq)]
439pub enum SemanticClassMethodResolutionError {
440    /// The requested file is not part of the retained module graph.
441    FileNotFound,
442    /// The requested owner or method does not exist in the file.
443    SymbolNotFound,
444    /// More than one declaration matches the exact owner and method.
445    AmbiguousSymbol,
446    /// The matching declaration is not a supported class method.
447    UnsupportedSyntax,
448}
449
450impl std::fmt::Display for SemanticClassMethodResolutionError {
451    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
452        let reason = match self {
453            Self::FileNotFound => "file-not-found",
454            Self::SymbolNotFound => "unknown-symbol",
455            Self::AmbiguousSymbol => "ambiguous-symbol",
456            Self::UnsupportedSyntax => "unsupported-syntax",
457        };
458        formatter.write_str(reason)
459    }
460}
461
462/// Resolve one exact exported class method without a name-based fallback.
463pub fn semantic_symbol_for_exact_class_method(
464    graph: &ModuleGraph,
465    root: &Path,
466    file_path: &str,
467    owner_name: &str,
468    member_name: &str,
469) -> Result<fallow_types::semantic::SemanticSymbol, SemanticClassMethodResolutionError> {
470    use fallow_types::extract::MemberKind;
471    use fallow_types::semantic::{SemanticNamespace, SemanticSymbol};
472
473    let module = find_module(graph, root, file_path)
474        .ok_or(SemanticClassMethodResolutionError::FileNotFound)?;
475    let mut owners = module
476        .exports
477        .iter()
478        .filter(|export| export.name.matches_str(owner_name));
479    let owner = owners
480        .next()
481        .ok_or(SemanticClassMethodResolutionError::SymbolNotFound)?;
482    if owners.next().is_some() {
483        return Err(SemanticClassMethodResolutionError::AmbiguousSymbol);
484    }
485    let mut members = owner
486        .members
487        .iter()
488        .filter(|member| member.name == member_name);
489    let member = members
490        .next()
491        .ok_or(SemanticClassMethodResolutionError::SymbolNotFound)?;
492    if members.next().is_some() {
493        return Err(SemanticClassMethodResolutionError::AmbiguousSymbol);
494    }
495    if member.kind != MemberKind::ClassMethod {
496        return Err(SemanticClassMethodResolutionError::UnsupportedSyntax);
497    }
498    let source = std::fs::read_to_string(&module.path)
499        .map_err(|_| SemanticClassMethodResolutionError::SymbolNotFound)?;
500    let offsets = fallow_types::extract::compute_line_offsets(&source);
501    let (line, col) = fallow_types::extract::byte_offset_to_line_col(&offsets, member.span.start);
502    Ok(SemanticSymbol {
503        path: relative_module_path(&module.path, root),
504        namespace: SemanticNamespace::Value,
505        declaration_kind: "class_method".to_string(),
506        exported_name: member_name.to_string(),
507        local_name: member_name.to_string(),
508        owner: Some(owner_name.to_string()),
509        line,
510        col,
511    })
512}
513
514/// Trace a class / enum / store MEMBER when `--trace FILE:NAME`'s `NAME` is not
515/// a top-level export but a member declared on one (issue #1744). Runs on the
516/// graph only, so it reports the OWNING export's reachability and usage (the
517/// gating precondition for member crediting) plus a pointer to the right
518/// `--unused-*-members` command, not per-member crediting provenance.
519#[must_use]
520pub fn trace_class_member(
521    graph: &ModuleGraph,
522    root: &Path,
523    file_path: &str,
524    member_name: &str,
525) -> Option<ClassMemberTrace> {
526    use fallow_types::extract::MemberKind;
527
528    let module = find_module(graph, root, file_path)?;
529
530    // Find the export that declares this member. When several declare a member
531    // of the same name (rare), prefer a used, non-type-only owner so the trace
532    // reports the reachable one.
533    let (owner, member_kind, is_protected) = module
534        .exports
535        .iter()
536        .filter_map(|export| {
537            export
538                .members
539                .iter()
540                .find(|member| member.name == member_name)
541                .map(|member| (export, member.kind, member.is_protected))
542        })
543        .max_by_key(|(export, _, _)| (!export.references.is_empty(), !export.is_type_only))?;
544
545    let owner_name = owner.name.to_string();
546    // Reuse the export trace to compute the owner's reachability / usage /
547    // references consistently with a plain `--trace FILE:OWNER`. The `?` here is
548    // a belt-and-suspenders guard: `owner` was just located in this module's
549    // `exports`, so `trace_export` resolves it in practice; the fallthrough to
550    // `None` (and the caller's "not found" error) is unreachable barring a graph
551    // inconsistency.
552    let owner_trace = trace_export(graph, root, file_path, &owner_name)?;
553
554    let class_filter = if is_protected {
555        "--unused-protected-class-members"
556    } else {
557        "--unused-class-members"
558    };
559    let (kind_str, filter_flag) = match member_kind {
560        MemberKind::ClassMethod => ("class-method", Some(class_filter)),
561        MemberKind::ClassProperty => ("class-property", Some(class_filter)),
562        MemberKind::EnumMember => ("enum-member", Some("--unused-enum-members")),
563        MemberKind::StoreMember => ("store-member", Some("--unused-store-members")),
564        MemberKind::NamespaceMember => ("namespace-member", Some("--unused-namespace-members")),
565    };
566
567    let reason = class_member_trace_reason(
568        member_name,
569        &owner_name,
570        kind_str,
571        filter_flag,
572        file_path,
573        &owner_trace,
574    );
575
576    Some(ClassMemberTrace {
577        file: owner_trace.file,
578        member_name: member_name.to_string(),
579        member_kind: kind_str.to_string(),
580        owner_export: owner_name,
581        owner_namespace: owner_trace.namespace,
582        owner_is_used: owner_trace.is_used,
583        owner_file_reachable: owner_trace.file_reachable,
584        owner_is_entry_point: owner_trace.is_entry_point,
585        owner_direct_references: owner_trace.direct_references,
586        owner_re_export_chains: owner_trace.re_export_chains,
587        reason,
588        semantic: None,
589    })
590}
591
592/// Build the human-readable reason for a class-member trace, keyed on the
593/// owner's reachability / usage (the precondition that gates member crediting).
594fn class_member_trace_reason(
595    member_name: &str,
596    owner_name: &str,
597    kind_str: &str,
598    filter_flag: Option<&str>,
599    file_path: &str,
600    owner_trace: &ExportTrace,
601) -> String {
602    let head =
603        format!("'{member_name}' is a {kind_str} of '{owner_name}', not a top-level export. ");
604    let body = if !owner_trace.file_reachable {
605        format!(
606            "The file is not reachable from any entry point, so '{owner_name}' and all its \
607             members are dead (see the unused-file finding)."
608        )
609    } else if !owner_trace.is_used {
610        format!(
611            "'{owner_name}' is reachable but referenced by no file, so it is reported as an \
612             unused export and its members are not judged individually."
613        )
614    } else {
615        let refs = owner_trace.direct_references.len();
616        match filter_flag {
617            Some(flag) => format!(
618                "'{owner_name}' is used by {refs} file(s); whether '{member_name}' itself is \
619                 flagged depends on cross-file member-access resolution. Run \
620                 `fallow dead-code {flag} --file {file_path}` to see the member finding."
621            ),
622            None => format!(
623                "'{owner_name}' is used by {refs} file(s); '{member_name}' is credited through \
624                 its namespace export."
625            ),
626        }
627    };
628    format!("{head}{body}")
629}
630
631fn select_export<'graph>(
632    graph: &'graph ModuleGraph,
633    module: &'graph crate::graph::ModuleNode,
634    export_name: &str,
635) -> Option<crate::graph::EffectiveExportSurface<'graph>> {
636    [ExportNamespace::Value, ExportNamespace::Type]
637        .into_iter()
638        .find_map(|namespace| {
639            graph.effective_export_surface(module.file_id, export_name, namespace)
640        })
641}
642
643/// Map a module's exports to [`TracedExport`] entries with relativized references.
644fn traced_exports(
645    graph: &ModuleGraph,
646    root: &Path,
647    module: &crate::graph::ModuleNode,
648) -> Vec<TracedExport> {
649    module
650        .exports
651        .iter()
652        .map(|e| {
653            let referenced_by: Vec<_> = e
654                .physical_references()
655                .map(|r| reference_to_export_reference(graph, root, r))
656                .collect();
657            TracedExport {
658                name: e.name.to_string(),
659                is_type_only: e.is_type_only,
660                reference_count: referenced_by.len(),
661                referenced_by,
662                plugin_credits: Vec::new(),
663            }
664        })
665        .collect()
666}
667
668/// Collect the root-relative paths a file imports from (forward graph edges).
669fn traced_imports_from(
670    graph: &ModuleGraph,
671    root: &Path,
672    module: &crate::graph::ModuleNode,
673) -> Vec<PathBuf> {
674    graph
675        .edges_for(module.file_id)
676        .iter()
677        .filter_map(|target_id| {
678            graph
679                .modules()
680                .get(target_id.0 as usize)
681                .map(|m| m.path.strip_prefix(root).unwrap_or(&m.path).to_path_buf())
682        })
683        .collect()
684}
685
686/// Collect the root-relative paths that import a file (reverse graph edges).
687fn traced_imported_by(
688    graph: &ModuleGraph,
689    root: &Path,
690    module: &crate::graph::ModuleNode,
691) -> Vec<PathBuf> {
692    graph
693        .reverse_deps
694        .get(module.file_id.0 as usize)
695        .map(|deps| {
696            deps.iter()
697                .filter_map(|fid| {
698                    graph
699                        .modules()
700                        .get(fid.0 as usize)
701                        .map(|m| m.path.strip_prefix(root).unwrap_or(&m.path).to_path_buf())
702                })
703                .collect()
704        })
705        .unwrap_or_default()
706}
707
708/// Map a module's re-exports to [`TracedReExport`] entries with relativized source paths.
709fn traced_re_exports(
710    graph: &ModuleGraph,
711    root: &Path,
712    module: &crate::graph::ModuleNode,
713) -> Vec<TracedReExport> {
714    module
715        .re_exports
716        .iter()
717        .map(|re| {
718            let source_path = graph.module(re.source_file).map_or_else(
719                || PathBuf::from(format!("<unknown:{}>", re.source_file.0)),
720                |m| m.path.strip_prefix(root).unwrap_or(&m.path).to_path_buf(),
721            );
722            TracedReExport {
723                source_file: source_path,
724                imported_name: re.imported_name.clone(),
725                exported_name: re.exported_name.clone(),
726            }
727        })
728        .collect()
729}
730
731/// Trace all edges for a file.
732#[must_use]
733pub fn trace_file(graph: &ModuleGraph, root: &Path, file_path: &str) -> Option<FileTrace> {
734    let module = find_module(graph, root, file_path)?;
735
736    Some(FileTrace {
737        file: relative_module_path(&module.path, root),
738        is_reachable: module.is_reachable(),
739        is_entry_point: module.is_entry_point(),
740        exports: traced_exports(graph, root, module),
741        imports_from: traced_imports_from(graph, root, module),
742        imported_by: traced_imported_by(graph, root, module),
743        re_exports: traced_re_exports(graph, root, module),
744        ..FileTrace::default()
745    })
746}
747
748/// The packages that the dependency trace credits although no file imports
749/// them.
750pub struct DependencyCredit<'a> {
751    /// The packages that scripts, CI configs and git hooks run.
752    pub script_used_packages: &'a FxHashSet<String>,
753    /// The packages that start the peer-dependency closures in addition to
754    /// the imported packages.
755    pub peer_seeds: &'a PeerClosureSeeds,
756}
757
758/// Trace where a dependency is used.
759///
760/// `script_used_packages` carries the package names recorded as binary invocations
761/// in package.json scripts (`build: microbundle ...`) and CI configs
762/// (`.github/workflows/*.yml`, `.gitlab-ci.yml`). The same set the unused-deps
763/// detector consults; passing it in lets the trace output match the detector's
764/// view of "used" instead of reporting `is_used=false` for tools invoked only
765/// through scripts. `ignore_patterns` hide workspace manifests from the peer
766/// closure, as in the unused-dependency check.
767#[must_use]
768pub fn trace_dependency(
769    graph: &ModuleGraph,
770    root: &Path,
771    workspace_roots: &[&Path],
772    ignore_patterns: &fallow_config::IgnorePatternSet,
773    package_name: &str,
774    credit: &DependencyCredit<'_>,
775) -> DependencyTrace {
776    let (imported_by, type_only_imported_by) = package_importers(graph, root, package_name);
777
778    let import_count = imported_by.len();
779    let used_in_scripts = credit.script_used_packages.contains(package_name);
780    let peer_of = crate::core_backend::peer_dependency_hosts(
781        graph,
782        root,
783        workspace_roots,
784        ignore_patterns,
785        package_name,
786        credit.peer_seeds,
787    );
788    let mut trace = DependencyTrace {
789        package_name: package_name.to_string(),
790        imported_by,
791        type_only_imported_by,
792        used_in_scripts,
793        is_used: import_count > 0 || used_in_scripts || !peer_of.is_empty(),
794        import_count,
795        peer_of,
796        sources: Vec::new(),
797        tooling_credit: None,
798        unused_in: Vec::new(),
799        usage: None,
800    };
801    trace.apply_tooling_credit(imported_types_target_credit(graph, package_name));
802    trace
803}
804
805/// The files that import `package_name`, each listed once, and the subset
806/// whose every import of the package is type-only.
807///
808/// The graph records one usage entry per import, so a file with two imports
809/// of the package appears twice. A file with a type-only import and a value
810/// import is not a type-only importer.
811fn package_importers(
812    graph: &ModuleGraph,
813    root: &Path,
814    package_name: &str,
815) -> (Vec<PathBuf>, Vec<PathBuf>) {
816    let counts = |usage: &FxHashMap<String, Vec<FileId>>| {
817        let mut counts: FxHashMap<FileId, usize> = FxHashMap::default();
818        for &fid in usage.get(package_name).into_iter().flatten() {
819            *counts.entry(fid).or_default() += 1;
820        }
821        counts
822    };
823    let mut all = counts(&graph.package_usage);
824    let type_only = counts(&graph.type_only_package_usage);
825    let mut imported_by = Vec::new();
826    let mut type_only_imported_by = Vec::new();
827    for &fid in graph.package_usage.get(package_name).into_iter().flatten() {
828        // The first entry of a file takes its count, so a repeat finds none.
829        let Some(total) = all.remove(&fid) else {
830            continue;
831        };
832        let Some(module) = graph.module(fid) else {
833            continue;
834        };
835        let path = relative_module_path(&module.path, root);
836        if type_only.get(&fid) == Some(&total) {
837            type_only_imported_by.push(path.clone());
838        }
839        imported_by.push(path);
840    }
841    (imported_by, type_only_imported_by)
842}
843
844/// The credit of a `@types/X` package whose target `X` the code imports, as
845/// the unused devDependency check gives it.
846fn imported_types_target_credit(graph: &ModuleGraph, package_name: &str) -> Option<ToolingCredit> {
847    let target = crate::core_backend::types_package_target(package_name)?;
848    graph
849        .package_usage
850        .get(target.as_str())
851        .is_some_and(|ids| !ids.is_empty())
852        .then(|| ToolingCredit {
853            reason: "types-target".to_string(),
854            plugin: None,
855            config: None,
856            reference: Some(target),
857        })
858}
859
860pub(super) fn format_reference_kind(kind: ReferenceKind) -> String {
861    match kind {
862        ReferenceKind::NamedImport => "named import".to_string(),
863        ReferenceKind::DefaultImport => "default import".to_string(),
864        ReferenceKind::NamespaceImport => "namespace import".to_string(),
865        ReferenceKind::ReExport => "re-export".to_string(),
866        ReferenceKind::DynamicImport => "dynamic import".to_string(),
867        ReferenceKind::SideEffectImport => "side-effect import".to_string(),
868    }
869}
870
871/// Compute the impact closure for a single file as the seed.
872///
873/// Resolves `file_path` to a graph `FileId`, walks `reverse_deps` + re-export
874/// chains to the transitive affected set, and reports the coordination gap (the
875/// seed's exported contracts consumed by modules outside the seed). Returns
876/// `None` when the file is not in the module graph.
877///
878/// Each coordination gap carries the literal-search check, so this reads the
879/// source of each consumer of the seed exports.
880#[must_use]
881pub fn trace_impact_closure(
882    graph: &ModuleGraph,
883    root: &Path,
884    file_path: &str,
885) -> Option<ImpactClosureTrace> {
886    impact_closure_trace(graph, root, file_path, true)
887}
888
889/// Compute the impact closure like [`trace_impact_closure`], without the
890/// literal-search check. The coordination gaps have no search fields, and no
891/// consumer source is read. Use it when only the affected set is needed.
892#[must_use]
893pub fn trace_impact_closure_without_search(
894    graph: &ModuleGraph,
895    root: &Path,
896    file_path: &str,
897) -> Option<ImpactClosureTrace> {
898    impact_closure_trace(graph, root, file_path, false)
899}
900
901fn impact_closure_trace(
902    graph: &ModuleGraph,
903    root: &Path,
904    file_path: &str,
905    check_search: bool,
906) -> Option<ImpactClosureTrace> {
907    let module = find_module(graph, root, file_path)?;
908
909    let closure = graph.impact_closure(&[module.file_id]);
910    let paths = graph.closure_with_paths(&closure, root);
911
912    let seed = paths
913        .in_diff
914        .first()
915        .cloned()
916        .unwrap_or_else(|| file_path.replace('\\', "/"));
917
918    let mut checks: FxHashMap<String, (String, SearchCheck)> =
919        if !check_search || paths.coordination_gap.is_empty() {
920            FxHashMap::default()
921        } else {
922            consumer_search_checks(graph, module.file_id)
923                .into_iter()
924                .filter_map(|(file_id, check)| {
925                    let consumer = graph.module(file_id)?;
926                    let path = consumer
927                        .path
928                        .strip_prefix(root)
929                        .unwrap_or(&consumer.path)
930                        .to_string_lossy()
931                        .replace('\\', "/");
932                    Some((path, check))
933                })
934                .collect()
935        };
936    let coordination_gap = paths
937        .coordination_gap
938        .into_iter()
939        .map(|gap| {
940            let (search_symbol, check) = checks.remove(&gap.consumer_file).unzip();
941            ImpactClosureGap {
942                consumer_file: gap.consumer_file,
943                consumed_symbols: gap.consumed_symbols,
944                note: "syntactic attention pointer, not a correctness proof".to_string(),
945                search_visibility: check.as_ref().map(|check| check.visibility),
946                reason: check.as_ref().and_then(|check| check.reason),
947                search_as: check.and_then(|check| check.search_as),
948                search_symbol,
949            }
950        })
951        .collect();
952
953    Some(ImpactClosureTrace {
954        seed,
955        affected_not_shown: paths.affected_not_shown,
956        coordination_gap,
957    })
958}
959
960/// The worst literal-search check per consumer of the value exports of
961/// `seed`, over every export the consumer references, with the name of the
962/// export that the check belongs to. The order of the levels is `missed`, then
963/// `renamed`, then `found`.
964fn consumer_search_checks(
965    graph: &ModuleGraph,
966    seed: FileId,
967) -> FxHashMap<FileId, (String, SearchCheck)> {
968    let mut checks: FxHashMap<FileId, (String, SearchCheck)> = FxHashMap::default();
969    let Some(module) = graph.module(seed) else {
970        return checks;
971    };
972    let mut sources = SourceCache::new(graph);
973    for export in module.exports.iter().filter(|export| !export.is_type_only) {
974        let name = export.name.to_string();
975        let target = SearchTarget::new(graph, &mut sources, seed, &name, ExportNamespace::Value);
976        let mut seen = FxHashSet::default();
977        for reference in &export.references {
978            if reference.from_file == seed || !seen.insert(reference.from_file) {
979                continue;
980            }
981            let Some(check) = target.check(graph, &mut sources, reference) else {
982                continue;
983            };
984            // A local use of one export outranks a pass-through of another.
985            let worse = checks.get(&reference.from_file).is_none_or(|(_, known)| {
986                check.visibility > known.visibility
987                    || (check.visibility == known.visibility
988                        && known.reason == Some(SearchGapReason::PassThrough)
989                        && check.reason != Some(SearchGapReason::PassThrough))
990            });
991            if worse {
992                checks.insert(reference.from_file, (name.clone(), check));
993            }
994        }
995    }
996    checks
997}
998
999/// Which endpoint of a `--path` request did not resolve to exactly one module.
1000#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1001pub enum ImportPathEndpoint {
1002    /// The module the walk would start from.
1003    From,
1004    /// The module the walk is looking for.
1005    To,
1006    /// Several modules match the starting path abbreviation.
1007    AmbiguousFrom,
1008    /// Several modules match the destination path abbreviation.
1009    AmbiguousTo,
1010}
1011
1012impl ImportPathEndpoint {
1013    /// The flag position this endpoint occupies, for diagnostics.
1014    #[must_use]
1015    pub const fn label(self) -> &'static str {
1016        match self {
1017            Self::From | Self::AmbiguousFrom => "from",
1018            Self::To | Self::AmbiguousTo => "to",
1019        }
1020    }
1021
1022    /// Whether the endpoint matched several modules instead of no module.
1023    #[must_use]
1024    pub const fn is_ambiguous(self) -> bool {
1025        matches!(self, Self::AmbiguousFrom | Self::AmbiguousTo)
1026    }
1027}
1028
1029fn import_path_endpoint_index(
1030    graph: &ModuleGraph,
1031    root: &Path,
1032    path: &str,
1033    missing: ImportPathEndpoint,
1034    ambiguous: ImportPathEndpoint,
1035) -> Result<usize, ImportPathEndpoint> {
1036    match matching_module_indexes(graph, root, path).as_slice() {
1037        [index] => Ok(*index),
1038        [] => Err(missing),
1039        _ => Err(ambiguous),
1040    }
1041}
1042
1043/// Resolve graph-level hops to the wire shape, turning each import span into a
1044/// 1-based line. Each source file is read at most once per trace; a file that
1045/// cannot be read yields `import_line: None` rather than a guessed line.
1046fn resolve_import_path_hops(
1047    graph: &ModuleGraph,
1048    root: &Path,
1049    hops: &[GraphImportPathHop],
1050) -> Vec<ImportPathHop> {
1051    let mut line_offsets: FxHashMap<FileId, Option<Vec<u32>>> = FxHashMap::default();
1052    hops.iter()
1053        .filter_map(|hop| {
1054            let from = graph.module(hop.from)?;
1055            let to = graph.module(hop.to)?;
1056            let import_line = hop.import_span_start.and_then(|span_start| {
1057                line_offsets
1058                    .entry(hop.from)
1059                    .or_insert_with(|| {
1060                        std::fs::read_to_string(&from.path)
1061                            .ok()
1062                            .map(|source| fallow_types::extract::compute_line_offsets(&source))
1063                    })
1064                    .as_ref()
1065                    .map(|offsets| {
1066                        fallow_types::extract::byte_offset_to_line_col(offsets, span_start).0
1067                    })
1068            });
1069            Some(ImportPathHop {
1070                from: relativize(&from.path, root),
1071                to: relativize(&to.path, root),
1072                type_only: hop.all_type_only,
1073                dynamic: hop.dynamic,
1074                import_line,
1075            })
1076        })
1077        .collect()
1078}
1079
1080/// Relativize a module path against the project root, forward-slashed.
1081pub fn relativize(path: &Path, root: &Path) -> String {
1082    path.strip_prefix(root)
1083        .unwrap_or(path)
1084        .to_string_lossy()
1085        .replace('\\', "/")
1086}
1087
1088/// Build a [`TracedCloneGroup`] from a raw clone group, computing the
1089/// fingerprint, group-level suggestion, and dominant-identifier name and
1090/// relativizing every instance path against `root`.
1091fn build_traced_group(
1092    group: &CloneGroup,
1093    root: &Path,
1094    fingerprints: &CloneFingerprintSet,
1095) -> TracedCloneGroup {
1096    TracedCloneGroup {
1097        fingerprint: fingerprints.fingerprint_for_group(group),
1098        token_count: group.token_count,
1099        line_count: group.line_count,
1100        spread: group.spread(),
1101        similarity: group.similarity,
1102        instances: group
1103            .instances
1104            .iter()
1105            .map(|inst| relativize_instance(inst, root))
1106            .collect(),
1107        suggestion: group_refactoring_suggestion(group),
1108        suggested_name: dominant_identifier(group),
1109    }
1110}
1111
1112#[must_use]
1113pub fn trace_clone(
1114    report: &DuplicationReport,
1115    root: &Path,
1116    file_path: &str,
1117    line: usize,
1118) -> CloneTrace {
1119    let resolved = root.join(file_path);
1120    let mut matched_instance = None;
1121    let mut clone_groups = Vec::new();
1122    let fingerprints = CloneFingerprintSet::from_groups(&report.clone_groups);
1123
1124    for group in &report.clone_groups {
1125        let matching = group.instances.iter().find(|inst| {
1126            let inst_matches = inst.file == resolved
1127                || inst.file.strip_prefix(root).unwrap_or(&inst.file) == Path::new(file_path);
1128            inst_matches && inst.start_line <= line && line <= inst.end_line
1129        });
1130
1131        if let Some(matched) = matching {
1132            if matched_instance.is_none() {
1133                matched_instance = Some(relativize_instance(matched, root));
1134            }
1135            clone_groups.push(build_traced_group(group, root, &fingerprints));
1136        }
1137    }
1138
1139    CloneTrace {
1140        file: PathBuf::from(file_path),
1141        line,
1142        matched_instance,
1143        clone_groups,
1144    }
1145}
1146
1147/// Trace a clone group by its stable content fingerprint.
1148///
1149/// Fingerprints are usually `dup:<8hex>` and widen only when needed to avoid a
1150/// collision inside the same report.
1151///
1152/// Returns a [`CloneTrace`] whose single `clone_groups` entry is the matched
1153/// group and whose `file` / `line` / `matched_instance` come from that group's
1154/// representative (first) instance. `matched_instance` is `None` (and
1155/// `clone_groups` empty) when no group matches the fingerprint.
1156#[must_use]
1157pub fn trace_clone_by_fingerprint(
1158    report: &DuplicationReport,
1159    root: &Path,
1160    fingerprint: &str,
1161) -> CloneTrace {
1162    let fingerprints = CloneFingerprintSet::from_groups(&report.clone_groups);
1163    let matched = fingerprints.find_group(&report.clone_groups, fingerprint);
1164
1165    let Some(group) = matched else {
1166        return CloneTrace {
1167            file: PathBuf::new(),
1168            line: 0,
1169            matched_instance: None,
1170            clone_groups: Vec::new(),
1171        };
1172    };
1173
1174    let representative = group
1175        .instances
1176        .first()
1177        .map(|inst| relativize_instance(inst, root));
1178    let (file, line) = representative.as_ref().map_or_else(
1179        || (PathBuf::new(), 0),
1180        |inst| (inst.file.clone(), inst.start_line),
1181    );
1182
1183    CloneTrace {
1184        file,
1185        line,
1186        matched_instance: representative,
1187        clone_groups: vec![build_traced_group(group, root, &fingerprints)],
1188    }
1189}
1190
1191/// Return a copy of `inst` with `file` rewritten relative to `root` (forward-slash normalized
1192/// for cross-platform JSON parity with `serde_path::serialize`). If `inst.file` is already
1193/// outside `root`, the path is left unchanged.
1194fn relativize_instance(inst: &CloneInstance, root: &Path) -> CloneInstance {
1195    let rel = inst.file.strip_prefix(root).map_or_else(
1196        |_| inst.file.clone(),
1197        |p| PathBuf::from(p.to_string_lossy().replace('\\', "/")),
1198    );
1199    CloneInstance {
1200        file: rel,
1201        ..inst.clone()
1202    }
1203}
1204
1205#[path = "trace_import_path.rs"]
1206mod trace_import_path;
1207pub use trace_import_path::trace_import_path;
1208
1209#[cfg(test)]
1210#[path = "trace_impl_dependency_tests.rs"]
1211mod dependency_tests;
1212
1213#[cfg(test)]
1214mod tests {
1215    use super::*;
1216
1217    use crate::discover::{DiscoveredFile, EntryPoint, EntryPointSource, FileId};
1218    use fallow_graph::resolve::{ResolveResult, ResolvedImport, ResolvedModule, ResolvedReExport};
1219    use fallow_types::extract::ReExportInfo;
1220    use fallow_types::extract::{ExportInfo, ExportName, ImportInfo, ImportedName, VisibilityTag};
1221
1222    fn resolved_re_export(
1223        source: FileId,
1224        imported_name: &str,
1225        exported_name: &str,
1226    ) -> ResolvedReExport {
1227        ResolvedReExport {
1228            info: ReExportInfo {
1229                source: "./source".to_string(),
1230                imported_name: imported_name.to_string(),
1231                exported_name: exported_name.to_string(),
1232                is_type_only: false,
1233                span: oxc_span::Span::default(),
1234                ..Default::default()
1235            },
1236            target: ResolveResult::InternalModule(source),
1237        }
1238    }
1239
1240    fn build_test_graph() -> ModuleGraph {
1241        build_test_graph_at(Path::new("/project"))
1242    }
1243
1244    /// The `entry -> utils` graph with module paths under `root`.
1245    fn build_test_graph_at(root: &Path) -> ModuleGraph {
1246        let src = |name: &str| root.join("src").join(name);
1247        let files = vec![
1248            DiscoveredFile {
1249                id: FileId(0),
1250                path: src("entry.ts"),
1251                size_bytes: 100,
1252            },
1253            DiscoveredFile {
1254                id: FileId(1),
1255                path: src("utils.ts"),
1256                size_bytes: 50,
1257            },
1258            DiscoveredFile {
1259                id: FileId(2),
1260                path: src("unused.ts"),
1261                size_bytes: 30,
1262            },
1263        ];
1264
1265        let entry_points = vec![EntryPoint {
1266            path: src("entry.ts"),
1267            source: EntryPointSource::PackageJsonMain,
1268        }];
1269
1270        let resolved_modules = vec![
1271            ResolvedModule {
1272                file_id: FileId(0),
1273                path: src("entry.ts"),
1274                resolved_imports: vec![ResolvedImport {
1275                    info: ImportInfo {
1276                        source: "./utils".to_string(),
1277                        imported_name: ImportedName::Named("foo".to_string()),
1278                        local_name: "foo".to_string(),
1279                        is_type_only: false,
1280                        is_type_only_star: false,
1281                        from_style: false,
1282                        span: oxc_span::Span::new(0, 10),
1283                        source_span: oxc_span::Span::default(),
1284                    },
1285                    target: ResolveResult::InternalModule(FileId(1)),
1286                }],
1287                ..Default::default()
1288            },
1289            ResolvedModule {
1290                file_id: FileId(1),
1291                path: src("utils.ts"),
1292                exports: vec![
1293                    ExportInfo {
1294                        name: ExportName::Named("foo".to_string()),
1295                        local_name: Some("foo".to_string()),
1296                        is_type_only: false,
1297                        visibility: VisibilityTag::None,
1298                        expected_unused_reason: None,
1299                        span: oxc_span::Span::new(0, 20),
1300                        members: vec![],
1301                        is_side_effect_used: false,
1302                        super_class: None,
1303                        deprecated: false,
1304                        deprecated_reason: None,
1305                    },
1306                    ExportInfo {
1307                        name: ExportName::Named("bar".to_string()),
1308                        local_name: Some("bar".to_string()),
1309                        is_type_only: false,
1310                        visibility: VisibilityTag::None,
1311                        expected_unused_reason: None,
1312                        span: oxc_span::Span::new(21, 40),
1313                        members: vec![],
1314                        is_side_effect_used: false,
1315                        super_class: None,
1316                        deprecated: false,
1317                        deprecated_reason: None,
1318                    },
1319                ]
1320                .into(),
1321                ..Default::default()
1322            },
1323            ResolvedModule {
1324                file_id: FileId(2),
1325                path: src("unused.ts"),
1326                exports: vec![ExportInfo {
1327                    name: ExportName::Named("baz".to_string()),
1328                    local_name: Some("baz".to_string()),
1329                    is_type_only: false,
1330                    visibility: VisibilityTag::None,
1331                    expected_unused_reason: None,
1332                    span: oxc_span::Span::new(0, 15),
1333                    members: vec![],
1334                    is_side_effect_used: false,
1335                    super_class: None,
1336                    deprecated: false,
1337                    deprecated_reason: None,
1338                }]
1339                .into(),
1340                ..Default::default()
1341            },
1342        ];
1343
1344        ModuleGraph::build(&resolved_modules, &entry_points, &files)
1345    }
1346
1347    #[test]
1348    fn trace_used_export() {
1349        let graph = build_test_graph();
1350        let root = Path::new("/project");
1351
1352        let trace = trace_export(&graph, root, "src/utils.ts", "foo").unwrap();
1353        assert!(trace.is_used);
1354        assert!(trace.file_reachable);
1355        assert_eq!(trace.direct_references.len(), 1);
1356        assert_eq!(
1357            trace.direct_references[0].from_file,
1358            PathBuf::from("src/entry.ts")
1359        );
1360        assert_eq!(trace.direct_references[0].kind, "named import");
1361    }
1362
1363    #[test]
1364    fn trace_unused_export() {
1365        let graph = build_test_graph();
1366        let root = Path::new("/project");
1367
1368        let trace = trace_export(&graph, root, "src/utils.ts", "bar").unwrap();
1369        assert!(!trace.is_used);
1370        assert!(trace.file_reachable);
1371        assert!(trace.direct_references.is_empty());
1372        assert_eq!(
1373            trace.namespace,
1374            fallow_types::semantic::SemanticNamespace::Value,
1375            "an unreferenced value export stays in the value namespace"
1376        );
1377    }
1378
1379    #[test]
1380    fn trace_unreachable_file_export() {
1381        let graph = build_test_graph();
1382        let root = Path::new("/project");
1383
1384        let trace = trace_export(&graph, root, "src/unused.ts", "baz").unwrap();
1385        assert!(!trace.is_used);
1386        assert!(!trace.file_reachable);
1387        assert!(trace.reason.contains("unreachable"));
1388    }
1389
1390    #[test]
1391    fn trace_nonexistent_export() {
1392        let graph = build_test_graph();
1393        let root = Path::new("/project");
1394
1395        let trace = trace_export(&graph, root, "src/utils.ts", "nonexistent");
1396        assert!(trace.is_none());
1397    }
1398
1399    fn assert_no_search_fields(reference: &ExportReference) {
1400        assert_eq!(reference.line, None);
1401        assert_eq!(reference.search_visibility, None);
1402        assert_eq!(reference.reason, None);
1403        assert_eq!(reference.search_as, None);
1404    }
1405
1406    fn assert_gap_has_no_search_fields(gap: &ImpactClosureGap) {
1407        assert_eq!(gap.search_visibility, None);
1408        assert_eq!(gap.reason, None);
1409        assert_eq!(gap.search_as, None);
1410        assert_eq!(gap.search_symbol, None);
1411    }
1412
1413    #[test]
1414    fn unreadable_consumer_leaves_the_search_fields_absent() {
1415        // The paths under `/project` do not exist, so no consumer source can be read.
1416        let graph = build_test_graph();
1417        let root = Path::new("/project");
1418
1419        let trace = trace_export(&graph, root, "src/utils.ts", "foo").unwrap();
1420        assert_eq!(trace.direct_references.len(), 1);
1421        assert_no_search_fields(&trace.direct_references[0]);
1422
1423        let impact = trace_impact_closure(&graph, root, "src/utils.ts").unwrap();
1424        assert_eq!(impact.coordination_gap.len(), 1);
1425        assert_gap_has_no_search_fields(&impact.coordination_gap[0]);
1426    }
1427
1428    #[test]
1429    fn impact_closure_without_search_reads_no_consumer_source() {
1430        let dir = tempfile::tempdir().expect("tempdir");
1431        let src = dir.path().join("src");
1432        std::fs::create_dir_all(&src).unwrap();
1433        std::fs::write(
1434            src.join("entry.ts"),
1435            "import { foo } from './utils';\nfoo();\n",
1436        )
1437        .unwrap();
1438        std::fs::write(
1439            src.join("utils.ts"),
1440            "export const foo = 1;\nexport const bar = 2;\n",
1441        )
1442        .unwrap();
1443        let graph = build_test_graph_at(dir.path());
1444
1445        let checked = trace_impact_closure(&graph, dir.path(), "src/utils.ts").unwrap();
1446        assert_eq!(checked.coordination_gap.len(), 1);
1447        assert_eq!(
1448            checked.coordination_gap[0].search_visibility,
1449            Some(fallow_types::trace::SearchVisibility::Found)
1450        );
1451        assert_eq!(
1452            checked.coordination_gap[0].search_symbol.as_deref(),
1453            Some("foo")
1454        );
1455
1456        let unchecked =
1457            trace_impact_closure_without_search(&graph, dir.path(), "src/utils.ts").unwrap();
1458        assert_eq!(unchecked.coordination_gap.len(), 1);
1459        assert_gap_has_no_search_fields(&unchecked.coordination_gap[0]);
1460        assert_eq!(unchecked.affected_not_shown, checked.affected_not_shown);
1461    }
1462
1463    #[test]
1464    fn trace_reports_only_the_effective_re_export_origin() {
1465        let files: Vec<_> = ["entry", "barrel", "star-source", "explicit-source"]
1466            .into_iter()
1467            .enumerate()
1468            .map(|(index, name)| DiscoveredFile {
1469                id: FileId(index as u32),
1470                path: PathBuf::from(format!("/project/src/{name}.ts")),
1471                size_bytes: 10,
1472            })
1473            .collect();
1474        let entry_points = vec![EntryPoint {
1475            path: files[0].path.clone(),
1476            source: EntryPointSource::PackageJsonMain,
1477        }];
1478        let re_export = |source: FileId, imported: &str, exported: &str| ResolvedReExport {
1479            info: ReExportInfo {
1480                source: format!("./{}", source.0),
1481                imported_name: imported.to_string(),
1482                exported_name: exported.to_string(),
1483                is_type_only: false,
1484                span: oxc_span::Span::default(),
1485                ..Default::default()
1486            },
1487            target: ResolveResult::InternalModule(source),
1488        };
1489        let export = || ExportInfo {
1490            name: ExportName::Named("foo".to_string()),
1491            local_name: Some("foo".to_string()),
1492            is_type_only: false,
1493            visibility: VisibilityTag::None,
1494            expected_unused_reason: None,
1495            span: oxc_span::Span::new(0, 3),
1496            members: Vec::new(),
1497            is_side_effect_used: false,
1498            super_class: None,
1499            deprecated: false,
1500            deprecated_reason: None,
1501        };
1502        let resolved = vec![
1503            ResolvedModule {
1504                file_id: FileId(0),
1505                path: files[0].path.clone(),
1506                resolved_imports: vec![ResolvedImport {
1507                    info: ImportInfo {
1508                        source: "./barrel".to_string(),
1509                        imported_name: ImportedName::Named("foo".to_string()),
1510                        local_name: "foo".to_string(),
1511                        is_type_only: false,
1512                        is_type_only_star: false,
1513                        from_style: false,
1514                        span: oxc_span::Span::default(),
1515                        source_span: oxc_span::Span::default(),
1516                    },
1517                    target: ResolveResult::InternalModule(FileId(1)),
1518                }],
1519                ..Default::default()
1520            },
1521            ResolvedModule {
1522                file_id: FileId(1),
1523                path: files[1].path.clone(),
1524                re_exports: vec![
1525                    re_export(FileId(2), "*", "*"),
1526                    re_export(FileId(3), "foo", "foo"),
1527                ],
1528                ..Default::default()
1529            },
1530            ResolvedModule {
1531                file_id: FileId(2),
1532                path: files[2].path.clone(),
1533                exports: vec![export()].into(),
1534                ..Default::default()
1535            },
1536            ResolvedModule {
1537                file_id: FileId(3),
1538                path: files[3].path.clone(),
1539                exports: vec![export()].into(),
1540                ..Default::default()
1541            },
1542        ];
1543        let graph = ModuleGraph::build(&resolved, &entry_points, &files);
1544
1545        let shadowed = trace_export(&graph, Path::new("/project"), "src/star-source.ts", "foo")
1546            .expect("shadowed source export exists");
1547        let effective = trace_export(
1548            &graph,
1549            Path::new("/project"),
1550            "src/explicit-source.ts",
1551            "foo",
1552        )
1553        .expect("effective source export exists");
1554
1555        assert!(shadowed.re_export_chains.is_empty());
1556        assert_eq!(effective.re_export_chains.len(), 1);
1557        assert_eq!(effective.re_export_chains[0].exported_as, "foo");
1558    }
1559
1560    fn star_surface_trace_graph(root: &Path) -> ModuleGraph {
1561        let src = root.join("src");
1562        std::fs::create_dir_all(&src).expect("create source directory");
1563        let paths: Vec<_> = ["source", "barrel-a", "barrel-b", "outer", "entry"]
1564            .into_iter()
1565            .map(|name| src.join(format!("{name}.ts")))
1566            .collect();
1567        std::fs::write(&paths[0], "\n\nexport const foo = 1;\n").expect("write source");
1568        for path in &paths[1..] {
1569            std::fs::write(path, "export {};\n").expect("write module");
1570        }
1571        let files: Vec<_> = paths
1572            .iter()
1573            .enumerate()
1574            .map(|(index, path)| DiscoveredFile {
1575                id: FileId(index as u32),
1576                path: path.clone(),
1577                size_bytes: 20,
1578            })
1579            .collect();
1580        let resolved = vec![
1581            ResolvedModule {
1582                file_id: FileId(0),
1583                path: paths[0].clone(),
1584                exports: vec![ExportInfo {
1585                    name: ExportName::Named("foo".to_string()),
1586                    local_name: Some("foo".to_string()),
1587                    is_type_only: false,
1588                    visibility: VisibilityTag::None,
1589                    expected_unused_reason: None,
1590                    span: oxc_span::Span::new(2, 5),
1591                    members: Vec::new(),
1592                    is_side_effect_used: false,
1593                    super_class: None,
1594                    deprecated: false,
1595                    deprecated_reason: None,
1596                }]
1597                .into(),
1598                ..Default::default()
1599            },
1600            ResolvedModule {
1601                file_id: FileId(1),
1602                path: paths[1].clone(),
1603                re_exports: vec![resolved_re_export(FileId(0), "*", "*")],
1604                ..Default::default()
1605            },
1606            ResolvedModule {
1607                file_id: FileId(2),
1608                path: paths[2].clone(),
1609                re_exports: vec![resolved_re_export(FileId(0), "*", "*")],
1610                ..Default::default()
1611            },
1612            ResolvedModule {
1613                file_id: FileId(3),
1614                path: paths[3].clone(),
1615                re_exports: vec![
1616                    resolved_re_export(FileId(1), "foo", "left"),
1617                    resolved_re_export(FileId(1), "foo", "right"),
1618                ],
1619                ..Default::default()
1620            },
1621            ResolvedModule {
1622                file_id: FileId(4),
1623                path: paths[4].clone(),
1624                resolved_imports: vec![
1625                    ResolvedImport {
1626                        info: ImportInfo {
1627                            source: "./outer".to_string(),
1628                            imported_name: ImportedName::Named("left".to_string()),
1629                            local_name: "left".to_string(),
1630                            is_type_only: false,
1631                            is_type_only_star: false,
1632                            from_style: false,
1633                            span: oxc_span::Span::new(10, 20),
1634                            source_span: oxc_span::Span::default(),
1635                        },
1636                        target: ResolveResult::InternalModule(FileId(3)),
1637                    },
1638                    ResolvedImport {
1639                        info: ImportInfo {
1640                            source: "./barrel-b".to_string(),
1641                            imported_name: ImportedName::Named("foo".to_string()),
1642                            local_name: "otherFoo".to_string(),
1643                            is_type_only: false,
1644                            is_type_only_star: false,
1645                            from_style: false,
1646                            span: oxc_span::Span::new(30, 40),
1647                            source_span: oxc_span::Span::default(),
1648                        },
1649                        target: ResolveResult::InternalModule(FileId(2)),
1650                    },
1651                ],
1652                ..Default::default()
1653            },
1654        ];
1655        let entry_points = vec![EntryPoint {
1656            path: paths[4].clone(),
1657            source: EntryPointSource::PackageJsonMain,
1658        }];
1659        ModuleGraph::build(&resolved, &entry_points, &files)
1660    }
1661
1662    #[test]
1663    fn star_surface_trace_keeps_aliases_separate_and_uses_origin_identity() {
1664        let root = tempfile::tempdir().expect("temporary project");
1665        let graph = star_surface_trace_graph(root.path());
1666
1667        let used = trace_export(&graph, root.path(), "src/barrel-a.ts", "foo")
1668            .expect("aliased barrel exposes foo");
1669        let sibling = trace_export(&graph, root.path(), "src/barrel-b.ts", "foo")
1670            .expect("sibling barrel exposes foo");
1671        assert!(used.is_used);
1672        assert_eq!(used.direct_references.len(), 1);
1673        assert!(sibling.is_used);
1674        assert_eq!(sibling.direct_references.len(), 1);
1675
1676        let source_trace = trace_export(&graph, root.path(), "src/source.ts", "foo")
1677            .expect("source declaration is traceable");
1678        let chain_count = |file: &str, name: &str| {
1679            source_trace
1680                .re_export_chains
1681                .iter()
1682                .find(|chain| chain.barrel_file == Path::new(file) && chain.exported_as == name)
1683                .map(|chain| chain.reference_count)
1684        };
1685        assert_eq!(chain_count("src/barrel-a.ts", "foo"), Some(1));
1686        assert_eq!(chain_count("src/barrel-b.ts", "foo"), Some(1));
1687        assert_eq!(chain_count("src/outer.ts", "left"), Some(1));
1688        assert_eq!(chain_count("src/outer.ts", "right"), Some(0));
1689
1690        let semantic = semantic_symbol_for_export(&graph, root.path(), "src/barrel-a.ts", "foo")
1691            .expect("star surface resolves to its declaration identity");
1692        assert_eq!(semantic.path, Path::new("src/source.ts"));
1693        assert_eq!(semantic.exported_name, "foo");
1694        assert_eq!(semantic.local_name, "foo");
1695        assert_eq!((semantic.line, semantic.col), (3, 0));
1696
1697        let alias = semantic_symbol_for_export(&graph, root.path(), "src/outer.ts", "left")
1698            .expect("named re-export keeps its export-specifier identity");
1699        assert_eq!(alias.path, Path::new("src/outer.ts"));
1700        assert_eq!(alias.exported_name, "left");
1701        assert_eq!(alias.local_name, "foo");
1702    }
1703
1704    #[test]
1705    fn trace_follows_renamed_and_convergent_re_export_routes() {
1706        let names = [
1707            "source",
1708            "renamed",
1709            "final",
1710            "left",
1711            "right",
1712            "diamond-entry",
1713        ];
1714        let files: Vec<_> = names
1715            .into_iter()
1716            .enumerate()
1717            .map(|(index, name)| DiscoveredFile {
1718                id: FileId(index as u32),
1719                path: PathBuf::from(format!("/project/src/{name}.ts")),
1720                size_bytes: 10,
1721            })
1722            .collect();
1723        let re_export = |source: FileId, imported: &str, exported: &str| ResolvedReExport {
1724            info: ReExportInfo {
1725                source: format!("./{}", source.0),
1726                imported_name: imported.to_string(),
1727                exported_name: exported.to_string(),
1728                is_type_only: false,
1729                span: oxc_span::Span::default(),
1730                ..Default::default()
1731            },
1732            target: ResolveResult::InternalModule(source),
1733        };
1734        let mut resolved: Vec<_> = files
1735            .iter()
1736            .map(|file| ResolvedModule {
1737                file_id: file.id,
1738                path: file.path.clone(),
1739                ..Default::default()
1740            })
1741            .collect();
1742        resolved[0].exports = vec![ExportInfo {
1743            name: ExportName::Named("foo".to_string()),
1744            local_name: Some("foo".to_string()),
1745            is_type_only: false,
1746            visibility: VisibilityTag::None,
1747            expected_unused_reason: None,
1748            span: oxc_span::Span::new(0, 3),
1749            members: Vec::new(),
1750            is_side_effect_used: false,
1751            super_class: None,
1752            deprecated: false,
1753            deprecated_reason: None,
1754        }]
1755        .into();
1756        resolved[1].re_exports = vec![re_export(FileId(0), "foo", "bar")];
1757        resolved[2].re_exports = vec![re_export(FileId(1), "bar", "baz")];
1758        resolved[3].re_exports = vec![re_export(FileId(0), "*", "*")];
1759        resolved[4].re_exports = vec![re_export(FileId(0), "*", "*")];
1760        resolved[5].re_exports = vec![
1761            re_export(FileId(3), "*", "*"),
1762            re_export(FileId(4), "*", "*"),
1763        ];
1764        let entry_points = vec![EntryPoint {
1765            path: files[5].path.clone(),
1766            source: EntryPointSource::PackageJsonMain,
1767        }];
1768        let graph = ModuleGraph::build(&resolved, &entry_points, &files);
1769
1770        let trace = trace_export(&graph, Path::new("/project"), "src/source.ts", "foo")
1771            .expect("source export exists");
1772        let routes: FxHashSet<_> = trace
1773            .re_export_chains
1774            .iter()
1775            .map(|route| (route.barrel_file.as_path(), route.exported_as.as_str()))
1776            .collect();
1777
1778        assert_eq!(routes.len(), 5);
1779        assert!(routes.contains(&(Path::new("src/renamed.ts"), "bar")));
1780        assert!(routes.contains(&(Path::new("src/final.ts"), "baz")));
1781        assert!(routes.contains(&(Path::new("src/left.ts"), "foo")));
1782        assert!(routes.contains(&(Path::new("src/right.ts"), "foo")));
1783        assert!(routes.contains(&(Path::new("src/diamond-entry.ts"), "foo")));
1784    }
1785
1786    #[test]
1787    fn trace_prefers_the_value_namespace_independent_of_usage() {
1788        let files = vec![
1789            DiscoveredFile {
1790                id: FileId(0),
1791                path: PathBuf::from("/project/src/entry.ts"),
1792                size_bytes: 10,
1793            },
1794            DiscoveredFile {
1795                id: FileId(1),
1796                path: PathBuf::from("/project/src/source.ts"),
1797                size_bytes: 10,
1798            },
1799        ];
1800        let export = |is_type_only| ExportInfo {
1801            name: ExportName::Named("Foo".to_string()),
1802            local_name: Some("Foo".to_string()),
1803            is_type_only,
1804            visibility: VisibilityTag::None,
1805            expected_unused_reason: None,
1806            span: oxc_span::Span::new(0, 3),
1807            members: Vec::new(),
1808            is_side_effect_used: false,
1809            super_class: None,
1810            deprecated: false,
1811            deprecated_reason: None,
1812        };
1813        let resolved = vec![
1814            ResolvedModule {
1815                file_id: FileId(0),
1816                path: files[0].path.clone(),
1817                resolved_imports: vec![ResolvedImport {
1818                    info: ImportInfo {
1819                        source: "./source".to_string(),
1820                        imported_name: ImportedName::Named("Foo".to_string()),
1821                        local_name: "Foo".to_string(),
1822                        is_type_only: true,
1823                        is_type_only_star: false,
1824                        from_style: false,
1825                        span: oxc_span::Span::default(),
1826                        source_span: oxc_span::Span::default(),
1827                    },
1828                    target: ResolveResult::InternalModule(FileId(1)),
1829                }],
1830                ..Default::default()
1831            },
1832            ResolvedModule {
1833                file_id: FileId(1),
1834                path: files[1].path.clone(),
1835                exports: vec![export(false), export(true)].into(),
1836                ..Default::default()
1837            },
1838        ];
1839        let entry_points = vec![EntryPoint {
1840            path: files[0].path.clone(),
1841            source: EntryPointSource::PackageJsonMain,
1842        }];
1843        let graph = ModuleGraph::build(&resolved, &entry_points, &files);
1844
1845        let trace = trace_export(&graph, Path::new("/project"), "src/source.ts", "Foo")
1846            .expect("value export exists");
1847
1848        // The type import credits the distinct `export type Foo` declaration,
1849        // so dead-code still reports the value `Foo`; the trace must agree and
1850        // must not borrow the type lane here (issue #2371). A declaration
1851        // merge that splits across lanes, `interface Foo` next to `class Foo`,
1852        // reaches the graph as this same pair of surfaces, so it is the shape
1853        // the documented gap names: dead-code credits the class through the
1854        // merge while the trace still reports it unused.
1855        assert_eq!(
1856            trace.namespace,
1857            fallow_types::semantic::SemanticNamespace::Value
1858        );
1859        assert!(!trace.is_used, "type usage must not select the type export");
1860    }
1861
1862    /// Consumer `entry.ts` importing `Foo` from `source.ts`, whose exports are
1863    /// supplied by the caller.
1864    fn source_consumer_graph(
1865        source_exports: Vec<ExportInfo>,
1866        import_is_type_only: bool,
1867        classified_usage: bool,
1868        semantic_facts: Vec<fallow_types::extract::SemanticFact>,
1869    ) -> ModuleGraph {
1870        let files = vec![
1871            DiscoveredFile {
1872                id: FileId(0),
1873                path: PathBuf::from("/project/src/entry.ts"),
1874                size_bytes: 10,
1875            },
1876            DiscoveredFile {
1877                id: FileId(1),
1878                path: PathBuf::from("/project/src/source.ts"),
1879                size_bytes: 10,
1880            },
1881        ];
1882        let classified = if classified_usage {
1883            vec!["Foo".to_string()]
1884        } else {
1885            Vec::new()
1886        };
1887        let resolved = vec![
1888            ResolvedModule {
1889                file_id: FileId(0),
1890                path: files[0].path.clone(),
1891                resolved_imports: vec![ResolvedImport {
1892                    info: ImportInfo {
1893                        source: "./source".to_string(),
1894                        imported_name: ImportedName::Named("Foo".to_string()),
1895                        local_name: "Foo".to_string(),
1896                        is_type_only: import_is_type_only,
1897                        is_type_only_star: false,
1898                        from_style: false,
1899                        span: oxc_span::Span::new(0, 10),
1900                        source_span: oxc_span::Span::default(),
1901                    },
1902                    target: ResolveResult::InternalModule(FileId(1)),
1903                }],
1904                type_referenced_import_bindings: classified.clone(),
1905                value_referenced_import_bindings: classified,
1906                ..Default::default()
1907            },
1908            ResolvedModule {
1909                file_id: FileId(1),
1910                path: files[1].path.clone(),
1911                exports: source_exports.into(),
1912                semantic_facts: semantic_facts.into(),
1913                ..Default::default()
1914            },
1915        ];
1916        let entry_points = vec![EntryPoint {
1917            path: files[0].path.clone(),
1918            source: EntryPointSource::PackageJsonMain,
1919        }];
1920        ModuleGraph::build(&resolved, &entry_points, &files)
1921    }
1922
1923    /// Two consumers of `source.ts`: `entry.ts` imports `Foo` in value
1924    /// position and `typed.ts` imports the same name with `import type`, so
1925    /// one effective binding carries a reference in both lanes.
1926    fn dual_lane_consumer_graph(source_exports: Vec<ExportInfo>) -> ModuleGraph {
1927        let files = vec![
1928            DiscoveredFile {
1929                id: FileId(0),
1930                path: PathBuf::from("/project/src/entry.ts"),
1931                size_bytes: 10,
1932            },
1933            DiscoveredFile {
1934                id: FileId(1),
1935                path: PathBuf::from("/project/src/source.ts"),
1936                size_bytes: 10,
1937            },
1938            DiscoveredFile {
1939                id: FileId(2),
1940                path: PathBuf::from("/project/src/typed.ts"),
1941                size_bytes: 10,
1942            },
1943        ];
1944        let consumer = |file_id: FileId, path: PathBuf, is_type_only: bool| ResolvedModule {
1945            file_id,
1946            path,
1947            resolved_imports: vec![ResolvedImport {
1948                info: ImportInfo {
1949                    source: "./source".to_string(),
1950                    imported_name: ImportedName::Named("Foo".to_string()),
1951                    local_name: "Foo".to_string(),
1952                    is_type_only,
1953                    is_type_only_star: false,
1954                    from_style: false,
1955                    span: oxc_span::Span::new(0, 10),
1956                    source_span: oxc_span::Span::default(),
1957                },
1958                target: ResolveResult::InternalModule(FileId(1)),
1959            }],
1960            ..Default::default()
1961        };
1962        let resolved = vec![
1963            consumer(FileId(0), files[0].path.clone(), false),
1964            ResolvedModule {
1965                file_id: FileId(1),
1966                path: files[1].path.clone(),
1967                exports: source_exports.into(),
1968                ..Default::default()
1969            },
1970            consumer(FileId(2), files[2].path.clone(), true),
1971        ];
1972        let entry_points = vec![
1973            EntryPoint {
1974                path: files[0].path.clone(),
1975                source: EntryPointSource::PackageJsonMain,
1976            },
1977            EntryPoint {
1978                path: files[2].path.clone(),
1979                source: EntryPointSource::PackageJsonMain,
1980            },
1981        ];
1982        ModuleGraph::build(&resolved, &entry_points, &files)
1983    }
1984
1985    fn class_method(name: &str, start: u32, end: u32) -> fallow_types::extract::MemberInfo {
1986        fallow_types::extract::MemberInfo {
1987            name: name.to_string(),
1988            kind: fallow_types::extract::MemberKind::ClassMethod,
1989            span: oxc_span::Span::new(start, end),
1990            has_decorator: false,
1991            decorator_names: vec![],
1992            is_instance_returning_static: false,
1993            is_self_returning: false,
1994            override_base: None,
1995            is_protected: false,
1996            is_static: false,
1997            pairs_with_symbol_dispose: false,
1998        }
1999    }
2000
2001    fn named_foo_export(is_type_only: bool) -> ExportInfo {
2002        ExportInfo {
2003            name: ExportName::Named("Foo".to_string()),
2004            local_name: Some("Foo".to_string()),
2005            is_type_only,
2006            visibility: VisibilityTag::None,
2007            expected_unused_reason: None,
2008            span: oxc_span::Span::new(0, 3),
2009            members: Vec::new(),
2010            is_side_effect_used: false,
2011            super_class: None,
2012            deprecated: false,
2013            deprecated_reason: None,
2014        }
2015    }
2016
2017    #[test]
2018    fn trace_credits_a_value_only_export_through_the_type_lane() {
2019        // Issue #2371: `import type { Foo }` of `export const Foo` lands on the
2020        // value declaration through the type-lane fallback, and dead-code
2021        // counts that as a use. The trace reports the crediting lane.
2022        let graph = source_consumer_graph(vec![named_foo_export(false)], true, false, Vec::new());
2023
2024        let trace = trace_export(&graph, Path::new("/project"), "src/source.ts", "Foo")
2025            .expect("value export exists");
2026
2027        assert_eq!(
2028            trace.namespace,
2029            fallow_types::semantic::SemanticNamespace::Type,
2030            "the type lane carries the only credit"
2031        );
2032        assert!(
2033            trace.is_used,
2034            "a type-only import credits a value-only export"
2035        );
2036        assert_eq!(trace.direct_references.len(), 1);
2037        assert_eq!(
2038            trace.direct_references[0].from_file,
2039            PathBuf::from("src/entry.ts")
2040        );
2041        assert_eq!(trace.direct_references[0].kind, "named import");
2042        assert_eq!(trace.reason, "Used by 1 file(s)");
2043    }
2044
2045    #[test]
2046    fn trace_omits_redundant_single_namespace_evidence() {
2047        let graph = source_consumer_graph(vec![named_foo_export(false)], false, false, Vec::new());
2048
2049        let trace = trace_export(&graph, Path::new("/project"), "src/source.ts", "Foo")
2050            .expect("value export exists");
2051
2052        assert_eq!(
2053            trace.namespace,
2054            fallow_types::semantic::SemanticNamespace::Value
2055        );
2056        assert_eq!(trace.direct_references.len(), 1);
2057        assert!(trace.direct_references_by_namespace.is_empty());
2058        let json = serde_json::to_value(&trace).expect("serialize trace");
2059        assert!(json.get("direct_references_by_namespace").is_none());
2060    }
2061
2062    #[test]
2063    fn trace_keeps_the_value_lane_when_one_binding_carries_both_lanes() {
2064        // The preferred lane wins whenever it carries a reference, including
2065        // when the other lane resolves to the SAME binding and carries one
2066        // too: `export class Foo` consumed by a value importer and by an
2067        // `import type` importer must keep reporting the value consumer.
2068        // Without that rule the type lane would take over the payload.
2069        let graph = dual_lane_consumer_graph(vec![named_foo_export(false)]);
2070
2071        let trace = trace_export(&graph, Path::new("/project"), "src/source.ts", "Foo")
2072            .expect("value export exists");
2073
2074        assert_eq!(
2075            trace.namespace,
2076            fallow_types::semantic::SemanticNamespace::Value
2077        );
2078        assert!(trace.is_used);
2079        assert_eq!(trace.direct_references.len(), 1);
2080        assert_eq!(
2081            trace.direct_references[0].from_file,
2082            PathBuf::from("src/entry.ts"),
2083            "the value consumer stays the listed reference"
2084        );
2085        assert_eq!(trace.direct_references_by_namespace.len(), 2);
2086        assert!(trace.direct_references_by_namespace.iter().any(|lane| {
2087            lane.namespace == fallow_types::semantic::SemanticNamespace::Type
2088                && lane.reference_count == 1
2089                && lane.references[0].from_file == Path::new("src/typed.ts")
2090        }));
2091    }
2092
2093    #[test]
2094    fn trace_credits_a_declaration_merge_that_stays_one_binding() {
2095        // A merge whose parts share the value lane, `class Foo` next to
2096        // `namespace Foo`, is one effective binding in both lanes, so a bound
2097        // `import type` credits it and the trace reports the crediting lane.
2098        let graph = source_consumer_graph(
2099            vec![named_foo_export(false), named_foo_export(false)],
2100            true,
2101            false,
2102            Vec::new(),
2103        );
2104
2105        let trace = trace_export(&graph, Path::new("/project"), "src/source.ts", "Foo")
2106            .expect("value export exists");
2107
2108        assert_eq!(
2109            trace.namespace,
2110            fallow_types::semantic::SemanticNamespace::Type,
2111            "the merged binding is reachable from the type lane"
2112        );
2113        assert!(trace.is_used);
2114        assert_eq!(trace.direct_references.len(), 1);
2115        assert_eq!(
2116            trace.direct_references[0].from_file,
2117            PathBuf::from("src/entry.ts")
2118        );
2119    }
2120
2121    #[test]
2122    fn trace_credits_a_class_interface_declaration_merge() {
2123        let mut interface = named_foo_export(true);
2124        interface.span = oxc_span::Span::new(0, 3);
2125        let mut class = named_foo_export(false);
2126        class.span = oxc_span::Span::new(4, 7);
2127        let graph = source_consumer_graph(
2128            vec![interface, class],
2129            true,
2130            true,
2131            vec![fallow_types::extract::SemanticFact::DeclarationMerge(
2132                fallow_types::extract::DeclarationMergeFact {
2133                    export_spans: vec![(0, 3), (4, 7)],
2134                },
2135            )],
2136        );
2137
2138        let trace = trace_export(&graph, Path::new("/project"), "src/source.ts", "Foo")
2139            .expect("merged class export exists");
2140
2141        assert_eq!(
2142            trace.namespace,
2143            fallow_types::semantic::SemanticNamespace::Type
2144        );
2145        assert!(trace.is_used);
2146        assert_eq!(trace.direct_references.len(), 1);
2147    }
2148
2149    #[test]
2150    fn trace_keeps_the_value_namespace_when_lanes_hold_distinct_bindings() {
2151        // Deliberate negative control: two same-name declarations in opposite
2152        // lanes are two bindings, so the value lane is kept even though the
2153        // type lane also carries a reference. The value lane holds the
2154        // reference here, so this pins the preferred-lane rule;
2155        // `trace_prefers_the_value_namespace_independent_of_usage` is the test
2156        // that reaches and pins the binding-equality guard.
2157        let graph = source_consumer_graph(
2158            vec![named_foo_export(false), named_foo_export(true)],
2159            false,
2160            true,
2161            Vec::new(),
2162        );
2163
2164        let trace = trace_export(&graph, Path::new("/project"), "src/source.ts", "Foo")
2165            .expect("value export exists");
2166
2167        assert_eq!(
2168            trace.namespace,
2169            fallow_types::semantic::SemanticNamespace::Value
2170        );
2171        assert!(trace.is_used);
2172        assert_eq!(trace.direct_references.len(), 1);
2173        assert_eq!(
2174            trace.direct_references[0].from_file,
2175            PathBuf::from("src/entry.ts")
2176        );
2177    }
2178
2179    #[test]
2180    fn class_member_trace_inherits_the_type_lane_credit_of_its_owner() {
2181        // Issue #2371: the member trace is built from the owner's export
2182        // trace, so an owner credited only through the type lane reports a
2183        // used owner instead of the "referenced by no file" reason.
2184        let mut owner = named_foo_export(false);
2185        owner.members = vec![class_method("run", 0, 3)];
2186        let graph = source_consumer_graph(vec![owner], true, false, Vec::new());
2187
2188        let trace = trace_class_member(&graph, Path::new("/project"), "src/source.ts", "run")
2189            .expect("member of the traced export");
2190
2191        assert!(trace.owner_is_used, "the type lane credits the owner");
2192        assert_eq!(
2193            trace.owner_namespace,
2194            fallow_types::semantic::SemanticNamespace::Type,
2195            "the member payload names the lane that credits its owner"
2196        );
2197        assert_eq!(trace.owner_direct_references.len(), 1);
2198        assert_eq!(
2199            trace.owner_direct_references[0].from_file,
2200            PathBuf::from("src/entry.ts")
2201        );
2202        assert!(
2203            trace.reason.contains("'Foo' is used by 1 file(s)"),
2204            "the reason must follow the owner's credit: {}",
2205            trace.reason
2206        );
2207    }
2208
2209    #[test]
2210    #[expect(
2211        clippy::too_many_lines,
2212        reason = "the fixture names every ExportInfo field so a new field is a compile error here"
2213    )]
2214    fn trace_preserves_dual_namespace_named_re_exports() {
2215        let files: Vec<_> = ["entry", "barrel", "types", "values"]
2216            .into_iter()
2217            .enumerate()
2218            .map(|(index, name)| DiscoveredFile {
2219                id: FileId(index as u32),
2220                path: PathBuf::from(format!("/project/src/{name}.ts")),
2221                size_bytes: 10,
2222            })
2223            .collect();
2224        let export = |is_type_only| ExportInfo {
2225            name: ExportName::Named("Foo".to_string()),
2226            local_name: Some("Foo".to_string()),
2227            is_type_only,
2228            visibility: VisibilityTag::None,
2229            expected_unused_reason: None,
2230            span: oxc_span::Span::new(0, 3),
2231            members: Vec::new(),
2232            is_side_effect_used: false,
2233            super_class: None,
2234            deprecated: false,
2235            deprecated_reason: None,
2236        };
2237        let re_export = |source: FileId, is_type_only| ResolvedReExport {
2238            info: ReExportInfo {
2239                source: format!("./{}", source.0),
2240                imported_name: "Foo".to_string(),
2241                exported_name: "Foo".to_string(),
2242                is_type_only,
2243                span: oxc_span::Span::default(),
2244                statement_span: oxc_span::Span::default(),
2245                source_span: oxc_span::Span::default(),
2246                visibility: VisibilityTag::None,
2247                expected_unused_reason: None,
2248            },
2249            target: ResolveResult::InternalModule(source),
2250        };
2251        let mut resolved = vec![
2252            ResolvedModule {
2253                file_id: FileId(0),
2254                path: files[0].path.clone(),
2255                resolved_imports: vec![ResolvedImport {
2256                    info: ImportInfo {
2257                        source: "./barrel".to_string(),
2258                        imported_name: ImportedName::Named("Foo".to_string()),
2259                        local_name: "Foo".to_string(),
2260                        is_type_only: false,
2261                        is_type_only_star: false,
2262                        from_style: false,
2263                        span: oxc_span::Span::new(0, 10),
2264                        source_span: oxc_span::Span::default(),
2265                    },
2266                    target: ResolveResult::InternalModule(FileId(1)),
2267                }],
2268                ..Default::default()
2269            },
2270            ResolvedModule {
2271                file_id: FileId(1),
2272                path: files[1].path.clone(),
2273                re_exports: vec![re_export(FileId(2), true), re_export(FileId(3), false)],
2274                ..Default::default()
2275            },
2276            ResolvedModule {
2277                file_id: FileId(2),
2278                path: files[2].path.clone(),
2279                exports: vec![export(true)].into(),
2280                ..Default::default()
2281            },
2282            ResolvedModule {
2283                file_id: FileId(3),
2284                path: files[3].path.clone(),
2285                exports: vec![export(false)].into(),
2286                ..Default::default()
2287            },
2288        ];
2289        let entry_points = vec![EntryPoint {
2290            path: files[0].path.clone(),
2291            source: EntryPointSource::PackageJsonMain,
2292        }];
2293        let graph = ModuleGraph::build(&resolved, &entry_points, &files);
2294        resolved[1].re_exports.reverse();
2295        let reversed_graph = ModuleGraph::build(&resolved, &entry_points, &files);
2296
2297        let trace = trace_export(&graph, Path::new("/project"), "src/barrel.ts", "Foo")
2298            .expect("barrel exposes Foo in both namespaces");
2299
2300        assert_eq!(
2301            trace.namespace,
2302            fallow_types::semantic::SemanticNamespace::Value
2303        );
2304        assert!(
2305            trace.is_used,
2306            "the value import must credit the value surface"
2307        );
2308        assert_eq!(trace.direct_references.len(), 1);
2309        let reversed_trace = trace_export(
2310            &reversed_graph,
2311            Path::new("/project"),
2312            "src/barrel.ts",
2313            "Foo",
2314        )
2315        .expect("reversed declarations expose the same surface");
2316        assert_eq!(
2317            serde_json::to_value(trace).expect("serialize trace"),
2318            serde_json::to_value(reversed_trace).expect("serialize reversed trace")
2319        );
2320    }
2321
2322    fn build_class_member_graph() -> ModuleGraph {
2323        let files = vec![
2324            DiscoveredFile {
2325                id: FileId(0),
2326                path: PathBuf::from("/project/src/entry.ts"),
2327                size_bytes: 100,
2328            },
2329            DiscoveredFile {
2330                id: FileId(1),
2331                path: PathBuf::from("/project/src/controller.ts"),
2332                size_bytes: 50,
2333            },
2334        ];
2335        let entry_points = vec![EntryPoint {
2336            path: PathBuf::from("/project/src/entry.ts"),
2337            source: EntryPointSource::PackageJsonMain,
2338        }];
2339        let method = |name: &str| class_method(name, 0, 4);
2340        let resolved_modules = vec![
2341            ResolvedModule {
2342                file_id: FileId(0),
2343                path: PathBuf::from("/project/src/entry.ts"),
2344                resolved_imports: vec![ResolvedImport {
2345                    info: ImportInfo {
2346                        source: "./controller".to_string(),
2347                        imported_name: ImportedName::Named("Ctrl".to_string()),
2348                        local_name: "Ctrl".to_string(),
2349                        is_type_only: false,
2350                        is_type_only_star: false,
2351                        from_style: false,
2352                        span: oxc_span::Span::new(0, 10),
2353                        source_span: oxc_span::Span::default(),
2354                    },
2355                    target: ResolveResult::InternalModule(FileId(1)),
2356                }],
2357                ..Default::default()
2358            },
2359            ResolvedModule {
2360                file_id: FileId(1),
2361                path: PathBuf::from("/project/src/controller.ts"),
2362                exports: vec![ExportInfo {
2363                    name: ExportName::Named("Ctrl".to_string()),
2364                    local_name: Some("Ctrl".to_string()),
2365                    is_type_only: false,
2366                    visibility: VisibilityTag::None,
2367                    expected_unused_reason: None,
2368                    span: oxc_span::Span::new(0, 20),
2369                    members: vec![method("used"), method("dead")],
2370                    is_side_effect_used: false,
2371                    super_class: None,
2372                    deprecated: false,
2373                    deprecated_reason: None,
2374                }]
2375                .into(),
2376                ..Default::default()
2377            },
2378        ];
2379        ModuleGraph::build(&resolved_modules, &entry_points, &files)
2380    }
2381
2382    #[test]
2383    fn trace_class_member_reports_owner_class() {
2384        // #1744: `--trace FILE:MEMBER` on a class member reports the owning
2385        // class instead of erroring "export not found".
2386        let graph = build_class_member_graph();
2387        let root = Path::new("/project");
2388
2389        let trace = trace_class_member(&graph, root, "src/controller.ts", "dead").unwrap();
2390        assert_eq!(trace.owner_export, "Ctrl");
2391        assert_eq!(trace.member_name, "dead");
2392        assert_eq!(trace.member_kind, "class-method");
2393        assert!(trace.owner_is_used);
2394        assert!(trace.owner_file_reachable);
2395        assert_eq!(trace.owner_direct_references.len(), 1);
2396        assert!(
2397            trace.reason.contains("--unused-class-members"),
2398            "reason should point at the member command: {}",
2399            trace.reason
2400        );
2401    }
2402
2403    #[test]
2404    fn trace_class_member_absent_name_is_none() {
2405        // A name that is neither a top-level export nor a declared member falls
2406        // through so the caller emits the "not found" error.
2407        let graph = build_class_member_graph();
2408        let root = Path::new("/project");
2409        assert!(trace_class_member(&graph, root, "src/controller.ts", "nope").is_none());
2410    }
2411
2412    fn exact_class_method_fixture() -> (tempfile::TempDir, ModuleGraph) {
2413        let temp = tempfile::tempdir().unwrap();
2414        let root = temp.path();
2415        let path = root.join("repository.ts");
2416        let source =
2417            "export class Repository {\n  save(): void;\n  save(): void {}\n  run(): void {}\n}\n";
2418        std::fs::write(&path, source).unwrap();
2419        let first = source.find("save").unwrap() as u32;
2420        let second = source.rfind("save").unwrap() as u32;
2421        let run = source.find("run").unwrap() as u32;
2422        let member = |name: &str, start| class_method(name, start, start + 4);
2423        let files = vec![DiscoveredFile {
2424            id: FileId(0),
2425            path: path.clone(),
2426            size_bytes: source.len() as u64,
2427        }];
2428        let resolved_modules = vec![ResolvedModule {
2429            file_id: FileId(0),
2430            path,
2431            exports: vec![ExportInfo {
2432                name: ExportName::Named("Repository".to_string()),
2433                local_name: Some("Repository".to_string()),
2434                is_type_only: false,
2435                visibility: VisibilityTag::None,
2436                expected_unused_reason: None,
2437                span: oxc_span::Span::new(0, source.len() as u32),
2438                members: vec![
2439                    member("save", first),
2440                    member("save", second),
2441                    member("run", run),
2442                ],
2443                is_side_effect_used: false,
2444                super_class: None,
2445                deprecated: false,
2446                deprecated_reason: None,
2447            }]
2448            .into(),
2449            ..Default::default()
2450        }];
2451        let graph = ModuleGraph::build(&resolved_modules, &[], &files);
2452        (temp, graph)
2453    }
2454
2455    #[test]
2456    fn exact_class_method_resolution_rejects_overloads_without_guessing() {
2457        let (temp, graph) = exact_class_method_fixture();
2458        let root = temp.path();
2459        assert_eq!(
2460            semantic_symbol_for_exact_class_method(
2461                &graph,
2462                root,
2463                "repository.ts",
2464                "Repository",
2465                "save",
2466            ),
2467            Err(SemanticClassMethodResolutionError::AmbiguousSymbol)
2468        );
2469        assert_eq!(
2470            semantic_symbol_for_exact_class_method(
2471                &graph,
2472                root,
2473                "repository.ts",
2474                "OtherRepository",
2475                "save",
2476            ),
2477            Err(SemanticClassMethodResolutionError::SymbolNotFound)
2478        );
2479        let resolved = semantic_symbol_for_exact_class_method(
2480            &graph,
2481            root,
2482            "repository.ts",
2483            "Repository",
2484            "run",
2485        )
2486        .unwrap();
2487        assert_eq!(resolved.owner.as_deref(), Some("Repository"));
2488        assert_eq!(resolved.local_name, "run");
2489    }
2490
2491    #[test]
2492    fn exact_class_method_resolution_preserves_error_precedence() {
2493        use fallow_types::extract::MemberKind;
2494
2495        let (temp, mut graph) = exact_class_method_fixture();
2496        let root = temp.path();
2497        for (file, owner, member, expected) in [
2498            (
2499                "missing.ts",
2500                "Repository",
2501                "run",
2502                SemanticClassMethodResolutionError::FileNotFound,
2503            ),
2504            (
2505                "repository.ts",
2506                "Repository",
2507                "missing",
2508                SemanticClassMethodResolutionError::SymbolNotFound,
2509            ),
2510        ] {
2511            assert_eq!(
2512                semantic_symbol_for_exact_class_method(&graph, root, file, owner, member),
2513                Err(expected),
2514            );
2515        }
2516        graph.modules_mut()[0].exports[0].members[2].kind = MemberKind::ClassProperty;
2517        assert_eq!(
2518            semantic_symbol_for_exact_class_method(
2519                &graph,
2520                root,
2521                "repository.ts",
2522                "Repository",
2523                "run"
2524            ),
2525            Err(SemanticClassMethodResolutionError::UnsupportedSyntax),
2526        );
2527        graph.modules_mut()[0].exports[0].members[2].kind = MemberKind::ClassMethod;
2528        std::fs::remove_file(&graph.modules()[0].path).expect("remove fixture source");
2529        assert_eq!(
2530            semantic_symbol_for_exact_class_method(
2531                &graph,
2532                root,
2533                "repository.ts",
2534                "Repository",
2535                "run"
2536            ),
2537            Err(SemanticClassMethodResolutionError::SymbolNotFound),
2538        );
2539        let (_other_temp, mut other_graph) = exact_class_method_fixture();
2540        let duplicate = other_graph.modules_mut()[0]
2541            .exports
2542            .pop()
2543            .expect("fixture declares an owner");
2544        graph.modules_mut()[0].exports.push(duplicate);
2545        assert_eq!(
2546            semantic_symbol_for_exact_class_method(
2547                &graph,
2548                root,
2549                "repository.ts",
2550                "Repository",
2551                "run"
2552            ),
2553            Err(SemanticClassMethodResolutionError::AmbiguousSymbol),
2554            "owner ambiguity must be reported before reading source",
2555        );
2556    }
2557
2558    /// Build a graph where the controller declaring `Ctrl` is NOT imported by
2559    /// the entry, so its file is unreachable and every member is dead.
2560    fn build_unreachable_class_member_graph() -> ModuleGraph {
2561        let files = vec![
2562            DiscoveredFile {
2563                id: FileId(0),
2564                path: PathBuf::from("/project/src/entry.ts"),
2565                size_bytes: 100,
2566            },
2567            DiscoveredFile {
2568                id: FileId(1),
2569                path: PathBuf::from("/project/src/controller.ts"),
2570                size_bytes: 50,
2571            },
2572        ];
2573        let entry_points = vec![EntryPoint {
2574            path: PathBuf::from("/project/src/entry.ts"),
2575            source: EntryPointSource::PackageJsonMain,
2576        }];
2577        let method = |name: &str| class_method(name, 0, 4);
2578        let resolved_modules = vec![
2579            ResolvedModule {
2580                file_id: FileId(0),
2581                path: PathBuf::from("/project/src/entry.ts"),
2582                // Entry imports nothing, so controller.ts is unreachable.
2583                ..Default::default()
2584            },
2585            ResolvedModule {
2586                file_id: FileId(1),
2587                path: PathBuf::from("/project/src/controller.ts"),
2588                exports: vec![ExportInfo {
2589                    name: ExportName::Named("Ctrl".to_string()),
2590                    local_name: Some("Ctrl".to_string()),
2591                    is_type_only: false,
2592                    visibility: VisibilityTag::None,
2593                    expected_unused_reason: None,
2594                    span: oxc_span::Span::new(0, 20),
2595                    members: vec![method("dead")],
2596                    is_side_effect_used: false,
2597                    super_class: None,
2598                    deprecated: false,
2599                    deprecated_reason: None,
2600                }]
2601                .into(),
2602                ..Default::default()
2603            },
2604        ];
2605        ModuleGraph::build(&resolved_modules, &entry_points, &files)
2606    }
2607
2608    #[test]
2609    fn trace_class_member_unreachable_owner_reports_dead_reason() {
2610        // `!file_reachable` branch: the owning file is not reachable from any
2611        // entry point, so the reason states the class and its members are dead.
2612        let graph = build_unreachable_class_member_graph();
2613        let root = Path::new("/project");
2614
2615        let trace = trace_class_member(&graph, root, "src/controller.ts", "dead").unwrap();
2616        assert!(!trace.owner_file_reachable);
2617        assert!(
2618            trace.reason.contains("not reachable"),
2619            "unreachable owner reason should say so: {}",
2620            trace.reason
2621        );
2622        // The unreachable branch does not point at a member command (the file is
2623        // dead wholesale via the unused-file finding).
2624        assert!(!trace.reason.contains("--unused-class-members"));
2625    }
2626
2627    #[test]
2628    fn trace_class_member_prefers_used_owner_on_name_collision() {
2629        // Two exports declare a member of the same name; the tie-break in
2630        // `max_by_key` must prefer the used, non-type-only owner so the trace
2631        // reports the reachable class rather than a type-only shadow.
2632
2633        let files = vec![
2634            DiscoveredFile {
2635                id: FileId(0),
2636                path: PathBuf::from("/project/src/entry.ts"),
2637                size_bytes: 100,
2638            },
2639            DiscoveredFile {
2640                id: FileId(1),
2641                path: PathBuf::from("/project/src/controller.ts"),
2642                size_bytes: 50,
2643            },
2644        ];
2645        let entry_points = vec![EntryPoint {
2646            path: PathBuf::from("/project/src/entry.ts"),
2647            source: EntryPointSource::PackageJsonMain,
2648        }];
2649        let method = |name: &str| class_method(name, 0, 4);
2650        let resolved_modules = vec![
2651            ResolvedModule {
2652                file_id: FileId(0),
2653                path: PathBuf::from("/project/src/entry.ts"),
2654                resolved_imports: vec![ResolvedImport {
2655                    info: ImportInfo {
2656                        source: "./controller".to_string(),
2657                        imported_name: ImportedName::Named("UsedCtrl".to_string()),
2658                        local_name: "UsedCtrl".to_string(),
2659                        is_type_only: false,
2660                        is_type_only_star: false,
2661                        from_style: false,
2662                        span: oxc_span::Span::new(0, 10),
2663                        source_span: oxc_span::Span::default(),
2664                    },
2665                    target: ResolveResult::InternalModule(FileId(1)),
2666                }],
2667                ..Default::default()
2668            },
2669            ResolvedModule {
2670                file_id: FileId(1),
2671                path: PathBuf::from("/project/src/controller.ts"),
2672                exports: vec![
2673                    // Type-only, unreferenced owner declared FIRST: must lose the
2674                    // tie-break to the used, non-type-only owner below.
2675                    ExportInfo {
2676                        name: ExportName::Named("TypeCtrl".to_string()),
2677                        local_name: Some("TypeCtrl".to_string()),
2678                        is_type_only: true,
2679                        visibility: VisibilityTag::None,
2680                        expected_unused_reason: None,
2681                        span: oxc_span::Span::new(0, 20),
2682                        members: vec![method("shared")],
2683                        is_side_effect_used: false,
2684                        super_class: None,
2685                        deprecated: false,
2686                        deprecated_reason: None,
2687                    },
2688                    ExportInfo {
2689                        name: ExportName::Named("UsedCtrl".to_string()),
2690                        local_name: Some("UsedCtrl".to_string()),
2691                        is_type_only: false,
2692                        visibility: VisibilityTag::None,
2693                        expected_unused_reason: None,
2694                        span: oxc_span::Span::new(0, 20),
2695                        members: vec![method("shared")],
2696                        is_side_effect_used: false,
2697                        super_class: None,
2698                        deprecated: false,
2699                        deprecated_reason: None,
2700                    },
2701                ]
2702                .into(),
2703                ..Default::default()
2704            },
2705        ];
2706        let graph = ModuleGraph::build(&resolved_modules, &entry_points, &files);
2707        let root = Path::new("/project");
2708
2709        let trace = trace_class_member(&graph, root, "src/controller.ts", "shared").unwrap();
2710        assert_eq!(
2711            trace.owner_export, "UsedCtrl",
2712            "tie-break must prefer the used, non-type-only owner"
2713        );
2714        assert!(trace.owner_is_used);
2715    }
2716
2717    #[test]
2718    fn trace_nonexistent_file() {
2719        let graph = build_test_graph();
2720        let root = Path::new("/project");
2721
2722        let trace = trace_export(&graph, root, "src/nope.ts", "foo");
2723        assert!(trace.is_none());
2724    }
2725
2726    #[test]
2727    fn trace_file_edges() {
2728        let graph = build_test_graph();
2729        let root = Path::new("/project");
2730
2731        let trace = trace_file(&graph, root, "src/entry.ts").unwrap();
2732        assert!(trace.is_entry_point);
2733        assert!(trace.is_reachable);
2734        assert_eq!(trace.imports_from.len(), 1);
2735        assert_eq!(trace.imports_from[0], PathBuf::from("src/utils.ts"));
2736        assert!(trace.imported_by.is_empty());
2737    }
2738
2739    fn build_nested_duplicate_path_graph() -> ModuleGraph {
2740        let export = |name: &str| ExportInfo {
2741            name: ExportName::Named(name.to_string()),
2742            local_name: Some(name.to_string()),
2743            is_type_only: false,
2744            visibility: VisibilityTag::None,
2745            expected_unused_reason: None,
2746            span: oxc_span::Span::new(0, 20),
2747            members: vec![],
2748            is_side_effect_used: false,
2749            super_class: None,
2750            deprecated: false,
2751            deprecated_reason: None,
2752        };
2753        let nested = PathBuf::from("/project/packages/x/src/a.ts");
2754        let root_file = PathBuf::from("/project/src/a.ts");
2755        let files = vec![
2756            DiscoveredFile {
2757                id: FileId(0),
2758                path: nested.clone(),
2759                size_bytes: 20,
2760            },
2761            DiscoveredFile {
2762                id: FileId(1),
2763                path: root_file.clone(),
2764                size_bytes: 20,
2765            },
2766        ];
2767        let entry_points = vec![EntryPoint {
2768            path: root_file.clone(),
2769            source: EntryPointSource::PackageJsonMain,
2770        }];
2771        let resolved_modules = vec![
2772            ResolvedModule {
2773                file_id: FileId(0),
2774                path: nested,
2775                exports: vec![export("nestedOnly")].into(),
2776                ..Default::default()
2777            },
2778            ResolvedModule {
2779                file_id: FileId(1),
2780                path: root_file,
2781                exports: vec![export("rootOnly")].into(),
2782                ..Default::default()
2783            },
2784        ];
2785        ModuleGraph::build(&resolved_modules, &entry_points, &files)
2786    }
2787
2788    fn graph_with_module_paths(paths: &[PathBuf]) -> ModuleGraph {
2789        let files: Vec<DiscoveredFile> = paths
2790            .iter()
2791            .enumerate()
2792            .map(|(index, path)| DiscoveredFile {
2793                id: FileId(u32::try_from(index).expect("small fixture")),
2794                path: path.clone(),
2795                size_bytes: 1,
2796            })
2797            .collect();
2798        let resolved_modules: Vec<ResolvedModule> = files
2799            .iter()
2800            .map(|file| ResolvedModule {
2801                file_id: file.id,
2802                path: file.path.clone(),
2803                ..Default::default()
2804            })
2805            .collect();
2806        ModuleGraph::build(&resolved_modules, &[], &files)
2807    }
2808
2809    fn assert_lookup_matches_single_scan(graph: &ModuleGraph, root: &Path, queries: &[&str]) {
2810        let lookup = ModulePathLookup::new(graph, root);
2811        for query in queries {
2812            assert_eq!(
2813                lookup.matching(query),
2814                matching_module_indexes(graph, root, query),
2815                "query {query:?}"
2816            );
2817        }
2818    }
2819
2820    const LOOKUP_QUERIES: &[&str] = &[
2821        "src/a.ts",
2822        "./src/a.ts",
2823        "src//a.ts",
2824        r"src\a.ts",
2825        "a.ts",
2826        "x/src/a.ts",
2827        "packages/x/src/a.ts",
2828        "sub/c.ts",
2829        "c.ts",
2830        "src/",
2831        "",
2832        "missing.ts",
2833        "/elsewhere/src/a.ts",
2834    ];
2835
2836    /// The indexed lookup must return the same modules, in the same order, as
2837    /// the single-scan lookup for exact, suffix, ambiguous and missing paths.
2838    #[test]
2839    fn module_path_lookup_matches_single_scan_lookup() {
2840        let root = Path::new("/project");
2841        let paths: Vec<PathBuf> = [
2842            "src/a.ts",
2843            "packages/x/src/a.ts",
2844            "packages/y/a.ts",
2845            "src/sub/c.ts",
2846            "lib/b.ts",
2847        ]
2848        .iter()
2849        .map(|relative| root.join(relative))
2850        .collect();
2851        let graph = graph_with_module_paths(&paths);
2852        let mut queries = LOOKUP_QUERIES.to_vec();
2853        let absolute = root.join("src/a.ts").to_string_lossy().into_owned();
2854        queries.push(&absolute);
2855        assert_lookup_matches_single_scan(&graph, root, &queries);
2856    }
2857
2858    /// With real files, the canonical-root and canonical-target forms take
2859    /// part too. On macOS the temp dir sits behind a symlink.
2860    #[test]
2861    fn module_path_lookup_matches_single_scan_lookup_on_disk() {
2862        let dir = tempfile::tempdir().expect("tempdir");
2863        let root = dir.path();
2864        for relative in ["src/a.ts", "packages/x/src/a.ts", "src/sub/c.ts"] {
2865            let path = root.join(relative);
2866            std::fs::create_dir_all(path.parent().expect("parent")).expect("mkdir");
2867            std::fs::write(&path, "").expect("write");
2868        }
2869        let canonical_root = dunce::canonicalize(root).expect("canonical root");
2870        let paths: Vec<PathBuf> = ["src/a.ts", "packages/x/src/a.ts", "src/sub/c.ts"]
2871            .iter()
2872            .map(|relative| canonical_root.join(relative))
2873            .collect();
2874        let graph = graph_with_module_paths(&paths);
2875        assert_lookup_matches_single_scan(&graph, root, LOOKUP_QUERIES);
2876    }
2877
2878    #[test]
2879    fn root_relative_path_prefers_exact_module_over_nested_suffix() {
2880        let graph = build_nested_duplicate_path_graph();
2881        let root = Path::new("/project");
2882
2883        let file = trace_file(&graph, root, "src/a.ts").expect("root file resolves");
2884        assert_eq!(file.file, PathBuf::from("src/a.ts"));
2885        assert!(file.is_entry_point);
2886
2887        let export = trace_export(&graph, root, "src/a.ts", "rootOnly");
2888        assert!(
2889            export.is_some(),
2890            "an export of the root-level file must resolve"
2891        );
2892    }
2893
2894    #[test]
2895    fn abbreviated_path_keeps_first_suffix_match() {
2896        let graph = build_nested_duplicate_path_graph();
2897        let root = Path::new("/project");
2898
2899        let file = trace_file(&graph, root, "a.ts").expect("suffix match resolves");
2900        assert_eq!(file.file, PathBuf::from("packages/x/src/a.ts"));
2901    }
2902
2903    #[test]
2904    fn trace_file_imported_by() {
2905        let graph = build_test_graph();
2906        let root = Path::new("/project");
2907
2908        let trace = trace_file(&graph, root, "src/utils.ts").unwrap();
2909        assert!(!trace.is_entry_point);
2910        assert!(trace.is_reachable);
2911        assert_eq!(trace.exports.len(), 2);
2912        assert_eq!(trace.imported_by.len(), 1);
2913        assert_eq!(trace.imported_by[0], PathBuf::from("src/entry.ts"));
2914    }
2915
2916    #[test]
2917    fn trace_unreachable_file() {
2918        let graph = build_test_graph();
2919        let root = Path::new("/project");
2920
2921        let trace = trace_file(&graph, root, "src/unused.ts").unwrap();
2922        assert!(!trace.is_reachable);
2923        assert!(!trace.is_entry_point);
2924        assert!(trace.imported_by.is_empty());
2925    }
2926
2927    #[test]
2928    fn trace_clone_finds_matching_group() {
2929        use crate::duplicates::{CloneGroup, CloneInstance, DuplicationReport, DuplicationStats};
2930        let report = DuplicationReport {
2931            clone_groups: vec![CloneGroup {
2932                instances: vec![
2933                    CloneInstance {
2934                        is_symlink: false,
2935                        file: PathBuf::from("/project/src/a.ts"),
2936                        start_line: 10,
2937                        end_line: 20,
2938                        start_col: 0,
2939                        end_col: 0,
2940                        fragment: "fn foo() {}".to_string(),
2941                    },
2942                    CloneInstance {
2943                        is_symlink: false,
2944                        file: PathBuf::from("/project/src/b.ts"),
2945                        start_line: 5,
2946                        end_line: 15,
2947                        start_col: 0,
2948                        end_col: 0,
2949                        fragment: "fn foo() {}".to_string(),
2950                    },
2951                ],
2952                token_count: 60,
2953                line_count: 11,
2954                similarity: None,
2955            }],
2956            stats: DuplicationStats {
2957                total_files: 2,
2958                files_with_clones: 2,
2959                total_lines: 100,
2960                duplicated_lines: 22,
2961                total_tokens: 200,
2962                duplicated_tokens: 120,
2963                clone_groups: 1,
2964                clone_families: 0,
2965                clone_instances: 2,
2966                duplication_percentage: 22.0,
2967                clone_groups_below_min_occurrences: 0,
2968                clone_groups_ignored: 0,
2969                near_candidates_skipped: 0,
2970            },
2971            ..Default::default()
2972        };
2973        let trace = trace_clone(&report, Path::new("/project"), "src/a.ts", 15);
2974        assert!(trace.matched_instance.is_some());
2975        assert_eq!(trace.clone_groups.len(), 1);
2976        assert_eq!(trace.clone_groups[0].instances.len(), 2);
2977        assert!(trace.clone_groups[0].fingerprint.starts_with("dup:"));
2978        assert_eq!(trace.clone_groups[0].suggestion.estimated_savings, 11);
2979    }
2980
2981    #[test]
2982    fn trace_clone_by_fingerprint_resolves_and_misses() {
2983        use crate::duplicates::{
2984            CloneGroup, CloneInstance, DuplicationReport, DuplicationStats, clone_fingerprint,
2985        };
2986        let report = DuplicationReport {
2987            clone_groups: vec![CloneGroup {
2988                instances: vec![
2989                    CloneInstance {
2990                        is_symlink: false,
2991                        file: PathBuf::from("/project/src/a.ts"),
2992                        start_line: 10,
2993                        end_line: 20,
2994                        start_col: 0,
2995                        end_col: 0,
2996                        fragment: "fn buildInvoice() {}".to_string(),
2997                    },
2998                    CloneInstance {
2999                        is_symlink: false,
3000                        file: PathBuf::from("/project/src/b.ts"),
3001                        start_line: 5,
3002                        end_line: 15,
3003                        start_col: 0,
3004                        end_col: 0,
3005                        fragment: "fn buildInvoice() {}".to_string(),
3006                    },
3007                ],
3008                token_count: 60,
3009                line_count: 11,
3010                similarity: None,
3011            }],
3012            stats: DuplicationStats::default(),
3013            ..Default::default()
3014        };
3015        let fp = clone_fingerprint(&report.clone_groups[0].instances);
3016
3017        let hit = trace_clone_by_fingerprint(&report, Path::new("/project"), &fp);
3018        assert!(hit.matched_instance.is_some());
3019        assert_eq!(hit.clone_groups.len(), 1);
3020        assert_eq!(hit.clone_groups[0].fingerprint, fp);
3021        assert_eq!(hit.line, 10);
3022
3023        let miss = trace_clone_by_fingerprint(&report, Path::new("/project"), "dup:deadbeef");
3024        assert!(miss.matched_instance.is_none());
3025        assert!(miss.clone_groups.is_empty());
3026    }
3027
3028    #[test]
3029    fn trace_clone_no_match() {
3030        use crate::duplicates::{CloneGroup, CloneInstance, DuplicationReport, DuplicationStats};
3031        let report = DuplicationReport {
3032            clone_groups: vec![CloneGroup {
3033                instances: vec![CloneInstance {
3034                    is_symlink: false,
3035                    file: PathBuf::from("/project/src/a.ts"),
3036                    start_line: 10,
3037                    end_line: 20,
3038                    start_col: 0,
3039                    end_col: 0,
3040                    fragment: "fn foo() {}".to_string(),
3041                }],
3042                token_count: 60,
3043                line_count: 11,
3044                similarity: None,
3045            }],
3046            stats: DuplicationStats {
3047                total_files: 1,
3048                files_with_clones: 1,
3049                total_lines: 50,
3050                duplicated_lines: 11,
3051                total_tokens: 100,
3052                duplicated_tokens: 60,
3053                clone_groups: 1,
3054                clone_families: 0,
3055                clone_instances: 1,
3056                duplication_percentage: 22.0,
3057                clone_groups_below_min_occurrences: 0,
3058                clone_groups_ignored: 0,
3059                near_candidates_skipped: 0,
3060            },
3061            ..Default::default()
3062        };
3063        let trace = trace_clone(&report, Path::new("/project"), "src/a.ts", 25);
3064        assert!(trace.matched_instance.is_none());
3065        assert!(trace.clone_groups.is_empty());
3066    }
3067
3068    #[test]
3069    fn trace_clone_line_boundary() {
3070        use crate::duplicates::{CloneGroup, CloneInstance, DuplicationReport, DuplicationStats};
3071        let report = DuplicationReport {
3072            clone_groups: vec![CloneGroup {
3073                instances: vec![
3074                    CloneInstance {
3075                        is_symlink: false,
3076                        file: PathBuf::from("/project/src/a.ts"),
3077                        start_line: 10,
3078                        end_line: 20,
3079                        start_col: 0,
3080                        end_col: 0,
3081                        fragment: "code".to_string(),
3082                    },
3083                    CloneInstance {
3084                        is_symlink: false,
3085                        file: PathBuf::from("/project/src/b.ts"),
3086                        start_line: 1,
3087                        end_line: 11,
3088                        start_col: 0,
3089                        end_col: 0,
3090                        fragment: "code".to_string(),
3091                    },
3092                ],
3093                token_count: 50,
3094                line_count: 11,
3095                similarity: None,
3096            }],
3097            stats: DuplicationStats {
3098                total_files: 2,
3099                files_with_clones: 2,
3100                total_lines: 100,
3101                duplicated_lines: 22,
3102                total_tokens: 200,
3103                duplicated_tokens: 100,
3104                clone_groups: 1,
3105                clone_families: 0,
3106                clone_instances: 2,
3107                duplication_percentage: 22.0,
3108                clone_groups_below_min_occurrences: 0,
3109                clone_groups_ignored: 0,
3110                near_candidates_skipped: 0,
3111            },
3112            ..Default::default()
3113        };
3114        let root = Path::new("/project");
3115        assert!(
3116            trace_clone(&report, root, "src/a.ts", 10)
3117                .matched_instance
3118                .is_some()
3119        );
3120        assert!(
3121            trace_clone(&report, root, "src/a.ts", 20)
3122                .matched_instance
3123                .is_some()
3124        );
3125        assert!(
3126            trace_clone(&report, root, "src/a.ts", 21)
3127                .matched_instance
3128                .is_none()
3129        );
3130    }
3131
3132    #[test]
3133    fn trace_clone_returns_relative_instance_paths() {
3134        use crate::duplicates::{CloneGroup, CloneInstance, DuplicationReport, DuplicationStats};
3135        let report = DuplicationReport {
3136            clone_groups: vec![CloneGroup {
3137                instances: vec![
3138                    CloneInstance {
3139                        is_symlink: false,
3140                        file: PathBuf::from("/project/src/a.ts"),
3141                        start_line: 1,
3142                        end_line: 10,
3143                        start_col: 0,
3144                        end_col: 0,
3145                        fragment: "code".to_string(),
3146                    },
3147                    CloneInstance {
3148                        is_symlink: false,
3149                        file: PathBuf::from("/project/src/b.ts"),
3150                        start_line: 1,
3151                        end_line: 10,
3152                        start_col: 0,
3153                        end_col: 0,
3154                        fragment: "code".to_string(),
3155                    },
3156                ],
3157                token_count: 50,
3158                line_count: 10,
3159                similarity: None,
3160            }],
3161            stats: DuplicationStats {
3162                total_files: 2,
3163                files_with_clones: 2,
3164                total_lines: 50,
3165                duplicated_lines: 20,
3166                total_tokens: 100,
3167                duplicated_tokens: 100,
3168                clone_groups: 1,
3169                clone_families: 0,
3170                clone_instances: 2,
3171                duplication_percentage: 40.0,
3172                clone_groups_below_min_occurrences: 0,
3173                clone_groups_ignored: 0,
3174                near_candidates_skipped: 0,
3175            },
3176            ..Default::default()
3177        };
3178        let trace = trace_clone(&report, Path::new("/project"), "src/a.ts", 5);
3179        let matched = trace.matched_instance.as_ref().expect("match expected");
3180        assert_eq!(matched.file, PathBuf::from("src/a.ts"));
3181        for group in &trace.clone_groups {
3182            for inst in &group.instances {
3183                let as_str = inst.file.to_string_lossy();
3184                assert!(
3185                    !as_str.starts_with('/'),
3186                    "instance file should be relative, got {as_str}",
3187                );
3188                assert!(
3189                    !as_str.contains(":\\") && !as_str.contains(":/"),
3190                    "instance file should not have a drive letter, got {as_str}",
3191                );
3192            }
3193        }
3194
3195        let json = serde_json::to_string(&trace).expect("serializes");
3196        assert!(
3197            !json.contains("\"/project/"),
3198            "serialized trace should not leak absolute paths: {json}",
3199        );
3200    }
3201
3202    /// Regression for the MCP e2e `trace_export` / `trace_file` Windows
3203    /// failures: the MCP layer passes forward-slashed user input
3204    /// (`src/utils.ts`) but `module_path` on Windows uses backslash
3205    /// separators (`D:\a\fallow\...\src\utils.ts`). The byte-level
3206    /// equality check missed every match. The lookup now normalises
3207    /// both sides to forward slashes before comparing.
3208    fn single_module_graph(path: &str) -> ModuleGraph {
3209        let path = PathBuf::from(path);
3210        let files = vec![DiscoveredFile {
3211            id: FileId(0),
3212            path: path.clone(),
3213            size_bytes: 10,
3214        }];
3215        let resolved_modules = vec![ResolvedModule {
3216            file_id: FileId(0),
3217            path,
3218            ..Default::default()
3219        }];
3220        ModuleGraph::build(&resolved_modules, &[], &files)
3221    }
3222
3223    #[test]
3224    fn find_module_normalises_windows_module_path_against_posix_user_path() {
3225        let root = Path::new(r"D:\a\fallow\fallow\tests\fixtures\basic-project");
3226        let graph =
3227            single_module_graph(r"D:\a\fallow\fallow\tests\fixtures\basic-project\src\utils.ts");
3228        assert!(find_module(&graph, root, "src/utils.ts").is_some());
3229        assert!(find_module(&graph, root, r"src\utils.ts").is_some());
3230    }
3231
3232    #[test]
3233    fn find_module_suffix_fallback_handles_mixed_separators() {
3234        let root = Path::new("/some/other/root");
3235        let graph =
3236            single_module_graph(r"D:\a\fallow\fallow\tests\fixtures\basic-project\src\utils.ts");
3237        assert!(find_module(&graph, root, "src/utils.ts").is_some());
3238    }
3239
3240    /// Regression for the MCP e2e trace_export / trace_file failures: even
3241    /// after `find_module` correctly identified the file on Windows, the
3242    /// trace output struct's `file: PathBuf` field serialized the stored
3243    /// backslash-shaped path verbatim. JSON consumers (MCP agents, CI
3244    /// pipelines, the cross-platform trace_file assertion in
3245    /// `e2e_trace_file_returns_json`) expect forward-slash. Pin the
3246    /// contract via raw-string Windows-shaped `PathBuf::from` so the test
3247    /// runs cross-platform.
3248    #[test]
3249    fn export_trace_serializes_windows_path_with_forward_slashes() {
3250        let trace = ExportTrace {
3251            file: PathBuf::from(r"src\utils.ts"),
3252            export_name: "foo".to_string(),
3253            namespace: fallow_types::semantic::SemanticNamespace::Value,
3254            file_reachable: true,
3255            is_entry_point: false,
3256            is_used: true,
3257            direct_references: vec![ExportReference::new(
3258                PathBuf::from(r"src\entry.ts"),
3259                "named import".to_string(),
3260            )],
3261            direct_references_by_namespace: Vec::new(),
3262            star_export_ambiguity: None,
3263            re_export_chains: vec![ReExportChain {
3264                barrel_file: PathBuf::from(r"src\index.ts"),
3265                exported_as: "foo".to_string(),
3266                reference_count: 1,
3267            }],
3268            plugin_credits: Vec::new(),
3269            kept_by_tag: None,
3270            kept_by_signature: None,
3271            reason: "ok".to_string(),
3272            semantic: None,
3273        };
3274        let json = serde_json::to_string(&trace).expect("serializes");
3275        assert!(
3276            json.contains("\"file\":\"src/utils.ts\""),
3277            "ExportTrace.file must serialize with forward slashes: {json}"
3278        );
3279        assert!(
3280            json.contains("\"from_file\":\"src/entry.ts\""),
3281            "ExportReference.from_file must serialize with forward slashes: {json}"
3282        );
3283        assert!(
3284            json.contains("\"barrel_file\":\"src/index.ts\""),
3285            "ReExportChain.barrel_file must serialize with forward slashes: {json}"
3286        );
3287        assert!(
3288            !json.contains(r"\\"),
3289            "no backslash sequence should remain anywhere in the JSON: {json}"
3290        );
3291    }
3292
3293    #[test]
3294    fn file_trace_serializes_windows_paths_with_forward_slashes() {
3295        let trace = FileTrace {
3296            file: PathBuf::from(r"src\utils.ts"),
3297            is_reachable: true,
3298            is_entry_point: false,
3299            exports: vec![],
3300            imports_from: vec![PathBuf::from(r"src\helpers.ts")],
3301            imported_by: vec![PathBuf::from(r"src\entry.ts")],
3302            re_exports: vec![TracedReExport {
3303                source_file: PathBuf::from(r"src\source.ts"),
3304                imported_name: "foo".to_string(),
3305                exported_name: "foo".to_string(),
3306            }],
3307            ..FileTrace::default()
3308        };
3309        let json = serde_json::to_string(&trace).expect("serializes");
3310        assert!(json.contains("\"file\":\"src/utils.ts\""), "got {json}");
3311        assert!(
3312            json.contains("\"imports_from\":[\"src/helpers.ts\"]"),
3313            "got {json}"
3314        );
3315        assert!(
3316            json.contains("\"imported_by\":[\"src/entry.ts\"]"),
3317            "got {json}"
3318        );
3319        assert!(
3320            json.contains("\"source_file\":\"src/source.ts\""),
3321            "got {json}"
3322        );
3323        assert!(!json.contains(r"\\"), "no backslash should remain: {json}");
3324    }
3325}