From 186d9fa280644669513a2d82ba3df4b482d0d2bf Mon Sep 17 00:00:00 2001 From: Alexander Lichter Date: Mon, 4 May 2026 17:04:08 +0200 Subject: [PATCH 1/7] feat(dev): wire /__void/{scheduled,queue} into Class A framework dev MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes the last gap from the framework-triggers rollout. TanStack Start, React Router, vinext (App and Pages routers) now expose the same trigger endpoints as default Void mode and the Class B/C frameworks. Mechanism: - We wrap the framework's worker entry inside dev miniflare. A new `.void/-trigger-wrapper.ts` becomes `workerConfig.main`, imports the framework's original entry plus the dispatch table, and intercepts /__void/{scheduled,queue} before delegating. The block is gated on `import.meta.env.DEV` so it tree-shakes in prod (where cli/wrapper.ts owns the deploy-time wrapping). - For tanstack-start and vinext-app we wrap a third-party entry (`@tanstack/react-start/server-entry`, `vinext/server/app-router-entry`) with `...original` spread so any `scheduled`/`queue` exports from the framework still pass through. - For react-router and vinext-pages we already generate their entries, so the wrapper imports those generated files directly. - frameworkTriggersPlugin now also exports `writeFrameworkTriggersDispatch` so getFrameworkEntry can write `.void/dev-triggers.ts` synchronously before the build starts parsing modules. The plugin's configResolved hook stays for HMR of cron/queue files in dev. Token persistence: - `@cloudflare/vite-plugin` spawns a separate worker-environment Vite that re-evaluates the user's vite.config and re-calls voidPlugin(). Each call generated a fresh devTriggerToken, so the dispatch file ended up with one token while the hint plugin printed a different one and curls hit `unauthorized`. Persist the token at `/.void/dev-trigger-token` so all voidPlugin() invocations in the same dev session converge. Verified end-to-end (cron POST → DB row inserted + KV key written) in playground/{tanstack-start, react-router, vinext-pages, vinext-app}. --- docs/guide/jobs.md | 2 +- docs/guide/queues.md | 2 +- packages/void/src/index.ts | 89 ++++++++++++++++++- .../void/src/plugin-framework-triggers.ts | 22 +++-- playground/react-router/crons/heartbeat.ts | 12 +++ playground/tanstack-start/crons/heartbeat.ts | 12 +++ playground/vinext-app/crons/heartbeat.ts | 12 +++ playground/vinext-pages/crons/heartbeat.ts | 12 +++ 8 files changed, 150 insertions(+), 13 deletions(-) create mode 100644 playground/react-router/crons/heartbeat.ts create mode 100644 playground/tanstack-start/crons/heartbeat.ts create mode 100644 playground/vinext-app/crons/heartbeat.ts create mode 100644 playground/vinext-pages/crons/heartbeat.ts diff --git a/docs/guide/jobs.md b/docs/guide/jobs.md index 512c56a8a..f3bdf5d01 100644 --- a/docs/guide/jobs.md +++ b/docs/guide/jobs.md @@ -84,7 +84,7 @@ curl -X POST http://localhost:5173/__void/scheduled \ If you set `__VOID_PROXY_TOKEN` in `.dev.vars`, that explicit token takes precedence and the printed curl command uses `x-void-internal: ` instead. -This works the same in default Void mode and framework mode (SvelteKit, Nuxt, Astro). In framework mode, the cron handler runs inside the framework adapter's request pipeline, so it sees whatever bindings the adapter exposes (D1, KV, R2, queues, etc.). Analog support is pending — its Nitro variant doesn't expose h3 helpers the same way. +This works the same in default Void mode and every supported framework — SvelteKit, Nuxt, Analog, Astro, TanStack Start, React Router, and vinext. In framework mode the cron handler runs inside the framework adapter's request pipeline (or the dev miniflare for Class A frameworks), so it sees whatever bindings the adapter exposes (D1, KV, R2, queues, AI, etc.). ## Deployment behavior diff --git a/docs/guide/queues.md b/docs/guide/queues.md index 6be66e7af..6223a96fd 100644 --- a/docs/guide/queues.md +++ b/docs/guide/queues.md @@ -137,4 +137,4 @@ curl -X POST http://localhost:5173/__void/queue \ If you set `__VOID_PROXY_TOKEN` in `.dev.vars`, that explicit token takes precedence and the printed curl command uses `x-void-internal: ` instead. -In **framework mode** (SvelteKit, Nuxt, Astro), the `/__void/queue` endpoint runs inside the framework adapter's request pipeline, so the consumer sees whatever bindings the adapter exposes (D1, KV, R2, queue producers, etc.). Native Miniflare queue delivery is not wired up in framework mode — use the manual dispatch endpoint to exercise a consumer. Analog support is pending. +In **framework mode** (SvelteKit, Nuxt, Analog, Astro, TanStack Start, React Router, vinext), the `/__void/queue` endpoint runs inside the framework adapter's request pipeline (or the dev miniflare for Class A frameworks), so the consumer sees whatever bindings the adapter exposes (D1, KV, R2, queue producers, etc.). Native Miniflare queue delivery is not wired up in framework mode — use the manual dispatch endpoint to exercise a consumer. diff --git a/packages/void/src/index.ts b/packages/void/src/index.ts index 306a2f539..2567a61e1 100644 --- a/packages/void/src/index.ts +++ b/packages/void/src/index.ts @@ -27,6 +27,7 @@ import { frameworkTriggersDispatchPath, frameworkTriggersPlugin, nitroDevTriggerInjectPlugin, + writeFrameworkTriggersDispatch, } from './plugin-framework-triggers.ts'; import { inferProjectBindings, @@ -46,8 +47,51 @@ import { filterLoadedEnv, resolveRemoteMode, stripInternalEnvKeys } from './shar import { DEFAULT_PROXY_URL, STAGING_PROXY_URL } from './shared/proxy.ts'; import { validateSsrEntry } from './ssr/entry.ts'; -/** Resolve the server entry module for a Class A framework. */ -function getFrameworkEntry(framework: Framework, root: string): string { +/** + * Persist the per-process dev-trigger token at `/.void/dev-trigger-token` + * so subsequent voidPlugin() invocations (e.g. the worker-environment Vite + * spawned by `@cloudflare/vite-plugin`) re-read the same value. Without this, + * each call to voidPlugin generates a fresh UUID, the dispatch file ends up + * with one token while the hint plugin prints a different one, and curls + * land on `unauthorized`. + * + * The token is removed on dev-server close by the framework-triggers / + * injection plugins (alongside the dispatch file) so a stale token from a + * previous session never leaks into the next one. + */ +function getOrCreateDevTriggerToken(root: string): string { + const tokenPath = join(root, '.void', 'dev-trigger-token'); + if (existsSync(tokenPath)) { + const existing = readFileSync(tokenPath, 'utf-8').trim(); + if (existing) { + return existing; + } + } + const fresh = crypto.randomUUID(); + mkdirSync(join(root, '.void'), { recursive: true }); + writeFileSync(tokenPath, fresh); + return fresh; +} + +/** + * Resolve the server entry module for a Class A framework. We always wrap + * the framework's own entry with a tiny shim that intercepts + * `/__void/{scheduled,queue}` in dev so cron and queue handlers run with + * the worker's full CF bindings. The interception block is gated on + * `import.meta.env.DEV` so it tree-shakes in prod (where `cli/wrapper.ts` + * generates the deploy-time wrapper instead). + */ +function getFrameworkEntry(framework: Framework, root: string, devTriggerToken: string): string { + // Write the dispatch file synchronously so the wrapper's static import is + // resolvable the moment Vite/rolldown starts parsing modules. The plugin + // hook would write it later (configResolved), which is too late in build + // mode where module resolution begins right after voidPlugin() returns. + writeFrameworkTriggersDispatch(root, devTriggerToken); + return generateClassATriggerWrapper(root, framework, getOriginalFrameworkEntry(framework, root)); +} + +/** The framework's own server entry, before our trigger wrapper. */ +function getOriginalFrameworkEntry(framework: Framework, root: string): string { switch (framework) { case 'tanstack-start': return '@tanstack/react-start/server-entry'; @@ -60,6 +104,42 @@ function getFrameworkEntry(framework: Framework, root: string): string { } } +/** + * Generate `/.void/-trigger-wrapper.ts`. This file becomes + * `workerConfig.main` so the dev miniflare/workerd evaluates *our* fetch + * first, dispatches `/__void/{scheduled,queue}` if it matches, and otherwise + * delegates to the framework's original entry. + */ +function generateClassATriggerWrapper( + root: string, + framework: Framework, + original: string, +): string { + const outDir = join(root, '.void'); + mkdirSync(outDir, { recursive: true }); + const wrapperPath = join(outDir, `${framework}-trigger-wrapper.ts`); + const dispatchPath = frameworkTriggersDispatchPath(root); + writeFileSync( + wrapperPath, + `// @ts-nocheck — Auto-generated by Void. Do NOT edit. +import original from ${JSON.stringify(original)}; +import { handleDevTrigger } from ${JSON.stringify(dispatchPath)}; + +export default { + ...original, + async fetch(request, env, ctx) { + if (import.meta.env.DEV) { + const response = await handleDevTrigger(request, env, ctx); + if (response) return response; + } + return original.fetch(request, env, ctx); + }, +}; +`, + ); + return wrapperPath; +} + /** Generate a worker entry for vinext Pages Router projects. */ function generateVinextPagesEntry(root: string): string { const outDir = join(root, '.void'); @@ -314,7 +394,7 @@ export function voidPlugin(options?: { }): Array { // Resolve root relative to CWD — this runs at config time const root = process.cwd(); - const devTriggerToken = crypto.randomUUID(); + const devTriggerToken = getOrCreateDevTriggerToken(root); const config = readConfig(root); const dialect = getDatabaseDialect(config); const detected = detectFramework(root); @@ -967,7 +1047,7 @@ export function voidPlugin(options?: { }; if (framework) { - workerConfig.main = getFrameworkEntry(framework, root); + workerConfig.main = getFrameworkEntry(framework, root, devTriggerToken); const existingFlags = (workerConfig.compatibility_flags as Array | undefined) ?? []; if (!existingFlags.includes('nodejs_compat')) { workerConfig.compatibility_flags = [...existingFlags, 'nodejs_compat']; @@ -1027,6 +1107,7 @@ export function voidPlugin(options?: { }), migrationPlugin(root, getDatabaseDialect(config)), ...(vinextCompat ? [vinextCompat] : []), + frameworkTriggersPlugin(root, { devTriggerToken }), devTriggersHintPlugin(root, { framework: true, devTriggerToken }), ...cloudflare({ ...inspectorPortOption, diff --git a/packages/void/src/plugin-framework-triggers.ts b/packages/void/src/plugin-framework-triggers.ts index 17a554c7a..c79a4bc7b 100644 --- a/packages/void/src/plugin-framework-triggers.ts +++ b/packages/void/src/plugin-framework-triggers.ts @@ -14,6 +14,20 @@ export function frameworkTriggersDispatchPath(root: string): string { return join(root, '.void', 'dev-triggers.ts'); } +/** + * Synchronously emit `/.void/dev-triggers.ts`. We expose this directly + * (in addition to the Vite plugin below) so callers like the Class A entry + * wrapper can guarantee the file exists at the moment they reference it, + * without depending on `configResolved` ordering. + */ +export function writeFrameworkTriggersDispatch(root: string, devTriggerToken: string): void { + const jobs = scanJobsSync(root); + const queues = scanQueuesSync(root); + const target = frameworkTriggersDispatchPath(root); + mkdirSync(dirname(target), { recursive: true }); + writeFileSync(target, generateModule(root, jobs, queues, devTriggerToken)); +} + /** * Writes a real file at `/.void/dev-triggers.ts` exporting * `handleDevTrigger(request, env, ctx)`. We use a real file (not a Vite @@ -23,13 +37,7 @@ export function frameworkTriggersDispatchPath(root: string): string { * with the framework adapter's real bindings. */ export function frameworkTriggersPlugin(root: string, options: FrameworkTriggersOptions): Plugin { - const writeDispatch = () => { - const jobs = scanJobsSync(root); - const queues = scanQueuesSync(root); - const target = frameworkTriggersDispatchPath(root); - mkdirSync(dirname(target), { recursive: true }); - writeFileSync(target, generateModule(root, jobs, queues, options.devTriggerToken)); - }; + const writeDispatch = () => writeFrameworkTriggersDispatch(root, options.devTriggerToken); return { name: 'void:framework-triggers', diff --git a/playground/react-router/crons/heartbeat.ts b/playground/react-router/crons/heartbeat.ts new file mode 100644 index 000000000..448445b4d --- /dev/null +++ b/playground/react-router/crons/heartbeat.ts @@ -0,0 +1,12 @@ +import { db } from 'void/db'; +import { kv } from 'void/kv'; +import { users } from '../db/schema.ts'; + +export const cron = '0 * * * *'; + +export default async function heartbeat() { + const now = new Date().toISOString(); + await db.insert(users).values({ name: `cron-${now}`, email: `cron-${now}@local` }); + await kv.put('last-cron-run', now); + console.log('[cron] heartbeat fired at', now); +} diff --git a/playground/tanstack-start/crons/heartbeat.ts b/playground/tanstack-start/crons/heartbeat.ts new file mode 100644 index 000000000..448445b4d --- /dev/null +++ b/playground/tanstack-start/crons/heartbeat.ts @@ -0,0 +1,12 @@ +import { db } from 'void/db'; +import { kv } from 'void/kv'; +import { users } from '../db/schema.ts'; + +export const cron = '0 * * * *'; + +export default async function heartbeat() { + const now = new Date().toISOString(); + await db.insert(users).values({ name: `cron-${now}`, email: `cron-${now}@local` }); + await kv.put('last-cron-run', now); + console.log('[cron] heartbeat fired at', now); +} diff --git a/playground/vinext-app/crons/heartbeat.ts b/playground/vinext-app/crons/heartbeat.ts new file mode 100644 index 000000000..448445b4d --- /dev/null +++ b/playground/vinext-app/crons/heartbeat.ts @@ -0,0 +1,12 @@ +import { db } from 'void/db'; +import { kv } from 'void/kv'; +import { users } from '../db/schema.ts'; + +export const cron = '0 * * * *'; + +export default async function heartbeat() { + const now = new Date().toISOString(); + await db.insert(users).values({ name: `cron-${now}`, email: `cron-${now}@local` }); + await kv.put('last-cron-run', now); + console.log('[cron] heartbeat fired at', now); +} diff --git a/playground/vinext-pages/crons/heartbeat.ts b/playground/vinext-pages/crons/heartbeat.ts new file mode 100644 index 000000000..448445b4d --- /dev/null +++ b/playground/vinext-pages/crons/heartbeat.ts @@ -0,0 +1,12 @@ +import { db } from 'void/db'; +import { kv } from 'void/kv'; +import { users } from '../db/schema.ts'; + +export const cron = '0 * * * *'; + +export default async function heartbeat() { + const now = new Date().toISOString(); + await db.insert(users).values({ name: `cron-${now}`, email: `cron-${now}@local` }); + await kv.put('last-cron-run', now); + console.log('[cron] heartbeat fired at', now); +} From 7aabba9b9afb52a8c76247c5f6eb556529facfef Mon Sep 17 00:00:00 2001 From: Alexander Lichter Date: Mon, 4 May 2026 17:24:58 +0200 Subject: [PATCH 2/7] fix(dev): keep dev-trigger dispatch out of Class A prod bundles MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Class A wrapper imported `handleDevTrigger` statically. The named import was used only inside `if (import.meta.env.DEV)`, but rolldown kept the dispatch module — and its transitive user-cron imports — alive in the worker bundle produced by `vite build`, leaking dev-only code (token literal, dispatch logic, user crons) into anyone running `vite build && wrangler deploy`. Move the import into a dynamic `await import()` inside the DEV branch. Vite replaces DEV with `false` in build, the branch becomes dead code, and rolldown drops the dynamic import along with everything it pulls in. Verified by rebuilding playground/react-router and playground/tanstack-start and grepping for `handleDevTrigger`, `x-void-dev-trigger`, `__VOID_PROXY_TOKEN`, and `heartbeat` in the resulting server bundles — all 0 hits. --- packages/void/src/index.ts | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/packages/void/src/index.ts b/packages/void/src/index.ts index 2567a61e1..7f1dc08e2 100644 --- a/packages/void/src/index.ts +++ b/packages/void/src/index.ts @@ -78,14 +78,16 @@ function getOrCreateDevTriggerToken(root: string): string { * the framework's own entry with a tiny shim that intercepts * `/__void/{scheduled,queue}` in dev so cron and queue handlers run with * the worker's full CF bindings. The interception block is gated on - * `import.meta.env.DEV` so it tree-shakes in prod (where `cli/wrapper.ts` - * generates the deploy-time wrapper instead). + * `import.meta.env.DEV` and the dispatch module is loaded via dynamic + * `import()` so the entire dev path (including user cron imports) is + * dead-code-eliminated in `vite build`. Production deploys go through + * `cli/wrapper.ts` instead. */ function getFrameworkEntry(framework: Framework, root: string, devTriggerToken: string): string { - // Write the dispatch file synchronously so the wrapper's static import is - // resolvable the moment Vite/rolldown starts parsing modules. The plugin - // hook would write it later (configResolved), which is too late in build - // mode where module resolution begins right after voidPlugin() returns. + // Eagerly write the dispatch file so the dev fetch handler can dynamically + // import it on the very first request — the plugin's `configResolved` hook + // also rewrites it, but we can't rely on that having run before the first + // request hits the worker. writeFrameworkTriggersDispatch(root, devTriggerToken); return generateClassATriggerWrapper(root, framework, getOriginalFrameworkEntry(framework, root)); } @@ -109,6 +111,12 @@ function getOriginalFrameworkEntry(framework: Framework, root: string): string { * `workerConfig.main` so the dev miniflare/workerd evaluates *our* fetch * first, dispatches `/__void/{scheduled,queue}` if it matches, and otherwise * delegates to the framework's original entry. + * + * The dispatch module is loaded via dynamic `import()` inside the + * `import.meta.env.DEV` branch. Vite replaces `DEV` with `false` in build + * mode, the entire branch becomes dead code, and rolldown drops the dynamic + * import — so the dispatch file (and its transitive user-cron imports) never + * lands in production worker bundles produced by `vite build`. */ function generateClassATriggerWrapper( root: string, @@ -123,12 +131,12 @@ function generateClassATriggerWrapper( wrapperPath, `// @ts-nocheck — Auto-generated by Void. Do NOT edit. import original from ${JSON.stringify(original)}; -import { handleDevTrigger } from ${JSON.stringify(dispatchPath)}; export default { ...original, async fetch(request, env, ctx) { if (import.meta.env.DEV) { + const { handleDevTrigger } = await import(${JSON.stringify(dispatchPath)}); const response = await handleDevTrigger(request, env, ctx); if (response) return response; } From 1673960c8e56b90837f0c48f0fff931ee6df5deb Mon Sep 17 00:00:00 2001 From: Alexander Lichter Date: Mon, 4 May 2026 17:25:38 +0200 Subject: [PATCH 3/7] docs: drop Analog from supported-framework lists The previous PR added Analog to the framework-mode supporters in docs/guide/jobs.md and docs/guide/queues.md, but the implementation still defers Analog explicitly (packages/void/src/index.ts:582-587) because @analogjs/vite-plugin-nitro evaluates server middleware before Nitro's plugins populate event.context.cloudflare. Restore the "Analog support is pending" caveat and align the comment in plugin-dev-triggers-hint.ts. --- docs/guide/jobs.md | 2 +- docs/guide/queues.md | 2 +- packages/void/src/plugin-dev-triggers-hint.ts | 5 +++-- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/guide/jobs.md b/docs/guide/jobs.md index f3bdf5d01..8fb9c8140 100644 --- a/docs/guide/jobs.md +++ b/docs/guide/jobs.md @@ -84,7 +84,7 @@ curl -X POST http://localhost:5173/__void/scheduled \ If you set `__VOID_PROXY_TOKEN` in `.dev.vars`, that explicit token takes precedence and the printed curl command uses `x-void-internal: ` instead. -This works the same in default Void mode and every supported framework — SvelteKit, Nuxt, Analog, Astro, TanStack Start, React Router, and vinext. In framework mode the cron handler runs inside the framework adapter's request pipeline (or the dev miniflare for Class A frameworks), so it sees whatever bindings the adapter exposes (D1, KV, R2, queues, AI, etc.). +This works the same in default Void mode and every supported framework — SvelteKit, Nuxt, Astro, TanStack Start, React Router, and vinext. In framework mode the cron handler runs inside the framework adapter's request pipeline (or the dev miniflare for Class A frameworks), so it sees whatever bindings the adapter exposes (D1, KV, R2, queues, AI, etc.). Analog support is pending — its Nitro variant doesn't expose h3 helpers the same way. ## Deployment behavior diff --git a/docs/guide/queues.md b/docs/guide/queues.md index 6223a96fd..6f5ec948b 100644 --- a/docs/guide/queues.md +++ b/docs/guide/queues.md @@ -137,4 +137,4 @@ curl -X POST http://localhost:5173/__void/queue \ If you set `__VOID_PROXY_TOKEN` in `.dev.vars`, that explicit token takes precedence and the printed curl command uses `x-void-internal: ` instead. -In **framework mode** (SvelteKit, Nuxt, Analog, Astro, TanStack Start, React Router, vinext), the `/__void/queue` endpoint runs inside the framework adapter's request pipeline (or the dev miniflare for Class A frameworks), so the consumer sees whatever bindings the adapter exposes (D1, KV, R2, queue producers, etc.). Native Miniflare queue delivery is not wired up in framework mode — use the manual dispatch endpoint to exercise a consumer. +In **framework mode** (SvelteKit, Nuxt, Astro, TanStack Start, React Router, vinext), the `/__void/queue` endpoint runs inside the framework adapter's request pipeline (or the dev miniflare for Class A frameworks), so the consumer sees whatever bindings the adapter exposes (D1, KV, R2, queue producers, etc.). Native Miniflare queue delivery is not wired up in framework mode — use the manual dispatch endpoint to exercise a consumer. Analog support is pending. diff --git a/packages/void/src/plugin-dev-triggers-hint.ts b/packages/void/src/plugin-dev-triggers-hint.ts index c16deee25..ed5c3bd94 100644 --- a/packages/void/src/plugin-dev-triggers-hint.ts +++ b/packages/void/src/plugin-dev-triggers-hint.ts @@ -8,8 +8,9 @@ import { parseDotenvFile } from './shared/dotenv.ts'; /** * Prints a one-shot hint on dev server start when the project has crons * or queues, explaining how to trigger them locally. Both default Void mode - * and framework mode (SvelteKit/Nuxt/Analog/Astro) expose - * `/__void/scheduled` and `/__void/queue`. + * and framework mode (SvelteKit, Nuxt, Astro, TanStack Start, React Router, + * vinext) expose `/__void/scheduled` and `/__void/queue`. Analog support is + * pending. */ export function devTriggersHintPlugin( root: string, From d0871f76b21cff8c1f0f40c6d591d0d3ba45e305 Mon Sep 17 00:00:00 2001 From: Alexander Lichter Date: Mon, 4 May 2026 17:26:01 +0200 Subject: [PATCH 4/7] docs(dev): correct dev-trigger token lifecycle comment MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The previous docstring claimed the token was removed on dev-server close, but no code in the tree deletes `.void/dev-trigger-token` or `.void/dev-triggers.ts` — both files persist across runs by design (so the parent and worker-environment child Vite agree on the same value). Rewrite the comment to describe actual behavior instead of an aspirational cleanup that never happens. --- packages/void/src/index.ts | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/packages/void/src/index.ts b/packages/void/src/index.ts index 7f1dc08e2..85d81f14a 100644 --- a/packages/void/src/index.ts +++ b/packages/void/src/index.ts @@ -48,16 +48,20 @@ import { DEFAULT_PROXY_URL, STAGING_PROXY_URL } from './shared/proxy.ts'; import { validateSsrEntry } from './ssr/entry.ts'; /** - * Persist the per-process dev-trigger token at `/.void/dev-trigger-token` - * so subsequent voidPlugin() invocations (e.g. the worker-environment Vite - * spawned by `@cloudflare/vite-plugin`) re-read the same value. Without this, - * each call to voidPlugin generates a fresh UUID, the dispatch file ends up - * with one token while the hint plugin prints a different one, and curls - * land on `unauthorized`. + * Persist the dev-trigger token at `/.void/dev-trigger-token` so + * every voidPlugin() invocation against the same project reads the same + * value. This matters because `@cloudflare/vite-plugin` spawns a + * worker-environment child Vite that re-imports vite.config.ts and calls + * voidPlugin() again — without persistence the parent and child would + * generate different UUIDs, the dispatch file would embed one and the + * hint plugin would print the other, and curls would land on + * `unauthorized`. * - * The token is removed on dev-server close by the framework-triggers / - * injection plugins (alongside the dispatch file) so a stale token from a - * previous session never leaks into the next one. + * The file persists across dev sessions by design (it lives under `.void/`, + * which is gitignored and only wiped by `void deploy`). The token is local + * to the project and only honored by a worker bound to localhost; treat it + * like the rest of `.void/` — disposable scratch state, safe to remove + * manually if desired. */ function getOrCreateDevTriggerToken(root: string): string { const tokenPath = join(root, '.void', 'dev-trigger-token'); From 41f1633f3bc37a31893c90c91de6914a042d5b92 Mon Sep 17 00:00:00 2001 From: Alexander Lichter Date: Mon, 4 May 2026 17:26:21 +0200 Subject: [PATCH 5/7] fix(dev): regenerate trigger dispatch on cron/queue file edits MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The watcher only listened to `add` and `unlink`, so editing the exported `cron` schedule string (or a queue's name) in an existing handler didn't rewrite `.void/dev-triggers.ts`. The handler module itself reloads via Vite HMR but the schedule-to-handler routing table stays stale until restart, silently breaking newly-edited schedules in dev. Listen on `change` too. Codegen is idempotent and cheap — running it on every save costs a small sync glob + file write. --- packages/void/src/plugin-framework-triggers.ts | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/packages/void/src/plugin-framework-triggers.ts b/packages/void/src/plugin-framework-triggers.ts index c79a4bc7b..968d6aa7a 100644 --- a/packages/void/src/plugin-framework-triggers.ts +++ b/packages/void/src/plugin-framework-triggers.ts @@ -46,20 +46,20 @@ export function frameworkTriggersPlugin(root: string, options: FrameworkTriggers writeDispatch(); }, configureServer(server) { - // Re-emit on cron or queue file add/remove so newly-added handlers are - // routable without a full restart. + // Re-emit on any cron/queue file mutation so add/remove and edits to + // the schedule string or queue name (which are baked into the + // generated `__jobs`/`__queues` table at codegen time) are picked up + // without a full restart. const isInteresting = (file: string) => file.startsWith(join(root, 'crons')) || file.startsWith(join(root, 'queues')); - server.watcher.on('add', (file) => { + const onChange = (file: string) => { if (isInteresting(file)) { writeDispatch(); } - }); - server.watcher.on('unlink', (file) => { - if (isInteresting(file)) { - writeDispatch(); - } - }); + }; + server.watcher.on('add', onChange); + server.watcher.on('change', onChange); + server.watcher.on('unlink', onChange); }, }; } From 63c8c9bc24492dd6e184268c11e5516b981e00b1 Mon Sep 17 00:00:00 2001 From: Alexander Lichter Date: Mon, 4 May 2026 23:31:31 +0200 Subject: [PATCH 6/7] fix(dev): harden Class A trigger dispatch and watcher - Token: atomic create with `openSync(wx)` + EEXIST re-read so parent and child Vite invocations converge on the same UUID instead of racing distinct ones. - Token: preserved across `void deploy` so saved curl scripts keep working between deploys. - Watcher: invalidate the dispatch module in every Vite environment after rewrite so the worker's dynamic import sees the new file (the dispatch path lives under the watch-ignored `.void/` tree). - Watcher: `normalizePath` both sides of the cron/queue prefix check so chokidar's POSIX paths match on Windows. - Dispatch: drop the production-only queue-name suffix match in the dev path; exact match only. - Dispatch: thrown queue handlers return `{ok:false}` with no partial decisions, mirroring CF's batch-retry semantics. - Inference: scan `crons/` and `queues/` so a Class A user whose only `void/kv` import lives in a cron file gets KV inferred. - Build: skip eager dev-token and dispatch writes for `vite build` /`vite preview` so CI checkouts stay free of generated dev state. - Comment: rewrite the Nitro middleware note to match the deferred Analog status documented in `index.ts`. --- packages/void/src/cli/wrapper.ts | 22 ++++- packages/void/src/index.ts | 96 ++++++++++++++++--- packages/void/src/plugin-dev-triggers-hint.ts | 9 ++ .../void/src/plugin-framework-triggers.ts | 59 +++++++++--- packages/void/src/plugin-inference.ts | 10 +- 5 files changed, 164 insertions(+), 32 deletions(-) diff --git a/packages/void/src/cli/wrapper.ts b/packages/void/src/cli/wrapper.ts index b6434c607..7e2a76450 100644 --- a/packages/void/src/cli/wrapper.ts +++ b/packages/void/src/cli/wrapper.ts @@ -2,6 +2,7 @@ import { existsSync, mkdirSync, writeFileSync, + readFileSync, rmSync, renameSync, copyFileSync, @@ -174,10 +175,27 @@ export async function bundleEntry(root: string, entry: string): Promise { + try { + const existing = readFileSync(tokenPath, 'utf-8').trim(); + return existing.length > 0 ? existing : undefined; + } catch { + return undefined; } + }; + + const existing = readExisting(); + if (existing) { + return existing; } - const fresh = crypto.randomUUID(); + + // Atomic create — `wx` fails with EEXIST if the file appeared between the + // read above and the write below (parent + child Vite both racing). On + // EEXIST we re-read the winner's token and use that, so both processes + // converge on the same UUID. mkdirSync(join(root, '.void'), { recursive: true }); - writeFileSync(tokenPath, fresh); - return fresh; + const fresh = crypto.randomUUID(); + try { + const fd = openSync(tokenPath, 'wx'); + try { + writeSync(fd, fresh); + } finally { + closeSync(fd); + } + return fresh; + } catch (err) { + if ((err as NodeJS.ErrnoException).code !== 'EEXIST') { + throw err; + } + const winner = readExisting(); + if (winner) { + return winner; + } + // EEXIST but file is empty — extreme edge case (interrupted writer). + // Fall through and accept the fresh UUID; subsequent reads will win. + return fresh; + } } /** @@ -92,7 +145,14 @@ function getFrameworkEntry(framework: Framework, root: string, devTriggerToken: // import it on the very first request — the plugin's `configResolved` hook // also rewrites it, but we can't rely on that having run before the first // request hits the worker. - writeFrameworkTriggersDispatch(root, devTriggerToken); + // + // Skip in `vite build`/`vite preview`: the dispatch import is wrapped in + // `if (import.meta.env.DEV)` and DCE'd out of the prod bundle, so the + // file is unreferenced. Avoiding the write keeps CI checkouts free of + // generated dev state. + if (!isViteBuildOrPreview()) { + writeFrameworkTriggersDispatch(root, devTriggerToken); + } return generateClassATriggerWrapper(root, framework, getOriginalFrameworkEntry(framework, root)); } @@ -406,7 +466,13 @@ export function voidPlugin(options?: { }): Array { // Resolve root relative to CWD — this runs at config time const root = process.cwd(); - const devTriggerToken = getOrCreateDevTriggerToken(root); + // Token only matters in serve — the dispatch module that uses it is + // DCE'd from production worker bundles. In build/preview we still need + // *some* string (the wrapper embeds it for completeness), but we skip + // persisting it so build-only CI workflows don't materialize dev state. + const devTriggerToken = isViteBuildOrPreview() + ? crypto.randomUUID() + : getOrCreateDevTriggerToken(root); const config = readConfig(root); const dialect = getDatabaseDialect(config); const detected = detectFramework(root); diff --git a/packages/void/src/plugin-dev-triggers-hint.ts b/packages/void/src/plugin-dev-triggers-hint.ts index ed5c3bd94..2638139c5 100644 --- a/packages/void/src/plugin-dev-triggers-hint.ts +++ b/packages/void/src/plugin-dev-triggers-hint.ts @@ -53,6 +53,15 @@ export function devTriggersHintPlugin( console.log(); voidLog(`Detected ${summary.join(' and ')}. Trigger locally:`); + // `__VOID_PROXY_TOKEN` is the platform's prod handshake header, mirrored + // locally via `.dev.vars` (which @cloudflare/vite-plugin populates into + // worker bindings). Other env sources are intentionally NOT considered: + // `.env`/process.env entries are stripped by `stripInternalEnvKeys` on + // the Void path, and wrangler `[vars]` go through the CF plugin which + // also surfaces them via the worker env — but that's a deploy-config + // path, not a dev-trigger ergonomics one. `.dev.vars` is the single + // place a developer is expected to define this token, so it's the + // single source we consult here to keep hint and dispatcher in sync. const configuredProxyToken = parseDotenvFile(join(root, '.dev.vars'), { expand: false, }).__VOID_PROXY_TOKEN; diff --git a/packages/void/src/plugin-framework-triggers.ts b/packages/void/src/plugin-framework-triggers.ts index 968d6aa7a..bfd9b4e38 100644 --- a/packages/void/src/plugin-framework-triggers.ts +++ b/packages/void/src/plugin-framework-triggers.ts @@ -1,6 +1,6 @@ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; -import type { Plugin } from 'vite'; +import { normalizePath, type Plugin } from 'vite'; import { scanJobsSync, type JobDefinition } from './crons/scan.ts'; import { voidWarn } from './log.ts'; import { scanQueuesSync, type QueueDefinition } from './queues/scan.ts'; @@ -38,6 +38,7 @@ export function writeFrameworkTriggersDispatch(root: string, devTriggerToken: st */ export function frameworkTriggersPlugin(root: string, options: FrameworkTriggersOptions): Plugin { const writeDispatch = () => writeFrameworkTriggersDispatch(root, options.devTriggerToken); + const dispatchPath = frameworkTriggersDispatchPath(root); return { name: 'void:framework-triggers', @@ -50,11 +51,33 @@ export function frameworkTriggersPlugin(root: string, options: FrameworkTriggers // the schedule string or queue name (which are baked into the // generated `__jobs`/`__queues` table at codegen time) are picked up // without a full restart. - const isInteresting = (file: string) => - file.startsWith(join(root, 'crons')) || file.startsWith(join(root, 'queues')); + // + // chokidar emits POSIX-style paths on every platform, so normalize the + // root prefixes to match — otherwise this comparison silently no-ops + // on Windows where `join(root, 'crons')` uses backslashes. + const cronsPrefix = normalizePath(join(root, 'crons')); + const queuesPrefix = normalizePath(join(root, 'queues')); + const isInteresting = (file: string) => { + const normalized = normalizePath(file); + return normalized.startsWith(cronsPrefix) || normalized.startsWith(queuesPrefix); + }; const onChange = (file: string) => { - if (isInteresting(file)) { - writeDispatch(); + if (!isInteresting(file)) { + return; + } + writeDispatch(); + // The dispatch file lives under `.void/`, which `envPlugin.config` + // adds to `server.watch.ignored` (to stop miniflare's SQLite writes + // from triggering infinite HMR). Without explicit invalidation the + // worker environment would keep returning the cached dispatch + // module on the next dynamic import, so a renamed/added cron would + // never route until the dev server restarts. Walk every Vite + // environment and drop the cached dispatch module. + for (const env of Object.values(server.environments)) { + const mod = env.moduleGraph.getModuleById(dispatchPath); + if (mod) { + env.moduleGraph.invalidateModule(mod); + } } }; server.watcher.on('add', onChange); @@ -151,9 +174,11 @@ async function __dispatchScheduled(request, env, ctx) { async function __dispatchQueue(request, env) { const payload = await request.json(); - const q = __queues.find( - (entry) => entry.name === payload.queue || payload.queue.endsWith("-" + entry.name), - ); + // Exact match only — payload.queue is the user-typed queue name from the + // dev curl. The prod platform-side dispatch suffix-matches against + // project-prefixed queue names, but that isn't relevant here and would + // cause false positives between e.g. "events" and "user-events". + const q = __queues.find((entry) => entry.name === payload.queue); if (!q) { return __json({ error: \`No queue handler matches "\${payload.queue}"\` }, 404); } @@ -169,15 +194,17 @@ async function __dispatchQueue(request, env) { for (const m of messages) m.retry(opts); }, }; - let ok = true; try { await q.handler(batch, env); } catch (err) { - ok = false; console.error("[void] queue handler threw:", err); + // CF queues retry the entire batch when a consumer throws, regardless + // of any ack/retry calls made before the throw — drop partial decisions + // so dev-mode response semantics match prod. + return __json({ ok: false }); } return __json({ - ok, + ok: true, ...(decisions.size > 0 ? { decisions: Object.fromEntries(decisions) } : {}), }); } @@ -207,9 +234,13 @@ export async function handleDevTrigger(request, env, ctx) { const NITRO_MIDDLEWARE_FILENAME = '__void-dev-trigger.ts'; function nitroMiddlewareSource(dispatchPath: string): string { - // Plain async default export, no h3 imports. Works in both Nuxt's real - // Nitro pipeline and @analogjs/vite-plugin-nitro's dev loader, which - // evaluates middleware via Vite SSR without applying Nitro's auto-imports. + // Plain async default export, no h3 imports — kept dependency-free so the + // same source compiles under Nuxt's real Nitro pipeline. Analog's + // `@analogjs/vite-plugin-nitro` evaluates middleware via Vite SSR before + // its `nitro-cloudflare-dev` plugin populates `event.context.cloudflare`, + // so this file is shaped for Nuxt only — Analog wiring is deferred until + // upstream applies Nitro's runtime plugins to dev middleware (see the + // `index.ts` comment at the Class B/C branch). return `// @ts-nocheck — Auto-generated by Void in dev. Do NOT edit. Removed when the dev server stops. import { handleDevTrigger } from ${JSON.stringify(dispatchPath)}; diff --git a/packages/void/src/plugin-inference.ts b/packages/void/src/plugin-inference.ts index 232259534..3ee85df15 100644 --- a/packages/void/src/plugin-inference.ts +++ b/packages/void/src/plugin-inference.ts @@ -18,7 +18,15 @@ export interface DetectedFramework { export type Framework = 'tanstack-start' | 'react-router' | 'vinext-app' | 'vinext-pages'; /** Directories to scan for binding inference in framework mode. */ -export const FRAMEWORK_SCAN_DIRS = ['src', 'app', 'pages', 'routes', 'server'] as const; +export const FRAMEWORK_SCAN_DIRS = [ + 'src', + 'app', + 'pages', + 'routes', + 'server', + 'crons', + 'queues', +] as const; /** * Map from npm package name to framework identifier. From 08a02fad4a57ba0ea2381e52d0c76bf083706d0d Mon Sep 17 00:00:00 2001 From: Alexander Lichter Date: Tue, 5 May 2026 08:33:59 +0200 Subject: [PATCH 7/7] fix(dev): emit dispatch-free wrapper for vite build MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Earlier review claimed the dev-trigger dispatch was DCE'd from prod worker bundles via `if (import.meta.env.DEV)` around the dynamic import. CI proves otherwise: rolldown emits chunks for dynamic imports during chunk splitting (before constant folding eliminates the dead branch), so the dispatch file's user cron/queue handlers and the dev-trigger UUID were shipping in production worker bundles. Generate the wrapper in two shapes — a serve variant with the unconditional dispatch import, and a build variant that simply delegates to the framework's original fetch. Skip writing the dispatch file in build mode entirely (the wrapper doesn't reference it). Verified locally: a clean tanstack-start build now leaves `dist/` free of `handleDevTrigger`, `dev-triggers`, the heartbeat cron body, and the dev-trigger UUID, and the integration test that failed in CI now passes. --- packages/void/src/index.ts | 73 ++++++++++++++++++++++++-------------- 1 file changed, 47 insertions(+), 26 deletions(-) diff --git a/packages/void/src/index.ts b/packages/void/src/index.ts index d5e043471..b15b82e8c 100644 --- a/packages/void/src/index.ts +++ b/packages/void/src/index.ts @@ -142,19 +142,27 @@ function getOrCreateDevTriggerToken(root: string): string { * `cli/wrapper.ts` instead. */ function getFrameworkEntry(framework: Framework, root: string, devTriggerToken: string): string { - // Eagerly write the dispatch file so the dev fetch handler can dynamically - // import it on the very first request — the plugin's `configResolved` hook - // also rewrites it, but we can't rely on that having run before the first - // request hits the worker. + const isBuild = isViteBuildOrPreview(); + // In dev, eagerly write the dispatch file so the wrapper's dynamic + // import resolves on the very first request (the plugin's + // `configResolved` hook also rewrites it, but we can't rely on that + // having run before the first request hits the worker). // - // Skip in `vite build`/`vite preview`: the dispatch import is wrapped in - // `if (import.meta.env.DEV)` and DCE'd out of the prod bundle, so the - // file is unreferenced. Avoiding the write keeps CI checkouts free of - // generated dev state. - if (!isViteBuildOrPreview()) { + // In `vite build`, we instead emit a dispatch-free wrapper, so the + // dispatch file is unreferenced and we don't write it. Rolldown + // would otherwise emit it as a separate chunk in the prod bundle — + // an `if (import.meta.env.DEV)` guard around `await import()` is + // *not* enough to suppress chunk emission, because chunk splitting + // runs before constant folding eliminates the dead branch. + if (!isBuild) { writeFrameworkTriggersDispatch(root, devTriggerToken); } - return generateClassATriggerWrapper(root, framework, getOriginalFrameworkEntry(framework, root)); + return generateClassATriggerWrapper( + root, + framework, + getOriginalFrameworkEntry(framework, root), + isBuild, + ); } /** The framework's own server entry, before our trigger wrapper. */ @@ -177,39 +185,52 @@ function getOriginalFrameworkEntry(framework: Framework, root: string): string { * first, dispatches `/__void/{scheduled,queue}` if it matches, and otherwise * delegates to the framework's original entry. * - * The dispatch module is loaded via dynamic `import()` inside the - * `import.meta.env.DEV` branch. Vite replaces `DEV` with `false` in build - * mode, the entire branch becomes dead code, and rolldown drops the dynamic - * import — so the dispatch file (and its transitive user-cron imports) never - * lands in production worker bundles produced by `vite build`. + * We emit two shapes of the wrapper depending on the Vite command: + * + * - Serve: dispatch is dynamically imported and gets a chance to handle + * `/__void/{scheduled,queue}` before falling through to the framework. + * - Build: dispatch is omitted entirely. The wrapper just delegates fetch. + * + * We can't simply gate the dynamic import on `import.meta.env.DEV` and + * trust DCE: rolldown emits chunks for dynamic imports during chunk + * splitting, *before* constant folding removes the dead branch, so the + * dispatch file (and its transitive user-cron/queue imports + dev token) + * would still ship in the production bundle. */ function generateClassATriggerWrapper( root: string, framework: Framework, original: string, + isBuild: boolean, ): string { const outDir = join(root, '.void'); mkdirSync(outDir, { recursive: true }); const wrapperPath = join(outDir, `${framework}-trigger-wrapper.ts`); - const dispatchPath = frameworkTriggersDispatchPath(root); - writeFileSync( - wrapperPath, - `// @ts-nocheck — Auto-generated by Void. Do NOT edit. + const body = isBuild + ? `// @ts-nocheck — Auto-generated by Void for vite build. Do NOT edit. import original from ${JSON.stringify(original)}; export default { ...original, async fetch(request, env, ctx) { - if (import.meta.env.DEV) { - const { handleDevTrigger } = await import(${JSON.stringify(dispatchPath)}); - const response = await handleDevTrigger(request, env, ctx); - if (response) return response; - } return original.fetch(request, env, ctx); }, }; -`, - ); +` + : `// @ts-nocheck — Auto-generated by Void in dev. Do NOT edit. +import original from ${JSON.stringify(original)}; + +export default { + ...original, + async fetch(request, env, ctx) { + const { handleDevTrigger } = await import(${JSON.stringify(frameworkTriggersDispatchPath(root))}); + const response = await handleDevTrigger(request, env, ctx); + if (response) return response; + return original.fetch(request, env, ctx); + }, +}; +`; + writeFileSync(wrapperPath, body); return wrapperPath; }