Skip to content
Merged
2 changes: 1 addition & 1 deletion docs/guide/jobs.md
Original file line number Diff line number Diff line change
Expand Up @@ -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: <your-token>` 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

Expand Down
2 changes: 1 addition & 1 deletion docs/guide/queues.md
Original file line number Diff line number Diff line change
Expand Up @@ -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: <your-token>` 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.
22 changes: 20 additions & 2 deletions packages/void/src/cli/wrapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
existsSync,
mkdirSync,
writeFileSync,
readFileSync,
rmSync,
renameSync,
copyFileSync,
Expand Down Expand Up @@ -174,10 +175,27 @@ export async function bundleEntry(root: string, entry: string): Promise<WrapperR
}

/**
* Clean up generated wrapper/bundle files.
* Clean up generated wrapper/bundle files. Preserves `dev-trigger-token`
* across the wipe so that subsequent `void dev` sessions keep using the
* same UUID — invalidating it on every deploy would force users to update
* any saved curl scripts that exercise `/__void/{scheduled,queue}`.
*/
export function cleanupWrapper(root: string): void {
rmSync(join(root, '.void'), { recursive: true, force: true });
const voidDir = join(root, '.void');
const tokenPath = join(voidDir, 'dev-trigger-token');
let preservedToken: string | undefined;
if (existsSync(tokenPath)) {
try {
preservedToken = readFileSync(tokenPath, 'utf-8');
} catch {
// Best-effort — fall through and let the next dev session regenerate.
}
}
rmSync(voidDir, { recursive: true, force: true });
if (preservedToken !== undefined) {
mkdirSync(voidDir, { recursive: true });
writeFileSync(tokenPath, preservedToken);
}
}

// ─── Source Generators ─────────────────────────────────────────────
Expand Down
190 changes: 185 additions & 5 deletions packages/void/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import {
closeSync,
existsSync,
mkdirSync,
openSync,
readFileSync,
writeFileSync,
writeSync,
} from 'node:fs';
import { fileURLToPath } from 'node:url';
import { cloudflare, type PluginConfig, type WorkerConfig } from '@cloudflare/vite-plugin';
import { join } from 'pathe';
Expand Down Expand Up @@ -28,6 +36,7 @@ import {
frameworkTriggersDispatchPath,
frameworkTriggersPlugin,
nitroDevTriggerInjectPlugin,
writeFrameworkTriggersDispatch,
} from './plugin-framework-triggers.ts';
import {
inferProjectBindings,
Expand All @@ -47,6 +56,81 @@ import { filterLoadedEnv, resolveRemoteMode, stripInternalEnvKeys } from './shar
import { DEFAULT_PROXY_URL, STAGING_PROXY_URL } from './shared/proxy.ts';
import { validateSsrEntry } from './ssr/entry.ts';

/**
* Persist the dev-trigger token at `<root>/.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"`.
*
Expand Down Expand Up @@ -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';
Expand All @@ -95,6 +213,61 @@ function getFrameworkEntry(framework: Framework, root: string): string {
}
}

/**
* Generate `<root>/.void/<framework>-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');
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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<string> | undefined) ?? [];
if (!existingFlags.includes('nodejs_compat')) {
workerConfig.compatibility_flags = [...existingFlags, 'nodejs_compat'];
Expand Down Expand Up @@ -1058,6 +1237,7 @@ export function voidPlugin(options?: {
}),
migrationPlugin(root, getDatabaseDialect(config)),
...(vinextCompat ? [vinextCompat] : []),
frameworkTriggersPlugin(root, { devTriggerToken }),
devTriggersHintPlugin(root, { framework: true, devTriggerToken }),
...cloudflare({
...inspectorPortOption,
Expand Down
13 changes: 11 additions & 2 deletions packages/void/src/plugin-dev-triggers-hint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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;
Expand Down
Loading