diff --git a/docs/guide/jobs.md b/docs/guide/jobs.md index 7a69f941c..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, Analog, 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.). +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 59ec77702..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, Analog, 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. +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/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/.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 file persists across dev sessions by design — it lives under `.void/` + * (gitignored), and `cleanupWrapper` in `void deploy` explicitly preserves + * it across its own wipe so saved curl scripts keep working between deploys. + * 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. + */ +/** + * Best-effort detection of `vite build` (and `vite preview`) so we can skip + * dev-only side effects — writing the dev-trigger token and the dispatch + * file — when no dev server will run. Vite's CLI passes the subcommand as + * `process.argv[2]`; programmatic API users (and `vite` with no subcommand) + * default to `dev`, which we detect as the absence of a build-shaped first + * positional. This is intentionally permissive: when in doubt, we behave as + * if we're in dev so first-request correctness is preserved. + */ +function isViteBuildOrPreview(): boolean { + const subcommand = process.argv[2]; + return subcommand === 'build' || subcommand === 'preview'; +} + +function getOrCreateDevTriggerToken(root: string): string { + const tokenPath = join(root, '.void', 'dev-trigger-token'); + const readExisting = (): string | undefined => { + try { + const existing = readFileSync(tokenPath, 'utf-8').trim(); + return existing.length > 0 ? existing : undefined; + } catch { + return undefined; + } + }; + + const existing = readExisting(); + if (existing) { + return existing; + } + + // 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 }); + 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; + } +} + /** * Warn when the project's `package.json` does not declare `"type": "module"`. * @@ -81,8 +165,42 @@ function warnIfPackageJsonIsNotEsm(root: string): void { ); } -/** Resolve the server entry module for a Class A framework. */ -function getFrameworkEntry(framework: Framework, root: string): string { +/** + * 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` 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 { + 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). + // + // 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), + isBuild, + ); +} + +/** 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'; @@ -95,6 +213,61 @@ 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. + * + * 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 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) { + 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; +} + /** Generate a worker entry for vinext Pages Router projects. */ function generateVinextPagesEntry(root: string): string { const outDir = join(root, '.void'); @@ -350,7 +523,13 @@ export function voidPlugin(options?: { // Resolve root relative to CWD — this runs at config time const root = process.cwd(); warnIfPackageJsonIsNotEsm(root); - const devTriggerToken = crypto.randomUUID(); + // 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); @@ -998,7 +1177,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']; @@ -1058,6 +1237,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-dev-triggers-hint.ts b/packages/void/src/plugin-dev-triggers-hint.ts index c16deee25..40241c24d 100644 --- a/packages/void/src/plugin-dev-triggers-hint.ts +++ b/packages/void/src/plugin-dev-triggers-hint.ts @@ -8,8 +8,8 @@ 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, Analog, Astro, TanStack Start, React + * Router, vinext) expose `/__void/scheduled` and `/__void/queue`. */ export function devTriggersHintPlugin( root: string, @@ -52,6 +52,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 e3bf91c19..2063983ed 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 'pathe'; -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'; @@ -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,8 @@ 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); + const dispatchPath = frameworkTriggersDispatchPath(root); return { name: 'void:framework-triggers', @@ -38,20 +47,42 @@ 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. - const isInteresting = (file: string) => - file.startsWith(join(root, 'crons')) || file.startsWith(join(root, 'queues')); - server.watcher.on('add', (file) => { - if (isInteresting(file)) { - writeDispatch(); + // 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. + // + // 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)) { + return; } - }); - server.watcher.on('unlink', (file) => { - if (isInteresting(file)) { - writeDispatch(); + 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); + server.watcher.on('change', onChange); + server.watcher.on('unlink', onChange); }, }; } @@ -143,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); } @@ -161,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) } : {}), }); } @@ -199,9 +234,12 @@ 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 uses a + // different injection path (`analogDevTriggerInjectPlugin` below) because + // `@analogjs/vite-plugin-nitro` evaluates middleware via Vite SSR before + // its `nitro-cloudflare-dev` plugin populates `event.context.cloudflare`, + // so this middleware shape would never see CF bindings there. 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 0808fb3ab..b28010acb 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. 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); +}