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/dist/index.js CHANGED
@@ -44,9 +44,7 @@ export const inProcess = () => ({
44
44
  * ```
45
45
  */
46
46
  export function init() {
47
- return constructors();
48
- }
49
- function constructors() {
47
+ // One implementation behind the typed overloads of `Constructor`: the checks here are the runtime half of those types.
50
48
  const make = (kind) => (def) => {
51
49
  const where = def?.description ? `"${def.description}"` : `a ${kind}`;
52
50
  if (def.authorize !== undefined && typeof def.authorize !== "function")
@@ -55,9 +53,11 @@ function constructors() {
55
53
  throw new Error(`[logic-sdk] expose on ${where} must be \`true\` or left out.`);
56
54
  if (def.expose && !def.authorize)
57
55
  throw new Error(`[logic-sdk] ${where} has expose: true but no authorize. Say who may call it.`);
58
- if (def.expose && !def.outputSchema)
59
- throw new Error(`[logic-sdk] ${where} has expose: true but no outputSchema. Say what callers may see.`);
60
- return Object.freeze({ [BRAND]: kind, kind, outputSchema: undefined, ...def });
56
+ if (def.expose && !def.output)
57
+ throw new Error(`[logic-sdk] ${where} has expose: true but no output. Say what callers may see.`);
58
+ if (typeof def.handler !== "function")
59
+ throw new Error(`[logic-sdk] ${where} needs a handler(ctx, input).`);
60
+ return Object.freeze({ [BRAND]: kind, kind, ...def });
61
61
  };
