Skip to main content

fallow_graph/graph/
mod.rs

1//! Module dependency graph with re-export chain propagation and reachability analysis.
2//!
3//! The graph is built from resolved modules and entry points, then used to determine
4//! which files are reachable and which exports are referenced.
5
6mod ambiguity;
7mod build;
8mod cycle_edge_span;
9mod cycles;
10mod effective_exports;
11mod effective_re_exports;
12mod entry_load;
13mod entry_marks;
14mod fan_io;
15mod impact_closure;
16mod namespace_aliases;
17mod namespace_escapes;
18mod namespace_indexes;
19mod namespace_re_exports;
20mod narrowing;
21pub mod package_entry;
22mod partition_order;
23mod public_exports;
24mod re_exports;
25mod reachability;
26mod shortest_import_path;
27mod support_reach;
28mod test_reach;
29pub mod types;
30
31use std::path::Path;
32
33use fixedbitset::FixedBitSet;
34use rustc_hash::{FxHashMap, FxHashSet};
35
36use crate::resolve::{ResolvedModule, ResolvedReplacedModuleTarget};
37use fallow_types::discover::{DiscoveredFile, EntryPoint, FileId};
38use fallow_types::extract::{ImportLoadKind, ImportedName, ModuleLoadMechanism};
39use types::{ReferencePathInterner, ReferencePathNode, ReferenceRouteNodeId, ReferenceRoutes};
40
41/// Strip `root` and forward-slash-normalize a module path so report keys match
42/// across platforms. Every report surface that emits a root-relative path key
43/// goes through this, so the four surfaces cannot drift apart.
44pub(super) fn relativize(path: &Path, root: &Path) -> String {
45    path.strip_prefix(root)
46        .unwrap_or(path)
47        .to_string_lossy()
48        .replace('\\', "/")
49}
50
51pub use ambiguity::{AmbiguityParticipants, AmbiguousStarExport};
52pub use cycles::{CycleOptions, CycleSearch, MAX_CYCLE_LENGTH, MAX_CYCLES_PER_SCC};
53pub use effective_exports::{EffectiveExportBinding, EffectiveExportResolution, ExportNamespace};
54pub use effective_re_exports::EffectiveReExportRoute;
55pub use entry_load::{DominatingImport, EntryLoadClosure};
56pub use entry_marks::untracked_load_targets;
57pub use fan_io::{FocusFileFacts, FocusFileFactsPaths};
58pub use impact_closure::{
59    CoordinationGap, CoordinationGapPaths, ImpactClosure, ImpactClosurePaths,
60};
61pub use namespace_escapes::{NamespaceEscape, NamespaceEscapeReason};
62pub use partition_order::{PartitionOrder, PartitionOrderPaths, ReviewUnit, ReviewUnitPaths};
63pub use public_exports::PublicExportOrigin;
64pub use re_exports::GraphReExportCycle;
65pub use shortest_import_path::ImportPathHop;
66pub use test_reach::{ExportTestReach, ExportTestReachResult, TestMaskingState};
67pub use types::{
68    ExportSymbol, ModuleNode, ReExportEdge, ReachabilityRoots, ReferenceKind, ReferencePathId,
69    SymbolReference,
70};
71
72/// Direct declaration selected by one unique effective export binding.
73#[derive(Debug, Clone, Copy)]
74pub struct EffectiveExportOrigin<'graph> {
75    file_id: FileId,
76    export: &'graph ExportSymbol,
77}
78
79/// One namespace-specific export exposed by a module and its effective binding.
80#[derive(Debug, Clone, Copy)]
81pub struct EffectiveExportSurface<'graph> {
82    binding: EffectiveExportBinding,
83    namespace: ExportNamespace,
84    export: Option<&'graph ExportSymbol>,
85    origin: Option<EffectiveExportOrigin<'graph>>,
86    local_export: bool,
87}
88
89impl<'graph> EffectiveExportSurface<'graph> {
90    /// Canonical binding exposed by the requested module/name/namespace.
91    #[must_use]
92    pub const fn binding(self) -> EffectiveExportBinding {
93        self.binding
94    }
95
96    /// Namespace selected for this surface.
97    #[must_use]
98    pub const fn namespace(self) -> ExportNamespace {
99        self.namespace
100    }
101
102    /// Reference-bearing graph export selected for this surface.
103    ///
104    /// Direct declarations use their origin export. Named re-exports use their
105    /// single barrel surface while references remain namespace-specific;
106    /// namespace objects and implicit SFC defaults have no declaration export.
107    #[must_use]
108    pub const fn export(self) -> Option<&'graph ExportSymbol> {
109        self.export
110    }
111
112    /// Direct declaration that owns this binding, when one exists.
113    #[must_use]
114    pub const fn origin(self) -> Option<EffectiveExportOrigin<'graph>> {
115        self.origin
116    }
117}
118
119impl<'graph> EffectiveExportOrigin<'graph> {
120    /// Module that owns the selected declaration.
121    #[must_use]
122    pub const fn file_id(self) -> FileId {
123        self.file_id
124    }
125
126    /// Selected declaration in its owning module.
127    #[must_use]
128    pub const fn export(self) -> &'graph ExportSymbol {
129        self.export
130    }
131}
132
133/// True when the path's final component looks like a TypeScript declaration
134/// file (`.d.ts`, `.d.mts`, `.d.cts`). Used to seed declaration files as
135/// overall entry points so ambient `typeof import()` references stay alive;
136/// see [`ModuleGraph::build_with_declaration_seeding`] for the exception.
137///
138/// The analysis layer reuses this predicate. Keep it in sync with the
139/// discovery walk's declaration-file predicate, which exempts declaration
140/// files from the file-size skip.
141#[must_use]
142pub fn is_declaration_file_path(path: &Path) -> bool {
143    path.file_name()
144        .and_then(|n| n.to_str())
145        .is_some_and(|name| {
146            name.ends_with(".d.ts") || name.ends_with(".d.mts") || name.ends_with(".d.cts")
147        })
148}
149
150/// The core module dependency graph.
151///
152/// Derives `serde` so the whole graph can be persisted to `.fallow/graph-cache.bin`
153/// (see `crate::cache`) and skipped on a re-run whose inputs are byte-identical.
154/// `namespace_imported` is a derived `FixedBitSet` reconstructed from the edge
155/// set on cache load (`reconstruct_namespace_imported`), so it is
156/// `#[serde(skip, default)]` rather than persisted.
157#[derive(Debug, serde::Serialize, serde::Deserialize)]
158pub struct ModuleGraph {
159    /// All modules indexed by `FileId`.
160    ///
161    /// Invariant: `modules[file_id.0 as usize].file_id == file_id` for every
162    /// `FileId` in the graph. Holds because `discover/walk.rs` assigns FileIds
163    /// sequentially via `.enumerate()` after path-sorting, and
164    /// `build::populate_edges` pushes one `ModuleNode` per file in iteration
165    /// order. Detectors rely on this for O(1) FileId-to-module lookup
166    /// (`graph.modules.get(file_id.0 as usize)`) instead of building a
167    /// per-call `FxHashMap<FileId, &ModuleNode>`.
168    pub modules: Vec<ModuleNode>,
169    /// Flat edge storage for cache-friendly iteration.
170    edges: Vec<Edge>,
171    /// Maps npm package names to the `FileId`s that import them, with one
172    /// entry per import. A file with two imports of a package appears twice.
173    pub package_usage: FxHashMap<String, Vec<FileId>>,
174    /// Maps npm package names to the `FileId`s that import them with type-only
175    /// imports, with one entry per type-only import.
176    /// A package appearing here but not in `package_usage` (or only in both) indicates
177    /// it's only used for types and could be a devDependency.
178    pub type_only_package_usage: FxHashMap<String, Vec<FileId>>,
179    /// Maps npm package names to the `FileId`s that read a file of the
180    /// package through a webpack asset loader (`raw-loader!pkg/file.txt`).
181    /// The bundle holds the text, the bytes or a URL of the file, so the
182    /// package is used at build time and the import is not a runtime import.
183    /// Every entry is also in `package_usage`.
184    pub asset_package_usage: FxHashMap<String, Vec<FileId>>,
185    /// Package specifiers that each module imports statically with a runtime
186    /// value (no `import()`, no type-only import). Read by the startup weight
187    /// report to list the packages on the startup path of an entry.
188    pub eager_package_imports: FxHashMap<FileId, Vec<EagerPackageImport>>,
189    /// All entry point `FileId`s.
190    pub entry_points: FxHashSet<FileId>,
191    /// Runtime/application entry point `FileId`s.
192    pub runtime_entry_points: FxHashSet<FileId>,
193    /// Test entry point `FileId`s.
194    pub test_entry_points: FxHashSet<FileId>,
195    /// Support entry point `FileId`s, such as files that package.json scripts run.
196    support_entry_points: FxHashSet<FileId>,
197    /// Compact correlation index for distinct test-root replacement profiles.
198    ///
199    /// Empty when no test root declares a project-internal replacement. That
200    /// preserves the ordinary single-BFS test reachability path.
201    test_reachability_index: TestReachabilityIndex,
202    /// Flat interned linked paths used by exact export references.
203    reference_paths: Vec<ReferencePathNode>,
204    /// Compact transition graphs used by namespace-derived references.
205    reference_routes: ReferenceRoutes,
206    /// Reverse index: for each `FileId`, which files import it.
207    pub reverse_deps: Vec<Vec<FileId>>,
208    /// Precomputed: which modules have namespace imports (import * as ns).
209    ///
210    /// Derived entirely from the edge set (a module is namespace-imported iff
211    /// some edge to it carries an `ImportedName::Namespace` symbol), so it is
212    /// not persisted: on cache load it is rebuilt by
213    /// [`ModuleGraph::reconstruct_namespace_imported`], which replicates the
214    /// exact insertion logic from `build.rs`.
215    #[serde(skip, default)]
216    namespace_imported: FixedBitSet,
217    /// Re-export cycles and self-loops detected during Phase 4 chain
218    /// resolution. Each entry names the participating files (sorted
219    /// lexicographically) and a `is_self_loop` flag distinguishing
220    /// single-file self-re-exports from multi-node cycles. Populated by
221    /// `re_exports::find_re_export_cycles` and consumed by the analysis
222    /// backend, which wraps each entry in a typed `ReExportCycleFinding`.
223    pub re_export_cycles: Vec<GraphReExportCycle>,
224    /// Namespace bindings that get the full export credit of their target,
225    /// sorted by consumer and import position. See [`NamespaceEscape`].
226    pub namespace_escapes: Vec<NamespaceEscape>,
227    /// Canonical direct and transitive export binding resolution.
228    effective_exports: effective_exports::EffectiveExportIndex,
229}
230
231/// An edge in the module graph.
232///
233/// Public consumers inspect relationships through summary methods such as
234/// [`ModuleGraph::direct_importer_summaries`] and
235/// [`ModuleGraph::outgoing_edge_summaries`]. Keeping the raw storage private
236/// preserves graph invariants and the `Edge == 32` size assertion below.
237#[derive(Debug, serde::Serialize, serde::Deserialize)]
238pub struct Edge {
239    /// Source module of this import edge.
240    source: FileId,
241    /// Target module imported by `source`.
242    target: FileId,
243    /// Symbols imported across this edge.
244    symbols: Vec<ImportedSymbol>,
245}
246
247impl Edge {
248    /// Whether the target can run as code through this edge (see
249    /// [`ImportLoadKind::runs_target_code`]). An edge whose every symbol is an
250    /// asset reference keeps the target in use, but reachability does not
251    /// continue into the imports of the target.
252    #[must_use]
253    fn runs_target_code(&self) -> bool {
254        self.symbols.is_empty()
255            || self
256                .symbols
257                .iter()
258                .any(|symbol| symbol.load_kind.runs_target_code())
259    }
260
261    /// Whether a test that loads the target through this edge runs target
262    /// code. The build erases a type-only import before the test runs, so an
263    /// edge whose every symbol is type-only gives no test reach. Dead-code
264    /// reachability keeps [`Self::runs_target_code`].
265    #[must_use]
266    fn runs_target_code_in_tests(&self) -> bool {
267        self.symbols.is_empty()
268            || self
269                .symbols
270                .iter()
271                .any(|symbol| !symbol.is_type_only && symbol.load_kind.runs_target_code())
272    }
273}
274
275/// One package specifier that a module imports statically with a runtime value.
276#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
277pub struct EagerPackageImport {
278    /// The package name, for example `lodash` or `@scope/pkg`.
279    pub package: String,
280    /// The specifier as written, for example `lodash/debounce`.
281    pub specifier: String,
282}
283
284/// A symbol imported across an edge.
285#[derive(Debug, serde::Serialize, serde::Deserialize)]
286pub struct ImportedSymbol {
287    /// The name as imported from the target (`Named`, `Default`, `Namespace`,
288    /// `SideEffect`).
289    pub imported_name: ImportedName,
290    /// Local binding name in the importing file.
291    pub local_name: String,
292    /// Byte span of the import statement in the source file.
293    #[serde(with = "crate::cache::span_serde")]
294    pub import_span: oxc_span::Span,
295    /// Whether this import is type-only (`import type { ... }`).
296    /// Used to skip type-only edges in circular dependency detection.
297    pub is_type_only: bool,
298    /// Whether the ambient star this symbol stands for is spelled
299    /// `export type *` (issue #2375), which forwards type meanings only.
300    pub(crate) is_type_only_star: bool,
301    /// Runtime module mechanism that created this symbol edge.
302    mechanism: ModuleLoadMechanism,
303    /// When the target loads relative to the importer, and whether it runs
304    /// at all. Fits in the padding after the flags, so the 64-byte size
305    /// assertion holds.
306    load_kind: ImportLoadKind,
307}
308
309impl ImportedSymbol {
310    /// When the target of this symbol edge loads, relative to the importer.
311    #[must_use]
312    pub const fn load_kind(&self) -> ImportLoadKind {
313        self.load_kind
314    }
315
316    /// Whether this symbol loads its target before the importer runs and
317    /// carries a runtime value, so the target is on the startup path.
318    #[must_use]
319    pub const fn is_eager_value(&self) -> bool {
320        self.load_kind.is_eager_value(self.is_type_only)
321    }
322
323    /// Whether this symbol runs its target (see
324    /// [`ImportLoadKind::loads_target`]). A path reference and an asset
325    /// reference keep the target in use without running it.
326    #[must_use]
327    pub const fn loads_target(&self) -> bool {
328        self.load_kind.loads_target()
329    }
330
331    /// Whether this symbol is the whole-module shape of `export *` or
332    /// `export * as ns` inside a `declare module '...'` body (issue #2357):
333    /// type-only, bound to no local name, and naming the module namespace or
334    /// its `default` member (recorded for the `export * as ns` form).
335    ///
336    /// The ambient body is erased at runtime, so package usage stays
337    /// type-only, but the star forwards every export of the target, so the
338    /// graph credits its star surface instead of narrowing to imported names.
339    /// Every other type-only symbol, bound (`import type { x }`) or not (an
340    /// ambient named re-export, an `import()` type reference), credits the
341    /// names it actually imports.
342    #[must_use]
343    fn is_ambient_star(&self) -> bool {
344        self.is_type_only
345            && self.local_name.is_empty()
346            && matches!(
347                self.imported_name,
348                ImportedName::Namespace | ImportedName::Default
349            )
350    }
351
352    /// Whether this ambient star forwards both meanings of every name it
353    /// carries.
354    ///
355    /// `export *` inside the body re-exports the target's value and type
356    /// declarations alike, so it credits both namespaces. `export type *`
357    /// erases every value meaning (issue #2375), so it credits type space
358    /// only, exactly like the ambient named re-exports of issue #2349.
359    #[must_use]
360    fn is_value_bearing_ambient_star(&self) -> bool {
361        self.is_ambient_star() && !self.is_type_only_star
362    }
363}
364
365/// Flat bitset index mapping files to the test profiles that reach them.
366///
367/// Each file owns `words_per_file` contiguous reachable-profile words. Masks are
368/// target-sparse: only explicit replacement targets own a row, while every row
369/// retains dense profile words for constant-time word lookup. Retained storage
370/// is `O((files + replaced_targets) * ceil(profiles / 64))`; correlation queries
371/// intersect machine words instead of scanning profile file lists.
372#[derive(Debug, Default, serde::Serialize, serde::Deserialize)]
373struct TestReachabilityIndex {
374    profile_count: usize,
375    words_per_file: usize,
376    reachable_profiles: Vec<u64>,
377    masked_profiles: Vec<MaskedTestProfiles>,
378    /// The test roots of each profile, by profile index. The per-root query
379    /// reads it to find the replacement mask of one root.
380    profile_roots: Vec<Vec<FileId>>,
381    /// True when test roots declare replacement masks, but the distinct mask
382    /// count passed the profile safety cap. Reachability then ignores the
383    /// masks, so a mocked module counts as reached.
384    masking_capped: bool,
385}
386
387/// Sparse profile-mask row for one replaced target.
388#[derive(Debug, serde::Serialize, serde::Deserialize)]
389struct MaskedTestProfiles {
390    target: FileId,
391    profiles: Vec<u64>,
392}
393
394impl TestReachabilityIndex {
395    fn new(file_capacity: usize, profile_count: usize) -> Self {
396        let words_per_file = profile_count.div_ceil(u64::BITS as usize);
397        let storage_len = file_capacity.saturating_mul(words_per_file);
398        Self {
399            profile_count,
400            words_per_file,
401            reachable_profiles: vec![0; storage_len],
402            masked_profiles: Vec::new(),
403            profile_roots: Vec::new(),
404            masking_capped: false,
405        }
406    }
407
408    /// The replaced targets of each test root that has a replacement, sorted
409    /// by target id.
410    fn root_masks(&self) -> FxHashMap<FileId, Vec<FileId>> {
411        let mut masks: FxHashMap<FileId, Vec<FileId>> = FxHashMap::default();
412        for row in &self.masked_profiles {
413            for (profile, roots) in self.profile_roots.iter().enumerate() {
414                let masked = row
415                    .profiles
416                    .get(profile / u64::BITS as usize)
417                    .is_some_and(|word| word & (1_u64 << (profile % u64::BITS as usize)) != 0);
418                if !masked {
419                    continue;
420                }
421                for &root in roots {
422                    masks.entry(root).or_default().push(row.target);
423                }
424            }
425        }
426        masks
427    }
428
429    fn set_sparse_masks(&mut self, masks: FxHashMap<FileId, Vec<u64>>) {
430        let mut rows: Vec<_> = masks
431            .into_iter()
432            .map(|(target, profiles)| MaskedTestProfiles { target, profiles })
433            .collect();
434        rows.sort_unstable_by_key(|row| row.target.0);
435        self.masked_profiles = rows;
436    }
437
438    fn profiles_for<'a>(&self, storage: &'a [u64], file_id: FileId) -> Option<&'a [u64]> {
439        let start = (file_id.0 as usize).checked_mul(self.words_per_file)?;
440        let end = start.checked_add(self.words_per_file)?;
441        storage.get(start..end)
442    }
443
444    fn masked_profiles_for(&self, file_id: FileId) -> Option<&[u64]> {
445        self.masked_profiles
446            .binary_search_by_key(&file_id.0, |row| row.target.0)
447            .ok()
448            .map(|index| self.masked_profiles[index].profiles.as_slice())
449    }
450
451    fn covers_reference_path(
452        &self,
453        source: FileId,
454        path: types::ReferencePathId,
455        paths: &[ReferencePathNode],
456        routes: &ReferenceRoutes,
457    ) -> bool {
458        let Some(source_profiles) = self.profiles_for(&self.reachable_profiles, source) else {
459            return false;
460        };
461
462        for (word_index, &source_word) in source_profiles.iter().enumerate() {
463            let mut active_profiles = source_word;
464            if active_profiles == 0 {
465                continue;
466            }
467
468            let mut next = Some(path);
469            while let Some(path_id) = next {
470                let Some(path_node) = paths.get(path_id.index()) else {
471                    return false;
472                };
473                next = path_node.parent();
474                active_profiles = match *path_node {
475                    ReferencePathNode::Hop {
476                        target, mechanism, ..
477                    } => self.active_hop_profiles(target, mechanism, word_index, active_profiles),
478                    ReferencePathNode::Route {
479                        graph,
480                        start,
481                        terminal,
482                        start_mechanism,
483                        ..
484                    } => self.active_route_profiles(
485                        routes,
486                        graph,
487                        start,
488                        terminal,
489                        start_mechanism,
490                        word_index,
491                        active_profiles,
492                    ),
493                };
494                if active_profiles == 0 {
495                    break;
496                }
497            }
498
499            if active_profiles != 0 {
500                return true;
501            }
502        }
503
504        false
505    }
506
507    fn active_hop_profiles(
508        &self,
509        target: FileId,
510        mechanism: ModuleLoadMechanism,
511        word_index: usize,
512        mut active_profiles: u64,
513    ) -> u64 {
514        let Some(target_word) = self
515            .profiles_for(&self.reachable_profiles, target)
516            .and_then(|profiles| profiles.get(word_index))
517        else {
518            return 0;
519        };
520        active_profiles &= target_word;
521        if matches!(mechanism, ModuleLoadMechanism::EsModule)
522            && let Some(masked_profiles) = self.masked_profiles_for(target)
523        {
524            let Some(masked_word) = masked_profiles.get(word_index) else {
525                return 0;
526            };
527            active_profiles &= !masked_word;
528        }
529        active_profiles
530    }
531
532    /// Evaluate one compact namespace transition graph with a monotone
533    /// profile-bit worklist. Each `(route node, profile bit)` is processed at
534    /// most once, including cyclic graphs.
535    #[expect(
536        clippy::too_many_arguments,
537        reason = "the route identity and profile word form one evaluation contract"
538    )]
539    fn active_route_profiles(
540        &self,
541        routes: &ReferenceRoutes,
542        graph_id: types::ReferenceRouteGraphId,
543        start: ReferenceRouteNodeId,
544        terminal: ReferenceRouteNodeId,
545        start_mechanism: Option<ModuleLoadMechanism>,
546        word_index: usize,
547        candidate_profiles: u64,
548    ) -> u64 {
549        let Some(graph) = routes.graphs.get(graph_id.0 as usize) else {
550            return 0;
551        };
552        let node_count = graph.nodes.end.saturating_sub(graph.nodes.start) as usize;
553        let start_index = start.0 as usize;
554        let terminal_index = terminal.0 as usize;
555        if start_index >= node_count || terminal_index >= node_count {
556            return 0;
557        }
558
559        let mut attempted = vec![0_u64; node_count];
560        let mut pending = vec![0_u64; node_count];
561        let mut queued = vec![false; node_count];
562        let mut queue = std::collections::VecDeque::from([start_index]);
563        pending[start_index] = candidate_profiles;
564        queued[start_index] = true;
565        let mut successful_profiles = 0_u64;
566
567        while let Some(local_index) = queue.pop_front() {
568            queued[local_index] = false;
569            let incoming = pending[local_index] & !attempted[local_index];
570            pending[local_index] = 0;
571            attempted[local_index] |= incoming;
572            if incoming == 0 {
573                continue;
574            }
575
576            let Some(node) = routes.nodes.get(graph.nodes.start as usize + local_index) else {
577                return 0;
578            };
579            let active = if local_index == start_index {
580                start_mechanism.map_or(incoming, |mechanism| {
581                    self.active_hop_profiles(node.target, mechanism, word_index, incoming)
582                })
583            } else {
584                self.active_hop_profiles(node.target, node.mechanism, word_index, incoming)
585            };
586            if active == 0 {
587                continue;
588            }
589            if local_index == terminal_index {
590                successful_profiles |= active;
591                continue;
592            }
593
594            let Some(successors) = routes
595                .edges
596                .get(node.successors.start as usize..node.successors.end as usize)
597            else {
598                return 0;
599            };
600            for successor in successors {
601                let successor_index = successor.0 as usize;
602                if successor_index >= node_count {
603                    return 0;
604                }
605                let new_profiles = active & !attempted[successor_index] & !pending[successor_index];
606                if new_profiles == 0 {
607                    continue;
608                }
609                pending[successor_index] |= new_profiles;
610                if !queued[successor_index] {
611                    queued[successor_index] = true;
612                    queue.push_back(successor_index);
613                }
614            }
615        }
616
617        successful_profiles
618    }
619
620    #[cfg(test)]
621    fn profile_contains(&self, storage: &[u64], file_id: FileId, profile: usize) -> bool {
622        self.profiles_for(storage, file_id)
623            .and_then(|words| words.get(profile / u64::BITS as usize))
624            .is_some_and(|word| word & (1_u64 << (profile % u64::BITS as usize)) != 0)
625    }
626
627    #[cfg(test)]
628    fn profile_reaches(&self, file_id: FileId, profile: usize) -> bool {
629        self.profile_contains(&self.reachable_profiles, file_id, profile)
630    }
631
632    #[cfg(test)]
633    fn profile_masks(&self, file_id: FileId, profile: usize) -> bool {
634        self.masked_profiles_for(file_id)
635            .and_then(|words| words.get(profile / u64::BITS as usize))
636            .is_some_and(|word| word & (1_u64 << (profile % u64::BITS as usize)) != 0)
637    }
638}
639
640/// One outgoing edge that runs its target, from
641/// [`ModuleGraph::outgoing_edge_summaries`].
642#[derive(Debug, Clone, Copy)]
643pub struct OutgoingEdgeSummary<'a> {
644    /// The imported module.
645    pub target: FileId,
646    /// Whether every symbol that loads the target is type-only, so the build
647    /// erases the import.
648    pub all_type_only: bool,
649    /// Byte offset of the first value symbol that loads the target, or of
650    /// the first loading symbol when all of them are type-only.
651    pub span_start: Option<u32>,
652    /// Every symbol of the edge, also the symbols that do not load the
653    /// target. Filter with [`ImportedSymbol::loads_target`].
654    pub symbols: &'a [ImportedSymbol],
655}
656
657/// Importer details for one file that directly imports a target module.
658#[derive(Debug, Clone, PartialEq, Eq)]
659pub struct DirectImporterSummary {
660    /// Source file that imports the requested target.
661    pub source: FileId,
662    /// Symbols imported from the target by this source file.
663    pub symbols: Vec<ImportedSymbolSummary>,
664}
665
666/// Symbol details for a direct import edge.
667#[derive(Debug, Clone, PartialEq, Eq)]
668pub struct ImportedSymbolSummary {
669    /// Imported binding name, using `default`, `*`, and `side-effect` for
670    /// non-named imports.
671    pub imported: String,
672    /// Local binding name in the importing file.
673    pub local: String,
674    /// Whether this symbol came from a type-only import.
675    pub type_only: bool,
676}
677
678#[cfg(target_pointer_width = "64")]
679const _: () = assert!(std::mem::size_of::<Edge>() == 32);
680#[cfg(target_pointer_width = "64")]
681const _: () = assert!(std::mem::size_of::<ImportedSymbol>() == 64);
682
683#[cold]
684#[inline(never)]
685fn propagate_namespace_references(
686    graph: &mut ModuleGraph,
687    module_by_id: &FxHashMap<FileId, &ResolvedModule>,
688    features: build::NamespaceFeatures,
689    exposed_namespace_targets: &re_exports::ExposedNamespaceTargets,
690    reference_paths: &mut ReferencePathInterner,
691) {
692    let indexes = namespace_indexes::NamespacePropagationIndexes::new(graph, module_by_id);
693    if features.has_aliases {
694        namespace_aliases::propagate_cross_package_aliases(
695            graph,
696            module_by_id,
697            &indexes,
698            reference_paths,
699        );
700    }
701    if features.has_re_exports {
702        namespace_re_exports::propagate_namespace_re_exports(
703            graph,
704            &indexes,
705            exposed_namespace_targets,
706            reference_paths,
707        );
708    }
709}
710
711impl ModuleGraph {
712    fn resolve_entry_point_ids(
713        entry_points: &[EntryPoint],
714        path_to_id: &FxHashMap<&Path, FileId>,
715    ) -> FxHashSet<FileId> {
716        entry_points
717            .iter()
718            .filter_map(|ep| {
719                path_to_id.get(ep.path.as_path()).copied().or_else(|| {
720                    dunce::canonicalize(&ep.path)
721                        .ok()
722                        .and_then(|path| path_to_id.get(path.as_path()).copied())
723                })
724            })
725            .collect()
726    }
727
728    /// Build the module graph from resolved modules and entry points.
729    pub fn build(
730        resolved_modules: &[ResolvedModule],
731        entry_points: &[EntryPoint],
732        files: &[DiscoveredFile],
733    ) -> Self {
734        Self::build_with_reachability_roots(
735            resolved_modules,
736            entry_points,
737            entry_points,
738            &[],
739            files,
740        )
741    }
742
743    /// Build the module graph with explicit runtime and test reachability roots.
744    fn build_with_reachability_roots(
745        resolved_modules: &[ResolvedModule],
746        entry_points: &[EntryPoint],
747        runtime_entry_points: &[EntryPoint],
748        test_entry_points: &[EntryPoint],
749        files: &[DiscoveredFile],
750    ) -> Self {
751        Self::build_with_reachability_roots_and_replacements(
752            resolved_modules,
753            &[],
754            entry_points,
755            runtime_entry_points,
756            test_entry_points,
757            files,
758        )
759    }
760
761    /// Build the module graph with root-specific test-time module replacements.
762    pub fn build_with_reachability_roots_and_replacements(
763        resolved_modules: &[ResolvedModule],
764        replaced_module_targets: &[ResolvedReplacedModuleTarget],
765        entry_points: &[EntryPoint],
766        runtime_entry_points: &[EntryPoint],
767        test_entry_points: &[EntryPoint],
768        files: &[DiscoveredFile],
769    ) -> Self {
770        Self::build_with_declaration_seeding(
771            resolved_modules,
772            replaced_module_targets,
773            &ReachabilityRoots {
774                all: entry_points,
775                runtime: runtime_entry_points,
776                test: test_entry_points,
777                consumer_checked: &FxHashSet::default(),
778            },
779            files,
780            &FxHashSet::default(),
781        )
782    }
783
784    /// Build the module graph like
785    /// [`Self::build_with_reachability_roots_and_replacements`], except that
786    /// the declaration files in `unseeded_declaration_files` are not seeded as
787    /// entry points.
788    ///
789    /// Every other declaration file is seeded so ambient declarations and
790    /// their `typeof import()` references stay alive. The caller names the
791    /// orphan module declaration files: a module declaration file that nothing
792    /// points to adds nothing to the global scope, so it must be reachable
793    /// through an import to stay used.
794    pub fn build_with_declaration_seeding(
795        resolved_modules: &[ResolvedModule],
796        replaced_module_targets: &[ResolvedReplacedModuleTarget],
797        roots: &ReachabilityRoots<'_>,
798        files: &[DiscoveredFile],
799        unseeded_declaration_files: &FxHashSet<FileId>,
800    ) -> Self {
801        let ReachabilityRoots {
802            all: entry_points,
803            runtime: runtime_entry_points,
804            test: test_entry_points,
805            consumer_checked,
806        } = *roots;
807        let _span = tracing::info_span!("build_graph").entered();
808
809        let module_count = files.len();
810
811        let max_file_id = files
812            .iter()
813            .map(|f| f.id.0 as usize)
814            .max()
815            .map_or(0, |m| m + 1);
816        let total_capacity = max_file_id.max(module_count);
817
818        let path_to_id: FxHashMap<&Path, FileId> =
819            files.iter().map(|f| (f.path.as_path(), f.id)).collect();
820
821        let module_by_id: FxHashMap<FileId, &ResolvedModule> =
822            resolved_modules.iter().map(|m| (m.file_id, m)).collect();
823
824        let mut entry_point_ids = Self::resolve_entry_point_ids(entry_points, &path_to_id);
825        let runtime_entry_point_ids =
826            Self::resolve_entry_point_ids(runtime_entry_points, &path_to_id);
827        let test_entry_point_ids = Self::resolve_entry_point_ids(test_entry_points, &path_to_id);
828
829        for file in files {
830            if is_declaration_file_path(&file.path)
831                && !unseeded_declaration_files.contains(&file.id)
832            {
833                entry_point_ids.insert(file.id);
834            }
835        }
836
837        let (mut graph, namespace_features) = Self::populate_edges(&build::PopulateEdgesInput {
838            files,
839            module_by_id: &module_by_id,
840            entry_point_ids: &entry_point_ids,
841            runtime_entry_point_ids: &runtime_entry_point_ids,
842            test_entry_point_ids: &test_entry_point_ids,
843            module_count,
844            total_capacity,
845        });
846        graph.index_exports(resolved_modules, consumer_checked);
847
848        let test_reachability_plan = reachability::TestReachabilityPlan::new(
849            &test_entry_point_ids,
850            replaced_module_targets,
851            total_capacity,
852        );
853
854        let mut reference_paths =
855            ReferencePathInterner::new(test_reachability_plan.requires_reference_provenance());
856        let mut whole_module_targets =
857            graph.populate_references(&module_by_id, &entry_point_ids, &mut reference_paths);
858        graph.namespace_escapes = whole_module_targets.take_escapes();
859        // Entry-point reachability depends on edges alone, so it is available
860        // here and is reused verbatim by `mark_reachable` below. The exposed
861        // namespace closure needs it to stay off modules the report already
862        // calls unused files.
863        let entry_reachable = graph.collect_reachable(&entry_point_ids, total_capacity);
864        let exposed_namespace_targets = graph.collect_exposed_namespace_targets(
865            &whole_module_targets,
866            &entry_reachable,
867            &module_by_id,
868        );
869
870        if namespace_features.has_aliases || namespace_features.has_re_exports {
871            propagate_namespace_references(
872                &mut graph,
873                &module_by_id,
874                namespace_features,
875                &exposed_namespace_targets,
876                &mut reference_paths,
877            );
878        }
879
880        graph.mark_reachable(
881            &entry_reachable,
882            &entry_point_ids,
883            &runtime_entry_point_ids,
884            test_reachability_plan,
885            total_capacity,
886        );
887
888        graph.re_export_cycles = graph.resolve_re_export_chains(
889            &module_by_id,
890            &exposed_namespace_targets,
891            consumer_checked,
892            &mut reference_paths,
893        );
894        namespace_escapes::normalize(&mut graph.namespace_escapes);
895        let finalized_paths = reference_paths.finalize(&mut graph.modules);
896        graph.reference_paths = finalized_paths.paths;
897        graph.reference_routes = finalized_paths.routes;
898
899        graph
900    }
901
902    /// Total number of modules.
903    #[must_use]
904    pub const fn module_count(&self) -> usize {
905        self.modules.len()
906    }
907
908    /// Total number of edges.
909    #[must_use]
910    pub const fn edge_count(&self) -> usize {
911        self.edges.len()
912    }
913
914    /// Return whether any test-root traversal reaches `file_id`.
915    #[must_use]
916    pub fn is_test_reachable(&self, file_id: FileId) -> bool {
917        self.modules
918            .get(file_id.0 as usize)
919            .is_some_and(ModuleNode::is_test_reachable)
920    }
921
922    /// Return whether one test-root traversal covers the export reference at
923    /// `reference_index` on `export`.
924    ///
925    /// Coverage requires one profile that reaches the referencing file and
926    /// every target hop. ESM hops also require that profile not to replace the
927    /// hop target; CommonJS hops remain active because Vitest replacement mocks
928    /// do not intercept `require()`.
929    ///
930    /// Only a value reference can give coverage. A type reference never runs
931    /// the export, so it never gives coverage. This includes `import type` and
932    /// a plain import that the test uses only in type positions.
933    #[must_use]
934    fn is_test_reference_covered(&self, export: &ExportSymbol, reference_index: usize) -> bool {
935        let Some(reference) = export.references.get(reference_index) else {
936            return false;
937        };
938        if reference.namespace != ExportNamespace::Value {
939            return false;
940        }
941        if self.test_reachability_index.profile_count == 0 {
942            return self.is_test_reachable(reference.from_file);
943        }
944
945        let Some(path) = export.reference_path(reference_index) else {
946            return false;
947        };
948
949        self.test_reachability_index.covers_reference_path(
950            reference.from_file,
951            path,
952            &self.reference_paths,
953            &self.reference_routes,
954        )
955    }
956
957    /// Return whether any reference on `export` is covered by a test-root
958    /// traversal.
959    #[must_use]
960    pub fn is_any_test_reference_covered(&self, export: &ExportSymbol) -> bool {
961        (0..export.references.len())
962            .any(|reference_index| self.is_test_reference_covered(export, reference_index))
963    }
964
965    #[cfg(test)]
966    fn reference_path_hops(
967        &self,
968        export: &ExportSymbol,
969        reference_index: usize,
970    ) -> Vec<(FileId, ModuleLoadMechanism)> {
971        let mut hops = Vec::new();
972        let mut next = export.reference_path(reference_index);
973        while let Some(path_id) = next {
974            let Some(node) = self.reference_paths.get(path_id.index()) else {
975                return Vec::new();
976            };
977            next = node.parent();
978            match *node {
979                ReferencePathNode::Hop {
980                    target, mechanism, ..
981                } => hops.push((target, mechanism)),
982                ReferencePathNode::Route {
983                    graph,
984                    start,
985                    terminal,
986                    start_mechanism,
987                    ..
988                } => hops.extend(self.reference_routes.canonical_hops(
989                    graph,
990                    start,
991                    terminal,
992                    start_mechanism,
993                )),
994            }
995        }
996        hops
997    }
998
999    /// Rebuild the `namespace_imported` bitset from the edge set.
1000    ///
1001    /// `namespace_imported` is `#[serde(skip)]`, so a graph loaded from the
1002    /// persisted cache (`crate::cache`) arrives with an empty default bitset.
1003    /// This restores it by replicating the EXACT insertion rule from
1004    /// `build.rs`: a target `FileId` is namespace-imported iff some edge to it
1005    /// carries an `ImportedName::Namespace` symbol. Both build-time insertion
1006    /// sites (static / dynamic `import * as ns` in `collect_import_edge`, and
1007    /// glob dynamic-import patterns in `collect_edges_for_module`) push a
1008    /// `Namespace` symbol onto the target's edge, so iterating the persisted
1009    /// edges and checking for a `Namespace` symbol reproduces the original
1010    /// bitset bit-for-bit. The capacity matches `build.rs`'s
1011    /// `max_file_id.max(module_count)`, which equals `modules.len()` under the
1012    /// dense path-sorted FileId invariant.
1013    pub(crate) fn reconstruct_namespace_imported(&mut self) {
1014        let capacity = self
1015            .edges
1016            .iter()
1017            .map(|edge| edge.target.0 as usize + 1)
1018            .max()
1019            .unwrap_or(0)
1020            .max(self.modules.len());
1021        let mut bitset = FixedBitSet::with_capacity(capacity);
1022        for edge in &self.edges {
1023            if edge
1024                .symbols
1025                .iter()
1026                .any(|sym| matches!(sym.imported_name, ImportedName::Namespace))
1027            {
1028                let idx = edge.target.0 as usize;
1029                if idx < capacity {
1030                    bitset.insert(idx);
1031                }
1032            }
1033        }
1034        self.namespace_imported = bitset;
1035    }
1036
1037    /// Resolve the effective declaration exported under `name` in one namespace.
1038    ///
1039    /// This is the canonical graph contract for direct exports and every named
1040    /// or star re-export path. Missing and ambiguous bindings are explicit so
1041    /// consumers cannot accidentally credit an arbitrary source declaration.
1042    #[must_use]
1043    pub fn resolve_export(
1044        &self,
1045        file_id: FileId,
1046        name: &str,
1047        namespace: ExportNamespace,
1048    ) -> EffectiveExportResolution {
1049        self.effective_exports.resolve(file_id, name, namespace)
1050    }
1051
1052    /// Whether two effective bindings denote the same declaration surface.
1053    ///
1054    /// TypeScript declaration merges occupy separate export slots while
1055    /// representing one symbol. Consumers that compare type and value lanes
1056    /// use this instead of raw binding equality so either half can carry the
1057    /// reference credit for the merged declaration.
1058    #[must_use]
1059    pub fn effective_bindings_share_declaration_group(
1060        &self,
1061        left: EffectiveExportBinding,
1062        right: EffectiveExportBinding,
1063    ) -> bool {
1064        if left == right || left.origin_file() != right.origin_file() {
1065            return left == right;
1066        }
1067        let Some(right_slot) = right.origin_slot() else {
1068            return false;
1069        };
1070        self.effective_exports
1071            .declaration_group_slots(left)
1072            .contains(&right_slot)
1073    }
1074
1075    /// Resolve one exported name to its unique direct declaration.
1076    ///
1077    /// Missing and ambiguous bindings return `None`. Namespace-object exports
1078    /// are bindings in their own right rather than direct declarations, so
1079    /// they also have no declaration origin.
1080    #[must_use]
1081    pub fn resolve_export_origin(
1082        &self,
1083        file_id: FileId,
1084        name: &str,
1085        namespace: ExportNamespace,
1086    ) -> Option<EffectiveExportOrigin<'_>> {
1087        let EffectiveExportResolution::Unique(binding) =
1088            self.resolve_export(file_id, name, namespace)
1089        else {
1090            return None;
1091        };
1092        self.export_binding_origin(binding)
1093    }
1094
1095    /// Resolve one module surface to its canonical binding and reference-bearing
1096    /// graph export. Value and type namespaces are selected independently.
1097    #[must_use]
1098    pub fn effective_export_surface(
1099        &self,
1100        file_id: FileId,
1101        name: &str,
1102        namespace: ExportNamespace,
1103    ) -> Option<EffectiveExportSurface<'_>> {
1104        let EffectiveExportResolution::Unique(binding) =
1105            self.resolve_export(file_id, name, namespace)
1106        else {
1107            return None;
1108        };
1109        let module = self.modules.get(file_id.0 as usize)?;
1110        let exact_surface = module.exports.iter().find(|export| {
1111            export.name.matches_str(name)
1112                && match namespace {
1113                    ExportNamespace::Type => export.is_type_only,
1114                    ExportNamespace::Value => !export.is_type_only,
1115                }
1116        });
1117        let surface_export = exact_surface.or_else(|| {
1118            module
1119                .exports
1120                .iter()
1121                .find(|export| export.name.matches_str(name))
1122        });
1123        let origin = self.export_binding_origin(binding);
1124        let export = surface_export.or_else(|| origin.map(|o| o.export));
1125        Some(EffectiveExportSurface {
1126            binding,
1127            namespace,
1128            export,
1129            origin,
1130            local_export: surface_export.is_some(),
1131        })
1132    }
1133
1134    /// Local re-export specifier that owns one effective module surface.
1135    ///
1136    /// Direct declarations and star-only forwarded surfaces return `None`.
1137    /// Named and namespace re-exports return the namespace-compatible edge
1138    /// whose source resolves to the same canonical binding.
1139    #[must_use]
1140    pub fn effective_export_surface_re_export(
1141        &self,
1142        file_id: FileId,
1143        name: &str,
1144        namespace: ExportNamespace,
1145    ) -> Option<&ReExportEdge> {
1146        let EffectiveExportResolution::Unique(binding) =
1147            self.resolve_export(file_id, name, namespace)
1148        else {
1149            return None;
1150        };
1151        self.modules
1152            .get(file_id.0 as usize)?
1153            .re_exports
1154            .iter()
1155            .find(|re_export| {
1156                re_export.exported_name == name
1157                    && (namespace == ExportNamespace::Type || !re_export.is_type_only)
1158                    && if re_export.imported_name == "*" {
1159                        binding.namespace_source() == Some(re_export.source_file)
1160                    } else {
1161                        self.resolve_export(
1162                            re_export.source_file,
1163                            &re_export.imported_name,
1164                            namespace,
1165                        ) == EffectiveExportResolution::Unique(binding)
1166                    }
1167            })
1168    }
1169
1170    /// References that reach one exact module export surface.
1171    ///
1172    /// Star-only surfaces share their declaration with other barrels, so their
1173    /// origin references are filtered by recorded provenance instead of being
1174    /// borrowed wholesale from the declaration.
1175    #[must_use]
1176    pub fn effective_export_surface_references(
1177        &self,
1178        file_id: FileId,
1179        name: &str,
1180        namespace: ExportNamespace,
1181    ) -> Vec<&SymbolReference> {
1182        let Some(surface) = self.effective_export_surface(file_id, name, namespace) else {
1183            return Vec::new();
1184        };
1185        let Some(export) = surface.export() else {
1186            return Vec::new();
1187        };
1188        if surface.local_export
1189            || surface
1190                .origin()
1191                .is_none_or(|origin| origin.file_id() == file_id)
1192        {
1193            return export.references_in(namespace).collect();
1194        }
1195        let mut exposed: FxHashMap<FileId, FxHashSet<String>> = FxHashMap::default();
1196        exposed.entry(file_id).or_default().insert(name.to_string());
1197        for route in self.effective_re_export_routes(file_id, name, namespace) {
1198            exposed
1199                .entry(route.barrel_file())
1200                .or_default()
1201                .insert(route.exported_name().to_string());
1202        }
1203        export
1204            .references
1205            .iter()
1206            .filter(|reference| {
1207                reference.namespace == namespace
1208                    && self.reference_reaches_surface(reference, &exposed, namespace)
1209            })
1210            .collect()
1211    }
1212
1213    fn reference_reaches_surface(
1214        &self,
1215        reference: &SymbolReference,
1216        exposed: &FxHashMap<FileId, FxHashSet<String>>,
1217        namespace: ExportNamespace,
1218    ) -> bool {
1219        if reference.kind == ReferenceKind::ReExport && exposed.contains_key(&reference.from_file) {
1220            return true;
1221        }
1222        self.outgoing_symbol_edges(reference.from_file)
1223            .any(|(target, symbols)| {
1224                let Some(names) = exposed.get(&target) else {
1225                    return false;
1226                };
1227                symbols.iter().any(|symbol| {
1228                    symbol.import_span == reference.import_span
1229                        && (namespace == ExportNamespace::Type
1230                            || !symbol.is_type_only
1231                            || symbol.is_value_bearing_ambient_star())
1232                        && match &symbol.imported_name {
1233                            ImportedName::Named(imported) => names.contains(imported.as_str()),
1234                            ImportedName::Default => names.contains("default"),
1235                            ImportedName::Namespace => true,
1236                            ImportedName::SideEffect => false,
1237                        }
1238                })
1239            })
1240    }
1241
1242    /// Resolve a unique binding to its direct declaration, when it has one.
1243    #[must_use]
1244    pub fn export_binding_origin(
1245        &self,
1246        binding: EffectiveExportBinding,
1247    ) -> Option<EffectiveExportOrigin<'_>> {
1248        let origin_file = binding.origin_file();
1249        let export = self
1250            .modules
1251            .get(origin_file.0 as usize)?
1252            .exports
1253            .get(binding.origin_slot()?)?;
1254        Some(EffectiveExportOrigin {
1255            file_id: origin_file,
1256            export,
1257        })
1258    }
1259
1260    /// Unique bindings exposed by a module in one namespace.
1261    ///
1262    /// Multiple names that resolve to the same declaration are deduplicated;
1263    /// missing and ambiguous exports are excluded.
1264    #[must_use]
1265    pub fn unique_export_bindings(
1266        &self,
1267        file_id: FileId,
1268        namespace: ExportNamespace,
1269    ) -> FxHashSet<EffectiveExportBinding> {
1270        self.effective_exports.unique_bindings(file_id, namespace)
1271    }
1272
1273    /// Whether `importer` connects to `source` as an origin of `name`.
1274    ///
1275    /// Any direct import connects the two modules for duplicate-export
1276    /// grouping, even when it imports a different symbol. A re-export-only edge
1277    /// connects them only when it contributes this binding, including each
1278    /// contributor to an ambiguous star export and excluding star bindings
1279    /// shadowed by an explicit export.
1280    #[must_use]
1281    pub fn importer_connects_export_origin(
1282        &self,
1283        importer: FileId,
1284        source: FileId,
1285        name: &str,
1286        namespace: ExportNamespace,
1287    ) -> bool {
1288        let Some(importer_module) = self.modules.get(importer.0 as usize) else {
1289            return false;
1290        };
1291        let re_export_count = importer_module
1292            .re_exports
1293            .iter()
1294            .filter(|re_export| re_export.source_file == source)
1295            .count();
1296        if self.edges[importer_module.edge_range.clone()]
1297            .iter()
1298            .any(|edge| edge.target == source && edge.symbols.len() > re_export_count)
1299        {
1300            return true;
1301        }
1302
1303        importer_module.re_exports.iter().any(|re_export| {
1304            if re_export.source_file != source
1305                || (namespace == ExportNamespace::Value && re_export.is_type_only)
1306            {
1307                return false;
1308            }
1309            let exported_name = if re_export.imported_name == "*" {
1310                if re_export.exported_name != "*" || name == "default" {
1311                    return false;
1312                }
1313                name
1314            } else {
1315                if re_export.imported_name != name {
1316                    return false;
1317                }
1318                &re_export.exported_name
1319            };
1320            self.effective_exports.contributes_through(
1321                importer,
1322                exported_name,
1323                source,
1324                name,
1325                namespace,
1326            )
1327        })
1328    }
1329
1330    /// Check if any importer uses `import * as ns` for this module.
1331    /// Uses precomputed bitset, O(1) lookup.
1332    #[must_use]
1333    pub fn has_namespace_import(&self, file_id: FileId) -> bool {
1334        // `FixedBitSet::contains` is false for an index past the end.
1335        self.namespace_imported.contains(file_id.0 as usize)
1336    }
1337
1338    /// Get the target `FileId`s of all outgoing edges for a module.
1339    #[must_use]
1340    pub fn edges_for(&self, file_id: FileId) -> Vec<FileId> {
1341        let idx = file_id.0 as usize;
1342        if idx >= self.modules.len() {
1343            return Vec::new();
1344        }
1345        let range = &self.modules[idx].edge_range;
1346        self.edges[range.clone()].iter().map(|e| e.target).collect()
1347    }
1348
1349    /// Iterate the outgoing edges of `file_id` with full per-symbol data.
1350    ///
1351    /// `fallow trace` needs the raw `ImportedSymbol` set on each edge in
1352    /// both directions, which the flattened summary structs cannot express.
1353    /// Returns an empty iterator for out-of-range file ids.
1354    pub fn outgoing_symbol_edges(
1355        &self,
1356        file_id: FileId,
1357    ) -> impl Iterator<Item = (FileId, &[ImportedSymbol])> + '_ {
1358        let idx = file_id.0 as usize;
1359        let range = if idx < self.modules.len() {
1360            self.modules[idx].edge_range.clone()
1361        } else {
1362            0..0
1363        };
1364        self.edges[range]
1365            .iter()
1366            .map(|edge| (edge.target, edge.symbols.as_slice()))
1367    }
1368
1369    /// The importer `FileId`s that directly import `target` (reverse-dep view).
1370    ///
1371    /// Returns an empty slice when `target` is out of range.
1372    #[must_use]
1373    pub fn importers_of(&self, target: FileId) -> &[FileId] {
1374        self.reverse_deps
1375            .get(target.0 as usize)
1376            .map_or(&[], Vec::as_slice)
1377    }
1378
1379    /// Summarize files that directly import `target`.
1380    ///
1381    /// Uses existing reverse dependency and edge indexes. Returns an empty
1382    /// list when the target is out of range or has no importers.
1383    #[must_use]
1384    pub fn direct_importer_summaries(&self, target: FileId) -> Vec<DirectImporterSummary> {
1385        let Some(importers) = self.reverse_deps.get(target.0 as usize) else {
1386            return Vec::new();
1387        };
1388
1389        let mut summaries = Vec::new();
1390        for &source in importers {
1391            let idx = source.0 as usize;
1392            let Some(source_node) = self.modules.get(idx) else {
1393                continue;
1394            };
1395            let mut symbols = Vec::new();
1396            for edge in &self.edges[source_node.edge_range.clone()] {
1397                if edge.target != target {
1398                    continue;
1399                }
1400                symbols.extend(edge.symbols.iter().map(|symbol| ImportedSymbolSummary {
1401                    imported: imported_name_label(&symbol.imported_name),
1402                    local: symbol.local_name.clone(),
1403                    type_only: symbol.is_type_only,
1404                }));
1405            }
1406            symbols.sort_by(|a, b| {
1407                a.imported
1408                    .cmp(&b.imported)
1409                    .then_with(|| a.local.cmp(&b.local))
1410                    .then_with(|| a.type_only.cmp(&b.type_only))
1411            });
1412            symbols.dedup();
1413            summaries.push(DirectImporterSummary { source, symbols });
1414        }
1415        summaries.sort_by_key(|summary| summary.source.0);
1416        summaries
1417    }
1418
1419    /// Iterate the outgoing edges of `file_id` that run their target, with
1420    /// the data the boundary detector and the security scans need in a single
1421    /// pass.
1422    ///
1423    /// Only symbols that load the target count (see
1424    /// [`ImportedSymbol::loads_target`]). A `require.resolve('./x')` path
1425    /// reference and an asset loader request (`raw-loader!./x.js`) keep the
1426    /// target in use but do not run it, so they cannot cross an architecture
1427    /// boundary or carry code into a bundle. An edge without such a symbol is
1428    /// skipped.
1429    ///
1430    /// When `featureB` has both `import type { Foo } from './x'` and
1431    /// `import { bar } from './x'`, fallow groups them into ONE edge with the
1432    /// type-only symbol first and the value symbol second. The summary
1433    /// anchors on the value symbol, so findings anchor on the runtime import
1434    /// line; otherwise a `// fallow-ignore-next-line` above the type-only line
1435    /// would silently suppress the real violation.
1436    ///
1437    /// Returns an empty iterator for out-of-range file ids.
1438    pub fn outgoing_edge_summaries(
1439        &self,
1440        file_id: FileId,
1441    ) -> impl Iterator<Item = OutgoingEdgeSummary<'_>> + '_ {
1442        self.outgoing_symbol_edges(file_id)
1443            .filter_map(|(target, symbols)| {
1444                let mut loading = symbols.iter().filter(|s| s.loads_target()).peekable();
1445                let first = loading.peek().copied()?;
1446                let value = loading.find(|s| !s.is_type_only);
1447                Some(OutgoingEdgeSummary {
1448                    target,
1449                    all_type_only: value.is_none(),
1450                    span_start: Some(value.unwrap_or(first).import_span.start),
1451                    symbols,
1452                })
1453            })
1454    }
1455
1456    /// Iterate outgoing edges with the symbols of each edge.
1457    ///
1458    /// One edge holds every import from `file_id` to one target, so
1459    /// `import type { Y } from './y'` and `import { y } from './y'` share an
1460    /// edge. Use this method when a consumer must suppress or report each
1461    /// import statement on its own line; [`Self::outgoing_edge_summaries`]
1462    /// gives only one span per edge. A re-export or a dynamic import pattern
1463    /// has an empty `import_span`.
1464    ///
1465    /// Returns an empty iterator for out-of-range file ids.
1466    pub fn outgoing_edge_symbols(
1467        &self,
1468        file_id: FileId,
1469    ) -> impl Iterator<Item = (FileId, &[ImportedSymbol])> + '_ {
1470        let idx = file_id.0 as usize;
1471        let range = if idx < self.modules.len() {
1472            self.modules[idx].edge_range.clone()
1473        } else {
1474            0..0
1475        };
1476        self.edges[range]
1477            .iter()
1478            .map(|edge| (edge.target, edge.symbols.as_slice()))
1479    }
1480
1481    /// Like [`Self::outgoing_edge_summaries`] (only edges that run their
1482    /// target, and only their loading symbols) but additionally reports, as a
1483    /// fourth boolean, whether EVERY non-type-only symbol on the edge has an
1484    /// `import_span` start in `excluded_span_starts` (`all_client_only`). The
1485    /// security `client-server-leak` BFS passes the `next/dynamic ssr:false`
1486    /// dynamic-import span starts so it can skip an edge reached ONLY through the
1487    /// client-only escape hatch. An edge with no non-type-only symbols, or with at
1488    /// least one non-type-only symbol whose span is not excluded, reports `false`
1489    /// (so a target also reached via a real static import stays in the cone).
1490    ///
1491    /// Unlike [`Self::outgoing_edge_summaries`], a named symbol also counts as
1492    /// type-only when the name resolves on the target to a type declaration and
1493    /// to no value declaration (`import { Props } from "./x"` where `x` has
1494    /// `export interface Props`). The build erases such an import, so it cannot
1495    /// leak into a client bundle. Default, namespace, and side-effect imports,
1496    /// and names that do not resolve to a type, stay live.
1497    ///
1498    /// Returns an empty iterator for out-of-range file ids.
1499    pub fn outgoing_edge_summaries_with_exclusions<'a>(
1500        &'a self,
1501        file_id: FileId,
1502        excluded_span_starts: &'a FxHashSet<u32>,
1503    ) -> impl Iterator<Item = (FileId, bool, Option<u32>, bool)> + 'a {
1504        let idx = file_id.0 as usize;
1505        let range = if idx < self.modules.len() {
1506            self.modules[idx].edge_range.clone()
1507        } else {
1508            0..0
1509        };
1510        self.edges[range].iter().filter_map(move |edge| {
1511            let loading = || edge.symbols.iter().filter(|s| s.loads_target());
1512            let first = loading().next()?;
1513            let erased = |s: &&ImportedSymbol| {
1514                s.is_type_only || self.names_only_type_exports(edge.target, &s.imported_name)
1515            };
1516            let all_type_only = loading().all(|s| erased(&s));
1517            let span = loading()
1518                .find(|s| !erased(s))
1519                .unwrap_or(first)
1520                .import_span
1521                .start;
1522            // `all_client_only`: there is at least one non-type-only symbol and
1523            // every such symbol's import span is in the excluded set. A
1524            // non-excluded value symbol keeps the edge live.
1525            let mut value_symbols = loading().filter(|s| !erased(s)).peekable();
1526            let all_client_only = value_symbols.peek().is_some()
1527                && value_symbols.all(|s| excluded_span_starts.contains(&s.import_span.start));
1528            Some((edge.target, all_type_only, Some(span), all_client_only))
1529        })
1530    }
1531}
1532
1533impl ModuleGraph {
1534    /// Return `true` when `name` is a named import that resolves on `target`
1535    /// to a type declaration and to no value declaration. Default, namespace,
1536    /// and side-effect imports return `false`, and so does a name that the
1537    /// graph cannot resolve in the type namespace.
1538    fn names_only_type_exports(&self, target: FileId, name: &ImportedName) -> bool {
1539        let ImportedName::Named(name) = name else {
1540            return false;
1541        };
1542        matches!(
1543            self.resolve_export(target, name, ExportNamespace::Value),
1544            EffectiveExportResolution::Missing
1545        ) && matches!(
1546            self.resolve_export(target, name, ExportNamespace::Type),
1547            EffectiveExportResolution::Unique(_)
1548        )
1549    }
1550}
1551
1552fn imported_name_label(name: &ImportedName) -> String {
1553    match name {
1554        ImportedName::Named(name) => name.clone(),
1555        ImportedName::Default => "default".to_string(),
1556        ImportedName::Namespace => "*".to_string(),
1557        ImportedName::SideEffect => "side-effect".to_string(),
1558    }
1559}
1560
1561#[cfg(test)]
1562#[path = "graph_tests.rs"]
1563mod tests;