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

main
ts 578 lines 19.9 KB
Raw
1 import * as Context from "effect/Context";
2 import * as Data from "effect/Data";
3 import type * as DateTime from "effect/DateTime";
4 import type * as Duration from "effect/Duration";
5 import type * as Effect from "effect/Effect";
6 import type * as Option from "effect/Option";
7 import * as Schema from "effect/Schema";
8 import type * as Stream from "effect/Stream";
9 import type * as Aggregate from "./Aggregate.ts";
10 import type * as Event from "./Event.ts";
11 import type { Filter } from "./Filter.ts";
12 import { evolveView, type LocalViewInput } from "./internal.ts";
13 import type * as Key from "./Key.ts";
14 import type * as Middleware from "./Middleware.ts";
15 import type * as Read from "./Read.ts";
16 import type * as Rejection from "./Rejection.ts";
17
18 /**
19 * Raised by `waitFor` when the predicate does not hold before the timeout.
20 */
21 export class WaitTimeout extends Data.TaggedError("WaitTimeout")<{
22 readonly view: string;
23 readonly key: string;
24 }> {}
25
26 /**
27 * Raised by a read with `atLeast` when the view has not applied that write
28 * before the timeout. A client receives it like a rejection.
29 */
30 export class ConsistencyTimeout extends Schema.TaggedError<ConsistencyTimeout>()(
31 "ConsistencyTimeout",
32 {
33 view: Schema.String,
34 key: Schema.String,
35 stream: Schema.String,
36 version: Schema.Number,
37 },
38 ) {}
39
40 /** A handler, or one handler per named route. */
41 type Handlers = {
42 readonly [key: string]:
43 | ((...args: never[]) => unknown)
44 | { readonly [route: string]: ((...args: never[]) => unknown) | undefined }
45 | undefined;
46 };
47
48 /**
49 * Structural constraint satisfied by every view class.
50 */
51 export interface Any extends Context.Key<unknown, unknown> {
52 readonly kind: "View";
53 readonly viewName: string;
54 readonly definition: {
55 readonly from: ReadonlyArray<Aggregate.Any | Any>;
56 readonly key: Key.Any;
57 readonly state?: Schema.Top;
58 readonly initial?: unknown;
59 readonly keyOf?: Handlers;
60 readonly evolve?: Handlers;
61 readonly events?: ReadonlyArray<Event.Any>;
62 readonly emit?: Handlers;
63 readonly computed?: { readonly [name: string]: ((state: never) => unknown) | undefined };
64 readonly version?: number;
65 } & Read.AnyContract;
66 /** Type-level only: the view's state. */
67 readonly "~state": unknown;
68 /** Type-level only: the events the view emits. */
69 readonly "~events": unknown;
70 }
71
72 /** Something a view or policy can consume: an aggregate or a view. */
73 export type Source = Aggregate.Any | Any;
74
75 /** The state type of a view class (`null` for a view without state). */
76 export type StateOf<V extends Any> = V["~state"];
77 /** The events a view class emits. */
78 export type EventOf<V extends Any> = V["~events"];
79 /** The key aggregate of a view class. */
80 export type KeyOf<V extends Any> = V["definition"]["key"];
81
82 /** The name of a source. */
83 export type NameOf<S> = S extends Aggregate.Any
84 ? S["aggregateName"]
85 : S extends Any
86 ? S["viewName"]
87 : never;
88 /** The events a source produces. */
89 export type SourceEvent<S> = S extends Aggregate.Any
90 ? Aggregate.EventOf<S>
91 : S extends Any
92 ? EventOf<S>
93 : never;
94 /** The key that identifies a source's instances: an aggregate, or a view's key. */
95 export type SourceKey<S> = S extends Aggregate.Any ? S : S extends Any ? KeyOf<S> : never;
96 /** What a source attaches to each event: a view's state after it, nothing for an aggregate. */
97 export type SourceState<S> = S extends Any ? StateOf<S> | null : undefined;
98
99 /**
100 * One input to a view or policy: an event, the source instance it came from,
101 * and (for a view source) that view's state after the event.
102 */
103 export type Input<S> = S extends unknown
104 ? SourceEvent<S> extends infer E
105 ? E extends unknown
106 ? {
107 readonly name: NameOf<S>;
108 readonly event: E;
109 readonly source: Key.RefOf<SourceKey<S>>;
110 readonly state: SourceState<S>;
111 }
112 : never
113 : never
114 : never;
115
116 /** Every input a list of sources produces. */
117 export type Inputs<From extends ReadonlyArray<unknown>> = Input<From[number]>;
118 type EventTag<From extends ReadonlyArray<unknown>> = Inputs<From>["event"] extends infer E
119 ? E extends { readonly _tag: infer T extends string }
120 ? T
121 : never
122 : never;
123 /**
124 * What a handler may be keyed by: an event tag, or a source's name to handle
125 * every event from that source.
126 */
127 export type HandlerKey<From extends ReadonlyArray<unknown>> = EventTag<From> | Inputs<From>["name"];
128 /** The inputs a handler keyed by `K` (an event tag or a source name) receives. */
129 export type InputFor<From extends ReadonlyArray<unknown>, K> =
130 | Extract<Inputs<From>, { readonly event: { readonly _tag: K } }>
131 | Extract<Inputs<From>, { readonly name: K }>;
132
133 /** The state of a view with state schema `S` (`null` without one). */
134 export type StateType<S> = S extends Schema.Top ? S["Type"] : null;
135 /** What a view emits: its declared events, or every event it consumes. */
136 export type Output<
137 From extends ReadonlyArray<unknown>,
138 Events extends ReadonlyArray<Event.Any>,
139 > = Events extends readonly [] ? Inputs<From>["event"] : Aggregate.InstanceOf<Events[number]>;
140
141 /**
142 * Where an input is delivered and what handlers receive alongside it.
143 */
144 export interface Routing<I> {
145 readonly event: I extends { readonly event: infer E } ? E : never;
146 /** The source instance the event came from. */
147 readonly source: I extends { readonly source: infer R } ? R : never;
148 /** For a view source: its state after the event. */
149 readonly state: I extends { readonly state: infer S } ? S : never;
150 readonly envelope: Aggregate.Envelope;
151 }
152
153 /**
154 * The context passed to `evolve` and `emit` handlers.
155 */
156 export interface HandlerContext<Key extends Key.Any, I> {
157 /** The view instance being updated: a ref, or the value of a Schema key. */
158 readonly key: Key.RefOf<Key>;
159 /** The source instance the event came from. */
160 readonly source: Routing<I>["source"];
161 /** For a view source: its state after the event. */
162 readonly state: Routing<I>["state"];
163 readonly envelope: Aggregate.Envelope;
164 /** The commit time of the originating event. */
165 readonly at: DateTime.Utc;
166 }
167
168 /** The context passed to `emit` handlers. */
169 export interface EmitContext<Key extends Key.Any, I, St> extends HandlerContext<Key, I> {
170 /** This view's state before the event. */
171 readonly before: St;
172 /** This view's state after the event (`null` if it was deleted). */
173 readonly after: St | null;
174 }
175
176 /** Picks the key an input goes to, or `undefined` for none. */
177 export type KeyFn<Key extends Key.Any, I> = (routing: Routing<I>) => Key.RefOf<Key> | undefined;
178 type EvolveFn<St, Key extends Key.Any, I> = (
179 state: St,
180 event: Routing<I>["event"],
181 context: HandlerContext<Key, I>,
182 ) => St | null;
183 type EmitFn<St, Key extends Key.Any, I, Out> = (
184 event: Routing<I>["event"],
185 context: EmitContext<Key, I, St>,
186 ) => Out | ReadonlyArray<Out> | undefined;
187
188 /** A handler, or one handler per route named in `keyOf`. */
189 export type Routed<F> = F | { readonly [route: string]: F };
190
191 /**
192 * The pure definition of a view.
193 */
194 export interface Definition<
195 From extends ReadonlyArray<Source>,
196 Key extends Key.Any,
197 S extends Schema.Top | undefined,
198 Events extends ReadonlyArray<Event.Any>,
199 Computed extends Record<string, unknown>,
200 Ms extends Middleware.List = readonly [],
201 Rejects extends ReadonlyArray<Rejection.Any> = readonly [],
202 > extends Read.Contract<Key.RefOf<Key>, StateType<S> | null, Ms, Rejects> {
203 /** The aggregates and views this view consumes. */
204 readonly from: From;
205 /**
206 * What keys this view's instances: an aggregate, whose refs key them, or a
207 * string Schema (such as an org id), whose values key them with no
208 * aggregate behind them.
209 */
210 readonly key: Key;
211 /**
212 * Which instance each input updates, keyed by event tag or source name. May
213 * be omitted for a source keyed by the same aggregate or Schema (the source
214 * is the key). Return a ref (an aggregate key) or a value (a Schema key), or
215 * an object of named routes to update several instances; each route then
216 * gets its own `evolve` and `emit` handler.
217 */
218 readonly keyOf?: {
219 readonly [K in HandlerKey<From>]?: Routed<KeyFn<Key, InputFor<From, K>>>;
220 };
221 /** Schema of the view's state. Omit it for a view that only emits events. */
222 readonly state?: S;
223 /** The state every instance starts from. */
224 readonly initial?: StateType<S>;
225 /**
226 * Fold inputs into state, keyed by event tag or source name. Return `null`
227 * to delete the instance.
228 */
229 readonly evolve?: {
230 readonly [K in HandlerKey<From>]?: Routed<EvolveFn<StateType<S>, Key, InputFor<From, K>>>;
231 };
232 /**
233 * The events this view emits. Without `events`, a view emits every event it
234 * applies, unchanged.
235 */
236 readonly events?: Events;
237 /**
238 * Derive the events to emit for an input, keyed by event tag or source name.
239 * Runs after `evolve`, with the state before and after. A declared event
240 * with no `emit` handler passes through unchanged.
241 */
242 readonly emit?: {
243 readonly [K in HandlerKey<From>]?: Routed<
244 EmitFn<StateType<S>, Key, InputFor<From, K>, Aggregate.InstanceOf<Events[number]>>
245 >;
246 };
247 /** Values derived from state when read. */
248 readonly computed?: ComputedFns<StateType<S>, Computed>;
249 /**
250 * Bump it whenever you change what the view computes (`evolve`, `emit`,
251 * `keyOf`, `state`, the events or sources it reads): every key is computed
252 * again from the history, and so is every view and projection that reads
253 * this one. Only ever increase it.
254 *
255 * A view keyed by the one aggregate it reads is rebuilt in place: the deploy
256 * waits for nothing, and each key re-reads its own instance's events the
257 * first time it is touched. Any other view is rebuilt from the history
258 * before the deploy finishes.
259 *
260 * @default 0
261 */
262 readonly version?: number;
263 }
264
265 /** Derived-value functions of a view. */
266 export type ComputedFns<State, Computed> = {
267 readonly [K in keyof Computed]: (state: State) => Computed[K];
268 };
269
270 /**
271 * An event a view emitted, with the view's state after it.
272 */
273 export interface Entry<S, E, Id = string> {
274 readonly event: E;
275 /** The view's state after the event (`null` if deleted, or for a view without state). */
276 readonly state: S | null;
277 /** `id` is the view key, `stream` is `View/key`, `seq` counts the key's events. */
278 readonly envelope: Aggregate.Envelope<Id>;
279 }
280
281 /**
282 * A page of entries.
283 */
284 export interface Page<Entry> {
285 readonly entries: ReadonlyArray<Entry>;
286 /** Pass as `after` to continue; `null` when there are no more entries. */
287 readonly cursor: number | null;
288 }
289
290 /**
291 * Options for watching a view key.
292 */
293 export interface WatchOptions<S> {
294 /** Only emit states matching this filter; emits `none` when filtered out. */
295 readonly where?: Filter<S>;
296 }
297
298 /**
299 * How much of the history recorded before a view or projection (or before its
300 * current version) has reached it. A consumer added to a model that already
301 * has events, or rebuilt by bumping its version, receives that history first.
302 */
303 export interface History {
304 /** Every event recorded before it has reached it: its answers cover the whole history. */
305 readonly complete: boolean;
306 }
307
308 /**
309 * The read API of a view, obtained with `yield* MyView`.
310 */
311 export interface Host<S, Key extends Key.Any, E> {
312 /**
313 * Whether the history recorded before this view, or before its current
314 * version, has reached it. Until it has, its answers cover only part of
315 * the history: a screen can say so, or hold its reads until it is complete.
316 */
317 readonly history: Effect.Effect<History>;
318 /** Read the current state of a key. `none` if it does not exist. */
319 readonly query: (
320 key: Key.RefOf<Key>,
321 options?: {
322 /** Wait until the view has applied this write (a command's `stream` and `version`). */
323 readonly atLeast?: { readonly stream: string; readonly version: number };
324 readonly timeout?: Duration.Input;
325 },
326 ) => Effect.Effect<Option.Option<S>, ConsistencyTimeout>;
327 /**
328 * Read the current state of a key together with its cursor: the `seq` of
329 * the last event the key emitted when the state was read. Pass the cursor
330 * to `events` as `after` to follow every later change once.
331 */
332 readonly snapshot: (
333 key: Key.RefOf<Key>,
334 options?: {
335 /** Wait until the view has applied this write (a command's `stream` and `version`). */
336 readonly atLeast?: { readonly stream: string; readonly version: number };
337 readonly timeout?: Duration.Input;
338 },
339 ) => Effect.Effect<Read.Snapshot<S | null>, ConsistencyTimeout>;
340 /** Wait until a key's state matches a filter. */
341 readonly waitFor: (
342 key: Key.RefOf<Key>,
343 where: Filter<S>,
344 options: { readonly timeout: Duration.Input },
345 ) => Effect.Effect<S, WaitTimeout>;
346 /** The current state, then every change. */
347 readonly watch: (
348 key: Key.RefOf<Key>,
349 options?: WatchOptions<S>,
350 ) => Stream.Stream<Option.Option<S>>;
351 /**
352 * Follow a changing set of keys derived from a parent stream, emitting the
353 * parent together with the current state of every key that exists and
354 * matches `where`.
355 */
356 readonly watchEach: <P, Err, R>(
357 parent: Stream.Stream<P, Err, R>,
358 keysOf: (parent: P) => ReadonlyArray<Key.RefOf<Key>>,
359 options?: WatchOptions<S>,
360 ) => Stream.Stream<readonly [P, ReadonlyArray<readonly [Key.RefOf<Key>, S]>], Err, R>;
361 /**
362 * Every event the key emitted, with the state after it: history (from
363 * `after`, a cursor or entry `seq`), then live.
364 */
365 readonly events: (
366 key: Key.RefOf<Key>,
367 options?: { readonly after?: number; readonly where?: Filter<E> },
368 ) => Stream.Stream<Entry<S, E, Key.IdOf<Key>>>;
369 /** A page of the key's emitted events, oldest first unless `order` is `"desc"`. */
370 readonly list: (
371 key: Key.RefOf<Key>,
372 options?: {
373 readonly where?: Filter<E>;
374 readonly order?: "asc" | "desc";
375 readonly take?: number;
376 readonly after?: number;
377 },
378 ) => Effect.Effect<Page<Entry<S, E, Key.IdOf<Key>>>>;
379 }
380
381 /**
382 * Type-level identity of a view in an Effect's requirements.
383 */
384 export interface ViewKey<Name extends string> {
385 readonly "~alchemy/Domain/View": Name;
386 }
387
388 /**
389 * A read model: events folded into state per key, kept up to date as new
390 * events arrive. A view can emit events of its own, route one event to
391 * several keys, and decide who may read it.
392 *
393 * ### Folding events into state
394 * **Example:** An account's balance
395 * ```typescript
396 * import * as Domain from "@alchemy.run/domain";
397 * import * as Schema from "effect/Schema";
398 * import { Account } from "./Account.ts";
399 *
400 * export class AccountSummary extends Domain.View("AccountSummary", {
401 * from: [Account],
402 * key: Account,
403 * state: Schema.Struct({ balance: Schema.Int }),
404 * initial: { balance: 0 },
405 * evolve: {
406 * MoneyDeposited: (v, e) => ({ ...v, balance: e.balanceAfter }),
407 * MoneyWithdrawn: (v, e) => ({ ...v, balance: e.balanceAfter }),
408 * },
409 * }) {}
410 * ```
411 *
412 * ### Emitting events
413 * **Example:** One statement line per movement
414 * ```typescript
415 * import * as Domain from "@alchemy.run/domain";
416 * import * as Schema from "effect/Schema";
417 * import { Account } from "./Account.ts";
418 *
419 * export class StatementLine extends Domain.Event("StatementLine", {
420 * kind: Schema.Literals(["deposit", "withdrawal"]),
421 * amount: Schema.Int,
422 * }) {}
423 *
424 * export class Statement extends Domain.View("Statement", {
425 * from: [Account],
426 * key: Account,
427 * events: [StatementLine],
428 * emit: {
429 * MoneyDeposited: (e) => new StatementLine({ kind: "deposit", amount: e.amount }),
430 * MoneyWithdrawn: (e) => new StatementLine({ kind: "withdrawal", amount: e.amount }),
431 * },
432 * }) {}
433 * ```
434 *
435 * ### Routing one event to several keys
436 * **Example:** A transfer appears on both accounts
437 * ```typescript
438 * keyOf: {
439 * TransferRequested: {
440 * out: ({ event }) => Account.ref(event.from),
441 * in: ({ event }) => Account.ref(event.to),
442 * },
443 * },
444 * ```
445 *
446 * ### Keying by a value
447 * **Example:** One schedule per org, with no Org aggregate
448 * ```typescript
449 * key: OrgId, // a string Schema
450 * keyOf: { Tour: ({ event }) => event.orgId },
451 * ```
452 *
453 * ### Validating reads
454 * **Example:** Only the owner may read
455 * ```typescript
456 * middleware: [Session],
457 * rejects: [NotOwner],
458 * validate: Effect.fn(function* (_request, summary) {
459 * const actor = yield* CurrentActor;
460 * if (summary?.owner && summary.owner !== actor.customerId) return yield* new NotOwner();
461 * }),
462 * ```
463 *
464 * @primitive
465 */
466 export const make = <
467 const Name extends string,
468 const From extends ReadonlyArray<Source>,
469 Key extends Key.Any,
470 S extends Schema.Top | undefined = undefined,
471 const Events extends ReadonlyArray<Event.Any> = readonly [],
472 Computed extends Record<string, unknown> = {},
473 const Ms extends Middleware.List = readonly [],
474 const Rejects extends ReadonlyArray<Rejection.Any> = readonly [],
475 >(
476 name: Name,
477 definition: Definition<From, Key, S, Events, Computed, Ms, Rejects>,
478 ): ViewClass<
479 Name,
480 Definition<From, Key, S, Events, Computed, Ms, Rejects>,
481 S,
482 StateType<S>,
483 Key,
484 ComputedFns<StateType<S>, Computed>,
485 Output<From, Events>
486 > => {
487 const Tag = Context.Service<ViewKey<Name>, Host<StateType<S>, Key, Output<From, Events>>>()(
488 `alchemy/Domain/View/${name}`,
489 );
490 return class extends Tag {
491 static readonly kind = "View" as const;
492 static readonly viewName: Name = name;
493 static readonly definition: Definition<From, Key, S, Events, Computed, Ms, Rejects> =
494 definition;
495 /** The view's state schema. */
496 static readonly State = definition.state;
497 /** Derived values, computed from a state when read. */
498 static readonly computed = definition.computed ?? {};
499 /** Apply one input to one key's state, as the server's view does. */
500 static evolve(state: unknown, input: LocalViewInput) {
501 return evolveView({ definition }, state, input);
502 }
503 } as unknown as ViewClass<
504 Name,
505 Definition<From, Key, S, Events, Computed, Ms, Rejects>,
506 S,
507 StateType<S>,
508 Key,
509 ComputedFns<StateType<S>, Computed>,
510 Output<From, Events>
511 >;
512 };
513
514 /** One source input, with the source's state optional (aggregates attach none). */
515 type LocalSourceInput<I> = I extends {
516 readonly name: infer N;
517 readonly event: infer E;
518 readonly source: infer R;
519 readonly state: infer S;
520 }
521 ? { readonly name: N; readonly event: E; readonly source: R; readonly state?: S }
522 : never;
523
524 /** What {@link ViewClass.evolve} applies: a source input, its envelope, and the key. */
525 export type LocalInput<Def, Key extends Key.Any> = (Def extends {
526 readonly from: infer From extends ReadonlyArray<unknown>;
527 }
528 ? LocalSourceInput<Inputs<From>>
529 : never) & {
530 readonly envelope: Aggregate.Envelope;
531 /** The key to update: defaults to what `keyOf` returns, or to the source. */
532 readonly key?: Key.RefOf<Key>;
533 };
534
535 /**
536 * The class type returned by {@link make}.
537 */
538 export interface ViewClass<
539 Name extends string,
540 Def,
541 S extends Schema.Top | undefined,
542 St,
543 Key extends Key.Any,
544 Computed,
545 Out,
546 > extends Context.ServiceClass<ViewKey<Name>, string, Host<St, Key, Out>> {
547 readonly kind: "View";
548 readonly viewName: Name;
549 readonly definition: Def;
550 /** The view's state schema. */
551 readonly State: S;
552 /** Derived values, computed from a state when read. */
553 readonly computed: Computed;
554 /**
555 * Apply one input (an event of a source) to one key's state, with this
556 * view's own `keyOf` and `evolve`: the state the server's view will hold
557 * after it. Use it with the events of `Aggregate.predict` to show a view's
558 * next state before the server answers. `key` defaults to what `keyOf`
559 * returns, or to the source; it is required for a view with routes.
560 *
561 * **Example:** The next balance of a predicted withdrawal
562 * ```typescript
563 * const next = outcome.events.reduce(
564 * (state, event, i) =>
565 * AccountSummary.evolve(state, {
566 * name: "Account",
567 * event,
568 * source: Account.ref(id),
569 * envelope: outcome.envelopes[i],
570 * }),
571 * summary,
572 * );
573 * ```
574 */
575 evolve(state: St | null, input: LocalInput<Def, Key>): St | null;
576 readonly "~state": St;
577 readonly "~events": Out;
578 }