logic-sdk 0.2.0 → 0.4.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/src/index.ts CHANGED
@@ -5,8 +5,8 @@ import type { StandardSchemaV1 } from "@standard-schema/spec";
5
5
  * ──────────────────────────────────────────────────────────────────────────── */
6
6
 
7
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;
8
+ type In<S> = S extends StandardSchemaV1<infer I, unknown> ? I : never;
9
+ type Out<S> = S extends StandardSchemaV1<unknown, infer O> ? O : never;
10
10
 
11
11
  /** What you declare once in `init<...>()`. */
12
12
  export interface Config {
@@ -18,6 +18,11 @@ export interface Config {
18
18
  reader?: unknown;
19
19
  /** Side-effecting services (mailer, payments...). Only actions and listeners receive them. */
20
20
  services?: object;
21
+ /**
22
+ * Your app's settings, read as `ctx.config` in every function: base URL, limits, switches. Plain data, read-only.
23
+ * Build it once from your env at the entry; clients built from secrets go in `services` instead.
24
+ */
25
+ config?: object;
21
26
  /** The shape of `meta` on your functions (tags, rate limits, "agent may call"...). Read by `wrap` and adapters. */
22
27
  meta?: object;
23
28
  }
@@ -26,48 +31,65 @@ type DbOf<C extends Config> = C extends { db: infer D } ? D : never;
26
31
  type ReaderOf<C extends Config> = C extends { reader: infer R } ? R : DbOf<C>;
27
32
  type ServicesOf<C extends Config> = C extends { services: infer S } ? S : {};
28
33
  type MetaOf<C extends Config> = C extends { meta: infer M } ? M : never;
34
+ /** Without a declared `config`, nothing may be passed or read: no silently ignored settings. */
35
+ type ConfigOf<C extends Config> = C extends { config: infer F } ? F : Record<string, never>;
36
+
37
+ type Primitive = string | number | boolean | bigint | symbol | null | undefined;
38
+ /** Read-only all the way down: what `ctx.config` gives you. Primitives (branded ones too) stay as they are. */
39
+ export type Frozen<T> = T extends Primitive
40
+ ? T
41
+ : T extends readonly (infer U)[]
42
+ ? readonly Frozen<U>[]
43
+ : { readonly [K in keyof T]: Frozen<T[K]> };
44
+ /** Any part of `T`, at any depth: what a test may override in `config`. Arrays are replaced whole, like at runtime. */
45
+ export type DeepPartial<T> = T extends Primitive | readonly unknown[] ? T : { [K in keyof T]?: DeepPartial<T[K]> };
29
46
 
30
47
  export type Kind = "query" | "mutation" | "action";
31
48
 
32
49
  declare const types: unique symbol;
33
- const BRAND: unique symbol = Symbol.for("logic-sdk.brand") as any;
50
+ const BRAND: unique symbol = Symbol.for("logic-sdk.brand");
34
51
 
35
52
  /** 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> {
53
+ export interface Fn<K extends Kind = Kind, I = unknown, O = unknown, E extends boolean = boolean> {
37
54
  readonly [BRAND]: K;
38
55
  readonly kind: K;
39
56
  readonly description: string;
40
- readonly inputSchema: Schema;
41
- readonly outputSchema?: Schema;
57
+ /** What callers pass, validated on every call. Left out: the function takes nothing (`run(fn)`). */
58
+ readonly input?: Schema;
59
+ /** What callers get back, checked before it leaves. */
60
+ readonly output?: Schema;
42
61
  /** 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;
62
+ readonly meta?: Readonly<Record<string, unknown>>;
44
63
  /** Who may call it (from `authorize`). Runs on every call, before validation. */
45
- readonly authorize?: Policy<any>;
46
- /** `true`: adapters may publish it (HTTP, oRPC, AI tools). Requires `authorize` and `outputSchema`. */
64
+ readonly authorize?: Policy<never>;
65
+ /** `true`: adapters may publish it (HTTP, oRPC, AI tools). Requires `authorize` and `output`. */
47
66
  readonly expose?: true;
48
- readonly execute: (input: any, ctx: any) => Promise<any>;
67
+ readonly handler: (ctx: never, input: never) => Promise<unknown>;
49
68
  /** Phantom types, never set at runtime. */
50
69
  readonly [types]?: { input: I; output: O; exposed: E };
51
70
  }
71
+ /** The exposed functions of one module: what adapters publish. */
72
+ export type ExposedOf<T> = { [N in keyof T as T[N] extends Fn<Kind, unknown, unknown, true> ? N : never]: T[N] };
52
73
  /** A function with `expose: true`: adapters may publish it. */
53
- export type ExposedFn<K extends Kind = Kind, I = any, O = any> = Fn<K, I, O, true>;
74
+ export type ExposedFn<K extends Kind = Kind, I = unknown, O = unknown> = Fn<K, I, O, true>;
54
75
  /** What callers pass to a function. */
55
- export type FnIn<F> = F extends Fn<any, infer I, any> ? I : never;
76
+ export type FnIn<F> = F extends Fn<Kind, infer I, unknown> ? I : never;
56
77
  /** What a function returns. */
57
- export type FnOut<F> = F extends Fn<any, any, infer O> ? O : never;
78
+ export type FnOut<F> = F extends Fn<Kind, unknown, infer O> ? O : never;
58
79
 
