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