logic-sdk 0.4.0 → 0.6.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.
Files changed (58) hide show
  1. package/README.md +40 -15
  2. package/bin/logic-sdk.js +1 -1
  3. package/dist/ai.d.ts +16 -26
  4. package/dist/ai.js +8 -21
  5. package/dist/cloudflare.d.ts +55 -0
  6. package/dist/cloudflare.js +85 -0
  7. package/dist/drizzle/pg.d.ts +236 -0
  8. package/dist/drizzle/pg.js +67 -0
  9. package/dist/drizzle/sqlite.d.ts +242 -0
  10. package/dist/drizzle/sqlite.js +194 -0
  11. package/dist/errors.d.ts +33 -0
  12. package/dist/errors.js +45 -0
  13. package/dist/fetch.d.ts +15 -18
  14. package/dist/fetch.js +18 -55
  15. package/dist/index.d.ts +78 -379
  16. package/dist/index.js +240 -186
  17. package/dist/jobs.d.ts +44 -0
  18. package/dist/jobs.js +252 -0
  19. package/dist/node.d.ts +26 -0
  20. package/dist/node.js +76 -0
  21. package/dist/orpc.d.ts +10 -17
  22. package/dist/orpc.js +19 -28
  23. package/dist/pg-boss.d.ts +55 -0
  24. package/dist/pg-boss.js +211 -0
  25. package/dist/postgres.d.ts +28 -0
  26. package/dist/postgres.js +82 -0
  27. package/dist/schedule.d.ts +23 -0
  28. package/dist/schedule.js +109 -0
  29. package/dist/sqlite.d.ts +9 -0
  30. package/dist/sqlite.js +65 -0
  31. package/dist/stored-jobs.d.ts +64 -0
  32. package/dist/stored-jobs.js +188 -0
  33. package/dist/testing.d.ts +50 -14
  34. package/dist/testing.js +198 -46
  35. package/dist/types.d.ts +655 -0
  36. package/dist/types.js +6 -0
  37. package/package.json +45 -7
  38. package/skills/logic-sdk/SKILL.md +114 -0
  39. package/src/ai.ts +23 -46
  40. package/src/cloudflare.ts +107 -0
  41. package/src/drizzle/pg.ts +110 -0
  42. package/src/drizzle/sqlite.ts +236 -0
  43. package/src/errors.ts +59 -0
  44. package/src/fetch.ts +17 -65
  45. package/src/index.ts +404 -564
  46. package/src/jobs.ts +296 -0
  47. package/src/node.ts +99 -0
  48. package/src/orpc.ts +24 -42
  49. package/src/pg-boss.ts +242 -0
  50. package/src/postgres.ts +90 -0
  51. package/src/schedule.ts +129 -0
  52. package/src/sqlite.ts +74 -0
  53. package/src/stored-jobs.ts +260 -0
  54. package/src/testing.ts +252 -55
  55. package/src/types.ts +685 -0
  56. package/dist/drizzle.d.ts +0 -18
  57. package/dist/drizzle.js +0 -23
  58. package/src/drizzle.ts +0 -39
