Unverified Commit 7c8bec41 authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

test(turbopack): compare CommonJS tree shaking with webpack

Co-authored-by: 's avatarJimmy Miller <6071338+jimmyhmiller@users.noreply.github.com>
parent 6cfca45f
...@@ -178,6 +178,8 @@ pub async fn compute_binding_usage_info( ...@@ -178,6 +178,8 @@ pub async fn compute_binding_usage_info(
return Ok(GraphTraversalAction::Continue); return Ok(GraphTraversalAction::Continue);
}; };
let mut effective_export_usage = ref_data.binding_usage.export.clone();
if remove_unused_imports { if remove_unused_imports {
// If this is an evaluation reference and the target has no side effects // If this is an evaluation reference and the target has no side effects
// then we can drop it. NOTE: many `imports` create parallel Evaluation // then we can drop it. NOTE: many `imports` create parallel Evaluation
...@@ -203,14 +205,24 @@ pub async fn compute_binding_usage_info( ...@@ -203,14 +205,24 @@ pub async fn compute_binding_usage_info(
} }
// If the current edge is an unused import, skip it // If the current edge is an unused import, skip it
match &ref_data.binding_usage.import { match &ref_data.binding_usage.import {
ImportUsage::Exports(exports) => { ImportUsage::Exports(exports)
| ImportUsage::ExportsWithEvaluation(exports) => {
let source_used_exports = used_exports let source_used_exports = used_exports
.get(&parent) .get(&parent)
.context("parent module must have usage info")?; .context("parent module must have usage info")?;
if exports let owning_exports_unused = exports
.iter() .iter()
.all(|e| !source_used_exports.is_export_used(e)) .all(|e| !source_used_exports.is_export_used(e));
{ let evaluation_can_be_dropped =
matches!(&ref_data.binding_usage.import, ImportUsage::Exports(_))
|| side_effect_free_modules
.as_ref()
.expect(
"this must be present if `remove_unused_imports` is \
true",
)
.contains(&target);
if owning_exports_unused && evaluation_can_be_dropped {
// all exports are unused // all exports are unused
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
debug_unused_references_name.insert(( debug_unused_references_name.insert((
...@@ -226,6 +238,14 @@ pub async fn compute_binding_usage_info( ...@@ -226,6 +238,14 @@ pub async fn compute_binding_usage_info(
return Ok(GraphTraversalAction::Skip); return Ok(GraphTraversalAction::Skip);
} else { } else {
if owning_exports_unused
&& matches!(
&ref_data.binding_usage.import,
ImportUsage::ExportsWithEvaluation(_)
)
{
effective_export_usage = ExportUsage::Evaluation;
}
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
debug_unused_references_name.remove(&( debug_unused_references_name.remove(&(
parent, parent,
...@@ -266,7 +286,7 @@ pub async fn compute_binding_usage_info( ...@@ -266,7 +286,7 @@ pub async fn compute_binding_usage_info(
} }
let is_first_visit = !used_exports.contains_key(&target); let is_first_visit = !used_exports.contains_key(&target);
let changed = match &ref_data.binding_usage.export { let changed = match &effective_export_usage {
ExportUsage::Passthrough { ExportUsage::Passthrough {
namespace_object_may_escape, namespace_object_may_escape,
} => { } => {
......
...@@ -162,6 +162,13 @@ pub enum ImportUsage { ...@@ -162,6 +162,13 @@ pub enum ImportUsage {
/// (This is only ever set on `ModulePart::Export` references. Side effects are handled via /// (This is only ever set on `ModulePart::Export` references. Side effects are handled via
/// `ModulePart::Evaluation` references, which always have `ImportUsage::TopLevel`.) /// `ModulePart::Evaluation` references, which always have `ImportUsage::TopLevel`.)
Exports(FrozenSet<RcStr>), Exports(FrozenSet<RcStr>),
/// This import is used only by these exports, but the same reference also performs module
/// evaluation. It can only be removed when all owning exports are unused *and* the target is
/// declared side-effect-free.
///
/// CommonJS direct-property re-exports use this because a single `require()` both reads the
/// forwarded value and evaluates the dependency.
ExportsWithEvaluation(FrozenSet<RcStr>),
} }
/// Defines what parts of a module are used by another module /// Defines what parts of a module are used by another module
......
...@@ -4,7 +4,7 @@ use swc_core::{ ...@@ -4,7 +4,7 @@ use swc_core::{
common::BytePos, common::BytePos,
ecma::{ast::*, visit::VisitWithAstPath}, ecma::{ast::*, visit::VisitWithAstPath},
}; };
use turbopack_core::resolve::ExportUsage; use turbopack_core::resolve::{ExportUsage, ImportUsage};
pub use crate::analyzer::graph::{ pub use crate::analyzer::graph::{
effects::{ effects::{
...@@ -41,6 +41,9 @@ pub struct VarGraph<'a> { ...@@ -41,6 +41,9 @@ pub struct VarGraph<'a> {
/// calls fall back to `ExportUsage::All`. /// calls fall back to `ExportUsage::All`.
pub require_usage: FxHashMap<BytePos, ExportUsage>, pub require_usage: FxHashMap<BytePos, ExportUsage>,
/// [`ImportUsage`] per `require("…")` call when its evaluation is owned by named exports.
pub require_import_usage: FxHashMap<BytePos, ImportUsage>,
/// Present when the module is a statically-analyzable CommonJS module (no /// Present when the module is a statically-analyzable CommonJS module (no
/// dynamic exports); carries its named exports for scope hoisting. /// dynamic exports); carries its named exports for scope hoisting.
pub cjs_static_exports: Option<CjsStaticExports>, pub cjs_static_exports: Option<CjsStaticExports>,
...@@ -76,6 +79,7 @@ pub fn create_graph<'a>( ...@@ -76,6 +79,7 @@ pub fn create_graph<'a>(
effects: Default::default(), effects: Default::default(),
code_gens: Default::default(), code_gens: Default::default(),
require_usage: Default::default(), require_usage: Default::default(),
require_import_usage: Default::default(),
cjs_static_exports: Default::default(), cjs_static_exports: Default::default(),
}, },
eval_context, eval_context,
......
...@@ -115,6 +115,9 @@ struct CjsExportsCollector { ...@@ -115,6 +115,9 @@ struct CjsExportsCollector {
has_top_level_return: bool, has_top_level_return: bool,
/// Whether any export is defined with `Object.defineProperty`. /// Whether any export is defined with `Object.defineProperty`.
has_define_property_export: bool, has_define_property_export: bool,
/// Whether an export write is nested in top-level control flow. Such writes are droppable,
/// but aren't unconditional bindings that can participate in scope hoisting.
has_conditional_export: bool,
} }
/// The removable writes, the always-removable ones, and whether the `__esModule` /// The removable writes, the always-removable ones, and whether the `__esModule`
...@@ -585,6 +588,7 @@ mod analyzer_state { ...@@ -585,6 +588,7 @@ mod analyzer_state {
pub(in crate::analyzer::graph) fn enable_require_usage(&mut self, imports: &ImportMap) { pub(in crate::analyzer::graph) fn enable_require_usage(&mut self, imports: &ImportMap) {
let cjs_imports = imports.cjs_imports(); let cjs_imports = imports.cjs_imports();
self.data.require_usage = cjs_imports.resolved.clone(); self.data.require_usage = cjs_imports.resolved.clone();
self.data.require_import_usage = cjs_imports.import_usage.clone();
// Seed each namespace binding as `Evaluation`; a binding that's never // Seed each namespace binding as `Evaluation`; a binding that's never
// read keeps that (only the target's side effects matter), while a // read keeps that (only the target's side effects matter), while a
// member read upgrades it to `PartialNamespaceObject` below. // member read upgrades it to `PartialNamespaceObject` below.
...@@ -705,6 +709,12 @@ mod analyzer_state { ...@@ -705,6 +709,12 @@ mod analyzer_state {
} }
} }
pub(super) fn set_cjs_has_conditional_export(&mut self) {
if let Some(c) = &mut self.state.cjs_exports {
c.has_conditional_export = true;
}
}
pub(super) fn record_cjs_export(&mut self, name: RcStr, path: AstPath) { pub(super) fn record_cjs_export(&mut self, name: RcStr, path: AstPath) {
self.push_cjs_export(DroppableCjsExportAssignment::Write { name, path }); self.push_cjs_export(DroppableCjsExportAssignment::Write { name, path });
} }
...@@ -743,24 +753,24 @@ mod analyzer_state { ...@@ -743,24 +753,24 @@ mod analyzer_state {
// A top-level `return` skips the writes after it, and would abandon the rest // A top-level `return` skips the writes after it, and would abandon the rest
// of a merged factory. An `Object.defineProperty` export keeps its value in // of a merged factory. An `Object.defineProperty` export keeps its value in
// the descriptor, which the merge has no local to bind it to. // the descriptor, which the merge has no local to bind it to.
let static_exports = let static_exports = (!c.has_top_level_return
(!c.has_top_level_return && !c.has_define_property_export).then(|| { && !c.has_define_property_export
CjsStaticExports { && !c.has_conditional_export)
export_names: c .then(|| CjsStaticExports {
.writes export_names: c
.iter() .writes
.flat_map(|w| match w { .iter()
DroppableCjsExportAssignment::Write { name, .. } => { .flat_map(|w| match w {
std::slice::from_ref(name) DroppableCjsExportAssignment::Write { name, .. } => {
} std::slice::from_ref(name)
DroppableCjsExportAssignment::ObjectLiteral { names, .. } => { }
names.as_slice() DroppableCjsExportAssignment::ObjectLiteral { names, .. } => {
} names.as_slice()
}) }
.cloned() })
.collect(), .cloned()
has_es_module: c.has_es_module, .collect(),
} has_es_module: c.has_es_module,
}); });
// Dropping an unused write stays sound regardless of the `return`, but // Dropping an unused write stays sound regardless of the `return`, but
// `__esModule` may be set after it, so it can't be claimed. // `__esModule` may be set after it, so it can't be claimed.
...@@ -780,7 +790,7 @@ mod analyzer_state { ...@@ -780,7 +790,7 @@ mod analyzer_state {
let AssignTarget::Simple(SimpleAssignTarget::Member(member)) = target else { let AssignTarget::Simple(SimpleAssignTarget::Member(member)) = target else {
return false; return false;
}; };
if !matches!(member.prop, MemberProp::Ident(_)) { if extract_name_from_member_prop(&member.prop).is_none() {
return false; return false;
} }
is_exports_object(&member.obj, self.eval_context.unresolved_mark) is_exports_object(&member.obj, self.eval_context.unresolved_mark)
...@@ -1467,25 +1477,32 @@ impl<'a> Analyzer<'a, '_> { ...@@ -1467,25 +1477,32 @@ impl<'a> Analyzer<'a, '_> {
if n.op != AssignOp::Assign { if n.op != AssignOp::Assign {
return; return;
} }
// Only top-level writes can be dropped. // Writes inside functions run after module evaluation and can mutate the export
if self.is_in_fn() || self.is_in_nested_block_scope() { // namespace at arbitrary times. Top-level control-flow blocks are safe to track:
// dropping an unused assignment keeps both the branch and its RHS effects intact.
if self.is_in_fn() {
self.taint_cjs_exports(); self.taint_cjs_exports();
return; return;
} }
if self.is_in_nested_block_scope() {
self.set_cjs_has_conditional_export();
}
let AssignTarget::Simple(SimpleAssignTarget::Member(member)) = &n.left else { let AssignTarget::Simple(SimpleAssignTarget::Member(member)) = &n.left else {
return; return;
}; };
// After a replacement only `module.exports` still reaches the exports object. // After a replacement only `module.exports` still reaches the exports object.
let dead = self.cjs_exports_object_replaced() let dead = self.cjs_exports_object_replaced()
&& !is_module_exports_chain(&member.obj, self.eval_context.unresolved_mark); && !is_module_exports_chain(&member.obj, self.eval_context.unresolved_mark);
let MemberProp::Ident(name) = &member.prop else { let Some(name) =
extract_name_from_member_prop(&member.prop).and_then(|names| names.into_iter().next())
else {
return; return;
}; };
// Transpilers use this to signal that this is transpiled esm. // Transpilers use this to signal that this is transpiled esm.
// Which in turn changes the behavior of default exports. such that `import foo from // Which in turn changes the behavior of default exports. such that `import foo from
// 'transpiled-esm-cjs'` gets the `default` export instead of the namespace // 'transpiled-esm-cjs'` gets the `default` export instead of the namespace
if !dead && name.sym.as_ref() == "__esModule" { if !dead && &*name == "__esModule" {
// Only a literal `true` is the interop marker. // Only a literal `true` is the interop marker.
if matches!(unparen(&n.right), Expr::Lit(Lit::Bool(b)) if b.value) { if matches!(unparen(&n.right), Expr::Lit(Lit::Bool(b)) if b.value) {
self.set_cjs_has_es_module(); self.set_cjs_has_es_module();
...@@ -1494,7 +1511,6 @@ impl<'a> Analyzer<'a, '_> { ...@@ -1494,7 +1511,6 @@ impl<'a> Analyzer<'a, '_> {
} }
// The RHS isn't inspected; the code-gen keeps it as `<value>`. // The RHS isn't inspected; the code-gen keeps it as `<value>`.
let name = RcStr::from(name.sym.as_str());
let path = as_parent_path(ast_path).into(); let path = as_parent_path(ast_path).into();
if dead { if dead {
self.record_dead_cjs_write(name, path); self.record_dead_cjs_write(name, path);
......
...@@ -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, is_module_dot_exports}, cjs_ast::{is_exports_object, is_global, is_module_dot_exports},
graph::{AssignmentScope, AssignmentScopes, EvalContext}, graph::{AssignmentScope, AssignmentScopes, EvalContext},
is_unresolved, is_unresolved_id, is_unresolved, is_unresolved_id,
}, },
...@@ -370,7 +370,7 @@ impl ProgramDeclUsage { ...@@ -370,7 +370,7 @@ impl ProgramDeclUsage {
// Fold re-exports (`export { x } from "foo"`) into `import_usage` for tree-shaking. // Fold re-exports (`export { x } from "foo"`) into `import_usage` for tree-shaking.
for (reference, names) in &self.named_reexports { for (reference, names) in &self.named_reexports {
let usage = match import_usage.get(reference) { let usage = match import_usage.get(reference) {
Some(ImportUsage::TopLevel) => continue, Some(ImportUsage::TopLevel | ImportUsage::ExportsWithEvaluation(_)) => continue,
// Used locally and re-exported, e.g. // Used locally and re-exported, e.g.
// `import {foo} from 'm'; export function w(){foo()} export {foo} from 'm'` // `import {foo} from 'm'; export function w(){foo()} export {foo} from 'm'`
// → union: Exports({"w"}) ∪ {"foo"}. // → union: Exports({"w"}) ∪ {"foo"}.
...@@ -472,6 +472,9 @@ pub(crate) struct CjsImports { ...@@ -472,6 +472,9 @@ pub(crate) struct CjsImports {
/// `const x = require("m")` /// `const x = require("m")`
pub(crate) bindings: FxHashMap<Id, BytePos>, pub(crate) bindings: FxHashMap<Id, BytePos>,
/// A direct-property `require()` whose value is owned by named CommonJS exports.
pub(crate) import_usage: FxHashMap<BytePos, ImportUsage>,
} }
/// Represents a collection of [webpack-style "magic comments"][magic] that override import /// Represents a collection of [webpack-style "magic comments"][magic] that override import
...@@ -1536,15 +1539,33 @@ impl Visit for Analyzer<'_> { ...@@ -1536,15 +1539,33 @@ impl Visit for Analyzer<'_> {
fn visit_assign_expr(&mut self, node: &AssignExpr) { fn visit_assign_expr(&mut self, node: &AssignExpr) {
if node.op == AssignOp::Assign if node.op == AssignOp::Assign
&& let AssignTarget::Simple(SimpleAssignTarget::Member(target)) = &node.left && 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( if is_module_dot_exports(target, self.unresolved_mark)
call.span.lo, && let Some(call) = as_require_call(&node.right, self.unresolved_mark)
ExportUsage::Passthrough { {
namespace_object_may_escape: true, self.data.cjs_imports.resolved.insert(
}, call.span.lo,
); ExportUsage::Passthrough {
namespace_object_may_escape: true,
},
);
} else if is_exports_object(&target.obj, self.unresolved_mark)
&& let Some(exported) = extract_name_from_member_prop(&target.prop)
.and_then(|names| names.into_iter().next())
&& let Expr::Member(source) = unparen(&node.right)
&& let Some(call) = as_require_call(&source.obj, self.unresolved_mark)
&& let Some(imported) = extract_name_from_member_prop(&source.prop)
.and_then(|names| names.into_iter().next())
{
self.data
.cjs_imports
.resolved
.insert(call.span.lo, ExportUsage::Named(imported));
self.data.cjs_imports.import_usage.insert(
call.span.lo,
ImportUsage::ExportsWithEvaluation([exported].into_iter().collect()),
);
}
} }
node.visit_children_with(self); node.visit_children_with(self);
} }
......
...@@ -105,6 +105,7 @@ pub struct CjsRequireAssetReference { ...@@ -105,6 +105,7 @@ pub struct CjsRequireAssetReference {
chunking_type_attribute: Option<SpecifiedChunkingType>, chunking_type_attribute: Option<SpecifiedChunkingType>,
resolve_override: Option<ResolvedVc<Box<dyn Module>>>, resolve_override: Option<ResolvedVc<Box<dyn Module>>>,
usage: ExportUsage, usage: ExportUsage,
import_usage: ImportUsage,
cjs_tree_shaking: bool, cjs_tree_shaking: bool,
} }
...@@ -117,6 +118,7 @@ impl CjsRequireAssetReference { ...@@ -117,6 +118,7 @@ impl CjsRequireAssetReference {
chunking_type_attribute: Option<SpecifiedChunkingType>, chunking_type_attribute: Option<SpecifiedChunkingType>,
resolve_override: Option<ResolvedVc<Box<dyn Module>>>, resolve_override: Option<ResolvedVc<Box<dyn Module>>>,
usage: ExportUsage, usage: ExportUsage,
import_usage: ImportUsage,
cjs_tree_shaking: bool, cjs_tree_shaking: bool,
) -> Self { ) -> Self {
CjsRequireAssetReference { CjsRequireAssetReference {
...@@ -127,6 +129,7 @@ impl CjsRequireAssetReference { ...@@ -127,6 +129,7 @@ impl CjsRequireAssetReference {
chunking_type_attribute, chunking_type_attribute,
resolve_override, resolve_override,
usage, usage,
import_usage,
cjs_tree_shaking, cjs_tree_shaking,
} }
} }
...@@ -163,7 +166,7 @@ impl ModuleReference for CjsRequireAssetReference { ...@@ -163,7 +166,7 @@ impl ModuleReference for CjsRequireAssetReference {
fn binding_usage(&self) -> BindingUsage { fn binding_usage(&self) -> BindingUsage {
BindingUsage { BindingUsage {
import: ImportUsage::TopLevel, import: self.import_usage.clone(),
export: self.usage.clone(), export: self.usage.clone(),
} }
} }
......
...@@ -863,6 +863,7 @@ async fn analyze_ecmascript_module_internal( ...@@ -863,6 +863,7 @@ async fn analyze_ecmascript_module_internal(
let effects = take(&mut var_graph.effects); let effects = take(&mut var_graph.effects);
// How each `require("…")` call's result is used, keyed by call position. // How each `require("…")` call's result is used, keyed by call position.
let require_binding_usage = take(&mut var_graph.require_usage); let require_binding_usage = take(&mut var_graph.require_usage);
let require_import_usage = take(&mut var_graph.require_import_usage);
// The module's static CommonJS exports, if any, for scope hoisting. // The module's static CommonJS exports, if any, for scope hoisting.
analysis.cjs_static_exports = take(&mut var_graph.cjs_static_exports); analysis.cjs_static_exports = take(&mut var_graph.cjs_static_exports);
let compile_time_info_ref = compile_time_info.await?; let compile_time_info_ref = compile_time_info.await?;
...@@ -1111,6 +1112,10 @@ async fn analyze_ecmascript_module_internal( ...@@ -1111,6 +1112,10 @@ async fn analyze_ecmascript_module_internal(
.get(&span.lo) .get(&span.lo)
.cloned() .cloned()
.unwrap_or(ExportUsage::All); .unwrap_or(ExportUsage::All);
let call_import_usage = require_import_usage
.get(&span.lo)
.cloned()
.unwrap_or(ImportUsage::TopLevel);
let args = process_effect_args(args, &mut queue_stack); let args = process_effect_args(args, &mut queue_stack);
handle_call( handle_call(
...@@ -1124,6 +1129,7 @@ async fn analyze_ecmascript_module_internal( ...@@ -1124,6 +1129,7 @@ async fn analyze_ecmascript_module_internal(
new, new,
eval_context.imports.get_attributes(span), eval_context.imports.get_attributes(span),
call_usage, call_usage,
call_import_usage,
) )
.await?; .await?;
} }
...@@ -1224,6 +1230,7 @@ async fn analyze_ecmascript_module_internal( ...@@ -1224,6 +1230,7 @@ async fn analyze_ecmascript_module_internal(
// A member call (`obj.method(...)`) result isn't narrowed // A member call (`obj.method(...)`) result isn't narrowed
// for require export usage. // for require export usage.
ExportUsage::All, ExportUsage::All,
ImportUsage::TopLevel,
) )
.await?; .await?;
} }
...@@ -1686,6 +1693,7 @@ async fn handle_call<'a>( ...@@ -1686,6 +1693,7 @@ async fn handle_call<'a>(
new: bool, new: bool,
attributes: &ImportAttributes, attributes: &ImportAttributes,
call_usage: ExportUsage, call_usage: ExportUsage,
call_import_usage: ImportUsage,
) -> Result<()> { ) -> Result<()> {
let &AnalysisState { let &AnalysisState {
handler, handler,
...@@ -1746,6 +1754,7 @@ async fn handle_call<'a>( ...@@ -1746,6 +1754,7 @@ async fn handle_call<'a>(
tracing_only, tracing_only,
attributes, attributes,
call_usage.clone(), call_usage.clone(),
call_import_usage.clone(),
) )
.await?; .await?;
} }
...@@ -1773,6 +1782,7 @@ async fn handle_call<'a>( ...@@ -1773,6 +1782,7 @@ async fn handle_call<'a>(
tracing_only, tracing_only,
attributes, attributes,
call_usage, call_usage,
call_import_usage,
) )
.await?; .await?;
} }
...@@ -1964,6 +1974,7 @@ async fn handle_well_known_function_call<'a, 'l, F, Fut>( ...@@ -1964,6 +1974,7 @@ async fn handle_well_known_function_call<'a, 'l, F, Fut>(
tracing_only: bool, tracing_only: bool,
attributes: &ImportAttributes, attributes: &ImportAttributes,
call_usage: ExportUsage, call_usage: ExportUsage,
call_import_usage: ImportUsage,
) -> Result<()> ) -> Result<()>
where where
'a: 'l, 'a: 'l,
...@@ -2290,6 +2301,7 @@ where ...@@ -2290,6 +2301,7 @@ where
attributes.chunking_type, attributes.chunking_type,
resolve_override, resolve_override,
call_usage.clone(), call_usage.clone(),
call_import_usage.clone(),
state.cjs_tree_shaking, state.cjs_tree_shaking,
), ),
ast_path.to_vec().into(), ast_path.to_vec().into(),
...@@ -2347,6 +2359,7 @@ where ...@@ -2347,6 +2359,7 @@ where
attributes.chunking_type, attributes.chunking_type,
None, None,
call_usage.clone(), call_usage.clone(),
call_import_usage.clone(),
state.cjs_tree_shaking, state.cjs_tree_shaking,
), ),
ast_path.to_vec().into(), ast_path.to_vec().into(),
......
import assert from 'node:assert/strict'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { spawnSync } from 'node:child_process'
import { createRequire } from 'node:module'
const [fixtureArg, repoRootArg] = process.argv.slice(2)
if (!fixtureArg || !repoRootArg) {
throw new Error('usage: node cjs-webpack-parity.mjs <fixture> <repo-root>')
}
const fixture = path.resolve(fixtureArg)
const repoRoot = path.resolve(repoRootArg)
const input = path.join(fixture, 'input')
const turbopackOutput = path.join(fixture, 'output')
const expectedPath = path.join(fixture, 'differential.json')
const update = process.env.UPDATE === '1'
const requireFromRoot = createRequire(path.join(repoRoot, 'package.json'))
const webpackPath = requireFromRoot.resolve('webpack')
const webpack = requireFromRoot(webpackPath)
const webpackVersion = requireFromRoot('webpack/package.json').version
assert.equal(webpackVersion, '5.98.0', 'unexpected root-pinned webpack version')
const cases = {
direct: {
modules: ['direct.js'],
sentinels: ['USED_DIRECT_EXPORT', 'UNUSED_DIRECT_EXPORT'],
},
objectLiteral: {
modules: ['object-literal.js'],
sentinels: ['USED_OBJECT_LITERAL', 'UNUSED_OBJECT_LITERAL'],
},
defineProperty: {
modules: ['define-property.js'],
sentinels: ['USED_DEFINE_PROPERTY', 'UNUSED_DEFINE_PROPERTY'],
},
computed: {
modules: ['computed.js'],
sentinels: ['USED_COMPUTED_KEY', 'UNUSED_COMPUTED_KEY'],
},
dynamicComputed: {
modules: ['dynamic-computed.js'],
sentinels: [
'USED_DYNAMIC_COMPUTED',
'USED_DYNAMIC_FIXED',
'UNUSED_DYNAMIC_CONSERVATIVE',
],
},
conditional: {
modules: ['conditional.js'],
sentinels: [
'USED_CONDITIONAL_THEN',
'USED_CONDITIONAL_ELSE',
'UNUSED_CONDITIONAL_THEN',
'UNUSED_CONDITIONAL_ELSE',
'conditional:condition',
'conditional:unused-rhs-then',
'conditional:unused-rhs-else',
],
},
wholeReexport: {
modules: ['whole-reexport.js', 'whole-reexport-leaf.js'],
sentinels: ['USED_WHOLE_REEXPORT_LEAF', 'UNUSED_WHOLE_REEXPORT_LEAF'],
},
directProperty: {
modules: [
'direct-property-reexport.js',
'direct-property-used-leaf.js',
'direct-property-unused-leaf.js',
'direct-property-side-effect-leaf.js',
],
sentinels: [
'USED_DIRECT_PROPERTY_REEXPORT_LEAF',
'UNUSED_DIRECT_PROPERTY_REEXPORT_LEAF',
'UNUSED_SIDE_EFFECT_EXPORT_VALUE',
'direct-property:side-effect-leaf',
],
},
cycle: {
modules: ['cycle-a.js', 'cycle-b.js'],
sentinels: [
'USED_CYCLE_A_BEFORE',
'USED_CYCLE_A_AFTER',
'USED_CYCLE_B_VALUE',
],
},
}
function allJavaScript(directory) {
return fs
.readdirSync(directory, { recursive: true, withFileTypes: true })
.filter((entry) => entry.isFile() && entry.name.endsWith('.js'))
.map((entry) =>
fs.readFileSync(path.join(entry.parentPath, entry.name), 'utf8')
)
.join('\n')
}
function execute(entry) {
const result = spawnSync(process.execPath, [entry], {
cwd: path.dirname(entry),
encoding: 'utf8',
})
if (result.status !== 0) {
throw new Error(
`bundle execution failed (${entry})\nstdout:\n${result.stdout}\nstderr:\n${result.stderr}`
)
}
const line = result.stdout
.split(/\r?\n/)
.find((candidate) => candidate.startsWith('CJS_PARITY_RESULT='))
if (!line) {
throw new Error(
`bundle emitted no CJS_PARITY_RESULT line:\n${result.stdout}`
)
}
return JSON.parse(line.slice('CJS_PARITY_RESULT='.length))
}
function manifest(bundle) {
return Object.fromEntries(
Object.entries(cases).map(([name, definition]) => [
name,
{
modules: Object.fromEntries(
definition.modules.map((module) => [
module,
bundle.includes(`/${module}`) || bundle.includes(`./${module}`),
])
),
sentinels: Object.fromEntries(
definition.sentinels.map((sentinel) => [
sentinel,
bundle.includes(sentinel),
])
),
},
])
)
}
function flatten(value, prefix = '') {
return Object.entries(value).flatMap(([key, child]) => {
const field = prefix ? `${prefix}.${key}` : key
return child && typeof child === 'object'
? flatten(child, field)
: [[field, child]]
})
}
function differences(turbopack, webpackManifest) {
const webpackFields = new Map(flatten(webpackManifest))
return flatten(turbopack)
.filter(([field, value]) => webpackFields.get(field) !== value)
.map(([field, turbopackValue]) => ({
field,
turbopack: turbopackValue,
webpack: webpackFields.get(field),
}))
}
function webpackBuild(outputPath) {
return new Promise((resolve, reject) => {
webpack(
{
mode: 'production',
target: 'node',
context: input,
entry: './index.js',
devtool: false,
output: {
path: outputPath,
filename: 'index.js',
},
module: {
rules: [
{
// Match the Turbopack-only `use turbopack: no side effects` directive in the
// shared leaf without changing the canonical input for either bundler.
test: /direct-property-unused-leaf\.js$/,
sideEffects: false,
},
],
},
optimization: {
usedExports: true,
minimize: true,
// Stable path-based IDs let the retention manifest observe module presence in the
// emitted JavaScript without relying on webpack stats or hashed numeric IDs.
moduleIds: 'named',
// Keep each CommonJS producer visible as its own module; concatenation would erase
// module boundaries and make a module-presence comparison meaningless.
concatenateModules: false,
},
},
(error, stats) => {
if (error) return reject(error)
if (stats.hasErrors()) {
return reject(new Error(stats.toString({ all: false, errors: true })))
}
resolve()
}
)
})
}
const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'cjs-webpack-parity-'))
try {
await webpackBuild(temp)
const runtime = {
turbopack: execute(path.join(turbopackOutput, 'index.entry.js')),
webpack: execute(path.join(temp, 'index.js')),
}
const retention = {
turbopack: manifest(allJavaScript(turbopackOutput)),
webpack: manifest(allJavaScript(temp)),
}
const actualDifferences = differences(retention.turbopack, retention.webpack)
if (update || !fs.existsSync(expectedPath)) {
const previous = fs.existsSync(expectedPath)
? JSON.parse(fs.readFileSync(expectedPath, 'utf8'))
: { classifications: [] }
const previousClassifications = new Map(
previous.classifications.map((item) => [
JSON.stringify([item.field, item.turbopack, item.webpack]),
item,
])
)
const classifications = actualDifferences.map((difference) => {
const previousItem = previousClassifications.get(
JSON.stringify([
difference.field,
difference.turbopack,
difference.webpack,
])
)
return {
...difference,
classification: previousItem?.classification ?? 'REVIEW_REQUIRED',
reason: previousItem?.reason ?? 'REVIEW_REQUIRED',
}
})
fs.writeFileSync(
expectedPath,
`${JSON.stringify(
{
webpackVersion,
runtime: runtime.turbopack,
retention,
classifications,
},
null,
2
)}\n`
)
if (!update) {
throw new Error(`missing ${expectedPath}; generated a review draft`)
}
console.log(`updated ${expectedPath}`)
} else {
const expected = JSON.parse(fs.readFileSync(expectedPath, 'utf8'))
assert.deepEqual(runtime.turbopack, runtime.webpack, 'runtime differential')
assert.deepEqual(runtime.turbopack, expected.runtime, 'runtime oracle')
assert.deepEqual(retention, expected.retention, 'retention oracle')
assert.deepEqual(
actualDifferences,
expected.classifications.map(
({ classification, reason, ...difference }) => difference
),
'unclassified retention difference'
)
for (const item of expected.classifications) {
assert.match(
item.classification,
/^(turbopack-gap|turbopack-improvement|intentional-divergence)$/,
`invalid classification for ${item.field}`
)
assert.ok(item.reason && item.reason !== 'REVIEW_REQUIRED')
}
console.log(
`CJS webpack parity passed (webpack ${webpackVersion}, ${actualDifferences.length} classified retention differences)`
)
}
} finally {
fs.rmSync(temp, { recursive: true, force: true })
}
globalThis.CJS_PARITY_TRACE = []
globalThis.CJS_PARITY_SIDE_EFFECT_LEAF_EVALUATIONS = 0
const {
used: direct,
} = require('../../../../../snapshot/cjs-remove-unused-exports/webpack-parity/input/direct.js')
const objectLiteral =
require('../../../../../snapshot/cjs-remove-unused-exports/webpack-parity/input/object-literal.js').used
const defineProperty =
require('../../../../../snapshot/cjs-remove-unused-exports/webpack-parity/input/define-property.js').used
const computed =
require('../../../../../snapshot/cjs-remove-unused-exports/webpack-parity/input/computed.js').used
const dynamicComputed = require('../../../../../snapshot/cjs-remove-unused-exports/webpack-parity/input/dynamic-computed.js')
const conditional =
require('../../../../../snapshot/cjs-remove-unused-exports/webpack-parity/input/conditional.js').used
const wholeReexport = require('../../../../../snapshot/cjs-remove-unused-exports/webpack-parity/input/whole-reexport.js')
const wholeReexportLeaf = require('../../../../../snapshot/cjs-remove-unused-exports/webpack-parity/input/whole-reexport-leaf.js')
const directProperty =
require('../../../../../snapshot/cjs-remove-unused-exports/webpack-parity/input/direct-property-reexport.js').used
const cycle = require('../../../../../snapshot/cjs-remove-unused-exports/webpack-parity/input/cycle-a.js')
const cycleB = require('../../../../../snapshot/cjs-remove-unused-exports/webpack-parity/input/cycle-b.js')
it('matches the CommonJS parity runtime oracle', () => {
expect({
values: {
direct,
objectLiteral,
defineProperty,
computed,
dynamicComputed: dynamicComputed.dynamic,
dynamicFixed: dynamicComputed.fixed,
conditional,
wholeReexport: wholeReexport.used,
directPropertyReexport: directProperty,
},
trace: globalThis.CJS_PARITY_TRACE,
sideEffectLeafEvaluations:
globalThis.CJS_PARITY_SIDE_EFFECT_LEAF_EVALUATIONS,
wholeReexportIdentity: wholeReexport === wholeReexportLeaf,
cache: {
wrapper: Boolean(
require.cache[
require.resolve(
'../../../../../snapshot/cjs-remove-unused-exports/webpack-parity/input/whole-reexport.js'
)
]
),
leaf: Boolean(
require.cache[
require.resolve(
'../../../../../snapshot/cjs-remove-unused-exports/webpack-parity/input/whole-reexport-leaf.js'
)
]
),
},
cycle: {
before: cycle.before,
fromB: cycle.fromB,
after: cycle.after,
bSawBefore: cycleB.sawBefore,
bSawAfter: cycleB.sawAfter ?? null,
},
}).toEqual({
values: {
direct: 'USED_DIRECT_EXPORT',
objectLiteral: 'USED_OBJECT_LITERAL',
defineProperty: 'USED_DEFINE_PROPERTY',
computed: 'USED_COMPUTED_KEY',
dynamicComputed: 'USED_DYNAMIC_COMPUTED',
dynamicFixed: 'USED_DYNAMIC_FIXED',
conditional: 'USED_CONDITIONAL_ELSE',
wholeReexport: 'USED_WHOLE_REEXPORT_LEAF',
directPropertyReexport: 'USED_DIRECT_PROPERTY_REEXPORT_LEAF',
},
trace: [
'conditional:condition',
'conditional:unused-rhs-else',
'direct-property:side-effect-leaf',
],
sideEffectLeafEvaluations: 1,
wholeReexportIdentity: true,
cache: { wrapper: true, leaf: true },
cycle: {
before: 'USED_CYCLE_A_BEFORE',
fromB: 'USED_CYCLE_B_VALUE',
after: 'USED_CYCLE_A_AFTER',
bSawBefore: 'USED_CYCLE_A_BEFORE',
bSawAfter: null,
},
})
})
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
mod util; mod util;
use std::{collections::VecDeque, fs, fs::canonicalize, io, path::PathBuf}; use std::{collections::VecDeque, fs, fs::canonicalize, io, path::PathBuf, process::Command};
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use rustc_hash::FxHashSet; use rustc_hash::FxHashSet;
...@@ -232,7 +232,20 @@ fn test(resource: PathBuf) { ...@@ -232,7 +232,20 @@ fn test(resource: PathBuf) {
// Separating this into a different function fixes my IDE's types for some // Separating this into a different function fixes my IDE's types for some
// reason... // reason...
run(resource).unwrap(); run(resource.clone()).unwrap();
if resource.join("differential.json").is_file() {
let script = PathBuf::from(REPO_ROOT.as_str())
.join("turbopack/crates/turbopack-tests/js/cjs-webpack-parity.mjs");
let status = Command::new("node")
.arg(script)
.arg(&resource)
.arg(REPO_ROOT.as_str())
.status()
.context("failed to run CommonJS webpack parity helper")
.unwrap();
assert!(status.success(), "CommonJS webpack parity helper failed");
}
} }
#[tokio::main(flavor = "multi_thread", worker_threads = 2)] #[tokio::main(flavor = "multi_thread", worker_threads = 2)]
......
{
"webpackVersion": "5.98.0",
"runtime": {
"values": {
"direct": "USED_DIRECT_EXPORT",
"objectLiteral": "USED_OBJECT_LITERAL",
"defineProperty": "USED_DEFINE_PROPERTY",
"computed": "USED_COMPUTED_KEY",
"dynamicComputed": "USED_DYNAMIC_COMPUTED",
"dynamicFixed": "USED_DYNAMIC_FIXED",
"conditional": "USED_CONDITIONAL_ELSE",
"wholeReexport": "USED_WHOLE_REEXPORT_LEAF",
"directPropertyReexport": "USED_DIRECT_PROPERTY_REEXPORT_LEAF"
},
"trace": [
"conditional:condition",
"conditional:unused-rhs-else",
"direct-property:side-effect-leaf"
],
"sideEffectLeafEvaluations": 1,
"wholeReexportIdentity": true,
"cache": {
"wrapper": true,
"leaf": true
},
"cycle": {
"before": "USED_CYCLE_A_BEFORE",
"fromB": "USED_CYCLE_B_VALUE",
"after": "USED_CYCLE_A_AFTER",
"bSawBefore": "USED_CYCLE_A_BEFORE",
"bSawAfter": null
}
},
"retention": {
"turbopack": {
"direct": {
"modules": {
"direct.js": true
},
"sentinels": {
"USED_DIRECT_EXPORT": true,
"UNUSED_DIRECT_EXPORT": false
}
},
"objectLiteral": {
"modules": {
"object-literal.js": true
},
"sentinels": {
"USED_OBJECT_LITERAL": true,
"UNUSED_OBJECT_LITERAL": false
}
},
"defineProperty": {
"modules": {
"define-property.js": true
},
"sentinels": {
"USED_DEFINE_PROPERTY": true,
"UNUSED_DEFINE_PROPERTY": false
}
},
"computed": {
"modules": {
"computed.js": true
},
"sentinels": {
"USED_COMPUTED_KEY": true,
"UNUSED_COMPUTED_KEY": false
}
},
"dynamicComputed": {
"modules": {
"dynamic-computed.js": true
},
"sentinels": {
"USED_DYNAMIC_COMPUTED": true,
"USED_DYNAMIC_FIXED": true,
"UNUSED_DYNAMIC_CONSERVATIVE": true
}
},
"conditional": {
"modules": {
"conditional.js": true
},
"sentinels": {
"USED_CONDITIONAL_THEN": false,
"USED_CONDITIONAL_ELSE": true,
"UNUSED_CONDITIONAL_THEN": false,
"UNUSED_CONDITIONAL_ELSE": false,
"conditional:condition": true,
"conditional:unused-rhs-then": false,
"conditional:unused-rhs-else": true
}
},
"wholeReexport": {
"modules": {
"whole-reexport.js": true,
"whole-reexport-leaf.js": true
},
"sentinels": {
"USED_WHOLE_REEXPORT_LEAF": true,
"UNUSED_WHOLE_REEXPORT_LEAF": true
}
},
"directProperty": {
"modules": {
"direct-property-reexport.js": true,
"direct-property-used-leaf.js": true,
"direct-property-unused-leaf.js": false,
"direct-property-side-effect-leaf.js": true
},
"sentinels": {
"USED_DIRECT_PROPERTY_REEXPORT_LEAF": true,
"UNUSED_DIRECT_PROPERTY_REEXPORT_LEAF": false,
"UNUSED_SIDE_EFFECT_EXPORT_VALUE": false,
"direct-property:side-effect-leaf": true
}
},
"cycle": {
"modules": {
"cycle-a.js": true,
"cycle-b.js": true
},
"sentinels": {
"USED_CYCLE_A_BEFORE": true,
"USED_CYCLE_A_AFTER": true,
"USED_CYCLE_B_VALUE": true
}
}
},
"webpack": {
"direct": {
"modules": {
"direct.js": true
},
"sentinels": {
"USED_DIRECT_EXPORT": true,
"UNUSED_DIRECT_EXPORT": true
}
},
"objectLiteral": {
"modules": {
"object-literal.js": true
},
"sentinels": {
"USED_OBJECT_LITERAL": true,
"UNUSED_OBJECT_LITERAL": true
}
},
"defineProperty": {
"modules": {
"define-property.js": true
},
"sentinels": {
"USED_DEFINE_PROPERTY": true,
"UNUSED_DEFINE_PROPERTY": false
}
},
"computed": {
"modules": {
"computed.js": true
},
"sentinels": {
"USED_COMPUTED_KEY": true,
"UNUSED_COMPUTED_KEY": false
}
},
"dynamicComputed": {
"modules": {
"dynamic-computed.js": true
},
"sentinels": {
"USED_DYNAMIC_COMPUTED": true,
"USED_DYNAMIC_FIXED": true,
"UNUSED_DYNAMIC_CONSERVATIVE": true
}
},
"conditional": {
"modules": {
"conditional.js": true
},
"sentinels": {
"USED_CONDITIONAL_THEN": false,
"USED_CONDITIONAL_ELSE": true,
"UNUSED_CONDITIONAL_THEN": false,
"UNUSED_CONDITIONAL_ELSE": false,
"conditional:condition": true,
"conditional:unused-rhs-then": false,
"conditional:unused-rhs-else": true
}
},
"wholeReexport": {
"modules": {
"whole-reexport.js": true,
"whole-reexport-leaf.js": true
},
"sentinels": {
"USED_WHOLE_REEXPORT_LEAF": true,
"UNUSED_WHOLE_REEXPORT_LEAF": true
}
},
"directProperty": {
"modules": {
"direct-property-reexport.js": true,
"direct-property-used-leaf.js": true,
"direct-property-unused-leaf.js": true,
"direct-property-side-effect-leaf.js": true
},
"sentinels": {
"USED_DIRECT_PROPERTY_REEXPORT_LEAF": true,
"UNUSED_DIRECT_PROPERTY_REEXPORT_LEAF": false,
"UNUSED_SIDE_EFFECT_EXPORT_VALUE": false,
"direct-property:side-effect-leaf": true
}
},
"cycle": {
"modules": {
"cycle-a.js": true,
"cycle-b.js": true
},
"sentinels": {
"USED_CYCLE_A_BEFORE": true,
"USED_CYCLE_A_AFTER": true,
"USED_CYCLE_B_VALUE": true
}
}
}
},
"classifications": [
{
"field": "direct.sentinels.UNUSED_DIRECT_EXPORT",
"turbopack": false,
"webpack": true,
"classification": "turbopack-improvement",
"reason": "Turbopack recognizes direct dot-property CommonJS writes as named exports and removes the unused pure assignment; webpack 5.98.0 retains its literal."
},
{
"field": "objectLiteral.sentinels.UNUSED_OBJECT_LITERAL",
"turbopack": false,
"webpack": true,
"classification": "turbopack-improvement",
"reason": "Turbopack removes the unused pure property from a module.exports object literal; webpack 5.98.0 retains it."
},
{
"field": "directProperty.modules.direct-property-unused-leaf.js",
"turbopack": false,
"webpack": true,
"classification": "turbopack-improvement",
"reason": "Turbopack drops the export-owned require edge when the outer export is unused and the leaf is explicitly side-effect-free; webpack 5.98.0 keeps the empty leaf module."
}
]
}
// String-literal computed keys are static export names, just like dot properties.
exports['used'] = 'USED_COMPUTED_KEY'
exports['unused'] = 'UNUSED_COMPUTED_KEY'
// Top-level control-flow writes remain statically named exports.
const condition =
(globalThis.CJS_PARITY_TRACE.push('conditional:condition'), false)
if (condition) {
exports.used = 'USED_CONDITIONAL_THEN'
exports.unused =
(globalThis.CJS_PARITY_TRACE.push('conditional:unused-rhs-then'),
'UNUSED_CONDITIONAL_THEN')
} else {
exports.used = 'USED_CONDITIONAL_ELSE'
exports.unused =
(globalThis.CJS_PARITY_TRACE.push('conditional:unused-rhs-else'),
'UNUSED_CONDITIONAL_ELSE')
}
exports.before = 'USED_CYCLE_A_BEFORE'
const b = require('./cycle-b.js')
exports.fromB = b.value
exports.after = 'USED_CYCLE_A_AFTER'
const a = require('./cycle-a.js')
exports.sawBefore = a.before
exports.sawAfter = a.after
exports.value = 'USED_CYCLE_B_VALUE'
Object.defineProperty(exports, 'used', {
enumerable: true,
get() {
return 'USED_DEFINE_PROPERTY'
},
})
Object.defineProperty(exports, 'unused', {
enumerable: true,
get() {
return 'UNUSED_DEFINE_PROPERTY'
},
})
exports.used = require('./direct-property-used-leaf.js').value
exports.unused = require('./direct-property-unused-leaf.js').value
// A side-effectful dependency must remain evaluated even though its outer export is unused.
exports.sideEffect = require('./direct-property-side-effect-leaf.js').value
globalThis.CJS_PARITY_TRACE.push('direct-property:side-effect-leaf')
globalThis.CJS_PARITY_SIDE_EFFECT_LEAF_EVALUATIONS =
(globalThis.CJS_PARITY_SIDE_EFFECT_LEAF_EVALUATIONS || 0) + 1
exports.value = 'UNUSED_SIDE_EFFECT_EXPORT_VALUE'
'use turbopack: no side effects'
exports.value = 'UNUSED_DIRECT_PROPERTY_REEXPORT_LEAF'
exports.used = 'USED_DIRECT_EXPORT'
exports.unused = 'UNUSED_DIRECT_EXPORT'
const dynamicName = 'dynamic'
exports[dynamicName] = 'USED_DYNAMIC_COMPUTED'
exports.fixed = 'USED_DYNAMIC_FIXED'
exports.unused = 'UNUSED_DYNAMIC_CONSERVATIVE'
globalThis.CJS_PARITY_TRACE = []
globalThis.CJS_PARITY_SIDE_EFFECT_LEAF_EVALUATIONS = 0
const { used: direct } = require('./direct.js')
const objectLiteral = require('./object-literal.js').used
const defineProperty = require('./define-property.js').used
const computed = require('./computed.js').used
const dynamicComputed = require('./dynamic-computed.js')
const conditional = require('./conditional.js').used
const wholeReexport = require('./whole-reexport.js')
const wholeReexportLeaf = require('./whole-reexport-leaf.js')
const directPropertyReexport = require('./direct-property-reexport.js').used
const cycle = require('./cycle-a.js')
const cycleB = require('./cycle-b.js')
const result = {
values: {
direct,
objectLiteral,
defineProperty,
computed,
dynamicComputed: dynamicComputed.dynamic,
dynamicFixed: dynamicComputed.fixed,
conditional,
wholeReexport: wholeReexport.used,
directPropertyReexport,
},
trace: globalThis.CJS_PARITY_TRACE,
sideEffectLeafEvaluations: globalThis.CJS_PARITY_SIDE_EFFECT_LEAF_EVALUATIONS,
wholeReexportIdentity: wholeReexport === wholeReexportLeaf,
cache: {
wrapper: Boolean(require.cache[require.resolve('./whole-reexport.js')]),
leaf: Boolean(require.cache[require.resolve('./whole-reexport-leaf.js')]),
},
cycle: {
before: cycle.before,
fromB: cycle.fromB,
after: cycle.after,
bSawBefore: cycleB.sawBefore,
bSawAfter: cycleB.sawAfter ?? null,
},
}
console.log(`CJS_PARITY_RESULT=${JSON.stringify(result)}`)
const used = 'USED_OBJECT_LITERAL'
const unused = 'UNUSED_OBJECT_LITERAL'
module.exports = { used, unused }
exports.used = 'USED_WHOLE_REEXPORT_LEAF'
exports.unused = 'UNUSED_WHOLE_REEXPORT_LEAF'
// Known gap: a whole CommonJS re-export remains as an intermediate module.
module.exports = require('./whole-reexport-leaf.js')
{
"runtime": "NodeJs",
"runtimeType": "Production",
"removeUnusedImports": true,
"removeUnusedExports": true,
"cjsTreeShaking": true,
"followReexports": true,
"minifyType": {
"Minify": {
"mangle": null
}
}
}
module.exports=["[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/computed.js [test] (ecmascript)",(__turbopack_context__,module1,exports)=>{exports.used="USED_COMPUTED_KEY"},"[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/conditional.js [test] (ecmascript)",(__turbopack_context__,module1,exports)=>{globalThis.CJS_PARITY_TRACE.push("conditional:condition"),exports.used="USED_CONDITIONAL_ELSE",globalThis.CJS_PARITY_TRACE.push("conditional:unused-rhs-else")},"[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/cycle-a.js [test] (ecmascript)",(__turbopack_context__,module1,exports)=>{exports.before="USED_CYCLE_A_BEFORE",exports.fromB=__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/cycle-b.js [test] (ecmascript)").value,exports.after="USED_CYCLE_A_AFTER"},"[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/cycle-b.js [test] (ecmascript)",(__turbopack_context__,module1,exports)=>{let a=__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/cycle-a.js [test] (ecmascript)");exports.sawBefore=a.before,exports.sawAfter=a.after,exports.value="USED_CYCLE_B_VALUE"},"[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/define-property.js [test] (ecmascript)",(__turbopack_context__,module1,exports)=>{Object.defineProperty(exports,"used",{enumerable:!0,get:()=>"USED_DEFINE_PROPERTY"})},"[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/direct-property-reexport.js [test] (ecmascript)",(__turbopack_context__,module1,exports)=>{exports.used=__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/direct-property-used-leaf.js [test] (ecmascript)").value,0..value,__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/direct-property-side-effect-leaf.js [test] (ecmascript)").value},"[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/direct-property-side-effect-leaf.js [test] (ecmascript)",(__turbopack_context__,module1,exports)=>{globalThis.CJS_PARITY_TRACE.push("direct-property:side-effect-leaf"),globalThis.CJS_PARITY_SIDE_EFFECT_LEAF_EVALUATIONS=(globalThis.CJS_PARITY_SIDE_EFFECT_LEAF_EVALUATIONS||0)+1},"[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/direct-property-used-leaf.js [test] (ecmascript)",(__turbopack_context__,module1,exports)=>{exports.value="USED_DIRECT_PROPERTY_REEXPORT_LEAF"},"[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/direct.js [test] (ecmascript)",(__turbopack_context__,module1,exports)=>{exports.used="USED_DIRECT_EXPORT"},"[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/dynamic-computed.js [test] (ecmascript)",(__turbopack_context__,module1,exports)=>{exports.dynamic="USED_DYNAMIC_COMPUTED",exports.fixed="USED_DYNAMIC_FIXED",exports.unused="UNUSED_DYNAMIC_CONSERVATIVE"},"[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/index.js [test] (ecmascript)",(__turbopack_context__,module1,exports)=>{globalThis.CJS_PARITY_TRACE=[],globalThis.CJS_PARITY_SIDE_EFFECT_LEAF_EVALUATIONS=0;let{used:direct}=__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/direct.js [test] (ecmascript)"),objectLiteral=__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/object-literal.js [test] (ecmascript)").used,defineProperty=__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/define-property.js [test] (ecmascript)").used,computed=__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/computed.js [test] (ecmascript)").used,dynamicComputed=__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/dynamic-computed.js [test] (ecmascript)"),conditional=__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/conditional.js [test] (ecmascript)").used,wholeReexport=__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/whole-reexport.js [test] (ecmascript)"),wholeReexportLeaf=__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/whole-reexport-leaf.js [test] (ecmascript)"),directPropertyReexport=__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/direct-property-reexport.js [test] (ecmascript)").used,cycle=__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/cycle-a.js [test] (ecmascript)"),cycleB=__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/cycle-b.js [test] (ecmascript)"),result={values:{direct,objectLiteral,defineProperty,computed,dynamicComputed:dynamicComputed.dynamic,dynamicFixed:dynamicComputed.fixed,conditional,wholeReexport:wholeReexport.used,directPropertyReexport},trace:globalThis.CJS_PARITY_TRACE,sideEffectLeafEvaluations:globalThis.CJS_PARITY_SIDE_EFFECT_LEAF_EVALUATIONS,wholeReexportIdentity:wholeReexport===wholeReexportLeaf,cache:{wrapper:!!__turbopack_context__.c["[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/whole-reexport.js [test] (ecmascript)"],leaf:!!__turbopack_context__.c["[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/whole-reexport-leaf.js [test] (ecmascript)"]},cycle:{before:cycle.before,fromB:cycle.fromB,after:cycle.after,bSawBefore:cycleB.sawBefore,bSawAfter:cycleB.sawAfter??null}};console.log(`CJS_PARITY_RESULT=${JSON.stringify(result)}`)},"[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/object-literal.js [test] (ecmascript)",(__turbopack_context__,module1,exports)=>{module1.exports={used:"USED_OBJECT_LITERAL"}},"[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/whole-reexport-leaf.js [test] (ecmascript)",(__turbopack_context__,module1,exports)=>{exports.used="USED_WHOLE_REEXPORT_LEAF",exports.unused="UNUSED_WHOLE_REEXPORT_LEAF"},"[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/whole-reexport.js [test] (ecmascript)",(__turbopack_context__,module1,exports)=>{module1.exports=__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/whole-reexport-leaf.js [test] (ecmascript)")}];
//# sourceMappingURL=1jsg_tests_snapshot_cjs-remove-unused-exports_webpack-parity_input_1sbzh_1p37sm6._.js.map
\ No newline at end of file
{"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/computed.js","turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/conditional.js","turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/cycle-a.js","turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/cycle-b.js","turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/define-property.js","turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/direct-property-reexport.js","turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/direct-property-side-effect-leaf.js","turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/direct-property-used-leaf.js","turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/direct.js","turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/dynamic-computed.js","turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/index.js","turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/object-literal.js","turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/whole-reexport-leaf.js","turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/whole-reexport.js"],"sourcesContent":["// String-literal computed keys are static export names, just like dot properties.\nexports['used'] = 'USED_COMPUTED_KEY'\nexports['unused'] = 'UNUSED_COMPUTED_KEY'\n","// Top-level control-flow writes remain statically named exports.\nconst condition =\n (globalThis.CJS_PARITY_TRACE.push('conditional:condition'), false)\nif (condition) {\n exports.used = 'USED_CONDITIONAL_THEN'\n exports.unused =\n (globalThis.CJS_PARITY_TRACE.push('conditional:unused-rhs-then'),\n 'UNUSED_CONDITIONAL_THEN')\n} else {\n exports.used = 'USED_CONDITIONAL_ELSE'\n exports.unused =\n (globalThis.CJS_PARITY_TRACE.push('conditional:unused-rhs-else'),\n 'UNUSED_CONDITIONAL_ELSE')\n}\n","exports.before = 'USED_CYCLE_A_BEFORE'\nconst b = require('./cycle-b.js')\nexports.fromB = b.value\nexports.after = 'USED_CYCLE_A_AFTER'\n","const a = require('./cycle-a.js')\nexports.sawBefore = a.before\nexports.sawAfter = a.after\nexports.value = 'USED_CYCLE_B_VALUE'\n","Object.defineProperty(exports, 'used', {\n enumerable: true,\n get() {\n return 'USED_DEFINE_PROPERTY'\n },\n})\nObject.defineProperty(exports, 'unused', {\n enumerable: true,\n get() {\n return 'UNUSED_DEFINE_PROPERTY'\n },\n})\n","exports.used = require('./direct-property-used-leaf.js').value\nexports.unused = require('./direct-property-unused-leaf.js').value\n// A side-effectful dependency must remain evaluated even though its outer export is unused.\nexports.sideEffect = require('./direct-property-side-effect-leaf.js').value\n","globalThis.CJS_PARITY_TRACE.push('direct-property:side-effect-leaf')\nglobalThis.CJS_PARITY_SIDE_EFFECT_LEAF_EVALUATIONS =\n (globalThis.CJS_PARITY_SIDE_EFFECT_LEAF_EVALUATIONS || 0) + 1\nexports.value = 'UNUSED_SIDE_EFFECT_EXPORT_VALUE'\n","exports.value = 'USED_DIRECT_PROPERTY_REEXPORT_LEAF'\n","exports.used = 'USED_DIRECT_EXPORT'\nexports.unused = 'UNUSED_DIRECT_EXPORT'\n","const dynamicName = 'dynamic'\nexports[dynamicName] = 'USED_DYNAMIC_COMPUTED'\nexports.fixed = 'USED_DYNAMIC_FIXED'\nexports.unused = 'UNUSED_DYNAMIC_CONSERVATIVE'\n","globalThis.CJS_PARITY_TRACE = []\nglobalThis.CJS_PARITY_SIDE_EFFECT_LEAF_EVALUATIONS = 0\n\nconst { used: direct } = require('./direct.js')\nconst objectLiteral = require('./object-literal.js').used\nconst defineProperty = require('./define-property.js').used\nconst computed = require('./computed.js').used\nconst dynamicComputed = require('./dynamic-computed.js')\nconst conditional = require('./conditional.js').used\nconst wholeReexport = require('./whole-reexport.js')\nconst wholeReexportLeaf = require('./whole-reexport-leaf.js')\nconst directPropertyReexport = require('./direct-property-reexport.js').used\nconst cycle = require('./cycle-a.js')\nconst cycleB = require('./cycle-b.js')\n\nconst result = {\n values: {\n direct,\n objectLiteral,\n defineProperty,\n computed,\n dynamicComputed: dynamicComputed.dynamic,\n dynamicFixed: dynamicComputed.fixed,\n conditional,\n wholeReexport: wholeReexport.used,\n directPropertyReexport,\n },\n trace: globalThis.CJS_PARITY_TRACE,\n sideEffectLeafEvaluations: globalThis.CJS_PARITY_SIDE_EFFECT_LEAF_EVALUATIONS,\n wholeReexportIdentity: wholeReexport === wholeReexportLeaf,\n cache: {\n wrapper: Boolean(require.cache[require.resolve('./whole-reexport.js')]),\n leaf: Boolean(require.cache[require.resolve('./whole-reexport-leaf.js')]),\n },\n cycle: {\n before: cycle.before,\n fromB: cycle.fromB,\n after: cycle.after,\n bSawBefore: cycleB.sawBefore,\n bSawAfter: cycleB.sawAfter ?? null,\n },\n}\n\nconsole.log(`CJS_PARITY_RESULT=${JSON.stringify(result)}`)\n","const used = 'USED_OBJECT_LITERAL'\nconst unused = 'UNUSED_OBJECT_LITERAL'\n\nmodule.exports = { used, unused }\n","exports.used = 'USED_WHOLE_REEXPORT_LEAF'\nexports.unused = 'UNUSED_WHOLE_REEXPORT_LEAF'\n","// Known gap: a whole CommonJS re-export remains as an intermediate module.\nmodule.exports = require('./whole-reexport-leaf.js')\n"],"names":["exports","condition","globalThis","CJS_PARITY_TRACE","push","used","before","b","fromB","value","after","a","sawBefore","sawAfter","Object","defineProperty","enumerable","get","CJS_PARITY_SIDE_EFFECT_LEAF_EVALUATIONS","dynamicName","fixed","unused","direct","objectLiteral","computed","dynamicComputed","conditional","wholeReexport","wholeReexportLeaf","directPropertyReexport","cycle","cycleB","result","values","dynamic","dynamicFixed","trace","sideEffectLeafEvaluations","wholeReexportIdentity","cache","wrapper","Boolean","leaf","bSawBefore","bSawAfter","console","log","JSON","stringify","module"],"mappings":"qMACAA,OAAO,CAAC,IAAO,CAAG,6MCCfE,WAAWC,gBAAgB,CAACC,IAAI,CAAC,yBAOlCJ,CAP4D,KAAK,EAOzDK,IAAI,CAAG,wBAEZH,WAAWC,gBAAgB,CAACC,IAAI,CAAC,gCAClC,oLCZJJ,QAAQM,MAAM,CAAG,sBAEjBN,QAAQQ,KAAK,CAAGD,AADVA,sBAAAA,CAAAA,CAAAA,2IACYE,KAAK,CACvBT,QAAQU,KAAK,CAAG,0MCHhB,IAAMC,EAAAA,sBAAAA,CAAAA,CAAAA,2IACNX,QAAQY,SAAS,CAAGD,EAAEL,MAAM,CAC5BN,QAAQa,QAAQ,CAAGF,EAAED,KAAK,CAC1BV,QAAQS,KAAK,CAAG,kNCHhBK,OAAOC,cAAc,CAACf,QAAS,OAAQ,CACrCgB,YAAY,MACZC,IACS,sBAEX,yMCLAjB,QAAQK,IAAI,CAAG,sBAAA,CAAA,CAAA,6JAA0CI,KAAK,CAC7C,GAA4CA,KAAK,CAE7C,sBAAA,CAAA,CAAA,oKAAiDA,KAAK,+MCH3EP,WAAWC,gBAAgB,CAACC,IAAI,CAAC,oCACjCF,WAAWgB,uCAAuC,CAChD,CAAChB,WAAWgB,uCAAuC,EAAI,CAAC,EAAI,yMCF9DlB,QAAQS,KAAK,CAAG,yNCAhBT,QAAQK,IAAI,CAAG,mNCCfL,OAAO,CAACmB,AADY,OACA,CAAG,wBACvBnB,QAAQoB,KAAK,CAAG,qBAChBpB,QAAQqB,MAAM,CAAG,iNCHjBnB,WAAWC,gBAAgB,CAAG,EAAE,CAChCD,WAAWgB,uCAAuC,CAAG,EAErD,GAAM,CAAEb,KAAMiB,MAAM,CAAE,CAAA,sBAAA,CAAA,CAAA,0IAChBC,cAAgB,sBAAA,CAAA,CAAA,kJAA+BlB,IAAI,CACnDU,eAAiB,sBAAA,CAAA,CAAA,mJAAgCV,IAAI,CACrDmB,SAAW,sBAAA,CAAA,CAAA,4IAAyBnB,IAAI,CACxCoB,gBAAAA,sBAAAA,CAAAA,CAAAA,oJACAC,YAAc,sBAAA,CAAA,CAAA,+IAA4BrB,IAAI,CAC9CsB,cAAAA,sBAAAA,CAAAA,CAAAA,kJACAC,kBAAAA,sBAAAA,CAAAA,CAAAA,uJACAC,uBAAyB,sBAAA,CAAA,CAAA,4JAAyCxB,IAAI,CACtEyB,MAAAA,sBAAAA,CAAAA,CAAAA,2IACAC,OAAAA,sBAAAA,CAAAA,CAAAA,2IAEAC,OAAS,CACbC,OAAQ,CACNX,OACAC,cACAR,eACAS,SACAC,gBAAiBA,gBAAgBS,OAAO,CACxCC,aAAcV,gBAAgBL,KAAK,CACnCM,YACAC,cAAeA,cAActB,IAAI,CACjCwB,sBACF,EACAO,MAAOlC,WAAWC,gBAAgB,CAClCkC,0BAA2BnC,WAAWgB,uCAAuC,CAC7EoB,sBAAuBX,gBAAkBC,kBACzCW,MAAO,CACLC,SAASC,CAAQ,sBAAA,CAAa,CAAA,iJAAwC,CACtEC,MAAMD,CAAQ,sBAAA,CAAa,CAAA,sJAA6C,AAC1E,EACAX,MAAO,CACLxB,OAAQwB,MAAMxB,MAAM,CACpBE,MAAOsB,MAAMtB,KAAK,CAClBE,MAAOoB,MAAMpB,KAAK,CAClBiC,WAAYZ,OAAOnB,SAAS,CAC5BgC,UAAWb,OAAOlB,QAAQ,EAAI,IAChC,CACF,EAEAgC,QAAQC,GAAG,CAAC,CAAC,kBAAkB,EAAEC,KAAKC,SAAS,CAAChB,QAAAA,CAAS,8LCxCzDiB,QAAOjD,OAAO,CAAG,CAAEK,KAHN,qBAGmB,mMCHhCL,QAAQK,IAAI,CAAG,2BACfL,QAAQqB,MAAM,CAAG,yNCAjB4B,QAAOjD,OAAO,CAAA,sBAAA,CAAA,CAAA"}
\ No newline at end of file
var R=require("./[turbopack]_runtime.js")("output/index.entry.js")
R.c("output/1jsg_tests_snapshot_cjs-remove-unused-exports_webpack-parity_input_1sbzh_1p37sm6._.js")
R.m("[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/index.js [test] (ecmascript)")
module.exports=R.m("[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/webpack-parity/input/index.js [test] (ecmascript)").exports
\ 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