Skip to content

Commit d127400

Browse files
cursoragent0froq
andcommitted
fix(dev): load one better-auth module in the dev worker
The workerd dependency optimizer excluded void, so an app import of better-auth/api was prebundled while Void's runtime loaded the package from source. OAuth request state lives on a module-local ref, and getOAuthState() then missed the state the runtime set. Exclude better-auth in those environments as well. Co-authored-by: sayhola <sayhola@froq.me>
1 parent 5d2a2ff commit d127400

5 files changed

Lines changed: 95 additions & 4 deletions

File tree

‎packages/void/AGENTS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ generated entries must preserve the module-boundary rules below.
102102

103103
- **Import redirection**: The routing plugin's `resolveId` hook redirects bare `"void"` imports to `void/handler` (the lightweight subpath). Without this, route files pull the entire plugin (vite, @cloudflare/vite-plugin, lightningcss) into the Worker bundle. Uses `import.meta.resolve()` to compute absolute paths at plugin init. Class A frameworks and Astro get the same redirect for their server environments from `createBareVoidRedirectPlugin`, in dev and build: their dev trigger dispatch imports every cron and queue file into workerd, so one `import { defineScheduled } from 'void'` would otherwise break every trigger (and, in Astro, every request).
104104

105-
- **Installed runtime module identity**: Keep `void` server runtime subpaths out of Vite dependency optimization. Generated entries import runtime modules by resolved file path; prebundling a bare `void/kv` creates a second `envContext` and loses request bindings. Workspace symlinks can hide this defect. The shared runtime-optimizer plugin excludes the package in server environments on every target while preserving client optimization; packed-consumer checks exercise actual npm/pnpm installations. Vite never discovers bare imports from inside node_modules, so the same plugin prebundles Void's CommonJS dependencies (`void > email-validator`, the void/db driver) in every environment whose resolve conditions contain `workerd`: Void's worker, class A frameworks and Astro. Node environments get only the exclusion. SvelteKit's dev server runs server code in Vite's Node `ssr` graph, which externalizes a bare import that resolves into node_modules before any plugin resolves it, so an installed `void/db` would load the package's D1 runtime. The SvelteKit plugin sets `ssr.noExternal: ['void']` during serve; Vite matches it by package name, so the whole package moves into that graph together and the injected `void/_env` shares void/db's env module. Like the routing plugin, it sends bare `void` to `void/handler` in server environments. In SvelteKit dev for PostgreSQL and MySQL apps, the plugin also inlines installed ES module packages that depend on void, so their `void/db` is the app's. In a D1 app, and for a CommonJS package or one that does not list void, the package stays external and loads its own copy of the env modules. `envContext` and the request scope therefore live on `globalThis` under versioned `Symbol.for` keys, like `authContext`, so every copy reads the current request; this also covers modules that a dependency-optimizer reload evaluates again during a request. Change a key when its store shape changes, because two Void versions in one process share it.
105+
- **Installed runtime module identity**: Keep `void` server runtime subpaths out of Vite dependency optimization. Generated entries import runtime modules by resolved file path; prebundling a bare `void/kv` creates a second `envContext` and loses request bindings. Workspace symlinks can hide this defect. The shared runtime-optimizer plugin excludes the package in server environments on every target while preserving client optimization; packed-consumer checks exercise actual npm/pnpm installations. Vite never discovers bare imports from inside node_modules, so the same plugin prebundles Void's CommonJS dependencies (`void > email-validator`, the void/db driver) in every environment whose resolve conditions contain `workerd`: Void's worker, class A frameworks and Astro. Node environments get only the exclusion. Workerd environments also exclude `better-auth`. Its OAuth request state is a module-local ref, and the dev worker must load the same module Void's runtime does: prebundling an app import of `better-auth/api` while the excluded `void` package loads `better-auth` from source makes `getOAuthState()` miss the state the runtime set. A production build already bundles one copy. SvelteKit's dev server runs server code in Vite's Node `ssr` graph, which externalizes a bare import that resolves into node_modules before any plugin resolves it, so an installed `void/db` would load the package's D1 runtime. The SvelteKit plugin sets `ssr.noExternal: ['void']` during serve; Vite matches it by package name, so the whole package moves into that graph together and the injected `void/_env` shares void/db's env module. Like the routing plugin, it sends bare `void` to `void/handler` in server environments. In SvelteKit dev for PostgreSQL and MySQL apps, the plugin also inlines installed ES module packages that depend on void, so their `void/db` is the app's. In a D1 app, and for a CommonJS package or one that does not list void, the package stays external and loads its own copy of the env modules. `envContext` and the request scope therefore live on `globalThis` under versioned `Symbol.for` keys, like `authContext`, so every copy reads the current request; this also covers modules that a dependency-optimizer reload evaluates again during a request. Change a key when its store shape changes, because two Void versions in one process share it.
106106
- **Plugin entry imports**: Every `vp dev` and `vp build` imports the plugin entry before it starts. Import dependencies that only some apps or commands use (feature codegen, CLI-only helpers) where they are used, so other apps don't load them at startup. `test/unit/plugin-entry-imports.test.ts` guards this; add a mock there when you move a heavy import out.
107107
- **pnpm scaffold build policy**: Keep `create-void` and `void init` aligned with the repository: `better-sqlite3: false` uses version 13's bundled Node-API binaries; `esbuild`, `sharp`, and `workerd` have approved builds. Do not require an unnecessary node-gyp rebuild in fresh applications.
108108
- **Scaffold dependency installation**: Vite+ projects install through local/global `vp`, bootstrapping with `npx` when neither is available. Preserve existing package-manager pins and lockfiles; fresh Vite+ projects select pnpm through the build-policy YAML without adding a version pin. Plain Vite projects use their selected package manager. Do not run a global package manager directly for Vite+ installs.

