From 88883a0a5859ab6457f80b3df39796ee7e83e378 Mon Sep 17 00:00:00 2001 From: Alexander Lichter Date: Fri, 4 Dec 2026 12:42:48 +0100 Subject: [PATCH] fix(dev): prebundle Void runtime deps the scanner cannot reach --- packages/void/src/index.ts | 4 + packages/void/src/pages/plugin.ts | 19 ++- .../void/src/plugin-worker-environment.ts | 41 +++++- .../plugin-vite-environment.test.ts | 29 +++++ .../void/test/unit/pages-build-id.test.ts | 2 +- packages/void/test/unit/pages-plugin.test.ts | 47 +++++++ .../unit/plugin-dev-asset-routing.test.ts | 17 +-- .../unit/worker-runtime-optimizer.test.ts | 123 ++++++++++++++++++ 8 files changed, 261 insertions(+), 21 deletions(-) create mode 100644 packages/void/test/unit/worker-runtime-optimizer.test.ts diff --git a/packages/void/src/index.ts b/packages/void/src/index.ts index f82a925e0..69a151a7b 100644 --- a/packages/void/src/index.ts +++ b/packages/void/src/index.ts @@ -296,6 +296,10 @@ export function voidPlugin(options?: { detected || isNodeTarget(config.target) ? undefined : { root, scan: () => getNativeWorkerSourceFiles(application) }, + () => ({ + authContext: authEnabled || bindings.needsLive === true || application.websockets.length > 0, + database: application.needsDatabase, + }), ); // Scan queues/websocket routes early so both framework-mode and default-mode // branches can safely close over these bindings. diff --git a/packages/void/src/pages/plugin.ts b/packages/void/src/pages/plugin.ts index 6bf1401e5..d2a8e522f 100644 --- a/packages/void/src/pages/plugin.ts +++ b/packages/void/src/pages/plugin.ts @@ -1,6 +1,6 @@ import { existsSync } from 'node:fs'; import { dirname, isAbsolute, join } from 'pathslash'; -import { loadEnv, normalizePath } from 'vite'; +import { loadEnv, mergeConfig, normalizePath } from 'vite'; import type { Plugin, ResolvedConfig, UserConfig } from 'vite'; import { computePagesBuildId, endPagesBuild } from './build-id-source.ts'; import type { PagesBuildInputs } from './build-id-source.ts'; @@ -15,6 +15,13 @@ import type { PageScanResult } from './types.ts'; const RENDERER_ID = 'virtual:void-pages-renderer'; const CLIENT_ENTRY_ID = 'virtual:void-pages-client'; +// The generated client entry reaches void/pages-client, which imports devalue, through a virtual +// module and the adapter package, so the client scan does not find it. A linked void is served as +// source, and the first page load would find devalue and run the optimizer again. +const DEV_CLIENT_CONFIG: UserConfig = { + environments: { client: { optimizeDeps: { include: ['void > devalue'] } } }, +}; + type PagesPluginContext = { isDev: boolean; scan: () => Promise; @@ -263,12 +270,10 @@ export function createPagesPlugin(pagesDir: string, options: CreatePagesPluginOp // The dev server serves a single build, so a tab never outlives the chunks // it imported, and an app without a client entry has no tab to recover. // Leaving the id undefined keeps every build check a no-op there. - if ( - dev || - resolved === null || - resolved === undefined || - options.deployRecovery === false - ) { + if (dev) { + return mergeConfig(resolved ?? {}, DEV_CLIENT_CONFIG); + } + if (resolved === null || resolved === undefined || options.deployRecovery === false) { return resolved; } // An explicit app define pins the id, for a fixture or for one that diff --git a/packages/void/src/plugin-worker-environment.ts b/packages/void/src/plugin-worker-environment.ts index e6ae0f27f..44a8c4d2c 100644 --- a/packages/void/src/plugin-worker-environment.ts +++ b/packages/void/src/plugin-worker-environment.ts @@ -218,6 +218,33 @@ const DATABASE_DRIVER_DEPS: Record> = { mysql: ['void > mysql2'], }; +// The generated entry loads Void's routing runtime, which imports these for itself and for the +// generated routes. +const ROUTING_RUNTIME_DEPS = [ + 'void > devalue', + 'void > hono', + 'void > hono/route', + 'void > hono/utils/url', +]; + +// Void's request auth context, which void/auth, void/live and WebSocket routes load. +const AUTH_CONTEXT_DEPS = ['void > hono/http-exception']; + +// void/schema-* re-exports the dialect's Drizzle schema builders. App schemas and the generated +// auth schema import it. +const DATABASE_SCHEMA_DEPS: Record> = { + sqlite: ['void > drizzle-orm/sqlite-core'], + postgresql: ['void > drizzle-orm/pg-core'], + mysql: ['void > drizzle-orm/mysql-core'], +}; + +/** The parts of Void's runtime that an app loads beyond the routing runtime. */ +export type WorkerRuntimeFeatures = { + /** Auth, void/live or a WebSocket route. */ + authContext: boolean; + database: boolean; +}; + const NODE_BUILTIN = new RegExp(`^(?:node:)?(?:${builtinModules.join('|')})$`); const NODE_BUILTIN_REQUIRE_PREFIX = '\0void:node-require:'; @@ -255,6 +282,7 @@ export function createServerRuntimeOptimizerPlugin( readCompat: () => WranglerCompat, ssrEntry: string | null = null, nativeWorker?: { root: string; scan: () => Promise> }, + readFeatures: () => WorkerRuntimeFeatures = () => ({ authContext: false, database: false }), ): Plugin { let workerdNodeBuiltins: Promise> | undefined; let scanNativeWorker = false; @@ -299,6 +327,7 @@ export function createServerRuntimeOptimizerPlugin( entries.push(...(await nativeWorker.scan())); } } + const features = readFeatures(); return { optimizeDeps: { // `better-auth` keeps OAuth request state on a module-local ref. Prebundling an app @@ -313,14 +342,16 @@ export function createServerRuntimeOptimizerPlugin( // Excluding void also skips converting its CommonJS dependencies, which workerd cannot // evaluate: an installed void/email fails with "exports is not defined". // - // Void's routing runtime imports Hono for itself and for the generated routes. Naming - // it here prebundles it before the Worker starts, not on its first request. + // The Worker reaches Void's runtime through generated modules and this excluded + // package, so the scan never sees the runtime's own imports. Naming them here + // prebundles them before the Worker starts. Each one found during a request instead + // reloads the Worker. include: [ - 'void > devalue', 'void > email-validator', - 'void > hono', - 'void > hono/route', + ...ROUTING_RUNTIME_DEPS, + ...(features.authContext ? AUTH_CONTEXT_DEPS : []), ...DATABASE_DRIVER_DEPS[dialect], + ...(features.database ? DATABASE_SCHEMA_DEPS[dialect] : []), ], }, }; diff --git a/packages/void/test/integration/plugin-vite-environment.test.ts b/packages/void/test/integration/plugin-vite-environment.test.ts index 470d772c4..529556f78 100644 --- a/packages/void/test/integration/plugin-vite-environment.test.ts +++ b/packages/void/test/integration/plugin-vite-environment.test.ts @@ -312,6 +312,35 @@ export default defineDurableState({ initialState: { count }, methods: { get(c) { expect(config.environments.ssr.optimizeDeps.exclude ?? []).not.toContain('better-auth'); }); + it('prebundles the runtime modules an app loads in the worker environment', async () => { + const plain = createProjectRoot(); + vi.spyOn(process, 'cwd').mockReturnValue(plain); + const plainConfig = await resolveConfig( + { root: plain, configFile: false, plugins: [voidPlugin()] }, + 'serve', + 'development', + ); + const plainIncludes = plainConfig.environments.void_worker.optimizeDeps.include; + expect(plainIncludes).toContain('void > hono/utils/url'); + expect(plainIncludes).not.toContain('void > hono/http-exception'); + expect(plainIncludes).not.toContain('void > drizzle-orm/sqlite-core'); + + const withAuth = createProjectRoot(); + vi.spyOn(process, 'cwd').mockReturnValue(withAuth); + writeFileSync( + join(withAuth, 'auth.ts'), + "import { defineAuth } from 'void/auth'; export default defineAuth({});", + ); + const authConfig = await resolveConfig( + { root: withAuth, configFile: false, plugins: [voidPlugin()] }, + 'serve', + 'development', + ); + expect(authConfig.environments.void_worker.optimizeDeps.include).toEqual( + expect.arrayContaining(['void > hono/http-exception', 'void > drizzle-orm/sqlite-core']), + ); + }); + it.each(['before', 'after'])( 'prebundles them in an adapter-owned workerd environment with Void listed %s it', async (order) => { diff --git a/packages/void/test/unit/pages-build-id.test.ts b/packages/void/test/unit/pages-build-id.test.ts index e3a6bcacf..60809f110 100644 --- a/packages/void/test/unit/pages-build-id.test.ts +++ b/packages/void/test/unit/pages-build-id.test.ts @@ -476,7 +476,7 @@ describe('createPagesPlugin build id', () => { it('defines nothing in the dev server, which serves one build', async () => { const config = createConfigHook(); - expect(await config({}, { command: 'serve' })).toEqual({}); + expect(await config({}, { command: 'serve' })).not.toHaveProperty('define'); }); it('leaves an id the app defines to Vite, without hashing the tree', async () => { diff --git a/packages/void/test/unit/pages-plugin.test.ts b/packages/void/test/unit/pages-plugin.test.ts index d3d108280..c43757a03 100644 --- a/packages/void/test/unit/pages-plugin.test.ts +++ b/packages/void/test/unit/pages-plugin.test.ts @@ -138,6 +138,53 @@ describe('shared Pages plugin scan lifecycle', () => { }); }); +describe('shared Pages plugin dev dependencies', () => { + let root: string; + + beforeEach(() => { + root = normalizePath(mkdtempSync(join(tmpdir(), 'void-pages-plugin-'))); + mkdirSync(join(root, 'pages')); + }); + + afterEach(() => { + rmSync(root, { recursive: true, force: true }); + }); + + function setup(adapterConfig: () => import('vite').UserConfig | void) { + return createPagesPlugin(join(root, 'pages'), { + name: 'test:pages', + generateRenderer: () => '', + generateClient: () => '', + config: adapterConfig, + }) as unknown as PagesPluginHooks; + } + + it("prebundles the pages client's devalue import with the adapter's dev config", () => { + const plugin = setup(() => ({ + optimizeDeps: { include: ['react'] }, + environments: { client: { optimizeDeps: { include: ['react-dom/client'] } } }, + })); + + expect(plugin.config({}, { command: 'serve' })).toEqual({ + optimizeDeps: { include: ['react'] }, + environments: { + client: { optimizeDeps: { include: ['react-dom/client', 'void > devalue'] } }, + }, + }); + expect(setup(() => {}).config({}, { command: 'serve' })).toEqual({ + environments: { client: { optimizeDeps: { include: ['void > devalue'] } } }, + }); + }); + + it('leaves build config to the adapter', () => { + const plugin = setup(() => ({ optimizeDeps: { include: ['react'] } })); + + expect(plugin.config({}, { command: 'build' })).toEqual( + expect.not.objectContaining({ environments: expect.anything() }), + ); + }); +}); + describe('resolvePrefetchConfig', () => { it('leaves Links without a prefetch prop off by default', () => { expect(resolvePrefetchConfig(undefined)).toEqual({ diff --git a/packages/void/test/unit/plugin-dev-asset-routing.test.ts b/packages/void/test/unit/plugin-dev-asset-routing.test.ts index 2b2ce2e00..3a97c2b78 100644 --- a/packages/void/test/unit/plugin-dev-asset-routing.test.ts +++ b/packages/void/test/unit/plugin-dev-asset-routing.test.ts @@ -228,6 +228,13 @@ describe('voidPlugin dev asset routing', () => { // The Cloudflare plugin gives each environment it runs in workerd these conditions. const workerd = { resolve: { conditions: ['workerd', 'worker', 'module', 'browser'] } }; const node = { resolve: { conditions: ['module', 'node'] } }; + const workerdIncludes = [ + 'void > email-validator', + 'void > devalue', + 'void > hono', + 'void > hono/route', + 'void > hono/utils/url', + ]; async function resolveRuntimeOptimizerConfig( root: string, @@ -254,7 +261,7 @@ describe('voidPlugin dev asset routing', () => { const workerdOptimizer = { optimizeDeps: { exclude: ['void', 'better-auth'], - include: ['void > devalue', 'void > email-validator', 'void > hono', 'void > hono/route'], + include: workerdIncludes, }, }; const nodeOptimizer = { optimizeDeps: { exclude: ['void'] } }; @@ -295,13 +302,7 @@ describe('voidPlugin dev asset routing', () => { optimizeDeps: drivers ? { exclude: ['void', 'better-auth'], - include: [ - 'void > devalue', - 'void > email-validator', - 'void > hono', - 'void > hono/route', - ...drivers, - ], + include: [...workerdIncludes, ...drivers], } : { exclude: ['void'] }, }); diff --git a/packages/void/test/unit/worker-runtime-optimizer.test.ts b/packages/void/test/unit/worker-runtime-optimizer.test.ts new file mode 100644 index 000000000..d42c77614 --- /dev/null +++ b/packages/void/test/unit/worker-runtime-optimizer.test.ts @@ -0,0 +1,123 @@ +import { existsSync, readFileSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import type { UserConfig } from 'vite'; +import { parseSync } from 'vite'; +import { describe, expect, it } from 'vite-plus/test'; +import type { DatabaseDialect } from '../../src/config.ts'; +import { createServerRuntimeOptimizerPlugin } from '../../src/plugin-worker-environment.ts'; +import type { WorkerRuntimeFeatures } from '../../src/plugin-worker-environment.ts'; +import { staticModuleReferences } from '../../src/shared/module-references.ts'; +import { getHookHandler } from '../helpers/vite-hooks.ts'; + +const runtimeDir = fileURLToPath(new URL('../../src/runtime/', import.meta.url)); + +async function workerIncludes( + features: WorkerRuntimeFeatures, + dialect: DatabaseDialect = 'sqlite', +): Promise> { + const plugin = createServerRuntimeOptimizerPlugin( + dialect, + () => ({ compatibilityDate: '2026-02-24' }), + null, + undefined, + () => features, + ); + const configEnvironment = getHookHandler(plugin.configEnvironment); + const config = (await configEnvironment.call( + {} as ThisParameterType, + 'void_worker', + { resolve: { conditions: ['workerd'] } }, + { command: 'serve', mode: 'development' }, + )) as UserConfig; + return config.optimizeDeps?.include ?? []; +} + +function resolveSource(specifier: string, importer: string): string { + const base = resolve(dirname(importer), specifier); + const file = [base, base.replace(/\.js$/, '.ts'), `${base}.ts`, join(base, 'index.ts')].find( + (candidate) => candidate.endsWith('.ts') && existsSync(candidate), + ); + if (!file) { + throw new Error(`Cannot resolve ${specifier} from ${importer}`); + } + return file; +} + +/** The packages that these runtime modules and the modules they import load at runtime. */ +function runtimeImports(modules: Array): Set { + const packages = new Set(); + const pending = modules.map((module) => join(runtimeDir, module)); + const seen = new Set(); + for (let file = pending.pop(); file !== undefined; file = pending.pop()) { + if (seen.has(file)) { + continue; + } + seen.add(file); + const code = readFileSync(file, 'utf8'); + const parsed = parseSync(file, code); + const specifiers = staticModuleReferences(parsed, code).map(({ source }) => source); + for (const { moduleRequest } of parsed.module.dynamicImports) { + const literal = /^(["'])([^"'`]+)\1$/.exec( + code.slice(moduleRequest.start, moduleRequest.end), + ); + if (literal) { + specifiers.push(literal[2]); + } + } + for (const specifier of specifiers) { + if (specifier.startsWith('.')) { + // Queried imports such as `?raw` load assets, not modules. + if (!specifier.includes('?')) { + pending.push(resolveSource(specifier, file)); + } + } else if (!/^(?:node:|cloudflare:|#)/.test(specifier)) { + packages.add(specifier); + } + } + } + return packages; +} + +// Void's own packages are linked in a workspace and installed beside void otherwise, so Vite +// serves them as source. The Worker loads void's copy of better-auth from source on purpose. +const NOT_PREBUNDLED = /^(?:@void\/|better-auth$)/; + +function expectPrebundled(modules: Array, includes: Array): void { + const missing = [...runtimeImports(modules)].filter( + (specifier) => !NOT_PREBUNDLED.test(specifier) && !includes.includes(`void > ${specifier}`), + ); + expect(missing).toEqual([]); +} + +describe('Worker runtime dependency optimizer', () => { + it('prebundles what the routing runtime imports in every Worker', async () => { + const includes = await workerIncludes({ authContext: false, database: false }); + + expectPrebundled(['routing/index.ts', 'env/runtime.ts'], includes); + expect(includes).not.toContain('void > hono/http-exception'); + expect(includes.filter((include) => include.startsWith('void > drizzle-orm'))).toEqual([]); + }); + + it("prebundles the auth context's imports for auth, void/live and WebSocket routes", async () => { + const includes = await workerIncludes({ authContext: true, database: false }); + + expectPrebundled( + ['auth/index.ts', 'live/index.ts', 'live/server.ts', 'ws/room.ts', 'ws/server.ts'], + includes, + ); + }); + + it.each([ + ['sqlite', 'schema/d1.ts'], + ['postgresql', 'schema/postgres.ts'], + ['mysql', 'schema/mysql.ts'], + ] as const)( + 'prebundles the %s schema builders for an app with a database', + async (dialect, schema) => { + const includes = await workerIncludes({ authContext: false, database: true }, dialect); + + expectPrebundled([`db/${schema}`], includes); + }, + ); +});