logic-sdk 0.3.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 {
@@ -47,44 +47,49 @@ export type DeepPartial<T> = T extends Primitive | readonly unknown[] ? T : { [K
47
47
  export type Kind = "query" | "mutation" | "action";
48
48
 
49
49
  declare const types: unique symbol;
50
- const BRAND: unique symbol = Symbol.for("logic-sdk.brand") as any;
50
+ const BRAND: unique symbol = Symbol.for("logic-sdk.brand");
51
51
 
52
52
  /** A query, mutation or action. Call it with `caller.run(fn, input)` or `ctx.run(fn, input)`. */
53
- 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> {
54
54
  readonly [BRAND]: K;
55
55
  readonly kind: K;
56
56
  readonly description: string;
57
- readonly inputSchema: Schema;
58
- 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;
59
61
  /** Your own data about the function. Checked against `meta` in `init` where you set it, typed in `wrap`; loose here, for adapters. */
60
- readonly meta?: any;
62
+ readonly meta?: Readonly<Record<string, unknown>>;
61
63
  /** Who may call it (from `authorize`). Runs on every call, before validation. */
62
- readonly authorize?: Policy<any>;
63
- /** `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`. */
64
66
  readonly expose?: true;
65
- readonly execute: (input: any, ctx: any) => Promise<any>;
67
+ readonly handler: (ctx: never, input: never) => Promise<unknown>;
66
68
  /** Phantom types, never set at runtime. */
67
69
  readonly [types]?: { input: I; output: O; exposed: E };
68
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] };
69
73
  /** A function with `expose: true`: adapters may publish it. */
70
- 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>;
71
75
  /** What callers pass to a function. */
72
- 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;
73
77
  /** What a function returns. */
74
- 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;
75
79
 
76
- /** `I`: what `emit` takes. `O`: what listeners receive (after the schema's transforms and defaults). */
77
- 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> {
78
82
  readonly [BRAND]: "event";
79
83
  readonly kind: "event";
80
- readonly schema: Schema;
84
+ /** The payload's schema, checked when emitted and again at delivery. */
85
+ readonly payload: Schema;
81
86
  readonly description?: string;
82
87
  readonly [types]?: { input: I; payload: O };
83
88
  }
84
89
 
85
90
  /**
86
91
  * What a dispatcher stores and delivers. Fully JSON: `payload` is what was emitted (validated),
87
- * 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.
88
93
  */
89
94
  export interface Envelope<P = unknown, S = object> {
90
95
  id: string;
@@ -94,13 +99,13 @@ export interface Envelope<P = unknown, S = object> {
94
99
  occurredAt: string;
95
100
  }
96
101
 
97
- export interface Listener<O = any> {
102
+ export interface Listener<O = unknown> {
98
103
  readonly [BRAND]: "listener";
99
104
  readonly kind: "listener";
100
105
  /** Lazy, so listeners can import other modules' barrels without import cycles. */
101
- readonly event: () => EventDef<any, O>;
106
+ readonly event: () => EventDef<unknown, O>;
102
107
  readonly description?: string;
103
- readonly execute: (payload: O, ctx: any) => Promise<unknown>;
108
+ readonly handler: (ctx: never, payload: O) => Promise<unknown>;
104
109
  }
105
110
 
106
111
  /** What a single call may change: who it runs as (part of the scope) and when to give up. Nothing else. */
@@ -116,7 +121,11 @@ export interface RunOptions<S = object> {
116
121
  */
117
122
  signal?: AbortSignal;
118
123
  }
119
- type Run<Allowed extends Kind, S> = <F extends Fn<Allowed>>(fn: F, input: FnIn<F>, options?: RunOptions<S>) => Promise<FnOut<F>>;
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>>;
120
129
 
121
130
  /**
122
131
  * Expected failures, namespaced to the module you're in: inside `bookings`, `ctx.errors.reject("not_pending")` has
@@ -141,7 +150,7 @@ interface BaseCtx<C extends Config, S> {
141
150
  /** Current time. Fixed in tests. */
142
151
  now: () => Date;
143
152
  }
144
- /** `S` is the scope, narrowed by the function's policy. Alias it in init.ts: `type QueryCtx = Core.QueryCtx<Config>`. */
153
+ /** `S` is the scope, narrowed by the function's policy. Alias it next to `init`: `type QueryCtx = QueryCtx<Config>`. */
145
154
  export interface QueryCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C, S> {
146
155
  db: ReaderOf<C>;
147
156
  /** Call another query, with its policy, validation and output check: `await ctx.run(pricing.quote, { nights })`. */
@@ -155,7 +164,7 @@ export interface MutationCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C
155
164
  */
156
165
  run: Run<"query" | "mutation", ScopeOf<C>>;
157
166
  /** Queue an event. Delivered to listeners only after the transaction commits. */
158
- emit<I>(event: EventDef<I, any>, payload: I): void;
167
+ emit<I>(event: EventDef<I, unknown>, payload: I): void;
159
168
  }
160
169
  export interface ActionCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C, S> {
161
170
  services: ServicesOf<C>;
@@ -170,8 +179,8 @@ export interface ListenerCtx<C extends Config, O = unknown> extends ActionCtx<C>
170
179
 
171
180
  /**
172
181
  * Who may call a function at all: signed in, admin, staff. Sync, reads only the scope, returns exactly `true` to allow.
173
- * Write it as a type guard (`(s): s is Admin => ...`) to narrow `ctx.scope` in `execute`.
174
- * 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.
175
184
  */
176
185
  export type Policy<S> = (scope: S) => boolean;
177
186
  type Guarded<F, S> = F extends (scope: any) => scope is infer G ? G : S;
@@ -181,37 +190,40 @@ type CtxOf<C extends Config, K extends Kind, S> = K extends "query"
181
190
  ? MutationCtx<C, S>
182
191
  : ActionCtx<C, S>;
183
192
 
193
+ /** What a function without `input` gets: nothing. */
194
+ type NoInput = StandardSchemaV1<undefined, undefined>;
184
195
  type Def<IS extends Schema, Ctx, R> = {
185
196
  /** One sentence, shown to humans, adapters and AI tools. */
186
197
  description: string;
187
- inputSchema: IS;
188
- 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>;
189
201
  };
190
202
  type NotExposed = { expose?: undefined };
191
203
  type NoPolicy = { authorize?: undefined };
192
204
  type WithMeta<C extends Config> = { meta?: MetaOf<C> };
193
- type WithOutput<OS extends Schema> = { outputSchema: OS };
205
+ type WithOutput<OS extends Schema> = { output: OS };
194
206
 
195
207
  /**
196
- * `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,
197
209
  * and what leaves your process is a contract. Internal functions may skip both; `authorize` still runs if set.
198
210
  */
199
211
  interface Constructor<C extends Config, K extends Kind> {
200
- <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>>>(
201
213
  def: Def<IS, CtxOf<C, K, Guarded<P, ScopeOf<C>>>, In<OS>> &
202
214
  WithOutput<OS> &
203
215
  WithMeta<C> & { authorize: P; expose: true },
204
216
  ): Fn<K, In<IS>, Out<OS>, true>;
205
- <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>>>(
206
218
  def: Def<IS, CtxOf<C, K, Guarded<P, ScopeOf<C>>>, In<OS>> & WithOutput<OS> & WithMeta<C> & { authorize: P } & NotExposed,
207
219
  ): Fn<K, In<IS>, Out<OS>, false>;
208
- <IS extends Schema, R, P extends Policy<ScopeOf<C>>>(
220
+ <IS extends Schema = NoInput, R = unknown, P extends Policy<ScopeOf<C>> = Policy<ScopeOf<C>>>(
209
221
  def: Def<IS, CtxOf<C, K, Guarded<P, ScopeOf<C>>>, R> & WithMeta<C> & { authorize: P } & NotExposed,
210
222
  ): Fn<K, In<IS>, R, false>;
211
- <IS extends Schema, OS extends Schema>(
223
+ <IS extends Schema = NoInput, OS extends Schema = Schema>(
212
224
  def: Def<IS, CtxOf<C, K, ScopeOf<C>>, In<OS>> & WithOutput<OS> & WithMeta<C> & NoPolicy & NotExposed,
213
225
  ): Fn<K, In<IS>, Out<OS>, false>;
214
- <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>;
215
227
  }
216
228
 
217
229
  /* ────────────────────────────────────────────────────────────────────────────
@@ -296,7 +308,7 @@ export interface Call<M = unknown> {
296
308
  export interface RegistryOptions<Mods extends Record<string, object>> {
297
309
  /** One entry per module: `{ bookings, availability }` with `import * as bookings from "./bookings"`. */
298
310
  modules: Mods;
299
- database?: DatabaseAdapter<any, any>;
311
+ database?: DatabaseAdapter<unknown, unknown>;
300
312
  services?: object;
301
313
  /** Settings every function reads as `ctx.config`. Plain data: it's copied and frozen. */
302
314
  config?: object;
@@ -326,7 +338,7 @@ export interface RegistryOptions<Mods extends Record<string, object>> {
326
338
  export interface Caller<S extends object = object> {
327
339
  readonly scope: S;
328
340
  /** Run any function as this caller: `await caller.run(bookings.cancel, input, { signal: request.signal })`. */
329
- run<F extends Fn>(fn: F, input: FnIn<F>, options?: RunOptions<S>): Promise<FnOut<F>>;
341
+ run<F extends Fn>(fn: F, ...args: RunArgs<F, S>): Promise<FnOut<F>>;
330
342
  }
331
343
 
332
344
  export interface Registered {
@@ -351,7 +363,7 @@ type TypedOptions<C extends Config, Mods extends Record<string, object>> = Omit<
351
363
  } &
352
364
  ({} extends ServicesOf<C> ? { services?: ServicesOf<C> } : { services: ServicesOf<C> }) &
353
365
  ({} extends ConfigOf<C> ? { config?: ConfigOf<C> } : { config: ConfigOf<C> }) &
354
- ([DbOf<C>] extends [never] ? { database?: undefined } : { database: DatabaseAdapter<any, DbOf<C>> });
366
+ ([DbOf<C>] extends [never] ? { database?: undefined } : { database: DatabaseAdapter<unknown, DbOf<C>> });
355
367
 
356
368
  /** Keys `Config` doesn't know are errors, so a typo like `servises` can't be silently ignored. */
357
369
  type OnlyKnownKeys<C> = { [K in Exclude<keyof C, keyof Config>]: never };
@@ -364,10 +376,7 @@ type OnlyKnownKeys<C> = { [K in Exclude<keyof C, keyof Config>]: never };
364
376
  * ```
365
377
  */
366
378
  export function init<C extends Config & OnlyKnownKeys<C>>() {
367
- return constructors<C>();
368
- }
369
-
370
- function constructors<C extends Config>() {
379
+ // One implementation behind the typed overloads of `Constructor`: the checks here are the runtime half of those types.
371
380
  const make =
372
381
  <K extends Kind>(kind: K) =>
373
382
  (def: any): any => {
@@ -378,9 +387,10 @@ function constructors<C extends Config>() {
378
387
  throw new Error(`[logic-sdk] expose on ${where} must be \`true\` or left out.`);
379
388
  if (def.expose && !def.authorize)
380
389
  throw new Error(`[logic-sdk] ${where} has expose: true but no authorize. Say who may call it.`);
381
- if (def.expose && !def.outputSchema)
382
- throw new Error(`[logic-sdk] ${where} has expose: true but no outputSchema. Say what callers may see.`);
383
- 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 });
384
394
  };
385
395
 
386
396
  return {
@@ -394,12 +404,12 @@ function constructors<C extends Config>() {
394
404
  /** Talks to the outside world (payments, email, AI). No transaction; each mutation it runs commits on its own. */
395
405
  action: make("action") as Constructor<C, "action">,
396
406
  /** Something that happened. Emitted by mutations, delivered after commit. */
397
- 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>> =>
398
408
  Object.freeze({ [BRAND]: "event" as const, kind: "event" as const, ...def }),
399
- /** 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) => …)` */
400
410
  on: <O>(
401
- event: () => EventDef<any, O>,
402
- execute: (payload: O, ctx: ListenerCtx<C, O>) => Promise<unknown>,
411
+ event: () => EventDef<unknown, O>,
412
+ handler: (ctx: ListenerCtx<C, O>, payload: O) => Promise<unknown>,
403
413
  opts: { description?: string } = {},
404
414
  ): Listener<O> =>
405
415
  Object.freeze({
@@ -407,7 +417,7 @@ function constructors<C extends Config>() {
407
417
  kind: "listener" as const,
408
418
  event,
409
419
  description: opts.description,
410
- execute: execute as Listener<O>["execute"],
420
+ handler,
411
421
  }),
412
422
  };
413
423
  }
@@ -416,7 +426,7 @@ function constructors<C extends Config>() {
416
426
  * createRegistry
417
427
  * ──────────────────────────────────────────────────────────────────────────── */
418
428
 
419
- const INTERNAL: unique symbol = Symbol.for("logic-sdk.internal") as any;
429
+ const INTERNAL: unique symbol = Symbol.for("logic-sdk.internal");
420
430
 
421
431
  interface TxState {
422
432
  db: unknown;
@@ -437,19 +447,45 @@ interface Frame {
437
447
  }
438
448
 
439
449
  export interface Overrides {
440
- database?: DatabaseAdapter<any, any>;
450
+ database?: DatabaseAdapter<unknown, unknown>;
441
451
  services?: object;
442
452
  /** Merged over the registry's config, section by section. */
443
453
  config?: object;
444
454
  events?: Dispatcher;
445
455
  now?: () => Date;
446
- stubs?: Map<Fn, (input: any, ctx: any) => Promise<any>>;
456
+ stubs?: Map<Fn, (ctx: never, input: never) => Promise<unknown>>;
447
457
  record?: (envelope: Envelope) => void;
448
458
  }
449
459
 
450
- export type Registry<S extends object = object, Mods extends Record<string, object> = Record<string, object>, Cf = unknown> = ReturnType<
451
- typeof build<S, Mods, Cf>
452
- >;
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
+ }
453
489
 
454
490
  /** Create the registry once at startup. Prefer the `createRegistry` returned by `init()`: it's typed with your config. */
455
491
  export function createRegistry<S extends object = object, const Mods extends Record<string, object> = Record<string, object>>(
@@ -488,6 +524,8 @@ function freezeConfig(value: unknown, path = "config"): unknown {
488
524
  const describeIssues = (issues: readonly StandardSchemaV1.Issue[]) =>
489
525
  issues.map((i) => ({ message: i.message, path: i.path?.map((p) => (typeof p === "object" ? p.key : p)) }));
490
526
 
527
+ const isBranded = (v: unknown): v is Fn | EventDef | Listener => !!v && typeof v === "object" && BRAND in v;
528
+
491
529
  /**
492
530
  * What `createRegistry` finds in your modules, without a database or services: every function, event and
493
531
  * listener with its id. For tools (the CLI, docs generators) that inspect an app without running it.
@@ -495,26 +533,26 @@ const describeIssues = (issues: readonly StandardSchemaV1.Issue[]) =>
495
533
  export function describeModules(modules: Record<string, object>) {
496
534
  const ids = new Map<object, string>();
497
535
  const functions: RegisteredFn[] = [];
498
- const events: (Registered & { event: EventDef })[] = [];
499
- const listeners: (Registered & { listener: Listener; event: EventDef })[] = [];
536
+ const events: RegisteredEvent[] = [];
537
+ const listeners: RegisteredListener[] = [];
500
538
 
501
539
  for (const [module, ns] of Object.entries(modules)) {
502
540
  for (const [name, value] of Object.entries(ns)) {
503
- if (!value || typeof value !== "object" || !(BRAND in value) || ids.has(value)) continue;
541
+ if (!isBranded(value) || ids.has(value)) continue;
504
542
  const id = `${module}.${name}`;
505
543
  ids.set(value, id);
506
- const kind = (value as any)[BRAND];
507
- if (kind === "event") events.push({ id, module, name, event: value as EventDef });
508
- else if (kind === "listener") {
509
- const listener = value as Listener;
510
- listeners.push({ id, module, name, listener, event: listener.event() });
511
- } 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 });
512
547
  }
513
548
  }
514
549
  return { ids, functions, events, listeners };
515
550
  }
516
551
 
517
- function build<S extends object, Mods extends Record<string, object>, Cf = unknown>(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> {
518
556
  const { ids, functions, events, listeners } = describeModules(options.modules);
519
557
 
520
558
  const database = o.database ?? options.database;
@@ -569,7 +607,7 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
569
607
  }
570
608
 
571
609
  // ── listeners ────────────────────────────────────────────────────────────
572
- const byEvent = new Map<string, (Registered & { listener: Listener })[]>();
610
+ const byEvent = new Map<string, RegisteredListener[]>();
573
611
  for (const l of listeners) {
574
612
  const name = idOf(l.event);
575
613
  byEvent.set(name, [...(byEvent.get(name) ?? []), l]);
@@ -584,8 +622,8 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
584
622
  const frame: Frame = { scope: envelope.scope, depth: 0, eventDepth };
585
623
  try {
586
624
  await wrap({ id: l.id, kind: "listener", meta: undefined, input: envelope.payload, scope: envelope.scope, depth: 0 }, async () => {
587
- const payload = event ? await parseOwn(event.schema, envelope.payload, `${envelope.name} payload`) : envelope.payload;
588
- 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
589
627
  });
590
628
  } catch (error) {
591
629
  failures.push({ listener: l.id, error });
@@ -619,25 +657,23 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
619
657
  abortOn: options?.signal,
620
658
  });
621
659
 
622
- function queryCtx(frame: Frame, id: string): QueryCtx<any> {
623
- return {
624
- errors: errorsFor(id),
625
- scope: frame.scope,
626
- config: config as any,
627
- now,
628
- db: frame.tx ? frame.tx.db : database?.db,
629
- run: (fn, input, options) => invoke(fn, input, enter(frame, options), ["query"]),
630
- };
631
- }
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
+ });
632
672
  function mutationCtx(frame: Frame, id: string): MutationCtx<any> {
633
673
  const tx = frame.tx!;
634
674
  return {
635
- errors: errorsFor(id),
636
- scope: frame.scope,
637
- config: config as any,
638
- now,
675
+ ...baseCtx(frame, id, ["query", "mutation"]),
639
676
  db: tx.db,
640
- run: (fn, input, options) => invoke(fn, input, enter(frame, options), ["query", "mutation"]),
641
677
  emit: (event, payload) => {
642
678
  const name = idOf(event);
643
679
  payload = structuredClone(payload); // what was emitted is what gets delivered, even if the caller mutates it after
@@ -650,23 +686,17 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
650
686
  occurredAt: now().toISOString(),
651
687
  };
652
688
  tx.outbox.push(envelope);
653
- const check = parseOwn(event.schema, payload, `${name} payload`).then(() => {});
689
+ const check = parseOwn(event.payload, payload, `${name} payload`).then(() => {});
654
690
  check.catch(() => {}); // surfaced at commit; never an unhandled rejection
655
691
  tx.pending.push(check);
656
692
  },
657
693
  };
658
694
  }
659
- function actionCtx(frame: Frame, id: string): ActionCtx<any> {
660
- return {
661
- errors: errorsFor(id),
662
- scope: frame.scope,
663
- config: config as any,
664
- now,
665
- signal: frame.signal,
666
- services,
667
- run: (fn, input, options) => invoke(fn, input, enter({ ...frame, tx: undefined }, options), ["query", "mutation", "action"]),
668
- };
669
- }
695
+ const actionCtx = (frame: Frame, id: string): ActionCtx<any> => ({
696
+ ...baseCtx(frame, id, ["query", "mutation", "action"]),
697
+ signal: frame.signal,
698
+ services,
699
+ });
670
700
 
671
701
  // ── invoke ───────────────────────────────────────────────────────────────
672
702
  async function invoke(fn: Fn, rawInput: unknown, frame: Frame, allowed: Kind[]): Promise<any> {
@@ -680,17 +710,21 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
680
710
  const prepare = async () => {
681
711
  frame.abortOn?.throwIfAborted();
682
712
  if (fn.authorize) {
683
- const allowed: unknown = fn.authorize(frame.scope);
684
- 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)
685
716
  throw new Error(`[logic-sdk] The policy on ${id} returned a Promise. Policies are sync and read only the scope.`);
686
- if (allowed !== true) throw new DomainError("forbidden", `${id}.forbidden`);
717
+ if (verdict !== true) throw new DomainError("forbidden", `${id}.forbidden`);
687
718
  }
688
- 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;
689
721
  };
690
722
  const execute = async (input: unknown, ctx: unknown) => {
691
- const stub = o.stubs?.get(fn);
692
- const out = await (stub ? stub(input, ctx) : fn.execute(input, ctx));
693
- 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;
694
728
  };
695
729
 
696
730
  return wrap(call, async () => {
@@ -774,30 +808,20 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
774
808
  }
775
809
  }
776
810
 
777
- function makeCaller(scope: S): Caller<S> {
778
- return {
779
- scope,
780
- run: (fn, input, options) =>
781
- invoke(fn, input, enter({ scope, depth: -1 }, options as RunOptions | undefined), ["query", "mutation", "action"]), // depth 0
782
- };
783
- }
784
-
785
811
  return {
786
- /** The modules you registered (typed), for adapters that build typed routers. */
787
812
  modules: options.modules,
788
- /** Bind who is calling, once per request, job or test: `const caller = registry.as(scope)`. */
789
- as: (scope: S): Caller<S> => makeCaller(scope),
790
- /** Everything the registry can do. Adapters read this. */
791
- functions: functions as readonly RegisteredFn[],
792
- events: events as readonly (Registered & { event: EventDef })[],
793
- 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,
794
821
  idOf,
795
- /** Deliver one stored envelope to its listeners (durable dispatchers). Throws if any listener failed, so you can retry. */
796
822
  dispatch,
797
- /** @internal used by `logic-sdk/testing` */
798
823
  [INTERNAL]: {
799
824
  options,
800
- overrides: o,
801
825
  config,
802
826
  derive: (more: Overrides) => build<S, Mods, Cf>(options, { ...o, ...more, config: mergeConfig(o.config, more.config) as object | undefined }),
803
827
  },
@@ -805,4 +829,4 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
805
829
  }
806
830
 
807
831
  /** @internal */
808
- export const internal = (registry: Registry<any, any, any>) => registry[INTERNAL];
832
+ export const internal = <S extends object, Mods extends Record<string, object>, Cf>(registry: Registry<S, Mods, Cf>) => registry[INTERNAL];
package/src/orpc.ts CHANGED
@@ -1,12 +1,12 @@
1
1
  import { ORPCError, os, type Procedure } from "@orpc/server";
2
2
  import type { StandardSchemaV1 } from "@standard-schema/spec";
3
- import { isDomainError, type Caller, type ErrorKind, type Fn, type Registry } from "./index.ts";
3
+ import { isDomainError, type Caller, type ErrorKind, type ExposedOf, type Fn, type Kind, type Registry } from "./index.ts";
4
4
 
5
5
  /** oRPC context the router expects: bind who is calling per request, in your handler or middleware. */
6
6
  export type ORPCContext<S extends object> = { caller: Caller<S> };
7
7
 
8
8
  type ProcedureOf<S extends object, F> =
9
- F extends Fn<any, infer I, infer O, true>
9
+ F extends Fn<Kind, infer I, infer O, true>
10
10
  ? Procedure<ORPCContext<S>, ORPCContext<S>, StandardSchemaV1<I, I>, StandardSchemaV1<O, O>, {}>
11
11
  : never;
12
12
 
@@ -16,7 +16,6 @@ export type ORPCRouterOf<S extends object, Mods> = {
16
16
  [N in keyof ExposedOf<Mods[M]>]: ProcedureOf<S, Mods[M][N & keyof Mods[M]]>;
17
17
  };
18
18
  };
19
- type ExposedOf<T> = { [N in keyof T as T[N] extends Fn<any, any, any, true> ? N : never]: T[N] };
20
19
 
21
20
  /** Domain error kind → oRPC error code (and so HTTP status through oRPC's handlers). */
22
21
  export const orpcCodeOf: Record<ErrorKind, string> = {
@@ -46,8 +45,8 @@ export function toORPCRouter<S extends object, Mods extends Record<string, objec
46
45
 
47
46
  for (const f of registry.functions) {
48
47
  if (!f.exposed) continue;
49
- let b = base.input(f.fn.inputSchema as StandardSchemaV1);
50
- if (f.fn.outputSchema) b = b.output(f.fn.outputSchema as StandardSchemaV1) as any;
48
+ let b = f.fn.input ? base.input(f.fn.input) : base;
49
+ if (f.fn.output) b = b.output(f.fn.output) as any;
51
50
  (router[f.module] ??= {})[f.name] = b.handler(async ({ input, context, signal }) => {
52
51
  try {
53
52
  return await context.caller.run(f.fn, input, { signal });
package/src/testing.ts CHANGED
@@ -15,7 +15,7 @@ export interface TestTransaction<S extends object, Mods extends Record<string, o
15
15
  /** Bind who is calling, exactly like `registry.as(...)`. */
16
16
  as(scope: S): Caller<S>;
17
17
  /** Replace a function's implementation for this test. Matched by identity, so `run(availability.hold, …)` hits the stub. */
18
- stub<F extends Fn>(fn: F, impl: (input: FnIn<F>, ctx: any) => Promise<FnOut<F>>): void;
18
+ stub<F extends Fn>(fn: F, impl: (ctx: unknown, input: FnIn<F>) => Promise<FnOut<F>>): void;
19
19
  /** Every event emitted (and committed) so far, in order. */
20
20
  readonly events: Envelope[];
21
21
  /** The test transaction itself: read rows to assert on them. */
@@ -42,7 +42,7 @@ export function createTestRegistry<S extends object, Mods extends Record<string,
42
42
  : typeof options.now === "function"
43
43
  ? options.now
44
44
  : (() => {
45
- const fixed = new Date(options.now as Date | string);
45
+ const fixed = new Date(options.now);
46
46
  return () => new Date(fixed);
47
47
  })();
48
48
 
@@ -52,7 +52,7 @@ export function createTestRegistry<S extends object, Mods extends Record<string,
52
52
  let result!: T;
53
53
 
54
54
  const body = async (outer: unknown) => {
55
- const stubs = new Map<Fn, (input: any, ctx: any) => Promise<any>>();
55
+ const stubs = new Map<Fn, (ctx: never, input: never) => Promise<unknown>>();
56
56
  const events: Envelope[] = [];
57
57
  const derived = internal(registry).derive({
58
58
  database: outer !== undefined && database?.nest ? database.nest(outer) : database,
@@ -62,10 +62,10 @@ export function createTestRegistry<S extends object, Mods extends Record<string,
62
62
  stubs,
63
63
  record: (e) => events.push(e),
64
64
  events: options.listeners === false ? { deliver: async () => {} } : undefined,
65
- }) as Registry<S, Mods, Cf>;
65
+ });
66
66
  result = await fn({
67
67
  as: (scope) => derived.as(scope),
68
- stub: (f, impl) => void stubs.set(f, impl as (input: any, ctx: any) => Promise<any>),
68
+ stub: (f, impl) => void stubs.set(f, impl),
69
69
  events,
70
70
  db: outer,
71
71
  registry: derived,