package/src/index.ts CHANGED
@@ -1,369 +1,123 @@
1
- import type { StandardSchemaV1 } from "@standard-schema/spec";
2
-
3
- /* ────────────────────────────────────────────────────────────────────────────
4
- * Types
5
- * ──────────────────────────────────────────────────────────────────────────── */
6
-
7
- type Schema<I = any, O = any> = StandardSchemaV1<I, O>;
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
-
11
- /** What you declare once in `init<...>()`. */
12
- export interface Config {
13
- /** Who and where: actor, account, locale... Must be JSON-serializable (it travels with events). */
14
- scope: object;
15
- /** The transaction handle mutations receive (e.g. a Drizzle transaction). */
16
- db?: unknown;
17
- /** What queries receive. Defaults to `db`. Use a read-only type (e.g. `DrizzleReader<Tx>`). */
18
- reader?: unknown;
19
- /** Side-effecting services (mailer, payments...). Only actions and listeners receive them. */
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;
26
- /** The shape of `meta` on your functions (tags, rate limits, "agent may call"...). Read by `wrap` and adapters. */
27
- meta?: object;
28
- }
29
- type ScopeOf<C extends Config> = C["scope"];
30
- type DbOf<C extends Config> = C extends { db: infer D } ? D : never;
31
- type ReaderOf<C extends Config> = C extends { reader: infer R } ? R : DbOf<C>;
32
- type ServicesOf<C extends Config> = C extends { services: infer S } ? S : {};
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]> };
46
-
47
- export type Kind = "query" | "mutation" | "action";
48
-
49
- declare const types: unique symbol;
50
- const BRAND: unique symbol = Symbol.for("logic-sdk.brand");
51
-
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 = unknown, O = unknown, E extends boolean = boolean> {
54
- readonly [BRAND]: K;
55
- readonly kind: K;
56
- readonly description: string;
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;
61
- /** Your own data about the function. Checked against `meta` in `init` where you set it, typed in `wrap`; loose here, for adapters. */
62
- readonly meta?: Readonly<Record<string, unknown>>;
63
- /** Who may call it (from `authorize`). Runs on every call, before validation. */
64
- readonly authorize?: Policy<never>;
65
- /** `true`: adapters may publish it (HTTP, oRPC, AI tools). Requires `authorize` and `output`. */
66
- readonly expose?: true;
67
- readonly handler: (ctx: never, input: never) => Promise<unknown>;
68
- /** Phantom types, never set at runtime. */
69
- readonly [types]?: { input: I; output: O; exposed: E };
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] };
73
- /** A function with `expose: true`: adapters may publish it. */
74
- export type ExposedFn<K extends Kind = Kind, I = unknown, O = unknown> = Fn<K, I, O, true>;
75
- /** What callers pass to a function. */
76
- export type FnIn<F> = F extends Fn<Kind, infer I, unknown> ? I : never;
77
- /** What a function returns. */
78
- export type FnOut<F> = F extends Fn<Kind, unknown, infer O> ? O : never;
79
-
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> {
82
- readonly [BRAND]: "event";
83
- readonly kind: "event";
84
- /** The payload's schema, checked when emitted and again at delivery. */
85
- readonly payload: Schema;
86
- readonly description?: string;
87
- readonly [types]?: { input: I; payload: O };
88
- }
89
-
90
- /**
91
- * What a dispatcher stores and delivers. Fully JSON: `payload` is what was emitted (validated),
92
- * and listeners get it parsed again by the event's payload schema at delivery.
93
- */
94
- export interface Envelope<P = unknown, S = object> {
95
- id: string;
96
- name: string;
97
- payload: P;
98
- scope: S;
99
- occurredAt: string;
100
- }
101
-
102
- export interface Listener<O = unknown> {
103
- readonly [BRAND]: "listener";
104
- readonly kind: "listener";
105
- /** Lazy, so listeners can import other modules' barrels without import cycles. */
106
- readonly event: () => EventDef<unknown, O>;
107
- readonly description?: string;
108
- readonly handler: (ctx: never, payload: O) => Promise<unknown>;
109
- }
110
-
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>>;
129
-
130
- /**
131
- * Expected failures, namespaced to the module you're in: inside `bookings`, `ctx.errors.reject("not_pending")` has
132
- * code `"bookings.not_pending"`. Throw what they return. Codes are plain strings on purpose (see the errors docs).
133
- */
134
- export interface Errors {
135
- /** A business rule said no, and trying again won't help. `throw ctx.errors.reject("not_pending", { status })` */
136
- reject(code: string, details?: unknown): DomainError;
137
- /** Someone else got there first, or it already exists. Refreshing and retrying may work. */
138
- conflict(code: string, details?: unknown): DomainError;
139
- /** It doesn't exist, or isn't visible in this scope. Code defaults to `"<module>.not_found"`. */
140
- notFound(code?: string, details?: unknown): DomainError;
141
- /** The caller is known but may not do this. Code defaults to `"<module>.<function>.forbidden"`. */
142
- deny(code?: string, details?: unknown): DomainError;
143
- }
144
- interface BaseCtx<C extends Config, S> {
145
- scope: S;
146
- /** Your settings from `createRegistry({ config })`. Read-only; tests override parts of it. */
147
- config: Frozen<ConfigOf<C>>;
148
- /** Expected failures: `throw ctx.errors.reject("not_pending")`. */
149
- errors: Errors;
150
- /** Current time. Fixed in tests. */
151
- now: () => Date;
152
- }
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> {
155
- db: ReaderOf<C>;
156
- /** Call another query, with its policy, validation and output check: `await ctx.run(pricing.quote, { nights })`. */
157
- run: Run<"query", ScopeOf<C>>;
158
- }
159
- export interface MutationCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C, S> {
160
- db: DbOf<C>;
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>>;
166
- /** Queue an event. Delivered to listeners only after the transaction commits. */
167
- emit<I>(event: EventDef<I, unknown>, payload: I): void;
168
- }
169
- export interface ActionCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C, S> {
170
- services: ServicesOf<C>;
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). */
174
- signal: AbortSignal | undefined;
175
- }
176
- export interface ListenerCtx<C extends Config, O = unknown> extends ActionCtx<C> {
177
- event: Envelope<unknown, ScopeOf<C>> & { payload: O };
178
- }
179
-
180
- /**
181
- * Who may call a function at all: signed in, admin, staff. Sync, reads only the scope, returns exactly `true` to allow.
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.
184
- */
185
- export type Policy<S> = (scope: S) => boolean;
186
- type Guarded<F, S> = F extends (scope: any) => scope is infer G ? G : S;
187
- type CtxOf<C extends Config, K extends Kind, S> = K extends "query"
188
- ? QueryCtx<C, S>
189
- : K extends "mutation"
190
- ? MutationCtx<C, S>
191
- : ActionCtx<C, S>;
192
-
193
- /** What a function without `input` gets: nothing. */
194
- type NoInput = StandardSchemaV1<undefined, undefined>;
195
- type Def<IS extends Schema, Ctx, R> = {
196
- /** One sentence, shown to humans, adapters and AI tools. */
197
- description: string;
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>;
201
- };
202
- type NotExposed = { expose?: undefined };
203
- type NoPolicy = { authorize?: undefined };
204
- type WithMeta<C extends Config> = { meta?: MetaOf<C> };
205
- type WithOutput<OS extends Schema> = { output: OS };
206
-
207
- /**
208
- * `expose: true` needs `authorize` and `output`: you can't publish something without saying who may call it,
209
- * and what leaves your process is a contract. Internal functions may skip both; `authorize` still runs if set.
210
- */
211
- interface Constructor<C extends Config, K extends Kind> {
212
- <IS extends Schema = NoInput, OS extends Schema = Schema, P extends Policy<ScopeOf<C>> = Policy<ScopeOf<C>>>(
213
- def: Def<IS, CtxOf<C, K, Guarded<P, ScopeOf<C>>>, In<OS>> &
214
- WithOutput<OS> &
215
- WithMeta<C> & { authorize: P; expose: true },
216
- ): Fn<K, In<IS>, Out<OS>, true>;
217
- <IS extends Schema = NoInput, OS extends Schema = Schema, P extends Policy<ScopeOf<C>> = Policy<ScopeOf<C>>>(
218
- def: Def<IS, CtxOf<C, K, Guarded<P, ScopeOf<C>>>, In<OS>> & WithOutput<OS> & WithMeta<C> & { authorize: P } & NotExposed,
219
- ): Fn<K, In<IS>, Out<OS>, false>;
220
- <IS extends Schema = NoInput, R = unknown, P extends Policy<ScopeOf<C>> = Policy<ScopeOf<C>>>(
221
- def: Def<IS, CtxOf<C, K, Guarded<P, ScopeOf<C>>>, R> & WithMeta<C> & { authorize: P } & NotExposed,
222
- ): Fn<K, In<IS>, R, false>;
223
- <IS extends Schema = NoInput, OS extends Schema = Schema>(
224
- def: Def<IS, CtxOf<C, K, ScopeOf<C>>, In<OS>> & WithOutput<OS> & WithMeta<C> & NoPolicy & NotExposed,
225
- ): Fn<K, In<IS>, Out<OS>, 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>;
227
- }
228
-
229
- /* ────────────────────────────────────────────────────────────────────────────
230
- * Errors
231
- * ──────────────────────────────────────────────────────────────────────────── */
232
-
233
- export type ErrorKind = "invalid" | "unauthenticated" | "forbidden" | "not_found" | "conflict" | "rejected";
234
-
235
- /**
236
- * An expected failure: a `kind` (a small fixed set), a namespaced `code` and optional `details`. No HTTP here;
237
- * adapters map kinds to statuses. Anything else thrown (including invalid output or event payloads, which are
238
- * bugs) is unexpected: adapters answer 500 and report it.
239
- */
240
- export class DomainError extends Error {
241
- readonly kind: ErrorKind;
242
- readonly code: string;
243
- readonly details: unknown;
244
- constructor(kind: ErrorKind, code: string, details?: unknown) {
245
- // the details are in the message too: logs and AI tool errors (which show only the message) stay useful
246
- super(details === undefined ? code : `${code} ${JSON.stringify(details)}`);
247
- this.name = "DomainError";
248
- this.kind = kind;
249
- this.code = code;
250
- this.details = details;
251
- }
252
- }
253
- /** `isDomainError(e)`, or with a code: `isDomainError(e, "availability.dates_unavailable")`. */
254
- export const isDomainError = (e: unknown, code?: string): e is DomainError =>
255
- e instanceof DomainError && (code === undefined || e.code === code);
256
-
257
- /** `ctx.errors` for one function or listener (`id` like "bookings.confirm"). */
258
- const errorsFor = (id: string): Errors => {
259
- const module = id.slice(0, id.indexOf("."));
260
- return {
261
- reject: (code, details) => new DomainError("rejected", `${module}.${code}`, details),
262
- conflict: (code, details) => new DomainError("conflict", `${module}.${code}`, details),
263
- notFound: (code = "not_found", details) => new DomainError("not_found", `${module}.${code}`, details),
264
- deny: (code, details) => new DomainError("forbidden", code ? `${module}.${code}` : `${id}.forbidden`, details),
265
- };
266
- };
267
-
268
- /* ────────────────────────────────────────────────────────────────────────────
269
- * Adapters and dispatcher seams
270
- * ──────────────────────────────────────────────────────────────────────────── */
271
-
272
- export interface DatabaseAdapter<Db = unknown, Tx = Db> {
273
- /** Root handle, used by top-level queries. */
274
- readonly db: Db;
275
- readonly transactions: "interactive";
276
- transaction<T>(fn: (tx: Tx) => Promise<T>): Promise<T>;
277
- /** An adapter bound to an existing transaction (nested transactions become savepoints). Used by the test helper. */
278
- nest?(tx: Tx): DatabaseAdapter<Tx, Tx>;
279
- /** Did this transaction lose a race the database says to retry (deadlock, serialization failure)? */
280
- retryable?(error: unknown): boolean;
281
- }
282
-
283
- export interface Dispatcher {
284
- /** Inside the transaction, before commit. In-process: nothing. Outbox: insert rows with `tx`. */
285
- enqueue?(tx: unknown, envelopes: Envelope[]): Promise<void>;
286
- /** After commit. `dispatch` runs the listeners for one envelope and never throws (failures go to `onError`). */
287
- deliver(envelopes: Envelope[], dispatch: (envelope: Envelope) => Promise<void>): Promise<void>;
288
- }
289
-
290
- /** Default dispatcher: delivers right after commit, in this process. Lost on crash: use an outbox when that matters. */
291
- export const inProcess = (): Dispatcher => ({
292
- async deliver(envelopes, dispatch) {
293
- for (const e of envelopes) await dispatch(e);
294
- },
295
- });
296
-
297
- export interface Call<M = unknown> {
298
- id: string;
299
- kind: Kind | "listener";
300
- /** The function's `meta` (undefined for listeners and functions without it). */
301
- meta: M | undefined;
302
- /** Raw input as received (before validation). */
303
- input: unknown;
304
- scope: object;
305
- depth: number;
306
- }
307
-
308
- export interface RegistryOptions<Mods extends Record<string, object>> {
309
- /** One entry per module: `{ bookings, availability }` with `import * as bookings from "./bookings"`. */
310
- modules: Mods;
311
- database?: DatabaseAdapter<unknown, unknown>;
312
- services?: object;
313
- /** Settings every function reads as `ctx.config`. Plain data: it's copied and frozen. */
314
- config?: object;
315
- events?: Dispatcher;
316
- /** Wraps every call, including ones that fail validation or authorization: logging, tracing, audit. */
317
- wrap?: (call: Call, next: () => Promise<unknown>) => Promise<unknown>;
318
- /**
319
- * Serverless: let listeners finish after the response. Pass the platform's global:
320
- * `import { waitUntil } from "cloudflare:workers"` or `import { waitUntil } from "@vercel/functions"`.
321
- * Without it, `run` waits for listeners, which is what tests and long-lived servers want.
322
- */
323
- waitUntil?: (promise: Promise<unknown>) => void;
324
- /** Failures after commit land here (listeners, dispatcher). They never fail the caller. */
325
- onError?: (error: unknown, info: { listener: string; envelope: Envelope | undefined }) => void;
326
- now?: () => Date;
327
- /** Max chain of listener → mutation → event → listener… before delivery stops. Default 8 (real chains are 2 or 3). */
328
- maxEventDepth?: number;
329
- /**
330
- * Re-run a top-level mutation in a fresh transaction when the database says it lost a race (deadlock,
331
- * serialization failure). Safe because mutations have no side effects and events are rebuilt per attempt.
332
- * Default 3 attempts in total; `{ attempts: 1 }` turns it off.
333
- */
334
- retry?: { attempts?: number };
335
- }
336
-
337
- /** A registry bound to who is calling: `const caller = registry.as(scope)`. */
338
- export interface Caller<S extends object = object> {
339
- readonly scope: 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>>;
342
- }
343
-
344
- export interface Registered {
345
- id: string;
346
- module: string;
347
- name: string;
348
- }
349
- export interface RegisteredFn extends Registered {
350
- fn: Fn;
351
- kind: Kind;
352
- /** Has `expose: true`: adapters may publish it. */
353
- exposed: boolean;
354
- }
1
+ import { describeIssues, DomainError, errorsFor } from "./errors.ts";
2
+ import { inProcess, makeJobs, replaceKeyOf, runsNow } from "./jobs.ts";
3
+ import { assertTimeZone, parseSchedule } from "./schedule.ts";
4
+ import { BRAND, INTERNAL } from "./types.ts";
5
+ import type {
6
+ ActionCtx,
7
+ Call,
8
+ CallJob,
9
+ CallMetaOf,
10
+ Config,
11
+ ConfigOf,
12
+ Constructor,
13
+ Cron,
14
+ DatabaseAdapter,
15
+ DbOf,
16
+ Envelope,
17
+ EventDef,
18
+ FailureInfo,
19
+ Fn,
20
+ FnIn,
21
+ Frozen,
22
+ In,
23
+ Job,
24
+ JobsOptions,
25
+ Kind,
26
+ Listener,
27
+ ListenerCtx,
28
+ ListenerMetaOf,
29
+ MutationCtx,
30
+ Out,
31
+ Overrides,
32
+ OwnModules,
33
+ QueryCtx,
34
+ RegisteredCron,
35
+ RegisteredEvent,
36
+ RegisteredFn,
37
+ RegisteredListener,
38
+ Registry,
39
+ RegistryOptions,
40
+ RunOptions,
41
+ Schema,
42
+ ScopeOf,
43
+ ServicesOf,
44
+ } from "./types.ts";
45
+
46
+ export type {
47
+ ActionCtx,
48
+ Call,
49
+ CallJob,
50
+ Caller,
51
+ Config,
52
+ Constructor,
53
+ Cron,
54
+ CronJob,
55
+ DatabaseAdapter,
56
+ DeepPartial,
57
+ Delivery,
58
+ Envelope,
59
+ Errors,
60
+ EventDef,
61
+ FailureInfo,
62
+ Fn,
63
+ FnIn,
64
+ FnOut,
65
+ ForFunctions,
66
+ ForListeners,
67
+ Frozen,
68
+ In,
69
+ InProcess,
70
+ Job,
71
+ JobOutcome,
72
+ JobsAdapter,
73
+ JobScope,
74
+ Jobs,
75
+ JobsOptions,
76
+ Kind,
77
+ Listener,
78
+ ListenerCtx,
79
+ ListenerEvent,
80
+ MutationCtx,
81
+ Out,
82
+ Policy,
83
+ PublishableFn,
84
+ ScopeOfFn,
85
+ QueryCtx,
86
+ ReadWrite,
87
+ Registered,
88
+ RegisteredCron,
89
+ RegisteredEvent,
90
+ RegisteredFn,
91
+ RegisteredListener,
92
+ Registry,
93
+ RegistryOptions,
94
+ RunArgs,
95
+ RunJob,
96
+ RunJobOptions,
97
+ RunOptions,
98
+ Runner,
99
+ ScheduleOptions,
100
+ Schema,
101
+ SqlDatabase,
102
+ SweepResult,
103
+ } from "./types.ts";
104
+ export { DomainError, isDomainError, unauthenticated, type ErrorKind } from "./errors.ts";
105
+ export { inProcess, replaceKeyOf } from "./jobs.ts";
355
106
 
