logic-sdk 0.4.0 → 0.5.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 (57) hide show
  1. package/README.md +39 -13
  2. package/dist/ai.d.ts +16 -26
  3. package/dist/ai.js +8 -21
  4. package/dist/cloudflare.d.ts +55 -0
  5. package/dist/cloudflare.js +85 -0
  6. package/dist/drizzle/pg.d.ts +237 -0
  7. package/dist/drizzle/pg.js +67 -0
  8. package/dist/drizzle/sqlite.d.ts +242 -0
  9. package/dist/drizzle/sqlite.js +194 -0
  10. package/dist/errors.d.ts +33 -0
  11. package/dist/errors.js +45 -0
  12. package/dist/fetch.d.ts +15 -18
  13. package/dist/fetch.js +18 -55
  14. package/dist/index.d.ts +75 -379
  15. package/dist/index.js +228 -181
  16. package/dist/jobs.d.ts +44 -0
  17. package/dist/jobs.js +252 -0
  18. package/dist/node.d.ts +26 -0
  19. package/dist/node.js +76 -0
  20. package/dist/orpc.d.ts +10 -17
  21. package/dist/orpc.js +19 -28
  22. package/dist/pg-boss.d.ts +55 -0
  23. package/dist/pg-boss.js +211 -0
  24. package/dist/postgres.d.ts +28 -0
  25. package/dist/postgres.js +82 -0
  26. package/dist/schedule.d.ts +23 -0
  27. package/dist/schedule.js +109 -0
  28. package/dist/sqlite.d.ts +9 -0
  29. package/dist/sqlite.js +65 -0
  30. package/dist/stored-jobs.d.ts +64 -0
  31. package/dist/stored-jobs.js +188 -0
  32. package/dist/testing.d.ts +50 -14
  33. package/dist/testing.js +198 -46
  34. package/dist/types.d.ts +653 -0
  35. package/dist/types.js +6 -0
  36. package/package.json +45 -7
  37. package/skills/logic-sdk/SKILL.md +114 -0
  38. package/src/ai.ts +23 -46
  39. package/src/cloudflare.ts +107 -0
  40. package/src/drizzle/pg.ts +111 -0
  41. package/src/drizzle/sqlite.ts +236 -0
  42. package/src/errors.ts +59 -0
  43. package/src/fetch.ts +17 -65
  44. package/src/index.ts +384 -558
  45. package/src/jobs.ts +296 -0
  46. package/src/node.ts +99 -0
  47. package/src/orpc.ts +24 -42
  48. package/src/pg-boss.ts +242 -0
  49. package/src/postgres.ts +90 -0
  50. package/src/schedule.ts +129 -0
  51. package/src/sqlite.ts +74 -0
  52. package/src/stored-jobs.ts +260 -0
  53. package/src/testing.ts +252 -55
  54. package/src/types.ts +683 -0
  55. package/dist/drizzle.d.ts +0 -18
  56. package/dist/drizzle.js +0 -23
  57. 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,35 +147,100 @@ 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
+ /** Any query, mutation or action: it runs with its policy, validation and tracing. */
219
+ run: F;
220
+ /** Who it runs as: a cron has no caller. */
221
+ scope: S;
222
+ /** Tries in total, like a listener's. Default 1. */
223
+ attempts?: number;
224
+ } & (undefined extends FnIn<F> ? { input?: FnIn<F> } : { input: FnIn<F> });
225
+
226
+ function checkAttempts(what: string, attempts: number | undefined) {
227
+ if (attempts !== undefined && !(Number.isInteger(attempts) && attempts >= 1))
228
+ throw new Error(`[logic-sdk] ${what} attempts must be a whole number of tries, 1 or more (got ${attempts}).`);
229
+ }
230
+
425
231
  /* ────────────────────────────────────────────────────────────────────────────
426
232
  * createRegistry
427
233
  * ──────────────────────────────────────────────────────────────────────────── */
428
234
 
429
- const INTERNAL: unique symbol = Symbol.for("logic-sdk.internal");
430
-
431
235
  interface TxState {
432
236
  db: unknown;
433
237
  doomed: boolean;
434
238
  reason: unknown;
435
- outbox: Envelope[];
239
+ events: Envelope[];
240
+ /** Each event's payload as its schema parsed it, for listeners' `when`: the value their handler gets. */
241
+ parsed: Map<Envelope, unknown>;
242
+ /** What `ctx.schedule` asked for, enqueued with the events at commit. */
243
+ calls: CallJob[];
436
244
  pending: Promise<void>[];
437
245
  }
