logic-sdk 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +126 -2
- package/bin/logic-sdk.js +14 -0
- package/dist/ai.d.ts +32 -0
- package/dist/ai.js +39 -0
- package/dist/drizzle.d.ts +18 -0
- package/dist/drizzle.js +23 -0
- package/dist/fetch.d.ts +20 -0
- package/dist/fetch.js +68 -0
- package/dist/index.d.ts +440 -0
- package/dist/index.js +374 -0
- package/dist/orpc.d.ts +31 -0
- package/dist/orpc.js +46 -0
- package/dist/testing.d.ts +29 -0
- package/dist/testing.js +61 -0
- package/package.json +106 -4
- package/src/ai.ts +64 -0
- package/src/drizzle.ts +39 -0
- package/src/fetch.ts +81 -0
- package/src/index.ts +719 -0
- package/src/orpc.ts +65 -0
- package/src/testing.ts +88 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,719 @@
|
|
|
1
|
+
import type { StandardSchemaV1 } from "@standard-schema/spec";
|
|
2
|
+
|
|
3
|
+
/* ────────────────────────────────────────────────────────────────────────────
|
|
4
|
+
* Types
|
|
5
|
+
* ──────────────────────────────────────────────────────────────────────────── */
|
|
6
|
+
|
|
7
|
+
type Schema<I = any, O = any> = StandardSchemaV1<I, O>;
|
|
8
|
+
type In<S> = S extends Schema<infer I, any> ? I : never;
|
|
9
|
+
type Out<S> = S extends Schema<any, infer O> ? O : never;
|
|
10
|
+
type Awaitable<T> = T | Promise<T>;
|
|
11
|
+
|
|
12
|
+
/** What you declare once in `init<...>()`. */
|
|
13
|
+
export interface Config {
|
|
14
|
+
/** Who and where: actor, account, locale... Must be JSON-serializable (it travels with events). */
|
|
15
|
+
scope: object;
|
|
16
|
+
/** The transaction handle mutations receive (e.g. a Drizzle transaction). */
|
|
17
|
+
db?: unknown;
|
|
18
|
+
/** What queries receive. Defaults to `db`. Use a read-only type (e.g. `DrizzleReader<Tx>`). */
|
|
19
|
+
reader?: unknown;
|
|
20
|
+
/** Side-effecting services (mailer, payments...). Only actions and listeners receive them. */
|
|
21
|
+
services?: object;
|
|
22
|
+
/** The shape of `meta` on your functions (tags, rate limits, "agent may call"...). Read by `wrap` and adapters. */
|
|
23
|
+
meta?: object;
|
|
24
|
+
}
|
|
25
|
+
type ScopeOf<C extends Config> = C["scope"];
|
|
26
|
+
type DbOf<C extends Config> = C extends { db: infer D } ? D : never;
|
|
27
|
+
type ReaderOf<C extends Config> = C extends { reader: infer R } ? R : DbOf<C>;
|
|
28
|
+
type ServicesOf<C extends Config> = C extends { services: infer S } ? S : {};
|
|
29
|
+
type MetaOf<C extends Config> = C extends { meta: infer M } ? M : never;
|
|
30
|
+
|
|
31
|
+
export type Kind = "query" | "mutation" | "action";
|
|
32
|
+
|
|
33
|
+
declare const types: unique symbol;
|
|
34
|
+
const BRAND: unique symbol = Symbol.for("logic-sdk.brand") as any;
|
|
35
|
+
|
|
36
|
+
/** A query, mutation or action. Call it with `caller.run(fn, input)` or `ctx.run(fn, input)`. */
|
|
37
|
+
export interface Fn<K extends Kind = Kind, I = any, O = any, E extends boolean = boolean> {
|
|
38
|
+
readonly [BRAND]: K;
|
|
39
|
+
readonly kind: K;
|
|
40
|
+
readonly description: string;
|
|
41
|
+
readonly inputSchema: Schema;
|
|
42
|
+
readonly outputSchema?: Schema;
|
|
43
|
+
/** Your own data about the function. Checked against `meta` in `init` where you set it, typed in `wrap`; loose here, for adapters. */
|
|
44
|
+
readonly meta?: any;
|
|
45
|
+
/** Set when the function is exposed: who may call it. Runs on every call. */
|
|
46
|
+
readonly check?: (scope: any, input: any) => Awaitable<boolean>;
|
|
47
|
+
readonly execute: (input: any, ctx: any) => Promise<any>;
|
|
48
|
+
/** Phantom types, never set at runtime. */
|
|
49
|
+
readonly [types]?: { input: I; output: O; exposed: E };
|
|
50
|
+
}
|
|
51
|
+
/** A function with `expose`: adapters publish it. */
|
|
52
|
+
export type ExposedFn<K extends Kind = Kind, I = any, O = any> = Fn<K, I, O, true>;
|
|
53
|
+
/** What callers pass to a function. */
|
|
54
|
+
export type FnIn<F> = F extends Fn<any, infer I, any> ? I : never;
|
|
55
|
+
/** What a function returns. */
|
|
56
|
+
export type FnOut<F> = F extends Fn<any, any, infer O> ? O : never;
|
|
57
|
+
|
|
58
|
+
/** `I`: what `emit` takes. `O`: what listeners receive (after the schema's transforms and defaults). */
|
|
59
|
+
export interface EventDef<I = any, O = I> {
|
|
60
|
+
readonly [BRAND]: "event";
|
|
61
|
+
readonly kind: "event";
|
|
62
|
+
readonly schema: Schema;
|
|
63
|
+
readonly description?: string;
|
|
64
|
+
readonly [types]?: { input: I; payload: O };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* What a dispatcher stores and delivers. Fully JSON: `payload` is what was emitted (validated),
|
|
69
|
+
* and listeners get it parsed again by the event's schema at delivery.
|
|
70
|
+
*/
|
|
71
|
+
export interface Envelope<P = unknown, S = object> {
|
|
72
|
+
id: string;
|
|
73
|
+
name: string;
|
|
74
|
+
payload: P;
|
|
75
|
+
scope: S;
|
|
76
|
+
occurredAt: string;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export interface Listener<O = any> {
|
|
80
|
+
readonly [BRAND]: "listener";
|
|
81
|
+
readonly kind: "listener";
|
|
82
|
+
/** Lazy, so listeners can import other modules' barrels without import cycles. */
|
|
83
|
+
readonly event: () => EventDef<any, O>;
|
|
84
|
+
readonly description?: string;
|
|
85
|
+
readonly execute: (payload: O, ctx: any) => Promise<unknown>;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
type Run<Allowed extends Kind> = <F extends Fn<Allowed>>(fn: F, input: FnIn<F>) => Promise<FnOut<F>>;
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Expected failures, namespaced to the module you're in: inside `bookings`, `ctx.reject("not_pending")` has
|
|
92
|
+
* code `"bookings.not_pending"`. Throw what they return. Codes are plain strings on purpose (see the errors docs).
|
|
93
|
+
*/
|
|
94
|
+
interface Fail {
|
|
95
|
+
/** A business rule said no, and trying again won't help. `throw ctx.reject("not_pending", { status })` */
|
|
96
|
+
reject(code: string, details?: unknown): DomainError;
|
|
97
|
+
/** Someone else got there first, or it already exists. Refreshing and retrying may work. */
|
|
98
|
+
conflict(code: string, details?: unknown): DomainError;
|
|
99
|
+
/** It doesn't exist, or isn't visible in this scope. Code defaults to `"<module>.not_found"`. */
|
|
100
|
+
notFound(code?: string, details?: unknown): DomainError;
|
|
101
|
+
/** The caller is known but may not do this. Code defaults to `"<module>.<function>.forbidden"`. */
|
|
102
|
+
deny(code?: string, details?: unknown): DomainError;
|
|
103
|
+
}
|
|
104
|
+
interface BaseCtx<S> extends Fail {
|
|
105
|
+
scope: S;
|
|
106
|
+
/** Current time. Fixed in tests. */
|
|
107
|
+
now: () => Date;
|
|
108
|
+
}
|
|
109
|
+
/** `S` is the scope, narrowed by the function's policy. Alias it in init.ts: `type QueryCtx = Core.QueryCtx<Config>`. */
|
|
110
|
+
export interface QueryCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<S> {
|
|
111
|
+
db: ReaderOf<C>;
|
|
112
|
+
run: Run<"query">;
|
|
113
|
+
/** The caller's abort signal, if any. */
|
|
114
|
+
signal: AbortSignal | undefined;
|
|
115
|
+
with(patch: Partial<ScopeOf<C>>): QueryCtx<C>;
|
|
116
|
+
}
|
|
117
|
+
export interface MutationCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<S> {
|
|
118
|
+
db: DbOf<C>;
|
|
119
|
+
run: Run<"query" | "mutation">;
|
|
120
|
+
/** Queue an event. Delivered to listeners only after the transaction commits. */
|
|
121
|
+
emit<I>(event: EventDef<I, any>, payload: I): void;
|
|
122
|
+
signal: AbortSignal | undefined;
|
|
123
|
+
with(patch: Partial<ScopeOf<C>>): MutationCtx<C>;
|
|
124
|
+
}
|
|
125
|
+
export interface ActionCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<S> {
|
|
126
|
+
services: ServicesOf<C>;
|
|
127
|
+
/** Each mutation you run here gets its own transaction. */
|
|
128
|
+
run: Run<Kind>;
|
|
129
|
+
/** The caller's abort signal. Always undefined in listeners (they outlive the request). */
|
|
130
|
+
signal: AbortSignal | undefined;
|
|
131
|
+
with(patch: Partial<ScopeOf<C>>): ActionCtx<C>;
|
|
132
|
+
}
|
|
133
|
+
export interface ListenerCtx<C extends Config, O = unknown> extends ActionCtx<C> {
|
|
134
|
+
event: Envelope<unknown, ScopeOf<C>> & { payload: O };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Who may call an exposed function. Write it as a type guard (`(s): s is Staff => ...`) to narrow `scope` in `execute`. */
|
|
138
|
+
export type Policy<S> = (scope: S) => boolean;
|
|
139
|
+
type Guarded<F, S> = F extends (scope: any) => scope is infer G ? G : S;
|
|
140
|
+
type Inline<C extends Config, IS extends Schema> = (scope: ScopeOf<C>, input: Out<IS>) => Awaitable<boolean>;
|
|
141
|
+
/** A policy name from `init`, or an inline check that also sees the input. */
|
|
142
|
+
type Exposure<C extends Config, P, IS extends Schema> = (keyof P & string) | Inline<C, IS>;
|
|
143
|
+
type ScopeFor<C extends Config, P, E> = E extends keyof P ? Guarded<P[E], ScopeOf<C>> : ScopeOf<C>;
|
|
144
|
+
type CtxOf<C extends Config, K extends Kind, S> = K extends "query"
|
|
145
|
+
? QueryCtx<C, S>
|
|
146
|
+
: K extends "mutation"
|
|
147
|
+
? MutationCtx<C, S>
|
|
148
|
+
: ActionCtx<C, S>;
|
|
149
|
+
|
|
150
|
+
type Def<IS extends Schema, Ctx, R> = {
|
|
151
|
+
/** One sentence, shown to humans, adapters and AI tools. */
|
|
152
|
+
description: string;
|
|
153
|
+
inputSchema: IS;
|
|
154
|
+
execute: (input: Out<IS>, ctx: Ctx) => Promise<R>;
|
|
155
|
+
};
|
|
156
|
+
type Internal = { expose?: undefined };
|
|
157
|
+
type WithMeta<C extends Config> = { meta?: MetaOf<C> };
|
|
158
|
+
type WithOutput<OS extends Schema> = { outputSchema: OS };
|
|
159
|
+
|
|
160
|
+
/** Exposed functions must declare `outputSchema`: what leaves your process is a contract. Internal ones may skip it. */
|
|
161
|
+
interface Constructor<C extends Config, K extends Kind, P> {
|
|
162
|
+
<IS extends Schema, OS extends Schema, const E extends Exposure<C, P, IS>>(
|
|
163
|
+
def: Def<IS, CtxOf<C, K, ScopeFor<C, P, E>>, In<OS>> & WithOutput<OS> & WithMeta<C> & { expose: E },
|
|
164
|
+
): Fn<K, In<IS>, Out<OS>, true>;
|
|
165
|
+
<IS extends Schema, OS extends Schema>(
|
|
166
|
+
def: Def<IS, CtxOf<C, K, ScopeOf<C>>, In<OS>> & WithOutput<OS> & WithMeta<C> & Internal,
|
|
167
|
+
): Fn<K, In<IS>, Out<OS>, false>;
|
|
168
|
+
<IS extends Schema, R>(def: Def<IS, CtxOf<C, K, ScopeOf<C>>, R> & WithMeta<C> & Internal): Fn<K, In<IS>, R, false>;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/* ────────────────────────────────────────────────────────────────────────────
|
|
172
|
+
* Errors
|
|
173
|
+
* ──────────────────────────────────────────────────────────────────────────── */
|
|
174
|
+
|
|
175
|
+
export type ErrorKind = "invalid" | "unauthenticated" | "forbidden" | "not_found" | "conflict" | "rejected";
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* An expected failure: a `kind` (a small fixed set), a namespaced `code` and optional `details`. No HTTP here;
|
|
179
|
+
* adapters map kinds to statuses. Anything else thrown (including invalid output or event payloads, which are
|
|
180
|
+
* bugs) is unexpected: adapters answer 500 and report it.
|
|
181
|
+
*/
|
|
182
|
+
export class DomainError extends Error {
|
|
183
|
+
readonly kind: ErrorKind;
|
|
184
|
+
readonly code: string;
|
|
185
|
+
readonly details: unknown;
|
|
186
|
+
constructor(kind: ErrorKind, code: string, details?: unknown) {
|
|
187
|
+
// the details are in the message too: logs and AI tool errors (which show only the message) stay useful
|
|
188
|
+
super(details === undefined ? code : `${code} ${JSON.stringify(details)}`);
|
|
189
|
+
this.name = "DomainError";
|
|
190
|
+
this.kind = kind;
|
|
191
|
+
this.code = code;
|
|
192
|
+
this.details = details;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
/** For the edge (`resolveScope`): no valid session. Inside modules, use `ctx.deny()`. */
|
|
196
|
+
export const unauthenticated = (code = "unauthenticated", details?: unknown) =>
|
|
197
|
+
new DomainError("unauthenticated", code, details);
|
|
198
|
+
/** `isDomainError(e)`, or with a code: `isDomainError(e, "availability.dates_unavailable")`. */
|
|
199
|
+
export const isDomainError = (e: unknown, code?: string): e is DomainError =>
|
|
200
|
+
e instanceof DomainError && (code === undefined || e.code === code);
|
|
201
|
+
|
|
202
|
+
/** `ctx.reject` and friends for one function or listener (`id` like "bookings.confirm"). */
|
|
203
|
+
const failFor = (id: string): Fail => {
|
|
204
|
+
const module = id.slice(0, id.indexOf("."));
|
|
205
|
+
return {
|
|
206
|
+
reject: (code, details) => new DomainError("rejected", `${module}.${code}`, details),
|
|
207
|
+
conflict: (code, details) => new DomainError("conflict", `${module}.${code}`, details),
|
|
208
|
+
notFound: (code = "not_found", details) => new DomainError("not_found", `${module}.${code}`, details),
|
|
209
|
+
deny: (code, details) => new DomainError("forbidden", code ? `${module}.${code}` : `${id}.forbidden`, details),
|
|
210
|
+
};
|
|
211
|
+
};
|
|
212
|
+
|
|
213
|
+
/* ────────────────────────────────────────────────────────────────────────────
|
|
214
|
+
* Adapters and dispatcher seams
|
|
215
|
+
* ──────────────────────────────────────────────────────────────────────────── */
|
|
216
|
+
|
|
217
|
+
export interface DatabaseAdapter<Db = unknown, Tx = Db> {
|
|
218
|
+
/** Root handle, used by top-level queries. */
|
|
219
|
+
readonly db: Db;
|
|
220
|
+
readonly transactions: "interactive";
|
|
221
|
+
transaction<T>(fn: (tx: Tx) => Promise<T>): Promise<T>;
|
|
222
|
+
/** An adapter bound to an existing transaction (nested transactions become savepoints). Used by the test helper. */
|
|
223
|
+
nest?(tx: Tx): DatabaseAdapter<Tx, Tx>;
|
|
224
|
+
/** Did this transaction lose a race the database says to retry (deadlock, serialization failure)? */
|
|
225
|
+
retryable?(error: unknown): boolean;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
export interface Dispatcher {
|
|
229
|
+
/** Inside the transaction, before commit. In-process: nothing. Outbox: insert rows with `tx`. */
|
|
230
|
+
enqueue?(tx: unknown, envelopes: Envelope[]): Promise<void>;
|
|
231
|
+
/** After commit. `dispatch` runs the listeners for one envelope and never throws (failures go to `onError`). */
|
|
232
|
+
deliver(envelopes: Envelope[], dispatch: (envelope: Envelope) => Promise<void>): Promise<void>;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** Default dispatcher: delivers right after commit, in this process. Lost on crash: use an outbox when that matters. */
|
|
236
|
+
export const inProcess = (): Dispatcher => ({
|
|
237
|
+
async deliver(envelopes, dispatch) {
|
|
238
|
+
for (const e of envelopes) await dispatch(e);
|
|
239
|
+
},
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
export interface Call<M = unknown> {
|
|
243
|
+
id: string;
|
|
244
|
+
kind: Kind | "listener";
|
|
245
|
+
/** The function's `meta` (undefined for listeners and functions without it). */
|
|
246
|
+
meta: M | undefined;
|
|
247
|
+
/** Raw input as received (before validation). */
|
|
248
|
+
input: unknown;
|
|
249
|
+
scope: object;
|
|
250
|
+
depth: number;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
export interface RegistryOptions<Mods extends Record<string, object>> {
|
|
254
|
+
/** One entry per module: `{ bookings, availability }` with `import * as bookings from "./bookings"`. */
|
|
255
|
+
modules: Mods;
|
|
256
|
+
database?: DatabaseAdapter<any, any>;
|
|
257
|
+
services?: object;
|
|
258
|
+
events?: Dispatcher;
|
|
259
|
+
/** Wraps every call, including ones that fail validation or authorization: logging, tracing, audit. */
|
|
260
|
+
wrap?: (call: Call, next: () => Promise<unknown>) => Promise<unknown>;
|
|
261
|
+
/**
|
|
262
|
+
* Serverless: let listeners finish after the response. Pass the platform's global:
|
|
263
|
+
* `import { waitUntil } from "cloudflare:workers"` or `import { waitUntil } from "@vercel/functions"`.
|
|
264
|
+
* Without it, `run` waits for listeners, which is what tests and long-lived servers want.
|
|
265
|
+
*/
|
|
266
|
+
waitUntil?: (promise: Promise<unknown>) => void;
|
|
267
|
+
/** Failures after commit land here (listeners, dispatcher). They never fail the caller. */
|
|
268
|
+
onError?: (error: unknown, info: { listener: string; envelope: Envelope | undefined }) => void;
|
|
269
|
+
now?: () => Date;
|
|
270
|
+
/** Max chain of listener → mutation → event → listener… before delivery stops. Default 8 (real chains are 2 or 3). */
|
|
271
|
+
maxEventDepth?: number;
|
|
272
|
+
/**
|
|
273
|
+
* Re-run a top-level mutation in a fresh transaction when the database says it lost a race (deadlock,
|
|
274
|
+
* serialization failure). Safe because mutations have no side effects and events are rebuilt per attempt.
|
|
275
|
+
* Default 3 attempts in total; `{ attempts: 1 }` turns it off.
|
|
276
|
+
*/
|
|
277
|
+
retry?: { attempts?: number };
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
export interface CallerOptions {
|
|
281
|
+
/** Aborts the call before it starts work. Listeners never get it: they outlive the request. */
|
|
282
|
+
signal?: AbortSignal;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** A registry bound to a scope: `const caller = registry.as(scope)`. */
|
|
286
|
+
export interface Caller<S extends object = object> {
|
|
287
|
+
readonly scope: S;
|
|
288
|
+
run<F extends Fn>(fn: F, input: FnIn<F>): Promise<FnOut<F>>;
|
|
289
|
+
with(patch: Partial<S>): Caller<S>;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
export interface Registered {
|
|
293
|
+
id: string;
|
|
294
|
+
module: string;
|
|
295
|
+
name: string;
|
|
296
|
+
}
|
|
297
|
+
export interface RegisteredFn extends Registered {
|
|
298
|
+
fn: Fn;
|
|
299
|
+
kind: Kind;
|
|
300
|
+
/** Has `expose`: adapters publish it. */
|
|
301
|
+
exposed: boolean;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/* ────────────────────────────────────────────────────────────────────────────
|
|
305
|
+
* init: typed constructors
|
|
306
|
+
* ──────────────────────────────────────────────────────────────────────────── */
|
|
307
|
+
|
|
308
|
+
type TypedOptions<C extends Config, Mods extends Record<string, object>> = Omit<RegistryOptions<Mods>, "wrap"> & {
|
|
309
|
+
/** Wraps every call, including ones that fail validation or authorization: logging, tracing, audit. */
|
|
310
|
+
wrap?: (call: Call<MetaOf<C>>, next: () => Promise<unknown>) => Promise<unknown>;
|
|
311
|
+
} &
|
|
312
|
+
({} extends ServicesOf<C> ? { services?: ServicesOf<C> } : { services: ServicesOf<C> }) &
|
|
313
|
+
([DbOf<C>] extends [never] ? { database?: undefined } : { database: DatabaseAdapter<any, DbOf<C>> });
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* Typed constructors for your app. Curried so policy names are inferred while `Config` is explicit:
|
|
317
|
+
*
|
|
318
|
+
* ```ts
|
|
319
|
+
* export const { query, mutation, action, event, on, createRegistry } = init<Config>()({
|
|
320
|
+
* policies: { public: () => true, staff: (s): s is Staff => isStaff(s) },
|
|
321
|
+
* });
|
|
322
|
+
* ```
|
|
323
|
+
*/
|
|
324
|
+
/** Keys `Config` doesn't know are errors, so a typo like `servises` can't be silently ignored. */
|
|
325
|
+
type OnlyKnownKeys<C> = { [K in Exclude<keyof C, keyof Config>]: never };
|
|
326
|
+
|
|
327
|
+
export function init<C extends Config & OnlyKnownKeys<C>>(): Init<C> {
|
|
328
|
+
return ((options?: { policies?: Record<string, Policy<any>> }) => constructors<C, {}>(options?.policies ?? {})) as Init<C>;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
interface Init<C extends Config> {
|
|
332
|
+
(): Constructors<C, {}>;
|
|
333
|
+
<P extends Record<string, Policy<ScopeOf<C>>>>(options: { policies: P }): Constructors<C, P>;
|
|
334
|
+
}
|
|
335
|
+
type Constructors<C extends Config, P> = ReturnType<typeof constructors<C, P>>;
|
|
336
|
+
|
|
337
|
+
function constructors<C extends Config, P>(policies: Record<string, Policy<any>>) {
|
|
338
|
+
const make =
|
|
339
|
+
<K extends Kind>(kind: K) =>
|
|
340
|
+
({ expose, ...def }: any): any => {
|
|
341
|
+
let check: Fn["check"];
|
|
342
|
+
if (typeof expose === "function") check = expose;
|
|
343
|
+
else if (expose !== undefined) {
|
|
344
|
+
check = policies[expose];
|
|
345
|
+
if (!check) throw new Error(`[logic-sdk] Unknown policy "${expose}". Define it in init()({ policies }).`);
|
|
346
|
+
}
|
|
347
|
+
return Object.freeze({ [BRAND]: kind, kind, outputSchema: undefined, ...def, check });
|
|
348
|
+
};
|
|
349
|
+
|
|
350
|
+
return {
|
|
351
|
+
/** Create the registry once at startup: `createRegistry({ modules, database, services })`. */
|
|
352
|
+
createRegistry: <const Mods extends Record<string, object>>(options: TypedOptions<C, Mods>) =>
|
|
353
|
+
build<ScopeOf<C>, Mods>(options as RegistryOptions<Mods>, {}), // meta in wrap is typed by MetaOf<C>; the values come from typed defs
|
|
354
|
+
/** Reads data. Can run other queries. No writes, no events, no services. */
|
|
355
|
+
query: make("query") as Constructor<C, "query", P>,
|
|
356
|
+
/** Changes data inside one transaction. Can run queries and mutations (same transaction) and emit events. */
|
|
357
|
+
mutation: make("mutation") as Constructor<C, "mutation", P>,
|
|
358
|
+
/** Talks to the outside world (payments, email, AI). No transaction; each mutation it runs commits on its own. */
|
|
359
|
+
action: make("action") as Constructor<C, "action", P>,
|
|
360
|
+
/** Something that happened. Emitted by mutations, delivered after commit. */
|
|
361
|
+
event: <S extends Schema>(def: { schema: S; description?: string }): EventDef<In<S>, Out<S>> =>
|
|
362
|
+
Object.freeze({ [BRAND]: "event" as const, kind: "event" as const, ...def }),
|
|
363
|
+
/** React to an event after commit, like an action. Must be idempotent. `on(() => bookings.confirmed, ...)` */
|
|
364
|
+
on: <O>(
|
|
365
|
+
event: () => EventDef<any, O>,
|
|
366
|
+
execute: (payload: O, ctx: ListenerCtx<C, O>) => Promise<unknown>,
|
|
367
|
+
opts: { description?: string } = {},
|
|
368
|
+
): Listener<O> =>
|
|
369
|
+
Object.freeze({
|
|
370
|
+
[BRAND]: "listener" as const,
|
|
371
|
+
kind: "listener" as const,
|
|
372
|
+
event,
|
|
373
|
+
description: opts.description,
|
|
374
|
+
execute: execute as Listener<O>["execute"],
|
|
375
|
+
}),
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/* ────────────────────────────────────────────────────────────────────────────
|
|
380
|
+
* createRegistry
|
|
381
|
+
* ──────────────────────────────────────────────────────────────────────────── */
|
|
382
|
+
|
|
383
|
+
const INTERNAL: unique symbol = Symbol.for("logic-sdk.internal") as any;
|
|
384
|
+
|
|
385
|
+
interface TxState {
|
|
386
|
+
db: unknown;
|
|
387
|
+
doomed: boolean;
|
|
388
|
+
reason: unknown;
|
|
389
|
+
outbox: Envelope[];
|
|
390
|
+
pending: Promise<void>[];
|
|
391
|
+
}
|
|
392
|
+
interface Frame {
|
|
393
|
+
scope: object;
|
|
394
|
+
depth: number;
|
|
395
|
+
opts: CallerOptions & { eventDepth?: number };
|
|
396
|
+
tx?: TxState;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
export interface Overrides {
|
|
400
|
+
database?: DatabaseAdapter<any, any>;
|
|
401
|
+
services?: object;
|
|
402
|
+
events?: Dispatcher;
|
|
403
|
+
now?: () => Date;
|
|
404
|
+
stubs?: Map<Fn, (input: any, ctx: any) => Promise<any>>;
|
|
405
|
+
record?: (envelope: Envelope) => void;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
export type Registry<S extends object = object, Mods extends Record<string, object> = Record<string, object>> = ReturnType<
|
|
409
|
+
typeof build<S, Mods>
|
|
410
|
+
>;
|
|
411
|
+
|
|
412
|
+
/** Create the registry once at startup. Prefer the `createRegistry` returned by `init()`: it's typed with your config. */
|
|
413
|
+
export function createRegistry<S extends object = object, const Mods extends Record<string, object> = Record<string, object>>(
|
|
414
|
+
options: RegistryOptions<Mods>,
|
|
415
|
+
) {
|
|
416
|
+
return build<S, Mods>(options, {});
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
const describeIssues = (issues: readonly StandardSchemaV1.Issue[]) =>
|
|
420
|
+
issues.map((i) => ({ message: i.message, path: i.path?.map((p) => (typeof p === "object" ? p.key : p)) }));
|
|
421
|
+
|
|
422
|
+
/**
|
|
423
|
+
* What `createRegistry` finds in your modules, without a database or services: every function, event and
|
|
424
|
+
* listener with its id. For tools (the CLI, docs generators) that inspect an app without running it.
|
|
425
|
+
*/
|
|
426
|
+
export function describeModules(modules: Record<string, object>) {
|
|
427
|
+
const ids = new Map<object, string>();
|
|
428
|
+
const functions: RegisteredFn[] = [];
|
|
429
|
+
const events: (Registered & { event: EventDef })[] = [];
|
|
430
|
+
const listeners: (Registered & { listener: Listener; event: EventDef })[] = [];
|
|
431
|
+
|
|
432
|
+
for (const [module, ns] of Object.entries(modules)) {
|
|
433
|
+
for (const [name, value] of Object.entries(ns)) {
|
|
434
|
+
if (!value || typeof value !== "object" || !(BRAND in value) || ids.has(value)) continue;
|
|
435
|
+
const id = `${module}.${name}`;
|
|
436
|
+
ids.set(value, id);
|
|
437
|
+
const kind = (value as any)[BRAND];
|
|
438
|
+
if (kind === "event") events.push({ id, module, name, event: value as EventDef });
|
|
439
|
+
else if (kind === "listener") {
|
|
440
|
+
const listener = value as Listener;
|
|
441
|
+
listeners.push({ id, module, name, listener, event: listener.event() });
|
|
442
|
+
} else functions.push({ id, module, name, kind, fn: value as Fn, exposed: typeof (value as Fn).check === "function" });
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
return { ids, functions, events, listeners };
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
function build<S extends object, Mods extends Record<string, object>>(options: RegistryOptions<Mods>, o: Overrides) {
|
|
449
|
+
const { ids, functions, events, listeners } = describeModules(options.modules);
|
|
450
|
+
|
|
451
|
+
const database = o.database ?? options.database;
|
|
452
|
+
const services = o.services ?? options.services ?? {};
|
|
453
|
+
const dispatcher = o.events ?? options.events ?? inProcess();
|
|
454
|
+
const now = o.now ?? options.now ?? (() => new Date());
|
|
455
|
+
const wrap = options.wrap ?? ((_c, next) => next());
|
|
456
|
+
const maxEventDepth = options.maxEventDepth ?? 8;
|
|
457
|
+
const attempts = Math.max(1, options.retry?.attempts ?? 3);
|
|
458
|
+
const reportRaw =
|
|
459
|
+
options.onError ?? ((e, info) => console.error(`[logic-sdk] ${info.listener} failed`, e));
|
|
460
|
+
const report = (e: unknown, info: { listener: string; envelope: Envelope | undefined }) => {
|
|
461
|
+
try {
|
|
462
|
+
reportRaw(e, info);
|
|
463
|
+
} catch (inner) {
|
|
464
|
+
console.error("[logic-sdk] onError threw", inner, "while reporting", e);
|
|
465
|
+
}
|
|
466
|
+
};
|
|
467
|
+
|
|
468
|
+
if (functions.some((f) => f.kind === "mutation") && database?.transactions !== "interactive")
|
|
469
|
+
throw new Error(
|
|
470
|
+
"[logic-sdk] Mutations need a database adapter with interactive transactions (e.g. drizzleAdapter(db)). " +
|
|
471
|
+
"Drivers without them (Cloudflare D1, HTTP drivers) are not supported for mutations.",
|
|
472
|
+
);
|
|
473
|
+
for (const l of listeners)
|
|
474
|
+
if (!l.event || !ids.has(l.event))
|
|
475
|
+
throw new Error(`[logic-sdk] Listener ${l.id} listens to an event that isn't registered in any module.`);
|
|
476
|
+
|
|
477
|
+
const idOf = (x: object) => {
|
|
478
|
+
const id = ids.get(x);
|
|
479
|
+
if (!id) throw new Error("[logic-sdk] This function or event isn't registered. Add its module to createRegistry({ modules }).");
|
|
480
|
+
return id;
|
|
481
|
+
};
|
|
482
|
+
|
|
483
|
+
async function parseInput(schema: Schema, value: unknown, code: string) {
|
|
484
|
+
const r = await schema["~standard"].validate(value);
|
|
485
|
+
if (r.issues) throw new DomainError("invalid", code, { issues: describeIssues(r.issues) });
|
|
486
|
+
return r.value;
|
|
487
|
+
}
|
|
488
|
+
/** Output and event payloads are produced by our own code: invalid means a bug, not a bad request. */
|
|
489
|
+
async function parseOwn(schema: Schema, value: unknown, what: string) {
|
|
490
|
+
const r = await schema["~standard"].validate(value);
|
|
491
|
+
if (r.issues) throw new Error(`[logic-sdk] ${what} is invalid: ${JSON.stringify(describeIssues(r.issues))}`);
|
|
492
|
+
return r.value;
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
// ── listeners ────────────────────────────────────────────────────────────
|
|
496
|
+
const byEvent = new Map<string, (Registered & { listener: Listener })[]>();
|
|
497
|
+
for (const l of listeners) {
|
|
498
|
+
const name = idOf(l.event);
|
|
499
|
+
byEvent.set(name, [...(byEvent.get(name) ?? []), l]);
|
|
500
|
+
}
|
|
501
|
+
const eventByName = new Map(events.map((e) => [e.id, e.event]));
|
|
502
|
+
|
|
503
|
+
/** Run every listener for one envelope. Returns the failures instead of throwing. */
|
|
504
|
+
async function runListeners(envelope: Envelope, eventDepth: number) {
|
|
505
|
+
const failures: { listener: string; error: unknown }[] = [];
|
|
506
|
+
const event = eventByName.get(envelope.name);
|
|
507
|
+
for (const l of byEvent.get(envelope.name) ?? []) {
|
|
508
|
+
const frame: Frame = { scope: envelope.scope, depth: 0, opts: { eventDepth } };
|
|
509
|
+
try {
|
|
510
|
+
await wrap({ id: l.id, kind: "listener", meta: undefined, input: envelope.payload, scope: envelope.scope, depth: 0 }, async () => {
|
|
511
|
+
const payload = event ? await parseOwn(event.schema, envelope.payload, `${envelope.name} payload`) : envelope.payload;
|
|
512
|
+
return l.listener.execute(payload, { ...actionCtx(frame, l.id), event: { ...envelope, payload } });
|
|
513
|
+
});
|
|
514
|
+
} catch (error) {
|
|
515
|
+
failures.push({ listener: l.id, error });
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
return failures;
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
/** In-process delivery: failures go to onError. */
|
|
522
|
+
const deliverOne = (eventDepth: number) => async (envelope: Envelope) => {
|
|
523
|
+
for (const f of await runListeners(envelope, eventDepth)) report(f.error, { listener: f.listener, envelope });
|
|
524
|
+
};
|
|
525
|
+
|
|
526
|
+
/** Public: for durable dispatchers. Throws an AggregateError if any listener failed, so the consumer can retry. */
|
|
527
|
+
async function dispatch(envelope: Envelope) {
|
|
528
|
+
const failures = await runListeners(envelope, 1);
|
|
529
|
+
if (failures.length)
|
|
530
|
+
throw new AggregateError(
|
|
531
|
+
failures.map((f) => f.error),
|
|
532
|
+
`[logic-sdk] ${failures.length} listener(s) failed for ${envelope.name}: ${failures.map((f) => f.listener).join(", ")}`,
|
|
533
|
+
);
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
// ── ctx ──────────────────────────────────────────────────────────────────
|
|
537
|
+
const child = (frame: Frame): Frame => ({ ...frame, depth: frame.depth + 1 });
|
|
538
|
+
const rescope = (frame: Frame, patch: object): Frame => ({ ...frame, scope: { ...frame.scope, ...patch } });
|
|
539
|
+
|
|
540
|
+
function queryCtx(frame: Frame, id: string): QueryCtx<any> {
|
|
541
|
+
return {
|
|
542
|
+
...failFor(id),
|
|
543
|
+
scope: frame.scope,
|
|
544
|
+
now,
|
|
545
|
+
signal: frame.opts.signal,
|
|
546
|
+
db: frame.tx ? frame.tx.db : database?.db,
|
|
547
|
+
run: (fn, input) => invoke(fn, input, child(frame), ["query"]),
|
|
548
|
+
with: (patch) => queryCtx(rescope(frame, patch), id),
|
|
549
|
+
};
|
|
550
|
+
}
|
|
551
|
+
function mutationCtx(frame: Frame, id: string): MutationCtx<any> {
|
|
552
|
+
const tx = frame.tx!;
|
|
553
|
+
return {
|
|
554
|
+
...failFor(id),
|
|
555
|
+
scope: frame.scope,
|
|
556
|
+
now,
|
|
557
|
+
signal: frame.opts.signal,
|
|
558
|
+
db: tx.db,
|
|
559
|
+
run: (fn, input) => invoke(fn, input, child(frame), ["query", "mutation"]),
|
|
560
|
+
emit: (event, payload) => {
|
|
561
|
+
const name = idOf(event);
|
|
562
|
+
payload = structuredClone(payload); // what was emitted is what gets delivered, even if the caller mutates it after
|
|
563
|
+
// reserve the slot now so events keep emit order, even with async schemas
|
|
564
|
+
const envelope: Envelope = {
|
|
565
|
+
id: crypto.randomUUID(),
|
|
566
|
+
name,
|
|
567
|
+
payload,
|
|
568
|
+
scope: structuredClone(frame.scope),
|
|
569
|
+
occurredAt: now().toISOString(),
|
|
570
|
+
};
|
|
571
|
+
tx.outbox.push(envelope);
|
|
572
|
+
const check = parseOwn(event.schema, payload, `${name} payload`).then(() => {});
|
|
573
|
+
check.catch(() => {}); // surfaced at commit; never an unhandled rejection
|
|
574
|
+
tx.pending.push(check);
|
|
575
|
+
},
|
|
576
|
+
with: (patch) => mutationCtx(rescope(frame, patch), id),
|
|
577
|
+
};
|
|
578
|
+
}
|
|
579
|
+
function actionCtx(frame: Frame, id: string): ActionCtx<any> {
|
|
580
|
+
return {
|
|
581
|
+
...failFor(id),
|
|
582
|
+
scope: frame.scope,
|
|
583
|
+
now,
|
|
584
|
+
signal: frame.opts.signal,
|
|
585
|
+
services,
|
|
586
|
+
run: (fn, input) => invoke(fn, input, child({ ...frame, tx: undefined }), ["query", "mutation", "action"]),
|
|
587
|
+
with: (patch) => actionCtx(rescope(frame, patch), id),
|
|
588
|
+
};
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
// ── invoke ───────────────────────────────────────────────────────────────
|
|
592
|
+
async function invoke(fn: Fn, rawInput: unknown, frame: Frame, allowed: Kind[]): Promise<any> {
|
|
593
|
+
const id = idOf(fn);
|
|
594
|
+
if (!allowed.includes(fn.kind))
|
|
595
|
+
throw new Error(`[logic-sdk] ${id} is a ${fn.kind}; it can't be run from here (allowed: ${allowed.join(", ")}).`);
|
|
596
|
+
|
|
597
|
+
const call: Call = { id, kind: fn.kind, meta: fn.meta, input: rawInput, scope: frame.scope, depth: frame.depth };
|
|
598
|
+
|
|
599
|
+
/** Validate and check before any transaction opens: bad or denied calls never touch the database. */
|
|
600
|
+
const prepare = async () => {
|
|
601
|
+
frame.opts.signal?.throwIfAborted();
|
|
602
|
+
const input = await parseInput(fn.inputSchema, rawInput, `${id}.invalid_input`);
|
|
603
|
+
if (fn.check && !(await fn.check(frame.scope, input))) throw new DomainError("forbidden", `${id}.forbidden`);
|
|
604
|
+
return input;
|
|
605
|
+
};
|
|
606
|
+
const execute = async (input: unknown, ctx: unknown) => {
|
|
607
|
+
const stub = o.stubs?.get(fn);
|
|
608
|
+
const out = await (stub ? stub(input, ctx) : fn.execute(input, ctx));
|
|
609
|
+
return fn.outputSchema ? parseOwn(fn.outputSchema, out, `${id} output`) : out;
|
|
610
|
+
};
|
|
611
|
+
|
|
612
|
+
return wrap(call, async () => {
|
|
613
|
+
if (fn.kind === "query") return execute(await prepare(), queryCtx(frame, id));
|
|
614
|
+
if (fn.kind === "action") return execute(await prepare(), actionCtx(frame, id));
|
|
615
|
+
|
|
616
|
+
// mutation joining an open transaction: any failure dooms it, even if the caller catches
|
|
617
|
+
if (frame.tx) {
|
|
618
|
+
const tx = frame.tx;
|
|
619
|
+
try {
|
|
620
|
+
return await execute(await prepare(), mutationCtx(frame, id));
|
|
621
|
+
} catch (e) {
|
|
622
|
+
if (!tx.doomed) {
|
|
623
|
+
tx.doomed = true;
|
|
624
|
+
tx.reason = e;
|
|
625
|
+
}
|
|
626
|
+
throw e;
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
// top-level mutation: open the transaction, commit, then deliver events.
|
|
631
|
+
// A lost race (deadlock, serialization failure) re-runs it in a fresh transaction.
|
|
632
|
+
const input = await prepare();
|
|
633
|
+
let committed: { out: unknown; outbox: Envelope[] };
|
|
634
|
+
for (let attempt = 1; ; attempt++) {
|
|
635
|
+
let state: TxState | undefined;
|
|
636
|
+
try {
|
|
637
|
+
committed = await database!.transaction(async (txDb) => {
|
|
638
|
+
// fresh per attempt, so a retry never reuses events from a failed attempt
|
|
639
|
+
const tx: TxState = (state = { db: txDb, doomed: false, reason: undefined, outbox: [], pending: [] });
|
|
640
|
+
const out = await execute(input, mutationCtx({ ...frame, tx }, id));
|
|
641
|
+
await Promise.all(tx.pending);
|
|
642
|
+
if (tx.doomed) throw tx.reason;
|
|
643
|
+
await dispatcher.enqueue?.(txDb, tx.outbox);
|
|
644
|
+
return { out, outbox: tx.outbox };
|
|
645
|
+
});
|
|
646
|
+
break;
|
|
647
|
+
} catch (e) {
|
|
648
|
+
if (attempt < attempts && database!.retryable?.(e)) {
|
|
649
|
+
// a random pause, so transactions that just deadlocked don't retry in lockstep and collide again
|
|
650
|
+
await new Promise((r) => setTimeout(r, Math.random() * 20 * attempt));
|
|
651
|
+
continue;
|
|
652
|
+
}
|
|
653
|
+
throw e;
|
|
654
|
+
} finally {
|
|
655
|
+
if (state) await Promise.allSettled(state.pending);
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
// committed. Nothing below may fail the caller.
|
|
660
|
+
if (committed.outbox.length) await afterCommit(committed.outbox, frame);
|
|
661
|
+
return committed.out;
|
|
662
|
+
});
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
async function afterCommit(outbox: Envelope[], frame: Frame) {
|
|
666
|
+
try {
|
|
667
|
+
for (const e of outbox) o.record?.(e);
|
|
668
|
+
const eventDepth = (frame.opts.eventDepth ?? 0) + 1;
|
|
669
|
+
if (eventDepth > maxEventDepth) {
|
|
670
|
+
report(new Error(`[logic-sdk] event chain deeper than ${maxEventDepth}: stopped delivering (listener loop?)`), {
|
|
671
|
+
listener: "(dispatcher)",
|
|
672
|
+
envelope: outbox[0],
|
|
673
|
+
});
|
|
674
|
+
return;
|
|
675
|
+
}
|
|
676
|
+
const delivery = (async () => dispatcher.deliver(outbox, deliverOne(eventDepth)))().catch((e) =>
|
|
677
|
+
report(e, { listener: "(dispatcher)", envelope: outbox[0] }),
|
|
678
|
+
);
|
|
679
|
+
if (options.waitUntil) {
|
|
680
|
+
try {
|
|
681
|
+
options.waitUntil(delivery);
|
|
682
|
+
return;
|
|
683
|
+
} catch (e) {
|
|
684
|
+
report(e, { listener: "(waitUntil)", envelope: outbox[0] });
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
await delivery;
|
|
688
|
+
} catch (e) {
|
|
689
|
+
report(e, { listener: "(after commit)", envelope: outbox[0] });
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
function makeCaller(scope: S, opts: CallerOptions): Caller<S> {
|
|
694
|
+
return {
|
|
695
|
+
scope,
|
|
696
|
+
run: (fn, input) => invoke(fn, input, { scope, depth: 0, opts }, ["query", "mutation", "action"]),
|
|
697
|
+
with: (patch) => makeCaller({ ...scope, ...patch }, opts),
|
|
698
|
+
};
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
return {
|
|
702
|
+
/** The modules you registered (typed), for adapters that build typed routers. */
|
|
703
|
+
modules: options.modules,
|
|
704
|
+
/** Bind who is calling, once per request, job or test: `const caller = registry.as(scope)`. */
|
|
705
|
+
as: (scope: S, opts: CallerOptions = {}): Caller<S> => makeCaller(scope, opts),
|
|
706
|
+
/** Everything the registry can do. Adapters read this. */
|
|
707
|
+
functions: functions as readonly RegisteredFn[],
|
|
708
|
+
events: events as readonly (Registered & { event: EventDef })[],
|
|
709
|
+
listeners: listeners as readonly (Registered & { listener: Listener; event: EventDef })[],
|
|
710
|
+
idOf,
|
|
711
|
+
/** Deliver one stored envelope to its listeners (durable dispatchers). Throws if any listener failed, so you can retry. */
|
|
712
|
+
dispatch,
|
|
713
|
+
/** @internal used by `logic-sdk/testing` */
|
|
714
|
+
[INTERNAL]: { options, overrides: o, derive: (more: Overrides) => build<S, Mods>(options, { ...o, ...more }) },
|
|
715
|
+
};
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
/** @internal */
|
|
719
|
+
export const internal = (registry: Registry<any, any>) => registry[INTERNAL];
|