Skip to main content

fallow_graph/resolve/
mod.rs

1//! Import specifier resolution using `oxc_resolver`.
2//!
3//! Orchestrates the resolution pipeline: for every extracted module, resolves all
4//! import specifiers in parallel (via rayon) to an [`ResolveResult`], internal file,
5//! npm package, external file, or unresolvable. The entry point is [`resolve_all_imports`].
6//!
7//! Resolution is split into submodules by import kind:
8//! - `static_imports`: ES `import` declarations
9//! - `dynamic_imports`: `import()` expressions and glob-based dynamic patterns
10//! - `require_imports`: CommonJS `require()` calls
11//! - `re_exports`: `export { x } from './y'` re-export sources
12//! - `upgrades`: post-resolution pass fixing non-deterministic bare specifier results
13//!
14//! Handles tsconfig path aliases (auto-discovered per file), pnpm virtual store paths,
15//! React Native platform extensions, and package.json `exports` subpath resolution with
16//! output-to-source directory fallback.
17
18mod auto_imports;
19mod base_url_directory;
20mod dynamic_imports;
21mod extension_alias;
22pub(crate) mod fallbacks;
23mod file_attempt;
24mod inline_loaders;
25mod jsx_runtime;
26mod memo;
27mod output_entry;
28mod package_credit;
29mod package_import_conditions;
30mod path_info;
31mod project_root;
32mod re_exports;
33mod react_native;
34mod require_imports;
35mod root_relative;
36mod specifier;
37mod static_imports;
38#[cfg(test)]
39mod tests;
40mod tsconfig_scope;
41mod types;
42mod upgrades;
43mod url_suffix;
44mod work;
45mod workspace_alias;
46
47pub use auto_imports::{UnreadableAutoImportRead, unreadable_auto_import_reads};
48pub use fallbacks::extract_package_name_from_node_modules_path;
49pub use inline_loaders::InlineLoaderRequest;
50pub use output_entry::{directory_index_entry, output_entry_to_source_path};
51pub use path_info::{
52    extract_package_name, is_bare_specifier, is_path_alias, is_valid_package_name,
53    normalize_npm_specifier,
54};
55pub use react_native::{PlatformFamilyKey, has_react_native_plugin, platform_family_key};
56pub use types::{
57    MISSING_ONLY_OUTPUT_DIRS, MissingExportTarget, OUTPUT_DIRS, ResolveResult, ResolvedImport,
58    ResolvedModule, ResolvedProject, ResolvedReExport, ResolvedReplacedModuleTarget,
59    ResolvedSourceEdge, ScopedPathAlias,
60};
61pub use work::ResolveWork;
62
63use std::sync::Arc;
64
65use std::path::{Path, PathBuf};
66use std::sync::Mutex;
67
68use rayon::prelude::*;
69use rustc_hash::{FxHashMap, FxHashSet};
70
71use fallow_config::{AutoImportKind, AutoImportRule, JsxImportSourceRule};
72use fallow_types::discover::{DiscoveredFile, FileId};
73use fallow_types::extract::{ImportInfo, ImportedName, ModuleInfo, SemanticFact};
74use oxc_span::Span;
75
76use auto_imports::synthesize_auto_import_edges;
77use dynamic_imports::{GlobMatcherCache, resolve_dynamic_imports, resolve_dynamic_patterns};
78use jsx_runtime::resolve_config_jsx_runtime_imports;
79pub use jsx_runtime::{CompiledJsxRule, compile_jsx_rules};
80use package_import_conditions::synthesize_package_import_condition_edges;
81use re_exports::resolve_re_exports;
82use react_native::{build_condition_names, build_extensions, synthesize_platform_family_edges};
83use require_imports::resolve_require_imports;
84use specifier::{build_resolve_options, create_resolver};
85use static_imports::resolve_static_imports;
86use types::{DenoImportMapEntry, PackageManifestInfo, ResolveContext};
87use upgrades::{ResolvedVitestMockOperation, apply_specifier_upgrades};
88
89/// Inputs used to resolve imports for a complete extracted project.
90pub struct ResolveAllImportsInput<'a> {
91    /// Extracted modules whose imports should be resolved.
92    pub modules: &'a [ModuleInfo],
93    /// Discovered source files indexed by [`FileId`].
94    pub files: &'a [DiscoveredFile],
95    /// Workspace package roots used for package self-resolution.
96    pub workspaces: &'a [fallow_config::WorkspaceInfo],
97    /// Active plugin names that affect extensions and resolver conditions.
98    pub active_plugins: &'a [String],
99    /// Configured TypeScript path alias pairs.
100    pub path_aliases: &'a [(String, String)],
101    /// Plugin path aliases that apply only to the files of one workspace.
102    pub scoped_path_aliases: &'a [ScopedPathAlias],
103    /// Auto-import rules that synthesize implicit graph edges.
104    pub auto_imports: &'a [AutoImportRule],
105    /// JSX import sources from bundler and test configs. Each adds a runtime
106    /// edge to the matching modules that have JSX and no runtime pragma.
107    pub jsx_import_sources: &'a [JsxImportSourceRule],
108    /// Additional Sass and SCSS include directories.
109    pub scss_include_paths: &'a [PathBuf],
110    /// Static directory mappings for framework-specific asset resolution.
111    pub static_dir_mappings: &'a [(PathBuf, String)],
112    /// Mounts a framework serves for the whole project; see `ResolveContext`.
113    pub framework_static_dir_mappings: &'a [(PathBuf, String)],
114    /// Project root used for package manifest and relative-path resolution.
115    pub root: &'a Path,
116    /// Extra resolver conditions supplied by configuration.
117    pub extra_conditions: &'a [String],
118}
119
120/// Reusable per-project resolver state: the resolver instances, package
121/// manifests, and workspace canonicalization that do not depend on the specific
122/// modules being resolved.
123///
124/// Building these is the bulk of `resolve_all_imports`'s non-parallel setup cost
125/// (workspace `dunce::canonicalize`, root + workspace `package.json` loads, and
126/// resolver construction). A caller that resolves many small inputs against the
127/// same project (the external-stylesheet scanner resolves dozens of node_modules
128/// stylesheets one file at a time) builds a session once and reuses it across
129/// every resolution instead of rebuilding this state per call.
130pub struct ResolverSession {
131    resolver: crate::read_trace::Resolver,
132    script_resolver: crate::read_trace::Resolver,
133    style_resolver: crate::read_trace::Resolver,
134    extensions: Vec<String>,
135    condition_names: Vec<String>,
136    package_manifests: Vec<PackageManifestInfo>,
137    has_deno_import_maps: bool,
138    canonical_ws_roots: Vec<PathBuf>,
139    root_is_canonical: bool,
140}
141
142impl ResolverSession {
143    /// Build the reusable resolver state for `input`'s project context (root,
144    /// workspaces, active plugins, and resolver conditions).
145    ///
146    /// The session is valid for any later [`resolve_all_imports_with_session`]
147    /// call whose input shares that project context; in particular the
148    /// `workspaces` slice must be the same (same entries and order) so workspace
149    /// names line up with the cached `canonical_ws_roots`.
150    #[must_use]
151    pub fn new(input: &ResolveAllImportsInput<'_>) -> Self {
152        let canonical_ws_roots: Vec<PathBuf> = input
153            .workspaces
154            .par_iter()
155            .map(|ws| crate::read_trace::canonicalize(&ws.root).unwrap_or_else(|_| ws.root.clone()))
156            .collect();
157        let package_manifests = build_package_manifests(input, &canonical_ws_roots);
158        let has_deno_import_maps = package_manifests
159            .iter()
160            .any(|manifest| !manifest.deno_import_map.is_empty());
161        let root_is_canonical =
162            crate::read_trace::canonicalize(input.root).is_ok_and(|c| c == input.root);
163
164        let extensions = build_extensions(input.active_plugins);
165        let condition_names = build_condition_names(input.active_plugins, input.extra_conditions);
166        let resolver = create_resolver(input.root, input.active_plugins, input.extra_conditions);
167        let script_resolver = specifier::create_script_resolver(&resolver);
168        let mut style_conditions = input.extra_conditions.to_vec();
169        style_conditions.push("sass".to_string());
170        style_conditions.push("style".to_string());
171        // Derived from the main resolver so both share one filesystem cache and,
172        // on Yarn PnP projects, one parsed manifest.
173        let style_resolver = resolver.clone_with_options(build_resolve_options(
174            input.root,
175            input.active_plugins,
176            &style_conditions,
177        ));
178
179        Self {
180            resolver,
181            script_resolver,
182            style_resolver,
183            extensions,
184            condition_names,
185            package_manifests,
186            has_deno_import_maps,
187            canonical_ws_roots,
188            root_is_canonical,
189        }
190    }
191}
192
193/// Resolve all imports across all modules in parallel.
194#[must_use]
195pub fn resolve_all_imports(input: &ResolveAllImportsInput<'_>) -> ResolvedProject {
196    let session = ResolverSession::new(input);
197    resolve_all_imports_with_session(input, &session)
198}
199
200/// Resolve all imports for `input`, reusing a prebuilt [`ResolverSession`].
201///
202/// This is the single resolution code path; [`resolve_all_imports`] is the
203/// convenience wrapper that builds a fresh session first. `session` MUST have
204/// been built from an input with the same project context as `input` (same
205/// `root`, `workspaces` slice and order, `active_plugins`, and
206/// `extra_conditions`); only `modules` and `files` may differ.
207#[must_use]
208pub fn resolve_all_imports_with_session(
209    input: &ResolveAllImportsInput<'_>,
210    session: &ResolverSession,
211) -> ResolvedProject {
212    // `ResolverSession::new` reads only the root, the workspace roots and
213    // their manifests, which the graph cache key covers by name.
214    let missed_probes = crate::missed_probes::MissRecorder::start(input.root);
215    let root_is_canonical = session.root_is_canonical;
216    let workspace_roots = build_workspace_roots(input.workspaces, &session.canonical_ws_roots);
217    let canonical_paths = build_canonical_file_paths(input.files, root_is_canonical);
218    let mut work = ResolveWork {
219        canonicalize_calls: canonical_paths.len() as u64,
220        ..ResolveWork::default()
221    };
222    let path_to_id = build_path_to_id(input.files, &canonical_paths, root_is_canonical);
223    let raw_path_to_id: FxHashMap<&Path, FileId> = input
224        .files
225        .iter()
226        .map(|f| (f.path.as_path(), f.id))
227        .collect();
228
229    let file_paths: Vec<&Path> = input.files.iter().map(|f| f.path.as_path()).collect();
230
231    let canonical_fallback = if root_is_canonical {
232        Some(types::CanonicalFallback::new(input.files))
233    } else {
234        None
235    };
236
237    let tsconfig_warned: Mutex<FxHashSet<String>> = Mutex::new(FxHashSet::default());
238    let tsconfig_cache = types::TsconfigCache::default();
239    let canonicalize_cache = types::CanonicalizeCache::default();
240    let glob_matcher_cache = GlobMatcherCache::with_module_extensions(&session.extensions);
241    // Dynamic import patterns match against canonical file paths when the
242    // root is not canonical, so their root containment check needs the
243    // canonical root too.
244    let pattern_root = if canonical_paths.is_empty() {
245        input.root.to_path_buf()
246    } else {
247        crate::read_trace::canonicalize(input.root).unwrap_or_else(|_| input.root.to_path_buf())
248    };
249    let jsx_rules = compile_jsx_rules(input.jsx_import_sources);
250
251    let ctx = ResolveContext {
252        resolver: &session.resolver,
253        script_resolver: &session.script_resolver,
254        style_resolver: &session.style_resolver,
255        extensions: &session.extensions,
256        path_to_id: &path_to_id,
257        raw_path_to_id: &raw_path_to_id,
258        workspace_roots: &workspace_roots,
259        package_manifests: &session.package_manifests,
260        has_deno_import_maps: session.has_deno_import_maps,
261        condition_names: &session.condition_names,
262        path_aliases: input.path_aliases,
263        scoped_path_aliases: input.scoped_path_aliases,
264        scss_include_paths: input.scss_include_paths,
265        static_dir_mappings: input.static_dir_mappings,
266        framework_static_dir_mappings: input.framework_static_dir_mappings,
267        root: input.root,
268        canonical_fallback: canonical_fallback.as_ref(),
269        tsconfig_warned: &tsconfig_warned,
270        tsconfig_cache: &tsconfig_cache,
271        canonicalize_cache: &canonicalize_cache,
272    };
273
274    let resolved_outputs: Vec<ResolvedModuleOutput> = input
275        .modules
276        .par_iter()
277        .filter_map(|module| {
278            resolve_module_imports(
279                module,
280                &ctx,
281                &ProjectResolveRules {
282                    glob_matcher_cache: &glob_matcher_cache,
283                    pattern_root: &pattern_root,
284                    jsx_rules: &jsx_rules,
285                },
286                &file_paths,
287                &canonical_paths,
288                input.files,
289            )
290        })
291        .collect();
292    let mut resolved = Vec::with_capacity(resolved_outputs.len());
293    let mut vitest_mock_operations = Vec::new();
294    for output in resolved_outputs {
295        resolved.push(output.module);
296        vitest_mock_operations.extend(output.vitest_mock_operations);
297        work += output.work;
298    }
299    work.canonicalize_calls += canonicalize_cache.distinct_paths() as u64;
300
301    apply_specifier_upgrades(&mut resolved, &mut vitest_mock_operations);
302
303    synthesize_platform_family_edges(&mut resolved, input.files, input.active_plugins);
304
305    synthesize_package_import_condition_edges(&mut resolved, &ctx);
306
307    synthesize_auto_import_edges(
308        &mut resolved,
309        input.modules,
310        input.auto_imports,
311        &path_to_id,
312        &raw_path_to_id,
313    );
314
315    let replaced_module_targets = final_replaced_module_targets(vitest_mock_operations);
316    let probes = missed_probes.finish();
317
318    ResolvedProject {
319        modules: resolved,
320        replaced_module_targets,
321        work,
322        missed_probes: probes.missed,
323        package_manifests: probes.package_manifests,
324    }
325}
326
327fn build_workspace_roots<'a>(
328    workspaces: &'a [fallow_config::WorkspaceInfo],
329    canonical_ws_roots: &'a [PathBuf],
330) -> FxHashMap<&'a str, &'a Path> {
331    workspaces
332        .iter()
333        .zip(canonical_ws_roots.iter())
334        .map(|(ws, canonical)| (ws.name.as_str(), canonical.as_path()))
335        .collect()
336}
337
338fn build_canonical_file_paths(files: &[DiscoveredFile], root_is_canonical: bool) -> Vec<PathBuf> {
339    if root_is_canonical {
340        return Vec::new();
341    }
342
343    files
344        .par_iter()
345        .map(|f| crate::read_trace::canonicalize(&f.path).unwrap_or_else(|_| f.path.clone()))
346        .collect()
347}
348
349/// Load the root package manifest plus each workspace manifest into the
350/// `PackageManifestInfo` list used for `exports` / `imports` resolution.
351///
352/// Manifests come from `package.json` when present, otherwise `deno.json` /
353/// `deno.jsonc` (`name` + `exports`), so pure Deno workspaces resolve without
354/// npm bridge files.
355fn build_package_manifests(
356    input: &ResolveAllImportsInput<'_>,
357    canonical_ws_roots: &[PathBuf],
358) -> Vec<PackageManifestInfo> {
359    let root_canonical =
360        crate::read_trace::canonicalize(input.root).unwrap_or_else(|_| input.root.to_path_buf());
361    let root_probe = fallow_config::probe_dir_manifest(input.root);
362    let root_import_map = merge_deno_import_maps(&[], input.root, root_probe.deno_import_map);
363    let mut package_manifests = Vec::new();
364    if let Ok(Some((_name, package_json, _deps))) = root_probe.manifest {
365        package_manifests.push(PackageManifestInfo {
366            root: input.root.to_path_buf(),
367            canonical_root: root_canonical,
368            name: package_json.name.clone(),
369            package_json,
370            deno_import_map: root_import_map.clone(),
371        });
372    }
373    for (ws, canonical_root) in input.workspaces.iter().zip(canonical_ws_roots.iter()) {
374        let ws_probe = fallow_config::probe_dir_manifest(&ws.root);
375        if let Ok(Some((_name, package_json, _deps))) = ws_probe.manifest {
376            package_manifests.push(PackageManifestInfo {
377                root: ws.root.clone(),
378                canonical_root: canonical_root.clone(),
379                name: package_json.name.clone().or_else(|| Some(ws.name.clone())),
380                package_json,
381                deno_import_map: merge_deno_import_maps(
382                    &root_import_map,
383                    &ws.root,
384                    ws_probe.deno_import_map,
385                ),
386            });
387        }
388    }
389    package_manifests
390}
391
392/// Merge inherited and package-local Deno import maps once per resolver
393/// session. Equal local keys replace inherited keys while retaining the
394/// declaring directory needed for relative target resolution. The local map
395/// comes from the caller's single-probe manifest load so the Deno config is
396/// not read and parsed a second time.
397fn merge_deno_import_maps(
398    inherited: &[DenoImportMapEntry],
399    package_root: &Path,
400    local: Option<(PathBuf, Vec<(String, String)>)>,
401) -> Vec<DenoImportMapEntry> {
402    let mut entries: FxHashMap<String, DenoImportMapEntry> = inherited
403        .iter()
404        .cloned()
405        .map(|entry| (entry.key.clone(), entry))
406        .collect();
407
408    if let Some((config_path, local_entries)) = local {
409        let declaring_dir = config_path.parent().unwrap_or(package_root).to_path_buf();
410        for (key, target) in local_entries {
411            entries.insert(
412                key.clone(),
413                DenoImportMapEntry {
414                    key,
415                    target,
416                    declaring_dir: declaring_dir.clone(),
417                },
418            );
419        }
420    }
421
422    let mut entries: Vec<_> = entries.into_values().collect();
423    entries.sort_by(|a, b| a.key.cmp(&b.key));
424    entries
425}
426
427/// Build the path-to-`FileId` index, keyed by canonical paths when the root is
428/// not already canonical and by raw paths otherwise.
429fn build_path_to_id<'a>(
430    files: &'a [DiscoveredFile],
431    canonical_paths: &'a [PathBuf],
432    root_is_canonical: bool,
433) -> FxHashMap<&'a Path, FileId> {
434    if root_is_canonical {
435        files.iter().map(|f| (f.path.as_path(), f.id)).collect()
436    } else {
437        canonical_paths
438            .iter()
439            .enumerate()
440            .map(|(idx, canonical)| (canonical.as_path(), files[idx].id))
441            .collect()
442    }
443}
444
445/// Per-run state that every module resolution reads.
446struct ProjectResolveRules<'a> {
447    glob_matcher_cache: &'a GlobMatcherCache,
448    pattern_root: &'a Path,
449    jsx_rules: &'a [CompiledJsxRule<'a>],
450}
451
452fn resolve_module_imports(
453    module: &ModuleInfo,
454    ctx: &ResolveContext<'_>,
455    rules: &ProjectResolveRules<'_>,
456    file_paths: &[&Path],
457    canonical_paths: &[PathBuf],
458    files: &[DiscoveredFile],
459) -> Option<ResolvedModuleOutput> {
460    let Some(file_path) = file_paths.get(module.file_id.0 as usize) else {
461        tracing::warn!(
462            file_id = module.file_id.0,
463            "Skipping module with unknown file_id during resolution"
464        );
465        return None;
466    };
467
468    let resolve = || {
469        let mut all_imports = resolve_static_imports(ctx, file_path, &module.imports);
470        all_imports.extend(resolve_config_jsx_runtime_imports(
471            ctx,
472            file_path,
473            module,
474            rules.jsx_rules,
475        ));
476        all_imports.extend(resolve_require_imports(
477            ctx,
478            file_path,
479            &module.require_calls,
480        ));
481
482        let from_dir = if canonical_paths.is_empty() {
483            file_path.parent().unwrap_or(file_path)
484        } else {
485            canonical_paths
486                .get(module.file_id.0 as usize)
487                .and_then(|p| p.parent())
488                .unwrap_or(file_path)
489        };
490
491        let vitest_mock_operations =
492            resolve_vitest_mock_operations(module.file_id, &module.semantic_facts, ctx, file_path);
493        let module = build_resolved_module(ResolvedModuleBuildInput {
494            module,
495            ctx,
496            glob_matcher_cache: rules.glob_matcher_cache,
497            pattern_root: rules.pattern_root,
498            file_path,
499            from_dir,
500            canonical_paths,
501            files,
502            all_imports,
503        });
504        (module, vitest_mock_operations)
505    };
506    let ((module, vitest_mock_operations), work) =
507        memo::in_file_scope(file_path, || work::in_module_scope(resolve));
508
509    Some(ResolvedModuleOutput {
510        module,
511        vitest_mock_operations,
512        work,
513    })
514}
515
516struct ResolvedModuleOutput {
517    module: ResolvedModule,
518    vitest_mock_operations: Vec<ResolvedVitestMockOperation>,
519    work: ResolveWork,
520}
521
522fn resolve_vitest_mock_operations(
523    source_file: FileId,
524    semantic_facts: &[SemanticFact],
525    ctx: &ResolveContext<'_>,
526    file_path: &Path,
527) -> Vec<ResolvedVitestMockOperation> {
528    let mut operations: Vec<_> = semantic_facts
529        .iter()
530        .filter_map(|fact| {
531            let SemanticFact::VitestModuleMockOperation(operation) = fact else {
532                return None;
533            };
534            Some(ResolvedVitestMockOperation {
535                source_file,
536                source_specifier: operation.source.clone(),
537                call_start: operation.call_start,
538                action: operation.action,
539                target: specifier::resolve_import_specifier(
540                    ctx,
541                    file_path,
542                    &operation.source,
543                    false,
544                ),
545            })
546        })
547        .collect();
548    operations.sort_unstable_by(|left, right| {
549        left.call_start
550            .cmp(&right.call_start)
551            .then_with(|| left.source_specifier.cmp(&right.source_specifier))
552    });
553    operations
554}
555
556fn final_replaced_module_targets(
557    mut operations: Vec<ResolvedVitestMockOperation>,
558) -> Vec<ResolvedReplacedModuleTarget> {
559    operations.sort_unstable_by(|left, right| {
560        left.source_file
561            .0
562            .cmp(&right.source_file.0)
563            .then_with(|| left.call_start.cmp(&right.call_start))
564            .then_with(|| left.source_specifier.cmp(&right.source_specifier))
565    });
566
567    let mut final_operations = FxHashMap::default();
568    for operation in operations {
569        let Some(target_file) = operation.target.internal_file_id() else {
570            continue;
571        };
572        final_operations.insert((operation.source_file, target_file), operation.action);
573    }
574
575    let mut targets: Vec<_> = final_operations
576        .into_iter()
577        .filter_map(|((source_file, target_file), action)| {
578            action
579                .replaces_original()
580                .then_some(ResolvedReplacedModuleTarget {
581                    source_file,
582                    target_file,
583                })
584        })
585        .collect();
586    targets.sort_unstable_by_key(|target| (target.source_file.0, target.target_file.0));
587    targets
588}
589
590struct ResolvedModuleBuildInput<'a> {
591    module: &'a ModuleInfo,
592    ctx: &'a ResolveContext<'a>,
593    glob_matcher_cache: &'a GlobMatcherCache,
594    pattern_root: &'a Path,
595    file_path: &'a Path,
596    from_dir: &'a Path,
597    canonical_paths: &'a [PathBuf],
598    files: &'a [DiscoveredFile],
599    all_imports: Vec<types::ResolvedImport>,
600}
601
602fn build_resolved_module(input: ResolvedModuleBuildInput<'_>) -> ResolvedModule {
603    let ctx = input.ctx;
604    let mut module = resolved_module_without_export_hints(input);
605    module.missing_export_targets = collect_missing_export_targets(ctx, &module);
606    module
607}
608
609/// Record the missing target paths of each unresolved specifier once: the
610/// `exports` paths of a bare specifier, or else the paths that a matching
611/// path alias substitutes.
612fn collect_missing_export_targets(
613    ctx: &ResolveContext<'_>,
614    module: &ResolvedModule,
615) -> Vec<MissingExportTarget> {
616    let mut seen: FxHashSet<&str> = FxHashSet::default();
617    let mut targets: Vec<MissingExportTarget> = module
618        .all_resolved_source_edges()
619        .filter_map(|edge| match edge.target() {
620            ResolveResult::Unresolvable(specifier) => Some(specifier.as_str()),
621            _ => None,
622        })
623        .filter(|specifier| seen.insert(specifier))
624        .filter_map(|specifier| {
625            let aliased = workspace_alias::aliased_specifier(ctx, &module.path, specifier);
626            fallbacks::missing_package_export_paths(ctx, aliased.as_deref().unwrap_or(specifier))
627                .or_else(|| missing_alias_targets(ctx, &module.path, specifier))
628                .map(|paths| MissingExportTarget {
629                    specifier: specifier.to_string(),
630                    paths,
631                })
632        })
633        .collect();
634    targets.sort_unstable_by(|left, right| left.specifier.cmp(&right.specifier));
635    targets
636}
637
638/// The paths that the nearest tsconfig `paths` entry substitutes for an
639/// unresolved `specifier`, or else the paths that a plugin path alias
640/// substitutes. `None` when no alias matches.
641fn missing_alias_targets(
642    ctx: &ResolveContext<'_>,
643    from_file: &Path,
644    specifier: &str,
645) -> Option<Vec<PathBuf>> {
646    let tsconfig_targets =
647        package_credit::nearest_tsconfig_alias_targets(ctx, from_file, specifier);
648    if tsconfig_targets.is_empty() {
649        return fallbacks::missing_path_alias_targets(ctx, from_file, specifier);
650    }
651    Some(
652        tsconfig_targets
653            .iter()
654            .map(|target| fallbacks::normalize_path_lexically(target))
655            .collect(),
656    )
657}
658
659fn resolved_module_without_export_hints(input: ResolvedModuleBuildInput<'_>) -> ResolvedModule {
660    ResolvedModule {
661        file_id: input.module.file_id,
662        path: input.file_path.to_path_buf(),
663        exports: Arc::clone(&input.module.exports),
664        re_exports: resolve_re_exports(input.ctx, input.file_path, &input.module.re_exports),
665        resolved_imports: input.all_imports,
666        resolved_dynamic_imports: resolve_dynamic_imports(
667            input.ctx,
668            input.file_path,
669            &input.module.dynamic_imports,
670        ),
671        resolved_dynamic_patterns: resolve_dynamic_patterns(
672            input.glob_matcher_cache,
673            input.pattern_root,
674            input.from_dir,
675            &input.module.dynamic_import_patterns,
676            input.canonical_paths,
677            input.files,
678        ),
679        member_accesses: Arc::clone(&input.module.member_accesses),
680        semantic_facts: Arc::clone(&input.module.semantic_facts),
681        whole_object_uses: Arc::clone(&input.module.whole_object_uses),
682        has_cjs_exports: input.module.has_cjs_exports,
683        has_angular_component_template_url: input.module.has_angular_component_template_url,
684        unused_import_bindings: input
685            .module
686            .unused_import_bindings
687            .iter()
688            .cloned()
689            .collect(),
690        type_referenced_import_bindings: input.module.type_referenced_import_bindings.clone(),
691        value_referenced_import_bindings: input.module.value_referenced_import_bindings.clone(),
692        namespace_object_aliases: input.module.namespace_object_aliases.clone(),
693        exported_factory_returns: Arc::clone(&input.module.exported_factory_returns),
694        exported_factory_return_object_shapes: Arc::clone(
695            &input.module.exported_factory_return_object_shapes,
696        ),
697        type_member_types: Arc::clone(&input.module.type_member_types),
698        missing_export_targets: Vec::new(),
699    }
700}
701
702fn is_auto_import_builtin(name: &str) -> bool {
703    is_js_auto_import_builtin(name)
704        || is_vue_auto_import_builtin(name)
705        || is_nuxt_auto_import_builtin(name)
706}
707
708fn is_js_auto_import_builtin(name: &str) -> bool {
709    matches!(
710        name,
711        "AbortController"
712            | "AbortSignal"
713            | "Array"
714            | "ArrayBuffer"
715            | "BigInt"
716            | "Blob"
717            | "Boolean"
718            | "Buffer"
719            | "CSS"
720            | "DOMParser"
721            | "Date"
722            | "Document"
723            | "Error"
724            | "Event"
725            | "EventTarget"
726            | "File"
727            | "FormData"
728            | "Intl"
729            | "JSON"
730            | "Map"
731            | "Math"
732            | "Number"
733            | "Object"
734            | "Promise"
735            | "Reflect"
736            | "RegExp"
737            | "Response"
738            | "Set"
739            | "String"
740            | "Symbol"
741            | "URL"
742            | "URLSearchParams"
743            | "WeakMap"
744            | "WeakSet"
745            | "Window"
746            | "alert"
747            | "clearInterval"
748            | "clearTimeout"
749            | "console"
750            | "document"
751            | "fetch"
752            | "global"
753            | "globalThis"
754            | "localStorage"
755            | "navigator"
756            | "process"
757            | "requestAnimationFrame"
758            | "sessionStorage"
759            | "setInterval"
760            | "setTimeout"
761            | "window"
762    )
763}
764
765fn is_vue_auto_import_builtin(name: &str) -> bool {
766    matches!(name, |"computed"| "customRef"
767        | "defineAsyncComponent"
768        | "defineComponent"
769        | "effectScope"
770        | "getCurrentInstance"
771        | "h"
772        | "inject"
773        | "isProxy"
774        | "isReactive"
775        | "isReadonly"
776        | "isRef"
777        | "markRaw"
778        | "nextTick"
779        | "onActivated"
780        | "onBeforeMount"
781        | "onBeforeUnmount"
782        | "onBeforeUpdate"
783        | "onDeactivated"
784        | "onErrorCaptured"
785        | "onMounted"
786        | "onRenderTracked"
787        | "onRenderTriggered"
788        | "onScopeDispose"
789        | "onServerPrefetch"
790        | "onUnmounted"
791        | "onUpdated"
792        | "provide"
793        | "reactive"
794        | "readonly"
795        | "ref"
796        | "resolveComponent"
797        | "shallowReactive"
798        | "shallowReadonly"
799        | "shallowRef"
800        | "toRaw"
801        | "toRef"
802        | "toRefs"
803        | "triggerRef"
804        | "unref"
805        | "watch"
806        | "watchEffect"
807        | "watchPostEffect"
808        | "watchSyncEffect")
809}
810
811fn is_nuxt_auto_import_builtin(name: &str) -> bool {
812    matches!(name, |"useAsyncData"| "useCookie"
813        | "useError"
814        | "useFetch"
815        | "useHead"
816        | "useLazyAsyncData"
817        | "useLazyFetch"
818        | "useNuxtApp"
819        | "useRequestEvent"
820        | "useRequestHeaders"
821        | "useRoute"
822        | "useRouter"
823        | "useRuntimeConfig"
824        | "useSeoMeta"
825        | "useState")
826}
827
828/// Build a synthetic [`ImportInfo`] for a convention auto-import. Component and
829/// default kinds credit the default export; named kinds credit the named export.
830fn synthetic_auto_import_info(name: &str, kind: AutoImportKind) -> ImportInfo {
831    let imported_name = match kind {
832        AutoImportKind::Named => ImportedName::Named(name.to_string()),
833        AutoImportKind::Default | AutoImportKind::DefaultComponent => ImportedName::Default,
834    };
835    ImportInfo {
836        source: format!("<auto-import:{name}>"),
837        imported_name,
838        local_name: name.to_string(),
839        is_type_only: false,
840        is_type_only_star: false,
841        from_style: false,
842        span: Span::default(),
843        source_span: Span::default(),
844    }
845}