438
246
  interface Frame {
@@ -442,51 +250,13 @@ interface Frame {
442
250
  signal?: AbortSignal;
443
251
  /** Passed to this very call: checked before it starts. */
444
252
  abortOn?: AbortSignal;
445
- eventDepth?: number;
253
+ /** Hops in the chain of events and calls due now that led here: 0 for a call from outside. */
254
+ eventDepth: number;
255
+ /** Inside a job: where the jobs it queues wait until it's settled. */
256
+ queued?: Job[];
446
257
  tx?: TxState;
447
258
  }
448
259
 
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
260
  /** Create the registry once at startup. Prefer the `createRegistry` returned by `init()`: it's typed with your config. */
491
261
  export function createRegistry<S extends object = object, const Mods extends Record<string, object> = Record<string, object>>(
492
262
  options: RegistryOptions<Mods>,
@@ -505,67 +275,111 @@ function mergeConfig(base: unknown, patch: unknown): unknown {
505
275
  return Object.fromEntries([...keys].map((k) => [k, mergeConfig(base[k], patch[k])])); // fromEntries: `__proto__` stays a key
506
276
  }
507
277
 
278
+ /** A frozen copy of plain data, so settings can't change under everyone else or hide behavior (a client, a class). */
279
+ function freezeConfig(value: unknown): unknown {
280
+ assertPlain(value, "config", "config holds plain data: pass a Date as an ISO string, and put clients in services");
281
+ const freeze = (v: unknown): unknown => {
282
+ if (v && typeof v === "object") {
283
+ for (const item of Object.values(v)) freeze(item);
284
+ Object.freeze(v);
285
+ }
286
+ return v;
287
+ };
288
+ return freeze(structuredClone(value));
289
+ }
290
+
508
291
  /**
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.
292
+ * Plain data, what survives JSON: plain objects, arrays, strings, finite numbers, booleans, null (undefined is dropped).
293
+ * Anything else (a Date, a Map, a class instance, a function, a cycle) is rejected with its path.
511
294
  */
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
- );
295
+ function assertPlain(value: unknown, what: string, hint: string): void {
296
+ const seen = new Set<object>();
297
+ const check = (v: unknown, path: string): void => {
298
+ const fail = (found: string): never => {
299
+ throw new Error(`[logic-sdk] ${what} isn't plain data${path ? ` at ${path}` : ""}: ${found}. ${hint}.`);
300
+ };
301
+ if (v === null || v === undefined || typeof v === "string" || typeof v === "boolean") return;
302
+ if (typeof v === "number") {
303
+ if (!Number.isFinite(v)) fail(String(v));
304
+ return;
305
+ }
306
+ if (typeof v !== "object") return fail(`a ${typeof v}`);
307
+ if (seen.has(v)) fail("a circular reference");
308
+ seen.add(v);
309
+ if (Array.isArray(v)) v.forEach((item, i) => check(item, `${path}[${i}]`));
310
+ else {
311
+ if (!isPlain(v)) fail(`a ${v.constructor?.name ?? "class instance"}`);
312
+ for (const [k, item] of Object.entries(v)) check(item, path ? `${path}.${k}` : k);
313
+ }
314
+ seen.delete(v);
315
+ };
316
+ check(value, "");
522
317
  }
523
318
 
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;
319
+ const isBranded = (v: unknown): v is Fn | EventDef | Listener | Cron => !!v && typeof v === "object" && BRAND in v;
528
320
 
529
321
  /**
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.
322
+ * What `createRegistry` finds in your modules, without a database or services: every function, event, listener and
323
+ * cron with its id. For tools (the CLI, docs generators) that inspect an app without running it.
532
324
  */
533
325
  export function describeModules(modules: Record<string, object>) {
534
326
  const ids = new Map<object, string>();
535
327
  const functions: RegisteredFn[] = [];
536
328
  const events: RegisteredEvent[] = [];
537
329
  const listeners: RegisteredListener[] = [];
330
+ const crons: RegisteredCron[] = [];
331
+
332
+ const taken = new Map<string, string>();
538
333
 
539
334
  for (const [module, ns] of Object.entries(modules)) {
540
335
  for (const [name, value] of Object.entries(ns)) {
541
336
  if (!isBranded(value) || ids.has(value)) continue;
542
- const id = `${module}.${name}`;
337
+ const local = value.id ?? name;
338
+ if (value.id !== undefined && (typeof value.id !== "string" || !/^[A-Za-z0-9_-]+$/.test(value.id)))
339
+ 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>.`);
340
+ const id = `${module}.${local}`;
341
+ const other = taken.get(id);
342
+ 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.`);
343
+ taken.set(id, name);
543
344
  ids.set(value, id);
544
345
  if (value.kind === "event") events.push({ id, module, name, event: value });
545
346
  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 });
347
+ else if (value.kind === "cron") crons.push({ id, module, name, cron: value });
348
+ else functions.push({ id, module, name, kind: value.kind, fn: value });
547
349
  }