‎packages/void/src/plugin-worker-environment.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,11 @@ export function createServerRuntimeOptimizerPlugin(
212212
}
213213
return {
214214
optimizeDeps: {
215-
exclude: ['void'],
215+
// `better-auth` keeps OAuth request state on a module-local ref. Prebundling an app
216+
// import of `better-auth/api` while this excluded package loads `better-auth` from
217+
// source gives the dev worker two copies, so `getOAuthState()` misses the state the
218+
// runtime set. A production build already bundles one copy.
219+
exclude: ['void', 'better-auth'],
216220
// Excluding void also skips converting its CommonJS dependencies, which workerd cannot
217221
// evaluate: an installed void/email fails with "exports is not defined".
218222
include: ['void > email-validator', ...DATABASE_DRIVER_DEPS[dialect]],
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
2+
import { tmpdir } from 'node:os';
3+
import { dirname, join } from 'node:path';
4+
import { fileURLToPath } from 'node:url';
5+
import { createServer } from 'vite';
6+
import { afterEach, describe, expect, it, vi } from 'vite-plus/test';
7+
import { voidPlugin } from '../../src/index.ts';
8+
9+
const repoRoot = fileURLToPath(new URL('../../../..', import.meta.url));
10+
const roots: Array<string> = [];
11+
12+
afterEach(() => {
13+
vi.restoreAllMocks();
14+
for (const root of roots.splice(0, roots.length)) {
15+
rmSync(root, { recursive: true, force: true });
16+
}
17+
});
18+
19+
describe('void dev better-auth module', () => {
20+
it('loads one OAuth state module for the worker runtime and app code', async () => {
21+
const root = realpathSync.native(mkdtempSync(join(tmpdir(), 'void-better-auth-')));
22+
roots.push(root);
23+
// The package export is `dist/index.mjs`.
24+
const betterAuthEntry = fileURLToPath(import.meta.resolve('better-auth'));
25+
const betterAuthRoot = realpathSync(dirname(dirname(betterAuthEntry)));
26+
mkdirSync(join(root, 'node_modules', 'void'), { recursive: true });
27+
symlinkSync(betterAuthRoot, join(root, 'node_modules', 'better-auth'), 'dir');
28+
writeFileSync(
29+
join(root, 'package.json'),
30+
JSON.stringify({ type: 'module', dependencies: { 'better-auth': '*', void: '*' } }),
31+
);
32+
// Auth apps enable nodejs_compat because Better Auth hashes passwords with node:crypto.
33+
writeFileSync(
34+
join(root, 'void.json'),
35+
JSON.stringify({
36+
worker: { compatibility_date: '2026-02-24', compatibility_flags: ['nodejs_compat'] },
37+
}),
38+
);
39+
// An installed `void` is excluded from dependency optimization, so its import of
40+
// better-auth stays on the package source. This probe is that file: the relative path
41+
// is the module the runtime reaches, and the route imports the public subpath a plugin uses.
42+
writeFileSync(
43+
join(root, 'node_modules', 'void', 'package.json'),
44+
JSON.stringify({
45+
name: 'void',
46+
type: 'module',
47+
exports: { './oauth-probe': './oauth-probe.mjs' },
48+
}),
49+
);
50+
writeFileSync(
51+
join(root, 'node_modules', 'void', 'oauth-probe.mjs'),
52+
"export { getOAuthState } from '../better-auth/dist/api/state/oauth.mjs';\n",
53+
);
54+
mkdirSync(join(root, 'routes', 'api'), { recursive: true });
55+
writeFileSync(
56+
join(root, 'routes', 'api', 'oauth-state.ts'),
57+
[
58+
"import { getOAuthState as fromApp } from 'better-auth/api';",
59+
"import { getOAuthState as fromRuntime } from 'void/oauth-probe';",
60+
'export const GET = () => Response.json({ same: fromApp === fromRuntime });',
61+
'',
62+
].join('\n'),
63+
);
64+
vi.spyOn(process, 'cwd').mockReturnValue(root);
65+
66+
const server = await createServer({
67+
root,
68+
configFile: false,
69+
logLevel: 'silent',
70+
server: { host: '127.0.0.1', port: 0, fs: { allow: [root, repoRoot] } },
71+
plugins: [voidPlugin()],
72+
});
73+
try {
74+
await server.listen();
75+
const response = await fetch(new URL('/api/oauth-state', server.resolvedUrls!.local[0]!));
76+
const body = await response.text();
77+
expect(response.status, body).toBe(200);
78+
expect(JSON.parse(body)).toEqual({ same: true });
79+
} finally {
80+
await server.close();
81+
}
82+
}, 60_000);
83+
});

‎packages/void/test/unit/plugin-dev-asset-routing.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -252,7 +252,7 @@ describe('voidPlugin dev asset routing', () => {
252252

253253
it('converts void CommonJS dependencies only in environments that run in workerd', async () => {
254254
const workerdOptimizer = {
255-
optimizeDeps: { exclude: ['void'], include: ['void > email-validator'] },
255+
optimizeDeps: { exclude: ['void', 'better-auth'], include: ['void > email-validator'] },
256256
};
257257
const nodeOptimizer = { optimizeDeps: { exclude: ['void'] } };
258258
const cases = [
@@ -290,7 +290,7 @@ describe('voidPlugin dev asset routing', () => {
290290
`${createRoot.name} ${database}`,
291291
).resolves.toEqual({
292292
optimizeDeps: drivers
293-
? { exclude: ['void'], include: ['void > email-validator', ...drivers] }
293+
? { exclude: ['void', 'better-auth'], include: ['void > email-validator', ...drivers] }
294294
: { exclude: ['void'] },
295295
});
296296
}

‎packages/void/test/unit/plugin-vite-environment.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,11 @@ describe('voidPlugin Vite environments', () => {
174174
expect(config.environments.void_worker.optimizeDeps.include).toEqual(
175175
expect.arrayContaining(['void > email-validator', 'void > pg']),
176176
);
177+
expect(config.environments.void_worker.optimizeDeps.exclude).toEqual(
178+
expect.arrayContaining(['void', 'better-auth']),
179+
);
177180
expect(config.environments.ssr.optimizeDeps.include).toEqual([]);
181+
expect(config.environments.ssr.optimizeDeps.exclude ?? []).not.toContain('better-auth');
178182
});
179183

180184
it.each(['before', 'after'])(

0 commit comments

Comments
 (0)