The best way to control Claude Code, Codex and more from any computer or phone

main
ts 1,250 lines 44.3 KB
Raw
1 import * as Domain from "@alchemy.run/domain";
2 import { errorSchema } from "@alchemy.run/domain/ExternalSystem";
3 import { InMemory } from "@alchemy.run/domain/InMemory";
4 import {
5 type Checked,
6 type ProvideStep,
7 type RejectedStep,
8 type RepliedStep,
9 type Step,
10 Story,
11 type WhenStep,
12 } from "@alchemy.run/domain/Story";
13 import { describe, expect, it } from "@alchemy.run/test";
14 import * as Cause from "effect/Cause";
15 import * as DateTime from "effect/DateTime";
16 import * as Duration from "effect/Duration";
17 import * as Effect from "effect/Effect";
18 import * as Exit from "effect/Exit";
19 import * as Fiber from "effect/Fiber";
20 import * as Headers from "effect/http/Headers";
21 import * as Layer from "effect/Layer";
22 import * as Option from "effect/Option";
23 import * as Redacted from "effect/Redacted";
24 import * as RpcMiddleware from "effect/rpc/RpcMiddleware";
25 import * as Schema from "effect/Schema";
26 import * as Stream from "effect/Stream";
27
28 // A tiny counter domain exercising every concept the story runner supports.
29 class Incremented extends Domain.Event("Incremented", {
30 by: Schema.Number,
31 total: Schema.Number,
32 }) {}
33 class Capped extends Domain.Event("Capped") {}
34 class TooBig extends Domain.Rejection("TooBig", { max: Schema.Number }) {}
35 // Who is operating a counter: provided by middleware, read by `decide`.
36 class Operator extends Domain.RequestContext<Operator>()("Test/Operator", Schema.String) {}
37 class Unauthenticated extends Domain.Rejection("Unauthenticated") {}
38 class OperatorSession extends RpcMiddleware.Service<OperatorSession, { provides: Operator }>()(
39 "Test/OperatorSession",
40 { error: Unauthenticated },
41 ) {}
42 const OperatorSessionLive = Layer.succeed(OperatorSession, (effect, { headers }) =>
43 Option.match(Headers.get(headers, "x-operator"), {
44 onNone: () => Effect.fail(new Unauthenticated()),
45 onSome: (name) => Effect.provideService(effect, Operator, name),
46 }),
47 );
48
49 class WasReset extends Domain.Event("WasReset", { by: Schema.String }) {}
50 class NotAnOperator extends Domain.Rejection("NotAnOperator") {}
51 class ResetCounter extends Domain.Command("ResetCounter", {
52 target: Schema.String,
53 events: [WasReset],
54 rejects: [NotAnOperator],
55 reply: { total: Schema.Number },
56 middleware: [OperatorSession],
57 }) {}
58
59 /** Guests may not read counters. */
60 const notGuest = Effect.fn(function* () {
61 if ((yield* Operator) === "guest") return yield* new NotAnOperator();
62 });
63
64 class Increment extends Domain.Command("Increment", {
65 target: Schema.String,
66 input: { by: Schema.Number },
67 events: [Incremented],
68 rejects: [TooBig],
69 reply: { total: Schema.Number },
70 }) {}
71 class Cap extends Domain.Command("Cap", { target: Schema.String, events: [Capped] }) {}
72 class Reminded extends Domain.Event("Reminded") {}
73 /** Never rejects, so it can be scheduled. */
74 class Remind extends Domain.Command("Remind", { target: Schema.String, events: [Reminded] }) {}
75
76 class Counter extends Domain.Aggregate("Counter", {
77 id: Schema.String,
78 state: Schema.Struct({ total: Schema.Number, capped: Schema.Boolean }),
79 initial: { total: 0, capped: false },
80 commands: [Increment, Cap, ResetCounter, Remind],
81 decide: {
82 ResetCounter: Effect.fn(function* () {
83 const operator = yield* Operator;
84 if (operator === "guest") return yield* new NotAnOperator();
85 return [new WasReset({ by: operator })];
86 }),
87 Increment: (s, cmd) =>
88 cmd.by > 10
89 ? new TooBig({ max: 10 })
90 : [new Incremented({ by: cmd.by, total: s.total + cmd.by })],
91 Cap: (s) => (s.capped ? [] : [new Capped()]),
92 Remind: (s) => (s.capped ? [new Reminded()] : []),
93 },
94 evolve: {
95 Incremented: (s, e) => ({ ...s, total: e.total }),
96 Capped: (s) => ({ ...s, capped: true }),
97 WasReset: (s) => ({ ...s, total: 0 }),
98 Reminded: (s) => s,
99 },
100 reply: {
101 Increment: (s) => ({ total: s.total }),
102 ResetCounter: (s) => ({ total: s.total }),
103 },
104 read: {
105 middleware: [OperatorSession],
106 rejects: [NotAnOperator],
107 validate: () => notGuest(),
108 },
109 }) {}
110
111 class Totals extends Domain.View("Totals", {
112 from: [Counter],
113 key: Counter,
114 middleware: [OperatorSession],
115 rejects: [NotAnOperator],
116 state: Schema.Struct({ total: Schema.Number }),
117 initial: { total: 0 },
118 evolve: {
119 Incremented: (_, e) => ({ total: e.total }),
120 WasReset: () => ({ total: 0 }),
121 },
122 validate: () => notGuest(),
123 }) {}
124
125 class Logged extends Domain.Event("Logged", { by: Schema.Number }) {}
126
127 // A view without state that maps events.
128 class History extends Domain.View("History", {
129 from: [Counter],
130 key: Counter,
131 events: [Logged],
132 emit: { Incremented: (e) => new Logged({ by: e.by }) },
133 }) {}
134
135 // Moves between counters exercise named routes, view-to-view state and a
136 // policy listening to a view.
137 class Moved extends Domain.Event("Moved", {
138 from: Schema.String,
139 to: Schema.String,
140 amount: Schema.Number,
141 }) {}
142 class MakeMove extends Domain.Command("MakeMove", {
143 target: Schema.String,
144 input: { from: Schema.String, to: Schema.String, amount: Schema.Number },
145 events: [Moved],
146 }) {}
147 class Move extends Domain.Aggregate("Move", {
148 id: Schema.String,
149 state: Schema.Struct({}),
150 initial: {},
151 commands: [MakeMove],
152 decide: { MakeMove: (_, { from, to, amount }) => [new Moved({ from, to, amount })] },
153 evolve: { Moved: (s) => s },
154 }) {}
155
156 class Flowed extends Domain.Event("Flowed", {
157 direction: Schema.Literals(["in", "out"]),
158 amount: Schema.Number,
159 }) {}
160
161 class Flows extends Domain.View("Flows", {
162 from: [Move],
163 key: Counter,
164 keyOf: {
165 Moved: {
166 out: ({ event }) => Counter.ref(event.from),
167 in: ({ event }) => Counter.ref(event.to),
168 },
169 },
170 state: Schema.Struct({ balance: Schema.Number }),
171 initial: { balance: 0 },
172 evolve: {
173 Moved: {
174 out: (s, e) => ({ balance: s.balance - e.amount }),
175 in: (s, e) => ({ balance: s.balance + e.amount }),
176 },
177 },
178 events: [Flowed],
179 emit: {
180 Moved: {
181 out: (e) => new Flowed({ direction: "out", amount: e.amount }),
182 in: (e) => new Flowed({ direction: "in", amount: e.amount }),
183 },
184 },
185 }) {}
186
187 // Consumes Flows' events with Flows' state after each.
188 class Rich extends Domain.View("Rich", {
189 from: [Flows],
190 key: Counter,
191 state: Schema.Struct({ rich: Schema.Boolean }),
192 initial: { rich: false },
193 evolve: { Flows: (_, __, { state }) => ({ rich: (state?.balance ?? 0) >= 100 }) },
194 }) {}
195
196 class CapWhenOverdrawn extends Domain.Policy("CapWhenOverdrawn", { from: Flows, on: [Flowed] }) {}
197 const CapWhenOverdrawnLive = CapWhenOverdrawn.toLayer(
198 Effect.gen(function* () {
199 const counters = yield* Counter;
200 return Effect.fn(function* ({ source, state }) {
201 if (state && state.balance < 0) yield* counters.send(source, new Cap());
202 });
203 }),
204 );
205
206 class ApprovalUnavailable extends Domain.Rejection("ApprovalUnavailable") {}
207
208 class Approval extends Domain.ExternalSystem("Approval", {
209 check: {
210 args: { total: Schema.Number },
211 success: { ok: Schema.Boolean },
212 error: ApprovalUnavailable,
213 },
214 }) {}
215
216 class CapWhenLarge extends Domain.Policy("CapWhenLarge", { from: Counter, on: [Incremented] }) {}
217 const CapWhenLargeLive = CapWhenLarge.toLayer(
218 Effect.gen(function* () {
219 const approval = yield* Approval;
220 const counters = yield* Counter;
221 return Effect.fn(function* ({ source, event }) {
222 if (event.total < 15) return;
223 // Without an answer, the counter stays uncapped.
224 const ok = yield* approval.check({ total: event.total }).pipe(
225 Effect.map(({ ok }) => ok),
226 Effect.catchTag("ApprovalUnavailable", () => Effect.succeed(false)),
227 );
228 if (ok) yield* counters.send(source, new Cap());
229 });
230 }),
231 );
232
233 // An hour after a counter is capped, remind someone.
234 class RemindWhenCapped extends Domain.Policy("RemindWhenCapped", { from: Counter, on: [Capped] }) {}
235 const RemindWhenCappedLive = RemindWhenCapped.toLayer(
236 Effect.gen(function* () {
237 const counters = yield* Counter;
238 return Effect.fn(function* ({ source }) {
239 yield* counters
240 .schedule(source, new Remind(), { after: "1 hour" })
241 .pipe(Effect.catchTag("AlreadyExecuted", () => Effect.void));
242 });
243 }),
244 );
245
246 class Counters extends Domain.Model("Counters", {
247 aggregates: [Counter, Move],
248 views: [Totals, History, Flows, Rich],
249 policies: [CapWhenLarge, CapWhenOverdrawn, RemindWhenCapped],
250 }) {}
251
252 const story = Story.make(Counters, {
253 layer: Layer.mergeAll(CapWhenLargeLive, CapWhenOverdrawnLive, RemindWhenCappedLive),
254 stub: [Approval],
255 });
256
257 // Approval called for real, through an adapter: 20 and over is unavailable,
258 // 17 breaks the connection, 19 answers slowly, and even totals are approved.
259 const ApprovalAdapter = Approval.toLayer(
260 Effect.succeed({
261 check: ({ total }) =>
262 total >= 20
263 ? Effect.fail(new ApprovalUnavailable())
264 : total === 17
265 ? Effect.die(new Error("socket closed"))
266 : Effect.succeed({ ok: total % 2 === 0 }).pipe(
267 Effect.delay(total === 19 ? "50 millis" : "0 millis"),
268 ),
269 }),
270 );
271 const unstubbed = Story.make(Counters, {
272 layer: Layer.mergeAll(CapWhenLargeLive, CapWhenOverdrawnLive, RemindWhenCappedLive),
273 });
274 const real = (...steps: ReadonlyArray<Step>) =>
275 unstubbed(...steps).pipe(Effect.provide(ApprovalAdapter));
276
277 // A system that is not stubbed must be provided as a Layer.
278 // @ts-expect-error Approval is not provided
279 export const unprovided: Effect.Effect<void, unknown, never> = unstubbed();
280
281 // Each step is checked against the last command: `rejected` takes only a
282 // rejection it declares, `replied` only its reply type, and a command whose
283 // middleware provides a service needs a `provide` step for it first.
284 export const typed = () => [
285 story(Story.when(c1, new Increment({ by: 11 })), Story.rejected(new TooBig({ max: 10 }))),
286 story(Story.when(c1, new Increment({ by: 1 })), Story.replied({ total: 1 })),
287 story(Story.provide(Operator, "sam"), Story.when(c1, new ResetCounter())),
288 // @ts-expect-error Increment does not reject with NotAnOperator
289 story(Story.when(c1, new Increment({ by: 1 })), Story.rejected(new NotAnOperator())),
290 // @ts-expect-error Increment replies with a number total
291 story(Story.when(c1, new Increment({ by: 1 })), Story.replied({ total: "1" })),
292 // @ts-expect-error Cap declares no reply
293 story(Story.when(c1, new Cap()), Story.replied({ total: 1 })),
294 // @ts-expect-error ResetCounter's middleware provides Operator, and no step does
295 story(Story.when(c1, new ResetCounter())),
296 // A step typed as a plain Step may be a `provide`, so it turns the checks off.
297 story(Story.provide(Operator, "sam") as Step, Story.when(c1, new ResetCounter())),
298 ];
299
300 // The type error names the mistake on the step that makes it.
301 export const messages: [
302 Checked<[WhenStep<typeof Increment>, RejectedStep<NotAnOperator>]>[1],
303 Checked<[WhenStep<typeof Cap>, RepliedStep<{ total: number }>]>[1],
304 Checked<[WhenStep<typeof ResetCounter>]>[0],
305 Checked<[ProvideStep<Operator>, WhenStep<typeof ResetCounter>]>[1],
306 ] = [
307 "Increment does not reject with NotAnOperator",
308 "Cap declares no reply",
309 "ResetCounter needs Story.provide(Test/Operator) before it",
310 Story.when(Counter.ref("c-1"), new ResetCounter()),
311 ];
312
313 const c1 = Counter.ref("c-1");
314 const c2 = Counter.ref("c-2");
315 const m1 = Move.ref("m-1");
316
317 describe("Domain Story", { tags: ["unit", "local"] }, () => {
318 it.effect("decides, evolves, replies and projects", () =>
319 story(
320 Story.given(c1, new Incremented({ by: 2, total: 2 })),
321 Story.when(c1, new Increment({ by: 3 })),
322 Story.then(c1, new Incremented({ by: 3, total: 5 })),
323 Story.replied({ total: 5 }),
324 Story.view(Totals, c1, { total: 5 }),
325 Story.emitted(History, c1, [{ by: 2 }, { by: 3 }]),
326 ),
327 );
328
329 it.effect("asserts part of an aggregate's state", () =>
330 story(
331 Story.given(c1, new Incremented({ by: 2, total: 2 })),
332 Story.state(c1, { total: 2 }),
333 Story.state(c1, { total: 2, capped: false }),
334 ),
335 );
336
337 it.effect("a partial state that does not match fails", () =>
338 story(
339 Story.given(c1, new Incremented({ by: 2, total: 2 })),
340 Story.state(c1, { total: 3 }),
341 ).pipe(
342 Effect.flip,
343 Effect.map((failure) =>
344 expect(String((failure as any).message)).toContain(
345 'Counter/c-1\n expected {"total":3}\n actual {"total":2,"capped":false}',
346 ),
347 ),
348 ),
349 );
350
351 it.effect("asserts rejections", () =>
352 story(
353 Story.when(c1, new Increment({ by: 11 })),
354 Story.rejected(new TooBig({ max: 10 })),
355 Story.then(c1),
356 ),
357 );
358
359 it.effect("suspends a policy on an external system call until it is answered", () =>
360 story(
361 Story.given(c1, new Incremented({ by: 10, total: 10 })),
362 Story.when(c1, new Increment({ by: 6 })),
363 Story.call(Approval.check, { total: 16 }),
364 Story.then(c1, new Incremented({ by: 6, total: 16 })),
365 Story.succeed(Approval.check, { ok: true }),
366 Story.then(c1, new Capped()),
367 Story.state(c1, (s) => expect(s.capped).toBe(true)),
368 ),
369 );
370
371 it.effect("answers two pending calls by tag, in any order", () =>
372 story(
373 Story.given(c1, new Incremented({ by: 10, total: 10 })),
374 Story.given(c2, new Incremented({ by: 10, total: 10 })),
375 Story.when(c1, new Increment({ by: 6 })),
376 Story.when(c2, new Increment({ by: 10 })),
377 Story.call("c1", Approval.check, { total: 16 }),
378 Story.call("c2", Approval.check, { total: 20 }),
379 Story.succeed("c2", Approval.check, { ok: false }),
380 Story.succeed("c1", Approval.check, { ok: true }),
381 Story.then(c1, new Incremented({ by: 6, total: 16 }), new Capped()),
382 Story.then(c2, new Incremented({ by: 10, total: 20 })),
383 ),
384 );
385
386 it.effect("tags identical calls in the order they were made", () =>
387 story(
388 Story.given(c1, new Incremented({ by: 10, total: 10 })),
389 Story.given(c2, new Incremented({ by: 10, total: 10 })),
390 Story.when(c1, new Increment({ by: 6 })),
391 Story.when(c2, new Increment({ by: 6 })),
392 Story.call("c1", Approval.check, { total: 16 }),
393 Story.call("c2", Approval.check, { total: 16 }),
394 Story.succeed("c1", Approval.check, { ok: false }),
395 Story.succeed("c2", Approval.check, { ok: true }),
396 Story.then(c1, new Incremented({ by: 6, total: 16 })),
397 Story.then(c2, new Incremented({ by: 6, total: 16 }), new Capped()),
398 ),
399 );
400
401 it.effect("fails a pending call with the operation's declared error", () =>
402 story(
403 Story.given(c1, new Incremented({ by: 10, total: 10 })),
404 Story.when(c1, new Increment({ by: 6 })),
405 Story.call(Approval.check, { total: 16 }),
406 Story.fail(Approval.check, new ApprovalUnavailable()),
407 Story.then(c1, new Incremented({ by: 6, total: 16 })),
408 Story.state(c1, (s) => expect(s.capped).toBe(false)),
409 ),
410 );
411
412 it.effect("a pending call that dies fails the policy", () =>
413 story(
414 Story.given(c1, new Incremented({ by: 10, total: 10 })),
415 Story.when(c1, new Increment({ by: 6 })),
416 Story.call("c1", Approval.check, { total: 16 }),
417 Story.die("c1", Approval.check, new Error("socket closed")),
418 ).pipe(
419 Effect.flip,
420 Effect.map((failure) =>
421 expect(String((failure as any).message)).toMatch(
422 /a policy or projection failed: .*socket closed/,
423 ),
424 ),
425 ),
426 );
427
428 it.effect("an answer the success schema rejects fails the policy", () =>
429 story(
430 Story.given(c1, new Incremented({ by: 10, total: 10 })),
431 Story.when(c1, new Increment({ by: 6 })),
432 Story.call(Approval.check, { total: 16 }),
433 Story.succeed(Approval.check, { ok: "yes" } as never),
434 ).pipe(
435 Effect.flip,
436 Effect.map((failure) =>
437 expect(String((failure as any).message)).toMatch(
438 /a policy or projection failed: .*Approval\.check returned a value its success schema rejects/s,
439 ),
440 ),
441 ),
442 );
443
444 it.effect("asserts what a real call was sent and returned", () =>
445 real(
446 Story.given(c1, new Incremented({ by: 10, total: 10 })),
447 Story.when(c1, new Increment({ by: 6 })),
448 Story.call(Approval.check, { total: 16 }),
449 Story.returned(Approval.check, { ok: true }),
450 Story.then(c1, new Incremented({ by: 6, total: 16 }), new Capped()),
451 ),
452 );
453
454 it.effect("asserts a real call's declared error", () =>
455 real(
456 Story.given(c1, new Incremented({ by: 10, total: 10 })),
457 Story.when(c1, new Increment({ by: 10 })),
458 Story.call(Approval.check, { total: 20 }),
459 Story.failed(Approval.check, new ApprovalUnavailable()),
460 Story.then(c1, new Incremented({ by: 10, total: 20 })),
461 ),
462 );
463
464 it.effect("asserts that a real call died", () =>
465 real(
466 Story.given(c1, new Incremented({ by: 10, total: 10 })),
467 Story.when(c1, new Increment({ by: 7 })),
468 Story.call("c1", Approval.check, { total: 17 }),
469 Story.died("c1", Approval.check),
470 ).pipe(
471 Effect.flip,
472 // The policy did not handle the defect, so the story still fails on it.
473 Effect.map((failure) =>
474 expect(String((failure as any).message)).toMatch(/a policy or projection failed/),
475 ),
476 ),
477 );
478
479 it.live("waits for a slow real call", () =>
480 real(
481 Story.given(c1, new Incremented({ by: 10, total: 10 })),
482 Story.when(c1, new Increment({ by: 9 })),
483 Story.call(Approval.check, { total: 19 }),
484 Story.returned(Approval.check, { ok: false }),
485 Story.then(c1, new Incremented({ by: 9, total: 19 })),
486 ),
487 );
488
489 it.effect("a real call returning something else fails", () =>
490 real(
491 Story.given(c1, new Incremented({ by: 10, total: 10 })),
492 Story.when(c1, new Increment({ by: 6 })),
493 Story.call(Approval.check, { total: 16 }),
494 Story.returned(Approval.check, { ok: false }),
495 ).pipe(
496 Effect.flip,
497 Effect.map((failure) =>
498 expect(String((failure as any).message)).toContain(
499 'expected {"_tag":"Success","value":{"ok":false}}',
500 ),
501 ),
502 ),
503 );
504
505 it.effect("a real call no step asserts fails the story", () =>
506 real(
507 Story.given(c1, new Incremented({ by: 10, total: 10 })),
508 Story.when(c1, new Increment({ by: 6 })),
509 Story.call(Approval.check, { total: 16 }),
510 ).pipe(
511 Effect.flip,
512 Effect.map((failure) =>
513 expect(String((failure as any).message)).toContain(
514 "real external system calls no step asserts",
515 ),
516 ),
517 ),
518 );
519
520 it.effect("answering a call no call step checked fails", () =>
521 story(
522 Story.given(c1, new Incremented({ by: 10, total: 10 })),
523 Story.when(c1, new Increment({ by: 6 })),
524 Story.succeed(Approval.check, { ok: true }),
525 ).pipe(
526 Effect.flip,
527 Effect.map((failure) =>
528 expect(String((failure as any).message)).toContain(
529 'Approval.check({"total":16}) is answered before a call step checks its arguments',
530 ),
531 ),
532 ),
533 );
534
535 it.effect("asserting a real call no call step checked fails", () =>
536 real(
537 Story.given(c1, new Incremented({ by: 10, total: 10 })),
538 Story.when(c1, new Increment({ by: 6 })),
539 Story.returned(Approval.check, { ok: true }),
540 ).pipe(
541 Effect.flip,
542 Effect.map((failure) =>
543 expect(String((failure as any).message)).toContain(
544 'Approval.check({"total":16}) is asserted before a call step checks its arguments',
545 ),
546 ),
547 ),
548 );
549
550 it.effect("an untagged succeed with several pending calls fails", () =>
551 story(
552 Story.given(c1, new Incremented({ by: 10, total: 10 })),
553 Story.given(c2, new Incremented({ by: 10, total: 10 })),
554 Story.when(c1, new Increment({ by: 6 })),
555 Story.when(c2, new Increment({ by: 6 })),
556 Story.succeed(Approval.check, { ok: true }),
557 ).pipe(
558 Effect.flip,
559 Effect.map((failure) =>
560 expect(String((failure as any).message)).toContain("2 pending calls to Approval.check"),
561 ),
562 ),
563 );
564
565 it.effect("answering a tag no call has fails", () =>
566 story(
567 Story.given(c1, new Incremented({ by: 10, total: 10 })),
568 Story.when(c1, new Increment({ by: 6 })),
569 Story.call("c1", Approval.check, { total: 16 }),
570 Story.succeed("c3", Approval.check, { ok: true }),
571 ).pipe(
572 Effect.flip,
573 Effect.map((failure) =>
574 expect(String((failure as any).message)).toContain(
575 'no pending call is named "c3"; named: "c1"',
576 ),
577 ),
578 ),
579 );
580
581 it.effect("fails on an unasserted rejection", () =>
582 story(Story.when(c1, new Increment({ by: 99 }))).pipe(
583 Effect.flip,
584 Effect.map((failure) => expect(String((failure as any).message)).toContain("TooBig")),
585 ),
586 );
587
588 it.effect("fails on an unanswered external system call", () =>
589 story(
590 Story.given(c1, new Incremented({ by: 10, total: 10 })),
591 Story.when(c1, new Increment({ by: 9 })),
592 ).pipe(
593 Effect.flip,
594 Effect.map((failure) =>
595 expect(String((failure as any).message)).toContain("unanswered external system calls"),
596 ),
597 ),
598 );
599
600 it.effect("routes one event to two keys, each with its own handlers", () =>
601 story(
602 Story.when(m1, new MakeMove({ from: "c-1", to: "c-2", amount: 30 })),
603 Story.then(m1, new Moved({ from: "c-1", to: "c-2", amount: 30 })),
604 Story.view(Flows, c1, { balance: -30 }),
605 Story.view(Flows, c2, { balance: 30 }),
606 Story.emitted(Flows, c1, [{ direction: "out", amount: 30 }]),
607 Story.emitted(Flows, c2, (entries) => {
608 expect(entries.map((e) => e.event.direction)).toEqual(["in"]);
609 expect(entries[0]!.state).toEqual({ balance: 30 });
610 }),
611 // A policy listening to a view receives the view's state.
612 Story.then(c1, new Capped()),
613 Story.then(c2),
614 ),
615 );
616
617 it.effect("a view consumes another view's events with its state", () =>
618 story(
619 Story.given(m1, new Moved({ from: "c-1", to: "c-2", amount: 120 })),
620 Story.view(Rich, c2, { rich: true }),
621 Story.view(Rich, c1, { rich: false }),
622 ),
623 );
624
625 it.effect("history reaches views but never policies", () =>
626 story(
627 Story.given(m1, new Moved({ from: "c-1", to: "c-2", amount: 30 })),
628 Story.view(Flows, c1, { balance: -30 }),
629 Story.then(c1),
630 ),
631 );
632
633 it.effect("decide reads the context its command's middleware provides", () =>
634 story(
635 Story.given(c1, new Incremented({ by: 4, total: 4 })),
636 Story.provide(Operator, "sam"),
637 Story.when(c1, new ResetCounter()),
638 Story.then(c1, new WasReset({ by: "sam" })),
639 Story.replied({ total: 0 }),
640 Story.provide(Operator, "guest"),
641 Story.when(c1, new ResetCounter()),
642 Story.rejected(new NotAnOperator()),
643 ),
644 );
645
646 it.effect("a command without its context fails", () =>
647 // @ts-expect-error ResetCounter's middleware provides Operator, and no step does
648 story(Story.when(c1, new ResetCounter())).pipe(
649 Effect.flip,
650 Effect.map((failure) => expect(String(failure)).toContain("Test/Operator")),
651 Effect.catchDefect((defect) =>
652 Effect.sync(() => expect(String(defect)).toContain("Test/Operator")),
653 ),
654 ),
655 );
656
657 it.live("an Api exposes a command; its middleware provides the context", () =>
658 Effect.gen(function* () {
659 class CounterApi extends Domain.Api("CounterApi", {
660 model: Counters,
661 commands: ["ResetCounter"],
662 }) {}
663 const client = yield* CounterApi.clientInProcess;
664 const counters = yield* Counter;
665 yield* counters.send(c1, new Increment({ by: 3 }));
666 const reset = yield* client.ResetCounter(
667 "c-1",
668 {},
669 { headers: Headers.fromInput({ "x-operator": "sam" }) },
670 );
671 expect(reset).toEqual({ reply: { total: 0 }, stream: "Counter/c-1", version: 2 });
672 const denied = yield* client
673 .ResetCounter("c-1", {}, { headers: Headers.fromInput({ "x-operator": "guest" }) })
674 .pipe(Effect.flip);
675 expect(denied._tag).toBe("NotAnOperator");
676 const anonymous = yield* client.ResetCounter("c-1").pipe(Effect.flip);
677 expect(anonymous._tag).toBe("Unauthenticated");
678 }).pipe(
679 Effect.scoped,
680 Effect.provide(
681 Layer.mergeAll(
682 OperatorSessionLive,
683 Counters.layer(
684 Layer.mergeAll(CapWhenLargeLive, CapWhenOverdrawnLive, RemindWhenCappedLive),
685 ),
686 ).pipe(
687 Layer.provide(
688 Layer.mergeAll(
689 InMemory,
690 Approval.toLayer(Effect.succeed({ check: () => Effect.succeed({ ok: false }) })),
691 ),
692 ),
693 ),
694 ),
695 ),
696 );
697
698 it.live("an Api exposes views and aggregates; validate judges every read", () =>
699 Effect.gen(function* () {
700 class CounterApi extends Domain.Api("CounterApi", {
701 model: Counters,
702 commands: ["ResetCounter"],
703 views: ["Totals"],
704 aggregates: ["Counter"],
705 }) {}
706 const client = yield* CounterApi.clientInProcess;
707 const counters = yield* Counter;
708 const sam = { headers: Headers.fromInput({ "x-operator": "sam" }) };
709 const guest = { headers: Headers.fromInput({ "x-operator": "guest" }) };
710
711 const receipt = yield* counters.send(c1, new Increment({ by: 3 }));
712 const atLeast = { stream: receipt.stream, version: receipt.version };
713 expect(yield* client.Totals.get("c-1", { ...sam, atLeast })).toEqual({ total: 3 });
714 // The client's filter only narrows what a permitted read returns.
715 expect(
716 yield* client.Totals.get("c-1", { ...sam, atLeast, where: { total: { gt: 10 } } }),
717 ).toBeNull();
718 expect((yield* client.Totals.get("c-1", guest).pipe(Effect.flip))._tag).toBe("NotAnOperator");
719 // A snapshot is judged like a get, and its filter narrows the same way.
720 expect(yield* client.Totals.snapshot("c-1", { ...sam, atLeast })).toEqual({
721 state: { total: 3 },
722 cursor: 1,
723 });
724 expect(
725 (yield* client.Totals.snapshot("c-1", { ...sam, where: { total: { gt: 10 } } })).state,
726 ).toBeNull();
727 expect((yield* client.Totals.snapshot("c-1", guest).pipe(Effect.flip))._tag).toBe(
728 "NotAnOperator",
729 );
730 expect((yield* client.Totals.list("c-1", guest).pipe(Effect.flip))._tag).toBe(
731 "NotAnOperator",
732 );
733 expect(yield* client.Counter.get("c-1", sam)).toEqual({ total: 3, capped: false });
734 expect((yield* client.Counter.get("c-1", guest).pipe(Effect.flip))._tag).toBe(
735 "NotAnOperator",
736 );
737
738 // A read without a session fails with the middleware's error, and the client's type has it.
739 const anonymous = [
740 yield* client.Totals.get("c-1").pipe(
741 Effect.catchTag("Unauthenticated", (e) => Effect.succeed(e._tag)),
742 ),
743 yield* client.Totals.watch("c-1").pipe(
744 Stream.runCollect,
745 Effect.catchTag("Unauthenticated", (e) => Effect.succeed(e._tag)),
746 ),
747 yield* client.Counter.get("c-1").pipe(
748 Effect.catchTag("Unauthenticated", (e) => Effect.succeed(e._tag)),
749 ),
750 yield* client.Counter.watch("c-1").pipe(
751 Stream.runCollect,
752 Effect.catchTag("Unauthenticated", (e) => Effect.succeed(e._tag)),
753 ),
754 ];
755 expect(anonymous).toEqual(Array(4).fill("Unauthenticated"));
756
757 // A watch sees the current state, then each change.
758 const totals = yield* client.Totals.watch("c-1", sam).pipe(
759 Stream.take(2),
760 Stream.runCollect,
761 Effect.forkChild,
762 );
763 const states = yield* client.Counter.watch("c-1", sam).pipe(
764 Stream.take(2),
765 Stream.runCollect,
766 Effect.forkChild,
767 );
768 yield* Effect.sleep("20 millis");
769 yield* counters.send(c1, new Increment({ by: 2 }));
770 expect(yield* Fiber.join(totals)).toEqual([
771 { state: { total: 3 }, cursor: 1 },
772 { state: { total: 5 }, cursor: 2 },
773 ]);
774 expect((yield* Fiber.join(states)).map(({ state }) => state.total)).toEqual([3, 5]);
775
776 const events = yield* client.Counter.events("c-1", sam).pipe(
777 Stream.filter(Domain.Read.isEvent),
778 Stream.take(2),
779 Stream.runCollect,
780 );
781 expect(events.map((e) => e.event._tag)).toEqual(["Incremented", "Incremented"]);
782 }).pipe(
783 Effect.scoped,
784 Effect.provide(
785 Layer.mergeAll(
786 OperatorSessionLive,
787 Counters.layer(
788 Layer.mergeAll(CapWhenLargeLive, CapWhenOverdrawnLive, RemindWhenCappedLive),
789 ),
790 ).pipe(
791 Layer.provide(
792 Layer.mergeAll(
793 InMemory,
794 Approval.toLayer(Effect.succeed({ check: () => Effect.succeed({ ok: false }) })),
795 ),
796 ),
797 ),
798 ),
799 ),
800 );
801
802 it.effect("a failed then reports every step and the events so far", () =>
803 story(
804 Story.clock("2026-03-01T09:00:00Z"),
805 Story.given(c1, new Incremented({ by: 2, total: 2 })),
806 Story.when(c1, new Increment({ by: 3 })),
807 Story.then(c1, new Incremented({ by: 4, total: 6 })),
808 Story.replied({ total: 6 }),
809 ).pipe(
810 Effect.flip,
811 Effect.map((failure) => {
812 expect(failure.step).toBe(4);
813 expect(failure.reason).toContain("Then: on Counter/c-1");
814 expect(failure.message).toBe(
815 [
816 failure.reason,
817 "",
818 " ✓ 1 Clock 2026-03-01T09:00:00.000Z",
819 " ✓ 2 Given Counter/c-1: Incremented { by: 2, total: 2 }",
820 " ✓ 3 When Counter/c-1: Increment { by: 3 }",
821 " ✗ 4 Then Counter/c-1: expected Incremented { by: 4, total: 6 }",
822 " got Incremented { by: 3, total: 5 }",
823 " 5 Replied { total: 6 }",
824 " events so far",
825 " Counter/c-1: Incremented → Incremented",
826 ].join("\n"),
827 );
828 expect(failure.steps.map((s) => s.status)).toEqual([
829 "passed",
830 "passed",
831 "passed",
832 "failed",
833 "not-run",
834 ]);
835 expect(failure.events).toEqual({ "Counter/c-1": ["Incremented", "Incremented"] });
836 }),
837 ),
838 );
839
840 it.effect("an unasserted rejection is marked on its command", () =>
841 story(
842 Story.given(c1, new Incremented({ by: 2, total: 2 })),
843 Story.when(c1, new Increment({ by: 99 })),
844 Story.then(c1),
845 ).pipe(
846 Effect.flip,
847 Effect.map((failure) =>
848 expect(failure.message).toBe(
849 [
850 "the command was rejected with TooBig, which no step asserts",
851 "",
852 " ✓ 1 Given Counter/c-1: Incremented { by: 2, total: 2 }",
853 " ✗ 2 When Counter/c-1: Increment { by: 99 }",
854 " rejected TooBig { max: 10 }",
855 " 3 Then Counter/c-1: nothing new",
856 " events so far",
857 " Counter/c-1: Incremented",
858 ].join("\n"),
859 ),
860 ),
861 ),
862 );
863
864 it.effect("a wrong rejection shows what was expected and what came", () =>
865 story(Story.when(c1, new Increment({ by: 99 })), Story.rejected(new TooBig({ max: 5 }))).pipe(
866 Effect.flip,
867 Effect.map((failure) =>
868 expect(failure.message.split("\n\n")[1]).toBe(
869 [
870 " ✓ 1 When Counter/c-1: Increment { by: 99 }",
871 " ✗ 2 Rejected expected TooBig { max: 5 }",
872 " got TooBig { max: 10 }",
873 " events so far",
874 " Counter/c-1: nothing",
875 ].join("\n"),
876 ),
877 ),
878 ),
879 );
880
881 it.effect("a view that emits an event it does not declare fails with a DefinitionError", () => {
882 class Loud extends Domain.View("Loud", {
883 from: [Counter],
884 key: Counter,
885 events: [Logged],
886 emit: { Incremented: () => new Capped() as never },
887 }) {}
888 class Louds extends Domain.Model("Louds", { aggregates: [Counter], views: [Loud] }) {}
889 return Story.make(Louds)(Story.when(c1, new Increment({ by: 1 }))).pipe(
890 Effect.flip,
891 Effect.map((failure) => {
892 expect(failure._tag).toBe("StoryFailure");
893 expect(failure.reason).toContain(
894 "DefinitionError: Loud emitted 'Capped', which it does not declare in events",
895 );
896 }),
897 );
898 });
899
900 it.effect("a failed policy is marked on the step that ran it", () => {
901 class Boom extends Domain.Policy("Boom", { from: Counter, on: [Capped] }) {}
902 class Breaks extends Domain.Model("Breaks", { aggregates: [Counter], policies: [Boom] }) {}
903 const breaks = Story.make(Breaks, {
904 layer: Boom.toLayer(Effect.succeed(() => Effect.die(new Error("boom")))),
905 });
906 return breaks(
907 Story.when(c1, new Increment({ by: 1 })),
908 Story.when(c1, new Cap()),
909 Story.then(c1, new Incremented({ by: 1, total: 1 }), new Capped()),
910 ).pipe(
911 Effect.flip,
912 Effect.map((failure) => {
913 expect(failure.step).toBe(2);
914 expect(failure.reason).toContain("a policy or projection failed");
915 expect(failure.reason).toContain("boom");
916 expect(failure.message.split("\n\n").at(-1)).toBe(
917 [
918 " ✓ 1 When Counter/c-1: Increment { by: 1 }",
919 " ✗ 2 When Counter/c-1: Cap",
920 " 3 Then Counter/c-1: Incremented { by: 1, total: 1 }, Capped",
921 " events so far",
922 " Counter/c-1: Incremented → Capped",
923 ].join("\n"),
924 );
925 }),
926 );
927 });
928
929 it.effect("a report never prints a redacted value", () => {
930 class Keyed extends Domain.Event("Keyed", { secret: Schema.Redacted(Schema.String) }) {}
931 class SetKey extends Domain.Command("SetKey", {
932 target: Schema.String,
933 input: { secret: Schema.Redacted(Schema.String) },
934 events: [Keyed],
935 }) {}
936 class Lock extends Domain.Aggregate("Lock", {
937 id: Schema.String,
938 state: Schema.Struct({}),
939 initial: {},
940 commands: [SetKey],
941 decide: { SetKey: (_, { secret }) => [new Keyed({ secret })] },
942 evolve: { Keyed: (s) => s },
943 }) {}
944 class Locks extends Domain.Model("Locks", { aggregates: [Lock] }) {}
945 const lock = Lock.ref("l-1");
946 return Story.make(Locks)(
947 Story.when(lock, new SetKey({ secret: Redacted.make("hunter2") })),
948 Story.then(lock, new Keyed({ secret: Redacted.make("swordfish") })),
949 ).pipe(
950 Effect.flip,
951 Effect.map((failure) => {
952 expect(failure.message).not.toContain("hunter2");
953 expect(failure.message).not.toContain("swordfish");
954 expect(failure.message).toContain(
955 " ✗ 2 Then Lock/l-1: expected Keyed { secret: <redacted> }",
956 );
957 }),
958 );
959 });
960
961 it.effect("fails on a committed event no step asserts", () =>
962 story(
963 Story.given(c1, new Incremented({ by: 2, total: 2 })),
964 Story.when(c1, new Increment({ by: 3 })),
965 Story.replied({ total: 5 }),
966 ).pipe(
967 Effect.flip,
968 Effect.map((failure) => {
969 expect(failure.step).toBe(3);
970 expect(failure.reason).toBe(
971 "committed events no step asserts (assert them with then): Counter/c-1: Incremented { by: 3, total: 5 } (from step 2)",
972 );
973 expect(failure.message.split("\n\n")[1]).toBe(
974 [
975 " ✓ 1 Given Counter/c-1: Incremented { by: 2, total: 2 }",
976 " ✓ 2 When Counter/c-1: Increment { by: 3 }",
977 " ✓ 3 Replied { total: 5 }",
978 " ✗ end Counter/c-1: Incremented { by: 3, total: 5 } (from step 2)",
979 " events so far",
980 " Counter/c-1: Incremented → Incremented",
981 ].join("\n"),
982 );
983 }),
984 ),
985 );
986
987 it.effect("fails on the events after the ones a then names", () =>
988 story(
989 Story.given(c1, new Incremented({ by: 10, total: 10 })),
990 Story.when(c1, new Increment({ by: 6 })),
991 Story.call(Approval.check, { total: 16 }),
992 Story.succeed(Approval.check, { ok: true }),
993 Story.then(c1, new Incremented({ by: 6, total: 16 })),
994 ).pipe(
995 Effect.flip,
996 Effect.map((failure) =>
997 expect(failure.reason).toContain("Counter/c-1: Capped (from step 4)"),
998 ),
999 ),
1000 );
1001
1002 it.effect("fails on events a policy commits on a stream no step names", () =>
1003 story(
1004 Story.when(m1, new MakeMove({ from: "c-1", to: "c-2", amount: 30 })),
1005 Story.then(m1, new Moved({ from: "c-1", to: "c-2", amount: 30 })),
1006 ).pipe(
1007 Effect.flip,
1008 Effect.map((failure) => {
1009 expect(failure.reason).toContain("Counter/c-1: Capped (from step 1)");
1010 expect(failure.events).toEqual({ "Move/m-1": ["Moved"], "Counter/c-1": ["Capped"] });
1011 }),
1012 ),
1013 );
1014
1015 it.effect("a scheduled command fires when the clock reaches it", () =>
1016 story(
1017 Story.clock("2026-01-01T00:00:00Z"),
1018 Story.when(c1, new Cap()),
1019 Story.then(c1, new Capped()),
1020 Story.clock("2026-01-01T00:59:00Z"),
1021 Story.then(c1),
1022 Story.clock(DateTime.makeUnsafe("2026-01-01T01:00:00Z")),
1023 Story.then(c1, new Reminded()),
1024 ),
1025 );
1026
1027 it.effect("the clock never moves back", () =>
1028 story(
1029 Story.clock("2026-01-02T00:00:00Z"),
1030 Story.when(c1, new Increment({ by: 1 })),
1031 Story.then(c1, new Incremented({ by: 1, total: 1 })),
1032 Story.clock("2026-01-01T12:00:00Z"),
1033 ).pipe(
1034 Effect.flip,
1035 Effect.map((failure) => {
1036 expect(failure.step).toBe(4);
1037 expect(failure.reason).toBe(
1038 "Clock: the clock cannot move back, from 2026-01-02T00:00:00.000Z to 2026-01-01T12:00:00.000Z",
1039 );
1040 expect(failure.message).toContain(
1041 [
1042 " ✗ 4 Clock expected 2026-01-02T00:00:00.000Z or later",
1043 " got 2026-01-01T12:00:00.000Z",
1044 ].join("\n"),
1045 );
1046 }),
1047 ),
1048 );
1049
1050 it.effect("a command at the start time keeps the clock from moving before it", () =>
1051 story(
1052 Story.when(c1, new Increment({ by: 1 })),
1053 Story.then(c1, new Incremented({ by: 1, total: 1 })),
1054 Story.clock("2025-12-31T00:00:00Z"),
1055 ).pipe(
1056 Effect.flip,
1057 Effect.map((failure) =>
1058 expect(failure.reason).toContain(
1059 "the clock cannot move back, from 2026-01-01T00:00:00.000Z",
1060 ),
1061 ),
1062 ),
1063 );
1064
1065 it.effect("the first clock step may set any time, and the same time again", () =>
1066 story(
1067 Story.provide(Operator, "sam"),
1068 Story.clock("2025-06-01T00:00:00Z"),
1069 Story.when(c1, new Increment({ by: 1 })),
1070 Story.then(c1, new Incremented({ by: 1, total: 1 })),
1071 Story.clock("2025-06-01T00:00:00Z"),
1072 ),
1073 );
1074
1075 it.effect("advance moves the clock forward by a duration", () =>
1076 story(
1077 Story.when(c1, new Cap()),
1078 Story.then(c1, new Capped()),
1079 Story.advance("59 minutes"),
1080 Story.then(c1),
1081 Story.advance(Duration.minutes(1)),
1082 Story.then(c1, new Reminded()),
1083 Story.clock("2026-01-01T01:00:00Z"),
1084 ),
1085 );
1086
1087 it.effect("advance by a negative duration fails", () =>
1088 story(Story.advance("-1 hour")).pipe(
1089 Effect.flip,
1090 Effect.map((failure) => {
1091 expect(failure.reason).toBe("Advance: the clock only moves forward, not by -1h");
1092 expect(failure.message).toContain(" ✗ 1 Advance -1h");
1093 }),
1094 ),
1095 );
1096
1097 it.effect("advance by something that is not a duration fails", () =>
1098 story(Story.advance("Infinity")).pipe(
1099 Effect.flip,
1100 Effect.map((failure) => {
1101 expect(failure.reason).toBe("Advance: Infinity is not a duration");
1102 expect(failure.message).toContain(" ✗ 1 Advance Infinity");
1103 }),
1104 ),
1105 );
1106
1107 it.effect("a clock step that is not a time fails", () =>
1108 story(Story.clock("tomorrow")).pipe(
1109 Effect.flip,
1110 Effect.map((failure) => {
1111 expect(failure.reason).toBe("Clock: tomorrow is not a time");
1112 expect(failure.message).toContain(" ✗ 1 Clock tomorrow");
1113 }),
1114 ),
1115 );
1116 });
1117
1118 // An operation that declares several errors: the policy handles each one.
1119 class LockOffline extends Domain.Rejection("LockOffline") {}
1120 class CodeTaken extends Domain.Rejection("CodeTaken", { code: Schema.String }) {}
1121 class LockJammed extends Domain.Rejection("LockJammed") {}
1122 class Keypad extends Domain.ExternalSystem("Keypad", {
1123 setCode: {
1124 args: { code: Schema.String },
1125 success: { codeId: Schema.String },
1126 error: [LockOffline, CodeTaken],
1127 },
1128 }) {}
1129
1130 class CodeRequested extends Domain.Event("CodeRequested", { code: Schema.String }) {}
1131 class CodeOutcome extends Domain.Event("CodeOutcome", { outcome: Schema.String }) {}
1132 class RequestCode extends Domain.Command("RequestCode", {
1133 target: Schema.String,
1134 input: { code: Schema.String },
1135 events: [CodeRequested],
1136 }) {}
1137 class RecordOutcome extends Domain.Command("RecordOutcome", {
1138 target: Schema.String,
1139 input: { outcome: Schema.String },
1140 events: [CodeOutcome],
1141 }) {}
1142 class Door extends Domain.Aggregate("Door", {
1143 id: Schema.String,
1144 state: Schema.Struct({}),
1145 initial: {},
1146 commands: [RequestCode, RecordOutcome],
1147 decide: {
1148 RequestCode: (_, { code }) => [new CodeRequested({ code })],
1149 RecordOutcome: (_, { outcome }) => [new CodeOutcome({ outcome })],
1150 },
1151 evolve: { CodeRequested: (s) => s, CodeOutcome: (s) => s },
1152 }) {}
1153 class SetCodeOnLock extends Domain.Policy("SetCodeOnLock", {
1154 from: Door,
1155 on: [CodeRequested],
1156 }) {}
1157 const SetCodeOnLockLive = SetCodeOnLock.toLayer(
1158 Effect.gen(function* () {
1159 const keypad = yield* Keypad;
1160 const doors = yield* Door;
1161 return Effect.fn(function* ({ source, event }) {
1162 const outcome = yield* keypad.setCode({ code: event.code }).pipe(
1163 Effect.map(({ codeId }) => `set ${codeId}`),
1164 Effect.catchTags({
1165 LockOffline: () => Effect.succeed("offline"),
1166 CodeTaken: ({ code }) => Effect.succeed(`taken ${code}`),
1167 }),
1168 );
1169 yield* doors.send(source, new RecordOutcome({ outcome }));
1170 });
1171 }),
1172 );
1173 class Doors extends Domain.Model("Doors", { aggregates: [Door], policies: [SetCodeOnLock] }) {}
1174 const doorStory = Story.make(Doors, { layer: SetCodeOnLockLive, stub: [Keypad] });
1175 const d1 = Door.ref("d-1");
1176
1177 // Only a declared error type-checks.
1178 // @ts-expect-error LockJammed is not one of setCode's errors
1179 export const undeclared = Story.fail(Keypad.setCode, new LockJammed());
1180
1181 // A union schema declares the same errors.
1182 class UnionKeypad extends Domain.ExternalSystem("UnionKeypad", {
1183 setCode: { args: { code: Schema.String }, error: Schema.Union([LockOffline, CodeTaken]) },
1184 }) {}
1185 export const unionErrors = [
1186 Story.fail(UnionKeypad.setCode, new LockOffline()),
1187 Story.fail(UnionKeypad.setCode, new CodeTaken({ code: "1234" })),
1188 ];
1189 // @ts-expect-error LockJammed is not in the union
1190 export const undeclaredInUnion = Story.fail(UnionKeypad.setCode, new LockJammed());
1191
1192 describe("Domain Story: an operation with several errors", { tags: ["unit", "local"] }, () => {
1193 it.effect("fails a pending call with each declared error", () =>
1194 doorStory(
1195 Story.when(d1, new RequestCode({ code: "1234" })),
1196 Story.then(d1, new CodeRequested({ code: "1234" })),
1197 Story.call(Keypad.setCode, { code: "1234" }),
1198 Story.fail(Keypad.setCode, new LockOffline()),
1199 Story.then(d1, new CodeOutcome({ outcome: "offline" })),
1200 Story.when(d1, new RequestCode({ code: "5678" })),
1201 Story.then(d1, new CodeRequested({ code: "5678" })),
1202 Story.call(Keypad.setCode, { code: "5678" }),
1203 Story.fail(Keypad.setCode, new CodeTaken({ code: "5678" })),
1204 Story.then(d1, new CodeOutcome({ outcome: "taken 5678" })),
1205 ),
1206 );
1207
1208 it.effect("answers a call with its success when it declares several errors", () =>
1209 doorStory(
1210 Story.when(d1, new RequestCode({ code: "1234" })),
1211 Story.call(Keypad.setCode, { code: "1234" }),
1212 Story.succeed(Keypad.setCode, { codeId: "k_1" }),
1213 Story.then(d1, new CodeRequested({ code: "1234" }), new CodeOutcome({ outcome: "set k_1" })),
1214 ),
1215 );
1216
1217 it("reads every form of a declared error as one schema", () => {
1218 const declared = [new LockOffline(), new CodeTaken({ code: "1234" })];
1219 for (const spec of [Keypad.ops.setCode, UnionKeypad.ops.setCode]) {
1220 const is = Schema.is(errorSchema(spec));
1221 expect(declared.map((error) => is(error))).toEqual([true, true]);
1222 expect(is(new LockJammed())).toBe(false);
1223 }
1224 expect(Schema.is(errorSchema({}))(new LockOffline())).toBe(false);
1225 });
1226
1227 it.effect("a real call fails with either declared error", () =>
1228 Story.make(Doors, { layer: SetCodeOnLockLive })(
1229 Story.when(d1, new RequestCode({ code: "0000" })),
1230 Story.call(Keypad.setCode, { code: "0000" }),
1231 Story.failed(Keypad.setCode, new CodeTaken({ code: "0000" })),
1232 Story.then(
1233 d1,
1234 new CodeRequested({ code: "0000" }),
1235 new CodeOutcome({ outcome: "taken 0000" }),
1236 ),
1237 ).pipe(
1238 Effect.provide(
1239 Keypad.toLayer(
1240 Effect.succeed({
1241 setCode: ({ code }) =>
1242 code === "0000"
1243 ? Effect.fail(new CodeTaken({ code }))
1244 : Effect.fail(new LockOffline()),
1245 }),
1246 ),
1247 ),
1248 ),
1249 );
1250 });