Skip to main content

fallow_graph/resolve/
types.rs

1//! Type definitions and constants for import resolution.
2
3use std::path::{Path, PathBuf};
4use std::sync::{Arc, Mutex};
5
6use dashmap::DashMap;
7use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet};
8use serde_json::Value;
9
10use fallow_config::{MergedTsconfig, SourceLoader, TsconfigOutputMap};
11use fallow_types::discover::FileId;
12
13use crate::read_trace::Resolver;
14
15/// Result of resolving an import specifier.
16#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
17pub enum ResolveResult {
18    /// Resolved to a file within the project.
19    InternalModule(FileId),
20    /// Resolved from a CommonJS `require()` to a file within the project.
21    CommonJsInternalModule(FileId),
22    /// Resolved to a project file through a framework convention auto-import.
23    SyntheticAutoImport(FileId),
24    /// Resolved to a workspace or self package source file while preserving
25    /// dependency usage for package accounting.
26    InternalPackageModule {
27        /// Internal source file reached by the package map.
28        file_id: FileId,
29        /// Package name that was used in the import specifier.
30        package_name: String,
31    },
32    /// Resolved from a CommonJS `require()` to workspace or self-package source.
33    CommonJsInternalPackageModule {
34        /// Internal source file reached by the package map.
35        file_id: FileId,
36        /// Package name used in the require specifier.
37        package_name: String,
38    },
39    /// Resolved to a file outside the project (`node_modules`, `.json`, etc.).
40    ExternalFile(PathBuf),
41    /// Bare specifier — an npm package.
42    NpmPackage(String),
43    /// Bare npm package referenced through CommonJS `require()`.
44    CommonJsNpmPackage(String),
45    /// Could not resolve.
46    Unresolvable(String),
47}
48
49impl ResolveResult {
50    /// Return the target file for any project-internal result.
51    #[must_use]
52    pub const fn internal_file_id(&self) -> Option<FileId> {
53        match self {
54            Self::InternalModule(file_id)
55            | Self::CommonJsInternalModule(file_id)
56            | Self::SyntheticAutoImport(file_id)
57            | Self::InternalPackageModule { file_id, .. }
58            | Self::CommonJsInternalPackageModule { file_id, .. } => Some(*file_id),
59            Self::ExternalFile(_)
60            | Self::NpmPackage(_)
61            | Self::CommonJsNpmPackage(_)
62            | Self::Unresolvable(_) => None,
63        }
64    }
65
66    /// Return whether this edge was synthesized from framework auto-import conventions.
67    #[must_use]
68    pub const fn is_synthetic_auto_import(&self) -> bool {
69        matches!(self, Self::SyntheticAutoImport(_))
70    }
71
72    /// Return whether this edge originated from CommonJS `require()`.
73    #[must_use]
74    pub(crate) const fn is_commonjs_require(&self) -> bool {
75        matches!(
76            self,
77            Self::CommonJsInternalModule(_)
78                | Self::CommonJsInternalPackageModule { .. }
79                | Self::CommonJsNpmPackage(_)
80        )
81    }
82
83    /// Return whether this target is an unresolved bare package edge.
84    #[must_use]
85    pub const fn is_bare_package(&self) -> bool {
86        matches!(self, Self::NpmPackage(_) | Self::CommonJsNpmPackage(_))
87    }
88
89    /// Retain CommonJS provenance on targets that can participate in upgrades.
90    #[must_use]
91    pub(crate) fn into_commonjs_require(self) -> Self {
92        match self {
93            Self::InternalModule(file_id) => Self::CommonJsInternalModule(file_id),
94            Self::InternalPackageModule {
95                file_id,
96                package_name,
97            } => Self::CommonJsInternalPackageModule {
98                file_id,
99                package_name,
100            },
101            Self::NpmPackage(package_name) => Self::CommonJsNpmPackage(package_name),
102            other => other,
103        }
104    }
105
106    /// Return the package name that should receive dependency usage credit.
107    #[must_use]
108    pub fn package_usage_name(&self) -> Option<&str> {
109        match self {
110            Self::InternalPackageModule { package_name, .. }
111            | Self::CommonJsInternalPackageModule { package_name, .. }
112            | Self::NpmPackage(package_name)
113            | Self::CommonJsNpmPackage(package_name) => Some(package_name),
114            Self::InternalModule(_)
115            | Self::CommonJsInternalModule(_)
116            | Self::SyntheticAutoImport(_)
117            | Self::ExternalFile(_)
118            | Self::Unresolvable(_) => None,
119        }
120    }
121}
122
123/// Resolver output for one extracted project.
124#[derive(Debug, Default)]
125pub struct ResolvedProject {
126    /// Modules with every ordinary import and re-export resolved.
127    pub modules: Vec<ResolvedModule>,
128    /// Proven test-time replacements whose targets resolve inside the project.
129    pub replaced_module_targets: Vec<ResolvedReplacedModuleTarget>,
130    /// Deterministic work counts of the resolution that built this project.
131    /// Zero for a project restored from the graph cache.
132    pub work: super::ResolveWork,
133    /// The paths below the root that the resolution checked and did not
134    /// find. A file that appears at one of them can change a resolution, so
135    /// the graph cache stores them (see [`crate::missed_probes`]).
136    pub missed_probes: crate::missed_probes::MissedProbes,
137    /// The package manifests below `node_modules` that the resolution read,
138    /// sorted. A path above the root has `../` steps. The graph cache keys
139    /// the versions of the Bun installs among them (see
140    /// [`crate::installed_versions`]). Empty for a project restored from the
141    /// graph cache.
142    pub package_manifests: Vec<String>,
143}
144
145/// One project-internal module replacement resolved from its declaring source file.
146#[derive(Debug, Clone, Copy, PartialEq, Eq)]
147pub struct ResolvedReplacedModuleTarget {
148    /// File that declares the replacement fact.
149    pub source_file: FileId,
150    /// Project file replaced for this source's test-root traversal.
151    pub target_file: FileId,
152}
153
154/// A resolved import with its target.
155#[derive(Debug, Clone)]
156pub struct ResolvedImport {
157    /// The original import information.
158    pub info: fallow_types::extract::ImportInfo,
159    /// Where the import resolved to.
160    pub target: ResolveResult,
161}
162
163/// A resolved re-export with its target.
164#[derive(Debug, Clone)]
165pub struct ResolvedReExport {
166    /// The original re-export information.
167    pub info: fallow_types::extract::ReExportInfo,
168    /// Where the re-export source resolved to.
169    pub target: ResolveResult,
170}
171
172/// Any source-bearing module edge that resolves one literal specifier.
173pub enum ResolvedSourceEdge<'a> {
174    /// Static or literal dynamic import edge.
175    Import(&'a ResolvedImport),
176    /// Re-export source edge.
177    ReExport(&'a ResolvedReExport),
178}
179
180impl<'a> ResolvedSourceEdge<'a> {
181    /// Return the original source specifier.
182    #[must_use]
183    pub fn source_specifier(&self) -> &'a str {
184        match self {
185            Self::Import(import) => &import.info.source,
186            Self::ReExport(re_export) => &re_export.info.source,
187        }
188    }
189
190    /// Return the resolved target.
191    #[must_use]
192    pub const fn target(&self) -> &'a ResolveResult {
193        match self {
194            Self::Import(import) => &import.target,
195            Self::ReExport(re_export) => &re_export.target,
196        }
197    }
198
199    /// Return whether this edge is type-only.
200    #[must_use]
201    pub const fn is_type_only(&self) -> bool {
202        match self {
203            Self::Import(import) => import.info.is_type_only,
204            Self::ReExport(re_export) => re_export.info.is_type_only,
205        }
206    }
207
208    /// Return the span of the full import or re-export declaration.
209    #[must_use]
210    pub const fn span(&self) -> oxc_span::Span {
211        match self {
212            Self::Import(import) => import.info.span,
213            Self::ReExport(re_export) => re_export.info.span,
214        }
215    }
216
217    /// Return the source literal span when the extractor has one.
218    #[must_use]
219    pub const fn source_span(&self) -> oxc_span::Span {
220        match self {
221            Self::Import(import) => import.info.source_span,
222            Self::ReExport(re_export) => re_export.info.source_span,
223        }
224    }
225
226    /// Return the span of the enclosing statement.
227    ///
228    /// Imports do not record a statement span, so their per-binding
229    /// declaration span is the closest available statement anchor.
230    #[must_use]
231    pub const fn statement_span(&self) -> oxc_span::Span {
232        match self {
233            Self::Import(import) => import.info.span,
234            Self::ReExport(re_export) => re_export.info.statement_span,
235        }
236    }
237}
238
239/// Fully resolved module with all imports mapped to targets.
240///
241/// The `Arc<[T]>` fields are refcounted views of the same allocations owned by
242/// the source [`fallow_types::extract::ModuleInfo`], not copies; see the note
243/// on that struct.
244#[derive(Debug, Clone)]
245pub struct ResolvedModule {
246    /// Unique file identifier.
247    pub file_id: FileId,
248    /// Absolute path to the module file.
249    pub path: PathBuf,
250    /// All export declarations in this module.
251    pub exports: Arc<[fallow_types::extract::ExportInfo]>,
252    /// All re-exports with resolved targets.
253    pub re_exports: Vec<ResolvedReExport>,
254    /// All static imports with resolved targets.
255    pub resolved_imports: Vec<ResolvedImport>,
256    /// All dynamic imports with resolved targets.
257    pub resolved_dynamic_imports: Vec<ResolvedImport>,
258    /// Dynamic import patterns and their matched target files.
259    pub resolved_dynamic_patterns: Vec<(fallow_types::extract::DynamicImportPattern, Vec<FileId>)>,
260    /// Static member accesses (e.g., `Status.Active`).
261    pub member_accesses: Arc<[fallow_types::extract::MemberAccess]>,
262    /// Typed semantic facts produced by extraction for cross-layer analysis.
263    pub semantic_facts: Arc<[fallow_types::extract::SemanticFact]>,
264    /// Identifiers used as whole objects (Object.values, for..in, spread, etc.).
265    pub whole_object_uses: Arc<[String]>,
266    /// Whether this module uses `CommonJS` exports.
267    pub has_cjs_exports: bool,
268    /// Whether this module declares at least one Angular `@Component({
269    /// templateUrl: ... })` decorator. Mirrors `ModuleInfo.has_angular_component_template_url`;
270    /// see that field for the contract this gate enforces.
271    pub has_angular_component_template_url: bool,
272    /// Local names of import bindings that are never referenced in this file.
273    pub unused_import_bindings: FxHashSet<String>,
274    /// Local import bindings referenced from type positions.
275    pub type_referenced_import_bindings: Vec<String>,
276    /// Local import bindings referenced from runtime/value positions.
277    pub value_referenced_import_bindings: Vec<String>,
278    /// Namespace-import aliases re-exported through an object literal.
279    /// See `fallow_types::extract::NamespaceObjectAlias` for the shape.
280    pub namespace_object_aliases: Vec<fallow_types::extract::NamespaceObjectAlias>,
281    /// Exported free-function factories that provably return one class instance.
282    /// See `fallow_types::extract::FactoryReturnExport` and issue #1441 (Part A).
283    pub exported_factory_returns: Arc<[fallow_types::extract::FactoryReturnExport]>,
284    /// Object-literal factory-return shapes (`export function createUi() {
285    /// return { orders: factory.ordersPage } }`), threaded from `ModuleInfo` for
286    /// the analyze-layer member-crediting join. See issue #1858.
287    pub exported_factory_return_object_shapes:
288        Arc<[fallow_types::extract::FactoryReturnObjectShapeExport]>,
289    /// Named-type property types declared by this module's top-level interfaces
290    /// and type-literal aliases. See `fallow_types::extract::TypeMemberTypeEntry`
291    /// and issue #1785.
292    pub type_member_types: Arc<[fallow_types::extract::TypeMemberTypeEntry]>,
293    /// Unresolved specifiers with known missing target paths, in specifier
294    /// order: a bare specifier whose package `exports` entry names only paths
295    /// that do not exist, or a specifier that a path alias substitutes. The
296    /// resolver records the paths so that the unresolved-import check can test
297    /// them against the ignore rules of the repository. No edge points at
298    /// these paths.
299    pub missing_export_targets: Vec<MissingExportTarget>,
300}
301
302/// A plugin path alias that applies only to the files of one workspace package.
303///
304/// A framework alias such as SvelteKit `$lib` or Nuxt `~/` maps to a directory
305/// of the package that owns the framework config. Two packages can declare the
306/// same prefix, so the resolver must apply an alias only to an importing file
307/// inside the package that declared it.
308#[derive(Debug, Clone, PartialEq, Eq)]
309pub struct ScopedPathAlias {
310    /// The workspace root, relative to the project root. A workspace outside
311    /// the project tree keeps its absolute path.
312    pub scope: String,
313    /// The import prefix, for example `$lib/`.
314    pub prefix: String,
315    /// The replacement directory, relative to the project root.
316    pub replacement: String,
317}
318
319/// The missing paths that the `exports` map of a project package names for
320/// one unresolved bare specifier.
321#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
322pub struct MissingExportTarget {
323    /// The import specifier, for example `store/enums`.
324    pub specifier: String,
325    /// The absolute paths that the matched `exports` entry names.
326    pub paths: Vec<PathBuf>,
327}
328
329impl Default for ResolvedModule {
330    fn default() -> Self {
331        Self {
332            file_id: FileId(0),
333            path: PathBuf::new(),
334            exports: Arc::default(),
335            re_exports: vec![],
336            resolved_imports: vec![],
337            resolved_dynamic_imports: vec![],
338            resolved_dynamic_patterns: vec![],
339            member_accesses: Arc::default(),
340            semantic_facts: Arc::default(),
341            whole_object_uses: Arc::default(),
342            has_cjs_exports: false,
343            has_angular_component_template_url: false,
344            unused_import_bindings: FxHashSet::default(),
345            type_referenced_import_bindings: vec![],
346            value_referenced_import_bindings: vec![],
347            namespace_object_aliases: vec![],
348            exported_factory_returns: Arc::default(),
349            exported_factory_return_object_shapes: Arc::default(),
350            type_member_types: Arc::default(),
351            missing_export_targets: vec![],
352        }
353    }
354}
355
356impl ResolvedModule {
357    /// Iterate over all concrete resolved imports in source order buckets.
358    ///
359    /// Includes static `import`/`require` edges and literal dynamic `import()`
360    /// edges. Dynamic import patterns are intentionally excluded because they
361    /// resolve to sets of files rather than single import specifiers.
362    pub fn all_resolved_imports(&self) -> impl Iterator<Item = &ResolvedImport> {
363        self.resolved_imports
364            .iter()
365            .chain(self.resolved_dynamic_imports.iter())
366    }
367
368    /// Iterate over every literal source edge that has one resolved target.
369    ///
370    /// Includes static imports, literal dynamic imports, and re-export sources.
371    /// Dynamic import patterns are excluded because they resolve to sets of
372    /// files rather than single import specifiers.
373    pub fn all_resolved_source_edges(&self) -> impl Iterator<Item = ResolvedSourceEdge<'_>> {
374        self.resolved_imports
375            .iter()
376            .map(ResolvedSourceEdge::Import)
377            .chain(
378                self.resolved_dynamic_imports
379                    .iter()
380                    .map(ResolvedSourceEdge::Import),
381            )
382            .chain(self.re_exports.iter().map(ResolvedSourceEdge::ReExport))
383    }
384}
385
386/// Shared context for resolving import specifiers.
387///
388/// Groups the immutable lookup tables and caches that are shared across all
389/// `resolve_specifier` calls within a single `resolve_all_imports` invocation.
390pub(super) struct ResolveContext<'a> {
391    /// The oxc_resolver instance (configured once, shared across threads).
392    pub resolver: &'a Resolver,
393    /// Script and JSON extension inference, with explicit asset targets intact.
394    /// Shares the broad resolver's filesystem and PnP cache.
395    pub script_resolver: &'a Resolver,
396    /// CSS-only resolver with package.json `sass` and `style` conditions enabled.
397    /// Used only for stylesheet package subpaths so JS/TS imports do not
398    /// accidentally prefer CSS export branches.
399    pub style_resolver: &'a Resolver,
400    /// Ordered extension list used by the resolver.
401    pub extensions: &'a [String],
402    /// Canonical path → FileId lookup (raw paths when root is canonical).
403    pub path_to_id: &'a FxHashMap<&'a Path, FileId>,
404    /// Raw (non-canonical) path → FileId lookup.
405    pub raw_path_to_id: &'a FxHashMap<&'a Path, FileId>,
406    /// Workspace name → canonical root path.
407    pub workspace_roots: &'a FxHashMap<&'a str, &'a Path>,
408    /// Package manifests for the root package and workspace packages.
409    pub package_manifests: &'a [PackageManifestInfo],
410    /// Whether any package scope declared a Deno import map; false skips map
411    /// lookup per import.
412    pub has_deno_import_maps: bool,
413    /// Ordered package condition names matching the resolver configuration.
414    pub condition_names: &'a [String],
415    /// Plugin-provided path aliases (prefix, replacement).
416    pub path_aliases: &'a [(String, String)],
417    /// Plugin-provided path aliases that apply only inside one workspace.
418    pub scoped_path_aliases: &'a [ScopedPathAlias],
419    /// Absolute directories to search when resolving bare SCSS/Sass
420    /// `@import` / `@use` specifiers. Populated from Angular's
421    /// `stylePreprocessorOptions.includePaths` and equivalent settings.
422    pub scss_include_paths: &'a [PathBuf],
423    /// Static directory URL mappings from framework config.
424    /// Each tuple is `(absolute_source_dir, normalized_url_mount)`.
425    pub static_dir_mappings: &'a [(PathBuf, String)],
426    /// Mounts a framework serves for the whole project, reachable from any HTML
427    /// document, unlike `static_dir_mappings`, which stays scoped to the tool
428    /// whose config declared it.
429    pub framework_static_dir_mappings: &'a [(PathBuf, String)],
430    /// Project root directory.
431    pub root: &'a Path,
432    /// Lazy canonical path → FileId fallback for intra-project symlinks.
433    /// Only initialized on first miss when root is canonical. `None` when
434    /// path_to_id already uses canonical paths (root is not canonical).
435    pub canonical_fallback: Option<&'a CanonicalFallback<'a>>,
436    /// Dedup set for broken-tsconfig warnings. Emits one `tracing::warn!`
437    /// per unique error message instead of spamming the log with one
438    /// warning per affected file. Shared across all parallel resolver
439    /// threads via `Mutex`. Empty and unused when no tsconfig errors occur.
440    pub tsconfig_warned: &'a Mutex<FxHashSet<String>>,
441    /// Per-analysis cache for local tsconfig discovery and JSON parsing.
442    /// Import resolution calls these fallbacks for every unresolved or
443    /// tsconfig-poisoned specifier, so keeping it session-local avoids
444    /// repeated filesystem work without risking stale data across runs.
445    pub tsconfig_cache: &'a TsconfigCache,
446    /// Per-analysis cache of `dunce::canonicalize` results keyed by resolved
447    /// path. Every import resolving to a `node_modules` / output-dir / symlinked
448    /// target is realpath'd during classification, and the same package path is
449    /// re-canonicalized for every file that imports the package. The result is a
450    /// pure function of the path's on-disk state (constant within a run), so the
451    /// cache is session-local for watch-mode safety.
452    pub canonicalize_cache: &'a CanonicalizeCache,
453}
454
455/// Session-local cache of `dunce::canonicalize` results keyed by input path.
456#[derive(Default)]
457pub(super) struct CanonicalizeCache {
458    map: DashMap<PathBuf, Option<PathBuf>, FxBuildHasher>,
459}
460
461impl CanonicalizeCache {
462    /// Return the cached `dunce::canonicalize(path)` outcome, computing it on
463    /// first miss. `None` (a path that fails to canonicalize) is cached too so a
464    /// repeated probe of the same missing path does not re-issue the syscall.
465    pub fn get(&self, path: &Path) -> Option<PathBuf> {
466        if let Some(value) = self.map.get(path) {
467            return value.clone();
468        }
469        let value = crate::read_trace::canonicalize(path).ok();
470        self.map.insert(path.to_path_buf(), value.clone());
471        value
472    }
473
474    /// Number of distinct paths this cache canonicalized. Two threads that
475    /// miss the same path at once can both call the filesystem, so this is the
476    /// work the run needs, not an exact syscall count.
477    pub fn distinct_paths(&self) -> usize {
478        self.map.len()
479    }
480}
481
482/// Session-local cache for tsconfig helper lookups used during import resolution.
483#[derive(Default)]
484pub(super) struct TsconfigCache {
485    json: DashMap<PathBuf, Option<Arc<Value>>, FxBuildHasher>,
486    chains: DashMap<PathBuf, Arc<[PathBuf]>, FxBuildHasher>,
487    merged: DashMap<PathBuf, Option<Arc<MergedTsconfig>>, FxBuildHasher>,
488    output_maps: DashMap<PathBuf, Arc<TsconfigOutputMap>, FxBuildHasher>,
489}
490
491impl TsconfigCache {
492    /// Return a cached parsed tsconfig JSON value, loading it on first miss.
493    ///
494    /// Handing back an [`Arc`] rather than a clone matters: a tsconfig chain is
495    /// walked several times per import specifier, and deep-copying every parsed
496    /// document on each hop dominated resolution on large project-reference
497    /// graphs.
498    pub fn json(
499        &self,
500        path: &Path,
501        load: impl FnOnce(&Path) -> Option<Value>,
502    ) -> Option<Arc<Value>> {
503        if let Some(value) = self.json.get(path) {
504            return value.clone();
505        }
506
507        let value = load(path).map(Arc::new);
508        self.json.insert(path.to_path_buf(), value.clone());
509        value
510    }
511
512    /// Return the merged settings of a tsconfig and its `extends` chain,
513    /// reading them through `load` on first miss.
514    pub fn merged(&self, path: &Path, load: &SourceLoader<'_>) -> Option<Arc<MergedTsconfig>> {
515        if let Some(merged) = self.merged.get(path) {
516            return merged.clone();
517        }
518        let merged = MergedTsconfig::read_with_loader(path, load).map(Arc::new);
519        self.merged.insert(path.to_path_buf(), merged.clone());
520        merged
521    }
522
523    /// Return the cached tsconfig chain for a source file, if one exists.
524    pub fn chain(&self, from_file: &Path) -> Option<Arc<[PathBuf]>> {
525        self.chains.get(from_file).map(|entry| Arc::clone(&entry))
526    }
527
528    /// Store the computed tsconfig chain for a source file.
529    pub fn store_chain(&self, from_file: &Path, chain: Arc<[PathBuf]>) {
530        self.chains.insert(from_file.to_path_buf(), chain);
531    }
532
533    /// Return the output-to-source map of a package root, building it on
534    /// first miss. Each package root reads its tsconfig files once per run.
535    pub fn output_map(&self, package_root: &Path) -> Arc<TsconfigOutputMap> {
536        if let Some(map) = self.output_maps.get(package_root) {
537            return Arc::clone(&map);
538        }
539        let map = Arc::new(TsconfigOutputMap::from_project(package_root));
540        self.output_maps
541            .insert(package_root.to_path_buf(), Arc::clone(&map));
542        map
543    }
544}
545
546/// Package manifest data used by source fallbacks.
547#[derive(Debug, Clone)]
548pub(super) struct PackageManifestInfo {
549    /// Package root path as discovered from the workspace tree.
550    pub root: PathBuf,
551    /// Canonical package root path for node_modules symlink comparisons.
552    pub canonical_root: PathBuf,
553    /// Parsed package name.
554    pub name: Option<String>,
555    /// Parsed package.json fields.
556    pub package_json: fallow_config::PackageJson,
557    /// Effective Deno import map for this package scope.
558    pub deno_import_map: Vec<DenoImportMapEntry>,
559}
560
561/// One effective Deno import-map entry with the directory that declared it.
562#[derive(Debug, Clone)]
563pub(super) struct DenoImportMapEntry {
564    pub key: String,
565    pub target: String,
566    pub declaring_dir: PathBuf,
567}
568
569/// Thread-safe lazy canonical path index, built on first access.
570pub(super) struct CanonicalFallback<'a> {
571    files: &'a [fallow_types::discover::DiscoveredFile],
572    map: std::sync::OnceLock<FxHashMap<std::path::PathBuf, FileId>>,
573}
574
575impl<'a> CanonicalFallback<'a> {
576    pub const fn new(files: &'a [fallow_types::discover::DiscoveredFile]) -> Self {
577        Self {
578            files,
579            map: std::sync::OnceLock::new(),
580        }
581    }
582
583    /// Look up a canonical path, lazily building the index on first call.
584    pub fn get(&self, canonical: &Path) -> Option<FileId> {
585        let map = self.map.get_or_init(|| {
586            super::work::note_canonicalize(self.files.len() as u64);
587            tracing::debug!(
588                "intra-project symlinks detected, building canonical path index ({} files)",
589                self.files.len()
590            );
591            self.files
592                .iter()
593                .filter_map(|f| {
594                    crate::read_trace::canonicalize(&f.path)
595                        .ok()
596                        .map(|canonical| (canonical, f.id))
597                })
598                .collect()
599        });
600        map.get(canonical).copied()
601    }
602}
603
604#[cfg(all(test, not(miri)))]
605mod tests {
606    use super::*;
607    use fallow_types::discover::DiscoveredFile;
608
609    #[test]
610    fn canonical_fallback_returns_none_for_empty_files() {
611        let files: Vec<DiscoveredFile> = vec![];
612        let fallback = CanonicalFallback::new(&files);
613        assert!(fallback.get(Path::new("/nonexistent")).is_none());
614    }
615
616    #[test]
617    fn canonical_fallback_finds_existing_file() {
618        let temp = std::env::temp_dir().join("fallow-test-canonical-fallback");
619        let _ = std::fs::create_dir_all(&temp);
620        let test_file = temp.join("test.ts");
621        std::fs::write(&test_file, "").unwrap();
622
623        let files = vec![DiscoveredFile {
624            id: FileId(42),
625            path: test_file.clone(),
626            size_bytes: 0,
627        }];
628        let fallback = CanonicalFallback::new(&files);
629
630        let canonical = dunce::canonicalize(&test_file).unwrap();
631        assert_eq!(fallback.get(&canonical), Some(FileId(42)));
632
633        assert_eq!(fallback.get(&canonical), Some(FileId(42)));
634
635        let _ = std::fs::remove_dir_all(&temp);
636    }
637
638    #[test]
639    fn canonical_fallback_returns_none_for_missing_path() {
640        let temp = std::env::temp_dir().join("fallow-test-canonical-miss");
641        let _ = std::fs::create_dir_all(&temp);
642        let test_file = temp.join("exists.ts");
643        std::fs::write(&test_file, "").unwrap();
644
645        let files = vec![DiscoveredFile {
646            id: FileId(1),
647            path: test_file,
648            size_bytes: 0,
649        }];
650        let fallback = CanonicalFallback::new(&files);
651        assert!(fallback.get(Path::new("/nonexistent/file.ts")).is_none());
652
653        let _ = std::fs::remove_dir_all(&temp);
654    }
655
656    #[test]
657    fn tsconfig_cache_loads_once_and_shares_the_parsed_document() {
658        let cache = TsconfigCache::default();
659        let path = Path::new("/project/tsconfig.json");
660        let loads = std::sync::atomic::AtomicUsize::new(0);
661        let load = |_: &Path| {
662            loads.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
663            Some(serde_json::json!({ "compilerOptions": {} }))
664        };
665
666        let first = cache.json(path, load).unwrap();
667        let second = cache.json(path, load).unwrap();
668
669        assert_eq!(loads.load(std::sync::atomic::Ordering::SeqCst), 1);
670        assert!(
671            Arc::ptr_eq(&first, &second),
672            "repeat reads must share one allocation rather than deep-copy"
673        );
674    }
675
676    /// An unreadable tsconfig is cached as a miss so the read is not retried.
677    #[test]
678    fn tsconfig_cache_caches_a_failed_load() {
679        let cache = TsconfigCache::default();
680        let path = Path::new("/project/missing.json");
681        let loads = std::sync::atomic::AtomicUsize::new(0);
682        let load = |_: &Path| {
683            loads.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
684            None
685        };
686
687        assert!(cache.json(path, load).is_none());
688        assert!(cache.json(path, load).is_none());
689        assert_eq!(loads.load(std::sync::atomic::Ordering::SeqCst), 1);
690    }
691
692    #[test]
693    fn tsconfig_cache_round_trips_a_chain() {
694        let cache = TsconfigCache::default();
695        let from_file = Path::new("/project/src/index.ts");
696        assert!(cache.chain(from_file).is_none());
697
698        let chain: Arc<[PathBuf]> = vec![PathBuf::from("/project/tsconfig.json")].into();
699        cache.store_chain(from_file, Arc::clone(&chain));
700
701        assert!(Arc::ptr_eq(&cache.chain(from_file).unwrap(), &chain));
702    }
703
704    /// Both caches are read concurrently by rayon workers during resolution.
705    #[test]
706    fn tsconfig_cache_is_consistent_under_concurrent_access() {
707        const THREADS: usize = 8;
708        const PATHS: usize = 32;
709
710        let cache = TsconfigCache::default();
711        std::thread::scope(|scope| {
712            for _ in 0..THREADS {
713                scope.spawn(|| {
714                    for index in 0..PATHS {
715                        let path = PathBuf::from(format!("/project/{index}/tsconfig.json"));
716                        let json = cache
717                            .json(&path, |_| Some(serde_json::json!({ "index": index })))
718                            .unwrap();
719                        assert_eq!(json["index"], index);
720                    }
721                });
722            }
723        });
724    }
725
726    #[test]
727    fn canonicalize_cache_returns_the_same_result_on_repeat_lookups() {
728        let temp = tempfile::tempdir().expect("create temp dir");
729        let file = temp.path().join("file.ts");
730        std::fs::write(&file, "").unwrap();
731
732        let cache = CanonicalizeCache::default();
733        let expected = dunce::canonicalize(&file).ok();
734        assert_eq!(cache.get(&file), expected);
735        assert_eq!(cache.get(&file), expected);
736        assert!(cache.get(&temp.path().join("missing.ts")).is_none());
737    }
738
739    #[test]
740    fn commonjs_provenance_wraps_internal_and_bare_package_targets() {
741        assert!(matches!(
742            ResolveResult::InternalModule(FileId(4)).into_commonjs_require(),
743            ResolveResult::CommonJsInternalModule(FileId(4))
744        ));
745        assert!(matches!(
746            ResolveResult::InternalPackageModule {
747                file_id: FileId(5),
748                package_name: "pkg".to_string(),
749            }
750            .into_commonjs_require(),
751            ResolveResult::CommonJsInternalPackageModule {
752                file_id: FileId(5),
753                package_name,
754            } if package_name == "pkg"
755        ));
756        assert!(matches!(
757            ResolveResult::NpmPackage("pkg".to_string()).into_commonjs_require(),
758            ResolveResult::CommonJsNpmPackage(package_name) if package_name == "pkg"
759        ));
760    }
761}
762
763/// Known output directory names that may appear in exports map targets.
764/// When an exports map points to `./dist/utils.js`, we try replacing these
765/// prefixes with `src/` (the conventional source directory) to find the tracked
766/// source file.
767pub const OUTPUT_DIRS: &[&str] = &["dist", "build", "out", "esm", "cjs"];
768
769/// Output directory names that map to `src/` only when the target is absent.
770///
771/// Many TypeScript libraries build `src/` into `lib/`, but older packages keep
772/// hand-written source in `lib/`. Thus `lib` maps to `src/` only when the
773/// `lib/` target is absent from the analyzed file set (for example in a fresh
774/// clone before the build, or a gitignored build), and only for package
775/// manifest targets. A `lib/` file in the file set always wins, and generic
776/// relative imports never use this list.
777pub const MISSING_ONLY_OUTPUT_DIRS: &[&str] = &["lib"];
778
779/// Source extensions to try when mapping a built output file back to source.
780pub const SOURCE_EXTS: &[&str] = &["ts", "tsx", "mts", "cts", "js", "jsx", "mjs", "cjs"];
781
782/// React Native platform extension prefixes.
783/// Metro resolves platform-specific files (e.g., `./foo` -> `./foo.web.tsx` on web).
784pub const RN_PLATFORM_PREFIXES: &[&str] = &[".web", ".ios", ".android", ".native"];