356
107
  /* ────────────────────────────────────────────────────────────────────────────
357
108
  * init: typed constructors
358
109
  * ──────────────────────────────────────────────────────────────────────────── */
359
110
 
360
- type TypedOptions<C extends Config, Mods extends Record<string, object>> = Omit<RegistryOptions<Mods>, "wrap"> & {
111
+ type TypedOptions<C extends Config, Mods extends Record<string, object>, T> = Omit<RegistryOptions<Mods>, "wrap" | "jobs"> & {
112
+ /** Background work: `jobs: { adapter: databaseQueue(database), scope: { store, load } }`. Default: in-process, scope as-is (nothing waits). */
113
+ jobs?: JobsOptions<ScopeOf<C>, T>;
361
114
  /** Wraps every call, including ones that fail validation or authorization: logging, tracing, audit. */
362
- wrap?: (call: Call<MetaOf<C>>, next: () => Promise<unknown>) => Promise<unknown>;
115
+ wrap?: (call: Call<CallMetaOf<C>>, next: () => Promise<unknown>) => Promise<unknown>;
363
116
  } &
364
117
  ({} extends ServicesOf<C> ? { services?: ServicesOf<C> } : { services: ServicesOf<C> }) &
365
118
  ({} extends ConfigOf<C> ? { config?: ConfigOf<C> } : { config: ConfigOf<C> }) &
366
- ([DbOf<C>] extends [never] ? { database?: undefined } : { database: DatabaseAdapter<unknown, DbOf<C>> });
119
+ ([DbOf<C>] extends [never] ? { database?: undefined } : { database: DatabaseAdapter<unknown, DbOf<C>> }) &
120
+ { modules: OwnModules<C, Mods> };
367
121
 
368
122
  /** Keys `Config` doesn't know are errors, so a typo like `servises` can't be silently ignored. */
369
123
  type OnlyKnownKeys<C> = { [K in Exclude<keyof C, keyof Config>]: never };
@@ -372,31 +126,20 @@ type OnlyKnownKeys<C> = { [K in Exclude<keyof C, keyof Config>]: never };
372
126
  * Typed constructors for your app:
373
127
  *
374
128
  * ```ts
375
- * export const { query, mutation, action, event, on, createRegistry } = init<Config>();
129
+ * export const { query, mutation, action, event, listener, createRegistry } = init<Config>();
376
130
  * ```
377
131
  */
378
132
  export function init<C extends Config & OnlyKnownKeys<C>>() {
379
- // One implementation behind the typed overloads of `Constructor`: the checks here are the runtime half of those types.
133
+ // One implementation behind the typed signature of `Constructor`: the types are the contract, the adapters check `authorize`.
380
134
  const make =
381
135
  <K extends Kind>(kind: K) =>
382
- (def: any): any => {
383
- const where = def?.description ? `"${def.description}"` : `a ${kind}`;
384
- if (def.authorize !== undefined && typeof def.authorize !== "function")
385
- throw new Error(`[logic-sdk] authorize on ${where} must be a policy function, like \`authorize: member\`.`);
386
- if (def.expose !== undefined && def.expose !== true)
387
- throw new Error(`[logic-sdk] expose on ${where} must be \`true\` or left out.`);
388
- if (def.expose && !def.authorize)
389
- throw new Error(`[logic-sdk] ${where} has expose: true but no authorize. Say who may call it.`);
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 });
394
- };
136
+ (def: object) =>
137
+ Object.freeze({ [BRAND]: kind, kind, ...def });
395
138
 
