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