Skip to content

Commit c4d91c0

Browse files
feat(dev): wire /__void/{scheduled,queue} into Class A framework dev (#179)
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
1 parent 70bdb9d commit c4d91c0

11 files changed

Lines changed: 342 additions & 41 deletions

File tree

‎docs/guide/jobs.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ curl -X POST http://localhost:5173/__void/scheduled \
8484

8585
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.
8686

87-
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.).
87+
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.).
8888

8989
## Deployment behavior
9090

‎docs/guide/queues.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -137,4 +137,4 @@ curl -X POST http://localhost:5173/__void/queue \
137137

138138
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.
139139

140-
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.
140+
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.

‎packages/void/src/cli/wrapper.ts‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import {
22
existsSync,
33
mkdirSync,
44
writeFileSync,
5+
readFileSync,
56
rmSync,
67
renameSync,
78
copyFileSync,
@@ -178,10 +179,27 @@ export async function bundleEntry(root: string, entry: string): Promise<WrapperR
178179
}
179180

180181
/**
181-
* Clean up generated wrapper/bundle files.
182+
* Clean up generated wrapper/bundle files. Preserves `dev-trigger-token`
183+
* across the wipe so that subsequent `void dev` sessions keep using the
184+
* same UUID — invalidating it on every deploy would force users to update
185+
* any saved curl scripts that exercise `/__void/{scheduled,queue}`.
182186
*/
183187
export function cleanupWrapper(root: string): void {
184-
rmSync(join(root, '.void'), { recursive: true, force: true });
188+
const voidDir = join(root, '.void');
189+
const tokenPath = join(voidDir, 'dev-trigger-token');
190+
let preservedToken: string | undefined;
191+
if (existsSync(tokenPath)) {
192+
try {
193+
preservedToken = readFileSync(tokenPath, 'utf-8');
194+
} catch {
195+
// Best-effort — fall through and let the next dev session regenerate.
196+
}
197+
}
198+
rmSync(voidDir, { recursive: true, force: true });
199+
if (preservedToken !== undefined) {
200+
mkdirSync(voidDir, { recursive: true });
201+
writeFileSync(tokenPath, preservedToken);
202+
}
185203
}
186204

187205
// ─── Source Generators ─────────────────────────────────────────────

‎packages/void/src/index.ts‎

