Skip to content
Merged
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/hono.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ import { defineMiddleware } from 'void';
export default defineMiddleware(cors({ origin: 'https://example.com' }));
```

In `vp dev` and `vp preview`, this middleware answers CORS requests, preflights included, as it does in your deployed app. If you turn on Vite's own CORS handling with [`server.cors`](https://vite.dev/config/server-options#server-cors) in `vite.config.ts`, Vite answers preflight requests before your middleware runs. `vp preview` uses [`preview.cors`](https://vite.dev/config/preview-options#preview-cors) when you set it, and `server.cors` otherwise.

```ts
// routes/api/products.ts (per-route cache)
import { cache } from 'hono/cache';
Expand Down
3 changes: 2 additions & 1 deletion packages/void/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@ generated entries must preserve the module-boundary rules below.

- **Installed runtime module identity**: Keep `void` server runtime subpaths out of Vite dependency optimization. Generated entries import runtime modules by resolved file path; prebundling a bare `void/kv` creates a second `envContext` and loses request bindings. Workspace symlinks can hide this defect. The shared runtime-optimizer plugin excludes the package in server environments on every target while preserving client optimization; packed-consumer checks exercise actual npm/pnpm installations. Vite never discovers bare imports from inside node_modules, so the same plugin prebundles Void's CommonJS dependencies (`void > email-validator`, the void/db driver) in every environment whose resolve conditions contain `workerd`: Void's worker, class A frameworks and Astro. Node environments get only the exclusion. Workerd environments also exclude `better-auth`. Its OAuth request state is a module-local ref, and the dev worker must load the same module Void's runtime does: prebundling an app import of `better-auth/api` while the excluded `void` package loads `better-auth` from source makes `getOAuthState()` miss the state the runtime set. A production build already bundles one copy. SvelteKit's dev server runs server code in Vite's Node `ssr` graph, which externalizes a bare import that resolves into node_modules before any plugin resolves it, so an installed `void/db` would load the package's D1 runtime. The SvelteKit plugin sets `ssr.noExternal: ['void']` during serve; Vite matches it by package name, so the whole package moves into that graph together and the injected `void/_env` shares void/db's env module. Like the routing plugin, it sends bare `void` to `void/handler` in server environments. In SvelteKit dev for PostgreSQL and MySQL apps, the plugin also inlines installed ES module packages that depend on void, so their `void/db` is the app's. In a D1 app, and for a CommonJS package or one that does not list void, the package stays external and loads its own copy of the env modules. `envContext` and the request scope therefore live on `globalThis` under versioned `Symbol.for` keys, like `authContext`, so every copy reads the current request; this also covers modules that a dependency-optimizer reload evaluates again during a request. Change a key when its store shape changes, because two Void versions in one process share it.
- **Plugin entry imports**: Every `vp dev` and `vp build` imports the plugin entry before it starts. Import dependencies that only some apps or commands use (feature codegen, CLI-only helpers) where they are used, so other apps don't load them at startup. `test/unit/plugin-entry-imports.test.ts` guards this; add a mock there when you move a heavy import out.
- **Dev server CORS**: A Void app answers CORS from its own middleware in dev and preview, as the deployed Worker does. Vite adds its CORS middleware ahead of every plugin middleware and ends each `OPTIONS` request there, so the `void:env` config hook sets `server.cors: false` unless the config sets `server.cors`; `preview.cors` falls back to it. Class A frameworks keep Vite's default. `test/unit/plugin-dev-cors.test.ts` checks the resolved `server.cors` and `preview.cors`; `test/integration/dev-cors.test.ts` sends preflights to dev and preview.
- **pnpm scaffold build policy**: Keep `create-void` and `void init` aligned with the repository: `better-sqlite3: false` uses version 13's bundled Node-API binaries; `esbuild`, `sharp`, and `workerd` have approved builds. Do not require an unnecessary node-gyp rebuild in fresh applications.
- **Scaffold dependency installation**: Vite+ projects install through local/global `vp`, bootstrapping with `npx` when neither is available. Preserve existing package-manager pins and lockfiles; fresh Vite+ projects select pnpm through the build-policy YAML without adding a version pin. Plain Vite projects use their selected package manager. Do not run a global package manager directly for Vite+ installs.
- **Vite+ starter versions**: Bundle the build-time `vite-plus/package.json` metadata into the CLI and scaffold its exact CLI/core pairing, including package-manager overrides. Preserve existing Vite+ pairings and catalogs. Bootstrap with the project's selected version (a pnpm, Bun or Yarn catalog entry, where `catalog:` and `catalog:default` name the same catalog), or the CLI's own Vite+ version when that entry cannot be read; upgrades belong to `vp migrate`, which coordinates the toolchain.
Expand Down Expand Up @@ -250,7 +251,7 @@ production functions and real generated entries rather than copied code.
- **Self-host ISR requires a user-declared `ISR_CACHE` KV.** There is no `id: 'local'` injection for it: a placeholder id is fine for miniflare-backed dev but breaks a real `wrangler deploy`, which rejects an unknown namespace id. The user creates the namespace and binds it as `ISR_CACHE`; `readIsrCache`/`writeIsrCache` fail open to a live render when it is absent.
- **Workers AI has no local emulator.** For a saved direct Cloudflare destination, `shouldBindWorkersAi()` injects the owner's remote AI binding during development and preview, using the same Cloudflare credentials as the CLI. Production builds use the normal AI binding. The root `ai.binding` takes precedence over `inference.bindings.ai`, with `AI` as the default name; `__VOID_AI_BINDING` records a custom runtime name. Managed and unsaved projects keep the Void proxy path during development. Apps without inferred AI usage must perform no AI authentication or entitlement probe.
- **`mergeBindings` may remove a generated Cloudflare entry only under the name Void itself writes, gated on the matching `needs*` flag.** The Cloudflare plugin `defu`-merges the returned patch over `resolved` (arrays concatenate, `undefined` is skipped), so the only way to drop a key is to mutate `resolved` — and a mutation there is a change to the user's own config, which the CF-plugin-API rule above says takes precedence. The `send_email` serve-strip once deleted the whole field, so an app that drove Cloudflare's email API through its own `send_email: [{ name: "MAILER" }]` without ever importing `void/email` started `void dev` with `env.MAILER` undefined. It now filters out only the reserved `SEND_EMAIL` entry (`SEND_EMAIL_BINDING` from `cli/email-cloudflare.ts`, the name `void deploy --platform cloudflare` writes and the runtime reads), only when `bindings.needsEmail` — the same signal that arms the dev inbox — and drops the key only when nothing is left. `test/unit/plugin-email-config.test.ts` runs the real closure through a mocked `cloudflare()`.
- **Every `/__void/inbox` route requires the dev-trigger token; the worker's capture POST carries it via a var.** Vite's host validation (`server.allowedHosts`, runs before plugin middlewares) only rejects DNS-rebinding hostnames — any IP-literal `Host` passes — and its default CORS reflects every `localhost` origin, so an unauthenticated inbox middleware hands every peer under `--host` (and every other local dev server) the raw MIME with Bcc and attachments, a DELETE, and a capture endpoint to plant messages. `plugin-email-dev-inbox.ts` therefore checks the same per-project token the cron/queue dev routes and the pages dev-CSS loopback use (`getOrCreateDevTriggerToken`, `.void/dev-trigger-token`), accepted as the `x-void-dev-trigger` header (worker, curl) or `?token=` (browser — the plugin prints the tokenized URL on `listening` and renders its own links with it; responses already send `Referrer-Policy: no-referrer`). Missing or wrong → `401` with a one-line body naming both forms and no ack header. The compiled router embeds the token as a module-local const that `runtime/email/index.ts` cannot import, so `mergeBindings` injects `__VOID_EMAIL_DEV_INBOX_TOKEN` next to `__VOID_EMAIL_DEV_INBOX` under the one `shouldInjectEmailDevInboxVar` gate (dev only — never in a build's `wrangler.json`); `sendEmail` sends it and, on a non-2xx, echoes the first line of the dev server's body so a missing token is diagnosable. Nothing on the worker side ever skips the inbox for a real transport because the token is absent. Because that file is now the inbox's whole credential and loopback needs no `--host`, `getOrCreateDevTriggerToken` creates it `0600` (`openSync(.., 'wx', 0o600)`) and best-effort `chmod`s a pre-existing file whose group/other bits are set, never rotating it (skipped on Windows, which has no such bits) — a default-umask `0644` file would hand every other account on a shared host the raw MIME, the DELETE, and the capture endpoint. `.void/dev-triggers.ts` (`plugin-framework-triggers.ts`) embeds the same token for Class A frameworks and is written `0600` the same way. `/__void/ping` stays open: it exposes no data. `/__void/restart` answers `403` unless the POST is same-origin (`Sec-Fetch-Site`, else `Origin`) and carries this server instance's random token in `x-void-restart` — browsers send no Fetch Metadata to plain-HTTP LAN origins (`--host`), so the token, embedded only in the `virtual:void/binding-hint` toast (which navigates with `&t=`; Vite's default CORS exposes it to localhost origins only, like the HMR token), is what stops a foreign page from opening `/__void/restarting` and riding its auto-POST. `/__void/restarting` refuses a navigation whose `Sec-Fetch-Site` is not `same-origin` or `none`, sends `Referrer-Policy: no-referrer`, and only navigates to a same-origin path from `?return=`, falling back to `/`.
- **Every `/__void/inbox` route requires the dev-trigger token; the worker's capture POST carries it via a var.** Vite's host validation (`server.allowedHosts`, runs before plugin middlewares) only rejects DNS-rebinding hostnames — any IP-literal `Host` passes — and its default CORS reflects every `localhost` origin, so an unauthenticated inbox middleware hands every peer under `--host` (and every other local dev server) the raw MIME with Bcc and attachments, a DELETE, and a capture endpoint to plant messages. `plugin-email-dev-inbox.ts` therefore checks the same per-project token the cron/queue dev routes and the pages dev-CSS loopback use (`getOrCreateDevTriggerToken`, `.void/dev-trigger-token`), accepted as the `x-void-dev-trigger` header (worker, curl) or `?token=` (browser — the plugin prints the tokenized URL on `listening` and renders its own links with it; responses already send `Referrer-Policy: no-referrer`). Missing or wrong → `401` with a one-line body naming both forms and no ack header. The compiled router embeds the token as a module-local const that `runtime/email/index.ts` cannot import, so `mergeBindings` injects `__VOID_EMAIL_DEV_INBOX_TOKEN` next to `__VOID_EMAIL_DEV_INBOX` under the one `shouldInjectEmailDevInboxVar` gate (dev only — never in a build's `wrangler.json`); `sendEmail` sends it and, on a non-2xx, echoes the first line of the dev server's body so a missing token is diagnosable. Nothing on the worker side ever skips the inbox for a real transport because the token is absent. Because that file is now the inbox's whole credential and loopback needs no `--host`, `getOrCreateDevTriggerToken` creates it `0600` (`openSync(.., 'wx', 0o600)`) and best-effort `chmod`s a pre-existing file whose group/other bits are set, never rotating it (skipped on Windows, which has no such bits) — a default-umask `0644` file would hand every other account on a shared host the raw MIME, the DELETE, and the capture endpoint. `.void/dev-triggers.ts` (`plugin-framework-triggers.ts`) embeds the same token for Class A frameworks and is written `0600` the same way. `/__void/ping` stays open: it exposes no data. `/__void/restart` answers `403` unless the POST is same-origin (`Sec-Fetch-Site`, else `Origin`) and carries this server instance's random token in `x-void-restart` — browsers send no Fetch Metadata to plain-HTTP LAN origins (`--host`), so the token, embedded only in the `virtual:void/binding-hint` toast (which navigates with `&t=`; Vite's default CORS exposes it to localhost origins only, like the HMR token, and Void apps turn that middleware off by default), is what stops a foreign page from opening `/__void/restarting` and riding its auto-POST. `/__void/restarting` refuses a navigation whose `Sec-Fetch-Site` is not `same-origin` or `none`, sends `Referrer-Policy: no-referrer`, and only navigates to a same-origin path from `?return=`, falling back to `/`.
- **The dev server never serves the dev-trigger token or old database URLs.** Vite serves any root file not in `server.fs.deny`, and its CORS lets every localhost origin read the reply. `devTriggerSecretGuardPlugin` (`plugin-dev-config.ts`, registered in every serve plugin list) therefore answers 404 to `.void/dev-trigger*`, to Nitro dev bundles (`.nuxt/dev/`, `.nitro/dev/`, which inline the dispatch), to Astro's `.astro/dev.log` (background `astro dev` output, which includes the startup hint) and to `.void/drizzle.config.json` (older CLI versions left `db push` / `db studio` database URLs there; only drizzle-kit reads it) in any URL form, and `void:routing` refuses `virtual:void-routes` in the client environment. Do not switch to `server.fs.deny`: a plugin's list replaces Vite's defaults, and denying `.void/dev-triggers.ts` breaks the worker import.

- **Sandbox SDK 1.0**: Keep the packaged Dockerfile helper version, the custom-image example in `docs/guide/sandboxes.md`, and the managed controller’s verified helper-layer digest in sync with `@cloudflare/sandbox`. Native execution uses Durable Object scheduling with named images; managed controller protocol 2 preserves admission, metering, and cleanup, including retained protocol 1 deployments. Cancellation crosses Workers RPC as a stream, not an AbortSignal. Run the Sandbox RPC and lifecycle tests when changing this boundary.
Expand Down
14 changes: 11 additions & 3 deletions packages/void/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -498,20 +498,28 @@ export function voidPlugin(options?: {
assets.run_worker_first = [...DEV_ASSET_ROUTING_EXCLUSIONS, '/**'];
}

const watchConfig = { server: { watch: { ignored } } };
// A Void app answers CORS, preflights included, from its own middleware.
// Vite adds its CORS middleware ahead of every plugin's and ends each
// OPTIONS request there, so with it on no preflight reaches the app in
// dev or preview. `preview.cors` falls back to `server.cors`, so preview
// follows this unless the config sets it. Framework apps keep Vite's default.
const turnOffViteCors = !framework && userConfig.server?.cors === undefined;
const serverConfig = {
server: { watch: { ignored }, ...(turnOffViteCors && { cors: false }) },
};

// Minify worker bundles for smaller deploys (skip when output: "static"
// because prerendering runs the SSR bundle in Miniflare, which cannot
// resolve template-literal dynamic imports produced by the minifier)
if (!isNodeTarget(config.target) && config.output !== 'static') {
const envNames = framework === 'vinext-app' ? ['rsc', 'ssr'] : ['ssr'];
return {
...watchConfig,
...serverConfig,
environments: Object.fromEntries(envNames.map((n) => [n, { build: { minify: true } }])),
};
}

return watchConfig;
return serverConfig;
},
configureServer(server) {
// Remote mode status — log which bindings are using the proxy
Expand Down
6 changes: 3 additions & 3 deletions packages/void/src/plugin-restart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,9 +134,9 @@ export function isSameOriginNavigation(req: IncomingMessage): boolean {

/**
* The toast is the only in-app way to reach `/__void/restarting`, so it is
* the only place that knows the restart token. Vite's default `server.cors`
* lets only localhost origins read this module, the same exposure as the
* HMR token in `/@vite/client`.
* the only place that knows the restart token. Vite's default CORS middleware
* lets only localhost origins read this module, the same exposure as the HMR
* token in `/@vite/client`. Void apps turn that middleware off by default.
*/
const clientModule = (token: string): string => `if (import.meta.hot) {
const token = ${JSON.stringify(token)};
Expand Down
Loading