Unverified Commit 4bb6fc4b authored by Sam Poder's avatar Sam Poder Committed by GitHub

[turbopack] Forward usage information across re-exports (#96282)

## What?

This PR improves tree-shaking across whole-namespace re-exports. It is
the middle PR in the stack: #98680 provides the independently reviewable
`EsmAssetReferenceOptions` constructor refactor requested during review,
and #96396 builds on this PR to narrow static member reads on
namespace-valued named exports.

A representative case is a CommonJS re-export followed by an ESM star
barrel:

```js
// index.js
const { m } = require('./cjs')

// cjs.js
module.exports = require('./barrel') // CJS re-export

// barrel.js
export * from './base' // ESM star barrel

// base.js
export const m = 1
export const n = 2 // nobody ever uses this
```

Only `m` is observed by the entrypoint, so that usage can now flow
through both re-export layers to `base.js` and allow `n` to be removed.

## Why?

Turbopack now has a generic `ExportUsage::Passthrough` mechanism,
introduced on `canary` for client-component and Next.js module proxies.
It carries the referencing module's accumulated used-export set into a
transparent target.

However, CommonJS whole-module forwarding and ordinary ESM star barrels
do not opt into that mechanism. Applying this PR's tests to plain
`canary` showed that all runtime values are already correct, but unused
exports remain retained in four important shapes:

- an ESM named consumer through `module.exports = require(ESM)`;
- a deep CommonJS forwarding chain;
- CommonJS forwarding into an ESM `export *` barrel;
- a CommonJS diamond with disjoint used exports.

This PR therefore remains a tree-shaking precision change rather than
introducing a second forwarding model.

There is also an independent name-observability concern. A CommonJS
forwarder exposes a raw namespace object's properties under their
original names, while named consumers of an ESM `export *` can be
rewritten if an export is mangled. Namespace provenance must survive
multiple passthrough hops without unnecessarily disabling mangling for
ordinary ESM named forwarding.

## How?

### Configure forwarding at construction time

#98680 replaces `EsmAssetReference`'s positional behavior arguments with
`EsmAssetReferenceOptions`. This PR extends that options object with an
optional passthrough mode. ESM star references receive `Some(false)`
directly when constructed; free-variable references receive `None`; and
the existing annotation-driven client-proxy path still contributes
`Some(true)`.

The two sources merge conservatively: an annotation that exposes the
namespace's original names cannot be weakened by a syntax-driven
`Some(false)` on the same reference. The former mutating
`mark_namespace_reexport()` API is removed.

### Reuse the generic passthrough fixed point

The implementation uses canary's existing model:

```rust
ExportUsage::Passthrough {
    namespace_object_may_escape: bool,
}
```

The boolean describes whether the edge itself exposes the target
namespace's original property names:

- `module.exports = require('…')` records `Passthrough {
namespace_object_may_escape: true }` directly in the existing CommonJS
import-usage map;
- `export * from '…'` records `Passthrough {
namespace_object_may_escape: false }`, because statically known ESM
consumers can be rewritten when target exports are mangled.

No parallel `TargetExportUsage` type, graph field, call parameter, or
second fixed-point implementation is added.

Detection is limited to a simple assignment using the unresolved/global
`module` and `require` bindings. Shadowed bindings, member requires, and
compound assignments retain their existing behavior.

### Propagate keys and namespace provenance independently

A passthrough edge merges the parent module's resolved `Evaluation`,
`Exports`, or `All` state into its target. The merge remains monotonic
and idempotent, so chains, cycles, and diamonds converge.

Namespace provenance is carried independently of the used key set:

- an edge with `namespace_object_may_escape: true` makes the target's
original names observable;
- every passthrough also carries namespace provenance that already
reached its parent;
- a newly propagated provenance bit retriggers traversal even when the
used key set did not change.

This preserves original names through multi-hop namespace reads while
keeping unrelated ordinary named exports mangleable. Passthrough
references are also exposed correctly to scope-hoisted merged modules.

## Testing

Enabled execution coverage includes:

- deep CommonJS chains, CommonJS → ESM star barrels, cycles, diamonds,
and overwrite behavior;
- ESM named/default/namespace import interop through `module.exports =
require(ESM)`;
- opaque whole-namespace and evaluation-only consumption, including
single evaluation;
- native `export *`, default/local-shadow filtering, and the
optimization-disabled mode;
- namespace provenance across forwarding edges and a multi-hop diamond;
- both mangling safety and non-pessimization for ordinary named
forwarding;
- shadowed `module`/`require`, member-require, and non-simple assignment
boundaries;
- runtime counterparts for every nested precision case that remains
skipped.

Known optimization-only limitations remain under
`__skipped__/deep-reexports`: nested `export * as` through CJS,
namespace-property unwrapping in a CJS assignment, depth-two nested
namespaces, and unwrapping after a forwarding hop. Their runtime
semantics are covered by the enabled
`reexport-forwarding-nested-runtime` fixture.

Verification on the rebased stack:

- plain-canary reassessment: 7/9 fixtures, with only four expected
precision failures;
- integrated bottom layer: 9/9 forwarding fixtures;
- passthrough unit tests: 2/2, plus the six-case construction-option
merge lattice;
- combined stack: 14/14 focused execution/snapshot tests and 60/60
analyzer graph tests;
- affected Cargo checks, `next-core` check, `build-all`, and the
forwarding/namespace HMR test pass.

<!-- 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 7c87468a
...@@ -270,17 +270,25 @@ pub async fn compute_binding_usage_info( ...@@ -270,17 +270,25 @@ pub async fn compute_binding_usage_info(
ExportUsage::Passthrough { ExportUsage::Passthrough {
namespace_object_may_escape, namespace_object_may_escape,
} => { } => {
if *namespace_object_may_escape { // Passthrough edges always carry namespace provenance that already reached
partial_namespace_modules.insert(target); // their parent. Some edges (for example a forwarded CommonJS namespace)
} // additionally expose the target's original property names themselves.
let namespace_changed = if *namespace_object_may_escape
|| partial_namespace_modules.contains(&parent)
{
partial_namespace_modules.insert(target)
} else {
false
};
let passthrough_usage = used_exports let passthrough_usage = used_exports
.get(&parent) .get(&parent)
.context("parent module must have usage info")? .context("parent module must have usage info")?
.clone(); .clone();
used_exports let usage_changed = used_exports
.entry(target) .entry(target)
.or_default() .or_default()
.add_usage_info(&passthrough_usage) .add_usage_info(&passthrough_usage);
namespace_changed || usage_changed
} }
export_usage => { export_usage => {
if matches!(export_usage, ExportUsage::PartialNamespaceObject(_)) { if matches!(export_usage, ExportUsage::PartialNamespaceObject(_)) {
...@@ -292,8 +300,8 @@ pub async fn compute_binding_usage_info( ...@@ -292,8 +300,8 @@ pub async fn compute_binding_usage_info(
} }
}; };
if changed || is_first_visit { if changed || is_first_visit {
// First visit, or the used exports changed. This can cause more imports to get // First visit, or the used exports/namespace provenance changed. Either can
// used downstream. // cause more imports to become used downstream.
Ok(GraphTraversalAction::Continue) Ok(GraphTraversalAction::Continue)
} else { } else {
Ok(GraphTraversalAction::Skip) Ok(GraphTraversalAction::Skip)
...@@ -485,13 +493,21 @@ mod tests { ...@@ -485,13 +493,21 @@ mod tests {
use crate::resolve::ExportUsage; use crate::resolve::ExportUsage;
#[test] #[test]
fn resolved_usage_merges_exports() { fn resolved_usage_join_is_monotonic() {
let mut usage = ModuleExportUsageInfo::Exports([rcstr!("first")].into_iter().collect()); let mut usage = ModuleExportUsageInfo::Evaluation;
let additional = ModuleExportUsageInfo::Exports([rcstr!("second")].into_iter().collect()); let first = ModuleExportUsageInfo::Exports([rcstr!("first")].into_iter().collect());
let second = ModuleExportUsageInfo::Exports([rcstr!("second")].into_iter().collect());
assert!(usage.add_usage_info(&additional)); assert!(!usage.add_usage_info(&ModuleExportUsageInfo::Evaluation));
assert!(usage.add_usage_info(&first));
assert!(usage.is_export_used(&rcstr!("first"))); assert!(usage.is_export_used(&rcstr!("first")));
assert!(!usage.add_usage_info(&first));
assert!(usage.add_usage_info(&second));
assert!(usage.is_export_used(&rcstr!("second"))); assert!(usage.is_export_used(&rcstr!("second")));
assert!(!usage.add_usage_info(&ModuleExportUsageInfo::Evaluation));
assert!(usage.add_usage_info(&ModuleExportUsageInfo::All));
assert!(!usage.add_usage_info(&second));
assert!(matches!(usage, ModuleExportUsageInfo::All));
} }
#[test] #[test]
......
...@@ -534,7 +534,9 @@ pub async fn compute_merged_modules(module_graph: Vc<ModuleGraph>) -> Result<Vc< ...@@ -534,7 +534,9 @@ pub async fn compute_merged_modules(module_graph: Vc<ModuleGraph>) -> Result<Vc<
if parent_info.is_some_and(|(_, r)| { if parent_info.is_some_and(|(_, r)| {
matches!( matches!(
r.binding_usage.export, r.binding_usage.export,
ExportUsage::All | ExportUsage::PartialNamespaceObject(_) ExportUsage::All
| ExportUsage::PartialNamespaceObject(_)
| ExportUsage::Passthrough { .. }
) )
}) { }) {
// This module needs to be exposed: // This module needs to be exposed:
......
...@@ -177,10 +177,13 @@ pub enum ExportUsage { ...@@ -177,10 +177,13 @@ pub enum ExportUsage {
/// Only side effects are used. /// Only side effects are used.
Evaluation, Evaluation,
/// Use the same exports that are used from the referencing module. This is used by transparent /// Use the same exports that are used from the referencing module. This is used by transparent
/// module proxies that forward their export surface to another module. /// module proxies and re-exports that forward their export surface to another module.
///
/// Namespace provenance that reached the referencing module is forwarded independently of the
/// used names. This keeps multi-hop namespace reads safe for export-name mangling.
Passthrough { Passthrough {
/// The forwarded exports are read through a namespace object, so their original names may /// Whether this edge itself exposes a namespace object's original property names, even if
/// be observed even when the individual used names are known. /// the referencing module was only consumed through statically known named exports.
namespace_object_may_escape: bool, namespace_object_may_escape: bool,
}, },
} }
......
...@@ -32,7 +32,7 @@ use crate::{ ...@@ -32,7 +32,7 @@ use crate::{
SpecifiedModuleType, SpecifiedModuleType,
analyzer::{ analyzer::{
Bump, ConstantString, ConstantValue, ObjectPart, Bump, ConstantString, ConstantValue, ObjectPart,
cjs_ast::is_global, cjs_ast::{is_global, is_module_dot_exports},
graph::{AssignmentScope, AssignmentScopes, EvalContext}, graph::{AssignmentScope, AssignmentScopes, EvalContext},
is_unresolved, is_unresolved_id, is_unresolved, is_unresolved_id,
}, },
...@@ -1533,6 +1533,22 @@ impl Visit for Analyzer<'_> { ...@@ -1533,6 +1533,22 @@ impl Visit for Analyzer<'_> {
node.visit_children_with(self); node.visit_children_with(self);
} }
fn visit_assign_expr(&mut self, node: &AssignExpr) {
if node.op == AssignOp::Assign
&& let AssignTarget::Simple(SimpleAssignTarget::Member(target)) = &node.left
&& is_module_dot_exports(target, self.unresolved_mark)
&& let Some(call) = as_require_call(&node.right, self.unresolved_mark)
{
self.data.cjs_imports.resolved.insert(
call.span.lo,
ExportUsage::Passthrough {
namespace_object_may_escape: true,
},
);
}
node.visit_children_with(self);
}
fn visit_expr_stmt(&mut self, node: &ExprStmt) { fn visit_expr_stmt(&mut self, node: &ExprStmt) {
// A bare `require("…")` statement discards its result → evaluation only. // A bare `require("…")` statement discards its result → evaluation only.
if let Some(call) = as_require_call(&node.expr, self.unresolved_mark) { if let Some(call) = as_require_call(&node.expr, self.unresolved_mark) {
......
...@@ -454,6 +454,9 @@ pub struct EsmAssetReferenceOptions { ...@@ -454,6 +454,9 @@ pub struct EsmAssetReferenceOptions {
pub import_usage: ImportUsage, pub import_usage: ImportUsage,
pub import_externals: bool, pub import_externals: bool,
pub module_fragments_enabled: bool, pub module_fragments_enabled: bool,
/// Explicit export-usage passthrough mode for syntax-driven forwarding. `Some(false)` forwards
/// used names without exposing the target namespace's original property names.
pub export_usage_passthrough: Option<bool>,
pub resolve_override: Option<ResolvedVc<Box<dyn Module>>>, pub resolve_override: Option<ResolvedVc<Box<dyn Module>>>,
} }
...@@ -484,17 +487,28 @@ struct EsmReferenceExtras { ...@@ -484,17 +487,28 @@ struct EsmReferenceExtras {
module_type: Option<RcStr>, module_type: Option<RcStr>,
/// The chunking-type annotation (drives `chunking_type`). /// The chunking-type annotation (drives `chunking_type`).
chunking_type: Option<SpecifiedChunkingType>, chunking_type: Option<SpecifiedChunkingType>,
/// Whether the importing module's used exports should be forwarded to the target. /// Whether the importing module's used exports should be forwarded to the target. The boolean
export_usage_passthrough: bool, /// records whether this edge itself exposes the target namespace's original property names.
export_usage_passthrough: Option<bool>,
/// A module to resolve to directly, bypassing resolution (from a matched inner asset). /// A module to resolve to directly, bypassing resolution (from a matched inner asset).
resolve_override: Option<ResolvedVc<Box<dyn Module>>>, resolve_override: Option<ResolvedVc<Box<dyn Module>>>,
} }
fn merge_export_usage_passthrough(
explicit: Option<bool>,
annotation_passthrough: bool,
) -> Option<bool> {
// An annotation is an explicit request to expose the namespace's original names, so it must
// not be weakened by a syntax-driven passthrough mode on the same reference.
annotation_passthrough.then_some(true).or(explicit)
}
impl EsmReferenceExtras { impl EsmReferenceExtras {
/// Builds the extras from import annotations and a resolve override, returning `None` (rather /// Builds the extras from import annotations and a resolve override, returning `None` (rather
/// than an all-empty box) when nothing relevant is present — the common case. /// than an all-empty box) when nothing relevant is present — the common case.
fn new( fn new(
annotations: Option<&ImportAnnotations>, annotations: Option<&ImportAnnotations>,
export_usage_passthrough: Option<bool>,
resolve_override: Option<ResolvedVc<Box<dyn Module>>>, resolve_override: Option<ResolvedVc<Box<dyn Module>>>,
) -> Option<Box<Self>> { ) -> Option<Box<Self>> {
let extras = EsmReferenceExtras { let extras = EsmReferenceExtras {
...@@ -505,13 +519,40 @@ impl EsmReferenceExtras { ...@@ -505,13 +519,40 @@ impl EsmReferenceExtras {
.and_then(|a| a.module_type()) .and_then(|a| a.module_type())
.map(|m| RcStr::from(&*m.to_string_lossy())), .map(|m| RcStr::from(&*m.to_string_lossy())),
chunking_type: annotations.and_then(|a| a.chunking_type()), chunking_type: annotations.and_then(|a| a.chunking_type()),
export_usage_passthrough: annotations.is_some_and(|a| a.export_usage_passthrough()), export_usage_passthrough: merge_export_usage_passthrough(
export_usage_passthrough,
annotations.is_some_and(|a| a.export_usage_passthrough()),
),
resolve_override, resolve_override,
}; };
(extras != EsmReferenceExtras::default()).then(|| Box::new(extras)) (extras != EsmReferenceExtras::default()).then(|| Box::new(extras))
} }
} }
#[cfg(test)]
mod tests {
use super::merge_export_usage_passthrough;
#[test]
fn annotation_passthrough_cannot_be_weakened() {
assert_eq!(merge_export_usage_passthrough(None, false), None);
assert_eq!(
merge_export_usage_passthrough(Some(false), false),
Some(false)
);
assert_eq!(
merge_export_usage_passthrough(Some(true), false),
Some(true)
);
assert_eq!(merge_export_usage_passthrough(None, true), Some(true));
assert_eq!(
merge_export_usage_passthrough(Some(false), true),
Some(true)
);
assert_eq!(merge_export_usage_passthrough(Some(true), true), Some(true));
}
}
impl EsmAssetReference { impl EsmAssetReference {
async fn new_inner( async fn new_inner(
module: ResolvedVc<EcmascriptModuleAsset>, module: ResolvedVc<EcmascriptModuleAsset>,
...@@ -527,6 +568,7 @@ impl EsmAssetReference { ...@@ -527,6 +568,7 @@ impl EsmAssetReference {
import_usage, import_usage,
import_externals, import_externals,
module_fragments_enabled, module_fragments_enabled,
export_usage_passthrough,
resolve_override, resolve_override,
} = options; } = options;
...@@ -551,7 +593,11 @@ impl EsmAssetReference { ...@@ -551,7 +593,11 @@ impl EsmAssetReference {
import_externals, import_externals,
module_fragments_enabled, module_fragments_enabled,
is_pure_import, is_pure_import,
extras: EsmReferenceExtras::new(annotations.as_ref(), resolve_override), extras: EsmReferenceExtras::new(
annotations.as_ref(),
export_usage_passthrough,
resolve_override,
),
}) })
} }
...@@ -722,22 +768,22 @@ impl ModuleReference for EsmAssetReference { ...@@ -722,22 +768,22 @@ impl ModuleReference for EsmAssetReference {
} }
fn binding_usage(&self) -> BindingUsage { fn binding_usage(&self) -> BindingUsage {
let export_usage_passthrough = self
.extras
.as_deref()
.and_then(|extras| extras.export_usage_passthrough);
BindingUsage { BindingUsage {
import: self.import_usage.clone(), import: self.import_usage.clone(),
export: match &self.export_name { export: match (&self.export_name, export_usage_passthrough) {
// Evaluation references preserve their side-effect-only semantics even when the // Evaluation references preserve their side-effect-only semantics even when the
// corresponding import forwards export usage. // corresponding import forwards export usage.
Some(ModulePart::Evaluation) => ExportUsage::Evaluation, (Some(ModulePart::Evaluation), _) => ExportUsage::Evaluation,
_ if self (_, Some(namespace_object_may_escape)) => ExportUsage::Passthrough {
.extras namespace_object_may_escape,
.as_deref() },
.is_some_and(|extras| extras.export_usage_passthrough) => (Some(ModulePart::Export(export_name)), _) => {
{ ExportUsage::Named(export_name.clone())
ExportUsage::Passthrough {
namespace_object_may_escape: true,
}
} }
Some(ModulePart::Export(export_name)) => ExportUsage::Named(export_name.clone()),
_ => ExportUsage::All, _ => ExportUsage::All,
}, },
} }
......
use anyhow::{Result, bail}; use anyhow::{Result, bail};
use rustc_hash::FxHashSet;
use swc_core::{ use swc_core::{
common::source_map::SmallPos, common::source_map::SmallPos,
ecma::ast::{Expr, Ident, ImportDecl, MemberProp, Program, Stmt}, ecma::ast::{Expr, Ident, ImportDecl, MemberProp, Program, Stmt},
...@@ -80,6 +81,8 @@ pub async fn compute_ecmascript_module_exports( ...@@ -80,6 +81,8 @@ pub async fn compute_ecmascript_module_exports(
let mut esm_reexport_reference_idxs: Vec<usize> = vec![]; let mut esm_reexport_reference_idxs: Vec<usize> = vec![];
let mut esm_evaluation_reference_idxs: Vec<usize> = vec![]; let mut esm_evaluation_reference_idxs: Vec<usize> = vec![];
let namespace_reexports: FxHashSet<usize> =
eval_context.imports.reexport_namespaces().collect();
let span = tracing::trace_span!("esm import references"); let span = tracing::trace_span!("esm import references");
let import_references = async { let import_references = async {
...@@ -139,6 +142,7 @@ pub async fn compute_ecmascript_module_exports( ...@@ -139,6 +142,7 @@ pub async fn compute_ecmascript_module_exports(
.unwrap_or_default(), .unwrap_or_default(),
import_externals, import_externals,
module_fragments_enabled: options.module_fragments_enabled, module_fragments_enabled: options.module_fragments_enabled,
export_usage_passthrough: namespace_reexports.contains(&i).then_some(false),
resolve_override, resolve_override,
}, },
) )
......
...@@ -3752,6 +3752,7 @@ async fn handle_free_var_reference( ...@@ -3752,6 +3752,7 @@ async fn handle_free_var_reference(
import_usage: ImportUsage::TopLevel, import_usage: ImportUsage::TopLevel,
import_externals: state.import_externals, import_externals: state.import_externals,
module_fragments_enabled: state.module_fragments_enabled, module_fragments_enabled: state.module_fragments_enabled,
export_usage_passthrough: None,
resolve_override: None, resolve_override: None,
}, },
) )
......
import * as forwarded from './forwarded-barrel'
export function readForwardedNamespace() {
const { veryLongForwardedExportName } = forwarded
return veryLongForwardedExportName
}
import { getEnums } from './provider' import { getEnums } from './provider'
import { multiHopExportsInfo, readMultiHopDiamond } from './multi-hop-provider'
import { readForwardedNamespace } from './forwarded-provider'
import {
forwardedExportsInfo,
veryLongMangleableForwardedExportName,
} from './mangleable-forwarded-barrel'
import { enumsNs } from './reexport' import { enumsNs } from './reexport'
import { getCjs } from './cjs-provider' import { getCjs } from './cjs-provider'
import { read } from './destr' import { read } from './destr'
...@@ -47,6 +53,26 @@ it('should keep an escaped CommonJS namespace interop correct', () => { ...@@ -47,6 +53,26 @@ it('should keep an escaped CommonJS namespace interop correct', () => {
expect(ns.CJS_B).toBe('cjs-b') expect(ns.CJS_B).toBe('cjs-b')
}) })
it('should preserve namespace reads through an export-star forwarding edge', () => {
expect(readForwardedNamespace()).toBe('forwarded-value')
})
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()
})
it('should still mangle ordinary named reads through an export-star forwarding edge', () => {
expect(veryLongMangleableForwardedExportName).toBe('mangleable-forwarded')
expect(
forwardedExportsInfo.veryLongMangleableForwardedExportName.canMangle
).toBe(true)
expect(
forwardedExportsInfo.veryLongMangleableForwardedExportName.mangledName
).not.toBe('veryLongMangleableForwardedExportName')
})
it('should still mangle a sibling module that does not escape', () => { it('should still mangle a sibling module that does not escape', () => {
expect(someLongExportName).toBe('mangled-1') expect(someLongExportName).toBe('mangled-1')
expect(anotherLongExportName).toBe('mangled-2') expect(anotherLongExportName).toBe('mangled-2')
......
export const veryLongMangleableForwardedExportName = 'mangleable-forwarded'
export const forwardedExportsInfo = {
veryLongMangleableForwardedExportName:
__webpack_exports_info__.veryLongMangleableForwardedExportName,
}
import * as namespacePath from './multi-hop-2'
import { veryLongMultiHopExportName as namedPath } from './multi-hop-source'
export { multiHopExportsInfo } from './multi-hop-source'
export function readMultiHopDiamond() {
const { veryLongMultiHopExportName } = namespacePath
return [veryLongMultiHopExportName, namedPath]
}
export const veryLongMultiHopExportName = 'multi-hop'
export const multiHopExportsInfo = {
veryLongMultiHopExportName:
__webpack_exports_info__.veryLongMultiHopExportName,
}
export * from './source'
export const shadowed = 'local'
export default 'local-default'
import value, { shadowed, shadowedUsed, defaultUsed } from './barrel'
it('does not forward locally shadowed or default names through export star', () => {
expect(value).toBe('local-default')
expect(shadowed).toBe('local')
expect(shadowedUsed).toBe(false)
expect(defaultUsed).toBe(false)
})
export const shadowed = 'source'
export default 'source-default'
export const shadowedUsed = __webpack_exports_info__.shadowed.used
export const defaultUsed = __webpack_exports_info__.default.used
import { m, mUsed, nUsed } from './barrel'
it('should keep narrowing exports through an `export *` barrel', () => {
expect(m).toBe(1)
if (process.env.NODE_ENV === 'production') {
expect(mUsed).toBe(true)
expect(nUsed).toBe(false)
}
})
it('A: should tree-shake through a 4-level CJS star-reexport chain', () => { // Runtime semantics for these cases are covered by the enabled
const d = require('./a-l4') // `reexport-forwarding-nested-runtime` fixture. This fixture remains skipped only because the
expect(d.a).toBe(1) // used/unused precision assertions below are not implemented yet.
if (process.env.NODE_ENV === 'production') {
expect(d.aUsed).toBe(true)
expect(d.bUsed).toBe(false) // b is never read across the chain
}
})
it('B: should tree-shake a nested namespace reexported through CJS', () => { it('B: should tree-shake a nested namespace reexported through CJS', () => {
const m = require('./b-mid') const m = require('./b-mid')
...@@ -25,20 +20,6 @@ it('C: should tree-shake a sub-namespace star-reexport (ids != [])', () => { ...@@ -25,20 +20,6 @@ it('C: should tree-shake a sub-namespace star-reexport (ids != [])', () => {
} }
}) })
it('D: should tree-shake a CJS star-reexport of an ESM `export *` barrel', () => {
const d = require('./d-cjs')
expect(d.m).toBe(1)
if (process.env.NODE_ENV === 'production') {
expect(d.mUsed).toBe(true)
expect(d.nUsed).toBe(false)
}
})
it('E: should handle circular CJS star-reexports at runtime', () => {
const one = require('./e-one')
expect(one.second).toBe(2)
})
it('F: should tree-shake a depth-2 nested namespace reexported through CJS', () => { it('F: should tree-shake a depth-2 nested namespace reexported through CJS', () => {
const m = require('./f-cjs') const m = require('./f-cjs')
expect(m.mid.deep.x).toBe(1) expect(m.mid.deep.x).toBe(1)
...@@ -48,19 +29,6 @@ it('F: should tree-shake a depth-2 nested namespace reexported through CJS', () ...@@ -48,19 +29,6 @@ it('F: should tree-shake a depth-2 nested namespace reexported through CJS', ()
} }
}) })
it('G: should tree-shake a diamond of CJS reexports with disjoint usage', () => {
const a = require('./g-p1').a
const b = require('./g-p2').b
expect(a).toBe(1)
expect(b).toBe(2)
if (process.env.NODE_ENV === 'production') {
// each property is pulled through a different reexport path
expect(require('./g-p1').aUsed).toBe(true)
expect(require('./g-p2').bUsed).toBe(true)
expect(require('./g-p1').cUsed).toBe(false) // c used through neither path
}
})
it('J: should tree-shake when ids unwrap a namespace after a star hop', () => { it('J: should tree-shake when ids unwrap a namespace after a star hop', () => {
const m = require('./j-hop2') const m = require('./j-hop2')
expect(m.w).toBe(1) expect(m.w).toBe(1)
...@@ -69,10 +37,3 @@ it('J: should tree-shake when ids unwrap a namespace after a star hop', () => { ...@@ -69,10 +37,3 @@ it('J: should tree-shake when ids unwrap a namespace after a star hop', () => {
expect(m.zUsed).toBe(false) expect(m.zUsed).toBe(false)
} }
}) })
it('H: should resolve mutually circular CJS star-reexports at runtime', () => {
const a = require('./h-a')
expect(a.onlyB).toBe('B')
expect(a.alsoB).toBe('B2')
expect('onlyA' in a).toBe(false) // overwritten by module.exports = require("./h-b")
})
import sourceDefault, { named } from './forwarder'
import * as namespace from './forwarder'
import './side-effect-forwarder'
it('preserves ESM default, named, and namespace interop through a CJS forwarder', () => {
expect(sourceDefault).toBe('default')
expect(named).toBe('named')
expect(namespace.named).toBe('named')
expect(namespace.other).toBe('other')
expect(namespace.default).toBe('default')
})
it('forwards opaque whole-namespace usage and evaluates the target once', () => {
const opaque = Object(require('./forwarder'))
expect(Object.keys(opaque)).toEqual(
expect.arrayContaining(['default', 'named', 'other'])
)
expect(globalThis.__forwarded_side_effects).toBe(1)
})
it('preserves evaluation through a forwarder when no exports are read', () => {
expect(globalThis.__side_effect_only_forwarded).toBe(1)
})
globalThis.__side_effect_only_forwarded =
(globalThis.__side_effect_only_forwarded ?? 0) + 1
export const neverRead = 'never-read'
globalThis.__forwarded_side_effects ??= 0
globalThis.__forwarded_side_effects++
export const named = 'named'
export const other = 'other'
export default 'default'
import { used, usedInfo, unusedInfo } from './forwarder'
it('supports an ESM named import through a CommonJS whole-module reexport', () => {
expect(used).toBe('used')
expect(usedInfo).toBe(true)
expect(unusedInfo).toBe(false)
})
export const used = 'used'
export const unused = 'unused'
export const usedInfo = __webpack_exports_info__.used.used
export const unusedInfo = __webpack_exports_info__.unused.used
export const x = 1
export const y = 2
export const xUsed = __webpack_exports_info__.x.used
export const yUsed = __webpack_exports_info__.y.used
export const p = 1
export const q = 2
export const pUsed = __webpack_exports_info__.p.used
export const qUsed = __webpack_exports_info__.q.used
export const x = 1
export const y = 2
export const xUsed = __webpack_exports_info__.x.used
export const yUsed = __webpack_exports_info__.y.used
it('preserves a nested namespace reexported through CJS', () => {
expect(require('./b-mid').inner.x).toBe(1)
})
it('preserves a namespace member assigned through CJS', () => {
expect(require('./c-mid').p).toBe(1)
})
it('preserves a depth-two nested namespace reexported through CJS', () => {
expect(require('./f-cjs').mid.deep.x).toBe(1)
})
it('preserves namespace unwrapping after a forwarding hop', () => {
expect(require('./j-hop2').w).toBe(1)
})
export const w = 1
export const z = 2
export const wUsed = __webpack_exports_info__.w.used
export const zUsed = __webpack_exports_info__.z.used
import sourceDefault, { named } from './forwarder'
import * as namespace from './forwarder'
import './side-effect-forwarder'
it('preserves ESM default, named, and namespace interop through a CJS forwarder', () => {
expect(sourceDefault).toBe('default')
expect(named).toBe('named')
expect(namespace.named).toBe('named')
expect(namespace.other).toBe('other')
expect(namespace.default).toBe('default')
})
it('forwards opaque whole-namespace usage and evaluates the target once', () => {
const opaque = Object(require('./forwarder'))
expect(Object.keys(opaque)).toEqual(
expect.arrayContaining(['default', 'named', 'other'])
)
expect(globalThis.__forwarded_side_effects).toBe(1)
})
it('preserves evaluation through a forwarder when no exports are read', () => {
expect(globalThis.__side_effect_only_forwarded).toBe(1)
})
globalThis.__side_effect_only_forwarded =
(globalThis.__side_effect_only_forwarded ?? 0) + 1
export const neverRead = 'never-read'
globalThis.__forwarded_side_effects ??= 0
globalThis.__forwarded_side_effects++
export const named = 'named'
export const other = 'other'
export default 'default'
it('does not classify shadowed module and require bindings as forwarding', () => {
expect(require('./shadowed').value).toBe('shadowed')
})
it('preserves a require member assigned to module.exports', () => {
expect(require('./member').value).toBe('inner')
})
it('preserves non-simple module.exports assignments', () => {
expect(require('./compound').value).toBe('value')
})
function create(module, require) {
module.exports = require('./ignored')
return module.exports
}
module.exports = create({}, () => ({ value: 'shadowed' }))
export const m = 1
export const n = 2
export const mUsed = __webpack_exports_info__.m.used
export const nUsed = __webpack_exports_info__.n.used
it('A: should tree-shake through a 4-level CJS star-reexport chain', () => {
const d = require('./a-l4')
expect(d.a).toBe(1)
if (process.env.NODE_ENV === 'production') {
expect(d.aUsed).toBe(true)
expect(d.bUsed).toBe(false) // b is never read across the chain
}
})
it('D: should tree-shake a CJS star-reexport of an ESM `export *` barrel', () => {
const d = require('./d-cjs')
expect(d.m).toBe(1)
if (process.env.NODE_ENV === 'production') {
expect(d.mUsed).toBe(true)
expect(d.nUsed).toBe(false)
}
})
it('E: should handle circular CJS star-reexports at runtime', () => {
const one = require('./e-one')
expect(one.second).toBe(2)
})
it('G: should tree-shake a diamond of CJS reexports with disjoint usage', () => {
const a = require('./g-p1').a
const b = require('./g-p2').b
expect(a).toBe(1)
expect(b).toBe(2)
if (process.env.NODE_ENV === 'production') {
// each property is pulled through a different reexport path
expect(require('./g-p1').aUsed).toBe(true)
expect(require('./g-p2').bUsed).toBe(true)
expect(require('./g-p1').cUsed).toBe(false) // c used through neither path
}
})
it('H: should resolve mutually circular CJS star-reexports at runtime', () => {
const a = require('./h-a')
expect(a.onlyB).toBe('B')
expect(a.alsoB).toBe('B2')
expect('onlyA' in a).toBe(false) // overwritten by module.exports = require("./h-b")
})
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