Repository navigation
Conversation
…ed "module.exports" export
…blocks In a require cycle the namespace is live. One try block held both reads, so a TDZ `__esModule` export hid an initialized "module.exports" export, and require() returned and cached the namespace. The default Module._extensions handlers have the same two lines.
…"module.exports" A compiled file still returns the namespace: six expected failures in the parity run, and one line in the compatibility page. An ES file that a compiled program loads from disk goes through require() of the compiled library (the second text of builtins/CommonJS): a stored program covers it.
|
Status: ready for review. No CI failure comes from this change. How I reproduced it: the three files under "Repro" in the description. CI (build 140781, finished): 186 jobs passed, also the ASAN lanes. The new tests ran and passed, for example
Four other tests failed once and passed on a retry. |
|
Updated 3:06 PM PT - Nov 12th, 2026
❌ @robobun, your commit d2218c2 has 10 failures in
🧪 To try this PR locally: bunx bun-pr 48743That installs a local version of the PR into your bun-48743 --bun |
|
No actionable comments were generated in the recent review. WalkthroughCommonJS conversion paths now read ChangesESM require during evaluation
Suggested reviewers: Merge Risk:
|
There was a problem hiding this comment.
Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.
Beyond the inline findings, I also checked the AOT second text: the SHA-256 in the header of src/js/ahead-of-time/builtins/CommonJS.ts matches the primary file after this change, and the two edited hunks are identical in both texts (the remaining differences are the pre-existing AOT-only lines). I found no other in-tree site that reads __esModule and "module.exports" from a live namespace in one try block; the engine's copy (whatRequireMakesOfNamespace) is in oven-sh/WebKit, outside this repo. I did not run the test suite or the AOT parallel fixture, so the claim that the 12 new tests fail on main and pass here is unverified by this review.
Extended reasoning...
The change splits one try block into two at four sites (overridableRequire and requireESMFromHijackedExtension in the primary and AOT copies of CommonJS.ts), updates the AOT header hash, adds tests for the require-cycle TDZ case across require/import.meta.require/createRequire/Module.prototype.require/_extensions handlers, registers six AOT expected failures, adds one AOT fixture, and adds one line to docs/compiler/compatibility.mdx. It touches the module loader but no auth, crypto, or input-parsing surface. Inline findings already exist (a nit about an unproven second try, and two pre-existing namespace-caching gaps the PR description itself excludes), so this note only records what else was ruled out by reading.
Additional findings (outside the current diff — GitHub can't attach inline comments there):
-
🟣
src/js/builtins/CommonJS.ts— Callers who readrequire.cache[path]for an import-loaded ES module, thenrequire()it, still get the namespace instead of its "module.exports" value. The split at src/js/builtins/CommonJS.ts:141-143 fixes only the two require tails. createRequireCache at src/js/builtins/CommonJS.ts:280-284 is a third site that turns a namespace into a cache entry and never applies the"module.exports"/__esModulerule, somod.exportsis the namespace and the laterrequire()at :181-185 hands it out. Fix: apply the same two reads (each in its own try) wherever a namespace becomesmod.exports, by extracting one helper used at :138-159, :232-253 and :280-284.Why this was flagged
Trigger: an ES module with
export { x as "module.exports" }is loaded byimport; some CJS code (patchers like require-in-the-middle, or any code that touchesrequire.cache[key]) reads the proxy at src/js/builtins/CommonJS.ts:274-289 before anyone callsrequire()on that path. The get trap at :280-284 calls$esmNamespaceForCjsand$createCommonJSModule(key, namespace, true, owner), storing the raw namespace asmod.exportsand inserting it intorequireMap. The nextrequire()of that path hits theloadedbranch of the require path and returns the namespace, never the "module.exports" value. The base branch behaves the same, but this PR's stated rule is 'one export in TDZ hides only itself' and REVIEW.md says to fix every sibling site of the same pattern in the same PR; this is the one site that producesmod.exportsfrom a namespace without the rule, and the PR excludes it only by description. Remedy: route :280-284 through the same read-both-exports helper as the two require tails.Verification: Pre-existing: the diff does not touch this path and the base fails the same way. The proxy get trap at src/js/builtins/CommonJS.ts:280-284 calls
$esmNamespaceForCjs(key, owner)and then$createCommonJSModule(key, namespace, true, owner); neither reads"module.exports"or__esModule. The nextrequire()then hitsrequireMap.$get(id)at CommonJS.ts:46-47 and returnsexisting.exportsat :69, the namespace.
…s in TDZ The read of "module.exports" throws there, and the second try block of requireESMFromHijackedExtension swallows it. Without that block these two tests fail.
|
About the read of I did not put the two reads into the get trap. A read of The other two findings have replies in their threads. The handler test for the second |
There was a problem hiding this comment.
LGTM — the new commit covers the one gap I raised earlier (the second try in requireESMFromHijackedExtension is now exercised by the both-in-TDZ handler tests), and the source change itself is a two-line split at each of the four sites.
What was reviewed:
- Both texts of CommonJS.ts: the split is identical at all four read sites, and the SHA-256 recorded in the ahead-of-time header matches src/js/builtins/CommonJS.ts at HEAD; no other runtime site in this repo reads
namespace["module.exports"]. - Behaviour when only
__esModuleis in TDZ now falls through to the already-initialized"module.exports"value; every other state (both in TDZ,"module.exports"alone in TDZ,__esModulefalse) ends at the samemoduleExports ?? namespaceas before. - Tests follow the harness shape (tempDir, bunExe/bunEnv, Promise.all drain, whole-object toEqual, test.each / describe.concurrent); the AOT parity rows and the compatibility.mdx line record the engine-side gap rather than hide it.
- Not run here: the USE_SYSTEM_BUN=1 fail-on-unfixed-build check and the
--aotstored program; the claim that main fails the 12 new cases rests on the author's description.
Extended reasoning...
The diff splits one shared try block into two at the __esModule / "module.exports" reads in overridableRequire and requireESMFromHijackedExtension, mirrored in src/js/builtins/CommonJS.ts and src/js/ahead-of-time/builtins/CommonJS.ts with the header hash updated, plus tests, six AOT parity expected-failure rows, a stored AOT program and one docs line. It touches the CommonJS require loader but no auth, crypto, permission or input-parsing surface. The source change is small and purely additive (an export in TDZ now hides only its own read), the AOT twin is kept in sync, and the latest commit ce15f5f added the test I had asked for, so no open objection of mine remains; no CODEOWNERS entry covers the changed paths and the hunt ran dry with no findings.
Problem
require()of an ES module returns the namespace ([object Module]), not its"module.exports"export. It happens while its__esModuleexport is in TDZ.require.cachekeeps the namespace.tryblock holds both reads (src/js/builtins/CommonJS.ts:138and:230). The__esModuleread throws, so the"module.exports"read never runs.Fix
try, inoverridableRequireand inrequireESMFromHijackedExtension, which the defaultModule._extensionshandlers call.test/js/bun/resolve/require-esm-evaluating-cycle.test.ts,test/js/node/module/require-extensions.test.ts(main fails 12 new tests), one stored--aotprogram. Alsotest/js/node/module,test/js/bun/resolve,test/js/bun/test/mock.Background
letexport throws a ReferenceError until its declaration runs (TDZ)."module.exports"export names whatrequire()returns in place of the namespace.__esModuleis the mark that transpiled CommonJS code reads.src/js/ahead-of-time/builtins/CommonJS.tsis the builtin's second text, forbun build --compile --aot. Its header holds the SHA-256 of the first text.__importDefault(require(esm))until Give the module namespace prototype a Structure that prohibits property caching #48720 lands (Notes).Downsides
--aotstill returns the namespace: the engine answersrequire()there.test/aot/transpiler-parity-cases.tsanddocs/compiler/compatibility.mdxrecord it.jmpbytecode per firstrequire(esm)and 56 bytes of text. User instructions per firstrequire(esm): 140,160 to 140,334 (+0.12%), inside the 0.14% to 0.55% spread between runs.Notes
Repro
bun entry.mjsprintsinner [object Module] | later [object Module]on main andinner custom | later customwith this PR.Main is wrong in a fresh process and with the JIT off. After some tens of earlier
require()calls of ES modules it is often right: the__esModuleread then goes through the property cache that #48720 describes, and does not throw. This PR givescustomin each case.require()calls of ES modulesBUN_JSC_useJIT=0, after 0, 60, 150 and 300Where the state comes from
trycame with bundler: with --splitting --target bun, require() of an ES module is a chunk boundary #40519 (1a50bfa), under a comment that calls it a guard for TDZ.ERR_REQUIRE_CYCLE_MODULEfor arequire()of an ES module that is still evaluating. So the state exists only under Bun's rule that such arequire()returns the live namespace. require(esm): return the live namespace in a cycle that a require() began #48610 asks a maintainer whether that rule stays.Tests
require,import.meta.require,createRequire,Module.prototype.require), a CommonJS file requires it back, and a re-export of__esModulefrom a module that is still evaluating..mjs,.js,.ts,.ctsand.mtscalled by a file on itself, and a handler that calls the handler it replaced.[object Module], expectedcustom)."module.exports"itself is in TDZ:require()returns the namespace. It passes on main too. Its second row (both exports in TDZ) is the check that the new secondtryofoverridableRequireswallows its own throw..mjsand.ts, one for each native loader) call the default handler while both exports are in TDZ: the handler stores the namespace. They pass on main too. With the secondtryremoved fromrequireESMFromHijackedExtensionthese two fail, and the other 28 tests of the file pass.test/aot/parallel/code-from-disk-beside-the-compiled-library/it-requires-itself-before-its-mark-is-ready.cjsis a stored program fortest/aot/run-parallel.ts. A compiled program loads an ES file from disk (--aot-allow-code-from-disk), and that file goes throughrequire()of the compiled library, which is the second text. It is the only test that runs the second text's edit. A build of main prints[object Module]there, this PR printscustom, in all four build ways.What this PR does not change
--aot. The engine has its own copy of the rule (Modules::whatRequireMakesOfNamespacein oven-sh/WebKit), and it reads"module.exports"only after a successful read of__esModule. Five of the six cycle cases return the namespace when compiled, and the sixth is refused (this executable can't load a module from a dynamic path). Six rows intest/aot/transpiler-parity-cases.tslist them as expected failures.require()after a read ofrequire.cache[key]for an ES module that animportloaded. The read makes a cache entry with the namespace, andrequire()returns it, without a cycle. Main does the same."module.exports"export is in TDZ stays inrequire.cacheas the namespace after the export has its value.require()began: the inner call returns{}. That is the subject of require(esm): return the live namespace in a cycle that a require() began #48610.The native version that this PR replaced
An earlier version of this branch moved the rule into one native function, which
require()and the default handlers called, and deleted both JS tails. A self-review of it (36 concerns) ended with the verdict to send this guard first. The main reasons:__esModuleexport and does not lay the mark. Main's JS tail, once the JIT has compiled it, lays the mark through the property cache of Give the module namespace prototype a Structure that prohibits property caching #48720, and a warm reader ofmod.__esModulereads that mark. So tsc's__importDefault(require(esm))for a module that exports__esModule = truefailed withTypeError: lib.default is not a functionafter 130 earlier calls: in 10 of 20 runs with the native version, and in 1 of 20 on main. WithBUN_JSC_useConcurrentJIT=0it was 20 of 20 and 0 of 20. This PR leaves those lines as they are: the same probe works in 10 of 10 runs after 130 calls, with the concurrent JIT on and off, as on main.requireESMFromHijackedExtension, which require(esm): return the live namespace in a cycle that a require() began #48610 calls from new native code.require.cacheread stay.The native version is on the branch
robobun/6508bf3c/require-esm-native-interop. It fits after #48720 and #48610.The 8 steps of the verdict, all done here: the source files back to main except the two texts, the split at the four sites, the new SHA-256, the 12 tests, the six parity rows, the stored program, the line in
docs/compiler/compatibility.mdx, and no assertion on the cached answer of the other TDZ states.Measurements
Release builds of main at 7f964e6 and of the same commit with this PR's two source files, on one machine. #48677, the one commit on main after that, does not touch these two files.
overridableRequirebytecoderequireESMFromHijackedExtensionbytecoderequire(esm), minimum of 9 runsjmpto the next instruction between the two reads, which the normal path runs, and acatchwith ajmpfor the new handler, which run only after a throw.perf_event_open(user mode) around a process that requires 2,000 small ES modules, minus a process that requires none, divided by 2,000. The runs of one binary differ by 0.14% to 0.55%, so the difference between the binaries is inside the noise.Other open PRs
requireESMFromHijackedExtension, so it gets this fix.BUN_JSC_useJIT=0it is wrong in 40 of 40 runs. This PR does not depend on the cache.BunPlugin.cpp:3528,no member named 'SuspendExceptionScope' in namespace 'JSC', since AOT: strings that packages evaluate, modules in bundles, class factories, mocks in import cycles #48677). A debug build of this branch needs it too. I ran the debug tests with that include added locally.Suites
Release builds, main and this PR back to back:
test/js/node/module: 163 pass, 0 fail. Main: 157 pass, and it fails the 6 new handler tests.test/js/bun/resolve: 843 pass, 0 fail in the best of three runs. Main fails the 6 new cycle tests. Both builds have runs with timeouts (5 s limit) inload-same-js-file-a-lot.test.tsandimport-meta-glob.test.tson this machine.import-meta-glob.test.tsalone passes 399 of 399 on both, three times each.test/js/bun/test/mock: 1,314 pass on both.parity()oftest/aot/transpiler-parity-cases.ts): pass.it does not print what its last comment says.test/internal/second-texts-of-modules.test.ts,test/internal/export-lists-of-both-texts-of-modules.test.ts,test/internal/arms-of-modules-for-compiled-programs.test.ts,test/aot/the-two-texts-of-a-library-file-read-the-same-names.test.ts: pass.Debug ASAN build of this branch on ccb3611, with the include of #48722 added locally: the two test files pass (9 and 30 tests), and the stored program passes in all four build ways.