548
350
  }
549
- return { ids, functions, events, listeners };
351
+ return { ids, functions, events, listeners, crons };
550
352
  }
551
353
 
552
354
  function build<S extends object, Mods extends Record<string, object>, Cf = unknown>(
553
355
  options: RegistryOptions<Mods>,
554
356
  o: Overrides,
555
357
  ): Registry<S, Mods, Cf> {
556
- const { ids, functions, events, listeners } = describeModules(options.modules);
358
+ const { ids, functions, events, listeners, crons } = describeModules(options.modules);
557
359
 
558
360
  const database = o.database ?? options.database;
559
361
  const services = o.services ?? options.services ?? {};
560
362
  const config = freezeConfig(mergeConfig(options.config ?? {}, o.config)) as Frozen<Cf>;
561
- const dispatcher = o.events ?? options.events ?? inProcess();
363
+ const jobsAdapter = o.adapter ?? options.jobs?.adapter ?? inProcess();
364
+ const jobScope = options.jobs?.scope;
365
+ 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.");
366
+ // a job any adapter but inProcess() keeps runs as a scope saved earlier: rebuild it, or its roles are the ones from
367
+ // back then (AshOban's actor_persister). The app's adapter, so a test registry agrees with the app it wraps.
368
+ const appAdapter = options.jobs?.adapter;
369
+ if (appAdapter && !runsNow(appAdapter) && !jobScope?.load)
370
+ throw new Error(
371
+ "[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 " +
372
+ "roles (null discards the job). Add `store` to save only ids. To keep the scope as it was, `load: (saved) => saved`.",
373
+ );
562
374
  const now = o.now ?? options.now ?? (() => new Date());
563
375
  const wrap = options.wrap ?? ((_c, next) => next());
564
- const maxEventDepth = options.maxEventDepth ?? 8;
565
- const attempts = Math.max(1, options.retry?.attempts ?? 3);
376
+ const maxEventDepth = options.jobs?.maxEventDepth ?? 8;
377
+ checkAttempts("database transaction", options.database?.transactionAttempts);
378
+ const transactionAttempts = options.database?.transactionAttempts ?? 3; // the app's, so a test's nested adapter keeps it
379
+ const waitUntil = "waitUntil" in o ? o.waitUntil : options.waitUntil; // tests turn it off: listeners finish inside the test
566
380
  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 }) => {
381
+ o.onError ?? options.onError ?? ((e, info) => console.error(`[logic-sdk] ${info.source} failed`, e));
382
+ const report = (e: unknown, info: FailureInfo) => {
569
383
  try {
570
384
  reportRaw(e, info);
571
385
  } catch (inner) {
@@ -573,14 +387,15 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
573
387
  }
574
388
  };
575
389
 
576
- if (functions.some((f) => f.kind === "mutation") && database?.transactions !== "interactive")
390
+ if (!database && functions.some((f) => f.kind === "mutation"))
577
391
  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.",
392
+ "[logic-sdk] Mutations need a database: createRegistry({ database: drizzleAdapter(db) }). It needs interactive " +
393
+ "transactions, so Cloudflare D1 and HTTP drivers can't run mutations.",
580
394
  );
581
395
  for (const l of listeners)
