pure-effect 0.17.0 → 0.19.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  # Pure Effect
2
2
 
3
- [![npm version](https://img.shields.io/npm/v/pure-effect)](https://www.npmjs.com/package/pure-effect) [![minified size (gzip)](https://img.shields.io/bundlejs/size/pure-effect)](https://bundlejs.com/?q=pure-effect) [![license](https://img.shields.io/npm/l/pure-effect)](https://github.com/aycangulez/pure-effect/blob/main/LICENSE)
3
+ [![npm version](https://img.shields.io/npm/v/pure-effect)](https://www.npmjs.com/package/pure-effect) [![CI](https://github.com/aycangulez/pure-effect/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/aycangulez/pure-effect/actions/workflows/ci.yml) [![node](https://img.shields.io/node/v/pure-effect)](https://www.npmjs.com/package/pure-effect) [![license](https://img.shields.io/npm/l/pure-effect)](https://github.com/aycangulez/pure-effect/blob/main/LICENSE)
4
4
 
5
5
  **Pure Effect** records what your business logic did in production and replays it anywhere: time-travel debugging for JavaScript and TypeScript, with zero dependencies. Business logic is plain data you can test without mocks.
6
6
 
@@ -9,17 +9,17 @@
9
9
  - Inject context without touching function signatures
10
10
  - Built-in retry, plus parallel execution that cancels sibling branches on the first failure
11
11
  - OpenTelemetry-ready via lifecycle hooks
12
- - Zero dependencies, under 8 KB minified and gzipped
12
+ - Zero dependencies, about 11 KB minified and gzipped
13
13
  - Works in JavaScript, and in TypeScript 5.1 or later (full generics, bundled `.d.ts`)
14
14
 
15
15
  ## Table of Contents
16
16
 
17
- - **Getting started:** [Installation](#installation) · [Quick Start](#quick-start) · [How It Works](#how-it-works) · [Testing Without Mocks](#testing-without-mocks) · [Coming from async/await](#coming-from-asyncawait)
18
- - **Recording and replay:** [Time-Travel Debugging](#time-travel-debugging) · [Recording in Production](#recording-in-production)
19
- - **Building flows:** [Passing Runtime Context](#passing-runtime-context) · [Retrying Transient Failures](#retrying-transient-failures) · [Running Effects in Parallel](#running-effects-in-parallel) · [Composing Larger Flows](#composing-larger-flows) · [Which Errors Are Data](#which-errors-are-data) · [TypeScript](#typescript-typed-errors-and-context)
17
+ - **Getting started:** [Installation](#installation) · [Quick Start](#quick-start) · [How It Works](#how-it-works) · [Testing Without Mocks](#testing-without-mocks) · [Coming from async/await](#coming-from-asyncawait) · [Writing Flows as Generators](#writing-flows-as-generators)
18
+ - **Recording and replay:** [Time-Travel Debugging](#time-travel-debugging) · [Recording in Production](#recording-in-production) · [Hooks](#hooks)
19
+ - **Building flows:** [Passing Runtime Context](#passing-runtime-context) · [Retrying Transient Failures](#retrying-transient-failures) · [Running Effects in Parallel](#running-effects-in-parallel) · [Composing Larger Flows](#composing-larger-flows) · [Writing Loops](#writing-loops) · [Which Errors Are Data](#which-errors-are-data) · [Generator Flows in Depth](#generator-flows-in-depth) · [TypeScript](#typescript-typed-errors-and-context)
20
20
  - **Reference:** [Why Pure Effect](#why-pure-effect) · [Load Tests](#load-tests) · [API Reference](#api-reference) · [Limitations](#limitations)
21
21
 
22
- The five sections under Getting started are enough to write and test a flow. Come back to the rest when a flow needs it: recording, retries, steps that run at the same time, or TypeScript.
22
+ The six sections under Getting started are enough to write and test a flow. Come back to the rest when a flow needs it: recording, retries, loops, steps that run at the same time, or TypeScript.
23
23
 
24
24
  ## Installation
25
25
 
@@ -70,9 +70,21 @@ async function registerUser(input) {
70
70
  }
71
71
  ```
72
72
 
73
+ The same flow can be written as a generator, with `yield* step(...)` where `async` code writes `await`. [Writing Flows as Generators](#writing-flows-as-generators) covers what to know.
74
+
75
+ ```js
76
+ import { effectGen, step } from 'pure-effect';
77
+
78
+ const registerUserFlowGen = effectGen(function* (input) {
79
+ yield* step(validateRegistration(input));
80
+ yield* step(ensureEmailAvailable(input));
81
+ return yield* step(saveUser(input));
82
+ });
83
+ ```
84
+
73
85
  ## How It Works
74
86
 
75
- A flow is a chain of pairs: an I/O call, and a `next` function that receives its answer and returns the next Command, a Success, or a Failure. `runEffect` walks the chain in a loop.
87
+ A flow is a chain of pairs: an I/O call, and a `next` function that receives its answer and returns the next Command, a Success, or a Failure. `runEffect` walks the chain in a loop. A generator flow builds the same Commands: `effectGen` runs your function up to each `yield*` and continues it with the answer.
76
88
 
77
89
  Recording and replay hook into the one place where a Command's function is called. Recording writes down each answer. Replay supplies the recorded answer instead of making the call, so a replayed flow does no I/O.
78
90
 
@@ -80,13 +92,11 @@ Building a flow runs the pure steps right away: `registerUserFlow(badInput)` ret
80
92
 
81
93
  ## Testing Without Mocks
82
94
 
83
- Pipelines return plain objects, so you can check what the code will do without running it.
84
-
85
- Validation runs as soon as you build the flow, so testing it needs nothing else:
95
+ A flow is plain objects, so a test can check what it will do without running it. Validation runs as soon as the flow is built, so testing it needs nothing else:
86
96
 
87
97
  ```js
88
98
  const badInput = { email: 'bad-email', password: '123' };
89
- assert.deepEqual(registerUserFlow(badInput), Failure('Invalid email.', badInput));
99
+ assert.deepEqual(registerUserFlow(badInput), Failure('Invalid email.'));
90
100
  ```
91
101
 
92
102
  Next, test the steps. Hand a step an answer and check what it returns:
@@ -114,64 +124,63 @@ assert.equal(commandName(step2), 'cmdSaveUser');
114
124
  // The database was never touched.
115
125
  ```
116
126
 
117
- Write both kinds, because they catch different bugs. Only step tests see the value passed from one step to the next.
127
+ Write both kinds: only a step test sees the value passed from one step to the next. If the email guard returned `Success(true)` instead of `Success(input)`, the step test would fail, but the flow test would still pass, since the calls and their order are unchanged, while the flow saved `true` instead of the user.
118
128
 
119
- For example, if the email guard returned `Success(true)` instead of `Success(input)`, the step test would fail: it expects the input back and gets `true`. The flow test would still pass, because `cmdFindUser` is still the first call and `cmdSaveUser` the second, while the flow saves `true` to the database instead of the user.
129
+ A walk meets a `Retry` or a `Parallel` as a step of its own. A `Retry` holds the step it repeats as `effect`, a `Parallel` holds its branches as `effects`, and the `next` of either is the rest of the flow. The walks in [Writing Loops](#writing-loops) and [Undoing what succeeded when a branch fails](#undoing-what-succeeded-when-a-branch-fails) go through each.
120
130
 
121
- A step tested on its own returns a `Failure` without `initialInput`. That is why the assertion above is `Failure('Email already in use.')`, while the validation one is `Failure('Invalid email.', badInput)`: `effectPipe` adds the input when it builds a flow.
122
-
123
- A walk stops at each Command to be handed its answer. To run the whole flow instead, `Retry` and `Parallel` included, hand `replayEffect` a function that answers each Command by name. Nothing is called and a retry does not wait, and answering `{ error }` makes that Command throw, which is how a test reaches a `Retry`'s fallback:
131
+ To run the whole flow instead of walking it, `Retry` and `Parallel` included, hand `replayEffect` a function that answers each Command by name. Nothing is called and no retry waits; answering `{ error }` makes that Command throw, which is how a test reaches a `Retry`'s fallback:
124
132
 
125
133
  ```js
134
+ import { replayEffect } from 'pure-effect';
135
+
126
136
  const answers = { cmdFindUser: null, cmdSaveUser: { id: 1, ...input } };
127
137
  const answer = (step) => (step.name in answers ? { result: answers[step.name] } : undefined);
128
138
  const { result } = await replayEffect(registerUserFlow(input), answer);
129
139
  assert.deepEqual(result, Success({ id: 1, ...input }));
130
140
  ```
131
141
 
132
- Tests cannot see inside a Command's function without running it. If `cmdFindUser` said `db.findUser(input.name)` instead of `input.email`, every test on this page would still pass. Keep those functions to a single call, and let an integration test cover them.
142
+ Hand it a recorded run instead, and each Command gets what it returned the first time. That is how a run recorded in production replays on your machine, with nothing connected:
133
143
 
134
- **In TypeScript**, a flow is typed as any kind of step it could start with, since validation may already have returned a `Success` or a `Failure`, so `.cmd` and `.next` compile only after the test checks that the step is a Command. `node:assert`'s `assert(step.type === 'Command')` is such a check, and TypeScript follows it. Jest's and Vitest's `expect` is not, so a walk needs a check at every step, and a small helper makes that one line per step with any test framework:
135
-
136
- ```ts
137
- import assert from 'node:assert/strict';
138
- import { commandName } from 'pure-effect';
139
- import type { Effect } from 'pure-effect';
144
+ ```js
145
+ import { recordEffect } from 'pure-effect';
140
146
 
141
- // Fails unless the step is the Command named, and returns it typed as one.
142
- function assertCommand<T, E, C>(step: Effect<T, E, C>, name: string) {
143
- assert(step.type === 'Command', `expected ${name}, got ${step.type}`);
144
- assert.equal(commandName(step), name);
145
- return step;
146
- }
147
+ // A real run returns its result, and a trace of what each Command returned.
148
+ const { result: live, trace } = await recordEffect(registerUserFlow, input);
147
149
 
148
- const step1 = assertCommand(registerUserFlow(input), 'cmdFindUser');
149
- assertCommand(step1.next(null), 'cmdSaveUser');
150
+ // Anywhere else, with nothing connected, the same flow gets the same answers.
151
+ const { result: replayed } = await replayEffect(registerUserFlow(trace.initialInput), trace);
152
+ assert.deepEqual(replayed, live);
150
153
  ```
151
154
 
152
- For a step that returns its Command directly, as in `ensureEmailAvailable(input).next(found)`, `next` is checked against what the Command's function returns, so where the tests above pass `{ id: 1 }` for a user that was found, a TypeScript test passes a whole user, of the type `db.findUser` returns. A Command reached any other way, by walking the whole flow or through an `Ask`'s `next`, accepts any value, since its type does not say which Command it is.
155
+ [Time-Travel Debugging](#time-travel-debugging) turns such a trace into a regression test, and [Recording in Production](#recording-in-production) records every run of an application.
156
+
157
+ Tests cannot see inside a Command's function without running it. If `cmdFindUser` said `db.findUser(input.name)` instead of `input.email`, every test on this page would still pass. Keep those functions to a single call, and let an integration test cover them, with the services passed in as [Passing Runtime Context](#passing-runtime-context) shows.
158
+
159
+ In TypeScript, a walk needs a check at each step that the step is a Command; [Testing a flow in TypeScript](#testing-a-flow-in-typescript) has a helper that makes that one line.
153
160
 
154
161
  ## Coming from async/await
155
162
 
156
- A flow does what `async`/`await` code does, as data. Instead of making a call and waiting for it, a step returns a Command that says which call to make and what to do with the answer. That is what lets a test hand a step an answer instead of mocking the database, and a replay hand it the recorded one. Each thing you would write with `async`/`await` has an equivalent:
163
+ A flow does what `async`/`await` code does, as data: instead of making a call and waiting for it, a step returns a Command that says which call to make and what to do with the answer. Each thing you would write with `async`/`await` has an equivalent:
157
164
 
158
- | With `async`/`await` | In a flow |
159
- | --- | --- |
160
- | `const user = await db.findUser(email)` | a Command: `Command(() => db.findUser(email), next)` |
161
- | the code after the `await`, which uses `user` | the Command's `next`, which receives `user` |
162
- | an `if` on `user` after the `await` | a branch in `next` |
163
- | `return value` | `Success(value)` |
164
- | `throw` to stop | `Failure(error)` |
165
- | a call inside `try`/`catch` | catch inside the Command's function and return a value for `next` to branch on; see [Which Errors Are Data](#which-errors-are-data) |
166
- | a loop that retries a call | `Retry(Command(...), options)` |
167
- | `await Promise.all([...])` | `Parallel([...])` |
168
- | a `for` loop with an `await` inside | a step that gets the list, then `Parallel(list.map(...), { limit: 1 })` |
169
- | a `try`/`catch` inside a loop, to keep going past a failure | the same `Parallel`, with `settled: true` |
170
- | a later call that needs two earlier results | a named step that passes both on; see [Composing Larger Flows](#composing-larger-flows) |
171
- | a value from the request, such as the tenant | `Ask`; see [Passing Runtime Context](#passing-runtime-context) |
172
- | `Date.now()` or a random ID | a Command, so a replay gets the recorded value |
173
-
174
- One rule is behind every row. In `async` code, an `if` or a loop can have an `await` inside it. In a flow it can't: an `if` goes in a step or a Command's `next`, where the answer has already arrived, and a loop that makes calls becomes a `Parallel` or a `Retry`. So each decision lives in a small function of its own, which a test can call directly.
165
+ | `async`/`await` | Generator flow | Pipeline |
166
+ | --- | --- | --- |
167
+ | `await db.findUser(email)` | `yield* step(findUser(email))` | `Command(() => db.findUser(email), next)` |
168
+ | the code after the `await` | the next `yield*` | the Command's `next` |
169
+ | an `if` on a result | a step that returns `Success` or `Failure` | a branch in `next` |
170
+ | `return value` | `return value` | `Success(value)` |
171
+ | `throw` to stop | a step that returns `Failure(error)` | `Failure(error)` |
172
+ | `try`/`catch` around a call | a catch inside the Command's function | the same |
173
+ | a loop that retries a call | `yield* step(Retry(...))` | `Retry(...)` |
174
+ | `await Promise.all([...])` | `yield* step(Parallel([...]))` | `Parallel([...])` |
175
+ | a `for` loop with an `await` inside | the same loop, with `yield*` | `Parallel(list.map(...), { limit: 1 })` |
176
+ | a loop that keeps going past a failure | `Parallel(..., { settled: true })` | the same |
177
+ | a call that needs two earlier results | two variables | a named step that passes both on |
178
+ | a value from the request | `yield* step(Ask())` | `Ask` |
179
+ | `Date.now()` or a random ID | a Command | a Command |
180
+
181
+ `findUser` stands for a step that returns the Command, as `ensureEmailAvailable` does in the Quick Start. A `catch` around `yield*` can log and rethrow, but it cannot recover; see [Which Errors Are Data](#which-errors-are-data).
182
+
183
+ One rule is behind both columns: each decision lives in a small step function that receives the answer it depends on and returns `Success` or `Failure`, so a test can call it directly. A pipeline joins those steps with `effectPipe`; a generator flow puts them in order with `yield*`. An `if` around a `yield*` works, but it can be tested only by walking the whole flow, so keep the body to putting steps in order. A `for` loop that runs a step for each item decides nothing, so it is fine.
175
184
 
176
185
  The Quick Start's `registerUserFlow` is this function, translated row by row: each `await` became a Command, the code after it became that Command's `next`, and each `throw` became a `Failure`.
177
186
 
@@ -184,7 +193,7 @@ async function registerUserAsync(input) {
184
193
  }
185
194
  ```
186
195
 
187
- The difference shows most in the tests. To reach the branch where the email is taken, a test of `registerUserAsync` has to replace the database's methods, run the function, and put the methods back. Here it is with Node's built-in mocks; Jest's `spyOn` works the same way:
196
+ The difference shows in the tests. To reach the branch where the email is taken, a test of `registerUserAsync` has to replace the database's methods, run the function, and put them back, here with Node's built-in mocks:
188
197
 
189
198
  ```js
190
199
  import { mock } from 'node:test';
@@ -205,9 +214,9 @@ The flow's test of the same branch hands one step the answer, with nothing to re
205
214
  assert.deepEqual(ensureEmailAvailable(input).next({ id: 1 }), Failure('Email already in use.'));
206
215
  ```
207
216
 
208
- This is what the small functions are for. Each step is a place a test can start, so a branch is tested by calling the step it lives in. An `async` function has one way in, so a test of any branch runs everything before it, with every call on the way replaced. The mocks can check one thing these tests cannot: the arguments each call received, which [Testing Without Mocks](#testing-without-mocks) leaves to an integration test.
217
+ Each step is a place a test can start, so a branch is tested by calling the step it lives in, where a test of an `async` function runs everything before the branch, with every call on the way replaced. The mocks do check one thing these tests cannot: the arguments each call received, which [Testing Without Mocks](#testing-without-mocks) leaves to an integration test.
209
218
 
210
- You can switch one function at a time. The function keeps its name and parameters, and its body runs the flow and turns a `Failure` back into a throw, so the code that calls it does not change. The mocked test above passes against this version too, so it checks the switch before the flow's own tests replace it:
219
+ You can switch one function at a time: keep its name and parameters, run the flow in its body, and turn a `Failure` back into a throw, so the code that calls it does not change. The mocked test above passes against this version too:
211
220
 
212
221
  ```js
213
222
  // Callers still await registerUserAsync and catch what it throws.
@@ -221,84 +230,49 @@ async function registerUserAsync(input) {
221
230
  await assert.rejects(registerUserAsync({ email: 'bad-email', password: '123' }), { message: 'Invalid email.' });
222
231
  ```
223
232
 
224
- A loop is written in two parts: a step that gets the list, and a `Parallel` over it. `Parallel` runs a list of flows, at the same time unless told otherwise, and `limit: 1` makes it run them one after another, like a `for` loop. The `async` version is usually split the same way. Paying a customer's unpaid invoices in order, and stopping at the first that fails:
233
+ A loop becomes a step that gets the list and a `Parallel` over it, as the table shows; [Writing Loops](#writing-loops) translates one.
225
234
 
226
- ```js
227
- async function payUnpaidAsync(customerId) {
228
- const invoices = await billing.findUnpaid(customerId);
229
- for (const invoice of invoices) {
230
- const receipt = await payments.charge(invoice);
231
- await mailer.sendReceipt(receipt);
232
- }
233
- }
235
+ ## Writing Flows as Generators
234
236
 
235
- // First part: get the list.
236
- const findUnpaidInvoices = (customerId) => {
237
- const cmdFindUnpaid = () => billing.findUnpaid(customerId);
238
- return Command(cmdFindUnpaid);
239
- };
237
+ A generator flow is written like `async` code, with `yield* step(...)` where `async` code writes `await`. `effectGen` turns it into the same Commands a pipeline builds, so recording, replay, `Retry`, `Parallel` and the tests above work the same for both. The Quick Start's `registerUserFlowGen` is one. The same steps in the same order record the same paths in either form, so a trace recorded from a pipeline replays against its generator version. A loop written as a `for` loop rather than a `Parallel` records differently; see [Writing Loops](#writing-loops).
240
238
 
241
- // Second part: the loop's body, a flow of its own for one invoice.
242
- const chargeInvoice = (invoice) => {
243
- const cmdChargeInvoice = () => payments.charge(invoice);
244
- return Retry(Command(cmdChargeInvoice), { attempts: 3 });
245
- };
239
+ ### Where a generator helps
246
240
 
247
- const sendReceipt = (receipt) => {
248
- const cmdSendReceipt = () => mailer.sendReceipt(receipt);
249
- return Command(cmdSendReceipt);
250
- };
251
-
252
- const payInvoice = (invoice) => effectPipe(chargeInvoice, sendReceipt)(invoice);
241
+ A generator earns its keep when a later step needs the results of more than one earlier step. Here the welcome email needs both the saved user and the workspace created for them, and each is a variable:
253
242
 
254
- // The loop: one body per invoice, run one at a time.
255
- const payAll = (invoices) => Parallel(invoices.map(payInvoice), { limit: 1 });
243
+ ```js
244
+ const onboardUser = effectGen(function* (input) {
245
+ const user = yield* step(registerUserFlowGen(input));
256
246
 
257
- const payUnpaid = (customerId) => effectPipe(findUnpaidInvoices, payAll)(customerId);
247
+ const cmdCreateWorkspace = () => db.createWorkspace(user.id);
248
+ const workspace = yield* step(Command(cmdCreateWorkspace));
258
249
 
259
- // The flow starts by getting the list, and hands what it gets to the loop.
260
- const flow = payUnpaid('cus_1');
261
- assert.equal(commandName(flow), 'cmdFindUnpaid');
262
- assert.equal(flow.next([{ id: 1 }, { id: 2 }]).effects.length, 2);
250
+ const cmdSendWelcome = () => mailer.sendWelcome(user.email, workspace.name);
251
+ yield* step(Command(cmdSendWelcome));
263
252
 
264
- // The body is tested on its own: the Retry holds only the charge, and the receipt comes after it.
265
- const body = payInvoice({ id: 1 });
266
- assert.equal(commandName(body.effect), 'cmdChargeInvoice');
267
- assert.equal(commandName(body.next({ id: 'receipt_1' })), 'cmdSendReceipt');
253
+ return { user, workspace };
254
+ });
268
255
 
269
- // An empty list runs nothing.
270
- assert.deepEqual(await runEffect(payAll([])), Success([]));
256
+ const onboarded = await runEffect(onboardUser(input));
257
+ assert.equal(onboarded.value.workspace.ownerId, onboarded.value.user.id);
271
258
  ```
272
259
 
273
- Each invoice is paid after the one before it has finished, and the first that fails stops the rest from starting, as in the `async` version. When the payments can overlap, a higher `limit` runs several at a time.
260
+ A pipeline would need a step that passes the user and the workspace on together; see [Composing Larger Flows](#composing-larger-flows). Keep decisions in step functions all the same, as `registerUserFlowGen` does, so each can be tested on its own.
274
261
 
275
- The loop's body is a flow built for one item, so it can hold as many steps as the body of a `for` loop. Put a `Retry` inside it, on the step that needs one. Around the whole loop, a `Retry` would pay every invoice again after one failed, charging the ones already paid; around the whole body, a receipt that failed to send would charge the card again. See [Retrying Transient Failures](#retrying-transient-failures).
262
+ The body can run more than once: under a `Retry`, when one flow value is run twice, and when a test walks a second branch. So keep it to its own variables, and get `Date.now()` or a random ID from a Command. [Generator Flows in Depth](#generator-flows-in-depth) covers when it runs again, how a `catch` or `finally` in it behaves when a step stops the flow, and the mistakes `effectGen` catches.
276
263
 
277
- The `Parallel`'s `next` receives what each body returned, in order, so a total or a summary of the loop goes there: `Parallel(invoices.map(payInvoice), (receipts) => Success(receipts.length), { limit: 1 })`. To keep going past a failure, as a `try`/`catch` inside the loop would, add `settled: true`: every invoice is tried, and `next` receives one `Success` or `Failure` per invoice. See [Running Effects in Parallel](#running-effects-in-parallel).
264
+ ### Testing a generator flow
278
265
 
279
- Sometimes getting the list is a loop of its own. Paging through an API with a cursor is one: each request needs the cursor from the page before, so the requests cannot be listed in advance. Write that loop as an ordinary `async` function, call it from one Command, and map over the list it returns, as above:
266
+ Test each step function by handing it an answer, as [Testing Without Mocks](#testing-without-mocks) does, since the generator only puts the steps in order. Then run the whole flow with each Command answered by name, as for a pipeline:
280
267
 
281
268
  ```js
282
- async function fetchAllOrders() {
283
- const orders = [];
284
- let cursor = null;
285
- do {
286
- const page = await api.listOrders(cursor);
287
- orders.push(...page.items);
288
- cursor = page.nextCursor;
289
- } while (cursor);
290
- return orders;
291
- }
292
-
293
- const listAllOrders = () => {
294
- const cmdListAllOrders = () => fetchAllOrders();
295
- return Command(cmdListAllOrders);
296
- };
269
+ const answers = { cmdFindUser: null, cmdSaveUser: { id: 1, ...input } };
270
+ const answerByName = (asked) => (asked.name in answers ? { result: answers[asked.name] } : undefined);
271
+ const { result } = await replayEffect(registerUserFlowGen(input), answerByName);
272
+ assert.deepEqual(result, Success({ id: 1, ...input }));
297
273
  ```
298
274
 
299
- To the flow, the whole loop is one step. A trace records the finished list as that step's result, and a replay hands the list back without replaying the pages. A `Retry` around the Command starts again from the first page. A flow test cannot see inside it, so, like any Command's function, it is left to an integration test.
300
-
301
- The loop belongs in the flow only when the flow has to decide something on each pass, such as stopping at the first order that matches, or saving each page as it arrives. Then the Command's `next` returns the Command for the next page instead of a `Success`, until there are no more pages.
275
+ Walking the flow step by step works as it does for a pipeline: a walk straight through runs the body once, and walking a second branch runs it again.
302
276
 
303
277
  ## Time-Travel Debugging
304
278
 
@@ -353,7 +327,7 @@ it('prod incident 8f3a: a 100% promo produces a $0 charge', async () => {
353
327
  });
354
328
  ```
355
329
 
356
- The test checks that the flow still takes the recorded path and handles the recorded outcomes the same way. If a refactor reorders or replaces a step, the replay ends in a `Failure` whose error is a `TimeParadox` naming where it diverged. It is not thrown, so a test that expects a `Failure` should check the error too, as this one checks its `code`. If the error handling changes, the assertion fails.
330
+ The test checks that the flow still takes the recorded path and handles the recorded outcomes the same way. It does not check the values the flow computes, since every result comes from the recording; see [What a replay cannot check](#what-a-replay-cannot-check). If a refactor reorders or replaces a step, the replay ends in a `Failure` whose error is a `TimeParadox` naming where it diverged. It is not thrown, so a test that expects a `Failure` should check the error too, as this one checks its `code`. A step the trace lacks ends the replay in a `Failure` holding a `ReplayError`. A trace lacks a step that comes after the end of the recording, one a hook vetoed in production, and one the recorder dropped under `maxEntries`.
357
331
 
358
332
  A flow that stops issuing Commands before the recording ends (for example, a fix that skips the charge) produces no `TimeParadox`, and the replay can end in `Success` with recorded steps left over. `replayEffect` returns those steps as `unreached`, so a test can assert which ones it expects to skip:
359
333
 
@@ -368,34 +342,66 @@ it('incident 8f3a fixed: a 100% promo checks out without a charge', async () =>
368
342
  });
369
343
  ```
370
344
 
371
- For every other recording, `unreached` should be empty, so a fix that skips a step by accident fails the test.
345
+ For every other recording, `unreached` should be empty, so a fix that skips a step by accident fails the test. This works when the removed step is the last one the flow reaches. Remove a step from the middle and every later step moves to a different path, so the replay stops at a `TimeParadox`, and `unreached` lists the steps it never got to.
346
+
347
+ ### Reading a trace
348
+
349
+ A trace is plain JSON. This one is from a checkout whose card charge timed out once and then went through:
350
+
351
+ ```text
352
+ {
353
+ "flowName": "checkout",
354
+ "version": "b42",
355
+ "initialInput": { "cartId": "cart_1" },
356
+ "context": { "flowName": "checkout" },
357
+ "dropped": 0,
358
+ "trace": [
359
+ { "command": "cmdFetchCart", "path": "0", "result": { "total": 120 }, "durationMs": 41.3 },
360
+ { "command": "cmdChargeCard", "path": "1r0/0", "threw": true,
361
+ "error": { "__error": true, "name": "Error", "message": "gateway timeout", "code": "ETIMEDOUT" }, "durationMs": 5002.1 },
362
+ { "command": "cmdChargeCard", "path": "1r1/0", "result": { "chargeId": "ch_1" }, "durationMs": 181.5 }
363
+ ]
364
+ }
365
+ ```
372
366
 
373
- This works when the removed step is the last one the flow reaches. Remove a step from the middle and every later step moves to a different path, so the replay stops at a `TimeParadox`. In that case `unreached` lists the steps the replay never got to, not the steps the fix made unnecessary.
367
+ `trace` holds one entry per step, in the order the steps finished; [`recorder`](#recorderoptions) lists each kind of entry. A replay matches each step by its `path`, its position in the flow, and a `TimeParadox` names the path where the flow and the trace part ways:
374
368
 
375
- **Replay checks the path, not the values.** It shows that the flow asks for the same Commands in the same order and handles the same answers. It cannot check what the flow computes, because every Command's result comes from the recording, not from the new code. If you fix how a refund amount is calculated and replay the bad run, the charge step gets the old amount from the recording: the replay reports `Success`, returns the value from before the fix, and flags nothing. Test a change to a value against the pure step that computes it.
369
+ - A number counts the Commands, `Retry`s and `Parallel`s the flow reached, from `0`. A `Success` or an `Ask` between them adds nothing.
370
+ - `r` and a number is one attempt of the `Retry` at that position, `r0` being the first try, and `rf` is its `onExhausted` fallback.
371
+ - `p` and a number is one branch of the `Parallel` at that position, from `p0`. The `Parallel` has an entry of its own, at a path such as `2p`, which records whether a branch cancelled the others.
372
+ - `/` goes one level in: `1r1/0` is the first step of the second try of the `Retry` at position 1, and `2p1/0` is the first step of the second branch of the `Parallel` at position 2.
376
373
 
377
- **A replay cannot check a fix inside a Command's function either.** The function never runs, so the replay hands the flow what it returned or threw before the fix: catch a duplicate-key error inside the function and return it as data, and the old trace still replays the throw. Cover such a fix with an integration test. And when a Command's result changes shape, rename the Command, since a trace matches it by name: under the old name, an old trace hands the new code a result in the old shape, which it can take for another answer without any `TimeParadox`.
374
+ ### What a replay cannot check
378
375
 
379
- **A trace records what each Command returned, not the arguments it was called with.** Given the recorded input and results, the flow does the same thing again, so replaying up to a step rebuilds the arguments that Command ran with. You can inspect them in a debugger, but you cannot assert on them. Storing arguments would also double what `redact` has to cover, since arguments are usually the sensitive part of a call.
376
+ A replay proves that the flow asks for the same Commands in the same order and handles the same answers. Every result comes from the recording, so it cannot check:
380
377
 
381
- **Put anything that varies between runs inside a Command.** For replay, the current time or a random ID counts as I/O. Wrapped in a Command, it is recorded and replayed like any other result. A step that calls `Date.now()` directly gets a new value on every replay and drifts from the trace.
378
+ - **What the flow computes.** Fix how a refund amount is calculated and replay the bad run, and the charge step still gets the old amount from the recording: the replay reports `Success`, returns the value from before the fix, and flags nothing. Test a value change against the pure step that computes it.
379
+ - **A fix inside a Command's function.** The function never runs, so an old trace hands the flow what it returned or threw before the fix: catch a duplicate-key error inside the function and return it as data, and the old trace still replays the throw. Cover such a fix with an integration test.
380
+ - **The arguments a Command was called with.** A trace records results only. Given the recorded input and results, the flow does the same thing again, so replaying up to a step rebuilds its arguments for a debugger, but a test cannot assert on them. Storing them would also double what `redact` has to cover, since arguments are usually the sensitive part of a call.
382
381
 
383
- **To check for this,** record a flow, send the trace through JSON as your storage would, replay it, and compare the outcomes. A step that computes a new value on each run shows up as a `TimeParadox` if it changes which Commands run, or as a different final value. Going through JSON also catches a result that storage cannot keep, such as a `Date`, a class instance, or `undefined` in an array, which is where a replay from memory and a replay from storage part ways:
382
+ When a Command's result changes shape, rename the Command. A trace matches it by name, so under the old name an old trace hands the new code a result in the old shape, which it can take for another answer without any `TimeParadox`.
383
+
384
+ ### Keeping a replay faithful
385
+
386
+ Put anything that varies between runs inside a Command. For replay, the current time or a random ID counts as I/O: in a Command it is recorded and replayed like any other result, while a step that calls `Date.now()` directly gets a new value on every replay and drifts from the trace. To check a flow, record it, replay the trace, and compare the outcomes: a step that computes a fresh value shows up as a different final value, or as a `TimeParadox` if it changes which Commands run. A trace holds each result in the form JSON stores it, so this also catches a result your storage cannot keep, such as a `Date` the flow calls a method on:
384
387
 
385
388
  ```js
386
389
  const { result, trace } = await recordEffect(registerUserFlow, input);
387
- const stored = JSON.parse(JSON.stringify(trace)); // what your storage gives back
388
- const { result: replayed } = await replayEffect(registerUserFlow(input), stored);
389
- assert.deepEqual(replayed, result); // fails if a step computed a fresh value, or a result did not survive JSON
390
+ const { result: replayed } = await replayEffect(registerUserFlow(input), trace);
391
+ assert.deepEqual(replayed, result); // fails if a step computed a fresh value, or a result did not survive storage
390
392
  ```
391
393
 
392
- This also works for a `Failure`: an error read back from a trace keeps its message, name, cause, custom properties, and an `AggregateError`'s list of errors, and is deep-equal to the one the Command threw, including one whose `name` or `cause` was set after it was created. The exception is a custom error class, which comes back as a plain `Error` with that class's name; compare `error.name` and `error.message` instead.
394
+ A `Failure` compares the same way when the Command threw a plain `Error`, which comes back with its message, name, cause, custom properties and an `AggregateError`'s list of errors, even a `name` or `cause` set after it was created. An error of any other class, built-in ones included, comes back as a plain `Error` carrying that class's name, so `deepEqual` from `node:assert/strict` refuses the replayed `TypeError` that `fetch` rejects with when the network fails. Where a Command can throw one, compare `error.name` and `error.message` instead.
393
395
 
394
- **You choose the trace format.** `replayEffect` also accepts a resolver function instead of a trace, so you can replay from OpenTelemetry spans, a log pipeline, or a database table, not only from the JSON that `recorder` produces.
396
+ ### Replaying from your own storage
397
+
398
+ `replayEffect` also accepts a resolver function instead of a trace, so you can replay from OpenTelemetry spans, a log pipeline, or a database table, not only from the JSON that `recorder` produces. Whatever you store needs each step's `path`, which `onStep` receives, and its result; the telemetry example records neither, since it keeps values off spans.
395
399
 
396
400
  ```js
397
- // A resolver answers one question: what did production get back for this step?
398
- const resolve = (step) => ({ result: mySpans[step.index].attributes.output });
401
+ // A resolver answers one question: what did production get back for this step? Look the step up by its path, its
402
+ // position in the flow. `step.index` counts steps in the order they finished, which shifts around a Parallel.
403
+ const outputs = new Map(mySpans.map((span) => [span.attributes.path, span.attributes.output]));
404
+ const resolve = (step) => (outputs.has(step.path) ? { result: outputs.get(step.path) } : undefined);
399
405
  await replayEffect(checkoutFlow(input), resolve);
400
406
  ```
401
407
 
@@ -422,14 +428,126 @@ configureEffect(
422
428
  );
423
429
  ```
424
430
 
425
- By default, successful runs are held in memory and then discarded. A run that rejects because your own code threw, such as a `TypeError` after an API changed the shape of its response, is offered to `keep` as a `Failure` carrying the thrown error, so by default its trace is kept, and the run still rejects. Replaying that trace reproduces the throw. If `keep` or the sink throws, for example because `JSON.stringify` meets a value it cannot serialize, the run keeps its own outcome and the error goes to `onSinkError`, which defaults to `console.error`. `redact` runs before anything enters the trace, including the stored `initialInput` and `context`. `maxEntries` caps the length of a trace and reports the overflow as `dropped`; a capped trace replays only up to the first step it lacks, so the example warns through `onWarning` the first time it keeps one for a flow. It warns the same way about a flow whose steps include any named `'anonymous'`. The sink can write a trace to S3 or a database column as JSON, as long as your Commands return plain data.
431
+ What the example does with each run:
432
+
433
+ - **Which runs it keeps.** `keep` decides, and by default keeps a run that ended in a `Failure`; successful runs are held in memory and then discarded. When your own code throws, such as a `TypeError` after an API changed the shape of its response, the run rejects. `keep` is offered a `Failure` carrying the thrown error, so by default its trace is kept. Replaying that trace reproduces the throw. A step before the flow's first Command runs when the flow is built, outside `runEffect`, so its throw reaches no hook and is not recorded; that run did no I/O, so its input reproduces it.
434
+ - **What a trace holds.** `redact` runs before anything enters the trace, including the stored `initialInput` and `context`. A value it throws on, or one JSON cannot hold, such as a `BigInt`, is left out of the trace, which marks where with `unrecorded`, and a replay stops there. Everything else is already in the form JSON holds, so the sink can write it to S3 or a database column with `JSON.stringify`.
435
+ - **How long a trace gets.** `maxEntries` caps it and reports the overflow as `dropped`, and a capped trace replays only up to the first step it lacks.
436
+ - **When storage fails.** If `keep` or the sink throws, for example because storage is unreachable, the run keeps its own outcome and the error goes to `onSinkError`, which defaults to `console.error`.
437
+ - **What it warns about.** The example warns through `onWarning`, once per flow, when it keeps a trace that was capped, one holding values it could not record, or one whose steps include any named `'anonymous'`.
426
438
 
427
- The example reads the input from the flow itself, where `effectPipe` stores it, so build the outermost flow with `effectPipe`. A flow that starts with a bare `Command`, `Ask`, `Retry`, or `Parallel` records no input, and `timeTravel` would rebuild it from `undefined`. A one-step pipeline is enough, as in `runEffect(effectPipe(loadProfile)(userId))`. The example warns through `onWarning`, which defaults to `console.warn`, the first time it keeps a trace of such a flow, and `timeTravel` warns when it replays one. The example also takes the context from the run's first Command, so a run that stops before any Command, for example at an `Ask` check, records no context. Such a run did no I/O, so running the flow again with its input and the context from your logs reproduces it.
439
+ The example takes the input from `onRun`, which is handed it only for a flow `effectPipe` built, so build the outermost flow with `effectPipe`. A flow that starts with a bare `Command`, `Ask`, `Retry`, or `Parallel` records no input, and `timeTravel` would rebuild it from `undefined`. A one-step pipeline is enough, as in `runEffect(effectPipe(loadProfile)(userId))`. The example warns through `onWarning`, which defaults to `console.warn`, the first time it keeps a trace of such a flow, and `timeTravel` warns when it replays one.
428
440
 
429
- **A trace keeps data, not objects.** A result is copied when it is recorded, and copied again each time a replay hands it to the flow, so neither a later step nor a replay can change what the trace says. The copy keeps values but not classes: a money object or a database entity comes back as a plain object without its methods, and a `Buffer` as a plain byte array. An error returned inside a result keeps its message but loses properties such as `code`. Writing the trace as JSON loses more: a `Date` becomes a string, a `Map` becomes `{}`, an error inside a result becomes `{}`, `undefined` in an array becomes `null`, and a `BigInt` makes the sink throw.
441
+ The example also takes the context from the run's first Command, so a run that stops before any Command, for example at an `Ask` check, records no context. Such a run did no I/O, so running the flow again with its input and the context from your logs reproduces it.
442
+
443
+ **A trace keeps data, not objects.** A value is copied into the form JSON stores when it is recorded, and copied again each time a replay hands it to the flow, so neither a later step nor a replay can change what the trace says, and a replay from memory gets what a replay from storage gets. The copy keeps values but not classes: a money object or a database entity comes back as a plain object without its methods, a `Date` as a string, a `Map` or a `Set` as `{}`, a `Buffer` as `{ type: 'Buffer', data }`, `undefined` in an array as `null`, and an error returned inside a result with its own fields, such as `code`, but without its message. A reference back to an object the value is inside of, as between an HTTP client's request and response, is cut. A value JSON cannot hold at all, such as a `BigInt` or an object whose getter throws, is left out of the trace and marked `unrecorded` before `redact` sees it, so a context holding a lazy client is left out whole.
430
444
 
431
445
  So return plain data from a Command's function. Turn a class instance into a plain object before returning it, with a small named function you can test on its own, as in `() => db.findCart(id).then(cartToData)`, and rebuild the object in `next` if the flow needs its methods. When you catch an error to return it as data, copy the fields the flow branches on, as in `.catch((error) => ({ ok: false, code: error.code }))`, rather than returning the error itself.
432
446
 
447
+ ### Keeping secrets out of a trace
448
+
449
+ `redact` sees everything a trace stores: each result, each thrown error, the flow's input and the context, told apart by `kind`. It gets a copy in the form the trace stores, so changing it in place is safe, and what it returns is stored in that form too. A thrown `Error` arrives as a plain object holding its `name`, `message` and own fields, and any object returned for it replays as an `Error`.
450
+
451
+ Check a value before replacing a field in it, since `{ ...value, email: '[redacted]' }` turns a `null` into an object and the replay takes the other branch:
452
+
453
+ ```js
454
+ // Masks a field only where there is one, so a lookup that found nothing still records null.
455
+ const mask = (value, field) =>
456
+ value && typeof value === 'object' && field in value ? { ...value, [field]: '[redacted]' } : value;
457
+
458
+ const redact = (value, name, kind) => {
459
+ if (kind === 'initialInput') return mask(value, 'cardNumber');
460
+ if (kind === 'context') return mask(value, 'authToken');
461
+ if (kind === 'error') return mask(value, 'attempted');
462
+ return name === 'cmdFetchUser' ? mask(value, 'email') : value;
463
+ };
464
+ recorder({ redact });
465
+
466
+ assert.equal(redact(null, 'cmdFetchUser', 'result'), null); // still nothing found
467
+ assert.equal(redact('card_declined', 'cmdCharge', 'error'), 'card_declined'); // still a string
468
+ ```
469
+
470
+ A replay rebuilds the flow from the redacted input and context, so a field a step checks, such as a password, needs a stand-in the check treats the same way, as the example at the top of this section does, and a context field an `Ask` reads should stay.
471
+
472
+ ## Hooks
473
+
474
+ Hooks see every run, and recording, replay and the telemetry example are built on them. There are three: `onRun` wraps a whole run, `onStep` wraps each Command and each `Parallel`, and `onBeforeCommand` runs before each Command and can veto it by throwing. A hook that only watches must `await` what it wraps and return its result; [`configureEffect`](#configureeffectconfigs) lists each hook's arguments.
475
+
476
+ `configureEffect` adds a layer of hooks for the whole process and returns a function that removes it. Removing a layer removes only that layer, even when others were installed after it, so a library can add and remove its own hooks without touching the application's:
477
+
478
+ ```js
479
+ const remove = configureEffect(telemetryHooks(), recordingHooks({ sink }));
480
+ // the same as configureEffect(telemetryHooks()) followed by configureEffect(recordingHooks({ sink }))
481
+ remove();
482
+ ```
483
+
484
+ Layers run in the order they were installed, the first outermost, so a result or a thrown error unwinds from the innermost hook out:
485
+
486
+ ```
487
+ runEffect(flow(input))
488
+ │
489
+ ├─ telemetry.onRun first configuration: outermost
490
+ │ └─ recording.onRun last configuration: innermost
491
+ │ │
492
+ │ │ for each Command:
493
+ │ ├─ telemetry.onBeforeCommand interceptors all run, in the order given
494
+ │ ├─ recording.onBeforeCommand
495
+ │ ├─ telemetry.onStep
496
+ │ │ └─ recording.onStep closest to the Command
497
+ │ │ └─ cmd()
498
+ │ │ ┌─ recording.onStep returns a result, or a thrown error, unwinds
499
+ │ ├─ telemetry.onStep returns from the inside out
500
+ │ │
501
+ │ ┌─ recording.onRun returns
502
+ ├─ telemetry.onRun returns
503
+ ```
504
+
505
+ **Knowing which request a step belongs to.** `onStep` and `onRun` get no context, so a hook that logs per request finds the request the way the rest of your logging does. An `AsyncLocalStorage` scope entered around `runEffect` reaches every hook the run calls, and the recording example uses one to give each run its own recorder:
506
+
507
+ ```js
508
+ import { AsyncLocalStorage } from 'node:async_hooks';
509
+
510
+ const requestScope = new AsyncLocalStorage();
511
+ const stepLog = [];
512
+
513
+ // Logs each step with its request and duration, and returns what the step returned.
514
+ const removeStepLog = configureEffect({
515
+ onStep: async (name, type, op, path) => {
516
+ const started = performance.now();
517
+ try {
518
+ return await op();
519
+ } finally {
520
+ const { requestId } = requestScope.getStore() ?? {};
521
+ stepLog.push({ requestId, name, path, ms: performance.now() - started });
522
+ }
523
+ }
524
+ });
525
+
526
+ await requestScope.run({ requestId: 'req_1' }, () => runEffect(registerUserFlow(input)));
527
+ assert.deepEqual(
528
+ stepLog.map((line) => [line.requestId, line.name]),
529
+ [
530
+ ['req_1', 'cmdFindUser'],
531
+ ['req_1', 'cmdSaveUser']
532
+ ]
533
+ );
534
+ removeStepLog();
535
+ ```
536
+
537
+ A Command that `onBeforeCommand` vetoes never reaches `onStep`, so log a veto where you make it. In tests, call `configureEffect()` with no arguments in a `beforeEach`, so a test that fails before removing its hooks does not leave them installed for the next.
538
+
539
+ **Per-call hooks.** `runEffect`'s third argument takes hooks for that call only. They are merged with the configured ones by the same rules: the configured wrappers run outside them, and the configured `onBeforeCommand` hooks run first. `inherit: false` leaves the configured hooks out. With configured hooks `C` and a call `K` that supplies only `onStep`:
540
+
541
+ ```
542
+ inherit: true (default) inherit: false
543
+
544
+ onRun C.onRun (none)
545
+ onBeforeCommand C.onBeforeCommand (none)
546
+ onStep C.onStep( K.onStep( cmd ) ) K.onStep
547
+ ```
548
+
549
+ `recordEffect` inherits, so recording inside an application that already traces still produces spans. `replayEffect` passes `inherit: false` unless `hooks: true`.
550
+
433
551
  ## Passing Runtime Context
434
552
 
435
553
  Some values come from the framework (an authenticated tenant, a request ID, environment config) rather than from the data being processed. `Ask` lets a step read the `context` object passed to `runEffect` without passing it through every function:
@@ -446,7 +564,7 @@ const findProduct = (productId) =>
446
564
  app.post('/checkout', async (req, res) => {
447
565
  const result = await runEffect(checkoutFlow(req.body.productId), { tenant: req.tenant });
448
566
  if (result.type === 'Success') return res.json(result.value);
449
- // A Failure also carries the flow's input, so send the client only an error meant for it.
567
+ // A Failure holds the full error, so send the client only an error meant for it.
450
568
  // Answer the errors the flow returns by name, and anything else, such as a database outage, as a server error.
451
569
  if (result.error === 'Product not found.') return res.status(400).json({ error: result.error });
452
570
  res.status(500).json({ error: 'Checkout failed.' });
@@ -455,16 +573,33 @@ app.post('/checkout', async (req, res) => {
455
573
 
456
574
  Recording stores the context alongside the trace, so `Ask` replays with the values the original request saw. It is copied once per run, so read a value that can change while a run is under way, such as a switch an operator can flip to stop a batch, in a Command, whose result the trace records each time.
457
575
 
576
+ Keep the context to plain values such as IDs, flags and settings. Recording copies it into every trace, so a database client or connection pool in it puts its connection string in the trace, and one whose properties throw when read, as a lazy client's can, leaves the whole context out, so a replay needs it passed in. Reach a service from the Command's function, as `findProduct` reaches `db`. To run a flow against fakes or a test database, have the function that builds it take the services, and pass them in the test:
577
+
578
+ ```js
579
+ // Takes its catalog, so a test can run it against a fake.
580
+ const makeFindProduct = (catalog) => (productId) => {
581
+ const cmdFindProduct = () => catalog.findProduct(productId);
582
+ return Command(cmdFindProduct, (product) => (product ? Success(product) : Failure('Product not found.')));
583
+ };
584
+
585
+ // The fake answers by the ID it receives, so the test also checks what the Command's function sends.
586
+ const findInFakeCatalog = makeFindProduct({ findProduct: async (id) => (id === 'abc' ? { id } : null) });
587
+ assert.deepEqual(await runEffect(findInFakeCatalog('abc')), Success({ id: 'abc' }));
588
+ assert.deepEqual(await runEffect(findInFakeCatalog('xyz')), Failure('Product not found.'));
589
+ ```
590
+
591
+ A walk or a replay never runs a Command's function, so this is the test that catches one passing the wrong value.
592
+
458
593
  ## Retrying Transient Failures
459
594
 
460
- `Retry` runs part of a flow again when its I/O fails, meaning a Command's function throws. It does not retry a `Failure` that a step returned: that means the flow decided to stop, so the `Failure` is passed on at once, unchanged. Options are given where `Retry` is used, since they describe one dependency. An option set to `undefined` keeps its default, so settings read from configuration can leave a key out. To reuse the same settings, share an object:
595
+ `Retry` runs part of a flow again when a Command's function throws. A `Failure` a step returned is not retried: the flow decided to stop, so the `Failure` passes on at once, unchanged. Options are given where `Retry` is used, since they describe one dependency; to reuse settings, share an object:
461
596
 
462
597
  ```js
463
598
  const flakyNetwork = { attempts: 3, delay: 200, backoff: 2 };
464
599
  Retry(fetchPrice(sku), flakyNetwork);
465
600
  ```
466
601
 
467
- The retry settings are a plain object, so you can inspect and assert on them without running anything:
602
+ The settings are a plain object, so a test can check them without running anything:
468
603
 
469
604
  ```js
470
605
  import { Success, Failure, Command, Retry, runEffect } from 'pure-effect';
@@ -483,7 +618,7 @@ assert.equal(weatherFn.type, 'Retry');
483
618
  assert.equal(weatherFn.options.attempts, 3);
484
619
  ```
485
620
 
486
- **Wrap the Command that fails, not the pipeline.** Each attempt re-runs everything inside the `Retry`, including Commands that already succeeded:
621
+ **Wrap the Command that fails, not the pipeline.** Each attempt runs everything inside the `Retry` again, including Commands that already succeeded:
487
622
 
488
623
  ```js
489
624
  // Dangerous: a flaky receipt step charges the customer again on every attempt.
@@ -495,7 +630,7 @@ effectPipe(chargeCard, (charge) => Retry(sendReceipt(charge), { attempts: 3 }))(
495
630
 
496
631
  Wrapping a pipeline is safe only when every Command in it is idempotent (safe to run more than once).
497
632
 
498
- **Wrapping one Command is not always enough.** A Command's `next` is inside the `Retry` too, so if `next` continues the flow, everything after it is retried as well. This looks like it follows the advice above, but it does not:
633
+ **Wrapping one Command is not always enough.** A Command's `next` is inside the `Retry` too, so a `next` that continues the flow puts everything after it inside the `Retry` as well:
499
634
 
500
635
  ```js
501
636
  // Dangerous: `next` continues the booking, so every later step is inside the Retry.
@@ -505,9 +640,7 @@ Retry(
505
640
  );
506
641
  ```
507
642
 
508
- If a later Command's function throws, the `Retry` runs again, which repeats the seat hold and the charge. With two of these nested, a failure in the last step of a booking charges the card nine times.
509
-
510
- Instead, leave the retried Command with its default `next` and continue in a later pipeline step, outside the `Retry`:
643
+ If a later Command's function throws, the `Retry` holds the seat and charges the card again. With two of these nested, a failure in the last step of a booking charges the card nine times. Instead, give the retried Command its default `next` and continue in a later step, outside the `Retry`:
511
644
 
512
645
  ```js
513
646
  // Safe: the tree the Retry repeats is that one Command.
@@ -523,9 +656,9 @@ When every attempt fails, `runEffect` returns a `Failure` with this error:
523
656
  { retryExhausted: true, lastError: <the last error>, attempts: 3 }
524
657
  ```
525
658
 
526
- In TypeScript, a `Retry` adds `RetryExhaustedError` to the pipeline's error union, next to the error type of the steps it wraps, since a `Failure` those steps return passes through unchanged. `lastError` is typed `unknown`: it is whatever the Command's function threw, and nothing in the types says what that is, so check it before using it, for example with `instanceof Error`.
659
+ In TypeScript, a `Retry` adds `RetryExhaustedError` to the error union, beside the errors of the steps it wraps. `lastError` is typed `unknown`, since it is whatever the Command's function threw, so check it before using it, for example with `instanceof Error`.
527
660
 
528
- **Use `onExhausted` to fall back when every attempt fails.** The fallback runs instead of returning the `Failure`. If it succeeds, its value continues down the pipeline. If it fails, its own `Failure` is returned as is:
661
+ **Use `onExhausted` to fall back when every attempt fails.** The fallback runs in place of the `Failure`. If it succeeds, its value continues down the pipeline; if it fails, its own `Failure` is returned as is. The fallback can be any Effect, such as a Command that reads a cache, or `Success(defaultValue)`:
529
662
 
530
663
  ```js
531
664
  const fetchPrice = (sku) =>
@@ -535,9 +668,7 @@ const fetchPrice = (sku) =>
535
668
  });
536
669
  ```
537
670
 
538
- Fallback steps are recorded, so a replay repeats the fallback too. A fallback never starts in a `Parallel` branch that has already been cancelled. With `onExhausted` set, the `Retry` adds the fallback's error type to the TypeScript error union instead of `RetryExhaustedError`.
539
-
540
- Every attempt is recorded, so a replay repeats the same sequence of failures, without the delays.
671
+ Every attempt and the fallback are recorded, so a replay repeats the same failures and the same fallback, without the delays. A fallback never starts in a `Parallel` branch that has already been cancelled. With `onExhausted` set, the fallback's error type takes the place of `RetryExhaustedError` in the TypeScript error union.
541
672
 
542
673
  ## Running Effects in Parallel
543
674
 
@@ -570,7 +701,7 @@ Without `settled`, one failing branch cancels the rest and becomes the result of
570
701
  Parallel(subscriptions.map(billOne), (outcomes) => Success(outcomes.map(summarize)), { limit: 5, settled: true });
571
702
  ```
572
703
 
573
- A `Failure` in the list carries its branch's input when that branch was built with `effectPipe`, and no input otherwise, so match outcomes to records by their position in the list. When you report the outcomes, pick the fields you need rather than logging the whole object:
704
+ A `Failure` in the list holds only its error, so match outcomes to records by their position in the list. To report them, read `value` from a `Success` and `error` from a `Failure`:
574
705
 
575
706
  ```js
576
707
  Parallel(work, (outcomes) => Success(outcomes.map((o) => (o.type === 'Success' ? o.value : o.error.message))), {
@@ -578,13 +709,31 @@ Parallel(work, (outcomes) => Success(outcomes.map((o) => (o.type === 'Success' ?
578
709
  });
579
710
  ```
580
711
 
581
- Logging the outcomes as they are would include each branch's input, which for a registration or login contains credentials.
582
-
583
712
  The outcomes are plain `Success` and `Failure` objects. Returning one of them from `next` is the same as returning any other `Failure`: the flow stops, and `Retry` does not run it again.
584
713
 
585
- Bugs in the flow are not collected. An `EffectTypeError`, thrown for a malformed flow, and an error thrown by a `next` function or a pure step both still escape a settled `Parallel`, after the other branches are cancelled.
714
+ **Collecting some failures and stopping on others.** `settled` decides for every failure at once. When a batch should note a missing record and go on, but stop everything when its credentials expire, leave `settled` off and decide in each branch: return what should be collected as a value inside a `Success`, and what should stop the batch as a `Failure`, which cancels the other branches:
715
+
716
+ ```js
717
+ // A missing user is counted; an expired token stops the batch.
718
+ const fetchProfile = (userId) => {
719
+ const cmdFetchProfile = () => api.getProfile(userId); // resolves to { status, body }
720
+ return Command(cmdFetchProfile, (response) => {
721
+ if (response.status === 401) return Failure('auth_expired');
722
+ if (response.status === 404) return Success({ userId, found: false });
723
+ return Success({ userId, found: true, profile: response.body });
724
+ });
725
+ };
726
+
727
+ const fetchProfiles = (userIds) => Parallel(userIds.map(fetchProfile), { limit: 4 });
728
+
729
+ const profiles = fetchProfiles(['u1', 'u2']);
730
+ assert.deepEqual(profiles.effects[0].next({ status: 404 }), Success({ userId: 'u1', found: false }));
731
+ assert.deepEqual(profiles.effects[1].next({ status: 401 }), Failure('auth_expired'));
732
+ ```
733
+
734
+ A Command whose function throws, such as on a network error, also stops the batch. Wrap it in `Retry` if the error is likely to pass, or catch it in the function and return it as data if it should be counted; see [Which Errors Are Data](#which-errors-are-data).
586
735
 
587
- `limit` caps how many branches run at once; the rest start as others finish. Results and recorded paths stay in array order, so a limit changes only the pacing, and a trace recorded with a limit replays the same without one. A `limit` that is not a positive integer throws a `TypeError`.
736
+ `limit` caps how many branches run at once; the rest start as others finish. Results and recorded paths stay in array order, so a limit changes only the pacing, and a trace recorded with a limit replays the same without one. A `limit` that is not a positive integer throws an `EffectTypeError` where the `Parallel` is built.
588
737
 
589
738
  **Cancelling is a request, not a guarantee.** A cancelled branch starts no new Commands: a three-step branch whose first step is running when a sibling fails finishes that step and stops. To stop the running step itself, its function has to take the `AbortSignal` as a parameter, written without a default value, and pass it on to the I/O:
590
739
 
@@ -598,9 +747,9 @@ const fetchProfileUncancellable = (userId) => Command(() => fetch(`/users/${user
598
747
 
599
748
  Outside a `Parallel`, the function is called with no arguments. A `Retry` inside a cancelled branch stops retrying.
600
749
 
601
- Which branch failed first and cancelled the others depends on timing, so it is recorded with the trace. A replay of a cancelled `Parallel` returns the same failure production did, and stops each other branch where production stopped it, rather than letting whichever branch the replay reaches first decide. The same holds when the branch that cancelled the others was a `next` function or a pure step that threw: the replay throws the same error. If the branch that cancelled the others no longer fails, or the `Parallel` no longer has that branch, the replay ends in a `TimeParadox` naming it.
750
+ ### Undoing what succeeded when a branch fails
602
751
 
603
- **Undoing what succeeded when a branch fails.** Without `settled`, the failing branch's `Failure` is the whole result, and the values of the branches that succeeded are dropped. When one of them did something that has to be undone, such as charging a card for an order whose stock then ran out, the code that called `runEffect` no longer has the charge to refund. Use `settled: true`, so `next` sees every outcome, and have it return the steps that undo whatever succeeded, followed by the failure:
752
+ Without `settled`, the failing branch's `Failure` is the whole result, and the values of the branches that succeeded are dropped. When one of them did something that has to be undone, such as charging a card for an order whose stock then ran out, the code that called `runEffect` no longer has the charge to refund. Use `settled: true`, so `next` sees every outcome, and have it return the steps that undo whatever succeeded, followed by the failure:
604
753
 
605
754
  ```js
606
755
  const reserveStock = (order) => {
@@ -660,6 +809,32 @@ assert.deepEqual(
660
809
 
661
810
  A settled `Parallel` cancels nothing, so both steps always run to the end, and the undoing starts once both have finished. The undo steps are part of the flow, so a trace records them and a replay repeats them. An undo step that fails ends the flow with its own error rather than the original one; wrap it in `Retry` if it can fail for a moment.
662
811
 
812
+ ### Errors no branch returned
813
+
814
+ A `Failure` among a settled `Parallel`'s outcomes can also hold an error the branch never returned: what one of its Commands threw, or what an `onBeforeCommand` hook vetoed it with. Neither is in the branch's declared error type, so give the code that reads the outcomes a case for an error it does not recognise, as for a run's result (see [TypeScript](#typescript-typed-errors-and-context)), rather than letting it fall into the last error it expects, which would report a vetoed charge as a declined card.
815
+
816
+ Fewer such errors reach the outcomes when a branch returns what it can as data. Catch an error the flow can handle inside the Command's function and return it (see [Which Errors Are Data](#which-errors-are-data)), and stop a batch by reading the operator's switch in a Command whose `next` returns a `Failure`, rather than by vetoing in `onBeforeCommand`:
817
+
818
+ ```js
819
+ // Read before each charge, so a switch flipped mid-batch stops the charges that have not started.
820
+ const cmdBillingHalted = () => flags.get('billing.halted');
821
+ const billUnlessHalted = (subscription) =>
822
+ Command(cmdBillingHalted, (halted) => (halted ? Failure('halted') : billOne(subscription)));
823
+
824
+ Parallel(subscriptions.map(billUnlessHalted), (outcomes) => Success(outcomes.map(summarize)), {
825
+ limit: 5,
826
+ settled: true
827
+ });
828
+ ```
829
+
830
+ The halt is then one of the branch's declared errors, typed like a declined card, and the trace records each read of the switch, so the batch replays. A vetoed Command leaves no entry in the trace, so a replay of a vetoed batch fails at the first veto.
831
+
832
+ Bugs in the flow are not collected. An `EffectTypeError`, thrown for a malformed flow, and an error thrown by a `next` function or a pure step both still escape a settled `Parallel`, after the other branches are cancelled.
833
+
834
+ ### Replaying a cancelled `Parallel`
835
+
836
+ Which branch failed first and cancelled the others depends on timing, so it is recorded with the trace. A replay of a cancelled `Parallel` returns the same failure production did, and stops each other branch where production stopped it, rather than letting whichever branch the replay reaches first decide. The same holds when the branch that cancelled the others was a `next` function or a pure step that threw: the replay throws the same error. If the branch that cancelled the others no longer fails, or the `Parallel` no longer has that branch, the replay ends in a `TimeParadox` naming it. The trace also records how many branches each `Parallel` had, so a replay of one that has gained or lost a branch ends in a `TimeParadox` before any of its branches run.
837
+
663
838
  ## Composing Larger Flows
664
839
 
665
840
  `effectPipe` runs steps in a straight line. Branching and joining use the same pieces:
@@ -695,6 +870,111 @@ When the lookup is written in place rather than reused, the Command's own `next`
695
870
 
696
871
  **Pass only what the next steps need.** Avoid one object that collects everything computed so far. When a step's input is all it gets, it cannot depend on a value from far upstream without showing it, stale fields do not linger, and two steps cannot clash over the same key. Data also lives only as long as the flow needs it, which matters for credentials and personal data. In TypeScript, it keeps the pipeline type-checked: if an upstream step changes what it returns, the step that reads the value fails to compile instead of getting `undefined` at runtime.
697
872
 
873
+ In a generator flow, most of this comes for free. A step that branches into another flow is yielded like any other, as in `yield* step(processOrder(order))`. Values that do not depend on each other are joined with `const [cart, user] = yield* step(Parallel([fetchCart(input.cartId), fetchUser(input.userId)]))`. Values that do are variables, with no step to pass them on together; see [Where a generator helps](#where-a-generator-helps). Keep each decision in a step function that takes only what it needs, as the advice above says for a pipeline's steps.
874
+
875
+ ## Writing Loops
876
+
877
+ A loop is written in two parts: a step that gets the list, and a `Parallel` over it, with `limit: 1` so the items run one after another, as in a `for` loop. The `async` version is usually split the same way. Paying a customer's unpaid invoices in order, and stopping at the first that fails:
878
+
879
+ ```js
880
+ async function payUnpaidAsync(customerId) {
881
+ const invoices = await billing.findUnpaid(customerId);
882
+ for (const invoice of invoices) {
883
+ const receipt = await payments.charge(invoice);
884
+ await mailer.sendReceipt(receipt);
885
+ }
886
+ }
887
+
888
+ // First part: get the list.
889
+ const findUnpaidInvoices = (customerId) => {
890
+ const cmdFindUnpaid = () => billing.findUnpaid(customerId);
891
+ return Command(cmdFindUnpaid);
892
+ };
893
+
894
+ // Second part: the loop's body, a flow of its own for one invoice.
895
+ const chargeInvoice = (invoice) => {
896
+ const cmdChargeInvoice = () => payments.charge(invoice);
897
+ return Retry(Command(cmdChargeInvoice), { attempts: 3 });
898
+ };
899
+
900
+ const sendReceipt = (receipt) => {
901
+ const cmdSendReceipt = () => mailer.sendReceipt(receipt);
902
+ return Command(cmdSendReceipt);
903
+ };
904
+
905
+ const payInvoice = (invoice) => effectPipe(chargeInvoice, sendReceipt)(invoice);
906
+
907
+ // The loop: one body per invoice, run one at a time.
908
+ const payAll = (invoices) => Parallel(invoices.map(payInvoice), { limit: 1 });
909
+
910
+ const payUnpaid = (customerId) => effectPipe(findUnpaidInvoices, payAll)(customerId);
911
+
912
+ // The flow starts by getting the list, and hands what it gets to the loop.
913
+ const flow = payUnpaid('cus_1');
914
+ assert.equal(commandName(flow), 'cmdFindUnpaid');
915
+ assert.equal(flow.next([{ id: 1 }, { id: 2 }]).effects.length, 2);
916
+
917
+ // The body is tested on its own: the Retry holds only the charge as its effect, and its next leads to the receipt.
918
+ const body = payInvoice({ id: 1 });
919
+ assert.equal(commandName(body.effect), 'cmdChargeInvoice');
920
+ assert.equal(commandName(body.next({ id: 'receipt_1' })), 'cmdSendReceipt');
921
+
922
+ // An empty list runs nothing.
923
+ assert.deepEqual(await runEffect(payAll([])), Success([]));
924
+ ```
925
+
926
+ Each invoice is paid after the one before it has finished, and the first that fails stops the rest from starting, as in the `async` version. When the payments can overlap, a higher `limit` runs several at a time.
927
+
928
+ The loop's body is a flow built for one item, so it can hold as many steps as the body of a `for` loop. Put a `Retry` inside it, on the step that needs one, since a `Retry` runs everything it wraps again (see [Retrying Transient Failures](#retrying-transient-failures)): around the whole loop it would charge the invoices already paid, and around the whole body a receipt that failed to send would charge the card again.
929
+
930
+ The `Parallel`'s `next` receives what each body returned, in order, so a total or a summary of the loop goes there: `Parallel(invoices.map(payInvoice), (receipts) => Success(receipts.length), { limit: 1 })`. To keep going past a failure, as a `try`/`catch` inside the loop would, add `settled: true`: every invoice is tried, and `next` receives one `Success` or `Failure` per invoice. See [Running Effects in Parallel](#running-effects-in-parallel).
931
+
932
+ In a generator flow, the same loop can be a `for` loop over the list, with the body's steps inside it:
933
+
934
+ ```js
935
+ const payUnpaidGen = effectGen(function* (customerId) {
936
+ const invoices = yield* step(findUnpaidInvoices(customerId));
937
+ for (const invoice of invoices) yield* step(payInvoice(invoice));
938
+ });
939
+
940
+ // Every charge is declined, so both forms give up on the first invoice once its retries run out, with the same Failure.
941
+ const answers = {
942
+ cmdFindUnpaid: { result: [{ id: 1 }, { id: 2 }] },
943
+ cmdChargeInvoice: { error: new Error('declined') }
944
+ };
945
+ const answer = (asked) => answers[asked.name];
946
+ const fromLoop = await replayEffect(payUnpaidGen('cus_1'), answer);
947
+ const fromParallel = await replayEffect(payUnpaid('cus_1'), answer);
948
+ assert.equal(fromLoop.result.error.retryExhausted, true);
949
+ assert.deepEqual(fromLoop.result, fromParallel.result);
950
+ ```
951
+
952
+ It stops at the first invoice that fails, as the `Parallel` with `limit: 1` does. Use the `Parallel` instead when the loop is long, since a generator run keeps every step's result until it ends. Use it too when payments can overlap, with a higher `limit`, or when the loop has to keep going past a failure, with `settled: true`, since a `catch` in the body cannot recover. The two forms record differently, so a trace recorded from one replays against the other as a `TimeParadox`.
953
+
954
+ Sometimes getting the list is a loop of its own. Paging through an API with a cursor is one: each request needs the cursor from the page before, so the requests cannot be listed in advance. Write that loop as an ordinary `async` function, call it from one Command, and map over the list it returns, as above:
955
+
956
+ ```js
957
+ async function fetchAllOrders() {
958
+ const orders = [];
959
+ let cursor = null;
960
+ do {
961
+ const page = await api.listOrders(cursor);
962
+ orders.push(...page.items);
963
+ cursor = page.nextCursor;
964
+ } while (cursor);
965
+ return orders;
966
+ }
967
+
968
+ const listAllOrders = () => {
969
+ const cmdListAllOrders = () => fetchAllOrders();
970
+ return Command(cmdListAllOrders);
971
+ };
972
+ ```
973
+
974
+ To the flow, the whole loop is one step. A trace records the finished list as that step's result, and a replay hands the list back without replaying the pages. A `Retry` around the Command starts again from the first page. A flow test cannot see inside it, so, like any Command's function, it is left to an integration test.
975
+
976
+ The loop belongs in the flow only when the flow has to decide something on each pass, such as stopping at the first order that matches, or saving each page as it arrives. Then the Command's `next` returns the Command for the next page instead of a `Success`, until there are no more pages.
977
+
698
978
  ## Which Errors Are Data
699
979
 
700
980
  Pure Effect has no catch, on purpose. A flow's outcomes are of two kinds, and each is written differently.
@@ -717,7 +997,7 @@ const fetchPrice = (sku) => {
717
997
  };
718
998
  ```
719
999
 
720
- The failed attempt is recorded as that Command's result, with the error's `code` and `message`, so a replay takes the same fallback branch. Copy the fields you need rather than returning the error itself: a trace keeps data, not objects, so an error stored inside a result loses its properties (see [Recording in Production](#recording-in-production)).
1000
+ The failed attempt is recorded as that Command's result, with the error's `code` and `message`, so a replay takes the same fallback branch. Copy the fields you need rather than returning the error itself: a trace keeps data, not objects, so an error stored inside a result loses its message (see [Recording in Production](#recording-in-production)).
721
1001
 
722
1002
  **A `Failure` means abort.** It stops the flow and goes back to the code that called `runEffect`, which decides what it means: an HTTP status, a queue retry, an alert. Nothing inside the flow can catch a `Failure`, so a reader never has to look elsewhere for a handler.
723
1003
 
@@ -754,7 +1034,97 @@ Retry(
754
1034
  | a Command's function threw | an I/O fault | retries it | the exhaustion, once the attempts are gone |
755
1035
  | a `next` function or a pure step threw, or the flow is malformed | a bug | nothing; it is thrown, not returned | nothing |
756
1036
 
757
- In short, **you can recover from an error your I/O produced, but you cannot catch a `Failure` a step returned.** Only the code that called `runEffect` acts on it. For the same reason, do not throw business errors from a Command's function: a throw there tells `Retry` that the I/O broke, and `Retry` will try again. A throw anywhere else in the flow is treated as a bug: `runEffect` rejects with the thrown error instead of returning a `Failure`.
1037
+ In short, **you can recover from an error your I/O produced, but you cannot catch a `Failure` a step returned.** Only the code that called `runEffect` acts on it. For the same reason, do not throw business errors from a Command's function: a throw there tells `Retry` that the I/O broke, and `Retry` will try again. A throw anywhere else in the flow is treated as a bug and thrown as it is instead of returned as a `Failure`: `runEffect` rejects with it, or, from a step before the first Command, the call that builds the flow throws it.
1038
+
1039
+ ### A malformed flow
1040
+
1041
+ A flow that is not made of Effects is a bug, so it throws an `EffectTypeError` that says where, rather than returning a `Failure`. The steps before a flow's first Command run as it is built, so a mistake in one of them is thrown by the call that builds the flow, as `registerUserFlow(input)` would throw if its first step returned a plain object:
1042
+
1043
+ ```
1044
+ Step 'validateRegistration' returned a plain object. Return Success, Failure, Command, Ask,
1045
+ Retry, or Parallel: a plain value has to be wrapped, as in Success(value).
1046
+ ```
1047
+
1048
+ A mistake after the first Command makes `runEffect` reject. That covers a missing `return`, a `next` that returns a plain value, a step or `next` written as `async` (do the awaited work in a Command instead), and `runEffect(flow)` where `runEffect(flow(input))` was meant. The building blocks check their arguments where they are built, before their own I/O runs, so `Command(db.findUser(email))`, which makes the call while the flow is built, `Command(fn, { name })`, with the metadata in `next`'s place, and a `Parallel` or `effectPipe` given the wrong thing each throw an `EffectTypeError` there; one built inside a `next` is checked when that `next` runs.
1049
+
1050
+ ## Generator Flows in Depth
1051
+
1052
+ What [Writing Flows as Generators](#writing-flows-as-generators) leaves out: when a body runs again, what a `catch` or `finally` in it can do, and the mistakes `effectGen` catches.
1053
+
1054
+ ### What runs once, and what runs again
1055
+
1056
+ A run goes through the body once, top to bottom, as `async` code does. Anything that uses the flow a second time runs it again from the top, since a generator cannot be copied: running one flow value again, or putting it in two branches of a `Parallel`, so build the flow from its input for each run; a `Retry` around the flow, which starts the body afresh for each attempt, as a retried `async` function does; and a test that hands an earlier step a second answer, to walk another branch:
1057
+
1058
+ ```js
1059
+ const flow = registerUserFlowGen(input);
1060
+ assert.equal(commandName(flow), 'cmdFindUser');
1061
+
1062
+ // The first answer finds a user, so the flow stops there.
1063
+ assert.deepEqual(flow.next({ id: 1 }), Failure('Email already in use.'));
1064
+
1065
+ // A second answer to the same step runs the body again from the top, and this time it goes on to save.
1066
+ assert.equal(commandName(flow.next(null)), 'cmdSaveUser');
1067
+ ```
1068
+
1069
+ So keep the body to its own variables. When it runs again, it has to ask for the same steps in the same order, and a body that asks for a different one stops the run with an `EffectTypeError` naming both. `Date.now()`, a random ID, or a variable outside the body can change between runs: get the first two from a Command, as a pipeline does, and pass the third in the flow's input.
1070
+
1071
+ ### How a generator flow stops
1072
+
1073
+ `return` ends the flow. A plain value is its `Success`, `return Failure(error)` stops it with that error, and returning a Command or any other Effect runs it, as `return fetch(url)` does in an `async` function. A `throw` in the body is a bug, as one in a pipeline step is, and `runEffect` rejects with it.
1074
+
1075
+ When a step stops the flow, because its Command threw or it returned a `Failure`, the body's `catch` and `finally` blocks run, as they would for an `await` that rejected. The `catch` gets an error saying where the flow stopped, not the original, which is the flow's `Failure`, so it cannot branch on the original's fields: `e.code` and the like are `undefined`, and `e.name` is `FlowStopped`. It can log, but it cannot recover:
1076
+
1077
+ ```js
1078
+ const unreliableDb = {
1079
+ saveUser: async () => {
1080
+ throw new Error('connection reset');
1081
+ }
1082
+ };
1083
+
1084
+ const saveUser = effectGen(function* (user) {
1085
+ try {
1086
+ const cmdSaveUser = () => unreliableDb.saveUser(user);
1087
+ return yield* step(Command(cmdSaveUser));
1088
+ } catch (error) {
1089
+ // Runs when the save throws. It can log, and it has to let the error pass.
1090
+ throw error;
1091
+ }
1092
+ });
1093
+
1094
+ const result = await runEffect(saveUser({ id: 1 }));
1095
+ assert.equal(result.error.message, 'connection reset');
1096
+ ```
1097
+
1098
+ A `catch` that returns or carries on, one that throws a different error, and a `finally` that runs another step all stop the run with an `EffectTypeError` that says so:
1099
+
1100
+ ```js
1101
+ const saveLater = effectGen(function* (user) {
1102
+ try {
1103
+ const cmdSaveUser = () => unreliableDb.saveUser(user);
1104
+ return yield* step(Command(cmdSaveUser));
1105
+ } catch {
1106
+ return 'saved later';
1107
+ }
1108
+ });
1109
+
1110
+ await assert.rejects(runEffect(saveLater({ id: 1 })), /kept going after Command 'cmdSaveUser' stopped it/);
1111
+ ```
1112
+
1113
+ Handle an error the flow expects inside the Command's function, and return it as data for the body to branch on; recover from one that keeps happening with `Retry`'s `onExhausted`. See [Which Errors Are Data](#which-errors-are-data). Cleanup for the whole run goes in a `try`/`finally` around `runEffect`, as it does for a pipeline.
1114
+
1115
+ ### Mistakes it catches
1116
+
1117
+ | Written | What happens |
1118
+ | --- | --- |
1119
+ | `yield step(x)`, without the star | an `EffectTypeError`: write `yield*` |
1120
+ | `yield x` | an `EffectTypeError`: write `yield* step(x)` |
1121
+ | `yield* x`, without `step` | the engine's `TypeError`, which on V8 becomes an `EffectTypeError` saying to write `yield* step(x)` |
1122
+ | `const found = step(x)`, then `found.id` | an `EffectTypeError`: `step(...)` was used as a value |
1123
+ | `[...step(x)]` or `for (const v of step(x))` | an `EffectTypeError`: `step(...)` was iterated outside `yield*` |
1124
+ | `step(db.findUser(email))` | an `EffectTypeError`: put the call in a Command |
1125
+ | `effectGen(async function* () {})` | an `EffectTypeError`: write `function*` |
1126
+
1127
+ In TypeScript, most of these do not compile; see [TypeScript](#typescript-typed-errors-and-context).
758
1128
 
759
1129
  ## TypeScript: Typed Errors and Context
760
1130
 
@@ -777,12 +1147,18 @@ if (result.type === 'Failure') {
777
1147
  }
778
1148
  ```
779
1149
 
780
- The annotations are optional. Without them, the union holds whatever each step can pass to `Failure`, each error kept exactly as written, whether a string or an object, and a step that cannot fail, such as a Command without a `next`, adds nothing. The union covers the `Failure`s your steps return. A Command whose function throws, or that an `onBeforeCommand` hook vetoes, also ends the run with a `Failure` the union does not name, so where the result is handled, give it one fallback, such as a `default` in a `switch` over `result.error`, and treat what reaches it as a server error. One fallback covers the whole flow: catch inside a Command's function only what the flow can handle, and let the rest throw, which is also what lets `Retry` act on it. To check for a thrown error, copy it into a variable typed `unknown` first, as in `const error: unknown = result.error`, since TypeScript refuses `instanceof Error` on an error type made only of strings, or on a flow that declares none.
1150
+ The annotations are optional. Without them, the union holds whatever each step can pass to `Failure`, each error kept exactly as written, whether a string or an object, and a step that cannot fail, such as a Command without a `next`, adds nothing.
1151
+
1152
+ **The union covers only the `Failure`s your steps return.** A Command whose function throws, or that an `onBeforeCommand` hook vetoes, also ends the run with a `Failure`, and its error is not in the union. So where the result is handled, give it one fallback, such as a `default` in a `switch` over `result.error`, and treat what reaches it as a server error; the same goes for the outcomes a settled `Parallel` hands `next`. One fallback covers the whole flow: catch inside a Command's function only what the flow can handle, and let the rest throw, which is also what lets `Retry` act on it.
1153
+
1154
+ To check for a thrown error, copy it into a variable typed `unknown` first, as in `const error: unknown = result.error`, since TypeScript refuses `instanceof Error` on an error type made only of strings, or on a flow that declares none.
781
1155
 
782
1156
  To type what a Command's function returns, such as a JSON response, write the function's result type, as in `Command((): Promise<User | null> => fetchJson(url), next)`. `Command<User | null>(…)` also compiles, but with some type arguments given TypeScript infers none of the others, so that Command's errors are typed `unknown`, which hides the rest of the union.
783
1157
 
784
1158
  Value types are checked through the pipeline too, so a step that reads a field the previous step does not return is a compile error. This only works while every step uses the value it receives. A step written as `() => doSomething(outer)` ignores it, and the types stop being checked at that point.
785
1159
 
1160
+ `Failure` keeps a literal exactly as written, but `Success` widens it, as TypeScript does for any object: `Success({ status: 'queued' })` holds a `status` of type `string`. A later step that tells values apart by such a field then refuses it, often several steps from where the value was built, so give the type there, as in `Success<Queued>({ status: 'queued', jobId })`.
1161
+
786
1162
  `effectPipe` is typed for up to 20 steps. A pipeline is itself a step, so a longer one nests, which is usually easier to read anyway: `effectPipe(effectPipe(s1, s2), effectPipe(s3, s4))`.
787
1163
 
788
1164
  ### Typed context with `Ask`
@@ -798,7 +1174,44 @@ const findProduct = (productId: string): Effect<Product, 'not_found', AppContext
798
1174
  const result = await runEffect(findProduct('abc'), { tenant: 'acme', requestId: '123' });
799
1175
  ```
800
1176
 
801
- Every step's context counts, so a pipeline needs all the contexts its steps read, even when the first step reads none, and a `Parallel` needs every context its branches read. `runEffect` requires a context whenever the flow reads one, since the flow would otherwise get an empty object.
1177
+ Every step's context counts, so a pipeline needs all the contexts its steps read, even when the first step reads none, and a `Parallel` needs every context its branches read. `runEffect` requires a context whenever the flow reads one, since the flow would otherwise get an empty object, and checks one passed as a variable against what the flow reads, as it checks one written in place, so a variable whose type lacks a field the flow reads does not compile. `recordEffect`, `replayEffect` and `timeTravel` check a context the same way, and `replayEffect` given a resolver requires one, since a resolver holds none.
1178
+
1179
+ ### Generator flows
1180
+
1181
+ `effectGen` infers everything from the body. Each `yield*` is typed by its own step, the error union collects every step's errors and every `Failure` the body returns, and the context collects what every step reads:
1182
+
1183
+ ```ts
1184
+ const registerUser = effectGen(function* (input: { email: string }) {
1185
+ const found = yield* step(findUser(input.email)); // User | null
1186
+ if (found) return Failure('EMAIL_TAKEN');
1187
+ return yield* step(saveUser(input));
1188
+ });
1189
+ // (input: { email: string }) => Effect<User, 'EMAIL_TAKEN' | the errors findUser and saveUser declare>
1190
+ ```
1191
+
1192
+ `yield* x` without `step`, reading a property of a step, and an `async function*` do not compile, and a body that returns an untyped value keeps its steps' errors. Returning a step or a Promise compiles, so that a generic helper returning a value of its type parameter does too, and fails when it runs. `yield step(x)` without the star does, and fails when it runs. Name the context `Ask()` reads as `Ask<AppContext>()`.
1193
+
1194
+ ### Testing a flow in TypeScript
1195
+
1196
+ A flow is typed as any kind of step it could start with, since validation may already have returned a `Success` or a `Failure`, so `.cmd` and `.next` compile only after the test checks that the step is a Command. `node:assert`'s `assert(step.type === 'Command')` is such a check, and TypeScript follows it. Jest's and Vitest's `expect` is not, so a walk needs a check at every step, and a small helper makes that one line per step with any test framework:
1197
+
1198
+ ```ts
1199
+ import assert from 'node:assert/strict';
1200
+ import { commandName } from 'pure-effect';
1201
+ import type { Effect } from 'pure-effect';
1202
+
1203
+ // Fails unless the step is the Command named, and returns it typed as one.
1204
+ function assertCommand<T, E, C>(step: Effect<T, E, C>, name: string) {
1205
+ assert(step.type === 'Command', `expected ${name}, got ${step.type}`);
1206
+ assert.equal(commandName(step), name);
1207
+ return step;
1208
+ }
1209
+
1210
+ const step1 = assertCommand(registerUserFlow(input), 'cmdFindUser');
1211
+ assertCommand(step1.next(null), 'cmdSaveUser');
1212
+ ```
1213
+
1214
+ For a step that returns its Command directly, as in `ensureEmailAvailable(input).next(found)`, `next` is checked against what the Command's function returns, so where [Testing Without Mocks](#testing-without-mocks) passes `{ id: 1 }` for a user that was found, a TypeScript test passes a whole user, of the type `db.findUser` returns. A Command reached any other way, by walking the whole flow or through an `Ask`'s `next`, accepts any value, since its type does not say which Command it is.
802
1215
 
803
1216
  ## Why Pure Effect
804
1217
 
@@ -831,7 +1244,7 @@ Timings are from Node 22 on a MacBook Pro with M4 Pro CPU:
831
1244
 
832
1245
  ## API Reference
833
1246
 
834
- Every `options` argument below throws for a name it does not read, so a misspelt option fails instead of running with its default.
1247
+ Every `options` argument and hook configuration below throws for a name it does not read or a value it cannot use, so a misspelt option fails instead of running with its default. `Retry` and `Parallel` throw an `EffectTypeError` where they are built.
835
1248
 
836
1249
  ### Building blocks
837
1250
 
@@ -839,9 +1252,9 @@ Every `options` argument below throws for a name it does not read, so a misspelt
839
1252
 
840
1253
  Returns `{ type: 'Success', value }`.
841
1254
 
842
- #### `Failure(error, initialInput?)`
1255
+ #### `Failure(error)`
843
1256
 
844
- Returns `{ type: 'Failure', error, initialInput }`. Stops the pipeline immediately.
1257
+ Returns `{ type: 'Failure', error }`. Stops the pipeline immediately.
845
1258
 
846
1259
  #### `Command(cmdFn, nextFn?, meta?)`
847
1260
 
@@ -867,17 +1280,17 @@ Use `meta.name` in code that gets minified, since a minifier renames functions a
867
1280
 
868
1281
  Returns a Command's name, chosen in the order above, so a test checks a step by the name its trace would record: `assert.equal(commandName(step), 'cmdFindUser')`. Anything but a Command throws an `EffectTypeError`.
869
1282
 
870
- #### `Ask(nextFn)`
1283
+ #### `Ask(nextFn?)`
871
1284
 
872
- Returns `{ type: 'Ask', next }`. Passes the `context` from `runEffect` into `nextFn`.
1285
+ Returns `{ type: 'Ask', next }`. Passes the `context` from `runEffect` into `nextFn`. With no argument, the flow gets the context itself, as `yield* step(Ask())` reads it.
873
1286
 
874
1287
  #### `Retry(effect, options?)`
875
1288
 
876
1289
  Returns `{ type: 'Retry', effect, options, next }`.
877
1290
 
878
- - `options.attempts`: Max retries, not counting the first try (default: `3`). Must be a positive integer; anything else, including `0`, throws a `TypeError`. To handle an outcome without retrying, branch on it in the Command's `next`, or isolate a failing branch with `Parallel`'s `settled`.
879
- - `options.delay`: Ms before the first retry (default: `100`). Must be a finite number of 0 or more, or it throws a `TypeError`.
880
- - `options.backoff`: Multiplier applied to the delay on each attempt (default: `1`, flat). Must be a finite number of 0 or more, or it throws a `TypeError`.
1291
+ - `options.attempts`: Max retries, not counting the first try (default: `3`). Must be a positive integer; anything else, including `0`, throws. To handle an outcome without retrying, branch on it in the Command's `next`, or isolate a failing branch with `Parallel`'s `settled`.
1292
+ - `options.delay`: Ms before the first retry (default: `100`). Must be a finite number of 0 or more.
1293
+ - `options.backoff`: Multiplier applied to the delay on each attempt (default: `1`, flat). Must be a finite number of 0 or more.
881
1294
 
882
1295
  An option set to `undefined` keeps its default.
883
1296
 
@@ -916,6 +1329,19 @@ In either language, a Command a step builds and does not return never runs, and
916
1329
 
917
1330
  Return the Command, and have its `next` return the value the rest of the pipeline needs.
918
1331
 
1332
+ #### `effectGen(body)`
1333
+
1334
+ Returns a flow function, `(input) => Effect`, from a generator function, `function* (input) { ... }`. See [Writing Flows as Generators](#writing-flows-as-generators).
1335
+
1336
+ - Calling it runs the body up to its first `yield*`, so a `Failure` before the first step comes back at once, as a pipeline's does.
1337
+ - `return value` is `Success(value)`, `return Failure(error)` stops the flow, and a returned Effect runs.
1338
+ - When a step stops the flow, the body's `catch` and `finally` blocks run; a `catch` that recovers or throws another error, or a `finally` that runs a step, rejects the run.
1339
+ - An `async function*`, and a body that yields anything but `yield* step(effect)`, throws an `EffectTypeError`.
1340
+
1341
+ #### `step(effect)`
1342
+
1343
+ Wraps an Effect for `yield*` inside `effectGen`, which gives back its value: `const user = yield* step(findUser(email))`. Anything but an Effect throws an `EffectTypeError`, and so does using the result any other way than `yield*`.
1344
+
919
1345
  ### Running a flow
920
1346
 
921
1347
  #### `runEffect(effect, context?, callConfig?)`
@@ -923,66 +1349,19 @@ Return the Command, and have its `next` return the value the rest of the pipelin
923
1349
  Runs a flow and resolves with its `Success` or `Failure`.
924
1350
 
925
1351
  - `context`: what `Ask` reads, also passed to `onBeforeCommand`. `context.flowName` names the run in traces and telemetry.
926
- - `callConfig`: `onStep`, `onRun` and `onBeforeCommand` for this call only, added to the `configureEffect` wiring, or used alone with `inherit: false`; see [`configureEffect`](#configureeffectconfigs). `onRun` wraps the run once, retries included. A `retry` key throws a `TypeError`, since retry options belong to each `Retry`.
927
-
928
- A flow that is not made of Effects is a bug, so `runEffect` rejects with an `EffectTypeError` that says where, rather than returning a `Failure`:
929
-
930
- ```
931
- Step 'validateRegistration' returned a plain object. Return Success, Failure, Command, Ask,
932
- Retry, or Parallel: a plain value has to be wrapped, as in Success(value).
933
- ```
934
-
935
- That covers a missing `return`, a `next` that returns a plain value, a step or `next` written as `async` (do the awaited work in a Command instead), and `runEffect(flow)` where `runEffect(flow(input))` was meant. The building blocks check their arguments as the flow is built, before any of its I/O runs, so `Command(db.findUser(email))`, which makes the call while the flow is built, `Command(fn, { name })`, with the metadata in `next`'s place, and a `Parallel` or `effectPipe` given the wrong thing each throw an `EffectTypeError` there. A throw from a Command's function, or from an `onBeforeCommand` veto, is a `Failure`; a throw from a `next` or a pure step is a bug too, and `runEffect` rejects with it as thrown.
1352
+ - `callConfig`: `onStep`, `onRun` and `onBeforeCommand` for this call only, added to the configured hooks, or used alone with `inherit: false`; see [Hooks](#hooks).
1353
+ - A throw from a Command's function, or an `onBeforeCommand` veto, ends the run with a `Failure`. A malformed flow, or a throw from a `next` or a pure step, is a bug and is thrown: by the call that builds the flow when it comes before the first Command, and otherwise as a rejection of `runEffect`. See [Which Errors Are Data](#which-errors-are-data).
936
1354
 
937
1355
  #### `configureEffect(...configs)`
938
1356
 
939
- Adds a layer of hooks for the whole process and returns a function that removes it. Several configurations passed to one call form one layer, the same as installing each on its own. Removing a layer removes only that layer, even when others were installed after it, so a library can add and remove its own hooks without touching the application's. `configureEffect()` with no arguments removes every layer, and a call whose arguments are all `undefined`, such as `configureEffect(flag ? hooks : undefined)`, changes nothing. A `retry` key throws a `TypeError`, since retry options belong to each `Retry`.
940
-
941
- ```js
942
- const remove = configureEffect(telemetryHooks(), recordingHooks({ sink }));
943
- // the same as configureEffect(telemetryHooks()) followed by configureEffect(recordingHooks({ sink }))
944
- remove();
945
- ```
1357
+ Adds a layer of hooks for the whole process and returns a function that removes that layer only. Several configurations passed to one call form one layer. `configureEffect()` with no arguments removes every layer, and a call whose arguments are all `undefined` changes nothing. A configuration that is not an object, a key other than the three below, a `retry` key, and a hook that is not a function, `null` included, each throw a `TypeError` before anything is installed. See [Hooks](#hooks).
946
1358
 
947
- - `onRun(effect, pipeline, flowName)`: wraps the whole run. It must `await pipeline()` and return its result.
1359
+ - `onRun(effect, pipeline, flowName, initialInput)`: wraps the whole run once, retries included. It must `await pipeline()` and return its result. `initialInput` is what the flow was called with when `effectPipe` built it, and `undefined` otherwise; pass it on to any hook it calls.
948
1360
  - `onStep(name, type, op, path)`: wraps each Command, and each `Parallel` with `name` and `type` both `'Parallel'`. It must `await op()` and return its result, and pass `path` on to any hook it calls, since a replay matches steps on it.
949
1361
  - For a Command, `op()` returns a promise, even for a synchronous function. Returning a value without calling `op()` answers for the Command, which is how replay works, and throwing without calling it counts as the Command failing.
950
1362
  - A throw after `op()` succeeded, or `undefined` returned in place of its value, as a hook that forgot its `return` or its `await` does, is a bug in the hook: the run rejects, and `Retry` does not run the Command again.
951
- - For a `Parallel`, `op()` runs the branches, so a hook must call it or the run rejects with a `TypeError`. It returns which branch, if any, cancelled the others, as in `{ cancelled: true, branch: 0 }`, even when a branch threw.
952
- - `onBeforeCommand(command, context)`: runs before each Command. A throw vetoes the Command: the run returns a `Failure` carrying the thrown error, and `Retry` does not retry it.
953
-
954
- Layers run in the order they were installed, the first outermost, so a result or a thrown error unwinds from the innermost hook out:
955
-
956
- ```
957
- runEffect(flow(input))
958
- │
959
- ├─ telemetry.onRun first configuration: outermost
960
- │ └─ recording.onRun last configuration: innermost
961
- │ │
962
- │ │ for each Command:
963
- │ ├─ telemetry.onBeforeCommand interceptors all run, in the order given
964
- │ ├─ recording.onBeforeCommand
965
- │ ├─ telemetry.onStep
966
- │ │ └─ recording.onStep closest to the Command
967
- │ │ └─ cmd()
968
- │ │ ┌─ recording.onStep returns a result, or a thrown error, unwinds
969
- │ ├─ telemetry.onStep returns from the inside out
970
- │ │
971
- │ ┌─ recording.onRun returns
972
- ├─ telemetry.onRun returns
973
- ```
974
-
975
- **Per-call hooks.** The hooks in a `callConfig` are merged over the configured ones by the same rules, the configured wrappers outside and the configured `onBeforeCommand` hooks first. `inherit: false` leaves the configured hooks out. With configured hooks `C` and a call `K` that supplies only `onStep`:
976
-
977
- ```
978
- inherit: true (default) inherit: false
979
-
980
- onRun C.onRun (none)
981
- onBeforeCommand C.onBeforeCommand (none)
982
- onStep C.onStep( K.onStep( cmd ) ) K.onStep
983
- ```
984
-
985
- `recordEffect` inherits, so recording inside an application that already traces still produces spans. `replayEffect` passes `inherit: false` unless `hooks: true`.
1363
+ - For a `Parallel`, `op()` runs the branches, so a hook must call it or the run rejects with a `TypeError`. It returns which branch, if any, cancelled the others, and how many branches there were, as in `{ cancelled: true, branch: 0, branches: 2 }`, even when a branch threw, which adds `threw: true`.
1364
+ - `onBeforeCommand(command, context)`: runs before each Command. A throw vetoes the Command: the run returns a `Failure` carrying the thrown error, and `Retry` does not retry it. A vetoed Command leaves no entry in a trace, so a replay of that run fails where it was vetoed; see [Errors no branch returned](#errors-no-branch-returned).
986
1365
 
987
1366
  ### Recording and replay
988
1367
 
@@ -990,40 +1369,23 @@ onStep C.onStep( K.onStep( cmd ) ) K.onStep
990
1369
 
991
1370
  Returns `{ onStep, entries, toTrace }`, a hook that records every step of a run, passed as `runEffect(flow, context, { onStep })`. Give each run its own recorder: one shared by a whole application mixes requests into one trace, which a replay refuses. `recordEffect` and the [recording example](https://github.com/aycangulez/pure-effect/blob/main/examples/recording-example.js) both do this for you.
992
1371
 
993
- - `onStep`: the hook. Recording never changes a run's outcome; a value `redact` fails on is recorded as `'[redaction failed]'`.
1372
+ - `onStep`: the hook. Recording never changes a run's outcome.
994
1373
  - `entries`: the steps recorded so far, one per Command and one per `Parallel`. `path` is the step's position in the flow, which a replay matches on; an older entry with `error` and no `threw` still counts as a throw.
995
1374
 
996
1375
  ```text
997
- { command, path, result, durationMs } a Command that returned
998
- { command, path, threw: true, error, durationMs } a Command that threw
999
- { command: 'Parallel', path, result: { cancelled, branch } } which branch, if any, cancelled the others
1376
+ { command, path, result, durationMs } a Command that returned
1377
+ { command, path, threw: true, error, durationMs } a Command that threw
1378
+ { command: 'Parallel', path, result: { cancelled, branch, branches } } which branch, if any, cancelled the others,
1379
+ and how many branches there were
1380
+ { command, path, unrecorded, durationMs } a Command whose result or error could not be recorded,
1381
+ because 'redact' threw on it or the 'copy' failed
1000
1382
  ```
1001
1383
 
1002
- - `toTrace(meta)`: the entries as a trace, with `meta`'s `initialInput`, `context`, `flowName` and `version`, copied when it is called (a part that cannot be copied, such as a function, is kept as it is). If a Command can change the input or the context, as an ORM save that adds an id does, call it before the run for those and again afterwards for the entries, as `recordEffect` does.
1003
- - `options.redact(value, name, kind)`: returns what the trace stores in place of `value`. `kind` is `'result'`, `'error'`, `'initialInput'` or `'context'`, and `name` is the Command's name, or the kind. It gets a copy, so changing it in place is safe.
1384
+ - `toTrace(meta)`: the entries as a trace, with `meta`'s `initialInput`, `context`, `flowName` and `version`, copied into the form JSON stores when it is called. If a Command can change the input or the context, as an ORM save that adds an id does, call it before the run for those and again afterwards for the entries, as `recordEffect` does.
1385
+ - `options.redact(value, name, kind)`: returns what the trace stores in place of `value`. `kind` is `'result'`, `'error'`, `'initialInput'` or `'context'`, and `name` is the Command's name, or the kind. See [Keeping secrets out of a trace](#keeping-secrets-out-of-a-trace).
1004
1386
  - `options.maxEntries`: the most entries a trace keeps; the rest are counted in `dropped`, and a replay stops at the first step the trace lacks.
1005
1387
  - `options.stack`: record stack traces for thrown errors (off by default).
1006
-
1007
- Results are copied as they are recorded, so a later step cannot change them; see [Recording in Production](#recording-in-production) for what a copy keeps. When writing `redact`, check a value before replacing a field in it, since `{ ...value, email: '[redacted]' }` turns a `null` into an object and the replay takes the other branch:
1008
-
1009
- ```js
1010
- // Masks a field only where there is one, so a lookup that found nothing still records null.
1011
- const mask = (value, field) =>
1012
- value && typeof value === 'object' && field in value ? { ...value, [field]: '[redacted]' } : value;
1013
-
1014
- const redact = (value, name, kind) => {
1015
- if (kind === 'initialInput') return mask(value, 'cardNumber');
1016
- if (kind === 'context') return mask(value, 'authToken');
1017
- if (kind === 'error') return mask(value, 'attempted');
1018
- return name === 'cmdFetchUser' ? mask(value, 'email') : value;
1019
- };
1020
- recorder({ redact });
1021
-
1022
- assert.equal(redact(null, 'cmdFetchUser', 'result'), null); // still nothing found
1023
- assert.equal(redact('card_declined', 'cmdCharge', 'error'), 'card_declined'); // still a string
1024
- ```
1025
-
1026
- A replay rebuilds the flow from the redacted input and context, so a field a step checks, such as a password, needs a stand-in the check treats the same way, as the recording example in [Recording in Production](#recording-in-production) does, and a context field an `Ask` reads should stay.
1388
+ - A value `redact` throws on, or one JSON cannot hold, is left out and marked `unrecorded`, on its entry or, for the input and context, in the trace's `unrecorded`, as in `{ context: 'copy' }`. A replay stops there with a `ReplayError` rather than hand the flow a stand-in. See [Recording in Production](#recording-in-production) for what a copy keeps.
1027
1389
 
1028
1390
  #### `recordEffect(flowFn, initialInput, options?)`
1029
1391
 
@@ -1031,29 +1393,32 @@ Runs a flow for real while recording, returning `{ result, trace }`. Accepts `re
1031
1393
 
1032
1394
  #### `replayEffect(effect, traceOrResolver, options?)`
1033
1395
 
1034
- Runs a flow with each Command answered from a trace instead of run, and returns `{ result, unreached }`: the flow's outcome, and the recorded steps it never asked for, which is where a flow that stops early shows up. A flow that no longer matches the trace ends in a `Failure` whose `error` is a `TimeParadox`, or a `ReplayError` for a step the trace lacks. Neither is thrown, so a test checks `error.name`, which tells them apart, and not only `result.type`. A malformed trace rejects with a `ReplayError`.
1396
+ Runs a flow with each Command answered from a trace instead of run, and returns `{ result, unreached }`: the flow's outcome, and the recorded steps it never asked for. A flow that no longer matches the trace ends in a `Failure` whose `error` is a `TimeParadox`, or a `ReplayError` for a step the trace lacks; neither is thrown, so a test checks `error.name`. A malformed trace rejects with a `ReplayError`. See [Time-Travel Debugging](#time-travel-debugging).
1035
1397
 
1036
- - `traceOrResolver`: a trace, its bare entries, or a resolver, a function that answers each step with `{ result }`, `{ error }`, or `undefined` for a step it has no record of, so a trace stored in any shape can be replayed. With a resolver, `unreached` is absent, since a resolver cannot list what it holds. A resolver is also asked about each `Parallel`, with `step.type` set to `'Parallel'`: answering with the recorded cancellation as `{ result }` replays it as production decided, and anything else replays it by timing.
1037
- - `options.context`: the context for `Ask`, by default the one the trace recorded. A resolver has none, so pass one if the flow reads `Ask`.
1038
- - `options.onMissing`: `'throw'` (default) stops at a step the trace lacks. `'execute'` runs its Command for real, so use it only where Commands reach test doubles or only read. A trace can lack a step because a hook vetoed it in production, because it was added to the flow since the recording, or because the recorder dropped it under `maxEntries`; a trace that dropped entries refuses `'execute'`, so record the flow again with a higher `maxEntries`. After a flow changes shape, as when a Command is newly wrapped in `Retry`, every step sits at a new position and `'execute'` would run them all live: record the flow again instead.
1398
+ - `traceOrResolver`: a trace, its bare entries, or a resolver: a function that answers each step with `{ result }`, `{ error }`, or `undefined` for a step it has no record of. Any other answer, `null` included, or a throw from the resolver, rejects the replay. With a resolver, `unreached` is absent. See [Replaying from your own storage](#replaying-from-your-own-storage).
1399
+ - A resolver is also asked about each `Parallel`, with `step.type` set to `'Parallel'`: answering with the recorded cancellation as `{ result }` replays it as production decided, and anything else replays it by timing.
1400
+ - `options.context`: the context for `Ask`, by default the one the trace recorded. A resolver has none, so pass one if the flow reads `Ask`, and a trace whose context could not be recorded refuses to replay without one.
1401
+ - `options.onMissing`: `'throw'` (default) stops at a step the trace lacks; `'execute'` runs its Command for real, so use it only where Commands reach test doubles or only read. A trace that dropped entries refuses `'execute'`, and a flow that changed shape, as when a Command is newly wrapped in `Retry` or moved into a new `Parallel` branch, stops at a `TimeParadox` even under `'execute'`.
1039
1402
  - `options.fastRetry` (default `true`): strip `Retry` delays.
1040
1403
  - `options.hooks` (default `false`): run the replay inside the configured hooks, a configured recorder included, so they see the replayed steps. Off, a replay cannot reach a telemetry backend or a trace sink.
1041
1404
  - `options.onResolved(step, outcome)`: observes each replayed step. A throw stops the replay, and `replayEffect` rejects with it; it never changes an outcome.
1042
-
1043
- A trace whose entries have no `path`, written by hand or recorded before paths existed, is matched by position. That works for a sequential flow, and a `Parallel` step in such a trace is refused with a `ReplayError`, since the order branches finish in cannot tell them apart.
1405
+ - A trace whose entries have no `path`, written by hand or recorded before paths existed, is matched in order, and a Command inside a `Parallel` is refused with a `ReplayError`.
1044
1406
 
1045
1407
  #### `timeTravel(flowFn, traceLog, options?)`
1046
1408
 
1047
- Replays a trace and narrates each step with its recorded duration, naming any recorded steps that were never reached, and warning when the trace's `version` differs from `options.version` or when steps are named `'anonymous'`. Returns the flow's outcome; for the unreached entries as data, use `replayEffect`. Takes `options.context` to override the trace's, and `options.log` in place of `console.log`.
1409
+ Replays a trace and narrates each step with its recorded duration, naming any recorded steps that were never reached, and warning when the trace's `version` differs from `options.version` or when steps are named `'anonymous'`. Returns the flow's outcome; for the unreached entries as data, use `replayEffect`. A trace whose input could not be recorded is refused, since the flow is rebuilt from it. Takes `options.context` to override the trace's, and `options.log` in place of `console.log`.
1048
1410
 
1049
1411
  ## Limitations
1050
1412
 
1051
- - **`Retry` repeats everything it wraps, including a Command's `next`.** When a Command's function throws, every Command inside the `Retry` runs again, including the ones that already succeeded. If a retried Command's `next` continues the flow, everything after it is retried too. Give a retried Command the default `next` and continue in a later pipeline step, or make sure every Command it reaches is safe to run more than once. A `Failure` a step returned is not retried at all, so a function that catches its own error and returns it as a value is never retried: see [Which Errors Are Data](#which-errors-are-data).
1413
+ - **`Retry` repeats everything it wraps, including a Command's `next`.** Each attempt runs every Command inside the `Retry` again, the ones that already succeeded included, and a retried Command whose `next` continues the flow takes the rest of the flow with it. Wrap only the Command that fails, and continue in a later step, as [Retrying Transient Failures](#retrying-transient-failures) shows. A function that catches its own error is never retried; see [Which Errors Are Data](#which-errors-are-data).
1052
1414
  - **Cancelling a `Parallel` branch cannot stop everything.** A cancelled branch starts no new Commands, and a function that uses the `AbortSignal` it is given can be stopped while running. A function that ignores the signal runs to completion, so a branch whose _first_ Command is a write can still write after another branch has failed. So does a function that is never given the signal: one written as `(...args)` or `({ signal } = {})`, or wrapped by a helper that hides its parameters. `Parallel` waits for every branch to finish before returning, so no cancelled work is still running after the `Failure` is returned.
1053
- - **Inside a `Parallel`, a Command's function that takes a parameter gets the `AbortSignal` in it.** A function passed by name whose first parameter is optional but written without a default value takes the signal for it, so the same Command behaves differently inside a `Parallel` than outside one: `function listUsers(page) { page ??= 1; return db.users(page); }` gets the signal as its page. A parameter with a default value does not count, so `Command(nanoid)`, whose size is written `size = 21`, works everywhere. Wrap such a function, as in `Command(() => listUsers())`. In TypeScript, a function whose first parameter cannot be an `AbortSignal` does not compile as a Command.
1054
- - **A `Failure` carries everything.** It holds the full error and the `initialInput` that `effectPipe` attached, and neither is trimmed, because tests and debugging need both. `redact` keeps sensitive data out of a **trace**. Keeping it out of your **logs** is up to you: log `result.error` rather than the whole `Failure`. The same goes for the outcomes a settled `Parallel` passes to `next`, which can carry their branch's input; for a login or registration flow, that input holds credentials.
1055
- - **Replay checks the path, not the values.** Replaying an old trace cannot check a fix that changes what a flow computes, because every Command's result comes from the recording: the replay hands the step the value from before the fix, reports `Success`, and flags nothing. It can check a fix that changes which Commands run. A removed step shows up in `unreached` only if it was the last step the flow reached; removed from the middle, it shifts the later paths and the replay stops at a `TimeParadox`.
1056
- - **A trace keeps data, not objects.** Recorded results come back without their classes: a money object or a database entity as a plain object, a `Buffer` as a plain byte array, and an error inside a result without properties such as `code`. Through JSON, a `Date` also comes back as a string and a `Map` as `{}`. A flow whose `next` calls a method on a result, or branches on one of those properties, replays differently from production. Return plain data from Commands; see [Recording in Production](#recording-in-production).
1057
- - **Replay reproduces what one flow saw, not timing.** A stale read replays exactly. A race between two concurrent requests does not, because a trace records one flow. `Parallel` branches replay with the results each branch saw, and a cancelled `Parallel` with the branch that cancelled it, but not the order they ran in, so replay cannot settle a race between branches that share state.
1415
+ - **Inside a `Parallel`, a Command's function that takes a parameter gets the `AbortSignal` in it.** This catches a function passed by name whose first parameter is optional and has no default value. Inside a `Parallel` that parameter gets the signal, and outside one it gets nothing, so the same Command behaves differently in the two places: `function listUsers(page) { page ??= 1; return db.users(page); }` gets the signal as its page. A parameter with a default value does not count, so `Command(nanoid)`, whose size is written `size = 21`, works everywhere. Wrap such a function, as in `Command(() => listUsers())`. In TypeScript, a function whose first parameter cannot be an `AbortSignal` does not compile as a Command.
1416
+ - **`redact` covers a trace, not a result.** A `Failure` holds the full error, untrimmed, because tests and debugging need all of it, and an error can quote what a Command sent, as a database's duplicate-key error quotes the key. `redact` keeps sensitive data out of a **trace**. Keeping it out of your **logs** is up to you.
1417
+ - **Replay checks the path, not the values.** Every Command's result comes from the recording, so replaying an old trace cannot check a fix that changes what a flow computes, and a step removed from the middle of a flow stops the replay at a `TimeParadox` instead of showing in `unreached`; see [Time-Travel Debugging](#time-travel-debugging).
1418
+ - **A trace keeps data, not objects.** A result replays as JSON stores it, so a class instance comes back without its methods and a `Date` as a string, and a thrown error comes back as a plain `Error` with its class's name, so a flow that checks `instanceof TypeError` replays differently; check `error.name` instead. Return plain data from Commands; see [Recording in Production](#recording-in-production).
1419
+ - **Replay reproduces what one flow saw, not timing.** A stale read replays exactly. A race between two concurrent requests does not, because a trace records one flow. `Parallel` branches replay with the results each branch saw, and a cancelled `Parallel` with the branch that cancelled it, but not the order they ran in, so replay cannot settle a race between branches that share state. A generator flow in a branch a recorded cancellation stopped can run its `catch` and `finally` at a different step in a replay, since a trace marks where a branch stopped only by its Commands: one cancelled during a `Retry`'s wait, just before an `Ask`, or at a `Retry` or `Parallel` with no Command in it, replays as though it stopped at its next Command.
1058
1420
  - **Configuration belongs to one copy of the library.** `configureEffect` stores hooks in module state, so two copies of the library in one process (from a dual ESM and CJS setup, two versions in the dependency tree, or a worker thread) each have their own. Hooks configured in one do not apply to the other, and nothing warns you.
1059
1421
  - **A Command needs a name.** `meta.name` survives minification. `cmd.name` does not, unless the minifier is set to keep function names.
1422
+ - **A generator flow's body can run more than once,** and code in it that changes something outside it, such as a counter or a log line, does so again; see [What runs once, and what runs again](#what-runs-once-and-what-runs-again).
1423
+ - **A generator run keeps every step's result until it ends,** since running the body again needs them. A long loop that fetches large pages holds every page; write it as a pipeline whose `next` asks for the next page.
1424
+ - **A generator body's `finally` does not always run.** It does not run when a bug or a `TimeParadox` rejects the run. In a `Parallel` where one branch threw, another branch that stops for its own reason before the rejection reaches it may still run its `catch` and `finally`, depending on timing. A step in a body's `finally` is not supported: it runs when the body ends normally and is refused when a step stopped the body, but if an error is passing through the body when its `finally` reaches a step, and the flow is cancelled before that step starts, the error is lost. Put cleanup in a `try`/`finally` around `runEffect`.