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