Skip to main content

turbopack_ecmascript/references/esm/
base.rs

1use anyhow::{Result, bail};
2use async_trait::async_trait;
3use bincode::{Decode, Encode};
4use either::Either;
5use rustc_hash::FxHashSet;
6use strsim::jaro;
7use swc_core::{
8    common::{
9        BytePos, DUMMY_SP, Span, SyntaxContext,
10        source_map::{PURE_SP, SmallPos},
11    },
12    ecma::ast::{
13        ComputedPropName, Decl, Expr, ExprStmt, Ident, Lit, MemberExpr, MemberProp, Number,
14        SeqExpr, Stmt, Str,
15    },
16    quote,
17};
18use turbo_rcstr::{RcStr, rcstr};
19use turbo_tasks::{
20    NonLocalValue, ResolvedVc, ValueToString, Vc, debug::ValueDebugFormat, turbobail,
21};
22use turbo_tasks_fs::FileSystemPath;
23use turbopack_core::{
24    chunk::{ChunkingContext, ChunkingType, ModuleChunkItemIdExt},
25    issue::{
26        Issue, IssueExt, IssueSeverity, IssueSource, IssueStage, StyledString,
27        code_gen::CodeGenerationIssue,
28    },
29    loader::{ResolvedWebpackLoaderItem, WebpackLoaderItem},
30    module::{Module, ModuleSideEffects},
31    module_graph::binding_usage_info::ModuleExportUsageInfo,
32    reference::ModuleReference,
33    reference_type::{EcmaScriptModulesReferenceSubType, ReferenceType},
34    resolve::{
35        BindingUsage, ExportUsage, ExternalType, ImportUsage, ModulePart, ModuleResolveResult,
36        ModuleResolveResultItem, RequestKey, ResolveErrorMode,
37        origin::{ResolveOrigin, ResolveOriginExt},
38        parse::Request,
39        resolve,
40    },
41    source::Source,
42};
43use turbopack_resolve::ecmascript::esm_resolve;
44
45use crate::{
46    EcmascriptModuleAsset, EcmascriptParsable, ScopeHoistingContext,
47    analyzer::imports::{ImportAnnotations, ImportedSymbol},
48    chunk::{EcmascriptChunkPlaceable, EcmascriptExports},
49    code_gen::{CodeGeneration, CodeGenerationHoistedStmt},
50    export::Liveness,
51    magic_identifier,
52    module_fragments::{TURBOPACK_PART_IMPORT_SOURCE, part::module::EcmascriptModulePartAsset},
53    parse::ParseResult,
54    references::{
55        esm::{
56            EsmExport,
57            export::{SubsumedImports, all_known_export_names, is_export_missing},
58            mangle::generated_export_key,
59        },
60        util::{SpecifiedChunkingType, throw_module_not_found_expr},
61    },
62    runtime_functions::{TURBOPACK_EXTERNAL_IMPORT, TURBOPACK_EXTERNAL_REQUIRE, TURBOPACK_IMPORT},
63    utils::module_id_to_lit,
64};
65
66#[derive(PartialEq, Eq)]
67pub enum ReferencedAsset {
68    Some(ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>),
69    External(RcStr, ExternalType),
70    /// The request resolved to a module that can't be placed in an ECMAScript
71    /// chunk (e.g. a stylesheet or a raw module), so it has no bindings to
72    /// import. Importing it for its side effects is fine, reading a binding off
73    /// it is not.
74    NonPlaceable(ResolvedVc<Box<dyn Module>>),
75    None,
76    /// The module was aliased to `false`, resolving to an empty module.
77    Empty,
78    Unresolvable,
79}
80
81#[derive(Clone, Debug)]
82pub enum ReferencedAssetIdent {
83    /// The given export (or namespace) is a local binding in the current scope hoisting group.
84    LocalBinding {
85        ident: RcStr,
86        ctxt: SyntaxContext,
87        liveness: Liveness,
88    },
89    /// The given export (or namespace) should be imported and accessed as `export` on the
90    /// `import_source.namespace_ident()` variable.
91    Module {
92        ctxt: Option<SyntaxContext>,
93        export: Option<RcStr>,
94        /// What to import to populate the variable that will hold the imported namespace.
95        ///
96        /// When the ident was resolved through a re-export chain (e.g. `export * as X from
97        /// './inner'`), this is the final module in that chain, not the directly referenced
98        /// asset.
99        import_source: ImportSource,
100    },
101}
102
103/// The source to import when initializing a `ReferencedAssetIdent::Module` variable.
104#[derive(Clone, Debug)]
105pub enum ImportSource {
106    /// Import an in-graph module.
107    Module {
108        asset: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>,
109        /// The name of the variable that should hold the imported namespace.
110        namespace_ident: String,
111    },
112    /// Import an external dependency. The emitting site decides between
113    /// `__turbopack_external_import` and `__turbopack_external_require` based on its own
114    /// `import_externals` flag.
115    External {
116        request: RcStr,
117        ty: ExternalType,
118        /// The name of the variable that should hold the imported namespace.
119        namespace_ident: String,
120    },
121}
122
123impl ImportSource {
124    async fn new_module(
125        asset: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>,
126        chunking_context: Vc<Box<dyn ChunkingContext>>,
127    ) -> Result<Self> {
128        Ok(ImportSource::Module {
129            asset,
130            namespace_ident: ReferencedAsset::get_ident_from_placeable(*asset, chunking_context)
131                .await?,
132        })
133    }
134
135    fn new_external(request: RcStr, ty: ExternalType) -> Self {
136        let namespace_ident = magic_identifier::mangle(&format!("{ty} external {request}"));
137        ImportSource::External {
138            request,
139            ty,
140            namespace_ident,
141        }
142    }
143
144    /// The name of the variable that should hold the imported namespace.
145    pub fn namespace_ident(&self) -> &str {
146        match self {
147            ImportSource::Module {
148                namespace_ident, ..
149            }
150            | ImportSource::External {
151                namespace_ident, ..
152            } => namespace_ident,
153        }
154    }
155
156    /// Like [`ImportSource::namespace_ident`], but takes ownership of the name.
157    pub fn into_namespace_ident(self) -> String {
158        match self {
159            ImportSource::Module {
160                namespace_ident, ..
161            }
162            | ImportSource::External {
163                namespace_ident, ..
164            } => namespace_ident,
165        }
166    }
167}
168
169impl ReferencedAssetIdent {
170    pub fn into_module_namespace_ident(self) -> Option<(String, Option<SyntaxContext>)> {
171        match self {
172            ReferencedAssetIdent::Module {
173                import_source,
174                ctxt,
175                ..
176            } => Some((import_source.into_namespace_ident(), ctxt)),
177            ReferencedAssetIdent::LocalBinding { .. } => None,
178        }
179    }
180
181    pub fn as_expr_individual(&self, span: Span) -> Either<Ident, MemberExpr> {
182        match self {
183            ReferencedAssetIdent::LocalBinding {
184                ident,
185                ctxt,
186                liveness: _,
187            } => Either::Left(Ident::new(ident.as_str().into(), span, *ctxt)),
188            ReferencedAssetIdent::Module {
189                ctxt,
190                export,
191                import_source,
192            } => {
193                let namespace_ident = import_source.namespace_ident();
194                if let Some(export) = export {
195                    Either::Right(MemberExpr {
196                        span,
197                        obj: Box::new(Expr::Ident(Ident::new(
198                            namespace_ident.into(),
199                            DUMMY_SP,
200                            ctxt.unwrap_or_default(),
201                        ))),
202                        prop: MemberProp::Computed(ComputedPropName {
203                            span: DUMMY_SP,
204                            expr: Box::new(Expr::Lit(Lit::Str(Str {
205                                span: DUMMY_SP,
206                                value: export.as_str().into(),
207                                raw: None,
208                            }))),
209                        }),
210                    })
211                } else {
212                    Either::Left(Ident::new(
213                        namespace_ident.into(),
214                        span,
215                        ctxt.unwrap_or_default(),
216                    ))
217                }
218            }
219        }
220    }
221    pub fn as_expr(&self, span: Span, is_callee: bool) -> Expr {
222        match self.as_expr_individual(span) {
223            Either::Left(ident) => ident.into(),
224            Either::Right(member) => {
225                if is_callee {
226                    Expr::Seq(SeqExpr {
227                        exprs: vec![
228                            Box::new(Expr::Lit(Lit::Num(Number {
229                                span: DUMMY_SP,
230                                value: 0.0,
231                                raw: None,
232                            }))),
233                            Box::new(member.into()),
234                        ],
235                        span: DUMMY_SP,
236                    })
237                } else {
238                    member.into()
239                }
240            }
241        }
242    }
243}
244
245impl ReferencedAsset {
246    pub async fn get_ident(
247        &self,
248        chunking_context: Vc<Box<dyn ChunkingContext>>,
249        export: Option<RcStr>,
250        scope_hoisting_context: ScopeHoistingContext<'_>,
251    ) -> Result<Option<ReferencedAssetIdent>> {
252        self.get_ident_inner(chunking_context, export, scope_hoisting_context, None)
253            .await
254    }
255
256    async fn get_ident_inner(
257        &self,
258        chunking_context: Vc<Box<dyn ChunkingContext>>,
259        export: Option<RcStr>,
260        scope_hoisting_context: ScopeHoistingContext<'_>,
261        initial: Option<&ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>>,
262    ) -> Result<Option<ReferencedAssetIdent>> {
263        Ok(match self {
264            ReferencedAsset::Some(asset) => {
265                if let Some(ctxt) = scope_hoisting_context.get_module_syntax_context(*asset)
266                    && let Some(export) = &export
267                    && let EcmascriptExports::EsmExports(exports) = *asset.get_exports().await?
268                {
269                    let exports = exports.expand_exports(ModuleExportUsageInfo::all()).await?;
270                    let esm_export = exports.exports.get(export);
271                    match esm_export {
272                        Some(EsmExport::LocalBinding(_name, liveness)) => {
273                            // A local binding in a module that is merged in the same group. Use the
274                            // export name as identifier, it will be replaced with the actual
275                            // variable name during AST merging.
276                            return Ok(Some(ReferencedAssetIdent::LocalBinding {
277                                ident: export.clone(),
278                                ctxt,
279                                liveness: *liveness,
280                            }));
281                        }
282                        Some(b @ EsmExport::ImportedBinding(esm_ref, _, _))
283                        | Some(b @ EsmExport::ImportedNamespace(esm_ref)) => {
284                            let imported = if let EsmExport::ImportedBinding(_, export, _) = b {
285                                Some(export.clone())
286                            } else {
287                                None
288                            };
289
290                            let referenced_asset =
291                                ReferencedAsset::from_resolve_result(esm_ref.resolve_reference())
292                                    .await?;
293
294                            if let Some(&initial) = initial
295                                && referenced_asset == ReferencedAsset::Some(initial)
296                            {
297                                // `initial` reexports from `asset` reexports from
298                                // `referenced_asset` (which is `initial`)
299                                CircularReExport {
300                                    export: export.clone(),
301                                    import: imported.clone(),
302                                    module: *asset,
303                                    module_cycle: initial,
304                                }
305                                .resolved_cell()
306                                .emit();
307                                return Ok(None);
308                            }
309
310                            // If the target module is still in the same group, we can
311                            // refer it locally, otherwise it will be imported
312                            return Ok(
313                                match Box::pin(referenced_asset.get_ident_inner(
314                                    chunking_context,
315                                    imported,
316                                    scope_hoisting_context,
317                                    Some(asset),
318                                ))
319                                .await?
320                                {
321                                    Some(ReferencedAssetIdent::Module {
322                                        // Overwrite the context. This import isn't
323                                        // inserted in the module that uses the import,
324                                        // but in the module containing the reexport
325                                        ctxt: None,
326                                        export,
327                                        import_source,
328                                    }) => Some(ReferencedAssetIdent::Module {
329                                        ctxt: Some(ctxt),
330                                        export,
331                                        import_source,
332                                    }),
333                                    ident => ident,
334                                },
335                            );
336                        }
337                        Some(EsmExport::Error) => {
338                            // The export has failed to resolve. The module is merged into this
339                            // scope hoisting group, so it might not have a module factory that
340                            // could be imported. There is nothing to bind to, so the binding
341                            // evaluates to `undefined`.
342                            return Ok(None);
343                        }
344                        None if exports.dynamic_exports.is_empty() => {
345                            // The export is statically known to not exist. The module is merged
346                            // into this scope hoisting group, so it might not have a module
347                            // factory that could be imported. There is nothing to bind to, so the
348                            // binding evaluates to `undefined`.
349                            return Ok(None);
350                        }
351                        None => {
352                            // Export not found, this is some dynamic (CJS) (re)export situation.
353                        }
354                    }
355                }
356
357                let import_source = ImportSource::new_module(*asset, chunking_context).await?;
358                Some(ReferencedAssetIdent::Module {
359                    ctxt: None,
360                    // The target module may emit its exports under shortened keys. This is the
361                    // only place a cross-module export access is materialized, and it resolves
362                    // the same map the producing module uses (see
363                    // `EsmExports::code_generation`), so the two always agree.
364                    export: match &export {
365                        Some(export) => {
366                            Some(generated_export_key(*asset, chunking_context, export).await?)
367                        }
368                        None => None,
369                    },
370                    import_source,
371                })
372            }
373            ReferencedAsset::External(request, ty) => Some(ReferencedAssetIdent::Module {
374                ctxt: None,
375                export,
376                import_source: ImportSource::new_external(request.clone(), *ty),
377            }),
378            ReferencedAsset::NonPlaceable(module) => {
379                // The module exists but has no ECMAScript bindings, so there is
380                // nothing this identifier could refer to. Report it instead of
381                // silently evaluating to `undefined`.
382                CodeGenerationIssue {
383                    severity: IssueSeverity::Error,
384                    title: StyledString::Text(rcstr!("non-ecmascript placeable asset"))
385                        .resolved_cell(),
386                    message: StyledString::Text(
387                        format!(
388                            "{} has no ECMAScript exports, so {} can't be read from it. It can \
389                             only be imported for its side effects.",
390                            module.ident().to_string().await?,
391                            match &export {
392                                Some(export) => format!("the export {export:?}"),
393                                None => "a namespace".to_string(),
394                            }
395                        )
396                        .into(),
397                    )
398                    .resolved_cell(),
399                    path: module.ident().await?.path.clone(),
400                    source: None,
401                }
402                .resolved_cell()
403                .emit();
404                None
405            }
406            ReferencedAsset::None | ReferencedAsset::Empty | ReferencedAsset::Unresolvable => None,
407        })
408    }
409
410    pub(crate) async fn get_ident_from_placeable(
411        asset: Vc<Box<dyn EcmascriptChunkPlaceable>>,
412        chunking_context: Vc<Box<dyn ChunkingContext>>,
413    ) -> Result<String> {
414        let id = asset.chunk_item_id(chunking_context).await?;
415        // There are a number of places in `next` that match on this prefix.
416        // See `packages/next/src/shared/lib/magic-identifier.ts`
417        Ok(magic_identifier::mangle(&format!("imported module {id}")))
418    }
419}
420
421impl ReferencedAsset {
422    pub async fn from_resolve_result(resolve_result: Vc<ModuleResolveResult>) -> Result<Self> {
423        // TODO handle multiple keyed results
424        let result = resolve_result.await?;
425        if result.is_unresolvable() {
426            return Ok(ReferencedAsset::Unresolvable);
427        }
428        let mut non_placeable = None;
429        for (_, result) in result.primary.iter() {
430            match result {
431                ModuleResolveResultItem::External {
432                    name: request, ty, ..
433                } => {
434                    return Ok(ReferencedAsset::External(request.clone(), *ty));
435                }
436                ModuleResolveResultItem::Module(module) => {
437                    if let Some(placeable) =
438                        ResolvedVc::try_downcast::<Box<dyn EcmascriptChunkPlaceable>>(*module)
439                    {
440                        return Ok(ReferencedAsset::Some(placeable));
441                    }
442                    non_placeable = non_placeable.or(Some(*module));
443                }
444                ModuleResolveResultItem::Empty => {
445                    return Ok(ReferencedAsset::Empty);
446                }
447                // TODO ignore should probably be handled differently
448                _ => {}
449            }
450        }
451        Ok(match non_placeable {
452            Some(module) => ReferencedAsset::NonPlaceable(module),
453            None => ReferencedAsset::None,
454        })
455    }
456}
457
458#[turbo_tasks::value(transparent)]
459pub struct EsmAssetReferences(Vec<ResolvedVc<EsmAssetReference>>);
460
461#[turbo_tasks::value_impl]
462impl EsmAssetReferences {
463    #[turbo_tasks::function]
464    pub fn empty() -> Vc<Self> {
465        Vc::cell(Vec::new())
466    }
467}
468
469#[turbo_tasks::value(shared)]
470#[derive(Hash, Debug, ValueToString)]
471#[value_to_string("import {request}")]
472pub struct EsmAssetReference {
473    pub module: ResolvedVc<EcmascriptModuleAsset>,
474    /// The resolve origin, with any annotation-driven transition already applied at construction.
475    pub origin: ResolvedVc<Box<dyn ResolveOrigin>>,
476    // Request is a string to avoid eagerly parsing into a `Request` VC
477    pub request: RcStr,
478    pub issue_source: IssueSource,
479    pub export_name: Option<ModulePart>,
480    pub import_usage: ImportUsage,
481    pub import_externals: bool,
482    pub module_fragments_enabled: bool,
483    pub is_pure_import: bool,
484    /// Rarely-present, slightly-large fields (import-annotation overrides and a resolve override),
485    /// boxed off the common path so the typical reference stays small. `None` whenever every field
486    /// would be empty.
487    extras: Option<Box<EsmReferenceExtras>>,
488}
489
490/// Construction options for an [`EsmAssetReference`].
491///
492/// The module, origin, and request stay as constructor arguments because they identify the
493/// reference. The remaining behavior is named here so call sites don't depend on argument order.
494pub struct EsmAssetReferenceOptions {
495    pub issue_source: IssueSource,
496    pub annotations: Option<ImportAnnotations>,
497    pub export_name: Option<ModulePart>,
498    pub import_usage: ImportUsage,
499    pub import_externals: bool,
500    pub module_fragments_enabled: bool,
501    /// Explicit export-usage passthrough mode for syntax-driven forwarding. `Some(false)` forwards
502    /// used names without exposing the target namespace's original property names.
503    pub export_usage_passthrough: Option<bool>,
504    /// An internal part imported only to preserve evaluation order, without reading its exports.
505    pub evaluation_only: bool,
506    /// The named binding read from an internal fragment, rather than its namespace.
507    pub internal_binding: Option<RcStr>,
508    pub resolve_override: Option<ResolvedVc<Box<dyn Module>>>,
509}
510
511/// Optional extra state for an [`EsmAssetReference`] that is rarely present: the few values
512/// extracted from `ImportAnnotations` (the full `ImportAnnotations` — a `BTreeMap` plus several
513/// `Option`s — is not retained) plus a `resolve_override` from matched inner assets.
514#[derive(
515    Clone, Default, PartialEq, Eq, Hash, Debug, ValueDebugFormat, NonLocalValue, Encode, Decode,
516)]
517struct EsmReferenceExtras {
518    /// `turbopackLoader` configuration (drives `ImportWithTurbopackUse`).
519    turbopack_loader: Option<WebpackLoaderItem>,
520    /// `turbopackAs` rename configuration.
521    turbopack_rename_as: Option<RcStr>,
522    /// `turbopackModuleType` override (distinct from the `with { type: ... }` attribute).
523    turbopack_module_type: Option<RcStr>,
524    /// The `with { type: ... }` attribute (drives `ImportWithType`).
525    module_type: Option<RcStr>,
526    /// The chunking-type annotation (drives `chunking_type`).
527    chunking_type: Option<SpecifiedChunkingType>,
528    /// Whether the importing module's used exports should be forwarded to the target. The boolean
529    /// records whether this edge itself exposes the target namespace's original property names.
530    export_usage_passthrough: Option<bool>,
531    /// The target is an internal module fragment imported only to run it before this one
532    /// (reported as a required `ExportUsage::Evaluation`, see `BindingUsage::required`).
533    evaluation_only: bool,
534    /// The single binding this edge reads from an internal module fragment or the `exports`
535    /// fragment (reported as `ExportUsage::Named`).
536    internal_binding: Option<RcStr>,
537    /// A module to resolve to directly, bypassing resolution (from a matched inner asset).
538    resolve_override: Option<ResolvedVc<Box<dyn Module>>>,
539}
540
541fn merge_export_usage_passthrough(
542    explicit: Option<bool>,
543    annotation_passthrough: bool,
544) -> Option<bool> {
545    // An annotation is an explicit request to expose the namespace's original names, so it must
546    // not be weakened by a syntax-driven passthrough mode on the same reference.
547    annotation_passthrough.then_some(true).or(explicit)
548}
549
550impl EsmReferenceExtras {
551    /// Builds the extras from import annotations and a resolve override, returning `None` (rather
552    /// than an all-empty box) when nothing relevant is present — the common case.
553    fn new(
554        annotations: Option<&ImportAnnotations>,
555        export_usage_passthrough: Option<bool>,
556        evaluation_only: bool,
557        internal_binding: Option<RcStr>,
558        resolve_override: Option<ResolvedVc<Box<dyn Module>>>,
559    ) -> Option<Box<Self>> {
560        let extras = EsmReferenceExtras {
561            turbopack_loader: annotations.and_then(|a| a.turbopack_loader().cloned()),
562            turbopack_rename_as: annotations.and_then(|a| a.turbopack_rename_as().cloned()),
563            turbopack_module_type: annotations.and_then(|a| a.turbopack_module_type().cloned()),
564            module_type: annotations
565                .and_then(|a| a.module_type())
566                .map(|m| RcStr::from(&*m.to_string_lossy())),
567            chunking_type: annotations.and_then(|a| a.chunking_type()),
568            export_usage_passthrough: merge_export_usage_passthrough(
569                export_usage_passthrough,
570                annotations.is_some_and(|a| a.export_usage_passthrough()),
571            ),
572            evaluation_only,
573            internal_binding,
574            resolve_override,
575        };
576        (extras != EsmReferenceExtras::default()).then(|| Box::new(extras))
577    }
578}
579
580#[cfg(test)]
581mod tests {
582    use super::merge_export_usage_passthrough;
583
584    #[test]
585    fn annotation_passthrough_cannot_be_weakened() {
586        assert_eq!(merge_export_usage_passthrough(None, false), None);
587        assert_eq!(
588            merge_export_usage_passthrough(Some(false), false),
589            Some(false)
590        );
591        assert_eq!(
592            merge_export_usage_passthrough(Some(true), false),
593            Some(true)
594        );
595        assert_eq!(merge_export_usage_passthrough(None, true), Some(true));
596        assert_eq!(
597            merge_export_usage_passthrough(Some(false), true),
598            Some(true)
599        );
600        assert_eq!(merge_export_usage_passthrough(Some(true), true), Some(true));
601    }
602}
603
604impl EsmAssetReference {
605    async fn new_inner(
606        module: ResolvedVc<EcmascriptModuleAsset>,
607        origin: ResolvedVc<Box<dyn ResolveOrigin>>,
608        request: RcStr,
609        options: EsmAssetReferenceOptions,
610        is_pure_import: bool,
611    ) -> Result<Self> {
612        let EsmAssetReferenceOptions {
613            issue_source,
614            annotations,
615            export_name,
616            import_usage,
617            import_externals,
618            module_fragments_enabled,
619            export_usage_passthrough,
620            evaluation_only,
621            internal_binding,
622            resolve_override,
623        } = options;
624
625        // Apply any annotation-driven transition eagerly so the stored origin is final and the
626        // `annotations` don't need to be retained on the reference.
627        let origin = if let Some(transition) = annotations.as_ref().and_then(|a| a.transition()) {
628            origin
629                .with_transition(transition.into())
630                .await?
631                .to_resolved()
632                .await?
633        } else {
634            origin
635        };
636        Ok(EsmAssetReference {
637            module,
638            origin,
639            request,
640            issue_source,
641            export_name,
642            import_usage,
643            import_externals,
644            module_fragments_enabled,
645            is_pure_import,
646            extras: EsmReferenceExtras::new(
647                annotations.as_ref(),
648                export_usage_passthrough,
649                evaluation_only,
650                internal_binding,
651                resolve_override,
652            ),
653        })
654    }
655
656    pub async fn new(
657        module: ResolvedVc<EcmascriptModuleAsset>,
658        origin: ResolvedVc<Box<dyn ResolveOrigin>>,
659        request: RcStr,
660        options: EsmAssetReferenceOptions,
661    ) -> Result<Self> {
662        Self::new_inner(
663            module, origin, request, options, /* is_pure_import */ false,
664        )
665        .await
666    }
667
668    pub async fn new_pure(
669        module: ResolvedVc<EcmascriptModuleAsset>,
670        origin: ResolvedVc<Box<dyn ResolveOrigin>>,
671        request: RcStr,
672        options: EsmAssetReferenceOptions,
673    ) -> Result<Self> {
674        Self::new_inner(
675            module, origin, request, options, /* is_pure_import */ true,
676        )
677        .await
678    }
679
680    /// Builds a copy of this reference for a single resolved namespace export
681    /// (`import * as ns from 'foo'; ns.bar` → behave like `import { bar } from 'foo'`).
682    ///
683    /// Reuses the already-transitioned `origin` and the `extras` (annotation values + resolve
684    /// override), overriding only the `export_name`. Stays synchronous (no transition / annotation
685    /// re-extraction) so it can be called from the synchronous namespace-rewrite path.
686    pub fn rewrite_for_export(&self, export_name: ModulePart) -> Self {
687        EsmAssetReference {
688            module: self.module,
689            origin: self.origin,
690            request: self.request.clone(),
691            issue_source: self.issue_source,
692            export_name: Some(export_name),
693            // TODO this is correct, but an overapproximation. We should have individual
694            // import_usage data for each export. This would be fixed by moving this
695            // logic earlier.
696            import_usage: self.import_usage.clone(),
697            import_externals: self.import_externals,
698            module_fragments_enabled: self.module_fragments_enabled,
699            is_pure_import: self.is_pure_import,
700            extras: self.extras.clone(),
701        }
702    }
703
704    pub(crate) fn get_referenced_asset(
705        self: Vc<Self>,
706    ) -> impl Future<Output = Result<ReferencedAsset>> {
707        ReferencedAsset::from_resolve_result(self.resolve_reference())
708    }
709}
710
711#[turbo_tasks::value_impl]
712impl ModuleReference for EsmAssetReference {
713    #[turbo_tasks::function]
714    async fn resolve_reference(&self) -> Result<Vc<ModuleResolveResult>> {
715        let extras = self.extras.as_deref();
716        if let Some(resolved) = extras.and_then(|e| e.resolve_override) {
717            return Ok(*ModuleResolveResult::module(resolved));
718        }
719        let ty = if let Some(loader) = extras.and_then(|e| e.turbopack_loader.as_ref()) {
720            // Resolve the loader path relative to the importing file
721            let origin_ref = self.origin.into_trait_ref().await?;
722            let origin_path = origin_ref.origin_path();
723            let loader_request = Request::parse(loader.loader.clone().into());
724            let resolved = resolve(
725                origin_path.parent(),
726                ReferenceType::Loader,
727                loader_request,
728                origin_ref.resolve_options(),
729            );
730            let loader_fs_path = if let Some(source) = resolved.await?.first_source() {
731                source.ident().await?.path.clone()
732            } else {
733                bail!("Unable to resolve turbopackLoader '{}'", loader.loader);
734            };
735
736            EcmaScriptModulesReferenceSubType::ImportWithTurbopackUse {
737                loader: ResolvedWebpackLoaderItem {
738                    loader: loader_fs_path,
739                    options: loader.options.clone(),
740                },
741                rename_as: extras.and_then(|e| e.turbopack_rename_as.clone()),
742                module_type: extras.and_then(|e| e.turbopack_module_type.clone()),
743            }
744        } else if let Some(module_type) = extras.and_then(|e| e.module_type.as_ref()) {
745            EcmaScriptModulesReferenceSubType::ImportWithType(module_type.clone())
746        } else if let Some(part) = &self.export_name {
747            EcmaScriptModulesReferenceSubType::ImportPart(part.clone())
748        } else {
749            EcmaScriptModulesReferenceSubType::Import
750        };
751
752        let request = Request::parse(self.request.clone().into());
753
754        if self.module_fragments_enabled {
755            if let Some(ModulePart::Evaluation) = &self.export_name
756                && *self.module.side_effects().await? == ModuleSideEffects::SideEffectFree
757            {
758                return Ok(ModuleResolveResult {
759                    primary: Box::new([(RequestKey::default(), ModuleResolveResultItem::Ignore)]),
760                    affecting_sources: Default::default(),
761                }
762                .cell());
763            }
764
765            if let Request::Module { module, .. } = &*request.await?
766                && module.is_match(TURBOPACK_PART_IMPORT_SOURCE)
767            {
768                if let Some(part) = &self.export_name {
769                    return Ok(*ModuleResolveResult::module(ResolvedVc::upcast(
770                        EcmascriptModulePartAsset::select_part(*self.module, part.clone())
771                            .to_resolved()
772                            .await?,
773                    )));
774                }
775                bail!("export_name is required for part import")
776            }
777        }
778
779        let result = esm_resolve(
780            *self.origin,
781            request,
782            ty,
783            ResolveErrorMode::Error,
784            Some(self.issue_source),
785        )
786        .await?;
787
788        if let Some(export_name) = self.export_name.as_ref().and_then(ModulePart::get_export) {
789            for &module in result.await?.primary_modules().await?.iter() {
790                if let Some(module) = ResolvedVc::try_downcast(module)
791                    && *is_export_missing(*module, export_name.clone()).await?
792                {
793                    InvalidExport {
794                        export: export_name.clone(),
795                        module,
796                        source: self.issue_source,
797                        importing_module: self.module,
798                        request: self.request.clone(),
799                    }
800                    .resolved_cell()
801                    .emit();
802                }
803            }
804        }
805
806        Ok(result)
807    }
808
809    fn chunking_type(&self) -> Option<ChunkingType> {
810        self.extras
811            .as_deref()
812            .and_then(|e| e.chunking_type)
813            .map_or_else(
814                || {
815                    Some(ChunkingType::Parallel {
816                        inherit_async: true,
817                        hoisted: true,
818                    })
819                },
820                |c| c.as_chunking_type(true, true),
821            )
822    }
823
824    fn binding_usage(&self) -> BindingUsage {
825        let export_usage_passthrough = self
826            .extras
827            .as_deref()
828            .and_then(|extras| extras.export_usage_passthrough);
829        let evaluation_only = self.extras.as_deref().is_some_and(|e| e.evaluation_only);
830        BindingUsage {
831            import: self.import_usage.clone(),
832            export: match (&self.export_name, export_usage_passthrough) {
833                // Evaluation references preserve their side-effect-only semantics even when the
834                // corresponding import forwards export usage.
835                (Some(ModulePart::Evaluation), _) => ExportUsage::Evaluation,
836                _ if evaluation_only => ExportUsage::Evaluation,
837                _ if let Some(binding) = self
838                    .extras
839                    .as_deref()
840                    .and_then(|e| e.internal_binding.as_ref()) =>
841                {
842                    ExportUsage::Named(binding.clone())
843                }
844                (_, Some(namespace_object_may_escape)) => ExportUsage::Passthrough {
845                    namespace_object_may_escape,
846                },
847                (
848                    Some(
849                        ModulePart::Export(export_name)
850                        | ModulePart::PartialExport {
851                            export: export_name,
852                            ..
853                        },
854                    ),
855                    _,
856                ) => {
857                    // Until resolution proves a partial export is a namespace, it is still an
858                    // ordinary named read of the outer module. The synthesized namespace rename
859                    // reference records the member read on the resolved target.
860                    ExportUsage::Named(export_name.clone())
861                }
862                _ => ExportUsage::All,
863            },
864            required: evaluation_only,
865        }
866    }
867
868    fn source(&self) -> Option<IssueSource> {
869        Some(self.issue_source)
870    }
871}
872
873impl EsmAssetReference {
874    pub(crate) async fn code_generation(
875        self: ResolvedVc<Self>,
876        chunking_context: Vc<Box<dyn ChunkingContext>>,
877        scope_hoisting_context: ScopeHoistingContext<'_>,
878        // References a compact re-export registration (`TURBOPACK_ESM_REEXPORT`) already imports
879        // for itself. Emitting them here too would instantiate the module twice.
880        subsumed_imports: &SubsumedImports,
881    ) -> Result<CodeGeneration> {
882        let this = &*self.await?;
883
884        if chunking_context
885            .unused_references()
886            .contains_key(&ResolvedVc::upcast(self))
887            .await?
888        {
889            return Ok(CodeGeneration::empty());
890        }
891
892        // only chunked references can be imported
893        if this
894            .extras
895            .as_deref()
896            .and_then(|e| e.chunking_type)
897            .is_none_or(|v| v != SpecifiedChunkingType::None)
898        {
899            let import_externals = this.import_externals;
900            let referenced_asset = self.get_referenced_asset().await?;
901
902            match &referenced_asset {
903                ReferencedAsset::Unresolvable => {
904                    // Insert code that throws immediately at time of import if a request is
905                    // unresolvable
906                    let request = &this.request;
907                    let stmt = Stmt::Expr(ExprStmt {
908                        expr: Box::new(throw_module_not_found_expr(request)),
909                        span: DUMMY_SP,
910                    });
911                    return Ok(CodeGeneration::hoisted_stmt(
912                        format!("throw {request}").into(),
913                        stmt,
914                    ));
915                }
916                // A module without ECMAScript bindings (e.g. a stylesheet) may still
917                // be imported for its side effects, which needs no code generation.
918                ReferencedAsset::None
919                | ReferencedAsset::Empty
920                | ReferencedAsset::NonPlaceable(_) => {}
921                _ => {
922                    let mut result = vec![];
923
924                    let merged_index = if let ReferencedAsset::Some(asset) = &referenced_asset {
925                        scope_hoisting_context.get_module_index(*asset)
926                    } else {
927                        None
928                    };
929
930                    if let Some(merged_index) = merged_index {
931                        // Insert a placeholder to inline the merged module at the right place
932                        // relative to the other references (so to keep reference order).
933                        result.push(CodeGenerationHoistedStmt::new(
934                            format!("hoisted {merged_index}").into(),
935                            quote!(
936                                "__turbopack_merged_esm__($id);" as Stmt,
937                                id: Expr = Lit::Num(merged_index.into()).into(),
938                            ),
939                        ));
940                    }
941
942                    if merged_index.is_some()
943                        && matches!(this.export_name, Some(ModulePart::Evaluation))
944                    {
945                        // No need to import, the module was already executed and is available in
946                        // the same scope hoisting group (unless it's a
947                        // namespace import)
948                    } else {
949                        'import: {
950                            let ident = referenced_asset
951                                .get_ident(
952                                    chunking_context,
953                                    this.export_name
954                                        .as_ref()
955                                        .and_then(ModulePart::get_export)
956                                        .cloned(),
957                                    scope_hoisting_context,
958                                )
959                                .await?;
960                            // `referenced_asset` must not be used past this point: the ident
961                            // carries everything about the import
962                            // target (see `ImportSource`) — notably,
963                            // when the ident was resolved through a re-export chain, the
964                            // directly-referenced asset is the outer (rename) module, not the one
965                            // the emitted variable actually holds.
966                            drop(referenced_asset);
967                            let span = this
968                                .issue_source
969                                .to_swc_offsets()
970                                .await?
971                                .map_or(DUMMY_SP, |(start, end)| {
972                                    Span::new(BytePos(start), BytePos(end))
973                                });
974                            match ident {
975                                Some(ReferencedAssetIdent::LocalBinding { .. }) => {
976                                    // no need to import
977                                }
978                                Some(ReferencedAssetIdent::Module {
979                                    ctxt,
980                                    export: _,
981                                    import_source,
982                                }) => {
983                                    let namespace_key =
984                                        (import_source.namespace_ident().to_owned(), ctxt);
985                                    if subsumed_imports.namespaces.contains(&namespace_key)
986                                        && (!matches!(
987                                            this.export_name,
988                                            Some(ModulePart::Evaluation)
989                                        ) || subsumed_imports.evaluation_spans.contains(&span))
990                                    {
991                                        // A compact re-export registration performs this import.
992                                        // An evaluation import with a different span is a separate
993                                        // earlier declaration of the same module and stays in
994                                        // place.
995                                        break 'import;
996                                    }
997                                    let name = Ident::new(
998                                        namespace_key.0.into(),
999                                        DUMMY_SP,
1000                                        ctxt.unwrap_or_default(),
1001                                    );
1002                                    let (key, mut call_expr) = match import_source {
1003                                        ImportSource::Module { asset, .. } => {
1004                                            let id = asset.chunk_item_id(chunking_context).await?;
1005                                            // Include ctxt in the key to prevent incorrect
1006                                            // deduplication when multiple merged modules import the
1007                                            // same target but have different syntax contexts (which
1008                                            // would cause hygiene to rename one of them).
1009                                            (
1010                                                format!("{} {:?}", id, ctxt).into(),
1011                                                quote!(
1012                                                    "$turbopack_import($id)" as Expr,
1013                                                    turbopack_import: Expr = TURBOPACK_IMPORT.into(),
1014                                                    id: Expr = module_id_to_lit(&id),
1015                                                ),
1016                                            )
1017                                        }
1018                                        ImportSource::External {
1019                                            request,
1020                                            ty: ExternalType::EcmaScriptModule,
1021                                            ..
1022                                        } => {
1023                                            if !*chunking_context
1024                                                .environment()
1025                                                .supports_esm_externals()
1026                                                .await?
1027                                            {
1028                                                turbobail!(
1029                                                    "the chunking context ({}) does not support \
1030                                                     external modules (esm request: {request})",
1031                                                    chunking_context.name()
1032                                                );
1033                                            }
1034                                            let call = if import_externals {
1035                                                quote!(
1036                                                    "$turbopack_external_import($id)" as Expr,
1037                                                    turbopack_external_import: Expr = TURBOPACK_EXTERNAL_IMPORT.into(),
1038                                                    id: Expr = Expr::Lit(request.to_string().into())
1039                                                )
1040                                            } else {
1041                                                quote!(
1042                                                    "$turbopack_external_require($id, () => require($id), true)" as Expr,
1043                                                    turbopack_external_require: Expr = TURBOPACK_EXTERNAL_REQUIRE.into(),
1044                                                    id: Expr = Expr::Lit(request.to_string().into())
1045                                                )
1046                                            };
1047                                            (name.sym.as_str().into(), call)
1048                                        }
1049                                        ImportSource::External {
1050                                            request,
1051                                            ty: ExternalType::CommonJs | ExternalType::Url,
1052                                            ..
1053                                        } => {
1054                                            if !*chunking_context
1055                                                .environment()
1056                                                .supports_commonjs_externals()
1057                                                .await?
1058                                            {
1059                                                turbobail!(
1060                                                    "the chunking context ({}) does not support \
1061                                                     external modules (request: {request})",
1062                                                    chunking_context.name()
1063                                                );
1064                                            }
1065                                            let call = quote!(
1066                                                "$turbopack_external_require($id, () => require($id), true)" as Expr,
1067                                                turbopack_external_require: Expr = TURBOPACK_EXTERNAL_REQUIRE.into(),
1068                                                id: Expr = Expr::Lit(request.to_string().into())
1069                                            );
1070                                            (name.sym.as_str().into(), call)
1071                                        }
1072                                        // fallback in case we introduce a new `ExternalType`
1073                                        #[allow(unreachable_patterns)]
1074                                        ImportSource::External { request, ty, .. } => {
1075                                            bail!(
1076                                                "Unsupported external type {:?} for ESM reference \
1077                                                 with request: {:?}",
1078                                                ty,
1079                                                request
1080                                            )
1081                                        }
1082                                    };
1083                                    if this.is_pure_import {
1084                                        call_expr.set_span(PURE_SP);
1085                                    }
1086                                    result.push(CodeGenerationHoistedStmt::new(
1087                                        key,
1088                                        var_decl_with_span(
1089                                            quote!(
1090                                                "var $name = $call;" as Stmt,
1091                                                name = name,
1092                                                call: Expr = call_expr
1093                                            ),
1094                                            span,
1095                                        ),
1096                                    ));
1097                                }
1098                                None => {
1099                                    // Nothing to import.
1100                                }
1101                            }
1102                        }
1103                    }
1104                    return Ok(CodeGeneration::hoisted_stmts(result));
1105                }
1106            }
1107        };
1108
1109        Ok(CodeGeneration::empty())
1110    }
1111}
1112
1113fn var_decl_with_span(mut decl: Stmt, span: Span) -> Stmt {
1114    match &mut decl {
1115        Stmt::Decl(Decl::Var(decl)) => decl.span = span,
1116        _ => panic!("Expected Stmt::Decl::Var"),
1117    };
1118    decl
1119}
1120
1121#[turbo_tasks::value(shared)]
1122pub struct InvalidExport {
1123    export: RcStr,
1124    module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>,
1125    source: IssueSource,
1126    /// The module containing the import declaration, used to find the other names imported by the
1127    /// same declaration (so they aren't suggested as alternatives).
1128    importing_module: ResolvedVc<EcmascriptModuleAsset>,
1129    /// The request of the import declaration.
1130    request: RcStr,
1131}
1132
1133impl InvalidExport {
1134    /// Returns the export names referenced by the other specifiers of the import (or re-export)
1135    /// declaration that requested the missing export. All specifiers of one declaration share the
1136    /// declaration's span and request.
1137    ///
1138    /// This reads the importing module's parse result, so it's only meant to be called when the
1139    /// issue is rendered.
1140    async fn names_imported_by_same_declaration(&self) -> Result<FxHashSet<RcStr>> {
1141        let ParseResult::Ok { eval_context, .. } = &*self.importing_module.failsafe_parse().await?
1142        else {
1143            return Ok(FxHashSet::default());
1144        };
1145        let source = self.importing_module.await?.source;
1146        Ok(eval_context
1147            .imports
1148            .references()
1149            .filter_map(|r| {
1150                let ImportedSymbol::Symbol(name) = &r.imported_symbol else {
1151                    return None;
1152                };
1153                (IssueSource::from_swc_offsets(source, r.span.lo.to_u32(), r.span.hi.to_u32())
1154                    == self.source
1155                    && *r.module_path.to_string_lossy() == *self.request)
1156                    .then(|| RcStr::from(&**name))
1157            })
1158            .collect())
1159    }
1160}
1161
1162#[async_trait]
1163#[turbo_tasks::value_impl]
1164impl Issue for InvalidExport {
1165    fn severity(&self) -> IssueSeverity {
1166        IssueSeverity::Error
1167    }
1168
1169    async fn title(&self) -> Result<StyledString> {
1170        Ok(StyledString::Line(vec![
1171            StyledString::Text(rcstr!("Export ")),
1172            StyledString::Code(self.export.clone()),
1173            StyledString::Text(rcstr!(" doesn't exist in target module")),
1174        ]))
1175    }
1176
1177    fn stage(&self) -> IssueStage {
1178        IssueStage::Bindings
1179    }
1180
1181    async fn file_path(&self) -> Result<FileSystemPath> {
1182        self.source.file_path().await
1183    }
1184
1185    async fn description(&self) -> Result<Option<StyledString>> {
1186        let export_names = all_known_export_names(*self.module).await?;
1187        let already_imported = self.names_imported_by_same_declaration().await?;
1188        let did_you_mean = export_names
1189            .iter()
1190            .filter(|s| !already_imported.contains(*s))
1191            .map(|s| (s, jaro(self.export.as_str(), s.as_str())))
1192            .max_by(|a, b| a.1.partial_cmp(&b.1).unwrap())
1193            .map(|(s, _)| s);
1194        let mut lines = vec![StyledString::Line(vec![
1195            StyledString::Text(rcstr!("The export ")),
1196            StyledString::Code(self.export.clone()),
1197            StyledString::Text(rcstr!(" was not found in module ")),
1198            StyledString::Strong(self.module.ident().to_string().owned().await?),
1199            StyledString::Text(rcstr!(".")),
1200        ])];
1201        if let Some(did_you_mean) = did_you_mean {
1202            lines.push(StyledString::Line(vec![
1203                StyledString::Text(rcstr!("Did you mean to import ")),
1204                StyledString::Code(did_you_mean.clone()),
1205                StyledString::Text(rcstr!("?")),
1206            ]));
1207        } else if export_names.is_empty() {
1208            lines.push(StyledString::Strong(rcstr!(
1209                "The module has no exports at all."
1210            )));
1211        }
1212        // Otherwise all exports are already imported by the same declaration, so there is nothing
1213        // to suggest.
1214        lines.push(StyledString::Text(
1215            "All exports of the module are statically known (It doesn't have dynamic exports). So \
1216             it's known statically that the requested export doesn't exist."
1217                .into(),
1218        ));
1219        Ok(Some(StyledString::Stack(lines)))
1220    }
1221
1222    async fn detail(&self) -> Result<Option<StyledString>> {
1223        let export_names = all_known_export_names(*self.module).await?;
1224        Ok(Some(StyledString::Line(vec![
1225            StyledString::Text(rcstr!("These are the exports of the module:\n")),
1226            StyledString::Code(
1227                export_names
1228                    .iter()
1229                    .map(|s| s.as_str())
1230                    .intersperse(", ")
1231                    .collect::<String>()
1232                    .into(),
1233            ),
1234        ])))
1235    }
1236
1237    fn source(&self) -> Option<IssueSource> {
1238        Some(self.source)
1239    }
1240}
1241
1242#[turbo_tasks::value(shared)]
1243pub struct CircularReExport {
1244    export: RcStr,
1245    import: Option<RcStr>,
1246    module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>,
1247    module_cycle: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>,
1248}
1249
1250#[async_trait]
1251#[turbo_tasks::value_impl]
1252impl Issue for CircularReExport {
1253    fn severity(&self) -> IssueSeverity {
1254        IssueSeverity::Error
1255    }
1256
1257    async fn title(&self) -> Result<StyledString> {
1258        Ok(StyledString::Line(vec![
1259            StyledString::Text(rcstr!("Export ")),
1260            StyledString::Code(self.export.clone()),
1261            StyledString::Text(rcstr!(" is a circular re-export")),
1262        ]))
1263    }
1264
1265    fn stage(&self) -> IssueStage {
1266        IssueStage::Bindings
1267    }
1268
1269    async fn file_path(&self) -> Result<FileSystemPath> {
1270        Ok(self.module.ident().await?.path.clone())
1271    }
1272
1273    async fn description(&self) -> Result<Option<StyledString>> {
1274        Ok(Some(StyledString::Stack(vec![
1275            StyledString::Line(vec![StyledString::Text(rcstr!("The export"))]),
1276            StyledString::Line(vec![
1277                StyledString::Code(self.export.clone()),
1278                StyledString::Text(rcstr!(" of module ")),
1279                StyledString::Strong(self.module.ident().to_string().owned().await?),
1280            ]),
1281            StyledString::Line(vec![StyledString::Text(rcstr!(
1282                "is a re-export of the export"
1283            ))]),
1284            StyledString::Line(vec![
1285                StyledString::Code(self.import.clone().unwrap_or_else(|| rcstr!("*"))),
1286                StyledString::Text(rcstr!(" of module ")),
1287                StyledString::Strong(self.module_cycle.ident().to_string().owned().await?),
1288                StyledString::Text(rcstr!(".")),
1289            ]),
1290        ])))
1291    }
1292
1293    fn source(&self) -> Option<IssueSource> {
1294        // TODO(PACK-4879): This should point at the buggy export by querying for the source
1295        // location
1296        None
1297    }
1298}