workflow 5.0.1 → 5.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -0
- package/dist/api-workflow.d.ts.map +1 -1
- package/dist/api-workflow.js +4 -2
- package/docs/ai/chat-session-modeling.mdx +8 -8
- package/docs/ai/human-in-the-loop.mdx +2 -2
- package/docs/ai/index.mdx +14 -14
- package/docs/ai/streaming-updates-from-tools.mdx +2 -2
- package/docs/api-reference/workflow-api/register-lifecycle-hooks.mdx +15 -5
- package/docs/api-reference/workflow-nest/index.mdx +4 -1
- package/docs/api-reference/workflow-nest/is-workflow-request.mdx +58 -0
- package/docs/api-reference/workflow-nest/meta.json +1 -0
- package/docs/api-reference/workflow-nest/workflow-controller.mdx +6 -2
- package/docs/api-reference/workflow-nest/workflow-module.mdx +9 -1
- package/docs/api-reference/workflow-observability/parse-step-name.mdx +1 -1
- package/docs/changelog/batched-event-writes.mdx +3 -3
- package/docs/configuration/framework-options.mdx +6 -0
- package/docs/configuration/runtime-tuning.mdx +7 -5
- package/docs/configuration/worlds.mdx +11 -8
- package/docs/cookbook/integrations/ai-sdk.mdx +8 -8
- package/docs/cookbook/integrations/chat-sdk.mdx +8 -8
- package/docs/cookbook/integrations/sandbox.mdx +8 -8
- package/docs/errors/node-js-module-in-workflow.mdx +36 -0
- package/docs/foundations/hooks.mdx +35 -0
- package/docs/foundations/serialization.mdx +16 -1
- package/docs/foundations/streaming.mdx +1 -1
- package/docs/getting-started/astro.mdx +7 -9
- package/docs/getting-started/express.mdx +4 -10
- package/docs/getting-started/fastify.mdx +4 -9
- package/docs/getting-started/hono.mdx +4 -10
- package/docs/getting-started/index.mdx +2 -2
- package/docs/getting-started/nestjs.mdx +157 -36
- package/docs/getting-started/next.mdx +15 -18
- package/docs/getting-started/nitro.mdx +4 -10
- package/docs/getting-started/nuxt.mdx +4 -10
- package/docs/getting-started/react-router/v7.mdx +6 -22
- package/docs/getting-started/react-router/v8.mdx +6 -22
- package/docs/getting-started/sveltekit.mdx +7 -9
- package/docs/getting-started/tanstack-start.mdx +7 -9
- package/docs/getting-started/vite.mdx +7 -9
- package/docs/how-it-works/code-transform.mdx +12 -8
- package/docs/how-it-works/encryption.mdx +3 -1
- package/docs/observability/lifecycle-hooks.mdx +69 -5
- package/docs/observability/tracing.mdx +3 -0
- package/docs/whats-new.mdx +7 -7
- package/docs/worlds/building-a-world.mdx +6 -1
- package/docs/worlds/local.mdx +4 -0
- package/docs/worlds/postgres.mdx +13 -33
- package/docs/worlds/upgrading-to-v5.mdx +1 -1
- package/docs/worlds/vercel.mdx +19 -9
- package/package.json +12 -12
|
@@ -66,9 +66,9 @@ Because the session *is* a workflow run, its history is recoverable from the eve
|
|
|
66
66
|
|
|
67
67
|
This pattern uses three files. The bot definition is separate from the workflow so adapter packages stay out of the workflow sandbox.
|
|
68
68
|
|
|
69
|
-
<
|
|
69
|
+
<TabsWithChildren tabs={["Bot Setup","Workflow","Event Handlers"]}>
|
|
70
70
|
|
|
71
|
-
<
|
|
71
|
+
<TabContent order={1}>
|
|
72
72
|
|
|
73
73
|
Register the `Chat` instance as a singleton so step functions can dynamically import it and resolve adapters + state:
|
|
74
74
|
|
|
@@ -95,9 +95,9 @@ export const bot = new Chat<typeof adapters, ThreadState>({
|
|
|
95
95
|
|
|
96
96
|
`registerSingleton()` is important: Chat SDK re-hydrates `Thread` objects inside step functions, and it needs a registered singleton to resolve adapters and state for those rehydrated instances.
|
|
97
97
|
|
|
98
|
-
</
|
|
98
|
+
</TabContent>
|
|
99
99
|
|
|
100
|
-
<
|
|
100
|
+
<TabContent order={2}>
|
|
101
101
|
|
|
102
102
|
The workflow is a plain loop over a hook. It receives the serialized thread + first message from the handler, revives them via Chat SDK's standalone `reviver`, and every platform-side effect goes inside a `"use step"` helper:
|
|
103
103
|
|
|
@@ -174,9 +174,9 @@ export type ChatTurnPayload = {
|
|
|
174
174
|
};
|
|
175
175
|
```
|
|
176
176
|
|
|
177
|
-
</
|
|
177
|
+
</TabContent>
|
|
178
178
|
|
|
179
|
-
<
|
|
179
|
+
<TabContent order={3}>
|
|
180
180
|
|
|
181
181
|
Handlers live outside the workflow file so adapter dependencies don't leak in. They decide whether to start a new workflow or resume an existing one, then store the `runId` in thread state:
|
|
182
182
|
|
|
@@ -256,9 +256,9 @@ export async function POST(
|
|
|
256
256
|
}
|
|
257
257
|
```
|
|
258
258
|
|
|
259
|
-
</
|
|
259
|
+
</TabContent>
|
|
260
260
|
|
|
261
|
-
</
|
|
261
|
+
</TabsWithChildren>
|
|
262
262
|
|
|
263
263
|
## How it works
|
|
264
264
|
|
|
@@ -88,9 +88,9 @@ When the timer wins:
|
|
|
88
88
|
|
|
89
89
|
The only way out is an explicit `/destroy` command.
|
|
90
90
|
|
|
91
|
-
<
|
|
91
|
+
<TabsWithChildren tabs={["Workflow","API Routes","Client"]}>
|
|
92
92
|
|
|
93
|
-
<
|
|
93
|
+
<TabContent order={1}>
|
|
94
94
|
|
|
95
95
|
```typescript title="workflows/sandbox-session.ts" lineNumbers
|
|
96
96
|
import { defineHook, sleep, getWritable, getWorkflowMetadata } from "workflow";
|
|
@@ -298,9 +298,9 @@ export async function sandboxSessionWorkflow() {
|
|
|
298
298
|
}
|
|
299
299
|
```
|
|
300
300
|
|
|
301
|
-
</
|
|
301
|
+
</TabContent>
|
|
302
302
|
|
|
303
|
-
<
|
|
303
|
+
<TabContent order={2}>
|
|
304
304
|
|
|
305
305
|
Two endpoints manage the session. `/start` accepts an optional `{ runId }`: if the run still exists, it replays the event log from index 0 so a returning client fully rehydrates. `/command` resumes the hook and returns immediately; command output lands on the `/start` stream.
|
|
306
306
|
|
|
@@ -379,9 +379,9 @@ export async function POST(req: Request) {
|
|
|
379
379
|
}
|
|
380
380
|
```
|
|
381
381
|
|
|
382
|
-
</
|
|
382
|
+
</TabContent>
|
|
383
383
|
|
|
384
|
-
<
|
|
384
|
+
<TabContent order={3}>
|
|
385
385
|
|
|
386
386
|
On mount, reconnect to the existing run if `localStorage` contains a `runId`. Otherwise, start a new run. Send commands to `/command` with POST requests. Output arrives on the `/start` stream.
|
|
387
387
|
|
|
@@ -472,9 +472,9 @@ export function SandboxRunner() {
|
|
|
472
472
|
}
|
|
473
473
|
```
|
|
474
474
|
|
|
475
|
-
</
|
|
475
|
+
</TabContent>
|
|
476
476
|
|
|
477
|
-
</
|
|
477
|
+
</TabsWithChildren>
|
|
478
478
|
|
|
479
479
|
## How it works
|
|
480
480
|
|
|
@@ -27,6 +27,42 @@ Workflow functions run in a sandboxed environment without full Node.js runtime a
|
|
|
27
27
|
|
|
28
28
|
Node.js modules have side effects and non-deterministic behavior that could break workflow replay guarantees.
|
|
29
29
|
|
|
30
|
+
## Transitive dependencies and dynamic `require()`
|
|
31
|
+
|
|
32
|
+
The same error is reported for a module the workflow bundle could not inline, even when your own code never imports it directly:
|
|
33
|
+
|
|
34
|
+
```text
|
|
35
|
+
Workflow bundle cannot run in the workflow sandbox.
|
|
36
|
+
|
|
37
|
+
Imports left external (1):
|
|
38
|
+
• "node:fs"
|
|
39
|
+
imported by node_modules/leaky-pkg/index.js
|
|
40
|
+
via app/workflows/order.ts → node_modules/wrapper-pkg/index.js → node_modules/leaky-pkg/index.js
|
|
41
|
+
|
|
42
|
+
Unresolved require() calls (1):
|
|
43
|
+
• dynamic require() in node_modules/lazy-pkg/index.js (bundle 412:31)
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
The workflow sandbox has no `require`, so both would throw `ReferenceError: require is not defined` when the bundle loads. Follow the import chain to the first file you own and move that work into a step function, or replace a dynamic `require()` with a static import so the bundler can inline it.
|
|
47
|
+
|
|
48
|
+
A `require()` wrapped in `try`/`catch`, or behind a `typeof require` check, is not reported — that is how packages probe for an optional dependency or for a CommonJS environment, and in the sandbox the error is caught or the call never runs:
|
|
49
|
+
|
|
50
|
+
```js
|
|
51
|
+
try {
|
|
52
|
+
loadOptional(require("@emotion/is-prop-valid").default);
|
|
53
|
+
} catch {
|
|
54
|
+
// optional dependency, fall back
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
if (typeof require !== "undefined") {
|
|
58
|
+
crypto = require("crypto");
|
|
59
|
+
}
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
A `typeof require` check only excuses the branch it skips when `require` is undefined, so `typeof require === "undefined" ? require(x) : y` is still reported. A `try` only counts when it has a `catch`. The checks read the code's structure without running it, so a `catch` that rethrows the error is still treated as a guard, and the bundle fails at runtime if that code is reached.
|
|
63
|
+
|
|
64
|
+
As a last resort — for example a `require()` that can never run — set `WORKFLOW_ALLOW_UNSAFE_FLOW_BUNDLE=1` to downgrade the build failure to a warning. The bundle still fails at runtime if the code is reached.
|
|
65
|
+
|
|
30
66
|
## Quick fix
|
|
31
67
|
|
|
32
68
|
Move any code using Node.js modules to a step function. Step functions have full Node.js runtime access.
|
|
@@ -198,6 +198,41 @@ export async function dataCollectionWorkflow() {
|
|
|
198
198
|
|
|
199
199
|
Each time you call `resumeHook()` with the same token, the loop receives another value.
|
|
200
200
|
|
|
201
|
+
### Waiting with a timeout
|
|
202
|
+
|
|
203
|
+
Race a hook against `sleep()` to stop waiting after a deadline. To wait again after a timeout, create the hook's promise once and race that same promise on every attempt:
|
|
204
|
+
|
|
205
|
+
```typescript lineNumbers
|
|
206
|
+
import { createHook, sleep } from "workflow";
|
|
207
|
+
|
|
208
|
+
declare function sendReminder(): Promise<void>; // @setup
|
|
209
|
+
|
|
210
|
+
export async function reminderWorkflow() {
|
|
211
|
+
"use workflow";
|
|
212
|
+
|
|
213
|
+
using hook = createHook<{ approved: boolean }>();
|
|
214
|
+
const approval = hook.then((payload) => payload); // [!code highlight]
|
|
215
|
+
|
|
216
|
+
for (let reminder = 0; reminder < 3; reminder++) {
|
|
217
|
+
const result = await Promise.race([
|
|
218
|
+
approval, // [!code highlight]
|
|
219
|
+
sleep("1d").then(() => "timeout" as const),
|
|
220
|
+
]);
|
|
221
|
+
|
|
222
|
+
if (result !== "timeout") {
|
|
223
|
+
return result.approved;
|
|
224
|
+
}
|
|
225
|
+
await sendReminder();
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
return false;
|
|
229
|
+
}
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
Racing a fresh `hook.then()` on each attempt also receives an event that arrives while that race is running. An event that arrives between races, for example while `sendReminder()` runs, is delivered to the awaiter left behind by the earlier race, so the workflow never sees it. Don't race `iterator.next()` from `hook[Symbol.asyncIterator]()` either. The `next()` call that lost a race keeps waiting and takes the next event, even one that arrives while a later race is running. Race the promise you created once instead.
|
|
233
|
+
|
|
234
|
+
Don't await one hook from several places at the same time, for example `Promise.all([hook, hook])`. Which event each await receives depends on how far the workflow had replayed when it awaited, so it can differ between code that looks equivalent. To receive successive events, await them one after another or iterate with `for await...of`.
|
|
235
|
+
|
|
201
236
|
### Disposing hooks early
|
|
202
237
|
|
|
203
238
|
When a workflow ends, hooks are automatically disposed. However, you may want to release a hook token early so another workflow can use it while your workflow continues running. Use a block scope with `using` to control when disposal happens:
|
|
@@ -36,7 +36,7 @@ The following types can be serialized and passed through workflow functions:
|
|
|
36
36
|
- `BigInt64Array`, `BigUint64Array`
|
|
37
37
|
- `DataView`
|
|
38
38
|
- `Date`
|
|
39
|
-
- `Float32Array`, `Float64Array`
|
|
39
|
+
- `Float16Array`, `Float32Array`, `Float64Array`
|
|
40
40
|
- `Int8Array`, `Int16Array`, `Int32Array`
|
|
41
41
|
- `Map<Serializable, Serializable>`
|
|
42
42
|
- `RegExp`
|
|
@@ -59,6 +59,21 @@ These types have special handling and are explained in detail in the sections be
|
|
|
59
59
|
- `AbortController`
|
|
60
60
|
- `AbortSignal`
|
|
61
61
|
|
|
62
|
+
### Typing serializable values
|
|
63
|
+
|
|
64
|
+
Import the `Serializable` type from `workflow` to type values that cross a workflow or step boundary:
|
|
65
|
+
|
|
66
|
+
```typescript title="workflows/record-event.ts" lineNumbers
|
|
67
|
+
import type { Serializable } from "workflow";
|
|
68
|
+
|
|
69
|
+
async function recordEvent(payload: Serializable) {
|
|
70
|
+
"use step";
|
|
71
|
+
// ...
|
|
72
|
+
}
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
`Serializable` is a union of the JSON and built-in types listed above. It doesn't include `Request`, `Float16Array`, or classes with [custom serialization](#custom-class-serialization), so type those values directly.
|
|
76
|
+
|
|
62
77
|
## Pass-by-value semantics
|
|
63
78
|
|
|
64
79
|
**Parameters are passed by value, not by reference.** Steps receive deserialized copies of data. Mutations inside a step won't affect the original in the workflow.
|
|
@@ -337,7 +337,7 @@ async function runTurn(holderRunId: string, turn: number) {
|
|
|
337
337
|
Pass `{ namespace: "name" }` to target a [namespaced stream](#namespaced-streams). The writable can also be forwarded through `start()` and into steps.
|
|
338
338
|
|
|
339
339
|
<Callout type="warn">
|
|
340
|
-
Contributors should call `releaseLock()`, which flushes pending writes. Calling `close()` closes the shared stream for every writer.
|
|
340
|
+
Contributors should call `releaseLock()`, which flushes pending writes. Calling `close()` closes the shared stream for every writer. Calling `abort()` keeps the chunks already written and leaves the shared stream open.
|
|
341
341
|
</Callout>
|
|
342
342
|
|
|
343
343
|
The API grants append access, not read access or additional authorization. The owning run controls the stream's lifecycle, and writes to an unknown run fail.
|
|
@@ -61,12 +61,12 @@ export default defineConfig({
|
|
|
61
61
|
| --- | --- | --- | --- |
|
|
62
62
|
| `sourcemap` | `boolean \| 'inline' \| 'linked' \| 'external' \| 'both'` | `'inline'` (dev) / `false` (prod) | Controls source maps on generated workflow bundles. Accepts the same values as esbuild's `sourcemap` option. Defaults to `'inline'` in development and `false` in production (smaller function bundles, which helps stay under the Vercel 250 MB function size limit). Set it explicitly, or use the `WORKFLOW_SOURCEMAP` environment variable, to override in either environment. |
|
|
63
63
|
|
|
64
|
-
<
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
64
|
+
<Details>
|
|
65
|
+
<Summary className="[&_h3]:my-0">
|
|
66
|
+
|
|
67
|
+
### Set up IntelliSense for TypeScript (optional)
|
|
68
|
+
|
|
69
|
+
</Summary>
|
|
70
70
|
|
|
71
71
|
To enable helpful hints in your IDE, set up the workflow plugin in `tsconfig.json`:
|
|
72
72
|
|
|
@@ -83,9 +83,7 @@ To enable helpful hints in your IDE, set up the workflow plugin in `tsconfig.jso
|
|
|
83
83
|
}
|
|
84
84
|
```
|
|
85
85
|
|
|
86
|
-
|
|
87
|
-
</AccordionItem>
|
|
88
|
-
</Accordion>
|
|
86
|
+
</Details>
|
|
89
87
|
|
|
90
88
|
</Step>
|
|
91
89
|
|
|
@@ -72,12 +72,9 @@ export default defineNitroConfig({
|
|
|
72
72
|
});
|
|
73
73
|
```
|
|
74
74
|
|
|
75
|
-
<
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
Setup IntelliSense for TypeScript (Optional)
|
|
79
|
-
</AccordionTrigger>
|
|
80
|
-
<AccordionContent className="[&_p]:my-2">
|
|
75
|
+
<Details>
|
|
76
|
+
<Summary>Setup IntelliSense for TypeScript (Optional)</Summary>
|
|
77
|
+
|
|
81
78
|
To enable helpful hints in your IDE, setup the workflow plugin in `tsconfig.json`:
|
|
82
79
|
|
|
83
80
|
```json title="tsconfig.json" lineNumbers
|
|
@@ -93,10 +90,7 @@ To enable helpful hints in your IDE, setup the workflow plugin in `tsconfig.json
|
|
|
93
90
|
}
|
|
94
91
|
```
|
|
95
92
|
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
</AccordionItem>
|
|
99
|
-
</Accordion>
|
|
93
|
+
</Details>
|
|
100
94
|
|
|
101
95
|
### Update `package.json`
|
|
102
96
|
|
|
@@ -72,12 +72,9 @@ export default defineNitroConfig({
|
|
|
72
72
|
});
|
|
73
73
|
```
|
|
74
74
|
|
|
75
|
-
<
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
Setup IntelliSense for TypeScript (Optional)
|
|
79
|
-
</AccordionTrigger>
|
|
80
|
-
<AccordionContent className="[&_p]:my-2">
|
|
75
|
+
<Details>
|
|
76
|
+
<Summary>Setup IntelliSense for TypeScript (Optional)</Summary>
|
|
77
|
+
|
|
81
78
|
To enable helpful hints in your IDE, set up the workflow plugin in `tsconfig.json`:
|
|
82
79
|
|
|
83
80
|
```json title="tsconfig.json" lineNumbers
|
|
@@ -93,9 +90,7 @@ To enable helpful hints in your IDE, set up the workflow plugin in `tsconfig.jso
|
|
|
93
90
|
}
|
|
94
91
|
```
|
|
95
92
|
|
|
96
|
-
|
|
97
|
-
</AccordionItem>
|
|
98
|
-
</Accordion>
|
|
93
|
+
</Details>
|
|
99
94
|
|
|
100
95
|
### Update `package.json`
|
|
101
96
|
|
|
@@ -55,12 +55,9 @@ export default defineConfig({
|
|
|
55
55
|
});
|
|
56
56
|
```
|
|
57
57
|
|
|
58
|
-
<
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
Setup IntelliSense for TypeScript (Optional)
|
|
62
|
-
</AccordionTrigger>
|
|
63
|
-
<AccordionContent className="[&_p]:my-2">
|
|
58
|
+
<Details>
|
|
59
|
+
<Summary>Setup IntelliSense for TypeScript (Optional)</Summary>
|
|
60
|
+
|
|
64
61
|
To enable helpful hints in your IDE, setup the workflow plugin in `tsconfig.json`:
|
|
65
62
|
|
|
66
63
|
```json title="tsconfig.json" lineNumbers
|
|
@@ -76,10 +73,7 @@ To enable helpful hints in your IDE, setup the workflow plugin in `tsconfig.json
|
|
|
76
73
|
}
|
|
77
74
|
```
|
|
78
75
|
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
</AccordionItem>
|
|
82
|
-
</Accordion>
|
|
76
|
+
</Details>
|
|
83
77
|
|
|
84
78
|
### Update `package.json`
|
|
85
79
|
|
|
@@ -80,14 +80,14 @@ import { SiReactrouter } from "@icons-pack/react-simple-icons";
|
|
|
80
80
|
<div className="flex flex-col items-center justify-center gap-2">
|
|
81
81
|
<Python className="size-16" />
|
|
82
82
|
<span className="font-medium">Python</span>
|
|
83
|
-
<Badge variant="
|
|
83
|
+
<Badge variant="gray" size="sm">Beta</Badge>
|
|
84
84
|
</div>
|
|
85
85
|
</Card>
|
|
86
86
|
<Card href="/docs/getting-started/nestjs">
|
|
87
87
|
<div className="flex flex-col items-center justify-center gap-2">
|
|
88
88
|
<Nest className="size-16 dark:invert" />
|
|
89
89
|
<span className="font-medium">NestJS</span>
|
|
90
|
-
<Badge variant="secondary">
|
|
90
|
+
<Badge variant="secondary">Beta</Badge>
|
|
91
91
|
</div>
|
|
92
92
|
</Card>
|
|
93
93
|
</Cards>
|
|
@@ -16,7 +16,7 @@ related:
|
|
|
16
16
|
Set up your first durable workflow in a NestJS app and learn the core Workflow SDK concepts.
|
|
17
17
|
|
|
18
18
|
<Callout>
|
|
19
|
-
NestJS integration is
|
|
19
|
+
NestJS integration is in beta. Deployment to Vercel is supported via the
|
|
20
20
|
`workflow-nest build --vercel` command. See [Deploy to Vercel](#deploy-to-vercel) below.
|
|
21
21
|
</Callout>
|
|
22
22
|
|
|
@@ -140,12 +140,9 @@ Add scripts to regenerate the SWC configuration before builds:
|
|
|
140
140
|
}
|
|
141
141
|
```
|
|
142
142
|
|
|
143
|
-
<
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
Set up IntelliSense for TypeScript (optional)
|
|
147
|
-
</AccordionTrigger>
|
|
148
|
-
<AccordionContent className="[&_p]:my-2">
|
|
143
|
+
<Details>
|
|
144
|
+
<Summary>Set up IntelliSense for TypeScript (optional)</Summary>
|
|
145
|
+
|
|
149
146
|
To enable helpful hints in your IDE, set up the workflow plugin in `tsconfig.json`:
|
|
150
147
|
|
|
151
148
|
```json title="tsconfig.json" lineNumbers
|
|
@@ -161,10 +158,7 @@ To enable helpful hints in your IDE, set up the workflow plugin in `tsconfig.jso
|
|
|
161
158
|
}
|
|
162
159
|
```
|
|
163
160
|
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
</AccordionItem>
|
|
167
|
-
</Accordion>
|
|
161
|
+
</Details>
|
|
168
162
|
|
|
169
163
|
</Step>
|
|
170
164
|
|
|
@@ -384,10 +378,7 @@ import { AppModule } from '../dist/app.module.js';
|
|
|
384
378
|
let ready: Promise<express.Express> | undefined;
|
|
385
379
|
|
|
386
380
|
async function createHandler() {
|
|
387
|
-
const app = await NestFactory.create<NestExpressApplication>(AppModule
|
|
388
|
-
bodyParser: false,
|
|
389
|
-
});
|
|
390
|
-
app.use(express.json());
|
|
381
|
+
const app = await NestFactory.create<NestExpressApplication>(AppModule);
|
|
391
382
|
await app.init();
|
|
392
383
|
return app.getHttpAdapter().getInstance();
|
|
393
384
|
}
|
|
@@ -416,6 +407,16 @@ Deploy as usual. `workflow-nest build --vercel` runs automatically on Vercel (it
|
|
|
416
407
|
`VERCEL` environment variable), writing `.vercel/output` with the consumer function so your runs
|
|
417
408
|
execute instead of staying `pending`.
|
|
418
409
|
|
|
410
|
+
<Callout type="info">
|
|
411
|
+
The app is bundled with esbuild. A package that resolves a dependency at runtime
|
|
412
|
+
behind a `try`/`catch` — a database driver reached through an ORM, an optional
|
|
413
|
+
logger transport — looks like a hard dependency to the bundler, which fails the
|
|
414
|
+
build on the first one your app has not installed. NestJS's own optional peers
|
|
415
|
+
are handled for you; pass anything else to `--external`, for example
|
|
416
|
+
`--external oracledb,mysql2`. Native addons (`*.node`) are not traced into the
|
|
417
|
+
deployed function and are reported as a build warning.
|
|
418
|
+
</Callout>
|
|
419
|
+
|
|
419
420
|
</Step>
|
|
420
421
|
|
|
421
422
|
</Steps>
|
|
@@ -473,6 +474,12 @@ WorkflowModule.forRoot({
|
|
|
473
474
|
// (default: true, or false when VERCEL is set because dedicated functions
|
|
474
475
|
// serve the bundles there).
|
|
475
476
|
preloadBundles: true,
|
|
477
|
+
|
|
478
|
+
// Keep the application's body parser away from the workflow routes, so queue
|
|
479
|
+
// deliveries are not capped at Express's 100 KB limit and signed webhook
|
|
480
|
+
// bodies stay byte-exact (default: true). See "Request bodies and body
|
|
481
|
+
// parsers" below.
|
|
482
|
+
bypassBodyParser: true,
|
|
476
483
|
});
|
|
477
484
|
```
|
|
478
485
|
|
|
@@ -521,41 +528,148 @@ function generates matching URLs:
|
|
|
521
528
|
workflow-nest build --vercel --base-path /api
|
|
522
529
|
```
|
|
523
530
|
|
|
531
|
+
<Callout type="info">
|
|
532
|
+
`setGlobalPrefix(prefix, { exclude })` that excludes the workflow routes is
|
|
533
|
+
honoured too: they stay at the origin root, and the SDK generates unprefixed
|
|
534
|
+
URLs to match. `app.enableVersioning()` does not move them at all; see
|
|
535
|
+
[Route versioning](#route-versioning).
|
|
536
|
+
</Callout>
|
|
537
|
+
|
|
538
|
+
---
|
|
539
|
+
|
|
540
|
+
## Request bodies and body parsers
|
|
541
|
+
|
|
542
|
+
The workflow routes are a byte pipe, in both directions and at whatever size the
|
|
543
|
+
data happens to be:
|
|
544
|
+
|
|
545
|
+
- The queue delivers run inputs, step inputs and step outputs in the body of a
|
|
546
|
+
`POST /.well-known/workflow/v1/flow`. Express caps request bodies at 100 KB
|
|
547
|
+
and NestJS installs that parser by default, so a workflow that passes an array
|
|
548
|
+
of any size around would get `413 request entity too large` on every delivery,
|
|
549
|
+
with nothing but a retry loop to show for it.
|
|
550
|
+
- A webhook that verifies a signature over its raw body (Stripe, GitHub,
|
|
551
|
+
Shopify, Slack) only verifies if the bytes the sender signed arrive unchanged,
|
|
552
|
+
and a parser that has already turned the request into an object has destroyed
|
|
553
|
+
them.
|
|
554
|
+
|
|
555
|
+
`WorkflowModule` handles both by keeping the application's body parsers away
|
|
556
|
+
from `.well-known/workflow/v1`, and nothing else. On **Express**, workflow
|
|
557
|
+
requests are read straight from the request stream, so they are neither
|
|
558
|
+
size-limited nor re-serialized, and your own routes keep the parsers and limits
|
|
559
|
+
you configured. No bootstrap configuration is needed, and `{ rawBody: true }` is
|
|
560
|
+
not required for signed webhooks.
|
|
561
|
+
|
|
562
|
+
Set `bypassBodyParser: false` to opt out and handle parsing yourself.
|
|
563
|
+
|
|
524
564
|
<Callout type="warn">
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
565
|
+
This stream bypass only applies to **uncompressed Express** requests. Two cases
|
|
566
|
+
fall back to re-serializing the parsed body with `JSON.stringify`, which does
|
|
567
|
+
**not** preserve whitespace or key order and therefore breaks webhook signature
|
|
568
|
+
verification (Stripe, GitHub, Shopify, Slack):
|
|
569
|
+
|
|
570
|
+
- **Fastify.** Fastify's content-type parser always consumes the request
|
|
571
|
+
stream before the route runs — `WorkflowModule` cannot stand it aside the way
|
|
572
|
+
it does Express's middleware — so the raw bytes are gone by the time the
|
|
573
|
+
handler sees them. Fastify's body limit is also enforced per instance rather
|
|
574
|
+
than per route; raise it on the adapter (for example
|
|
575
|
+
`new FastifyAdapter({ bodyLimit: 16 * 1024 * 1024 })`).
|
|
576
|
+
- **Compressed bodies.** A body that arrives with a `content-encoding` always
|
|
577
|
+
goes through the parser on Express too, because that is what inflates it.
|
|
578
|
+
|
|
579
|
+
For signed webhooks in either case, create the app with `{ rawBody: true }`
|
|
580
|
+
(`NestFactory.create(AppModule, new FastifyAdapter(), { rawBody: true })` on
|
|
581
|
+
Fastify) so the integration can recover the exact bytes the sender signed.
|
|
582
|
+
NestJS keeps them on `req.rawBody` on both platforms, so no extra plugin is
|
|
583
|
+
needed. Without it, the integration logs a one-time warning and falls back to
|
|
584
|
+
the lossy `JSON.stringify` path.
|
|
528
585
|
</Callout>
|
|
529
586
|
|
|
587
|
+
<Callout type="info">
|
|
588
|
+
On Vercel the flow and webhook routes are served by their own Build Output
|
|
589
|
+
functions rather than by your NestJS app, so this only affects self-hosted
|
|
590
|
+
deployments.
|
|
591
|
+
</Callout>
|
|
592
|
+
|
|
593
|
+
---
|
|
594
|
+
|
|
595
|
+
## Guards, interceptors, and pipes
|
|
596
|
+
|
|
597
|
+
The workflow routes are served by a controller inside your application, so a
|
|
598
|
+
global guard runs for them too. A guard that rejects unauthenticated requests
|
|
599
|
+
rejects every queue delivery and webhook with `403`, and runs stop making
|
|
600
|
+
progress.
|
|
601
|
+
|
|
602
|
+
Exempt them with `isWorkflowRequest`:
|
|
603
|
+
|
|
604
|
+
{/*@skip-typecheck - Illustrates the pattern, not a complete app*/}
|
|
605
|
+
|
|
606
|
+
```typescript
|
|
607
|
+
import { Injectable, type CanActivate, type ExecutionContext } from '@nestjs/common';
|
|
608
|
+
import { isWorkflowRequest } from 'workflow/nest';
|
|
609
|
+
|
|
610
|
+
@Injectable()
|
|
611
|
+
export class AuthGuard implements CanActivate {
|
|
612
|
+
canActivate(context: ExecutionContext) {
|
|
613
|
+
if (isWorkflowRequest(context)) return true;
|
|
614
|
+
// ...your own checks
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
```
|
|
618
|
+
|
|
619
|
+
The workflow routes authenticate their own callers — queue deliveries are signed
|
|
620
|
+
and webhook tokens are single-use secrets — so letting them past an application
|
|
621
|
+
guard exposes nothing.
|
|
622
|
+
|
|
623
|
+
Interceptors and exception filters are safe to leave in place. The handlers
|
|
624
|
+
write through `@Res()`, so the exact status and body the workflow runtime
|
|
625
|
+
produced reach the caller, which is what the queue and third-party webhook
|
|
626
|
+
senders key off.
|
|
627
|
+
|
|
628
|
+
---
|
|
629
|
+
|
|
630
|
+
## Route versioning
|
|
631
|
+
|
|
632
|
+
`app.enableVersioning()` moves every route under a version segment. The workflow
|
|
633
|
+
controller is registered as `VERSION_NEUTRAL`, so it stays at
|
|
634
|
+
`.well-known/workflow/v1` whichever strategy you enable, and the URLs the SDK
|
|
635
|
+
generates keep resolving. A global prefix still applies on top, and is adopted
|
|
636
|
+
automatically.
|
|
637
|
+
|
|
530
638
|
---
|
|
531
639
|
|
|
532
|
-
##
|
|
640
|
+
## Fastify
|
|
533
641
|
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
signed reach the workflow unchanged, and a body parser that has already turned
|
|
537
|
-
the request into an object destroys them.
|
|
642
|
+
`@nestjs/platform-fastify` is supported alongside `@nestjs/platform-express`,
|
|
643
|
+
with two differences.
|
|
538
644
|
|
|
539
|
-
|
|
645
|
+
Fastify enforces its body limit before any content-type parser runs, and the
|
|
646
|
+
limit is per instance rather than per route, so it cannot be scoped to the
|
|
647
|
+
workflow routes. Raise it on the adapter; `WorkflowModule` warns at startup
|
|
648
|
+
while it is still at Fastify's 1 MiB default:
|
|
540
649
|
|
|
541
650
|
{/*@skip-typecheck - Bootstrap snippet*/}
|
|
542
651
|
|
|
543
652
|
```typescript
|
|
544
|
-
const app = await NestFactory.create(
|
|
653
|
+
const app = await NestFactory.create(
|
|
654
|
+
AppModule,
|
|
655
|
+
new FastifyAdapter({ bodyLimit: 16 * 1024 * 1024 })
|
|
656
|
+
);
|
|
545
657
|
```
|
|
546
658
|
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
659
|
+
Fastify also answers content types it has no parser for with `415` before the
|
|
660
|
+
request reaches a controller. Register a catch-all parser if your webhooks send
|
|
661
|
+
`application/octet-stream` or another unparsed media type:
|
|
550
662
|
|
|
551
|
-
|
|
552
|
-
without the parser registered, custom media types) are read straight from the
|
|
553
|
-
request stream and need no configuration.
|
|
663
|
+
{/*@skip-typecheck - Bootstrap snippet*/}
|
|
554
664
|
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
665
|
+
```typescript
|
|
666
|
+
app
|
|
667
|
+
.getHttpAdapter()
|
|
668
|
+
.getInstance()
|
|
669
|
+
.addContentTypeParser('*', { parseAs: 'buffer' }, (_request, body, done) =>
|
|
670
|
+
done(null, body)
|
|
671
|
+
);
|
|
672
|
+
```
|
|
559
673
|
|
|
560
674
|
---
|
|
561
675
|
|
|
@@ -631,11 +745,18 @@ plain functions so the intent is clear.
|
|
|
631
745
|
leave `skipBuild` unset so the bundles are built during startup. With
|
|
632
746
|
`skipBuild` set and no bundles present, startup fails with an explicit error
|
|
633
747
|
rather than serving broken workflow routes.
|
|
634
|
-
-
|
|
748
|
+
- Exempt the workflow routes from any global guard with `isWorkflowRequest`, or
|
|
749
|
+
every queue delivery is rejected with `403`.
|
|
635
750
|
- Set `basePath` (or rely on the adopted global prefix) so generated URLs match
|
|
636
751
|
the routes NestJS serves.
|
|
637
752
|
- Set `manageWorldLifecycle: true` for a self-hosted World, and call
|
|
638
753
|
`app.enableShutdownHooks()` so the World is closed on a signal.
|
|
754
|
+
- On Fastify, raise the adapter's `bodyLimit` above the data your workflows pass
|
|
755
|
+
between steps.
|
|
756
|
+
- Install exactly one copy of `@nestjs/core`. With two, NestJS hands
|
|
757
|
+
`@workflow/nest` neither the global prefix nor the HTTP adapter, which
|
|
758
|
+
silently disables prefix handling and the body-parser bypass; a warning is
|
|
759
|
+
logged at startup when this happens.
|
|
639
760
|
- `skipBuild` defaults to `true` when the `VERCEL` environment variable is set,
|
|
640
761
|
so no Vercel-specific branch is needed in your module configuration.
|
|
641
762
|
|