diff --git a/.github/scripts/packed-consumer-scope.test.mjs b/.github/scripts/packed-consumer-scope.test.mjs index 27846a316..d987d49c2 100644 --- a/.github/scripts/packed-consumer-scope.test.mjs +++ b/.github/scripts/packed-consumer-scope.test.mjs @@ -13,7 +13,7 @@ test('skips documentation-only changes and keeps ordinary runtime changes small' 'skip', ); assert.equal( - selectPackedSuite(['docs/guide/env-vars.md', 'packages/void/src/runtime/env-public.ts']), + selectPackedSuite(['docs/guide/env-vars.md', 'packages/void/src/runtime/env/public.ts']), 'smoke', ); assert.equal(selectPackedSuite(['platform/packages/api/src/routes/projects.ts']), 'smoke'); @@ -66,7 +66,7 @@ test('compares the full pushed range rather than just the last commit', async () event: { repository, before, after }, request: async (path) => { assert(path.includes(`${before}...${after}`)); - return { files: [{ filename: 'packages/void/src/runtime/kv.ts' }] }; + return { files: [{ filename: 'packages/void/src/runtime/kv/index.ts' }] }; }, }); assert.equal(result, 'smoke'); diff --git a/TESTING.md b/TESTING.md index e704dc5e0..9f470b8b2 100644 --- a/TESTING.md +++ b/TESTING.md @@ -58,7 +58,7 @@ artifact check. For a leaf-module edit with known import-based consumers, Vitest's native related command is useful: ```sh -vp test related --run packages/void/src/runtime/sse.ts --project unit --project unit-pglite --project cli-unit +vp test related --run packages/void/src/runtime/sse/index.ts --project unit --project unit-pglite --project cli-unit vp test list packages/void/test/unit/plugin-routing.test.ts --filesOnly ``` diff --git a/packages/react/test/unit/plugin-pages.test.ts b/packages/react/test/unit/plugin-pages.test.ts index 2ac82bc90..1d415ac3e 100644 --- a/packages/react/test/unit/plugin-pages.test.ts +++ b/packages/react/test/unit/plugin-pages.test.ts @@ -42,7 +42,7 @@ describe('installedDependencies', () => { 'void/pages-client': '/app/node_modules/.pnpm/void@1.6.2/node_modules/void/dist/pages/client.mjs', 'void/pages-prefetch': 'C:\\app\\node_modules\\void\\dist\\pages\\prefetch.mjs', - 'void/live/client': '/repo/packages/void/dist/runtime/live-client.mjs', + 'void/live/client': '/repo/packages/void/dist/runtime/live/client.mjs', }; expect(installedDependencies(Object.keys(files), (specifier) => files[specifier]!)).toEqual([ diff --git a/packages/void/AGENTS.md b/packages/void/AGENTS.md index f7359065f..496bc61c9 100644 --- a/packages/void/AGENTS.md +++ b/packages/void/AGENTS.md @@ -68,12 +68,20 @@ Recover response-less 4xx/5xx Hono `HTTPException`s only for page GET/HEAD reque The Vite entry is `src/index.ts`; `src/plugin-*` wires feature plugins. `src/router`, `src/pages` and `src/codegen` scan and compile application -code. `src/runtime` contains Worker-safe public helpers; `src/cli` owns +code. `src/runtime` groups application helpers by feature (`auth`, `client`, +`db`, `env`, `handler`, `routing`, and service-specific directories). Remove +only redundant feature prefixes from filenames; retain engine names and roles +such as `better-auth-*`, `*-handler`, and `public-client`. Standalone public +runtime features use `/index.ts`. Browser entry points import their +feature's client modules directly; feature entry points must not combine +browser and server implementations. +Keep feature-specific helpers alongside their entry point and cross-feature +pure helpers in `src/shared`. `src/cli` owns commands, packaging and deployment. Database authoring and migration helpers live in `src/drizzle` and `src/migrations`. The routing compiler emits imports, metadata and runtime factory calls. Ordinary -request execution lives in `runtime/routing.ts` and its asset, Pages, error and +request execution lives in `runtime/routing/index.ts` and its asset, Pages, error and Worker modules, resolved through private `#self/runtime/routing`. Test these production functions directly and retain actual generated-Worker coverage; do not restore mirrored middleware implementations or execution strings. @@ -146,9 +154,9 @@ generated entries must preserve the module-boundary rules below. Two features need extra wiring on a self-hosted `vite build && wrangler deploy` (no Void platform proxy/dispatch in front of the worker). Both are inert on managed `void deploy`. -- **`ai.gateway`, custom AI bindings, and private runtime vars** — `void.config.ts`'s `ai.gateway` (validated in `config.ts` as `ai?: { gateway?: string }`; non-empty string, `additionalProperties: false`) names a Cloudflare AI Gateway in the user's own account. `inference.bindings.ai` accepts a string custom binding name. `mergeBindings` (`index.ts`) injects the resolved binding only when `shouldBindWorkersAi()` is true — the app infers `needsAI`, it is a build or a saved direct Cloudflare development/preview session, and neither the resolved generated Cloudflare config nor the result already declares an `ai` binding — so an authored `cloudflare.ai` declaration stays authoritative. Direct development adds `remote: true` because Workers AI has no local emulator. It emits `vars.__VOID_AI_BINDING` for a non-default binding and `vars.__VOID_AI_GATEWAY` when configured. At runtime, `runtime/ai.ts` `resolveBackend()` uses that resolved binding when no `__VOID_PROXY`/`__VOID_TOKEN` exists. `ai.run/stream/image` hit Workers AI directly; `ai.provider().fetch()` routes through the user's own gateway via `directAi.gateway(__VOID_AI_GATEWAY).getUrl(provider)` with the provider key from the user's own secret (`resolveProviderKey` → `env[PROVIDER_KEY_MAP[provider]]`), returning HTTP 501 if `__VOID_AI_GATEWAY` is unset. No cross-tenant metering on this path. +- **`ai.gateway`, custom AI bindings, and private runtime vars** — `void.config.ts`'s `ai.gateway` (validated in `config.ts` as `ai?: { gateway?: string }`; non-empty string, `additionalProperties: false`) names a Cloudflare AI Gateway in the user's own account. `inference.bindings.ai` accepts a string custom binding name. `mergeBindings` (`index.ts`) injects the resolved binding only when `shouldBindWorkersAi()` is true — the app infers `needsAI`, it is a build or a saved direct Cloudflare development/preview session, and neither the resolved generated Cloudflare config nor the result already declares an `ai` binding — so an authored `cloudflare.ai` declaration stays authoritative. Direct development adds `remote: true` because Workers AI has no local emulator. It emits `vars.__VOID_AI_BINDING` for a non-default binding and `vars.__VOID_AI_GATEWAY` when configured. At runtime, `runtime/ai/index.ts` `resolveBackend()` uses that resolved binding when no `__VOID_PROXY`/`__VOID_TOKEN` exists. `ai.run/stream/image` hit Workers AI directly; `ai.provider().fetch()` routes through the user's own gateway via `directAi.gateway(__VOID_AI_GATEWAY).getUrl(provider)` with the provider key from the user's own secret (`resolveProviderKey` → `env[PROVIDER_KEY_MAP[provider]]`), returning HTTP 501 if `__VOID_AI_GATEWAY` is unset. No cross-tenant metering on this path. - **Internal-binding leak check permits the AI routing markers** — the integration guard (`test/integration/kitchen-sink-build.test.ts`) that asserts no credential-bearing `__VOID_*` var reaches `dist/ssr/wrangler.json` permits `__VOID_AI_BINDING` and `__VOID_AI_GATEWAY`, because they are legitimate, non-credential runtime routing values (unlike the credential keys in `INTERNAL_ENV_KEYS`, which are stripped). -- **`ISR_CACHE` self-host requirement** — self-host ISR (`@void/isr/runtime`, `runtime/isr.ts`) reads `env.ISR_CACHE` (a `KVNamespace`) + `env.__VOID_ISR_DEPLOYMENT_ID`. Unlike D1/KV/R2, `ISR_CACHE` is **not** auto-injected (a KV binding needs a real namespace id), so the user must create the namespace and declare it as `ISR_CACHE` in `cloudflare.kv_namespaces`. `routing.revalidate` (void.config.ts) and per-page `export const revalidate` are merged by `collectRevalidate` (`isr-config.ts`) and baked as `__VOID_ISR_REVALIDATE`. On-demand `revalidate()` on self-host purges the worker's own KV (global) plus the local-colo `caches.default` edge variants only. +- **`ISR_CACHE` self-host requirement** — self-host ISR (`@void/isr/runtime`, `runtime/isr/index.ts`) reads `env.ISR_CACHE` (a `KVNamespace`) + `env.__VOID_ISR_DEPLOYMENT_ID`. Unlike D1/KV/R2, `ISR_CACHE` is **not** auto-injected (a KV binding needs a real namespace id), so the user must create the namespace and declare it as `ISR_CACHE` in `cloudflare.kv_namespaces`. `routing.revalidate` (void.config.ts) and per-page `export const revalidate` are merged by `collectRevalidate` (`isr-config.ts`) and baked as `__VOID_ISR_REVALIDATE`. On-demand `revalidate()` on self-host purges the worker's own KV (global) plus the local-colo `caches.default` edge variants only. - **Framework ISR on direct deploy** — `void deploy --platform cloudflare` wraps each supported framework Worker when `routing.revalidate` is active. Its ISR runtime is bundled as `__void_isr.mjs` beside the Worker entry because Class A output uses `no_bundle: true`; keep the import relative and exclude the module from co-located static assets. Only HTML document requests and responses enter this cache. Managed framework deploys use platform dispatch instead. ### Package Exports @@ -235,7 +243,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.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), 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 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. diff --git a/packages/void/package.json b/packages/void/package.json index c401168f9..6c4b9c736 100644 --- a/packages/void/package.json +++ b/packages/void/package.json @@ -27,25 +27,25 @@ ], "type": "module", "imports": { - "#self/_env": "./dist/runtime/env.mjs", - "#self/email": "./dist/runtime/email.mjs", - "#self/env": "./dist/runtime/env-public.mjs", - "#self/client": "./dist/runtime/client.mjs", - "#self/handler": "./dist/runtime/handler.mjs", - "#self/queues": "./dist/runtime/queues.mjs", + "#self/_env": "./dist/runtime/env/runtime.mjs", + "#self/email": "./dist/runtime/email/index.mjs", + "#self/env": "./dist/runtime/env/public.mjs", + "#self/client": "./dist/runtime/client/index.mjs", + "#self/handler": "./dist/runtime/handler/index.mjs", + "#self/queues": "./dist/runtime/queues/index.mjs", "#self/remote": "./dist/runtime/remote/index.mjs", "#self/remote/binding-handler": "./dist/runtime/remote/binding-handler.mjs", - "#self/sandbox": "./dist/runtime/sandbox.mjs", - "#self/runtime/live-server": "./dist/runtime/live-server.mjs", - "#self/runtime/fetch": "./dist/runtime/fetch.mjs", - "#self/runtime/fetch-server": "./dist/runtime/fetch-server.mjs", - "#self/runtime/fetch-stream": "./dist/runtime/fetch-stream.mjs", - "#self/runtime/route-url": "./dist/runtime/route-url.mjs", - "#self/runtime/migration-handler": "./dist/runtime/migration-handler.mjs", - "#self/runtime/migration-handler-pg": "./dist/runtime/migration-handler-pg.mjs", - "#self/runtime/migration-handler-mysql": "./dist/runtime/migration-handler-mysql.mjs", - "#self/runtime/ws-server": "./dist/runtime/ws-server.mjs", - "#self/runtime/routing": "./dist/runtime/routing.mjs" + "#self/sandbox": "./dist/runtime/sandbox/index.mjs", + "#self/runtime/live-server": "./dist/runtime/live/server.mjs", + "#self/runtime/fetch": "./dist/runtime/client/fetch.mjs", + "#self/runtime/fetch-server": "./dist/runtime/client/fetch-server.mjs", + "#self/runtime/fetch-stream": "./dist/runtime/client/fetch-stream.mjs", + "#self/runtime/route-url": "./dist/runtime/routing/route-url.mjs", + "#self/runtime/migration-handler": "./dist/runtime/db/migrations/d1-handler.mjs", + "#self/runtime/migration-handler-pg": "./dist/runtime/db/migrations/postgres-handler.mjs", + "#self/runtime/migration-handler-mysql": "./dist/runtime/db/migrations/mysql-handler.mjs", + "#self/runtime/ws-server": "./dist/runtime/ws/server.mjs", + "#self/runtime/routing": "./dist/runtime/routing/index.mjs" }, "exports": { ".": { @@ -70,24 +70,24 @@ "require": "./dist/edge.mjs" }, "./handler": { - "types": "./dist/runtime/handler.d.mts", - "import": "./dist/runtime/handler.mjs", - "require": "./dist/runtime/handler.mjs" + "types": "./dist/runtime/handler/index.d.mts", + "import": "./dist/runtime/handler/index.mjs", + "require": "./dist/runtime/handler/index.mjs" }, "./response": { - "types": "./dist/runtime/response.d.mts", - "import": "./dist/runtime/response.mjs", - "require": "./dist/runtime/response.mjs" + "types": "./dist/runtime/handler/response.d.mts", + "import": "./dist/runtime/handler/response.mjs", + "require": "./dist/runtime/handler/response.mjs" }, "./auth": { - "types": "./dist/runtime/auth.d.mts", - "import": "./dist/runtime/auth.mjs", - "require": "./dist/runtime/auth.mjs" + "types": "./dist/runtime/auth/index.d.mts", + "import": "./dist/runtime/auth/index.mjs", + "require": "./dist/runtime/auth/index.mjs" }, "./validator": { - "types": "./dist/runtime/validator.d.mts", - "import": "./dist/runtime/validator.mjs", - "require": "./dist/runtime/validator.mjs" + "types": "./dist/runtime/handler/validator.d.mts", + "import": "./dist/runtime/handler/validator.mjs", + "require": "./dist/runtime/handler/validator.mjs" }, "./routes": { "types": "./dist/routes-stub.d.mts", @@ -105,139 +105,139 @@ "require": "./dist/sveltekit.mjs" }, "./client": { - "types": "./dist/runtime/client.d.mts", - "import": "./dist/runtime/client.mjs", - "require": "./dist/runtime/client.mjs" + "types": "./dist/runtime/client/index.d.mts", + "import": "./dist/runtime/client/index.mjs", + "require": "./dist/runtime/client/index.mjs" }, "./client/react": { - "types": "./dist/runtime/client-react.d.mts", - "import": "./dist/runtime/client-react.mjs", - "require": "./dist/runtime/client-react.mjs" + "types": "./dist/runtime/client/react.d.mts", + "import": "./dist/runtime/client/react.mjs", + "require": "./dist/runtime/client/react.mjs" }, "./client/vue": { - "types": "./dist/runtime/client-vue.d.mts", - "import": "./dist/runtime/client-vue.mjs", - "require": "./dist/runtime/client-vue.mjs" + "types": "./dist/runtime/client/vue.d.mts", + "import": "./dist/runtime/client/vue.mjs", + "require": "./dist/runtime/client/vue.mjs" }, "./client/svelte": { - "types": "./dist/runtime/client-svelte.d.mts", - "import": "./dist/runtime/client-svelte.mjs", - "require": "./dist/runtime/client-svelte.mjs" + "types": "./dist/runtime/client/svelte.d.mts", + "import": "./dist/runtime/client/svelte.mjs", + "require": "./dist/runtime/client/svelte.mjs" }, "./client/solid": { - "types": "./dist/runtime/client-solid.d.mts", - "import": "./dist/runtime/client-solid.mjs", - "require": "./dist/runtime/client-solid.mjs" + "types": "./dist/runtime/client/solid.d.mts", + "import": "./dist/runtime/client/solid.mjs", + "require": "./dist/runtime/client/solid.mjs" }, "./sse": { - "types": "./dist/runtime/sse.d.mts", - "import": "./dist/runtime/sse.mjs", - "require": "./dist/runtime/sse.mjs" + "types": "./dist/runtime/sse/index.d.mts", + "import": "./dist/runtime/sse/index.mjs", + "require": "./dist/runtime/sse/index.mjs" }, "./sse/client": { - "types": "./dist/runtime/sse-client.d.mts", - "import": "./dist/runtime/sse-client.mjs", - "require": "./dist/runtime/sse-client.mjs" + "types": "./dist/runtime/sse/client.d.mts", + "import": "./dist/runtime/sse/client.mjs", + "require": "./dist/runtime/sse/client.mjs" }, "./live": { - "types": "./dist/runtime/live.d.mts", - "import": "./dist/runtime/live.mjs", - "require": "./dist/runtime/live.mjs" + "types": "./dist/runtime/live/index.d.mts", + "import": "./dist/runtime/live/index.mjs", + "require": "./dist/runtime/live/index.mjs" }, "./live/client": { - "types": "./dist/runtime/live-client.d.mts", - "import": "./dist/runtime/live-client.mjs", - "require": "./dist/runtime/live-client.mjs" + "types": "./dist/runtime/live/client.d.mts", + "import": "./dist/runtime/live/client.mjs", + "require": "./dist/runtime/live/client.mjs" }, "./ws": { - "types": "./dist/runtime/ws.d.mts", - "import": "./dist/runtime/ws.mjs", - "require": "./dist/runtime/ws.mjs" + "types": "./dist/runtime/ws/index.d.mts", + "import": "./dist/runtime/ws/index.mjs", + "require": "./dist/runtime/ws/index.mjs" }, "./db": { - "types": "./dist/runtime/db.d.mts", - "import": "./dist/runtime/db.mjs", - "require": "./dist/runtime/db.mjs" + "types": "./dist/runtime/db/index.d.mts", + "import": "./dist/runtime/db/index.mjs", + "require": "./dist/runtime/db/index.mjs" }, "./durable": { - "types": "./dist/runtime/durable.d.mts", - "import": "./dist/runtime/durable.mjs", - "require": "./dist/runtime/durable.mjs" + "types": "./dist/runtime/durable/index.d.mts", + "import": "./dist/runtime/durable/index.mjs", + "require": "./dist/runtime/durable/index.mjs" }, "./seed": { - "types": "./dist/runtime/seed.d.mts", - "import": "./dist/runtime/seed.mjs", - "require": "./dist/runtime/seed.mjs" + "types": "./dist/runtime/db/seed.d.mts", + "import": "./dist/runtime/db/seed.mjs", + "require": "./dist/runtime/db/seed.mjs" }, "./drizzle-zod": { - "types": "./dist/runtime/drizzle-zod.d.mts", - "import": "./dist/runtime/drizzle-zod.mjs", - "require": "./dist/runtime/drizzle-zod.mjs" + "types": "./dist/runtime/db/validators/drizzle-zod.d.mts", + "import": "./dist/runtime/db/validators/drizzle-zod.mjs", + "require": "./dist/runtime/db/validators/drizzle-zod.mjs" }, "./drizzle-valibot": { - "types": "./dist/runtime/drizzle-valibot.d.mts", - "import": "./dist/runtime/drizzle-valibot.mjs", - "require": "./dist/runtime/drizzle-valibot.mjs" + "types": "./dist/runtime/db/validators/drizzle-valibot.d.mts", + "import": "./dist/runtime/db/validators/drizzle-valibot.mjs", + "require": "./dist/runtime/db/validators/drizzle-valibot.mjs" }, "./drizzle-arktype": { - "types": "./dist/runtime/drizzle-arktype.d.mts", - "import": "./dist/runtime/drizzle-arktype.mjs", - "require": "./dist/runtime/drizzle-arktype.mjs" + "types": "./dist/runtime/db/validators/drizzle-arktype.d.mts", + "import": "./dist/runtime/db/validators/drizzle-arktype.mjs", + "require": "./dist/runtime/db/validators/drizzle-arktype.mjs" }, "./schema-d1": { - "types": "./dist/runtime/schema-d1.d.mts", - "import": "./dist/runtime/schema-d1.mjs", - "require": "./dist/runtime/schema-d1.mjs" + "types": "./dist/runtime/db/schema/d1.d.mts", + "import": "./dist/runtime/db/schema/d1.mjs", + "require": "./dist/runtime/db/schema/d1.mjs" }, "./schema-pg": { - "types": "./dist/runtime/schema-pg.d.mts", - "import": "./dist/runtime/schema-pg.mjs", - "require": "./dist/runtime/schema-pg.mjs" + "types": "./dist/runtime/db/schema/postgres.d.mts", + "import": "./dist/runtime/db/schema/postgres.mjs", + "require": "./dist/runtime/db/schema/postgres.mjs" }, "./schema-mysql": { - "types": "./dist/runtime/schema-mysql.d.mts", - "import": "./dist/runtime/schema-mysql.mjs", - "require": "./dist/runtime/schema-mysql.mjs" + "types": "./dist/runtime/db/schema/mysql.d.mts", + "import": "./dist/runtime/db/schema/mysql.mjs", + "require": "./dist/runtime/db/schema/mysql.mjs" }, "./kv": { - "types": "./dist/runtime/kv.d.mts", - "import": "./dist/runtime/kv.mjs", - "require": "./dist/runtime/kv.mjs" + "types": "./dist/runtime/kv/index.d.mts", + "import": "./dist/runtime/kv/index.mjs", + "require": "./dist/runtime/kv/index.mjs" }, "./queues": { - "types": "./dist/runtime/queues.d.mts", - "import": "./dist/runtime/queues.mjs", - "require": "./dist/runtime/queues.mjs" + "types": "./dist/runtime/queues/index.d.mts", + "import": "./dist/runtime/queues/index.mjs", + "require": "./dist/runtime/queues/index.mjs" }, "./storage": { - "types": "./dist/runtime/storage.d.mts", - "import": "./dist/runtime/storage.mjs", - "require": "./dist/runtime/storage.mjs" + "types": "./dist/runtime/storage/index.d.mts", + "import": "./dist/runtime/storage/index.mjs", + "require": "./dist/runtime/storage/index.mjs" }, "./isr": { - "types": "./dist/runtime/isr.d.mts", - "import": "./dist/runtime/isr.mjs", - "require": "./dist/runtime/isr.mjs" + "types": "./dist/runtime/isr/index.d.mts", + "import": "./dist/runtime/isr/index.mjs", + "require": "./dist/runtime/isr/index.mjs" }, "./log": { - "types": "./dist/runtime/log.d.mts", - "import": "./dist/runtime/log.mjs", - "require": "./dist/runtime/log.mjs" + "types": "./dist/runtime/log/index.d.mts", + "import": "./dist/runtime/log/index.mjs", + "require": "./dist/runtime/log/index.mjs" }, "./ai": { - "types": "./dist/runtime/ai.d.mts", - "import": "./dist/runtime/ai.mjs", - "require": "./dist/runtime/ai.mjs" + "types": "./dist/runtime/ai/index.d.mts", + "import": "./dist/runtime/ai/index.mjs", + "require": "./dist/runtime/ai/index.mjs" }, "./email": { - "types": "./dist/runtime/email.d.mts", - "import": "./dist/runtime/email.mjs", - "require": "./dist/runtime/email.mjs" + "types": "./dist/runtime/email/index.d.mts", + "import": "./dist/runtime/email/index.mjs", + "require": "./dist/runtime/email/index.mjs" }, "./_email-protocol": { - "types": "./dist/runtime/email-protocol.d.mts", - "import": "./dist/runtime/email-protocol.mjs", - "require": "./dist/runtime/email-protocol.mjs" + "types": "./dist/runtime/email/protocol.d.mts", + "import": "./dist/runtime/email/protocol.mjs", + "require": "./dist/runtime/email/protocol.mjs" }, "./email/testing": { "types": "./dist/runtime/email/testing.d.mts", @@ -245,9 +245,9 @@ "require": "./dist/runtime/email/testing.mjs" }, "./sandbox": { - "types": "./dist/runtime/sandbox.d.mts", - "import": "./dist/runtime/sandbox.mjs", - "require": "./dist/runtime/sandbox.mjs" + "types": "./dist/runtime/sandbox/index.d.mts", + "import": "./dist/runtime/sandbox/index.mjs", + "require": "./dist/runtime/sandbox/index.mjs" }, "./remote": { "types": "./dist/runtime/remote/index.d.mts", @@ -290,52 +290,52 @@ "require": "./dist/pages/islands-plugin.mjs" }, "./env": { - "types": "./dist/runtime/env-public.d.mts", + "types": "./dist/runtime/env/public.d.mts", "workerd": { - "import": "./dist/runtime/env-public.mjs", - "require": "./dist/runtime/env-public.mjs" + "import": "./dist/runtime/env/public.mjs", + "require": "./dist/runtime/env/public.mjs" }, "worker": { - "import": "./dist/runtime/env-public.mjs", - "require": "./dist/runtime/env-public.mjs" + "import": "./dist/runtime/env/public.mjs", + "require": "./dist/runtime/env/public.mjs" }, "browser": { - "import": "./dist/runtime/env-public-client.mjs", - "require": "./dist/runtime/env-public-client.mjs" + "import": "./dist/runtime/env/public-client.mjs", + "require": "./dist/runtime/env/public-client.mjs" }, "default": { - "import": "./dist/runtime/env-public.mjs", - "require": "./dist/runtime/env-public.mjs" + "import": "./dist/runtime/env/public.mjs", + "require": "./dist/runtime/env/public.mjs" } }, "./_env": { - "types": "./dist/runtime/env.d.mts", - "import": "./dist/runtime/env.mjs", - "require": "./dist/runtime/env.mjs" + "types": "./dist/runtime/env/runtime.d.mts", + "import": "./dist/runtime/env/runtime.mjs", + "require": "./dist/runtime/env/runtime.mjs" }, "./_db": { - "types": "./dist/runtime/db.d.mts", - "import": "./dist/runtime/db.mjs", - "require": "./dist/runtime/db.mjs" + "types": "./dist/runtime/db/index.d.mts", + "import": "./dist/runtime/db/index.mjs", + "require": "./dist/runtime/db/index.mjs" }, "./_db-pg": { - "types": "./dist/runtime/db-pg.d.mts", - "import": "./dist/runtime/db-pg.mjs", - "require": "./dist/runtime/db-pg.mjs" + "types": "./dist/runtime/db/postgres.d.mts", + "import": "./dist/runtime/db/postgres.mjs", + "require": "./dist/runtime/db/postgres.mjs" }, "./_db-mysql": { - "types": "./dist/runtime/db-mysql.d.mts", - "import": "./dist/runtime/db-mysql.mjs", - "require": "./dist/runtime/db-mysql.mjs" + "types": "./dist/runtime/db/mysql.d.mts", + "import": "./dist/runtime/db/mysql.mjs", + "require": "./dist/runtime/db/mysql.mjs" }, "./_sandbox-container": { - "types": "./dist/runtime/sandbox-container.d.mts", - "import": "./dist/runtime/sandbox-container.mjs" + "types": "./dist/runtime/sandbox/container.d.mts", + "import": "./dist/runtime/sandbox/container.mjs" }, "./limits": { - "types": "./dist/runtime/limits.d.mts", - "import": "./dist/runtime/limits.mjs", - "require": "./dist/runtime/limits.mjs" + "types": "./dist/runtime/limits/index.d.mts", + "import": "./dist/runtime/limits/index.mjs", + "require": "./dist/runtime/limits/index.mjs" }, "./deploy": { "types": "./dist/deploy.d.mts", diff --git a/packages/void/src/auth/config.ts b/packages/void/src/auth/config.ts index 9dd85ea06..16aedbf0e 100644 --- a/packages/void/src/auth/config.ts +++ b/packages/void/src/auth/config.ts @@ -8,7 +8,7 @@ import { } from 'vite'; import { discoverSchema } from '../drizzle/discover.ts'; import { readProjectPaths, type ProjectPaths } from '../project-paths.ts'; -import type { VoidAuthConfig } from '../runtime/auth.ts'; +import type { VoidAuthConfig } from '../runtime/auth/index.ts'; import type { AstNode, AstProgram } from '../shared/ast.ts'; function isVoidAuthConfigSource(code: string, filename: string): boolean { diff --git a/packages/void/src/auth/drizzle.ts b/packages/void/src/auth/drizzle.ts index b61c32889..5eb203868 100644 --- a/packages/void/src/auth/drizzle.ts +++ b/packages/void/src/auth/drizzle.ts @@ -5,8 +5,8 @@ import { type BetterAuthDBSchema, type DBFieldAttribute, } from 'better-auth/db'; -import type { VoidAuthConfig } from '../runtime/auth.ts'; -import type { VoidAuthRuntimeOptions } from '../runtime/better-auth-shared.ts'; +import type { VoidAuthRuntimeOptions } from '../runtime/auth/better-auth-shared.ts'; +import type { VoidAuthConfig } from '../runtime/auth/index.ts'; import { VOID_EMAIL_AUTH_PROVIDER, isVoidSocialAuthProvider, diff --git a/packages/void/src/auth/node.ts b/packages/void/src/auth/node.ts index 4ce1e442e..ae999553b 100644 --- a/packages/void/src/auth/node.ts +++ b/packages/void/src/auth/node.ts @@ -2,14 +2,14 @@ import { mkdirSync } from 'node:fs'; import { dirname } from 'pathslash'; import { readConfig } from '../config.ts'; import { getMiniflareDatabasePath } from '../migrations/runner.ts'; +import type { VoidAuthDialect, VoidAuthEnv } from '../runtime/auth/better-auth-shared.ts'; import { applyMySqlAuthMigrations, applyPgAuthMigrations, applySqliteAuthMigrations, mysqlMigrationRunner, pgMigrationRunner, -} from '../runtime/auth-migrations.ts'; -import type { VoidAuthDialect, VoidAuthEnv } from '../runtime/better-auth-shared.ts'; +} from '../runtime/auth/migrations.ts'; import { loadLocalEnv } from '../shared/env.ts'; import { findVoidAuthConfig, diff --git a/packages/void/src/cli/db.ts b/packages/void/src/cli/db.ts index 851af9957..5e406876c 100644 --- a/packages/void/src/cli/db.ts +++ b/packages/void/src/cli/db.ts @@ -33,7 +33,7 @@ import type { MySqlClient } from '../migrations/runner-mysql.ts'; import { assertJournalCoherence, validateMigrations } from '../migrations/validate.ts'; import { detectFramework } from '../plugin-inference.ts'; import { readProjectPaths } from '../project-paths.ts'; -import type { SeedFn } from '../runtime/seed.ts'; +import type { SeedFn } from '../runtime/db/seed.ts'; import { cfAccessHeaders } from '../shared/cf-access.ts'; import { loadLocalEnv } from '../shared/env.ts'; import { getProxyUrl, getToken } from './auth.ts'; diff --git a/packages/void/src/cli/deploy-managed-framework.ts b/packages/void/src/cli/deploy-managed-framework.ts index e045544ab..5b8039908 100644 --- a/packages/void/src/cli/deploy-managed-framework.ts +++ b/packages/void/src/cli/deploy-managed-framework.ts @@ -228,7 +228,7 @@ export async function runFrameworkDeploy( }); // Migration SQL bytes ride along inside the worker bundle (compiled in - // by the framework via `migration-handler.ts`); the deploy body only + // by the framework via `runtime/db/migrations`); the deploy body only // needs `manifest.migrations.pending` so the platform knows to invoke // the worker's `/__void/migrate` endpoint after dispatch. const result = await streamDirectR2Deploy({ diff --git a/packages/void/src/cli/env-validation.ts b/packages/void/src/cli/env-validation.ts index 6b060646b..7250f2800 100644 --- a/packages/void/src/cli/env-validation.ts +++ b/packages/void/src/cli/env-validation.ts @@ -10,7 +10,7 @@ import { dirname, join, resolve } from 'pathslash'; import { findEnvFile } from '../codegen/env-types.ts'; import { loadUserEnvFile } from '../host/load-user-env.ts'; import { voidWarn } from '../log.ts'; -import type { EnvValidationReport } from '../runtime/env-public.ts'; +import type { EnvValidationReport } from '../runtime/env/public.ts'; import { scanWranglerDotenvKeys } from '../shared/dotenv.ts'; import { findLegacyEnvFiles, @@ -31,7 +31,7 @@ import { readGeneratedWranglerConfigFile } from './generated-wrangler-config.ts' import { resolveCloudflareOperationArgv } from './preset.ts'; type EnvPublicModule = Pick< - typeof import('../runtime/env-public.ts'), + typeof import('../runtime/env/public.ts'), '_getRegisteredSchema' | '_hasRegisteredSchema' | '_getSchemaDefaults' | 'validateAllEnv' >; @@ -74,7 +74,7 @@ export async function validateSecretValues( /** Load the registered schema by importing the user's env.ts. */ async function loadSchema(envFile: string): Promise { await loadUserEnvFile(envFile); - const mod = await import('../runtime/env-public.ts'); + const mod = await import('../runtime/env/public.ts'); if (!mod._hasRegisteredSchema()) { return null; } diff --git a/packages/void/src/cli/wrapper.ts b/packages/void/src/cli/wrapper.ts index 423d3e53a..29f118fae 100644 --- a/packages/void/src/cli/wrapper.ts +++ b/packages/void/src/cli/wrapper.ts @@ -191,17 +191,31 @@ export async function generateWrapper( features.migrationDialect === 'sqlite' ? buildMigrationPlanBundle(migrations) : undefined; const handlerName = features.migrationDialect === 'postgresql' - ? 'migration-handler-pg' + ? 'postgres-handler' : features.migrationDialect === 'mysql' - ? 'migration-handler-mysql' - : 'migration-handler'; + ? 'mysql-handler' + : 'd1-handler'; const handlerFilename_ = `${handlerName}.mjs`; - let handlerPath = join(import.meta.dirname, '..', 'runtime', `${handlerName}.ts`); + let handlerPath = join( + import.meta.dirname, + '..', + 'runtime', + 'db', + 'migrations', + `${handlerName}.ts`, + ); if (!existsSync(handlerPath)) { - handlerPath = join(import.meta.dirname, 'runtime', handlerFilename_); + handlerPath = join(import.meta.dirname, 'runtime', 'db', 'migrations', handlerFilename_); } if (!existsSync(handlerPath)) { - handlerPath = join(import.meta.dirname, '..', 'runtime', handlerFilename_); + handlerPath = join( + import.meta.dirname, + '..', + 'runtime', + 'db', + 'migrations', + handlerFilename_, + ); } if (!existsSync(handlerPath)) { throw new Error( diff --git a/packages/void/src/client-asset-manifest.ts b/packages/void/src/client-asset-manifest.ts index 183890a80..dae4728b1 100644 --- a/packages/void/src/client-asset-manifest.ts +++ b/packages/void/src/client-asset-manifest.ts @@ -1,7 +1,7 @@ import { compilePattern, matchPattern } from '@void/edge'; import type { Rolldown } from 'vite'; -import type { ClientManifest } from './runtime/routing-assets.ts'; -import type { RoutingHeaderRule } from './runtime/routing.ts'; +import type { ClientManifest } from './runtime/routing/assets.ts'; +import type { RoutingHeaderRule } from './runtime/routing/index.ts'; /** * Attach cache provenance to the existing manifest without changing its entry inventory. diff --git a/packages/void/src/host/load-user-env.ts b/packages/void/src/host/load-user-env.ts index e3aceaad3..867ca93f6 100644 --- a/packages/void/src/host/load-user-env.ts +++ b/packages/void/src/host/load-user-env.ts @@ -9,7 +9,7 @@ * * Side-effect contract: loading the file evaluates the user's `defineEnv` * call, which registers the schema in the singleton state in - * `runtime/env-public.ts`. Callers read the result from there. + * `runtime/env/public.ts`. Callers read the result from there. * * Node-only (lives under `host/`). Must not be imported from anything * that ships in worker bundles. diff --git a/packages/void/src/index.ts b/packages/void/src/index.ts index 811dbe3ba..dede83314 100644 --- a/packages/void/src/index.ts +++ b/packages/void/src/index.ts @@ -1061,7 +1061,7 @@ export { defineHead, defineQueue, VoidAssetRewriteError, -} from './runtime/handler.ts'; +} from './runtime/handler/index.ts'; export type { CloudContext, @@ -1075,13 +1075,13 @@ export type { QueueBatch, QueueMessage, QueueRetryOptions, -} from './runtime/handler.ts'; +} from './runtime/handler/index.ts'; -export type { ValidatorSlots, HandlerInput } from './runtime/validator.ts'; +export type { ValidatorSlots, HandlerInput } from './runtime/handler/validator.ts'; -export type { AuthUser } from './runtime/auth.ts'; +export type { AuthUser } from './runtime/auth/index.ts'; -export type { QueueMap } from './runtime/queues.ts'; +export type { QueueMap } from './runtime/queues/index.ts'; export { defer } from './pages/defer.ts'; diff --git a/packages/void/src/migrations/runner-mysql.ts b/packages/void/src/migrations/runner-mysql.ts index de6a82356..00ca24b9e 100644 --- a/packages/void/src/migrations/runner-mysql.ts +++ b/packages/void/src/migrations/runner-mysql.ts @@ -3,8 +3,8 @@ import { mySqlMigrationLockError, mySqlMigrationLockName, readMySqlMigrationLease, -} from '../runtime/migration-lock-mysql.ts'; -import { splitMySqlMigrationSql } from '../runtime/mysql-migration-sql.ts'; +} from '../runtime/db/migrations/mysql-lock.ts'; +import { splitMySqlMigrationSql } from '../runtime/db/migrations/mysql-sql.ts'; import { collectMigrations } from './collect.ts'; export type MySqlClient = { diff --git a/packages/void/src/pages/client.ts b/packages/void/src/pages/client.ts index 25a039776..838dca02a 100644 --- a/packages/void/src/pages/client.ts +++ b/packages/void/src/pages/client.ts @@ -1,8 +1,8 @@ /// import type { ActionUrl, ResolveActionBody, ResolveActionParams, RouteUrlInput } from 'void/routes'; -import { toUrlString } from '../runtime/route-url.ts'; -import { interpolateRouteParams } from '../runtime/route-url.ts'; +import { toUrlString } from '../runtime/routing/route-url.ts'; +import { interpolateRouteParams } from '../runtime/routing/route-url.ts'; import { withPageQuery } from './action-key.ts'; import { VoidActionError, diff --git a/packages/void/src/pages/defer.ts b/packages/void/src/pages/defer.ts index 008457546..ea47e312d 100644 --- a/packages/void/src/pages/defer.ts +++ b/packages/void/src/pages/defer.ts @@ -1,4 +1,4 @@ -import type { CloudContext } from '../runtime/handler.ts'; +import type { CloudContext } from '../runtime/handler/index.ts'; export const DEFERRED: unique symbol = Symbol('deferred'); diff --git a/packages/void/src/pages/protocol.ts b/packages/void/src/pages/protocol.ts index c31fcfdd0..eccd6fb45 100644 --- a/packages/void/src/pages/protocol.ts +++ b/packages/void/src/pages/protocol.ts @@ -1,9 +1,9 @@ import { PAGES_PROTOCOL_VERSION } from '@void/edge'; import type { Context } from 'hono'; import type { HTTPException } from 'hono/http-exception'; -import { executeComposedHandler, getHandlerComposition } from '../runtime/handler-composition.ts'; -import type { CloudBindings, CloudContext } from '../runtime/handler.ts'; -import { isConvertedResponse } from '../runtime/response.ts'; +import { executeComposedHandler, getHandlerComposition } from '../runtime/handler/composition.ts'; +import type { CloudBindings, CloudContext } from '../runtime/handler/index.ts'; +import { isConvertedResponse } from '../runtime/handler/response.ts'; import { hasActionKey, searchWithoutActionKey } from './action-key.ts'; import { DEFERRED, separateDeferred, type ResolvedDeferredGroup } from './defer.ts'; import { diff --git a/packages/void/src/plugin-client-stubs.ts b/packages/void/src/plugin-client-stubs.ts index c9ef1066b..cec7c9d04 100644 --- a/packages/void/src/plugin-client-stubs.ts +++ b/packages/void/src/plugin-client-stubs.ts @@ -9,7 +9,7 @@ export function createClientStubsPlugin(): Plugin { 'void/queues': 'export const queues = {};', 'void/storage': 'export const storage = {}; export const createStorage = () => ({});', 'void/isr': 'export const revalidate = async () => {};', - // Client stub must mirror the real runtime/sandbox.ts surface so any + // Client stub must mirror the real runtime/sandbox/index.ts surface so any // client-side `instanceof` check for either runtime error doesn't crash with a // TypeError, and async `await getSandbox(...)` callers don't silently // mis-handle a sync return. Throwing here makes accidental client imports @@ -33,7 +33,7 @@ export function createClientStubsPlugin(): Plugin { } export const sandbox = { get: getSandbox }; `, - // `void/email` reaches `runtime/env-raw.ts` (`node:async_hooks`), so an + // `void/email` reaches `runtime/env/raw.ts` (`node:async_hooks`), so an // unstubbed client import builds with only a warning and white-screens on // load. `void/email/testing` needs its own entry (the filter is anchored) // because it pulls build-time router code and Node built-ins. Both throw, diff --git a/packages/void/src/plugin-env-client-guard.ts b/packages/void/src/plugin-env-client-guard.ts index 11127b1fc..72794d0b5 100644 --- a/packages/void/src/plugin-env-client-guard.ts +++ b/packages/void/src/plugin-env-client-guard.ts @@ -13,7 +13,7 @@ import { import { isClientEnvKey } from './shared/env.ts'; type EnvPublicModule = Pick< - typeof import('./runtime/env-public.ts'), + typeof import('./runtime/env/public.ts'), '_getRegisteredSchema' | '_hasRegisteredSchema' | '_getSchemaDefaults' | 'validateAllEnv' >; @@ -23,7 +23,7 @@ export async function loadEnvPublic(): Promise { if (cachedModule) { return cachedModule; } - const mod = await import('./runtime/env-public.ts'); + const mod = await import('./runtime/env/public.ts'); cachedModule = mod; return mod; } @@ -226,7 +226,7 @@ function recordHit(node: AstMemberExpression, hits: Array): void { * Vite plugin that fails the client build when a server-only env key * (anything in `defineEnv` not prefixed with `VITE_`) is referenced from a * module that ends up in the client bundle. The runtime proxy in - * `env-public-client.ts` already throws for the same class of bug at + * `runtime/env/public-client.ts` already throws for the same class of bug at * request time — this plugin moves the diagnosis forward to compile time * so it shows up in `pnpm build` and the dev overlay, not in production * after an admin clicks the offending route. diff --git a/packages/void/src/plugin-routing.ts b/packages/void/src/plugin-routing.ts index 9d3d0e231..04589a8ea 100644 --- a/packages/void/src/plugin-routing.ts +++ b/packages/void/src/plugin-routing.ts @@ -56,7 +56,7 @@ import { } from './router/compile.ts'; import type { RouteEnvironment } from './router/parse-filename.ts'; import type { ScanResult } from './router/scan.ts'; -import type { VoidAuthRuntimeOptions } from './runtime/better-auth-shared.ts'; +import type { VoidAuthRuntimeOptions } from './runtime/auth/better-auth-shared.ts'; import { loadLocalEnv } from './shared/env.ts'; import { invalidateSourceAnalysis } from './shared/source-analysis-cache.ts'; import { @@ -232,17 +232,17 @@ export function routingPlugin( const resolveFile = (specifier: string) => fileURLToPath(import.meta.resolve(specifier)); const handlerFile = resolveFile('#self/handler'); - const runtimeDir = dirname(resolveFile('#self/client')); + const authRuntimeDir = dirname(resolveFile('void/auth')); const fetchPath = resolveFile('#self/runtime/fetch'); const fetchStreamPath = resolveFile('#self/runtime/fetch-stream'); const sandboxRuntimePath = resolveFile('#self/sandbox'); const drizzleAdapterPath = resolveFile('better-auth/adapters/drizzle'); - let authClientPath = join(runtimeDir, 'auth-client.mjs'); + let authClientPath = join(authRuntimeDir, 'client.mjs'); const explicitAuthClientPaths: Record = { - react: join(runtimeDir, 'auth-client-react.mjs'), - vue: join(runtimeDir, 'auth-client-vue.mjs'), - svelte: join(runtimeDir, 'auth-client-svelte.mjs'), - solid: join(runtimeDir, 'auth-client-solid.mjs'), + react: join(authRuntimeDir, 'client-react.mjs'), + vue: join(authRuntimeDir, 'client-vue.mjs'), + svelte: join(authRuntimeDir, 'client-svelte.mjs'), + solid: join(authRuntimeDir, 'client-solid.mjs'), }; const remote = options.remoteMode ? { @@ -311,10 +311,10 @@ export function routingPlugin( compileOptions.auth = { authRuntimePath: dialect === 'postgresql' - ? join(runtimeDir, 'better-auth-pg.mjs') + ? join(authRuntimeDir, 'better-auth-postgres.mjs') : dialect === 'mysql' - ? join(runtimeDir, 'better-auth-mysql.mjs') - : join(runtimeDir, 'better-auth.mjs'), + ? join(authRuntimeDir, 'better-auth-mysql.mjs') + : join(authRuntimeDir, 'better-auth-d1.mjs'), authConfigPath, authDatabasePath: join(outDir, 'better-auth-db.ts'), authSchemaPath: join(outDir, 'better-auth-schema.ts'), @@ -431,7 +431,7 @@ export function routingPlugin( if (config.plugins.some((plugin) => plugin.name === 'void-solid:pages')) { return explicitAuthClientPaths.solid; } - return join(runtimeDir, 'auth-client.mjs'); + return join(authRuntimeDir, 'client.mjs'); } function getClientAuthPath(id: string): string { diff --git a/packages/void/src/prerender.ts b/packages/void/src/prerender.ts index 8c2fcccc4..96a698cf0 100644 --- a/packages/void/src/prerender.ts +++ b/packages/void/src/prerender.ts @@ -17,7 +17,7 @@ import { type PrerenderResult, } from './prerender-render.ts'; export type { PrerenderResult } from './prerender-render.ts'; -import { renderDefaultErrorPage } from './runtime/error-pages/index.ts'; +import { renderDefaultErrorPage } from './runtime/routing/error-pages/index.ts'; import { scopedAccessCredentials } from './shared/cf-access.ts'; import { collectFiles } from './shared/collect-files.ts'; import { stripInternalEnvKeys } from './shared/env.ts'; diff --git a/packages/void/src/router/compile.ts b/packages/void/src/router/compile.ts index 1391d7377..86546bbd0 100644 --- a/packages/void/src/router/compile.ts +++ b/packages/void/src/router/compile.ts @@ -9,8 +9,8 @@ import { resolveLayoutIds } from '../pages/layout-resolution.ts'; import { patternToRegex } from '../pages/manifest.ts'; import { cloudflareQueueName, type CloudflareQueueNames } from '../queues/cloudflare-names.ts'; import { generateQueueResolverSource } from '../queues/dispatch.ts'; -import { INTERNAL_BINDING_EXACT_NAMES, INTERNAL_BINDING_PREFIXES } from '../runtime/env-raw.ts'; -import { ASSET_EXTENSIONS } from '../runtime/routing-assets.ts'; +import { INTERNAL_BINDING_EXACT_NAMES, INTERNAL_BINDING_PREFIXES } from '../runtime/env/raw.ts'; +import { ASSET_EXTENSIONS } from '../runtime/routing/assets.ts'; import { DEFAULT_SANDBOX_CLASS_NAME } from '../sandbox/config.ts'; import type { ScanResult } from './scan.ts'; diff --git a/packages/void/src/router/email.ts b/packages/void/src/router/email.ts index 528a3fc81..de0d8ecda 100644 --- a/packages/void/src/router/email.ts +++ b/packages/void/src/router/email.ts @@ -28,22 +28,14 @@ import { join } from 'pathslash'; import { globSync } from 'tinyglobby'; +import { + compareEmailRoutes, + compileEmailPattern, + type CompiledEmailPattern, +} from '../shared/email-pattern.ts'; const EMAIL_EXTENSIONS = ['ts', 'mts', 'js', 'mjs']; -/** Token identifies a single segment of the local-part pattern (before/after the `+`). */ -type Segment = { kind: 'literal'; value: string } | { kind: 'param'; name: string }; - -export type EmailPatternKind = 'static' | 'static-tag' | 'dynamic' | 'dynamic-tag'; - -export interface CompiledEmailPattern { - kind: EmailPatternKind; - /** Regex source (anchored). Apply with the `i` flag; see the file header. */ - regexSource: string; - /** Capture-group names in order; empty for `static`. */ - paramNames: Array; -} - export interface EmailHandlerDefinition { /** Original basename without extension, e.g. "support" or "support+[ticket]". */ address: string; @@ -60,133 +52,6 @@ export interface EmailHandlersScan { defaultHandler?: string; } -const PARAM_RE = /^\[([a-z][a-z0-9]*)\]$/; -const LITERAL_RE = /^[a-z0-9._-]+$/; - -function compileSegment(part: string): Segment | null { - const param = PARAM_RE.exec(part); - if (param) { - return { kind: 'param', name: param[1] }; - } - if (!LITERAL_RE.test(part)) { - return null; - } - return { kind: 'literal', value: part }; -} - -function escapeLiteral(value: string): string { - // Of the allowed literal chars `[a-z0-9._-]`, only `.` is regex-meaningful. - return value.replace(/\./g, '\\.'); -} - -function segmentRegex(s: Segment): string { - return s.kind === 'literal' ? escapeLiteral(s.value) : '([^+@]+)'; -} - -function patternKind(prefix: Segment, tag?: Segment): EmailPatternKind { - const prefixDynamic = prefix.kind === 'param'; - if (tag) { - return prefixDynamic ? 'dynamic-tag' : 'static-tag'; - } - return prefixDynamic ? 'dynamic' : 'static'; -} - -/** - * Compile a basename like `support`, `support+[ticket]`, `[user]`, or - * `[user]+[tag]` into a match pattern, or return `null` if the basename - * uses characters or shapes outside the supported grammar. - */ -export function compileEmailPattern(basename: string): CompiledEmailPattern | null { - const lower = basename.toLowerCase(); - // We allow at most one `+` separator (subaddress tag). Anything else is invalid. - const parts = lower.split('+'); - if (parts.length > 2) { - return null; - } - const prefix = compileSegment(parts[0] ?? ''); - if (!prefix) { - return null; - } - let tag: Segment | undefined; - if (parts.length === 2) { - const compiled = compileSegment(parts[1] ?? ''); - if (!compiled) { - return null; - } - tag = compiled; - } - - const paramNames: Array = []; - if (prefix.kind === 'param') { - paramNames.push(prefix.name); - } - if (tag?.kind === 'param') { - paramNames.push(tag.name); - } - if (new Set(paramNames).size !== paramNames.length) { - const dupes = paramNames.filter((n, i) => paramNames.indexOf(n) !== i); - throw new Error( - `email handler "${basename}" has duplicate param names: ${dupes.join(', ')}. Each [name] segment must be unique within a single handler filename.`, - ); - } - - const segments: Array = [segmentRegex(prefix)]; - if (tag) { - segments.push('\\+', segmentRegex(tag)); - } - return { - kind: patternKind(prefix, tag), - regexSource: `^${segments.join('')}$`, - paramNames, - }; -} - -/** - * Kind order: most specific first. static-tag beats static (more - * constraints), dynamic-tag beats dynamic. Matches the precedence list in - * the file header. - */ -const DISPATCH_ORDER: Record = { - 'static-tag': 0, - static: 1, - 'dynamic-tag': 2, - dynamic: 3, -}; - -/** The two fields the dispatch order is computed from. */ -export interface EmailRouteOrderKey { - /** Handler name as written, e.g. "support+[ticket]" (a basename or a harness route key). */ - address: string; - pattern: CompiledEmailPattern; -} - -/** - * The ONE dispatch comparator. The generated `__emailHandler` and the - * `createInboundTestHarness` route table both return on the first pattern - * that matches, so whatever sorts first owns every address it matches. - * - * 1. kind, per `DISPATCH_ORDER` - * 2. fewer captures first — `support+vip` and `support+[tag]` are both - * `static-tag` and both match `support+vip@`; the literal tag must be - * tried first or the exact handler is dead code. Same for - * `[user]+vip` over `[user]+[tag]`. - * 3. alphabetical, so the table is deterministic across filesystems. - * - * Two patterns with the same regex source share a kind and a capture count, - * so the collision check below can still name the alphabetically-first one. - */ -export function compareEmailRoutes(a: EmailRouteOrderKey, b: EmailRouteOrderKey): number { - const kind = DISPATCH_ORDER[a.pattern.kind] - DISPATCH_ORDER[b.pattern.kind]; - if (kind !== 0) { - return kind; - } - const captures = a.pattern.paramNames.length - b.pattern.paramNames.length; - if (captures !== 0) { - return captures; - } - return a.address.localeCompare(b.address); -} - function parseEmailFiles(files: Array): { addresses: Array; defaultHandler?: string; diff --git a/packages/void/src/routes-stub.ts b/packages/void/src/routes-stub.ts index 68c76a2a3..31e5b24f6 100644 --- a/packages/void/src/routes-stub.ts +++ b/packages/void/src/routes-stub.ts @@ -1,4 +1,4 @@ -export { routeUrl } from './runtime/route-url.ts'; +export { routeUrl } from './runtime/routing/route-url.ts'; export type { Href, RoutePath, @@ -8,7 +8,7 @@ export type { RouteDestination, RouteUrl, RouteUrlInput, -} from './runtime/route-url.ts'; +} from './runtime/routing/route-url.ts'; /** Known URL patterns and their parameter names, augmented by .void/routes.d.ts. */ export interface RoutePathMap {} diff --git a/packages/void/src/runtime/ai.ts b/packages/void/src/runtime/ai/index.ts similarity index 98% rename from packages/void/src/runtime/ai.ts rename to packages/void/src/runtime/ai/index.ts index e962de836..a5f07de3b 100644 --- a/packages/void/src/runtime/ai.ts +++ b/packages/void/src/runtime/ai/index.ts @@ -1,13 +1,13 @@ -import { cfAccessHeaders } from '../shared/cf-access.ts'; +import { bytesToBase64 } from '../../shared/base64.ts'; +import { cfAccessHeaders } from '../../shared/cf-access.ts'; +import { getRawRuntimeEnv, type RuntimeEnv } from '../env/raw.ts'; +import { UsageLimit, limitFromResponse } from '../limits/index.ts'; import { PROVIDER_KEY_MAP, type AiProvider, type AiProviderFetchInit, type AiProviderOptions, -} from './ai-types.ts'; -import { bytesToBase64 } from './base64.ts'; -import { getRawRuntimeEnv, type RuntimeEnv } from './env-raw.ts'; -import { UsageLimit, limitFromResponse } from './limits.ts'; +} from './types.ts'; const VOID_FILE_MARKER = '__voidFile'; @@ -725,4 +725,4 @@ export type { AiProviderName, AiProviderOptions, ImageFileInput, -} from './ai-types.ts'; +} from './types.ts'; diff --git a/packages/void/src/runtime/ai-types.ts b/packages/void/src/runtime/ai/types.ts similarity index 100% rename from packages/void/src/runtime/ai-types.ts rename to packages/void/src/runtime/ai/types.ts diff --git a/packages/void/src/runtime/better-auth.ts b/packages/void/src/runtime/auth/better-auth-d1.ts similarity index 91% rename from packages/void/src/runtime/better-auth.ts rename to packages/void/src/runtime/auth/better-auth-d1.ts index 85b9c017c..ae1c71667 100644 --- a/packages/void/src/runtime/better-auth.ts +++ b/packages/void/src/runtime/auth/better-auth-d1.ts @@ -1,10 +1,10 @@ -import type { VoidAuthMigrationSchema } from '../auth/drizzle.ts'; -import { applySqliteAuthMigrations } from './auth-migrations.ts'; +import type { VoidAuthMigrationSchema } from '../../auth/drizzle.ts'; import { createVoidAuthRuntime, type VoidAuthEnv, type VoidAuthRuntimeApi, } from './better-auth-shared.ts'; +import { applySqliteAuthMigrations } from './migrations.ts'; async function applyMigrations( env: VoidAuthEnv, diff --git a/packages/void/src/runtime/better-auth-mysql.ts b/packages/void/src/runtime/auth/better-auth-mysql.ts similarity index 92% rename from packages/void/src/runtime/better-auth-mysql.ts rename to packages/void/src/runtime/auth/better-auth-mysql.ts index adb9a9476..1b998ea1e 100644 --- a/packages/void/src/runtime/better-auth-mysql.ts +++ b/packages/void/src/runtime/auth/better-auth-mysql.ts @@ -1,11 +1,11 @@ -import type { VoidAuthMigrationSchema } from '../auth/drizzle.ts'; -import { applyMySqlAuthMigrations, mysqlMigrationRunner } from './auth-migrations.ts'; +import type { VoidAuthMigrationSchema } from '../../auth/drizzle.ts'; import { createVoidAuthRuntime, resolveConnectionString, type VoidAuthEnv, type VoidAuthRuntimeApi, } from './better-auth-shared.ts'; +import { applyMySqlAuthMigrations, mysqlMigrationRunner } from './migrations.ts'; async function applyMigrations( env: VoidAuthEnv, diff --git a/packages/void/src/runtime/better-auth-pg.ts b/packages/void/src/runtime/auth/better-auth-postgres.ts similarity index 84% rename from packages/void/src/runtime/better-auth-pg.ts rename to packages/void/src/runtime/auth/better-auth-postgres.ts index 6635d366b..958972bce 100644 --- a/packages/void/src/runtime/better-auth-pg.ts +++ b/packages/void/src/runtime/auth/better-auth-postgres.ts @@ -1,12 +1,12 @@ -import type { VoidAuthMigrationSchema } from '../auth/drizzle.ts'; -import { applyPgAuthMigrations, pgMigrationRunner } from './auth-migrations.ts'; +import type { VoidAuthMigrationSchema } from '../../auth/drizzle.ts'; +import { disablePgPassFallback } from '../db/pgpass.ts'; import { createVoidAuthRuntime, resolveConnectionString, type VoidAuthEnv, type VoidAuthRuntimeApi, } from './better-auth-shared.ts'; -import { disablePgPassFallback } from './pg.ts'; +import { applyPgAuthMigrations, pgMigrationRunner } from './migrations.ts'; async function applyMigrations( env: VoidAuthEnv, diff --git a/packages/void/src/runtime/better-auth-shared.ts b/packages/void/src/runtime/auth/better-auth-shared.ts similarity index 99% rename from packages/void/src/runtime/better-auth-shared.ts rename to packages/void/src/runtime/auth/better-auth-shared.ts index 49f86b129..9c7e8fd0a 100644 --- a/packages/void/src/runtime/better-auth-shared.ts +++ b/packages/void/src/runtime/auth/better-auth-shared.ts @@ -2,7 +2,7 @@ import { randomBytes, scrypt, timingSafeEqual } from 'node:crypto'; import { betterAuth, type BetterAuthOptions, type BetterAuthPlugin } from 'better-auth'; import { createAuthMiddleware } from 'better-auth/api'; import type { Context } from 'hono'; -import type { VoidAuthMigrationSchema } from '../auth/drizzle.ts'; +import type { VoidAuthMigrationSchema } from '../../auth/drizzle.ts'; import { VOID_EMAIL_AUTH_PROVIDER, getVoidAuthProviderEnvNames, @@ -10,10 +10,10 @@ import { isVoidSocialAuthProvider, type VoidAuthProvider, type VoidSocialAuthProvider, -} from '../auth/providers.ts'; -import { SHARED_CACHE_HEADERS, authDependentRequests } from './auth-response.ts'; -import { authContext, type AuthState, type VoidAuthConfig } from './auth.ts'; -import { isUnchangedStaticAsset } from './static-asset-marker.ts'; +} from '../../auth/providers.ts'; +import { isUnchangedStaticAsset } from '../routing/static-asset-marker.ts'; +import { authContext, type AuthState, type VoidAuthConfig } from './index.ts'; +import { SHARED_CACHE_HEADERS, authDependentRequests } from './response.ts'; export type VoidAuthDialect = 'sqlite' | 'postgresql' | 'mysql'; diff --git a/packages/void/src/runtime/auth-client-react.ts b/packages/void/src/runtime/auth/client-react.ts similarity index 100% rename from packages/void/src/runtime/auth-client-react.ts rename to packages/void/src/runtime/auth/client-react.ts diff --git a/packages/void/src/runtime/auth-client-solid.ts b/packages/void/src/runtime/auth/client-solid.ts similarity index 100% rename from packages/void/src/runtime/auth-client-solid.ts rename to packages/void/src/runtime/auth/client-solid.ts diff --git a/packages/void/src/runtime/auth-client-svelte.ts b/packages/void/src/runtime/auth/client-svelte.ts similarity index 100% rename from packages/void/src/runtime/auth-client-svelte.ts rename to packages/void/src/runtime/auth/client-svelte.ts diff --git a/packages/void/src/runtime/auth-client-vue.ts b/packages/void/src/runtime/auth/client-vue.ts similarity index 100% rename from packages/void/src/runtime/auth-client-vue.ts rename to packages/void/src/runtime/auth/client-vue.ts diff --git a/packages/void/src/runtime/auth-client.ts b/packages/void/src/runtime/auth/client.ts similarity index 100% rename from packages/void/src/runtime/auth-client.ts rename to packages/void/src/runtime/auth/client.ts diff --git a/packages/void/src/runtime/auth.ts b/packages/void/src/runtime/auth/index.ts similarity index 100% rename from packages/void/src/runtime/auth.ts rename to packages/void/src/runtime/auth/index.ts diff --git a/packages/void/src/runtime/auth-migrations.ts b/packages/void/src/runtime/auth/migrations.ts similarity index 99% rename from packages/void/src/runtime/auth-migrations.ts rename to packages/void/src/runtime/auth/migrations.ts index 345545b92..c44217f14 100644 --- a/packages/void/src/runtime/auth-migrations.ts +++ b/packages/void/src/runtime/auth/migrations.ts @@ -2,7 +2,7 @@ import type { VoidAuthMigrationField, VoidAuthMigrationSchema, VoidAuthMigrationTable, -} from '../auth/drizzle.ts'; +} from '../../auth/drizzle.ts'; export type SqliteMigrationRunner = { all = Record>(sql: string): Promise>; diff --git a/packages/void/src/runtime/auth-response.ts b/packages/void/src/runtime/auth/response.ts similarity index 100% rename from packages/void/src/runtime/auth-response.ts rename to packages/void/src/runtime/auth/response.ts diff --git a/packages/void/src/runtime/client-react.ts b/packages/void/src/runtime/client-react.ts deleted file mode 100644 index 407aceba8..000000000 --- a/packages/void/src/runtime/client-react.ts +++ /dev/null @@ -1,4 +0,0 @@ -export { fetch, FetchError } from './fetch.ts'; -export { fetchStream, StreamError } from './fetch-stream.ts'; -export { auth, createAuthClient } from './auth-client-react.ts'; -export type { AuthSession, AuthState, AuthUser } from './auth.ts'; diff --git a/packages/void/src/runtime/client-solid.ts b/packages/void/src/runtime/client-solid.ts deleted file mode 100644 index 36708dea2..000000000 --- a/packages/void/src/runtime/client-solid.ts +++ /dev/null @@ -1,4 +0,0 @@ -export { fetch, FetchError } from './fetch.ts'; -export { fetchStream, StreamError } from './fetch-stream.ts'; -export { auth, createAuthClient } from './auth-client-solid.ts'; -export type { AuthSession, AuthState, AuthUser } from './auth.ts'; diff --git a/packages/void/src/runtime/client-svelte.ts b/packages/void/src/runtime/client-svelte.ts deleted file mode 100644 index ba1565a42..000000000 --- a/packages/void/src/runtime/client-svelte.ts +++ /dev/null @@ -1,4 +0,0 @@ -export { fetch, FetchError } from './fetch.ts'; -export { fetchStream, StreamError } from './fetch-stream.ts'; -export { auth, createAuthClient } from './auth-client-svelte.ts'; -export type { AuthSession, AuthState, AuthUser } from './auth.ts'; diff --git a/packages/void/src/runtime/client-vue.ts b/packages/void/src/runtime/client-vue.ts deleted file mode 100644 index 88ddc5397..000000000 --- a/packages/void/src/runtime/client-vue.ts +++ /dev/null @@ -1,4 +0,0 @@ -export { fetch, FetchError } from './fetch.ts'; -export { fetchStream, StreamError } from './fetch-stream.ts'; -export { auth, createAuthClient } from './auth-client-vue.ts'; -export type { AuthSession, AuthState, AuthUser } from './auth.ts'; diff --git a/packages/void/src/runtime/client.ts b/packages/void/src/runtime/client.ts deleted file mode 100644 index 7283bc2b2..000000000 --- a/packages/void/src/runtime/client.ts +++ /dev/null @@ -1,4 +0,0 @@ -export { fetch, FetchError } from './fetch.ts'; -export { fetchStream, StreamError } from './fetch-stream.ts'; -export { auth, createAuthClient } from './auth-client.ts'; -export type { AuthSession, AuthState, AuthUser } from './auth.ts'; diff --git a/packages/void/src/runtime/fetch-error.ts b/packages/void/src/runtime/client/fetch-error.ts similarity index 100% rename from packages/void/src/runtime/fetch-error.ts rename to packages/void/src/runtime/client/fetch-error.ts diff --git a/packages/void/src/runtime/fetch-server.ts b/packages/void/src/runtime/client/fetch-server.ts similarity index 100% rename from packages/void/src/runtime/fetch-server.ts rename to packages/void/src/runtime/client/fetch-server.ts diff --git a/packages/void/src/runtime/fetch-stream.ts b/packages/void/src/runtime/client/fetch-stream.ts similarity index 97% rename from packages/void/src/runtime/fetch-stream.ts rename to packages/void/src/runtime/client/fetch-stream.ts index d9473dc80..a01451075 100644 --- a/packages/void/src/runtime/fetch-stream.ts +++ b/packages/void/src/runtime/client/fetch-stream.ts @@ -1,7 +1,7 @@ import { ofetch } from 'ofetch'; +import { asUsageLimit, limitFromResponse } from '../limits/index.ts'; +import { interpolateRouteParams } from '../routing/route-url.ts'; import { FetchError } from './fetch-error.ts'; -import { asUsageLimit, limitFromResponse } from './limits.ts'; -import { interpolateRouteParams } from './route-url.ts'; export { FetchError as StreamError }; import type { RouteMap } from 'void/routes'; diff --git a/packages/void/src/runtime/fetch.ts b/packages/void/src/runtime/client/fetch.ts similarity index 98% rename from packages/void/src/runtime/fetch.ts rename to packages/void/src/runtime/client/fetch.ts index f69872256..9976d8681 100644 --- a/packages/void/src/runtime/fetch.ts +++ b/packages/void/src/runtime/client/fetch.ts @@ -1,6 +1,6 @@ import { createFetch } from 'ofetch'; +import { interpolateRouteParams } from '../routing/route-url.ts'; import { FetchError } from './fetch-error.ts'; -import { interpolateRouteParams } from './route-url.ts'; export { FetchError }; import type { RouteMap } from 'void/routes'; diff --git a/packages/void/src/runtime/client/index.ts b/packages/void/src/runtime/client/index.ts new file mode 100644 index 000000000..c1b191ea9 --- /dev/null +++ b/packages/void/src/runtime/client/index.ts @@ -0,0 +1,4 @@ +export { fetch, FetchError } from './fetch.ts'; +export { fetchStream, StreamError } from './fetch-stream.ts'; +export { auth, createAuthClient } from '../auth/client.ts'; +export type { AuthSession, AuthState, AuthUser } from '../auth/index.ts'; diff --git a/packages/void/src/runtime/client/react.ts b/packages/void/src/runtime/client/react.ts new file mode 100644 index 000000000..08ec47533 --- /dev/null +++ b/packages/void/src/runtime/client/react.ts @@ -0,0 +1,4 @@ +export { fetch, FetchError } from './fetch.ts'; +export { fetchStream, StreamError } from './fetch-stream.ts'; +export { auth, createAuthClient } from '../auth/client-react.ts'; +export type { AuthSession, AuthState, AuthUser } from '../auth/index.ts'; diff --git a/packages/void/src/runtime/client/solid.ts b/packages/void/src/runtime/client/solid.ts new file mode 100644 index 000000000..a5aaf7408 --- /dev/null +++ b/packages/void/src/runtime/client/solid.ts @@ -0,0 +1,4 @@ +export { fetch, FetchError } from './fetch.ts'; +export { fetchStream, StreamError } from './fetch-stream.ts'; +export { auth, createAuthClient } from '../auth/client-solid.ts'; +export type { AuthSession, AuthState, AuthUser } from '../auth/index.ts'; diff --git a/packages/void/src/runtime/client/svelte.ts b/packages/void/src/runtime/client/svelte.ts new file mode 100644 index 000000000..227d8e706 --- /dev/null +++ b/packages/void/src/runtime/client/svelte.ts @@ -0,0 +1,4 @@ +export { fetch, FetchError } from './fetch.ts'; +export { fetchStream, StreamError } from './fetch-stream.ts'; +export { auth, createAuthClient } from '../auth/client-svelte.ts'; +export type { AuthSession, AuthState, AuthUser } from '../auth/index.ts'; diff --git a/packages/void/src/runtime/client/vue.ts b/packages/void/src/runtime/client/vue.ts new file mode 100644 index 000000000..e5d7172a1 --- /dev/null +++ b/packages/void/src/runtime/client/vue.ts @@ -0,0 +1,4 @@ +export { fetch, FetchError } from './fetch.ts'; +export { fetchStream, StreamError } from './fetch-stream.ts'; +export { auth, createAuthClient } from '../auth/client-vue.ts'; +export type { AuthSession, AuthState, AuthUser } from '../auth/index.ts'; diff --git a/packages/void/src/runtime/db.ts b/packages/void/src/runtime/db/index.ts similarity index 96% rename from packages/void/src/runtime/db.ts rename to packages/void/src/runtime/db/index.ts index 1eac98cc0..94e3396f5 100644 --- a/packages/void/src/runtime/db.ts +++ b/packages/void/src/runtime/db/index.ts @@ -6,7 +6,11 @@ * This stub exists for the published npm package and type declarations. */ import { drizzle as _drizzle, type DrizzleD1Database } from 'drizzle-orm/d1'; -import { getRuntimeBinding, getRuntimeRequestResource, requireRuntimeBinding } from './env.ts'; +import { + getRuntimeBinding, + getRuntimeRequestResource, + requireRuntimeBinding, +} from '../env/runtime.ts'; // Re-export commonly used Drizzle utilities so consumers never need // to depend on drizzle-orm directly. diff --git a/packages/void/src/runtime/migration-handler.ts b/packages/void/src/runtime/db/migrations/d1-handler.ts similarity index 99% rename from packages/void/src/runtime/migration-handler.ts rename to packages/void/src/runtime/db/migrations/d1-handler.ts index b12dfc49a..9a0022233 100644 --- a/packages/void/src/runtime/migration-handler.ts +++ b/packages/void/src/runtime/db/migrations/d1-handler.ts @@ -5,7 +5,7 @@ import { isSingleStatement, splitSqlStatements, } from '@void/deploy-core'; -import type { MigrationExecutionPlan, MigrationPlanBundle } from '../migrations/plan.ts'; +import type { MigrationExecutionPlan, MigrationPlanBundle } from '../../../migrations/plan.ts'; export type MigrationEntry = { name: string; diff --git a/packages/void/src/runtime/migration-handler-mysql.ts b/packages/void/src/runtime/db/migrations/mysql-handler.ts similarity index 97% rename from packages/void/src/runtime/migration-handler-mysql.ts rename to packages/void/src/runtime/db/migrations/mysql-handler.ts index a7412eb55..386099375 100644 --- a/packages/void/src/runtime/migration-handler-mysql.ts +++ b/packages/void/src/runtime/db/migrations/mysql-handler.ts @@ -1,11 +1,11 @@ import type { Connection } from 'mysql2/promise'; -import type { MigrationEntry, MigrationResponse, MigrationResult } from './migration-handler.ts'; +import type { MigrationEntry, MigrationResponse, MigrationResult } from './d1-handler.ts'; import { acquireMySqlMigrationLease, holdMySqlMigrationLease, type MySqlMigrationLease, -} from './migration-lock-mysql.ts'; -import { splitMySqlMigrationStatements } from './mysql-migration-sql.ts'; +} from './mysql-lock.ts'; +import { splitMySqlMigrationStatements } from './mysql-sql.ts'; export function createMigrationHandler( env: Record, diff --git a/packages/void/src/runtime/migration-lock-mysql.ts b/packages/void/src/runtime/db/migrations/mysql-lock.ts similarity index 100% rename from packages/void/src/runtime/migration-lock-mysql.ts rename to packages/void/src/runtime/db/migrations/mysql-lock.ts diff --git a/packages/void/src/runtime/mysql-migration-sql.ts b/packages/void/src/runtime/db/migrations/mysql-sql.ts similarity index 98% rename from packages/void/src/runtime/mysql-migration-sql.ts rename to packages/void/src/runtime/db/migrations/mysql-sql.ts index 369f4f01a..4cd250217 100644 --- a/packages/void/src/runtime/mysql-migration-sql.ts +++ b/packages/void/src/runtime/db/migrations/mysql-sql.ts @@ -1,4 +1,4 @@ -import { splitMigrationSql } from './migration-handler.ts'; +import { splitMigrationSql } from './d1-handler.ts'; /** * Splits a MySQL migration file into the statements Void runs one query at a time. Hyperdrive diff --git a/packages/void/src/runtime/migration-handler-pg.ts b/packages/void/src/runtime/db/migrations/postgres-handler.ts similarity index 97% rename from packages/void/src/runtime/migration-handler-pg.ts rename to packages/void/src/runtime/db/migrations/postgres-handler.ts index 888b05813..2528858e7 100644 --- a/packages/void/src/runtime/migration-handler-pg.ts +++ b/packages/void/src/runtime/db/migrations/postgres-handler.ts @@ -1,5 +1,5 @@ -import type { MigrationEntry, MigrationResponse, MigrationResult } from './migration-handler.ts'; -import { disablePgPassFallback } from './pg.ts'; +import { disablePgPassFallback } from '../pgpass.ts'; +import type { MigrationEntry, MigrationResponse, MigrationResult } from './d1-handler.ts'; export function createMigrationHandler( env: Record, diff --git a/packages/void/src/runtime/db-mysql.ts b/packages/void/src/runtime/db/mysql.ts similarity index 100% rename from packages/void/src/runtime/db-mysql.ts rename to packages/void/src/runtime/db/mysql.ts diff --git a/packages/void/src/runtime/pg.ts b/packages/void/src/runtime/db/pgpass.ts similarity index 100% rename from packages/void/src/runtime/pg.ts rename to packages/void/src/runtime/db/pgpass.ts diff --git a/packages/void/src/runtime/db-pg.ts b/packages/void/src/runtime/db/postgres.ts similarity index 100% rename from packages/void/src/runtime/db-pg.ts rename to packages/void/src/runtime/db/postgres.ts diff --git a/packages/void/src/runtime/schema-d1.ts b/packages/void/src/runtime/db/schema/d1.ts similarity index 100% rename from packages/void/src/runtime/schema-d1.ts rename to packages/void/src/runtime/db/schema/d1.ts diff --git a/packages/void/src/runtime/schema-mysql.ts b/packages/void/src/runtime/db/schema/mysql.ts similarity index 100% rename from packages/void/src/runtime/schema-mysql.ts rename to packages/void/src/runtime/db/schema/mysql.ts diff --git a/packages/void/src/runtime/schema-pg.ts b/packages/void/src/runtime/db/schema/postgres.ts similarity index 100% rename from packages/void/src/runtime/schema-pg.ts rename to packages/void/src/runtime/db/schema/postgres.ts diff --git a/packages/void/src/runtime/seed.ts b/packages/void/src/runtime/db/seed.ts similarity index 100% rename from packages/void/src/runtime/seed.ts rename to packages/void/src/runtime/db/seed.ts diff --git a/packages/void/src/runtime/drizzle-arktype.ts b/packages/void/src/runtime/db/validators/drizzle-arktype.ts similarity index 100% rename from packages/void/src/runtime/drizzle-arktype.ts rename to packages/void/src/runtime/db/validators/drizzle-arktype.ts diff --git a/packages/void/src/runtime/drizzle-valibot.ts b/packages/void/src/runtime/db/validators/drizzle-valibot.ts similarity index 100% rename from packages/void/src/runtime/drizzle-valibot.ts rename to packages/void/src/runtime/db/validators/drizzle-valibot.ts diff --git a/packages/void/src/runtime/drizzle-zod.ts b/packages/void/src/runtime/db/validators/drizzle-zod.ts similarity index 100% rename from packages/void/src/runtime/drizzle-zod.ts rename to packages/void/src/runtime/db/validators/drizzle-zod.ts diff --git a/packages/void/src/runtime/durable.ts b/packages/void/src/runtime/durable/index.ts similarity index 98% rename from packages/void/src/runtime/durable.ts rename to packages/void/src/runtime/durable/index.ts index ad1a4dd46..c96146d25 100644 --- a/packages/void/src/runtime/durable.ts +++ b/packages/void/src/runtime/durable/index.ts @@ -1,6 +1,6 @@ import { DurableObject as CloudflareDurableObject } from 'cloudflare:workers'; -import { isResourceName } from '../shared/resource-name.ts'; -import { requireRuntimeBinding, withRuntimeEnv } from './env.ts'; +import { isResourceName } from '../../shared/resource-name.ts'; +import { requireRuntimeBinding, withRuntimeEnv } from '../env/runtime.ts'; const DEFAULT_STORAGE_KEY = '__void_durable_state'; diff --git a/packages/void/src/runtime/email/dev-inbox.ts b/packages/void/src/runtime/email/dev-inbox.ts index 2e7699c7b..9fed0fc1a 100644 --- a/packages/void/src/runtime/email/dev-inbox.ts +++ b/packages/void/src/runtime/email/dev-inbox.ts @@ -6,7 +6,7 @@ * isolate, such as `createEmailTestHarness`. */ -import { base64ToBytes, bytesToBase64 } from '../base64.ts'; +import { base64ToBytes, bytesToBase64 } from '../../shared/base64.ts'; import { MAX_MESSAGE_BYTES, newId } from './mime.ts'; import type { NormalizedEmail, NormalizedAttachment } from './types.ts'; diff --git a/packages/void/src/runtime/email/inbound.ts b/packages/void/src/runtime/email/inbound.ts index 7ba01e25b..8ad76c5b9 100644 --- a/packages/void/src/runtime/email/inbound.ts +++ b/packages/void/src/runtime/email/inbound.ts @@ -12,9 +12,8 @@ import { type EmailWireAction, } from '@void/platform/email-protocol'; import type { Email as PostalMimeEmail } from 'postal-mime'; -import { base64ToBytes } from '../base64.ts'; -import { withTimeout } from '../email-protocol.ts'; -import { getRawRuntimeEnv } from '../env-raw.ts'; +import { base64ToBytes } from '../../shared/base64.ts'; +import { getRawRuntimeEnv } from '../env/raw.ts'; import { buildMime, MAX_ADDRESS_LENGTH, @@ -22,6 +21,7 @@ import { normalizeEmail, validateAddressParts, } from './mime.ts'; +import { withTimeout } from './protocol.ts'; import { fitsHeaderLine, replyReferences, threadingId } from './threading.ts'; import type { Address, Attachment } from './types.ts'; diff --git a/packages/void/src/runtime/email.ts b/packages/void/src/runtime/email/index.ts similarity index 98% rename from packages/void/src/runtime/email.ts rename to packages/void/src/runtime/email/index.ts index 2d066a300..50d55fede 100644 --- a/packages/void/src/runtime/email.ts +++ b/packages/void/src/runtime/email/index.ts @@ -5,8 +5,7 @@ // project policy and quotas. import { isRecord } from '@void/deploy-core'; -import { bytesToBase64 } from './base64.ts'; -import { readBoundedJson, withTimeout } from './email-protocol.ts'; +import { bytesToBase64 } from '../../shared/base64.ts'; import { captureMessage, DEV_INBOX_ACK_HEADER, @@ -19,14 +18,15 @@ import { hasActiveSink, serializeCapturedMessage, type CapturedMessage, -} from './email/dev-inbox.ts'; +} from './dev-inbox.ts'; import { bytesToReadableStream, readEnvString, readProjectSlug, tryGetRawRuntimeEnv, -} from './email/inbound.ts'; -import { buildMime, MimeError, newId, normalizeEmail } from './email/mime.ts'; +} from './inbound.ts'; +import { buildMime, MimeError, newId, normalizeEmail } from './mime.ts'; +import { readBoundedJson, withTimeout } from './protocol.ts'; import type { EmailDeliveryState, NormalizedEmail, @@ -36,7 +36,7 @@ import type { SendEmailOptions, SendEmailRecipientResult, SendEmailResult, -} from './email/types.ts'; +} from './types.ts'; export type { Address, @@ -49,7 +49,7 @@ export type { SendEmailOptions, SendEmailRecipientResult, SendEmailResult, -} from './email/types.ts'; +} from './types.ts'; export { createMessageProxy, @@ -59,7 +59,7 @@ export { parseEmail, ParseEmailError, replyEmail, -} from './email/inbound.ts'; +} from './inbound.ts'; export type { EmailAction, EmailEnvelope, @@ -69,11 +69,11 @@ export type { ParsedEmail, ParseEmailErrorCode, ReplyEmailOptions, -} from './email/inbound.ts'; +} from './inbound.ts'; // `createEmail` throws `MimeError`; export it with the functions that throw it. -export { MimeError } from './email/mime.ts'; -export type { MimeErrorCode } from './email/mime.ts'; +export { MimeError } from './mime.ts'; +export type { MimeErrorCode } from './mime.ts'; function makeError(code: SendEmailErrorCode, message: string, cause?: unknown): SendEmailError { return cause === undefined ? { code, message } : { code, message, cause }; diff --git a/packages/void/src/runtime/email/mime.ts b/packages/void/src/runtime/email/mime.ts index ec924df74..269e4fca1 100644 --- a/packages/void/src/runtime/email/mime.ts +++ b/packages/void/src/runtime/email/mime.ts @@ -7,7 +7,7 @@ */ import { validate as isValidEmailSyntax } from 'email-validator'; -import { bytesToBase64 } from '../base64.ts'; +import { bytesToBase64 } from '../../shared/base64.ts'; import { indexOfControl, threadingId, threadingReferences, trimFws } from './threading.ts'; import type { Address, diff --git a/packages/void/src/runtime/email-protocol.ts b/packages/void/src/runtime/email/protocol.ts similarity index 100% rename from packages/void/src/runtime/email-protocol.ts rename to packages/void/src/runtime/email/protocol.ts diff --git a/packages/void/src/runtime/email/testing.ts b/packages/void/src/runtime/email/testing.ts index 2131e45a7..e58321683 100644 --- a/packages/void/src/runtime/email/testing.ts +++ b/packages/void/src/runtime/email/testing.ts @@ -33,7 +33,7 @@ import { compareEmailRoutes, compileEmailPattern, type CompiledEmailPattern, -} from '../../router/email.ts'; +} from '../../shared/email-pattern.ts'; import { registerEmailSink, type CapturedMessage } from './dev-inbox.ts'; import { createMessageProxy, diff --git a/packages/void/src/runtime/env-helpers.ts b/packages/void/src/runtime/env/helpers.ts similarity index 98% rename from packages/void/src/runtime/env-helpers.ts rename to packages/void/src/runtime/env/helpers.ts index c3d3474c3..d30d09f25 100644 --- a/packages/void/src/runtime/env-helpers.ts +++ b/packages/void/src/runtime/env/helpers.ts @@ -8,7 +8,7 @@ * Every helper returns a fluent builder with `.optional()` and * `.default(value)` modifiers. */ -import type { StandardSchemaV1 } from '../standard-schema.ts'; +import type { StandardSchemaV1 } from '../../standard-schema.ts'; type ParseResult = { ok: true; diff --git a/packages/void/src/runtime/env-public-client.ts b/packages/void/src/runtime/env/public-client.ts similarity index 98% rename from packages/void/src/runtime/env-public-client.ts rename to packages/void/src/runtime/env/public-client.ts index 8ce23da24..ed4ef81a3 100644 --- a/packages/void/src/runtime/env-public-client.ts +++ b/packages/void/src/runtime/env/public-client.ts @@ -85,4 +85,4 @@ export class EnvValidationError extends Error { } } -export { string, number, boolean, url, email, oneOf, json, type EnvSchema } from './env-helpers.ts'; +export { string, number, boolean, url, email, oneOf, json, type EnvSchema } from './helpers.ts'; diff --git a/packages/void/src/runtime/env-public.ts b/packages/void/src/runtime/env/public.ts similarity index 97% rename from packages/void/src/runtime/env-public.ts rename to packages/void/src/runtime/env/public.ts index 1326a96ee..83c796502 100644 --- a/packages/void/src/runtime/env-public.ts +++ b/packages/void/src/runtime/env/public.ts @@ -28,11 +28,11 @@ */ /// -import { isUnmaskActive, redactMessage } from '../shared/env-mask.ts'; -import { ENV_REGISTRY_KEY } from '../shared/env-registry.ts'; -import type { StandardSchemaV1 } from '../standard-schema.ts'; -import { getRawRuntimeEnv, type RuntimeEnv } from './env-raw.ts'; -import { getRuntimeEnv, isInternalBinding } from './env.ts'; +import { isUnmaskActive, redactMessage } from '../../shared/env-mask.ts'; +import { ENV_REGISTRY_KEY } from '../../shared/env-registry.ts'; +import type { StandardSchemaV1 } from '../../standard-schema.ts'; +import { getRawRuntimeEnv, type RuntimeEnv } from './raw.ts'; +import { getRuntimeEnv, isInternalBinding } from './runtime.ts'; type AnyValidator = StandardSchemaV1; type AnySchema = Record; @@ -545,7 +545,7 @@ export async function validateAllEnv( return report; } -export { string, number, boolean, url, email, oneOf, json, type EnvSchema } from './env-helpers.ts'; +export { string, number, boolean, url, email, oneOf, json, type EnvSchema } from './helpers.ts'; // Ambient Cloudflare.Env declarations so user tsconfigs that include // `types: ["void/env"]` expose D1/KV/R2 globals plus the auto-inferred Void @@ -557,7 +557,7 @@ declare global { KV: KVNamespace; STORAGE: R2Bucket; AI: Ai; - SANDBOX: DurableObjectNamespace; + SANDBOX: DurableObjectNamespace; ASSETS: Fetcher; /** @internal Service binding to proxy worker (AI, revalidation, future features) */ __VOID_PROXY?: Fetcher; diff --git a/packages/void/src/runtime/env-raw.ts b/packages/void/src/runtime/env/raw.ts similarity index 100% rename from packages/void/src/runtime/env-raw.ts rename to packages/void/src/runtime/env/raw.ts diff --git a/packages/void/src/runtime/env.ts b/packages/void/src/runtime/env/runtime.ts similarity index 99% rename from packages/void/src/runtime/env.ts rename to packages/void/src/runtime/env/runtime.ts index 5e553bbca..f0b549095 100644 --- a/packages/void/src/runtime/env.ts +++ b/packages/void/src/runtime/env/runtime.ts @@ -14,7 +14,7 @@ import { INTERNAL_BINDING_PREFIXES, isIsrActive, type RuntimeEnv, -} from './env-raw.ts'; +} from './raw.ts'; export type { RuntimeEnv }; diff --git a/packages/void/src/runtime/handler-composition.ts b/packages/void/src/runtime/handler/composition.ts similarity index 97% rename from packages/void/src/runtime/handler-composition.ts rename to packages/void/src/runtime/handler/composition.ts index 9ce206aef..916673e43 100644 --- a/packages/void/src/runtime/handler-composition.ts +++ b/packages/void/src/runtime/handler/composition.ts @@ -1,7 +1,7 @@ // Internal: not part of the package exports. `defineHandler(middleware..., leaf)` // records its middleware and leaf here so page loaders and actions can build the // page response inside the middleware chain, as route handlers do. -import type { CloudContext } from './handler.ts'; +import type { CloudContext } from './index.ts'; type Middleware = (c: CloudContext, next: () => Promise) => unknown; type Leaf = (c: CloudContext) => unknown; diff --git a/packages/void/src/runtime/handler.ts b/packages/void/src/runtime/handler/index.ts similarity index 96% rename from packages/void/src/runtime/handler.ts rename to packages/void/src/runtime/handler/index.ts index 978eda88b..46a33d497 100644 --- a/packages/void/src/runtime/handler.ts +++ b/packages/void/src/runtime/handler/index.ts @@ -1,13 +1,13 @@ import type { Context, Env, MiddlewareHandler, Next, TypedResponse } from 'hono'; import type { RedirectStatusCode } from 'hono/utils/http-status'; import type { RewriteDestination, RouteDestination, RouteUrl, RouteUrlInput } from 'void/routes'; -import type { HeadConfig, HeadDescriptor } from '../pages/head.ts'; -import type { AuthSession, AuthUser } from './auth.ts'; -import { base64ToBytes } from './base64.ts'; -import { executeComposedHandler, setHandlerComposition } from './handler-composition.ts'; +import type { HeadConfig, HeadDescriptor } from '../../pages/head.ts'; +import { base64ToBytes } from '../../shared/base64.ts'; +import type { AuthSession, AuthUser } from '../auth/index.ts'; +import type { TypedRoutes } from '../routing/route-url.ts'; +import type { AssetBinding } from '../routing/worker.ts'; +import { executeComposedHandler, setHandlerComposition } from './composition.ts'; import { convertReturnValue } from './response.ts'; -import type { TypedRoutes } from './route-url.ts'; -import type { AssetBinding } from './routing-worker.ts'; import { runValidation, type ValidatorSlots, type HandlerInput } from './validator.ts'; /** @@ -62,7 +62,7 @@ export interface CloudBindings extends VoidGeneratedEnvBindings { KV: KVNamespace; STORAGE: R2Bucket; AI: Ai; - SANDBOX: DurableObjectNamespace; + SANDBOX: DurableObjectNamespace; /** Node, Bun and Deno targets serve static files through a provider that takes only a `Request`. */ ASSETS: AssetBinding; [key: string]: unknown; @@ -512,6 +512,6 @@ export function defineQueue(handler: QueueFn): TypedQueueHandler } export type { ValidatorSlots, HandlerInput } from './validator.ts'; -export { ValidationError } from '../pages/validation-error.ts'; -export { defer } from '../pages/defer.ts'; -export type { Deferred, InferProps } from '../pages/defer.ts'; +export { ValidationError } from '../../pages/validation-error.ts'; +export { defer } from '../../pages/defer.ts'; +export type { Deferred, InferProps } from '../../pages/defer.ts'; diff --git a/packages/void/src/runtime/response.ts b/packages/void/src/runtime/handler/response.ts similarity index 100% rename from packages/void/src/runtime/response.ts rename to packages/void/src/runtime/handler/response.ts diff --git a/packages/void/src/runtime/validator.ts b/packages/void/src/runtime/handler/validator.ts similarity index 98% rename from packages/void/src/runtime/validator.ts rename to packages/void/src/runtime/handler/validator.ts index 87b1f60a8..1b515568f 100644 --- a/packages/void/src/runtime/validator.ts +++ b/packages/void/src/runtime/handler/validator.ts @@ -1,5 +1,5 @@ -import type { StandardSchemaV1 } from '../standard-schema.ts'; -import type { CloudContext } from './handler.ts'; +import type { StandardSchemaV1 } from '../../standard-schema.ts'; +import type { CloudContext } from './index.ts'; export type ValidatorSlots = { body?: StandardSchemaV1; diff --git a/packages/void/src/runtime/isr.ts b/packages/void/src/runtime/isr/index.ts similarity index 98% rename from packages/void/src/runtime/isr.ts rename to packages/void/src/runtime/isr/index.ts index 1c7385216..6e39bbc16 100644 --- a/packages/void/src/runtime/isr.ts +++ b/packages/void/src/runtime/isr/index.ts @@ -7,7 +7,7 @@ import { listIsrHosts, } from '@void/isr/runtime'; import type { RouteUrl } from 'void/routes'; -import { getRawRuntimeEnv } from './env-raw.ts'; +import { getRawRuntimeEnv } from '../env/raw.ts'; export type RevalidateOptions = { /** Paths to purge. Checked against the app's routes when `routing.typedRoutes` is on. */ diff --git a/packages/void/src/runtime/kv.ts b/packages/void/src/runtime/kv/index.ts similarity index 98% rename from packages/void/src/runtime/kv.ts rename to packages/void/src/runtime/kv/index.ts index 7d3a44a10..ae8f1a37f 100644 --- a/packages/void/src/runtime/kv.ts +++ b/packages/void/src/runtime/kv/index.ts @@ -168,7 +168,7 @@ export function createKV(namespace: KVNamespace): KVClient { return createKVClient(() => namespace); } -import { requireRuntimeBinding } from './env.ts'; +import { requireRuntimeBinding } from '../env/runtime.ts'; /** Default KV client — resolves `KV` from the active runtime environment. */ export const kv: KVClient = createKVClient(() => requireRuntimeBinding('KV')); diff --git a/packages/void/src/runtime/limits.ts b/packages/void/src/runtime/limits/index.ts similarity index 100% rename from packages/void/src/runtime/limits.ts rename to packages/void/src/runtime/limits/index.ts diff --git a/packages/void/src/runtime/live-client.ts b/packages/void/src/runtime/live/client.ts similarity index 99% rename from packages/void/src/runtime/live-client.ts rename to packages/void/src/runtime/live/client.ts index 6b08d637c..42690269e 100644 --- a/packages/void/src/runtime/live-client.ts +++ b/packages/void/src/runtime/live/client.ts @@ -1,5 +1,5 @@ -import type { LiveClientEvent, LiveControlOperation, LiveControlResponse } from './live.ts'; -import type { RequestUrl } from './route-url.ts'; +import type { RequestUrl } from '../routing/route-url.ts'; +import type { LiveClientEvent, LiveControlOperation, LiveControlResponse } from './index.ts'; export type LiveSubscribeOptions = { id: string; diff --git a/packages/void/src/runtime/live.ts b/packages/void/src/runtime/live/index.ts similarity index 98% rename from packages/void/src/runtime/live.ts rename to packages/void/src/runtime/live/index.ts index e6f8b076c..849b30ee3 100644 --- a/packages/void/src/runtime/live.ts +++ b/packages/void/src/runtime/live/index.ts @@ -1,12 +1,7 @@ -import { getUser, type AuthUser } from './auth.ts'; -import { getRawRuntimeEnv } from './env-raw.ts'; -import type { CloudContext, CloudEnv } from './handler.ts'; -import { - connectionInstanceName, - internalUrl, - topicDigest, - topicInstanceName, -} from './live-names.ts'; +import { getUser, type AuthUser } from '../auth/index.ts'; +import { getRawRuntimeEnv } from '../env/raw.ts'; +import type { CloudContext, CloudEnv } from '../handler/index.ts'; +import { connectionInstanceName, internalUrl, topicDigest, topicInstanceName } from './names.ts'; type MaybePromise = T | Promise; diff --git a/packages/void/src/runtime/live-names.ts b/packages/void/src/runtime/live/names.ts similarity index 92% rename from packages/void/src/runtime/live-names.ts rename to packages/void/src/runtime/live/names.ts index 7cb307e89..99cb802aa 100644 --- a/packages/void/src/runtime/live-names.ts +++ b/packages/void/src/runtime/live/names.ts @@ -1,4 +1,4 @@ -import { bytesToBase64 } from './base64.ts'; +import { bytesToBase64 } from '../../shared/base64.ts'; export async function topicDigest(streamId: string, topic: string): Promise { const bytes = new TextEncoder().encode(`${streamId}\u0000${topic}`); diff --git a/packages/void/src/runtime/live-server.ts b/packages/void/src/runtime/live/server.ts similarity index 99% rename from packages/void/src/runtime/live-server.ts rename to packages/void/src/runtime/live/server.ts index f42e4a196..c007c885d 100644 --- a/packages/void/src/runtime/live-server.ts +++ b/packages/void/src/runtime/live/server.ts @@ -1,9 +1,4 @@ -import { - connectionInstanceName, - internalUrl, - topicDigest, - topicInstanceName, -} from './live-names.ts'; +import { eventStream, type SseStream } from '../sse/index.ts'; import { __getLiveBindingName, type LiveClientEvent, @@ -12,8 +7,8 @@ import { type LiveControlOperationResult, type LiveControlResponse, type LiveLimits, -} from './live.ts'; -import { eventStream, type SseStream } from './sse.ts'; +} from './index.ts'; +import { connectionInstanceName, internalUrl, topicDigest, topicInstanceName } from './names.ts'; type LiveDurableObjectEnv = Record; diff --git a/packages/void/src/runtime/log.ts b/packages/void/src/runtime/log/index.ts similarity index 100% rename from packages/void/src/runtime/log.ts rename to packages/void/src/runtime/log/index.ts diff --git a/packages/void/src/runtime/queues.ts b/packages/void/src/runtime/queues/index.ts similarity index 88% rename from packages/void/src/runtime/queues.ts rename to packages/void/src/runtime/queues/index.ts index a3634f085..54558be6a 100644 --- a/packages/void/src/runtime/queues.ts +++ b/packages/void/src/runtime/queues/index.ts @@ -1,7 +1,7 @@ /** Stub interface augmented by generated .void/queues.d.ts */ export interface QueueMap {} -import { requireRuntimeBinding } from './env.ts'; +import { requireRuntimeBinding } from '../env/runtime.ts'; /** Typed queue producers — resolves `QUEUE_*` bindings from the active runtime environment. */ export const queues: QueueMap = new Proxy({} as QueueMap, { diff --git a/packages/void/src/runtime/remote/binding-handler.ts b/packages/void/src/runtime/remote/binding-handler.ts index 48c2c4c4e..bc6c71771 100644 --- a/packages/void/src/runtime/remote/binding-handler.ts +++ b/packages/void/src/runtime/remote/binding-handler.ts @@ -1,5 +1,5 @@ import { Hono, type Context } from 'hono'; -import { base64ToBytes } from '../base64.ts'; +import { base64ToBytes } from '../../shared/base64.ts'; import { R2_OBJECT_HEADER, parseR2Conditional, parseR2HttpMetadata } from './r2-conditions.ts'; type BindingRequest = { binding: string }; diff --git a/packages/void/src/runtime/remote/kv.ts b/packages/void/src/runtime/remote/kv.ts index ef5acbff9..06486d1f5 100644 --- a/packages/void/src/runtime/remote/kv.ts +++ b/packages/void/src/runtime/remote/kv.ts @@ -1,4 +1,4 @@ -import { bytesToBase64 } from '../base64.ts'; +import { bytesToBase64 } from '../../shared/base64.ts'; import type { ProxyClient } from './client.ts'; /** diff --git a/packages/void/src/runtime/remote/r2.ts b/packages/void/src/runtime/remote/r2.ts index 7f26f5a28..974bb1201 100644 --- a/packages/void/src/runtime/remote/r2.ts +++ b/packages/void/src/runtime/remote/r2.ts @@ -1,4 +1,4 @@ -import { bytesToBase64 } from '../base64.ts'; +import { bytesToBase64 } from '../../shared/base64.ts'; import type { ProxyClient } from './client.ts'; import { R2_OBJECT_HEADER, diff --git a/packages/void/src/runtime/routing-assets.ts b/packages/void/src/runtime/routing/assets.ts similarity index 98% rename from packages/void/src/runtime/routing-assets.ts rename to packages/void/src/runtime/routing/assets.ts index 8df6e8dcb..b84c7cdff 100644 --- a/packages/void/src/runtime/routing-assets.ts +++ b/packages/void/src/runtime/routing/assets.ts @@ -1,5 +1,5 @@ -import type { DevCssAsset } from '../pages/types.ts'; -import type { RuntimeEnvironment } from './routing-worker.ts'; +import type { DevCssAsset } from '../../pages/types.ts'; +import type { RuntimeEnvironment } from './worker.ts'; // `c.rewrite()` cannot reach files the asset layer serves. `.html` is excluded: routes may use it. export const ASSET_EXTENSIONS: Array = [ diff --git a/packages/void/src/runtime/error-pages/404.html b/packages/void/src/runtime/routing/error-pages/404.html similarity index 100% rename from packages/void/src/runtime/error-pages/404.html rename to packages/void/src/runtime/routing/error-pages/404.html diff --git a/packages/void/src/runtime/error-pages/500.html b/packages/void/src/runtime/routing/error-pages/500.html similarity index 100% rename from packages/void/src/runtime/error-pages/500.html rename to packages/void/src/runtime/routing/error-pages/500.html diff --git a/packages/void/src/runtime/error-pages/index.ts b/packages/void/src/runtime/routing/error-pages/index.ts similarity index 100% rename from packages/void/src/runtime/error-pages/index.ts rename to packages/void/src/runtime/routing/error-pages/index.ts diff --git a/packages/void/src/runtime/error-pages/inline.ts b/packages/void/src/runtime/routing/error-pages/inline.ts similarity index 100% rename from packages/void/src/runtime/error-pages/inline.ts rename to packages/void/src/runtime/routing/error-pages/inline.ts diff --git a/packages/void/src/runtime/error-pages/script.js b/packages/void/src/runtime/routing/error-pages/script.js similarity index 100% rename from packages/void/src/runtime/error-pages/script.js rename to packages/void/src/runtime/routing/error-pages/script.js diff --git a/packages/void/src/runtime/error-pages/style.css b/packages/void/src/runtime/routing/error-pages/style.css similarity index 100% rename from packages/void/src/runtime/error-pages/style.css rename to packages/void/src/runtime/routing/error-pages/style.css diff --git a/packages/void/src/runtime/routing-errors.ts b/packages/void/src/runtime/routing/errors.ts similarity index 100% rename from packages/void/src/runtime/routing-errors.ts rename to packages/void/src/runtime/routing/errors.ts diff --git a/packages/void/src/runtime/routing.ts b/packages/void/src/runtime/routing/index.ts similarity index 96% rename from packages/void/src/runtime/routing.ts rename to packages/void/src/runtime/routing/index.ts index 49826fe66..0e7791768 100644 --- a/packages/void/src/runtime/routing.ts +++ b/packages/void/src/runtime/routing/index.ts @@ -18,17 +18,17 @@ import { queryKey, searchWithoutActionKey, searchWithoutPreservedQuery, -} from '../pages/action-key.ts'; -import { pagesRedirectResponse } from '../pages/redirect.ts'; -import { SHARED_CACHE_HEADERS, authDependentRequests } from './auth-response.ts'; -import { VoidAssetRewriteError, type CloudContext } from './handler.ts'; -import { convertReturnValue } from './response.ts'; +} from '../../pages/action-key.ts'; +import { pagesRedirectResponse } from '../../pages/redirect.ts'; +import { SHARED_CACHE_HEADERS, authDependentRequests } from '../auth/response.ts'; +import { VoidAssetRewriteError, type CloudContext } from '../handler/index.ts'; +import { convertReturnValue } from '../handler/response.ts'; +import { ASSET_EXTENSIONS } from './assets.ts'; +import { markRouteHandler } from './pages.ts'; import { toUrlString } from './route-url.ts'; -import { ASSET_EXTENSIONS } from './routing-assets.ts'; -import { markRouteHandler } from './routing-pages.ts'; -import { intentionalNotFoundRequests } from './routing-worker.ts'; import { isUnchangedStaticAsset, markStaticAsset } from './static-asset-marker.ts'; -export { createErrorRenderer } from './routing-errors.ts'; +import { intentionalNotFoundRequests } from './worker.ts'; +export { createErrorRenderer } from './errors.ts'; export type RoutingRule = { source: string; @@ -579,7 +579,7 @@ export { createPagesFallback, createNamedActionMarker, markRouteHandler, -} from './routing-pages.ts'; +} from './pages.ts'; export function createModuleLoader(load: () => Promise, cache = true): () => Promise { let module: T | undefined; @@ -598,7 +598,7 @@ export { createWorkerFetch, filterInternalBindings, prerenderPathsResponse, -} from './routing-worker.ts'; -export { createClientAssetTags, createManifestLoader } from './routing-assets.ts'; -export { createSsrFallback, createAssetNotFound } from './routing-pages.ts'; +} from './worker.ts'; +export { createClientAssetTags, createManifestLoader } from './assets.ts'; +export { createSsrFallback, createAssetNotFound } from './pages.ts'; export { buildPrerenderPath } from './prerender-path.ts'; diff --git a/packages/void/src/runtime/routing-pages.ts b/packages/void/src/runtime/routing/pages.ts similarity index 97% rename from packages/void/src/runtime/routing-pages.ts rename to packages/void/src/runtime/routing/pages.ts index 467869d0c..fe77579cb 100644 --- a/packages/void/src/runtime/routing-pages.ts +++ b/packages/void/src/runtime/routing/pages.ts @@ -3,18 +3,22 @@ import { PRESERVED_QUERY_HEADER, markActionKey, searchWithoutPreservedQuery, -} from '../pages/action-key.ts'; +} from '../../pages/action-key.ts'; import { handlesPageLoaderNotFound, ownsLoaderNotFoundBoundary, -} from '../pages/not-found-context.ts'; -import { handlePageGet, handlePageMutation, recoverPageHttpException } from '../pages/protocol.ts'; -import { decodePagePath } from '../pages/url.ts'; -import type { ClientAssetTags } from './routing-assets.ts'; -import type { ErrorRenderer } from './routing-errors.ts'; -import { createAssetCachePolicy } from './routing-worker.ts'; -import type { RoutingRule, RoutingRuntime } from './routing.ts'; +} from '../../pages/not-found-context.ts'; +import { + handlePageGet, + handlePageMutation, + recoverPageHttpException, +} from '../../pages/protocol.ts'; +import { decodePagePath } from '../../pages/url.ts'; +import type { ClientAssetTags } from './assets.ts'; +import type { ErrorRenderer } from './errors.ts'; +import type { RoutingRule, RoutingRuntime } from './index.ts'; import { markStaticAsset } from './static-asset-marker.ts'; +import { createAssetCachePolicy } from './worker.ts'; type PageGetArguments = Parameters; type PageModule = { diff --git a/packages/void/src/runtime/prerender-path.ts b/packages/void/src/runtime/routing/prerender-path.ts similarity index 100% rename from packages/void/src/runtime/prerender-path.ts rename to packages/void/src/runtime/routing/prerender-path.ts diff --git a/packages/void/src/runtime/route-url.ts b/packages/void/src/runtime/routing/route-url.ts similarity index 100% rename from packages/void/src/runtime/route-url.ts rename to packages/void/src/runtime/routing/route-url.ts diff --git a/packages/void/src/runtime/static-asset-marker.ts b/packages/void/src/runtime/routing/static-asset-marker.ts similarity index 100% rename from packages/void/src/runtime/static-asset-marker.ts rename to packages/void/src/runtime/routing/static-asset-marker.ts diff --git a/packages/void/src/runtime/routing-worker.ts b/packages/void/src/runtime/routing/worker.ts similarity index 99% rename from packages/void/src/runtime/routing-worker.ts rename to packages/void/src/runtime/routing/worker.ts index 4b987fc62..35763f5ac 100644 --- a/packages/void/src/runtime/routing-worker.ts +++ b/packages/void/src/runtime/routing/worker.ts @@ -1,6 +1,6 @@ import { redirectToHttps } from '@void/edge'; import type { ExecutionContext } from 'hono'; -import { createManifestLoader, type ManifestLoader } from './routing-assets.ts'; +import { createManifestLoader, type ManifestLoader } from './assets.ts'; // Native Void routing records intentional 404s before Hono wraps HEAD responses. export const intentionalNotFoundRequests: WeakSet = new WeakSet(); diff --git a/packages/void/src/runtime/sandbox-container.ts b/packages/void/src/runtime/sandbox/container.ts similarity index 100% rename from packages/void/src/runtime/sandbox-container.ts rename to packages/void/src/runtime/sandbox/container.ts diff --git a/packages/void/src/runtime/sandbox.ts b/packages/void/src/runtime/sandbox/index.ts similarity index 98% rename from packages/void/src/runtime/sandbox.ts rename to packages/void/src/runtime/sandbox/index.ts index e0502ce58..a12b2c8c3 100644 --- a/packages/void/src/runtime/sandbox.ts +++ b/packages/void/src/runtime/sandbox/index.ts @@ -1,7 +1,7 @@ import type { Files } from '@cloudflare/sandbox'; -import { getRawRuntimeEnv } from './env-raw.ts'; -import { requireRuntimeBinding } from './env.ts'; -import { UsageLimit } from './limits.ts'; +import { getRawRuntimeEnv } from '../env/raw.ts'; +import { requireRuntimeBinding } from '../env/runtime.ts'; +import { UsageLimit } from '../limits/index.ts'; import { SandboxContainer, SANDBOX_PORT_HEADER, @@ -10,7 +10,7 @@ import { type SandboxOptions, type SandboxExecOptions, type SandboxProcessWire, -} from './sandbox-container.ts'; +} from './container.ts'; export * from '@cloudflare/sandbox'; export type { SandboxOptions, SandboxExecOptions }; diff --git a/packages/void/src/runtime/sse-client.ts b/packages/void/src/runtime/sse/client.ts similarity index 98% rename from packages/void/src/runtime/sse-client.ts rename to packages/void/src/runtime/sse/client.ts index cc6d5b461..96be59290 100644 --- a/packages/void/src/runtime/sse-client.ts +++ b/packages/void/src/runtime/sse/client.ts @@ -1,4 +1,4 @@ -import type { RequestUrl } from './route-url.ts'; +import type { RequestUrl } from '../routing/route-url.ts'; export type SseClientEvent = { data: T; diff --git a/packages/void/src/runtime/sse.ts b/packages/void/src/runtime/sse/index.ts similarity index 100% rename from packages/void/src/runtime/sse.ts rename to packages/void/src/runtime/sse/index.ts diff --git a/packages/void/src/runtime/storage.ts b/packages/void/src/runtime/storage/index.ts similarity index 89% rename from packages/void/src/runtime/storage.ts rename to packages/void/src/runtime/storage/index.ts index b0c4d55ca..c9e4b195a 100644 --- a/packages/void/src/runtime/storage.ts +++ b/packages/void/src/runtime/storage/index.ts @@ -3,7 +3,7 @@ export function createStorage(bucket: R2Bucket): R2Bucket { return bucket; } -import { requireRuntimeBinding } from './env.ts'; +import { requireRuntimeBinding } from '../env/runtime.ts'; /** Default storage client — resolves `STORAGE` from the active runtime environment. */ export const storage: R2Bucket = new Proxy({} as R2Bucket, { diff --git a/packages/void/src/runtime/ws.ts b/packages/void/src/runtime/ws/index.ts similarity index 97% rename from packages/void/src/runtime/ws.ts rename to packages/void/src/runtime/ws/index.ts index 7b49086a6..8024ef4f1 100644 --- a/packages/void/src/runtime/ws.ts +++ b/packages/void/src/runtime/ws/index.ts @@ -1,9 +1,9 @@ import type { WebSocketRouteMap } from 'void/routes'; -import { isResourceName } from '../shared/resource-name.ts'; -import type { StandardSchemaV1 } from '../standard-schema.ts'; -import type { AuthUser } from './auth.ts'; -import type { CloudEnv } from './handler.ts'; -import { interpolateRouteParams } from './route-url.ts'; +import { isResourceName } from '../../shared/resource-name.ts'; +import type { StandardSchemaV1 } from '../../standard-schema.ts'; +import type { AuthUser } from '../auth/index.ts'; +import type { CloudEnv } from '../handler/index.ts'; +import { interpolateRouteParams } from '../routing/route-url.ts'; type MaybePromise = T | Promise; type ParamsRecord = Record; diff --git a/packages/void/src/runtime/ws-server.ts b/packages/void/src/runtime/ws/server.ts similarity index 97% rename from packages/void/src/runtime/ws-server.ts rename to packages/void/src/runtime/ws/server.ts index 5c0e73551..6cc107e90 100644 --- a/packages/void/src/runtime/ws-server.ts +++ b/packages/void/src/runtime/ws/server.ts @@ -1,8 +1,8 @@ -import type { StandardSchemaV1 } from '../standard-schema.ts'; -import { authContext, type AuthState, type AuthUser } from './auth.ts'; -import type { VoidAuthEnv, VoidAuthRuntimeOptions } from './better-auth-shared.ts'; -import { withRuntimeEnv } from './env.ts'; -import type { CloudEnv } from './handler.ts'; +import type { StandardSchemaV1 } from '../../standard-schema.ts'; +import type { VoidAuthEnv, VoidAuthRuntimeOptions } from '../auth/better-auth-shared.ts'; +import { authContext, type AuthState, type AuthUser } from '../auth/index.ts'; +import { withRuntimeEnv } from '../env/runtime.ts'; +import type { CloudEnv } from '../handler/index.ts'; import type { AnyWebSocketDefinition, RoomContext, @@ -10,7 +10,7 @@ import type { SocketContext, WebSocketConnection, WebSocketInstanceKey, -} from './ws.ts'; +} from './index.ts'; export type WebSocketRouteMeta = { name?: string; diff --git a/packages/void/src/runtime/base64.ts b/packages/void/src/shared/base64.ts similarity index 100% rename from packages/void/src/runtime/base64.ts rename to packages/void/src/shared/base64.ts diff --git a/packages/void/src/shared/email-pattern.ts b/packages/void/src/shared/email-pattern.ts new file mode 100644 index 000000000..8b92f204b --- /dev/null +++ b/packages/void/src/shared/email-pattern.ts @@ -0,0 +1,145 @@ +/** + * Compile and order inbound email address patterns without filesystem access. + * Match with the `i` flag so captures preserve the recipient's original case. + * Order: static + tag, static, dynamic + tag, then dynamic. + */ + +/** Token identifies a single segment of the local-part pattern (before/after the `+`). */ +type Segment = { kind: 'literal'; value: string } | { kind: 'param'; name: string }; + +export type EmailPatternKind = 'static' | 'static-tag' | 'dynamic' | 'dynamic-tag'; + +export interface CompiledEmailPattern { + kind: EmailPatternKind; + /** Regex source (anchored). Apply with the `i` flag; see the file header. */ + regexSource: string; + /** Capture-group names in order; empty for `static`. */ + paramNames: Array; +} + +const PARAM_RE = /^\[([a-z][a-z0-9]*)\]$/; +const LITERAL_RE = /^[a-z0-9._-]+$/; + +function compileSegment(part: string): Segment | null { + const param = PARAM_RE.exec(part); + if (param) { + return { kind: 'param', name: param[1] }; + } + if (!LITERAL_RE.test(part)) { + return null; + } + return { kind: 'literal', value: part }; +} + +function escapeLiteral(value: string): string { + // Of the allowed literal chars `[a-z0-9._-]`, only `.` is regex-meaningful. + return value.replace(/\./g, '\\.'); +} + +function segmentRegex(s: Segment): string { + return s.kind === 'literal' ? escapeLiteral(s.value) : '([^+@]+)'; +} + +function patternKind(prefix: Segment, tag?: Segment): EmailPatternKind { + const prefixDynamic = prefix.kind === 'param'; + if (tag) { + return prefixDynamic ? 'dynamic-tag' : 'static-tag'; + } + return prefixDynamic ? 'dynamic' : 'static'; +} + +/** + * Compile a basename like `support`, `support+[ticket]`, `[user]`, or + * `[user]+[tag]` into a match pattern, or return `null` if the basename + * uses characters or shapes outside the supported grammar. + */ +export function compileEmailPattern(basename: string): CompiledEmailPattern | null { + const lower = basename.toLowerCase(); + // We allow at most one `+` separator (subaddress tag). Anything else is invalid. + const parts = lower.split('+'); + if (parts.length > 2) { + return null; + } + const prefix = compileSegment(parts[0] ?? ''); + if (!prefix) { + return null; + } + let tag: Segment | undefined; + if (parts.length === 2) { + const compiled = compileSegment(parts[1] ?? ''); + if (!compiled) { + return null; + } + tag = compiled; + } + + const paramNames: Array = []; + if (prefix.kind === 'param') { + paramNames.push(prefix.name); + } + if (tag?.kind === 'param') { + paramNames.push(tag.name); + } + if (new Set(paramNames).size !== paramNames.length) { + const dupes = paramNames.filter((n, i) => paramNames.indexOf(n) !== i); + throw new Error( + `email handler "${basename}" has duplicate param names: ${dupes.join(', ')}. Each [name] segment must be unique within a single handler filename.`, + ); + } + + const segments: Array = [segmentRegex(prefix)]; + if (tag) { + segments.push('\\+', segmentRegex(tag)); + } + return { + kind: patternKind(prefix, tag), + regexSource: `^${segments.join('')}$`, + paramNames, + }; +} + +/** + * Kind order: most specific first. static-tag beats static (more + * constraints), dynamic-tag beats dynamic. Matches the precedence list in + * the file header. + */ +const DISPATCH_ORDER: Record = { + 'static-tag': 0, + static: 1, + 'dynamic-tag': 2, + dynamic: 3, +}; + +/** The two fields the dispatch order is computed from. */ +export interface EmailRouteOrderKey { + /** Handler name as written, e.g. "support+[ticket]" (a basename or a harness route key). */ + address: string; + pattern: CompiledEmailPattern; +} + +/** + * The ONE dispatch comparator. The generated `__emailHandler` and the + * `createInboundTestHarness` route table both return on the first pattern + * that matches, so whatever sorts first owns every address it matches. + * + * 1. kind, per `DISPATCH_ORDER` + * 2. fewer captures first — `support+vip` and `support+[tag]` are both + * `static-tag` and both match `support+vip@`; the literal tag must be + * tried first or the exact handler is dead code. Same for + * `[user]+vip` over `[user]+[tag]`. + * 3. alphabetical, so the table is deterministic across filesystems. + * + * Two patterns with the same regex source share a kind and a capture count, + * so the scanner's collision check can still name the alphabetically-first one. + */ +export function compareEmailRoutes(a: EmailRouteOrderKey, b: EmailRouteOrderKey): number { + const kind = DISPATCH_ORDER[a.pattern.kind] - DISPATCH_ORDER[b.pattern.kind]; + if (kind !== 0) { + return kind; + } + const captures = a.pattern.paramNames.length - b.pattern.paramNames.length; + if (captures !== 0) { + return captures; + } + return a.address.localeCompare(b.address); +} diff --git a/packages/void/test/integration/auth-forwarded-cookies.test.ts b/packages/void/test/integration/auth-forwarded-cookies.test.ts index 4f61a57ce..9e6d3fbcf 100644 --- a/packages/void/test/integration/auth-forwarded-cookies.test.ts +++ b/packages/void/test/integration/auth-forwarded-cookies.test.ts @@ -5,13 +5,13 @@ import { getCookieCache } from 'better-auth/cookies'; import { Hono } from 'hono'; import { describe, expect, it, vi } from 'vite-plus/test'; import { PAGES_PROTOCOL_VERSION } from '../../../edge/src/pages-protocol.ts'; -import { getAuth, getSession, getUser, type VoidAuthConfig } from '../../src/runtime/auth.ts'; import { createVoidAuthRuntime, type VoidAuthRuntimeOptions, -} from '../../src/runtime/better-auth-shared.ts'; -import { createPageMutationHandler } from '../../src/runtime/routing-pages.ts'; -import { createRoutingRuntime, type RoutingContext } from '../../src/runtime/routing.ts'; +} from '../../src/runtime/auth/better-auth-shared.ts'; +import { getAuth, getSession, getUser, type VoidAuthConfig } from '../../src/runtime/auth/index.ts'; +import { createRoutingRuntime, type RoutingContext } from '../../src/runtime/routing/index.ts'; +import { createPageMutationHandler } from '../../src/runtime/routing/pages.ts'; const env = { BETTER_AUTH_SECRET: 'local-test-secret-with-at-least-32-characters' }; const origin = 'https://app.test'; diff --git a/packages/void/test/integration/auth-isr-cache-policy.test.ts b/packages/void/test/integration/auth-isr-cache-policy.test.ts index 3e64edcfb..b89ca8a89 100644 --- a/packages/void/test/integration/auth-isr-cache-policy.test.ts +++ b/packages/void/test/integration/auth-isr-cache-policy.test.ts @@ -3,18 +3,18 @@ import { memoryAdapter } from 'better-auth/adapters/memory'; import { Hono, type NotFoundHandler } from 'hono'; import { etag } from 'hono/etag'; import { describe, expect, it } from 'vite-plus/test'; -import { createVoidAuthRuntime } from '../../src/runtime/better-auth-shared.ts'; -import { createErrorRenderer } from '../../src/runtime/routing-errors.ts'; -import { - createAssetNotFound, - createPagesFallback, - createSsrFallback, -} from '../../src/runtime/routing-pages.ts'; +import { createVoidAuthRuntime } from '../../src/runtime/auth/better-auth-shared.ts'; +import { createErrorRenderer } from '../../src/runtime/routing/errors.ts'; import { createRoutingRuntime, type RoutingContext, type RoutingHeaderRule, -} from '../../src/runtime/routing.ts'; +} from '../../src/runtime/routing/index.ts'; +import { + createAssetNotFound, + createPagesFallback, + createSsrFallback, +} from '../../src/runtime/routing/pages.ts'; const env = { BETTER_AUTH_SECRET: 'local-test-secret-with-at-least-32-characters' }; const options = { dialect: 'sqlite' as const, providers: null }; diff --git a/packages/void/test/integration/auth-rate-limit.test.ts b/packages/void/test/integration/auth-rate-limit.test.ts index fcc07e923..542157f34 100644 --- a/packages/void/test/integration/auth-rate-limit.test.ts +++ b/packages/void/test/integration/auth-rate-limit.test.ts @@ -1,7 +1,7 @@ import { memoryAdapter } from 'better-auth/adapters/memory'; import { Hono } from 'hono'; import { describe, expect, it } from 'vite-plus/test'; -import { createVoidAuthRuntime } from '../../src/runtime/better-auth-shared.ts'; +import { createVoidAuthRuntime } from '../../src/runtime/auth/better-auth-shared.ts'; const env = { BETTER_AUTH_SECRET: 'local-test-secret-with-at-least-32-characters' }; const options = { dialect: 'sqlite' as const, providers: null }; diff --git a/packages/void/test/integration/durable-state-rpc.test.ts b/packages/void/test/integration/durable-state-rpc.test.ts index 9ccd23993..c0ff3f394 100644 --- a/packages/void/test/integration/durable-state-rpc.test.ts +++ b/packages/void/test/integration/durable-state-rpc.test.ts @@ -21,7 +21,7 @@ describe('Durable State through the generated Worker and actual RPC', () => { writeFileSync( definition, ` -import { defineDurableState } from ${JSON.stringify(join(root, 'packages/void/src/runtime/durable.ts'))}; +import { defineDurableState } from ${JSON.stringify(join(root, 'packages/void/src/runtime/durable/index.ts'))}; export default defineDurableState({ initialState: { count: 0 }, fetch(context) { context.state.count += 10; return Response.json(context.state.count); }, @@ -64,7 +64,7 @@ export default { async fetch(request) { writeFileSync( entry, compileWorkerEntry({ - runtimeEnvPath: join(root, 'packages/void/src/runtime/env.ts'), + runtimeEnvPath: join(root, 'packages/void/src/runtime/env/runtime.ts'), durableObjects: [ { bindingName: 'COUNTERS', className: 'CounterState', filePath: definition }, ], diff --git a/packages/void/test/integration/env-cli.test.ts b/packages/void/test/integration/env-cli.test.ts index 2fddff1e7..5882c7a94 100644 --- a/packages/void/test/integration/env-cli.test.ts +++ b/packages/void/test/integration/env-cli.test.ts @@ -7,7 +7,7 @@ import { afterEach, describe, expect, it } from 'vite-plus/test'; const PACKAGE_ROOT = join(import.meta.dirname, '..', '..'); const CLI_ENTRY = join(PACKAGE_ROOT, 'dist', 'cli', 'cli.mjs'); -const ENV_PUBLIC_DIST = join(PACKAGE_ROOT, 'dist', 'runtime', 'env-public.mjs'); +const ENV_PUBLIC_DIST = join(PACKAGE_ROOT, 'dist', 'runtime', 'env/public.mjs'); const roots: Array = []; diff --git a/packages/void/test/integration/env-server-build.test.ts b/packages/void/test/integration/env-server-build.test.ts index 530001050..1e3d98200 100644 --- a/packages/void/test/integration/env-server-build.test.ts +++ b/packages/void/test/integration/env-server-build.test.ts @@ -9,8 +9,8 @@ import { envSchemaPlugin } from '../../src/plugin-env-schema.ts'; const roots: Array = []; const runtime = join(import.meta.dirname, '../../src/runtime'); -const publicEnvUrl = pathToFileURL(join(runtime, 'env-public.ts')).href; -const runtimeEnvUrl = pathToFileURL(join(runtime, 'env.ts')).href; +const publicEnvUrl = pathToFileURL(join(runtime, 'env/public.ts')).href; +const runtimeEnvUrl = pathToFileURL(join(runtime, 'env/runtime.ts')).href; afterEach(() => { vi.unstubAllEnvs(); diff --git a/packages/void/test/integration/error-pages.test.ts b/packages/void/test/integration/error-pages.test.ts index 80da3bded..316d591e7 100644 --- a/packages/void/test/integration/error-pages.test.ts +++ b/packages/void/test/integration/error-pages.test.ts @@ -3,8 +3,8 @@ import { afterAll, beforeAll, describe, expect, it } from 'vite-plus/test'; // Exercise the bundle without loading its global declarations alongside source declarations. const { createErrorRenderer } = (await import( - new URL('../../dist/runtime/routing.mjs', import.meta.url).href -)) as typeof import('../../src/runtime/routing-errors.ts'); + new URL('../../dist/runtime/routing/index.mjs', import.meta.url).href +)) as typeof import('../../src/runtime/routing/errors.ts'); const errors = createErrorRenderer({ projectRoot: '/project', homeDir: '/home' }); let browser: Browser; diff --git a/packages/void/test/integration/jsx-websocket.test.ts b/packages/void/test/integration/jsx-websocket.test.ts index 9ff41da5c..5d1ed82d9 100644 --- a/packages/void/test/integration/jsx-websocket.test.ts +++ b/packages/void/test/integration/jsx-websocket.test.ts @@ -66,7 +66,7 @@ export default ${helper}({ types = generateRouteTypes(scan, join(root, 'routes'), join(root, '.void')).dts; const routeTable = join(root, 'generated-routes.ts'); const worker = join(root, 'generated-worker.ts'); - const runtimeEnvPath = join(repository, 'packages/void/src/runtime/env.ts'); + const runtimeEnvPath = join(repository, 'packages/void/src/runtime/env/runtime.ts'); writeFileSync( routeTable, compileRouteTable( @@ -80,7 +80,7 @@ export default ${helper}({ honoPath: import.meta.resolve('hono'), honoRoutePath: import.meta.resolve('hono/route'), runtimeEnvPath, - webSocketRuntimePath: join(repository, 'packages/void/src/runtime/ws-server.ts'), + webSocketRuntimePath: join(repository, 'packages/void/src/runtime/ws/server.ts'), projectRoot: root, homeDir: root, reactRefresh: false, diff --git a/packages/void/test/integration/native-asset-cache-policy.test.ts b/packages/void/test/integration/native-asset-cache-policy.test.ts index 72b8339f5..0d90c8bc8 100644 --- a/packages/void/test/integration/native-asset-cache-policy.test.ts +++ b/packages/void/test/integration/native-asset-cache-policy.test.ts @@ -193,10 +193,10 @@ beforeAll(async () => { ` import { Hono } from ${JSON.stringify(fileURLToPath(import.meta.resolve('hono')))}; import { compress } from ${JSON.stringify(fileURLToPath(import.meta.resolve('hono/compress')))}; - import { createPagesFallback, createSsrFallback, createAssetNotFound } from ${JSON.stringify(runtimeSource('routing-pages.ts'))}; - import { applyAssetCachePolicy, createAssetFallback } from ${JSON.stringify(runtimeSource('routing-worker.ts'))}; - import { createRoutingRuntime } from ${JSON.stringify(runtimeSource('routing.ts'))}; - import { createErrorRenderer } from ${JSON.stringify(runtimeSource('routing-errors.ts'))}; + import { createPagesFallback, createSsrFallback, createAssetNotFound } from ${JSON.stringify(runtimeSource('routing/pages.ts'))}; + import { applyAssetCachePolicy, createAssetFallback } from ${JSON.stringify(runtimeSource('routing/worker.ts'))}; + import { createRoutingRuntime } from ${JSON.stringify(runtimeSource('routing/index.ts'))}; + import { createErrorRenderer } from ${JSON.stringify(runtimeSource('routing/errors.ts'))}; const apps = {}; for (const mode of ['pages', 'ssr', 'static', 'headers', 'compressed']) { const pages = mode === 'pages' || mode === 'compressed'; diff --git a/packages/void/test/integration/node-target.test.ts b/packages/void/test/integration/node-target.test.ts index b917e2fe0..99c976240 100644 --- a/packages/void/test/integration/node-target.test.ts +++ b/packages/void/test/integration/node-target.test.ts @@ -9,7 +9,7 @@ import { type IsolatedPlayground, } from '../../../../test/integration-helpers.ts'; import { renderPrerenderPaths } from '../../src/prerender-render.ts'; -import { buildPrerenderPath } from '../../src/runtime/prerender-path.ts'; +import { buildPrerenderPath } from '../../src/runtime/routing/prerender-path.ts'; const ROOT = join(import.meta.dirname, '..', '..', '..', '..'); let DEV_BASE: string; diff --git a/packages/void/test/integration/plugin-env-schema.test.ts b/packages/void/test/integration/plugin-env-schema.test.ts index 79fa37027..127b51f27 100644 --- a/packages/void/test/integration/plugin-env-schema.test.ts +++ b/packages/void/test/integration/plugin-env-schema.test.ts @@ -93,8 +93,8 @@ describe('envSchemaPlugin auto-discovery', () => { it.each([undefined, 'Build shell'])( 'folds settled production values after concurrent config hooks (shell: %s)', async (shellValue) => { - const { defineEnv } = await import('../../src/runtime/env-public.ts'); - const { string } = await import('../../src/runtime/env-helpers.ts'); + const { defineEnv } = await import('../../src/runtime/env/public.ts'); + const { string } = await import('../../src/runtime/env/helpers.ts'); const root = createTempRoot(); writeFileSync(join(root, 'env.ts'), 'export default {};\n'); writeFileSync(join(root, '.env'), 'VITE_TITLE=Local only\n'); @@ -193,8 +193,8 @@ describe('envSchemaPlugin auto-discovery', () => { }); it('removes local .env client values from production builds', async () => { - const { defineEnv } = await import('../../src/runtime/env-public.ts'); - const { string } = await import('../../src/runtime/env-helpers.ts'); + const { defineEnv } = await import('../../src/runtime/env/public.ts'); + const { string } = await import('../../src/runtime/env/helpers.ts'); const root = createTempRoot(); writeFileSync(join(root, 'env.ts'), 'export default {};\n'); writeFileSync(join(root, '.env'), 'VITE_TITLE=Local only\n'); @@ -332,8 +332,8 @@ describe('envSchemaPlugin auto-discovery', () => { }); it('reports server and required names without values', async () => { - const { defineEnv } = await import('../../src/runtime/env-public.ts'); - const { string } = await import('../../src/runtime/env-helpers.ts'); + const { defineEnv } = await import('../../src/runtime/env/public.ts'); + const { string } = await import('../../src/runtime/env/helpers.ts'); defineEnv({ API_TOKEN: string(), OPTIONAL_REGION: string().optional(), @@ -357,8 +357,8 @@ describe('envSchemaPlugin auto-discovery', () => { // Register via defineEnv: jiti's env.ts module instance is invisible to Vitest. it('warns when vite `define` shadows a schema env key', async () => { - const { defineEnv } = await import('../../src/runtime/env-public.ts'); - const { string } = await import('../../src/runtime/env-helpers.ts'); + const { defineEnv } = await import('../../src/runtime/env/public.ts'); + const { string } = await import('../../src/runtime/env/helpers.ts'); defineEnv({ STRIPE_KEY: string(), VITE_TITLE: string() }); const root = createTempRoot(); @@ -395,8 +395,8 @@ describe('envSchemaPlugin auto-discovery', () => { }); it('does not warn when define has no overlap with the schema', async () => { - const { defineEnv } = await import('../../src/runtime/env-public.ts'); - const { string } = await import('../../src/runtime/env-helpers.ts'); + const { defineEnv } = await import('../../src/runtime/env/public.ts'); + const { string } = await import('../../src/runtime/env/helpers.ts'); defineEnv({ STRIPE_KEY: string() }); const root = createTempRoot(); @@ -427,8 +427,8 @@ describe('envSchemaPlugin auto-discovery', () => { }); it('adds client-exposed schema defaults to Vite env', async () => { - const { defineEnv } = await import('../../src/runtime/env-public.ts'); - const { number, string } = await import('../../src/runtime/env-helpers.ts'); + const { defineEnv } = await import('../../src/runtime/env/public.ts'); + const { number, string } = await import('../../src/runtime/env/helpers.ts'); const root = createTempRoot(); writeFileSync(join(root, 'env.ts'), 'export default {};\n'); @@ -450,8 +450,8 @@ describe('envSchemaPlugin auto-discovery', () => { }); it('does not overwrite a Vite env value with a schema default', async () => { - const { defineEnv } = await import('../../src/runtime/env-public.ts'); - const { string } = await import('../../src/runtime/env-helpers.ts'); + const { defineEnv } = await import('../../src/runtime/env/public.ts'); + const { string } = await import('../../src/runtime/env/helpers.ts'); const root = createTempRoot(); writeFileSync(join(root, 'env.ts'), 'export default {};\n'); @@ -472,8 +472,8 @@ describe('envSchemaPlugin auto-discovery', () => { }); it('uses VITE_ even when Vite has a custom envPrefix', async () => { - const { defineEnv } = await import('../../src/runtime/env-public.ts'); - const { string } = await import('../../src/runtime/env-helpers.ts'); + const { defineEnv } = await import('../../src/runtime/env/public.ts'); + const { string } = await import('../../src/runtime/env/helpers.ts'); const root = createTempRoot(); writeFileSync(join(root, 'env.ts'), 'export default {};\n'); @@ -508,7 +508,7 @@ describe('envSchemaPlugin reserved __VOID_ names', () => { } afterEach(async () => { - const { defineEnv } = await import('../../src/runtime/env-public.ts'); + const { defineEnv } = await import('../../src/runtime/env/public.ts'); defineEnv({}); }); @@ -565,8 +565,8 @@ describe('envSchemaPlugin reserved __VOID_ names', () => { it.each(['serve', 'build'] as const)( 'rejects a reserved name declared in env.ts (%s)', async (command) => { - const { defineEnv } = await import('../../src/runtime/env-public.ts'); - const { string } = await import('../../src/runtime/env-helpers.ts'); + const { defineEnv } = await import('../../src/runtime/env/public.ts'); + const { string } = await import('../../src/runtime/env/helpers.ts'); const root = createTempRoot(); writeFileSync(join(root, 'env.ts'), 'export default {};\n'); defineEnv({ API_URL: string(), __VOID_X: string().optional() }); @@ -580,7 +580,7 @@ describe('envSchemaPlugin reserved __VOID_ names', () => { describe('envSchemaPlugin with "sideEffects": false', () => { const publicEnvUrl = pathToFileURL( - join(import.meta.dirname, '../../src/runtime/env-public.ts'), + join(import.meta.dirname, '../../src/runtime/env/public.ts'), ).href; /** Build an app that declares no side effects, with an entry that imports env.ts for its side effect. */ diff --git a/packages/void/test/integration/plugin-vite-environment.test.ts b/packages/void/test/integration/plugin-vite-environment.test.ts index 0f85d6540..9abf71fb2 100644 --- a/packages/void/test/integration/plugin-vite-environment.test.ts +++ b/packages/void/test/integration/plugin-vite-environment.test.ts @@ -1266,7 +1266,7 @@ describe('Astro preview', () => { describe('Astro server entry', () => { const entry = '@astrojs/cloudflare/entrypoints/server'; const scopedEntry = '\0void:astro-server-entry'; - const envUrl = new URL('../../src/runtime/env.ts', import.meta.url).href; + const envUrl = new URL('../../src/runtime/env/runtime.ts', import.meta.url).href; type WrapperModule = { named: string; diff --git a/packages/void/test/integration/prepare-cli.test.ts b/packages/void/test/integration/prepare-cli.test.ts index 06180ff43..ec2f018ee 100644 --- a/packages/void/test/integration/prepare-cli.test.ts +++ b/packages/void/test/integration/prepare-cli.test.ts @@ -7,7 +7,7 @@ import { afterEach, describe, expect, it } from 'vite-plus/test'; const PACKAGE_ROOT = join(import.meta.dirname, '..', '..'); const CLI_ENTRY = join(PACKAGE_ROOT, 'dist', 'cli', 'cli.mjs'); -const ENV_PUBLIC_DIST = join(PACKAGE_ROOT, 'dist', 'runtime', 'env-public.mjs'); +const ENV_PUBLIC_DIST = join(PACKAGE_ROOT, 'dist', 'runtime', 'env/public.mjs'); const roots: Array = []; diff --git a/packages/void/test/integration/resource-name-migration.test.ts b/packages/void/test/integration/resource-name-migration.test.ts index 5b7de2fec..ac1790b00 100644 --- a/packages/void/test/integration/resource-name-migration.test.ts +++ b/packages/void/test/integration/resource-name-migration.test.ts @@ -95,7 +95,7 @@ describe('persistent resource names through generated Workers', () => { mkdirSync(dirname(roomPath), { recursive: true }); writeFileSync( durablePath, - `import { defineDurableState } from ${JSON.stringify(runtimePath('durable.ts'))}; + `import { defineDurableState } from ${JSON.stringify(runtimePath('durable/index.ts'))}; export default defineDurableState({ ${pinned ? "name: 'counter'," : ''} initialState: { count: 0 }, @@ -116,7 +116,7 @@ export async function GET(c) { ); writeFileSync( roomPath, - `import { defineRoom } from ${JSON.stringify(runtimePath('ws.ts'))}; + `import { defineRoom } from ${JSON.stringify(runtimePath('ws/index.ts'))}; const schema = { '~standard': { version: 1, vendor: 'fixture', validate: value => ({ value }) } }; export default defineRoom({ ${pinned ? "name: 'chat-room'," : ''} @@ -162,8 +162,8 @@ export default defineRoom({ { honoPath: import.meta.resolve('hono'), honoRoutePath: import.meta.resolve('hono/route'), - runtimeEnvPath: runtimePath('env.ts'), - webSocketRuntimePath: runtimePath('ws-server.ts'), + runtimeEnvPath: runtimePath('env/runtime.ts'), + webSocketRuntimePath: runtimePath('ws/server.ts'), projectRoot: directory, homeDir: directory, reactRefresh: false, @@ -174,7 +174,7 @@ export default defineRoom({ writeFileSync( entry, compileWorkerEntry({ - runtimeEnvPath: runtimePath('env.ts'), + runtimeEnvPath: runtimePath('env/runtime.ts'), durableObjects, webSocketClasses: scan.websockets?.map((route) => route.className), }), diff --git a/packages/void/test/integration/route-response-types-typecheck.test.ts b/packages/void/test/integration/route-response-types-typecheck.test.ts index 740d15492..e194ce27a 100644 --- a/packages/void/test/integration/route-response-types-typecheck.test.ts +++ b/packages/void/test/integration/route-response-types-typecheck.test.ts @@ -45,7 +45,7 @@ it('preserves tuples and JSON omissions in generated typed fetch responses', () allowImportingTsExtensions: true, paths: { void: [join(voidDist, 'index.d.mts')], - 'void/client': [join(voidDist, 'runtime/client.d.mts')], + 'void/client': [join(voidDist, 'runtime/client/index.d.mts')], 'void/routes': [join(root, '.void/routes.d.ts')], zod: [ join( diff --git a/packages/void/test/integration/sandbox-managed-rpc.test.ts b/packages/void/test/integration/sandbox-managed-rpc.test.ts index 8fc9102b0..eea45f6bc 100644 --- a/packages/void/test/integration/sandbox-managed-rpc.test.ts +++ b/packages/void/test/integration/sandbox-managed-rpc.test.ts @@ -60,8 +60,8 @@ export default class extends WorkerEntrypoint { writeFileSync( application, ` -import { getSandbox } from ${JSON.stringify(join(root, 'packages/void/src/runtime/sandbox.ts'))}; -import { UsageLimit } from ${JSON.stringify(join(root, 'packages/void/src/runtime/limits.ts'))}; +import { getSandbox } from ${JSON.stringify(join(root, 'packages/void/src/runtime/sandbox/index.ts'))}; +import { UsageLimit } from ${JSON.stringify(join(root, 'packages/void/src/runtime/limits/index.ts'))}; export default { async fetch(request) { const sandbox = await getSandbox('default'); const path = new URL(request.url).pathname; diff --git a/packages/void/test/integration/sandbox-native-websocket.test.ts b/packages/void/test/integration/sandbox-native-websocket.test.ts index eb556802a..4e33e27fd 100644 --- a/packages/void/test/integration/sandbox-native-websocket.test.ts +++ b/packages/void/test/integration/sandbox-native-websocket.test.ts @@ -16,9 +16,9 @@ it('transfers native Sandbox WebSockets through DO fetch and strips the routing writeFileSync( entry, ` -import { SandboxContainer } from ${JSON.stringify(join(root, 'src/runtime/sandbox-container.ts'))}; -import { getSandbox } from ${JSON.stringify(join(root, 'src/runtime/sandbox.ts'))}; -import { envContext } from ${JSON.stringify(join(root, 'src/runtime/env-raw.ts'))}; +import { SandboxContainer } from ${JSON.stringify(join(root, 'src/runtime/sandbox/container.ts'))}; +import { getSandbox } from ${JSON.stringify(join(root, 'src/runtime/sandbox/index.ts'))}; +import { envContext } from ${JSON.stringify(join(root, 'src/runtime/env/raw.ts'))}; export class NativeBox extends SandboxContainer { get container() { return { running: false, getTcpPort(port) { return { fetch(request) { const [client, server] = Object.values(new WebSocketPair()); diff --git a/packages/void/test/integration/secret-cli.test.ts b/packages/void/test/integration/secret-cli.test.ts index b221305ee..e46ab5b76 100644 --- a/packages/void/test/integration/secret-cli.test.ts +++ b/packages/void/test/integration/secret-cli.test.ts @@ -7,7 +7,7 @@ import { afterEach, expect, it } from 'vite-plus/test'; const packageRoot = join(import.meta.dirname, '../..'); const cliEntry = join(packageRoot, 'dist/cli/cli.mjs'); -const envPublicUrl = pathToFileURL(join(packageRoot, 'dist/runtime/env-public.mjs')).href; +const envPublicUrl = pathToFileURL(join(packageRoot, 'dist/runtime/env/public.mjs')).href; const roots: Array = []; afterEach(() => { diff --git a/packages/void/test/integration/typed-routing-runtime.test.ts b/packages/void/test/integration/typed-routing-runtime.test.ts index ff5cd5685..47eedf6ef 100644 --- a/packages/void/test/integration/typed-routing-runtime.test.ts +++ b/packages/void/test/integration/typed-routing-runtime.test.ts @@ -134,7 +134,7 @@ export { mutate as "action" }; { honoPath: fileURLToPath(import.meta.resolve('hono')), honoRoutePath: fileURLToPath(import.meta.resolve('hono/route')), - runtimeEnvPath: source('env.ts'), + runtimeEnvPath: source('env/runtime.ts'), projectRoot: directory, homeDir: tmpdir(), reactRefresh: false, @@ -154,7 +154,7 @@ export { mutate as "action" }; }, ), ); - writeFileSync(entry, compileWorkerEntry({ runtimeEnvPath: source('env.ts') })); + writeFileSync(entry, compileWorkerEntry({ runtimeEnvPath: source('env/runtime.ts') })); const preambleScript = dev ? '' : ''; @@ -167,8 +167,8 @@ export { mutate as "action" }; name: 'typed-routing-fixture', enforce: 'pre', resolveId(id) { - if (id.endsWith('/dist/runtime/routing.mjs')) { - return source('routing.ts'); + if (id.endsWith('/dist/runtime/routing/index.mjs')) { + return source('routing/index.ts'); } if (id === 'virtual:void-routes') { return routeTable; diff --git a/packages/void/test/integration/websocket-middleware.test.ts b/packages/void/test/integration/websocket-middleware.test.ts index 861434e3f..bd82dcbc4 100644 --- a/packages/void/test/integration/websocket-middleware.test.ts +++ b/packages/void/test/integration/websocket-middleware.test.ts @@ -172,7 +172,7 @@ export default { __kind: "socket", messages: { client: schema, server: schema } honoPath: import.meta.resolve('hono'), honoRoutePath: import.meta.resolve('hono/route'), runtimeEnvPath, - webSocketRuntimePath: join(root, 'packages/void/src/runtime/ws-server.ts'), + webSocketRuntimePath: join(root, 'packages/void/src/runtime/ws/server.ts'), projectRoot: temporary, homeDir: temporary, reactRefresh: false, diff --git a/packages/void/test/unit/ai.test.ts b/packages/void/test/unit/ai.test.ts index 2ff18e675..be5cf385c 100644 --- a/packages/void/test/unit/ai.test.ts +++ b/packages/void/test/unit/ai.test.ts @@ -22,8 +22,8 @@ describe('runtime ai', () => { 'keeps cancellation on the %s transport instead of serializing it as a binding option', async (transport) => { vi.resetModules(); - const { envContext } = await import('../../src/runtime/env-raw.ts'); - const { ai } = await import('../../src/runtime/ai.ts'); + const { envContext } = await import('../../src/runtime/env/raw.ts'); + const { ai } = await import('../../src/runtime/ai/index.ts'); const controller = new AbortController(); const request = vi.fn(async (_url: string, init: RequestInit) => { expect(init.signal).toBe(controller.signal); @@ -72,8 +72,8 @@ describe('runtime ai', () => { it('rejects missing proxy metadata without sending credentials', async () => { vi.resetModules(); - const { envContext } = await import('../../src/runtime/env-raw.ts'); - const { ai } = await import('../../src/runtime/ai.ts'); + const { envContext } = await import('../../src/runtime/env/raw.ts'); + const { ai } = await import('../../src/runtime/ai/index.ts'); const request = vi.fn(); vi.stubGlobal('fetch', request); await envContext.run({ __VOID_TOKEN: 'token', __VOID_PROJECT_ID: 'project' }, async () => { @@ -88,8 +88,8 @@ describe('runtime ai', () => { it('explains missing bindings without suggesting Void login for a direct Cloudflare project', async () => { vi.resetModules(); - const { envContext } = await import('../../src/runtime/env-raw.ts'); - const { ai } = await import('../../src/runtime/ai.ts'); + const { envContext } = await import('../../src/runtime/env/raw.ts'); + const { ai } = await import('../../src/runtime/ai/index.ts'); await envContext.run({}, async () => { await expect(ai.run('@cf/meta/llama', {})).rejects.toThrow( 'Configure a Workers AI binding (env.AI) for direct Cloudflare development', @@ -99,8 +99,8 @@ describe('runtime ai', () => { it('routes Cloudflare provider models through the run endpoint unchanged', async () => { vi.resetModules(); - const { envContext } = await import('../../src/runtime/env-raw.ts'); - const { ai } = await import('../../src/runtime/ai.ts'); + const { envContext } = await import('../../src/runtime/env/raw.ts'); + const { ai } = await import('../../src/runtime/ai/index.ts'); const fetchMock = vi.fn( async (_url: string | URL | Request, _init?: RequestInit) => @@ -139,8 +139,8 @@ describe('runtime ai', () => { it('routes provider-native JSON requests through the provider endpoint', async () => { vi.resetModules(); - const { envContext } = await import('../../src/runtime/env-raw.ts'); - const { ai } = await import('../../src/runtime/ai.ts'); + const { envContext } = await import('../../src/runtime/env/raw.ts'); + const { ai } = await import('../../src/runtime/ai/index.ts'); const fetchMock = vi.fn( async (_url: string | URL | Request, _init?: RequestInit) => @@ -193,8 +193,8 @@ describe('runtime ai', () => { it('returns non-2xx provider responses for service-binding proxy requests', async () => { vi.resetModules(); - const { envContext } = await import('../../src/runtime/env-raw.ts'); - const { ai } = await import('../../src/runtime/ai.ts'); + const { envContext } = await import('../../src/runtime/env/raw.ts'); + const { ai } = await import('../../src/runtime/ai/index.ts'); const proxyFetch = vi.fn( async (_url: string | URL | Request, _init?: RequestInit) => @@ -236,8 +236,8 @@ describe('runtime ai', () => { it('supports provider API-key env and header overrides', async () => { vi.resetModules(); - const { envContext } = await import('../../src/runtime/env-raw.ts'); - const { ai } = await import('../../src/runtime/ai.ts'); + const { envContext } = await import('../../src/runtime/env/raw.ts'); + const { ai } = await import('../../src/runtime/ai/index.ts'); const fetchMock = vi.fn( async (_url: string | URL | Request, _init?: RequestInit) => new Response('ok'), @@ -277,8 +277,8 @@ describe('runtime ai', () => { it('serializes provider-native multipart bodies', async () => { vi.resetModules(); - const { envContext } = await import('../../src/runtime/env-raw.ts'); - const { ai } = await import('../../src/runtime/ai.ts'); + const { envContext } = await import('../../src/runtime/env/raw.ts'); + const { ai } = await import('../../src/runtime/ai/index.ts'); const fetchMock = vi.fn( async (_url: string | URL | Request, _init?: RequestInit) => new Response('ok'), @@ -331,8 +331,8 @@ describe('runtime ai', () => { it('sends JSON provider bodies unchanged through the proxy', async () => { vi.resetModules(); - const { envContext } = await import('../../src/runtime/env-raw.ts'); - const { ai } = await import('../../src/runtime/ai.ts'); + const { envContext } = await import('../../src/runtime/env/raw.ts'); + const { ai } = await import('../../src/runtime/ai/index.ts'); const fetchMock = vi.fn( async (_url: string | URL | Request, _init?: RequestInit) => new Response('ok'), @@ -361,8 +361,8 @@ describe('runtime ai', () => { it('returns blobs for non-JSON run responses', async () => { vi.resetModules(); - const { envContext } = await import('../../src/runtime/env-raw.ts'); - const { ai } = await import('../../src/runtime/ai.ts'); + const { envContext } = await import('../../src/runtime/env/raw.ts'); + const { ai } = await import('../../src/runtime/ai/index.ts'); vi.stubGlobal( 'fetch', @@ -398,8 +398,8 @@ describe('runtime ai', () => { describe('direct AI backend (self-host, env.AI only)', () => { it('selects the direct backend when only env.AI is present (ai.run → directAi.run)', async () => { vi.resetModules(); - const { envContext } = await import('../../src/runtime/env-raw.ts'); - const { ai } = await import('../../src/runtime/ai.ts'); + const { envContext } = await import('../../src/runtime/env/raw.ts'); + const { ai } = await import('../../src/runtime/ai/index.ts'); // Any accidental fall-through to the Void proxy would hit fetch — assert it doesn't. const fetchMock = vi.fn( @@ -425,8 +425,8 @@ describe('runtime ai', () => { it('selects a custom binding named by the generated runtime variable', async () => { vi.resetModules(); - const { envContext } = await import('../../src/runtime/env-raw.ts'); - const { ai } = await import('../../src/runtime/ai.ts'); + const { envContext } = await import('../../src/runtime/env/raw.ts'); + const { ai } = await import('../../src/runtime/ai/index.ts'); const direct = makeDirectAi(); await envContext.run({ MY_AI: direct.AI, __VOID_AI_BINDING: 'MY_AI' }, async () => { @@ -442,8 +442,8 @@ describe('runtime ai', () => { it('provider().fetch hits the user gateway with provider auth and no metering header', async () => { vi.resetModules(); - const { envContext } = await import('../../src/runtime/env-raw.ts'); - const { ai } = await import('../../src/runtime/ai.ts'); + const { envContext } = await import('../../src/runtime/env/raw.ts'); + const { ai } = await import('../../src/runtime/ai/index.ts'); const fetchMock = vi.fn( async (_url: string | URL | Request, _init?: RequestInit) => @@ -493,8 +493,8 @@ describe('runtime ai', () => { 'sends the provider-native auth header for %s', async (provider, keyEnv, header, value, authorization) => { vi.resetModules(); - const { envContext } = await import('../../src/runtime/env-raw.ts'); - const { ai } = await import('../../src/runtime/ai.ts'); + const { envContext } = await import('../../src/runtime/env/raw.ts'); + const { ai } = await import('../../src/runtime/ai/index.ts'); const fetchMock = vi.fn( async (_url: string | URL | Request, _init?: RequestInit) => new Response('ok'), @@ -520,8 +520,8 @@ describe('runtime ai', () => { it('resolves to 501 when no AI gateway is configured', async () => { vi.resetModules(); - const { envContext } = await import('../../src/runtime/env-raw.ts'); - const { ai } = await import('../../src/runtime/ai.ts'); + const { envContext } = await import('../../src/runtime/env/raw.ts'); + const { ai } = await import('../../src/runtime/ai/index.ts'); const fetchMock = vi.fn( async (_url: string | URL | Request, _init?: RequestInit) => new Response('ok'), @@ -546,8 +546,8 @@ describe('runtime ai', () => { it('resolves to 400 naming the missing provider secret', async () => { vi.resetModules(); - const { envContext } = await import('../../src/runtime/env-raw.ts'); - const { ai } = await import('../../src/runtime/ai.ts'); + const { envContext } = await import('../../src/runtime/env/raw.ts'); + const { ai } = await import('../../src/runtime/ai/index.ts'); const fetchMock = vi.fn( async (_url: string | URL | Request, _init?: RequestInit) => new Response('ok'), @@ -571,8 +571,8 @@ describe('runtime ai', () => { it('resolves to 502 when the gateway getUrl lookup rejects', async () => { vi.resetModules(); - const { envContext } = await import('../../src/runtime/env-raw.ts'); - const { ai } = await import('../../src/runtime/ai.ts'); + const { envContext } = await import('../../src/runtime/env/raw.ts'); + const { ai } = await import('../../src/runtime/ai/index.ts'); const fetchMock = vi.fn( async (_url: string | URL | Request, _init?: RequestInit) => new Response('ok'), @@ -603,8 +603,8 @@ describe('runtime ai', () => { it('resolves to 400 for an unsafe absolute provider path', async () => { vi.resetModules(); - const { envContext } = await import('../../src/runtime/env-raw.ts'); - const { ai } = await import('../../src/runtime/ai.ts'); + const { envContext } = await import('../../src/runtime/env/raw.ts'); + const { ai } = await import('../../src/runtime/ai/index.ts'); const fetchMock = vi.fn( async (_url: string | URL | Request, _init?: RequestInit) => new Response('ok'), @@ -631,8 +631,8 @@ describe('runtime ai', () => { it('forwards a direct multipart/form-data body untouched (fetch sets the boundary)', async () => { vi.resetModules(); - const { envContext } = await import('../../src/runtime/env-raw.ts'); - const { ai } = await import('../../src/runtime/ai.ts'); + const { envContext } = await import('../../src/runtime/env/raw.ts'); + const { ai } = await import('../../src/runtime/ai/index.ts'); const fetchMock = vi.fn( async (_url: string | URL | Request, _init?: RequestInit) => new Response('ok'), @@ -674,8 +674,8 @@ describe('runtime ai', () => { describe('AI usage-limit rejections', () => { it('preserves ordinary inference failures', async () => { vi.resetModules(); - const { envContext } = await import('../../src/runtime/env-raw.ts'); - const { ai } = await import('../../src/runtime/ai.ts'); + const { envContext } = await import('../../src/runtime/env/raw.ts'); + const { ai } = await import('../../src/runtime/ai/index.ts'); const error = new Error('network failed'); const direct = makeDirectAi({ run: () => { @@ -692,10 +692,10 @@ describe('AI usage-limit rejections', () => { async (method) => { vi.resetModules(); const { Hono } = await import('hono'); - const { envContext } = await import('../../src/runtime/env-raw.ts'); - const { ai } = await import('../../src/runtime/ai.ts'); - const { createHttpRouteHandler } = await import('../../src/runtime/routing.ts'); - const { createErrorRenderer } = await import('../../src/runtime/routing-errors.ts'); + const { envContext } = await import('../../src/runtime/env/raw.ts'); + const { ai } = await import('../../src/runtime/ai/index.ts'); + const { createHttpRouteHandler } = await import('../../src/runtime/routing/index.ts'); + const { createErrorRenderer } = await import('../../src/runtime/routing/errors.ts'); const direct = makeDirectAi({ run: () => Response.json({}, { status: 429, headers: { 'Retry-After': '60' } }), }); @@ -722,9 +722,9 @@ describe('AI usage-limit rejections', () => { 'rejects %s quota failures with UsageLimit', async (method) => { vi.resetModules(); - const { envContext } = await import('../../src/runtime/env-raw.ts'); - const { ai } = await import('../../src/runtime/ai.ts'); - const { UsageLimit } = await import('../../src/runtime/limits.ts'); + const { envContext } = await import('../../src/runtime/env/raw.ts'); + const { ai } = await import('../../src/runtime/ai/index.ts'); + const { UsageLimit } = await import('../../src/runtime/limits/index.ts'); const fetch = vi.fn(async () => Response.json( { @@ -767,9 +767,9 @@ describe('AI usage-limit rejections', () => { it('preserves a quota interruption after streaming has started in a terminal event', async () => { vi.resetModules(); - const { envContext } = await import('../../src/runtime/env-raw.ts'); - const { ai } = await import('../../src/runtime/ai.ts'); - const { UsageLimit } = await import('../../src/runtime/limits.ts'); + const { envContext } = await import('../../src/runtime/env/raw.ts'); + const { ai } = await import('../../src/runtime/ai/index.ts'); + const { UsageLimit } = await import('../../src/runtime/limits/index.ts'); const limit = new UsageLimit({ resource: 'ai', reason: 'rate_limit', message: 'Provider limit' }); const body = new ReadableStream({ pull(controller) { @@ -789,8 +789,8 @@ it.each(['run', 'stream', 'image'] as const)( 'handles native %s quotas before the binding discards the HTTP status', async (method) => { vi.resetModules(); - const { envContext } = await import('../../src/runtime/env-raw.ts'); - const { ai } = await import('../../src/runtime/ai.ts'); + const { envContext } = await import('../../src/runtime/env/raw.ts'); + const { ai } = await import('../../src/runtime/ai/index.ts'); const direct = makeDirectAi({ run: () => Response.json( @@ -799,7 +799,7 @@ it.each(['run', 'stream', 'image'] as const)( ), }); await envContext.run({ AI: direct.AI }, async () => { - const { UsageLimit } = await import('../../src/runtime/limits.ts'); + const { UsageLimit } = await import('../../src/runtime/limits/index.ts'); const result = ai[method]('model', {}); await expect(result).rejects.toBeInstanceOf(UsageLimit); await expect(result).rejects.toMatchObject({ @@ -813,8 +813,8 @@ it.each(['run', 'stream', 'image'] as const)( it('decodes native JSON responses and preserves explicitly requested raw responses', async () => { vi.resetModules(); - const { envContext } = await import('../../src/runtime/env-raw.ts'); - const { ai } = await import('../../src/runtime/ai.ts'); + const { envContext } = await import('../../src/runtime/env/raw.ts'); + const { ai } = await import('../../src/runtime/ai/index.ts'); const direct = makeDirectAi({ run: () => Response.json({ response: 'hello' }) }); await envContext.run({ AI: direct.AI }, async () => { expect(await ai.run('model', {})).toEqual({ response: 'hello' }); diff --git a/packages/void/test/unit/ai.typecheck.ts b/packages/void/test/unit/ai.typecheck.ts index a89f24a20..2eb6b0e27 100644 --- a/packages/void/test/unit/ai.typecheck.ts +++ b/packages/void/test/unit/ai.typecheck.ts @@ -1,5 +1,5 @@ import { expectTypeOf } from 'vite-plus/test'; -import type { ai } from '../../src/runtime/ai.ts'; +import type { ai } from '../../src/runtime/ai/index.ts'; declare const client: typeof ai; const model = '@cf/meta/llama-3.3-70b-instruct-fp8-fast'; diff --git a/packages/void/test/unit/auth-client-frameworks.test.ts b/packages/void/test/unit/auth-client-frameworks.test.ts index 389dfa47e..eb8679cd3 100644 --- a/packages/void/test/unit/auth-client-frameworks.test.ts +++ b/packages/void/test/unit/auth-client-frameworks.test.ts @@ -30,11 +30,11 @@ vi.mock('better-auth/solid', () => ({ describe('client runtimes', () => { it.each([ - ['default', 'client', () => import('../../src/runtime/client.ts')], - ['React', 'react', () => import('../../src/runtime/client-react.ts')], - ['Vue', 'vue', () => import('../../src/runtime/client-vue.ts')], - ['Svelte', 'svelte', () => import('../../src/runtime/client-svelte.ts')], - ['Solid', 'solid', () => import('../../src/runtime/client-solid.ts')], + ['default', 'client', () => import('../../src/runtime/client/index.ts')], + ['React', 'react', () => import('../../src/runtime/client/react.ts')], + ['Vue', 'vue', () => import('../../src/runtime/client/vue.ts')], + ['Svelte', 'svelte', () => import('../../src/runtime/client/svelte.ts')], + ['Solid', 'solid', () => import('../../src/runtime/client/solid.ts')], ] as const)('re-exports the %s Better Auth client', async (_name, framework, load) => { const { auth, createAuthClient } = await load(); expect(createAuthClient).toBe(mocks[framework]); diff --git a/packages/void/test/unit/auth-context.test.ts b/packages/void/test/unit/auth-context.test.ts index a09d6b903..bd774d92b 100644 --- a/packages/void/test/unit/auth-context.test.ts +++ b/packages/void/test/unit/auth-context.test.ts @@ -5,7 +5,7 @@ import { getUser, type AuthState, type AuthUser, -} from '../../src/runtime/auth.ts'; +} from '../../src/runtime/auth/index.ts'; describe('authContext', () => { it('runs callback with provided store and exposes it via getUser/getSession', () => { @@ -48,9 +48,9 @@ describe('authContext', () => { it('returns the same ALS instance across module re-evaluations', async () => { // resetModules re-evaluates auth.ts, like a second module load. vi.resetModules(); - const first = await import('../../src/runtime/auth.ts'); + const first = await import('../../src/runtime/auth/index.ts'); vi.resetModules(); - const second = await import('../../src/runtime/auth.ts'); + const second = await import('../../src/runtime/auth/index.ts'); expect(first.authContext).toBe(second.authContext); expect(authContext).toBe(first.authContext); diff --git a/packages/void/test/unit/auth-d1-database.test.ts b/packages/void/test/unit/auth-d1-database.test.ts index 6cb77f262..2be9040e8 100644 --- a/packages/void/test/unit/auth-d1-database.test.ts +++ b/packages/void/test/unit/auth-d1-database.test.ts @@ -13,8 +13,8 @@ import { generateVoidAuthDrizzleSchema, } from '../../src/auth/drizzle.ts'; import { drizzlePlugin } from '../../src/plugin-drizzle.ts'; -import { envContext } from '../../src/runtime/env-raw.ts'; -import { withRuntimeEnv } from '../../src/runtime/env.ts'; +import { envContext } from '../../src/runtime/env/raw.ts'; +import { withRuntimeEnv } from '../../src/runtime/env/runtime.ts'; import { getHookHandler } from '../helpers/vite-hooks.ts'; const roots: Array = []; @@ -39,7 +39,7 @@ async function loadAuthDatabase(d1BindingName: string) { ), ), ); - const envUrl = new URL('../../src/runtime/env.ts', import.meta.url).href; + const envUrl = new URL('../../src/runtime/env/runtime.ts', import.meta.url).href; const dbPath = join(root, 'db.mjs'); const plugin = drizzlePlugin(root, false, 'sqlite', { d1BindingName, forceVirtualDb: true }); const load = getHookHandler(plugin.load) as (id: string) => string; diff --git a/packages/void/test/unit/auth-middleware.test.ts b/packages/void/test/unit/auth-middleware.test.ts index 6ac4d41e3..40f3200da 100644 --- a/packages/void/test/unit/auth-middleware.test.ts +++ b/packages/void/test/unit/auth-middleware.test.ts @@ -10,20 +10,20 @@ vi.mock('better-auth', () => ({ betterAuth: mocks.betterAuth, })); +import { + createVoidAuthRuntime, + privateCachePolicy, + type VoidAuthRuntimeOptions, +} from '../../src/runtime/auth/better-auth-shared.ts'; import { getAuth, getUser, requireAuth, type AuthState, type AuthUser, -} from '../../src/runtime/auth.ts'; -import { - createVoidAuthRuntime, - privateCachePolicy, - type VoidAuthRuntimeOptions, -} from '../../src/runtime/better-auth-shared.ts'; -import { createRoutingRuntime } from '../../src/runtime/routing.ts'; -import { markStaticAsset } from '../../src/runtime/static-asset-marker.ts'; +} from '../../src/runtime/auth/index.ts'; +import { createRoutingRuntime } from '../../src/runtime/routing/index.ts'; +import { markStaticAsset } from '../../src/runtime/routing/static-asset-marker.ts'; const authRuntimeOptions: VoidAuthRuntimeOptions = { dialect: 'sqlite', diff --git a/packages/void/test/unit/auth-migrations.test.ts b/packages/void/test/unit/auth-migrations.test.ts index a857ec795..cd9982ec2 100644 --- a/packages/void/test/unit/auth-migrations.test.ts +++ b/packages/void/test/unit/auth-migrations.test.ts @@ -14,7 +14,7 @@ import { applyPgAuthMigrations, applySqliteAuthMigrations, pgMigrationRunner, -} from '../../src/runtime/auth-migrations.ts'; +} from '../../src/runtime/auth/migrations.ts'; // PGlite serves the `pg` clients, and each client records the database it names. const state = vi.hoisted(() => ({ pg: null as PGlite | null, connections: [] as Array })); diff --git a/packages/void/test/unit/basic-auth.test.ts b/packages/void/test/unit/basic-auth.test.ts index 0a297a8b3..298bde545 100644 --- a/packages/void/test/unit/basic-auth.test.ts +++ b/packages/void/test/unit/basic-auth.test.ts @@ -1,8 +1,12 @@ import { Hono } from 'hono'; import { afterEach, describe, expect, it, vi } from 'vite-plus/test'; -import { env } from '../../src/runtime/env-public.ts'; -import { withRuntimeEnv } from '../../src/runtime/env.ts'; -import { basicAuth, type BasicAuthOptions, type CloudEnv } from '../../src/runtime/handler.ts'; +import { env } from '../../src/runtime/env/public.ts'; +import { withRuntimeEnv } from '../../src/runtime/env/runtime.ts'; +import { + basicAuth, + type BasicAuthOptions, + type CloudEnv, +} from '../../src/runtime/handler/index.ts'; function authorization(value: string) { const bytes = new TextEncoder().encode(value); diff --git a/packages/void/test/unit/better-auth.test.ts b/packages/void/test/unit/better-auth.test.ts index 41b255340..eb65a39f0 100644 --- a/packages/void/test/unit/better-auth.test.ts +++ b/packages/void/test/unit/better-auth.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vite-plus/test'; -import { voidAuthPassword } from '../../src/runtime/better-auth-shared.ts'; -import { resolveVoidAuthOptions } from '../../src/runtime/better-auth.ts'; +import { resolveVoidAuthOptions } from '../../src/runtime/auth/better-auth-d1.ts'; +import { voidAuthPassword } from '../../src/runtime/auth/better-auth-shared.ts'; describe('resolveVoidAuthOptions', () => { it('defaults to email auth when no providers are configured', async () => { diff --git a/packages/void/test/unit/client-subpath-exports.test.ts b/packages/void/test/unit/client-subpath-exports.test.ts index 411222769..f57eb4db2 100644 --- a/packages/void/test/unit/client-subpath-exports.test.ts +++ b/packages/void/test/unit/client-subpath-exports.test.ts @@ -10,9 +10,9 @@ describe('client package exports', () => { for (const framework of ['react', 'vue', 'svelte', 'solid']) { expect(packageJson.exports[`./client/${framework}`]).toEqual({ - import: `./dist/runtime/client-${framework}.mjs`, - require: `./dist/runtime/client-${framework}.mjs`, - types: `./dist/runtime/client-${framework}.d.mts`, + import: `./dist/runtime/client/${framework}.mjs`, + require: `./dist/runtime/client/${framework}.mjs`, + types: `./dist/runtime/client/${framework}.d.mts`, }); } }); diff --git a/packages/void/test/unit/cloudflare-deploy.test.ts b/packages/void/test/unit/cloudflare-deploy.test.ts index 3f3017be8..09e3cc7a8 100644 --- a/packages/void/test/unit/cloudflare-deploy.test.ts +++ b/packages/void/test/unit/cloudflare-deploy.test.ts @@ -958,8 +958,8 @@ function emittedVars(vars: Record = {}): EmittedWorkerVarsResul */ const srcFileUrl = (...segments: Array): string => pathToFileURL(join(import.meta.dirname, '..', '..', 'src', ...segments)).href; -const srcEnvPublic = srcFileUrl('runtime', 'env-public.ts'); -const srcEnvHelpers = srcFileUrl('runtime', 'env-helpers.ts'); +const srcEnvPublic = srcFileUrl('runtime', 'env/public.ts'); +const srcEnvHelpers = srcFileUrl('runtime', 'env/helpers.ts'); /** * Cloudflare credentials the parent may hold: Wrangler's names, their `CF_*` aliases and Void's diff --git a/packages/void/test/unit/compile-auth.test.ts b/packages/void/test/unit/compile-auth.test.ts index 02862273f..db0c281d3 100644 --- a/packages/void/test/unit/compile-auth.test.ts +++ b/packages/void/test/unit/compile-auth.test.ts @@ -14,14 +14,14 @@ const baseOptions = { honoPath: '/resolved/hono/index.mjs', honoRoutePath: '/resolved/hono/route.mjs', - runtimeEnvPath: '/resolved/void/runtime/env.mjs', + runtimeEnvPath: '/resolved/void/runtime/env/runtime.mjs', projectRoot: '/project', homeDir: '/Users/test', reactRefresh: false, }; const sqliteAuth: AuthCompileOptions = { - authRuntimePath: '/resolved/void/runtime/better-auth.mjs', + authRuntimePath: '/resolved/void/runtime/auth/better-auth-d1.mjs', authConfigPath: null, authDatabasePath: '/project/.void/better-auth-db.ts', authSchemaPath: '/project/.void/better-auth-schema.ts', @@ -30,7 +30,7 @@ const sqliteAuth: AuthCompileOptions = { }; const pgAuth: AuthCompileOptions = { - authRuntimePath: '/resolved/void/runtime/better-auth.mjs', + authRuntimePath: '/resolved/void/runtime/auth/better-auth-d1.mjs', authConfigPath: '/app/auth.ts', authDatabasePath: '/project/.void/better-auth-db.ts', authSchemaPath: '/project/.void/better-auth-schema.ts', @@ -82,7 +82,7 @@ describe('compileRouteTable auth integration', () => { auth: sqliteAuth, }); - expect(code).toContain('from "/resolved/void/runtime/better-auth.mjs"'); + expect(code).toContain('from "/resolved/void/runtime/auth/better-auth-d1.mjs"'); expect(code).toContain('import { __voidAuthDatabase } from "/project/.void/better-auth-db.ts"'); expect(code).toContain( 'import { migrationSchema as __voidAuthMigrationSchema } from "/project/.void/better-auth-schema.ts"', diff --git a/packages/void/test/unit/compile.test.ts b/packages/void/test/unit/compile.test.ts index c73eaaf57..b0d8035e5 100644 --- a/packages/void/test/unit/compile.test.ts +++ b/packages/void/test/unit/compile.test.ts @@ -13,7 +13,7 @@ import { type CompileOptions, } from '../../src/router/compile.ts'; import type { ScanResult } from '../../src/router/scan.ts'; -import { VoidAssetRewriteError } from '../../src/runtime/handler.ts'; +import { VoidAssetRewriteError } from '../../src/runtime/handler/index.ts'; import { createRoutingRuntime, createHttpRouteHandler, @@ -28,16 +28,16 @@ import { createSsrFallback, createAssetNotFound, type RoutingRuntime, -} from '../../src/runtime/routing.ts'; +} from '../../src/runtime/routing/index.ts'; const testOptions = { honoPath: '/resolved/hono/index.mjs', honoRoutePath: '/resolved/hono/route.mjs', - runtimeEnvPath: '/resolved/void/runtime/env.mjs', + runtimeEnvPath: '/resolved/void/runtime/env/runtime.mjs', projectRoot: '/project', homeDir: '/Users/test', - webSocketRuntimePath: '/resolved/void/runtime/ws-server.mjs', + webSocketRuntimePath: '/resolved/void/runtime/ws/server.mjs', reactRefresh: true, auth: null, }; @@ -229,7 +229,7 @@ describe('compileRouteTable', () => { it('generates the shared live durable object export when live is enabled', () => { const code = compile({ hasLive: true, - liveRuntimePath: '/resolved/void/runtime/live-server.mjs', + liveRuntimePath: '/resolved/void/runtime/live/server.mjs', }); expect(code).toContain('createLiveDurableObject'); diff --git a/packages/void/test/unit/db-casing.test.ts b/packages/void/test/unit/db-casing.test.ts index 589b7be03..c5ad1d9c1 100644 --- a/packages/void/test/unit/db-casing.test.ts +++ b/packages/void/test/unit/db-casing.test.ts @@ -12,8 +12,8 @@ import { generateVoidAuthDrizzleSchema } from '../../src/auth/drizzle.ts'; import { prepareProject } from '../../src/codegen/prepare.ts'; import type { DatabaseCasing } from '../../src/config.ts'; import { drizzlePlugin, voidDbBundlerPlugin } from '../../src/plugin-drizzle.ts'; -import { envContext } from '../../src/runtime/env-raw.ts'; -import { withRuntimeEnv } from '../../src/runtime/env.ts'; +import { envContext } from '../../src/runtime/env/raw.ts'; +import { withRuntimeEnv } from '../../src/runtime/env/runtime.ts'; import { startFakeMySqlServer } from '../helpers/fake-mysql-server.ts'; import { getHookHandler } from '../helpers/vite-hooks.ts'; @@ -32,7 +32,7 @@ type DbModule = { const roots: Array = []; // The generated module imports the built runtime env; tests share the source one. const builtEnv = JSON.stringify(fileURLToPath(import.meta.resolve('#self/_env'))); -const sourceEnv = JSON.stringify(new URL('../../src/runtime/env.ts', import.meta.url).href); +const sourceEnv = JSON.stringify(new URL('../../src/runtime/env/runtime.ts', import.meta.url).href); afterEach(() => { for (const root of roots.splice(0)) { diff --git a/packages/void/test/unit/db-request-pool.test.ts b/packages/void/test/unit/db-request-pool.test.ts index 1fe95b996..111ed02b0 100644 --- a/packages/void/test/unit/db-request-pool.test.ts +++ b/packages/void/test/unit/db-request-pool.test.ts @@ -8,7 +8,7 @@ import { PGlite } from '@electric-sql/pglite'; import { createServer } from 'pglite-server'; import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vite-plus/test'; import { drizzlePlugin } from '../../src/plugin-drizzle.ts'; -import { withRuntimeEnv } from '../../src/runtime/env.ts'; +import { withRuntimeEnv } from '../../src/runtime/env/runtime.ts'; import { startFakeMySqlServer, type FakeMySqlServer } from '../helpers/fake-mysql-server.ts'; import { getHookHandler } from '../helpers/vite-hooks.ts'; @@ -61,7 +61,7 @@ export const users = mysqlTable('users', { id: int('id').primaryKey(), name: var const plugin = drizzlePlugin(root, false, dialect); const load = getHookHandler(plugin.load) as (this: object, id: string) => string; - const envUrl = new URL('../../src/runtime/env.ts', import.meta.url).href; + const envUrl = new URL('../../src/runtime/env/runtime.ts', import.meta.url).href; const stateKey = `__void_db_request_pools_${crypto.randomUUID().replaceAll('-', '')}`; const state = { pools: [] as Array, checkouts: 0 }; (globalThis as Record)[stateKey] = state; diff --git a/packages/void/test/unit/db-session.typecheck.ts b/packages/void/test/unit/db-session.typecheck.ts index 307d88f3d..6a02f6c92 100644 --- a/packages/void/test/unit/db-session.typecheck.ts +++ b/packages/void/test/unit/db-session.typecheck.ts @@ -1,5 +1,5 @@ import { expectTypeOf } from 'vite-plus/test'; -import { createDb, type DrizzleD1Database } from '../../src/runtime/db.ts'; +import { createDb, type DrizzleD1Database } from '../../src/runtime/db/index.ts'; declare const binding: D1Database; diff --git a/packages/void/test/unit/db-types.typecheck.ts b/packages/void/test/unit/db-types.typecheck.ts index 8fc9f36a5..038c51673 100644 --- a/packages/void/test/unit/db-types.typecheck.ts +++ b/packages/void/test/unit/db-types.typecheck.ts @@ -10,7 +10,7 @@ import { type BatchItem, type SQL, type SQLWrapper, -} from '../../src/runtime/db.ts'; +} from '../../src/runtime/db/index.ts'; const posts = sqliteTable('posts', { id: integer('id').primaryKey(), diff --git a/packages/void/test/unit/define-handler.test.ts b/packages/void/test/unit/define-handler.test.ts index b254069cc..ab86e8010 100644 --- a/packages/void/test/unit/define-handler.test.ts +++ b/packages/void/test/unit/define-handler.test.ts @@ -7,9 +7,9 @@ import { defineMiddleware, type CloudContext, type TypedHandler, -} from '../../src/runtime/handler.ts'; -import { convertReturnValue } from '../../src/runtime/response.ts'; -import { createHttpRouteHandler } from '../../src/runtime/routing.ts'; +} from '../../src/runtime/handler/index.ts'; +import { convertReturnValue } from '../../src/runtime/handler/response.ts'; +import { createHttpRouteHandler } from '../../src/runtime/routing/index.ts'; import type { StandardSchemaV1 } from '../../src/standard-schema.ts'; type ValidationIssueBody = { @@ -20,7 +20,7 @@ type ValidationIssueBody = { }>; }; -/** Wraps the handler the way createHttpRouteHandler in runtime/routing.ts does. */ +/** Wraps the handler the way createHttpRouteHandler in runtime/routing/index.ts does. */ function createApp(handler: (c: CloudContext) => unknown) { const app = new Hono(); app.get('/test', async (c) => { diff --git a/packages/void/test/unit/deploy-asset-config.test.ts b/packages/void/test/unit/deploy-asset-config.test.ts index 4c922193e..90e291774 100644 --- a/packages/void/test/unit/deploy-asset-config.test.ts +++ b/packages/void/test/unit/deploy-asset-config.test.ts @@ -7,7 +7,7 @@ import { resolveAssetRoutingPolicy, workerOwnsHtmlRouting, } from '../../src/asset-routing.ts'; -import { createAssetFallback } from '../../src/runtime/routing-worker.ts'; +import { createAssetFallback } from '../../src/runtime/routing/worker.ts'; // `not_found_handling: 'none'` → asset binding 404s on unmatched paths, // worker (run_worker_first) owns HTML responses. diff --git a/packages/void/test/unit/deploy-prerender-skip.test.ts b/packages/void/test/unit/deploy-prerender-skip.test.ts index de5550f15..c2e7e6993 100644 --- a/packages/void/test/unit/deploy-prerender-skip.test.ts +++ b/packages/void/test/unit/deploy-prerender-skip.test.ts @@ -75,10 +75,10 @@ describe('__voidCollectPrerenderPaths — sources that can push a path', () => { honoPath: '/resolved/hono/index.mjs', honoRoutePath: '/resolved/hono/route.mjs', - runtimeEnvPath: '/resolved/void/runtime/env.mjs', + runtimeEnvPath: '/resolved/void/runtime/env/runtime.mjs', projectRoot: '/project', homeDir: '/Users/test', - webSocketRuntimePath: '/resolved/void/runtime/ws-server.mjs', + webSocketRuntimePath: '/resolved/void/runtime/ws/server.mjs', reactRefresh: false, auth: null, }; diff --git a/packages/void/test/unit/durable-object.test.ts b/packages/void/test/unit/durable-object.test.ts index b40e1752b..1a9cb65df 100644 --- a/packages/void/test/unit/durable-object.test.ts +++ b/packages/void/test/unit/durable-object.test.ts @@ -1,7 +1,7 @@ import { DurableObject } from 'cloudflare:workers'; import { describe, expect, it, vi } from 'vite-plus/test'; -import { defineDurableObject } from '../../src/runtime/durable.ts'; -import { withRuntimeEnv } from '../../src/runtime/env.ts'; +import { defineDurableObject } from '../../src/runtime/durable/index.ts'; +import { withRuntimeEnv } from '../../src/runtime/env/runtime.ts'; vi.mock('cloudflare:workers', () => ({ DurableObject: class {} })); diff --git a/packages/void/test/unit/durable-state.test.ts b/packages/void/test/unit/durable-state.test.ts index b5a1b7ffc..44910e88e 100644 --- a/packages/void/test/unit/durable-state.test.ts +++ b/packages/void/test/unit/durable-state.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vite-plus/test'; -import { defineDurableState } from '../../src/runtime/durable.ts'; -import { getRuntimeRequestResource, withRuntimeEnv } from '../../src/runtime/env.ts'; +import { defineDurableState } from '../../src/runtime/durable/index.ts'; +import { getRuntimeRequestResource, withRuntimeEnv } from '../../src/runtime/env/runtime.ts'; vi.mock('cloudflare:workers', () => ({ DurableObject: class { diff --git a/packages/void/test/unit/email-cloudflare.test.ts b/packages/void/test/unit/email-cloudflare.test.ts index 202c09763..f8797a998 100644 --- a/packages/void/test/unit/email-cloudflare.test.ts +++ b/packages/void/test/unit/email-cloudflare.test.ts @@ -21,7 +21,7 @@ import { type EmailWranglerRunResult, } from '../../src/cli/email-cloudflare.ts'; import type { EmailHandlersScan } from '../../src/router/email.ts'; -import { compileEmailPattern } from '../../src/router/email.ts'; +import { compileEmailPattern } from '../../src/shared/email-pattern.ts'; // ── Structured command fakes ─────────────────────────────────────────────────── diff --git a/packages/void/test/unit/email-dev-inbox.test.ts b/packages/void/test/unit/email-dev-inbox.test.ts index 4b764cf0b..a9902b5c4 100644 --- a/packages/void/test/unit/email-dev-inbox.test.ts +++ b/packages/void/test/unit/email-dev-inbox.test.ts @@ -8,7 +8,6 @@ import { Readable } from 'node:stream'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'; import { shouldInjectEmailDevInboxVar } from '../../src/plugin-binding-utils.ts'; import { emailDevInboxPlugin } from '../../src/plugin-email-dev-inbox.ts'; -import { sendEmail } from '../../src/runtime/email.ts'; import { captureMessage, clearDevBuffer, @@ -27,6 +26,7 @@ import { serializeCapturedMessage, type CapturedMessage, } from '../../src/runtime/email/dev-inbox.ts'; +import { sendEmail } from '../../src/runtime/email/index.ts'; import { buildMime, MAX_ADDRESS_LENGTH, @@ -34,7 +34,7 @@ import { MAX_RECIPIENTS, normalizeEmail, } from '../../src/runtime/email/mime.ts'; -import { withRuntimeEnv } from '../../src/runtime/env.ts'; +import { withRuntimeEnv } from '../../src/runtime/env/runtime.ts'; /** The per-project dev-trigger token `voidPlugin()` hands the plugin. */ const TOKEN = 'dev-token-test'; diff --git a/packages/void/test/unit/email-inbound.test.ts b/packages/void/test/unit/email-inbound.test.ts index efbe55b57..fb2896330 100644 --- a/packages/void/test/unit/email-inbound.test.ts +++ b/packages/void/test/unit/email-inbound.test.ts @@ -11,12 +11,7 @@ import { } from '../../../platform/src/email-protocol.ts'; import { compileRouteTable } from '../../src/router/compile.ts'; import { compileWorkerEntry } from '../../src/router/compile.ts'; -import { - compileEmailPattern, - hasEmailHandlers, - scanEmailHandlersSync, -} from '../../src/router/email.ts'; -import * as emailBarrel from '../../src/runtime/email.ts'; +import { hasEmailHandlers, scanEmailHandlersSync } from '../../src/router/email.ts'; import { buildReplyMessage, createMessageProxy, @@ -30,6 +25,7 @@ import { replyEmail, type EmailEnvelope, } from '../../src/runtime/email/inbound.ts'; +import * as emailBarrel from '../../src/runtime/email/index.ts'; import { MAX_MESSAGE_BYTES, MimeError } from '../../src/runtime/email/mime.ts'; /** The one shape message the address rule (`email-validator`) throws; it never echoes the address. */ @@ -37,7 +33,7 @@ const INVALID_ADDRESS = 'address is not a valid email address (ASCII local part and dotted domain, RFC 5322 dot-atom; ' + "at most 64 characters before the '@' and 254 in total)."; import { createInboundTestHarness } from '../../src/runtime/email/testing.ts'; -import { envContext } from '../../src/runtime/env-raw.ts'; +import { envContext } from '../../src/runtime/env/raw.ts'; vi.mock('cloudflare:email', () => ({ EmailMessage: class MockEmailMessage { @@ -183,68 +179,6 @@ describe('scanEmailHandlersSync', () => { }); }); -describe('compileEmailPattern', () => { - it('compiles static address', () => { - expect(compileEmailPattern('support')).toEqual({ - kind: 'static', - regexSource: '^support$', - paramNames: [], - }); - }); - - it('compiles static + tag', () => { - expect(compileEmailPattern('support+[ticket]')).toEqual({ - kind: 'static-tag', - regexSource: '^support\\+([^+@]+)$', - paramNames: ['ticket'], - }); - }); - - it('compiles dynamic', () => { - expect(compileEmailPattern('[user]')).toEqual({ - kind: 'dynamic', - regexSource: '^([^+@]+)$', - paramNames: ['user'], - }); - }); - - it('compiles dynamic + tag', () => { - expect(compileEmailPattern('[user]+[tag]')).toEqual({ - kind: 'dynamic-tag', - regexSource: '^([^+@]+)\\+([^+@]+)$', - paramNames: ['user', 'tag'], - }); - }); - - it('escapes literal dots', () => { - expect(compileEmailPattern('alerts.ops')).toEqual({ - kind: 'static', - regexSource: '^alerts\\.ops$', - paramNames: [], - }); - }); - - it('returns null for too many `+` separators', () => { - expect(compileEmailPattern('a+b+c')).toBeNull(); - }); - - it('returns null for invalid literal chars', () => { - expect(compileEmailPattern('hello world')).toBeNull(); - }); - - it('lowercases uppercase basenames before compilation', () => { - // Patterns are lowercased to match the lowercased recipient — uppercase - // in the filename is fine, just normalized. - expect(compileEmailPattern('[Foo]')?.paramNames).toEqual(['foo']); - expect(compileEmailPattern('Support')?.regexSource).toBe('^support$'); - }); - - it('returns null for invalid param shapes', () => { - expect(compileEmailPattern('[1abc]')).toBeNull(); // starts with digit - expect(compileEmailPattern('[]')).toBeNull(); // empty - }); -}); - describe('parseEmail', () => { it('parses a minimal RFC 5322 message via postal-mime', async () => { const raw = diff --git a/packages/void/test/unit/email-own-account.test.ts b/packages/void/test/unit/email-own-account.test.ts index 295a7a9d2..945f3470e 100644 --- a/packages/void/test/unit/email-own-account.test.ts +++ b/packages/void/test/unit/email-own-account.test.ts @@ -13,7 +13,6 @@ */ import { describe, expect, it, vi } from 'vite-plus/test'; import { compileWorkerEntry } from '../../src/router/compile.ts'; -import { sendEmail } from '../../src/runtime/email.ts'; import { createMessageProxy, enactEmailActions, @@ -21,10 +20,11 @@ import { parseEmail, replyEmail, } from '../../src/runtime/email/inbound.ts'; +import { sendEmail } from '../../src/runtime/email/index.ts'; import { MimeError } from '../../src/runtime/email/mime.ts'; import { createEmailTestHarness } from '../../src/runtime/email/testing.ts'; -import { envContext } from '../../src/runtime/env-raw.ts'; -import { withRuntimeEnv } from '../../src/runtime/env.ts'; +import { envContext } from '../../src/runtime/env/raw.ts'; +import { withRuntimeEnv } from '../../src/runtime/env/runtime.ts'; // Stand-in for workerd's `EmailMessage`. It only needs to be a recognisable // class that keeps its constructor arguments, so a test can assert which diff --git a/packages/void/test/unit/email-pattern.test.ts b/packages/void/test/unit/email-pattern.test.ts new file mode 100644 index 000000000..bbe2351bd --- /dev/null +++ b/packages/void/test/unit/email-pattern.test.ts @@ -0,0 +1,64 @@ +import { describe, expect, it } from 'vite-plus/test'; +import { compileEmailPattern } from '../../src/shared/email-pattern.ts'; + +describe('compileEmailPattern', () => { + it('compiles static address', () => { + expect(compileEmailPattern('support')).toEqual({ + kind: 'static', + regexSource: '^support$', + paramNames: [], + }); + }); + + it('compiles static + tag', () => { + expect(compileEmailPattern('support+[ticket]')).toEqual({ + kind: 'static-tag', + regexSource: '^support\\+([^+@]+)$', + paramNames: ['ticket'], + }); + }); + + it('compiles dynamic', () => { + expect(compileEmailPattern('[user]')).toEqual({ + kind: 'dynamic', + regexSource: '^([^+@]+)$', + paramNames: ['user'], + }); + }); + + it('compiles dynamic + tag', () => { + expect(compileEmailPattern('[user]+[tag]')).toEqual({ + kind: 'dynamic-tag', + regexSource: '^([^+@]+)\\+([^+@]+)$', + paramNames: ['user', 'tag'], + }); + }); + + it('escapes literal dots', () => { + expect(compileEmailPattern('alerts.ops')).toEqual({ + kind: 'static', + regexSource: '^alerts\\.ops$', + paramNames: [], + }); + }); + + it('returns null for too many `+` separators', () => { + expect(compileEmailPattern('a+b+c')).toBeNull(); + }); + + it('returns null for invalid literal chars', () => { + expect(compileEmailPattern('hello world')).toBeNull(); + }); + + it('lowercases uppercase basenames before compilation', () => { + // Patterns are lowercased to match the lowercased recipient — uppercase + // in the filename is fine, just normalized. + expect(compileEmailPattern('[Foo]')?.paramNames).toEqual(['foo']); + expect(compileEmailPattern('Support')?.regexSource).toBe('^support$'); + }); + + it('returns null for invalid param shapes', () => { + expect(compileEmailPattern('[1abc]')).toBeNull(); // starts with digit + expect(compileEmailPattern('[]')).toBeNull(); // empty + }); +}); diff --git a/packages/void/test/unit/email-protocol.test.ts b/packages/void/test/unit/email-protocol.test.ts index 5d5e59872..9572f9b43 100644 --- a/packages/void/test/unit/email-protocol.test.ts +++ b/packages/void/test/unit/email-protocol.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it, vi } from 'vite-plus/test'; -import { verifyEmailReceiptThroughProxy } from '../../src/runtime/email-protocol.ts'; +import { verifyEmailReceiptThroughProxy } from '../../src/runtime/email/protocol.ts'; const input = { receipt: 'receipt-token', diff --git a/packages/void/test/unit/email-send.test.ts b/packages/void/test/unit/email-send.test.ts index d911d4504..0e44eb8b1 100644 --- a/packages/void/test/unit/email-send.test.ts +++ b/packages/void/test/unit/email-send.test.ts @@ -1,12 +1,12 @@ import { afterEach, describe, expect, it, vi } from 'vite-plus/test'; -import { sendEmail } from '../../src/runtime/email.ts'; import { clearDevBuffer, DEV_INBOX_ENV_VAR, listDevMessages, } from '../../src/runtime/email/dev-inbox.ts'; +import { sendEmail } from '../../src/runtime/email/index.ts'; import { createEmailTestHarness } from '../../src/runtime/email/testing.ts'; -import { withRuntimeEnv } from '../../src/runtime/env.ts'; +import { withRuntimeEnv } from '../../src/runtime/env/runtime.ts'; afterEach(() => { clearDevBuffer(); diff --git a/packages/void/test/unit/env-client-guard.test.ts b/packages/void/test/unit/env-client-guard.test.ts index 9826a30ca..781b75810 100644 --- a/packages/void/test/unit/env-client-guard.test.ts +++ b/packages/void/test/unit/env-client-guard.test.ts @@ -1,7 +1,7 @@ import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'; import { envClientGuardPlugin } from '../../src/plugin-env-client-guard.ts'; -import { string } from '../../src/runtime/env-helpers.ts'; -import { defineEnv } from '../../src/runtime/env-public.ts'; +import { string } from '../../src/runtime/env/helpers.ts'; +import { defineEnv } from '../../src/runtime/env/public.ts'; const ROOT = '/project'; type MessagePayload = @@ -86,7 +86,7 @@ function resetSchema() { // flag is one-way (can't be unset), so we mock the module instead for // the no-schema test. async function withNoSchema(fn: () => Promise): Promise { - const mod = await import('../../src/runtime/env-public.ts'); + const mod = await import('../../src/runtime/env/public.ts'); vi.spyOn(mod, '_hasRegisteredSchema').mockReturnValue(false); vi.spyOn(mod, '_getRegisteredSchema').mockReturnValue(null); try { diff --git a/packages/void/test/unit/env-command-target.test.ts b/packages/void/test/unit/env-command-target.test.ts index 97cefed76..21fc51a6e 100644 --- a/packages/void/test/unit/env-command-target.test.ts +++ b/packages/void/test/unit/env-command-target.test.ts @@ -2,8 +2,8 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'; -import { string } from '../../src/runtime/env-helpers.ts'; -import { defineEnv } from '../../src/runtime/env-public.ts'; +import { string } from '../../src/runtime/env/helpers.ts'; +import { defineEnv } from '../../src/runtime/env/public.ts'; const mocks = vi.hoisted(() => ({ getToken: vi.fn((): string | null => 'void-token'), diff --git a/packages/void/test/unit/env-export-conditions.test.ts b/packages/void/test/unit/env-export-conditions.test.ts index 16358dbd4..4121d16b5 100644 --- a/packages/void/test/unit/env-export-conditions.test.ts +++ b/packages/void/test/unit/env-export-conditions.test.ts @@ -37,16 +37,16 @@ describe('void/env export map', () => { envExport, new Set(['workerd', 'worker', 'module', 'browser', 'import']), ); - expect(resolved).toBe('./dist/runtime/env-public.mjs'); + expect(resolved).toBe('./dist/runtime/env/public.mjs'); }); it('resolves to the server variant under Node SSR conditions', () => { const resolved = resolveConditional(envExport, new Set(['node', 'module', 'import'])); - expect(resolved).toBe('./dist/runtime/env-public.mjs'); + expect(resolved).toBe('./dist/runtime/env/public.mjs'); }); it('resolves to the client stub under browser conditions', () => { const resolved = resolveConditional(envExport, new Set(['browser', 'module', 'import'])); - expect(resolved).toBe('./dist/runtime/env-public-client.mjs'); + expect(resolved).toBe('./dist/runtime/env/public-client.mjs'); }); }); diff --git a/packages/void/test/unit/env-filtering.test.ts b/packages/void/test/unit/env-filtering.test.ts index be4792e1a..b46fbdac7 100644 --- a/packages/void/test/unit/env-filtering.test.ts +++ b/packages/void/test/unit/env-filtering.test.ts @@ -4,7 +4,7 @@ import { getRuntimeEnv, withRuntimeEnv, requireRuntimeBinding, -} from '../../src/runtime/env.ts'; +} from '../../src/runtime/env/runtime.ts'; describe('internal binding filtering (real implementation)', () => { const testEnv = { diff --git a/packages/void/test/unit/env-prod-validation.test.ts b/packages/void/test/unit/env-prod-validation.test.ts index 2e76ab624..3539bd6d3 100644 --- a/packages/void/test/unit/env-prod-validation.test.ts +++ b/packages/void/test/unit/env-prod-validation.test.ts @@ -3,8 +3,8 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'; import { formatEnvReport, validateProdEnv } from '../../src/cli/env-validation.ts'; -import { number, string } from '../../src/runtime/env-helpers.ts'; -import { defineEnv } from '../../src/runtime/env-public.ts'; +import { number, string } from '../../src/runtime/env/helpers.ts'; +import { defineEnv } from '../../src/runtime/env/public.ts'; // The fixture env.ts only has to exist: tests register the shared schema with defineEnv. diff --git a/packages/void/test/unit/env-schema.test.ts b/packages/void/test/unit/env-schema.test.ts index 357b2d9a0..80686bcc4 100644 --- a/packages/void/test/unit/env-schema.test.ts +++ b/packages/void/test/unit/env-schema.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, it, expect, beforeEach, vi } from 'vite-plus/test'; -import { boolean, email, json, number, oneOf, string, url } from '../../src/runtime/env-helpers.ts'; +import { boolean, email, json, number, oneOf, string, url } from '../../src/runtime/env/helpers.ts'; import { defineEnv, env, @@ -10,8 +10,12 @@ import { _hasRegisteredSchema, _prepareEnv, _validateEnvOnce, -} from '../../src/runtime/env-public.ts'; -import { getRuntimeBinding, requireRuntimeBinding, withRuntimeEnv } from '../../src/runtime/env.ts'; +} from '../../src/runtime/env/public.ts'; +import { + getRuntimeBinding, + requireRuntimeBinding, + withRuntimeEnv, +} from '../../src/runtime/env/runtime.ts'; import { ENV_REGISTRY_KEY } from '../../src/shared/env-registry.ts'; // Reset schema between tests so order doesn't leak state. @@ -808,7 +812,7 @@ describe('several copies of void/env in one Worker', () => { async function secondCopy() { vi.resetModules(); - return await import('../../src/runtime/env-public.ts'); + return await import('../../src/runtime/env/public.ts'); } beforeEach(resetSchema); diff --git a/packages/void/test/unit/env-validation-selfhost.test.ts b/packages/void/test/unit/env-validation-selfhost.test.ts index 18421a195..7aa725fce 100644 --- a/packages/void/test/unit/env-validation-selfhost.test.ts +++ b/packages/void/test/unit/env-validation-selfhost.test.ts @@ -18,8 +18,8 @@ import { type SecretListRunResult, type SelfHostSchemaFacts, } from '../../src/cli/env-validation.ts'; -import { number, string } from '../../src/runtime/env-helpers.ts'; -import { defineEnv } from '../../src/runtime/env-public.ts'; +import { number, string } from '../../src/runtime/env/helpers.ts'; +import { defineEnv } from '../../src/runtime/env/public.ts'; import { _resetUnmaskCacheForTests } from '../../src/shared/env-mask.ts'; import type { StandardSchemaV1 } from '../../src/standard-schema.ts'; diff --git a/packages/void/test/unit/env.test.ts b/packages/void/test/unit/env.test.ts index f4c70851e..fe86109e5 100644 --- a/packages/void/test/unit/env.test.ts +++ b/packages/void/test/unit/env.test.ts @@ -1,5 +1,5 @@ import { afterAll, beforeEach, describe, expect, it, vi } from 'vite-plus/test'; -import { getRuntimeBinding, getRuntimeEnv, withRuntimeEnv } from '../../src/runtime/env.ts'; +import { getRuntimeBinding, getRuntimeEnv, withRuntimeEnv } from '../../src/runtime/env/runtime.ts'; const globalScope = globalThis as { __env__?: unknown; @@ -41,9 +41,9 @@ describe('runtime env resolution', () => { // dependency optimizer reload evaluates them again while a request is in flight. it('shares the request env and scope with another copy of the env module', async () => { vi.resetModules(); - const first = await import('../../src/runtime/env.ts'); + const first = await import('../../src/runtime/env/runtime.ts'); vi.resetModules(); - const second = await import('../../src/runtime/env.ts'); + const second = await import('../../src/runtime/env/runtime.ts'); expect(second.withRuntimeEnv).not.toBe(first.withRuntimeEnv); const key = {}; diff --git a/packages/void/test/unit/error-page-assets.test.ts b/packages/void/test/unit/error-page-assets.test.ts index 3a9ccc166..5208873a6 100644 --- a/packages/void/test/unit/error-page-assets.test.ts +++ b/packages/void/test/unit/error-page-assets.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vite-plus/test'; -import { inlineErrorPageAssets } from '../../src/runtime/error-pages/inline.ts'; +import { inlineErrorPageAssets } from '../../src/runtime/routing/error-pages/inline.ts'; const template = ` diff --git a/packages/void/test/unit/fetch-stream.test.ts b/packages/void/test/unit/fetch-stream.test.ts index bb894efcd..f6313da6b 100644 --- a/packages/void/test/unit/fetch-stream.test.ts +++ b/packages/void/test/unit/fetch-stream.test.ts @@ -31,8 +31,8 @@ declare module 'void/routes' { } import { ofetch } from 'ofetch'; -import { fetchStream } from '../../src/runtime/fetch-stream.ts'; -import { UsageLimit } from '../../src/runtime/limits.ts'; +import { fetchStream } from '../../src/runtime/client/fetch-stream.ts'; +import { UsageLimit } from '../../src/runtime/limits/index.ts'; function makeSSEStream(chunks: Array): ReadableStream { const encoder = new TextEncoder(); diff --git a/packages/void/test/unit/fetch-worker.test.ts b/packages/void/test/unit/fetch-worker.test.ts index ec655faa1..21b8ac0e6 100644 --- a/packages/void/test/unit/fetch-worker.test.ts +++ b/packages/void/test/unit/fetch-worker.test.ts @@ -2,8 +2,8 @@ import { AsyncLocalStorage } from 'node:async_hooks'; import { Hono } from 'hono'; import { describe, expect, it, vi, beforeEach, afterEach } from 'vite-plus/test'; import { compileWorkerClient } from '../../src/router/compile.ts'; -import { FetchError as RuntimeFetchError } from '../../src/runtime/fetch-error.ts'; -import { createServerFetch } from '../../src/runtime/fetch-server.ts'; +import { FetchError as RuntimeFetchError } from '../../src/runtime/client/fetch-error.ts'; +import { createServerFetch } from '../../src/runtime/client/fetch-server.ts'; describe('compileWorkerClient', () => { it('wires the server runtime to the app and request context', () => { diff --git a/packages/void/test/unit/fetch.test.ts b/packages/void/test/unit/fetch.test.ts index 6e240e49f..4682c5bc3 100644 --- a/packages/void/test/unit/fetch.test.ts +++ b/packages/void/test/unit/fetch.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi, beforeEach, afterEach } from 'vite-plus/test'; -import { fetch as typedFetch, FetchError } from '../../src/runtime/fetch.ts'; +import { fetch as typedFetch, FetchError } from '../../src/runtime/client/fetch.ts'; declare module 'void/routes' { interface RouteMap { diff --git a/packages/void/test/unit/fetch.typecheck.ts b/packages/void/test/unit/fetch.typecheck.ts index 41a7536ac..32cc5bae3 100644 --- a/packages/void/test/unit/fetch.typecheck.ts +++ b/packages/void/test/unit/fetch.typecheck.ts @@ -1,5 +1,5 @@ import { describe, it } from 'vite-plus/test'; -import { fetch as typedFetch } from '../../src/runtime/fetch.ts'; +import { fetch as typedFetch } from '../../src/runtime/client/fetch.ts'; declare module 'void/routes' { interface RouteMap { diff --git a/packages/void/test/unit/infer-props.typecheck.ts b/packages/void/test/unit/infer-props.typecheck.ts index 5aa263195..101bb8386 100644 --- a/packages/void/test/unit/infer-props.typecheck.ts +++ b/packages/void/test/unit/infer-props.typecheck.ts @@ -1,7 +1,7 @@ import { describe, expectTypeOf, it } from 'vite-plus/test'; import { z } from 'zod'; import type { InferProps } from '../../src/pages/defer.ts'; -import { defineHandler, defineMiddleware } from '../../src/runtime/handler.ts'; +import { defineHandler, defineMiddleware } from '../../src/runtime/handler/index.ts'; type Book = { id: string; title: string }; type Author = { id: string; name: string }; diff --git a/packages/void/test/unit/isr.test.ts b/packages/void/test/unit/isr.test.ts index 07b831b28..8375fc41b 100644 --- a/packages/void/test/unit/isr.test.ts +++ b/packages/void/test/unit/isr.test.ts @@ -1,7 +1,7 @@ import { hostRegistryKey, htmlEdgeKey, isrKey, isrPrefix, jsonEdgeKey } from '@void/isr/runtime'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'; -import { envContext } from '../../src/runtime/env-raw.ts'; -import { revalidate } from '../../src/runtime/isr.ts'; +import { envContext } from '../../src/runtime/env/raw.ts'; +import { revalidate } from '../../src/runtime/isr/index.ts'; const DPL = 'dpl_1'; const HOST = 'app.example.com'; diff --git a/packages/void/test/unit/kv.test.ts b/packages/void/test/unit/kv.test.ts index d210fb54a..5847ce1a0 100644 --- a/packages/void/test/unit/kv.test.ts +++ b/packages/void/test/unit/kv.test.ts @@ -2,7 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vite-plus/test'; vi.mock('cloudflare:workers', () => ({ env: {} })); -import { createKV, type KVClient } from '../../src/runtime/kv.ts'; +import { createKV, type KVClient } from '../../src/runtime/kv/index.ts'; function createMockKVNamespace() { const ns = { diff --git a/packages/void/test/unit/limits.test.ts b/packages/void/test/unit/limits.test.ts index a74f5e999..e44a38473 100644 --- a/packages/void/test/unit/limits.test.ts +++ b/packages/void/test/unit/limits.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vite-plus/test'; -import { UsageLimit, asUsageLimit, limitFromResponse } from '../../src/runtime/limits.ts'; +import { UsageLimit, asUsageLimit, limitFromResponse } from '../../src/runtime/limits/index.ts'; describe('usage limits', () => { it('preserves the error type and identity when restoring structured limits', () => { diff --git a/packages/void/test/unit/live-client.test.ts b/packages/void/test/unit/live-client.test.ts index 7faf5673a..92504f3d8 100644 --- a/packages/void/test/unit/live-client.test.ts +++ b/packages/void/test/unit/live-client.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'; -import { connectLiveStream, type ConnectLiveStreamOptions } from '../../src/runtime/live-client.ts'; +import { connectLiveStream, type ConnectLiveStreamOptions } from '../../src/runtime/live/client.ts'; import { MockEventSource } from '../helpers/mock-event-source.ts'; const originalLocation = (globalThis as { location?: unknown }).location; diff --git a/packages/void/test/unit/live-server.test.ts b/packages/void/test/unit/live-server.test.ts index 0ccdf3ed0..b342965bb 100644 --- a/packages/void/test/unit/live-server.test.ts +++ b/packages/void/test/unit/live-server.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from 'vite-plus/test'; -import type { CloudContext } from '../../src/runtime/handler.ts'; -import { createLiveDurableObject } from '../../src/runtime/live-server.ts'; -import { __setLiveDev, defineLiveStream, type LiveLimits } from '../../src/runtime/live.ts'; +import type { CloudContext } from '../../src/runtime/handler/index.ts'; +import { __setLiveDev, defineLiveStream, type LiveLimits } from '../../src/runtime/live/index.ts'; +import { createLiveDurableObject } from '../../src/runtime/live/server.ts'; const LIMITS: LiveLimits = { maxSubscriptionsPerConnection: 256, diff --git a/packages/void/test/unit/migration-binding-consistency.test.ts b/packages/void/test/unit/migration-binding-consistency.test.ts index 8337d9dd7..d93d39bfb 100644 --- a/packages/void/test/unit/migration-binding-consistency.test.ts +++ b/packages/void/test/unit/migration-binding-consistency.test.ts @@ -6,7 +6,7 @@ import type { MigrationFile } from '../../src/migrations/validate.ts'; import { createMigrationHandler, type MigrationResponse, -} from '../../src/runtime/migration-handler.ts'; +} from '../../src/runtime/db/migrations/d1-handler.ts'; const noBindings: InferredBindings = { needsD1: false, diff --git a/packages/void/test/unit/migration-concurrency.test.ts b/packages/void/test/unit/migration-concurrency.test.ts index 5f9adb39f..dc41f34ba 100644 --- a/packages/void/test/unit/migration-concurrency.test.ts +++ b/packages/void/test/unit/migration-concurrency.test.ts @@ -5,7 +5,7 @@ import { createMigrationHandler, type MigrationEntry, type MigrationResponse, -} from '../../src/runtime/migration-handler.ts'; +} from '../../src/runtime/db/migrations/d1-handler.ts'; const databases: Array = []; afterEach(() => { diff --git a/packages/void/test/unit/migration-handler-pg.test.ts b/packages/void/test/unit/migration-handler-pg.test.ts index 7d5e5f648..3b1a3779c 100644 --- a/packages/void/test/unit/migration-handler-pg.test.ts +++ b/packages/void/test/unit/migration-handler-pg.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vite-plus/test'; -import { createMigrationHandler } from '../../src/runtime/migration-handler-pg.ts'; -import { disablePgPassFallback } from '../../src/runtime/pg.ts'; +import { createMigrationHandler } from '../../src/runtime/db/migrations/postgres-handler.ts'; +import { disablePgPassFallback } from '../../src/runtime/db/pgpass.ts'; // The names in `_void_migrations`, kept in memory by the fake client below. const pgApplied = vi.hoisted((): Array => []); diff --git a/packages/void/test/unit/mysql-migration-sql.test.ts b/packages/void/test/unit/mysql-migration-sql.test.ts index b92d6db3b..10d0d3c9f 100644 --- a/packages/void/test/unit/mysql-migration-sql.test.ts +++ b/packages/void/test/unit/mysql-migration-sql.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vite-plus/test'; -import { splitMySqlMigrationSql } from '../../src/runtime/mysql-migration-sql.ts'; +import { splitMySqlMigrationSql } from '../../src/runtime/db/migrations/mysql-sql.ts'; describe('splitMySqlMigrationSql', () => { it('splits a file without breakpoints at its semicolons', () => { diff --git a/packages/void/test/unit/nitro.test.ts b/packages/void/test/unit/nitro.test.ts index 08fe8bc53..04658f129 100644 --- a/packages/void/test/unit/nitro.test.ts +++ b/packages/void/test/unit/nitro.test.ts @@ -7,8 +7,8 @@ import { toSlash } from 'pathslash'; import type { Plugin } from 'vite'; import { afterEach, describe, expect, it } from 'vite-plus/test'; import voidNitroModule from '../../src/nitro.ts'; -import { db } from '../../src/runtime/db.ts'; -import { getRuntimeRequestResource, withRuntimeEnv } from '../../src/runtime/env.ts'; +import { db } from '../../src/runtime/db/index.ts'; +import { getRuntimeRequestResource, withRuntimeEnv } from '../../src/runtime/env/runtime.ts'; const roots: Array = []; const envModuleFile = fileURLToPath(import.meta.resolve('#self/_env')); diff --git a/packages/void/test/unit/page-boundaries.test.ts b/packages/void/test/unit/page-boundaries.test.ts index 57ad1213e..ce75686c6 100644 --- a/packages/void/test/unit/page-boundaries.test.ts +++ b/packages/void/test/unit/page-boundaries.test.ts @@ -12,10 +12,10 @@ import { renderHeadToString } from '../../src/pages/head.ts'; import { generateComponentManifest } from '../../src/pages/manifest.ts'; import { scanPages } from '../../src/pages/scan.ts'; import { deserializePageData } from '../../src/pages/serialize.ts'; -import { defineHandler, type CloudEnv } from '../../src/runtime/handler.ts'; -import { createErrorRenderer } from '../../src/runtime/routing-errors.ts'; -import { createPageGetHandler, createPagesFallback } from '../../src/runtime/routing-pages.ts'; -import { createRoutingRuntime } from '../../src/runtime/routing.ts'; +import { defineHandler, type CloudEnv } from '../../src/runtime/handler/index.ts'; +import { createErrorRenderer } from '../../src/runtime/routing/errors.ts'; +import { createRoutingRuntime } from '../../src/runtime/routing/index.ts'; +import { createPageGetHandler, createPagesFallback } from '../../src/runtime/routing/pages.ts'; const roots: Array = []; function fixture(files: Record) { diff --git a/packages/void/test/unit/page-http-errors.test.ts b/packages/void/test/unit/page-http-errors.test.ts index c3e4e54fa..13b63194d 100644 --- a/packages/void/test/unit/page-http-errors.test.ts +++ b/packages/void/test/unit/page-http-errors.test.ts @@ -4,15 +4,15 @@ import { matchedRoutes } from 'hono/route'; import { describe, expect, it, vi } from 'vite-plus/test'; import { PAGES_PROTOCOL_VERSION } from '../../../edge/src/pages-protocol.ts'; import { deserializePageData } from '../../src/pages/serialize.ts'; -import { defineHandler, defineMiddleware } from '../../src/runtime/handler.ts'; -import { createErrorRenderer } from '../../src/runtime/routing-errors.ts'; +import { defineHandler, defineMiddleware } from '../../src/runtime/handler/index.ts'; +import { createErrorRenderer } from '../../src/runtime/routing/errors.ts'; +import { createHttpRouteHandler } from '../../src/runtime/routing/index.ts'; import { createPageErrorHandler, createPageGetHandler, createPageMutationHandler, type PageRouteOptions, -} from '../../src/runtime/routing-pages.ts'; -import { createHttpRouteHandler } from '../../src/runtime/routing.ts'; +} from '../../src/runtime/routing/pages.ts'; const pagesHeaders = { 'X-VoidPages': 'true', 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION }; const origins = ['loader', 'handler middleware', 'application middleware'] as const; diff --git a/packages/void/test/unit/pages-client.test.ts b/packages/void/test/unit/pages-client.test.ts index 90aac5ce0..8a91fdb15 100644 --- a/packages/void/test/unit/pages-client.test.ts +++ b/packages/void/test/unit/pages-client.test.ts @@ -18,14 +18,14 @@ import { parseCacheFor } from '../../src/pages/prefetch.ts'; import { ValidationError } from '../../src/pages/protocol.ts'; import { decodePageData, serializePageData } from '../../src/pages/serialize.ts'; import type { PageDefinition } from '../../src/pages/types.ts'; -import type { CloudContext } from '../../src/runtime/handler.ts'; +import type { CloudContext } from '../../src/runtime/handler/index.ts'; import { createPageGetHandler, createPageMutationHandler, createNamedActionMarker, createRoutingRuntime, type RoutingContext, -} from '../../src/runtime/routing.ts'; +} from '../../src/runtime/routing/index.ts'; type DeferredTestWindow = Window & { __resolveDeferred(group: string, data: unknown): void; diff --git a/packages/void/test/unit/pages-compile.test.ts b/packages/void/test/unit/pages-compile.test.ts index 61afe9362..d64a25ce2 100644 --- a/packages/void/test/unit/pages-compile.test.ts +++ b/packages/void/test/unit/pages-compile.test.ts @@ -8,7 +8,7 @@ const testOptions = { honoPath: '/resolved/hono/index.mjs', honoRoutePath: '/resolved/hono/route.mjs', - runtimeEnvPath: '/resolved/void/runtime/env.mjs', + runtimeEnvPath: '/resolved/void/runtime/env/runtime.mjs', projectRoot: '/project', homeDir: '/Users/test', reactRefresh: false, diff --git a/packages/void/test/unit/pages-protocol.test.ts b/packages/void/test/unit/pages-protocol.test.ts index ff1d6a57b..ae19521b9 100644 --- a/packages/void/test/unit/pages-protocol.test.ts +++ b/packages/void/test/unit/pages-protocol.test.ts @@ -14,8 +14,12 @@ import { decodePageData, serializePageData, } from '../../src/pages/serialize.ts'; -import { defineHandler, type CloudContext, type CloudEnv } from '../../src/runtime/handler.ts'; -import { createRoutingRuntime } from '../../src/runtime/routing.ts'; +import { + defineHandler, + type CloudContext, + type CloudEnv, +} from '../../src/runtime/handler/index.ts'; +import { createRoutingRuntime } from '../../src/runtime/routing/index.ts'; type RenderPage = { component: string }; type PageResponse = { diff --git a/packages/void/test/unit/pages-redirect.test.ts b/packages/void/test/unit/pages-redirect.test.ts index 65a67bccb..8f194d3ad 100644 --- a/packages/void/test/unit/pages-redirect.test.ts +++ b/packages/void/test/unit/pages-redirect.test.ts @@ -2,7 +2,7 @@ import { Hono } from 'hono'; import { afterEach, beforeEach, expect, it, vi } from 'vite-plus/test'; import { submitIslandAction } from '../../src/pages/island-action.ts'; import { fetchPages } from '../../src/pages/redirect.ts'; -import { createRoutingRuntime } from '../../src/runtime/routing.ts'; +import { createRoutingRuntime } from '../../src/runtime/routing/index.ts'; beforeEach(() => { vi.stubGlobal('window', { location: { origin: 'https://app.test', pathname: '/', search: '' } }); diff --git a/packages/void/test/unit/plugin-dev-asset-routing.test.ts b/packages/void/test/unit/plugin-dev-asset-routing.test.ts index 83490d489..6ca120d58 100644 --- a/packages/void/test/unit/plugin-dev-asset-routing.test.ts +++ b/packages/void/test/unit/plugin-dev-asset-routing.test.ts @@ -578,8 +578,8 @@ describe('voidPlugin dev asset routing', () => { vi.stubEnv('VOID_TEST_UNDECLARED', 'from-shell'); vi.stubEnv('VOID_TEST_UNRELATED', 'must-stay-out'); - const { defineEnv } = await import('../../src/runtime/env-public.ts'); - const { string } = await import('../../src/runtime/env-helpers.ts'); + const { defineEnv } = await import('../../src/runtime/env/public.ts'); + const { string } = await import('../../src/runtime/env/helpers.ts'); defineEnv({ VOID_TEST_TOKEN: string(), VOID_TEST_FILE_ONLY: string(), diff --git a/packages/void/test/unit/plugin-drizzle.test.ts b/packages/void/test/unit/plugin-drizzle.test.ts index e16020b51..05bc5b0b5 100644 --- a/packages/void/test/unit/plugin-drizzle.test.ts +++ b/packages/void/test/unit/plugin-drizzle.test.ts @@ -16,7 +16,7 @@ vi.mock('../../src/log', () => ({ import { voidWarn } from '../../src/log.ts'; import { getMiniflareDatabasePath, openSqliteDatabase } from '../../src/migrations/runner.ts'; import { drizzlePlugin } from '../../src/plugin-drizzle.ts'; -import { withRuntimeEnv } from '../../src/runtime/env.ts'; +import { withRuntimeEnv } from '../../src/runtime/env/runtime.ts'; import { startFakeMySqlServer } from '../helpers/fake-mysql-server.ts'; const roots: Array = []; @@ -73,7 +73,7 @@ async function loadExecutableDbModule( fakeStateKeys.push(stateKey); const fakeDriverPath = join(root, 'fake-driver.mjs'); - const envUrl = new URL('../../src/runtime/env.ts', import.meta.url).href; + const envUrl = new URL('../../src/runtime/env/runtime.ts', import.meta.url).href; const stateExpression = `globalThis[${JSON.stringify(stateKey)}]`; const createDatabaseSource = ` function createPool(dialect, options) { @@ -209,7 +209,7 @@ async function loadDriverDbModule(dialect: 'postgresql' | 'mysql'): Promise<{ const root = createProjectRoot({ schema: false }); const plugin = drizzlePlugin(root, false, dialect, { forceVirtualDb: true }); const load = getHookHandler(plugin.load) as (this: object, id: string) => string; - const envUrl = new URL('../../src/runtime/env.ts', import.meta.url).href; + const envUrl = new URL('../../src/runtime/env/runtime.ts', import.meta.url).href; const clientsKey = `__void_db_clients_${dialect}_${crypto.randomUUID().replaceAll('-', '')}`; const clients: Array<{ end(): unknown }> = []; (globalThis as Record)[clientsKey] = clients; @@ -250,7 +250,7 @@ async function loadMySqlDbModule(): Promise<{ const root = createProjectRoot(); const plugin = drizzlePlugin(root, false, 'mysql', { forceVirtualDb: true }); const load = getHookHandler(plugin.load) as (this: object, id: string) => string; - const envUrl = new URL('../../src/runtime/env.ts', import.meta.url).href; + const envUrl = new URL('../../src/runtime/env/runtime.ts', import.meta.url).href; const code = load .call({}, '\0virtual:void-db') .replace( @@ -620,7 +620,7 @@ describe('drizzlePlugin db typing generation', () => { const root = createProjectRoot({ schema: hasSchema }); const plugin = drizzlePlugin(root, false, 'mysql', { forceVirtualDb: true }); const load = getHookHandler(plugin.load) as (this: object, id: string) => string; - const envUrl = new URL('../../src/runtime/env.ts', import.meta.url).href; + const envUrl = new URL('../../src/runtime/env/runtime.ts', import.meta.url).href; const code = load .call({}, '\0virtual:void-db') .replace( @@ -723,7 +723,7 @@ export const requestPoolConfig = (env) => const root = createProjectRoot({ schema: hasSchema }); const plugin = drizzlePlugin(root, false, 'postgresql', { forceVirtualDb: true }); const load = getHookHandler(plugin.load) as (this: object, id: string) => string; - const envUrl = new URL('../../src/runtime/env.ts', import.meta.url).href; + const envUrl = new URL('../../src/runtime/env/runtime.ts', import.meta.url).href; const code = load .call({}, '\0virtual:void-db') .replace( diff --git a/packages/void/test/unit/plugin-framework-triggers.test.ts b/packages/void/test/unit/plugin-framework-triggers.test.ts index 7bd3538a2..050e50088 100644 --- a/packages/void/test/unit/plugin-framework-triggers.test.ts +++ b/packages/void/test/unit/plugin-framework-triggers.test.ts @@ -21,7 +21,7 @@ import { hasOwnAstroMiddleware, nitroDevTriggerInjectPlugin, } from '../../src/plugin-framework-triggers.ts'; -import type { QueueBatch } from '../../src/runtime/handler.ts'; +import type { QueueBatch } from '../../src/runtime/handler/index.ts'; const tempDirs: Array = []; diff --git a/packages/void/test/unit/plugin-routing.test.ts b/packages/void/test/unit/plugin-routing.test.ts index 23b340fb8..59db7ee78 100644 --- a/packages/void/test/unit/plugin-routing.test.ts +++ b/packages/void/test/unit/plugin-routing.test.ts @@ -335,11 +335,11 @@ describe('routingPlugin', () => { ); const browserCode = await load('virtual:void-client-browser:react'); - expect(browserCode).toContain('auth-client-react.mjs'); + expect(browserCode).toContain('auth/client-react.mjs'); expect(browserCode).not.toContain('cloudflare:workers'); const workerCode = await load('virtual:void-client-worker:react'); - expect(workerCode).toContain('auth-client-react.mjs'); + expect(workerCode).toContain('auth/client-react.mjs'); expect(workerCode).toContain('cloudflare:workers'); }); @@ -778,7 +778,7 @@ describe('routingPlugin', () => { { change: 'database dialect', config: { database: 'pg', auth: { providers: ['email'] } }, - expected: 'better-auth-pg.mjs', + expected: 'auth/better-auth-postgres.mjs', }, ])('refreshes auth $change on a body save', async ({ config, expected }) => { const root = createTempRoot(); diff --git a/packages/void/test/unit/plugin-version-metadata.test.ts b/packages/void/test/unit/plugin-version-metadata.test.ts index 13d07da94..575cb2aca 100644 --- a/packages/void/test/unit/plugin-version-metadata.test.ts +++ b/packages/void/test/unit/plugin-version-metadata.test.ts @@ -3,7 +3,7 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import type { ConfigEnv, UserConfig } from 'vite'; import { afterEach, describe, expect, it, vi } from 'vite-plus/test'; -import { createWorkerFetch } from '../../src/runtime/routing-worker.ts'; +import { createWorkerFetch } from '../../src/runtime/routing/worker.ts'; import { CLOUDFLARE_DEPLOY_BUILD_ENV } from '../../src/shared/env.ts'; import { CLOUDFLARE_PRESERVE_BINDINGS_BUILD_ENV, diff --git a/packages/void/test/unit/prerender-path.test.ts b/packages/void/test/unit/prerender-path.test.ts index 7aa055941..2a68caed4 100644 --- a/packages/void/test/unit/prerender-path.test.ts +++ b/packages/void/test/unit/prerender-path.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vite-plus/test'; -import { buildPrerenderPath } from '../../src/runtime/prerender-path.ts'; +import { buildPrerenderPath } from '../../src/runtime/routing/prerender-path.ts'; const FILE = 'pages/blog/[slug].server.ts'; diff --git a/packages/void/test/unit/prerender-render.test.ts b/packages/void/test/unit/prerender-render.test.ts index 053c1860f..92446780b 100644 --- a/packages/void/test/unit/prerender-render.test.ts +++ b/packages/void/test/unit/prerender-render.test.ts @@ -10,7 +10,7 @@ import { renderPrerenderPaths, renderBoundary404, } from '../../src/prerender-render.ts'; -import { createAssetFallback } from '../../src/runtime/routing-worker.ts'; +import { createAssetFallback } from '../../src/runtime/routing/worker.ts'; const roots: Array = []; const pageHtml = (pageData: unknown) => diff --git a/packages/void/test/unit/prerender.test.ts b/packages/void/test/unit/prerender.test.ts index 791804f1e..97cebd8d9 100644 --- a/packages/void/test/unit/prerender.test.ts +++ b/packages/void/test/unit/prerender.test.ts @@ -12,7 +12,7 @@ import { prerenderPages, prerenderPagesNode, } from '../../src/prerender.ts'; -import { renderDefaultErrorPage } from '../../src/runtime/error-pages/index.ts'; +import { renderDefaultErrorPage } from '../../src/runtime/routing/error-pages/index.ts'; import { INTERNAL_ENV_KEYS, stripInternalEnvKeys } from '../../src/shared/env.ts'; const tempDirs: Array = []; diff --git a/packages/void/test/unit/remote/d1.test.ts b/packages/void/test/unit/remote/d1.test.ts index c9cc61a3c..ae47b31a7 100644 --- a/packages/void/test/unit/remote/d1.test.ts +++ b/packages/void/test/unit/remote/d1.test.ts @@ -1,6 +1,6 @@ import { integer, sqliteTable, text } from 'drizzle-orm/sqlite-core'; import { describe, it, expect, vi, afterEach } from 'vite-plus/test'; -import { createDb } from '../../../src/runtime/db.ts'; +import { createDb } from '../../../src/runtime/db/index.ts'; import { ProxyClient } from '../../../src/runtime/remote/client.ts'; import { ProxyD1Database } from '../../../src/runtime/remote/d1.ts'; diff --git a/packages/void/test/unit/require-auth.test.ts b/packages/void/test/unit/require-auth.test.ts index 6627dc909..474ea28ce 100644 --- a/packages/void/test/unit/require-auth.test.ts +++ b/packages/void/test/unit/require-auth.test.ts @@ -1,7 +1,7 @@ import { Hono } from 'hono'; import { HTTPException } from 'hono/http-exception'; import { describe, expect, it, vi } from 'vite-plus/test'; -import { requireAuth, type AuthUser } from '../../src/runtime/auth.ts'; +import { requireAuth, type AuthUser } from '../../src/runtime/auth/index.ts'; const user: AuthUser = { id: 'demo', diff --git a/packages/void/test/unit/resource-name-runtime.test.ts b/packages/void/test/unit/resource-name-runtime.test.ts index ea6d6597c..d52f60ee4 100644 --- a/packages/void/test/unit/resource-name-runtime.test.ts +++ b/packages/void/test/unit/resource-name-runtime.test.ts @@ -1,11 +1,11 @@ import { describe, expect, it, vi } from 'vite-plus/test'; -import { defineDurableState } from '../../src/runtime/durable.ts'; +import { defineDurableState } from '../../src/runtime/durable/index.ts'; +import { defineRoom, defineWebSocket } from '../../src/runtime/ws/index.ts'; import { buildWebSocketInstanceId, createWebSocketDurableObject, forwardWebSocketRequest, -} from '../../src/runtime/ws-server.ts'; -import { defineRoom, defineWebSocket } from '../../src/runtime/ws.ts'; +} from '../../src/runtime/ws/server.ts'; import type { StandardSchemaV1 } from '../../src/standard-schema.ts'; vi.mock('cloudflare:workers', () => ({ DurableObject: class {} })); diff --git a/packages/void/test/unit/response.test.ts b/packages/void/test/unit/response.test.ts index 95c5fd09f..a47b38ead 100644 --- a/packages/void/test/unit/response.test.ts +++ b/packages/void/test/unit/response.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vite-plus/test'; -import { convertReturnValue } from '../../src/runtime/response.ts'; +import { convertReturnValue } from '../../src/runtime/handler/response.ts'; describe('convertReturnValue', () => { it('passes through Response objects', () => { diff --git a/packages/void/test/unit/route-type-extraction.typecheck.ts b/packages/void/test/unit/route-type-extraction.typecheck.ts index ec62a72f1..218f7e8f0 100644 --- a/packages/void/test/unit/route-type-extraction.typecheck.ts +++ b/packages/void/test/unit/route-type-extraction.typecheck.ts @@ -2,7 +2,7 @@ import { type as arktype } from 'arktype'; import * as v from 'valibot'; import { describe, expectTypeOf, it } from 'vite-plus/test'; import { z } from 'zod'; -import { defineHandler, defineMiddleware } from '../../src/runtime/handler.ts'; +import { defineHandler, defineMiddleware } from '../../src/runtime/handler/index.ts'; import type { StandardSchemaV1 } from '../../src/standard-schema.ts'; type ExtractInput = { diff --git a/packages/void/test/unit/route-url-builder.test.ts b/packages/void/test/unit/route-url-builder.test.ts index 3475b46a0..4e2c496a0 100644 --- a/packages/void/test/unit/route-url-builder.test.ts +++ b/packages/void/test/unit/route-url-builder.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vite-plus/test'; import { routeUrl } from '../../src/routes-stub.ts'; -import { toUrlString } from '../../src/runtime/route-url.ts'; +import { toUrlString } from '../../src/runtime/routing/route-url.ts'; declare module 'void/routes' { interface RoutePathMap { diff --git a/packages/void/test/unit/route-url.test.ts b/packages/void/test/unit/route-url.test.ts index bba54a7a5..386dd2ced 100644 --- a/packages/void/test/unit/route-url.test.ts +++ b/packages/void/test/unit/route-url.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vite-plus/test'; -import { interpolateRouteParams } from '../../src/runtime/route-url.ts'; +import { interpolateRouteParams } from '../../src/runtime/routing/route-url.ts'; describe('route URL interpolation', () => { it.each([ diff --git a/packages/void/test/unit/routing-runtime.test.ts b/packages/void/test/unit/routing-runtime.test.ts index 79d8735dd..080d97ff3 100644 --- a/packages/void/test/unit/routing-runtime.test.ts +++ b/packages/void/test/unit/routing-runtime.test.ts @@ -8,11 +8,23 @@ import { PAGES_PROTOCOL_VERSION } from '../../../edge/src/pages-protocol.ts'; import { defer } from '../../src/pages/defer.ts'; import { ValidationError } from '../../src/pages/protocol.ts'; import { decodePageData, serializePageData } from '../../src/pages/serialize.ts'; -import { _validateEnvOnce, defineEnv, env } from '../../src/runtime/env-public.ts'; -import { withRuntimeEnv } from '../../src/runtime/env.ts'; -import { defineHandler, defineMiddleware, type CloudContext } from '../../src/runtime/handler.ts'; -import { createClientAssetTags, createManifestLoader } from '../../src/runtime/routing-assets.ts'; -import { createErrorRenderer } from '../../src/runtime/routing-errors.ts'; +import { _validateEnvOnce, defineEnv, env } from '../../src/runtime/env/public.ts'; +import { withRuntimeEnv } from '../../src/runtime/env/runtime.ts'; +import { + defineHandler, + defineMiddleware, + type CloudContext, +} from '../../src/runtime/handler/index.ts'; +import { createClientAssetTags, createManifestLoader } from '../../src/runtime/routing/assets.ts'; +import { createErrorRenderer } from '../../src/runtime/routing/errors.ts'; +import { + createHttpRouteHandler, + createModuleLoader, + createRoutingRuntime, + type RoutingContext, + type RoutingHeaderRule, + type RoutingRuntime, +} from '../../src/runtime/routing/index.ts'; import { createAssetNotFound, createPageGetHandler, @@ -21,7 +33,7 @@ import { createNamedActionMarker, createSsrFallback, markRouteHandler, -} from '../../src/runtime/routing-pages.ts'; +} from '../../src/runtime/routing/pages.ts'; import { applyAssetCachePolicy, createAssetCachePolicy, @@ -29,15 +41,7 @@ import { createWorkerFetch, filterInternalBindings, type RuntimeEnvironment, -} from '../../src/runtime/routing-worker.ts'; -import { - createHttpRouteHandler, - createModuleLoader, - createRoutingRuntime, - type RoutingContext, - type RoutingHeaderRule, - type RoutingRuntime, -} from '../../src/runtime/routing.ts'; +} from '../../src/runtime/routing/worker.ts'; import type { StandardSchemaV1 } from '../../src/standard-schema.ts'; const context = { waitUntil() {}, passThroughOnException() {}, props: {} }; diff --git a/packages/void/test/unit/runner-mysql.test.ts b/packages/void/test/unit/runner-mysql.test.ts index dcef1423e..08622db6a 100644 --- a/packages/void/test/unit/runner-mysql.test.ts +++ b/packages/void/test/unit/runner-mysql.test.ts @@ -10,9 +10,9 @@ import { runMySqlMigrations, type MySqlClient, } from '../../src/migrations/runner-mysql.ts'; -import { runVoidAuthMigrations } from '../../src/runtime/better-auth-mysql.ts'; -import { createMigrationHandler } from '../../src/runtime/migration-handler-mysql.ts'; -import { holdMySqlMigrationLease } from '../../src/runtime/migration-lock-mysql.ts'; +import { runVoidAuthMigrations } from '../../src/runtime/auth/better-auth-mysql.ts'; +import { createMigrationHandler } from '../../src/runtime/db/migrations/mysql-handler.ts'; +import { holdMySqlMigrationLease } from '../../src/runtime/db/migrations/mysql-lock.ts'; const mysqlConnections = vi.hoisted(() => [] as Array); const mysqlServer = vi.hoisted(() => ({ database: undefined as unknown })); diff --git a/packages/void/test/unit/runtime-log.test.ts b/packages/void/test/unit/runtime-log.test.ts index b9d4295b5..8af8bd190 100644 --- a/packages/void/test/unit/runtime-log.test.ts +++ b/packages/void/test/unit/runtime-log.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'; -import { logger } from '../../src/runtime/log.ts'; +import { logger } from '../../src/runtime/log/index.ts'; describe('runtime log', () => { beforeEach(() => { diff --git a/packages/void/test/unit/sandbox-runtime.test.ts b/packages/void/test/unit/sandbox-runtime.test.ts index 84fcf4e1c..f7e73095e 100644 --- a/packages/void/test/unit/sandbox-runtime.test.ts +++ b/packages/void/test/unit/sandbox-runtime.test.ts @@ -7,15 +7,15 @@ vi.mock('@cloudflare/sandbox', () => ({ S3Gateway: class {}, })); vi.mock('cloudflare:workers', () => ({ DurableObject: class {}, RpcTarget: class {} })); -import { envContext } from '../../src/runtime/env-raw.ts'; -import { UsageLimit } from '../../src/runtime/limits.ts'; +import { envContext } from '../../src/runtime/env/raw.ts'; +import { UsageLimit } from '../../src/runtime/limits/index.ts'; import { getSandbox, sandbox, __setSandboxBindingName, SandboxLimitError, SandboxUnavailableError, -} from '../../src/runtime/sandbox.ts'; +} from '../../src/runtime/sandbox/index.ts'; afterEach(() => { vi.clearAllMocks(); diff --git a/packages/void/test/unit/sandbox.typecheck.ts b/packages/void/test/unit/sandbox.typecheck.ts index 0d45ee003..fe9c75045 100644 --- a/packages/void/test/unit/sandbox.typecheck.ts +++ b/packages/void/test/unit/sandbox.typecheck.ts @@ -1,5 +1,5 @@ import { expectTypeOf } from 'vite-plus/test'; -import type { SandboxClient, SandboxProcess } from '../../src/runtime/sandbox.ts'; +import type { SandboxClient, SandboxProcess } from '../../src/runtime/sandbox/index.ts'; declare const sandboxClient: SandboxClient; declare const process: SandboxProcess; diff --git a/packages/void/test/unit/secret-cloudflare-validation.test.ts b/packages/void/test/unit/secret-cloudflare-validation.test.ts index b68ce664d..da46e94c9 100644 --- a/packages/void/test/unit/secret-cloudflare-validation.test.ts +++ b/packages/void/test/unit/secret-cloudflare-validation.test.ts @@ -3,8 +3,8 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { cancel, confirm, CANCEL_SYMBOL, password } from '@voidzero-dev/vite-plus-prompts'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'; -import { number, string } from '../../src/runtime/env-helpers.ts'; -import { defineEnv } from '../../src/runtime/env-public.ts'; +import { number, string } from '../../src/runtime/env/helpers.ts'; +import { defineEnv } from '../../src/runtime/env/public.ts'; const cloudflare = vi.hoisted(() => ({ put: vi.fn(), diff --git a/packages/void/test/unit/seed.typecheck.ts b/packages/void/test/unit/seed.typecheck.ts index 2f48bc509..689e3a4bc 100644 --- a/packages/void/test/unit/seed.typecheck.ts +++ b/packages/void/test/unit/seed.typecheck.ts @@ -1,7 +1,12 @@ -import { integer, sqliteTable, text as sqliteText } from '../../src/runtime/schema-d1.ts'; -import { int, mysqlTable, text as mysqlText } from '../../src/runtime/schema-mysql.ts'; -import { pgTable, serial, text as pgText, timestamp } from '../../src/runtime/schema-pg.ts'; -import { defineSeed } from '../../src/runtime/seed.ts'; +import { integer, sqliteTable, text as sqliteText } from '../../src/runtime/db/schema/d1.ts'; +import { int, mysqlTable, text as mysqlText } from '../../src/runtime/db/schema/mysql.ts'; +import { + pgTable, + serial, + text as pgText, + timestamp, +} from '../../src/runtime/db/schema/postgres.ts'; +import { defineSeed } from '../../src/runtime/db/seed.ts'; const sqliteSchema = { messages: sqliteTable('messages', { diff --git a/packages/void/test/unit/sse.test.ts b/packages/void/test/unit/sse.test.ts index af00f29fd..6d1e867bb 100644 --- a/packages/void/test/unit/sse.test.ts +++ b/packages/void/test/unit/sse.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'; -import { connectEventStream } from '../../src/runtime/sse-client.ts'; +import { connectEventStream } from '../../src/runtime/sse/client.ts'; import { eventStream, formatSse, @@ -7,7 +7,7 @@ import { getLastEventId, SseStreamClosedError, type SseStream, -} from '../../src/runtime/sse.ts'; +} from '../../src/runtime/sse/index.ts'; import { MockEventSource } from '../helpers/mock-event-source.ts'; const decoder = new TextDecoder(); diff --git a/packages/void/test/unit/storage.test.ts b/packages/void/test/unit/storage.test.ts index 043c74ec6..818ccec6d 100644 --- a/packages/void/test/unit/storage.test.ts +++ b/packages/void/test/unit/storage.test.ts @@ -2,7 +2,7 @@ import { describe, it, expect, vi } from 'vite-plus/test'; vi.mock('cloudflare:workers', () => ({ env: {} })); -import { createStorage } from '../../src/runtime/storage.ts'; +import { createStorage } from '../../src/runtime/storage/index.ts'; describe('createStorage', () => { it('returns the bucket directly', () => { diff --git a/packages/void/test/unit/sveltekit-hooks-transform.test.ts b/packages/void/test/unit/sveltekit-hooks-transform.test.ts index bbb950319..b19554fa1 100644 --- a/packages/void/test/unit/sveltekit-hooks-transform.test.ts +++ b/packages/void/test/unit/sveltekit-hooks-transform.test.ts @@ -1,7 +1,7 @@ import { parseSync } from 'vite'; import { afterEach, describe, expect, it, vi } from 'vite-plus/test'; -import { getRawRuntimeEnv } from '../../src/runtime/env-raw.ts'; -import { getRuntimeRequestResource, withRuntimeEnv } from '../../src/runtime/env.ts'; +import { getRawRuntimeEnv } from '../../src/runtime/env/raw.ts'; +import { getRuntimeRequestResource, withRuntimeEnv } from '../../src/runtime/env/runtime.ts'; import { injectSvelteKitBuildHooks, injectSvelteKitHooks, diff --git a/packages/void/test/unit/typed-navigation.typecheck.ts b/packages/void/test/unit/typed-navigation.typecheck.ts index d651e4522..e160e2a2e 100644 --- a/packages/void/test/unit/typed-navigation.typecheck.ts +++ b/packages/void/test/unit/typed-navigation.typecheck.ts @@ -14,10 +14,10 @@ import { defineMiddleware, type CloudContext, type CloudEnv, -} from '../../src/runtime/handler.ts'; -import { revalidate } from '../../src/runtime/isr.ts'; -import { connectLiveStream } from '../../src/runtime/live-client.ts'; -import { connectEventStream } from '../../src/runtime/sse-client.ts'; +} from '../../src/runtime/handler/index.ts'; +import { revalidate } from '../../src/runtime/isr/index.ts'; +import { connectLiveStream } from '../../src/runtime/live/client.ts'; +import { connectEventStream } from '../../src/runtime/sse/client.ts'; declare module 'void/routes' { interface RoutePathMap { diff --git a/packages/void/test/unit/validator-real-schemas.test.ts b/packages/void/test/unit/validator-real-schemas.test.ts index 8feb032c4..916a7aa06 100644 --- a/packages/void/test/unit/validator-real-schemas.test.ts +++ b/packages/void/test/unit/validator-real-schemas.test.ts @@ -3,8 +3,8 @@ import { Hono } from 'hono'; import * as v from 'valibot'; import { describe, expect, it } from 'vite-plus/test'; import { z } from 'zod'; -import { defineHandler, type CloudContext } from '../../src/runtime/handler.ts'; -import { convertReturnValue } from '../../src/runtime/response.ts'; +import { defineHandler, type CloudContext } from '../../src/runtime/handler/index.ts'; +import { convertReturnValue } from '../../src/runtime/handler/response.ts'; import type { StandardSchemaV1 } from '../../src/standard-schema.ts'; type ValidationIssueBody = { diff --git a/packages/void/test/unit/validator-real-schemas.typecheck.ts b/packages/void/test/unit/validator-real-schemas.typecheck.ts index 7bc5f2105..e7ad0ffc3 100644 --- a/packages/void/test/unit/validator-real-schemas.typecheck.ts +++ b/packages/void/test/unit/validator-real-schemas.typecheck.ts @@ -2,7 +2,7 @@ import { type } from 'arktype'; import * as v from 'valibot'; import { describe, it } from 'vite-plus/test'; import { z } from 'zod'; -import { defineHandler } from '../../src/runtime/handler.ts'; +import { defineHandler } from '../../src/runtime/handler/index.ts'; describe('withValidator + zod', () => { const CreateUser = z.object({ diff --git a/packages/void/test/unit/validator.test.ts b/packages/void/test/unit/validator.test.ts index 80e2fd51b..8081e7381 100644 --- a/packages/void/test/unit/validator.test.ts +++ b/packages/void/test/unit/validator.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vite-plus/test'; -import type { CloudContext } from '../../src/runtime/handler.ts'; -import { runValidation, type ValidatorSlots } from '../../src/runtime/validator.ts'; +import type { CloudContext } from '../../src/runtime/handler/index.ts'; +import { runValidation, type ValidatorSlots } from '../../src/runtime/handler/validator.ts'; import type { StandardSchemaV1 } from '../../src/standard-schema.ts'; type ValidationIssueBody = { diff --git a/packages/void/test/unit/ws-server-close.test.ts b/packages/void/test/unit/ws-server-close.test.ts index e1a10b0fc..e61befb6e 100644 --- a/packages/void/test/unit/ws-server-close.test.ts +++ b/packages/void/test/unit/ws-server-close.test.ts @@ -1,9 +1,9 @@ import { expect, it, vi } from 'vite-plus/test'; +import { defineRoom, defineWebSocket } from '../../src/runtime/ws/index.ts'; import { createWebSocketDurableObject, createWebSocketTombstoneDurableObject, -} from '../../src/runtime/ws-server.ts'; -import { defineRoom, defineWebSocket } from '../../src/runtime/ws.ts'; +} from '../../src/runtime/ws/server.ts'; import type { StandardSchemaV1 } from '../../src/standard-schema.ts'; const schema: StandardSchemaV1 = { diff --git a/packages/void/test/unit/ws.test.ts b/packages/void/test/unit/ws.test.ts index 929063e63..2f2f4d225 100644 --- a/packages/void/test/unit/ws.test.ts +++ b/packages/void/test/unit/ws.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'; -import { connect } from '../../src/runtime/ws.ts'; +import { connect } from '../../src/runtime/ws/index.ts'; declare module 'void/routes' { interface WebSocketRouteMap { diff --git a/packages/void/vite.config.ts b/packages/void/vite.config.ts index 71c0c6b37..17376145f 100644 --- a/packages/void/vite.config.ts +++ b/packages/void/vite.config.ts @@ -25,13 +25,13 @@ function injectWorkersTypesReferencePlugin() { for (const output of Object.values(bundle)) { // Patch declaration entrypoints whose source uses Cloudflare globals. const targets = new Set([ - 'runtime/handler.d.mts', - 'runtime/env-public.d.mts', - 'runtime/sandbox.d.mts', - 'runtime/sandbox-container.d.mts', - 'runtime/live.d.mts', - 'runtime/live-server.d.mts', - 'runtime/email.d.mts', + 'runtime/handler/index.d.mts', + 'runtime/env/public.d.mts', + 'runtime/sandbox/index.d.mts', + 'runtime/sandbox/container.d.mts', + 'runtime/live/index.d.mts', + 'runtime/live/server.d.mts', + 'runtime/email/index.d.mts', 'runtime/email/testing.d.mts', ]); if (!targets.has(output.fileName)) { @@ -66,67 +66,67 @@ export default defineConfig({ 'src/prerender-render.ts', 'src/database-provider.ts', 'src/edge.ts', - 'src/runtime/handler.ts', - 'src/runtime/response.ts', - 'src/runtime/routing.ts', - 'src/runtime/validator.ts', + 'src/runtime/handler/index.ts', + 'src/runtime/handler/response.ts', + 'src/runtime/routing/index.ts', + 'src/runtime/handler/validator.ts', 'src/routes-stub.ts', - 'src/runtime/client.ts', - 'src/runtime/client-react.ts', - 'src/runtime/client-vue.ts', - 'src/runtime/client-svelte.ts', - 'src/runtime/client-solid.ts', - 'src/runtime/fetch.ts', - 'src/runtime/fetch-server.ts', - 'src/runtime/fetch-stream.ts', - 'src/runtime/route-url.ts', - 'src/runtime/sse.ts', - 'src/runtime/sse-client.ts', - 'src/runtime/live.ts', - 'src/runtime/live-client.ts', - 'src/runtime/auth.ts', - 'src/runtime/auth-client.ts', - 'src/runtime/ws.ts', - 'src/runtime/auth-client-react.ts', - 'src/runtime/auth-client-vue.ts', - 'src/runtime/auth-client-svelte.ts', - 'src/runtime/auth-client-solid.ts', - 'src/runtime/better-auth.ts', - 'src/runtime/better-auth-pg.ts', - 'src/runtime/better-auth-mysql.ts', - 'src/runtime/env.ts', - 'src/runtime/env-public.ts', - 'src/runtime/env-public-client.ts', - 'src/runtime/db.ts', - 'src/runtime/db-pg.ts', - 'src/runtime/db-mysql.ts', - 'src/runtime/durable.ts', - 'src/runtime/seed.ts', - 'src/runtime/drizzle-zod.ts', - 'src/runtime/drizzle-valibot.ts', - 'src/runtime/drizzle-arktype.ts', - 'src/runtime/schema-d1.ts', - 'src/runtime/schema-pg.ts', - 'src/runtime/schema-mysql.ts', - 'src/runtime/kv.ts', - 'src/runtime/queues.ts', - 'src/runtime/storage.ts', - 'src/runtime/isr.ts', - 'src/runtime/log.ts', - 'src/runtime/ai.ts', - 'src/runtime/limits.ts', - 'src/runtime/email.ts', - 'src/runtime/email-protocol.ts', + 'src/runtime/client/index.ts', + 'src/runtime/client/react.ts', + 'src/runtime/client/vue.ts', + 'src/runtime/client/svelte.ts', + 'src/runtime/client/solid.ts', + 'src/runtime/client/fetch.ts', + 'src/runtime/client/fetch-server.ts', + 'src/runtime/client/fetch-stream.ts', + 'src/runtime/routing/route-url.ts', + 'src/runtime/sse/index.ts', + 'src/runtime/sse/client.ts', + 'src/runtime/live/index.ts', + 'src/runtime/live/client.ts', + 'src/runtime/auth/index.ts', + 'src/runtime/auth/client.ts', + 'src/runtime/ws/index.ts', + 'src/runtime/auth/client-react.ts', + 'src/runtime/auth/client-vue.ts', + 'src/runtime/auth/client-svelte.ts', + 'src/runtime/auth/client-solid.ts', + 'src/runtime/auth/better-auth-d1.ts', + 'src/runtime/auth/better-auth-postgres.ts', + 'src/runtime/auth/better-auth-mysql.ts', + 'src/runtime/env/runtime.ts', + 'src/runtime/env/public.ts', + 'src/runtime/env/public-client.ts', + 'src/runtime/db/index.ts', + 'src/runtime/db/postgres.ts', + 'src/runtime/db/mysql.ts', + 'src/runtime/durable/index.ts', + 'src/runtime/db/seed.ts', + 'src/runtime/db/validators/drizzle-zod.ts', + 'src/runtime/db/validators/drizzle-valibot.ts', + 'src/runtime/db/validators/drizzle-arktype.ts', + 'src/runtime/db/schema/d1.ts', + 'src/runtime/db/schema/postgres.ts', + 'src/runtime/db/schema/mysql.ts', + 'src/runtime/kv/index.ts', + 'src/runtime/queues/index.ts', + 'src/runtime/storage/index.ts', + 'src/runtime/isr/index.ts', + 'src/runtime/log/index.ts', + 'src/runtime/ai/index.ts', + 'src/runtime/limits/index.ts', + 'src/runtime/email/index.ts', + 'src/runtime/email/protocol.ts', 'src/runtime/email/testing.ts', - 'src/runtime/sandbox.ts', - 'src/runtime/sandbox-container.ts', + 'src/runtime/sandbox/index.ts', + 'src/runtime/sandbox/container.ts', 'src/runtime/remote/index.ts', 'src/runtime/remote/binding-handler.ts', - 'src/runtime/migration-handler.ts', - 'src/runtime/migration-handler-pg.ts', - 'src/runtime/migration-handler-mysql.ts', - 'src/runtime/ws-server.ts', - 'src/runtime/live-server.ts', + 'src/runtime/db/migrations/d1-handler.ts', + 'src/runtime/db/migrations/postgres-handler.ts', + 'src/runtime/db/migrations/mysql-handler.ts', + 'src/runtime/ws/server.ts', + 'src/runtime/live/server.ts', 'src/sveltekit.ts', 'src/nitro.ts', 'src/pages/index.ts', diff --git a/platform/packages/api/scripts/build-sandbox-controller.mjs b/platform/packages/api/scripts/build-sandbox-controller.mjs index 3cc5794f6..726461d5d 100644 --- a/platform/packages/api/scripts/build-sandbox-controller.mjs +++ b/platform/packages/api/scripts/build-sandbox-controller.mjs @@ -21,7 +21,7 @@ export function buildSandboxController(outputDirectory = join(packageRoot, 'dist alias: { 'void/_sandbox-container': join( packageRoot, - '../../../packages/void/src/runtime/sandbox-container.ts', + '../../../packages/void/src/runtime/sandbox/container.ts', ), }, }), diff --git a/platform/packages/api/test/unit/sandbox-controller-rpc.test.ts b/platform/packages/api/test/unit/sandbox-controller-rpc.test.ts index c4dda8b6a..9cc95b576 100644 --- a/platform/packages/api/test/unit/sandbox-controller-rpc.test.ts +++ b/platform/packages/api/test/unit/sandbox-controller-rpc.test.ts @@ -58,7 +58,7 @@ export default class extends SandboxService { writeFileSync( join(temporary, 'application.ts'), ` -import { getSandbox } from ${JSON.stringify(join(root, 'packages/void/src/runtime/sandbox.ts'))}; +import { getSandbox } from ${JSON.stringify(join(root, 'packages/void/src/runtime/sandbox/index.ts'))}; export default { async fetch(request, env) { const id = new URL(request.url).pathname.slice(1); const sandbox = await getSandbox(id, { inactivityTimeoutMs: 50 }); @@ -78,7 +78,7 @@ export default { async fetch(request, env) { logLevel: 'silent', resolve: { alias: { - 'void/_sandbox-container': join(root, 'packages/void/src/runtime/sandbox-container.ts'), + 'void/_sandbox-container': join(root, 'packages/void/src/runtime/sandbox/container.ts'), }, }, ssr: { noExternal: true }, diff --git a/vite.config.ts b/vite.config.ts index c94348e0e..7c7f8fe46 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -53,7 +53,7 @@ const hookTimeout = 120_000 * ciTimeoutScale; const platformAlias = { 'void/_sandbox-container': fileURLToPath( - new URL('packages/void/src/runtime/sandbox-container.ts', import.meta.url), + new URL('packages/void/src/runtime/sandbox/container.ts', import.meta.url), ), 'void:sandbox-controller-source': fileURLToPath( new URL('platform/packages/api/test/__mocks__/sandbox-controller-source.ts', import.meta.url),