Skip to main content

fallow_graph/resolve/
mod.rs

1//! Import specifier resolution using `oxc_resolver`.
2//!
3//! Orchestrates the resolution pipeline: for every extracted module, resolves all
4//! import specifiers in parallel (via rayon) to an [`ResolveResult`] — internal file,
5//! npm package, external file, or unresolvable. The entry point is [`resolve_all_imports`].
6//!
7//! Resolution is split into submodules by import kind:
8//! - `static_imports` — ES `import` declarations
9//! - `dynamic_imports` — `import()` expressions and glob-based dynamic patterns
10//! - `require_imports` — CommonJS `require()` calls
11//! - `re_exports` — `export { x } from './y'` re-export sources
12//! - `upgrades` — post-resolution pass fixing non-deterministic bare specifier results
13//!
14//! Handles tsconfig path aliases (auto-discovered per file), pnpm virtual store paths,
15//! React Native platform extensions, and package.json `exports` subpath resolution with
16//! output-to-source directory fallback.
17
18mod dynamic_imports;
19pub(crate) mod fallbacks;
20mod path_info;
21mod re_exports;
22mod react_native;
23mod require_imports;
24mod specifier;
25mod static_imports;
26#[cfg(test)]
27mod tests;
28mod types;
29mod upgrades;
30
31pub use path_info::{extract_package_name, is_bare_specifier, is_path_alias};
32pub use types::{ResolveResult, ResolvedImport, ResolvedModule, ResolvedReExport};
33
34use std::path::{Path, PathBuf};
35use std::sync::Mutex;
36
37use rayon::prelude::*;
38use rustc_hash::{FxHashMap, FxHashSet};
39
40use fallow_types::discover::{DiscoveredFile, FileId};
41use fallow_types::extract::ModuleInfo;
42
43use dynamic_imports::{resolve_dynamic_imports, resolve_dynamic_patterns};
44use re_exports::resolve_re_exports;
45use require_imports::resolve_require_imports;
46use specifier::create_resolver;
47use static_imports::resolve_static_imports;
48use types::ResolveContext;
49use upgrades::apply_specifier_upgrades;
50
51/// Resolve all imports across all modules in parallel.
52#[must_use]
53pub fn resolve_all_imports(
54    modules: &[ModuleInfo],
55    files: &[DiscoveredFile],
56    workspaces: &[fallow_config::WorkspaceInfo],
57    active_plugins: &[String],
58    path_aliases: &[(String, String)],
59    scss_include_paths: &[PathBuf],
60    root: &Path,
61) -> Vec<ResolvedModule> {
62    // Build workspace name → root index for pnpm store fallback.
63    // Canonicalize roots to match path_to_id (which uses canonical paths).
64    // Without this, macOS /var → /private/var and similar platform symlinks
65    // cause workspace roots to mismatch canonical file paths.
66    let canonical_ws_roots: Vec<PathBuf> = workspaces
67        .par_iter()
68        .map(|ws| dunce::canonicalize(&ws.root).unwrap_or_else(|_| ws.root.clone()))
69        .collect();
70    let workspace_roots: FxHashMap<&str, &Path> = workspaces
71        .iter()
72        .zip(canonical_ws_roots.iter())
73        .map(|(ws, canonical)| (ws.name.as_str(), canonical.as_path()))
74        .collect();
75
76    // Check if project root is already canonical (no symlinks in path).
77    // When true, raw paths == canonical paths for files under root, so we can skip
78    // the upfront bulk canonicalize() of all source files (21k+ syscalls on large projects).
79    // A lazy CanonicalFallback handles the rare intra-project symlink case.
80    let root_is_canonical = dunce::canonicalize(root).is_ok_and(|c| c == root);
81
82    // Pre-compute canonical paths ONCE for all files in parallel (avoiding repeated syscalls).
83    // Skipped when root is canonical — the lazy fallback below handles edge cases.
84    let canonical_paths: Vec<PathBuf> = if root_is_canonical {
85        Vec::new()
86    } else {
87        files
88            .par_iter()
89            .map(|f| dunce::canonicalize(&f.path).unwrap_or_else(|_| f.path.clone()))
90            .collect()
91    };
92
93    // Primary path → FileId index. When root is canonical, uses raw paths (fast).
94    // Otherwise uses pre-computed canonical paths (correct for all symlink configurations).
95    let path_to_id: FxHashMap<&Path, FileId> = if root_is_canonical {
96        files.iter().map(|f| (f.path.as_path(), f.id)).collect()
97    } else {
98        canonical_paths
99            .iter()
100            .enumerate()
101            .map(|(idx, canonical)| (canonical.as_path(), files[idx].id))
102            .collect()
103    };
104
105    // Also index by non-canonical path for fallback lookups
106    let raw_path_to_id: FxHashMap<&Path, FileId> =
107        files.iter().map(|f| (f.path.as_path(), f.id)).collect();
108
109    // FileIds are sequential 0..n, so direct array indexing is faster than FxHashMap.
110    let file_paths: Vec<&Path> = files.iter().map(|f| f.path.as_path()).collect();
111
112    // Create resolver ONCE and share across threads (oxc_resolver::Resolver is Send + Sync)
113    let resolver = create_resolver(active_plugins);
114
115    // Lazy canonical fallback — only needed when root is canonical (path_to_id uses raw paths).
116    // When root is NOT canonical, path_to_id already uses canonical paths, no fallback needed.
117    let canonical_fallback = if root_is_canonical {
118        Some(types::CanonicalFallback::new(files))
119    } else {
120        None
121    };
122
123    // Dedup set for broken-tsconfig warnings. See `ResolveContext::tsconfig_warned`.
124    let tsconfig_warned: Mutex<FxHashSet<String>> = Mutex::new(FxHashSet::default());
125
126    // Shared resolution context — avoids passing 6 arguments to every resolve_specifier call
127    let ctx = ResolveContext {
128        resolver: &resolver,
129        path_to_id: &path_to_id,
130        raw_path_to_id: &raw_path_to_id,
131        workspace_roots: &workspace_roots,
132        path_aliases,
133        scss_include_paths,
134        root,
135        canonical_fallback: canonical_fallback.as_ref(),
136        tsconfig_warned: &tsconfig_warned,
137    };
138
139    // Resolve in parallel — shared resolver instance.
140    // Each file resolves its own imports independently (no shared bare specifier cache).
141    // oxc_resolver's internal caches (package.json, tsconfig, directory entries) are
142    // shared across threads for performance.
143    let mut resolved: Vec<ResolvedModule> = modules
144        .par_iter()
145        .filter_map(|module| {
146            let Some(file_path) = file_paths.get(module.file_id.0 as usize) else {
147                tracing::warn!(
148                    file_id = module.file_id.0,
149                    "Skipping module with unknown file_id during resolution"
150                );
151                return None;
152            };
153
154            let mut all_imports = resolve_static_imports(&ctx, file_path, &module.imports);
155            all_imports.extend(resolve_require_imports(
156                &ctx,
157                file_path,
158                &module.require_calls,
159            ));
160
161            let from_dir = if canonical_paths.is_empty() {
162                // Root is canonical — raw paths are canonical
163                file_path.parent().unwrap_or(file_path)
164            } else {
165                canonical_paths
166                    .get(module.file_id.0 as usize)
167                    .and_then(|p| p.parent())
168                    .unwrap_or(file_path)
169            };
170
171            Some(ResolvedModule {
172                file_id: module.file_id,
173                path: file_path.to_path_buf(),
174                exports: module.exports.clone(),
175                re_exports: resolve_re_exports(&ctx, file_path, &module.re_exports),
176                resolved_imports: all_imports,
177                resolved_dynamic_imports: resolve_dynamic_imports(
178                    &ctx,
179                    file_path,
180                    &module.dynamic_imports,
181                ),
182                resolved_dynamic_patterns: resolve_dynamic_patterns(
183                    from_dir,
184                    &module.dynamic_import_patterns,
185                    &canonical_paths,
186                    files,
187                ),
188                member_accesses: module.member_accesses.clone(),
189                whole_object_uses: module.whole_object_uses.clone(),
190                has_cjs_exports: module.has_cjs_exports,
191                unused_import_bindings: module.unused_import_bindings.iter().cloned().collect(),
192            })
193        })
194        .collect();
195
196    apply_specifier_upgrades(&mut resolved);
197
198    resolved
199}