582
- if (!l.event || !ids.has(l.event))
396
+ if (!ids.has(l.event))
583
397
  throw new Error(`[logic-sdk] Listener ${l.id} listens to an event that isn't registered in any module.`);
398
+ jobsAdapter.check?.({ listeners, database });
584
399
 
585
400
  const idOf = (x: object) => {
586
401
  const id = ids.get(x);
@@ -605,46 +420,17 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
605
420
  if (r.issues) throw new Error(`[logic-sdk] ${what} is invalid: ${JSON.stringify(describeIssues(r.issues))}`);
606
421
  return r.value;
607
422
  }
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]);
423
+ /** What our own code passed a mutation's ctx, checked by the time it commits: a bad value fails the commit. */
424
+ function checkAtCommit(tx: TxState, schema: Schema, value: unknown, what: string, keep?: (parsed: unknown) => void) {
425
+ const check = parseOwn(schema, value, what).then((parsed) => keep?.(parsed));
426
+ check.catch(() => {}); // surfaced at commit; never an unhandled rejection
427
+ tx.pending.push(check);
614
428
  }
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
429
 
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
- );
430
+ for (const c of crons) {
431
+ if (!ids.has(c.cron.run))
432
+ throw new Error(`[logic-sdk] Cron ${c.id} runs a function that isn't registered. Export it from its module's index.ts.`);
433
+ 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
434
  }
649
435
 
650
436
  // ── ctx ──────────────────────────────────────────────────────────────────
@@ -669,35 +455,91 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
669
455
  ...baseCtx(frame, id, ["query"]),
670
456
  db: frame.tx ? frame.tx.db : database?.db,
671
457
  });
