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