Unverified Commit 8b067039 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

Turbopack: mangle exports behind an escaping namespace via the facade (#97770)

### What?

Allows Turbopack to keep mangling a module's internal export keys when
its namespace object escapes. A facade preserves the original public
names while forwarding each one to the mangled key in the locals module,
matching webpack's materialized-namespace behavior.

This PR is stacked on #98617. That lower PR now owns the generic
synthetic-facade compact registration, including empty evaluation
groups, descriptor reuse, scope-hoisted factories, pruned references,
and cycle/async fallbacks. This PR creates those facades for escaping
namespaces, so the generic path is exercised at scale here.

### Why?

A namespace import or dynamic import whose reads cannot be enumerated
currently disables mangling for the entire target module. That makes one
broad consumer lose the size benefit for every otherwise-static consumer
of the module.

Materializing the original namespace surface keeps ESM semantics intact
— including live values and `Object.keys()` — while allowing internal
consumers to use shorter names.

### How?

The facade's synthesized per-export references participate in the module
graph, so named usage propagates to the locals module. Its structural
locals edge carries evaluation usage only, while each forwarded name
carries its own export usage. Part-reference code generation also honors
references pruned by the graph, matching ordinary ESM references.

Modules with no exports are not split, async modules retain the existing
path, and real export-cycle circuit breakers avoid compact registration
because they require their getters to be visible before imports run.
Namespace grouping includes the SWC syntax context so scope-hoisted
modules cannot accidentally share the wrong generated binding.

### Testing

- `cargo test -p turbopack-ecmascript -p turbopack-tests` — **590 unit,
303 execution, 3 auxiliary, and 131 snapshot tests passed** on the
current stack
- `cargo clippy -p turbopack-ecmascript -p turbopack-core -- -D
warnings`
- `cargo fmt --all -- --check`
- `pnpm test-dev-experimental-turbo
test/development/app-dir/lazy-dynamic-imports/lazy-dynamic-imports.test.ts`
— 9/9 passed
- `pnpm test-dev
test/e2e/app-dir/instant-validation/suspense-boundaries.test.ts` — 38/38
passed
- `pnpm test-start-turbo
test/production/app-dir/barrel-optimization/mui/index.test.ts` — 1/1
passed
- `pnpm test-start-turbo
test/e2e/app-dir/cache-components-allow-otel-spans/cache-components-allow-otel-spans.test.ts`
— 4/4 passed
- `pnpm test-start-turbo
test/e2e/404-page-custom-error/404-page-custom-error.test.ts
test/e2e/app-dir/app-esm-js/index.test.ts
test/e2e/app-dir/app-esm-js/standalone.test.ts` — 9/9 passed
- Existing materialized-namespace fixtures verify namespace values, key
enumeration, dynamic imports, CommonJS consumers, and liveness through
the locals module
- A callable CommonJS namespace fixture regression-tests the compact
registration path after facade materialization
- The full execution suite specifically caught and now covers pruned
locals references and merged evaluation-only locals references in the
generic #98617 implementation

### Bundle-size measurements

Incremental effect of enabling `turbopackMangleExportNames` on this
stack. Both sides use the same native binary and retain #98617's compact
re-export registration; only mangling is toggled. Client reports raw and
deterministic gzip (`gzip -9 -n`, sorted files); server reports raw only
because Node.js consumes server code uncompressed. JavaScript files
only; source maps, CSS, and license sidecars are excluded.

#### Scope hoisting disabled

| benchmark | client raw | client gzip | server raw |
| --- | ---: | ---: | ---: |
| `basic-app` | −17,380 B | −1,131 B | −61,155 B |
| `heavy-npm-deps` *(three-dependency variant: lodash + Mantine +
Mermaid)* | −47,537 B | −6,720 B | −82,326 B |
| `module-cost` | −223,816 B | −2,113 B | −596,419 B |

#### Scope hoisting enabled

| benchmark | client raw | client gzip | server raw |
| --- | ---: | ---: | ---: |
| `basic-app` | −22,658 B | −7,634 B | −32,805 B |
| `heavy-npm-deps` *(three-dependency variant: lodash + Mantine +
Mermaid)* | −14,118 B | +1,291 B | −20,956 B |
| `module-cost` | +30 B | −785 B | −7,265 B |

The `heavy-npm-deps` rows use a modified benchmark fixture with Mantine
and Mermaid enabled alongside lodash; the committed fixture enables
lodash only. Positive/near-zero configurations were repeated and
reproduced byte-for-byte for every reported metric.

<!-- NEXT_JS_LLM -->

<!-- fleet ecdfa248-cd54-41ac-b4a2-c9d49e2a67ee -->

---------
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 e2e19c48
......@@ -771,7 +771,7 @@ async fn validate_pages_css_imports_individual(
graph: ResolvedVc<ModuleGraphLayer>,
is_single_page: bool,
entry: Vc<Box<dyn Module>>,
app_module: ResolvedVc<Box<dyn Module>>,
app_module_path: FileSystemPath,
) -> Result<()> {
let graph = graph.await?;
let entry = entry.to_resolved().await?;
......@@ -801,11 +801,6 @@ async fn validate_pages_css_imports_individual(
};
let parent_module = parent_node;
// Importing CSS from _app.js is always allowed.
if parent_module == app_module {
return Ok(GraphTraversalAction::Continue);
}
// If the module being imported isn't a global css module, there is nothing to
// validate.
let module_is_global_css = ResolvedVc::try_downcast_type::<CssModule>(module).is_some();
......@@ -824,12 +819,7 @@ async fn validate_pages_css_imports_individual(
return Ok(GraphTraversalAction::Continue);
}
// If all of the above invariants have been checked, we look to see if the parent
// module is the same as the app module. If it isn't we know it
// isn't a valid place to import global css.
if parent_module != app_module {
candidates.push(CssGlobalImportIssue::new(parent_module, module))
}
candidates.push(CssGlobalImportIssue::new(parent_module, module));
Ok(GraphTraversalAction::Continue)
},
......@@ -840,6 +830,12 @@ async fn validate_pages_css_imports_individual(
candidates
.into_iter()
.map(async |issue| {
// We allow the app module to import global CSS, but it may be split into multiple
// modules, so exempt references by path.
if issue.parent_module.ident().await?.path == app_module_path {
return Ok(None);
}
let ident = issue.module.ident().await?;
let path = &ident.path;
// We allow imports of global CSS files which are inside of `node_modules`.
......@@ -874,7 +870,7 @@ pub async fn validate_pages_css_imports(
graph: Vc<ModuleGraph>,
is_single_page: bool,
entry: Vc<Box<dyn Module>>,
app_module: Vc<Box<dyn Module>>,
app_module_path: FileSystemPath,
) -> Result<()> {
let graphs = graph.iter_graphs().await?;
graphs
......@@ -884,7 +880,7 @@ pub async fn validate_pages_css_imports(
graph.connect(),
is_single_page,
entry,
app_module,
app_module_path.clone(),
)
.as_side_effect()
})
......
......@@ -976,29 +976,11 @@ impl PageEndpoint {
// We only validate the global css imports when there is not a `app` folder at the
// root of the project.
if project.app_project().await?.is_none() {
// We recreate the app_module here because the one provided from the
// `internal_ssr_chunk_module` is not the same as the one
// provided from the `client_module_graph`. There can be cases where
// the `app_module` is None, and we are processing the `pages/_app.js` file
// as a page rather than the app module.
let app_module = project
.pages_project()
.client_module_context()
.process(
Vc::upcast(FileSource::new(
this.pages_structure.await?.app.file_path().owned().await?,
)),
ReferenceType::Entry(EntryReferenceSubType::Page),
)
.to_resolved()
.await?
.module();
validate_pages_css_imports(
client_module_graph,
per_page_module_graph,
self.client_module(),
app_module,
this.pages_structure.await?.app.file_path().owned().await?,
)
.await?;
}
......
......@@ -4,7 +4,7 @@ use turbopack::{ModuleAssetContext, transition::Transition};
use turbopack_core::{
context::ProcessResult,
file_source::FileSource,
reference_type::{EcmaScriptModulesReferenceSubType, EntryReferenceSubType, ReferenceType},
reference_type::{EntryReferenceSubType, ReferenceType},
source::Source,
};
use turbopack_ecmascript::chunk::EcmascriptChunkPlaceable;
......@@ -39,28 +39,16 @@ impl Transition for NextEcmascriptClientReferenceTransition {
self: Vc<Self>,
source: Vc<Box<dyn Source>>,
module_asset_context: Vc<ModuleAssetContext>,
reference_type: ReferenceType,
// The import part this resolution asked for is deliberately ignored: every part of the
// same client component maps to one client reference module, so that turbo-tasks interns
// it (and its generated proxy) once instead of once per part.
_reference_type: ReferenceType,
) -> Result<Vc<ProcessResult>> {
let part = match reference_type {
ReferenceType::EcmaScriptModules(EcmaScriptModulesReferenceSubType::ImportPart(
part,
)) => Some(part),
_ => None,
};
let module_asset_context = self.process_context(module_asset_context);
let this = self.await?;
let ident = match part {
Some(part) => source
.ident()
.owned()
.await?
.with_part(part.clone())
.into_vc(),
None => source.ident(),
};
let ident = source.ident();
let ident_ref = ident.await?;
let client_source = if ident_ref.path.path.contains("next/dist/esm/") {
let path = ident_ref
......
......@@ -322,8 +322,21 @@ impl EcmascriptExports {
/// Returns whether this module should be split into separate locals and facade modules.
///
/// Splitting is enabled when the module has re-exports (star exports or imported bindings),
/// which allows the tree-shaking optimization to separate local definitions from re-exports.
/// Splitting happens for either of two reasons:
///
/// 1. The module has re-exports (star exports or imported bindings), which lets the
/// tree-shaking optimization separate local definitions from re-exports.
/// 2. Its export names may be mangled. The facade then keeps the original names for whatever
/// reads this module from outside, while the locals module carries the mangled ones — see
/// the `references::esm::mangle` module.
///
/// A module with **no exports at all** is never split, even when mangling is enabled: there is
/// nothing to mangle or tree shake, and splitting is actively unsafe. Such a facade's only edge
/// to the original code would be the `ExportUsage::evaluation` reference from
/// `EcmascriptModuleFacadeModule::specific_references`, which `BindingUsageInfo` prunes when
/// the target looks side-effect free — as a `"sideEffects": false` package declaration
/// makes it, even for a body that has side effects. Unsplit, the module runs as a chunk
/// group entry regardless.
#[turbo_tasks::function]
pub async fn split_locals_and_reexports(&self) -> Result<Vc<bool>> {
Ok(match self {
......@@ -336,7 +349,11 @@ impl EcmascriptExports {
EsmExport::ImportedBinding(..) | EsmExport::ImportedNamespace(_)
)
});
Vc::cell(has_reexports)
// `has_reexports` already implies a non-empty export list, so the emptiness check
// only needs to guard the mangling case.
Vc::cell(
has_reexports || (exports.mangle_export_names && !exports.exports.is_empty()),
)
}
_ => Vc::cell(false),
})
......
......@@ -82,19 +82,40 @@ impl EcmascriptModuleFacadeModule {
);
};
let result = module.analyze().await?;
Ok((
vec![
// TODO skip if side effect free and no local exports
EcmascriptModulePartReference::new_part(
*self.module,
ModulePart::locals(),
ExportUsage::all(),
)
.to_resolved()
.await?,
],
result.esm_reexport_references,
))
// The locals module has to be *evaluated* for its side effects and ordering, which this
// reference is what guarantees. `evaluation()` rather than `all()`: the latter would also
// claim every export is used, widening the locals module's usage to `All` unconditionally
// and defeating both export mangling and tree shaking of its unused exports.
let mut part_references = vec![
EcmascriptModulePartReference::new_part(
*self.module,
ModulePart::locals(),
ExportUsage::evaluation(),
)
.to_resolved()
.await?,
];
// Then one reference per export that comes from the locals module, so the module graph
// carries *which* names this facade needs from it. Without these the evaluation reference
// would be the only facade -> locals edge, and it would have to claim `all()`.
if let EcmascriptExports::EsmExports(esm_exports) = &*self.module.get_exports().await? {
for (name, export) in &esm_exports.await?.exports {
if matches!(export, EsmExport::LocalBinding(..)) {
part_references.push(
EcmascriptModulePartReference::new_part(
*self.module,
ModulePart::locals(),
ExportUsage::named(name.clone()),
)
.to_resolved()
.await?,
);
}
}
}
Ok((part_references, result.esm_reexport_references))
}
}
......
......@@ -137,7 +137,17 @@ impl ModuleReference for EcmascriptModulePartReference {
fn binding_usage(&self) -> BindingUsage {
BindingUsage {
import: ImportUsage::TopLevel,
// A synthesized named facade -> locals edge implements the facade export of the same
// name. It is only needed when that facade export is used; telling the graph this lets
// it propagate the facade's per-name usage into locals instead of keeping every local
// export alive. Normal (non-synthesized) references and structural evaluation edges
// are top-level dependencies.
import: match (&self.mode, &self.export_usage) {
(EcmascriptModulePartReferenceMode::Synthesize, ExportUsage::Named(export)) => {
ImportUsage::Exports(std::iter::once(export.clone()).collect())
}
_ => ImportUsage::TopLevel,
},
export: self.export_usage.clone(),
}
}
......@@ -157,6 +167,8 @@ impl EcmascriptModulePartReference {
) -> Result<CodeGeneration> {
let this = self.await?;
// Skip generation for unused references, similar to `EsmAssetReference::code_generation`.
// Chunking may completely skip the target so we cannot reference it.
if chunking_context
.unused_references()
.contains_key(&ResolvedVc::upcast(self.to_resolved().await?))
......@@ -164,7 +176,6 @@ impl EcmascriptModulePartReference {
{
return Ok(CodeGeneration::empty());
}
let referenced_asset = ReferencedAsset::from_resolve_result(self.resolve_reference());
let referenced_asset = referenced_asset.await?;
......
......@@ -32,43 +32,82 @@ it('exported lets are live', () => {
expect(liveExports.foo).toBe('new')
})
// Whether a binding is emitted as a plain value or as a getter is decided by the module that
// *owns* the binding. These modules have their exports mangled, which splits each of them into a
// facade plus a `<locals>` module (see `EcmascriptExports::split_locals_and_reexports`); the
// bindings live on the locals module, and the facade only re-exposes them under their original
// names.
//
// That re-exposure is unconditionally a getter -- a facade forwards a name it does not own, so it
// cannot know the binding is never reassigned. Asserting on the namespace object of `import * as`
// therefore only ever observes the facade and says nothing about the optimization. These tests
// reach past it to the locals module, which is what actually decides value-vs-getter.
function localsNamespaceOf(fileName) {
const suffix = `exports/live/input/${fileName} [test] (ecmascript) <locals>`
const id = Array.from(__turbopack_modules__.keys()).find((m) =>
m.endsWith(suffix)
)
// Not a soft check: without the split there is no locals module to inspect, and every
// assertion below would be silently testing the facade instead.
expect(id).toEqual(expect.stringContaining(suffix))
return __turbopack_import__(id)
}
it('exported bindings that are not mutated are not live', () => {
expect(
Object.getOwnPropertyDescriptor(liveExports, 'obviouslyneverMutated')
).toEqual({
configurable: false,
enumerable: true,
value: 'obviouslyneverMutated',
writable: false,
})
expect(Object.getOwnPropertyDescriptor(liveExports, 'neverMutated')).toEqual({
configurable: false,
enumerable: true,
value: 'neverMutated',
writable: false,
})
expect(
Object.getOwnPropertyDescriptor(constDefaultExportFunction, 'default')
).toEqual({
configurable: false,
enumerable: true,
value: constDefaultExportFunction.default,
writable: false,
})
const locals = localsNamespaceOf('live_exports.js')
// Mangled keys, so look up what each original name was emitted as.
const info = liveExports.exportsInfo
expectValue(locals, info.neverMutated.mangledName, 'neverMutated')
expectValue(
locals,
info.obviouslyneverMutated.mangledName,
'obviouslyneverMutated'
)
// `const_default_export_function.js` exports only `default`, and a module with a single export
// to mangle always emits it under the same fixed key, so its namespace has exactly one own
// enumerable property and no lookup table is needed to find it.
const constDefaultLocals = localsNamespaceOf(
'const_default_export_function.js'
)
const keys = Object.keys(constDefaultLocals)
expect(keys).toHaveLength(1)
expectValue(constDefaultLocals, keys[0], expect.any(Function))
// The values are still reachable under the original names through the facade.
expect(liveExports.neverMutated).toBe('neverMutated')
expect(liveExports.obviouslyneverMutated).toBe('obviouslyneverMutated')
expect(constDefaultExportFunction.default).toEqual(expect.any(Function))
})
it('exported bindings that are free vars are live', () => {
expectGetter(liveExports, 'g')
// Reading `g` here is also what keeps it alive: export usage is tracked per name, so an export
// this file never mentions is dropped from the locals module altogether and would have no
// descriptor left to inspect.
expect(liveExports.g).toBe(globalThis)
const locals = localsNamespaceOf('live_exports.js')
expectGetter(locals, liveExports.exportsInfo.g.mangledName)
})
function expectValue(ns, propName, value) {
expect(Object.getOwnPropertyDescriptor(ns, propName)).toEqual({
value,
writable: false,
enumerable: true,
configurable: false,
})
}
function expectGetter(ns, propName) {
const gDesc = Object.getOwnPropertyDescriptor(ns, propName)
expect(gDesc).toEqual(
const desc = Object.getOwnPropertyDescriptor(ns, propName)
expect(desc).toEqual(
expect.objectContaining({
enumerable: true,
configurable: false,
set: undefined,
})
)
expect(gDesc).toHaveProperty('get')
expect(desc).toHaveProperty('get')
}
......@@ -25,3 +25,10 @@ export default function defaultFunction() {
export function setDefaultFunction(f) {
defaultFunction = f
}
// Test-only. `index.js` inspects this module's *locals* module directly (see the comment there),
// whose export keys are mangled. `__webpack_exports_info__` is the only way to learn which key an
// original export name ended up under: it is keyed by the original names and reports each one's
// emitted key as `mangledName`. Evaluated here rather than in `index.js` because it always
// describes the exports of the module it appears in.
export const exportsInfo = __webpack_exports_info__
......@@ -8,9 +8,10 @@ it('should keep a CommonJS consumer of an ESM module working', () => {
expect(someLongExportName).toBe('esm-1')
})
it('should not mangle a module that a CommonJS module requires', () => {
// The `esm.someLongExportName` accesses in `cjs-consumer.js` are user source, so the names have
// to stay as written.
expect(exportsInfo.someLongExportName.canMangle).toBe(false)
it('should keep a CommonJS consumer working against a mangled module', () => {
// The `esm.someLongExportName` accesses in `cjs-consumer.js` are user source, so what the
// CommonJS module receives has to keep carrying the original names. It does: the facade
// materializes them, forwarding to the mangled keys of the locals module underneath.
expect(exportsInfo.someLongExportName.canMangle).toBe(true)
expect(keys()).toContain('someLongExportName')
})
......@@ -21,12 +21,16 @@ it('should handle `default` when destructuring a namespace', () => {
expect(value).toBe('default-value')
})
it('should back off for a module read through a namespace binding', () => {
// Reads through an `import * as ns` binding are reported as a *partial namespace object*: we
// know which names are used, but not whether every read was lowered to a direct named access,
// and a read that wasn't (a destructuring pattern, say) still uses the original name. So the
// module keeps its names. Distinguishing lowered reads from a materialized namespace object is
// a follow-up; it would unlock mangling for namespace-imported modules too.
expect(mod.exportsInfo.aVeryLongExportName.canMangle).toBe(false)
expect(mod.exportsInfo.aVeryLongExportName.mangledName).toBe(null)
it('should mangle a module read through a namespace binding', () => {
// A namespace-imported module is still mangled internally. The facade keeps the original names
// for whoever reads the namespace object, and forwards them to the mangled keys of the locals
// module — so the reads above (member access, destructuring, `default`) all stay correct while
// the emitted keys get shorter.
expect(mod.exportsInfo.aVeryLongExportName.canMangle).toBe(true)
expect(mod.exportsInfo.aVeryLongExportName.mangledName).toEqual(
expect.any(String)
)
expect(
mod.exportsInfo.aVeryLongExportName.mangledName.length
).toBeLessThanOrEqual(2)
})
import { getEnums } from './provider'
import { multiHopExportsInfo, readMultiHopDiamond } from './multi-hop-provider'
import {
multiHopExportsInfo,
readMultiHopDiamond,
enumerateMultiHopNamespace,
readMultiHopByComputedKey,
} from './multi-hop-provider'
import { readForwardedNamespace } from './forwarded-provider'
import {
forwardedExportsInfo,
......@@ -59,8 +64,21 @@ it('should preserve namespace reads through an export-star forwarding edge', ()
it('should preserve namespace names through a multi-hop diamond', () => {
expect(readMultiHopDiamond()).toEqual(['multi-hop', 'multi-hop'])
expect(multiHopExportsInfo.veryLongMultiHopExportName.canMangle).toBe(false)
expect(multiHopExportsInfo.veryLongMultiHopExportName.mangledName).toBeNull()
// The materialized facade preserves the original public name, so the locals module remains
// mangleable even though the namespace escapes through multiple forwarding edges.
expect(multiHopExportsInfo.veryLongMultiHopExportName.canMangle).toBe(true)
expect(multiHopExportsInfo.veryLongMultiHopExportName.mangledName).not.toBe(
'veryLongMultiHopExportName'
)
// The escaped namespace must still expose the ORIGINAL names, both by enumeration and by
// dynamic (non-statically-analyzable) key access.
expect(enumerateMultiHopNamespace()).toEqual([
'multiHopExportsInfo',
'veryLongMultiHopExportName',
])
expect(readMultiHopByComputedKey('veryLongMultiHopExportName')).toBe(
'multi-hop'
)
})
it('should still mangle ordinary named reads through an export-star forwarding edge', () => {
......
......@@ -7,3 +7,11 @@ export function readMultiHopDiamond() {
const { veryLongMultiHopExportName } = namespacePath
return [veryLongMultiHopExportName, namedPath]
}
export function enumerateMultiHopNamespace() {
return Object.keys(namespacePath).sort()
}
export function readMultiHopByComputedKey(key) {
return namespacePath[key]
}
it('should keep the names of a module imported with webpackExports', async () => {
it('should mangle a module imported with webpackExports', async () => {
const { usedName, exportsInfo } = await import(
/* webpackExports: ["usedName", "exportsInfo"] */ './lazy'
)
expect(usedName).toBe('used')
// The magic comment narrows which exports are *used*, but the namespace object still exposes
// them under their original names, so the module has to back off.
expect(exportsInfo.usedName.canMangle).toBe(false)
expect(exportsInfo.usedName.mangledName).toBe(null)
// The magic comment narrows which exports are used. The module is still mangled internally —
// the namespace object the `import()` resolves to is materialized by the facade under the
// original names, forwarding to the mangled keys.
expect(exportsInfo.usedName.canMangle).toBe(true)
expect(exportsInfo.usedName.mangledName).toEqual(expect.any(String))
expect(exportsInfo.usedName.mangledName).not.toBe('usedName')
})
it('should keep the names of a module imported with turbopackExports', async () => {
it('should mangle a module imported with turbopackExports', async () => {
const ns = await import(
/* turbopackExports: ["otherUsedName", "exportsInfo"] */ './lazy'
)
expect(ns.otherUsedName).toBe('other-used')
expect(ns.exportsInfo.otherUsedName.canMangle).toBe(false)
expect(ns.exportsInfo.otherUsedName.canMangle).toBe(true)
})
it('should keep a plain dynamic import working', async () => {
const ns = await import('./lazy')
expect(ns.usedName).toBe('used')
// The materialized namespace object still exposes the original names.
expect(Object.keys(ns)).toContain('usedName')
})
......@@ -31,10 +31,12 @@ it('should keep all 60 values correct through the mangled keys', () => {
expect(values()).toEqual(expected)
})
it('should keep the names of a module read with a computed key', () => {
it('should keep computed-key reads working on a mangled module', () => {
for (let i = 0; i < 60; i++) {
const n = String(i).padStart(2, '0')
expect(manyAsNamespace[`exportNumber${n}`]).toBe(`value-${n}`)
}
expect(manyAsNamespace.exportsInfo.exportNumber00.canMangle).toBe(false)
// The module is mangled internally, but the computed reads go through the namespace object the
// facade materializes, which still carries every original name.
expect(manyAsNamespace.exportsInfo.exportNumber00.canMangle).toBe(true)
})
// NOT IMPLEMENTED YET — this fixture is expected to fail.
// A module whose namespace object escapes is still mangled, the way webpack does it: the internal
// export keys are shortened, and the namespace object handed to user code is *materialized* by the
// facade, mapping the original names onto those keys. One `import * as ns` in a dependency no
// longer un-mangles the whole module.
//
// Turbopack currently backs off completely when a namespace object of a module escapes: the module
// keeps its original export keys. Webpack does better — it keeps mangling the internal keys and
// *materializes* a namespace object that maps the original names onto them, so one `import * as ns`
// in a dependency no longer un-mangles the whole module.
//
// See webpack's `test/configCases/mangle/mangle-escaping-namespace`, which asserts both halves:
// Compare webpack's `test/configCases/mangle/mangle-escaping-namespace`, which asserts both halves:
// the raw export is not defined under its original name, and the materialized namespace object
// exposes the original name.
//
// What blocks it today is *export usage*, not module structure. When the namespace object genuinely
// escapes (`export const getEnums = () => ns`), the analysis cannot enumerate the reads, so the
// module's usage widens to `ModuleExportUsageInfo::All` and mangling backs off on that. Forcing the
// facade / locals split for mangled modules does not help: the widened usage propagates through the
// facade to the locals module, so both keep their original keys. Materialization needs the facade to
// pin the original names *while* declaring a known, named usage of the locals module.
//
// Lives under `__skipped__`, so the harness asserts it still fails. When materialization is
// implemented this fixture starts passing, the suite goes red, and it should be moved out of
// `__skipped__`.
import { getEnums } from './provider'
......@@ -35,8 +22,7 @@ it('should still mangle a module whose namespace escapes', () => {
'exportsInfo',
])
// ...while the module's own export keys are still shortened. This is the part that isn't
// implemented: today `canMangle` is false here because we back off instead.
// ...while the module's own export keys are shortened underneath.
expect(ns.exportsInfo.ENUM_A.canMangle).toBe(true)
expect(ns.exportsInfo.ENUM_A.mangledName).not.toBe('ENUM_A')
expect(ns.exportsInfo.ENUM_B.mangledName).not.toBe(
......
function callable() {
return 'called'
}
callable.named = 'named'
module.exports = callable
const ns = require('./consumer.cjs')
it('re-exports from a callable CommonJS namespace', () => {
expect(ns.default()).toBe('called')
expect(ns.named).toBe('named')
expect(globalThis.callableNamespaceAfter).toBe(true)
})
......@@ -3,9 +3,12 @@ import { Used } from './a.ts'
it('should retain PURE comments with scope hoisting', () => {
expect(Used.THIS_IS_USED).toBe(0)
// Matched with `includes` rather than `endsWith` so this finds the module whether or not it was
// split: export mangling splits a module with exports into a facade plus a `<locals>` module, and
// the code under test here lives in the latter, whose ident carries a ` <locals>` suffix.
let factory = __turbopack_modules__.get(
[...__turbopack_modules__.keys()].find((m) =>
m.endsWith('scope-hoisting/pure-comments/input/a.ts [test] (ecmascript)')
m.includes('scope-hoisting/pure-comments/input/a.ts [test] (ecmascript)')
)
)
......
......@@ -5,7 +5,5 @@ b.c()
import { modules } from 'dep/trackModules.js'
it('should not contain side-effect-free modules', () => {
// TODO: webpack can trim 'b'. The issue is that turbopack cannot follow namespace re-exports
// when it is tree shaking exports.
expect(modules).toEqual(['b', 'c'])
expect(modules).toEqual(['c'])
})
(()=>{"use strict";module.exports=["[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/escaping-namespace/input/escaping.js [test] (ecmascript)",s=>{s.S(["[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/escaping-namespace/input/escaping.js [test] (ecmascript) <locals>","anotherLongExportName,T,someLongExportName,z"])},"[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/escaping-namespace/input/escaping.js [test] (ecmascript) <locals>",s=>{s.s(["T",0,"long-2","z",0,"long-1"])},"[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/escaping-namespace/input/index.js [test] (ecmascript)",s=>{var t=s.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/escaping-namespace/input/escaping.js [test] (ecmascript)"),e=s.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/escaping-namespace/input/mangled.js [test] (ecmascript) <locals>");console.log(t,e.z,e.T),s.s([])},"[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/escaping-namespace/input/mangled.js [test] (ecmascript) <locals>",s=>{s.s(["T",0,"mangled-2","z",0,"mangled-1"])}]})();
//# sourceMappingURL=1jsg_tests_snapshot_mangle-exports_escaping-namespace_input_1bvx6nn6m4t6e._.js.map
\ No newline at end of file
{"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/escaping-namespace/input/escaping.js","turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/escaping-namespace/input/index.js","turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/escaping-namespace/input/mangled.js"],"sourcesContent":["// A namespace object of this module escapes, so it keeps its original export names.\nexport const someLongExportName = 'long-1'\nexport const anotherLongExportName = 'long-2'\n","import * as escaping from './escaping.js'\nimport { someLongExportName, anotherLongExportName } from './mangled.js'\n\nconst leak = () => escaping\n\nconsole.log(leak(), someLongExportName, anotherLongExportName)\n","// Nothing escapes here, so this module in the same graph is still mangled.\nexport const someLongExportName = 'mangled-1'\nexport const anotherLongExportName = 'mangled-2'\n"],"names":["someLongExportName","anotherLongExportName","leak","imported module [project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/escaping-namespace/input/escaping.js [test] (ecmascript)","console","log"],"mappings":"0MAEqC,gCADH,iJCDlC,IAAA,EAAA,EAAA,CAAA,CAAA,qIACA,EAAA,EAAA,CAAA,CAAA,oIAIAI,QAAQC,GAAG,CAFQF,AAEPD,EAAQ,EAAA,CAAkB,CAAE,EAAA,CAAqB,6JCHxB,kBADH"}
\ No newline at end of file
{"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/escaping-namespace/input/escaping.js","turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/escaping-namespace/input/index.js","turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/escaping-namespace/input/mangled.js"],"sourcesContent":["// A namespace object of this module escapes, so it keeps its original export names.\nexport const someLongExportName = 'long-1'\nexport const anotherLongExportName = 'long-2'\n","import * as escaping from './escaping.js'\nimport { someLongExportName, anotherLongExportName } from './mangled.js'\n\nconst leak = () => escaping\n\nconsole.log(leak(), someLongExportName, anotherLongExportName)\n","// Nothing escapes here, so this module in the same graph is still mangled.\nexport const someLongExportName = 'mangled-1'\nexport const anotherLongExportName = 'mangled-2'\n"],"names":["someLongExportName","anotherLongExportName","leak","imported module [project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/escaping-namespace/input/escaping.js [test] (ecmascript)","console","log"],"mappings":"2gBAEqC,eADH,iJCDlC,IAAA,EAAA,EAAA,CAAA,CAAA,qIACA,EAAA,EAAA,CAAA,CAAA,6IAIAI,QAAQC,GAAG,CAFQF,AAEPD,EAAQ,EAAA,CAAkB,CAAE,EAAA,CAAqB,sKCHxB,kBADH"}
\ No newline at end of file
(()=>{"use strict";module.exports=["[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/escaping-namespace/input/escaping.js [test] (ecmascript)",t=>{t.s(["anotherLongExportName",0,"long-2","someLongExportName",0,"long-1"])},"[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/escaping-namespace/input/index.js [test] (ecmascript)",t=>{var s=t.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/escaping-namespace/input/escaping.js [test] (ecmascript)"),e=t.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/escaping-namespace/input/mangled.js [test] (ecmascript)");console.log(s,e.z,e.T),t.s([])},"[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/escaping-namespace/input/mangled.js [test] (ecmascript)",t=>{t.s(["T",0,"mangled-2","z",0,"mangled-1"])}]})();
//# sourceMappingURL=1jsg_tests_snapshot_mangle-exports_escaping-namespace_input_1ysta134r3dyz._.js.map
\ No newline at end of file
var R=require("./[turbopack]_runtime.js")("output/index.entry.js")
R.c("output/1jsg_tests_snapshot_mangle-exports_escaping-namespace_input_1ysta134r3dyz._.js")
R.c("output/1jsg_tests_snapshot_mangle-exports_escaping-namespace_input_1bvx6nn6m4t6e._.js")
R.m("[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/escaping-namespace/input/index.js [test] (ecmascript)")
module.exports=R.m("[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/escaping-namespace/input/index.js [test] (ecmascript)").exports
\ No newline at end of file
(()=>{"use strict";module.exports=["[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/named-and-preserved/input/index.js [test] (ecmascript)",t=>{var e=t.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/named-and-preserved/input/lib.js [test] (ecmascript)");console.log(e.a,e.$,e.z,e.T,(0,e.X)()),t.s([])},"[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/named-and-preserved/input/lib.js [test] (ecmascript)",t=>{t.s(["a",0,"a","X",0,function(){return"fn"},"T",0,"long-2","$",0,"bb","z",0,"long-1"])}]})();
(()=>{"use strict";module.exports=["[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/named-and-preserved/input/index.js [test] (ecmascript)",t=>{var s=t.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/named-and-preserved/input/lib.js [test] (ecmascript) <locals>");console.log(s.a,s.$,s.z,s.T,(0,s.X)()),t.s([])},"[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/named-and-preserved/input/lib.js [test] (ecmascript) <locals>",t=>{t.s(["a",0,"a","X",0,function(){return"fn"},"T",0,"long-2","$",0,"bb","z",0,"long-1"])}]})();
//# sourceMappingURL=1jsg_tests_snapshot_mangle-exports_named-and-preserved_input_0pbreftkp_5pc._.js.map
\ No newline at end of file
//# sourceMappingURL=1jsg_tests_snapshot_mangle-exports_named-and-preserved_input_1si6yfvbtud7_._.js.map
\ No newline at end of file
{"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/named-and-preserved/input/index.js","turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/named-and-preserved/input/lib.js"],"sourcesContent":["import {\n a,\n bb,\n someLongExportName,\n anotherLongExportName,\n aLongFunctionName,\n} from './lib.js'\n\nconsole.log(\n a,\n bb,\n someLongExportName,\n anotherLongExportName,\n aLongFunctionName()\n)\n","export const a = 'a'\nexport const bb = 'bb'\nexport const someLongExportName = 'long-1'\nexport const anotherLongExportName = 'long-2'\nexport const unusedLongExportName = 'unused'\n\nexport function aLongFunctionName() {\n return 'fn'\n}\n"],"names":["console","log","a","bb","someLongExportName","anotherLongExportName","unusedLongExportName","aLongFunctionName"],"mappings":"yKAAA,IAAA,EAAA,EAAA,CAAA,CAAA,iIAQAA,QAAQC,GAAG,CACT,EAAA,CAAC,CACD,EAAA,CAAE,CACF,EAAA,CAAkB,CAClB,EAAA,CAAqB,CACrB,CAAA,EAAA,EAAA,CAAA,AAAiB,6JCbF,UAMV,SAASM,EACd,MAAO,IACT,QALqC,eAFnB,WACgB"}
\ No newline at end of file
{"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/named-and-preserved/input/index.js","turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/named-and-preserved/input/lib.js"],"sourcesContent":["import {\n a,\n bb,\n someLongExportName,\n anotherLongExportName,\n aLongFunctionName,\n} from './lib.js'\n\nconsole.log(\n a,\n bb,\n someLongExportName,\n anotherLongExportName,\n aLongFunctionName()\n)\n","export const a = 'a'\nexport const bb = 'bb'\nexport const someLongExportName = 'long-1'\nexport const anotherLongExportName = 'long-2'\nexport const unusedLongExportName = 'unused'\n\nexport function aLongFunctionName() {\n return 'fn'\n}\n"],"names":["console","log","a","bb","someLongExportName","anotherLongExportName","unusedLongExportName","aLongFunctionName"],"mappings":"yKAAA,IAAA,EAAA,EAAA,CAAA,CAAA,0IAQAA,QAAQC,GAAG,CACT,EAAA,CAAC,CACD,EAAA,CAAE,CACF,EAAA,CAAkB,CAClB,EAAA,CAAqB,CACrB,CAAA,EAAA,EAAA,CAAA,AAAiB,sKCbF,UAMV,SAASM,EACd,MAAO,IACT,QALqC,eAFnB,WACgB"}
\ No newline at end of file
var R=require("./[turbopack]_runtime.js")("output/index.entry.js")
R.c("output/1jsg_tests_snapshot_mangle-exports_named-and-preserved_input_0pbreftkp_5pc._.js")
R.c("output/1jsg_tests_snapshot_mangle-exports_named-and-preserved_input_1si6yfvbtud7_._.js")
R.m("[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/named-and-preserved/input/index.js [test] (ecmascript)")
module.exports=R.m("[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/named-and-preserved/input/index.js [test] (ecmascript)").exports
\ No newline at end of file
(()=>{"use strict";module.exports=["[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/single-export/input/index.js [test] (ecmascript)",t=>{console.log((0,t.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/single-export/input/lone.js [test] (ecmascript)").f)()),t.s([])},"[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/single-export/input/lone.js [test] (ecmascript)",t=>{t.s(["f",0,function(){return"lone"}])}]})();
(()=>{"use strict";module.exports=["[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/single-export/input/index.js [test] (ecmascript)",t=>{console.log((0,t.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/single-export/input/lone.js [test] (ecmascript) <locals>").f)()),t.s([])},"[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/single-export/input/lone.js [test] (ecmascript) <locals>",t=>{t.s(["f",0,function(){return"lone"}])}]})();
//# sourceMappingURL=0_9x_turbopack-tests_tests_snapshot_mangle-exports_single-export_input_1mf78g4ogdhgv._.js.map
\ No newline at end of file
//# sourceMappingURL=0_9x_turbopack-tests_tests_snapshot_mangle-exports_single-export_input_1xad2kk3iii3x._.js.map
\ No newline at end of file
{"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/single-export/input/index.js","turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/single-export/input/lone.js"],"sourcesContent":["import { aLongFunctionNameNobodyWantsInTheBundle } from './lone'\n\nconsole.log(aLongFunctionNameNobodyWantsInTheBundle())\n","// The only export of this module. It is emitted under the fixed single-export key rather than a\n// hashed one, so that every single-export module in the graph produces the same `.f` byte sequence\n// and gzip can share it. Visible in the committed output below.\nexport function aLongFunctionNameNobodyWantsInTheBundle() {\n return 'lone'\n}\n"],"names":["console","log","aLongFunctionNameNobodyWantsInTheBundle"],"mappings":"mKAEAA,QAAQC,GAAG,CAAC,CAAA,EAFZ,AAEY,EAFZ,CAAA,CAAA,4HAEY,CAAA,AAAuC,wJCC5C,SAASC,EACd,MAAO,MACT"}
\ No newline at end of file
{"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/single-export/input/index.js","turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/single-export/input/lone.js"],"sourcesContent":["import { aLongFunctionNameNobodyWantsInTheBundle } from './lone'\n\nconsole.log(aLongFunctionNameNobodyWantsInTheBundle())\n","// The only export of this module. It is emitted under the fixed single-export key rather than a\n// hashed one, so that every single-export module in the graph produces the same `.f` byte sequence\n// and gzip can share it. Visible in the committed output below.\nexport function aLongFunctionNameNobodyWantsInTheBundle() {\n return 'lone'\n}\n"],"names":["console","log","aLongFunctionNameNobodyWantsInTheBundle"],"mappings":"mKAEAA,QAAQC,GAAG,CAAC,CAAA,EAFZ,AAEY,EAFZ,CAAA,CAAA,qIAEY,CAAA,AAAuC,iKCC5C,SAASC,EACd,MAAO,MACT"}
\ No newline at end of file
var R=require("./[turbopack]_runtime.js")("output/index.entry.js")
R.c("output/0_9x_turbopack-tests_tests_snapshot_mangle-exports_single-export_input_1mf78g4ogdhgv._.js")
R.c("output/0_9x_turbopack-tests_tests_snapshot_mangle-exports_single-export_input_1xad2kk3iii3x._.js")
R.m("[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/single-export/input/index.js [test] (ecmascript)")
module.exports=R.m("[project]/turbopack/crates/turbopack-tests/tests/snapshot/mangle-exports/single-export/input/index.js [test] (ecmascript)").exports
\ No newline at end of file
......@@ -15,13 +15,11 @@ __turbopack_context__.s([
"x",
()=>__TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$reexport$2d$registration$2f$facade$2d$scope$2d$hoisted$2d$shared$2f$input$2f$x$2e$js__$5b$test$5d$__$28$ecmascript$29$__["x"]
], "[project]/turbopack/crates/turbopack-tests/tests/snapshot/reexport-registration/facade-scope-hoisted-shared/input/reexports.js [test] (ecmascript)");
__turbopack_context__.s([], "[project]/turbopack/crates/turbopack-tests/tests/snapshot/reexport-registration/facade-scope-hoisted-shared/input/reexports.js [test] (ecmascript) <locals>");
// MERGED MODULE: [project]/turbopack/crates/turbopack-tests/tests/snapshot/reexport-registration/facade-scope-hoisted-shared/input/reexports.js [test] (ecmascript)
;
// MERGED MODULE: [project]/turbopack/crates/turbopack-tests/tests/snapshot/reexport-registration/facade-scope-hoisted-shared/input/reexports.js [test] (ecmascript) <locals>
;
;
var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$reexport$2d$registration$2f$facade$2d$scope$2d$hoisted$2d$shared$2f$input$2f$reexports$2e$js__$5b$test$5d$__$28$ecmascript$29$__$3c$locals$3e$__ = __turbopack_context__.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/reexport-registration/facade-scope-hoisted-shared/input/reexports.js [test] (ecmascript) <locals>");
var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$reexport$2d$registration$2f$facade$2d$scope$2d$hoisted$2d$shared$2f$input$2f$x$2e$js__$5b$test$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/reexport-registration/facade-scope-hoisted-shared/input/x.js [test] (ecmascript)");
}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/reexport-registration/facade-scope-hoisted-shared/input/x.js [test] (ecmascript)", ((__turbopack_context__) => {
......
......@@ -4,5 +4,5 @@
"sections": [
{"offset": {"line": 4, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/reexport-registration/facade-scope-hoisted-shared/input/index.js"],"sourcesContent":["import * as source from './x'\n\nconsole.log(source)\nimport('./reexports').then((namespace) => console.log(namespace))\n"],"names":["console","log","imported module [project]/turbopack/crates/turbopack-tests/tests/snapshot/reexport-registration/facade-scope-hoisted-shared/input/x.js [test] (ecmascript)","then","namespace"],"mappings":";AAAA;;AAEAA,QAAQC,GAAG,CAACC;AACZ,0MAAsBC,IAAI,CAAC,CAACC,YAAcJ,QAAQC,GAAG,CAACG"}},
{"offset": {"line": 13, "column": 0}, "map": {"version":3,"sources":[],"names":[],"mappings":""}},
{"offset": {"line": 29, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/reexport-registration/facade-scope-hoisted-shared/input/x.js"],"sourcesContent":["export const x = 'x'\n"],"names":["x"],"mappings":";;;;AAAO,MAAMA,IAAI"}}]
{"offset": {"line": 27, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/reexport-registration/facade-scope-hoisted-shared/input/x.js"],"sourcesContent":["export const x = 'x'\n"],"names":["x"],"mappings":";;;;AAAO,MAAMA,IAAI"}}]
}
\ 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