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::Mutex;
5
6use oxc_resolver::Resolver;
7use rustc_hash::{FxHashMap, FxHashSet};
8use serde_json::Value;
9
10use fallow_types::discover::FileId;
11
12/// Result of resolving an import specifier.
13#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
14pub enum ResolveResult {
15    /// Resolved to a file within the project.
16    InternalModule(FileId),
17    /// Resolved from a CommonJS `require()` to a file within the project.
18    CommonJsInternalModule(FileId),
19    /// Resolved to a project file through a framework convention auto-import.
20    SyntheticAutoImport(FileId),
21    /// Resolved to a workspace or self package source file while preserving
22    /// dependency usage for package accounting.
23    InternalPackageModule {
24        /// Internal source file reached by the package map.
25        file_id: FileId,
26        /// Package name that was used in the import specifier.
27        package_name: String,
28    },
29    /// Resolved from a CommonJS `require()` to workspace or self-package source.
30    CommonJsInternalPackageModule {
31        /// Internal source file reached by the package map.
32        file_id: FileId,
33        /// Package name used in the require specifier.
34        package_name: String,
35    },
36    /// Resolved to a file outside the project (`node_modules`, `.json`, etc.).
37    ExternalFile(PathBuf),
38    /// Bare specifier — an npm package.
39    NpmPackage(String),
40    /// Bare npm package referenced through CommonJS `require()`.
41    CommonJsNpmPackage(String),
42    /// Could not resolve.
43    Unresolvable(String),
44}
45
46impl ResolveResult {
47    /// Return the target file for any project-internal result.
48    #[must_use]
49    pub const fn internal_file_id(&self) -> Option<FileId> {
50        match self {
51            Self::InternalModule(file_id)
52            | Self::CommonJsInternalModule(file_id)
53            | Self::SyntheticAutoImport(file_id)
54            | Self::InternalPackageModule { file_id, .. }
55            | Self::CommonJsInternalPackageModule { file_id, .. } => Some(*file_id),
56            Self::ExternalFile(_)
57            | Self::NpmPackage(_)
58            | Self::CommonJsNpmPackage(_)
59            | Self::Unresolvable(_) => None,
60        }
61    }
62
63    /// Return whether this edge was synthesized from framework auto-import conventions.
64    #[must_use]
65    pub const fn is_synthetic_auto_import(&self) -> bool {
66        matches!(self, Self::SyntheticAutoImport(_))
67    }
68
69    /// Return whether this edge originated from CommonJS `require()`.
70    #[must_use]
71    pub const fn is_commonjs_require(&self) -> bool {
72        matches!(
73            self,
74            Self::CommonJsInternalModule(_)
75                | Self::CommonJsInternalPackageModule { .. }
76                | Self::CommonJsNpmPackage(_)
77        )
78    }
79
80    /// Return whether this target is an unresolved bare package edge.
81    #[must_use]
82    pub const fn is_bare_package(&self) -> bool {
83        matches!(self, Self::NpmPackage(_) | Self::CommonJsNpmPackage(_))
84    }
85
86    /// Retain CommonJS provenance on targets that can participate in upgrades.
87    #[must_use]
88    pub fn into_commonjs_require(self) -> Self {
89        match self {
90            Self::InternalModule(file_id) => Self::CommonJsInternalModule(file_id),
91            Self::InternalPackageModule {
92                file_id,
93                package_name,
94            } => Self::CommonJsInternalPackageModule {
95                file_id,
96                package_name,
97            },
98            Self::NpmPackage(package_name) => Self::CommonJsNpmPackage(package_name),
99            other => other,
100        }
101    }
102
103    /// Remove CommonJS provenance while preserving the resolved destination.
104    #[must_use]
105    pub fn into_es_module(self) -> Self {
106        match self {
107            Self::CommonJsInternalModule(file_id) => Self::InternalModule(file_id),
108            Self::CommonJsInternalPackageModule {
109                file_id,
110                package_name,
111            } => Self::InternalPackageModule {
112                file_id,
113                package_name,
114            },
115            Self::CommonJsNpmPackage(package_name) => Self::NpmPackage(package_name),
116            other => other,
117        }
118    }
119
120    /// Return the package name that should receive dependency usage credit.
121    #[must_use]
122    pub fn package_usage_name(&self) -> Option<&str> {
123        match self {
124            Self::InternalPackageModule { package_name, .. }
125            | Self::CommonJsInternalPackageModule { package_name, .. }
126            | Self::NpmPackage(package_name)
127            | Self::CommonJsNpmPackage(package_name) => Some(package_name),
128            Self::InternalModule(_)
129            | Self::CommonJsInternalModule(_)
130            | Self::SyntheticAutoImport(_)
131            | Self::ExternalFile(_)
132            | Self::Unresolvable(_) => None,
133        }
134    }
135}
136
137/// Resolver output for one extracted project.
138#[derive(Debug, Default)]
139pub struct ResolvedProject {
140    /// Modules with every ordinary import and re-export resolved.
141    pub modules: Vec<ResolvedModule>,
142    /// Proven test-time replacements whose targets resolve inside the project.
143    pub replaced_module_targets: Vec<ResolvedReplacedModuleTarget>,
144}
145
146/// One project-internal module replacement resolved from its declaring source file.
147#[derive(Debug, Clone, Copy, PartialEq, Eq)]
148pub struct ResolvedReplacedModuleTarget {
149    /// File that declares the replacement fact.
150    pub source_file: FileId,
151    /// Project file replaced for this source's test-root traversal.
152    pub target_file: FileId,
153}
154
155/// A resolved import with its target.
156#[derive(Debug, Clone)]
157pub struct ResolvedImport {
158    /// The original import information.
159    pub info: fallow_types::extract::ImportInfo,
160    /// Where the import resolved to.
161    pub target: ResolveResult,
162}
163
164/// A resolved re-export with its target.
165#[derive(Debug, Clone)]
166pub struct ResolvedReExport {
167    /// The original re-export information.
168    pub info: fallow_types::extract::ReExportInfo,
169    /// Where the re-export source resolved to.
170    pub target: ResolveResult,
171}
172
173/// Any source-bearing module edge that resolves one literal specifier.
174pub enum ResolvedSourceEdge<'a> {
175    /// Static or literal dynamic import edge.
176    Import(&'a ResolvedImport),
177    /// Re-export source edge.
178    ReExport(&'a ResolvedReExport),
179}
180
181impl<'a> ResolvedSourceEdge<'a> {
182    /// Return the original source specifier.
183    #[must_use]
184    pub fn source_specifier(&self) -> &'a str {
185        match self {
186            Self::Import(import) => &import.info.source,
187            Self::ReExport(re_export) => &re_export.info.source,
188        }
189    }
190
191    /// Return the resolved target.
192    #[must_use]
193    pub const fn target(&self) -> &'a ResolveResult {
194        match self {
195            Self::Import(import) => &import.target,
196            Self::ReExport(re_export) => &re_export.target,
197        }
198    }
199
200    /// Return whether this edge is type-only.
201    #[must_use]
202    pub const fn is_type_only(&self) -> bool {
203        match self {
204            Self::Import(import) => import.info.is_type_only,
205            Self::ReExport(re_export) => re_export.info.is_type_only,
206        }
207    }
208
209    /// Return the span of the full import or re-export declaration.
210    #[must_use]
211    pub const fn span(&self) -> oxc_span::Span {
212        match self {
213            Self::Import(import) => import.info.span,
214            Self::ReExport(re_export) => re_export.info.span,
215        }
216    }
217
218    /// Return the source literal span when the extractor has one.
219    #[must_use]
220    pub const fn source_span(&self) -> oxc_span::Span {
221        match self {
222            Self::Import(import) => import.info.source_span,
223            Self::ReExport(_) => oxc_span::Span::new(0, 0),
224        }
225    }
226}
227
228/// Fully resolved module with all imports mapped to targets.
229#[derive(Debug)]
230pub struct ResolvedModule {
231    /// Unique file identifier.
232    pub file_id: FileId,
233    /// Absolute path to the module file.
234    pub path: PathBuf,
235    /// All export declarations in this module.
236    pub exports: Vec<fallow_types::extract::ExportInfo>,
237    /// All re-exports with resolved targets.
238    pub re_exports: Vec<ResolvedReExport>,
239    /// All static imports with resolved targets.
240    pub resolved_imports: Vec<ResolvedImport>,
241    /// All dynamic imports with resolved targets.
242    pub resolved_dynamic_imports: Vec<ResolvedImport>,
243    /// Dynamic import patterns matched against discovered files.
244    pub resolved_dynamic_patterns: Vec<(fallow_types::extract::DynamicImportPattern, Vec<FileId>)>,
245    /// Static member accesses (e.g., `Status.Active`).
246    pub member_accesses: Vec<fallow_types::extract::MemberAccess>,
247    /// Typed semantic facts produced by extraction for cross-layer analysis.
248    pub semantic_facts: Box<[fallow_types::extract::SemanticFact]>,
249    /// Identifiers used as whole objects (Object.values, for..in, spread, etc.).
250    pub whole_object_uses: Box<[String]>,
251    /// Whether this module uses `CommonJS` exports.
252    pub has_cjs_exports: bool,
253    /// Whether this module declares at least one Angular `@Component({
254    /// templateUrl: ... })` decorator. Mirrors `ModuleInfo.has_angular_component_template_url`;
255    /// see that field for the contract this gate enforces.
256    pub has_angular_component_template_url: bool,
257    /// Local names of import bindings that are never referenced in this file.
258    pub unused_import_bindings: FxHashSet<String>,
259    /// Local import bindings referenced from type positions.
260    pub type_referenced_import_bindings: Vec<String>,
261    /// Local import bindings referenced from runtime/value positions.
262    pub value_referenced_import_bindings: Vec<String>,
263    /// Namespace-import aliases re-exported through an object literal.
264    /// See `fallow_types::extract::NamespaceObjectAlias` for the shape.
265    pub namespace_object_aliases: Vec<fallow_types::extract::NamespaceObjectAlias>,
266    /// Exported free-function factories that provably return one class instance.
267    /// See `fallow_types::extract::FactoryReturnExport` and issue #1441 (Part A).
268    pub exported_factory_returns: Box<[fallow_types::extract::FactoryReturnExport]>,
269    /// Object-literal factory-return shapes (`export function createUi() {
270    /// return { orders: factory.ordersPage } }`), threaded from `ModuleInfo` for
271    /// the analyze-layer member-crediting join. See issue #1858.
272    pub exported_factory_return_object_shapes:
273        Box<[fallow_types::extract::FactoryReturnObjectShapeExport]>,
274    /// Named-type property types declared by this module's top-level interfaces
275    /// and type-literal aliases. See `fallow_types::extract::TypeMemberTypeEntry`
276    /// and issue #1785.
277    pub type_member_types: Box<[fallow_types::extract::TypeMemberTypeEntry]>,
278}
279
280impl Default for ResolvedModule {
281    fn default() -> Self {
282        Self {
283            file_id: FileId(0),
284            path: PathBuf::new(),
285            exports: vec![],
286            re_exports: vec![],
287            resolved_imports: vec![],
288            resolved_dynamic_imports: vec![],
289            resolved_dynamic_patterns: vec![],
290            member_accesses: vec![],
291            semantic_facts: Box::default(),
292            whole_object_uses: Box::default(),
293            has_cjs_exports: false,
294            has_angular_component_template_url: false,
295            unused_import_bindings: FxHashSet::default(),
296            type_referenced_import_bindings: vec![],
297            value_referenced_import_bindings: vec![],
298            namespace_object_aliases: vec![],
299            exported_factory_returns: Box::default(),
300            exported_factory_return_object_shapes: Box::default(),
301            type_member_types: Box::default(),
302        }
303    }
304}
305
306impl ResolvedModule {
307    /// Iterate over all concrete resolved imports in source order buckets.
308    ///
309    /// Includes static `import`/`require` edges and literal dynamic `import()`
310    /// edges. Dynamic import patterns are intentionally excluded because they
311    /// resolve to sets of files rather than single import specifiers.
312    pub fn all_resolved_imports(&self) -> impl Iterator<Item = &ResolvedImport> {
313        self.resolved_imports
314            .iter()
315            .chain(self.resolved_dynamic_imports.iter())
316    }
317
318    /// Iterate over every literal source edge that has one resolved target.
319    ///
320    /// Includes static imports, literal dynamic imports, and re-export sources.
321    /// Dynamic import patterns are excluded because they resolve to sets of
322    /// files rather than single import specifiers.
323    pub fn all_resolved_source_edges(&self) -> impl Iterator<Item = ResolvedSourceEdge<'_>> {
324        self.resolved_imports
325            .iter()
326            .map(ResolvedSourceEdge::Import)
327            .chain(
328                self.resolved_dynamic_imports
329                    .iter()
330                    .map(ResolvedSourceEdge::Import),
331            )
332            .chain(self.re_exports.iter().map(ResolvedSourceEdge::ReExport))
333    }
334}
335
336/// Shared context for resolving import specifiers.
337///
338/// Groups the immutable lookup tables and caches that are shared across all
339/// `resolve_specifier` calls within a single `resolve_all_imports` invocation.
340pub(super) struct ResolveContext<'a> {
341    /// The oxc_resolver instance (configured once, shared across threads).
342    pub resolver: &'a Resolver,
343    /// CSS-only resolver with package.json `sass` and `style` conditions enabled.
344    /// Used only for stylesheet package subpaths so JS/TS imports do not
345    /// accidentally prefer CSS export branches.
346    pub style_resolver: &'a Resolver,
347    /// Ordered extension list used by the resolver.
348    pub extensions: &'a [String],
349    /// Canonical path → FileId lookup (raw paths when root is canonical).
350    pub path_to_id: &'a FxHashMap<&'a Path, FileId>,
351    /// Raw (non-canonical) path → FileId lookup.
352    pub raw_path_to_id: &'a FxHashMap<&'a Path, FileId>,
353    /// Workspace name → canonical root path.
354    pub workspace_roots: &'a FxHashMap<&'a str, &'a Path>,
355    /// Package manifests for the root package and workspace packages.
356    pub package_manifests: &'a [PackageManifestInfo],
357    /// Whether any package scope declared a Deno import map; false skips map
358    /// lookup per import.
359    pub has_deno_import_maps: bool,
360    /// Ordered package condition names matching the resolver configuration.
361    pub condition_names: &'a [String],
362    /// Plugin-provided path aliases (prefix, replacement).
363    pub path_aliases: &'a [(String, String)],
364    /// Absolute directories to search when resolving bare SCSS/Sass
365    /// `@import` / `@use` specifiers. Populated from Angular's
366    /// `stylePreprocessorOptions.includePaths` and equivalent settings.
367    pub scss_include_paths: &'a [PathBuf],
368    /// Static directory URL mappings from framework config.
369    /// Each tuple is `(absolute_source_dir, normalized_url_mount)`.
370    pub static_dir_mappings: &'a [(PathBuf, String)],
371    /// Project root directory.
372    pub root: &'a Path,
373    /// Lazy canonical path → FileId fallback for intra-project symlinks.
374    /// Only initialized on first miss when root is canonical. `None` when
375    /// path_to_id already uses canonical paths (root is not canonical).
376    pub canonical_fallback: Option<&'a CanonicalFallback<'a>>,
377    /// Dedup set for broken-tsconfig warnings. Emits one `tracing::warn!`
378    /// per unique error message instead of spamming the log with one
379    /// warning per affected file. Shared across all parallel resolver
380    /// threads via `Mutex`. Empty and unused when no tsconfig errors occur.
381    pub tsconfig_warned: &'a Mutex<FxHashSet<String>>,
382    /// Per-analysis cache for local tsconfig discovery and JSON parsing.
383    /// Import resolution calls these fallbacks for every unresolved or
384    /// tsconfig-poisoned specifier, so keeping it session-local avoids
385    /// repeated filesystem work without risking stale data across runs.
386    pub tsconfig_cache: &'a TsconfigCache,
387    /// Per-analysis cache of `dunce::canonicalize` results keyed by resolved
388    /// path. Every import resolving to a `node_modules` / output-dir / symlinked
389    /// target is realpath'd during classification, and the same package path is
390    /// re-canonicalized for every file that imports the package. The result is a
391    /// pure function of the path's on-disk state (constant within a run), so the
392    /// cache is session-local for watch-mode safety.
393    pub canonicalize_cache: &'a CanonicalizeCache,
394}
395
396/// Session-local cache of `dunce::canonicalize` results keyed by input path.
397#[derive(Default)]
398pub(super) struct CanonicalizeCache {
399    map: Mutex<FxHashMap<PathBuf, Option<PathBuf>>>,
400}
401
402impl CanonicalizeCache {
403    /// Return the cached `dunce::canonicalize(path)` outcome, computing it on
404    /// first miss. `None` (a path that fails to canonicalize) is cached too so a
405    /// repeated probe of the same missing path does not re-issue the syscall.
406    pub fn get(&self, path: &Path) -> Option<PathBuf> {
407        if let Ok(cache) = self.map.lock()
408            && let Some(value) = cache.get(path)
409        {
410            return value.clone();
411        }
412        let value = dunce::canonicalize(path).ok();
413        if let Ok(mut cache) = self.map.lock() {
414            cache.insert(path.to_path_buf(), value.clone());
415        }
416        value
417    }
418}
419
420/// Session-local cache for tsconfig helper lookups used during import resolution.
421#[derive(Default)]
422pub(super) struct TsconfigCache {
423    json: Mutex<FxHashMap<PathBuf, Option<Value>>>,
424    chains: Mutex<FxHashMap<PathBuf, Vec<PathBuf>>>,
425}
426
427impl TsconfigCache {
428    /// Return a cached parsed tsconfig JSON value, loading it on first miss.
429    pub fn json(&self, path: &Path, load: impl FnOnce(&Path) -> Option<Value>) -> Option<Value> {
430        if let Ok(cache) = self.json.lock()
431            && let Some(value) = cache.get(path)
432        {
433            return value.clone();
434        }
435
436        let value = load(path);
437        if let Ok(mut cache) = self.json.lock() {
438            cache.insert(path.to_path_buf(), value.clone());
439        }
440        value
441    }
442
443    /// Return the cached tsconfig chain for a source file, if one exists.
444    pub fn chain(&self, from_file: &Path) -> Option<Vec<PathBuf>> {
445        self.chains
446            .lock()
447            .ok()
448            .and_then(|cache| cache.get(from_file).cloned())
449    }
450
451    /// Store the computed tsconfig chain for a source file.
452    pub fn store_chain(&self, from_file: &Path, chain: Vec<PathBuf>) {
453        if let Ok(mut cache) = self.chains.lock() {
454            cache.insert(from_file.to_path_buf(), chain);
455        }
456    }
457}
458
459/// Package manifest data used by source fallbacks.
460#[derive(Debug, Clone)]
461pub(super) struct PackageManifestInfo {
462    /// Package root path as discovered from the workspace tree.
463    pub root: PathBuf,
464    /// Canonical package root path for node_modules symlink comparisons.
465    pub canonical_root: PathBuf,
466    /// Parsed package name.
467    pub name: Option<String>,
468    /// Parsed package.json fields.
469    pub package_json: fallow_config::PackageJson,
470    /// Effective Deno import map for this package scope.
471    pub deno_import_map: Vec<DenoImportMapEntry>,
472}
473
474/// One effective Deno import-map entry with the directory that declared it.
475#[derive(Debug, Clone)]
476pub(super) struct DenoImportMapEntry {
477    pub key: String,
478    pub target: String,
479    pub declaring_dir: PathBuf,
480}
481
482/// Thread-safe lazy canonical path index, built on first access.
483pub(super) struct CanonicalFallback<'a> {
484    files: &'a [fallow_types::discover::DiscoveredFile],
485    map: std::sync::OnceLock<FxHashMap<std::path::PathBuf, FileId>>,
486}
487
488impl<'a> CanonicalFallback<'a> {
489    pub const fn new(files: &'a [fallow_types::discover::DiscoveredFile]) -> Self {
490        Self {
491            files,
492            map: std::sync::OnceLock::new(),
493        }
494    }
495
496    /// Look up a canonical path, lazily building the index on first call.
497    pub fn get(&self, canonical: &Path) -> Option<FileId> {
498        let map = self.map.get_or_init(|| {
499            tracing::debug!(
500                "intra-project symlinks detected, building canonical path index ({} files)",
501                self.files.len()
502            );
503            self.files
504                .iter()
505                .filter_map(|f| {
506                    dunce::canonicalize(&f.path)
507                        .ok()
508                        .map(|canonical| (canonical, f.id))
509                })
510                .collect()
511        });
512        map.get(canonical).copied()
513    }
514}
515
516#[cfg(all(test, not(miri)))]
517mod tests {
518    use super::*;
519    use fallow_types::discover::DiscoveredFile;
520
521    #[test]
522    fn canonical_fallback_returns_none_for_empty_files() {
523        let files: Vec<DiscoveredFile> = vec![];
524        let fallback = CanonicalFallback::new(&files);
525        assert!(fallback.get(Path::new("/nonexistent")).is_none());
526    }
527
528    #[test]
529    fn canonical_fallback_finds_existing_file() {
530        let temp = std::env::temp_dir().join("fallow-test-canonical-fallback");
531        let _ = std::fs::create_dir_all(&temp);
532        let test_file = temp.join("test.ts");
533        std::fs::write(&test_file, "").unwrap();
534
535        let files = vec![DiscoveredFile {
536            id: FileId(42),
537            path: test_file.clone(),
538            size_bytes: 0,
539        }];
540        let fallback = CanonicalFallback::new(&files);
541
542        let canonical = dunce::canonicalize(&test_file).unwrap();
543        assert_eq!(fallback.get(&canonical), Some(FileId(42)));
544
545        assert_eq!(fallback.get(&canonical), Some(FileId(42)));
546
547        let _ = std::fs::remove_dir_all(&temp);
548    }
549
550    #[test]
551    fn canonical_fallback_returns_none_for_missing_path() {
552        let temp = std::env::temp_dir().join("fallow-test-canonical-miss");
553        let _ = std::fs::create_dir_all(&temp);
554        let test_file = temp.join("exists.ts");
555        std::fs::write(&test_file, "").unwrap();
556
557        let files = vec![DiscoveredFile {
558            id: FileId(1),
559            path: test_file,
560            size_bytes: 0,
561        }];
562        let fallback = CanonicalFallback::new(&files);
563        assert!(fallback.get(Path::new("/nonexistent/file.ts")).is_none());
564
565        let _ = std::fs::remove_dir_all(&temp);
566    }
567
568    #[test]
569    fn commonjs_provenance_wraps_internal_and_bare_package_targets() {
570        assert!(matches!(
571            ResolveResult::InternalModule(FileId(4)).into_commonjs_require(),
572            ResolveResult::CommonJsInternalModule(FileId(4))
573        ));
574        assert!(matches!(
575            ResolveResult::InternalPackageModule {
576                file_id: FileId(5),
577                package_name: "pkg".to_string(),
578            }
579            .into_commonjs_require(),
580            ResolveResult::CommonJsInternalPackageModule {
581                file_id: FileId(5),
582                package_name,
583            } if package_name == "pkg"
584        ));
585        assert!(matches!(
586            ResolveResult::NpmPackage("pkg".to_string()).into_commonjs_require(),
587            ResolveResult::CommonJsNpmPackage(package_name) if package_name == "pkg"
588        ));
589    }
590}
591
592/// Known output directory names that may appear in exports map targets.
593/// When an exports map points to `./dist/utils.js`, we try replacing these
594/// prefixes with `src/` (the conventional source directory) to find the tracked
595/// source file.
596pub const OUTPUT_DIRS: &[&str] = &["dist", "build", "out", "esm", "cjs"];
597
598/// Source extensions to try when mapping a built output file back to source.
599pub const SOURCE_EXTS: &[&str] = &["ts", "tsx", "mts", "cts", "js", "jsx", "mjs", "cjs"];
600
601/// React Native platform extension prefixes.
602/// Metro resolves platform-specific files (e.g., `./foo` -> `./foo.web.tsx` on web).
603pub const RN_PLATFORM_PREFIXES: &[&str] = &[".web", ".ios", ".android", ".native"];