396
139
  return {
397
140
  /** Create the registry once at startup: `createRegistry({ modules, database, services })`. */
398
- createRegistry: <const Mods extends Record<string, object>>(options: TypedOptions<C, Mods>) =>
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
141
+ createRegistry: <const Mods extends Record<string, object>, T = ScopeOf<C>>(options: TypedOptions<C, Mods, T>) =>
142
+ build<ScopeOf<C>, Mods, ConfigOf<C>>(options as RegistryOptions<Mods>, {}), // meta in wrap is typed by CallMetaOf<C>; the values come from typed defs
400
143
  /** Reads data. Can run other queries. No writes, no events, no services. */
401
144
  query: make("query") as Constructor<C, "query">,
402
145
  /** Changes data inside one transaction. Can run queries and mutations (same transaction) and emit events. */
@@ -404,89 +147,123 @@ export function init<C extends Config & OnlyKnownKeys<C>>() {
404
147
  /** Talks to the outside world (payments, email, AI). No transaction; each mutation it runs commits on its own. */
405
148
  action: make("action") as Constructor<C, "action">,
406
149
  /** Something that happened. Emitted by mutations, delivered after commit. */
407
- event: <S extends Schema>(def: { payload: S; description?: string }): EventDef<In<S>, Out<S>> =>
150
+ event: <S extends Schema>(def: {
151
+ /**
152
+ * Stable id, local to its module: in a `notifications` module, `id: "send"` is `notifications.send`. Jobs store it,
153
+ * so set it before you rename the export and queued jobs keep finding this code. Defaults to the export name.
154
+ */
155
+ id?: string;
156
+ payload: S;
157
+ }): EventDef<In<S>, Out<S>> =>
408
158
  Object.freeze({ [BRAND]: "event" as const, kind: "event" as const, ...def }),
409
- /** React to an event after commit, like an action. Must be idempotent. `on(() => bookings.confirmed, async (ctx, payload) => …)` */
410
- on: <O>(
411
- event: () => EventDef<unknown, O>,
412
- handler: (ctx: ListenerCtx<C, O>, payload: O) => Promise<unknown>,
413
- opts: { description?: string } = {},
414
- ): Listener<O> =>
415
- Object.freeze({
416
- [BRAND]: "listener" as const,
417
- kind: "listener" as const,
418
- event,
419
- description: opts.description,
420
- handler,
421
- }),
159
+ /**
160
+ * Run a function on a schedule, as `scope` (a cron has no caller). Export it from a module, like listeners, and call
161
+ * `registry.jobs.tick()` every minute (or from your platform's cron trigger):
162
+ * `cron({ schedule: "0 9 * * 1", run: () => reports.sendWeekly, scope: system })`.
163
+ */
164
+ cron: <F extends Fn>(def: CronDef<ScopeOf<C>, F>): Cron<C> => {
165
+ const { id, schedule, timezone, run, input, scope, attempts } = def;
166
+ parseSchedule(schedule);
167
+ if (timezone !== undefined) assertTimeZone(timezone);
168
+ checkAttempts("cron", attempts);
169
+ return Object.freeze({ [BRAND]: "cron" as const, kind: "cron" as const, id, schedule, timezone, run, input, scope, attempts });
170
+ },
171
+ /**
172
+ * React to an event after commit, like an action. Must be idempotent.
173
+ * `listener({ event: () => bookings.confirmed, async handler(ctx, payload) {…} })`
174
+ */
175
+ listener: <O>(def: {
176
+ /**
177
+ * Stable id, local to its module: in a `notifications` module, `id: "send"` is `notifications.send`. Jobs store it,
178
+ * so set it before you rename the export and queued jobs keep finding this code. Defaults to the export name.
179
+ */
180
+ id?: string;
181
+ /** The event it reacts to, as a thunk so modules can import each other's barrels without cycles. */
182
+ event: () => EventDef<unknown, O>;
183
+ /**
184
+ * Tries in total, the first included, like Laravel's `$tries`. Default 1: a retry repeats side effects, so opt in.
185
+ * Once they're used, the job is `failed` (kept by `databaseQueue`, `outbox` and pg-boss, retried with `registry.jobs.retry(id)`).
186
+ */
187
+ attempts?: number;
188
+ /** Seconds after the event before the first try. Needs an adapter that holds jobs: `inProcess()` is refused. */
189
+ delay?: number;
190
+ /**
191
+ * Whether this event gets a job for this listener, like Laravel's `shouldQueue($event)`: false, and nothing is
192
+ * stored, run or counted. From the payload the handler gets (parsed), at commit, so sync and from the event only:
193
+ * a condition on the database belongs in the handler, since it can change before the job runs. A throw fails the
194
+ * mutation, as a bad payload does.
195
+ */
196
+ when?: (payload: O) => boolean;
197
+ meta?: ListenerMetaOf<C>;
198
+ handler: (ctx: ListenerCtx<C, O>, payload: O) => Promise<unknown>;
199
+ }): Listener<O, C> => {
200
+ const { id, event, attempts, delay, when, meta, handler } = def;
201
+ checkAttempts("listener", attempts);
202
+ if (delay !== undefined && !(Number.isFinite(delay) && delay >= 0))
203
+ throw new Error(`[logic-sdk] listener delay must be seconds, 0 or more (got ${delay}).`);
204
+ // meta is checked against ListenerMetaOf<C> above and stored loose, like Fn.meta, for wrap and adapters
205
+ return Object.freeze({ [BRAND]: "listener" as const, kind: "listener" as const, id, event, attempts, delay, when, meta: meta as Listener["meta"], handler });
206
+ },
422
207
  };
423
208
  }
424
209
 
