1mod 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#[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("style".to_string());
139 let style_resolver = create_resolver(active_plugins, &style_conditions);
140
141 let canonical_fallback = if root_is_canonical {
142 Some(types::CanonicalFallback::new(files))
143 } else {
144 None
145 };
146
147 let tsconfig_warned: Mutex<FxHashSet<String>> = Mutex::new(FxHashSet::default());
148
149 let ctx = ResolveContext {
150 resolver: &resolver,
151 style_resolver: &style_resolver,
152 extensions: &extensions,
153 path_to_id: &path_to_id,
154 raw_path_to_id: &raw_path_to_id,
155 workspace_roots: &workspace_roots,
156 package_manifests: &package_manifests,
157 condition_names: &condition_names,
158 path_aliases,
159 scss_include_paths,
160 static_dir_mappings,
161 root,
162 canonical_fallback: canonical_fallback.as_ref(),
163 tsconfig_warned: &tsconfig_warned,
164 };
165
166 let mut resolved: Vec<ResolvedModule> = modules
167 .par_iter()
168 .filter_map(|module| {
169 let Some(file_path) = file_paths.get(module.file_id.0 as usize) else {
170 tracing::warn!(
171 file_id = module.file_id.0,
172 "Skipping module with unknown file_id during resolution"
173 );
174 return None;
175 };
176
177 let mut all_imports = resolve_static_imports(&ctx, file_path, &module.imports);
178 all_imports.extend(resolve_require_imports(
179 &ctx,
180 file_path,
181 &module.require_calls,
182 ));
183
184 let from_dir = if canonical_paths.is_empty() {
185 file_path.parent().unwrap_or(file_path)
186 } else {
187 canonical_paths
188 .get(module.file_id.0 as usize)
189 .and_then(|p| p.parent())
190 .unwrap_or(file_path)
191 };
192
193 Some(ResolvedModule {
194 file_id: module.file_id,
195 path: file_path.to_path_buf(),
196 exports: module.exports.clone(),
197 re_exports: resolve_re_exports(&ctx, file_path, &module.re_exports),
198 resolved_imports: all_imports,
199 resolved_dynamic_imports: resolve_dynamic_imports(
200 &ctx,
201 file_path,
202 &module.dynamic_imports,
203 ),
204 resolved_dynamic_patterns: resolve_dynamic_patterns(
205 from_dir,
206 &module.dynamic_import_patterns,
207 &canonical_paths,
208 files,
209 ),
210 member_accesses: module.member_accesses.clone(),
211 whole_object_uses: module.whole_object_uses.clone(),
212 has_cjs_exports: module.has_cjs_exports,
213 has_angular_component_template_url: module.has_angular_component_template_url,
214 unused_import_bindings: module.unused_import_bindings.iter().cloned().collect(),
215 type_referenced_import_bindings: module.type_referenced_import_bindings.clone(),
216 value_referenced_import_bindings: module.value_referenced_import_bindings.clone(),
217 namespace_object_aliases: module.namespace_object_aliases.clone(),
218 })
219 })
220 .collect();
221
222 apply_specifier_upgrades(&mut resolved);
223
224 synthesize_auto_import_edges(
225 &mut resolved,
226 modules,
227 auto_imports,
228 &path_to_id,
229 &raw_path_to_id,
230 );
231
232 resolved
233}
234
235fn synthesize_auto_import_edges(
243 resolved: &mut [ResolvedModule],
244 modules: &[ModuleInfo],
245 auto_imports: &[AutoImportRule],
246 path_to_id: &FxHashMap<&Path, FileId>,
247 raw_path_to_id: &FxHashMap<&Path, FileId>,
248) {
249 if auto_imports.is_empty() {
250 return;
251 }
252
253 let mut table: FxHashMap<&str, Vec<(FileId, AutoImportKind)>> = FxHashMap::default();
254 for rule in auto_imports {
255 let source = rule.source.as_path();
256 let Some(file_id) = raw_path_to_id
257 .get(source)
258 .or_else(|| path_to_id.get(source))
259 .copied()
260 else {
261 continue;
262 };
263 table
264 .entry(rule.name.as_str())
265 .or_default()
266 .push((file_id, rule.kind));
267 }
268 if table.is_empty() {
269 return;
270 }
271
272 let candidates: FxHashMap<FileId, &[String]> = modules
273 .iter()
274 .filter(|module| !module.auto_import_candidates.is_empty())
275 .map(|module| (module.file_id, module.auto_import_candidates.as_slice()))
276 .collect();
277 if candidates.is_empty() {
278 return;
279 }
280
281 for module in resolved.iter_mut() {
282 let Some(names) = candidates.get(&module.file_id) else {
283 continue;
284 };
285 for name in *names {
286 if is_auto_import_builtin(name) {
287 continue;
288 }
289 let Some(targets) = table.get(name.as_str()) else {
290 continue;
291 };
292 for (target_id, kind) in targets {
293 if *target_id == module.file_id {
294 continue;
295 }
296 module.resolved_imports.push(ResolvedImport {
297 info: synthetic_auto_import_info(name, *kind),
298 target: ResolveResult::InternalModule(*target_id),
299 });
300 }
301 }
302 }
303}
304
305fn is_auto_import_builtin(name: &str) -> bool {
306 matches!(
307 name,
308 "AbortController"
309 | "AbortSignal"
310 | "Array"
311 | "ArrayBuffer"
312 | "BigInt"
313 | "Blob"
314 | "Boolean"
315 | "Buffer"
316 | "CSS"
317 | "DOMParser"
318 | "Date"
319 | "Document"
320 | "Error"
321 | "Event"
322 | "EventTarget"
323 | "File"
324 | "FormData"
325 | "Intl"
326 | "JSON"
327 | "Map"
328 | "Math"
329 | "Number"
330 | "Object"
331 | "Promise"
332 | "Reflect"
333 | "RegExp"
334 | "Response"
335 | "Set"
336 | "String"
337 | "Symbol"
338 | "URL"
339 | "URLSearchParams"
340 | "WeakMap"
341 | "WeakSet"
342 | "Window"
343 | "alert"
344 | "clearInterval"
345 | "clearTimeout"
346 | "console"
347 | "document"
348 | "fetch"
349 | "global"
350 | "globalThis"
351 | "localStorage"
352 | "navigator"
353 | "process"
354 | "requestAnimationFrame"
355 | "sessionStorage"
356 | "setInterval"
357 | "setTimeout"
358 | "window"
359 | "computed"
360 | "customRef"
361 | "defineAsyncComponent"
362 | "defineComponent"
363 | "effectScope"
364 | "getCurrentInstance"
365 | "h"
366 | "inject"
367 | "isProxy"
368 | "isReactive"
369 | "isReadonly"
370 | "isRef"
371 | "markRaw"
372 | "nextTick"
373 | "onActivated"
374 | "onBeforeMount"
375 | "onBeforeUnmount"
376 | "onBeforeUpdate"
377 | "onDeactivated"
378 | "onErrorCaptured"
379 | "onMounted"
380 | "onRenderTracked"
381 | "onRenderTriggered"
382 | "onScopeDispose"
383 | "onServerPrefetch"
384 | "onUnmounted"
385 | "onUpdated"
386 | "provide"
387 | "reactive"
388 | "readonly"
389 | "ref"
390 | "resolveComponent"
391 | "shallowReactive"
392 | "shallowReadonly"
393 | "shallowRef"
394 | "toRaw"
395 | "toRef"
396 | "toRefs"
397 | "triggerRef"
398 | "unref"
399 | "watch"
400 | "watchEffect"
401 | "watchPostEffect"
402 | "watchSyncEffect"
403 | "useAsyncData"
404 | "useCookie"
405 | "useError"
406 | "useFetch"
407 | "useHead"
408 | "useLazyAsyncData"
409 | "useLazyFetch"
410 | "useNuxtApp"
411 | "useRequestEvent"
412 | "useRequestHeaders"
413 | "useRoute"
414 | "useRouter"
415 | "useRuntimeConfig"
416 | "useSeoMeta"
417 | "useState"
418 )
419}
420
421fn synthetic_auto_import_info(name: &str, kind: AutoImportKind) -> ImportInfo {
424 let imported_name = match kind {
425 AutoImportKind::Named => ImportedName::Named(name.to_string()),
426 AutoImportKind::Default | AutoImportKind::DefaultComponent => ImportedName::Default,
427 };
428 ImportInfo {
429 source: format!("<auto-import:{name}>"),
430 imported_name,
431 local_name: name.to_string(),
432 is_type_only: false,
433 from_style: false,
434 span: Span::default(),
435 source_span: Span::default(),
436 }
437}