Skip to content

Commit 4fde783

Browse files
authored
Generate authentication files before dev server hooks. (#828)
Generate the customized authentication schema and database module during the routing plugin’s `configureServer` hook, so later startup hooks can import app code that references authentication tables. Document lazy imports for schema-dependent auth hooks so `void prepare` can generate those tables on a fresh clone. The fresh Cloudflare smoke test also passes on current main with a correctly configured alias. The failing regression directly exercises availability of the generated files before later startup hooks. Adds fresh-app coverage for `void prepare` and Cloudflare dev startup, including a foreign key to `userTable` and a custom authentication field. Validation: - The ordering regression fails before the fix. - Focused routing and fresh-app tests pass independently. - Combined fix-batch verification: 13,338 affected tests, 17,009 full-suite tests with `vp test run --pool forks`, `vp run build:all`, `vp run check`, formatting, linting, and build-artifact checks. The default full-suite run hit a native Node 24/V8 WebAssembly JIT assertion (`end > addr`); forked-worker verification completed successfully. Refs #823.
1 parent 7d34d61 commit 4fde783

4 files changed

Lines changed: 180 additions & 20 deletions

File tree

‎docs/guide/auth.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,8 @@ export default defineAuth(({ defaults }) => ({
240240

241241
`defaults` already includes Void's conventions. Extend it explicitly instead of expecting a deep merge.
242242

243+
In `auth.ts`, load helpers that import `@auth-schema` inside the hook that uses them, with `await import('./server/users')`. This lets `void prepare` generate the authentication schema on a fresh clone. The same applies when a helper imports your app's database schema and that schema references authentication tables.
244+
243245
For the full set of available options, see the official [Better Auth options reference](https://www.better-auth.com/docs/reference/options).
244246

245247
## Database and Migrations

‎packages/void/src/plugin-routing.ts‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -300,8 +300,7 @@ export function routingPlugin(
300300
}
301301
reloadFileRules();
302302

303-
// Auth compile options are set up lazily in buildStart (after env plugin
304-
// has run its config hook and the auth config file path is known).
303+
// Resolve auth after config hooks have run and the auth config path is known.
305304
function resolveAuthCompileOptions(): void {
306305
if (!options.isAuthEnabled() && !authConfigPath) {
307306
compileOptions.auth = null;
@@ -967,7 +966,7 @@ export function routingPlugin(
967966
}
968967
},
969968

970-
configureServer(devServer) {
969+
async configureServer(devServer) {
971970
const authEnvironment = devServer.environments[AUTH_CONFIG_ENVIRONMENT];
972971
authConfigEnvironment =
973972
authEnvironment && isRunnableDevEnvironment(authEnvironment) ? authEnvironment : undefined;
@@ -1155,6 +1154,16 @@ export function routingPlugin(
11551154
watcher.on('change', handleRulesFileChange);
11561155
watcher.on('unlink', handleRulesFileChange);
11571156
}
1157+
1158+
// Later configureServer hooks can load app modules before buildStart.
1159+
// Their imports may already reference the generated authentication tables.
1160+
if (options.isAuthEnabled()) {
1161+
await regenerateInOrder(async () => {
1162+
await rescan();
1163+
resolveAuthCompileOptions();
1164+
await writeAuthDatabaseFiles();
1165+
});
1166+
}
11581167
},
11591168
};
11601169
}
Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
import { execFileSync } from 'node:child_process';
2+
import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
3+
import { join } from 'node:path';
4+
import spawn from 'cross-spawn';
5+
import { afterEach, expect, it } from 'vite-plus/test';
6+
import {
7+
createIsolatedPlayground,
8+
killChild,
9+
startServer,
10+
type IsolatedPlayground,
11+
} from '../../../../test/integration-helpers.ts';
12+
13+
const repository = join(import.meta.dirname, '../../../..');
14+
let fixture: IsolatedPlayground;
15+
let child: ReturnType<typeof spawn> | undefined;
16+
17+
afterEach(async () => {
18+
if (child) {
19+
await killChild(child);
20+
child = undefined;
21+
}
22+
fixture?.cleanup();
23+
});
24+
25+
function freshAuthApp() {
26+
fixture = createIsolatedPlayground(repository, 'playground/kitchen-sink');
27+
for (const path of [
28+
'pages',
29+
'routes',
30+
'middleware',
31+
'db',
32+
'crons',
33+
'queues',
34+
'email',
35+
'lib',
36+
'env.ts',
37+
'index.html',
38+
]) {
39+
rmSync(join(fixture.root, path), { recursive: true, force: true });
40+
}
41+
const write = (path: string, source: string) => {
42+
const file = join(fixture.root, path);
43+
mkdirSync(join(file, '..'), { recursive: true });
44+
writeFileSync(file, source);
45+
};
46+
write(
47+
'vite.config.ts',
48+
"import { voidPlugin } from 'void'; export default { plugins: [voidPlugin()], resolve: { tsconfigPaths: true } };",
49+
);
50+
write('void.config.ts', "export default { auth: { providers: ['email'] } };");
51+
write(
52+
'tsconfig.json',
53+
JSON.stringify({
54+
extends: './.void/tsconfig.json',
55+
compilerOptions: { paths: { '@auth-schema': ['./.void/better-auth-schema.ts'] } },
56+
include: ['**/*.ts'],
57+
}),
58+
);
59+
write(
60+
'auth.ts',
61+
`import { defineAuth } from 'void/auth';
62+
export default defineAuth(({ defaults }) => ({
63+
...defaults,
64+
user: { additionalFields: { nickname: { type: 'string', required: false } } },
65+
databaseHooks: { user: { create: { after: async () => {
66+
const { authFields } = await import('./lib/users');
67+
authFields();
68+
} } } },
69+
}));`,
70+
);
71+
write(
72+
'lib/users.ts',
73+
"import { userTable } from '@auth-schema'; export const authFields = () => Object.keys(userTable);",
74+
);
75+
write(
76+
'db/schema.ts',
77+
`import { userTable } from '@auth-schema';
78+
import { sqliteTable, text } from 'void/schema-d1';
79+
export const postTable = sqliteTable('post', {
80+
id: text('id').primaryKey(),
81+
authorId: text('author_id').references(() => userTable.id),
82+
});`,
83+
);
84+
write(
85+
'routes/index.ts',
86+
`import 'void/db';
87+
import { postTable } from '../db/schema';
88+
import { authFields } from '../lib/users';
89+
export const GET = () => Response.json({ fields: authFields(), author: postTable.authorId.name });`,
90+
);
91+
}
92+
93+
it('prepares a fresh app whose auth hooks lazily import the generated schema', () => {
94+
freshAuthApp();
95+
execFileSync(process.execPath, [join(repository, 'packages/void/dist/cli/cli.mjs'), 'prepare'], {
96+
cwd: fixture.root,
97+
stdio: 'pipe',
98+
timeout: 30_000,
99+
});
100+
expect(readFileSync(join(fixture.root, '.void/better-auth-schema.ts'), 'utf8')).toContain(
101+
'"nickname"',
102+
);
103+
});
104+
105+
it('starts a fresh Cloudflare app with auth table imports without running prepare first', async () => {
106+
freshAuthApp();
107+
const server = await startServer(
108+
(port) => {
109+
child = spawn('vp', ['dev', '--host', '127.0.0.1', '--port', String(port), '--strictPort'], {
110+
cwd: fixture.root,
111+
stdio: ['ignore', 'pipe', 'pipe'],
112+
env: { ...process.env, VOID_INSPECTOR_PORT: 'false' },
113+
});
114+
return child;
115+
},
116+
30_000,
117+
{ expectBody: 'nickname' },
118+
);
119+
const response = await fetch(server.base);
120+
expect(response.status).toBe(200);
121+
expect(await response.json()).toMatchObject({
122+
fields: expect.arrayContaining(['nickname']),
123+
author: 'author_id',
124+
});
125+
});

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

Lines changed: 41 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -118,13 +118,13 @@ function fakeDevServer(
118118
return { server, invalidated, restart, emit, logError };
119119
}
120120

121-
function startDevServer(
121+
async function startDevServer(
122122
plugin: RoutingPlugin,
123123
moduleIds?: Array<string>,
124124
extraEnvironments?: Record<string, unknown>,
125125
) {
126126
const dev = fakeDevServer(moduleIds, extraEnvironments);
127-
(getHookHandler(plugin.configureServer) as (server: unknown) => void)(dev.server);
127+
await (getHookHandler(plugin.configureServer) as (server: unknown) => Promise<void>)(dev.server);
128128
return dev;
129129
}
130130

@@ -188,6 +188,26 @@ describe('routingPlugin', () => {
188188
expect(database).toContain('requireRuntimeBinding<D1Database>("AUTH_DB")');
189189
});
190190

191+
it('writes auth files before later configureServer hooks can load the Worker', async () => {
192+
const root = createTempRoot();
193+
writeFileSync(
194+
join(root, 'auth.ts'),
195+
"export type {} from 'void/auth';\nexport default { user: { additionalFields: { nickname: { type: 'string' } } } };",
196+
);
197+
const plugin = createRoutingPlugin(root, { isAuthEnabled: () => true });
198+
resolveConfig(plugin, 'serve');
199+
const dev = fakeDevServer();
200+
201+
await (getHookHandler(plugin.configureServer) as (server: unknown) => Promise<void>)(
202+
dev.server,
203+
);
204+
205+
expect(readFileSync(join(root, '.void', 'better-auth-schema.ts'), 'utf8')).toContain(
206+
'"nickname"',
207+
);
208+
expect(existsSync(join(root, '.void', 'better-auth-db.ts'))).toBe(true);
209+
});
210+
191211
it('resolves extensionless and Vite alias imports in auth.ts during a build', async () => {
192212
const root = createTempRoot();
193213
mkdirSync(join(root, 'lib'));
@@ -384,7 +404,7 @@ describe('routingPlugin', () => {
384404
});
385405
resolveConfig(plugin, 'serve');
386406
await runBuildStart(plugin);
387-
const { emit, restart } = startDevServer(plugin);
407+
const { emit, restart } = await startDevServer(plugin);
388408
restart.mockImplementation(() => runBuildStart(plugin));
389409

390410
const addedPath = join(root, 'routes', addedRoute);
@@ -405,7 +425,7 @@ describe('routingPlugin', () => {
405425
);
406426

407427
const plugin = createRoutingPlugin(root, { isAuthEnabled: () => false });
408-
const { emit, invalidated } = startDevServer(plugin, PAGE_MODULE_IDS);
428+
const { emit, invalidated } = await startDevServer(plugin, PAGE_MODULE_IDS);
409429

410430
writeFileSync(
411431
join(root, 'pages', 'test.tsx'),
@@ -429,7 +449,7 @@ describe('routingPlugin', () => {
429449

430450
const plugin = createRoutingPlugin(root, { isAuthEnabled: () => false });
431451
resolveConfig(plugin, 'serve', plugins);
432-
const { emit, invalidated, logError } = startDevServer(plugin, PAGE_MODULE_IDS);
452+
const { emit, invalidated, logError } = await startDevServer(plugin, PAGE_MODULE_IDS);
433453

434454
// Moving about.tsx to about/index.tsx adds the new file before the old one goes.
435455
const indexPath = join(root, 'pages', 'about', 'index.tsx');
@@ -463,7 +483,7 @@ describe('routingPlugin', () => {
463483
runConfig(plugin, { command: 'serve', mode: 'development' });
464484
resolveConfig(plugin, 'serve');
465485
await runBuildStart(plugin);
466-
const { emit, logError } = startDevServer(plugin, PAGE_MODULE_IDS);
486+
const { emit, logError } = await startDevServer(plugin, PAGE_MODULE_IDS);
467487
const typesPath = join(root, '.void', 'routes.d.ts');
468488
const before = readFileSync(typesPath, 'utf8');
469489
expect(before).toContain('pages/home.dev.server.ts');
@@ -490,7 +510,7 @@ describe('routingPlugin', () => {
490510
const plugin = createRoutingPlugin(root, { isAuthEnabled: () => false });
491511
resolveConfig(plugin, 'serve');
492512
await runBuildStart(plugin);
493-
const { emit, invalidated } = startDevServer(plugin, PAGE_MODULE_IDS);
513+
const { emit, invalidated } = await startDevServer(plugin, PAGE_MODULE_IDS);
494514

495515
writeFileSync(pagePath, 'export default function Index() { return <h1>Updated</h1>; }');
496516
await emit('change', pagePath);
@@ -519,7 +539,7 @@ describe('routingPlugin', () => {
519539
const plugin = createRoutingPlugin(root, { isAuthEnabled: () => false });
520540
resolveConfig(plugin, 'serve');
521541
await runBuildStart(plugin);
522-
const { emit, invalidated } = startDevServer(plugin, PAGE_MODULE_IDS);
542+
const { emit, invalidated } = await startDevServer(plugin, PAGE_MODULE_IDS);
523543

524544
writeFileSync(
525545
serverPath,
@@ -562,7 +582,9 @@ describe('routingPlugin', () => {
562582

563583
const typesPath = join(root, '.void', 'routes.d.ts');
564584
const previousTypes = readFileSync(typesPath, 'utf-8');
565-
const { server, emit, invalidated, logError } = startDevServer(plugin, ['virtual:void-routes']);
585+
const { server, emit, invalidated, logError } = await startDevServer(plugin, [
586+
'virtual:void-routes',
587+
]);
566588

567589
expect(previousTypes).not.toContain('POST: {');
568590

@@ -624,7 +646,7 @@ describe('routingPlugin', () => {
624646
const plugin = createRoutingPlugin(root, { isAuthEnabled: () => false });
625647
resolveConfig(plugin, 'serve');
626648
await runBuildStart(plugin);
627-
const { emit, invalidated } = startDevServer(plugin, ['virtual:void-routes']);
649+
const { emit, invalidated } = await startDevServer(plugin, ['virtual:void-routes']);
628650

629651
writeFileSync(envPath, 'export default { example: true };');
630652
await emit('change', envPath);
@@ -645,7 +667,9 @@ describe('routingPlugin', () => {
645667
const plugin = createRoutingPlugin(root, { isAuthEnabled: () => false });
646668
resolveConfig(plugin, 'serve');
647669
await runBuildStart(plugin);
648-
const { server, emit, invalidated, logError } = startDevServer(plugin, ['virtual:void-routes']);
670+
const { server, emit, invalidated, logError } = await startDevServer(plugin, [
671+
'virtual:void-routes',
672+
]);
649673
vi.spyOn(
650674
server.environments.void_worker.moduleGraph,
651675
'invalidateModule',
@@ -673,7 +697,7 @@ describe('routingPlugin', () => {
673697
const plugin = createRoutingPlugin(root, { isAuthEnabled: () => false });
674698
resolveConfig(plugin, 'serve');
675699
await runBuildStart(plugin);
676-
const { emit, invalidated } = startDevServer(plugin, ['virtual:void-routes']);
700+
const { emit, invalidated } = await startDevServer(plugin, ['virtual:void-routes']);
677701
const typesPath = join(root, '.void', 'routes.d.ts');
678702
const types = readFileSync(typesPath, 'utf8');
679703

@@ -701,7 +725,7 @@ describe('routingPlugin', () => {
701725
);
702726
const plugin = routingPlugin(root, { isAuthEnabled: () => true, getApplicationAnalysis });
703727
resolveConfig(plugin, 'serve');
704-
const { emit, invalidated } = startDevServer(plugin, ['virtual:void-routes']);
728+
const { emit, invalidated } = await startDevServer(plugin, ['virtual:void-routes']);
705729
if (overlap === 'another save') {
706730
await runBuildStart(plugin);
707731
}
@@ -768,7 +792,7 @@ describe('routingPlugin', () => {
768792
const plugin = createRoutingPlugin(root, { isAuthEnabled: () => true });
769793
resolveConfig(plugin, 'serve');
770794
await runBuildStart(plugin);
771-
const { emit, invalidated } = startDevServer(plugin, ['virtual:void-routes']);
795+
const { emit, invalidated } = await startDevServer(plugin, ['virtual:void-routes']);
772796
writeFileSync(configPath, 'export default ' + JSON.stringify(config));
773797
writeFileSync(routePath, 'export const GET = () => new Response("updated");');
774798
await emit('change', routePath);
@@ -797,7 +821,7 @@ describe('routingPlugin', () => {
797821
const plugin = createRoutingPlugin(root, { target, isAuthEnabled: () => auth });
798822
resolveConfig(plugin, 'serve');
799823
await runBuildStart(plugin);
800-
const { emit, invalidated } = startDevServer(plugin, ['virtual:void-routes']);
824+
const { emit, invalidated } = await startDevServer(plugin, ['virtual:void-routes']);
801825
const outputs = files.map((file) => {
802826
const path = join(root, '.void', file);
803827
const content = readFileSync(path, 'utf8');
@@ -969,7 +993,7 @@ describe('routingPlugin', () => {
969993
isAuthEnabled: () => false,
970994
onDevAssetRoutingPolicyChange: onPolicyChange,
971995
});
972-
const { emit, invalidated } = startDevServer(plugin, ['virtual:void-routes']);
996+
const { emit, invalidated } = await startDevServer(plugin, ['virtual:void-routes']);
973997

974998
const routePath = join(root, 'src', 'routes', 'api.ts');
975999
writeFileSync(routePath, 'export const GET = () => new Response("ok");\n');
@@ -988,7 +1012,7 @@ describe('routingPlugin', () => {
9881012
mkdirSync(join(root, 'src', 'pages'), { recursive: true });
9891013

9901014
const plugin = createRoutingPlugin(root, { isAuthEnabled: () => false });
991-
const { emit, invalidated } = startDevServer(plugin, PAGE_MODULE_IDS);
1015+
const { emit, invalidated } = await startDevServer(plugin, PAGE_MODULE_IDS);
9921016

9931017
const pagePath = join(root, 'src', 'pages', 'test.tsx');
9941018
writeFileSync(pagePath, 'export default function Test() { return null; }');

0 commit comments

Comments
 (0)