210
+ /** `cron({...})`: `input` is required exactly when the function needs one. */
211
+ type CronDef<S, F extends Fn> = {
212
+ /** Stable id, local to its module, like every definer's. Defaults to the export name. */
213
+ id?: string;
214
+ /** Five fields: minute hour day-of-month month day-of-week. `"*\/15 * * * *"`, `"0 9 * * 1"`. */
215
+ schedule: string;
216
+ /** IANA name, like `"Europe/Madrid"`. Default UTC. Matched on the wall clock, like Laravel: mind DST at 1 to 3 am. */
217
+ timezone?: string;
218
+ /**
219
+ * Any query, mutation or action, behind a function: `run: () => reports.sendWeekly`. It runs with its policy, validation
220
+ * and tracing. Read when the registry is built, like a listener's `event`, so no definer reads an import while files load.
221
+ */
222
+ run: () => F;
223
+ /** Who it runs as: a cron has no caller. */
224
+ scope: S;
225
+ /** Tries in total, like a listener's. Default 1. */
226
+ attempts?: number;
227
+ } & (undefined extends FnIn<F> ? { input?: FnIn<F> } : { input: FnIn<F> });
228
+
229
+ /** How deep `ctx.run` calls may nest. Past it, a function is running itself without end. */
230
+ const MAX_RUN_DEPTH = 64;
231
+
232
+ function checkAttempts(what: string, attempts: number | undefined) {
233
+ if (attempts !== undefined && !(Number.isInteger(attempts) && attempts >= 1))
234
+ throw new Error(`[logic-sdk] ${what} attempts must be a whole number of tries, 1 or more (got ${attempts}).`);
235
+ }
236
+
425
237
  /* ────────────────────────────────────────────────────────────────────────────
426
238
  * createRegistry
427
239
  * ──────────────────────────────────────────────────────────────────────────── */
428
240
 
429
- const INTERNAL: unique symbol = Symbol.for("logic-sdk.internal");
430
-
431
241
  interface TxState {
432
242
  db: unknown;
433
243
  doomed: boolean;
434
244
  reason: unknown;
435
- outbox: Envelope[];
245
+ events: Envelope[];
246
+ /** Each event's payload as its schema parsed it, for listeners' `when`: the value their handler gets. */
247
+ parsed: Map<Envelope, unknown>;
248
+ /** What `ctx.schedule` asked for, enqueued with the events at commit. */
249
+ calls: CallJob[];
436
250
  pending: Promise<void>[];
437
251
  }
438
252
  interface Frame {
439
253
  scope: object;
440
- depth: number;
254
+ /** The calls that led here, outermost first. How many there are is the next call's depth. */
255
+ trail: readonly string[];
441
256
  /** Inherited, for actions to pass on as ctx.signal. */
442
257
  signal?: AbortSignal;
443
258
  /** Passed to this very call: checked before it starts. */
444
259
  abortOn?: AbortSignal;
445
- eventDepth?: number;
260
+ /** Hops in the chain of events and calls due now that led here: 0 for a call from outside. */
261
+ eventDepth: number;
262
+ /** Inside a job: where the jobs it queues wait until it's settled. */
263
+ queued?: Job[];
446
264
  tx?: TxState;
447
265
  }
448
266
 
449
- export interface Overrides {
450
- database?: DatabaseAdapter<unknown, unknown>;
451
- services?: object;
452
- /** Merged over the registry's config, section by section. */
453
- config?: object;
454
- events?: Dispatcher;
455
- now?: () => Date;
456
- stubs?: Map<Fn, (ctx: never, input: never) => Promise<unknown>>;
457
- record?: (envelope: Envelope) => void;
458
- }
459
-
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
- }
489
-
490
267
  /** Create the registry once at startup. Prefer the `createRegistry` returned by `init()`: it's typed with your config. */
491
268
  export function createRegistry<S extends object = object, const Mods extends Record<string, object> = Record<string, object>>(
492
269
  options: RegistryOptions<Mods>,
@@ -505,67 +282,111 @@ function mergeConfig(base: unknown, patch: unknown): unknown {
505
282
  return Object.fromEntries([...keys].map((k) => [k, mergeConfig(base[k], patch[k])])); // fromEntries: `__proto__` stays a key
506
283
  }
507
284
 
285
+ /** A frozen copy of plain data, so settings can't change under everyone else or hide behavior (a client, a class). */
286
+ function freezeConfig(value: unknown): unknown {
287
+ assertPlain(value, "config", "config holds plain data: pass a Date as an ISO string, and put clients in services");
288
+ const freeze = (v: unknown): unknown => {
289
+ if (v && typeof v === "object") {
290
+ for (const item of Object.values(v)) freeze(item);
291
+ Object.freeze(v);
292
+ }
293
+ return v;
294
+ };
295
+ return freeze(structuredClone(value));
296
+ }
297
+
508
298
  /**
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.
299
+ * Plain data, what survives JSON: plain objects, arrays, strings, finite numbers, booleans, null (undefined is dropped).
300
+ * Anything else (a Date, a Map, a class instance, a function, a cycle) is rejected with its path.
511
301
  */
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
- );
302
+ function assertPlain(value: unknown, what: string, hint: string): void {
303
+ const seen = new Set<object>();
304
+ const check = (v: unknown, path: string): void => {
305
+ const fail = (found: string): never => {
306
+ throw new Error(`[logic-sdk] ${what} isn't plain data${path ? ` at ${path}` : ""}: ${found}. ${hint}.`);
307
+ };
308
+ if (v === null || v === undefined || typeof v === "string" || typeof v === "boolean") return;
309
+ if (typeof v === "number") {
310
+ if (!Number.isFinite(v)) fail(String(v));
311
+ return;
312
+ }
313
+ if (typeof v !== "object") return fail(`a ${typeof v}`);
314
+ if (seen.has(v)) fail("a circular reference");
315
+ seen.add(v);
316
+ if (Array.isArray(v)) v.forEach((item, i) => check(item, `${path}[${i}]`));
317
+ else {
318
+ if (!isPlain(v)) fail(`a ${v.constructor?.name ?? "class instance"}`);
319
+ for (const [k, item] of Object.entries(v)) check(item, path ? `${path}.${k}` : k);
320
+ }
321
+ seen.delete(v);
322
+ };
323
+ check(value, "");
522
324
  }
523
325
 
524
- const describeIssues = (issues: readonly StandardSchemaV1.Issue[]) =>
525
- issues.map((i) => ({ message: i.message, path: i.path?.map((p) => (typeof p === "object" ? p.key : p)) }));
526
-
527
- const isBranded = (v: unknown): v is Fn | EventDef | Listener => !!v && typeof v === "object" && BRAND in v;
326
+ const isBranded = (v: unknown): v is Fn | EventDef | Listener | Cron => !!v && typeof v === "object" && BRAND in v;
528
327
 
529
328
  /**
530
- * What `createRegistry` finds in your modules, without a database or services: every function, event and
531
- * listener with its id. For tools (the CLI, docs generators) that inspect an app without running it.
329
+ * What `createRegistry` finds in your modules, without a database or services: every function, event, listener and
330
+ * cron with its id. For tools (the CLI, docs generators) that inspect an app without running it.
532
331
  */
533
332
  export function describeModules(modules: Record<string, object>) {
534
333
  const ids = new Map<object, string>();
535
334
  const functions: RegisteredFn[] = [];
536
335
  const events: RegisteredEvent[] = [];
537
336
  const listeners: RegisteredListener[] = [];
337
+ const crons: RegisteredCron[] = [];
338
+
339
+ const taken = new Map<string, string>();
538
340
 
539
341
  for (const [module, ns] of Object.entries(modules)) {
540
342
  for (const [name, value] of Object.entries(ns)) {
541
343
  if (!isBranded(value) || ids.has(value)) continue;
542
- const id = `${module}.${name}`;
344
+ const local = value.id ?? name;
345
+ if (value.id !== undefined && (typeof value.id !== "string" || !/^[A-Za-z0-9_-]+$/.test(value.id)))
346
+ throw new Error(`[logic-sdk] ${module}.${name} has id ${JSON.stringify(value.id)}. Give the local name ("send"): the module key is added, so it's ${module}.<id>.`);
347
+ const id = `${module}.${local}`;
348
+ const other = taken.get(id);
349
+ if (other) throw new Error(`[logic-sdk] ${module}.${other} and ${module}.${name} both have the id ${id}. Ids must be unique: jobs find their code by it.`);
350
+ taken.set(id, name);
543
351
  ids.set(value, id);
544
352
  if (value.kind === "event") events.push({ id, module, name, event: value });
545
353
  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 });
354
+ else if (value.kind === "cron") crons.push({ id, module, name, cron: value, run: value.run() });
355
+ else functions.push({ id, module, name, kind: value.kind, fn: value });
547
356
  }
