Skip to content

bundler: keep the CommonJS wrapper when the lift leaves a module.exports value behind - #35665

Open
robobun wants to merge 2 commits into
mainfrom
farm/6f5015a8/fix-cjs-module-exports-escape
Open

robobun wants to merge 2 commits into
mainfrom
farm/6f5015a8/fix-cjs-module-exports-escape

Conversation

@robobun

@robobun robobun commented Jul 25, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #12518
Related to #14939

Problem

  • bun build lifts a CommonJS file to ES exports (no __commonJS wrapper), even one that uses module.exports as a value. That bundle throws ReferenceError: exports_lib is not defined or reads wrong data, and the build exits 0.
  • A default import regressed in 1.4.1 (bundler: bind the default import of a lifted CommonJS module to its namespace #41162).
  • Cause: the lift verdict (src/js_parser/parse/parse_entry.rs:1600) did not test for a module.exports value.

Fix

  • Count the module.exports nodes that the lift turns into $name (module_exports_lifted_count). bundler: keep the CommonJS wrapper when a file uses module beyond module.exports #41262 counts the nodes made.
  • More made than lifted, and module used in a live statement: the file keeps its wrapper, as Node and esbuild do.
  • Verified: test/bundler/bundler_cjs2esm.test.ts (25 of 139 fail on main), 640 of 640 matrix cells equal Node (main 352), 30 bundler suites.
  • Self-reviewed: 10 concerns raised, 9 addressed. Rejected: a tracker for a file that Node rejects too.

Background

  • A lifted exports.foo = x prints as var $foo = x.
  • Considered: an exports_ref use count (misses a value that --minify-syntax inlines), a linker re-wrap (the parser still publishes the wrong lift).

Downsides

Notes

Repro (the default import form, a regression in 1.4.1)

// lib.cjs
exports.add = (a, b) => a + b;
exports.default = module.exports; // also: globalThis.myLib = module.exports, Object.freeze(module.exports)
// app.mjs
import lib from "./lib.cjs";
console.log(lib.add(1, 2));

bun build app.mjs --outfile o.js && bun o.js prints 3 on 1.4.0 and with this PR. On 1.4.1, 1.4.3 and main it throws ReferenceError: exports_lib is not defined. The silent form is exports.a = 1; exports.b = 2; exports.out = Object.keys(module.exports);. Node prints ["a","b"]. main prints ["a","b","out"], because the stand-in object gets every key before the first statement runs.

The older forms never worked: a named import, import *, a side-effect import and the file as the entry point (#12518, #14939). On main the real rehackt@0.1.0 file over react throws TypeError: undefined is not a function.

How the verdict works

  • maybe_rewrite_property_access (src/js_parser/fold.rs) turns each module.exports into one ESpecial::ModuleExports node and adds 1 to module_exports_rewrite_count. When a property access follows (module.exports.foo), the same function turns the node into $foo. That is the only consumer. It now adds 1 to module_exports_lifted_count.
  • The verdict in Parser::_parse runs once per file, after the visit. The new arm keeps the wrapper when module_exports_rewrite_count > module_exports_lifted_count and the use count of module is not 0.
  • The parser takes back use counts when it removes a statement, but it does not take back the two counters. The test on the use count of module covers that case: if no statement that stays uses module, then no module.exports node stays, and the file is lifted as on main. A file that keeps its wrapper through this arm always has a use of module, so the wrapper binds exports and module.
  • --minify-syntax visits an expression again after it inlines a single-use const. That revisit records no symbol uses, so a node that it turns into $name is not counted: const m = module.exports; return m.a + 1 keeps the wrapper with and without the flag.
  • The counters are read only for ESM output. --format=cjs, --format=iife and the runtime transpiler do not lift, and their output does not change.

Merge order

Known limits, with the owner of each

  1. A wrapped CommonJS file gives no static export names to the bundle. As the entry it prints export default require_x(); only. Behind export * from in an ESM entry it gives no names: import { y } from the bundle fails at link, and ns.y is undefined at exit 0. This is true for every wrapped CommonJS file on main (Bun.build commonjs named exports conversion to ESM is broken #12463): exports.add = ...; exports.keys = Object.keys(exports).join(); behind export * fails in the same way on main, and Node exports add. esbuild 0.21.5 and 0.28.2 print the same export default for 9 of 9 package files. This PR moves the files that use module.exports as a value into that group. On main they are lifted, so export * over them works: 24 of 24 cells (12 library shapes, a named import and a namespace read) go from right to wrong. export { add } from works. Effect on bun build generates undefined variable when bundling @swc/wasm-typescript #14939: the undeclared exports_wasm is gone and the file loads, but the reporter's import { transform } from the bundle of the CommonJS entry fails with does not provide an export named 'transform'. A default import of the bundle works, and so does an ESM entry with export { transform } from "@swc/wasm-typescript".
  2. A file with a real ES export or a top-level await next to a live module.exports value now gets the wrapper. The ES export then reads undefined (2 1 becomes undefined 1), and the top-level await is a SyntaxError at load. main does the same today for the bare exports spelling of the same files. Node cannot load these files at all. Owner: js_parser: make the ESM/CJS classification and the module/exports bindings agree #40840, js_parser: do not bind module or exports in a file whose module type is ESM #46037.
  3. A top-level using in a file that now keeps its wrapper, for --target=node and --target=browser: ReferenceError: exports_lib is not defined becomes undefined exports at exit 0. --target=bun is right. The lowering of using does this to every wrapped file on main. Owner: js_parser: split a lifted CommonJS export into a declaration and a store when lowering top-level using #45562. With js_parser: split a lifted CommonJS export into a declaration and a store when lowering top-level using #45562 merged on this PR, the case prints 1 a 2 for all three targets.
  4. An unwrap-list require() (for example require("scheduler") in react-dom) of a package that now keeps its wrapper gets a __toESM copy: the object has a default key and is not identical to module.exports. Every wrapped package on that list has this on main. Owner: bundler: skip __toESM for an unwrapped require() of a package that keeps its CommonJS wrapper #46215.
  5. A value in code that never runs but that the parser does not remove (an unused function declaration, var exports = module.exports) keeps the wrapper. The output is right. The bundle grows by 1370 to 1381 B, and such a file as the entry exports default only. None of the 340 package files of the census below has this shape. A removed statement that holds the value next to a live module.exports.x keeps the wrapper too, until js_parser: roll back a removed statement's tracked uses along with its use counts #45345 rolls both counters back.
  6. An ES-syntax file with no lifted name, or one that takes the force_esm break, is not touched: module.exports["§"] = () => {}; export const b = 1; still prints an undeclared exports_b. Owner: js_parser: make the ESM/CJS classification and the module/exports bindings agree #40840, js_parser: do not bind module or exports in a file whose module type is ESM #46037.
  7. module.exports still prints as the wrapper's exports parameter after code replaces module.exports through an alias of module. Same output on main. This is follow-up work.
  8. With --minify, a file that the linker of main already put back into a wrapper gets other minified names, at the same size (39 of 48 matrix cells).
  9. A file that keeps its wrapper is not tree-shaken per export. This is the same as for a file that uses exports as a value on main. Measured: 300 files with 20 exported functions and one export that returns module.exports, and an app that imports one function from each. main 30,803 B (18,112 B with --minify), this PR 484,543 B (301,979 B). With exports in place of module.exports in the same files, main and this PR both print 482,444 B. On main the small output is right only while nothing calls the export that returns module.exports.

Can export * keep the names that the file assigns statically?

Yes, for the static names, but it needs linker work that is not in this PR.

Measurements (release builds of main 8a0e49e and of this diff on it, Linux x64, Node v26.3.0 as the yardstick)

  • Matrix: 16 library shapes x 10 importer forms (default by value, default by property, named, namespace, require(), import(), side-effect, export *, entry, import() with --splitting) x 4 configs (--target=node, bun, browser, node --minify). 640 of 640 cells equal Node. main: 352 (276 ReferenceError, 8 silent, 4 failed builds). All 160 control cells print the same as on main, and their bundles are byte-identical. No cell of this matrix is right on main and wrong here. Its export * form is a barrel inside the bundle. An ES entry with export * is limit 1: 24 of 24 cells go from right to wrong.
  • 340 package files that read module.exports as a value: 9 change, all from an undeclared exports_<file> to a wrapper (ansi-escapes 4.3.2, vite 6.2.3 index.cjs, mysql2 3.7.0 lib/packets/index.js, @npmcli/fs 3.1.1 lib/cp/errors.js, @swc/wasm and @swc/wasm-typescript 1.16.20 wasm.js, @prisma/prisma-schema-wasm 5.22.0, rehackt 0.1.0 index.js and rsc.js). On main 9 of 9 throw at load. Here 9 of 9 load. Other esm or esm --minify outputs changed: 0. iife and cjs outputs changed: 0.
  • As ESM entries the 9 files go from 192 export names in a bundle that throws at load to export default only. @swc/wasm-typescript behind export *: 64 names to 0.
  • An alias of module (exports.get = function () { const m = module; return m.exports.a + 1; }), 3 import forms x 4 flag sets (none, --minify-syntax, --minify, --production): 6 of 12 bundles differ from the unbundled program on main (ReferenceError: $a is not defined), 0 of 12 here. 1.4.0: 4 of 12. 1.4.1: 6 of 12.
  • react 18.3.1, 4 entry points x 4 modes: 0 of 16 builds differ (cmp).
  • Bundle bytes: the repro above 104 to 1485 B, the silent form 597 to 1537 B. The 9 package files: +267 B median, +398 B max, and 4 shrink (to -2965 B).
  • Output that main got right and that changes: export * inside a bundle +359 to +425 B (36 of 42 cells), a default import read by property +894 B (3 of 9 cells), the shapes of limit 5 +1370 to +1381 B (11 of 39 probed rows). All of them equal Node. No wrapper is printed without an exports parameter.
  • Instructions (gdb single-step): a lifted module.exports.x statement +3, an exports.x statement +1, a plain a.b.c; +0, --format=iife +0. Parser::_parse: +15 for a file with 12 lifted exports.x, +42 with 12 lifted module.exports.x, +0 for a plain file in a bundle and under bun run.
  • Size: size_of P 4080 to 4080 bytes (the u32 takes the tail padding). Release .text +0 B, file size of bun +0 B. maybe_rewrite_property_access -5 B, Parser::_parse +8 B and +5 B, P::init -7 B (nm -S). 8 of 140,561 sized symbols differ.

Tests

  • bun bd test test/bundler/bundler_cjs2esm.test.ts: 139 pass. On a release build of main: 114 pass, 25 fail.
  • New: the three default import forms, the key order form (default, named, export *), eight parent expressions (typeof, in, ?., spread, module["exports"], a computed key, a nested function with a local exports, destructuring), the entry point, a side-effect import, import() with --splitting, a React-family require(), a TypeScript file with import type, a dead exports = {}, a removed statement next to a live value, --minify-syntax aliases (const m = module and const m = module.exports, through a named import and through a default import that only calls get()), --target=bun, Bun.build with minifyIdentifiers, and rehackt@0.1.0/index.js as it is over a lifted and over a wrapped react.
  • Controls that stay lifted: a property read through module.exports, a read in dead code, a read in a statement that the parser removes.
  • cjs2esm/DeleteFoldedModuleExportsRef pinned the undeclared name and said the bundle cannot run. It now runs.
  • Also run on the debug build, same results as main: bundler_cjs, bundler_edgecase, bundler_minify, bundler_splitting, bundler_barrel, bundler_npm, bundler_regressions, bundler_browser, bundler_bun, bundler_jsx, bundler_string, bundler_loader, bundler_plugin, bundler_drop, bundler_naming, bundler_comments, bundler_feature_flag, bundler_defer, esbuild/default, esbuild/importstar, esbuild/importstar_ts, esbuild/dce, esbuild/extra, esbuild/packagejson, esbuild/ts, esbuild/tsconfig, esbuild/splitting, esbuild/loader, transpiler/preserve-use-strict-cjs, transpiler/function-tostring-require. The one failure, default/TopLevelAwaitForbiddenRequireSourceMapCLI, is a 5 s timeout that the debug build of main has too.

Self-review

  • Addressed in code: the arm now needs a live use of module (no wrapper for a value that only a removed statement holds, and no count of exports uses), one-line comments, two tests with the real rehackt file over react.
  • Addressed in this text: Related to #14939 in place of a closing keyword, the merge order, and the limits with their owners.
  • Follow-up work outside this PR: static export names for a wrapped CommonJS entry, the stale exports of limit 7, and a check in the itBundled harness for a generated name that nothing declares.
  • Rejected: a tracker for import os from "node:os"; globalThis.hasFoo = !!exports.foo;, which prints an undeclared exports_lib. Node throws ReferenceError: exports is not defined in ES module scope for the same file.

History

The first version of this PR (July) recorded a use of exports_ref at the rewrite and took it back at the property access. It had the same outcome for the first visit. It missed the module.exports that the --minify-syntax revisit makes or takes (const m = module.exports; return m.a + 1 printed $a is not defined), and it changed the shared use count for output formats that never lift. Its seven tests are kept.


[review] gate passed · iteration 2 · 2 files touched

fails on main (without fix)
ASAN without fix: 6 FAILED
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" "test/bundler/bundler_cjs2esm.test.ts"
bun test v1.4.0 (b5d5e2cf3)

test/bundler/bundler_cjs2esm.test.ts:
(pass) bundler > cjs2esm/ModuleExportsFunction [1737.57ms]
(pass) bundler > cjs2esm/ImportNamedFromExportStarCJSModuleRef [749.28ms]
(pass) bundler > cjs2esm/ImportNamedFromExportStarCJS [1485.24ms]
(pass) bundler > cjs2esm/BadNamedImportNamedReExportedFromCommonJS [2348.02ms]
(pass) bundler > cjs2esm/ExportsFunction [1461.89ms]
(pass) bundler > cjs2esm/ModuleExportsFunctionTreeShaking [5635.53ms]
(pass) bundler > cjs2esm/ModuleExportsEqualsRequire [1003.65ms]
(pass) bundler > cjs2esm/ModuleExportsBasedOnNodeEnvProduction [2867.45ms]
(pass) bundler > cjs2esm/ModuleExportsBasedOnNodeEnvDevelopment [1965.79ms]
(pass) bundler > cjs2esm/ModuleExportsEqualsRuntimeCondition [1631.32ms]
(pass) bundler > cjs2esm/UnwrappedModuleRequireAssigned [2284.03ms]
(pass) bundler > cjs2esm/ReactSpecificUnwrapping [1746.46ms]
(pass) bundler > cjs2esm/ReactSpecificUnwrapping2 [3384.06ms]
(pass) bundler > cjs2esm/ModuleExportsRenamingNoDeopt [1524.21ms]
... (truncated)

release without fix: 12 FAILED
bun test v1.4.0-canary.1 (1498d7b77)

test/bundler/bundler_cjs2esm.test.ts:
(pass) bundler > cjs2esm/ModuleExportsFunction [519.67ms]
(pass) bundler > cjs2esm/ImportNamedFromExportStarCJSModuleRef [37.39ms]
(pass) bundler > cjs2esm/ImportNamedFromExportStarCJS [39.37ms]
(pass) bundler > cjs2esm/BadNamedImportNamedReExportedFromCommonJS [38.44ms]
(pass) bundler > cjs2esm/ExportsFunction [85.04ms]
(pass) bundler > cjs2esm/ModuleExportsFunctionTreeShaking [34.86ms]
(pass) bundler > cjs2esm/ModuleExportsEqualsRequire [99.23ms]
(pass) bundler > cjs2esm/ModuleExportsBasedOnNodeEnvProduction [81.11ms]
(pass) bundler > cjs2esm/ModuleExportsBasedOnNodeEnvDevelopment [573.02ms]
(pass) bundler > cjs2esm/ModuleExportsEqualsRuntimeCondition [155.55ms]
(pass) bundler > cjs2esm/UnwrappedModuleRequireAssigned [549.05ms]
(pass) bundler > cjs2esm/ReactSpecificUnwrapping [317.46ms]
(pass) bundler > cjs2esm/ReactSpecificUnwrapping2 [244.83ms]
(pass) bundler > cjs2esm/ModuleExportsRenamingNoDeopt [87.84ms]
(pass) bundler > cjs2esm/ModuleExportsRenamingAssignDeOpt [103.92ms]
(pass) bundler > cjs2esm/ModuleExportsRenamingAssignExportsDeOpt [41.76ms]
397 |   // converted to `var $x = ...; 
... (truncated)
passes on PR (with fix)
ASAN with fix: all passed
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" "test/bundler/bundler_cjs2esm.test.ts"
bun test v1.4.0 (b5d5e2cf3)

test/bundler/bundler_cjs2esm.test.ts:
(pass) bundler > cjs2esm/ModuleExportsFunction [2726.00ms]
(pass) bundler > cjs2esm/ImportNamedFromExportStarCJSModuleRef [1823.76ms]
(pass) bundler > cjs2esm/ImportNamedFromExportStarCJS [1240.65ms]
(pass) bundler > cjs2esm/BadNamedImportNamedReExportedFromCommonJS [1404.92ms]
(pass) bundler > cjs2esm/ExportsFunction [1237.35ms]
(pass) bundler > cjs2esm/ModuleExportsFunctionTreeShaking [988.88ms]
(pass) bundler > cjs2esm/ModuleExportsEqualsRequire [950.13ms]
(pass) bundler > cjs2esm/ModuleExportsBasedOnNodeEnvProduction [1091.48ms]
(pass) bundler > cjs2esm/ModuleExportsBasedOnNodeEnvDevelopment [1977.02ms]
(pass) bundler > cjs2esm/ModuleExportsEqualsRuntimeCondition [1272.89ms]
(pass) bundler > cjs2esm/UnwrappedModuleRequireAssigned [1969.08ms]
(pass) bundler > cjs2esm/ReactSpecificUnwrapping [1161.44ms]
(pass) bundler > cjs2esm/ReactSpecificUnwrapping2 [2812.23ms]
(pass) bundler > cjs2esm/ModuleExportsRenamingNoDeopt [917.97ms]
(
... (truncated)

release with fix: all passed
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped) in 2380ms (unchanged)
ninja: Entering directory `/workspace/bun/build/release'
[1/51] gen cpp.rs (cppbind)
[2/51] gen generated_host_exports.rs
generated_host_exports.rs: 94 exports (host=3, lazy=10, generic=81, rust=0); 239 extern-C blocks audited
[2/51] cargo bun_bin → libbun_rust.a (--target x86_64-unknown-linux-gnu)

  nightly-2026-07-20-x86_64-unknown-linux-gnu unchanged - rustc 1.99.0-nightly (9f36de775 2026-07-19)

^[[1m^[[92m   Compiling^[[0m bun_js_parser v0.0.0 (/workspace/bun/src/js_parser)
^[[1m^[[92m   Compiling^[[0m bun_js_printer v0.0.0 (/workspace/bun/src/js_printer)
^[[1m^[[92m   Compiling^[[0m bun_resolver v0.0.0 (/workspace/bun/src/resolver)
^[[1m^[[92m   Compiling^[[0m bun_ini v0.0.0 (/workspace/bun/src/ini)
^[[1m^[[92m   Compiling^[[0m bun_router v0.0.0 (/workspace/bun/src/router)
^[[1m^[[92m   Compiling^[[0m bun_bundler v0.0.0 (/workspace/bun/src/bundler)
^[[1m^[[92m   Compiling^[[0m bun_standalone_graph v0.0.0 (/workspace/bun/src/standalone_graph)
^[[1m^[[92m   Compiling^[[0m bun_transpiler v0.0.0 (/workspace/bun/src/transpiler)
^[[1m^[[92m   Compiling^[[0m bun_bunfig v0.0.0 (/workspa
... (truncated)
diff hotspot
src/js_parser/fold.rs                |   8 ++-
 test/bundler/bundler_cjs2esm.test.ts | 118 +++++++++++++++++++++++++++++++++++
 2 files changed, 125 insertions(+), 1 deletion(-)

gate history · 1 passed · 0 rejected · iteration 2

evidence per changed file
file                                  reads  edits  tests
src/js_parser/fold.rs                     6      5      0
test/bundler/bundler_cjs2esm.test.ts      3      4      0

@coderabbitai

coderabbitai Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 7 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used all 10 included reviews currently available.

Learn how review limits work.

Review configuration:

Run configuration
Commits

Reviewing files that changed from the base of the PR and between 92e819d and 1111240.

Files selected for processing: 5
  • docs/bundler/index.mdx
  • src/js_parser/fold.rs
  • src/js_parser/p.rs
  • src/js_parser/parse/parse_entry.rs
  • test/bundler/bundler_cjs2esm.test.ts
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@robobun

robobun commented Jul 25, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 9:11 AM PT - Oct 27th, 2026

✅ @robobun, your commit 111124029e214d9aaff07941eae573bc08d6d5ff passed in Build #133694! 🎉


🧪   To try this PR locally:

bunx bun-pr 35665

That installs a local version of the PR into your bun-35665 executable, so you can run:

bun-35665 --bun

@github-actions

Copy link
Copy Markdown
Contributor

Found 4 issues this PR may fix:

  1. bun build generates undefined variable when bundling @swc/wasm-typescript #14939 - module.exports passed as a bare value (imports[...] = module.exports) causes bundler to generate undefined exports_wasm variable
  2. bun build bundling of CJS require("node:assert") does not properly expose exports. and returns an empty {} object #19808 - node:assert CJS bundling loses exports because module.exports = assert function assignment is incorrectly unwrapped to ESM
  3. bundling require("moment") throws "moment is not a function" #5004 - require("moment") throws "not a function" because the function export via module.exports is unwrapped to a plain object
  4. Error when importing a CommonJS package #26901 - CJS package import produces double-nested defaults due to incorrect unwrapping of module.exports

If this is helpful, copy the block below into the PR description to auto-close these issues on merge.

Fixes #14939
Fixes #19808
Fixes #5004
Fixes #26901

🤖 Generated with Claude Code

@robobun

robobun commented Jul 25, 2026 •

Copy link
Copy Markdown
Collaborator Author

Reproduced on main (8a0e49e), 1.4.1 and 1.4.3 with the default import form:

// lib.cjs
exports.add = (a, b) => a + b;
exports.default = module.exports;
// app.mjs
import lib from "./lib.cjs";
console.log(lib.add(1, 2));
bun build app.mjs --outfile o.js && bun o.js   # ReferenceError: exports_lib is not defined

1.4.0 and Node print 3. With exports.out = Object.keys(module.exports) in place of the second line, main prints ["a","b","out"] and Node prints ["a","b"]. The real rehackt@0.1.0 file over react (#12518) throws TypeError: undefined is not a function.

The branch is rebased onto main (92e819d). bun bd test test/bundler/bundler_cjs2esm.test.ts passes 139 of 139 with the change. 25 of them fail on a build of main.

PR: #35665

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't find any bugs, but this touches the CJS→ESM unwrapping heuristic in the parser — a shared hot path whose record/ignore usage balance is subtle — so it's worth a human look.

What was reviewed:

  • Traced the record_usage(exports_ref) / ignore_usage(exports_ref) balance across the module.exports → ESpecial::ModuleExports rewrite and the consuming property-access arm; confirmed they cancel for module.exports.foo and stay unbalanced when the value escapes.
  • Checked the deopt trigger at parse_entry.rs:1499 and that the extra exports_ref use is harmless when unwrap_commonjs_to_esm is off (module_ref already forces CJS; commonjs_named_exports stays empty).
  • Checked is_control_flow_dead and commonjs_named_exports_deoptimized gating on both arms — no path records without the matching ignore being reachable except where deopt is already set.
Extended reasoning...

Overview

Two files changed. src/js_parser/fold.rs adds a record_usage(exports_ref) at the point where module.exports is rewritten to ESpecial::ModuleExports, and a balancing ignore_usage(exports_ref) in the ESpecial::ModuleExports target arm that fires when the value is immediately consumed by a static property access. When module.exports escapes as a value (function argument, computed index, stored), the unbalanced use makes uses_exports_ref true, which the existing check at parse_entry.rs:1499 uses to call deoptimize_commonjs_named_exports() and keep the module wrapped as CommonJS. Six new itBundled tests cover the rehackt/Object.assign pattern, generic escape, computed index, namespace import, and a negative regression check that plain module.exports.X = ... still converts.

Security risks

None. This is a bundler correctness change to symbol usage counting; no untrusted input parsing, auth, crypto, or filesystem behavior is touched.

Level of scrutiny

High. maybe_rewrite_property_access runs on every property access in every bundled file, and the CJS→ESM unwrapping decision affects tree-shaking and named-import resolution for any CommonJS module. The record/ignore pair lives in two different match arms with slightly different guards: the record is gated only on !commonjs_named_exports_deoptimized, while the ignore is additionally gated on should_unwrap_common_js_to_esm(). I traced why this asymmetry is safe (when unwrap is off, commonjs_named_exports is never populated so the parse_entry.rs:1499 deopt condition can't fire, and uses_module_ref is already true from the module identifier so exports_kind is unchanged), but a maintainer familiar with this code should confirm there's no other consumer of the exact exports_ref use count that this could perturb. The delete module.exports.foo path also records without ignoring (the delete-target early return precedes the new ignore_usage), but that path already calls deoptimize_common_js_named_exports() so the extra count is redundant, not wrong.

Other factors

The PR description states all 29 bundler_cjs2esm tests pass plus bundler_cjs, bundler_edgecase, bundler_npm, and the esbuild default/importstar/dce suites — that's the right coverage set for this change. The ModuleExportsPropertyReadStillConverts test with cjs2esm: true is a good regression guard against over-deoptimizing. The comments added are load-bearing (they explain the non-local record/ignore pairing). Given the blast radius of the shared code path and the subtlety of the balance, deferring for a human sanity check.

@robobun

robobun commented Jul 25, 2026 •

Copy link
Copy Markdown
Collaborator Author

Of the four suggested, only #14939 is about this fault (module.exports read as a value). The description says what this change does for it and what stays open. #19808, #5004 and #26901 are about module.exports = <function or object> assignment, which takes the assign_target == Replace path and is untouched here.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't find any bugs. The record/ignore balancing is sound and the test coverage is thorough, but this changes the CJS→ESM unwrapping heuristic in a way that affects how real npm packages get flattened, so it's worth a maintainer sanity-check.

What was reviewed:

  • Traced the deopt path: unbalanced record_usage(exports_ref) → uses_exports_ref → deoptimize_commonjs_named_exports() at parse_entry.rs:1499 → is_deoptimized_commonjs() → ExportsKind::Cjs.
  • Confirmed ESpecial::ModuleExports is only produced at fold.rs:349, so every instance reaching the balancing arm has a matching record_usage.
  • Checked the should_unwrap_common_js_to_esm() == false imbalance is benign (module_ref stays used, so the module was already CJS); same for the is_delete_target early-return before ignore_usage.
  • Both sides are consistently gated on !is_control_flow_dead / !is_revisit_for_substitution.
Extended reasoning...

Overview

Two files touched: a 6-line change in src/js_parser/fold.rs (maybe_rewrite_property_access) and 7 new itBundled cases in test/bundler/bundler_cjs2esm.test.ts. The Rust change adds record_usage(exports_ref) where module.exports is rewritten to ESpecial::ModuleExports, and a balancing ignore_usage(exports_ref) where that special is immediately consumed by a static property access. When module.exports escapes as a value (Object.assign target, computed index, function argument), the use stays unbalanced, uses_exports_ref flips true, and the existing deopt at parse_entry.rs:1499 keeps the module wrapped as CommonJS instead of synthesizing an incomplete ESM export set.

Security risks

None. This is a build-time bundler heuristic; no untrusted input parsing, no auth/crypto/permissions surface.

Level of scrutiny

Medium-high. The diff is tiny, but the CJS→ESM unwrapping heuristic is load-bearing for how thousands of npm packages get flattened in --target=bun and --compile. The correctness of the fix depends on a cross-call invariant (record in the inner module.exports visit, ignore in the outer .foo visit) holding under all the surrounding gates. I verified the invariant against the current gates: both sides are guarded by !is_control_flow_dead / !is_revisit_for_substitution (via record_usage/ignore_usage themselves), and the record side is additionally inside !commonjs_named_exports_deoptimized which the ignore side matches. The one asymmetry — record fires regardless of should_unwrap_common_js_to_esm() but ignore requires it — is benign because module_ref is never ignored on this path, so uses_module_ref was already forcing CJS in that configuration. The is_delete_target early-return before ignore_usage also leaves an unbalanced use, but that path calls deoptimize_common_js_named_exports() anyway.

Other factors

Test coverage is strong: named import, namespace import, the exact rehackt shape with the dead if (0) hint, computed index, arbitrary function escape, the wasm-bindgen shape from #14939, plus ModuleExportsPropertyReadStillConverts as a regression guard that pure module.exports.X = Y modules still flatten (cjs2esm: true asserts no __commonJS wrapper). The author reports the full bundler_cjs2esm suite plus bundler_edgecase, bundler_npm, and the esbuild suites are clean. Deferring because a maintainer should confirm they're comfortable with the balancing approach vs. e.g. threading an explicit "escaped" flag, and because changes to this heuristic have historically had long tails in the npm ecosystem.

@robobun
robobun force-pushed the farm/6f5015a8/fix-cjs-module-exports-escape branch from 2fae94a to b5d5e2c Compare August 1, 2026 08:17
@robobun

robobun commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

Rebased onto main at 3ff3579 and re-verified: the real @apollo/client + rehackt@0.1.0 repro now bundles and runs correctly with --target=bun, all 30 tests in bundler_cjs2esm.test.ts pass (6 new cases fail without the src/ change), and bundler_cjs, bundler_edgecase, esbuild/importstar, esbuild/dce show no regressions.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't find any bugs. The record/ignore balance is sound and the regression guard (ModuleExportsPropertyReadStillConverts) confirms straightforward module.exports.X still unwraps. That said, this adjusts the CJS→ESM unwrapping heuristic in the parser — a subtle area where the failure mode is silent bundle-size regression for packages that were previously flattened — so it's worth a maintainer look.

What was reviewed:

  • Verified record_usage/ignore_usage are symmetric (both gated on !is_control_flow_dead && !is_revisit_for_substitution) and that the unbalanced use hits the existing deopt at parse_entry.rs:1441.
  • Checked the should_unwrap_common_js_to_esm() gate asymmetry between the record site and the ignore site — it's correct: when unwrapping is off, ESpecial::ModuleExports stays in the output and prints as exports_ref, so the recorded use is accurate.
  • Confirmed both maybe_rewrite_property_access callers (EDot and EIndex-with-string-key in visit_expr.rs) reach the balancing arm; only optional_chain skips it, which safely deopts.
Extended reasoning...

Overview

The PR changes 4 lines of logic in src/js_parser/fold.rs::maybe_rewrite_property_access and adds 7 itBundled cases to test/bundler/bundler_cjs2esm.test.ts. The fix records a use of exports_ref when module.exports is rewritten to ESpecial::ModuleExports, and balances it with ignore_usage when that node is immediately consumed as the target of a property access. Net effect: a bare/escaping module.exports value leaves an unbalanced use, making uses_exports_ref true and triggering the pre-existing deopt in parse_entry.rs so the module stays wrapped as CommonJS instead of being flattened with an incomplete static export set.

Security risks

None. This is compile-time bundler heuristics with no untrusted-input parsing, no allocation sizing, and no runtime code.

Level of scrutiny

High. The CJS→ESM unwrapper decides whether npm packages get flattened for tree-shaking. The change is small and the direction of failure is safe (over-deopt → wrap, which is always semantically correct), but the record/ignore pairing depends on the exact visit order and gate conditions matching between two separate match arms. I traced the callers in visit_expr.rs — both the EDot path (line 1423) and the EIndex-with-string-literal path (line 1037) route through maybe_rewrite_property_access and reach the balancing ESpecial::ModuleExports arm. The optional_chain.is_none() guard on both callers means module.exports?.foo would leave an unbalanced use and deopt, which is a harmless (and vanishingly rare) over-conservatism. The is_delete_target early-return in the ModuleExports arm skips the ignore_usage, but that path already calls deoptimize_common_js_named_exports() so the extra use is moot.

I also checked the gate asymmetry: record_usage is not gated on should_unwrap_common_js_to_esm() while ignore_usage is. This is correct — when the option is off, the ESpecial::ModuleExports node is not rewritten to a CommonJSExportIdentifier and prints as exports_ref, so the recorded use accurately reflects the output. And with the option off, commonjs_named_exports stays empty so the parse_entry.rs:1441 deopt condition (count() > 0) can't fire spuriously.

Other factors

Test coverage is thorough: five deopt shapes (Object.assign, dead-hint rehackt pattern, namespace import, function-arg escape, computed index, wasm-bindgen store-before-assign) plus one regression guard proving the simple property-access case still converts with cjs2esm: true. The author reports bundler_cjs, bundler_edgecase, bundler_npm, and the esbuild suites show no new failures, and verified against the real @apollo/client+rehackt and @swc/wasm-typescript reproductions. I'm deferring rather than approving because this is a heuristic change in core bundler logic where the interesting risk — a common npm shape that was previously unwrapped now getting wrapped — wouldn't show up as a test failure, only as a bundle-size regression, and a maintainer who owns this code is better placed to judge that.

@robobun

robobun commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

Verified this also covers the entry-file form of the bug (no importer at all), in addition to the side-effect import form:

// lib.cjs, built as the entry: bun build --target=browser lib.cjs
module.exports.answer = 42;
console.log(typeof module.exports);             // 1.4.3 bundle: "undefined"
console.log(Object.keys(module.exports).join()); // 1.4.3 bundle: ReferenceError: exports_lib is not defined

With the two fold.rs hunks from this PR applied on current main, the entry keeps its __commonJS wrapper (export default require_lib()) and prints object / answer for --target=browser|node|bun and --minify, same as node. It might be worth adding that shape as a test here. The branch currently conflicts with main in fold.rs (main added p.module_exports_rewrite_count += 1; right before the rewrite); the resolution is to keep both lines.

@robobun

robobun commented Oct 11, 2026

Copy link
Copy Markdown
Collaborator Author

I ran the used-import forms of this bug on main (7c96a1212f), once as is and once with the two fold.rs hunks of this PR applied. Both are debug builds of the same commit. The expected output of each cell is what node prints for the unbundled app.

Library shapes (lib.cjs, each one also has exports.add = (a, b) => a + b;):

  1. exports.default = module.exports;
  2. module.exports.default = module.exports;
  3. Object.assign(module.exports, { sub: (a, b) => a - b });
  4. Object.defineProperty(module.exports, "__esModule", { value: true });
  5. Object.freeze(module.exports);
  6. globalThis.myLib = module.exports;
  7. console.log("keys", Object.keys(module.exports).join());

Import forms: import lib, import { add }, import * as ns, require(), await import(). Each app calls add(1, 2).

block cells main main + this PR
7 shapes x 5 import forms 35 14 right 35 right
same, the library is a package in node_modules (bare specifier) 35 14 right 35 right
2 controls x 5 import forms (exports.add only, module.exports = { add }) 10 10 right 10 right
side-effect import, and the library as the entry file, 7 shapes 14 0 right 14 right
silent form (below), 5 apps 5 1 right 5 right

The counts are per mode, and they are the same for --target=node, --target=bun, --target=browser and --target=node --minify. The package block ran with --target=node only. On main, the 21 wrong cells are import lib, import { add } and import * as ns for all 7 shapes. Each one is ReferenceError: exports_lib is not defined at load (a one-letter name with --minify), and bun build exits 0.

Silent form

// lib.cjs
exports.a = 1;
exports.b = 2;
exports.out = Object.keys(module.exports);
// app.mjs
import lib from "./lib.cjs";
console.log(JSON.stringify(lib.out ?? lib.add(1, 2)));

node prints ["a","b"]. main prints ["a","b","out"]. The lifted file starts with var exports_lib = {}; __exportCjs(exports_lib, { a, b, out }), so the object has every key before the first statement runs. The result is the same when lib.nope, lib[k] or lib.extra = 1 is the expression that keeps the object. The fifth app stores the whole lib in a global, and it is right on main too. With this PR the file keeps its wrapper and all five print ["a","b"].

Emitted code, shape 1 with import { add }:

// main
var $add = (a, b) => a + b;
var $default = exports_lib;          // never declared
console.log($add(1, 2));

// main + this PR
var require_lib = __commonJS(function(exports, module) {
  exports.add = (a, b) => a + b;
  exports.default = exports;
});
var import_lib = __toESM(require_lib(), 1);
console.log(import_lib.add(1, 2));

What still lifts with this PR: a file that only writes exports.x or module.exports.x, and a file that reads a property through module.exports (module.exports.twice = x => module.exports.add(x, x) gives no __commonJS).

For the rebase

  • The conflict in fold.rs is one line. main has p.module_exports_rewrite_count += 1; in front of the return Some(Expr { ... ESpecial::ModuleExports ... }). Keep that line and put the record_usage after it. The second hunk applies as it is.
  • cjs2esm/DeleteFoldedModuleExportsRef in test/bundler/bundler_cjs2esm.test.ts fails with this PR. It is a shape check for delete (0, exports_<name>), and its comment says the bundle cannot be executed because of this bug. The new output is delete (0, exports) inside the __commonJS wrapper. That output is correct and it runs, so the test needs the new pattern and can get a run step.
  • Suites on main + this PR: bundler_cjs2esm, bundler_cjs, esbuild/default, esbuild/importstar, bundler_npm, bundler_regressions give 437 pass and 3 fail. One is the test above. The other two are default/TopLevelAwaitForbiddenRequireSourceMapCLI and ...API. They hit the 5 s limit in this debug build without the PR too, and they pass with a longer limit.

…orts` value behind

`bun build` with ESM output lifts a CommonJS file that has `exports.x = ...`
lines into ES module exports. It did that even when the file also used
`module.exports` as a value (`exports.default = module.exports`,
`Object.assign(module.exports, ...)`, `Object.keys(module.exports)`). The
value then printed as `exports_<file>`, a name that nothing declares, or
as a stand-in object that has every key before the first statement runs.

The parser makes one ESpecial::ModuleExports node for each
`module.exports` and counts it (module_exports_rewrite_count, #41262).
The lift consumes a node when a property access turns it into `$name`.
Count those too (module_exports_lifted_count). When the parser made more
nodes than the lift consumed, and a statement that is not removed still
uses `module`, the file keeps its `__commonJS` wrapper. It then has one
real exports object.

A node that the --minify-syntax substitution revisit consumes is not
counted, because the revisit does not record the use of `$name`.

Fixes #12518
@robobun robobun changed the title bundler: keep CJS wrapped when module.exports escapes as a value bundler: keep the CommonJS wrapper when the lift leaves a module.exports value behind Oct 27, 2026
@robobun
robobun force-pushed the farm/6f5015a8/fix-cjs-module-exports-escape branch from b5d5e2c to 9ac77ed Compare October 27, 2026 11:04

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Findings marked 🟡 are optional suggestions and need no follow-up push.

Additional findings (outside the current diff — GitHub can't attach inline comments there):

  • 🟡 src/js_parser/parse/parse_entry.rs — Bundles of a CommonJS file that also contains a top-level await and touches module.exports as a value now fail to load with a SyntaxError, where the base produced a bundle that ran when the value branch was cold. The force_esm break at src/js_parser/parse/parse_entry.rs:1591-1597 fires only when every export is a bare read, so a file with exports.a = 1, if (cond) globalThis.lib = module.exports and await x falls through to the new arm at parse_entry.rs:1610 and keeps a wrapper; await inside the __commonJS function is a SyntaxError. Fix: never wrap a file that has top_level_await_keyword or esm_export_keyword set; route those through the force_esm path, or report a build error that names the file, instead of printing an unparseable bundle.

    Why this was flagged

    Trigger: a .js file with exports.a = 1; if (typeof window !== "undefined") window.lib = module.exports; await Promise.resolve(); bundled to ESM for a server target. has_es_module_syntax is set by the top-level await, but needs_decl_count is 0 because exports.a is assigned, so parse_entry.rs:1594 does not take the force_esm break. parse_entry.rs:1604 does not fire (use 1, rewrite 1). parse_entry.rs:1610 fires (rewrite 1 > lifted 0, use 1) and calls deoptimize_commonjs_named_exports at parse_entry.rs:1616, so parse_entry.rs:1917 sets ExportsKind::Cjs before the top_level_await_keyword check at parse_entry.rs:1919. The linker then wraps the body in a non-async __commonJS closure and the await is a syntax error at load; the base lifted the file and the undeclared exports_lib reference threw only if the cold branch ran. Population: bundle authors with mixed files that Bun's runtime accepts; the build still exits 0, so the failure surfaces at deploy. Remedy: exclude files with a top-level await or ES export keyword from the new arm and emit a diagnostic.

    Verification: Trigger: a bundled-to-ESM file with lifted exports.a = 1, a live module.exports value use and a top-level await. The new arm at src/js_parser/parse/parse_entry.rs:1610-1616 fires and the deopt check at 1917-1920 wins over the TLA check, so the file gets WrapKind::Cjs and await lands inside a sync function: SyntaxError at load. On base exports_kind is Esm via 1919 and the bundle runs whenever the value branch is cold.

  • 🟡 src/js_parser/p.rs — Users who build with tree shaking off, or a file with a top-level using, get a CommonJS wrapper and lose static named exports for files whose only module.exports value use the parser already removed. With one part (src/js_parser/parse/parse_entry.rs:1108) the dead-part rollback at src/js_parser/p.rs:5552 never runs, so module keeps the use from a removed (function(){ return module.exports }) while the counters at src/js_parser/fold.rs:444 and fold.rs:734 are never rolled back; parse_entry.rs:1610 then wraps. Fix: roll back module_exports_rewrite_count and module_exports_lifted_count together with the use counts of a removed statement, in both the per-statement and single-part paths, so the verdict reflects only live statements.

    Why this was flagged

    Trigger: exports.y = 1; (function unused() { return module.exports; }); bundled with tree shaking disabled or with a top-level using in the file, which puts every statement in one part (src/js_parser/parse/parse_entry.rs:1108-1110). The visit removes the unused function expression, but src/js_parser/p.rs:5503-5562 only clears use counts when the whole part is empty, so module keeps use 1. src/js_parser/fold.rs:444 counted 1 rewrite, fold.rs:734 counted 0 lifts. parse_entry.rs:1610 sees 1 > 0 && 1 > 0 and wraps. On the base the same file is lifted (first arm: 1 > 1 is false), and ModuleExportsValueOnlyInRemovedStatementStillConverts pins the lift only for the default tree-shaking configuration. Consequence: the entry-point form prints export default require_x(); only and export * from an ESM wrapper exposes no names, so named imports of the bundle fail at load, plus +1.3 KB per file. Population: Bun.build callers with treeShaking disabled and every file with a top-level using. Remedy: decrement both counters when a statement that produced them is removed.

    Verification: nit — triggered when the whole file is one part (src/js_parser/parse/parse_entry.rs:1108-1110) and a side-effect-free top-level expression statement contains module.exports as a bare value. The rollback runs only when part_stmts is empty (src/js_parser/p.rs:5552), so module stays at use 1. On the base commit the same file is lifted.

Comment thread src/js_parser/parse/parse_entry.rs Resolved
@robobun

robobun commented Oct 27, 2026

Copy link
Copy Markdown
Collaborator Author

On the two optional findings:

Top-level await next to a module.exports value. Confirmed: exports.a = 1; if (cond) window.lib = module.exports; await x; now keeps the wrapper, and await inside __commonJS is a SyntaxError at load. This is limit 2 in the PR body. On main the same file prints an undeclared exports_t and throws as soon as the branch runs. Node does not load this file at all: the await makes it an ES module, where exports is not defined. The existing arm for module.constructor gives a file with top-level await the same wrapper on main. A build error for a wrapped file with top-level await is the right end state for that whole class, and #40840 and #46037 own it.

Single part with tree shaking off, or with a top-level using. I could not reproduce this one. exports.y = 1; (function unused() { return module.exports; }); is lifted with --no-tree-shaking, with --no-tree-shaking --minify-syntax, and with a top-level using in the file (--target=bun, with and without --minify-syntax). The output is var $y = 1; export { $y as y }; in every case, the same as on main.

…y-syntax

`import alias from "./alias.cjs"; alias.get()` binds the lifted `get`, as a
named import does. With --minify-syntax, a file that reaches its exports
through `const m = module` or `const m = module.exports` printed
`$a is not defined` for that form since 1.4.1. The named import form was
the only one in the test.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code review completed

Nothing new to post: everything this review found is already covered by existing comments on this pull request or didn't merit a separate one.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Compile Issue w/ @apollo/client

2 participants