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