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