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, ResolvedProject, ResolvedReExport,
37 ResolvedReplacedModuleTarget, ResolvedSourceEdge,
38};
39
40use std::path::{Path, PathBuf};
41use std::sync::Mutex;
42
43use rayon::prelude::*;
44use rustc_hash::{FxHashMap, FxHashSet};
45
46use fallow_config::{AutoImportKind, AutoImportRule};
47use fallow_types::discover::{DiscoveredFile, FileId};
48use fallow_types::extract::{ImportInfo, ImportedName, ModuleInfo, SemanticFact};
49use oxc_span::Span;
50
51use dynamic_imports::{resolve_dynamic_imports, resolve_dynamic_patterns};
52use re_exports::resolve_re_exports;
53use react_native::{build_condition_names, build_extensions, synthesize_platform_family_edges};
54use require_imports::resolve_require_imports;
55use specifier::create_resolver;
56use static_imports::resolve_static_imports;
57use types::{DenoImportMapEntry, PackageManifestInfo, ResolveContext};
58use upgrades::{ResolvedVitestMockOperation, apply_specifier_upgrades};
59
60pub struct ResolveAllImportsInput<'a> {
62 pub modules: &'a [ModuleInfo],
64 pub files: &'a [DiscoveredFile],
66 pub workspaces: &'a [fallow_config::WorkspaceInfo],
68 pub active_plugins: &'a [String],
70 pub path_aliases: &'a [(String, String)],
72 pub auto_imports: &'a [AutoImportRule],
74 pub scss_include_paths: &'a [PathBuf],
76 pub static_dir_mappings: &'a [(PathBuf, String)],
78 pub root: &'a Path,
80 pub extra_conditions: &'a [String],
82}
83
84pub struct ResolverSession {
95 resolver: oxc_resolver::Resolver,
96 style_resolver: oxc_resolver::Resolver,
97 extensions: Vec<String>,
98 condition_names: Vec<String>,
99 package_manifests: Vec<PackageManifestInfo>,
100 has_deno_import_maps: bool,
101 canonical_ws_roots: Vec<PathBuf>,
102 root_is_canonical: bool,
103}
104
105impl ResolverSession {
106 #[must_use]
114 pub fn new(input: &ResolveAllImportsInput<'_>) -> Self {
115 let canonical_ws_roots: Vec<PathBuf> = input
116 .workspaces
117 .par_iter()
118 .map(|ws| dunce::canonicalize(&ws.root).unwrap_or_else(|_| ws.root.clone()))
119 .collect();
120 let package_manifests = build_package_manifests(input, &canonical_ws_roots);
121 let has_deno_import_maps = package_manifests
122 .iter()
123 .any(|manifest| !manifest.deno_import_map.is_empty());
124 let root_is_canonical = dunce::canonicalize(input.root).is_ok_and(|c| c == input.root);
125
126 let extensions = build_extensions(input.active_plugins);
127 let condition_names = build_condition_names(input.active_plugins, input.extra_conditions);
128 let resolver = create_resolver(input.active_plugins, input.extra_conditions);
129 let mut style_conditions = input.extra_conditions.to_vec();
130 style_conditions.push("sass".to_string());
131 style_conditions.push("style".to_string());
132 let style_resolver = create_resolver(input.active_plugins, &style_conditions);
133
134 Self {
135 resolver,
136 style_resolver,
137 extensions,
138 condition_names,
139 package_manifests,
140 has_deno_import_maps,
141 canonical_ws_roots,
142 root_is_canonical,
143 }
144 }
145}
146
147#[must_use]
149pub fn resolve_all_imports(input: &ResolveAllImportsInput<'_>) -> ResolvedProject {
150 let session = ResolverSession::new(input);
151 resolve_all_imports_with_session(input, &session)
152}
153
154#[must_use]
162pub fn resolve_all_imports_with_session(
163 input: &ResolveAllImportsInput<'_>,
164 session: &ResolverSession,
165) -> ResolvedProject {
166 let root_is_canonical = session.root_is_canonical;
167 let workspace_roots = build_workspace_roots(input.workspaces, &session.canonical_ws_roots);
168 let canonical_paths = build_canonical_file_paths(input.files, root_is_canonical);
169 let path_to_id = build_path_to_id(input.files, &canonical_paths, root_is_canonical);
170 let raw_path_to_id: FxHashMap<&Path, FileId> = input
171 .files
172 .iter()
173 .map(|f| (f.path.as_path(), f.id))
174 .collect();
175
176 let file_paths: Vec<&Path> = input.files.iter().map(|f| f.path.as_path()).collect();
177
178 let canonical_fallback = if root_is_canonical {
179 Some(types::CanonicalFallback::new(input.files))
180 } else {
181 None
182 };
183
184 let tsconfig_warned: Mutex<FxHashSet<String>> = Mutex::new(FxHashSet::default());
185 let tsconfig_cache = types::TsconfigCache::default();
186 let canonicalize_cache = types::CanonicalizeCache::default();
187
188 let ctx = ResolveContext {
189 resolver: &session.resolver,
190 style_resolver: &session.style_resolver,
191 extensions: &session.extensions,
192 path_to_id: &path_to_id,
193 raw_path_to_id: &raw_path_to_id,
194 workspace_roots: &workspace_roots,
195 package_manifests: &session.package_manifests,
196 has_deno_import_maps: session.has_deno_import_maps,
197 condition_names: &session.condition_names,
198 path_aliases: input.path_aliases,
199 scss_include_paths: input.scss_include_paths,
200 static_dir_mappings: input.static_dir_mappings,
201 root: input.root,
202 canonical_fallback: canonical_fallback.as_ref(),
203 tsconfig_warned: &tsconfig_warned,
204 tsconfig_cache: &tsconfig_cache,
205 canonicalize_cache: &canonicalize_cache,
206 };
207
208 let resolved_outputs: Vec<ResolvedModuleOutput> = input
209 .modules
210 .par_iter()
211 .filter_map(|module| {
212 resolve_module_imports(module, &ctx, &file_paths, &canonical_paths, input.files)
213 })
214 .collect();
215 let mut resolved = Vec::with_capacity(resolved_outputs.len());
216 let mut vitest_mock_operations = Vec::new();
217 for output in resolved_outputs {
218 resolved.push(output.module);
219 vitest_mock_operations.extend(output.vitest_mock_operations);
220 }
221
222 apply_specifier_upgrades(&mut resolved, &mut vitest_mock_operations);
223
224 synthesize_platform_family_edges(&mut resolved, input.files, input.active_plugins);
225
226 synthesize_auto_import_edges(
227 &mut resolved,
228 input.modules,
229 input.auto_imports,
230 &path_to_id,
231 &raw_path_to_id,
232 );
233
234 let replaced_module_targets = final_replaced_module_targets(vitest_mock_operations);
235
236 ResolvedProject {
237 modules: resolved,
238 replaced_module_targets,
239 }
240}
241
242fn build_workspace_roots<'a>(
243 workspaces: &'a [fallow_config::WorkspaceInfo],
244 canonical_ws_roots: &'a [PathBuf],
245) -> FxHashMap<&'a str, &'a Path> {
246 workspaces
247 .iter()
248 .zip(canonical_ws_roots.iter())
249 .map(|(ws, canonical)| (ws.name.as_str(), canonical.as_path()))
250 .collect()
251}
252
253fn build_canonical_file_paths(files: &[DiscoveredFile], root_is_canonical: bool) -> Vec<PathBuf> {
254 if root_is_canonical {
255 return Vec::new();
256 }
257
258 files
259 .par_iter()
260 .map(|f| dunce::canonicalize(&f.path).unwrap_or_else(|_| f.path.clone()))
261 .collect()
262}
263
264fn build_package_manifests(
271 input: &ResolveAllImportsInput<'_>,
272 canonical_ws_roots: &[PathBuf],
273) -> Vec<PackageManifestInfo> {
274 let root_canonical =
275 dunce::canonicalize(input.root).unwrap_or_else(|_| input.root.to_path_buf());
276 let root_probe = fallow_config::probe_dir_manifest(input.root);
277 let root_import_map = merge_deno_import_maps(&[], input.root, root_probe.deno_import_map);
278 let mut package_manifests = Vec::new();
279 if let Ok(Some((_name, package_json, _deps))) = root_probe.manifest {
280 package_manifests.push(PackageManifestInfo {
281 root: input.root.to_path_buf(),
282 canonical_root: root_canonical,
283 name: package_json.name.clone(),
284 package_json,
285 deno_import_map: root_import_map.clone(),
286 });
287 }
288 for (ws, canonical_root) in input.workspaces.iter().zip(canonical_ws_roots.iter()) {
289 let ws_probe = fallow_config::probe_dir_manifest(&ws.root);
290 if let Ok(Some((_name, package_json, _deps))) = ws_probe.manifest {
291 package_manifests.push(PackageManifestInfo {
292 root: ws.root.clone(),
293 canonical_root: canonical_root.clone(),
294 name: package_json.name.clone().or_else(|| Some(ws.name.clone())),
295 package_json,
296 deno_import_map: merge_deno_import_maps(
297 &root_import_map,
298 &ws.root,
299 ws_probe.deno_import_map,
300 ),
301 });
302 }
303 }
304 package_manifests
305}
306
307fn merge_deno_import_maps(
313 inherited: &[DenoImportMapEntry],
314 package_root: &Path,
315 local: Option<(PathBuf, Vec<(String, String)>)>,
316) -> Vec<DenoImportMapEntry> {
317 let mut entries: FxHashMap<String, DenoImportMapEntry> = inherited
318 .iter()
319 .cloned()
320 .map(|entry| (entry.key.clone(), entry))
321 .collect();
322
323 if let Some((config_path, local_entries)) = local {
324 let declaring_dir = config_path.parent().unwrap_or(package_root).to_path_buf();
325 for (key, target) in local_entries {
326 entries.insert(
327 key.clone(),
328 DenoImportMapEntry {
329 key,
330 target,
331 declaring_dir: declaring_dir.clone(),
332 },
333 );
334 }
335 }
336
337 let mut entries: Vec<_> = entries.into_values().collect();
338 entries.sort_by(|a, b| a.key.cmp(&b.key));
339 entries
340}
341
342fn build_path_to_id<'a>(
345 files: &'a [DiscoveredFile],
346 canonical_paths: &'a [PathBuf],
347 root_is_canonical: bool,
348) -> FxHashMap<&'a Path, FileId> {
349 if root_is_canonical {
350 files.iter().map(|f| (f.path.as_path(), f.id)).collect()
351 } else {
352 canonical_paths
353 .iter()
354 .enumerate()
355 .map(|(idx, canonical)| (canonical.as_path(), files[idx].id))
356 .collect()
357 }
358}
359
360fn resolve_module_imports(
361 module: &ModuleInfo,
362 ctx: &ResolveContext<'_>,
363 file_paths: &[&Path],
364 canonical_paths: &[PathBuf],
365 files: &[DiscoveredFile],
366) -> Option<ResolvedModuleOutput> {
367 let Some(file_path) = file_paths.get(module.file_id.0 as usize) else {
368 tracing::warn!(
369 file_id = module.file_id.0,
370 "Skipping module with unknown file_id during resolution"
371 );
372 return None;
373 };
374
375 let mut all_imports = resolve_static_imports(ctx, file_path, &module.imports);
376 all_imports.extend(resolve_require_imports(
377 ctx,
378 file_path,
379 &module.require_calls,
380 ));
381
382 let from_dir = if canonical_paths.is_empty() {
383 file_path.parent().unwrap_or(file_path)
384 } else {
385 canonical_paths
386 .get(module.file_id.0 as usize)
387 .and_then(|p| p.parent())
388 .unwrap_or(file_path)
389 };
390
391 let vitest_mock_operations =
392 resolve_vitest_mock_operations(module.file_id, &module.semantic_facts, ctx, file_path);
393 let module = build_resolved_module(ResolvedModuleBuildInput {
394 module,
395 ctx,
396 file_path,
397 from_dir,
398 canonical_paths,
399 files,
400 all_imports,
401 });
402
403 Some(ResolvedModuleOutput {
404 module,
405 vitest_mock_operations,
406 })
407}
408
409struct ResolvedModuleOutput {
410 module: ResolvedModule,
411 vitest_mock_operations: Vec<ResolvedVitestMockOperation>,
412}
413
414fn resolve_vitest_mock_operations(
415 source_file: FileId,
416 semantic_facts: &[SemanticFact],
417 ctx: &ResolveContext<'_>,
418 file_path: &Path,
419) -> Vec<ResolvedVitestMockOperation> {
420 let mut operations: Vec<_> = semantic_facts
421 .iter()
422 .filter_map(|fact| {
423 let SemanticFact::VitestModuleMockOperation(operation) = fact else {
424 return None;
425 };
426 Some(ResolvedVitestMockOperation {
427 source_file,
428 source_specifier: operation.source.clone(),
429 call_start: operation.call_start,
430 action: operation.action,
431 target: specifier::resolve_specifier(ctx, file_path, &operation.source, false),
432 })
433 })
434 .collect();
435 operations.sort_unstable_by(|left, right| {
436 left.call_start
437 .cmp(&right.call_start)
438 .then_with(|| left.source_specifier.cmp(&right.source_specifier))
439 });
440 operations
441}
442
443fn final_replaced_module_targets(
444 mut operations: Vec<ResolvedVitestMockOperation>,
445) -> Vec<ResolvedReplacedModuleTarget> {
446 operations.sort_unstable_by(|left, right| {
447 left.source_file
448 .0
449 .cmp(&right.source_file.0)
450 .then_with(|| left.call_start.cmp(&right.call_start))
451 .then_with(|| left.source_specifier.cmp(&right.source_specifier))
452 });
453
454 let mut final_operations = FxHashMap::default();
455 for operation in operations {
456 let Some(target_file) = operation.target.internal_file_id() else {
457 continue;
458 };
459 final_operations.insert((operation.source_file, target_file), operation.action);
460 }
461
462 let mut targets: Vec<_> = final_operations
463 .into_iter()
464 .filter_map(|((source_file, target_file), action)| {
465 action
466 .replaces_original()
467 .then_some(ResolvedReplacedModuleTarget {
468 source_file,
469 target_file,
470 })
471 })
472 .collect();
473 targets.sort_unstable_by_key(|target| (target.source_file.0, target.target_file.0));
474 targets
475}
476
477struct ResolvedModuleBuildInput<'a> {
478 module: &'a ModuleInfo,
479 ctx: &'a ResolveContext<'a>,
480 file_path: &'a Path,
481 from_dir: &'a Path,
482 canonical_paths: &'a [PathBuf],
483 files: &'a [DiscoveredFile],
484 all_imports: Vec<types::ResolvedImport>,
485}
486
487fn build_resolved_module(input: ResolvedModuleBuildInput<'_>) -> ResolvedModule {
488 ResolvedModule {
489 file_id: input.module.file_id,
490 path: input.file_path.to_path_buf(),
491 exports: input.module.exports.clone(),
492 re_exports: resolve_re_exports(input.ctx, input.file_path, &input.module.re_exports),
493 resolved_imports: input.all_imports,
494 resolved_dynamic_imports: resolve_dynamic_imports(
495 input.ctx,
496 input.file_path,
497 &input.module.dynamic_imports,
498 ),
499 resolved_dynamic_patterns: resolve_dynamic_patterns(
500 input.from_dir,
501 &input.module.dynamic_import_patterns,
502 input.canonical_paths,
503 input.files,
504 ),
505 member_accesses: input.module.member_accesses.clone(),
506 semantic_facts: input.module.semantic_facts.clone(),
507 whole_object_uses: input.module.whole_object_uses.clone(),
508 has_cjs_exports: input.module.has_cjs_exports,
509 has_angular_component_template_url: input.module.has_angular_component_template_url,
510 unused_import_bindings: input
511 .module
512 .unused_import_bindings
513 .iter()
514 .cloned()
515 .collect(),
516 type_referenced_import_bindings: input.module.type_referenced_import_bindings.clone(),
517 value_referenced_import_bindings: input.module.value_referenced_import_bindings.clone(),
518 namespace_object_aliases: input.module.namespace_object_aliases.clone(),
519 exported_factory_returns: input.module.exported_factory_returns.clone(),
520 exported_factory_return_object_shapes: input
521 .module
522 .exported_factory_return_object_shapes
523 .clone(),
524 type_member_types: input.module.type_member_types.clone(),
525 }
526}
527
528fn synthesize_auto_import_edges(
536 resolved: &mut [ResolvedModule],
537 modules: &[ModuleInfo],
538 auto_imports: &[AutoImportRule],
539 path_to_id: &FxHashMap<&Path, FileId>,
540 raw_path_to_id: &FxHashMap<&Path, FileId>,
541) {
542 if auto_imports.is_empty() {
543 return;
544 }
545
546 let mut table: FxHashMap<&str, Vec<(FileId, AutoImportKind)>> = FxHashMap::default();
547 for rule in auto_imports {
548 let source = rule.source.as_path();
549 let Some(file_id) = raw_path_to_id
550 .get(source)
551 .or_else(|| path_to_id.get(source))
552 .copied()
553 else {
554 continue;
555 };
556 table
557 .entry(rule.name.as_str())
558 .or_default()
559 .push((file_id, rule.kind));
560 }
561 if table.is_empty() {
562 return;
563 }
564
565 let candidates: FxHashMap<FileId, &[String]> = modules
566 .iter()
567 .filter(|module| !module.auto_import_candidates.is_empty())
568 .map(|module| (module.file_id, module.auto_import_candidates.as_slice()))
569 .collect();
570 if candidates.is_empty() {
571 return;
572 }
573
574 for module in resolved.iter_mut() {
575 let Some(names) = candidates.get(&module.file_id) else {
576 continue;
577 };
578 for name in *names {
579 if is_auto_import_builtin(name) {
580 continue;
581 }
582 let Some(targets) = table.get(name.as_str()) else {
583 continue;
584 };
585 for (target_id, kind) in targets {
586 if *target_id == module.file_id {
587 continue;
588 }
589 module.resolved_imports.push(ResolvedImport {
590 info: synthetic_auto_import_info(name, *kind),
591 target: ResolveResult::SyntheticAutoImport(*target_id),
592 });
593 }
594 }
595 }
596}
597
598fn is_auto_import_builtin(name: &str) -> bool {
599 is_js_auto_import_builtin(name)
600 || is_vue_auto_import_builtin(name)
601 || is_nuxt_auto_import_builtin(name)
602}
603
604fn is_js_auto_import_builtin(name: &str) -> bool {
605 matches!(
606 name,
607 "AbortController"
608 | "AbortSignal"
609 | "Array"
610 | "ArrayBuffer"
611 | "BigInt"
612 | "Blob"
613 | "Boolean"
614 | "Buffer"
615 | "CSS"
616 | "DOMParser"
617 | "Date"
618 | "Document"
619 | "Error"
620 | "Event"
621 | "EventTarget"
622 | "File"
623 | "FormData"
624 | "Intl"
625 | "JSON"
626 | "Map"
627 | "Math"
628 | "Number"
629 | "Object"
630 | "Promise"
631 | "Reflect"
632 | "RegExp"
633 | "Response"
634 | "Set"
635 | "String"
636 | "Symbol"
637 | "URL"
638 | "URLSearchParams"
639 | "WeakMap"
640 | "WeakSet"
641 | "Window"
642 | "alert"
643 | "clearInterval"
644 | "clearTimeout"
645 | "console"
646 | "document"
647 | "fetch"
648 | "global"
649 | "globalThis"
650 | "localStorage"
651 | "navigator"
652 | "process"
653 | "requestAnimationFrame"
654 | "sessionStorage"
655 | "setInterval"
656 | "setTimeout"
657 | "window"
658 )
659}
660
661fn is_vue_auto_import_builtin(name: &str) -> bool {
662 matches!(name, |"computed"| "customRef"
663 | "defineAsyncComponent"
664 | "defineComponent"
665 | "effectScope"
666 | "getCurrentInstance"
667 | "h"
668 | "inject"
669 | "isProxy"
670 | "isReactive"
671 | "isReadonly"
672 | "isRef"
673 | "markRaw"
674 | "nextTick"
675 | "onActivated"
676 | "onBeforeMount"
677 | "onBeforeUnmount"
678 | "onBeforeUpdate"
679 | "onDeactivated"
680 | "onErrorCaptured"
681 | "onMounted"
682 | "onRenderTracked"
683 | "onRenderTriggered"
684 | "onScopeDispose"
685 | "onServerPrefetch"
686 | "onUnmounted"
687 | "onUpdated"
688 | "provide"
689 | "reactive"
690 | "readonly"
691 | "ref"
692 | "resolveComponent"
693 | "shallowReactive"
694 | "shallowReadonly"
695 | "shallowRef"
696 | "toRaw"
697 | "toRef"
698 | "toRefs"
699 | "triggerRef"
700 | "unref"
701 | "watch"
702 | "watchEffect"
703 | "watchPostEffect"
704 | "watchSyncEffect")
705}
706
707fn is_nuxt_auto_import_builtin(name: &str) -> bool {
708 matches!(name, |"useAsyncData"| "useCookie"
709 | "useError"
710 | "useFetch"
711 | "useHead"
712 | "useLazyAsyncData"
713 | "useLazyFetch"
714 | "useNuxtApp"
715 | "useRequestEvent"
716 | "useRequestHeaders"
717 | "useRoute"
718 | "useRouter"
719 | "useRuntimeConfig"
720 | "useSeoMeta"
721 | "useState")
722}
723
724fn synthetic_auto_import_info(name: &str, kind: AutoImportKind) -> ImportInfo {
727 let imported_name = match kind {
728 AutoImportKind::Named => ImportedName::Named(name.to_string()),
729 AutoImportKind::Default | AutoImportKind::DefaultComponent => ImportedName::Default,
730 };
731 ImportInfo {
732 source: format!("<auto-import:{name}>"),
733 imported_name,
734 local_name: name.to_string(),
735 is_type_only: false,
736 from_style: false,
737 span: Span::default(),
738 source_span: Span::default(),
739 }
740}