@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 193 lines 6.37 KB
Raw
1 import * as Cause from "effect/Cause";
2 import * as Exit from "effect/Exit";
3 import * as Option from "effect/Option";
4 import type * as Schema from "effect/Schema";
5 import * as SchemaAST from "effect/SchemaAST";
6 import { DefinitionError, UndeclaredDecision } from "./DefinitionError.ts";
7
8 export { DefinitionError } from "./DefinitionError.ts";
9
10 const tags = new WeakMap<object, string>();
11
12 /**
13 * The `_tag` a rejection class declares: the literal its schema gives
14 * `_tag`, so any tagged error class can be a rejection.
15 *
16 * @internal
17 */
18 export const rejectionTag = (rejection: Schema.Top): string => {
19 const cached = tags.get(rejection);
20 if (cached !== undefined) return cached;
21 const encoded = SchemaAST.toEncoded(rejection.ast);
22 const tag = SchemaAST.isObjects(encoded)
23 ? encoded.propertySignatures.find((property) => property.name === "_tag")?.type
24 : undefined;
25 const value = tag && SchemaAST.isLiteral(tag) ? String(tag.literal) : "";
26 tags.set(rejection, value);
27 return value;
28 };
29
30 /** What `decide` returned, once its Effect (if any) ran. @internal */
31 export type Settled =
32 | { readonly _tag: "Decided"; readonly decision: unknown }
33 | { readonly _tag: "Failed"; readonly cause: Cause.Cause<unknown> };
34
35 /**
36 * Settle an effectful decision. A rejection is a `YieldableError`, so it is
37 * an Effect too: running it fails with the rejection itself, which is the
38 * decision. Any other failure, such as a defect, stays a failure.
39 *
40 * @internal
41 */
42 export const settle = (exit: Exit.Exit<unknown, unknown>): Settled => {
43 if (Exit.isSuccess(exit)) return { _tag: "Decided", decision: exit.value };
44 const rejection = Cause.findErrorOption(exit.cause);
45 return Option.isSome(rejection)
46 ? { _tag: "Decided", decision: rejection.value }
47 : { _tag: "Failed", cause: exit.cause };
48 };
49
50 /** A decision, judged against the command's declaration. @internal */
51 export type Judged =
52 | { readonly _tag: "Accepted"; readonly events: ReadonlyArray<{ readonly _tag: string }> }
53 | { readonly _tag: "Rejected"; readonly rejection: { readonly _tag: string } }
54 | { readonly _tag: "Undeclared"; readonly error: DefinitionError };
55
56 /**
57 * Judge a settled decision: the events to commit, the rejection, or the
58 * {@link DefinitionError} for an event or rejection the command does not
59 * declare.
60 *
61 * @internal
62 */
63 export const judge = (
64 aggregateName: string,
65 command: {
66 readonly tag: string;
67 readonly events: ReadonlyArray<{ readonly tag: string }>;
68 readonly rejects: ReadonlyArray<Schema.Top>;
69 },
70 decision: unknown,
71 ): Judged => {
72 if (!Array.isArray(decision)) {
73 const rejection = decision as { readonly _tag: string };
74 if (!command.rejects.some((r) => rejectionTag(r) === rejection?._tag)) {
75 return {
76 _tag: "Undeclared",
77 error: new DefinitionError({
78 reason: new UndeclaredDecision({
79 aggregate: aggregateName,
80 command: command.tag,
81 returned: String(rejection?._tag),
82 list: "rejects",
83 }),
84 }),
85 };
86 }
87 return { _tag: "Rejected", rejection };
88 }
89 for (const event of decision as ReadonlyArray<{ readonly _tag: string }>) {
90 if (!command.events.some((e) => e.tag === event._tag)) {
91 return {
92 _tag: "Undeclared",
93 error: new DefinitionError({
94 reason: new UndeclaredDecision({
95 aggregate: aggregateName,
96 command: command.tag,
97 returned: event._tag,
98 list: "events",
99 }),
100 }),
101 };
102 }
103 }
104 return { _tag: "Accepted", events: decision };
105 };
106
107 type AnyHandler = (...args: ReadonlyArray<unknown>) => unknown;
108 type HandlerMap = { readonly [key: string]: AnyHandler | Record<string, AnyHandler | undefined> };
109
110 /** The id a ref or a Schema key value addresses. @internal */
111 export const targetId = (target: unknown): string =>
112 typeof target === "object" && target !== null && "id" in target
113 ? String((target as { readonly id: unknown }).id)
114 : String(target);
115
116 /** One input for a view's evolve. @internal */
117 export interface LocalViewInput {
118 readonly name: string;
119 readonly event: { readonly _tag: string };
120 /** A ref for an aggregate source, the key value for a Schema-keyed view. */
121 readonly source: unknown;
122 readonly state?: unknown;
123 readonly envelope: { readonly at: unknown };
124 readonly key?: unknown;
125 }
126
127 /**
128 * Apply one input to one key of a view, with the view's own `keyOf` and
129 * `evolve`, as the kernel applies a delivery: each route whose `keyOf`
130 * reaches the key runs its handler. An input that reaches no route of the
131 * key leaves the state as it is.
132 *
133 * @internal
134 */
135 export const evolveView = (
136 view: {
137 readonly definition: {
138 readonly state?: unknown;
139 readonly initial?: unknown;
140 readonly keyOf?: unknown;
141 readonly evolve?: unknown;
142 };
143 },
144 state: unknown,
145 input: LocalViewInput,
146 ): unknown => {
147 const def = view.definition;
148 if (def.state === undefined) return null;
149 const tag = input.event._tag;
150 const keyOf = def.keyOf as HandlerMap | undefined;
151 const evolve = def.evolve as HandlerMap | undefined;
152 const routing = {
153 event: input.event,
154 source: input.source,
155 state: input.state,
156 envelope: input.envelope,
157 };
158 const custom = keyOf?.[tag] ?? keyOf?.[input.name];
159 let key: unknown;
160 let routes: ReadonlyArray<string | undefined>;
161 // A route returns a ref for an aggregate key, or the value of a Schema key.
162 const reaches = (reached: unknown) =>
163 reached !== undefined && key !== undefined && targetId(reached) === targetId(key);
164 if (typeof custom === "function") {
165 const reached = custom(routing);
166 key = input.key ?? reached;
167 routes = reaches(reached) ? [undefined] : [];
168 } else if (custom) {
169 key = input.key;
170 routes = Object.entries(custom).flatMap(([route, fn]) =>
171 reaches(fn?.(routing)) ? [route] : [],
172 );
173 } else {
174 key = input.key ?? input.source;
175 routes = reaches(input.source) ? [undefined] : [];
176 }
177 let current = state;
178 for (const route of routes) {
179 const handler = evolve?.[tag] ?? evolve?.[input.name];
180 const fn =
181 typeof handler === "function" ? handler : route !== undefined ? handler?.[route] : undefined;
182 if (!fn) continue;
183 current =
184 fn(current ?? def.initial, input.event, {
185 key,
186 source: input.source,
187 state: input.state,
188 envelope: input.envelope,
189 at: input.envelope.at,
190 }) ?? null;
191 }
192 return current;
193 };