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