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