672
- function mutationCtx(frame: Frame, id: string): MutationCtx<any> {
673
- const tx = frame.tx!;
458
+ function mutationCtx(frame: Frame, tx: TxState, id: string): MutationCtx<any> {
674
459
  return {
675
460
  ...baseCtx(frame, id, ["query", "mutation"]),
676
461
  db: tx.db,
677
462
  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
463
  // 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(),
464
+ const envelope = envelopeOf(event, payload, frame.scope, frame.eventDepth + 1);
465
+ tx.events.push(envelope);
466
+ checkAtCommit(tx, event.payload, envelope.payload, `${envelope.name} payload`, (parsed) => tx.parsed.set(envelope, parsed));
467
+ },
468
+ schedule: (fn, input, { at, delay, attempts = 1, replace }) => {
469
+ const fnId = idOf(fn);
470
+ const seconds = at ? (at.getTime() - now().getTime()) / 1000 : (delay ?? NaN);
471
+ if (!Number.isFinite(seconds) || (!at && seconds < 0))
472
+ throw new Error(`[logic-sdk] ctx.schedule(${fnId}) needs an \`at\` date or a \`delay\` in seconds, 0 or more.`);
473
+ checkAttempts(`ctx.schedule(${fnId})`, attempts);
474
+ if (replace !== undefined) {
475
+ if (!replace) throw new Error(`[logic-sdk] ctx.schedule(${fnId}) replace must be a non-empty key.`);
476
+ if (!jobsAdapter.replaces)
477
+ 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.`);
478
+ }
479
+ // due now (no delay, or an `at` already past): runs after commit like a listener, no holding needed
480
+ const waits = seconds > 0;
481
+ if (waits) checkHold(`ctx.schedule(${fnId})`, seconds);
482
+ assertPlain(input, `${fnId} input`, "Scheduled calls wait as JSON: send an ISO string and let the schema turn it into a Date");
483
+ const job: CallJob = {
484
+ kind: "call",
485
+ id: `${fnId}@${crypto.randomUUID()}`,
486
+ fn: fnId,
487
+ input: structuredClone(input),
488
+ scope: storedScope(frame.scope, `the scope scheduling ${fnId}`),
489
+ attempts,
490
+ depth: waits ? 0 : frame.eventDepth + 1, // due now, it's the next hop of this chain; a real wait starts a new one
687
491
  };
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);
492
+ if (waits) job.runAt = new Date(now().getTime() + seconds * 1000).toISOString();
493
+ if (replace !== undefined) {
494
+ job.replace = replace;
495
+ // scheduled twice in this transaction: the later one wins here too (the dropped one's input is still checked:
496
+ // a bad input is a bug wherever it is)
497
+ const earlier = tx.calls.findIndex((c) => replaceKeyOf(c) === replaceKeyOf(job));
498
+ if (earlier >= 0) tx.calls.splice(earlier, 1);
499
+ }
500
+ tx.calls.push(job);
501
+ // our own code passed it: a bad input is a bug, surfaced at commit like an event's payload
502
+ if (fn.input) checkAtCommit(tx, fn.input, job.input, `${fnId} input`);
503
+ return job.id;
692
504
  },
693
505
  };
694
506
  }
507
+ /** An emitted event as jobs carry it: plain JSON, and copied, so what was emitted is what gets delivered. */
508
+ function envelopeOf(event: EventDef, payload: unknown, scope: object, depth: number): Envelope {
509
+ const name = idOf(event);
510
+ // a queue carries JSON: a Date or a class instance would work in-process and break only in production
511
+ assertPlain(payload, `${name} payload`, "Events travel through queues as JSON: send an ISO string and let the schema turn it into a Date");
512
+ return { id: crypto.randomUUID(), name, payload: structuredClone(payload), scope: storedScope(scope, `the scope emitting ${name}`), occurredAt: now().toISOString(), depth };
513
+ }
514
+ /** What a job keeps of the scope it runs as: `jobs.scope.store`'s pick, as a JSON copy. */
515
+ function storedScope(scope: object, what: string): object {
516
+ const stored = jobScope?.store ? jobScope.store(scope) : scope;
517
+ assertPlain(stored, what, "Jobs carry the scope through queues as JSON: keep it to ids (jobs.scope.store picks what's saved)");
518
+ return structuredClone(stored);
519
+ }
520
+
695
521
  const actionCtx = (frame: Frame, id: string): ActionCtx<any> => ({
696
522
  ...baseCtx(frame, id, ["query", "mutation", "action"]),
697
523
  signal: frame.signal,
698
524
  services,
699
525
  });
700
526
 
527
+ const { toJobs, deliver, jobs, due, checkHold } = makeJobs({
528
+ listeners,
529
+ crons,
530
+ functions,
531
+ idOf,
532
+ jobsAdapter,
533
+ database,
534
+ jobScope,
535
+ maxEventDepth,
536
+ now,
537
+ wrap,
538
+ report,
539
+ runAs: (fn, input, scope, eventDepth, queued) => invoke(fn, input, enter({ scope, depth: -1, eventDepth, queued }, undefined), ["query", "mutation", "action"]),
540
+ listenerCtx: (scope, eventDepth, id, queued) => actionCtx({ scope, depth: 0, eventDepth, queued }, id),
541
+ });
542
+
701
543
  // ── invoke ───────────────────────────────────────────────────────────────
702
544
  async function invoke(fn: Fn, rawInput: unknown, frame: Frame, allowed: Kind[]): Promise<any> {
703
545
  const id = idOf(fn);
@@ -711,10 +553,7 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
711
553
  frame.abortOn?.throwIfAborted();
712
554
  if (fn.authorize) {
713
555
  // 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`);
556
+ if (fn.authorize(frame.scope as never) !== true) throw new DomainError("forbidden", `${id}.forbidden`);
718
557
  }
719
558
  // no `input`: the function takes nothing, whatever an adapter sends (AI tools send `{}`)
720
559
  return fn.input ? parseInput(fn.input, rawInput, id, frame.depth > 0) : undefined;
@@ -735,7 +574,7 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
735
574
  if (frame.tx) {
736
575
  const tx = frame.tx;
737
576
  try {
738
- return await execute(await prepare(), mutationCtx(frame, id));
577
+ return await execute(await prepare(), mutationCtx(frame, tx, id));
739
578
  } catch (e) {
740
579
  if (!tx.doomed) {
741
580
  tx.doomed = true;
@@ -748,85 +587,72 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
748
587
  // top-level mutation: open the transaction, commit, then deliver events.
749
588
  // A lost race (deadlock, serialization failure) re-runs it in a fresh transaction.
750
589
  const input = await prepare();
751
- let committed: { out: unknown; outbox: Envelope[] };
590
+ let committed: { out: unknown; events: Envelope[]; jobs: Job[] };
752
591
  for (let attempt = 1; ; attempt++) {
753
- let state: TxState | undefined;
754
592
  try {
593
+ // SAFETY: createRegistry refuses mutations without a database that has interactive transactions
755
594
  committed = await database!.transaction(async (txDb) => {
756
595
  // 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));
596
+ const tx: TxState = { db: txDb, doomed: false, reason: undefined, events: [], parsed: new Map(), calls: [], pending: [] };
597
+ const out = await execute(input, mutationCtx({ ...frame, tx }, tx, id));
759
598
  await Promise.all(tx.pending);
760
599
  if (tx.doomed) throw tx.reason;
761
- await dispatcher.enqueue?.(txDb, tx.outbox);
762
- return { out, outbox: tx.outbox };
600
+ const jobs = toJobs(tx.events, tx.calls, tx.parsed);
601
+ if (jobs.length) await jobsAdapter.enqueue?.(txDb, jobs);
602
+ return { out, events: tx.events, jobs };
763
603
  });
764
604
  break;
765
605
  } catch (e) {
766
- if (attempt < attempts && database!.retryable?.(e)) {
606
+ if (attempt < transactionAttempts && database!.retryable?.(e)) { // SAFETY: as above
767
607
  // a random pause, so transactions that just deadlocked don't retry in lockstep and collide again
768
608
  await new Promise((r) => setTimeout(r, Math.random() * 20 * attempt));
769
609
  continue;
770
610
  }
771
611
  throw e;
772
- } finally {
773
- if (state) await Promise.allSettled(state.pending);
774
612
  }
775
613
  }
776
614
 
777
615
  // committed. Nothing below may fail the caller.
778
- if (committed.outbox.length) await afterCommit(committed.outbox, frame);
616
+ await afterCommit(committed.events, committed.jobs, frame.queued);
779
617
  return committed.out;
780
618
  });
781
619
  }
782
620
 
783
- async function afterCommit(outbox: Envelope[], frame: Frame) {
621
+ async function afterCommit(emitted: Envelope[], jobs: Job[], queued: Job[] | undefined) {
784
622
  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) {
623
+ for (const e of emitted) o.record?.(e);
624
+ if (!jobs.length) return;
625
+ if (queued) return void queued.push(...jobs); // queued by a job: delivered once that job is settled
626
+ const delivery = deliver(jobs);
627
+ if (waitUntil) {
798
628
  try {
799
- options.waitUntil(delivery);
629
+ waitUntil(delivery);
800
630
  return;
801
631
  } catch (e) {
802
- report(e, { listener: "(waitUntil)", envelope: outbox[0] });
632
+ report(e, { source: "(waitUntil)" });
803
633
  }
804
634
  }
805
635
  await delivery;
806
636
  } catch (e) {
807
- report(e, { listener: "(after commit)", envelope: outbox[0] });
637
+ report(e, { source: "(after commit)" });
808
638
  }
809
639
  }
810
640
 
811
641
  return {
812
- modules: options.modules,
813
642
  as: (scope) => ({
814
643
  scope,
815
644
  run: (fn: Fn, input?: unknown, options?: RunOptions) =>
816
- invoke(fn, input, enter({ scope, depth: -1 }, options), ["query", "mutation", "action"]), // depth 0
645
+ invoke(fn, input, enter({ scope, depth: -1, eventDepth: 0 }, options), ["query", "mutation", "action"]), // depth 0
817
646
  }),
818
- functions,
819
- events,
820
- listeners,
647
+ definitions: { functions, events, listeners, crons },
821
648
  idOf,
822
- dispatch,
649
+ jobs,
823
650
  [INTERNAL]: {
824
651
  options,
825
652
  config,
826
- derive: (more: Overrides) => build<S, Mods, Cf>(options, { ...o, ...more, config: mergeConfig(o.config, more.config) as object | undefined }),
653
+ derive: (more: Overrides) => build<S, Mods, Cf>(options, { ...o, ...more, config: mergeConfig(o.config, more.config) }),
654
+ envelope: (event, payload, scope) => envelopeOf(event, payload, scope, 1),
655
+ due,
827
656
  },
828
657
  };
829
658
  }
830
-
831
- /** @internal */
832
- export const internal = <S extends object, Mods extends Record<string, object>, Cf>(registry: Registry<S, Mods, Cf>) => registry[INTERNAL];