548
357
  }
549
- return { ids, functions, events, listeners };
358
+ return { ids, functions, events, listeners, crons };
550
359
  }
551
360
 
552
361
  function build<S extends object, Mods extends Record<string, object>, Cf = unknown>(
553
362
  options: RegistryOptions<Mods>,
554
363
  o: Overrides,
555
364
  ): Registry<S, Mods, Cf> {
556
- const { ids, functions, events, listeners } = describeModules(options.modules);
365
+ const { ids, functions, events, listeners, crons } = describeModules(options.modules);
557
366
 
558
367
  const database = o.database ?? options.database;
559
368
  const services = o.services ?? options.services ?? {};
560
369
  const config = freezeConfig(mergeConfig(options.config ?? {}, o.config)) as Frozen<Cf>;
561
- const dispatcher = o.events ?? options.events ?? inProcess();
370
+ const jobsAdapter = o.adapter ?? options.jobs?.adapter ?? inProcess();
371
+ const jobScope = options.jobs?.scope;
372
+ if (jobScope?.store && !jobScope.load) throw new Error("[logic-sdk] jobs.scope has store but no load. Jobs run as a scope, so rebuild it from what store saved.");
373
+ // a job any adapter but inProcess() keeps runs as a scope saved earlier: rebuild it, or its roles are the ones from
374
+ // back then (AshOban's actor_persister). The app's adapter, so a test registry agrees with the app it wraps.
375
+ const appAdapter = options.jobs?.adapter;
376
+ if (appAdapter && !runsNow(appAdapter) && !jobScope?.load)
377
+ throw new Error(
378
+ "[logic-sdk] Your jobs adapter keeps jobs to run later, so set jobs.scope.load: it rebuilds the scope when a job runs, with today's " +
379
+ "roles (null discards the job). Add `store` to save only ids. To keep the scope as it was, `load: (saved) => saved`.",
380
+ );
562
381
  const now = o.now ?? options.now ?? (() => new Date());
563
382
  const wrap = options.wrap ?? ((_c, next) => next());
564
- const maxEventDepth = options.maxEventDepth ?? 8;
565
- const attempts = Math.max(1, options.retry?.attempts ?? 3);
383
+ const maxEventDepth = options.jobs?.maxEventDepth ?? 8;
384
+ checkAttempts("database transaction", options.database?.transactionAttempts);
385
+ const transactionAttempts = options.database?.transactionAttempts ?? 3; // the app's, so a test's nested adapter keeps it
386
+ const waitUntil = "waitUntil" in o ? o.waitUntil : options.waitUntil; // tests turn it off: listeners finish inside the test
566
387
  const reportRaw =
567
- options.onError ?? ((e, info) => console.error(`[logic-sdk] ${info.listener} failed`, e));
568
- const report = (e: unknown, info: { listener: string; envelope: Envelope | undefined }) => {
388
+ o.onError ?? options.onError ?? ((e, info) => console.error(`[logic-sdk] ${info.source} failed`, e));
389
+ const report = (e: unknown, info: FailureInfo) => {
569
390
  try {
570
391
  reportRaw(e, info);
571
392
  } catch (inner) {
@@ -573,14 +394,15 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
573
394
  }
574
395
  };
575
396
 
576
- if (functions.some((f) => f.kind === "mutation") && database?.transactions !== "interactive")
397
+ if (!database && functions.some((f) => f.kind === "mutation"))
577
398
  throw new Error(
578
- "[logic-sdk] Mutations need a database adapter with interactive transactions (e.g. drizzleAdapter(db)). " +
579
- "Drivers without them (Cloudflare D1, HTTP drivers) are not supported for mutations.",
399
+ "[logic-sdk] Mutations need a database: createRegistry({ database: drizzleAdapter(db) }). It needs interactive " +
400
+ "transactions, so Cloudflare D1 and HTTP drivers can't run mutations.",
580
401
  );
581
402
  for (const l of listeners)
582
- if (!l.event || !ids.has(l.event))
403
+ if (!ids.has(l.event))
583
404
  throw new Error(`[logic-sdk] Listener ${l.id} listens to an event that isn't registered in any module.`);
405
+ jobsAdapter.check?.({ listeners, database });
584
406
 
585
407
  const idOf = (x: object) => {
586
408
  const id = ids.get(x);
@@ -605,53 +427,23 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
605
427
  if (r.issues) throw new Error(`[logic-sdk] ${what} is invalid: ${JSON.stringify(describeIssues(r.issues))}`);
606
428
  return r.value;
607
429
  }
608
-
609
- // ── listeners ────────────────────────────────────────────────────────────
610
- const byEvent = new Map<string, RegisteredListener[]>();
611
- for (const l of listeners) {
612
- const name = idOf(l.event);
613
- byEvent.set(name, [...(byEvent.get(name) ?? []), l]);
430
+ /** What our own code passed a mutation's ctx, checked by the time it commits: a bad value fails the commit. */
431
+ function checkAtCommit(tx: TxState, schema: Schema, value: unknown, what: string, keep?: (parsed: unknown) => void) {
432
+ const check = parseOwn(schema, value, what).then((parsed) => keep?.(parsed));
433
+ check.catch(() => {}); // surfaced at commit; never an unhandled rejection
434
+ tx.pending.push(check);
614
435
  }
615
- const eventByName = new Map(events.map((e) => [e.id, e.event]));
616
-
617
- /** Run every listener for one envelope. Returns the failures instead of throwing. */
618
- async function runListeners(envelope: Envelope, eventDepth: number) {
619
- const failures: { listener: string; error: unknown }[] = [];
620
- const event = eventByName.get(envelope.name);
621
- for (const l of byEvent.get(envelope.name) ?? []) {
622
- const frame: Frame = { scope: envelope.scope, depth: 0, eventDepth };
623
- try {
624
- await wrap({ id: l.id, kind: "listener", meta: undefined, input: envelope.payload, scope: envelope.scope, depth: 0 }, async () => {
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
627
- });
628
- } catch (error) {
629
- failures.push({ listener: l.id, error });
630
- }
631
- }
632
- return failures;
633
- }
634
-
635
- /** In-process delivery: failures go to onError. */
636
- const deliverOne = (eventDepth: number) => async (envelope: Envelope) => {
637
- for (const f of await runListeners(envelope, eventDepth)) report(f.error, { listener: f.listener, envelope });
638
- };
639
436
 
640
- /** Public: for durable dispatchers. Throws an AggregateError if any listener failed, so the consumer can retry. */
641
- async function dispatch(envelope: Envelope) {
642
- const failures = await runListeners(envelope, 1);
643
- if (failures.length)
644
- throw new AggregateError(
645
- failures.map((f) => f.error),
646
- `[logic-sdk] ${failures.length} listener(s) failed for ${envelope.name}: ${failures.map((f) => f.listener).join(", ")}`,
647
- );
437
+ for (const c of crons) {
438
+ if (!ids.has(c.run))
439
+ throw new Error(`[logic-sdk] Cron ${c.id} runs a function that isn't registered. Export it from its module's index.ts.`);
440
+ assertPlain(c.cron.input, `${c.id} input`, "Cron runs travel through queues as JSON: send an ISO string and let the schema turn it into a Date");
648
441
  }
649
442
 
650
443
  // ── ctx ──────────────────────────────────────────────────────────────────
651
- /** The frame a call runs in: one level deeper, with this call's scope patch and signal. */
444
+ /** The frame for a call from here: its scope patch and signal. `invoke` adds the call to the trail. */
652
445
  const enter = (frame: Frame, options: RunOptions | undefined): Frame => ({
653
446
  ...frame,
654
- depth: frame.depth + 1,
655
447
  scope: options?.scope ? { ...frame.scope, ...options.scope } : frame.scope,
656
448
  signal: options?.signal ?? frame.signal,
657
449
  abortOn: options?.signal,
@@ -669,55 +461,116 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
669
461
  ...baseCtx(frame, id, ["query"]),
670
462
  db: frame.tx ? frame.tx.db : database?.db,
671
463
  });
672
- function mutationCtx(frame: Frame, id: string): MutationCtx<any> {
673
- const tx = frame.tx!;
464
+ function mutationCtx(frame: Frame, tx: TxState, id: string): MutationCtx<any> {
674
465
  return {
675
466
  ...baseCtx(frame, id, ["query", "mutation"]),
676
467
  db: tx.db,
677
468
  emit: (event, payload) => {
678
- const name = idOf(event);
679
- payload = structuredClone(payload); // what was emitted is what gets delivered, even if the caller mutates it after
680
469
  // reserve the slot now so events keep emit order, even with async schemas
681
- const envelope: Envelope = {
682
- id: crypto.randomUUID(),
683
- name,
684
- payload,
685
- scope: structuredClone(frame.scope),
686
- occurredAt: now().toISOString(),
470
+ const envelope = envelopeOf(event, payload, frame.scope, frame.eventDepth + 1);
471
+ tx.events.push(envelope);
472
+ checkAtCommit(tx, event.payload, envelope.payload, `${envelope.name} payload`, (parsed) => tx.parsed.set(envelope, parsed));
473
+ },
474
+ schedule: (fn, input, { at, delay, attempts = 1, replace }) => {
475
+ const fnId = idOf(fn);
476
+ const seconds = at ? (at.getTime() - now().getTime()) / 1000 : (delay ?? NaN);
477
+ if (!Number.isFinite(seconds) || (!at && seconds < 0))
478
+ throw new Error(`[logic-sdk] ctx.schedule(${fnId}) needs an \`at\` date or a \`delay\` in seconds, 0 or more.`);
479
+ checkAttempts(`ctx.schedule(${fnId})`, attempts);
480
+ if (replace !== undefined) {
481
+ if (!replace) throw new Error(`[logic-sdk] ctx.schedule(${fnId}) replace must be a non-empty key.`);
482
+ if (!jobsAdapter.replaces)
483
+ throw new Error(`[logic-sdk] ctx.schedule(${fnId}) replaces a waiting call, but your jobs adapter can't replace one it already has. Use databaseQueue(database), or outbox(database, queue) in front of your queue.`);
484
+ }
485
+ // due now (no delay, or an `at` already past): runs after commit like a listener, no holding needed
486
+ const waits = seconds > 0;
487
+ if (waits) checkHold(`ctx.schedule(${fnId})`, seconds);
488
+ assertPlain(input, `${fnId} input`, "Scheduled calls wait as JSON: send an ISO string and let the schema turn it into a Date");
489
+ const job: CallJob = {
490
+ kind: "call",
491
+ id: `${fnId}@${crypto.randomUUID()}`,
492
+ fn: fnId,
493
+ input: structuredClone(input),
494
+ scope: storedScope(frame.scope, `the scope scheduling ${fnId}`),
495
+ attempts,
496
+ depth: waits ? 0 : frame.eventDepth + 1, // due now, it's the next hop of this chain; a real wait starts a new one
687
497
  };
688
- tx.outbox.push(envelope);
689
- const check = parseOwn(event.payload, payload, `${name} payload`).then(() => {});
690
- check.catch(() => {}); // surfaced at commit; never an unhandled rejection
691
- tx.pending.push(check);
498
+ if (waits) job.runAt = new Date(now().getTime() + seconds * 1000).toISOString();
499
+ if (replace !== undefined) {
500
+ job.replace = replace;
501
+ // scheduled twice in this transaction: the later one wins here too (the dropped one's input is still checked:
502
+ // a bad input is a bug wherever it is)
503
+ const earlier = tx.calls.findIndex((c) => replaceKeyOf(c) === replaceKeyOf(job));
504
+ if (earlier >= 0) tx.calls.splice(earlier, 1);
505
+ }
506
+ tx.calls.push(job);
507
+ // our own code passed it: a bad input is a bug, surfaced at commit like an event's payload
508
+ if (fn.input) checkAtCommit(tx, fn.input, job.input, `${fnId} input`);
509
+ return job.id;
692
510
  },
693
511
  };
694
512
  }
513
+ /** An emitted event as jobs carry it: plain JSON, and copied, so what was emitted is what gets delivered. */
514
+ function envelopeOf(event: EventDef, payload: unknown, scope: object, depth: number): Envelope {
515
+ const name = idOf(event);
516
+ // a queue carries JSON: a Date or a class instance would work in-process and break only in production
517
+ assertPlain(payload, `${name} payload`, "Events travel through queues as JSON: send an ISO string and let the schema turn it into a Date");
518
+ return { id: crypto.randomUUID(), name, payload: structuredClone(payload), scope: storedScope(scope, `the scope emitting ${name}`), occurredAt: now().toISOString(), depth };
519
+ }
520
+ /** What a job keeps of the scope it runs as: `jobs.scope.store`'s pick, as a JSON copy. */
521
+ function storedScope(scope: object, what: string): object {
522
+ const stored = jobScope?.store ? jobScope.store(scope) : scope;
523
+ assertPlain(stored, what, "Jobs carry the scope through queues as JSON: keep it to ids (jobs.scope.store picks what's saved)");
524
+ return structuredClone(stored);
525
+ }
526
+
695
527
  const actionCtx = (frame: Frame, id: string): ActionCtx<any> => ({
696
528
  ...baseCtx(frame, id, ["query", "mutation", "action"]),
697
529
  signal: frame.signal,
698
530
  services,
699
531
  });
700
532
 
533
+ const { toJobs, deliver, jobs, due, checkHold } = makeJobs({
534
+ listeners,
535
+ crons,
536
+ functions,
537
+ idOf,
538
+ jobsAdapter,
539
+ database,
540
+ jobScope,
541
+ maxEventDepth,
542
+ now,
543
+ wrap,
544
+ report,
545
+ runAs: (fn, input, scope, eventDepth, queued) => invoke(fn, input, enter({ scope, trail: [], eventDepth, queued }, undefined), ["query", "mutation", "action"]),
546
+ listenerCtx: (scope, eventDepth, id, queued) => actionCtx({ scope, trail: [id], eventDepth, queued }, id),
547
+ });
548
+
701
549
  // ── invoke ───────────────────────────────────────────────────────────────
702
- async function invoke(fn: Fn, rawInput: unknown, frame: Frame, allowed: Kind[]): Promise<any> {
550
+ async function invoke(fn: Fn, rawInput: unknown, outer: Frame, allowed: Kind[]): Promise<any> {
703
551
  const id = idOf(fn);
704
552
  if (!allowed.includes(fn.kind))
705
553
  throw new Error(`[logic-sdk] ${id} is a ${fn.kind}; it can't be run from here (allowed: ${allowed.join(", ")}).`);
554
+ const depth = outer.trail.length;
555
+ // a function that runs itself, through other modules or not, never returns: stop it with the path, not run out of memory
556
+ if (depth > MAX_RUN_DEPTH)
557
+ throw new Error(
558
+ `[logic-sdk] ctx.run nested past ${MAX_RUN_DEPTH} calls: … → ${[...outer.trail.slice(-6), id].join(" → ")}. ` +
559
+ "Recurse in a plain helper that takes ctx, or make each step separate work (an event, or ctx.schedule).",
560
+ );
561
+ const frame: Frame = { ...outer, trail: [...outer.trail, id] };
706
562
 
707
- const call: Call = { id, kind: fn.kind, meta: fn.meta, input: rawInput, scope: frame.scope, depth: frame.depth };
563
+ const call: Call = { id, kind: fn.kind, meta: fn.meta, input: rawInput, scope: frame.scope, depth };
708
564
 
709
565
  /** Authorize, then validate, before any transaction opens: denied or bad calls never touch the database. */
710
566
  const prepare = async () => {
711
567
  frame.abortOn?.throwIfAborted();
712
568
  if (fn.authorize) {
713
569
  // 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)
716
- throw new Error(`[logic-sdk] The policy on ${id} returned a Promise. Policies are sync and read only the scope.`);
717
- if (verdict !== true) throw new DomainError("forbidden", `${id}.forbidden`);
570
+ if (fn.authorize(frame.scope as never) !== true) throw new DomainError("forbidden", `${id}.forbidden`);
718
571
  }
719
572
  // 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;
573
+ return fn.input ? parseInput(fn.input, rawInput, id, depth > 0) : undefined;
721
574
  };
722
575
  const execute = async (input: unknown, ctx: unknown) => {
723
576
  // SAFETY: the handler's types were erased when it was registered. `ctx` was built for its kind,
@@ -735,7 +588,7 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
735
588
  if (frame.tx) {
736
589
  const tx = frame.tx;
737
590
  try {
738
- return await execute(await prepare(), mutationCtx(frame, id));
591
+ return await execute(await prepare(), mutationCtx(frame, tx, id));
739
592
  } catch (e) {
740
593
  if (!tx.doomed) {
741
594
  tx.doomed = true;
@@ -748,85 +601,72 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
748
601
  // top-level mutation: open the transaction, commit, then deliver events.
749
602
  // A lost race (deadlock, serialization failure) re-runs it in a fresh transaction.
750
603
  const input = await prepare();
751
- let committed: { out: unknown; outbox: Envelope[] };
604
+ let committed: { out: unknown; events: Envelope[]; jobs: Job[] };
752
605
  for (let attempt = 1; ; attempt++) {
753
- let state: TxState | undefined;
754
606
  try {
607
+ // SAFETY: createRegistry refuses mutations without a database that has interactive transactions
755
608
  committed = await database!.transaction(async (txDb) => {
756
609
  // fresh per attempt, so a retry never reuses events from a failed attempt
757
- const tx: TxState = (state = { db: txDb, doomed: false, reason: undefined, outbox: [], pending: [] });
758
- const out = await execute(input, mutationCtx({ ...frame, tx }, id));
610
+ const tx: TxState = { db: txDb, doomed: false, reason: undefined, events: [], parsed: new Map(), calls: [], pending: [] };
611
+ const out = await execute(input, mutationCtx({ ...frame, tx }, tx, id));
759
612
  await Promise.all(tx.pending);
760
613
  if (tx.doomed) throw tx.reason;
761
- await dispatcher.enqueue?.(txDb, tx.outbox);
762
- return { out, outbox: tx.outbox };
614
+ const jobs = toJobs(tx.events, tx.calls, tx.parsed);
615
+ if (jobs.length) await jobsAdapter.enqueue?.(txDb, jobs);
616
+ return { out, events: tx.events, jobs };
763
617
  });
764
618
  break;
765
619
  } catch (e) {
766
- if (attempt < attempts && database!.retryable?.(e)) {
620
+ if (attempt < transactionAttempts && database!.retryable?.(e)) { // SAFETY: as above
767
621
  // a random pause, so transactions that just deadlocked don't retry in lockstep and collide again
768
622
  await new Promise((r) => setTimeout(r, Math.random() * 20 * attempt));
769
623
  continue;
770
624
  }
771
625
  throw e;
772
- } finally {
773
- if (state) await Promise.allSettled(state.pending);
774
626
  }
775
627
  }
776
628
 
777
629
  // committed. Nothing below may fail the caller.
778
- if (committed.outbox.length) await afterCommit(committed.outbox, frame);
630
+ await afterCommit(committed.events, committed.jobs, frame.queued);
779
631
  return committed.out;
780
632
  });
781
633
  }
782
634
 
783
- async function afterCommit(outbox: Envelope[], frame: Frame) {
635
+ async function afterCommit(emitted: Envelope[], jobs: Job[], queued: Job[] | undefined) {
784
636
  try {
785
- for (const e of outbox) o.record?.(e);
786
- const eventDepth = (frame.eventDepth ?? 0) + 1;
787
- if (eventDepth > maxEventDepth) {
788
- report(new Error(`[logic-sdk] event chain deeper than ${maxEventDepth}: stopped delivering (listener loop?)`), {
789
- listener: "(dispatcher)",
790
- envelope: outbox[0],
791
- });
792
- return;
793
- }
794
- const delivery = (async () => dispatcher.deliver(outbox, deliverOne(eventDepth)))().catch((e) =>
795
- report(e, { listener: "(dispatcher)", envelope: outbox[0] }),
796
- );
797
- if (options.waitUntil) {
637
+ for (const e of emitted) o.record?.(e);
638
+ if (!jobs.length) return;
639
+ if (queued) return void queued.push(...jobs); // queued by a job: delivered once that job is settled
640
+ const delivery = deliver(jobs);
641
+ if (waitUntil) {
798
642
  try {
799
- options.waitUntil(delivery);
643
+ waitUntil(delivery);
800
644
  return;
801
645
  } catch (e) {
802
- report(e, { listener: "(waitUntil)", envelope: outbox[0] });
646
+ report(e, { source: "(waitUntil)" });
803
647
  }
804
648
  }
805
649
  await delivery;
806
650
  } catch (e) {
807
- report(e, { listener: "(after commit)", envelope: outbox[0] });
651
+ report(e, { source: "(after commit)" });
808
652
  }
809
653
  }
810
654
 
811
655
  return {
812
- modules: options.modules,
813
656
  as: (scope) => ({
814
657
  scope,
815
658
  run: (fn: Fn, input?: unknown, options?: RunOptions) =>
816
- invoke(fn, input, enter({ scope, depth: -1 }, options), ["query", "mutation", "action"]), // depth 0
659
+ invoke(fn, input, enter({ scope, trail: [], eventDepth: 0 }, options), ["query", "mutation", "action"]),
817
660
  }),
818
- functions,
819
- events,
820
- listeners,
661
+ definitions: { functions, events, listeners, crons },
821
662
  idOf,
822
- dispatch,
663
+ jobs,
823
664
  [INTERNAL]: {
824
665
  options,
825
666
  config,
826
- derive: (more: Overrides) => build<S, Mods, Cf>(options, { ...o, ...more, config: mergeConfig(o.config, more.config) as object | undefined }),
667
+ derive: (more: Overrides) => build<S, Mods, Cf>(options, { ...o, ...more, config: mergeConfig(o.config, more.config) }),
668
+ envelope: (event, payload, scope) => envelopeOf(event, payload, scope, 1),
669
+ due,
827
670
  },
828
671
  };
829
672
  }
830
-
831
- /** @internal */
832
- export const internal = <S extends object, Mods extends Record<string, object>, Cf>(registry: Registry<S, Mods, Cf>) => registry[INTERNAL];