logic-sdk 0.0.0-stage → 0.2.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.
@@ -0,0 +1,444 @@
1
+ import type { StandardSchemaV1 } from "@standard-schema/spec";
2
+ type Schema<I = any, O = any> = StandardSchemaV1<I, O>;
3
+ type In<S> = S extends Schema<infer I, any> ? I : never;
4
+ type Out<S> = S extends Schema<any, infer O> ? O : never;
5
+ /** What you declare once in `init<...>()`. */
6
+ export interface Config {
7
+ /** Who and where: actor, account, locale... Must be JSON-serializable (it travels with events). */
8
+ scope: object;
9
+ /** The transaction handle mutations receive (e.g. a Drizzle transaction). */
10
+ db?: unknown;
11
+ /** What queries receive. Defaults to `db`. Use a read-only type (e.g. `DrizzleReader<Tx>`). */
12
+ reader?: unknown;
13
+ /** Side-effecting services (mailer, payments...). Only actions and listeners receive them. */
14
+ services?: object;
15
+ /** The shape of `meta` on your functions (tags, rate limits, "agent may call"...). Read by `wrap` and adapters. */
16
+ meta?: object;
17
+ }
18
+ type ScopeOf<C extends Config> = C["scope"];
19
+ type DbOf<C extends Config> = C extends {
20
+ db: infer D;
21
+ } ? D : never;
22
+ type ReaderOf<C extends Config> = C extends {
23
+ reader: infer R;
24
+ } ? R : DbOf<C>;
25
+ type ServicesOf<C extends Config> = C extends {
26
+ services: infer S;
27
+ } ? S : {};
28
+ type MetaOf<C extends Config> = C extends {
29
+ meta: infer M;
30
+ } ? M : never;
31
+ export type Kind = "query" | "mutation" | "action";
32
+ declare const types: unique symbol;
33
+ declare const BRAND: unique symbol;
34
+ /** A query, mutation or action. Call it with `caller.run(fn, input)` or `ctx.run(fn, input)`. */
35
+ export interface Fn<K extends Kind = Kind, I = any, O = any, E extends boolean = boolean> {
36
+ readonly [BRAND]: K;
37
+ readonly kind: K;
38
+ readonly description: string;
39
+ readonly inputSchema: Schema;
40
+ readonly outputSchema?: Schema;
41
+ /** Your own data about the function. Checked against `meta` in `init` where you set it, typed in `wrap`; loose here, for adapters. */
42
+ readonly meta?: any;
43
+ /** Who may call it (from `authorize`). Runs on every call, before validation. */
44
+ readonly authorize?: Policy<any>;
45
+ /** `true`: adapters may publish it (HTTP, oRPC, AI tools). Requires `authorize` and `outputSchema`. */
46
+ readonly expose?: true;
47
+ readonly execute: (input: any, ctx: any) => Promise<any>;
48
+ /** Phantom types, never set at runtime. */
49
+ readonly [types]?: {
50
+ input: I;
51
+ output: O;
52
+ exposed: E;
53
+ };
54
+ }
55
+ /** A function with `expose: true`: adapters may publish it. */
56
+ export type ExposedFn<K extends Kind = Kind, I = any, O = any> = Fn<K, I, O, true>;
57
+ /** What callers pass to a function. */
58
+ export type FnIn<F> = F extends Fn<any, infer I, any> ? I : never;
59
+ /** What a function returns. */
60
+ export type FnOut<F> = F extends Fn<any, any, infer O> ? O : never;
61
+ /** `I`: what `emit` takes. `O`: what listeners receive (after the schema's transforms and defaults). */
62
+ export interface EventDef<I = any, O = I> {
63
+ readonly [BRAND]: "event";
64
+ readonly kind: "event";
65
+ readonly schema: Schema;
66
+ readonly description?: string;
67
+ readonly [types]?: {
68
+ input: I;
69
+ payload: O;
70
+ };
71
+ }
72
+ /**
73
+ * What a dispatcher stores and delivers. Fully JSON: `payload` is what was emitted (validated),
74
+ * and listeners get it parsed again by the event's schema at delivery.
75
+ */
76
+ export interface Envelope<P = unknown, S = object> {
77
+ id: string;
78
+ name: string;
79
+ payload: P;
80
+ scope: S;
81
+ occurredAt: string;
82
+ }
83
+ export interface Listener<O = any> {
84
+ readonly [BRAND]: "listener";
85
+ readonly kind: "listener";
86
+ /** Lazy, so listeners can import other modules' barrels without import cycles. */
87
+ readonly event: () => EventDef<any, O>;
88
+ readonly description?: string;
89
+ readonly execute: (payload: O, ctx: any) => Promise<unknown>;
90
+ }
91
+ type Run<Allowed extends Kind> = <F extends Fn<Allowed>>(fn: F, input: FnIn<F>) => Promise<FnOut<F>>;
92
+ /**
93
+ * Expected failures, namespaced to the module you're in: inside `bookings`, `ctx.errors.reject("not_pending")` has
94
+ * code `"bookings.not_pending"`. Throw what they return. Codes are plain strings on purpose (see the errors docs).
95
+ */
96
+ export interface Errors {
97
+ /** A business rule said no, and trying again won't help. `throw ctx.errors.reject("not_pending", { status })` */
98
+ reject(code: string, details?: unknown): DomainError;
99
+ /** Someone else got there first, or it already exists. Refreshing and retrying may work. */
100
+ conflict(code: string, details?: unknown): DomainError;
101
+ /** It doesn't exist, or isn't visible in this scope. Code defaults to `"<module>.not_found"`. */
102
+ notFound(code?: string, details?: unknown): DomainError;
103
+ /** The caller is known but may not do this. Code defaults to `"<module>.<function>.forbidden"`. */
104
+ deny(code?: string, details?: unknown): DomainError;
105
+ }
106
+ interface BaseCtx<S> {
107
+ scope: S;
108
+ /** Expected failures: `throw ctx.errors.reject("not_pending")`. */
109
+ errors: Errors;
110
+ /** Current time. Fixed in tests. */
111
+ now: () => Date;
112
+ }
113
+ /** `S` is the scope, narrowed by the function's policy. Alias it in init.ts: `type QueryCtx = Core.QueryCtx<Config>`. */
114
+ export interface QueryCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<S> {
115
+ db: ReaderOf<C>;
116
+ run: Run<"query">;
117
+ /** The caller's abort signal, if any. */
118
+ signal: AbortSignal | undefined;
119
+ with(patch: Partial<ScopeOf<C>>): QueryCtx<C>;
120
+ }
121
+ export interface MutationCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<S> {
122
+ db: DbOf<C>;
123
+ run: Run<"query" | "mutation">;
124
+ /** Queue an event. Delivered to listeners only after the transaction commits. */
125
+ emit<I>(event: EventDef<I, any>, payload: I): void;
126
+ signal: AbortSignal | undefined;
127
+ with(patch: Partial<ScopeOf<C>>): MutationCtx<C>;
128
+ }
129
+ export interface ActionCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<S> {
130
+ services: ServicesOf<C>;
131
+ /** Each mutation you run here gets its own transaction. */
132
+ run: Run<Kind>;
133
+ /** The caller's abort signal. Always undefined in listeners (they outlive the request). */
134
+ signal: AbortSignal | undefined;
135
+ with(patch: Partial<ScopeOf<C>>): ActionCtx<C>;
136
+ }
137
+ export interface ListenerCtx<C extends Config, O = unknown> extends ActionCtx<C> {
138
+ event: Envelope<unknown, ScopeOf<C>> & {
139
+ payload: O;
140
+ };
141
+ }
142
+ /**
143
+ * Who may call a function at all: signed in, admin, staff. Sync, reads only the scope, returns exactly `true` to allow.
144
+ * Write it as a type guard (`(s): s is Admin => ...`) to narrow `ctx.scope` in `execute`.
145
+ * Rules about one record ("only the owner may cancel") go in `execute`, after loading it.
146
+ */
147
+ export type Policy<S> = (scope: S) => boolean;
148
+ type Guarded<F, S> = F extends (scope: any) => scope is infer G ? G : S;
149
+ type CtxOf<C extends Config, K extends Kind, S> = K extends "query" ? QueryCtx<C, S> : K extends "mutation" ? MutationCtx<C, S> : ActionCtx<C, S>;
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 NotExposed = {
157
+ expose?: undefined;
158
+ };
159
+ type NoPolicy = {
160
+ authorize?: undefined;
161
+ };
162
+ type WithMeta<C extends Config> = {
163
+ meta?: MetaOf<C>;
164
+ };
165
+ type WithOutput<OS extends Schema> = {
166
+ outputSchema: OS;
167
+ };
168
+ /**
169
+ * `expose: true` needs `authorize` and `outputSchema`: you can't publish something without saying who may call it,
170
+ * and what leaves your process is a contract. Internal functions may skip both; `authorize` still runs if set.
171
+ */
172
+ interface Constructor<C extends Config, K extends Kind> {
173
+ <IS extends Schema, OS extends Schema, P extends Policy<ScopeOf<C>>>(def: Def<IS, CtxOf<C, K, Guarded<P, ScopeOf<C>>>, In<OS>> & WithOutput<OS> & WithMeta<C> & {
174
+ authorize: P;
175
+ expose: true;
176
+ }): Fn<K, In<IS>, Out<OS>, true>;
177
+ <IS extends Schema, OS extends Schema, P extends Policy<ScopeOf<C>>>(def: Def<IS, CtxOf<C, K, Guarded<P, ScopeOf<C>>>, In<OS>> & WithOutput<OS> & WithMeta<C> & {
178
+ authorize: P;
179
+ } & NotExposed): Fn<K, In<IS>, Out<OS>, false>;
180
+ <IS extends Schema, R, P extends Policy<ScopeOf<C>>>(def: Def<IS, CtxOf<C, K, Guarded<P, ScopeOf<C>>>, R> & WithMeta<C> & {
181
+ authorize: P;
182
+ } & NotExposed): Fn<K, In<IS>, R, false>;
183
+ <IS extends Schema, OS extends Schema>(def: Def<IS, CtxOf<C, K, ScopeOf<C>>, In<OS>> & WithOutput<OS> & WithMeta<C> & NoPolicy & NotExposed): Fn<K, In<IS>, Out<OS>, false>;
184
+ <IS extends Schema, R>(def: Def<IS, CtxOf<C, K, ScopeOf<C>>, R> & WithMeta<C> & NoPolicy & NotExposed): Fn<K, In<IS>, R, false>;
185
+ }
186
+ export type ErrorKind = "invalid" | "unauthenticated" | "forbidden" | "not_found" | "conflict" | "rejected";
187
+ /**
188
+ * An expected failure: a `kind` (a small fixed set), a namespaced `code` and optional `details`. No HTTP here;
189
+ * adapters map kinds to statuses. Anything else thrown (including invalid output or event payloads, which are
190
+ * bugs) is unexpected: adapters answer 500 and report it.
191
+ */
192
+ export declare class DomainError extends Error {
193
+ readonly kind: ErrorKind;
194
+ readonly code: string;
195
+ readonly details: unknown;
196
+ constructor(kind: ErrorKind, code: string, details?: unknown);
197
+ }
198
+ /** `isDomainError(e)`, or with a code: `isDomainError(e, "availability.dates_unavailable")`. */
199
+ export declare const isDomainError: (e: unknown, code?: string) => e is DomainError;
200
+ export interface DatabaseAdapter<Db = unknown, Tx = Db> {
201
+ /** Root handle, used by top-level queries. */
202
+ readonly db: Db;
203
+ readonly transactions: "interactive";
204
+ transaction<T>(fn: (tx: Tx) => Promise<T>): Promise<T>;
205
+ /** An adapter bound to an existing transaction (nested transactions become savepoints). Used by the test helper. */
206
+ nest?(tx: Tx): DatabaseAdapter<Tx, Tx>;
207
+ /** Did this transaction lose a race the database says to retry (deadlock, serialization failure)? */
208
+ retryable?(error: unknown): boolean;
209
+ }
210
+ export interface Dispatcher {
211
+ /** Inside the transaction, before commit. In-process: nothing. Outbox: insert rows with `tx`. */
212
+ enqueue?(tx: unknown, envelopes: Envelope[]): Promise<void>;
213
+ /** After commit. `dispatch` runs the listeners for one envelope and never throws (failures go to `onError`). */
214
+ deliver(envelopes: Envelope[], dispatch: (envelope: Envelope) => Promise<void>): Promise<void>;
215
+ }
216
+ /** Default dispatcher: delivers right after commit, in this process. Lost on crash: use an outbox when that matters. */
217
+ export declare const inProcess: () => Dispatcher;
218
+ export interface Call<M = unknown> {
219
+ id: string;
220
+ kind: Kind | "listener";
221
+ /** The function's `meta` (undefined for listeners and functions without it). */
222
+ meta: M | undefined;
223
+ /** Raw input as received (before validation). */
224
+ input: unknown;
225
+ scope: object;
226
+ depth: number;
227
+ }
228
+ export interface RegistryOptions<Mods extends Record<string, object>> {
229
+ /** One entry per module: `{ bookings, availability }` with `import * as bookings from "./bookings"`. */
230
+ modules: Mods;
231
+ database?: DatabaseAdapter<any, any>;
232
+ services?: object;
233
+ events?: Dispatcher;
234
+ /** Wraps every call, including ones that fail validation or authorization: logging, tracing, audit. */
235
+ wrap?: (call: Call, next: () => Promise<unknown>) => Promise<unknown>;
236
+ /**
237
+ * Serverless: let listeners finish after the response. Pass the platform's global:
238
+ * `import { waitUntil } from "cloudflare:workers"` or `import { waitUntil } from "@vercel/functions"`.
239
+ * Without it, `run` waits for listeners, which is what tests and long-lived servers want.
240
+ */
241
+ waitUntil?: (promise: Promise<unknown>) => void;
242
+ /** Failures after commit land here (listeners, dispatcher). They never fail the caller. */
243
+ onError?: (error: unknown, info: {
244
+ listener: string;
245
+ envelope: Envelope | undefined;
246
+ }) => void;
247
+ now?: () => Date;
248
+ /** Max chain of listener → mutation → event → listener… before delivery stops. Default 8 (real chains are 2 or 3). */
249
+ maxEventDepth?: number;
250
+ /**
251
+ * Re-run a top-level mutation in a fresh transaction when the database says it lost a race (deadlock,
252
+ * serialization failure). Safe because mutations have no side effects and events are rebuilt per attempt.
253
+ * Default 3 attempts in total; `{ attempts: 1 }` turns it off.
254
+ */
255
+ retry?: {
256
+ attempts?: number;
257
+ };
258
+ }
259
+ export interface CallerOptions {
260
+ /** Aborts the call before it starts work. Listeners never get it: they outlive the request. */
261
+ signal?: AbortSignal;
262
+ }
263
+ /** A registry bound to a scope: `const caller = registry.as(scope)`. */
264
+ export interface Caller<S extends object = object> {
265
+ readonly scope: S;
266
+ run<F extends Fn>(fn: F, input: FnIn<F>): Promise<FnOut<F>>;
267
+ with(patch: Partial<S>): Caller<S>;
268
+ }
269
+ export interface Registered {
270
+ id: string;
271
+ module: string;
272
+ name: string;
273
+ }
274
+ export interface RegisteredFn extends Registered {
275
+ fn: Fn;
276
+ kind: Kind;
277
+ /** Has `expose: true`: adapters may publish it. */
278
+ exposed: boolean;
279
+ }
280
+ type TypedOptions<C extends Config, Mods extends Record<string, object>> = Omit<RegistryOptions<Mods>, "wrap"> & {
281
+ /** Wraps every call, including ones that fail validation or authorization: logging, tracing, audit. */
282
+ wrap?: (call: Call<MetaOf<C>>, next: () => Promise<unknown>) => Promise<unknown>;
283
+ } & ({} extends ServicesOf<C> ? {
284
+ services?: ServicesOf<C>;
285
+ } : {
286
+ services: ServicesOf<C>;
287
+ }) & ([DbOf<C>] extends [never] ? {
288
+ database?: undefined;
289
+ } : {
290
+ database: DatabaseAdapter<any, DbOf<C>>;
291
+ });
292
+ /** Keys `Config` doesn't know are errors, so a typo like `servises` can't be silently ignored. */
293
+ type OnlyKnownKeys<C> = {
294
+ [K in Exclude<keyof C, keyof Config>]: never;
295
+ };
296
+ /**
297
+ * Typed constructors for your app:
298
+ *
299
+ * ```ts
300
+ * export const { query, mutation, action, event, on, createRegistry } = init<Config>();
301
+ * ```
302
+ */
303
+ export declare function init<C extends Config & OnlyKnownKeys<C>>(): {
304
+ /** Create the registry once at startup: `createRegistry({ modules, database, services })`. */
305
+ createRegistry: <const Mods extends Record<string, object>>(options: TypedOptions<C, Mods>) => {
306
+ /** The modules you registered (typed), for adapters that build typed routers. */
307
+ modules: Mods;
308
+ /** Bind who is calling, once per request, job or test: `const caller = registry.as(scope)`. */
309
+ as: (scope: ScopeOf<C>, opts?: CallerOptions) => Caller<ScopeOf<C>>;
310
+ /** Everything the registry can do. Adapters read this. */
311
+ functions: readonly RegisteredFn[];
312
+ events: readonly (Registered & {
313
+ event: EventDef;
314
+ })[];
315
+ listeners: readonly (Registered & {
316
+ listener: Listener;
317
+ event: EventDef;
318
+ })[];
319
+ idOf: (x: object) => string;
320
+ /** Deliver one stored envelope to its listeners (durable dispatchers). Throws if any listener failed, so you can retry. */
321
+ dispatch: (envelope: Envelope) => Promise<void>;
322
+ /** @internal used by `logic-sdk/testing` */
323
+ [INTERNAL]: {
324
+ options: RegistryOptions<Mods>;
325
+ overrides: Overrides;
326
+ derive: (more: Overrides) => /*elided*/ any;
327
+ };
328
+ };
329
+ /** Reads data. Can run other queries. No writes, no events, no services. */
330
+ query: Constructor<C, "query">;
331
+ /** Changes data inside one transaction. Can run queries and mutations (same transaction) and emit events. */
332
+ mutation: Constructor<C, "mutation">;
333
+ /** Talks to the outside world (payments, email, AI). No transaction; each mutation it runs commits on its own. */
334
+ action: Constructor<C, "action">;
335
+ /** Something that happened. Emitted by mutations, delivered after commit. */
336
+ event: <S extends Schema>(def: {
337
+ schema: S;
338
+ description?: string;
339
+ }) => EventDef<In<S>, Out<S>>;
340
+ /** React to an event after commit, like an action. Must be idempotent. `on(() => bookings.confirmed, ...)` */
341
+ on: <O>(event: () => EventDef<any, O>, execute: (payload: O, ctx: ListenerCtx<C, O>) => Promise<unknown>, opts?: {
342
+ description?: string;
343
+ }) => Listener<O>;
344
+ };
345
+ declare const INTERNAL: unique symbol;
346
+ export interface Overrides {
347
+ database?: DatabaseAdapter<any, any>;
348
+ services?: object;
349
+ events?: Dispatcher;
350
+ now?: () => Date;
351
+ stubs?: Map<Fn, (input: any, ctx: any) => Promise<any>>;
352
+ record?: (envelope: Envelope) => void;
353
+ }
354
+ export type Registry<S extends object = object, Mods extends Record<string, object> = Record<string, object>> = ReturnType<typeof build<S, Mods>>;
355
+ /** Create the registry once at startup. Prefer the `createRegistry` returned by `init()`: it's typed with your config. */
356
+ export declare function createRegistry<S extends object = object, const Mods extends Record<string, object> = Record<string, object>>(options: RegistryOptions<Mods>): {
357
+ /** The modules you registered (typed), for adapters that build typed routers. */
358
+ modules: Mods;
359
+ /** Bind who is calling, once per request, job or test: `const caller = registry.as(scope)`. */
360
+ as: (scope: S, opts?: CallerOptions) => Caller<S>;
361
+ /** Everything the registry can do. Adapters read this. */
362
+ functions: readonly RegisteredFn[];
363
+ events: readonly (Registered & {
364
+ event: EventDef;
365
+ })[];
366
+ listeners: readonly (Registered & {
367
+ listener: Listener;
368
+ event: EventDef;
369
+ })[];
370
+ idOf: (x: object) => string;
371
+ /** Deliver one stored envelope to its listeners (durable dispatchers). Throws if any listener failed, so you can retry. */
372
+ dispatch: (envelope: Envelope) => Promise<void>;
373
+ /** @internal used by `logic-sdk/testing` */
374
+ [INTERNAL]: {
375
+ options: RegistryOptions<Mods>;
376
+ overrides: Overrides;
377
+ derive: (more: Overrides) => /*elided*/ any;
378
+ };
379
+ };
380
+ /**
381
+ * What `createRegistry` finds in your modules, without a database or services: every function, event and
382
+ * listener with its id. For tools (the CLI, docs generators) that inspect an app without running it.
383
+ */
384
+ export declare function describeModules(modules: Record<string, object>): {
385
+ ids: Map<object, string>;
386
+ functions: RegisteredFn[];
387
+ events: (Registered & {
388
+ event: EventDef;
389
+ })[];
390
+ listeners: (Registered & {
391
+ listener: Listener;
392
+ event: EventDef;
393
+ })[];
394
+ };
395
+ declare function build<S extends object, Mods extends Record<string, object>>(options: RegistryOptions<Mods>, o: Overrides): {
396
+ /** The modules you registered (typed), for adapters that build typed routers. */
397
+ modules: Mods;
398
+ /** Bind who is calling, once per request, job or test: `const caller = registry.as(scope)`. */
399
+ as: (scope: S, opts?: CallerOptions) => Caller<S>;
400
+ /** Everything the registry can do. Adapters read this. */
401
+ functions: readonly RegisteredFn[];
402
+ events: readonly (Registered & {
403
+ event: EventDef;
404
+ })[];
405
+ listeners: readonly (Registered & {
406
+ listener: Listener;
407
+ event: EventDef;
408
+ })[];
409
+ idOf: (x: object) => string;
410
+ /** Deliver one stored envelope to its listeners (durable dispatchers). Throws if any listener failed, so you can retry. */
411
+ dispatch: (envelope: Envelope) => Promise<void>;
412
+ /** @internal used by `logic-sdk/testing` */
413
+ [INTERNAL]: {
414
+ options: RegistryOptions<Mods>;
415
+ overrides: Overrides;
416
+ derive: (more: Overrides) => /*elided*/ any;
417
+ };
418
+ };
419
+ /** @internal */
420
+ export declare const internal: (registry: Registry<any, any>) => {
421
+ options: RegistryOptions<any>;
422
+ overrides: Overrides;
423
+ derive: (more: Overrides) => {
424
+ /** The modules you registered (typed), for adapters that build typed routers. */
425
+ modules: any;
426
+ /** Bind who is calling, once per request, job or test: `const caller = registry.as(scope)`. */
427
+ as: (scope: any, opts?: CallerOptions) => Caller<any>;
428
+ /** Everything the registry can do. Adapters read this. */
429
+ functions: readonly RegisteredFn[];
430
+ events: readonly (Registered & {
431
+ event: EventDef;
432
+ })[];
433
+ listeners: readonly (Registered & {
434
+ listener: Listener;
435
+ event: EventDef;
436
+ })[];
437
+ idOf: (x: object) => string;
438
+ /** Deliver one stored envelope to its listeners (durable dispatchers). Throws if any listener failed, so you can retry. */
439
+ dispatch: (envelope: Envelope) => Promise<void>;
440
+ /** @internal used by `logic-sdk/testing` */
441
+ [INTERNAL]: /*elided*/ any;
442
+ };
443
+ };
444
+ export {};