From bce853d2a95e093bb0e5884a4e021b051e999862 Mon Sep 17 00:00:00 2001 From: Isak Gustavsen Date: Wed, 25 Nov 2026 01:09:50 +0100 Subject: [PATCH 1/2] feat(void): add Cloudflare Workflows through a workflows/ convention Each default-exported defineWorkflow() or defineWorkflowEntrypoint() module in workflows/ becomes a Cloudflare Workflow with a WORKFLOW_ binding and Workflow class, started from routes with Definition.create(), createBatch() and get(). Params can be validated with a Standard Schema. Discovery follows queues/: subdirectories are joined with '-' and paths with a '_'-prefixed segment are ignored, so step helpers can live beside the workflows. Deploys to Cloudflare name each Workflow -, since Workflow names are account-scoped, and verify the emitted set before upload. Void platform deploys, framework mode and Node targets reject workflows/ for now. The generated Worker entry now imports convention modules through their namespace and fails startup with a named error when a module does not default-export a definition; this also covers durable-objects/. Closes #779 Co-Authored-By: Claude Opus 5.5 --- docs/.vitepress/config.ts | 2 + docs/guide/workflows.md | 162 ++++++++++++ docs/reference/api.md | 2 + docs/reference/api/workflows.md | 57 ++++ docs/reference/cli/setup.md | 4 +- docs/reference/resource-inference.md | 4 + docs/reference/structure.md | 5 + packages/void/AGENTS.md | 3 +- packages/void/package.json | 5 + packages/void/skills/void/SKILL.md | 1 + packages/void/src/application-analysis.ts | 4 + .../src/cli/deploy-artifact-validation.ts | 24 ++ .../void/src/cli/deploy-binding-snapshot.ts | 18 ++ .../void/src/cli/deploy-cloudflare-build.ts | 8 +- .../void/src/cli/deploy-cloudflare-migrate.ts | 2 + .../src/cli/deploy-cloudflare-preflight.ts | 10 + packages/void/src/cli/deploy.ts | 2 + packages/void/src/cli/info.ts | 11 +- packages/void/src/deploy.ts | 2 + packages/void/src/index.ts | 35 +++ packages/void/src/plugin-client-stubs.ts | 5 +- packages/void/src/plugin-cloudflare-config.ts | 12 +- packages/void/src/plugin-routing.ts | 9 + packages/void/src/plugin-worker-bindings.ts | 36 ++- packages/void/src/router/compile.ts | 86 ++++-- packages/void/src/runtime/workflows/index.ts | 246 ++++++++++++++++++ packages/void/src/shared/env.ts | 6 + .../void/src/shared/resource-definition.ts | 4 +- packages/void/src/workflows/config.ts | 55 ++++ packages/void/src/workflows/platform.ts | 10 + packages/void/src/workflows/scan.ts | 111 ++++++++ .../cloudflare-durable-build.test.ts | 106 +++++++- .../test/integration/workflow-runtime.test.ts | 222 ++++++++++++++++ packages/void/test/unit/compile.test.ts | 52 +++- packages/void/test/unit/info.test.ts | 31 +++ .../void/test/unit/plugin-inference.test.ts | 64 ++++- .../void/test/unit/workflow-runtime.test.ts | 151 +++++++++++ packages/void/test/unit/workflow-scan.test.ts | 165 ++++++++++++ packages/void/vite.config.ts | 1 + 39 files changed, 1700 insertions(+), 33 deletions(-) create mode 100644 docs/guide/workflows.md create mode 100644 docs/reference/api/workflows.md create mode 100644 packages/void/src/runtime/workflows/index.ts create mode 100644 packages/void/src/workflows/config.ts create mode 100644 packages/void/src/workflows/platform.ts create mode 100644 packages/void/src/workflows/scan.ts create mode 100644 packages/void/test/integration/workflow-runtime.test.ts create mode 100644 packages/void/test/unit/workflow-runtime.test.ts create mode 100644 packages/void/test/unit/workflow-scan.test.ts diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts index af2f1a1aa..c0be1394b 100644 --- a/docs/.vitepress/config.ts +++ b/docs/.vitepress/config.ts @@ -126,6 +126,7 @@ const referenceItems: Array = [ { text: 'Authentication', link: '/reference/api/auth' }, { text: 'Fetch Client', link: '/reference/api/client' }, { text: 'Durable State and WebSockets', link: '/reference/api/durable' }, + { text: 'Workflows', link: '/reference/api/workflows' }, { text: 'Deployment artifacts', link: '/reference/api/deploy' }, { text: 'Database and Seeding', link: '/reference/api/database' }, { text: 'Resource Clients', link: '/reference/api/resources' }, @@ -385,6 +386,7 @@ export default extendConfig( { text: 'Sandboxes', link: '/guide/sandboxes' }, { text: 'Cron Jobs', link: '/guide/jobs' }, { text: 'Queues', link: '/guide/queues' }, + { text: 'Workflows', link: '/guide/workflows' }, { text: 'WebSockets', link: '/guide/websockets' }, { text: 'Server-Sent Events', link: '/guide/sse' }, { text: 'Live Event Streams', link: '/guide/live' }, diff --git a/docs/guide/workflows.md b/docs/guide/workflows.md new file mode 100644 index 000000000..90cc4617f --- /dev/null +++ b/docs/guide/workflows.md @@ -0,0 +1,162 @@ +--- +description: 'Run durable multi-step jobs with Cloudflare Workflows: retried steps, sleeps, and typed params.' +outline: deep +--- + +# Workflows + +Use a Workflow for work that runs across several steps and must finish even if one fails, such as onboarding emails, imports, or payment follow-ups. Each step's result is saved, failed steps are retried, and a Workflow can sleep for minutes or days between steps. + +Create a module in `workflows/` with `defineWorkflow()`. Void creates the Cloudflare Workflow and its binding for you. Workflows run in local development and in direct Cloudflare deployments (`void deploy --platform cloudflare`). + +## Define a workflow + +```ts +// workflows/onboarding.ts +import { defineWorkflow } from 'void/workflows'; +import type { WorkflowEvent } from 'void/workflows'; + +export const Onboarding = defineWorkflow({ + async run(event: WorkflowEvent<{ userId: string }>, step) { + await step.do('send welcome email', async () => { + await sendWelcomeEmail(event.payload.userId); + }); + await step.sleep('wait a day', '1 day'); + await step.do('send tips', async () => { + await sendTips(event.payload.userId); + }); + }, +}); + +export default Onboarding; +``` + +Default-export the object returned by `defineWorkflow()`. Named-export it too so routes can import it. + +TypeScript and JavaScript files are supported. Subdirectories are scanned too, and files or directories starting with `_` are ignored, so keep shared step helpers in files such as `workflows/_email.ts`. + +`run` receives: + +- `event`, with the `payload` passed to `create()`, the `instanceId`, and a `timestamp` +- `step`, Cloudflare's [`WorkflowStep`](https://developers.cloudflare.com/workflows/build/workers-api/#workflowstep) with `step.do()`, `step.sleep()`, `step.sleepUntil()`, and `step.waitForEvent()` +- a context with the Worker `env` + +Imports such as `void/env`, `void/db`, and `void/kv` work inside steps. Keep side effects inside `step.do()` so a retry or a resumed instance doesn't repeat them. + +## Start an instance from a route + +```ts +// routes/api/signup.ts +import { defineHandler } from 'void'; +import { Onboarding } from '../../workflows/onboarding'; + +export const POST = defineHandler(async () => { + const instance = await Onboarding.create({ params: { userId: 'user_123' } }); + return { instanceId: instance.id }; +}); +``` + +`create()` accepts the same options as Cloudflare's [`Workflow.create()`](https://developers.cloudflare.com/workflows/build/workers-api/#create), such as `id` and `retention`. Its `params` are typed from your definition. Use `createBatch()` to start up to 100 instances at once. + +Check on an instance with `get()`: + +```ts +// routes/api/onboarding/[id].ts +import { defineHandler } from 'void'; +import { Onboarding } from '../../../workflows/onboarding'; + +export const GET = defineHandler(async (c) => { + const instance = await Onboarding.get(c.req.param('id')); + return instance.status(); +}); +``` + +The returned instance can also `pause()`, `resume()`, `restart()`, `terminate()`, and `sendEvent()`. + +## Validate params + +Pass a [Standard Schema](https://standardschema.dev) validator, such as Zod, Valibot, or ArkType, as `params`. `create()` and `createBatch()` validate the params before starting an instance, and `run` receives the parsed value: + +```ts +import * as v from 'valibot'; +// workflows/import.ts +import { defineWorkflow } from 'void/workflows'; + +export const Import = defineWorkflow({ + params: v.object({ fileKey: v.string(), notify: v.optional(v.boolean(), false) }), + async run(event, step) { + const rows = await step.do('parse', () => parseFile(event.payload.fileKey)); + if (event.payload.notify) { + await step.do('notify', () => notifyOwner(rows.length)); + } + }, +}); + +export default Import; +``` + +Invalid params throw a `WorkflowParamsError`. Its `issues` list each message and path. + +## Native Workflow classes + +Use `defineWorkflowEntrypoint()` to keep a class that extends Cloudflare's `WorkflowEntrypoint`. Void binds and exports the class without changing it, and reads the params type from its `run` method: + +```ts +// workflows/report.ts +import { WorkflowEntrypoint } from 'cloudflare:workers'; +import type { WorkflowEvent, WorkflowStep } from 'cloudflare:workers'; +import { defineWorkflowEntrypoint } from 'void/workflows'; + +class ReportWorkflow extends WorkflowEntrypoint { + async run(event: WorkflowEvent<{ month: string }>, step: WorkflowStep) { + return step.do('build report', () => buildReport(event.payload.month)); + } +} + +export const Report = defineWorkflowEntrypoint({ class: ReportWorkflow }); +export default Report; +``` + +`Report.create()`, `Report.createBatch()`, and `Report.get()` work as they do for `defineWorkflow()`. + +## Names and bindings + +Void derives the names from the file's path in `workflows/`, joining directories with `-` as it does for [queues](./queues.md#defining-queues). `workflows/send-welcome.ts` creates: + +- the `WORKFLOW_SEND_WELCOME` binding +- the exported `SendWelcomeWorkflow` class +- a Cloudflare Workflow named `-send-welcome`, since Workflow names must be unique within your Cloudflare account + +`workflows/order/notifications.ts` creates `WORKFLOW_ORDER_NOTIFICATIONS`, `OrderNotificationsWorkflow`, and `-order-notifications`. Each Workflow must have a unique name. + +Instances belong to the Workflow name. Renaming the file or the Worker starts a new, empty Workflow, and instances of the old one stop running. To move a file without changing its name, run `void info` first and add the name it suggests: + +```ts +export const Onboarding = defineWorkflow({ + name: 'onboarding', + async run(event, step) { + // ... + }, +}); +``` + +`name` must be a static string containing words that start with a letter. To choose the Cloudflare Workflow name yourself, add an entry for the generated binding and class in `void.config.ts`: + +```ts +// void.config.ts +import { defineConfig } from 'void/config'; + +export default defineConfig({ + cloudflare: { + workflows: [ + { name: 'onboarding', binding: 'WORKFLOW_ONBOARDING', class_name: 'OnboardingWorkflow' }, + ], + }, +}); +``` + +## Deployment support + +Workflows are available on the Workers Free plan, within [Cloudflare's Workflows limits](https://developers.cloudflare.com/workflows/reference/limits/). Deploy to your own Cloudflare account with `void deploy --platform cloudflare`. + +Void platforms do not support Workflows yet: `void deploy` to a Void platform stops with an error while `workflows/` contains modules. Workflows are also unavailable in meta-framework apps and on Node.js, Bun, and Deno. diff --git a/docs/reference/api.md b/docs/reference/api.md index 05a09b43d..258377b18 100644 --- a/docs/reference/api.md +++ b/docs/reference/api.md @@ -24,6 +24,7 @@ Use this reference to find public imports, signatures, and return types. For set | [Authentication](./api/auth.md) | Sessions, users, and the auth client. | | [Fetch client](./api/client.md) | Typed requests and errors. | | [Durable State and WebSockets](./api/durable.md) | Persistent objects and typed connections. | +| [Workflows](./api/workflows.md) | Durable multi-step jobs. | | [Database and seeding](./api/database.md) | Queries, operators, and seed scripts. | | [KV, storage, AI, and logging](./api/resources.md) | Resource clients, cache revalidation, and logs. | | [Deployment artifacts](./api/deploy.md) | Package built apps for managed deployment. | @@ -45,6 +46,7 @@ Import Void's app-facing APIs from these paths: | `void/ws` | `defineRoom`, `defineWebSocket`, `connect`, WebSocket context, connection and action types | | `void/ws/server` | `getRoom`, `RoomHandle`, `RoomOptions`, `RoomPath`. Server-only: call room actions from routes, auth hooks, queues and cron jobs. | | `void/durable` | `defineDurableState`, `defineDurableObject`, typed state/RPC/context/migration types | +| `void/workflows` | `defineWorkflow`, `defineWorkflowEntrypoint`, `WorkflowParamsError`, Workflow event/step/API types. Server-only. | | `void/sse` | `eventStream`, `formatSse`, `formatSseText`, `getLastEventId`, `SseStreamClosedError`, SSE message and stream types | | `void/sse/client` | `connectEventStream`, browser `EventSource` wrapper types | | `void/live` | `defineLiveStream`, SSE topic fanout runtime types. Server-only. | diff --git a/docs/reference/api/workflows.md b/docs/reference/api/workflows.md new file mode 100644 index 000000000..e45f14e55 --- /dev/null +++ b/docs/reference/api/workflows.md @@ -0,0 +1,57 @@ +--- +description: 'Durable multi-step Workflows from void/workflows.' +outline: deep +--- + +# Workflows + +Imported from `"void/workflows"`. See [Workflows](../../guide/workflows.md) for the file convention and deployment support. + +## `defineWorkflow(definition)` {#defineworkflow-definition} + +Defines a Cloudflare Workflow from a run function. The returned object must be the default export of a module under `workflows/`; named-export the same object to start instances elsewhere in the app. + +```ts +function defineWorkflow(definition: { + name?: string; + params?: StandardSchemaV1; + run( + event: Readonly>, + step: WorkflowStep, + context: { env: TEnv; ctx: ExecutionContext }, + ): Promise; +}): WorkflowApi, TParams>; +``` + +With `params`, `run` receives the schema's output type and `create()` accepts its input type. Without it, the params type comes from the `event` annotation. + +## `defineWorkflowEntrypoint(definition)` {#defineworkflowentrypoint-definition} + +Registers a class that extends Cloudflare's `WorkflowEntrypoint` without changing it. The params type is read from the class's `run(event)` annotation. + +```ts +function defineWorkflowEntrypoint(definition: { + name?: string; + class: TClass; +}): WorkflowApi; +``` + +## `WorkflowApi` {#workflowapi} + +| Member | Description | +| ------------------------------ | ----------------------------------------------------------------------------------------------------- | +| `class` | The Workflow class Void exports from the Worker. | +| `create(options?)` | Starts an instance. Options match Cloudflare's `create()`; `params` are typed and validated. | +| `createBatch(instances)` | Starts up to 100 instances and returns Cloudflare's `{ created, errors }` result. | +| `get(id)` | Returns a `WorkflowInstance` for `status()`, `pause()`, `resume()`, `terminate()`, and `sendEvent()`. | +| `create(binding, options?)`, … | Each method also accepts an explicit `Workflow` binding as its first argument. | + +`name` optionally fixes the resource identity instead of deriving it from the filename. Run `void info` and pin the displayed name before moving a deployed definition. + +## `WorkflowParamsError` {#workflowparamserror} + +Thrown by `create()` and `createBatch()` when params fail the definition's schema. `issues` is an array of `{ message, path? }`. + +## Types {#types} + +`WorkflowEvent`, `WorkflowStep`, `WorkflowContext`, `WorkflowCreateOptions`, `WorkflowApi`, and `WorkflowRun`. diff --git a/docs/reference/cli/setup.md b/docs/reference/cli/setup.md index cdaeba5a1..d9d815357 100644 --- a/docs/reference/cli/setup.md +++ b/docs/reference/cli/setup.md @@ -12,9 +12,9 @@ void info void info --json ``` -Shows each Durable State and WebSocket definition's source file, inferred or explicit name, Worker class, and binding. WebSocket entries also include their route in JSON output. It runs locally without authentication, network requests, or file generation. +Shows each Durable State, WebSocket, and Workflow definition's source file, inferred or explicit name, Worker class, and binding. WebSocket entries also include their route in JSON output. It runs locally without authentication, network requests, or file generation. -Before moving a deployed definition, copy the suggested `name` into `defineDurableState()`, `defineRoom()`, or `defineWebSocket()`. Keep that name after moving the file to preserve the resource. See [Durable State](../../guide/durable-state.md#rename-a-file-while-keeping-its-state) and [WebSockets](../../guide/websockets.md#move-a-route-while-keeping-its-state) for migration flows, including WebSocket parameter renames. +Before moving a deployed definition, copy the suggested `name` into `defineDurableState()`, `defineRoom()`, `defineWebSocket()`, or `defineWorkflow()`. Keep that name after moving the file to preserve the resource. See [Durable State](../../guide/durable-state.md#rename-a-file-while-keeping-its-state) [WebSockets](../../guide/websockets.md#move-a-route-while-keeping-its-state), and [Workflows](../../guide/workflows.md#names-and-bindings) for migration flows, including WebSocket parameter renames. Resources recorded in `void.lock.json` without a matching definition appear separately. Adopt a suggested name only after identifying the resource you moved. If Void cannot suggest a name, restore its original source and inspect it before moving it again. diff --git a/docs/reference/resource-inference.md b/docs/reference/resource-inference.md index 0f0e3104b..13407199d 100644 --- a/docs/reference/resource-inference.md +++ b/docs/reference/resource-inference.md @@ -20,6 +20,7 @@ Void automatically detects which Cloudflare resources your project uses by scann | `QUEUE_*` | `Queue` | `import { queues } from "void/queues"` | `env.QUEUE_*` | | `VOID_LIVE` | `DurableObjectNamespace` | `import { defineLiveStream } from "void/live"` | n/a | | filename-derived | `DurableObjectNamespace` | A default-exported `defineDurableState()` module in `durable-objects/` | n/a | +| `WORKFLOW_*` | `Workflow` | A default-exported `defineWorkflow()` or `defineWorkflowEntrypoint()` module in `workflows/` | n/a | Auth detection also triggers when importing the `auth` specifier from `void/client` or a framework-specific client subpath such as `void/client/react` (but not when importing only `fetch`). @@ -29,6 +30,8 @@ use [explicit binding overrides](#explicit-binding-overrides). Durable state is inferred from files in `durable-objects/`. For example, `durable-objects/shopping-cart.ts` creates the `SHOPPING_CART` binding, exports `ShoppingCartDurableObject`, and records its migration. See [Durable State](../guide/durable-state.md). +Workflows are inferred from files in `workflows/`, including subdirectories; paths with a `_`-prefixed segment are ignored. For example, `workflows/send-welcome.ts` creates the `WORKFLOW_SEND_WELCOME` binding and exports `SendWelcomeWorkflow`. See [Workflows](../guide/workflows.md). + ## Scanned Directories ### Standard mode @@ -68,6 +71,7 @@ Regardless of mode, these are always checked: - **SSR entry** such as `src/main.ssr.ts`, for SSR apps that access bindings during rendering - **Application source** in `src/` or your configured `sourceDir`, including resource and auth imports - **`durable-objects/`**, which is scanned for typed Durable Object state modules in native Void apps +- **`workflows/`**, which is scanned for Workflow modules in native Void apps ## Custom Scan Directories diff --git a/docs/reference/structure.md b/docs/reference/structure.md index 954d5818b..59b9ecb7d 100644 --- a/docs/reference/structure.md +++ b/docs/reference/structure.md @@ -13,6 +13,7 @@ const items = [ { name: "queues/", description: "Async queue consumers", link: "#queues" }, { name: "email/", description: "Inbound email handlers", link: "#email" }, { name: "durable-objects/", description: "Durable State modules", link: "#durable-objects" }, + { name: "workflows/", description: "Durable multi-step Workflows", link: "#workflows" }, { name: "src/", description: "Shared app code", link: "#src" }, { name: "public/", description: "Static assets (served as-is)", link: "#public" }, { name: ".void/", description: "Auto-generated (gitignored)", link: "#void" }, @@ -126,6 +127,10 @@ Generate schema with `void gen model` or write it by hand. Generate migrations w [Durable State](/guide/durable-state) modules. Each file default-exports a `defineDurableState()` definition. +## `workflows/` + +[Workflow](/guide/workflows) modules. Each file default-exports a `defineWorkflow()` or `defineWorkflowEntrypoint()` definition. + ## `src/` Shared application code such as components, utilities, and types. This directory has no special convention, so organize it however you like. diff --git a/packages/void/AGENTS.md b/packages/void/AGENTS.md index 2df952b68..7bd23dc51 100644 --- a/packages/void/AGENTS.md +++ b/packages/void/AGENTS.md @@ -146,7 +146,8 @@ generated entries must preserve the module-boundary rules below. - **Framework env schema**: `env` has no schema in a Worker whose own modules have not loaded `env.ts`, whatever the Vite plugin loaded in its process, so it returns raw values. The Class A wrapper (TanStack Start, React Router, vinext) imports `env.ts` ahead of the framework entry and awaits `_prepareEnv(env)` on every request, in dev and build. Unlike `_validateEnvOnce`, it never rejects: a read of a key that failed throws that key's error, async validators included, so requests that do not read it and a build-time prerender without production secrets still run. Both keep one result per key, reuse a validation for the same raw values, and keep the results with the env object they received. Reads through another object (the `cloudflare:workers` env that a D1 app's framework reads outside a request scope, the remote dev copy) get the latest validation's result while they hold the raw value it came from; never copy results to that object, which can come to hold other values. A validation in which a validator threw serves its reads but runs again on the next call. Results live on the process-global registry because `void deploy` bundles cron and queue jobs apart from the app, with a copy of `void/env` of their own: the jobs call `registry.prepare`, the `_prepareEnv` of the copy that registered the schema (key in `shared/env-registry.ts`). SvelteKit, Nuxt, Analog and Astro Workers do not load `env.ts` yet. - **Reserved `__VOID_*` names**: `envSchemaPlugin.config` (every mode, with or without `env.ts`) and `void env check` reject `__VOID_*` names in the root `.env` or declared in `env.ts`. Do not try to strip them from dev `vars` instead: Wrangler reads `.env` itself and writes it over `vars`, so a strip cannot be enforced. Manual trigger auth is a compile-time literal (`__VOID_SERVE` from `CompileOptions.dev`, false in builds and `vite preview`): dev accepts only `x-void-dev-trigger`, builds use the proxy token or build key. Never key it on `import.meta.env.DEV`, which is true in a `NODE_ENV=development` build. - **Typed Durable State convention**: each default-exported `defineDurableState()` definition in `durable-objects/*.ts` becomes a filename-derived binding and worker class (`shopping-cart.ts` → `SHOPPING_CART` / `ShoppingCartDurableObject`). The generated entry calls the internal `__bind()` hook so named imports can use `State.get(name)` without touching `c.env`, exports `State.class`, and emits a stable `new_sqlite_classes` migration. `syncWranglerDurableObjects()` persists bindings and append-only class migration history in `void.lock.json` through the generated Cloudflare config; never regenerate migration order solely from the current sorted files. The generated class extends `DurableObject` from `cloudflare:workers` so namespace stubs expose real RPC methods; runtime state and helpers use JavaScript private fields and methods. Runtime operations are serialized and persisted after successful typed RPC, `fetch`, or `alarm` handlers; versioned value migrations run on load. This is native-Void + Cloudflare only and is supported by direct Cloudflare deploys. Typed `*.ws.ts` routes likewise use SQLite-backed classes; their root-config sync uses the comment-preserving writer, retains legacy `new_classes` histories, and appends a new migration tag only for new classes. -- **Persistent resource names**: optional static `name` on Durable State and WebSocket definitions uses the same identity derivation as unnamed filenames/routes. Preserve unnamed defaults exactly. `void info` reports names and verified unmatched lock identities without executing source or writing files. Scanners use the shared AST reader; runtime validation imports only the Worker-safe `shared/resource-name.ts` leaf. Carry explicit names through generated metadata and `__bind()`; runtime mismatches fail instead of selecting an inferred replacement. WebSocket `key({ params })` is shared by namespace selection and hook `ctx.id`; absent keys keep the existing ordered `param=value` format. +- **Workflows convention**: each default-exported `defineWorkflow()` / `defineWorkflowEntrypoint()` under `workflows/` becomes `WORKFLOW_` / `Workflow` (`send-welcome.ts` → `WORKFLOW_SEND_WELCOME` / `SendWelcomeWorkflow`), bound through the same `__bind()` hook as Durable State. The binding prefix matches `QUEUE_*`. Discovery follows `queues/` rather than `durable-objects/`: subdirectories are joined with `-` (`order/notifications.ts` → `order-notifications`) and `_`-prefixed path segments are skipped. Workflows need no class migrations, so they are not written to `void.lock.json`; `mergeWorkerBindings()` emits only the additions (the Cloudflare plugin concatenates arrays) via `planWorkflowAdditions()`, naming each `-` because Workflow names are account-scoped. `void deploy --platform cloudflare` passes its Worker name to the build as `VOID_CLOUDFLARE_WORKER_NAME`, and `reconstructExpectedWorkflows()` pins the exact emitted set for `verifyGeneratedDeployConfig()`. An authored entry with the same binding and class keeps its name. Void platform deploys, framework mode and Node targets reject `workflows/` until platform provisioning exists. The generated entry imports convention modules through their namespace and fails Worker startup with a named error when the default export is not a definition; this guard also covers `durable-objects/`. +- **Persistent resource names**: optional static `name` on Durable State, WebSocket, and Workflow definitions uses the same identity derivation as unnamed filenames/routes. Preserve unnamed defaults exactly. `void info` reports names and verified unmatched lock identities without executing source or writing files. Scanners use the shared AST reader; runtime validation imports only the Worker-safe `shared/resource-name.ts` leaf. Carry explicit names through generated metadata and `__bind()`; runtime mismatches fail instead of selecting an inferred replacement. WebSocket `key({ params })` is shared by namespace selection and hook `ctx.id`; absent keys keep the existing ordered `param=value` format. - **Server room actions**: `defineRoom({ actions })` keeps each action's declared parameters and return type (`RoomActions` accepts any annotated parameter list, so unannotated parameters become `never`). Codegen adds `actions` to `WebSocketRouteMap` for room routes only, and `getRoom()` from `void/ws/server` resolves the same `bindingName` plus `buildWebSocketInstanceId()` key as `forwardWebSocketRequest()`. The generated route table registers route metadata once, after attaching `key`, through `__registerWebSocketRoutes`; the map lives on `globalThis` because dev can evaluate the module twice. Dispatch is Durable Object RPC (`__voidRoomAction`), so the WebSocket DO class extends `DurableObject` from `cloudflare:workers`; its own helpers are `#` methods so they stay off that RPC surface, and actions are never reachable from `fetch`, `webSocketMessage`, or client HTTP. - **Journal coherence invariant**: `db/migrations/*.sql` and `db/migrations/meta/_journal.json` must stay in sync — every `.sql` file has a matching journal entry (by `tag`) and vice versa. `assertJournalCoherence` in `src/migrations/validate.ts` is the gate, called from `deploy`, `db status`, `db migrate`, and `db reset`. The two CLI commands that mutate migration state — `void gen migration` and `void db rename-migrations` — are responsible for keeping the journal coherent themselves: when the journal has entries, the first delegates to `drizzle-kit generate --custom --name `, which writes the empty `.sql`, appends the journal entry, and writes a snapshot of the current schema (it refuses if the last entry's snapshot is missing and byte-restores the journal if drizzle-kit fails); with no journal entries it writes a plain timestamped `.sql`. The second rewrites `tag` values alongside the file renames and also renames the matching `meta/_snapshot.json` (with byte-level rollback on failure). Drift will fail loudly before touching any remote DB. This prevents an orphan scaffolded `.sql` file from half-applying against D1 and blocking later deploys. diff --git a/packages/void/package.json b/packages/void/package.json index ae781040a..fbaddad40 100644 --- a/packages/void/package.json +++ b/packages/void/package.json @@ -170,6 +170,11 @@ "import": "./dist/runtime/durable/index.mjs", "require": "./dist/runtime/durable/index.mjs" }, + "./workflows": { + "types": "./dist/runtime/workflows/index.d.mts", + "import": "./dist/runtime/workflows/index.mjs", + "require": "./dist/runtime/workflows/index.mjs" + }, "./seed": { "types": "./dist/runtime/db/seed.d.mts", "import": "./dist/runtime/db/seed.mjs", diff --git a/packages/void/skills/void/SKILL.md b/packages/void/skills/void/SKILL.md index f36ee0b6e..25acb4eae 100644 --- a/packages/void/skills/void/SKILL.md +++ b/packages/void/skills/void/SKILL.md @@ -51,6 +51,7 @@ Use `void deploy --skip-migrations` when database migrations run separately; it | AI inference (Workers AI, providers) | `docs/guide/ai.md` | | Platform AI logging policy | `docs/reference/cli/platform-users.md#ai-gateway-logging` | | Durable State and WebSockets | `docs/guide/durable-state.md`, `docs/guide/websockets.md` | +| Workflows | `docs/guide/workflows.md`, `docs/reference/api/workflows.md` | | Server-sent events and live streams | `docs/guide/sse.md`, `docs/guide/live.md` | | Sandboxes | `docs/guide/sandboxes.md` | | Email | `docs/guide/email.md`, then the matching guide under `docs/guide/email/` | diff --git a/packages/void/src/application-analysis.ts b/packages/void/src/application-analysis.ts index 7c21af167..3dd814094 100644 --- a/packages/void/src/application-analysis.ts +++ b/packages/void/src/application-analysis.ts @@ -15,6 +15,7 @@ import type { RouteEnvironment } from './router/parse-filename.ts'; import { scanMiddlewareSync, scanRoutePatternsSync } from './router/scan.ts'; import { scanWebSocketRoutesSync } from './router/websocket.ts'; import { isSandboxEnabled } from './sandbox/config.ts'; +import { scanWorkflowModules } from './workflows/scan.ts'; export type ApplicationReasons = { database: Array; @@ -40,6 +41,7 @@ export type ApplicationAnalysis = { websockets: ReturnType; allWebsockets: ReturnType; durableObjects: ReturnType; + workflows: ReturnType; email: ReturnType; routes: ReturnType; middleware: ReturnType; @@ -81,6 +83,7 @@ export function analyzeApplicationSync( ); // Typed durable modules currently use the root convention on every target. const durableObjects = scanDurableObjectModules(root); + const workflows = scanWorkflowModules(root); const email = scanEmailHandlersSync(paths.sourceRoot); const overrides = config.inference?.bindings; const bindingReason = ( @@ -127,6 +130,7 @@ export function analyzeApplicationSync( websockets, allWebsockets, durableObjects, + workflows, email, routes: scanRoutePatternsSync(root, paths, environment), middleware: scanMiddlewareSync(root, paths), diff --git a/packages/void/src/cli/deploy-artifact-validation.ts b/packages/void/src/cli/deploy-artifact-validation.ts index 8a05b1b0f..69c45cf28 100644 --- a/packages/void/src/cli/deploy-artifact-validation.ts +++ b/packages/void/src/cli/deploy-artifact-validation.ts @@ -138,6 +138,8 @@ export function removeDeployPointer(root: string): void { const byName = (left: Record, right: Record) => String(left.name).localeCompare(String(right.name)); +const byBinding = (left: Record, right: Record) => + String(left.binding).localeCompare(String(right.binding)); /** * Check the generated deploy config before upload: the pinned account and Worker name, required @@ -168,6 +170,8 @@ export function verifyGeneratedDeployConfig( expectedContainers?: Array>; /** Exact pre-build Durable Object bindings, including Void's sandbox and live additions. */ expectedDurableObjectBindings?: Array>; + /** Exact pre-build Workflow entries, including Void's `workflows/` additions. */ + expectedWorkflows?: Array>; /** Exact pre-build migration sequence, including Void's sandbox and live additions. */ expectedMigrations?: Array>; /** Cron schedules the build should emit, derived from the source before the build. */ @@ -442,6 +446,26 @@ export function verifyGeneratedDeployConfig( }; } } + if (expected.expectedWorkflows) { + if (generated.workflows !== undefined && !Array.isArray(generated.workflows)) { + return { ok: false, reason: 'generated config workflows could not be verified.' }; + } + const emittedWorkflows = Array.isArray(generated.workflows) + ? (generated.workflows as Array>) + : []; + if ( + !deepEqual( + [...emittedWorkflows].sort(byBinding), + [...expected.expectedWorkflows].sort(byBinding), + ) + ) { + return { + ok: false, + reason: + 'generated config workflows differ from the pre-build Workflow set — refusing to deploy a Workflow the build added, removed, or retargeted.', + }; + } + } if (expected.expectedMigrations) { if (generated.migrations !== undefined && !Array.isArray(generated.migrations)) { return { ok: false, reason: 'generated config migrations could not be verified.' }; diff --git a/packages/void/src/cli/deploy-binding-snapshot.ts b/packages/void/src/cli/deploy-binding-snapshot.ts index f98147cc9..846d234cd 100644 --- a/packages/void/src/cli/deploy-binding-snapshot.ts +++ b/packages/void/src/cli/deploy-binding-snapshot.ts @@ -20,6 +20,7 @@ import { SANDBOX_MIGRATION_TAG, hasSandboxSqliteMigration, } from '../sandbox/config.ts'; +import { planWorkflowAdditions, workflowConfigEntries } from '../workflows/config.ts'; import type { BindingIdentitySnapshot } from './deploy-types.ts'; import { resolveCloudflareOperationArgv } from './preset.ts'; import type { DesiredResourceSet, ProvisionDriftEntry } from './provision.ts'; @@ -125,6 +126,7 @@ export const DEPLOY_PASSTHROUGH_EXCLUDE_FIELDS: ReadonlySet = new Set, + workerName: string, + analysis?: ApplicationAnalysis, +): Array> { + const configured = workflowConfigEntries(rootConfig.workflows); + const modules = (analysis ?? analyzeApplicationSync(root, { config })).workflows; + return [...configured, ...planWorkflowAdditions(configured, modules, workerName)]; +} + export function reconstructExpectedDurableObjectState( config: VoidConfig, root: string, diff --git a/packages/void/src/cli/deploy-cloudflare-build.ts b/packages/void/src/cli/deploy-cloudflare-build.ts index dbfd0f040..14decdbdf 100644 --- a/packages/void/src/cli/deploy-cloudflare-build.ts +++ b/packages/void/src/cli/deploy-cloudflare-build.ts @@ -10,7 +10,11 @@ import type { VoidConfig } from '../config.ts'; import { collectMigrations } from '../migrations/collect.ts'; import { SqliteMigrationError } from '../migrations/sqlite-validation.ts'; import type { detectFramework } from '../plugin-inference.ts'; -import { CLOUDFLARE_DEPLOY_BUILD_ENV, CLOUDFLARE_QUEUE_NAMES_BUILD_ENV } from '../shared/env.ts'; +import { + CLOUDFLARE_DEPLOY_BUILD_ENV, + CLOUDFLARE_QUEUE_NAMES_BUILD_ENV, + CLOUDFLARE_WORKER_NAME_BUILD_ENV, +} from '../shared/env.ts'; import { CLOUDFLARE_PRESERVE_BINDINGS_BUILD_ENV } from '../shared/version-metadata.ts'; import { prepareCfBuildOutput, prepareCfFrameworkBuildOutput } from './cf-build-output.ts'; import { @@ -82,6 +86,8 @@ export async function buildCloudflareWorker(input: { // but local files cannot be serialized into the artifact this command uploads. deleteEnvVarCaseAware(buildChildEnv, CLOUDFLARE_DEPLOY_BUILD_ENV); buildChildEnv[CLOUDFLARE_DEPLOY_BUILD_ENV] = '1'; + deleteEnvVarCaseAware(buildChildEnv, CLOUDFLARE_WORKER_NAME_BUILD_ENV); + buildChildEnv[CLOUDFLARE_WORKER_NAME_BUILD_ENV] = workerName; deleteEnvVarCaseAware(buildChildEnv, CLOUDFLARE_QUEUE_NAMES_BUILD_ENV); if (desired.queueNames) { buildChildEnv[CLOUDFLARE_QUEUE_NAMES_BUILD_ENV] = JSON.stringify(desired.queueNames); diff --git a/packages/void/src/cli/deploy-cloudflare-migrate.ts b/packages/void/src/cli/deploy-cloudflare-migrate.ts index 9707dac36..f5fadef6c 100644 --- a/packages/void/src/cli/deploy-cloudflare-migrate.ts +++ b/packages/void/src/cli/deploy-cloudflare-migrate.ts @@ -58,6 +58,7 @@ export async function migrateCloudflareWorker(input: { passthroughRawFields, expectedContainers, expectedDurableObjectState, + expectedWorkflows, runWrangler, assertUploaderStillPinned, schemaFacts, @@ -78,6 +79,7 @@ export async function migrateCloudflareWorker(input: { authEnabled, expectedContainers, expectedDurableObjectBindings: expectedDurableObjectState.bindings, + expectedWorkflows, expectedMigrations: expectedDurableObjectState.migrations, expectedCrons, }; diff --git a/packages/void/src/cli/deploy-cloudflare-preflight.ts b/packages/void/src/cli/deploy-cloudflare-preflight.ts index 1db27af46..2e719f616 100644 --- a/packages/void/src/cli/deploy-cloudflare-preflight.ts +++ b/packages/void/src/cli/deploy-cloudflare-preflight.ts @@ -33,6 +33,7 @@ import { snapshotPassthroughRawFields, reconstructExpectedContainers, reconstructExpectedDurableObjectState, + reconstructExpectedWorkflows, } from './deploy-binding-snapshot.ts'; import { isWranglerNonInteractiveOrCI, @@ -225,6 +226,7 @@ export async function preflightCloudflareWorker(input: { passthroughRawFields: ReturnType; expectedContainers: ReturnType; expectedDurableObjectState: ReturnType; + expectedWorkflows: ReturnType; }> { const { root, @@ -691,6 +693,13 @@ export async function preflightCloudflareWorker(input: { preBuildRootConfig, { needsSandbox, needsLive, analysis: source.analysis }, ); + const expectedWorkflows = reconstructExpectedWorkflows( + voidConfig, + root, + preBuildRootConfig, + workerName, + source.analysis, + ); return { apiBaseUrl, complianceRegion, @@ -712,5 +721,6 @@ export async function preflightCloudflareWorker(input: { passthroughRawFields, expectedContainers, expectedDurableObjectState, + expectedWorkflows, }; } diff --git a/packages/void/src/cli/deploy.ts b/packages/void/src/cli/deploy.ts index 9e5109756..483c02269 100644 --- a/packages/void/src/cli/deploy.ts +++ b/packages/void/src/cli/deploy.ts @@ -5,6 +5,7 @@ import { stashCloudflareDeployPointer } from '../cloudflare-config.ts'; import { readConfig } from '../config.ts'; import { detectFramework } from '../plugin-inference.ts'; import { buildEnv } from '../shared/untrusted-env.ts'; +import { assertNoWorkflowsForPlatform } from '../workflows/platform.ts'; import { getApiUrl, getToken, getTokenSource } from './auth.ts'; import { isExpiredTokenError, PlatformClient } from './client.ts'; import { maybeLinkCloudflareDeploy } from './cloudflare-link.ts'; @@ -300,6 +301,7 @@ async function runManagedDeploy( // Resolve the app type: void.config.ts > CLI flags > auto-detection. const voidConfig = readConfig(root); + assertNoWorkflowsForPlatform(root); cliLog.info('config_resolved', { target: voidConfig.target, appType: voidConfig.inference?.appType, diff --git a/packages/void/src/cli/info.ts b/packages/void/src/cli/info.ts index b2b9ee90c..e768986a1 100644 --- a/packages/void/src/cli/info.ts +++ b/packages/void/src/cli/info.ts @@ -9,11 +9,12 @@ import { deriveWebSocketClassNameFromName, inferWebSocketResourceName, } from '../router/websocket.ts'; +import { inferWorkflowResourceName } from '../workflows/scan.ts'; import type { InfoArgs } from './info-args.ts'; export type PersistentResourceInfo = { file: string; - definition: 'defineDurableState' | 'defineRoom' | 'defineWebSocket'; + definition: 'defineDurableState' | 'defineRoom' | 'defineWebSocket' | 'defineWorkflow'; name: string; nameSource: 'inferred' | 'explicit'; className: string; @@ -135,6 +136,14 @@ export function getProjectInfo(root: string): ProjectInfo { className: module.className, bindingName: module.bindingName, })), + ...analysis.workflows.map((module) => ({ + file: relative(root, module.filePath), + definition: 'defineWorkflow' as const, + name: module.name ?? inferWorkflowResourceName(module.relativePath), + nameSource: module.name === undefined ? ('inferred' as const) : ('explicit' as const), + className: module.className, + bindingName: module.bindingName, + })), ]; resources.sort((a, b) => a.file.localeCompare(b.file)); return { resources, recordedResources: readRecordedResources(root, resources) }; diff --git a/packages/void/src/deploy.ts b/packages/void/src/deploy.ts index 0216c529f..f9a6d9c3e 100644 --- a/packages/void/src/deploy.ts +++ b/packages/void/src/deploy.ts @@ -23,6 +23,7 @@ import { readConfig, isNodeTarget } from './config.ts'; import { collectRevalidate } from './isr-config.ts'; import { hasEmailHandlers } from './router/email.ts'; import { validateSsrEntry } from './ssr/entry.ts'; +import { assertNoWorkflowsForPlatform } from './workflows/platform.ts'; /** * A disposable Cloudflare Build Output directory. Experimental: it follows Cloudflare's draft @@ -83,6 +84,7 @@ export async function prepareDeployArtifact( if (isNodeTarget(config.target) || config.output === 'static') { throw new Error('Artifact preparation requires a Void Cloudflare Worker build.'); } + assertNoWorkflowsForPlatform(root); let preset = resolveStaticDeployPreset(root, config); let analysis: Awaited> | undefined; if (!preset) { diff --git a/packages/void/src/index.ts b/packages/void/src/index.ts index c878b5caf..7ebf27faa 100644 --- a/packages/void/src/index.ts +++ b/packages/void/src/index.ts @@ -263,6 +263,32 @@ export function voidPlugin(options?: { 'durable: durable-objects/ is currently supported in Void apps only, not framework adapter mode.', ); } + const workflows = application.workflows; + if (detected && workflows.length > 0) { + throw new Error( + 'workflows: workflows/ is currently supported in Void apps only, not framework adapter mode.', + ); + } + for (const module of workflows) { + const owner = + websocketRoutes.find( + (route) => route.bindingName === module.bindingName || route.className === module.className, + )?.filePath ?? + durableObjects.find( + (durable) => + durable.bindingName === module.bindingName || durable.className === module.className, + )?.filePath; + if ( + owner !== undefined || + (sandboxConfig && + (sandboxConfig.binding === module.bindingName || + sandboxConfig.className === module.className)) + ) { + throw new Error( + `workflows: workflows/${module.relativePath} conflicts with ${owner === undefined ? 'the configured Sandbox binding or class' : `'${owner}'`}. Rename one of the files.`, + ); + } + } for (const module of durableObjects) { const websocketCollision = websocketRoutes.find( (route) => route.bindingName === module.bindingName || route.className === module.className, @@ -299,10 +325,12 @@ export function voidPlugin(options?: { reservedBindings: [ ...websocketRoutes.map((route) => route.bindingName), ...durableObjects.map((module) => module.bindingName), + ...workflows.map((module) => module.bindingName), ], reservedClasses: [ ...websocketRoutes.map((route) => route.className), ...durableObjects.map((module) => module.className), + ...workflows.map((module) => module.className), sandboxConfig?.className, ], }) @@ -404,6 +432,7 @@ export function voidPlugin(options?: { devTriggerToken, queues, durableObjects, + workflows, sandboxConfig, shouldEmitLive, liveConfig, @@ -844,6 +873,11 @@ export function voidPlugin(options?: { `durable: durable-objects/ requires target: "cloudflare". It is not available with target: '${config.target}'.`, ); } + if (workflows.length > 0) { + throw new Error( + `workflows: workflows/ requires target: "cloudflare". It is not available with target: '${config.target}'.`, + ); + } // `compileNodeApp` imports only the Hono app from the route table; the // `__emailHandler` the table exports for `email/` is never invoked, so // without this the build succeeds and every inbound handler is dead code. @@ -1000,6 +1034,7 @@ export function voidPlugin(options?: { return shouldEmitLive() ? liveConfig : undefined; }, durableObjects, + workflows, websocketTombstones, onDevAssetRoutingPolicyChange: updateDevAssetRoutingPolicy, // Native builds of eligible apps let Cloudflare serve hashed build files directly. diff --git a/packages/void/src/plugin-client-stubs.ts b/packages/void/src/plugin-client-stubs.ts index 25f759b04..469192edb 100644 --- a/packages/void/src/plugin-client-stubs.ts +++ b/packages/void/src/plugin-client-stubs.ts @@ -59,6 +59,7 @@ export function createClientStubsPlugin(): Plugin { `, 'void/live': '', 'void/durable': '', + 'void/workflows': '', }; const STUB_RESOLVE_FILTER = new RegExp( `^(${Object.keys(SERVER_ONLY_STUBS) @@ -75,11 +76,11 @@ export function createClientStubsPlugin(): Plugin { filter: { id: STUB_RESOLVE_FILTER }, handler(id) { if (this.environment?.name === 'client') { - if (id === 'void/live' || id === 'void/durable') { + if (id === 'void/live' || id === 'void/durable' || id === 'void/workflows') { this.error( id === 'void/live' ? 'void/live is server-only and cannot be imported by browser code. Import void/live/client instead.' - : 'void/durable is server-only and cannot be imported by browser code.', + : `${id} is server-only and cannot be imported by browser code.`, ); } return STUB_PREFIX + id; diff --git a/packages/void/src/plugin-cloudflare-config.ts b/packages/void/src/plugin-cloudflare-config.ts index a409a8227..de5604192 100644 --- a/packages/void/src/plugin-cloudflare-config.ts +++ b/packages/void/src/plugin-cloudflare-config.ts @@ -47,17 +47,23 @@ export function mergeCloudflareConfig(patch: object, fallback: object): Record; + workflows?: Array<{ + bindingName: string; + className: string; + filePath: string; + relativePath?: string; + name?: string; + }>; /** Data-preserving exports for removed WebSocket Durable Object routes. */ websocketTombstones?: Array; onDevAssetRoutingPolicyChange?: (policy: AssetRoutingPolicy) => boolean; @@ -654,6 +661,7 @@ export function routingPlugin( isr, notFound: policy.assetConfig.not_found_handling ?? 'none', durableObjects: options.durableObjects, + workflows: options.workflows, }), ); } @@ -681,6 +689,7 @@ export function routingPlugin( sandbox: sandboxEntry, live: options.live, durableObjects: options.durableObjects, + workflows: options.workflows, }), ); } diff --git a/packages/void/src/plugin-worker-bindings.ts b/packages/void/src/plugin-worker-bindings.ts index e966e3081..6b6cd8239 100644 --- a/packages/void/src/plugin-worker-bindings.ts +++ b/packages/void/src/plugin-worker-bindings.ts @@ -16,6 +16,7 @@ import { readVoidDevCredentials, } from './plugin-ai-setup.ts'; import { hasBinding, shouldInjectEmailDevInboxVar } from './plugin-binding-utils.ts'; +import { defaultCloudflareWorkerName } from './plugin-cloudflare-config.ts'; import type { WorkerConfig } from './plugin-cloudflare-config.ts'; import type { EnvSchemaFacts } from './plugin-env-schema.ts'; import { cloudflareQueueName, readDeployBuildQueueNames } from './queues/cloudflare-names.ts'; @@ -29,11 +30,12 @@ import { sandboxContainerConfig, assertSandboxNamespaceConfig, } from './sandbox/config.ts'; -import { CLOUDFLARE_DEPLOY_BUILD_ENV } from './shared/env.ts'; +import { CLOUDFLARE_DEPLOY_BUILD_ENV, CLOUDFLARE_WORKER_NAME_BUILD_ENV } from './shared/env.ts'; import { CLOUDFLARE_PRESERVE_BINDINGS_BUILD_ENV, selectNativeVersionMetadataBinding, } from './shared/version-metadata.ts'; +import { planWorkflowAdditions, workflowConfigEntries } from './workflows/config.ts'; type DurableObjectBinding = { name: string; class_name: string }; type DurableObjectMigration = { @@ -63,6 +65,34 @@ function currentMigrations( return Array.isArray(current) ? (current as Array) : []; } +/** + * Add a `workflows` entry for each `workflows/` module. The Cloudflare plugin + * concatenates this patch with the resolved config, so only additions are emitted. + */ +function mergeWorkflowBindings( + result: Record, + resolved: WorkerConfig, + workflows: ApplicationAnalysis['workflows'], + root: string, +): void { + if (workflows.length === 0) { + return; + } + const patchEntries = workflowConfigEntries(result.workflows); + const deployWorkerName = + process.env[CLOUDFLARE_DEPLOY_BUILD_ENV] === '1' + ? process.env[CLOUDFLARE_WORKER_NAME_BUILD_ENV] + : undefined; + const additions = planWorkflowAdditions( + [...patchEntries, ...workflowConfigEntries((resolved as Record).workflows)], + workflows, + deployWorkerName || ((resolved as { name?: string }).name ?? defaultCloudflareWorkerName(root)), + ); + if (additions.length > 0) { + result.workflows = [...patchEntries, ...additions]; + } +} + export function mergeWorkerBindings( resolved: WorkerConfig, input: { @@ -81,6 +111,7 @@ export function mergeWorkerBindings( readonly devTriggerToken: string; readonly queues: ApplicationAnalysis['queues']; readonly durableObjects: ApplicationAnalysis['durableObjects']; + readonly workflows: ApplicationAnalysis['workflows']; readonly sandboxConfig: ReturnType | undefined; readonly shouldEmitLive: () => boolean; readonly liveConfig: ReturnType | undefined; @@ -104,6 +135,7 @@ export function mergeWorkerBindings( devTriggerToken, queues, durableObjects, + workflows, sandboxConfig, shouldEmitLive, liveConfig, @@ -390,6 +422,8 @@ export function mergeWorkerBindings( } } + mergeWorkflowBindings(result, resolved, workflows, root); + if (bindings.needsSandbox && sandboxConfig) { assertSandboxNamespaceConfig({ ...resolved, ...result }, sandboxConfig); const existingDurableObjectBindings = currentDurableObjectBindings(result, resolved); diff --git a/packages/void/src/router/compile.ts b/packages/void/src/router/compile.ts index 968366150..25b766923 100644 --- a/packages/void/src/router/compile.ts +++ b/packages/void/src/router/compile.ts @@ -1198,12 +1198,55 @@ export interface WorkerEntryOptions { * imported from `filePath`, bound to `bindingName`, and re-exported as * `className` so wrangler's `durable_objects.bindings` can find it. */ - durableObjects?: Array<{ - bindingName: string; - className: string; - filePath: string; - name?: string; - }>; + durableObjects?: Array; + /** + * Workflow definitions (`workflows/` directory). Each entry is imported from + * `filePath`, bound to `bindingName`, and re-exported as `className` so + * the Cloudflare `workflows` config can find it. + */ + workflows?: Array; +} + +type ResourceModuleCode = { imports: string; exports: string }; + +type ResourceModuleEntry = { + bindingName: string; + className: string; + filePath: string; + /** Path relative to the convention directory, for error messages. Defaults to the file name. */ + relativePath?: string; + name?: string; +}; + +/** + * Import each convention module through its namespace so a missing default + * export reaches the guard below instead of failing with a bundler error or a + * generic `Cannot read properties of undefined` at Worker startup. + */ +function compileResourceModules( + entries: ReadonlyArray, + options: { variable: string; directory: string; prefix: string; helpers: string }, +): ResourceModuleCode { + const imports = entries + .map( + ({ filePath }, index) => + `import * as ${options.variable}Module${index} from ${JSON.stringify(filePath)};`, + ) + .join('\n'); + const exports = entries + .map(({ bindingName, className, filePath, relativePath, name }, index) => { + const local = `${options.variable}${index}`; + const file = `${options.directory}/${relativePath ?? filePath.replaceAll('\\', '/').split('/').pop()}`; + const message = `${options.prefix}: ${file} must default-export ${options.helpers}.`; + return [ + `const ${local} = ${options.variable}Module${index}.default;`, + `if (typeof ${local}?.__bind !== "function") { throw new Error(${JSON.stringify(message)}); }`, + `${local}.__bind(${JSON.stringify(bindingName)}${name !== undefined ? `, ${JSON.stringify(name)}` : ''});`, + `export const ${className} = ${local}.class;`, + ].join('\n'); + }) + .join('\n'); + return { imports, exports }; } /** @@ -1239,6 +1282,7 @@ export function compileWorkerEntry(options: WorkerEntryOptions = {}): string { isr, notFound = 'none', durableObjects = [], + workflows = [], } = options; const remotePath = remote?.remotePath; const remoteBindingNames = JSON.stringify(remote?.bindingNames); @@ -1281,17 +1325,23 @@ export function compileWorkerEntry(options: WorkerEntryOptions = {}): string { ? `export { VoidLiveStreamDurableObject };\n__setLiveBindingName(${JSON.stringify(liveBindingName)});\n${liveDevCall}` : `export { VoidLiveStreamDurableObject as ${liveClassName} };\n__setLiveBindingName(${JSON.stringify(liveBindingName)});\n${liveDevCall}` : ''; - const durableObjectImports = durableObjects - .map( - ({ filePath }, index) => - `import __voidDurableObject${index} from ${JSON.stringify(filePath)};`, - ) + const durableObjectModules = compileResourceModules(durableObjects, { + variable: '__voidDurableObject', + directory: 'durable-objects', + prefix: 'durable', + helpers: 'defineDurableState() or defineDurableObject()', + }); + const workflowModules = compileResourceModules(workflows, { + variable: '__voidWorkflow', + directory: 'workflows', + prefix: 'workflows', + helpers: 'defineWorkflow() or defineWorkflowEntrypoint()', + }); + const resourceModuleImports = [durableObjectModules.imports, workflowModules.imports] + .filter(Boolean) .join('\n'); - const durableObjectExports = durableObjects - .map( - ({ bindingName, className, name }, index) => - `__voidDurableObject${index}.__bind(${JSON.stringify(bindingName)}${name !== undefined ? `, ${JSON.stringify(name)}` : ''});\nexport const ${className} = __voidDurableObject${index}.class;`, - ) + const resourceModuleExports = [durableObjectModules.exports, workflowModules.exports] + .filter(Boolean) .join('\n'); const runtimeEnvImport = `import { withRuntimeEnv } from ${JSON.stringify(runtimeEnvPath)};\n`; const remoteImport = remote @@ -1431,7 +1481,7 @@ ${envValidateCall}${remoteEnvSwap}${isrDeploymentStamp} const userEnv = __filte ` : ''; return `${sandboxImport}${entryImport}${liveRuntimeImport}import app, { scheduled, __voidCollectPrerenderPaths, __voidRenderStaticNotFound, __voidHandleInternalRoute, __withRawEnv${queueImport}${emailImport}${webSocketClasses.length > 0 ? `, ${webSocketClasses.join(', ')}` : ''}${liveRouteImport} } from 'virtual:void-routes'; -${durableObjectImports}\n${runtimeEnvImport}${emailProxyImport}${envSchemaImport}${remoteImport}${isrImport}${filterBindingsHelper}${assetHelper} +${resourceModuleImports}\n${runtimeEnvImport}${emailProxyImport}${envSchemaImport}${remoteImport}${isrImport}${filterBindingsHelper}${assetHelper} ${fetchDeclaration} ${scheduledHandler} ${emailHandler} @@ -1439,7 +1489,7 @@ ${emailReceiptHandler} ${queueFunction}${webSocketClasses.map((name) => `export { ${name} };`).join('\n')} ${liveExport} ${sandboxExport} -${durableObjectExports} +${resourceModuleExports} ${entryClass}`; } diff --git a/packages/void/src/runtime/workflows/index.ts b/packages/void/src/runtime/workflows/index.ts new file mode 100644 index 000000000..6aeba30ed --- /dev/null +++ b/packages/void/src/runtime/workflows/index.ts @@ -0,0 +1,246 @@ +import { WorkflowEntrypoint } from 'cloudflare:workers'; +import type { WorkflowEvent, WorkflowStep } from 'cloudflare:workers'; +import { isResourceName } from '../../shared/resource-name.ts'; +import type { StandardSchemaV1 } from '../../standard-schema.ts'; +import { requireRuntimeBinding, withRuntimeEnv } from '../env/runtime.ts'; + +export type { WorkflowEvent, WorkflowStep }; + +type NativeWorkflowClass = new (...args: Array) => { + run(event: never, step: never): Promise; +}; + +/** Params type of a native class, read from its `run(event)` annotation. */ +export type NativeWorkflowParams = + InstanceType extends { + run(event: Readonly>, ...rest: Array): unknown; + } + ? TParams + : unknown; + +/** Context passed to a `defineWorkflow()` run function next to the event and step. */ +export type WorkflowContext = { + readonly env: TEnv; + readonly ctx: ExecutionContext; +}; + +/** Options for starting one Workflow instance. */ +export type WorkflowCreateOptions = Omit & { + params?: TParams; +}; + +export type WorkflowApi = { + class: TClass; + /** @internal Called by Void's generated Worker entry. */ + __bind(bindingName: string, resourceName?: string): void; + /** Start a new instance. Params are validated when the definition has a `params` schema. */ + create(options?: WorkflowCreateOptions): Promise; + create(binding: Workflow, options?: WorkflowCreateOptions): Promise; + /** Start up to 100 instances. Each instance's params are validated first. */ + createBatch( + instances: ReadonlyArray>, + ): Promise; + createBatch( + binding: Workflow, + instances: ReadonlyArray>, + ): Promise; + /** Get a handle to an existing instance. */ + get(id: string): Promise; + get(binding: Workflow, id: string): Promise; +}; + +export type WorkflowRun = ( + event: Readonly>, + step: WorkflowStep, + context: WorkflowContext, +) => Promise; + +export type WorkflowClass = new ( + ctx: ExecutionContext, + env: Record, +) => WorkflowEntrypoint, TParams>; + +/** Error thrown by `create()` and `createBatch()` when params fail the definition's schema. */ +export class WorkflowParamsError extends Error { + readonly issues: ReadonlyArray<{ message: string; path?: string }>; + + constructor(issues: ReadonlyArray) { + const flattened = Array.from(issues, (issue) => ({ + message: issue.message, + ...(issue.path?.length + ? { + path: issue.path + .map((segment) => String(typeof segment === 'object' ? segment.key : segment)) + .join('.'), + } + : {}), + })); + super( + `workflows: invalid params: ${flattened + .map((issue) => (issue.path ? `${issue.path}: ${issue.message}` : issue.message)) + .join('; ')}`, + ); + this.name = 'WorkflowParamsError'; + this.issues = flattened; + } +} + +function isWorkflowBinding(value: Workflow | TOther): value is Workflow { + return ( + typeof value === 'object' && + value !== null && + typeof (value as { create?: unknown }).create === 'function' && + typeof (value as { get?: unknown }).get === 'function' + ); +} + +function createWorkflowApi( + definitionName: string | undefined, + workflowClass: TClass, + schema: StandardSchemaV1 | undefined, +): WorkflowApi { + if (definitionName !== undefined && !isResourceName(definitionName)) { + throw new Error('workflows: name must contain a word starting with a letter.'); + } + let bindingName: string | undefined; + + function boundWorkflow(): Workflow { + if (!bindingName) { + throw new Error( + 'workflows: this definition is not bound. Default-export it from a file in workflows/.', + ); + } + return requireRuntimeBinding(bindingName); + } + + async function prepare( + options: WorkflowCreateOptions | undefined, + ): Promise { + if (!schema) { + return options; + } + const result = await schema['~standard'].validate(options?.params); + if (result.issues) { + throw new WorkflowParamsError(result.issues); + } + return { ...options, params: result.value }; + } + + return { + class: workflowClass, + __bind(name, resourceName) { + if (definitionName !== resourceName) { + throw new Error( + 'workflows: name must be statically discoverable in the workflow definition. Run void info to inspect this definition.', + ); + } + if (bindingName && bindingName !== name) { + throw new Error( + `workflows: definition is already bound to '${bindingName}' and cannot also bind to '${name}'.`, + ); + } + bindingName = name; + }, + async create( + bindingOrOptions?: Workflow | WorkflowCreateOptions, + maybeOptions?: WorkflowCreateOptions, + ) { + const explicit = isWorkflowBinding(bindingOrOptions); + const binding = explicit ? bindingOrOptions : boundWorkflow(); + const options = explicit ? maybeOptions : bindingOrOptions; + return binding.create(await prepare(options)); + }, + async createBatch( + bindingOrInstances: Workflow | ReadonlyArray>, + maybeInstances?: ReadonlyArray>, + ) { + const explicit = isWorkflowBinding(bindingOrInstances); + const binding = explicit ? bindingOrInstances : boundWorkflow(); + const instances = explicit ? (maybeInstances ?? []) : bindingOrInstances; + const prepared = await Promise.all( + Array.from(instances, async (instance) => (await prepare(instance)) ?? {}), + ); + return binding.createBatch({ instances: prepared }); + }, + get(bindingOrId: Workflow | string, maybeId?: string) { + if (typeof bindingOrId === 'string') { + return boundWorkflow().get(bindingOrId); + } + if (maybeId === undefined) { + throw new Error('workflows: get(binding, id) requires an instance id.'); + } + return bindingOrId.get(maybeId); + }, + }; +} + +type WorkflowDefinitionBase = { + /** Optional persistent resource name. Pin the name reported by `void info` before moving this definition. */ + name?: string; +}; + +/** + * Define a Workflow from a run function. Void generates the Cloudflare + * `WorkflowEntrypoint` class. Default-export the result from a file in `workflows/`. + */ +export function defineWorkflow< + TSchema extends StandardSchemaV1, + TEnv extends Record = Record, +>( + definition: WorkflowDefinitionBase & { + /** Standard Schema that validates params in `create()` and `createBatch()`. */ + params: TSchema; + run: WorkflowRun, TEnv>; + }, +): WorkflowApi< + WorkflowClass>, + StandardSchemaV1.InferInput +>; +export function defineWorkflow< + TParams = unknown, + TEnv extends Record = Record, +>( + definition: WorkflowDefinitionBase & { + params?: undefined; + run: WorkflowRun; + }, +): WorkflowApi, TParams>; +export function defineWorkflow( + definition: WorkflowDefinitionBase & { + params?: StandardSchemaV1; + run: WorkflowRun>; + }, +): WorkflowApi, unknown> { + if (typeof definition.run !== 'function') { + throw new Error('workflows: defineWorkflow() requires a run function.'); + } + const run = definition.run; + + class VoidWorkflow extends WorkflowEntrypoint, unknown> { + override run(event: Readonly>, step: WorkflowStep): Promise { + const env = this.env; + const ctx = this.ctx; + return withRuntimeEnv(env, () => run(event, step, { env, ctx })); + } + } + + return createWorkflowApi(definition.name, VoidWorkflow, definition.params); +} + +/** + * Register a native Cloudflare `WorkflowEntrypoint` class without changing it. + * Default-export the result from a file in `workflows/`. + */ +export function defineWorkflowEntrypoint< + TClass extends NativeWorkflowClass, + TParams = NativeWorkflowParams, +>( + definition: WorkflowDefinitionBase & { + class: TClass; + }, +): WorkflowApi { + if (typeof definition.class !== 'function') { + throw new Error('workflows: defineWorkflowEntrypoint() requires a class.'); + } + return createWorkflowApi(definition.name, definition.class, undefined); +} diff --git a/packages/void/src/shared/env.ts b/packages/void/src/shared/env.ts index fdb3322eb..fdb638041 100644 --- a/packages/void/src/shared/env.ts +++ b/packages/void/src/shared/env.ts @@ -41,6 +41,12 @@ export const CLOUDFLARE_DEPLOY_BUILD_ENV = 'VOID_CLOUDFLARE_DEPLOY_BUILD'; */ export const CLOUDFLARE_QUEUE_NAMES_BUILD_ENV = 'VOID_CLOUDFLARE_QUEUE_NAMES'; +/** + * The Worker name `void deploy --platform cloudflare` deploys to. Set only for + * its Vite build, which prefixes account-scoped Workflow names with it. + */ +export const CLOUDFLARE_WORKER_NAME_BUILD_ENV = 'VOID_CLOUDFLARE_WORKER_NAME'; + /** * Find legacy Vite dotenv variants. Void intentionally supports only `.env`; * production configuration is project-scoped remote state instead of a file. diff --git a/packages/void/src/shared/resource-definition.ts b/packages/void/src/shared/resource-definition.ts index 2c74460b2..7e85aeb92 100644 --- a/packages/void/src/shared/resource-definition.ts +++ b/packages/void/src/shared/resource-definition.ts @@ -63,7 +63,9 @@ export function readResourceDefinition( ? new Set(['defineRoom', 'defineWebSocket']) : source === 'void/durable' ? new Set(['defineDurableState', 'defineDurableObject']) - : new Set(); + : source === 'void/workflows' + ? new Set(['defineWorkflow', 'defineWorkflowEntrypoint']) + : new Set(); for (const specifier of declaration.specifiers ?? []) { const local = specifier.local as AstNode | undefined; recordBindings(local); diff --git a/packages/void/src/workflows/config.ts b/packages/void/src/workflows/config.ts new file mode 100644 index 000000000..610a6ded1 --- /dev/null +++ b/packages/void/src/workflows/config.ts @@ -0,0 +1,55 @@ +import { cloudflareWorkflowName } from './scan.ts'; +import type { WorkflowModule } from './scan.ts'; + +export type WorkflowConfigEntry = Record & { + name?: unknown; + binding?: unknown; + class_name?: unknown; + script_name?: unknown; +}; + +export function workflowConfigEntries(value: unknown): Array { + if (value === undefined) { + return []; + } + if ( + !Array.isArray(value) || + value.some((entry) => !entry || typeof entry !== 'object' || Array.isArray(entry)) + ) { + throw new Error('Cloudflare workflows configuration must be an array of objects.'); + } + return value as Array; +} + +/** + * The `workflows` entries Void adds for `workflows/` modules, given the entries + * already configured. A module whose binding is already configured for the same + * local class is kept as configured, so an authored entry can pin the name. + */ +export function planWorkflowAdditions( + existing: ReadonlyArray, + modules: ReadonlyArray>, + workerName: string, +): Array<{ name: string; binding: string; class_name: string }> { + const additions: Array<{ name: string; binding: string; class_name: string }> = []; + for (const module of modules) { + const configured = existing.find((entry) => entry.binding === module.bindingName); + if (configured) { + if (configured.class_name !== module.className || configured.script_name !== undefined) { + throw new Error( + `workflows: binding '${module.bindingName}' is already configured for another Workflow, but workflows/ requires class '${module.className}'.`, + ); + } + continue; + } + const name = cloudflareWorkflowName(module.resourceName, workerName); + const owner = [...existing, ...additions].find((entry) => entry.name === name); + if (owner) { + throw new Error( + `workflows: Workflow name '${name}' is already configured for binding '${String(owner.binding)}'.`, + ); + } + additions.push({ name, binding: module.bindingName, class_name: module.className }); + } + return additions; +} diff --git a/packages/void/src/workflows/platform.ts b/packages/void/src/workflows/platform.ts new file mode 100644 index 000000000..b06544ff3 --- /dev/null +++ b/packages/void/src/workflows/platform.ts @@ -0,0 +1,10 @@ +import { scanWorkflowModules } from './scan.ts'; + +/** Void platform deploys do not provision Cloudflare Workflows yet. */ +export function assertNoWorkflowsForPlatform(root: string): void { + if (scanWorkflowModules(root).length > 0) { + throw new Error( + 'workflows: workflows/ is not supported on Void platforms yet. Deploy this app to your own Cloudflare account with `void deploy --platform cloudflare`.', + ); + } +} diff --git a/packages/void/src/workflows/scan.ts b/packages/void/src/workflows/scan.ts new file mode 100644 index 000000000..7385175f3 --- /dev/null +++ b/packages/void/src/workflows/scan.ts @@ -0,0 +1,111 @@ +import { existsSync, readFileSync } from 'node:fs'; +import { join } from 'pathslash'; +import { globSync } from 'tinyglobby'; +import { readResourceDefinition } from '../shared/resource-definition.ts'; +import { resourceNameWords } from '../shared/resource-name.ts'; + +export type WorkflowModule = { + filePath: string; + /** Path relative to `workflows/`, with `/` separators. */ + relativePath: string; + bindingName: string; + className: string; + /** Kebab-case resource name. Cloudflare Workflow names are derived from it. */ + resourceName: string; + name?: string; +}; + +const MODULE_PATTERN = /\.(?:[cm]?[jt]s)$/; +const MODULE_GLOB = '**/*.{ts,mts,cts,js,mjs,cjs}'; + +const WORKFLOW_HELPERS = new Set(['defineWorkflow', 'defineWorkflowEntrypoint']); + +/** + * The name a module gets without an explicit `name`: its path relative to + * `workflows/` without the extension, with directories joined by `-`, as + * queue names are (`order/notifications.ts` → `order-notifications`). + */ +export function inferWorkflowResourceName(relativePath: string): string { + return relativePath.replaceAll('\\', '/').replace(MODULE_PATTERN, '').replaceAll('/', '-'); +} + +/** Module files under `workflows/`, skipping declarations and `_`-prefixed files or directories. */ +function listWorkflowFiles(directory: string): Array { + return globSync(MODULE_GLOB, { cwd: directory }) + .map((file) => file.replaceAll('\\', '/')) + .filter( + (file) => + !file.endsWith('.d.ts') && + !file.endsWith('.d.mts') && + !file.endsWith('.d.cts') && + file.split('/').every((segment) => !segment.startsWith('_')), + ) + .sort((a, b) => a.localeCompare(b)); +} + +export function deriveWorkflowResourceIdentity(name: string): { + bindingName: string; + className: string; + resourceName: string; +} { + const parts = resourceNameWords(name); + const classBase = parts.map((part) => part[0].toUpperCase() + part.slice(1)).join(''); + return { + bindingName: `WORKFLOW_${parts.join('_').toUpperCase()}`, + className: `${classBase}Workflow`, + resourceName: parts.join('-').toLowerCase(), + }; +} + +/** + * Cloudflare Workflow names are unique per account. Deploys prefix them with the + * Worker name; local development, where names only need to be unique per Worker, + * uses the resource name alone. + */ +export function cloudflareWorkflowName(resourceName: string, workerName?: string): string { + if (!workerName) { + return resourceName; + } + const prefix = workerName.toLowerCase().replaceAll('_', '-'); + return `${prefix}-${resourceName}`.slice(0, 64); +} + +export function scanWorkflowModules(root: string): Array { + const directory = join(root, 'workflows'); + if (!existsSync(directory)) { + return []; + } + + const modules = listWorkflowFiles(directory).map((relativePath) => { + const filePath = join(directory, relativePath); + const definition = readResourceDefinition( + filePath, + readFileSync(filePath, 'utf8'), + WORKFLOW_HELPERS, + ); + const name = definition?.name; + const resourceName = name ?? inferWorkflowResourceName(relativePath); + if (resourceNameWords(resourceName).length === 0) { + throw new Error(`workflows: cannot derive a name from workflows/${relativePath}.`); + } + return { + filePath, + relativePath, + ...deriveWorkflowResourceIdentity(resourceName), + ...(name === undefined ? {} : { name }), + }; + }); + + const bindings = new Set(); + const classes = new Set(); + for (const module of modules) { + if (bindings.has(module.bindingName) || classes.has(module.className)) { + throw new Error( + `workflows: duplicate generated name for 'workflows/${module.relativePath}'. Choose a different resource name or rename one of the workflows files.`, + ); + } + bindings.add(module.bindingName); + classes.add(module.className); + } + return modules; +} diff --git a/packages/void/test/integration/cloudflare-durable-build.test.ts b/packages/void/test/integration/cloudflare-durable-build.test.ts index 571e2f8fa..c2c01e8b9 100644 --- a/packages/void/test/integration/cloudflare-durable-build.test.ts +++ b/packages/void/test/integration/cloudflare-durable-build.test.ts @@ -9,6 +9,7 @@ import { verifyGeneratedDeployConfig } from '../../src/cli/deploy-artifact-valid import { reconstructExpectedContainers, reconstructExpectedDurableObjectState, + reconstructExpectedWorkflows, snapshotBindingIdentities, snapshotPassthroughIdentities, snapshotPassthroughRawFields, @@ -18,7 +19,10 @@ import { syncWranglerBindings } from '../../src/cli/wrangler.ts'; import { materializeCloudflareConfig } from '../../src/cloudflare-config.ts'; import { renderVoidConfig } from '../../src/config-write.ts'; import { readConfig } from '../../src/config.ts'; -import { CLOUDFLARE_DEPLOY_BUILD_ENV } from '../../src/shared/env.ts'; +import { + CLOUDFLARE_DEPLOY_BUILD_ENV, + CLOUDFLARE_WORKER_NAME_BUILD_ENV, +} from '../../src/shared/env.ts'; const repository = join(import.meta.dirname, '..', '..', '..', '..'); const accountId = '0123456789abcdef0123456789abcdef'; @@ -149,6 +153,13 @@ export default defineDurableState({ initialState: { count: 0 }, methods: { incre ), expectedCrons: signals.expectedCrons, expectedDurableObjectBindings: durable.bindings, + expectedWorkflows: reconstructExpectedWorkflows( + config, + root, + rootConfig, + `durable-merge-${options.name}`, + analysis, + ), expectedMigrations: durable.migrations, }; const build = () => { @@ -172,9 +183,12 @@ export default defineDurableState({ initialState: { count: 0 }, methods: { incre containers?: Array; hyperdrive?: Array; ai?: unknown; + workflows?: Array; }; }; const emitted = build(); + // Workflows are opt-in: an app without workflows/ emits no Workflow config. + expect(emitted.workflows).toBeUndefined(); // Exercise worker/cloudflare overlap through the actual provider plugin, // alongside the existing native build rather than booting another one. if (options.name === 'native') { @@ -215,4 +229,94 @@ export default defineDurableState({ initialState: { count: 0 }, methods: { incre } }, ); + + it('emits Workflow entries named after the deployed Worker and keeps authored ones', () => { + const fixture = createIsolatedPlayground(repository, 'playground/ssr'); + const root = fixture.root; + try { + mkdirSync(join(root, 'workflows'), { recursive: true }); + writeFileSync( + join(root, 'workflows/welcome.ts'), + `import { defineWorkflow } from 'void/workflows'; +export default defineWorkflow({ async run(event, step) { return step.do('greet', async () => 'hi'); } });\n`, + ); + writeFileSync( + join(root, 'workflows/nightly-import.ts'), + `import { WorkflowEntrypoint } from 'cloudflare:workers'; +import { defineWorkflowEntrypoint } from 'void/workflows'; +class Importer extends WorkflowEntrypoint { async run() { return 'imported'; } } +export default defineWorkflowEntrypoint({ class: Importer });\n`, + ); + const pinned = { + name: 'legacy-import', + binding: 'WORKFLOW_NIGHTLY_IMPORT', + class_name: 'NightlyImportWorkflow', + }; + writeFileSync( + join(root, 'void.config.ts'), + renderVoidConfig({ + ...readConfig(root), + cloudflare: { name: 'workflow-merge', account_id: accountId, workflows: [pinned] }, + }), + ); + const config = readConfig(root); + const analysis = analyzeApplicationSync(root, { config }); + const configPath = materializeCloudflareConfig(root); + const rootConfig = parseRootWranglerConfig(configPath); + const expectedWorkflows = reconstructExpectedWorkflows( + config, + root, + rootConfig, + 'deployed-app', + analysis, + ); + expect(expectedWorkflows).toEqual([ + pinned, + { + name: 'deployed-app-welcome', + binding: 'WORKFLOW_WELCOME', + class_name: 'WelcomeWorkflow', + }, + ]); + const result = spawn.sync('vp', ['build'], { + cwd: root, + encoding: 'utf8', + timeout: 60_000, + maxBuffer: 10 * 1024 * 1024, + env: { + ...process.env, + [CLOUDFLARE_DEPLOY_BUILD_ENV]: '1', + [CLOUDFLARE_WORKER_NAME_BUILD_ENV]: 'deployed-app', + CLOUDFLARE_API_TOKEN: '', + CLOUDFLARE_API_KEY: '', + }, + }); + expect(result.status, `${result.stdout ?? ''}${result.stderr ?? ''}`).toBe(0); + const emitted = JSON.parse(readFileSync(join(root, 'dist/ssr/wrangler.json'), 'utf8')) as { + workflows?: Array>; + }; + expect(emitted.workflows).toEqual(expect.arrayContaining(expectedWorkflows)); + expect(emitted.workflows).toHaveLength(expectedWorkflows.length); + const worker = readFileSync(join(root, 'dist/ssr/index.js'), 'utf8'); + expect(worker).toMatch(/WelcomeWorkflow/); + expect(worker).toMatch(/NightlyImportWorkflow/); + expect( + verifyGeneratedDeployConfig(root, { + accountId, + workerName: 'workflow-merge', + passthroughIdentitySnapshot: snapshotPassthroughIdentities(rootConfig), + expectedWorkflows, + }), + ).toEqual({ ok: true }); + expect( + verifyGeneratedDeployConfig(root, { + accountId, + workerName: 'workflow-merge', + expectedWorkflows: [pinned], + }), + ).toMatchObject({ ok: false, reason: expect.stringContaining('workflows differ') }); + } finally { + fixture.cleanup(); + } + }, 120_000); }); diff --git a/packages/void/test/integration/workflow-runtime.test.ts b/packages/void/test/integration/workflow-runtime.test.ts new file mode 100644 index 000000000..8680a0131 --- /dev/null +++ b/packages/void/test/integration/workflow-runtime.test.ts @@ -0,0 +1,222 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { Miniflare, convertV4MiniflareOptions } from 'miniflare'; +import { build } from 'vite'; +import { afterAll, beforeAll, describe, expect, it } from 'vite-plus/test'; +import { compileWorkerEntry } from '../../src/router/compile.ts'; + +const root = join(import.meta.dirname, '..', '..', '..', '..'); +const runtimePath = join(root, 'packages/void/src/runtime/workflows/index.ts'); +const durablePath = join(root, 'packages/void/src/runtime/durable/index.ts'); +const temporary = mkdtempSync(join(tmpdir(), 'void-workflow-runtime-')); +type Runtime = { dispatchFetch(url: string): Promise; dispose(): Promise }; +let runtime: Runtime; + +const ROUTE_STUBS = ` +export const scheduled = async () => {}; +export const __voidCollectPrerenderPaths = async () => []; +export const __voidRenderStaticNotFound = async () => new Response(null, { status: 204 }); +export const __voidHandleInternalRoute = async () => null; +export const __withRawEnv = (_env, fn) => fn(); +`; + +/** Build a generated Worker entry for `entryOptions` into `name/worker.mjs`. */ +async function buildWorker( + name: string, + routes: string, + entryOptions: Parameters[0], +): Promise { + const directory = join(temporary, name); + const routesPath = join(temporary, `${name}-routes.ts`); + const entryPath = join(temporary, `${name}-entry.ts`); + writeFileSync(routesPath, ROUTE_STUBS + routes); + writeFileSync( + entryPath, + compileWorkerEntry({ + runtimeEnvPath: join(root, 'packages/void/src/runtime/env/runtime.ts'), + ...entryOptions, + }), + ); + await build({ + configFile: false, + logLevel: 'silent', + plugins: [ + { + name: 'workflow-runtime-fixture', + resolveId: (id) => (id === 'virtual:void-routes' ? routesPath : null), + }, + ], + ssr: { noExternal: true }, + build: { + outDir: directory, + emptyOutDir: true, + ssr: entryPath, + target: 'esnext', + rollupOptions: { + external: [/^cloudflare:/, /^node:/], + output: { entryFileNames: 'worker.mjs', codeSplitting: false }, + }, + }, + }); + return directory; +} + +function file(name: string, source: string): string { + const path = join(temporary, name); + writeFileSync(path, source); + return path; +} + +describe('Workflows through the generated Worker and a real Workflows engine', () => { + beforeAll(async () => { + const definition = file( + 'welcome.ts', + ` +import { defineWorkflow } from ${JSON.stringify(runtimePath)}; +const params = { '~standard': { version: 1, vendor: 'test', validate(value) { + return typeof value?.name === 'string' ? { value } : { issues: [{ message: 'name is required', path: ['name'] }] }; +} } }; +export const Welcome = defineWorkflow({ + params, + async run(event, step, { env }) { + const greeting = await step.do('greet', async () => env.GREETING + ', ' + event.payload.name); + return { greeting }; + }, +}); +export default Welcome; +`, + ); + const output = await buildWorker( + 'valid', + ` +import { Welcome } from ${JSON.stringify(definition)}; +export default { async fetch(request) { + const url = new URL(request.url); + if (url.pathname === '/start') { + try { + const instance = await Welcome.create({ id: url.searchParams.get('id'), params: { name: url.searchParams.get('name') ?? undefined } }); + return Response.json({ id: instance.id }); + } catch (error) { + return Response.json({ error: error.message }, { status: 400 }); + } + } + const instance = await Welcome.get(url.searchParams.get('id')); + return Response.json(await instance.status()); +}}; +`, + { + workflows: [ + { + bindingName: 'WORKFLOW_WELCOME', + className: 'WelcomeWorkflow', + filePath: definition, + }, + ], + }, + ); + runtime = new Miniflare( + convertV4MiniflareOptions({ + compatibilityDate: '2026-07-01', + compatibilityFlags: ['nodejs_compat'], + modules: true, + modulesRoot: output, + scriptPath: join(output, 'worker.mjs'), + bindings: { GREETING: 'Hello' }, + workflows: { WORKFLOW_WELCOME: { name: 'welcome', className: 'WelcomeWorkflow' } }, + }), + ) as unknown as Runtime; + }, 30_000); + + afterAll(async () => { + await runtime?.dispose(); + rmSync(temporary, { recursive: true, force: true }); + }); + + it('starts an instance from a route and runs its steps with the Worker env', async () => { + const started = await runtime.dispatchFetch('http://localhost/start?id=first&name=Ada'); + expect(started.status).toBe(200); + expect(await started.json()).toEqual({ id: 'first' }); + + let status: { status: string; output?: unknown } = { status: 'queued' }; + for (let attempt = 0; attempt < 100 && status.status !== 'complete'; attempt++) { + const response = await runtime.dispatchFetch('http://localhost/status?id=first'); + status = await response.json(); + if (status.status === 'errored') { + break; + } + await new Promise((resolve) => { + setTimeout(resolve, 50); + }); + } + expect(status).toMatchObject({ status: 'complete', output: { greeting: 'Hello, Ada' } }); + }); + + it('rejects invalid params before starting an instance', async () => { + const response = await runtime.dispatchFetch('http://localhost/start?id=invalid'); + expect(response.status).toBe(400); + expect(await response.json()).toEqual({ + error: 'workflows: invalid params: name: name is required', + }); + }); +}); + +describe('convention modules without a definition default export', () => { + it.each([ + { + kind: 'workflows', + source: 'export const Welcome = 1;', + message: + 'workflows: workflows/missing.ts must default-export defineWorkflow() or defineWorkflowEntrypoint().', + }, + { + kind: 'workflows', + source: 'export default class Welcome {}', + message: + 'workflows: workflows/missing.ts must default-export defineWorkflow() or defineWorkflowEntrypoint().', + }, + { + kind: 'durable-objects', + source: 'export const Counter = 1;', + message: + 'durable: durable-objects/missing.ts must default-export defineDurableState() or defineDurableObject().', + }, + { + kind: 'durable-objects', + source: `import { defineDurableState } from ${JSON.stringify(durablePath)}; +export const Counter = defineDurableState({ initialState: 0, methods: {} });`, + message: + 'durable: durable-objects/missing.ts must default-export defineDurableState() or defineDurableObject().', + }, + ])( + 'fails Worker startup with a clear error for $kind: $source', + async ({ kind, source, message }) => { + const name = `${kind}-${Math.random().toString(36).slice(2)}`; + const definition = join(temporary, name, kind); + mkdirSync(definition, { recursive: true }); + const filePath = join(definition, 'missing.ts'); + writeFileSync(filePath, source); + const entry = { bindingName: 'MISSING', className: 'Missing', filePath }; + const output = await buildWorker( + name, + 'export default { fetch: () => new Response("ok") };', + kind === 'workflows' ? { workflows: [entry] } : { durableObjects: [entry] }, + ); + const worker = new Miniflare( + convertV4MiniflareOptions({ + compatibilityDate: '2026-07-01', + compatibilityFlags: ['nodejs_compat'], + modules: true, + modulesRoot: output, + scriptPath: join(output, 'worker.mjs'), + }), + ) as unknown as Runtime; + try { + await expect(worker.dispatchFetch('http://localhost/')).rejects.toThrow(message); + } finally { + await worker.dispose().catch(() => {}); + } + }, + 30_000, + ); +}); diff --git a/packages/void/test/unit/compile.test.ts b/packages/void/test/unit/compile.test.ts index 267e6d9bd..517f63e49 100644 --- a/packages/void/test/unit/compile.test.ts +++ b/packages/void/test/unit/compile.test.ts @@ -857,11 +857,61 @@ describe('compileWorkerEntry', () => { ], }); - expect(code).toContain('import __voidDurableObject0 from "/app/durable-objects/counter.ts";'); + expect(code).toContain( + 'import * as __voidDurableObjectModule0 from "/app/durable-objects/counter.ts";', + ); expect(code).toContain('__voidDurableObject0.__bind("COUNTER");'); expect(code).toContain('export const CounterDurableObject = __voidDurableObject0.class;'); }); + it('re-exports Workflow modules as worker classes with their pinned names', () => { + const code = compileWorkerEntry({ + workflows: [ + { + bindingName: 'WORKFLOW_ONBOARDING', + className: 'OnboardingWorkflow', + filePath: '/app/workflows/onboarding.ts', + name: 'onboarding', + }, + ], + }); + + expect(code).toContain( + 'import * as __voidWorkflowModule0 from "/app/workflows/onboarding.ts";', + ); + expect(code).toContain('__voidWorkflow0.__bind("WORKFLOW_ONBOARDING", "onboarding");'); + expect(code).toContain('export const OnboardingWorkflow = __voidWorkflow0.class;'); + }); + + it('guards convention modules that do not default-export a definition', () => { + const code = compileWorkerEntry({ + durableObjects: [ + { + bindingName: 'COUNTER', + className: 'CounterDurableObject', + filePath: '/app/durable-objects/counter.ts', + }, + ], + workflows: [ + { + bindingName: 'WORKFLOW_ONBOARDING', + className: 'OnboardingWorkflow', + filePath: '/app/workflows/onboarding.ts', + }, + ], + }); + + expect(code).toContain( + 'if (typeof __voidDurableObject0?.__bind !== "function") { throw new Error("durable: durable-objects/counter.ts must default-export defineDurableState() or defineDurableObject()."); }', + ); + expect(code).toContain( + 'if (typeof __voidWorkflow0?.__bind !== "function") { throw new Error("workflows: workflows/onboarding.ts must default-export defineWorkflow() or defineWorkflowEntrypoint()."); }', + ); + expect(code.indexOf('typeof __voidWorkflow0?.__bind')).toBeLessThan( + code.indexOf('__voidWorkflow0.__bind('), + ); + }); + it('re-exports the live Durable Object class when enabled', () => { const code = compileWorkerEntry({ hasQueues: false, diff --git a/packages/void/test/unit/info.test.ts b/packages/void/test/unit/info.test.ts index c1474d0f4..0a6e13c42 100644 --- a/packages/void/test/unit/info.test.ts +++ b/packages/void/test/unit/info.test.ts @@ -92,6 +92,37 @@ describe('void info', () => { expect(existsSync(join(root, '.void'))).toBe(false); }); + it('reports Workflow identities with inferred and explicit names', () => { + const root = project(); + write(root, 'workflows/send-welcome.ts', 'export default defineWorkflow({ async run() {} });'); + write( + root, + 'workflows/import-v2.ts', + `import { defineWorkflowEntrypoint } from 'void/workflows'; +export default defineWorkflowEntrypoint({ name: 'import', class: Importer });`, + ); + const info = getProjectInfo(root); + expect(info.resources).toEqual([ + { + file: 'workflows/import-v2.ts', + definition: 'defineWorkflow', + name: 'import', + nameSource: 'explicit', + className: 'ImportWorkflow', + bindingName: 'WORKFLOW_IMPORT', + }, + { + file: 'workflows/send-welcome.ts', + definition: 'defineWorkflow', + name: 'send-welcome', + nameSource: 'inferred', + className: 'SendWelcomeWorkflow', + bindingName: 'WORKFLOW_SEND_WELCOME', + }, + ]); + expect(formatProjectInfo(info)).toContain("add this to 'defineWorkflow':"); + }); + it('keeps explicit names visible after moving code and respects configured source paths', () => { const root = project(); write(root, 'void.config.ts', "export default { sourceDir: 'src' };"); diff --git a/packages/void/test/unit/plugin-inference.test.ts b/packages/void/test/unit/plugin-inference.test.ts index f053de23f..ef8d34d15 100644 --- a/packages/void/test/unit/plugin-inference.test.ts +++ b/packages/void/test/unit/plugin-inference.test.ts @@ -761,6 +761,17 @@ describe('detectFramework', () => { 'void/durable', ), ).toThrow('void/durable is server-only'); + expect(() => + resolveId.call( + { + environment: { name: 'client' }, + error(message: string): never { + throw new Error(message); + }, + }, + 'void/workflows', + ), + ).toThrow('void/workflows is server-only'); } finally { cwd.mockRestore(); } @@ -830,8 +841,9 @@ describe('detectFramework', () => { try { voidPlugin(); const entry = readFileSync(join(root, '.void', 'entry.ts'), 'utf8'); - expect(entry).toContain('import __voidDurableObject0 from'); + expect(entry).toContain('import * as __voidDurableObjectModule0 from'); expect(entry).toContain('/durable-objects/shopping-cart.ts'); + expect(entry).toContain('const __voidDurableObject0 = __voidDurableObjectModule0.default;'); expect(entry).toContain('__voidDurableObject0.__bind("SHOPPING_CART")'); expect(entry).toContain( 'export const ShoppingCartDurableObject = __voidDurableObject0.class', @@ -841,6 +853,56 @@ describe('detectFramework', () => { } }); + it('exports convention-based Workflows from the worker entry', () => { + const root = createTempRoot(); + mkdirSync(join(root, 'routes'), { recursive: true }); + mkdirSync(join(root, 'workflows'), { recursive: true }); + writeFileSync(join(root, 'routes', 'index.ts'), 'export const GET = () => new Response("ok");'); + writeFileSync( + join(root, 'workflows', 'send-welcome.ts'), + 'export default { class: class SendWelcome {}, __bind() {} }', + ); + const cwd = vi.spyOn(process, 'cwd').mockReturnValue(root); + + try { + voidPlugin(); + const entry = readFileSync(join(root, '.void', 'entry.ts'), 'utf8'); + expect(entry).toContain('import * as __voidWorkflowModule0 from'); + expect(entry).toContain('/workflows/send-welcome.ts'); + expect(entry).toContain('__voidWorkflow0.__bind("WORKFLOW_SEND_WELCOME")'); + expect(entry).toContain('export const SendWelcomeWorkflow = __voidWorkflow0.class'); + expect(entry).toContain( + 'workflows: workflows/send-welcome.ts must default-export defineWorkflow() or defineWorkflowEntrypoint().', + ); + } finally { + cwd.mockRestore(); + } + }); + + it('rejects Workflow modules in framework adapter mode and on non-Cloudflare targets', () => { + const framework = createTempRoot(); + mkdirSync(join(framework, 'workflows'), { recursive: true }); + writeFileSync( + join(framework, 'package.json'), + JSON.stringify({ dependencies: { '@sveltejs/kit': '^2.0.0' } }), + ); + writeFileSync(join(framework, 'workflows', 'welcome.ts'), 'export default {}'); + const node = createTempRoot(); + mkdirSync(join(node, 'routes'), { recursive: true }); + mkdirSync(join(node, 'workflows'), { recursive: true }); + writeFileSync(join(node, 'void.json'), JSON.stringify({ target: 'node' })); + writeFileSync(join(node, 'workflows', 'welcome.ts'), 'export default {}'); + const cwd = vi.spyOn(process, 'cwd').mockReturnValue(framework); + + try { + expect(() => voidPlugin()).toThrow('workflows/ is currently supported in Void apps only'); + cwd.mockReturnValue(node); + expect(() => voidPlugin()).toThrow('workflows/ requires target: "cloudflare"'); + } finally { + cwd.mockRestore(); + } + }); + it('rejects typed Durable Object modules in framework adapter mode', () => { const root = createTempRoot(); mkdirSync(join(root, 'durable-objects'), { recursive: true }); diff --git a/packages/void/test/unit/workflow-runtime.test.ts b/packages/void/test/unit/workflow-runtime.test.ts new file mode 100644 index 000000000..7455c6d1b --- /dev/null +++ b/packages/void/test/unit/workflow-runtime.test.ts @@ -0,0 +1,151 @@ +import { WorkflowEntrypoint } from 'cloudflare:workers'; +import type { WorkflowEvent, WorkflowStep } from 'cloudflare:workers'; +import { describe, expect, expectTypeOf, it, vi } from 'vite-plus/test'; +import { getRuntimeEnv, withRuntimeEnv } from '../../src/runtime/env/runtime.ts'; +import { + defineWorkflow, + defineWorkflowEntrypoint, + WorkflowParamsError, +} from '../../src/runtime/workflows/index.ts'; +import type { WorkflowApi } from '../../src/runtime/workflows/index.ts'; +import type { StandardSchemaV1 } from '../../src/standard-schema.ts'; + +vi.mock('cloudflare:workers', () => ({ + WorkflowEntrypoint: class { + protected ctx: unknown; + protected env: unknown; + constructor(ctx: unknown, env: unknown) { + this.ctx = ctx; + this.env = env; + } + }, +})); + +function binding() { + const instance = { id: 'instance' } as unknown as WorkflowInstance; + return { + instance, + workflow: { + create: vi.fn(async (_options?: unknown) => instance), + createBatch: vi.fn(async (_options: unknown) => ({ created: [instance], errors: [] })), + get: vi.fn(async (_id: string) => instance), + }, + }; +} + +/** A minimal Standard Schema for `{ userId: string }` that trims the id. */ +const userSchema: StandardSchemaV1<{ userId: string }, { userId: string }> = { + '~standard': { + version: 1, + vendor: 'test', + validate(value) { + if ( + typeof value === 'object' && + value !== null && + typeof (value as { userId?: unknown }).userId === 'string' + ) { + return { value: { userId: (value as { userId: string }).userId.trim() } }; + } + return { issues: [{ message: 'Expected a string', path: [{ key: 'userId' }] }] }; + }, + }, +}; + +describe('defineWorkflow', () => { + it('generates an entrypoint that runs inside the Worker env', async () => { + const seen: Array = []; + const Welcome = defineWorkflow({ + async run(event: WorkflowEvent<{ userId: string }>, step, context) { + seen.push(event.payload.userId, context.env.GREETING, getRuntimeEnv().GREETING); + return step.do('greet', async () => 'done'); + }, + }); + const step = { do: vi.fn(async (_name: string, fn: () => Promise) => fn()) }; + const instance = new Welcome.class({} as ExecutionContext, { GREETING: 'hello' }); + expect(instance).toBeInstanceOf(WorkflowEntrypoint); + const result = await instance.run( + { payload: { userId: 'u1' } } as WorkflowEvent<{ userId: string }>, + step as unknown as WorkflowStep, + ); + expect(result).toBe('done'); + expect(seen).toEqual(['u1', 'hello', 'hello']); + }); + + it('starts, batches, and gets instances through its convention binding', async () => { + const { workflow, instance } = binding(); + const Welcome = defineWorkflow({ + async run(_event: WorkflowEvent<{ userId: string }>) {}, + }); + await expect(Welcome.create({ params: { userId: 'u1' } })).rejects.toThrow('not bound'); + Welcome.__bind('WORKFLOW_WELCOME'); + await withRuntimeEnv({ WORKFLOW_WELCOME: workflow }, async () => { + expect(await Welcome.create({ id: 'a', params: { userId: 'u1' } })).toBe(instance); + expect(await Welcome.get('a')).toBe(instance); + await Welcome.createBatch([{ params: { userId: 'u2' } }]); + }); + expect(workflow.create).toHaveBeenCalledWith({ id: 'a', params: { userId: 'u1' } }); + expect(workflow.get).toHaveBeenCalledWith('a'); + expect(workflow.createBatch).toHaveBeenCalledWith({ + instances: [{ params: { userId: 'u2' } }], + }); + expect(() => Welcome.__bind('OTHER')).toThrow('already bound'); + }); + + it('accepts an explicit binding', async () => { + const { workflow } = binding(); + const Welcome = defineWorkflow({ async run() {} }); + await Welcome.create(workflow as unknown as Workflow, { id: 'b' }); + await Welcome.get(workflow as unknown as Workflow, 'b'); + expect(workflow.create).toHaveBeenCalledWith({ id: 'b' }); + expect(workflow.get).toHaveBeenCalledWith('b'); + }); + + it('validates and transforms params with its schema before starting', async () => { + const { workflow } = binding(); + const Welcome = defineWorkflow({ + params: userSchema, + async run(event) { + expectTypeOf(event.payload).toEqualTypeOf>(); + }, + }); + Welcome.__bind('WORKFLOW_WELCOME'); + await withRuntimeEnv({ WORKFLOW_WELCOME: workflow }, async () => { + await Welcome.create({ params: { userId: ' u1 ' } }); + const invalid = Welcome.create({ params: { userId: 1 as unknown as string } }); + await expect(invalid).rejects.toBeInstanceOf(WorkflowParamsError); + await expect(invalid).rejects.toThrow('workflows: invalid params: userId: Expected a string'); + await expect(Welcome.create()).rejects.toThrow('invalid params'); + await expect( + Welcome.createBatch([{ params: { userId: 'ok' } }, { params: {} as { userId: string } }]), + ).rejects.toThrow('invalid params'); + }); + expect(workflow.create).toHaveBeenCalledTimes(1); + expect(workflow.create).toHaveBeenCalledWith({ params: { userId: 'u1' } }); + expect(workflow.createBatch).not.toHaveBeenCalled(); + }); + + it('rejects a runtime identity that differs from static analysis and invalid names', () => { + const Welcome = defineWorkflow({ name: 'welcome', async run() {} }); + expect(() => Welcome.__bind('WORKFLOW_WELCOME', 'other')).toThrow('statically discoverable'); + expect(() => defineWorkflow({ name: '123', async run() {} })).toThrow('name must contain'); + }); +}); + +describe('defineWorkflowEntrypoint', () => { + it('keeps the native class and infers params from its run annotation', async () => { + class Importer extends WorkflowEntrypoint, { file: string }> { + override async run(_event: Readonly>, _step: WorkflowStep) { + return 'imported'; + } + } + const { workflow } = binding(); + const Import = defineWorkflowEntrypoint({ name: 'import', class: Importer }); + expect(Import.class).toBe(Importer); + Import.__bind('WORKFLOW_IMPORT', 'import'); + await withRuntimeEnv({ WORKFLOW_IMPORT: workflow }, () => + Import.create({ params: { file: 'a.csv' } }), + ); + expectTypeOf(Import).toEqualTypeOf>(); + expect(workflow.create).toHaveBeenCalledWith({ params: { file: 'a.csv' } }); + }); +}); diff --git a/packages/void/test/unit/workflow-scan.test.ts b/packages/void/test/unit/workflow-scan.test.ts new file mode 100644 index 000000000..85da6f867 --- /dev/null +++ b/packages/void/test/unit/workflow-scan.test.ts @@ -0,0 +1,165 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { toSlash } from 'pathslash'; +import { afterEach, describe, expect, it } from 'vite-plus/test'; +import { planWorkflowAdditions } from '../../src/workflows/config.ts'; +import { assertNoWorkflowsForPlatform } from '../../src/workflows/platform.ts'; +import { + cloudflareWorkflowName, + deriveWorkflowResourceIdentity, + scanWorkflowModules, +} from '../../src/workflows/scan.ts'; + +const roots: Array = []; + +function createRoot(files: Record): string { + const root = mkdtempSync(join(tmpdir(), 'void-workflow-scan-')); + roots.push(root); + mkdirSync(join(root, 'workflows')); + for (const [filename, source] of Object.entries(files)) { + mkdirSync(dirname(join(root, 'workflows', filename)), { recursive: true }); + writeFileSync(join(root, 'workflows', filename), source); + } + return root; +} + +afterEach(() => { + for (const root of roots.splice(0)) { + rmSync(root, { recursive: true, force: true }); + } +}); + +describe('scanWorkflowModules', () => { + it('returns nothing without a workflows directory', () => { + const root = mkdtempSync(join(tmpdir(), 'void-workflow-scan-')); + roots.push(root); + expect(scanWorkflowModules(root)).toEqual([]); + expect(() => assertNoWorkflowsForPlatform(root)).not.toThrow(); + }); + + it('derives binding, class, and resource names from filenames', () => { + const root = createRoot({ 'send-welcome.ts': 'export default {}', 'types.d.ts': '' }); + expect(scanWorkflowModules(root)).toEqual([ + { + filePath: toSlash(join(root, 'workflows', 'send-welcome.ts')), + relativePath: 'send-welcome.ts', + bindingName: 'WORKFLOW_SEND_WELCOME', + className: 'SendWelcomeWorkflow', + resourceName: 'send-welcome', + }, + ]); + }); + + it('joins nested directories into the name, as queues do', () => { + const root = createRoot({ 'order/notifications.ts': 'export default {}' }); + expect(scanWorkflowModules(root)).toEqual([ + { + filePath: toSlash(join(root, 'workflows', 'order', 'notifications.ts')), + relativePath: 'order/notifications.ts', + bindingName: 'WORKFLOW_ORDER_NOTIFICATIONS', + className: 'OrderNotificationsWorkflow', + resourceName: 'order-notifications', + }, + ]); + }); + + it('ignores files and directories starting with an underscore', () => { + const root = createRoot({ + 'welcome.ts': 'export default {}', + '_steps.ts': 'export const send = () => {};', + '_lib/email.ts': 'export const send = () => {};', + 'order/_shared.ts': 'export const total = 0;', + }); + expect(scanWorkflowModules(root).map((module) => module.relativePath)).toEqual(['welcome.ts']); + }); + + it('rejects a nested path and a file that produce the same name', () => { + const root = createRoot({ + 'order/notifications.ts': 'export default {}', + 'order-notifications.ts': 'export default {}', + }); + expect(() => scanWorkflowModules(root)).toThrow('duplicate generated name'); + }); + + it('reads a static name through aliased imports without evaluating the module', () => { + const root = createRoot({ + 'renamed.ts': `import { defineWorkflowEntrypoint as workflow } from 'void/workflows'; + const name = 'nightly-import'; + export default workflow({ name, class: Importer });`, + }); + expect(scanWorkflowModules(root)[0]).toMatchObject({ + name: 'nightly-import', + ...deriveWorkflowResourceIdentity('nightly-import'), + }); + }); + + it('rejects files that normalize to the same generated names', () => { + const root = createRoot({ + 'send-welcome.ts': 'export default {}', + 'send_welcome.ts': 'export default {}', + }); + expect(() => scanWorkflowModules(root)).toThrow('duplicate generated name'); + }); + + it('rejects Void platform deploys while workflows exist', () => { + const root = createRoot({ 'welcome.ts': 'export default {}' }); + expect(() => assertNoWorkflowsForPlatform(root)).toThrow('void deploy --platform cloudflare'); + }); +}); + +describe('Cloudflare Workflow names', () => { + it('prefixes the account-scoped name with the Worker name', () => { + expect(cloudflareWorkflowName('welcome', 'My_App')).toBe('my-app-welcome'); + expect(cloudflareWorkflowName('welcome')).toBe('welcome'); + expect(cloudflareWorkflowName('w'.repeat(80), 'app')).toHaveLength(64); + }); + + it('adds only unconfigured modules and keeps an authored entry for the same class', () => { + const modules = [ + deriveWorkflowResourceIdentity('welcome'), + deriveWorkflowResourceIdentity('import'), + ]; + const authored = { + name: 'pinned-welcome', + binding: 'WORKFLOW_WELCOME', + class_name: 'WelcomeWorkflow', + }; + expect(planWorkflowAdditions([authored], modules, 'app')).toEqual([ + { name: 'app-import', binding: 'WORKFLOW_IMPORT', class_name: 'ImportWorkflow' }, + ]); + expect(planWorkflowAdditions([], [], 'app')).toEqual([]); + }); + + it('rejects a binding retargeted to another class or Worker, and a taken name', () => { + const modules = [deriveWorkflowResourceIdentity('welcome')]; + expect(() => + planWorkflowAdditions( + [{ name: 'x', binding: 'WORKFLOW_WELCOME', class_name: 'Other' }], + modules, + 'app', + ), + ).toThrow("binding 'WORKFLOW_WELCOME' is already configured"); + expect(() => + planWorkflowAdditions( + [ + { + name: 'x', + binding: 'WORKFLOW_WELCOME', + class_name: 'WelcomeWorkflow', + script_name: 'other-worker', + }, + ], + modules, + 'app', + ), + ).toThrow("binding 'WORKFLOW_WELCOME' is already configured"); + expect(() => + planWorkflowAdditions( + [{ name: 'app-welcome', binding: 'MINE', class_name: 'Mine' }], + modules, + 'app', + ), + ).toThrow("Workflow name 'app-welcome' is already configured for binding 'MINE'"); + }); +}); diff --git a/packages/void/vite.config.ts b/packages/void/vite.config.ts index a1773edb5..4d78ef351 100644 --- a/packages/void/vite.config.ts +++ b/packages/void/vite.config.ts @@ -104,6 +104,7 @@ export default defineConfig({ 'src/runtime/db/postgres.ts', 'src/runtime/db/mysql.ts', 'src/runtime/durable/index.ts', + 'src/runtime/workflows/index.ts', 'src/runtime/db/seed.ts', 'src/runtime/db/validators/drizzle-zod.ts', 'src/runtime/db/validators/drizzle-valibot.ts', From aafcfd64e32a48b4f82d1b6ec5b245fa33e37ffb Mon Sep 17 00:00:00 2001 From: Isak Gustavsen Date: Wed, 25 Nov 2026 01:13:36 +0100 Subject: [PATCH 2/2] fix(void): infer bindings from workflows/ modules Resource imports used only inside workflows/, including _-prefixed step helpers and nested folders, now count toward binding inference, as they already do for durable-objects/. Apps with a sourceDir scan workflows/ too. Co-Authored-By: Claude Opus 5.5 --- docs/reference/resource-inference.md | 2 +- packages/void/src/plugin-inference.ts | 4 +++- .../void/test/unit/plugin-inference.test.ts | 18 ++++++++++++++++++ 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/docs/reference/resource-inference.md b/docs/reference/resource-inference.md index 13407199d..8cfdaa096 100644 --- a/docs/reference/resource-inference.md +++ b/docs/reference/resource-inference.md @@ -71,7 +71,7 @@ Regardless of mode, these are always checked: - **SSR entry** such as `src/main.ssr.ts`, for SSR apps that access bindings during rendering - **Application source** in `src/` or your configured `sourceDir`, including resource and auth imports - **`durable-objects/`**, which is scanned for typed Durable Object state modules in native Void apps -- **`workflows/`**, which is scanned for Workflow modules in native Void apps +- **`workflows/`**, which is scanned for Workflow modules and the resources they use in native Void apps ## Custom Scan Directories diff --git a/packages/void/src/plugin-inference.ts b/packages/void/src/plugin-inference.ts index c3ec28f2c..e6c51e6d8 100644 --- a/packages/void/src/plugin-inference.ts +++ b/packages/void/src/plugin-inference.ts @@ -58,6 +58,7 @@ export const DEFAULT_SCAN_DIRS = [ 'crons', 'email', 'durable-objects', + 'workflows', 'src', ] as const; @@ -152,7 +153,8 @@ export function inferProjectBindings( ): InferredBindings { const paths = options?.paths ?? readProjectPaths(root); const dirs = - scanDirs ?? (paths.sourceDir ? [paths.sourceDir, 'durable-objects'] : DEFAULT_SCAN_DIRS); + scanDirs ?? + (paths.sourceDir ? [paths.sourceDir, 'durable-objects', 'workflows'] : DEFAULT_SCAN_DIRS); const allBindings: Array = []; const scannedFiles = new Set(); const routesPrefix = `${toSlash(paths.routesDir).replace(/\/$/, '')}/`; diff --git a/packages/void/test/unit/plugin-inference.test.ts b/packages/void/test/unit/plugin-inference.test.ts index ef8d34d15..4783d11f9 100644 --- a/packages/void/test/unit/plugin-inference.test.ts +++ b/packages/void/test/unit/plugin-inference.test.ts @@ -378,6 +378,24 @@ describe('inferProjectBindings', () => { }); }); + it('infers resources used only by Workflow modules and their helpers', () => { + const root = createTempRoot(); + mkdirSync(join(root, 'workflows', 'order'), { recursive: true }); + writeFileSync( + join(root, 'workflows', '_storage.ts'), + `import { createStorage } from 'void/storage'; + export const files = (env) => createStorage(env.STORAGE);`, + ); + writeFileSync( + join(root, 'workflows', 'order', 'summary.ts'), + `import { createAi } from 'void/ai'; + export const ai = (env) => createAi(env);`, + ); + expect(inferProjectBindings(root)).toMatchObject({ needsAI: true, needsR2: true }); + writeFileSync(join(root, 'void.json'), JSON.stringify({ sourceDir: 'src' })); + expect(inferProjectBindings(root)).toMatchObject({ needsAI: true, needsR2: true }); + }); + it('detects live from a stream module outside the default directories only when scanned', () => { const root = createTempRoot(); mkdirSync(join(root, 'routes'), { recursive: true });