Skip to content
Closed
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions src/jsc/bindings/ModuleLoader.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@

#include <JavaScriptCore/JSModuleLoader.h>
#include <JavaScriptCore/ModuleRegistryEntry.h>
#include <JavaScriptCore/JSModuleRecord.h>
#include <JavaScriptCore/Completion.h>
#include <JavaScriptCore/JSModuleNamespaceObject.h>
#include <JavaScriptCore/JSMap.h>
Expand Down Expand Up @@ -642,6 +643,44 @@ 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.
Comment thread
robobun marked this conversation as resolved.
Resolved
static bool hasESModuleSyntax(JSC::AbstractModuleRecord* record)
{
auto* module = dynamicDowncast<JSC::JSModuleRecord>(record);
if (!module)
return false;
Comment thread
robobun marked this conversation as resolved.
Resolved
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
// next require(). An ES module keeps its error.
Comment thread
robobun marked this conversation as resolved.
Resolved
Comment thread
robobun marked this conversation as resolved.
Resolved
static bool threwAsCommonJS(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<JSC::CyclicModuleRecord>(record))
threw = threw || cyclic->evaluationError();
return threw && !hasESModuleSyntax(record);
Comment thread
robobun marked this conversation as resolved.
Resolved
Comment thread
robobun marked this conversation as resolved.
Resolved
}

// 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(). The retry reads the file again, as `delete require.cache[key]`
// does, so the --isolate source cache is dropped with the entry.
Comment thread
robobun marked this conversation as resolved.
Resolved
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 || !threwAsCommonJS(entry))
return;
loader->removeEntry(key);
Bun::IsolatedModuleCache::evict(vm, specifier);
}

JSValue fetchCommonJSModule(
Zig::GlobalObject* globalObject,
JSCommonJSModule* target,
Expand All @@ -661,6 +700,8 @@ JSValue fetchCommonJSModule(

BunString specifier = Bun::toString(specifierWtfString);

evictFailedModuleRegistryEntry(vm, loader, specifierWtfString);
Comment thread
robobun marked this conversation as resolved.
Resolved

bool wasModuleMock = false;

// When "bun test" is enabled, allow users to override builtin modules
Expand Down Expand Up @@ -829,6 +870,9 @@ JSValue fetchCommonJSModuleNonBuiltin(
{
JSC::JSModuleLoader* loader = Bun::moduleLoaderOf(globalObject, scope, target->moduleGraph());
RETURN_IF_EXCEPTION(scope, {});
// 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);
if (res->success && res->result.value.isCommonJSModule) {
if constexpr (isExtension) {
Expand Down
39 changes: 39 additions & 0 deletions test/cli/test/isolation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1779,3 +1779,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 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": `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)).toBe("BunTranspiledModule");
writeFileSync(path, "globalThis.fixed = true;");
require("./flaky.js");
expect(globalThis.fixed).toBe(true);
expect(isolatedModuleCacheSourceType(path)).toBe("BunTranspiledModule");
});
`,
});

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);
});
265 changes: 264 additions & 1 deletion test/js/bun/resolve/require.test.ts
Original file line number Diff line number Diff line change
@@ -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);
Expand Down Expand Up @@ -45,6 +45,269 @@ 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: 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. 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 */ `
globalThis.evaluations = (globalThis.evaluations ?? 0) + 1;
if (globalThis.evaluations <= ${failures}) throw new Error("fail " + globalThis.evaluations);
`;

async function runEntry(files: Record<string, string>) {
using dir = tempDir("require-throwing-module", files);
const { stdout, stderr, exitCode } = await bunRun(path.join(String(dir), "entry.js"));
expect(stderr).toBe("");
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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("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 };`,
"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))},
}));
},
});
const attempts = [];
for (let i = 0; i < 2; i++) {
try {
require("virtual:flaky");
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 });
});

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 });
});

// 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.
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 */ `
(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;

Expand Down
Loading