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