From 5f1d4400dc972cad02b91c0bd971162bbcb678e6 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Thu, 21 May 2026 14:04:14 +0800 Subject: [PATCH] fix(build): inject createRequire banner so bundled CJS requires resolve MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit better-sqlite3's JS wrapper is pure CJS — its `require('fs')` / `require('path')` / `require('bindings')` calls get inlined into the ESM bundle as `__require("fs")` shims by rolldown. The shim's fast-path checks `typeof require !== "undefined"` (true in CJS, false in our `.mjs` output) and otherwise throws "Calling `require` for \"fs\" in an environment that doesn't expose the `require` function". The launcher crashed at startup the moment `@snowluma/sqlite` resolved its `import BetterSqlite3 from 'better-sqlite3'`. Inject `const require = createRequire(import.meta.url)` via `rollupOptions.output.banner` so every inlined CJS require routes to Node's CJS loader. No call-site changes; the only diff in the emitted bundle is two new top-of-file import/const lines. --- packages/core/vite.config.ts | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/packages/core/vite.config.ts b/packages/core/vite.config.ts index f4ca6e86..f7cd92a4 100644 --- a/packages/core/vite.config.ts +++ b/packages/core/vite.config.ts @@ -140,7 +140,27 @@ const BaseConfig = (source_map: boolean = false) => defineConfig({ fileName: (_, entryName) => `${entryName}.mjs` }, rollupOptions: { - external: [...nodeModules, ...external] + external: [...nodeModules, ...external], + output: { + // better-sqlite3's JS wrapper is pure CJS — its `require('fs')` / + // `require('path')` / `require('bindings')` calls get inlined into + // the ESM bundle as `__require("fs")` shims by rolldown. Those + // shims gate on `typeof require !== "undefined"`, which is true + // in CJS but FALSE in our `.mjs` output, so they fall through to + // a runtime `throw Error("Calling \`require\` ... in an environment + // that doesn't expose the \`require\` function.")` on first call — + // crashing the launcher immediately. + // + // Defining a module-scope `require` via `createRequire(import.meta.url)` + // at the very top of the bundle satisfies the `typeof` check, and + // the shim then transparently delegates every inlined CJS require + // to the real CJS loader. Node 18+ ships `createRequire` in the + // `node:module` builtin, so this is supported on every target. + banner: [ + "import { createRequire as __snowlumaCreateRequire } from 'node:module';", + "const require = __snowlumaCreateRequire(import.meta.url);", + ].join('\n'), + }, }, // Emit to monorepo root dist/ so the existing release pipeline keeps working. outDir: distDir,