62
62
  return {
63
63
  /** Create the registry once at startup: `createRegistry({ modules, database, services })`. */
@@ -70,13 +70,13 @@ function constructors() {
70
70
  action: make("action"),
71
71
  /** Something that happened. Emitted by mutations, delivered after commit. */
72
72
  event: (def) => Object.freeze({ [BRAND]: "event", kind: "event", ...def }),
73
- /** React to an event after commit, like an action. Must be idempotent. `on(() => bookings.confirmed, ...)` */
74
- on: (event, execute, opts = {}) => Object.freeze({
73
+ /** React to an event after commit, like an action. Must be idempotent. `on(() => bookings.confirmed, async (ctx, payload) => …)` */
74
+ on: (event, handler, opts = {}) => Object.freeze({
75
75
  [BRAND]: "listener",
76
76
  kind: "listener",
77
77
  event,
78
78
  description: opts.description,
79
- execute: execute,
79
+ handler,
80
80
  }),
81
81
  };
82
82
  }
@@ -114,6 +114,7 @@ function freezeConfig(value, path = "config") {
114
114
  "pass a Date as an ISO string, and put clients in services.");
115
115
  }
116
116
  const describeIssues = (issues) => issues.map((i) => ({ message: i.message, path: i.path?.map((p) => (typeof p === "object" ? p.key : p)) }));
117
+ const isBranded = (v) => !!v && typeof v === "object" && BRAND in v;
117
118
  /**
118
119
  * What `createRegistry` finds in your modules, without a database or services: every function, event and
119
120
  * listener with its id. For tools (the CLI, docs generators) that inspect an app without running it.
@@ -125,19 +126,16 @@ export function describeModules(modules) {
125
126
  const listeners = [];
126
127
  for (const [module, ns] of Object.entries(modules)) {
127
128
  for (const [name, value] of Object.entries(ns)) {
128
- if (!value || typeof value !== "object" || !(BRAND in value) || ids.has(value))
129
+ if (!isBranded(value) || ids.has(value))
129
130
  continue;
130
131
  const id = `${module}.${name}`;
131
132
  ids.set(value, id);
132
- const kind = value[BRAND];
133
- if (kind === "event")
133
+ if (value.kind === "event")
134
134
  events.push({ id, module, name, event: value });
135
- else if (kind === "listener") {
136
- const listener = value;
137
- listeners.push({ id, module, name, listener, event: listener.event() });
138
- }
135
+ else if (value.kind === "listener")
136
+ listeners.push({ id, module, name, listener: value, event: value.event() });
139
137
  else
140
- functions.push({ id, module, name, kind, fn: value, exposed: value.expose === true });
138
+ functions.push({ id, module, name, kind: value.kind, fn: value, exposed: value.expose === true });
141
139
  }
142
140
  }
143
141
  return { ids, functions, events, listeners };
@@ -205,8 +203,8 @@ function build(options, o) {
205
203
  const frame = { scope: envelope.scope, depth: 0, eventDepth };
206
204
  try {
207
205
  await wrap({ id: l.id, kind: "listener", meta: undefined, input: envelope.payload, scope: envelope.scope, depth: 0 }, async () => {
208
- const payload = event ? await parseOwn(event.schema, envelope.payload, `${envelope.name} payload`) : envelope.payload;
209
- return l.listener.execute(payload, { ...actionCtx(frame, l.id), event: { ...envelope, payload } });
206
+ const payload = event ? await parseOwn(event.payload, envelope.payload, `${envelope.name} payload`) : envelope.payload;
207
+ return l.listener.handler({ ...actionCtx(frame, l.id), event: { ...envelope, payload } }, payload); // SAFETY: as in invoke
210
208
  });
211
209
  }
212
210
  catch (error) {
@@ -235,25 +233,23 @@ function build(options, o) {
235
233
  signal: options?.signal ?? frame.signal,
236
234
  abortOn: options?.signal,
237
235
  });
238
- function queryCtx(frame, id) {
239
- return {
240
- errors: errorsFor(id),
241
- scope: frame.scope,
242
- config: config,
243
- now,
244
- db: frame.tx ? frame.tx.db : database?.db,
245
- run: (fn, input, options) => invoke(fn, input, enter(frame, options), ["query"]),
246
- };
247
- }
236
+ /** What every ctx has. `allowed`: the kinds its `run` may call. */
237
+ const baseCtx = (frame, id, allowed) => ({
238
+ errors: errorsFor(id),
239
+ scope: frame.scope,
240
+ config: config, // Frozen<Cf> here; each app's ctx types it from its own Config
241
+ now,
242
+ run: (fn, input, options) => invoke(fn, input, enter(frame, options), allowed),
243
+ });
244
+ const queryCtx = (frame, id) => ({
245
+ ...baseCtx(frame, id, ["query"]),
246
+ db: frame.tx ? frame.tx.db : database?.db,
247
+ });
248
248
  function mutationCtx(frame, id) {
249
249
  const tx = frame.tx;
250
250
  return {
251
- errors: errorsFor(id),
252
- scope: frame.scope,
253
- config: config,
254
- now,
251
+ ...baseCtx(frame, id, ["query", "mutation"]),
255
252
  db: tx.db,
256
- run: (fn, input, options) => invoke(fn, input, enter(frame, options), ["query", "mutation"]),
257
253
  emit: (event, payload) => {
258
254
  const name = idOf(event);
259
255
  payload = structuredClone(payload); // what was emitted is what gets delivered, even if the caller mutates it after
@@ -266,23 +262,17 @@ function build(options, o) {
266
262
  occurredAt: now().toISOString(),
267
263
  };
268
264
  tx.outbox.push(envelope);
269
- const check = parseOwn(event.schema, payload, `${name} payload`).then(() => { });
265
+ const check = parseOwn(event.payload, payload, `${name} payload`).then(() => { });
270
266
  check.catch(() => { }); // surfaced at commit; never an unhandled rejection
271
267
  tx.pending.push(check);
272
268
  },
273
269
  };
274
270
  }
275
- function actionCtx(frame, id) {
276
- return {
277
- errors: errorsFor(id),
278
- scope: frame.scope,
279
- config: config,
280
- now,
281
- signal: frame.signal,
282
- services,
283
- run: (fn, input, options) => invoke(fn, input, enter({ ...frame, tx: undefined }, options), ["query", "mutation", "action"]),
284
- };
285
- }
271
+ const actionCtx = (frame, id) => ({
272
+ ...baseCtx(frame, id, ["query", "mutation", "action"]),
273
+ signal: frame.signal,
274
+ services,
275
+ });
286
276
  // ── invoke ───────────────────────────────────────────────────────────────
287
277
  async function invoke(fn, rawInput, frame, allowed) {
288
278
  const id = idOf(fn);
@@ -293,18 +283,22 @@ function build(options, o) {
293
283
  const prepare = async () => {
294
284
  frame.abortOn?.throwIfAborted();
295
285
  if (fn.authorize) {
296
- const allowed = fn.authorize(frame.scope);
297
- if (allowed instanceof Promise || typeof allowed?.then === "function")
286
+ // SAFETY: the registry erases each policy's scope type; the caller's scope is the app's Scope by construction
287
+ const verdict = fn.authorize(frame.scope);
288
+ if (verdict instanceof Promise)
298
289
  throw new Error(`[logic-sdk] The policy on ${id} returned a Promise. Policies are sync and read only the scope.`);
299
- if (allowed !== true)
290
+ if (verdict !== true)
300
291
  throw new DomainError("forbidden", `${id}.forbidden`);
301
292
  }
302
- return parseInput(fn.inputSchema, rawInput, id, frame.depth > 0);
293
+ // no `input`: the function takes nothing, whatever an adapter sends (AI tools send `{}`)
294
+ return fn.input ? parseInput(fn.input, rawInput, id, frame.depth > 0) : undefined;
303
295
  };
304
296
  const execute = async (input, ctx) => {
305
- const stub = o.stubs?.get(fn);
306
- const out = await (stub ? stub(input, ctx) : fn.execute(input, ctx));
307
- return fn.outputSchema ? parseOwn(fn.outputSchema, out, `${id} output`) : out;
297
+ // SAFETY: the handler's types were erased when it was registered. `ctx` was built for its kind,
298
+ // and `input` just passed its own schema (or it takes none).
299
+ const handler = o.stubs?.get(fn) ?? fn.handler;
300
+ const out = await handler(ctx, input);
301
+ return fn.output ? parseOwn(fn.output, out, `${id} output`) : out;
308
302
  };
309
303
  return wrap(call, async () => {
310
304
  if (fn.kind === "query")
@@ -391,28 +385,19 @@ function build(options, o) {
391
385
  report(e, { listener: "(after commit)", envelope: outbox[0] });
392
386
  }
393
387
  }
394
- function makeCaller(scope) {
395
- return {
396
- scope,
397
- run: (fn, input, options) => invoke(fn, input, enter({ scope, depth: -1 }, options), ["query", "mutation", "action"]), // depth 0
398
- };
399
- }
400
388
  return {
401
- /** The modules you registered (typed), for adapters that build typed routers. */
402
389
  modules: options.modules,
403
- /** Bind who is calling, once per request, job or test: `const caller = registry.as(scope)`. */
404
- as: (scope) => makeCaller(scope),
405
- /** Everything the registry can do. Adapters read this. */
406
- functions: functions,
407
- events: events,
408
- listeners: listeners,
390
+ as: (scope) => ({
391
+ scope,
392
+ run: (fn, input, options) => invoke(fn, input, enter({ scope, depth: -1 }, options), ["query", "mutation", "action"]), // depth 0
393
+ }),
394
+ functions,
395
+ events,
396
+ listeners,
409
397
  idOf,
410
- /** Deliver one stored envelope to its listeners (durable dispatchers). Throws if any listener failed, so you can retry. */
411
398
  dispatch,
412
- /** @internal used by `logic-sdk/testing` */
413
399
  [INTERNAL]: {
414
400
  options,
415
- overrides: o,
416
401
  config,
417
402
  derive: (more) => build(options, { ...o, ...more, config: mergeConfig(o.config, more.config) }),
418
403
  },
package/dist/orpc.d.ts CHANGED
@@ -1,20 +1,17 @@
1
1
  import { type Procedure } from "@orpc/server";
2
2
  import type { StandardSchemaV1 } from "@standard-schema/spec";
3
- import { type Caller, type ErrorKind, type Fn, type Registry } from "./index.ts";
3
+ import { type Caller, type ErrorKind, type ExposedOf, type Fn, type Kind, type Registry } from "./index.ts";
4
4
  /** oRPC context the router expects: bind who is calling per request, in your handler or middleware. */
5
5
  export type ORPCContext<S extends object> = {
6
6
  caller: Caller<S>;
7
7
  };
8
- type ProcedureOf<S extends object, F> = F extends Fn<any, infer I, infer O, true> ? Procedure<ORPCContext<S>, ORPCContext<S>, StandardSchemaV1<I, I>, StandardSchemaV1<O, O>, {}> : never;
8
+ type ProcedureOf<S extends object, F> = F extends Fn<Kind, infer I, infer O, true> ? Procedure<ORPCContext<S>, ORPCContext<S>, StandardSchemaV1<I, I>, StandardSchemaV1<O, O>, {}> : never;
9
9
  /** `{ bookings: { confirm, cancel, … } }`: only functions with `expose: true`. */
10
10
  export type ORPCRouterOf<S extends object, Mods> = {
11
11
  [M in keyof Mods as {} extends ExposedOf<Mods[M]> ? never : M]: {
12
12
  [N in keyof ExposedOf<Mods[M]>]: ProcedureOf<S, Mods[M][N & keyof Mods[M]]>;
13
13
  };
14
14
  };
15
- type ExposedOf<T> = {
16
- [N in keyof T as T[N] extends Fn<any, any, any, true> ? N : never]: T[N];
17
- };
18
15
  /** Domain error kind → oRPC error code (and so HTTP status through oRPC's handlers). */
19
16
  export declare const orpcCodeOf: Record<ErrorKind, string>;
20
17
  /**
package/dist/orpc.js CHANGED
@@ -25,9 +25,9 @@ export function toORPCRouter(registry) {
25
25
  for (const f of registry.functions) {
26
26
  if (!f.exposed)
27
27
  continue;
28
- let b = base.input(f.fn.inputSchema);
29
- if (f.fn.outputSchema)
30
- b = b.output(f.fn.outputSchema);
28
+ let b = f.fn.input ? base.input(f.fn.input) : base;
29
+ if (f.fn.output)
30
+ b = b.output(f.fn.output);
31
31
  (router[f.module] ??= {})[f.name] = b.handler(async ({ input, context, signal }) => {
32
32
  try {
33
33
  return await context.caller.run(f.fn, input, { signal });
package/dist/testing.d.ts CHANGED
@@ -13,7 +13,7 @@ export interface TestTransaction<S extends object, Mods extends Record<string, o
13
13
  /** Bind who is calling, exactly like `registry.as(...)`. */
14
14
  as(scope: S): Caller<S>;
15
15
  /** Replace a function's implementation for this test. Matched by identity, so `run(availability.hold, …)` hits the stub. */
16
- stub<F extends Fn>(fn: F, impl: (input: FnIn<F>, ctx: any) => Promise<FnOut<F>>): void;
16
+ stub<F extends Fn>(fn: F, impl: (ctx: unknown, input: FnIn<F>) => Promise<FnOut<F>>): void;
17
17
  /** Every event emitted (and committed) so far, in order. */
18
18
  readonly events: Envelope[];
19
19
  /** The test transaction itself: read rows to assert on them. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "logic-sdk",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Queries, mutations, actions and events for TypeScript apps. Transactions, after-commit events and scopes, on any runtime.",
5
5
  "keywords": [
6
6
  "actions",
@@ -85,7 +85,7 @@
85
85
  "peerDependencies": {
86
86
  "@orpc/server": ">=2.0.0-beta.51 <3",
87
87
  "ai": ">=7 <8",
88
- "@logic-sdk/cli": ">=0.3.0 <0.4.0"
88
+ "@logic-sdk/cli": ">=0.4.0 <0.5.0"
89
89
  },
90
90
  "peerDependenciesMeta": {
91
91
  "@orpc/server": {
package/src/ai.ts CHANGED
@@ -1,7 +1,5 @@
1
- import { tool, type FlexibleSchema, type Tool } from "ai";
2
- import { isDomainError, type Caller, type Fn, type FnIn, type FnOut, type Registry, type RegisteredFn } from "./index.ts";
3
-
4
- type ExposedOf<T> = { [N in keyof T as T[N] extends Fn<any, any, any, true> ? N : never]: T[N] };
1
+ import { jsonSchema, tool, type Tool } from "ai";
2
+ import { isDomainError, type Caller, type ExposedFn, type ExposedOf, type FnIn, type FnOut, type Registry, type RegisteredFn } from "./index.ts";
5
3
  type UnionToIntersection<U> = (U extends unknown ? (u: U) => void : never) extends (i: infer I) => void ? I : never;
6
4
 
7
5
  /** `{ bookings_confirm, pricing_priceStay, … }`: one AI SDK tool per exposed function, typed. */
@@ -28,6 +26,9 @@ export interface AIToolsOptions extends AIToolOptions {
28
26
  filter: (fn: RegisteredFn) => boolean;
29
27
  }
30
28
 
29
+ /** What a function without input looks like to the model: an object with nothing in it. It sends `{}`, which run ignores. */
30
+ const noInput = jsonSchema({ type: "object", properties: {}, additionalProperties: false });
31
+
31
32
  /**
32
33
  * One exposed function as an AI SDK tool, run as `caller`: the agent goes through the same policy,
33
34
  * validation, transaction and events as your HTTP API. You name it, like any AI SDK tool.
@@ -40,8 +41,8 @@ export interface AIToolsOptions extends AIToolOptions {
40
41
  * Domain errors reach the model (it sees the code and can react). Anything unexpected is reported
41
42
  * to `onError` and the model gets "internal_error", so internals never land in its context.
42
43
  */
43
- export function toAITool<F extends Fn<any, any, any, true>>(
44
- caller: Caller<any>,
44
+ export function toAITool<F extends ExposedFn>(
45
+ caller: Caller<object>,
45
46
  fn: F,
46
47
  options: AIToolOptions = {},
47
48
  ): Tool<FnIn<F>, FnOut<F>> {
@@ -49,8 +50,8 @@ export function toAITool<F extends Fn<any, any, any, true>>(
49
50
  if (fn.expose !== true) throw new Error("[logic-sdk] toAITool needs a function with expose: true.");
50
51
  return tool({
51
52
  description: fn.description,
52
- inputSchema: fn.inputSchema as FlexibleSchema,
53
- outputSchema: fn.outputSchema as FlexibleSchema,
53
+ inputSchema: fn.input ?? noInput,
54
+ outputSchema: fn.output,
54
55
  async execute(input, { abortSignal }) {
55
56
  try {
56
57
  return await caller.run(fn, input, { signal: abortSignal });
@@ -79,6 +80,6 @@ export function toAITools<S extends object, Mods extends Record<string, object>>
79
80
  throw new Error("[logic-sdk] toAITools needs a filter: the agent door is opt-in. E.g. { filter: (f) => f.fn.meta?.agent === true }");
80
81
  const tools: Record<string, Tool> = {};
81
82
  for (const f of registry.functions)
82
- if (f.exposed && options.filter(f)) tools[`${f.module}_${f.name}`] = toAITool(caller, f.fn as Fn<any, any, any, true>, options);
83
+ if (f.exposed && options.filter(f)) tools[`${f.module}_${f.name}`] = toAITool(caller, f.fn as ExposedFn, options);
83
84
  return tools as Partial<AIToolsOf<Mods>>;
84
85
  }
package/src/drizzle.ts CHANGED
@@ -24,7 +24,7 @@ export function drizzleAdapter<Db extends Transactional>(db: Db): DatabaseAdapte
24
24
  db,
25
25
  transactions: "interactive",
26
26
  transaction: (fn) => db.transaction(fn),
27
- nest: (tx) => drizzleAdapter(tx as Transactional) as any,
27
+ nest: (tx) => drizzleAdapter(tx),
28
28
  retryable: (e) => RETRYABLE.has(sqlState(e) ?? ""),
29
29
  };
30
30
  }
package/src/fetch.ts CHANGED
@@ -34,7 +34,7 @@ const json = (body: unknown, status = 200) =>
34
34
  * Publishes only functions with `expose: true`. POST `{base}{id}` with a JSON body (`content-type: application/json` required);
35
35
  * queries also accept GET `?input=<json>`.
36
36
  */
37
- export function toFetchHandler<S extends object>(registry: Registry<S, any>, options: FetchOptions<S>) {
37
+ export function toFetchHandler<S extends object>(registry: Registry<S>, options: FetchOptions<S>) {
38
38
  const base = (options.basePath ?? "/").replace(/\/?$/, "/");
39
39
  const exposed = new Map(registry.functions.filter((f) => f.exposed).map((f) => [f.id, f]));
40
40
  const onError = options.onError ?? ((e) => console.error("[logic-sdk] unexpected error", e));