Unverified Commit b1c15da6 authored by Sam Poder's avatar Sam Poder Committed by GitHub

[turbopack] Track members across namespace re-exports (#96396)

## What?

This PR closes a missed tree-shaking opportunity for libraries that
expose a module namespace as a named export. One real-world example is
Zod, whose public API has a structure similar to the following (and this
pattern also appears in v0's codebase):

```js
// user.js
import { z } from './lib.js'

console.log(z.object(), z.string(), z.defaultLocale)
```

```js
// lib.js — mirrors zod/index.js
import * as z from './external.js'

export * from './external.js'
export { z }
export default z

// external.js — mirrors zod/v4/classic/external.js
import en from './locales/en.js'

export * as locales from './locales/index.js'

export const object = () => 'object'
export const string = () => 'string'
export const defaultLocale = en
```

The analyzer can now preserve the information that only `object`,
`string`, and `defaultLocale` are read from `z`, and use it after
resolving that named export to the namespace of `external.js`.

This PR is now standalone on `canary`. Its two former prerequisites have
landed: #98680 introduced the independently reviewed
`EsmAssetReferenceOptions` constructor refactor, and #96282 integrated
CommonJS and ESM whole-namespace forwarding with canary's generic
`ExportUsage::Passthrough` fixed point.

## Why?

Previously, Turbopack knew that the named export `z` was used, but lost
the static member information from expressions such as `z.object()`.
Once `z` resolved to a namespace object, the optimizer therefore kept
every export of `external.js` — including `locales` and all of
`./locales/index.js` in this example.

The optimization must remain conservative in several cases:

- a computed property whose name cannot be determined statically, such
as `z[key]`;
- a namespace binding that escapes to unknown code, such as passing `z`
to another function;
- static and opaque uses of the same binding, where the opaque use must
dominate narrowing;
- live exports and method calls, whose binding and receiver semantics
must not change.

It must also avoid changing ordinary named-import behavior. A property
read on an imported value is not proof that the value is a module
namespace; narrowing and namespace provenance are valid only after
re-export resolution proves that fact.

## How?

### Represent namespace-member requests explicitly

The module-part model now has explicit states for this operation:

- `ExportedNamespaceMember { export, member }` represents a static
member read on a named export before re-export resolution;
- `RenamedNamespaceMember { export, member }` represents the case after
that export resolves to a module namespace.

This avoids overloading an ordinary `Export` or an optional `member`
field with two meanings. It also keeps existing `Export` and
`RenamedNamespace` identities unchanged; the new variants have distinct
hashes only for the new states.

Multiple static reads and multiple aliases are tracked as independently
keyed references, so `z.object`, `z.string`, and `z.defaultLocale` all
survive rather than overwriting one another.

### Narrow only after proving the export is a namespace

The analyzer records a statically known member on an imported binding
while leaving the emitted member expression intact. Re-export following
first resolves the outer named export:

1. If it resolves to a namespace object, Turbopack synthesizes a
namespace-member reference to the resolved module and contributes
`PartialNamespaceObject({ member })` there.
2. If it resolves to an ordinary named export, it continues to behave
like a normal named read of the outer module. It does not mark the
module as namespace-observable or unnecessarily disable export-name
mangling.

Dynamic property access and escaping bindings do not produce a narrowed
member part, so they continue to retain the full namespace. When static
and opaque uses are joined, the full-namespace use wins.

The explicit module-part variants are threaded through both fragment and
non-fragment infrastructure so they remain valid graph identities. The
new `ExportedNamespaceMember` rewrite itself currently runs only when
module fragments are disabled. A dedicated `moduleFragmentsEnabled:
true` fixture verifies the supported existing split behavior without
claiming that this new rewrite is active there.

While rebasing, canary moved follow-reexport canonicalization into
`turbopack-ecmascript` so lazy dynamic imports can carry the same
canonicalization policy. Namespace-member handling now lives in that
canonicalization helper as well, preserving both the new
lazy-compilation path and this PR's namespace rewrite.

## Testing

Enabled coverage includes:

- the Zod-shaped snapshot showing only `object`, `string`, and
`defaultLocale` retained while the unused locale namespace is removed;
- multiple static members on one namespace-valued export;
- dynamic access, escaping use, and mixed static/opaque use retaining
the full namespace;
- direct `export * as`, including an enabled used/unused precision
assertion;
- computed-string, parenthesized, optional, and missing-property reads;
- `this`-sensitive method calls;
- default-exported and renamed namespace values;
- live bindings read and mutated through multiple aliases, with single
evaluation;
- nested namespace runtime behavior and top-level-await targets;
- scope-hoisted, non-scope-hoisted, and module-fragment configurations;
- export-name mangling safety and non-pessimization across #96282's
forwarding edges.

Development coverage updates both a value behind the CommonJS forwarding
edge and a statically read namespace member, verifying HMR observes each
new value without stale exports or runtime errors.

One optimization-only limitation is documented under
`__skipped__/namespace-value-reexport-nested`: member narrowing
currently stops after the first namespace level for a read such as
`z.locales.en`. The full nested runtime behavior is covered by the
enabled `namespace-value-reexport` fixture.

Local verification on the standalone canary rebase passes affected-crate
and `next-core` checks, 14 focused execution/snapshot tests, the merged
passthrough/annotation unit tests, 60 analyzer graph tests, `build-all`,
and the development/HMR test. A throwaway ordinary object-valued
named-import fixture also verified that the pre-resolution path
preserves property values and `this` for getters and methods; it was
removed after review.

<!-- NEXT_JS_LLM -->


<!-- fleet 993ef5d6-cc80-4082-8e14-ff9ac871ce33 -->
Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
Co-authored-by: 's avatarLuke Sandberg <210140+lukesandberg@users.noreply.github.com>
parent 1edced6f
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
'use client'
import { value } from '../lib/forwarder'
import { namespace } from '../lib/namespace-lib'
export default function Page() {
return (
<main>
<p id="forwarded">{value}</p>
<p id="namespace">{namespace.member}</p>
</main>
)
}
import * as namespace from './namespace-source'
export { namespace }
export const member = 'namespace-v1'
export const stale = 'namespace-stale-v1'
export const value = 'forwarded-v1'
export const stale = 'stale-v1'
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
const forwardedV2 = `
export const value = 'forwarded-v2'
export const replacement = 'replacement-v2'
`
const namespaceV2 = `
export const member = 'namespace-v2'
export const replacement = 'namespace-replacement-v2'
`
describe('Turbopack re-export HMR', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('updates forwarded exports and namespace members without stale values', async () => {
const browser = await next.browser('/')
expect(await browser.elementByCss('#forwarded').text()).toBe('forwarded-v1')
expect(await browser.elementByCss('#namespace').text()).toBe('namespace-v1')
await next.patchFile('lib/source.js', forwardedV2)
await retry(async () => {
expect(await browser.elementByCss('#forwarded').text()).toBe(
'forwarded-v2'
)
})
await next.patchFile('lib/namespace-source.js', namespaceV2)
await retry(async () => {
expect(await browser.elementByCss('#namespace').text()).toBe(
'namespace-v2'
)
})
expect(await browser.elementByCss('#forwarded').text()).not.toContain(
'stale'
)
expect(await browser.elementByCss('#namespace').text()).not.toContain(
'stale'
)
})
})
......@@ -249,30 +249,40 @@ impl AssetIdent {
2_u8.deterministic_hash(&mut hasher);
export.deterministic_hash(&mut hasher);
}
ModulePart::PartialExport { export, member } => {
3_u8.deterministic_hash(&mut hasher);
export.deterministic_hash(&mut hasher);
member.deterministic_hash(&mut hasher);
}
ModulePart::RenamedExport {
original_export,
export,
} => {
3_u8.deterministic_hash(&mut hasher);
4_u8.deterministic_hash(&mut hasher);
original_export.deterministic_hash(&mut hasher);
export.deterministic_hash(&mut hasher);
}
ModulePart::RenamedNamespace { export } => {
4_u8.deterministic_hash(&mut hasher);
5_u8.deterministic_hash(&mut hasher);
export.deterministic_hash(&mut hasher);
}
ModulePart::RenamedPartialNamespace { export, member } => {
6_u8.deterministic_hash(&mut hasher);
export.deterministic_hash(&mut hasher);
member.deterministic_hash(&mut hasher);
}
ModulePart::Internal(id) => {
5_u8.deterministic_hash(&mut hasher);
7_u8.deterministic_hash(&mut hasher);
id.deterministic_hash(&mut hasher);
}
ModulePart::Locals => {
6_u8.deterministic_hash(&mut hasher);
8_u8.deterministic_hash(&mut hasher);
}
ModulePart::Exports => {
7_u8.deterministic_hash(&mut hasher);
9_u8.deterministic_hash(&mut hasher);
}
ModulePart::Facade => {
8_u8.deterministic_hash(&mut hasher);
10_u8.deterministic_hash(&mut hasher);
}
}
......
......@@ -163,7 +163,7 @@ pub enum ImportUsage {
/// This import is used only by these specific exports, if all exports are unused, the import
/// can also be removed.
///
/// (This is only ever set on `ModulePart::Export` references. Side effects are handled via
/// (This is only ever set on named export module-part references. Side effects are handled via
/// `ModulePart::Evaluation` references, which always have `ImportUsage::TopLevel`.)
Exports(FrozenSet<RcStr>),
}
......@@ -241,6 +241,11 @@ impl ExportUsage {
Self::Named(name).cell()
}
#[turbo_tasks::function]
pub fn partial_namespace_object(names: Vec<RcStr>) -> Vc<Self> {
Self::PartialNamespaceObject(names.into_iter().collect()).cell()
}
#[turbo_tasks::function]
pub fn passthrough(namespace_object_may_escape: bool) -> Vc<Self> {
Self::Passthrough {
......@@ -3417,26 +3422,42 @@ async fn resolve_package_internal_with_imports_field(
#[turbo_tasks::task_input]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Hash, Encode, Decode)]
pub enum ModulePart {
/// Represents the side effects of a module. This part is evaluated even if
/// all exports are unused.
/// Represents the side effects of a module, such as `import "./module"`.
/// This part is evaluated even if all exports are unused.
Evaluation,
/// Represents an export of a module.
/// Represents a named export, such as `foo` in `import { foo } from "./module"`.
Export(RcStr),
/// Represents a renamed export of a module.
/// Represents an export for which one member is used.
///
/// For example, `import { value } from "./module"; value.member` is represented as
/// `{ export: "value", member: "member" }`. At this point, `value` has not yet been
/// resolved and might be either an ordinary value or a namespace object. If it is not a
/// namespace object, this behaves like [`ModulePart::Export`].
PartialExport { export: RcStr, member: RcStr },
/// Represents an export renamed while following re-exports, such as `foo` exported as `bar`
/// by `export { foo as bar } from "./module"`.
RenamedExport {
original_export: RcStr,
export: RcStr,
},
/// Represents a namespace object of a module exported as named export.
/// Represents a namespace object exported as a named export, such as `ns` in
/// `export * as ns from "./module"`.
RenamedNamespace { export: RcStr },
/// A pointer to a specific part.
/// Represents a namespace object exported as a named export when only one member is used.
///
/// For example, `import { ns } from "./lib"; ns.member`, where `lib` contains
/// `export * as ns from "./module"`, is represented as
/// `{ export: "ns", member: "member" }` after resolving `ns` to the namespace object.
RenamedPartialNamespace { export: RcStr, member: RcStr },
/// Points to a generated module-fragment part by its numeric index, such as the part that
/// contains one local declaration.
Internal(u32),
/// The local declarations of a module.
/// Represents the local declarations of a module, such as `const value = 1`.
Locals,
/// The whole exports of a module.
/// Represents the module's export declarations, such as `export { value }`.
Exports,
/// A facade of the module behaving like the original, but referencing
/// internal parts.
/// Represents a facade that behaves like the original module while referencing its internal
/// parts, such as the facade emitted for a split module.
Facade,
}
......@@ -3449,6 +3470,10 @@ impl ModulePart {
ModulePart::Export(export)
}
pub fn partial_export(export: RcStr, member: RcStr) -> Self {
ModulePart::PartialExport { export, member }
}
pub fn renamed_export(original_export: RcStr, export: RcStr) -> Self {
ModulePart::RenamedExport {
original_export,
......@@ -3460,6 +3485,22 @@ impl ModulePart {
ModulePart::RenamedNamespace { export }
}
pub fn renamed_partial_namespace(export: RcStr, member: RcStr) -> Self {
ModulePart::RenamedPartialNamespace { export, member }
}
/// Returns the named export exposed by this part, if it has one.
pub fn get_export(&self) -> Option<&RcStr> {
match self {
ModulePart::Export(export)
| ModulePart::PartialExport { export, .. }
| ModulePart::RenamedExport { export, .. }
| ModulePart::RenamedNamespace { export }
| ModulePart::RenamedPartialNamespace { export, .. } => Some(export),
_ => None,
}
}
pub fn internal(id: u32) -> Self {
ModulePart::Internal(id)
}
......@@ -3482,12 +3523,16 @@ impl Display for ModulePart {
match self {
ModulePart::Evaluation => f.write_str("module evaluation"),
ModulePart::Export(export) => write!(f, "export {export}"),
ModulePart::PartialExport { export, member } => {
write!(f, "export {export} .{member}")
}
ModulePart::RenamedExport {
original_export,
export,
} => write!(f, "export {original_export} as {export}"),
ModulePart::RenamedNamespace { export } => {
write!(f, "export * as {export}")
ModulePart::RenamedNamespace { export } => write!(f, "export * as {export}"),
ModulePart::RenamedPartialNamespace { export, member } => {
write!(f, "export * as {export} .{member}")
}
ModulePart::Internal(id) => write!(f, "internal part {id}"),
ModulePart::Locals => f.write_str("locals"),
......@@ -3515,6 +3560,44 @@ mod tests {
virtual_source::VirtualSource,
};
#[test]
fn module_part_export_names_and_display() {
let export = rcstr!("value");
let member = rcstr!("member");
let original = rcstr!("original");
let with_exports = [
ModulePart::export(export.clone()),
ModulePart::partial_export(export.clone(), member.clone()),
ModulePart::renamed_export(original, export.clone()),
ModulePart::renamed_namespace(export.clone()),
ModulePart::renamed_partial_namespace(export.clone(), member.clone()),
];
for part in with_exports {
assert_eq!(part.get_export(), Some(&export));
}
let without_exports = [
ModulePart::evaluation(),
ModulePart::internal(0),
ModulePart::locals(),
ModulePart::exports(),
ModulePart::facade(),
];
for part in without_exports {
assert_eq!(part.get_export(), None);
}
assert_eq!(
ModulePart::partial_export(export.clone(), member.clone()).to_string(),
"export value .member"
);
assert_eq!(
ModulePart::renamed_partial_namespace(export, member).to_string(),
"export * as value .member"
);
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_missing_paths_through_symlinks_do_not_error() {
......
......@@ -171,6 +171,8 @@ pub enum Effect<'a> {
ImportedBinding {
esm_reference_index: usize,
export: Option<RcStr>,
/// A single member read from a named import (`z.member`), used only to narrow the part.
member: Option<RcStr>,
ast_path: BumpBox<'a, [AstParentKind]>,
span: Span,
},
......
......@@ -2468,14 +2468,25 @@ impl VisitAstPath for Analyzer<'_, '_> {
self.add_effect(Effect::ImportedBinding {
esm_reference_index,
export: Some(prop_str.into()),
member: None,
// point to the MemberExpression instead
ast_path: as_parent_path_skip_in(self.arena, ast_path, 1),
span: member.span(),
});
} else {
// ast_path stays on the ident, so `.exportName` remains in the emitted code.
let mut member = None;
if export.is_some()
&& let Some(access) = member_access_parent(ast_path)
&& let Some(prop) = self.eval_context.eval_member_prop(self.arena, &access.prop)
&& let Some(prop_str) = prop.as_str()
{
member = Some(RcStr::from(prop_str));
}
self.add_effect(Effect::ImportedBinding {
esm_reference_index,
export: export.map(|e| RcStr::from(e.as_str())),
member,
ast_path: as_parent_path_in(self.arena, ast_path),
span: ident.span(),
})
......
......@@ -39,7 +39,7 @@ pub async fn canonicalize_ecmascript_module(
ModulePart::Evaluation => {
Vc::upcast(EcmascriptModuleLocalsModule::new(*module))
}
ModulePart::Export(_) => {
ModulePart::Export(_) | ModulePart::PartialExport { .. } => {
apply_reexport_tree_shaking(
Vc::upcast(
*EcmascriptModuleFacadeModule::new(Vc::upcast(*module))
......@@ -69,27 +69,36 @@ async fn apply_reexport_tree_shaking(
module: Vc<Box<dyn EcmascriptChunkPlaceable>>,
part: ModulePart,
) -> Result<Vc<Box<dyn EcmascriptChunkPlaceable>>> {
if let ModulePart::Export(export) = &part {
let FollowExportsResult {
module: final_module,
export_name: new_export,
..
} = &*follow_reexports(module, export.clone(), true).await?;
return Ok(if let Some(new_export) = new_export {
if *new_export == *export {
**final_module
} else {
Vc::upcast(EcmascriptModuleRenameModule::new(
**final_module,
ModulePart::renamed_export(new_export.clone(), export.clone()),
))
}
// The namespace member is only applied if this export resolves to a namespace object.
let (export, namespace_member) = match &part {
ModulePart::Export(export) => (export, None),
ModulePart::PartialExport { export, member } => (export, Some(member)),
_ => return Ok(module),
};
let FollowExportsResult {
module: final_module,
export_name: new_export,
..
} = &*follow_reexports(module, export.clone(), true).await?;
Ok(if let Some(new_export) = new_export {
if *new_export == *export {
**final_module
} else {
Vc::upcast(EcmascriptModuleRenameModule::new(
**final_module,
ModulePart::renamed_namespace(export.clone()),
ModulePart::renamed_export(new_export.clone(), export.clone()),
))
});
}
Ok(module)
}
} else {
Vc::upcast(EcmascriptModuleRenameModule::new(
**final_module,
match namespace_member {
Some(member) => {
ModulePart::renamed_partial_namespace(export.clone(), member.clone())
}
None => ModulePart::renamed_namespace(export.clone()),
},
))
})
}
......@@ -383,13 +383,16 @@ async fn get_part_id(result: &SplitResult, part: &ModulePart) -> Result<u32> {
// TODO implement ModulePart::Facade
let key = match part {
ModulePart::Evaluation => Key::ModuleEvaluation,
ModulePart::Export(export) => Key::Export(export.clone()),
ModulePart::Export(export) | ModulePart::PartialExport { export, .. } => {
Key::Export(export.clone())
}
ModulePart::Exports => Key::Exports,
ModulePart::Internal(part_id) => return Ok(*part_id),
ModulePart::Locals
| ModulePart::Facade
| ModulePart::RenamedExport { .. }
| ModulePart::RenamedNamespace { .. } => {
| ModulePart::RenamedNamespace { .. }
| ModulePart::RenamedPartialNamespace { .. } => {
bail!("invalid module part")
}
};
......@@ -408,7 +411,7 @@ async fn get_part_id(result: &SplitResult, part: &ModulePart) -> Result<u32> {
}
// This is required to handle `export * from 'foo'`
if let ModulePart::Export(..) = part
if part.get_export().is_some()
&& let Some(&v) = entrypoints
.get(&Key::StarExports)
.or_else(|| entrypoints.get(&Key::Exports))
......
......@@ -164,7 +164,12 @@ impl EcmascriptModulePartAsset {
));
}
ModulePart::Export(export) => {
part @ (ModulePart::Export(_) | ModulePart::PartialExport { .. }) => {
let (export, namespace_member) = match part {
ModulePart::Export(export) => (export, None),
ModulePart::PartialExport { export, member } => (export, Some(member)),
_ => unreachable!(),
};
if entrypoints.contains_key(&Key::Export(export.clone())) {
return Ok(Vc::upcast(
EcmascriptModulePartAsset::new_with_resolved_part(
......@@ -200,7 +205,12 @@ impl EcmascriptModulePartAsset {
ResolvedVc::upcast(
EcmascriptModuleRenameModule::new(
**final_module,
ModulePart::renamed_namespace(export.clone()),
match namespace_member {
Some(member) => {
ModulePart::renamed_partial_namespace(export.clone(), member)
}
None => ModulePart::renamed_namespace(export.clone()),
},
)
.to_resolved()
.await?,
......@@ -312,7 +322,9 @@ impl Module for EcmascriptModulePartAsset {
async fn references(&self) -> Result<Vc<ModuleReferences>> {
let part_dep = |part: ModulePart| -> Vc<Box<dyn ModuleReference>> {
let export = match &part {
ModulePart::Export(export) => ExportUsage::named(export.clone()),
ModulePart::Export(export) | ModulePart::PartialExport { export, .. } => {
ExportUsage::named(export.clone())
}
ModulePart::Evaluation => ExportUsage::evaluation(),
_ => ExportUsage::all(),
};
......@@ -343,7 +355,7 @@ impl Module for EcmascriptModulePartAsset {
#[turbo_tasks::function]
async fn side_effects(&self) -> Vc<ModuleSideEffects> {
match self.part {
ModulePart::Exports | ModulePart::Export(..) => {
ModulePart::Exports | ModulePart::Export(_) | ModulePart::PartialExport { .. } => {
ModuleSideEffects::SideEffectFree.cell()
}
_ => self.full_module.side_effects(),
......
......@@ -727,7 +727,7 @@ impl ModuleReference for EsmAssetReference {
)
.await?;
if let Some(ModulePart::Export(export_name)) = &self.export_name {
if let Some(export_name) = self.export_name.as_ref().and_then(ModulePart::get_export) {
for &module in result.await?.primary_modules().await?.iter() {
if let Some(module) = ResolvedVc::try_downcast(module)
&& *is_export_missing(*module, export_name.clone()).await?
......@@ -775,7 +775,19 @@ impl ModuleReference for EsmAssetReference {
(_, Some(namespace_object_may_escape)) => ExportUsage::Passthrough {
namespace_object_may_escape,
},
(Some(ModulePart::Export(export_name)), _) => {
(
Some(
ModulePart::Export(export_name)
| ModulePart::PartialExport {
export: export_name,
..
},
),
_,
) => {
// Until resolution proves a partial export is a namespace, it is still an
// ordinary named read of the outer module. The synthesized namespace rename
// reference records the member read on the resolved target.
ExportUsage::Named(export_name.clone())
}
_ => ExportUsage::All,
......@@ -868,12 +880,10 @@ impl EsmAssetReference {
let ident = referenced_asset
.get_ident(
chunking_context,
this.export_name.as_ref().and_then(|e| match e {
ModulePart::Export(export_name) => {
Some(export_name.clone())
}
_ => None,
}),
this.export_name
.as_ref()
.and_then(ModulePart::get_export)
.cloned(),
scope_hoisting_context,
)
.await?;
......
......@@ -1409,6 +1409,7 @@ async fn analyze_ecmascript_module_internal(
Effect::ImportedBinding {
esm_reference_index,
export,
member,
ast_path,
span: _,
} => {
......@@ -1483,6 +1484,33 @@ async fn analyze_ecmascript_module_internal(
));
continue;
}
if let Some(ModulePart::Export(export_name)) =
&original_reference.export_name
&& let Some(member) = member
{
// Ask for just the static member if the named export resolves to a
// namespace object.
let narrowed_reference = analysis
.add_esm_reference_namespace_resolved(
esm_reference_index,
member.clone(),
|| {
original_reference
.rewrite_for_export(ModulePart::partial_export(
export_name.clone(),
member.clone(),
))
.resolved_cell()
},
);
analysis.add_code_gen(EsmBinding::new(
narrowed_reference,
export,
analysis.intern_path(&ast_path),
));
continue;
}
}
analysis.add_esm_reference(esm_reference_index);
......
......@@ -39,7 +39,7 @@ pub struct EcmascriptModuleRenameModule {
module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>,
/// The part of the module that this facade represents.
/// ModulePart::Facade | ModulePart::RenamedExport |
/// ModulePart::RenamedNamespace
/// ModulePart::RenamedNamespace | ModulePart::RenamedPartialNamespace
part: ModulePart,
}
......@@ -53,7 +53,9 @@ impl EcmascriptModuleRenameModule {
assert!(
matches!(
part,
ModulePart::RenamedExport { .. } | ModulePart::RenamedNamespace { .. }
ModulePart::RenamedExport { .. }
| ModulePart::RenamedNamespace { .. }
| ModulePart::RenamedPartialNamespace { .. }
),
"{part:?} is unexpected for EcmascriptModuleRenameModule"
);
......@@ -91,6 +93,15 @@ impl EcmascriptModuleRenameModule {
.to_resolved()
.await
}
ModulePart::RenamedPartialNamespace { member, .. } => {
EcmascriptModulePartReference::new_normal(
*self.module,
self.part.clone(),
ExportUsage::partial_namespace_object(vec![member.clone()]),
)
.to_resolved()
.await
}
ModulePart::RenamedExport {
original_export, ..
} => {
......@@ -232,7 +243,8 @@ impl EcmascriptChunkPlaceable for EcmascriptModuleRenameModule {
false,
),
),
ModulePart::RenamedNamespace { export } => (
ModulePart::RenamedNamespace { export }
| ModulePart::RenamedPartialNamespace { export, .. } => (
export.clone(),
EsmExport::ImportedNamespace(ResolvedVc::upcast(reference)),
),
......
......@@ -26,6 +26,7 @@
export: Some(
"named",
),
member: None,
ast_path: [
Program(
Module,
......
......@@ -694,6 +694,7 @@
export: Some(
"x",
),
member: None,
ast_path: [
Program(
Module,
......@@ -746,6 +747,7 @@
export: Some(
"y",
),
member: None,
ast_path: [
Program(
Module,
......@@ -983,6 +985,7 @@
export: Some(
"z",
),
member: None,
ast_path: [
Program(
Module,
......
......@@ -158,6 +158,7 @@
export: Some(
"createRequire",
),
member: None,
ast_path: [
Program(
Module,
......
......@@ -18,6 +18,7 @@
export: Some(
"named",
),
member: None,
ast_path: [
Program(
Module,
......@@ -137,6 +138,7 @@
export: Some(
"named",
),
member: None,
ast_path: [
Program(
Module,
......
......@@ -4,6 +4,7 @@
export: Some(
"default",
),
member: None,
ast_path: [
Program(
Module,
......@@ -41,6 +42,7 @@
export: Some(
"a",
),
member: None,
ast_path: [
Program(
Module,
......@@ -76,6 +78,7 @@
ImportedBinding {
esm_reference_index: 6,
export: None,
member: None,
ast_path: [
Program(
Module,
......
......@@ -4,6 +4,7 @@
export: Some(
"useMemo",
),
member: None,
ast_path: [
Program(
Module,
......@@ -255,6 +256,7 @@
export: Some(
"jsx",
),
member: None,
ast_path: [
Program(
Module,
......@@ -788,6 +790,7 @@
export: Some(
"fooBar",
),
member: None,
ast_path: [
Program(
Module,
......
......@@ -13,6 +13,7 @@
export: Some(
"assert",
),
member: None,
ast_path: [
Program(
Module,
......@@ -274,6 +275,7 @@
export: Some(
"assert",
),
member: None,
ast_path: [
Program(
Module,
......@@ -431,6 +433,7 @@
export: Some(
"assert",
),
member: None,
ast_path: [
Program(
Module,
......
......@@ -238,6 +238,7 @@
export: Some(
"Redis",
),
member: None,
ast_path: [
Program(
Module,
......
......@@ -1096,6 +1096,9 @@
export: Some(
"default",
),
member: Some(
"join",
),
ast_path: [
Program(
Module,
......@@ -1139,6 +1142,7 @@
export: Some(
"join",
),
member: None,
ast_path: [
Program(
Module,
......
......@@ -4,6 +4,7 @@
export: Some(
"calledA1",
),
member: None,
ast_path: [
Program(
Module,
......@@ -175,6 +176,7 @@
export: Some(
"unreachableA3",
),
member: None,
ast_path: [
Program(
Module,
......@@ -297,6 +299,7 @@
export: Some(
"unreachableB1",
),
member: None,
ast_path: [
Program(
Module,
......@@ -496,6 +499,7 @@
export: Some(
"calledB1",
),
member: None,
ast_path: [
Program(
Module,
......@@ -618,6 +622,7 @@
export: Some(
"calledC1",
),
member: None,
ast_path: [
Program(
Module,
......@@ -817,6 +822,7 @@
export: Some(
"calledC2",
),
member: None,
ast_path: [
Program(
Module,
......
// Runtime behavior is covered by the enabled `namespace-value-reexport` fixtures. This remains
// skipped only because member narrowing currently stops at the first namespace level.
import { nestedNamespace } from './lib'
it('should narrow through a nested namespace-valued export', () => {
expect(nestedNamespace.locales.en).toBe('en')
expect(nestedNamespace.locales.enUsed).toBe(true)
expect(nestedNamespace.locales.deUsed).toBe(false)
})
export const en = 'en'
export const de = 'de'
export const enUsed = __webpack_exports_info__.en.used
export const deUsed = __webpack_exports_info__.de.used
export const value = 'value'
export const unused = 'unused'
export const unusedInfo = __webpack_exports_info__.unused.used
import { namespace } from './lib'
it('should narrow a member of a direct namespace reexport', () => {
expect(namespace.value).toBe('value')
expect(namespace.unusedInfo).toBe(false)
})
import { z } from './static-lib'
import { dynamicNamespace } from './dynamic-lib'
import { escapedNamespace } from './escape-lib'
it('reads multiple static members from a namespace-valued named export', () => {
expect(z.object()).toBe('object')
expect(z.string()).toBe('string')
expect(z.value).toBe('value')
})
it('keeps the full namespace for dynamic computed access', () => {
const read = (key) => dynamicNamespace[key]
expect(read('first')).toBe('first')
expect(read('second')).toBe('second')
})
it('keeps the full namespace when the binding escapes', () => {
const consume = (namespace) => Object.keys(namespace).sort()
expect(consume(escapedNamespace)).toEqual(['alpha', 'beta'])
})
export const object = () => 'object'
export const string = () => 'string'
export const value = 'value'
export const unused = 'unused'
{
"followReexports": true,
"moduleFragmentsEnabled": true,
"removeUnusedImports": true,
"removeUnusedExports": true,
"scopeHoisting": false
}
await Promise.resolve()
export const asyncValue = 'async-value'
export const asyncUnused = 'async-unused'
import * as defaultNamespace from './direct-external'
export default defaultNamespace
globalThis.__namespace_value_side_effects =
(globalThis.__namespace_value_side_effects ?? 0) + 1
export const value = 'direct-value'
export const sibling = 'sibling-value'
export const unused = 'unused'
export let live = 'before'
export function method() {
return this.sibling
}
export function setLive(value) {
live = value
}
export const unusedInfo = __webpack_exports_info__.unused.used
import * as dynamicNamespace from './dynamic-external'
export { dynamicNamespace }
import * as escapedNamespace from './escape-external'
export { escapedNamespace }
import { z } from './static-lib'
import { dynamicNamespace } from './dynamic-lib'
import { escapedNamespace } from './escape-lib'
import { direct as aliasA, direct as aliasB } from './direct-lib'
import defaultNamespace from './default-lib'
import { renamedNamespace } from './rename-barrel'
import { nestedNamespace } from './nested-lib'
import { asyncNamespace } from './async-lib'
it('reads multiple static members from a namespace-valued named export', () => {
expect(z.object()).toBe('object')
expect(z.string()).toBe('string')
expect(z.value).toBe('value')
})
it('keeps the full namespace for dynamic computed access', () => {
const read = (key) => dynamicNamespace[key]
expect(read('first')).toBe('first')
expect(read('second')).toBe('second')
})
it('keeps the full namespace when the binding escapes', () => {
const consume = (namespace) => Object.keys(namespace).sort()
expect(consume(escapedNamespace)).toEqual(['alpha', 'beta'])
})
it('joins static and opaque uses of the same namespace conservatively', () => {
const key = 'unused'
expect(z.object()).toBe('object')
expect(z[key]).toBe('unused')
expect(Object.keys(z)).toContain('unused')
})
it('supports direct export-star-as and static member expression variants', () => {
expect(aliasA['value']).toBe('direct-value')
expect(aliasA.value).toBe('direct-value')
expect(aliasA?.value).toBe('direct-value')
expect(aliasA.missing).toBe(undefined)
expect(aliasA.method()).toBe('sibling-value')
})
it('preserves live bindings and disjoint members across local aliases', () => {
expect(aliasA.live).toBe('before')
aliasB.setLive('after')
expect(aliasA.live).toBe('after')
expect(aliasB.sibling).toBe('sibling-value')
expect(globalThis.__namespace_value_side_effects).toBe(1)
})
it('supports default-exported and renamed namespace values', () => {
expect(defaultNamespace.value).toBe('direct-value')
expect(renamedNamespace.value).toBe('direct-value')
})
it('preserves nested namespace runtime behavior', () => {
expect(nestedNamespace.locales.en).toBe('en')
expect(nestedNamespace.locales.de).toBe('de')
})
it('supports a top-level-await namespace target', () => {
expect(asyncNamespace.asyncValue).toBe('async-value')
})
import * as nestedNamespace from './nested-external'
export { nestedNamespace }
import * as originalNamespace from './direct-external'
export { originalNamespace }
export const object = () => 'object'
export const string = () => 'string'
export const value = 'value'
export const unused = 'unused'
{
"followReexports": true,
"removeUnusedImports": true,
"removeUnusedExports": true,
"scopeHoisting": false
}
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([
"output/1ece_tests_snapshot_basic-tree-shake_tree-shake-test-1_input_index_03lf7hb30lgig.js",
"output/1ece_tests_snapshot_basic-tree-shake_tree-shake-test-1_input_index_1z5rlhbz-88y3.js",
{"otherChunks":["output/1jsg_tests_snapshot_basic-tree-shake_tree-shake-test-1_input_index_07jttq51-r0-b.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/tree-shake-test-1/input/index.js [test] (ecmascript)"]}
]);
// Dummy runtime
\ No newline at end of file
// Mirrors `zod/v4/classic/external.js`.
import en from './locales/en.js'
export * as locales from './locales/index.js'
export const object = () => 'object'
export const string = () => 'string'
export const defaultLocale = en
// The real-world zod shape: `z` is a namespace that lib.js hands out as a plain
// value, and the consumer only ever reads static members of it.
import { z } from './lib.js'
console.log(z.object(), z.string(), z.defaultLocale)
// Mirrors `zod/index.js`.
import * as z from './external.js'
export * from './external.js'
export { z }
export default z
export { default as en } from './en.js'
export { default as fr } from './fr.js'
export { default as de } from './de.js'
{
"followReexports": true,
"removeUnusedImports": true,
"removeUnusedExports": true,
"scopeHoisting": true
}
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([
"output/1ece_tests_snapshot_ns-value-reexport_named-import_input_index_0h-8qal3fspkd.js",
{"otherChunks":["output/1jsg_tests_snapshot_ns-value-reexport_named-import_input_index_1a3a-lomo0k0u.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/ns-value-reexport/named-import/input/index.js [test] (ecmascript)"]}
]);
// Dummy runtime
\ No newline at end of file
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1jsg_tests_snapshot_ns-value-reexport_named-import_input_index_1a3a-lomo0k0u.js",
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/ns-value-reexport/named-import/input/index.js [test] (ecmascript)", ((__turbopack_context__) => {
"use strict";
// MERGED MODULE: [project]/turbopack/crates/turbopack-tests/tests/snapshot/ns-value-reexport/named-import/input/index.js [test] (ecmascript)
;
// MERGED MODULE: [project]/turbopack/crates/turbopack-tests/tests/snapshot/ns-value-reexport/named-import/input/external.js [test] (ecmascript) <export * as z .object>
;
// MERGED MODULE: [project]/turbopack/crates/turbopack-tests/tests/snapshot/ns-value-reexport/named-import/input/external.js [test] (ecmascript)
;
// MERGED MODULE: [project]/turbopack/crates/turbopack-tests/tests/snapshot/ns-value-reexport/named-import/input/external.js [test] (ecmascript) <locals>
;
// MERGED MODULE: [project]/turbopack/crates/turbopack-tests/tests/snapshot/ns-value-reexport/named-import/input/locales/en.js [test] (ecmascript)
;
const __TURBOPACK__default__export__ = 'EN_USED_MARKER';
;
;
const object = ()=>'object';
const string = ()=>'string';
const defaultLocale = __TURBOPACK__default__export__;
__turbopack_context__.s([
"defaultLocale",
0,
defaultLocale,
"object",
0,
object,
"string",
0,
string
], "[project]/turbopack/crates/turbopack-tests/tests/snapshot/ns-value-reexport/named-import/input/external.js [test] (ecmascript) <locals>");
var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$ns$2d$value$2d$reexport$2f$named$2d$import$2f$input$2f$external$2e$js__$5b$test$5d$__$28$ecmascript$29$__$3c$locals$3e$__ = __turbopack_context__.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/ns-value-reexport/named-import/input/external.js [test] (ecmascript) <locals>");
__turbopack_context__.s([
"defaultLocale",
0,
defaultLocale,
"object",
0,
object,
"string",
0,
string
], "[project]/turbopack/crates/turbopack-tests/tests/snapshot/ns-value-reexport/named-import/input/external.js [test] (ecmascript)");
var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$ns$2d$value$2d$reexport$2f$named$2d$import$2f$input$2f$external$2e$js__$5b$test$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/ns-value-reexport/named-import/input/external.js [test] (ecmascript)");
var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$ns$2d$value$2d$reexport$2f$named$2d$import$2f$input$2f$external$2e$js__$5b$test$5d$__$28$ecmascript$29$__ = __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$ns$2d$value$2d$reexport$2f$named$2d$import$2f$input$2f$external$2e$js__$5b$test$5d$__$28$ecmascript$29$__;
// MERGED MODULE: [project]/turbopack/crates/turbopack-tests/tests/snapshot/ns-value-reexport/named-import/input/external.js [test] (ecmascript) <export * as z .string>
;
var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$ns$2d$value$2d$reexport$2f$named$2d$import$2f$input$2f$external$2e$js__$5b$test$5d$__$28$ecmascript$29$__1 = __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$ns$2d$value$2d$reexport$2f$named$2d$import$2f$input$2f$external$2e$js__$5b$test$5d$__$28$ecmascript$29$__;
var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$ns$2d$value$2d$reexport$2f$named$2d$import$2f$input$2f$external$2e$js__$5b$test$5d$__$28$ecmascript$29$__1 = __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$ns$2d$value$2d$reexport$2f$named$2d$import$2f$input$2f$external$2e$js__$5b$test$5d$__$28$ecmascript$29$__;
// MERGED MODULE: [project]/turbopack/crates/turbopack-tests/tests/snapshot/ns-value-reexport/named-import/input/external.js [test] (ecmascript) <export * as z .defaultLocale>
;
var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$ns$2d$value$2d$reexport$2f$named$2d$import$2f$input$2f$external$2e$js__$5b$test$5d$__$28$ecmascript$29$__2 = __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$ns$2d$value$2d$reexport$2f$named$2d$import$2f$input$2f$external$2e$js__$5b$test$5d$__$28$ecmascript$29$__;
var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$ns$2d$value$2d$reexport$2f$named$2d$import$2f$input$2f$external$2e$js__$5b$test$5d$__$28$ecmascript$29$__2 = __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$ns$2d$value$2d$reexport$2f$named$2d$import$2f$input$2f$external$2e$js__$5b$test$5d$__$28$ecmascript$29$__;
;
console.log(__TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$ns$2d$value$2d$reexport$2f$named$2d$import$2f$input$2f$external$2e$js__$5b$test$5d$__$28$ecmascript$29$__.object(), __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$ns$2d$value$2d$reexport$2f$named$2d$import$2f$input$2f$external$2e$js__$5b$test$5d$__$28$ecmascript$29$__1.string(), __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$ns$2d$value$2d$reexport$2f$named$2d$import$2f$input$2f$external$2e$js__$5b$test$5d$__$28$ecmascript$29$__2.defaultLocale);
__turbopack_context__.s([], "[project]/turbopack/crates/turbopack-tests/tests/snapshot/ns-value-reexport/named-import/input/index.js [test] (ecmascript)");
}),
]);
//# sourceMappingURL=1jsg_tests_snapshot_ns-value-reexport_named-import_input_index_1a3a-lomo0k0u.js.map
\ No newline at end of file
{
"version": 3,
"sources": [],
"sections": [
{"offset": {"line": 4, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/ns-value-reexport/named-import/input/locales/en.js","turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/ns-value-reexport/named-import/input/external.js","turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/ns-value-reexport/named-import/input/index.js"],"sourcesContent":["export default 'EN_USED_MARKER'\n","// Mirrors `zod/v4/classic/external.js`.\nimport en from './locales/en.js'\n\nexport * as locales from './locales/index.js'\n\nexport const object = () => 'object'\nexport const string = () => 'string'\nexport const defaultLocale = en\n","// The real-world zod shape: `z` is a namespace that lib.js hands out as a plain\n// value, and the consumer only ever reads static members of it.\nimport { z } from './lib.js'\n\nconsole.log(z.object(), z.string(), z.defaultLocale)\n"],"names":[],"mappings":";;;;;;;;;;uCAAe;;;ACKR,MAAM,SAAS,IAAM;AACrB,MAAM,SAAS,IAAM;AACrB,MAAM,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACH7B,QAAQ,GAAG,CAAC,4NAAE,MAAM,IAAI,6NAAE,MAAM,IAAI,6NAAE,aAAa"}}]
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment