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 fallbacks::extract_package_name_from_node_modules_path;
32pub use path_info::{
33    extract_package_name, is_bare_specifier, is_path_alias, is_valid_package_name,
34};
35pub use types::{
36    ResolveResult, ResolvedImport, ResolvedModule, ResolvedReExport, ResolvedSourceEdge,
37};
38
39use std::path::{Path, PathBuf};
40use std::sync::Mutex;
41
42use rayon::prelude::*;
43use rustc_hash::{FxHashMap, FxHashSet};
44
45use fallow_config::{AutoImportKind, AutoImportRule};
46use fallow_types::discover::{DiscoveredFile, FileId};
47use fallow_types::extract::{ImportInfo, ImportedName, ModuleInfo};
48use oxc_span::Span;
49
50use dynamic_imports::{resolve_dynamic_imports, resolve_dynamic_patterns};
51use re_exports::resolve_re_exports;
52use react_native::{build_condition_names, build_extensions};
53use require_imports::resolve_require_imports;
54use specifier::create_resolver;
55use static_imports::resolve_static_imports;
56use types::{PackageManifestInfo, ResolveContext};
57use upgrades::apply_specifier_upgrades;
58
59/// Resolve all imports across all modules in parallel.
60#[must_use]
61#[expect(
62    clippy::too_many_arguments,
63    reason = "resolver inputs come from disjoint sources (config, plugins, workspace, filesystem); \
64              bundling them into a struct would be a cross-cutting refactor outside this task"
65)]
66pub fn resolve_all_imports(
67    modules: &[ModuleInfo],
68    files: &[DiscoveredFile],
69    workspaces: &[fallow_config::WorkspaceInfo],
70    active_plugins: &[String],
71    path_aliases: &[(String, String)],
72    auto_imports: &[AutoImportRule],
73    scss_include_paths: &[PathBuf],
74    static_dir_mappings: &[(PathBuf, String)],
75    root: &Path,
76    extra_conditions: &[String],
77) -> Vec<ResolvedModule> {
78    let canonical_ws_roots: Vec<PathBuf> = workspaces
79        .par_iter()
80        .map(|ws| dunce::canonicalize(&ws.root).unwrap_or_else(|_| ws.root.clone()))
81        .collect();
82    let workspace_roots: FxHashMap<&str, &Path> = workspaces
83        .iter()
84        .zip(canonical_ws_roots.iter())
85        .map(|(ws, canonical)| (ws.name.as_str(), canonical.as_path()))
86        .collect();
87    let root_canonical = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
88    let mut package_manifests = Vec::new();
89    if let Ok(package_json) = fallow_config::PackageJson::load(&root.join("package.json")) {
90        package_manifests.push(PackageManifestInfo {
91            root: root.to_path_buf(),
92            canonical_root: root_canonical,
93            name: package_json.name.clone(),
94            package_json,
95        });
96    }
97    for (ws, canonical_root) in workspaces.iter().zip(canonical_ws_roots.iter()) {
98        if let Ok(package_json) = fallow_config::PackageJson::load(&ws.root.join("package.json")) {
99            package_manifests.push(PackageManifestInfo {
100                root: ws.root.clone(),
101                canonical_root: canonical_root.clone(),
102                name: package_json.name.clone().or_else(|| Some(ws.name.clone())),
103                package_json,
104            });
105        }
106    }
107
108    let root_is_canonical = dunce::canonicalize(root).is_ok_and(|c| c == root);
109
110    let canonical_paths: Vec<PathBuf> = if root_is_canonical {
111        Vec::new()
112    } else {
113        files
114            .par_iter()
115            .map(|f| dunce::canonicalize(&f.path).unwrap_or_else(|_| f.path.clone()))
116            .collect()
117    };
118
119    let path_to_id: FxHashMap<&Path, FileId> = if root_is_canonical {
120        files.iter().map(|f| (f.path.as_path(), f.id)).collect()
121    } else {
122        canonical_paths
123            .iter()
124            .enumerate()
125            .map(|(idx, canonical)| (canonical.as_path(), files[idx].id))
126            .collect()
127    };
128
129    let raw_path_to_id: FxHashMap<&Path, FileId> =
130        files.iter().map(|f| (f.path.as_path(), f.id)).collect();
131
132    let file_paths: Vec<&Path> = files.iter().map(|f| f.path.as_path()).collect();
133
134    let extensions = build_extensions(active_plugins);
135    let condition_names = build_condition_names(active_plugins, extra_conditions);
136    let resolver = create_resolver(active_plugins, extra_conditions);
137    let mut style_conditions = extra_conditions.to_vec();
138    style_conditions.push("sass".to_string());
139    style_conditions.push("style".to_string());
140    let style_resolver = create_resolver(active_plugins, &style_conditions);
141
142    let canonical_fallback = if root_is_canonical {
143        Some(types::CanonicalFallback::new(files))
144    } else {
145        None
146    };
147
148    let tsconfig_warned: Mutex<FxHashSet<String>> = Mutex::new(FxHashSet::default());
149
150    let ctx = ResolveContext {
151        resolver: &resolver,
152        style_resolver: &style_resolver,
153        extensions: &extensions,
154        path_to_id: &path_to_id,
155        raw_path_to_id: &raw_path_to_id,
156        workspace_roots: &workspace_roots,
157        package_manifests: &package_manifests,
158        condition_names: &condition_names,
159        path_aliases,
160        scss_include_paths,
161        static_dir_mappings,
162        root,
163        canonical_fallback: canonical_fallback.as_ref(),
164        tsconfig_warned: &tsconfig_warned,
165    };
166
167    let mut resolved: Vec<ResolvedModule> = modules
168        .par_iter()
169        .filter_map(|module| {
170            let Some(file_path) = file_paths.get(module.file_id.0 as usize) else {
171                tracing::warn!(
172                    file_id = module.file_id.0,
173                    "Skipping module with unknown file_id during resolution"
174                );
175                return None;
176            };
177
178            let mut all_imports = resolve_static_imports(&ctx, file_path, &module.imports);
179            all_imports.extend(resolve_require_imports(
180                &ctx,
181                file_path,
182                &module.require_calls,
183            ));
184
185            let from_dir = if canonical_paths.is_empty() {
186                file_path.parent().unwrap_or(file_path)
187            } else {
188                canonical_paths
189                    .get(module.file_id.0 as usize)
190                    .and_then(|p| p.parent())
191                    .unwrap_or(file_path)
192            };
193
194            Some(ResolvedModule {
195                file_id: module.file_id,
196                path: file_path.to_path_buf(),
197                exports: module.exports.clone(),
198                re_exports: resolve_re_exports(&ctx, file_path, &module.re_exports),
199                resolved_imports: all_imports,
200                resolved_dynamic_imports: resolve_dynamic_imports(
201                    &ctx,
202                    file_path,
203                    &module.dynamic_imports,
204                ),
205                resolved_dynamic_patterns: resolve_dynamic_patterns(
206                    from_dir,
207                    &module.dynamic_import_patterns,
208                    &canonical_paths,
209                    files,
210                ),
211                member_accesses: module.member_accesses.clone(),
212                whole_object_uses: module.whole_object_uses.clone(),
213                has_cjs_exports: module.has_cjs_exports,
214                has_angular_component_template_url: module.has_angular_component_template_url,
215                unused_import_bindings: module.unused_import_bindings.iter().cloned().collect(),
216                type_referenced_import_bindings: module.type_referenced_import_bindings.clone(),
217                value_referenced_import_bindings: module.value_referenced_import_bindings.clone(),
218                namespace_object_aliases: module.namespace_object_aliases.clone(),
219            })
220        })
221        .collect();
222
223    apply_specifier_upgrades(&mut resolved);
224
225    synthesize_auto_import_edges(
226        &mut resolved,
227        modules,
228        auto_imports,
229        &path_to_id,
230        &raw_path_to_id,
231    );
232
233    resolved
234}
235
236/// Synthesize module-graph edges for convention auto-imports.
237///
238/// For each module, every captured `auto_import_candidates` name is matched
239/// against the active plugins' auto-import table; on a hit a synthetic
240/// [`ResolvedImport`] is added so the existing graph builder credits the edge.
241/// Name collisions across files over-credit every match, keeping each provider
242/// reachable. Resolution is recomputed from the live file index each run.
243fn synthesize_auto_import_edges(
244    resolved: &mut [ResolvedModule],
245    modules: &[ModuleInfo],
246    auto_imports: &[AutoImportRule],
247    path_to_id: &FxHashMap<&Path, FileId>,
248    raw_path_to_id: &FxHashMap<&Path, FileId>,
249) {
250    if auto_imports.is_empty() {
251        return;
252    }
253
254    let mut table: FxHashMap<&str, Vec<(FileId, AutoImportKind)>> = FxHashMap::default();
255    for rule in auto_imports {
256        let source = rule.source.as_path();
257        let Some(file_id) = raw_path_to_id
258            .get(source)
259            .or_else(|| path_to_id.get(source))
260            .copied()
261        else {
262            continue;
263        };
264        table
265            .entry(rule.name.as_str())
266            .or_default()
267            .push((file_id, rule.kind));
268    }
269    if table.is_empty() {
270        return;
271    }
272
273    let candidates: FxHashMap<FileId, &[String]> = modules
274        .iter()
275        .filter(|module| !module.auto_import_candidates.is_empty())
276        .map(|module| (module.file_id, module.auto_import_candidates.as_slice()))
277        .collect();
278    if candidates.is_empty() {
279        return;
280    }
281
282    for module in resolved.iter_mut() {
283        let Some(names) = candidates.get(&module.file_id) else {
284            continue;
285        };
286        for name in *names {
287            if is_auto_import_builtin(name) {
288                continue;
289            }
290            let Some(targets) = table.get(name.as_str()) else {
291                continue;
292            };
293            for (target_id, kind) in targets {
294                if *target_id == module.file_id {
295                    continue;
296                }
297                module.resolved_imports.push(ResolvedImport {
298                    info: synthetic_auto_import_info(name, *kind),
299                    target: ResolveResult::InternalModule(*target_id),
300                });
301            }
302        }
303    }
304}
305
306fn is_auto_import_builtin(name: &str) -> bool {
307    matches!(
308        name,
309        "AbortController"
310            | "AbortSignal"
311            | "Array"
312            | "ArrayBuffer"
313            | "BigInt"
314            | "Blob"
315            | "Boolean"
316            | "Buffer"
317            | "CSS"
318            | "DOMParser"
319            | "Date"
320            | "Document"
321            | "Error"
322            | "Event"
323            | "EventTarget"
324            | "File"
325            | "FormData"
326            | "Intl"
327            | "JSON"
328            | "Map"
329            | "Math"
330            | "Number"
331            | "Object"
332            | "Promise"
333            | "Reflect"
334            | "RegExp"
335            | "Response"
336            | "Set"
337            | "String"
338            | "Symbol"
339            | "URL"
340            | "URLSearchParams"
341            | "WeakMap"
342            | "WeakSet"
343            | "Window"
344            | "alert"
345            | "clearInterval"
346            | "clearTimeout"
347            | "console"
348            | "document"
349            | "fetch"
350            | "global"
351            | "globalThis"
352            | "localStorage"
353            | "navigator"
354            | "process"
355            | "requestAnimationFrame"
356            | "sessionStorage"
357            | "setInterval"
358            | "setTimeout"
359            | "window"
360            | "computed"
361            | "customRef"
362            | "defineAsyncComponent"
363            | "defineComponent"
364            | "effectScope"
365            | "getCurrentInstance"
366            | "h"
367            | "inject"
368            | "isProxy"
369            | "isReactive"
370            | "isReadonly"
371            | "isRef"
372            | "markRaw"
373            | "nextTick"
374            | "onActivated"
375            | "onBeforeMount"
376            | "onBeforeUnmount"
377            | "onBeforeUpdate"
378            | "onDeactivated"
379            | "onErrorCaptured"
380            | "onMounted"
381            | "onRenderTracked"
382            | "onRenderTriggered"
383            | "onScopeDispose"
384            | "onServerPrefetch"
385            | "onUnmounted"
386            | "onUpdated"
387            | "provide"
388            | "reactive"
389            | "readonly"
390            | "ref"
391            | "resolveComponent"
392            | "shallowReactive"
393            | "shallowReadonly"
394            | "shallowRef"
395            | "toRaw"
396            | "toRef"
397            | "toRefs"
398            | "triggerRef"
399            | "unref"
400            | "watch"
401            | "watchEffect"
402            | "watchPostEffect"
403            | "watchSyncEffect"
404            | "useAsyncData"
405            | "useCookie"
406            | "useError"
407            | "useFetch"
408            | "useHead"
409            | "useLazyAsyncData"
410            | "useLazyFetch"
411            | "useNuxtApp"
412            | "useRequestEvent"
413            | "useRequestHeaders"
414            | "useRoute"
415            | "useRouter"
416            | "useRuntimeConfig"
417            | "useSeoMeta"
418            | "useState"
419    )
420}
421
422/// Build a synthetic [`ImportInfo`] for a convention auto-import. Component and
423/// default kinds credit the default export; named kinds credit the named export.
424fn synthetic_auto_import_info(name: &str, kind: AutoImportKind) -> ImportInfo {
425    let imported_name = match kind {
426        AutoImportKind::Named => ImportedName::Named(name.to_string()),
427        AutoImportKind::Default | AutoImportKind::DefaultComponent => ImportedName::Default,
428    };
429    ImportInfo {
430        source: format!("<auto-import:{name}>"),
431        imported_name,
432        local_name: name.to_string(),
433        is_type_only: false,
434        from_style: false,
435        span: Span::default(),
436        source_span: Span::default(),
437    }
438}