Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/integrations/frameworks/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ With `voidPlugin()` added to the framework's Vite config, frameworks get most of
- **Queue consumers:** typed producers and consumers via the `queues/` directory.
- **Revalidation and prerendering:** configure them with [`routing.revalidate`](../../guide/edge/revalidation.md) and [`routing.prerender`](../../guide/edge/prerendering.md) in `void.config.ts`. Void apps can also set these per page in companion `.server.ts` files.

In vinext dev and preview, `send()` succeeds but doesn't run this app's queue handler. In dev, run the handler with the [manual queue trigger](../../guide/queues.md#local-development), using the dev server's port and the token in `.void/dev-trigger-token`. Preview reads `queues/` and `env.ts` from the source tree, so don't change them between the build and preview.

For framework apps, Void revalidation caches public HTML document responses with both `void deploy` and `void deploy --platform cloudflare`. Client data requests continue to use the framework's own behavior. A response with `Set-Cookie` or `Cache-Control: private`, `no-store`, or `no-cache` is never shared.

Frameworks can also access bindings directly via the framework's own mechanisms (e.g. `env` from `cloudflare:workers` in SvelteKit 3, Analog, and Astro, `platform.env` in SvelteKit 2, `event.context.cloudflare.env` in Nuxt).
Expand Down
2 changes: 2 additions & 0 deletions docs/integrations/frameworks/react-router.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ export async function loader({}: Route.LoaderArgs) {

Use [KV](../../guide/kv.md), [object storage](../../guide/storage.md), and [AI](../../guide/ai.md) from server-side code with the same imports as a Void app. Add [cron jobs](../../guide/jobs.md) in `crons/` and [queue consumers](../../guide/queues.md) in `queues/`.

In dev and preview, `send()` succeeds but doesn't run this app's queue handler. In dev, run the handler with the [manual queue trigger](../../guide/queues.md#local-development), using the dev server's port and the token in `.void/dev-trigger-token`. Preview reads `queues/` and `env.ts` from the source tree, so don't change them between the build and preview.

### Environment Variables

Declare variables in `env.ts` and read them with `import { env } from "void/env"`. See [Environment Variables](../../guide/env-vars.md) for local values, production secrets, and public `VITE_*` values.
Expand Down
2 changes: 2 additions & 0 deletions docs/integrations/frameworks/tanstack-start.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ const getUsers = createServerFn().handler(async () => {

Use [KV](../../guide/kv.md), [object storage](../../guide/storage.md), and [AI](../../guide/ai.md) from server-side code with the same imports as a Void app. Add [cron jobs](../../guide/jobs.md) in `crons/` and [queue consumers](../../guide/queues.md) in `queues/`.

In dev and preview, `send()` succeeds but doesn't run this app's queue handler. In dev, run the handler with the [manual queue trigger](../../guide/queues.md#local-development), using the dev server's port and the token in `.void/dev-trigger-token`. Preview reads `queues/` and `env.ts` from the source tree, so don't change them between the build and preview.

### Environment Variables

Declare variables in `env.ts` and read them with `import { env } from "void/env"`. See [Environment Variables](../../guide/env-vars.md) for local values, production secrets, and public `VITE_*` values.
Expand Down
4 changes: 4 additions & 0 deletions packages/void/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -809,6 +809,10 @@ export function voidPlugin(options?: {
auxiliaryWorkers: options?.auxiliaryWorkers,
viteEnvironment,
config: mergeBindings,
localQueueProducers: () => ({
queues: application.queues,
reserved: envSchemaFacts?.serverKeys ?? [],
}),
}),
implicitDeployGuard,
];
Expand Down
58 changes: 56 additions & 2 deletions packages/void/src/plugin-cloudflare-config.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,59 @@
import { existsSync, readFileSync } from 'node:fs';
import { convertToWranglerConfig } from '@cloudflare/config';
import { bindings, convertToWranglerConfig } from '@cloudflare/config';
import type { CloudflareConfig, PluginConfig } from '@cloudflare/vite-plugin';
import { resolve, dirname, basename, join } from 'pathslash';
import { parse as parseToml } from 'smol-toml';
import { migrateBuiltWranglerConfig } from './cli/cf-config-migrate.ts';
import { readGeneratedWranglerConfigFile } from './cli/generated-wrangler-config.ts';
import { voidWarn } from './log.ts';
import type { QueueDefinition } from './queues/scan.ts';

/** Void keeps its Wrangler-shaped public options independently of the upstream plugin. */
export type WorkerConfig = ReturnType<typeof convertToWranglerConfig>;
export type WorkerConfigFields = Record<string, unknown>;

export type LocalQueueProducers = () => {
queues: ReadonlyArray<Pick<QueueDefinition, 'filePath' | 'name' | 'bindingName'>>;
reserved: ReadonlyArray<string>;
};

export function addLocalQueueProducers(
worker: Pick<CloudflareConfig['worker'], 'env'>,
read: LocalQueueProducers | undefined,
warn: (message: string) => void = voidWarn,
): Array<string> | undefined {
// A framework can open a dev or preview server while building its pages.
if (!read || process.env.CLOUDFLARE_VITE_BUILD === 'true') {
return;
}
const { queues, reserved } = read();
if (queues.length === 0) {
return;
}
const taken = new Set(reserved);
const byBinding = new Map<string, Array<(typeof queues)[number]>>();
for (const queue of queues) {
const group = byBinding.get(queue.bindingName) ?? [];
group.push(queue);
byBinding.set(queue.bindingName, group);
}
let added: Array<string> | undefined;
for (const [binding, group] of byBinding) {
if (group.length > 1) {
const files = group.map(({ filePath }) => filePath).join(', ');
warn(
`Queue files ${files} share binding ${binding}. Void skips inference for this binding. Rename the conflicting files so each queue has a distinct binding.`,
);
continue;
}
if (!taken.has(binding) && !Object.hasOwn(worker.env ?? {}, binding)) {
(worker.env ??= {})[binding] = bindings.queue({ name: group[0].name });
(added ??= []).push(binding);
}
}
return added;
}

type AuxiliaryConfig =
| Partial<WorkerConfig>
| ((
Expand Down Expand Up @@ -133,6 +177,7 @@ export function restoreLocalContainerBindings(worker: CloudflareConfig['worker']
export function nativeAuxiliaryWorkers(
workers: Array<AuxiliaryWorkerConfig> | undefined,
root: string,
readLocalQueueBindings?: () => ReadonlyArray<string> | undefined,
): PluginConfig['auxiliaryWorkers'] {
return workers?.map(({ configPath, config, ...options }) => ({
...options,
Expand All @@ -145,11 +190,20 @@ export function nativeAuxiliaryWorkers(
: readGeneratedWranglerConfigFile(path)
: {}
) as WorkerConfig;
let worker = entryWorkerConfig;
const localBindings = readLocalQueueBindings?.();
if (localBindings && typeof config === 'function') {
const env = { ...entryWorkerConfig.env };
for (const name of localBindings) {
delete env[name];
}
worker = { ...entryWorkerConfig, env };
}
const patch =
typeof config === 'function'
? config(base, {
entryWorkerConfig: convertToWranglerConfig({
worker: entryWorkerConfig,
worker,
containers: [],
}),
})
Expand Down
17 changes: 13 additions & 4 deletions packages/void/src/plugin-cloudflare-preview.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { getRootConfigPath, getWorkerConfigPath } from '@cloudflare/build-output-utils';
import type { CloudflareConfig } from '@cloudflare/vite-plugin';
import { dirname, join } from 'pathslash';
import type { Plugin } from 'vite';
import { addLocalQueueProducers } from './plugin-cloudflare-config.ts';
import type { LocalQueueProducers } from './plugin-cloudflare-config.ts';
import { writeFileAtomic } from './shared/atomic-write.ts';
import { loadLocalEnv } from './shared/env.ts';

/** Give preview local bindings without changing the deployable build or storing their values. */
export function withLocalPreviewBindings(plugins: Array<Plugin>, root: string): Array<Plugin> {
export function withLocalPreviewBindings(
plugins: Array<Plugin>,
root: string,
localQueueProducers?: LocalQueueProducers,
): Array<Plugin> {
let directory: string | undefined;
const cleanup = () => {
if (directory) {
Expand Down Expand Up @@ -35,9 +42,10 @@ export function withLocalPreviewBindings(plugins: Array<Plugin>, root: string):
const output = dirname(getRootConfigPath(root));
cpSync(output, dirname(getRootConfigPath(directory)), { recursive: true });
const path = getWorkerConfigPath(directory);
const worker = JSON.parse(readFileSync(path, 'utf8')) as {
env?: Record<string, { type?: unknown }>;
};
const worker = JSON.parse(readFileSync(path, 'utf8')) as Pick<
CloudflareConfig['worker'],
'env'
>;
worker.env ??= {};
const inlineBindingTypes = new Set<unknown>(['text', 'json', 'secret']);
for (const name of Object.keys(loadLocalEnv(root))) {
Expand All @@ -46,6 +54,7 @@ export function withLocalPreviewBindings(plugins: Array<Plugin>, root: string):
worker.env[name] = { type: 'secret' };
}
}
addLocalQueueProducers(worker, localQueueProducers);
writeFileAtomic(path, JSON.stringify(worker));
// The upstream preview resolves declared secrets from this env directory.
// A private artifact copy isolates local-only declarations from deployment
Expand Down
28 changes: 26 additions & 2 deletions packages/void/src/plugin-cloudflare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,19 @@ import type { PluginConfig } from '@cloudflare/vite-plugin';
import { dirname, isAbsolute, join, relative, resolve } from 'pathslash';
import type { BuildEnvironment, Plugin } from 'vite';
import { readGeneratedWranglerConfigFile } from './cli/generated-wrangler-config.ts';
import { voidWarn } from './log.ts';
import {
addLocalQueueProducers,
mergeCloudflareConfig,
nativeAuxiliaryWorkers,
restoreLocalContainerBindings,
toNativeCloudflareConfig,
} from './plugin-cloudflare-config.ts';
import type { AuxiliaryWorkerConfig, WorkerConfig } from './plugin-cloudflare-config.ts';
import type {
AuxiliaryWorkerConfig,
LocalQueueProducers,
WorkerConfig,
} from './plugin-cloudflare-config.ts';
import { withLocalPreviewBindings } from './plugin-cloudflare-preview.ts';
import { isVitestServer } from './plugin-dev-config.ts';
import { writeFileAtomic } from './shared/atomic-write.ts';
Expand Down Expand Up @@ -55,16 +61,21 @@ export function cloudflare(options: {
inspectorPort?: PluginConfig['inspectorPort'];
persistState?: PluginConfig['persistState'];
viteEnvironment: NonNullable<PluginConfig['viteEnvironment']>;
localQueueProducers?: LocalQueueProducers;
finalizeAssets?: (clientDir: string, environment: BuildEnvironment | undefined) => void;
}): Array<Plugin> {
const root = process.cwd();
let workerConfig: WorkerConfig;
let native: ReturnType<typeof toNativeCloudflareConfig>;
let pluginNative: ReturnType<typeof toNativeCloudflareConfig>;
let localQueueBindings: Array<string> | undefined;
let localQueueWarnings: Array<string> | undefined;
const outputDirectories = new Map<string, string>();
const bridge: Plugin = {
name: 'void:cloudflare-config',
config(_userConfig, environment) {
localQueueBindings = undefined;
localQueueWarnings = undefined;
if (environment.isPreview) {
return;
}
Expand Down Expand Up @@ -101,8 +112,16 @@ export function cloudflare(options: {
}
} else if (environment.command === 'serve') {
restoreLocalContainerBindings(pluginNative.worker);
localQueueBindings = addLocalQueueProducers(
pluginNative.worker,
options.localQueueProducers,
(message) => (localQueueWarnings ??= []).push(message),
);
}
},
configureServer() {
localQueueWarnings?.forEach(voidWarn);
},
};
const directories: Plugin = {
name: 'void:cloudflare-output-directories',
Expand Down Expand Up @@ -271,7 +290,11 @@ export function cloudflare(options: {
inspectorPort: options.inspectorPort,
persistState: options.persistState,
viteEnvironment: options.viteEnvironment,
auxiliaryWorkers: nativeAuxiliaryWorkers(options.auxiliaryWorkers, root),
auxiliaryWorkers: nativeAuxiliaryWorkers(
options.auxiliaryWorkers,
root,
() => localQueueBindings,
),
types: { generate: false },
config() {
// Replace the complete parsed configuration, including account settings
Expand All @@ -280,6 +303,7 @@ export function cloudflare(options: {
},
}),
root,
options.localQueueProducers,
),
output,
]);
Expand Down
99 changes: 78 additions & 21 deletions packages/void/test/integration/plugin-cloudflare-v2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,35 @@ export default {
expect(existsSync(join(root, '.gitignore'))).toBe(false);
});

it('keeps inferred local producers out of auxiliary Worker config callbacks', async () => {
const root = project();
vi.stubEnv('CLOUDFLARE_VITE_BUILD', undefined);
const helperProducers = vi.fn();
const plugins = cloudflare({
config: () => ({ name: 'entry', main: 'virtual:entry' }),
viteEnvironment: { name: 'ssr' },
localQueueProducers: () => ({
queues: [{ filePath: 'inbox.ts', name: 'inbox', bindingName: 'QUEUE_INBOX' }],
reserved: [],
}),
auxiliaryWorkers: [
{
config(_config, { entryWorkerConfig }) {
const producers = entryWorkerConfig.queues?.producers ?? [
{ binding: 'QUEUE_INBOX', queue: 'helper-original' },
];
helperProducers(producers);
return { name: 'helper', main: 'helper.js', queues: { producers } };
},
},
],
});
await resolveConfig({ root, configFile: false, plugins }, 'serve');
expect(helperProducers).toHaveBeenCalledExactlyOnceWith([
{ binding: 'QUEUE_INBOX', queue: 'helper-original' },
]);
});

it("starts no Worker in Vitest's server, in any mode, but keeps it in servers that tests start", async () => {
const root = project();
const plugins = () =>
Expand Down Expand Up @@ -462,7 +491,16 @@ export default {
writeFileSync(join(oldOutput, 'config.json'), '{}');
writeFileSync(
join(root, 'worker.js'),
"export default { fetch: (_request, env) => new Response(env.PREVIEW_VALUE ?? 'built-worker') };",
`export default { async fetch(_request, env) {
await env.QUEUE_INBOX?.send({ test: true });
return Response.json({
value: env.PREVIEW_VALUE ?? 'built-worker',
sent: Boolean(env.QUEUE_INBOX),
dotenv: env.QUEUE_DOTENV,
reserved: 'QUEUE_RESERVED' in env,
collision: 'QUEUE_TWO_NAMES' in env,
});
} };`,
);
writeFileSync(join(root, 'index.html'), '<p>asset</p>');
const plugins = () =>
Expand All @@ -476,6 +514,16 @@ export default {
}),
inspectorPort: false,
viteEnvironment: { name: 'ssr' },
localQueueProducers: () => ({
queues: [
{ filePath: 'inbox.ts', name: 'inbox', bindingName: 'QUEUE_INBOX' },
{ filePath: 'dotenv.ts', name: 'dotenv', bindingName: 'QUEUE_DOTENV' },
{ filePath: 'reserved.ts', name: 'reserved', bindingName: 'QUEUE_RESERVED' },
{ filePath: 'two-names.ts', name: 'two-names', bindingName: 'QUEUE_TWO_NAMES' },
{ filePath: 'two_names.ts', name: 'two_names', bindingName: 'QUEUE_TWO_NAMES' },
],
reserved: ['QUEUE_RESERVED'],
}),
});
const builder = await createBuilder({
root,
Expand All @@ -492,26 +540,35 @@ export default {
expect(existsSync(join(root, 'dist/ssr/index.js'))).toBe(true);
expect(existsSync(join(root, 'dist/client/index.html'))).toBe(true);
expect(existsSync(join(getWorkerAssetsDir(root), 'index.html'))).toBe(true);
expect(readFileSync(join(root, 'dist/ssr/wrangler.json'), 'utf8')).toContain(
'"main": "index.js"',
);
writeFileSync(join(root, '.env'), 'PREVIEW_VALUE=local-preview-only');
// Exercise the native plugin's Worker runtime as well as its build output.
const server = await preview({
root,
configFile: false,
plugins: plugins(),
logLevel: 'silent',
server: { port: 0 },
});
try {
const response = await fetch(server.resolvedUrls!.local[0]);
expect(await response.text()).toBe('local-preview-only');
expect((await readBuildOutput(root)).workers.default.config.env).not.toHaveProperty(
'PREVIEW_VALUE',
);
} finally {
await server.close();
const files = [output.workers.default.configPath, join(root, 'dist/ssr/wrangler.json')];
const buildConfigs = files.map((file) => readFileSync(file, 'utf8'));
expect(buildConfigs[1]).toContain('"main": "index.js"');
expect(buildConfigs.every((text) => !text.includes('QUEUE_INBOX'))).toBe(true);
writeFileSync(join(root, '.env'), 'PREVIEW_VALUE=local-preview-only\nQUEUE_DOTENV=kept');
// Framework prerendering opens preview while the build flag is set.
// Clear the flag for the second check to simulate a separate CLI invocation.
for (const building of [true, false]) {
vi.stubEnv('CLOUDFLARE_VITE_BUILD', building ? 'true' : undefined);
const server = await preview({
root,
configFile: false,
plugins: plugins(),
logLevel: 'silent',
server: { port: 0 },
});
try {
const response = await fetch(server.resolvedUrls!.local[0]);
expect(await response.json()).toEqual({
value: 'local-preview-only',
sent: !building,
dotenv: 'kept',
reserved: false,
collision: false,
});
} finally {
await server.close();
}
expect(files.map((file) => readFileSync(file, 'utf8'))).toEqual(buildConfigs);
}
});
});
Loading