From 0b289f8bc8c5a7be65bfda6d8b4098d3f0542f27 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 14 Aug 2026 19:04:12 +0000 Subject: [PATCH 01/10] require(): run a module again after an earlier load of it threw When a module's load goes through the module registry (a file the transpiler classifies as ESM, a CommonJS file first reached via import(), a plugin module, a direct require.extensions call) and it throws while being evaluated, the module is removed from the require map but the registry keeps the failed entry, and JSModuleLoader::loadModule settles every later load of that key with the stored error. Every later require() therefore rethrew the same exception instead of running the file again, while require.cache already reported the module as absent. Drop a failed registry entry before loading a module on behalf of require(), in fetchCommonJSModule and in the builtin Module._extensions loaders. Entries that are still loading or loaded successfully are left alone, since they may belong to an in-flight import(). import() of a failed module is unchanged. --- src/jsc/bindings/JSCommonJSExtensions.cpp | 2 + src/jsc/bindings/ModuleLoader.cpp | 43 +++++ src/jsc/bindings/ModuleLoader.h | 5 + test/cli/test/isolation.test.ts | 39 +++++ test/js/bun/resolve/require.test.ts | 183 +++++++++++++++++++++- 5 files changed, 271 insertions(+), 1 deletion(-) diff --git a/src/jsc/bindings/JSCommonJSExtensions.cpp b/src/jsc/bindings/JSCommonJSExtensions.cpp index eb8baaf5dee3..5c18f7f6dcdf 100644 --- a/src/jsc/bindings/JSCommonJSExtensions.cpp +++ b/src/jsc/bindings/JSCommonJSExtensions.cpp @@ -264,6 +264,8 @@ JSC::EncodedJSValue builtinLoader(JSC::JSGlobalObject* globalObject, JSC::CallFr res.success = false; memset(&res.result, 0, sizeof res.result); + evictFailedModuleRegistryEntry(global, specifierWtfString); + JSValue result = fetchCommonJSModuleNonBuiltin( global->bunVM(), vm, diff --git a/src/jsc/bindings/ModuleLoader.cpp b/src/jsc/bindings/ModuleLoader.cpp index 5c412ae16422..0d45d4cdd95f 100644 --- a/src/jsc/bindings/ModuleLoader.cpp +++ b/src/jsc/bindings/ModuleLoader.cpp @@ -29,6 +29,7 @@ #include #include +#include #include #include #include @@ -655,6 +656,46 @@ void evaluateCommonJSCustomExtension( RETURN_IF_EXCEPTION(scope, ); } +static bool moduleRegistryEntryFailed(JSC::ModuleRegistryEntry* entry) +{ + switch (entry->status()) { + case JSC::ModuleRegistryEntry::Status::FetchFailed: + case JSC::ModuleRegistryEntry::Status::InstantiationFailed: + case JSC::ModuleRegistryEntry::Status::EvaluationFailed: + return true; + default: + break; + } + // A module that threw while being evaluated as a dependency of some other + // module's graph keeps Status::Fetched; the error is recorded on its record. + auto* record = dynamicDowncast(entry->record()); + return record && record->evaluationError(); +} + +// A require() that throws removes the module from the require map +// (finishRequireWithError, the catch blocks in CommonJS.ts) so that, as in Node, +// the next require() runs the file again. If that load went through the module +// registry (a file the transpiler classified as ESM, a CommonJS file first +// reached via import(), a plugin module), the registry still holds the entry +// with the error stored on it, and JSModuleLoader::loadModule settles every +// later load of that key with the stored error without running anything. Only +// failed entries are dropped: an entry that is still loading or loaded fine may +// belong to an in-flight import(), and dropping it would evaluate that module +// twice. +void evictFailedModuleRegistryEntry(Zig::GlobalObject* globalObject, const WTF::String& specifier) +{ + auto* moduleLoader = globalObject->moduleLoader(); + auto key = JSC::Identifier::fromString(globalObject->vm(), specifier); + auto* entry = moduleLoader->registryEntry(key); + if (!entry || !moduleRegistryEntryFailed(entry)) + return; + + // JSModuleLoader::visitChildrenImpl iterates these maps on the GC thread + // under cellLock(); take the same lock so the removal can't race it. + WTF::Locker locker { moduleLoader->cellLock() }; + moduleLoader->removeEntry(key); +} + JSValue fetchCommonJSModule( Zig::GlobalObject* globalObject, JSCommonJSModule* target, @@ -675,6 +716,8 @@ JSValue fetchCommonJSModule( BunString specifier = Bun::toString(specifierWtfString); + evictFailedModuleRegistryEntry(globalObject, specifierWtfString); + bool wasModuleMock = false; // When "bun test" is enabled, allow users to override builtin modules diff --git a/src/jsc/bindings/ModuleLoader.h b/src/jsc/bindings/ModuleLoader.h index 790ddf09041c..aa6d0bc3e9f4 100644 --- a/src/jsc/bindings/ModuleLoader.h +++ b/src/jsc/bindings/ModuleLoader.h @@ -105,6 +105,11 @@ JSValue fetchCommonJSModule( BunString* referrer, BunString* typeAttribute); +// Call before loading a module on behalf of require(): drops the module +// registry entry for `specifier` if an earlier load of it failed, so the module +// is evaluated again instead of rethrowing the stored error. +void evictFailedModuleRegistryEntry(Zig::GlobalObject* globalObject, const WTF::String& specifier); + template JSValue fetchCommonJSModuleNonBuiltin( void* bunVM, diff --git a/test/cli/test/isolation.test.ts b/test/cli/test/isolation.test.ts index 2f052f268f16..270e1fb3d0c0 100644 --- a/test/cli/test/isolation.test.ts +++ b/test/cli/test/isolation.test.ts @@ -995,3 +995,42 @@ test.concurrent("--isolate: require(esm) caches a BunTranspiledModule SourceProv expect(exitCode, `run ${run}`).toBe(0); } }); + +// A module that throws while being evaluated is retried by the next require(). +// Under --isolate the first attempt leaves its SourceProvider in the cache, so +// the retry is served from there; it still has to get rid of the failed module +// registry entry the first attempt left behind, or it rethrows the stored error. +test.concurrent("--isolate: require() retries a cached module that threw", async () => { + using dir = tempDir("isolate-require-retry", { + // No CommonJS or ES module syntax on purpose: such files load through the + // module registry. + "flaky.js": ` + globalThis.evaluations = (globalThis.evaluations ?? 0) + 1; + if (globalThis.evaluations === 1) throw new Error("fail " + globalThis.evaluations); + `, + "a.test.ts": ` + import { test, expect } from "bun:test"; + import { isolatedModuleCacheSourceType } from "bun:internal-for-testing"; + + test("second require() evaluates the module again", () => { + const path = require.resolve("./flaky.js"); + expect(() => require("./flaky.js")).toThrow("fail 1"); + expect(isolatedModuleCacheSourceType(path)).not.toBeNull(); + require("./flaky.js"); + expect(globalThis.evaluations).toBe(2); + }); + `, + }); + + await using proc = Bun.spawn({ + cmd: [bunExe(), "test", "--isolate", "./a.test.ts"], + env: { ...bunEnv, BUN_FEATURE_FLAG_INTERNAL_FOR_TESTING: "1" }, + cwd: String(dir), + stderr: "pipe", + stdout: "pipe", + }); + const [, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stderr).toContain("1 pass"); + expect(stderr).toContain("0 fail"); + expect(exitCode).toBe(0); +}); diff --git a/test/js/bun/resolve/require.test.ts b/test/js/bun/resolve/require.test.ts index f305e55988a6..704e5c290e22 100644 --- a/test/js/bun/resolve/require.test.ts +++ b/test/js/bun/resolve/require.test.ts @@ -1,4 +1,4 @@ -import { bunRun, tempDirWithFiles } from "harness"; +import { bunRun, tempDir, tempDirWithFiles } from "harness"; import fs from "node:fs"; import path from "node:path"; const fixture = (...segs: string[]): string => path.join(import.meta.dirname, "fixtures", "require", ...segs); @@ -45,6 +45,187 @@ describe("require(specifier)", () => { it.todo("require('*.db') wraps a sqlite file in a Database object and exports it"); }); + // Like Node, a module that throws while it is being evaluated is dropped from + // the cache, and the next require() of it runs the file again. The fixtures + // below have no CommonJS or ES module syntax on purpose: Bun loads such files + // through the ES module registry, which also holds CommonJS files that were + // first reached via import() and modules provided by plugins. A failed entry + // in that registry used to make every later require() rethrow the stored + // error without running the module again. + describe.concurrent("when the module throws while being evaluated", () => { + // Throws the first `failures` times it is evaluated and succeeds afterwards. + const flakyModule = (failures: number) => /* js */ ` + globalThis.evaluations = (globalThis.evaluations ?? 0) + 1; + if (globalThis.evaluations <= ${failures}) throw new Error("fail " + globalThis.evaluations); + `; + + async function runEntry(files: Record) { + using dir = tempDir("require-throwing-module", files); + const { stdout, stderr, exitCode } = await bunRun(path.join(String(dir), "entry.js")); + expect(stderr).toBe(""); + expect(exitCode).toBe(0); + return JSON.parse(stdout); + } + + it("the next require() evaluates it again until it succeeds", async () => { + const result = await runEntry({ + "flaky.js": flakyModule(2), + "entry.js": /* js */ ` + const id = require.resolve("./flaky.js"); + const attempts = []; + for (let i = 0; i < 4; i++) { + let outcome; + try { + require("./flaky.js"); + outcome = "ok"; + } catch (e) { + outcome = e.message; + } + attempts.push({ outcome, cached: id in require.cache }); + } + console.log(JSON.stringify({ attempts, evaluations: globalThis.evaluations })); + `, + }); + expect(result).toEqual({ + attempts: [ + { outcome: "fail 1", cached: false }, + { outcome: "fail 2", cached: false }, + { outcome: "ok", cached: true }, + { outcome: "ok", cached: true }, + ], + evaluations: 3, + }); + }); + + it("require() evaluates a CommonJS module again after import() of it failed", async () => { + const result = await runEntry({ + "flaky.js": flakyModule(1) + `module.exports = { attempt: globalThis.evaluations };`, + "entry.js": /* js */ ` + (async () => { + let importOutcome, requireOutcome; + try { + await import("./flaky.js"); + importOutcome = "ok"; + } catch (e) { + importOutcome = e.message; + } + try { + requireOutcome = require("./flaky.js"); + } catch (e) { + requireOutcome = e.message; + } + console.log(JSON.stringify({ importOutcome, requireOutcome, evaluations: globalThis.evaluations })); + })(); + `, + }); + expect(result).toEqual({ importOutcome: "fail 1", requireOutcome: { attempt: 2 }, evaluations: 2 }); + }); + + it("require() evaluates it again after it threw as a dependency of an imported module", async () => { + const result = await runEntry({ + "flaky.js": flakyModule(1), + "parent.mjs": `import "./flaky.js";`, + "entry.js": /* js */ ` + (async () => { + let importOutcome, requireOutcome; + try { + await import("./parent.mjs"); + importOutcome = "ok"; + } catch (e) { + importOutcome = e.message; + } + try { + require("./flaky.js"); + requireOutcome = "ok"; + } catch (e) { + requireOutcome = e.message; + } + console.log(JSON.stringify({ importOutcome, requireOutcome, evaluations: globalThis.evaluations })); + })(); + `, + }); + expect(result).toEqual({ importOutcome: "fail 1", requireOutcome: "ok", evaluations: 2 }); + }); + + it("a module provided by a plugin is evaluated again by the next require()", async () => { + const result = await runEntry({ + "entry.js": /* js */ ` + Bun.plugin({ + name: "flaky virtual module", + setup(build) { + build.module("virtual:flaky", () => ({ + loader: "js", + contents: ${JSON.stringify(flakyModule(1) + `export const attempt = globalThis.evaluations;`)}, + })); + }, + }); + const attempts = []; + for (let i = 0; i < 2; i++) { + try { + attempts.push(require("virtual:flaky").attempt); + } catch (e) { + attempts.push(e.message); + } + } + console.log(JSON.stringify({ attempts, evaluations: globalThis.evaluations })); + `, + }); + expect(result).toEqual({ attempts: ["fail 1", 2], evaluations: 2 }); + }); + + it("calling require.extensions['.js'] directly evaluates it again", async () => { + const result = await runEntry({ + "flaky.js": flakyModule(1), + "entry.js": /* js */ ` + const Module = require("node:module"); + const filename = require.resolve("./flaky.js"); + const attempts = []; + for (let i = 0; i < 2; i++) { + const mod = new Module(filename); + mod.filename = filename; + try { + require.extensions[".js"](mod, filename); + attempts.push("ok"); + } catch (e) { + attempts.push(e.message); + } + } + console.log(JSON.stringify({ attempts, evaluations: globalThis.evaluations })); + `, + }); + expect(result).toEqual({ attempts: ["fail 1", "ok"], evaluations: 2 }); + }); + + // Only require() retries. An ES module that failed stays failed for + // import(), which rejects with the error the module threw, as in Node. + it("import() of an ES module that failed under require() still rejects with the original error", async () => { + const result = await runEntry({ + "bad.mjs": flakyModule(Infinity), + "entry.js": /* js */ ` + (async () => { + let requireError, importError; + try { + require("./bad.mjs"); + } catch (e) { + requireError = e; + } + try { + await import("./bad.mjs"); + } catch (e) { + importError = e; + } + console.log(JSON.stringify({ + requireError: requireError.message, + importRejectsWithSameError: importError === requireError, + evaluations: globalThis.evaluations, + })); + })(); + `, + }); + expect(result).toEqual({ requireError: "fail 1", importRejectsWithSameError: true, evaluations: 1 }); + }); + }); + describe("require.main", () => { let dir: string; From e0b9d1c113d5f46c0a8049cf72cad98a124b2e53 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 18 Sep 2026 21:27:18 +0000 Subject: [PATCH 02/10] require(): evict a failed registry entry without a second lock, only for what Node runs as CommonJS JSModuleLoader::removeEntry takes the loader's cellLock itself since the WebKit upgrade. The eviction held that lock around the call, so the second require() of a module that threw never returned. Call removeEntry bare, as main's other call sites do. Evict from the loader the load goes through: the requiring module's Bun.ModuleGraph's, or the global object's. The direct Module._extensions call now does this inside fetchCommonJSModuleNonBuiltin, which already has that loader, so ModuleLoader.h and JSCommonJSExtensions.cpp are unchanged. Evict only a module that Node would have run as CommonJS: an entry whose record has no import, export, top-level await or import.meta, or an entry with no JSModuleRecord (a CommonJS module that import() loaded first). An ES module that threw keeps its error for every later require(), as in Node. A failed fetch is left to the loader, which drops such an entry itself. --- src/jsc/bindings/JSCommonJSExtensions.cpp | 2 - src/jsc/bindings/ModuleLoader.cpp | 73 ++++++++++-------- src/jsc/bindings/ModuleLoader.h | 5 -- test/js/bun/module-graph/module-graph.test.ts | 17 +++++ test/js/bun/resolve/require.test.ts | 75 ++++++++++++++++--- 5 files changed, 123 insertions(+), 49 deletions(-) diff --git a/src/jsc/bindings/JSCommonJSExtensions.cpp b/src/jsc/bindings/JSCommonJSExtensions.cpp index 34122fa8fb62..4dece4f37e58 100644 --- a/src/jsc/bindings/JSCommonJSExtensions.cpp +++ b/src/jsc/bindings/JSCommonJSExtensions.cpp @@ -232,8 +232,6 @@ JSC::EncodedJSValue builtinLoader(JSC::JSGlobalObject* globalObject, JSC::CallFr JSC::VM& vm = globalObject->vm(); ErrorableResolvedSource res; - evictFailedModuleRegistryEntry(global, specifierWtfString); - JSValue result = fetchCommonJSModuleNonBuiltin( global->bunVM(), vm, diff --git a/src/jsc/bindings/ModuleLoader.cpp b/src/jsc/bindings/ModuleLoader.cpp index a416786b1f8f..49a1ca89d25f 100644 --- a/src/jsc/bindings/ModuleLoader.cpp +++ b/src/jsc/bindings/ModuleLoader.cpp @@ -29,7 +29,7 @@ #include #include -#include +#include #include #include #include @@ -643,44 +643,49 @@ void evaluateCommonJSCustomExtension( RETURN_IF_EXCEPTION(scope, ); } -static bool moduleRegistryEntryFailed(JSC::ModuleRegistryEntry* entry) +// import, export, top-level await or import.meta: the syntax that makes Node +// run a file as an ES module when its extension and package.json do not say. +static bool hasESModuleSyntax(JSC::AbstractModuleRecord* record) { - switch (entry->status()) { - case JSC::ModuleRegistryEntry::Status::FetchFailed: - case JSC::ModuleRegistryEntry::Status::InstantiationFailed: - case JSC::ModuleRegistryEntry::Status::EvaluationFailed: - return true; - default: - break; - } - // A module that threw while being evaluated as a dependency of some other - // module's graph keeps Status::Fetched; the error is recorded on its record. - auto* record = dynamicDowncast(entry->record()); - return record && record->evaluationError(); + auto* module = dynamicDowncast(record); + if (!module) + return false; + return !module->requestedModules().isEmpty() || !module->exportEntries().isEmpty() || module->hasTLA() || (module->features() & JSC::ImportMetaFeature); +} + +// Whether the next require() has to run the module of `entry` again: it threw +// while it was evaluated, and Node would have run it as CommonJS. That is a +// file with no ES module syntax (the transpiler defaults it to ESM), or a +// CommonJS module that import() loaded first (its entry has no JSModuleRecord). +// An ES module that threw keeps its error for every later load, as in Node. A +// failed fetch is not handled here: the loader drops that entry itself. +static bool shouldRequireEvaluateAgain(JSC::ModuleRegistryEntry* entry) +{ + auto* record = entry->record(); + bool threw = entry->status() == JSC::ModuleRegistryEntry::Status::EvaluationFailed; + // A module that threw as a dependency of some other module's graph keeps + // Status::Fetched; the error is recorded on its record. + if (auto* cyclic = dynamicDowncast(record)) + threw = threw || cyclic->evaluationError(); + return threw && !hasESModuleSyntax(record); } // A require() that throws removes the module from the require map // (finishRequireWithError, the catch blocks in CommonJS.ts) so that, as in Node, // the next require() runs the file again. If that load went through the module -// registry (a file the transpiler classified as ESM, a CommonJS file first -// reached via import(), a plugin module), the registry still holds the entry -// with the error stored on it, and JSModuleLoader::loadModule settles every -// later load of that key with the stored error without running anything. Only -// failed entries are dropped: an entry that is still loading or loaded fine may -// belong to an in-flight import(), and dropping it would evaluate that module -// twice. -void evictFailedModuleRegistryEntry(Zig::GlobalObject* globalObject, const WTF::String& specifier) +// registry, the registry still holds the entry with the error stored on it, and +// JSModuleLoader::loadModule settles every later load of that key with the +// stored error without running anything. No other entry is dropped: one that is +// still loading or loaded fine may belong to an in-flight import(), and dropping +// it would evaluate that module twice. `loader` is the one the load goes +// through: the requiring module's Bun.ModuleGraph's, or the global object's. +static void evictFailedModuleRegistryEntry(JSC::VM& vm, JSC::JSModuleLoader* loader, const WTF::String& specifier) { - auto* moduleLoader = globalObject->moduleLoader(); - auto key = JSC::Identifier::fromString(globalObject->vm(), specifier); - auto* entry = moduleLoader->registryEntry(key); - if (!entry || !moduleRegistryEntryFailed(entry)) + auto key = JSC::Identifier::fromString(vm, specifier); + auto* entry = loader->registryEntry(key); + if (!entry || !shouldRequireEvaluateAgain(entry)) return; - - // JSModuleLoader::visitChildrenImpl iterates these maps on the GC thread - // under cellLock(); take the same lock so the removal can't race it. - WTF::Locker locker { moduleLoader->cellLock() }; - moduleLoader->removeEntry(key); + loader->removeEntry(key); // takes the loader's cellLock itself } JSValue fetchCommonJSModule( @@ -702,7 +707,7 @@ JSValue fetchCommonJSModule( BunString specifier = Bun::toString(specifierWtfString); - evictFailedModuleRegistryEntry(globalObject, specifierWtfString); + evictFailedModuleRegistryEntry(vm, loader, specifierWtfString); bool wasModuleMock = false; @@ -872,6 +877,10 @@ JSValue fetchCommonJSModuleNonBuiltin( { JSC::JSModuleLoader* loader = Bun::moduleLoaderOf(globalObject, scope, target->moduleGraph()); RETURN_IF_EXCEPTION(scope, {}); + // A direct Module._extensions[ext](module, filename) call does not pass + // through fetchCommonJSModule. + if constexpr (isExtension) + evictFailedModuleRegistryEntry(vm, loader, specifierWtfString); Bun__transpileFile(bunVM, globalObject, specifier, referrer, typeAttribute, res, false, !isExtension, forceLoaderType); if (res->success && res->result.value.isCommonJSModule) { if constexpr (isExtension) { diff --git a/src/jsc/bindings/ModuleLoader.h b/src/jsc/bindings/ModuleLoader.h index 2db67b2977a2..17725477118c 100644 --- a/src/jsc/bindings/ModuleLoader.h +++ b/src/jsc/bindings/ModuleLoader.h @@ -106,11 +106,6 @@ JSValue fetchCommonJSModule( BunString* referrer, BunString* typeAttribute); -// Call before loading a module on behalf of require(): drops the module -// registry entry for `specifier` if an earlier load of it failed, so the module -// is evaluated again instead of rethrowing the stored error. -void evictFailedModuleRegistryEntry(Zig::GlobalObject* globalObject, const WTF::String& specifier); - template JSValue fetchCommonJSModuleNonBuiltin( void* bunVM, diff --git a/test/js/bun/module-graph/module-graph.test.ts b/test/js/bun/module-graph/module-graph.test.ts index c1cdf074e0df..63e7b9c645d7 100644 --- a/test/js/bun/module-graph/module-graph.test.ts +++ b/test/js/bun/module-graph/module-graph.test.ts @@ -1876,6 +1876,23 @@ describe("Bun.ModuleGraph — CommonJS surface per graph", () => { expect(Object.keys(require.cache).filter(k => k.endsWith("flaky.cjs"))).toEqual([]); rmSync(d, { recursive: true, force: true }); }); + test("a file with no module syntax that throws inside a graph is evaluated again by the graph's next require()", async () => { + // Such a file loads through the graph's own module registry, which kept the failed entry. + const d = fixture({ + "flaky.js": `attempts.n++; if (attempts.n < 3) throw new Error("attempt " + attempts.n);`, + "user.cjs": `exports.tryOnce = () => { try { require("./flaky.js"); return "ok" } catch (e) { return e.message } }`, + }); + const attempts = { n: 0 }; + const u = await ModuleGraph({ globals: { attempts } }).import(join(d, "user.cjs")); + expect([u.tryOnce(), u.tryOnce(), u.tryOnce(), u.tryOnce(), attempts.n]).toEqual([ + "attempt 1", + "attempt 2", + "ok", + "ok", + 3, + ]); + rmSync(d, { recursive: true, force: true }); + }); test("CommonJS code in graphs with different globals name sets resolves each graph's own names (one wrapper executable per name set)", async () => { const d = fixture({ "w.cjs": `module.exports = { a: typeof alpha === "undefined" ? "-" : alpha, b: typeof beta === "undefined" ? "-" : beta, p: typeof process.pid }`, diff --git a/test/js/bun/resolve/require.test.ts b/test/js/bun/resolve/require.test.ts index 704e5c290e22..0befe85f238a 100644 --- a/test/js/bun/resolve/require.test.ts +++ b/test/js/bun/resolve/require.test.ts @@ -47,11 +47,12 @@ describe("require(specifier)", () => { // Like Node, a module that throws while it is being evaluated is dropped from // the cache, and the next require() of it runs the file again. The fixtures - // below have no CommonJS or ES module syntax on purpose: Bun loads such files - // through the ES module registry, which also holds CommonJS files that were - // first reached via import() and modules provided by plugins. A failed entry + // below have no CommonJS or ES module syntax on purpose: Node runs such files + // as CommonJS, Bun loads them through the ES module registry, which also + // holds CommonJS files that were first reached via import(). A failed entry // in that registry used to make every later require() rethrow the stored - // error without running the module again. + // error without running the module again. A file with ES module syntax keeps + // its error, in Node too. describe.concurrent("when the module throws while being evaluated", () => { // Throws the first `failures` times it is evaluated and succeeds afterwards. const flakyModule = (failures: number) => /* js */ ` @@ -97,6 +98,27 @@ describe("require(specifier)", () => { }); }); + it("the next require() runs the file as it is on disk now", async () => { + const result = await runEntry({ + "fixed-later.js": `throw new Error("v1");`, + "entry.js": /* js */ ` + const path = require.resolve("./fixed-later.js"); + const attempt = () => { + try { + require(path); + return "ok, version " + globalThis.version; + } catch (e) { + return e.message; + } + }; + const before = attempt(); + require("node:fs").writeFileSync(path, "globalThis.version = 2;"); + console.log(JSON.stringify({ before, after: attempt() })); + `, + }); + expect(result).toEqual({ before: "v1", after: "ok, version 2" }); + }); + it("require() evaluates a CommonJS module again after import() of it failed", async () => { const result = await runEntry({ "flaky.js": flakyModule(1) + `module.exports = { attempt: globalThis.evaluations };`, @@ -155,14 +177,15 @@ describe("require(specifier)", () => { setup(build) { build.module("virtual:flaky", () => ({ loader: "js", - contents: ${JSON.stringify(flakyModule(1) + `export const attempt = globalThis.evaluations;`)}, + contents: ${JSON.stringify(flakyModule(1))}, })); }, }); const attempts = []; for (let i = 0; i < 2; i++) { try { - attempts.push(require("virtual:flaky").attempt); + require("virtual:flaky"); + attempts.push("ok"); } catch (e) { attempts.push(e.message); } @@ -170,7 +193,7 @@ describe("require(specifier)", () => { console.log(JSON.stringify({ attempts, evaluations: globalThis.evaluations })); `, }); - expect(result).toEqual({ attempts: ["fail 1", 2], evaluations: 2 }); + expect(result).toEqual({ attempts: ["fail 1", "ok"], evaluations: 2 }); }); it("calling require.extensions['.js'] directly evaluates it again", async () => { @@ -196,9 +219,41 @@ describe("require(specifier)", () => { expect(result).toEqual({ attempts: ["fail 1", "ok"], evaluations: 2 }); }); - // Only require() retries. An ES module that failed stays failed for - // import(), which rejects with the error the module threw, as in Node. - it("import() of an ES module that failed under require() still rejects with the original error", async () => { + // Only require() retries, and only what Node runs as CommonJS. A file with + // ES module syntax that threw is not evaluated again: as in Node, every + // later require() and import() of it gets the error it threw. + it("an ES module is not evaluated again", async () => { + const result = await runEntry({ + "bad.mjs": flakyModule(1) + `export const attempt = globalThis.evaluations;`, + "entry.js": /* js */ ` + (async () => { + const errors = []; + for (let i = 0; i < 2; i++) { + try { + require("./bad.mjs"); + } catch (e) { + errors.push(e); + } + } + try { + await import("./bad.mjs"); + } catch (e) { + errors.push(e); + } + console.log(JSON.stringify({ + messages: errors.map(e => e.message), + sameError: errors.every(e => e === errors[0]), + evaluations: globalThis.evaluations, + })); + })(); + `, + }); + expect(result).toEqual({ messages: ["fail 1", "fail 1", "fail 1"], sameError: true, evaluations: 1 }); + }); + + // import() never retries: it rejects with the error the module threw under + // require(), also for a file that the next require() would run again. + it("import() of a module that failed under require() rejects with the original error", async () => { const result = await runEntry({ "bad.mjs": flakyModule(Infinity), "entry.js": /* js */ ` From 87a6662329ba1ac790923e27d4856f6188ba6f60 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 18 Sep 2026 21:46:12 +0000 Subject: [PATCH 03/10] ModuleLoader: shorten the comments on the failed-entry eviction --- src/jsc/bindings/ModuleLoader.cpp | 38 ++++++++++++------------------- 1 file changed, 14 insertions(+), 24 deletions(-) diff --git a/src/jsc/bindings/ModuleLoader.cpp b/src/jsc/bindings/ModuleLoader.cpp index 49a1ca89d25f..4e1cc2b6e947 100644 --- a/src/jsc/bindings/ModuleLoader.cpp +++ b/src/jsc/bindings/ModuleLoader.cpp @@ -643,8 +643,8 @@ void evaluateCommonJSCustomExtension( RETURN_IF_EXCEPTION(scope, ); } -// import, export, top-level await or import.meta: the syntax that makes Node -// run a file as an ES module when its extension and package.json do not say. +// The syntax that makes Node run a file as an ES module when its extension +// and package.json do not decide. static bool hasESModuleSyntax(JSC::AbstractModuleRecord* record) { auto* module = dynamicDowncast(record); @@ -653,39 +653,30 @@ static bool hasESModuleSyntax(JSC::AbstractModuleRecord* record) return !module->requestedModules().isEmpty() || !module->exportEntries().isEmpty() || module->hasTLA() || (module->features() & JSC::ImportMetaFeature); } -// Whether the next require() has to run the module of `entry` again: it threw -// while it was evaluated, and Node would have run it as CommonJS. That is a -// file with no ES module syntax (the transpiler defaults it to ESM), or a -// CommonJS module that import() loaded first (its entry has no JSModuleRecord). -// An ES module that threw keeps its error for every later load, as in Node. A -// failed fetch is not handled here: the loader drops that entry itself. -static bool shouldRequireEvaluateAgain(JSC::ModuleRegistryEntry* entry) +// The module threw while it was evaluated, and Node runs it as CommonJS (no ES +// module syntax, or no JSModuleRecord at all). Node re-runs such a module on the +// next require(). An ES module keeps its error. +static bool threwAsCommonJS(JSC::ModuleRegistryEntry* entry) { auto* record = entry->record(); bool threw = entry->status() == JSC::ModuleRegistryEntry::Status::EvaluationFailed; - // A module that threw as a dependency of some other module's graph keeps - // Status::Fetched; the error is recorded on its record. + // A dependency that threw inside another module's graph keeps Status::Fetched. if (auto* cyclic = dynamicDowncast(record)) threw = threw || cyclic->evaluationError(); return threw && !hasESModuleSyntax(record); } -// A require() that throws removes the module from the require map -// (finishRequireWithError, the catch blocks in CommonJS.ts) so that, as in Node, -// the next require() runs the file again. If that load went through the module -// registry, the registry still holds the entry with the error stored on it, and -// JSModuleLoader::loadModule settles every later load of that key with the -// stored error without running anything. No other entry is dropped: one that is -// still loading or loaded fine may belong to an in-flight import(), and dropping -// it would evaluate that module twice. `loader` is the one the load goes -// through: the requiring module's Bun.ModuleGraph's, or the global object's. +// A failed require() drops its module from the require map, but the registry +// entry keeps the error and JSModuleLoader::loadModule replays it on every later +// load. Only a failed entry is removed: a pending or loaded one may belong to an +// in-flight import(). static void evictFailedModuleRegistryEntry(JSC::VM& vm, JSC::JSModuleLoader* loader, const WTF::String& specifier) { auto key = JSC::Identifier::fromString(vm, specifier); auto* entry = loader->registryEntry(key); - if (!entry || !shouldRequireEvaluateAgain(entry)) + if (!entry || !threwAsCommonJS(entry)) return; - loader->removeEntry(key); // takes the loader's cellLock itself + loader->removeEntry(key); } JSValue fetchCommonJSModule( @@ -877,8 +868,7 @@ JSValue fetchCommonJSModuleNonBuiltin( { JSC::JSModuleLoader* loader = Bun::moduleLoaderOf(globalObject, scope, target->moduleGraph()); RETURN_IF_EXCEPTION(scope, {}); - // A direct Module._extensions[ext](module, filename) call does not pass - // through fetchCommonJSModule. + // A direct Module._extensions[ext]() call skips fetchCommonJSModule. if constexpr (isExtension) evictFailedModuleRegistryEntry(vm, loader, specifierWtfString); Bun__transpileFile(bunVM, globalObject, specifier, referrer, typeAttribute, res, false, !isExtension, forceLoaderType); From 0e4e67f88a7fc172f6da6a4a8be1910c8544411c Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 18 Sep 2026 22:34:15 +0000 Subject: [PATCH 04/10] require(): drop the --isolate source cache entry with a failed registry entry delete require.cache[key] evicts both the registry entry and the --isolate SourceProvider cache. The retry of a module that threw now does the same, so it reads the file from disk again in every mode. --- src/jsc/bindings/ModuleLoader.cpp | 4 +++- test/cli/test/isolation.test.ts | 18 +++++++++--------- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/src/jsc/bindings/ModuleLoader.cpp b/src/jsc/bindings/ModuleLoader.cpp index 4e1cc2b6e947..dbc72ccdb64a 100644 --- a/src/jsc/bindings/ModuleLoader.cpp +++ b/src/jsc/bindings/ModuleLoader.cpp @@ -669,7 +669,8 @@ static bool threwAsCommonJS(JSC::ModuleRegistryEntry* entry) // A failed require() drops its module from the require map, but the registry // entry keeps the error and JSModuleLoader::loadModule replays it on every later // load. Only a failed entry is removed: a pending or loaded one may belong to an -// in-flight import(). +// in-flight import(). The retry reads the file again, as `delete require.cache[key]` +// does, so the --isolate source cache is dropped with the entry. static void evictFailedModuleRegistryEntry(JSC::VM& vm, JSC::JSModuleLoader* loader, const WTF::String& specifier) { auto key = JSC::Identifier::fromString(vm, specifier); @@ -677,6 +678,7 @@ static void evictFailedModuleRegistryEntry(JSC::VM& vm, JSC::JSModuleLoader* loa if (!entry || !threwAsCommonJS(entry)) return; loader->removeEntry(key); + Bun::IsolatedModuleCache::evict(vm, specifier); } JSValue fetchCommonJSModule( diff --git a/test/cli/test/isolation.test.ts b/test/cli/test/isolation.test.ts index 2d8fd4c320ac..a8898c061917 100644 --- a/test/cli/test/isolation.test.ts +++ b/test/cli/test/isolation.test.ts @@ -1781,27 +1781,27 @@ test.concurrent("--isolate: require(esm) caches a BunTranspiledModule SourceProv }); // A module that throws while being evaluated is retried by the next require(). -// Under --isolate the first attempt leaves its SourceProvider in the cache, so -// the retry is served from there; it still has to get rid of the failed module -// registry entry the first attempt left behind, or it rethrows the stored error. +// Under --isolate the first attempt leaves its SourceProvider in the cache and +// a failed entry in the module registry. The retry drops both, so it reads the +// file from disk again instead of rethrowing the stored error. test.concurrent("--isolate: require() retries a cached module that threw", async () => { using dir = tempDir("isolate-require-retry", { // No CommonJS or ES module syntax on purpose: such files load through the // module registry. - "flaky.js": ` - globalThis.evaluations = (globalThis.evaluations ?? 0) + 1; - if (globalThis.evaluations === 1) throw new Error("fail " + globalThis.evaluations); - `, + "flaky.js": `throw new Error("fail 1");`, "a.test.ts": ` import { test, expect } from "bun:test"; + import { writeFileSync } from "node:fs"; import { isolatedModuleCacheSourceType } from "bun:internal-for-testing"; test("second require() evaluates the module again", () => { const path = require.resolve("./flaky.js"); expect(() => require("./flaky.js")).toThrow("fail 1"); - expect(isolatedModuleCacheSourceType(path)).not.toBeNull(); + expect(isolatedModuleCacheSourceType(path)).toBe("BunTranspiledModule"); + writeFileSync(path, "globalThis.fixed = true;"); require("./flaky.js"); - expect(globalThis.evaluations).toBe(2); + expect(globalThis.fixed).toBe(true); + expect(isolatedModuleCacheSourceType(path)).toBe("BunTranspiledModule"); }); `, }); From db728c77fbbfa8029c538d9686f1305ee05b58ba Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 19 Sep 2026 01:31:10 +0000 Subject: [PATCH 05/10] require tests: move the Bun.ModuleGraph retry case into require.test.ts The case spawns one child process like its neighbours, so it does not need module-graph.test.ts. That file has 293 tests, several of which heat JIT tiers against a 5 s limit, and running it next to the concurrent require and --isolate tests on a debug build makes those time out. --- test/js/bun/module-graph/module-graph.test.ts | 17 ------------ test/js/bun/resolve/require.test.ts | 27 +++++++++++++++++++ 2 files changed, 27 insertions(+), 17 deletions(-) diff --git a/test/js/bun/module-graph/module-graph.test.ts b/test/js/bun/module-graph/module-graph.test.ts index 63e7b9c645d7..c1cdf074e0df 100644 --- a/test/js/bun/module-graph/module-graph.test.ts +++ b/test/js/bun/module-graph/module-graph.test.ts @@ -1876,23 +1876,6 @@ describe("Bun.ModuleGraph — CommonJS surface per graph", () => { expect(Object.keys(require.cache).filter(k => k.endsWith("flaky.cjs"))).toEqual([]); rmSync(d, { recursive: true, force: true }); }); - test("a file with no module syntax that throws inside a graph is evaluated again by the graph's next require()", async () => { - // Such a file loads through the graph's own module registry, which kept the failed entry. - const d = fixture({ - "flaky.js": `attempts.n++; if (attempts.n < 3) throw new Error("attempt " + attempts.n);`, - "user.cjs": `exports.tryOnce = () => { try { require("./flaky.js"); return "ok" } catch (e) { return e.message } }`, - }); - const attempts = { n: 0 }; - const u = await ModuleGraph({ globals: { attempts } }).import(join(d, "user.cjs")); - expect([u.tryOnce(), u.tryOnce(), u.tryOnce(), u.tryOnce(), attempts.n]).toEqual([ - "attempt 1", - "attempt 2", - "ok", - "ok", - 3, - ]); - rmSync(d, { recursive: true, force: true }); - }); test("CommonJS code in graphs with different globals name sets resolves each graph's own names (one wrapper executable per name set)", async () => { const d = fixture({ "w.cjs": `module.exports = { a: typeof alpha === "undefined" ? "-" : alpha, b: typeof beta === "undefined" ? "-" : beta, p: typeof process.pid }`, diff --git a/test/js/bun/resolve/require.test.ts b/test/js/bun/resolve/require.test.ts index 0befe85f238a..e47bb349076c 100644 --- a/test/js/bun/resolve/require.test.ts +++ b/test/js/bun/resolve/require.test.ts @@ -219,6 +219,33 @@ describe("require(specifier)", () => { expect(result).toEqual({ attempts: ["fail 1", "ok"], evaluations: 2 }); }); + // A Bun.ModuleGraph has its own module registry, which keeps the failed entry. + it("require() inside a Bun.ModuleGraph evaluates it again", async () => { + const result = await runEntry({ + "flaky.js": `attempts.n++; if (attempts.n < 3) throw new Error("attempt " + attempts.n);`, + "user.cjs": /* js */ ` + exports.tryOnce = () => { + try { + require("./flaky.js"); + return "ok"; + } catch (e) { + return e.message; + } + }; + `, + "entry.js": /* js */ ` + (async () => { + const attempts = { n: 0 }; + const graph = new Bun.ModuleGraph({ globals: { attempts } }); + const user = await graph.import(require.resolve("./user.cjs")); + const outcomes = [user.tryOnce(), user.tryOnce(), user.tryOnce(), user.tryOnce()]; + console.log(JSON.stringify({ outcomes, evaluations: attempts.n })); + })(); + `, + }); + expect(result).toEqual({ outcomes: ["attempt 1", "attempt 2", "ok", "ok"], evaluations: 3 }); + }); + // Only require() retries, and only what Node runs as CommonJS. A file with // ES module syntax that threw is not evaluated again: as in Node, every // later require() and import() of it gets the error it threw. From ed124ec94a74bf6cf1a608c0fc197a264840f68f Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 19 Sep 2026 01:56:06 +0000 Subject: [PATCH 06/10] require(): keep the error of a .mjs or "type": "module" file that threw Node runs a .mjs/.mts file, or a file under a package.json with "type": "module", as an ES module whatever its syntax, and never evaluates it again after it threw. The eviction now checks the resolved path's extension and the provider's package.json tag before it falls back to the syntax check. --- src/jsc/bindings/ModuleLoader.cpp | 23 +++++++++++++++-------- test/js/bun/resolve/require.test.ts | 25 ++++++++++++++++--------- 2 files changed, 31 insertions(+), 17 deletions(-) diff --git a/src/jsc/bindings/ModuleLoader.cpp b/src/jsc/bindings/ModuleLoader.cpp index dbc72ccdb64a..afce3540e68a 100644 --- a/src/jsc/bindings/ModuleLoader.cpp +++ b/src/jsc/bindings/ModuleLoader.cpp @@ -643,27 +643,34 @@ void evaluateCommonJSCustomExtension( RETURN_IF_EXCEPTION(scope, ); } -// The syntax that makes Node run a file as an ES module when its extension -// and package.json do not decide. -static bool hasESModuleSyntax(JSC::AbstractModuleRecord* record) +// What Node runs as an ES module: a .mjs/.mts file, a file under a package.json +// with "type": "module" (the provider's tag), or a file with import, export, +// top-level await or import.meta. +static bool isESModule(const WTF::String& specifier, JSC::AbstractModuleRecord* record) { auto* module = dynamicDowncast(record); if (!module) return false; + if (specifier.endsWith(".mjs"_s) || specifier.endsWith(".mts"_s)) + return true; + // Every JSModuleRecord in the registry is parsed from a Zig::SourceProvider. + auto* provider = static_cast(module->sourceCode().provider()); + if (provider && provider->m_tag == ResolvedSourceTagPackageJSONTypeModule) + return true; return !module->requestedModules().isEmpty() || !module->exportEntries().isEmpty() || module->hasTLA() || (module->features() & JSC::ImportMetaFeature); } -// The module threw while it was evaluated, and Node runs it as CommonJS (no ES -// module syntax, or no JSModuleRecord at all). Node re-runs such a module on the +// The module threw while it was evaluated, and Node runs it as CommonJS (not an +// ES module, or no JSModuleRecord at all). Node re-runs such a module on the // next require(). An ES module keeps its error. -static bool threwAsCommonJS(JSC::ModuleRegistryEntry* entry) +static bool threwAsCommonJS(const WTF::String& specifier, JSC::ModuleRegistryEntry* entry) { auto* record = entry->record(); bool threw = entry->status() == JSC::ModuleRegistryEntry::Status::EvaluationFailed; // A dependency that threw inside another module's graph keeps Status::Fetched. if (auto* cyclic = dynamicDowncast(record)) threw = threw || cyclic->evaluationError(); - return threw && !hasESModuleSyntax(record); + return threw && !isESModule(specifier, record); } // A failed require() drops its module from the require map, but the registry @@ -675,7 +682,7 @@ static void evictFailedModuleRegistryEntry(JSC::VM& vm, JSC::JSModuleLoader* loa { auto key = JSC::Identifier::fromString(vm, specifier); auto* entry = loader->registryEntry(key); - if (!entry || !threwAsCommonJS(entry)) + if (!entry || !threwAsCommonJS(specifier, entry)) return; loader->removeEntry(key); Bun::IsolatedModuleCache::evict(vm, specifier); diff --git a/test/js/bun/resolve/require.test.ts b/test/js/bun/resolve/require.test.ts index e47bb349076c..a4dc0c105fe5 100644 --- a/test/js/bun/resolve/require.test.ts +++ b/test/js/bun/resolve/require.test.ts @@ -62,7 +62,8 @@ describe("require(specifier)", () => { async function runEntry(files: Record) { using dir = tempDir("require-throwing-module", files); - const { stdout, stderr, exitCode } = await bunRun(path.join(String(dir), "entry.js")); + const entry = "entry.cjs" in files ? "entry.cjs" : "entry.js"; + const { stdout, stderr, exitCode } = await bunRun(path.join(String(dir), entry)); expect(stderr).toBe(""); expect(exitCode).toBe(0); return JSON.parse(stdout); @@ -246,24 +247,30 @@ describe("require(specifier)", () => { expect(result).toEqual({ outcomes: ["attempt 1", "attempt 2", "ok", "ok"], evaluations: 3 }); }); - // Only require() retries, and only what Node runs as CommonJS. A file with - // ES module syntax that threw is not evaluated again: as in Node, every - // later require() and import() of it gets the error it threw. - it("an ES module is not evaluated again", async () => { + // Only require() retries, and only what Node runs as CommonJS. An ES module + // that threw is not evaluated again: as in Node, every later require() and + // import() of it gets the error it threw. Node decides by the extension, + // then package.json "type", then the syntax. + it.each([ + ["ES module syntax", { "bad.mjs": flakyModule(1) + `export const attempt = globalThis.evaluations;` }], + [".mjs without module syntax", { "bad.mjs": flakyModule(1) }], + ['"type": "module" without module syntax', { "package.json": `{ "type": "module" }`, "bad.js": flakyModule(1) }], + ])("an ES module is not evaluated again: %s", async (_, files) => { + const specifier = "./" + Object.keys(files).find(name => name.startsWith("bad.")); const result = await runEntry({ - "bad.mjs": flakyModule(1) + `export const attempt = globalThis.evaluations;`, - "entry.js": /* js */ ` + ...files, + "entry.cjs": /* js */ ` (async () => { const errors = []; for (let i = 0; i < 2; i++) { try { - require("./bad.mjs"); + require(${JSON.stringify(specifier)}); } catch (e) { errors.push(e); } } try { - await import("./bad.mjs"); + await import(${JSON.stringify(specifier)}); } catch (e) { errors.push(e); } From 182cd24d0b3c9a50c44dfc4911e20fe688f2c0db Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 19 Sep 2026 02:22:59 +0000 Subject: [PATCH 07/10] require(): classify a failed module by its path and package.json, not the provider tag The provider tag is set only on the fresh transpile branch, so a "type": "module" file served from the runtime transpiler cache or the watcher lost its ES module classification. The registry can also hold a record parsed from a provider that is not Zig's (Bake), so the cast was not safe. Ask the resolver instead: Bun__isESModuleByPathOrPackage reads the extension (.mjs, .mts) and the nearest package.json of the resolved path, with a ?query stripped. Tests: a plain .js with an export and one with import.meta, so the syntax branch is the deciding check, a .mjs with a query, and the import() contract test now uses a file that require() would retry. --- src/jsc/bindings/ModuleLoader.cpp | 29 +++++++++++----------- src/runtime/jsc_hooks.rs | 38 +++++++++++++++++++++++++++++ test/js/bun/resolve/require.test.ts | 25 +++++++++++++------ 3 files changed, 69 insertions(+), 23 deletions(-) diff --git a/src/jsc/bindings/ModuleLoader.cpp b/src/jsc/bindings/ModuleLoader.cpp index afce3540e68a..31daddad27ab 100644 --- a/src/jsc/bindings/ModuleLoader.cpp +++ b/src/jsc/bindings/ModuleLoader.cpp @@ -643,19 +643,18 @@ void evaluateCommonJSCustomExtension( RETURN_IF_EXCEPTION(scope, ); } -// What Node runs as an ES module: a .mjs/.mts file, a file under a package.json -// with "type": "module" (the provider's tag), or a file with import, export, -// top-level await or import.meta. -static bool isESModule(const WTF::String& specifier, JSC::AbstractModuleRecord* record) +extern "C" bool Bun__isESModuleByPathOrPackage(void* bunVM, const BunString* specifier); + +// What Node runs as an ES module: a .mjs/.mts file, a .js/.ts file under a +// package.json with "type": "module", or a file with import, export, top-level +// await or import.meta. +static bool isESModule(void* bunVM, const WTF::String& specifier, JSC::AbstractModuleRecord* record) { auto* module = dynamicDowncast(record); if (!module) return false; - if (specifier.endsWith(".mjs"_s) || specifier.endsWith(".mts"_s)) - return true; - // Every JSModuleRecord in the registry is parsed from a Zig::SourceProvider. - auto* provider = static_cast(module->sourceCode().provider()); - if (provider && provider->m_tag == ResolvedSourceTagPackageJSONTypeModule) + BunString specifierString = Bun::toString(specifier); + if (Bun__isESModuleByPathOrPackage(bunVM, &specifierString)) return true; return !module->requestedModules().isEmpty() || !module->exportEntries().isEmpty() || module->hasTLA() || (module->features() & JSC::ImportMetaFeature); } @@ -663,14 +662,14 @@ static bool isESModule(const WTF::String& specifier, JSC::AbstractModuleRecord* // The module threw while it was evaluated, and Node runs it as CommonJS (not an // ES module, or no JSModuleRecord at all). Node re-runs such a module on the // next require(). An ES module keeps its error. -static bool threwAsCommonJS(const WTF::String& specifier, JSC::ModuleRegistryEntry* entry) +static bool threwAsCommonJS(void* bunVM, const WTF::String& specifier, JSC::ModuleRegistryEntry* entry) { auto* record = entry->record(); bool threw = entry->status() == JSC::ModuleRegistryEntry::Status::EvaluationFailed; // A dependency that threw inside another module's graph keeps Status::Fetched. if (auto* cyclic = dynamicDowncast(record)) threw = threw || cyclic->evaluationError(); - return threw && !isESModule(specifier, record); + return threw && !isESModule(bunVM, specifier, record); } // A failed require() drops its module from the require map, but the registry @@ -678,11 +677,11 @@ static bool threwAsCommonJS(const WTF::String& specifier, JSC::ModuleRegistryEnt // load. Only a failed entry is removed: a pending or loaded one may belong to an // in-flight import(). The retry reads the file again, as `delete require.cache[key]` // does, so the --isolate source cache is dropped with the entry. -static void evictFailedModuleRegistryEntry(JSC::VM& vm, JSC::JSModuleLoader* loader, const WTF::String& specifier) +static void evictFailedModuleRegistryEntry(JSC::VM& vm, void* bunVM, JSC::JSModuleLoader* loader, const WTF::String& specifier) { auto key = JSC::Identifier::fromString(vm, specifier); auto* entry = loader->registryEntry(key); - if (!entry || !threwAsCommonJS(specifier, entry)) + if (!entry || !threwAsCommonJS(bunVM, specifier, entry)) return; loader->removeEntry(key); Bun::IsolatedModuleCache::evict(vm, specifier); @@ -707,7 +706,7 @@ JSValue fetchCommonJSModule( BunString specifier = Bun::toString(specifierWtfString); - evictFailedModuleRegistryEntry(vm, loader, specifierWtfString); + evictFailedModuleRegistryEntry(vm, bunVM, loader, specifierWtfString); bool wasModuleMock = false; @@ -879,7 +878,7 @@ JSValue fetchCommonJSModuleNonBuiltin( RETURN_IF_EXCEPTION(scope, {}); // A direct Module._extensions[ext]() call skips fetchCommonJSModule. if constexpr (isExtension) - evictFailedModuleRegistryEntry(vm, loader, specifierWtfString); + evictFailedModuleRegistryEntry(vm, bunVM, loader, specifierWtfString); Bun__transpileFile(bunVM, globalObject, specifier, referrer, typeAttribute, res, false, !isExtension, forceLoaderType); if (res->success && res->result.value.isCommonJSModule) { if constexpr (isExtension) { diff --git a/src/runtime/jsc_hooks.rs b/src/runtime/jsc_hooks.rs index 6e1b8e21e7a5..1a364ee29cb0 100644 --- a/src/runtime/jsc_hooks.rs +++ b/src/runtime/jsc_hooks.rs @@ -4036,6 +4036,44 @@ fn intern_transpile_path(value: &[u8]) -> &'static [u8] { }) } +/// Whether Node runs the file at `specifier` as an ES module whatever its +/// syntax: a `.mjs`/`.mts` file, or a `.js`/`.ts` file under a package.json +/// with `"type": "module"`. +/// +/// # Safety +/// `jsc_vm` is the live per-thread VM. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Bun__isESModuleByPathOrPackage( + jsc_vm: *mut VirtualMachine, + specifier: &bun_core::String, +) -> bool { + let specifier = specifier.to_utf8(); + let path: &[u8] = match bun_core::strings::index_of_char_usize(&specifier, b'?') { + Some(query) => &specifier[..query], + None => &specifier, + }; + match bun_paths::extension(path) { + b".mjs" | b".mts" => return true, + b".js" | b".ts" => {} + _ => return false, + } + let Some(dir) = bun_paths::dirname(path) else { + return false; + }; + if !bun_paths::is_absolute(dir) { + return false; + } + // SAFETY: per fn contract. `read_dir_info` is re-entrant on the JS thread + // and returns a stable cache slot. + match unsafe { (*jsc_vm).transpiler.resolver.read_dir_info(dir) } { + Ok(Some(dir_info)) => dir_info + .package_json() + .or(dir_info.enclosing_package_json) + .is_some_and(|pkg| pkg.module_type == ModuleType::Esm), + _ => false, + } +} + /// Modules that must always transpile on-thread (see [`Bun__transpileFile`]). const ALWAYS_SYNC_MODULES: &[&[u8]] = &[b"reflect-metadata"]; diff --git a/test/js/bun/resolve/require.test.ts b/test/js/bun/resolve/require.test.ts index a4dc0c105fe5..8f2ffac698bd 100644 --- a/test/js/bun/resolve/require.test.ts +++ b/test/js/bun/resolve/require.test.ts @@ -252,11 +252,20 @@ describe("require(specifier)", () => { // import() of it gets the error it threw. Node decides by the extension, // then package.json "type", then the syntax. it.each([ - ["ES module syntax", { "bad.mjs": flakyModule(1) + `export const attempt = globalThis.evaluations;` }], - [".mjs without module syntax", { "bad.mjs": flakyModule(1) }], - ['"type": "module" without module syntax', { "package.json": `{ "type": "module" }`, "bad.js": flakyModule(1) }], - ])("an ES module is not evaluated again: %s", async (_, files) => { - const specifier = "./" + Object.keys(files).find(name => name.startsWith("bad.")); + [ + ".js with an export", + "./bad.js", + { "bad.js": flakyModule(1) + `export const attempt = globalThis.evaluations;` }, + ], + [".js with import.meta", "./bad.js", { "bad.js": flakyModule(1) + `globalThis.url = import.meta.url;` }], + [".mjs without module syntax", "./bad.mjs", { "bad.mjs": flakyModule(1) }], + [".mjs with a query", "./bad.mjs?v=1", { "bad.mjs": flakyModule(1) }], + [ + '"type": "module" without module syntax', + "./bad.js", + { "package.json": `{ "type": "module" }`, "bad.js": flakyModule(1) }, + ], + ])("an ES module is not evaluated again: %s", async (_, specifier, files) => { const result = await runEntry({ ...files, "entry.cjs": /* js */ ` @@ -289,17 +298,17 @@ describe("require(specifier)", () => { // require(), also for a file that the next require() would run again. it("import() of a module that failed under require() rejects with the original error", async () => { const result = await runEntry({ - "bad.mjs": flakyModule(Infinity), + "bad.js": flakyModule(Infinity), "entry.js": /* js */ ` (async () => { let requireError, importError; try { - require("./bad.mjs"); + require("./bad.js"); } catch (e) { requireError = e; } try { - await import("./bad.mjs"); + await import("./bad.js"); } catch (e) { importError = e; } From 1ea7ba0d0dd5ebb3a5046c1dcb31f23f9aa9713c Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 19 Sep 2026 02:41:42 +0000 Subject: [PATCH 08/10] require(): read "type" from the nearest package.json, named or not enclosing_package_json skips a package.json with no "name", so a file in a subdirectory of a nameless "type": "module" project was retried. Use package_json_for_module_type, the lookup the bundler uses for the same decision. --- src/runtime/jsc_hooks.rs | 3 +-- test/js/bun/resolve/require.test.ts | 5 +++++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/runtime/jsc_hooks.rs b/src/runtime/jsc_hooks.rs index 1a364ee29cb0..71506d276e98 100644 --- a/src/runtime/jsc_hooks.rs +++ b/src/runtime/jsc_hooks.rs @@ -4067,8 +4067,7 @@ pub unsafe extern "C" fn Bun__isESModuleByPathOrPackage( // and returns a stable cache slot. match unsafe { (*jsc_vm).transpiler.resolver.read_dir_info(dir) } { Ok(Some(dir_info)) => dir_info - .package_json() - .or(dir_info.enclosing_package_json) + .package_json_for_module_type .is_some_and(|pkg| pkg.module_type == ModuleType::Esm), _ => false, } diff --git a/test/js/bun/resolve/require.test.ts b/test/js/bun/resolve/require.test.ts index 8f2ffac698bd..d34835da590c 100644 --- a/test/js/bun/resolve/require.test.ts +++ b/test/js/bun/resolve/require.test.ts @@ -265,6 +265,11 @@ describe("require(specifier)", () => { "./bad.js", { "package.json": `{ "type": "module" }`, "bad.js": flakyModule(1) }, ], + [ + '"type": "module" in a nameless package.json, file in a subdirectory', + "./src/bad.js", + { "package.json": `{ "type": "module" }`, "src/bad.js": flakyModule(1) }, + ], ])("an ES module is not evaluated again: %s", async (_, specifier, files) => { const result = await runEntry({ ...files, From 2d0f43bec416b6d5cf7838df037cb95bb9a56fc3 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Mon, 19 Oct 2026 22:38:49 +0000 Subject: [PATCH 09/10] require(): declare Bun__isESModuleByPathOrPackage pub(crate) main builds bun_runtime with -D unreachable-pub. --- src/runtime/jsc_hooks.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/runtime/jsc_hooks.rs b/src/runtime/jsc_hooks.rs index 31f3e3a3de7f..d7ef2f56a2c8 100644 --- a/src/runtime/jsc_hooks.rs +++ b/src/runtime/jsc_hooks.rs @@ -4140,7 +4140,7 @@ fn intern_transpile_path(value: &[u8]) -> &'static [u8] { /// # Safety /// `jsc_vm` is the live per-thread VM. #[unsafe(no_mangle)] -pub unsafe extern "C" fn Bun__isESModuleByPathOrPackage( +pub(crate) unsafe extern "C" fn Bun__isESModuleByPathOrPackage( jsc_vm: *mut VirtualMachine, specifier: &bun_core::String, ) -> bool { From a8cfe9d51f463763fc44713e442c8344f6725429 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Wed, 21 Oct 2026 12:11:14 +0000 Subject: [PATCH 10/10] ci: retrigger