Lines changed: 185 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,12 @@
1-
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
1+
import {
2+
closeSync,
3+
existsSync,
4+
mkdirSync,
5+
openSync,
6+
readFileSync,
7+
writeFileSync,
8+
writeSync,
9+
} from 'node:fs';
210
import { fileURLToPath } from 'node:url';
311
import { cloudflare, type PluginConfig, type WorkerConfig } from '@cloudflare/vite-plugin';
412
import { join } from 'pathe';
@@ -28,6 +36,7 @@ import {
2836
frameworkTriggersDispatchPath,
2937
frameworkTriggersPlugin,
3038
nitroDevTriggerInjectPlugin,
39+
writeFrameworkTriggersDispatch,
3140
} from './plugin-framework-triggers.ts';
3241
import {
3342
inferProjectBindings,
@@ -47,6 +56,81 @@ import { filterLoadedEnv, resolveRemoteMode, stripInternalEnvKeys } from './shar
4756
import { DEFAULT_PROXY_URL, STAGING_PROXY_URL } from './shared/proxy.ts';
4857
import { validateSsrEntry } from './ssr/entry.ts';
4958

59+
/**
60+
* Persist the dev-trigger token at `<root>/.void/dev-trigger-token` so
61+
* every voidPlugin() invocation against the same project reads the same
62+
* value. This matters because `@cloudflare/vite-plugin` spawns a
63+
* worker-environment child Vite that re-imports vite.config.ts and calls
64+
* voidPlugin() again — without persistence the parent and child would
65+
* generate different UUIDs, the dispatch file would embed one and the
66+
* hint plugin would print the other, and curls would land on
67+
* `unauthorized`.
68+
*
69+
* The file persists across dev sessions by design — it lives under `.void/`
70+
* (gitignored), and `cleanupWrapper` in `void deploy` explicitly preserves
71+
* it across its own wipe so saved curl scripts keep working between deploys.
72+
* The token is local to the project and only honored by a worker bound to
73+
* localhost; treat it like the rest of `.void/` — disposable scratch state,
74+
* safe to remove manually if desired.
75+
*/
76+
/**
77+
* Best-effort detection of `vite build` (and `vite preview`) so we can skip
78+
* dev-only side effects — writing the dev-trigger token and the dispatch
79+
* file — when no dev server will run. Vite's CLI passes the subcommand as
80+
* `process.argv[2]`; programmatic API users (and `vite` with no subcommand)
81+
* default to `dev`, which we detect as the absence of a build-shaped first
82+
* positional. This is intentionally permissive: when in doubt, we behave as
83+
* if we're in dev so first-request correctness is preserved.
84+
*/
85+
function isViteBuildOrPreview(): boolean {
86+
const subcommand = process.argv[2];
87+
return subcommand === 'build' || subcommand === 'preview';
88+
}
89+
90+
function getOrCreateDevTriggerToken(root: string): string {
91+
const tokenPath = join(root, '.void', 'dev-trigger-token');
92+
const readExisting = (): string | undefined => {
93+
try {
94+
const existing = readFileSync(tokenPath, 'utf-8').trim();
95+
return existing.length > 0 ? existing : undefined;
96+
} catch {
97+
return undefined;
98+
}
99+
};
100+
101+
const existing = readExisting();
102+
if (existing) {
103+
return existing;
104+
}
105+
106+
// Atomic create — `wx` fails with EEXIST if the file appeared between the
107+
// read above and the write below (parent + child Vite both racing). On
108+
// EEXIST we re-read the winner's token and use that, so both processes
109+
// converge on the same UUID.
110+
mkdirSync(join(root, '.void'), { recursive: true });
111+
const fresh = crypto.randomUUID();
112+
try {
113+
const fd = openSync(tokenPath, 'wx');
114+
try {
115+
writeSync(fd, fresh);
116+
} finally {
117+
closeSync(fd);
118+
}
119+
return fresh;
120+
} catch (err) {
121+
if ((err as NodeJS.ErrnoException).code !== 'EEXIST') {
122+
throw err;
123+
}
124+
const winner = readExisting();
125+
if (winner) {
126+
return winner;
127+
}
128+
// EEXIST but file is empty — extreme edge case (interrupted writer).
129+
// Fall through and accept the fresh UUID; subsequent reads will win.
130+
return fresh;
131+
}
132+
}
133+
50134
/**
51135
* Warn when the project's `package.json` does not declare `"type": "module"`.
52136
*
@@ -81,8 +165,42 @@ function warnIfPackageJsonIsNotEsm(root: string): void {
81165
);
82166
}
83167

84-
/** Resolve the server entry module for a Class A framework. */
85-
function getFrameworkEntry(framework: Framework, root: string): string {
168+
/**
169+
* Resolve the server entry module for a Class A framework. We always wrap
170+
* the framework's own entry with a tiny shim that intercepts
171+
* `/__void/{scheduled,queue}` in dev so cron and queue handlers run with
172+
* the worker's full CF bindings. The interception block is gated on
173+
* `import.meta.env.DEV` and the dispatch module is loaded via dynamic
174+
* `import()` so the entire dev path (including user cron imports) is
175+
* dead-code-eliminated in `vite build`. Production deploys go through
176+
* `cli/wrapper.ts` instead.
177+
*/
178+
function getFrameworkEntry(framework: Framework, root: string, devTriggerToken: string): string {
179+
const isBuild = isViteBuildOrPreview();
180+
// In dev, eagerly write the dispatch file so the wrapper's dynamic
181+
// import resolves on the very first request (the plugin's
182+
// `configResolved` hook also rewrites it, but we can't rely on that
183+
// having run before the first request hits the worker).
184+
//
185+
// In `vite build`, we instead emit a dispatch-free wrapper, so the
186+
// dispatch file is unreferenced and we don't write it. Rolldown
187+
// would otherwise emit it as a separate chunk in the prod bundle —
188+
// an `if (import.meta.env.DEV)` guard around `await import()` is
189+
// *not* enough to suppress chunk emission, because chunk splitting
190+
// runs before constant folding eliminates the dead branch.
191+
if (!isBuild) {
192+
writeFrameworkTriggersDispatch(root, devTriggerToken);
193+
}
194+
return generateClassATriggerWrapper(
195+
root,
196+
framework,
197+
getOriginalFrameworkEntry(framework, root),
198+
isBuild,
199+
);
200+
}
201+
202+
/** The framework's own server entry, before our trigger wrapper. */
203+
function getOriginalFrameworkEntry(framework: Framework, root: string): string {
86204
switch (framework) {
87205
case 'tanstack-start':
88206
return '@tanstack/react-start/server-entry';
@@ -95,6 +213,61 @@ function getFrameworkEntry(framework: Framework, root: string): string {
95213
}
96214
}
97215

216+
/**
217+
* Generate `<root>/.void/<framework>-trigger-wrapper.ts`. This file becomes
218+
* `workerConfig.main` so the dev miniflare/workerd evaluates *our* fetch
219+
* first, dispatches `/__void/{scheduled,queue}` if it matches, and otherwise
220+
* delegates to the framework's original entry.
221+
*
222+
* We emit two shapes of the wrapper depending on the Vite command:
223+
*
224+
* - Serve: dispatch is dynamically imported and gets a chance to handle
225+
* `/__void/{scheduled,queue}` before falling through to the framework.
226+
* - Build: dispatch is omitted entirely. The wrapper just delegates fetch.
227+
*
228+
* We can't simply gate the dynamic import on `import.meta.env.DEV` and
229+
* trust DCE: rolldown emits chunks for dynamic imports during chunk
230+
* splitting, *before* constant folding removes the dead branch, so the
231+
* dispatch file (and its transitive user-cron/queue imports + dev token)
232+
* would still ship in the production bundle.
233+
*/
234+
function generateClassATriggerWrapper(
235+
root: string,
236+
framework: Framework,
237+
original: string,
238+
isBuild: boolean,
239+
): string {
240+
const outDir = join(root, '.void');
241+
mkdirSync(outDir, { recursive: true });
242+
const wrapperPath = join(outDir, `${framework}-trigger-wrapper.ts`);
243+
const body = isBuild
244+
? `// @ts-nocheck — Auto-generated by Void for vite build. Do NOT edit.
245+
import original from ${JSON.stringify(original)};
246+
247+
export default {
248+
...original,
249+
async fetch(request, env, ctx) {
250+
return original.fetch(request, env, ctx);
251+
},
252+
};
253+
`
254+
: `// @ts-nocheck — Auto-generated by Void in dev. Do NOT edit.
255+
import original from ${JSON.stringify(original)};
256+
257+
export default {
258+
...original,
259+
async fetch(request, env, ctx) {
260+
const { handleDevTrigger } = await import(${JSON.stringify(frameworkTriggersDispatchPath(root))});
261+
const response = await handleDevTrigger(request, env, ctx);
262+
if (response) return response;
263+
return original.fetch(request, env, ctx);
264+
},
265+
};
266+
`;
267+
writeFileSync(wrapperPath, body);
268+
return wrapperPath;
269+
}
270+
98271
/** Generate a worker entry for vinext Pages Router projects. */
99272
function generateVinextPagesEntry(root: string): string {
100273
const outDir = join(root, '.void');
@@ -350,7 +523,13 @@ export function voidPlugin(options?: {
350523
// Resolve root relative to CWD — this runs at config time
351524
const root = process.cwd();
352525
warnIfPackageJsonIsNotEsm(root);
353-
const devTriggerToken = crypto.randomUUID();
526+
// Token only matters in serve — the dispatch module that uses it is
527+
// DCE'd from production worker bundles. In build/preview we still need
528+
// *some* string (the wrapper embeds it for completeness), but we skip
529+
// persisting it so build-only CI workflows don't materialize dev state.
530+
const devTriggerToken = isViteBuildOrPreview()
531+
? crypto.randomUUID()
532+
: getOrCreateDevTriggerToken(root);
354533
const config = readConfig(root);
355534
const dialect = getDatabaseDialect(config);
356535
const detected = detectFramework(root);
@@ -998,7 +1177,7 @@ export function voidPlugin(options?: {
9981177
};
9991178

10001179
if (framework) {
1001-
workerConfig.main = getFrameworkEntry(framework, root);
1180+
workerConfig.main = getFrameworkEntry(framework, root, devTriggerToken);
10021181
const existingFlags = (workerConfig.compatibility_flags as Array<string> | undefined) ?? [];
10031182
if (!existingFlags.includes('nodejs_compat')) {
10041183
workerConfig.compatibility_flags = [...existingFlags, 'nodejs_compat'];
@@ -1058,6 +1237,7 @@ export function voidPlugin(options?: {
10581237
}),
10591238
migrationPlugin(root, getDatabaseDialect(config)),
10601239
...(vinextCompat ? [vinextCompat] : []),
1240+
frameworkTriggersPlugin(root, { devTriggerToken }),
10611241
devTriggersHintPlugin(root, { framework: true, devTriggerToken }),
10621242
...cloudflare({
10631243
...inspectorPortOption,

‎packages/void/src/plugin-dev-triggers-hint.ts‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ import { parseDotenvFile } from './shared/dotenv.ts';
88
/**
99
* Prints a one-shot hint on dev server start when the project has crons
1010
* or queues, explaining how to trigger them locally. Both default Void mode
11-
* and framework mode (SvelteKit/Nuxt/Analog/Astro) expose
12-
* `/__void/scheduled` and `/__void/queue`.
11+
* and framework mode (SvelteKit, Nuxt, Analog, Astro, TanStack Start, React
12+
* Router, vinext) expose `/__void/scheduled` and `/__void/queue`.
1313
*/
1414
export function devTriggersHintPlugin(
1515
root: string,
@@ -52,6 +52,15 @@ export function devTriggersHintPlugin(
5252

5353
console.log();
5454
voidLog(`Detected ${summary.join(' and ')}. Trigger locally:`);
55+
// `__VOID_PROXY_TOKEN` is the platform's prod handshake header, mirrored
56+
// locally via `.dev.vars` (which @cloudflare/vite-plugin populates into
57+
// worker bindings). Other env sources are intentionally NOT considered:
58+
// `.env`/process.env entries are stripped by `stripInternalEnvKeys` on
59+
// the Void path, and wrangler `[vars]` go through the CF plugin which
60+
// also surfaces them via the worker env — but that's a deploy-config
61+
// path, not a dev-trigger ergonomics one. `.dev.vars` is the single
62+
// place a developer is expected to define this token, so it's the
63+
// single source we consult here to keep hint and dispatcher in sync.
5564
const configuredProxyToken = parseDotenvFile(join(root, '.dev.vars'), {
5665
expand: false,
5766
}).__VOID_PROXY_TOKEN;

0 commit comments

Comments
 (0)