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};
8
9use fallow_types::discover::FileId;
10
11/// Result of resolving an import specifier.
12#[derive(Debug, Clone)]
13pub enum ResolveResult {
14    /// Resolved to a file within the project.
15    InternalModule(FileId),
16    /// Resolved to a file outside the project (`node_modules`, `.json`, etc.).
17    ExternalFile(PathBuf),
18    /// Bare specifier — an npm package.
19    NpmPackage(String),
20    /// Could not resolve.
21    Unresolvable(String),
22}
23
24/// A resolved import with its target.
25#[derive(Debug, Clone)]
26pub struct ResolvedImport {
27    /// The original import information.
28    pub info: fallow_types::extract::ImportInfo,
29    /// Where the import resolved to.
30    pub target: ResolveResult,
31}
32
33/// A resolved re-export with its target.
34#[derive(Debug, Clone)]
35pub struct ResolvedReExport {
36    /// The original re-export information.
37    pub info: fallow_types::extract::ReExportInfo,
38    /// Where the re-export source resolved to.
39    pub target: ResolveResult,
40}
41
42/// Fully resolved module with all imports mapped to targets.
43#[derive(Debug)]
44pub struct ResolvedModule {
45    /// Unique file identifier.
46    pub file_id: FileId,
47    /// Absolute path to the module file.
48    pub path: PathBuf,
49    /// All export declarations in this module.
50    pub exports: Vec<fallow_types::extract::ExportInfo>,
51    /// All re-exports with resolved targets.
52    pub re_exports: Vec<ResolvedReExport>,
53    /// All static imports with resolved targets.
54    pub resolved_imports: Vec<ResolvedImport>,
55    /// All dynamic imports with resolved targets.
56    pub resolved_dynamic_imports: Vec<ResolvedImport>,
57    /// Dynamic import patterns matched against discovered files.
58    pub resolved_dynamic_patterns: Vec<(fallow_types::extract::DynamicImportPattern, Vec<FileId>)>,
59    /// Static member accesses (e.g., `Status.Active`).
60    pub member_accesses: Vec<fallow_types::extract::MemberAccess>,
61    /// Identifiers used as whole objects (Object.values, for..in, spread, etc.).
62    pub whole_object_uses: Vec<String>,
63    /// Whether this module uses `CommonJS` exports.
64    pub has_cjs_exports: bool,
65    /// Local names of import bindings that are never referenced in this file.
66    pub unused_import_bindings: FxHashSet<String>,
67    /// Local import bindings referenced from type positions.
68    pub type_referenced_import_bindings: Vec<String>,
69    /// Local import bindings referenced from runtime/value positions.
70    pub value_referenced_import_bindings: Vec<String>,
71}
72
73impl Default for ResolvedModule {
74    fn default() -> Self {
75        Self {
76            file_id: FileId(0),
77            path: PathBuf::new(),
78            exports: vec![],
79            re_exports: vec![],
80            resolved_imports: vec![],
81            resolved_dynamic_imports: vec![],
82            resolved_dynamic_patterns: vec![],
83            member_accesses: vec![],
84            whole_object_uses: vec![],
85            has_cjs_exports: false,
86            unused_import_bindings: FxHashSet::default(),
87            type_referenced_import_bindings: vec![],
88            value_referenced_import_bindings: vec![],
89        }
90    }
91}
92
93/// Shared context for resolving import specifiers.
94///
95/// Groups the immutable lookup tables and caches that are shared across all
96/// `resolve_specifier` calls within a single `resolve_all_imports` invocation.
97pub(super) struct ResolveContext<'a> {
98    /// The oxc_resolver instance (configured once, shared across threads).
99    pub resolver: &'a Resolver,
100    /// CSS-only resolver with the package.json `style` condition enabled.
101    /// Used only for stylesheet package subpaths so JS/TS imports do not
102    /// accidentally prefer CSS export branches.
103    pub style_resolver: &'a Resolver,
104    /// Canonical path → FileId lookup (raw paths when root is canonical).
105    pub path_to_id: &'a FxHashMap<&'a Path, FileId>,
106    /// Raw (non-canonical) path → FileId lookup.
107    pub raw_path_to_id: &'a FxHashMap<&'a Path, FileId>,
108    /// Workspace name → canonical root path.
109    pub workspace_roots: &'a FxHashMap<&'a str, &'a Path>,
110    /// Plugin-provided path aliases (prefix, replacement).
111    pub path_aliases: &'a [(String, String)],
112    /// Absolute directories to search when resolving bare SCSS/Sass
113    /// `@import` / `@use` specifiers. Populated from Angular's
114    /// `stylePreprocessorOptions.includePaths` and equivalent settings.
115    pub scss_include_paths: &'a [PathBuf],
116    /// Project root directory.
117    pub root: &'a Path,
118    /// Lazy canonical path → FileId fallback for intra-project symlinks.
119    /// Only initialized on first miss when root is canonical. `None` when
120    /// path_to_id already uses canonical paths (root is not canonical).
121    pub canonical_fallback: Option<&'a CanonicalFallback<'a>>,
122    /// Dedup set for broken-tsconfig warnings. Emits one `tracing::warn!`
123    /// per unique error message instead of spamming the log with one
124    /// warning per affected file. Shared across all parallel resolver
125    /// threads via `Mutex`. Empty and unused when no tsconfig errors occur.
126    pub tsconfig_warned: &'a Mutex<FxHashSet<String>>,
127}
128
129/// Thread-safe lazy canonical path index, built on first access.
130pub(super) struct CanonicalFallback<'a> {
131    files: &'a [fallow_types::discover::DiscoveredFile],
132    map: std::sync::OnceLock<FxHashMap<std::path::PathBuf, FileId>>,
133}
134
135impl<'a> CanonicalFallback<'a> {
136    pub const fn new(files: &'a [fallow_types::discover::DiscoveredFile]) -> Self {
137        Self {
138            files,
139            map: std::sync::OnceLock::new(),
140        }
141    }
142
143    /// Look up a canonical path, lazily building the index on first call.
144    pub fn get(&self, canonical: &Path) -> Option<FileId> {
145        let map = self.map.get_or_init(|| {
146            tracing::debug!(
147                "intra-project symlinks detected — building canonical path index ({} files)",
148                self.files.len()
149            );
150            self.files
151                .iter()
152                .filter_map(|f| {
153                    dunce::canonicalize(&f.path)
154                        .ok()
155                        .map(|canonical| (canonical, f.id))
156                })
157                .collect()
158        });
159        map.get(canonical).copied()
160    }
161}
162
163#[cfg(all(test, not(miri)))]
164mod tests {
165    use super::*;
166    use fallow_types::discover::DiscoveredFile;
167
168    #[test]
169    fn canonical_fallback_returns_none_for_empty_files() {
170        let files: Vec<DiscoveredFile> = vec![];
171        let fallback = CanonicalFallback::new(&files);
172        assert!(fallback.get(Path::new("/nonexistent")).is_none());
173    }
174
175    #[test]
176    fn canonical_fallback_finds_existing_file() {
177        let temp = std::env::temp_dir().join("fallow-test-canonical-fallback");
178        let _ = std::fs::create_dir_all(&temp);
179        let test_file = temp.join("test.ts");
180        std::fs::write(&test_file, "").unwrap();
181
182        let files = vec![DiscoveredFile {
183            id: FileId(42),
184            path: test_file.clone(),
185            size_bytes: 0,
186        }];
187        let fallback = CanonicalFallback::new(&files);
188
189        let canonical = dunce::canonicalize(&test_file).unwrap();
190        assert_eq!(fallback.get(&canonical), Some(FileId(42)));
191
192        // Second call uses cached map (OnceLock)
193        assert_eq!(fallback.get(&canonical), Some(FileId(42)));
194
195        let _ = std::fs::remove_dir_all(&temp);
196    }
197
198    #[test]
199    fn canonical_fallback_returns_none_for_missing_path() {
200        let temp = std::env::temp_dir().join("fallow-test-canonical-miss");
201        let _ = std::fs::create_dir_all(&temp);
202        let test_file = temp.join("exists.ts");
203        std::fs::write(&test_file, "").unwrap();
204
205        let files = vec![DiscoveredFile {
206            id: FileId(1),
207            path: test_file,
208            size_bytes: 0,
209        }];
210        let fallback = CanonicalFallback::new(&files);
211        assert!(fallback.get(Path::new("/nonexistent/file.ts")).is_none());
212
213        let _ = std::fs::remove_dir_all(&temp);
214    }
215}
216
217/// Known output directory names that may appear in exports map targets.
218/// When an exports map points to `./dist/utils.js`, we try replacing these
219/// prefixes with `src/` (the conventional source directory) to find the tracked
220/// source file.
221pub const OUTPUT_DIRS: &[&str] = &["dist", "build", "out", "esm", "cjs"];
222
223/// Source extensions to try when mapping a built output file back to source.
224pub const SOURCE_EXTS: &[&str] = &["ts", "tsx", "mts", "cts", "js", "jsx", "mjs", "cjs"];
225
226/// React Native platform extension prefixes.
227/// Metro resolves platform-specific files (e.g., `./foo` -> `./foo.web.tsx` on web).
228pub const RN_PLATFORM_PREFIXES: &[&str] = &[".web", ".ios", ".android", ".native"];