59
- /** `I`: what `emit` takes. `O`: what listeners receive (after the schema's transforms and defaults). */
60
- export interface EventDef<I = any, O = I> {
80
+ /** `I`: what `emit` takes. `O`: what listeners receive (after the payload schema's transforms and defaults). */
81
+ export interface EventDef<I = unknown, O = I> {
61
82
  readonly [BRAND]: "event";
62
83
  readonly kind: "event";
63
- readonly schema: Schema;
84
+ /** The payload's schema, checked when emitted and again at delivery. */
85
+ readonly payload: Schema;
64
86
  readonly description?: string;
65
87
  readonly [types]?: { input: I; payload: O };
66
88
  }
67
89
 
68
90
  /**
69
91
  * What a dispatcher stores and delivers. Fully JSON: `payload` is what was emitted (validated),
70
- * and listeners get it parsed again by the event's schema at delivery.
92
+ * and listeners get it parsed again by the event's payload schema at delivery.
71
93
  */
72
94
  export interface Envelope<P = unknown, S = object> {
73
95
  id: string;
@@ -77,16 +99,33 @@ export interface Envelope<P = unknown, S = object> {
77
99
  occurredAt: string;
78
100
  }
79
101
 
80
- export interface Listener<O = any> {
102
+ export interface Listener<O = unknown> {
81
103
  readonly [BRAND]: "listener";
82
104
  readonly kind: "listener";
83
105
  /** Lazy, so listeners can import other modules' barrels without import cycles. */
84
- readonly event: () => EventDef<any, O>;
106
+ readonly event: () => EventDef<unknown, O>;
85
107
  readonly description?: string;
86
- readonly execute: (payload: O, ctx: any) => Promise<unknown>;
108
+ readonly handler: (ctx: never, payload: O) => Promise<unknown>;
87
109
  }
88
110
 
89
- type Run<Allowed extends Kind> = <F extends Fn<Allowed>>(fn: F, input: FnIn<F>) => Promise<FnOut<F>>;
111
+ /** What a single call may change: who it runs as (part of the scope) and when to give up. Nothing else. */
112
+ export interface RunOptions<S = object> {
113
+ /**
114
+ * Merged over the current scope for this call and everything it runs: `{ scope: { actor: system } }` to act as
115
+ * someone else on purpose, `{ scope: { locale: "es" } }` to render in another language. The callee's policy sees it.
116
+ */
117
+ scope?: Partial<S>;
118
+ /**
119
+ * Checked before this call starts. Inside, actions get it as `ctx.signal` to pass on (`fetch(url, { signal })`).
120
+ * Never checked between your steps, so a caller who gives up can't leave a workflow half done.
121
+ */
122
+ signal?: AbortSignal;
123
+ }
124
+ /** `run(fn, input, options?)`, or `run(fn)` for a function that takes no input. */
125
+ export type RunArgs<F, S> = undefined extends FnIn<F>
126
+ ? [input?: FnIn<F>, options?: RunOptions<S>]
127
+ : [input: FnIn<F>, options?: RunOptions<S>];
128
+ type Run<Allowed extends Kind, S> = <F extends Fn<Allowed>>(fn: F, ...args: RunArgs<F, S>) => Promise<FnOut<F>>;
90
129
 
91
130
  /**
92
131
  * Expected failures, namespaced to the module you're in: inside `bookings`, `ctx.errors.reject("not_pending")` has
@@ -102,36 +141,37 @@ export interface Errors {
102
141
  /** The caller is known but may not do this. Code defaults to `"<module>.<function>.forbidden"`. */
103
142
  deny(code?: string, details?: unknown): DomainError;
104
143
  }
105
- interface BaseCtx<S> {
144
+ interface BaseCtx<C extends Config, S> {
106
145
  scope: S;
146
+ /** Your settings from `createRegistry({ config })`. Read-only; tests override parts of it. */
147
+ config: Frozen<ConfigOf<C>>;
107
148
  /** Expected failures: `throw ctx.errors.reject("not_pending")`. */
108
149
  errors: Errors;
109
150
  /** Current time. Fixed in tests. */
110
151
  now: () => Date;
111
152
  }
112
- /** `S` is the scope, narrowed by the function's policy. Alias it in init.ts: `type QueryCtx = Core.QueryCtx<Config>`. */
113
- export interface QueryCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<S> {
153
+ /** `S` is the scope, narrowed by the function's policy. Alias it next to `init`: `type QueryCtx = QueryCtx<Config>`. */
154
+ export interface QueryCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C, S> {
114
155
  db: ReaderOf<C>;
115
- run: Run<"query">;
116
- /** The caller's abort signal, if any. */
117
- signal: AbortSignal | undefined;
118
- with(patch: Partial<ScopeOf<C>>): QueryCtx<C>;
156
+ /** Call another query, with its policy, validation and output check: `await ctx.run(pricing.quote, { nights })`. */
157
+ run: Run<"query", ScopeOf<C>>;
119
158
  }
120
- export interface MutationCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<S> {
159
+ export interface MutationCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C, S> {
121
160
  db: DbOf<C>;
122
- run: Run<"query" | "mutation">;
161
+ /**
162
+ * Call a query or mutation inside this same transaction, with its policy and validation:
163
+ * `await ctx.run(availability.hold, { propertyId })`. If it fails, the whole transaction rolls back.
164
+ */
165
+ run: Run<"query" | "mutation", ScopeOf<C>>;
123
166
  /** Queue an event. Delivered to listeners only after the transaction commits. */
124
- emit<I>(event: EventDef<I, any>, payload: I): void;
125
- signal: AbortSignal | undefined;
126
- with(patch: Partial<ScopeOf<C>>): MutationCtx<C>;
167
+ emit<I>(event: EventDef<I, unknown>, payload: I): void;
127
168
  }
128
- export interface ActionCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<S> {
169
+ export interface ActionCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C, S> {
129
170
  services: ServicesOf<C>;
130
- /** Each mutation you run here gets its own transaction. */
131
- run: Run<Kind>;
132
- /** The caller's abort signal. Always undefined in listeners (they outlive the request). */
171
+ /** Call any function: `await ctx.run(bookings.confirmPaid, { bookingId })`. Each mutation you run commits on its own. */
172
+ run: Run<Kind, ScopeOf<C>>;
173
+ /** The caller's abort signal: pass it on, `fetch(url, { signal: ctx.signal })`. Always undefined in listeners (they outlive the request). */
133
174
  signal: AbortSignal | undefined;
134
- with(patch: Partial<ScopeOf<C>>): ActionCtx<C>;
135
175
  }
136
176
  export interface ListenerCtx<C extends Config, O = unknown> extends ActionCtx<C> {
137
177
  event: Envelope<unknown, ScopeOf<C>> & { payload: O };
@@ -139,8 +179,8 @@ export interface ListenerCtx<C extends Config, O = unknown> extends ActionCtx<C>
139
179
 
140
180
  /**
141
181
  * Who may call a function at all: signed in, admin, staff. Sync, reads only the scope, returns exactly `true` to allow.
142
- * Write it as a type guard (`(s): s is Admin => ...`) to narrow `ctx.scope` in `execute`.
143
- * Rules about one record ("only the owner may cancel") go in `execute`, after loading it.
182
+ * Write it as a type guard (`(s): s is Admin => ...`) to narrow `ctx.scope` in `handler`.
183
+ * Rules about one record ("only the owner may cancel") go in `handler`, after loading it.
144
184
  */
145
185
  export type Policy<S> = (scope: S) => boolean;
146
186
  type Guarded<F, S> = F extends (scope: any) => scope is infer G ? G : S;
@@ -150,37 +190,40 @@ type CtxOf<C extends Config, K extends Kind, S> = K extends "query"
150
190
  ? MutationCtx<C, S>
151
191
  : ActionCtx<C, S>;
152
192
 
193
+ /** What a function without `input` gets: nothing. */
194
+ type NoInput = StandardSchemaV1<undefined, undefined>;
153
195
  type Def<IS extends Schema, Ctx, R> = {
154
196
  /** One sentence, shown to humans, adapters and AI tools. */
155
197
  description: string;
156
- inputSchema: IS;
157
- execute: (input: Out<IS>, ctx: Ctx) => Promise<R>;
198
+ /** What callers pass, validated on every call. Leave it out when the function takes nothing. */
199
+ input?: IS;
200
+ handler: (ctx: Ctx, input: Out<IS>) => Promise<R>;
158
201
  };
159
202
  type NotExposed = { expose?: undefined };
160
203
  type NoPolicy = { authorize?: undefined };
161
204
  type WithMeta<C extends Config> = { meta?: MetaOf<C> };
162
- type WithOutput<OS extends Schema> = { outputSchema: OS };
205
+ type WithOutput<OS extends Schema> = { output: OS };
163
206
 
164
207
  /**
165
- * `expose: true` needs `authorize` and `outputSchema`: you can't publish something without saying who may call it,
208
+ * `expose: true` needs `authorize` and `output`: you can't publish something without saying who may call it,
166
209
  * and what leaves your process is a contract. Internal functions may skip both; `authorize` still runs if set.
167
210
  */
168
211
  interface Constructor<C extends Config, K extends Kind> {
169
- <IS extends Schema, OS extends Schema, P extends Policy<ScopeOf<C>>>(
212
+ <IS extends Schema = NoInput, OS extends Schema = Schema, P extends Policy<ScopeOf<C>> = Policy<ScopeOf<C>>>(
170
213
  def: Def<IS, CtxOf<C, K, Guarded<P, ScopeOf<C>>>, In<OS>> &
171
214
  WithOutput<OS> &
172
215
  WithMeta<C> & { authorize: P; expose: true },
173
216
  ): Fn<K, In<IS>, Out<OS>, true>;
174
- <IS extends Schema, OS extends Schema, P extends Policy<ScopeOf<C>>>(
217
+ <IS extends Schema = NoInput, OS extends Schema = Schema, P extends Policy<ScopeOf<C>> = Policy<ScopeOf<C>>>(
175
218
  def: Def<IS, CtxOf<C, K, Guarded<P, ScopeOf<C>>>, In<OS>> & WithOutput<OS> & WithMeta<C> & { authorize: P } & NotExposed,
176
219
  ): Fn<K, In<IS>, Out<OS>, false>;
177
- <IS extends Schema, R, P extends Policy<ScopeOf<C>>>(
220
+ <IS extends Schema = NoInput, R = unknown, P extends Policy<ScopeOf<C>> = Policy<ScopeOf<C>>>(
178
221
  def: Def<IS, CtxOf<C, K, Guarded<P, ScopeOf<C>>>, R> & WithMeta<C> & { authorize: P } & NotExposed,
179
222
  ): Fn<K, In<IS>, R, false>;
180
- <IS extends Schema, OS extends Schema>(
223
+ <IS extends Schema = NoInput, OS extends Schema = Schema>(
181
224
  def: Def<IS, CtxOf<C, K, ScopeOf<C>>, In<OS>> & WithOutput<OS> & WithMeta<C> & NoPolicy & NotExposed,
182
225
  ): Fn<K, In<IS>, Out<OS>, false>;
183
- <IS extends Schema, R>(def: Def<IS, CtxOf<C, K, ScopeOf<C>>, R> & WithMeta<C> & NoPolicy & NotExposed): Fn<K, In<IS>, R, false>;
226
+ <IS extends Schema = NoInput, R = unknown>(def: Def<IS, CtxOf<C, K, ScopeOf<C>>, R> & WithMeta<C> & NoPolicy & NotExposed): Fn<K, In<IS>, R, false>;
184
227
  }
185
228
 
186
229
  /* ────────────────────────────────────────────────────────────────────────────
@@ -265,8 +308,10 @@ export interface Call<M = unknown> {
265
308
  export interface RegistryOptions<Mods extends Record<string, object>> {
266
309
  /** One entry per module: `{ bookings, availability }` with `import * as bookings from "./bookings"`. */
267
310
  modules: Mods;
268
- database?: DatabaseAdapter<any, any>;
311
+ database?: DatabaseAdapter<unknown, unknown>;
269
312
  services?: object;
313
+ /** Settings every function reads as `ctx.config`. Plain data: it's copied and frozen. */
314
+ config?: object;
270
315
  events?: Dispatcher;
271
316
  /** Wraps every call, including ones that fail validation or authorization: logging, tracing, audit. */
272
317
  wrap?: (call: Call, next: () => Promise<unknown>) => Promise<unknown>;
@@ -289,16 +334,11 @@ export interface RegistryOptions<Mods extends Record<string, object>> {
289
334
  retry?: { attempts?: number };
290
335
  }
291
336
 
292
- export interface CallerOptions {
293
- /** Aborts the call before it starts work. Listeners never get it: they outlive the request. */
294
- signal?: AbortSignal;
295
- }
296
-
297
- /** A registry bound to a scope: `const caller = registry.as(scope)`. */
337
+ /** A registry bound to who is calling: `const caller = registry.as(scope)`. */
298
338
  export interface Caller<S extends object = object> {
299
339
  readonly scope: S;
300
- run<F extends Fn>(fn: F, input: FnIn<F>): Promise<FnOut<F>>;
301
- with(patch: Partial<S>): Caller<S>;
340
+ /** Run any function as this caller: `await caller.run(bookings.cancel, input, { signal: request.signal })`. */
341
+ run<F extends Fn>(fn: F, ...args: RunArgs<F, S>): Promise<FnOut<F>>;
302
342
  }
303
343
 
304
344
  export interface Registered {
@@ -322,7 +362,8 @@ type TypedOptions<C extends Config, Mods extends Record<string, object>> = Omit<
322
362
  wrap?: (call: Call<MetaOf<C>>, next: () => Promise<unknown>) => Promise<unknown>;
323
363
  } &
324
364
  ({} extends ServicesOf<C> ? { services?: ServicesOf<C> } : { services: ServicesOf<C> }) &
325
- ([DbOf<C>] extends [never] ? { database?: undefined } : { database: DatabaseAdapter<any, DbOf<C>> });
365
+ ({} extends ConfigOf<C> ? { config?: ConfigOf<C> } : { config: ConfigOf<C> }) &
366
+ ([DbOf<C>] extends [never] ? { database?: undefined } : { database: DatabaseAdapter<unknown, DbOf<C>> });
326
367
 
327
368
  /** Keys `Config` doesn't know are errors, so a typo like `servises` can't be silently ignored. */
328
369
  type OnlyKnownKeys<C> = { [K in Exclude<keyof C, keyof Config>]: never };
@@ -335,10 +376,7 @@ type OnlyKnownKeys<C> = { [K in Exclude<keyof C, keyof Config>]: never };
335
376
  * ```
336
377
  */
337
378
  export function init<C extends Config & OnlyKnownKeys<C>>() {
338
- return constructors<C>();
339
- }
340
-
341
- function constructors<C extends Config>() {
379
+ // One implementation behind the typed overloads of `Constructor`: the checks here are the runtime half of those types.
342
380
  const make =
343
381
  <K extends Kind>(kind: K) =>
344
382
  (def: any): any => {
@@ -349,15 +387,16 @@ function constructors<C extends Config>() {
349
387
  throw new Error(`[logic-sdk] expose on ${where} must be \`true\` or left out.`);
350
388
  if (def.expose && !def.authorize)
351
389
  throw new Error(`[logic-sdk] ${where} has expose: true but no authorize. Say who may call it.`);
352
- if (def.expose && !def.outputSchema)
353
- throw new Error(`[logic-sdk] ${where} has expose: true but no outputSchema. Say what callers may see.`);
354
- return Object.freeze({ [BRAND]: kind, kind, outputSchema: undefined, ...def });
390
+ if (def.expose && !def.output)
391
+ throw new Error(`[logic-sdk] ${where} has expose: true but no output. Say what callers may see.`);
392
+ if (typeof def.handler !== "function") throw new Error(`[logic-sdk] ${where} needs a handler(ctx, input).`);
393
+ return Object.freeze({ [BRAND]: kind, kind, ...def });
355
394
  };
356
395
 
357
396
  return {
358
397
  /** Create the registry once at startup: `createRegistry({ modules, database, services })`. */
359
398
  createRegistry: <const Mods extends Record<string, object>>(options: TypedOptions<C, Mods>) =>
360
- build<ScopeOf<C>, Mods>(options as RegistryOptions<Mods>, {}), // meta in wrap is typed by MetaOf<C>; the values come from typed defs
399
+ build<ScopeOf<C>, Mods, ConfigOf<C>>(options as RegistryOptions<Mods>, {}), // meta in wrap is typed by MetaOf<C>; the values come from typed defs
361
400
  /** Reads data. Can run other queries. No writes, no events, no services. */
362
401
  query: make("query") as Constructor<C, "query">,
363
402
  /** Changes data inside one transaction. Can run queries and mutations (same transaction) and emit events. */
@@ -365,12 +404,12 @@ function constructors<C extends Config>() {
365
404
  /** Talks to the outside world (payments, email, AI). No transaction; each mutation it runs commits on its own. */
366
405
  action: make("action") as Constructor<C, "action">,
367
406
  /** Something that happened. Emitted by mutations, delivered after commit. */
368
- event: <S extends Schema>(def: { schema: S; description?: string }): EventDef<In<S>, Out<S>> =>
407
+ event: <S extends Schema>(def: { payload: S; description?: string }): EventDef<In<S>, Out<S>> =>
369
408
  Object.freeze({ [BRAND]: "event" as const, kind: "event" as const, ...def }),
370
- /** React to an event after commit, like an action. Must be idempotent. `on(() => bookings.confirmed, ...)` */
409
+ /** React to an event after commit, like an action. Must be idempotent. `on(() => bookings.confirmed, async (ctx, payload) => …)` */
371
410
  on: <O>(
372
- event: () => EventDef<any, O>,
373
- execute: (payload: O, ctx: ListenerCtx<C, O>) => Promise<unknown>,
411
+ event: () => EventDef<unknown, O>,
412
+ handler: (ctx: ListenerCtx<C, O>, payload: O) => Promise<unknown>,
374
413
  opts: { description?: string } = {},
375
414
  ): Listener<O> =>
376
415
  Object.freeze({
@@ -378,7 +417,7 @@ function constructors<C extends Config>() {
378
417
  kind: "listener" as const,
379
418
  event,
380
419
  description: opts.description,
381
- execute: execute as Listener<O>["execute"],
420
+ handler,
382
421
  }),
383
422
  };
384
423
  }
@@ -387,7 +426,7 @@ function constructors<C extends Config>() {
387
426
  * createRegistry
388
427
  * ──────────────────────────────────────────────────────────────────────────── */
389
428
 
390
- const INTERNAL: unique symbol = Symbol.for("logic-sdk.internal") as any;
429
+ const INTERNAL: unique symbol = Symbol.for("logic-sdk.internal");
391
430
 
392
431
  interface TxState {
393
432
  db: unknown;
@@ -399,22 +438,54 @@ interface TxState {
399
438
  interface Frame {
400
439
  scope: object;
401
440
  depth: number;
402
- opts: CallerOptions & { eventDepth?: number };
441
+ /** Inherited, for actions to pass on as ctx.signal. */
442
+ signal?: AbortSignal;
443
+ /** Passed to this very call: checked before it starts. */
444
+ abortOn?: AbortSignal;
445
+ eventDepth?: number;
403
446
  tx?: TxState;
404
447
  }
405
448
 
406
449
  export interface Overrides {
407
- database?: DatabaseAdapter<any, any>;
450
+ database?: DatabaseAdapter<unknown, unknown>;
408
451
  services?: object;
452
+ /** Merged over the registry's config, section by section. */
453
+ config?: object;
409
454
  events?: Dispatcher;
410
455
  now?: () => Date;
411
- stubs?: Map<Fn, (input: any, ctx: any) => Promise<any>>;
456
+ stubs?: Map<Fn, (ctx: never, input: never) => Promise<unknown>>;
412
457
  record?: (envelope: Envelope) => void;
413
458
  }
414
459
 
415
- export type Registry<S extends object = object, Mods extends Record<string, object> = Record<string, object>> = ReturnType<
416
- typeof build<S, Mods>
417
- >;
460
+ export interface RegisteredEvent extends Registered {
461
+ event: EventDef;
462
+ }
463
+ export interface RegisteredListener extends Registered {
464
+ listener: Listener;
465
+ event: EventDef;
466
+ }
467
+
468
+ /** What `createRegistry` returns. `Cf` is your config's type, so tests can override parts of it. */
469
+ export interface Registry<S extends object = object, Mods extends Record<string, object> = Record<string, object>, Cf = unknown> {
470
+ /** The modules you registered (typed), for adapters that build typed routers. */
471
+ readonly modules: Mods;
472
+ /** Bind who is calling, once per request, job or test: `const caller = registry.as(scope)`. */
473
+ as(scope: S): Caller<S>;
474
+ /** Everything the registry can do. Adapters read this. */
475
+ readonly functions: readonly RegisteredFn[];
476
+ readonly events: readonly RegisteredEvent[];
477
+ readonly listeners: readonly RegisteredListener[];
478
+ /** `"bookings.confirm"` for a registered function or event. Throws for anything unregistered. */
479
+ idOf(fnOrEvent: object): string;
480
+ /** Deliver one stored envelope to its listeners (durable dispatchers). Throws if any listener failed, so you can retry. */
481
+ dispatch(envelope: Envelope): Promise<void>;
482
+ /** @internal used by `logic-sdk/testing` */
483
+ readonly [INTERNAL]: {
484
+ options: RegistryOptions<Mods>;
485
+ config: Frozen<Cf>;
486
+ derive(more: Overrides): Registry<S, Mods, Cf>;
487
+ };
488
+ }
418
489
 
419
490
  /** Create the registry once at startup. Prefer the `createRegistry` returned by `init()`: it's typed with your config. */
420
491
  export function createRegistry<S extends object = object, const Mods extends Record<string, object> = Record<string, object>>(
@@ -423,9 +494,38 @@ export function createRegistry<S extends object = object, const Mods extends Rec
423
494
  return build<S, Mods>(options, {});
424
495
  }
425
496
 
497
+ const isPlain = (v: unknown): v is Record<string, unknown> =>
498
+ !!v && typeof v === "object" && (Object.getPrototypeOf(v) === Object.prototype || Object.getPrototypeOf(v) === null);
499
+
500
+ /** Plain objects merge key by key; anything else (values, arrays, null) replaces. `undefined` keeps the base. */
501
+ function mergeConfig(base: unknown, patch: unknown): unknown {
502
+ if (patch === undefined) return base;
503
+ if (!isPlain(base) || !isPlain(patch)) return patch;
504
+ const keys = new Set([...Object.keys(base), ...Object.keys(patch)]);
505
+ return Object.fromEntries([...keys].map((k) => [k, mergeConfig(base[k], patch[k])])); // fromEntries: `__proto__` stays a key
506
+ }
507
+
508
+ /**
509
+ * A frozen copy of plain data: strings, numbers, booleans, null, plain objects and arrays. Anything else (a Date, a Map,
510
+ * a client, a class) is rejected with its path, so settings can't change under everyone else or hide behavior.
511
+ */
512
+ function freezeConfig(value: unknown, path = "config"): unknown {
513
+ if (value === null || ["string", "number", "boolean", "undefined"].includes(typeof value)) return value;
514
+ if (Array.isArray(value)) return Object.freeze(value.map((v, i) => freezeConfig(v, `${path}[${i}]`)));
515
+ if (isPlain(value))
516
+ return Object.freeze(Object.fromEntries(Object.entries(value).map(([k, v]) => [k, freezeConfig(v, `${path}.${k}`)])));
517
+ const what = typeof value === "function" ? "a function" : (value as object).constructor?.name ?? typeof value;
518
+ throw new Error(
519
+ `[logic-sdk] ${path} is ${what}. config holds plain data (strings, numbers, booleans, null, objects, arrays): ` +
520
+ "pass a Date as an ISO string, and put clients in services.",
521
+ );
522
+ }
523
+
426
524
  const describeIssues = (issues: readonly StandardSchemaV1.Issue[]) =>
427
525
  issues.map((i) => ({ message: i.message, path: i.path?.map((p) => (typeof p === "object" ? p.key : p)) }));
428
526
 
527
+ const isBranded = (v: unknown): v is Fn | EventDef | Listener => !!v && typeof v === "object" && BRAND in v;
528
+
429
529
  /**
430
530
  * What `createRegistry` finds in your modules, without a database or services: every function, event and
431
531
  * listener with its id. For tools (the CLI, docs generators) that inspect an app without running it.
@@ -433,30 +533,31 @@ const describeIssues = (issues: readonly StandardSchemaV1.Issue[]) =>
433
533
  export function describeModules(modules: Record<string, object>) {
434
534
  const ids = new Map<object, string>();
435
535
  const functions: RegisteredFn[] = [];
436
- const events: (Registered & { event: EventDef })[] = [];
437
- const listeners: (Registered & { listener: Listener; event: EventDef })[] = [];
536
+ const events: RegisteredEvent[] = [];
537
+ const listeners: RegisteredListener[] = [];
438
538
 
439
539
  for (const [module, ns] of Object.entries(modules)) {
440
540
  for (const [name, value] of Object.entries(ns)) {
441
- if (!value || typeof value !== "object" || !(BRAND in value) || ids.has(value)) continue;
541
+ if (!isBranded(value) || ids.has(value)) continue;
442
542
  const id = `${module}.${name}`;
443
543
  ids.set(value, id);
444
- const kind = (value as any)[BRAND];
445
- if (kind === "event") events.push({ id, module, name, event: value as EventDef });
446
- else if (kind === "listener") {
447
- const listener = value as Listener;
448
- listeners.push({ id, module, name, listener, event: listener.event() });
449
- } else functions.push({ id, module, name, kind, fn: value as Fn, exposed: (value as Fn).expose === true });
544
+ if (value.kind === "event") events.push({ id, module, name, event: value });
545
+ else if (value.kind === "listener") listeners.push({ id, module, name, listener: value, event: value.event() });
546
+ else functions.push({ id, module, name, kind: value.kind, fn: value, exposed: value.expose === true });
450
547
  }
451
548
  }
452
549
  return { ids, functions, events, listeners };
453
550
  }
454
551
 
455
- function build<S extends object, Mods extends Record<string, object>>(options: RegistryOptions<Mods>, o: Overrides) {
552
+ function build<S extends object, Mods extends Record<string, object>, Cf = unknown>(
553
+ options: RegistryOptions<Mods>,
554
+ o: Overrides,
555
+ ): Registry<S, Mods, Cf> {
456
556
  const { ids, functions, events, listeners } = describeModules(options.modules);
457
557
 
458
558
  const database = o.database ?? options.database;
459
559
  const services = o.services ?? options.services ?? {};
560
+ const config = freezeConfig(mergeConfig(options.config ?? {}, o.config)) as Frozen<Cf>;
460
561
  const dispatcher = o.events ?? options.events ?? inProcess();
461
562
  const now = o.now ?? options.now ?? (() => new Date());
462
563
  const wrap = options.wrap ?? ((_c, next) => next());
@@ -506,7 +607,7 @@ function build<S extends object, Mods extends Record<string, object>>(options: R
506
607
  }
507
608
 
508
609
  // ── listeners ────────────────────────────────────────────────────────────
509
- const byEvent = new Map<string, (Registered & { listener: Listener })[]>();
610
+ const byEvent = new Map<string, RegisteredListener[]>();
510
611
  for (const l of listeners) {
511
612
  const name = idOf(l.event);
512
613
  byEvent.set(name, [...(byEvent.get(name) ?? []), l]);
@@ -518,11 +619,11 @@ function build<S extends object, Mods extends Record<string, object>>(options: R
518
619
  const failures: { listener: string; error: unknown }[] = [];
519
620
  const event = eventByName.get(envelope.name);
520
621
  for (const l of byEvent.get(envelope.name) ?? []) {
521
- const frame: Frame = { scope: envelope.scope, depth: 0, opts: { eventDepth } };
622
+ const frame: Frame = { scope: envelope.scope, depth: 0, eventDepth };
522
623
  try {
523
624
  await wrap({ id: l.id, kind: "listener", meta: undefined, input: envelope.payload, scope: envelope.scope, depth: 0 }, async () => {
524
- const payload = event ? await parseOwn(event.schema, envelope.payload, `${envelope.name} payload`) : envelope.payload;
525
- return l.listener.execute(payload, { ...actionCtx(frame, l.id), event: { ...envelope, payload } });
625
+ const payload = event ? await parseOwn(event.payload, envelope.payload, `${envelope.name} payload`) : envelope.payload;
626
+ return l.listener.handler({ ...actionCtx(frame, l.id), event: { ...envelope, payload } } as never, payload); // SAFETY: as in invoke
526
627
  });
527
628
  } catch (error) {
528
629
  failures.push({ listener: l.id, error });
@@ -547,29 +648,32 @@ function build<S extends object, Mods extends Record<string, object>>(options: R
547
648
  }
548
649
 
549
650
  // ── ctx ──────────────────────────────────────────────────────────────────
550
- const child = (frame: Frame): Frame => ({ ...frame, depth: frame.depth + 1 });
551
- const rescope = (frame: Frame, patch: object): Frame => ({ ...frame, scope: { ...frame.scope, ...patch } });
552
-
553
- function queryCtx(frame: Frame, id: string): QueryCtx<any> {
554
- return {
555
- errors: errorsFor(id),
556
- scope: frame.scope,
557
- now,
558
- signal: frame.opts.signal,
559
- db: frame.tx ? frame.tx.db : database?.db,
560
- run: (fn, input) => invoke(fn, input, child(frame), ["query"]),
561
- with: (patch) => queryCtx(rescope(frame, patch), id),
562
- };
563
- }
651
+ /** The frame a call runs in: one level deeper, with this call's scope patch and signal. */
652
+ const enter = (frame: Frame, options: RunOptions | undefined): Frame => ({
653
+ ...frame,
654
+ depth: frame.depth + 1,
655
+ scope: options?.scope ? { ...frame.scope, ...options.scope } : frame.scope,
656
+ signal: options?.signal ?? frame.signal,
657
+ abortOn: options?.signal,
658
+ });
659
+
660
+ /** What every ctx has. `allowed`: the kinds its `run` may call. */
661
+ const baseCtx = (frame: Frame, id: string, allowed: Kind[]) => ({
662
+ errors: errorsFor(id),
663
+ scope: frame.scope,
664
+ config: config as any, // Frozen<Cf> here; each app's ctx types it from its own Config
665
+ now,
666
+ run: (fn: Fn, input?: unknown, options?: RunOptions) => invoke(fn, input, enter(frame, options), allowed),
667
+ });
668
+ const queryCtx = (frame: Frame, id: string): QueryCtx<any> => ({
669
+ ...baseCtx(frame, id, ["query"]),
670
+ db: frame.tx ? frame.tx.db : database?.db,
671
+ });
564
672
  function mutationCtx(frame: Frame, id: string): MutationCtx<any> {
565
673
  const tx = frame.tx!;
566
674
  return {
567
- errors: errorsFor(id),
568
- scope: frame.scope,
569
- now,
570
- signal: frame.opts.signal,
675
+ ...baseCtx(frame, id, ["query", "mutation"]),
571
676
  db: tx.db,
572
- run: (fn, input) => invoke(fn, input, child(frame), ["query", "mutation"]),
573
677
  emit: (event, payload) => {
574
678
  const name = idOf(event);
575
679
  payload = structuredClone(payload); // what was emitted is what gets delivered, even if the caller mutates it after
@@ -582,24 +686,17 @@ function build<S extends object, Mods extends Record<string, object>>(options: R
582
686
  occurredAt: now().toISOString(),
583
687
  };
584
688
  tx.outbox.push(envelope);
585
- const check = parseOwn(event.schema, payload, `${name} payload`).then(() => {});
689
+ const check = parseOwn(event.payload, payload, `${name} payload`).then(() => {});
586
690
  check.catch(() => {}); // surfaced at commit; never an unhandled rejection
587
691
  tx.pending.push(check);
588
692
  },
589
- with: (patch) => mutationCtx(rescope(frame, patch), id),
590
- };
591
- }
592
- function actionCtx(frame: Frame, id: string): ActionCtx<any> {
593
- return {
594
- errors: errorsFor(id),
595
- scope: frame.scope,
596
- now,
597
- signal: frame.opts.signal,
598
- services,
599
- run: (fn, input) => invoke(fn, input, child({ ...frame, tx: undefined }), ["query", "mutation", "action"]),
600
- with: (patch) => actionCtx(rescope(frame, patch), id),
601
693
  };
602
694
  }
695
+ const actionCtx = (frame: Frame, id: string): ActionCtx<any> => ({
696
+ ...baseCtx(frame, id, ["query", "mutation", "action"]),
697
+ signal: frame.signal,
698
+ services,
699
+ });
603
700
 
604
701
  // ── invoke ───────────────────────────────────────────────────────────────
605
702
  async function invoke(fn: Fn, rawInput: unknown, frame: Frame, allowed: Kind[]): Promise<any> {
@@ -611,19 +708,23 @@ function build<S extends object, Mods extends Record<string, object>>(options: R
611
708
 
612
709
  /** Authorize, then validate, before any transaction opens: denied or bad calls never touch the database. */
613
710
  const prepare = async () => {
614
- frame.opts.signal?.throwIfAborted();
711
+ frame.abortOn?.throwIfAborted();
615
712
  if (fn.authorize) {
616
- const allowed: unknown = fn.authorize(frame.scope);
617
- if (allowed instanceof Promise || typeof (allowed as any)?.then === "function")
713
+ // SAFETY: the registry erases each policy's scope type; the caller's scope is the app's Scope by construction
714
+ const verdict: unknown = fn.authorize(frame.scope as never);
715
+ if (verdict instanceof Promise)
618
716
  throw new Error(`[logic-sdk] The policy on ${id} returned a Promise. Policies are sync and read only the scope.`);
619
- if (allowed !== true) throw new DomainError("forbidden", `${id}.forbidden`);
717
+ if (verdict !== true) throw new DomainError("forbidden", `${id}.forbidden`);
620
718
  }
621
- return parseInput(fn.inputSchema, rawInput, id, frame.depth > 0);
719
+ // no `input`: the function takes nothing, whatever an adapter sends (AI tools send `{}`)
720
+ return fn.input ? parseInput(fn.input, rawInput, id, frame.depth > 0) : undefined;
622
721
  };
623
722
  const execute = async (input: unknown, ctx: unknown) => {
624
- const stub = o.stubs?.get(fn);
625
- const out = await (stub ? stub(input, ctx) : fn.execute(input, ctx));
626
- return fn.outputSchema ? parseOwn(fn.outputSchema, out, `${id} output`) : out;
723
+ // SAFETY: the handler's types were erased when it was registered. `ctx` was built for its kind,
724
+ // and `input` just passed its own schema (or it takes none).
725
+ const handler = o.stubs?.get(fn) ?? fn.handler;
726
+ const out = await handler(ctx as never, input as never);
727
+ return fn.output ? parseOwn(fn.output, out, `${id} output`) : out;
627
728
  };
628
729
 
629
730
  return wrap(call, async () => {
@@ -682,7 +783,7 @@ function build<S extends object, Mods extends Record<string, object>>(options: R
682
783
  async function afterCommit(outbox: Envelope[], frame: Frame) {
683
784
  try {
684
785
  for (const e of outbox) o.record?.(e);
685
- const eventDepth = (frame.opts.eventDepth ?? 0) + 1;
786
+ const eventDepth = (frame.eventDepth ?? 0) + 1;
686
787
  if (eventDepth > maxEventDepth) {
687
788
  report(new Error(`[logic-sdk] event chain deeper than ${maxEventDepth}: stopped delivering (listener loop?)`), {
688
789
  listener: "(dispatcher)",
@@ -707,30 +808,25 @@ function build<S extends object, Mods extends Record<string, object>>(options: R
707
808
  }
708
809
  }
709
810
 
710
- function makeCaller(scope: S, opts: CallerOptions): Caller<S> {
711
- return {
712
- scope,
713
- run: (fn, input) => invoke(fn, input, { scope, depth: 0, opts }, ["query", "mutation", "action"]),
714
- with: (patch) => makeCaller({ ...scope, ...patch }, opts),
715
- };
716
- }
717
-
718
811
  return {
719
- /** The modules you registered (typed), for adapters that build typed routers. */
720
812
  modules: options.modules,
721
- /** Bind who is calling, once per request, job or test: `const caller = registry.as(scope)`. */
722
- as: (scope: S, opts: CallerOptions = {}): Caller<S> => makeCaller(scope, opts),
723
- /** Everything the registry can do. Adapters read this. */
724
- functions: functions as readonly RegisteredFn[],
725
- events: events as readonly (Registered & { event: EventDef })[],
726
- listeners: listeners as readonly (Registered & { listener: Listener; event: EventDef })[],
813
+ as: (scope) => ({
814
+ scope,
815
+ run: (fn: Fn, input?: unknown, options?: RunOptions) =>
816
+ invoke(fn, input, enter({ scope, depth: -1 }, options), ["query", "mutation", "action"]), // depth 0
817
+ }),
818
+ functions,
819
+ events,
820
+ listeners,
727
821
  idOf,
728
- /** Deliver one stored envelope to its listeners (durable dispatchers). Throws if any listener failed, so you can retry. */
729
822
  dispatch,
730
- /** @internal used by `logic-sdk/testing` */
731
- [INTERNAL]: { options, overrides: o, derive: (more: Overrides) => build<S, Mods>(options, { ...o, ...more }) },
823
+ [INTERNAL]: {
824
+ options,
825
+ config,
826
+ derive: (more: Overrides) => build<S, Mods, Cf>(options, { ...o, ...more, config: mergeConfig(o.config, more.config) as object | undefined }),
827
+ },
732
828
  };
733
829
  }
734
830
 
735
831
  /** @internal */
736
- export const internal = (registry: Registry<any, any>) => registry[INTERNAL];
832
+ export const internal = <S extends object, Mods extends Record<string, object>, Cf>(registry: Registry<S, Mods, Cf>) => registry[INTERNAL];