logic-sdk 0.7.1 → 0.7.3

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 (99) hide show
  1. package/README.md +9 -10
  2. package/dist/adapters/cloudflare-queue.d.ts +15 -0
  3. package/dist/adapters/cloudflare-queue.js +58 -0
  4. package/dist/adapters/drizzle-pg.d.ts +280 -0
  5. package/dist/adapters/drizzle-pg.js +78 -0
  6. package/dist/adapters/drizzle-sqlite.d.ts +273 -0
  7. package/dist/adapters/drizzle-sqlite.js +203 -0
  8. package/dist/adapters/postgres.d.ts +33 -0
  9. package/dist/adapters/postgres.js +129 -0
  10. package/dist/adapters/sqlite.d.ts +13 -0
  11. package/dist/adapters/sqlite.js +108 -0
  12. package/dist/adapters/stored-jobs.d.ts +89 -0
  13. package/dist/adapters/stored-jobs.js +370 -0
  14. package/dist/ai.d.ts +1 -32
  15. package/dist/ai.js +1 -40
  16. package/dist/cloudflare.d.ts +2 -55
  17. package/dist/cloudflare.js +2 -85
  18. package/dist/core/in-process.d.ts +9 -0
  19. package/dist/core/in-process.js +37 -0
  20. package/dist/core/jobs.d.ts +63 -0
  21. package/dist/core/jobs.js +514 -0
  22. package/dist/core/registry.d.ts +156 -0
  23. package/dist/core/registry.js +515 -0
  24. package/dist/core/testing.d.ts +75 -0
  25. package/dist/core/testing.js +232 -0
  26. package/dist/{types.d.ts → core/types.d.ts} +289 -64
  27. package/dist/drizzle/pg.d.ts +3 -236
  28. package/dist/drizzle/pg.js +2 -67
  29. package/dist/drizzle/sqlite.d.ts +3 -242
  30. package/dist/drizzle/sqlite.js +2 -194
  31. package/dist/fetch.d.ts +1 -19
  32. package/dist/fetch.js +1 -30
  33. package/dist/hosts/cloudflare.d.ts +43 -0
  34. package/dist/hosts/cloudflare.js +40 -0
  35. package/dist/hosts/node.d.ts +36 -0
  36. package/dist/hosts/node.js +103 -0
  37. package/dist/index.d.ts +5 -122
  38. package/dist/index.js +4 -492
  39. package/dist/integrations/ai.d.ts +32 -0
  40. package/dist/integrations/ai.js +40 -0
  41. package/dist/integrations/fetch.d.ts +19 -0
  42. package/dist/integrations/fetch.js +30 -0
  43. package/dist/integrations/orpc.d.ts +22 -0
  44. package/dist/integrations/orpc.js +37 -0
  45. package/dist/node.d.ts +1 -26
  46. package/dist/node.js +1 -76
  47. package/dist/orpc.d.ts +1 -21
  48. package/dist/orpc.js +1 -37
  49. package/dist/postgres.d.ts +2 -28
  50. package/dist/postgres.js +1 -82
  51. package/dist/sqlite.d.ts +2 -9
  52. package/dist/sqlite.js +1 -65
  53. package/dist/testing.d.ts +1 -75
  54. package/dist/testing.js +1 -227
  55. package/package.json +2 -12
  56. package/skills/logic-sdk/SKILL.md +6 -5
  57. package/src/adapters/cloudflare-queue.ts +65 -0
  58. package/src/adapters/drizzle-pg.ts +117 -0
  59. package/src/adapters/drizzle-sqlite.ts +241 -0
  60. package/src/adapters/postgres.ts +136 -0
  61. package/src/adapters/sqlite.ts +116 -0
  62. package/src/adapters/stored-jobs.ts +463 -0
  63. package/src/ai.ts +1 -62
  64. package/src/cloudflare.ts +2 -107
  65. package/src/core/in-process.ts +38 -0
  66. package/src/core/jobs.ts +548 -0
  67. package/src/core/registry.ts +719 -0
  68. package/src/core/testing.ts +309 -0
  69. package/src/{types.ts → core/types.ts} +280 -60
  70. package/src/drizzle/pg.ts +3 -110
  71. package/src/drizzle/sqlite.ts +3 -236
  72. package/src/fetch.ts +1 -31
  73. package/src/hosts/cloudflare.ts +55 -0
  74. package/src/hosts/node.ts +126 -0
  75. package/src/index.ts +17 -652
  76. package/src/integrations/ai.ts +63 -0
  77. package/src/integrations/fetch.ts +31 -0
  78. package/src/integrations/orpc.ts +47 -0
  79. package/src/node.ts +1 -99
  80. package/src/orpc.ts +1 -46
  81. package/src/postgres.ts +2 -90
  82. package/src/sqlite.ts +2 -74
  83. package/src/testing.ts +1 -305
  84. package/dist/jobs.d.ts +0 -44
  85. package/dist/jobs.js +0 -260
  86. package/dist/pg-boss.d.ts +0 -53
  87. package/dist/pg-boss.js +0 -213
  88. package/dist/stored-jobs.d.ts +0 -64
  89. package/dist/stored-jobs.js +0 -188
  90. package/src/jobs.ts +0 -307
  91. package/src/pg-boss.ts +0 -241
  92. package/src/stored-jobs.ts +0 -260
  93. /package/dist/{errors.d.ts → core/errors.d.ts} +0 -0
  94. /package/dist/{errors.js → core/errors.js} +0 -0
  95. /package/dist/{schedule.d.ts → core/schedule.d.ts} +0 -0
  96. /package/dist/{schedule.js → core/schedule.js} +0 -0
  97. /package/dist/{types.js → core/types.js} +0 -0
  98. /package/src/{errors.ts → core/errors.ts} +0 -0
  99. /package/src/{schedule.ts → core/schedule.ts} +0 -0
package/src/index.ts CHANGED
@@ -1,50 +1,7 @@
1
- import { CaughtNestedFailure, describeIssues, DomainError, errorsFor, forbiddenOf, moduleOf, PRIVATE } 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
- CronCtx,
15
- DatabaseAdapter,
16
- DbOf,
17
- Envelope,
18
- EventDef,
19
- FailureInfo,
20
- Fn,
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
1
  export type {
47
2
  ActionCtx,
3
+ AdapterSetup,
4
+ LocalWorker,
48
5
  Call,
49
6
  CallJob,
50
7
  Caller,
@@ -55,11 +12,19 @@ export type {
55
12
  CronRun,
56
13
  CronJob,
57
14
  DatabaseAdapter,
15
+ DatabaseOptions,
58
16
  DeepPartial,
59
17
  Delivery,
18
+ EmittedEvent,
60
19
  Envelope,
61
20
  Errors,
62
21
  EventDef,
22
+ FailedJob,
23
+ FailedJobs,
24
+ FailedOptions,
25
+ FailedPage,
26
+ FailedQuery,
27
+ FailedRow,
63
28
  FailureInfo,
64
29
  Fn,
65
30
  FnIn,
@@ -100,612 +65,12 @@ export type {
100
65
  Runner,
101
66
  ScheduleOptions,
102
67
  Schema,
68
+ ScopeMatch,
103
69
  SqlDatabase,
70
+ SweepOptions,
104
71
  SweepResult,
105
- } from "./types.ts";
106
- export { DomainError, isDomainError, unauthenticated, type ErrorKind } from "./errors.ts";
107
- export { inProcess, replaceKeyOf } from "./jobs.ts";
108
-
109
- /* ────────────────────────────────────────────────────────────────────────────
110
- * init: typed constructors
111
- * ──────────────────────────────────────────────────────────────────────────── */
112
-
113
- type TypedOptions<C extends Config, Mods extends Record<string, object>, T> = Omit<RegistryOptions<Mods>, "wrap" | "jobs"> & {
114
- /** Background work: `jobs: { adapter: databaseQueue(database), scope: { store, load } }`. Default: in-process, scope as-is (nothing waits). */
115
- jobs?: JobsOptions<ScopeOf<C>, T>;
116
- /** Wraps every call, including ones that fail validation or authorization: logging, tracing, audit. */
117
- wrap?: (call: Call<CallMetaOf<C>>, next: () => Promise<unknown>) => Promise<unknown>;
118
- } &
119
- ({} extends ServicesOf<C> ? { services?: ServicesOf<C> } : { services: ServicesOf<C> }) &
120
- ({} extends ConfigOf<C> ? { config?: ConfigOf<C> } : { config: ConfigOf<C> }) &
121
- ([DbOf<C>] extends [never] ? { database?: undefined } : { database: DatabaseAdapter<unknown, DbOf<C>> }) &
122
- { modules: OwnModules<C, Mods> };
123
-
124
- /** Keys `Config` doesn't know are errors, so a typo like `servises` can't be silently ignored. */
125
- type OnlyKnownKeys<C> = { [K in Exclude<keyof C, keyof Config>]: never };
126
-
127
- /**
128
- * Typed constructors for your app:
129
- *
130
- * ```ts
131
- * export const { query, mutation, action, event, listener, createRegistry } = init<Config>();
132
- * ```
133
- */
134
- export function init<C extends Config & OnlyKnownKeys<C>>() {
135
- // One implementation behind the typed signature of `Constructor`: the types are the contract, the adapters check `authorize`.
136
- const make =
137
- <K extends Kind>(kind: K) =>
138
- (def: object) =>
139
- Object.freeze({ [BRAND]: kind, kind, ...def });
140
-
141
- return {
142
- /** Create the registry once at startup: `createRegistry({ modules, database, services })`. */
143
- createRegistry: <const Mods extends Record<string, object>, T = ScopeOf<C>>(options: TypedOptions<C, Mods, T>) =>
144
- build<ScopeOf<C>, Mods, ConfigOf<C>>(options as RegistryOptions<Mods>, {}), // meta in wrap is typed by CallMetaOf<C>; the values come from typed defs
145
- /** Reads data. Can run other queries. No writes, no events, no services. */
146
- query: make("query") as Constructor<C, "query">,
147
- /** Changes data inside one transaction. Can run queries and mutations (same transaction) and emit events. */
148
- mutation: make("mutation") as Constructor<C, "mutation">,
149
- /** Talks to the outside world (payments, email, AI). No transaction; each mutation it runs commits on its own. */
150
- action: make("action") as Constructor<C, "action">,
151
- /** Something that happened. Emitted by mutations, delivered after commit. */
152
- event: <S extends Schema>(def: {
153
- /**
154
- * Stable id, local to its module: in a `notifications` module, `id: "send"` is `notifications.send`. Jobs store it,
155
- * so set it before you rename the export and queued jobs keep finding this code. Defaults to the export name.
156
- */
157
- id?: string;
158
- payload: S;
159
- }): EventDef<In<S>, Out<S>> =>
160
- Object.freeze({ [BRAND]: "event" as const, kind: "event" as const, ...def }),
161
- /**
162
- * Work on a schedule, as `scope` (a cron has no caller): a handler, like a listener's, run when the clock says. Export
163
- * it from a module and call `registry.jobs.tick()` every minute (or from your platform's cron trigger). Must be
164
- * idempotent: a retry runs the whole handler again.
165
- * `cron({ schedule: "0 9 * * MON", scope: { kind: "system", job: "reports.weekly" }, async handler(ctx) { await ctx.run(send) } })`.
166
- */
167
- cron: <const Sc extends ScopeOf<C>>(def: CronDef<C, Sc>): Cron<C> => {
168
- const { id, schedule, timezone, scope, attempts, meta, handler } = def;
169
- parseSchedule(schedule);
170
- if (timezone !== undefined) assertTimeZone(timezone);
171
- checkAttempts("cron", attempts);
172
- // meta is checked against ListenerMetaOf<C> above and stored loose, like a listener's, for wrap and adapters
173
- return Object.freeze({ [BRAND]: "cron" as const, kind: "cron" as const, id, schedule, timezone, scope, attempts, meta: meta as Cron["meta"], handler });
174
- },
175
- /**
176
- * React to an event after commit, like an action. Must be idempotent.
177
- * `listener({ event: () => bookings.confirmed, async handler(ctx, payload) {…} })`
178
- */
179
- listener: <O>(def: {
180
- /**
181
- * Stable id, local to its module: in a `notifications` module, `id: "send"` is `notifications.send`. Jobs store it,
182
- * so set it before you rename the export and queued jobs keep finding this code. Defaults to the export name.
183
- */
184
- id?: string;
185
- /** The event it reacts to, as a thunk so modules can import each other's barrels without cycles. */
186
- event: () => EventDef<unknown, O>;
187
- /**
188
- * Tries in total, the first included, like Laravel's `$tries`. Default 1: a retry repeats side effects, so opt in.
189
- * Once they're used, the job is `failed` (kept by `databaseQueue`, `outbox` and pg-boss, retried with `registry.jobs.retry(id)`).
190
- */
191
- attempts?: number;
192
- /** Seconds after the event before the first try. Needs an adapter that holds jobs: `inProcess()` is refused. */
193
- delay?: number;
194
- /**
195
- * Whether this event gets a job for this listener, like Laravel's `shouldQueue($event)`: false, and nothing is
196
- * stored, run or counted. From the payload the handler gets (parsed), at commit, so sync and from the event only:
197
- * a condition on the database belongs in the handler, since it can change before the job runs. A throw fails the
198
- * mutation, as a bad payload does.
199
- */
200
- when?: (payload: O) => boolean;
201
- meta?: ListenerMetaOf<C>;
202
- handler: (ctx: ListenerCtx<C, O>, payload: O) => Promise<unknown>;
203
- }): Listener<O, C> => {
204
- const { id, event, attempts, delay, when, meta, handler } = def;
205
- checkAttempts("listener", attempts);
206
- if (delay !== undefined && !(Number.isFinite(delay) && delay >= 0))
207
- throw new Error(`[logic-sdk] listener delay must be seconds, 0 or more (got ${delay}).`);
208
- // meta is checked against ListenerMetaOf<C> above and stored loose, like Fn.meta, for wrap and adapters
209
- return Object.freeze({ [BRAND]: "listener" as const, kind: "listener" as const, id, event, attempts, delay, when, meta: meta as Listener["meta"], handler });
210
- },
211
- };
212
- }
213
-
214
- /** `cron({...})`: its handler's `ctx.scope` is the scope it declares, so a policy-free read of it is typed. */
215
- type CronDef<C extends Config, Sc> = {
216
- /**
217
- * Stable id, local to its module, like every definer's. Defaults to the export name. Jobs and pg-boss's queue store it,
218
- * so set it before you rename the export.
219
- */
220
- id?: string;
221
- /** Five fields: minute hour day-of-month month day-of-week. `"*\/15 * * * *"`, `"0 9 * * MON"`. */
222
- schedule: string;
223
- /** IANA name, like `"Europe/Madrid"`. Default UTC. Matched on the wall clock, like Laravel: mind DST at 1 to 3 am. */
224
- timezone?: string;
225
- /** Who it runs as: a cron has no caller. Every function the handler runs checks its policy against it. */
226
- scope: Sc;
227
- /** Tries in total, like a listener's. Default 1: a retry runs the whole handler again. */
228
- attempts?: number;
229
- meta?: ListenerMetaOf<C>;
230
- /** The work, like a listener's handler: an action's ctx, plus `ctx.cron` (`scheduledAt`, `attempt`). */
231
- handler: (ctx: CronCtx<C, Sc>) => Promise<unknown>;
232
- };
233
-
234
- /** How deep `ctx.run` calls may nest. Past it, a function is running itself without end. */
235
- const MAX_RUN_DEPTH = 64;
236
-
237
- function checkAttempts(what: string, attempts: number | undefined) {
238
- if (attempts !== undefined && !(Number.isInteger(attempts) && attempts >= 1))
239
- throw new Error(`[logic-sdk] ${what} attempts must be a whole number of tries, 1 or more (got ${attempts}).`);
240
- }
241
-
242
- /* ────────────────────────────────────────────────────────────────────────────
243
- * createRegistry
244
- * ──────────────────────────────────────────────────────────────────────────── */
245
-
246
- interface TxState {
247
- db: unknown;
248
- doomed: boolean;
249
- reason: unknown;
250
- /** Where the transaction's own mutation sits in the trail: what the error at commit prints starts there. */
251
- from: number;
252
- /** The calls down to the nested mutation whose failure doomed it, from the transaction's own mutation. */
253
- doomedBy: readonly string[] | undefined;
254
- events: Envelope[];
255
- /** Each event's payload as its schema parsed it, for listeners' `when`: the value their handler gets. */
256
- parsed: Map<Envelope, unknown>;
257
- /** What `ctx.schedule` asked for, enqueued with the events at commit. */
258
- calls: CallJob[];
259
- pending: Promise<void>[];
260
- }
261
- interface Frame {
262
- scope: object;
263
- /** The calls that led here, outermost first. How many there are is the next call's depth. */
264
- trail: readonly string[];
265
- /** Inherited, for actions to pass on as ctx.signal. */
266
- signal?: AbortSignal;
267
- /** Passed to this very call: checked before it starts. */
268
- abortOn?: AbortSignal;
269
- /** Hops in the chain of events and calls due now that led here: 0 for a call from outside. */
270
- eventDepth: number;
271
- /** Inside a job: where the jobs it queues wait until it's settled. */
272
- queued?: Job[];
273
- tx?: TxState;
274
- }
275
-
276
- /** What a mutation throws at commit when a nested mutation failed and was caught: the transaction they share is doomed. */
277
- function caughtNestedFailure(id: string, tx: TxState): CaughtNestedFailure {
278
- let why: string;
279
- try {
280
- why = tx.reason instanceof Error ? tx.reason.message : String(tx.reason);
281
- } catch {
282
- why = Object.prototype.toString.call(tx.reason); // an object String() can't print
283
- }
284
- return new CaughtNestedFailure(
285
- `[logic-sdk] ${tx.doomedBy?.at(-1)} failed inside ${id}'s transaction (${tx.doomedBy?.join(" → ")}) and was ` +
286
- `caught, so ${id} can't commit: a mutation shares its transaction with the mutations it runs. To let each one ` +
287
- `commit or fail on its own, run them from an action. The failure (this error's cause): ${why}`,
288
- { cause: tx.reason },
289
- );
290
- }
291
-
292
- /** Create the registry once at startup. Prefer the `createRegistry` returned by `init()`: it's typed with your config. */
293
- export function createRegistry<S extends object = object, const Mods extends Record<string, object> = Record<string, object>>(
294
- options: RegistryOptions<Mods>,
295
- ) {
296
- return build<S, Mods>(options, {});
297
- }
298
-
299
- const isPlain = (v: unknown): v is Record<string, unknown> =>
300
- !!v && typeof v === "object" && (Object.getPrototypeOf(v) === Object.prototype || Object.getPrototypeOf(v) === null);
301
-
302
- /** Plain objects merge key by key; anything else (values, arrays, null) replaces. `undefined` keeps the base. */
303
- function mergeConfig(base: unknown, patch: unknown): unknown {
304
- if (patch === undefined) return base;
305
- if (!isPlain(base) || !isPlain(patch)) return patch;
306
- const keys = new Set([...Object.keys(base), ...Object.keys(patch)]);
307
- return Object.fromEntries([...keys].map((k) => [k, mergeConfig(base[k], patch[k])])); // fromEntries: `__proto__` stays a key
308
- }
309
-
310
- /** A frozen copy of plain data, so settings can't change under everyone else or hide behavior (a client, a class). */
311
- function freezeConfig(value: unknown): unknown {
312
- assertPlain(value, "config", "config holds plain data: pass a Date as an ISO string, and put clients in services");
313
- const freeze = (v: unknown): unknown => {
314
- if (v && typeof v === "object") {
315
- for (const item of Object.values(v)) freeze(item);
316
- Object.freeze(v);
317
- }
318
- return v;
319
- };
320
- return freeze(structuredClone(value));
321
- }
322
-
323
- /**
324
- * Plain data, what survives JSON: plain objects, arrays, strings, finite numbers, booleans, null (undefined is dropped).
325
- * Anything else (a Date, a Map, a class instance, a function, a cycle) is rejected with its path.
326
- */
327
- function assertPlain(value: unknown, what: string, hint: string): void {
328
- const seen = new Set<object>();
329
- const check = (v: unknown, path: string): void => {
330
- const fail = (found: string): never => {
331
- throw new Error(`[logic-sdk] ${what} isn't plain data${path ? ` at ${path}` : ""}: ${found}. ${hint}.`);
332
- };
333
- if (v === null || v === undefined || typeof v === "string" || typeof v === "boolean") return;
334
- if (typeof v === "number") {
335
- if (!Number.isFinite(v)) fail(String(v));
336
- return;
337
- }
338
- if (typeof v !== "object") return fail(`a ${typeof v}`);
339
- if (seen.has(v)) fail("a circular reference");
340
- seen.add(v);
341
- if (Array.isArray(v)) v.forEach((item, i) => check(item, `${path}[${i}]`));
342
- else {
343
- if (!isPlain(v)) fail(`a ${v.constructor?.name ?? "class instance"}`);
344
- for (const [k, item] of Object.entries(v)) check(item, path ? `${path}.${k}` : k);
345
- }
346
- seen.delete(v);
347
- };
348
- check(value, "");
349
- }
350
-
351
- const isBranded = (v: unknown): v is Fn | EventDef | Listener | Cron => !!v && typeof v === "object" && BRAND in v;
352
-
353
- /**
354
- * What `createRegistry` finds in your modules, without a database or services: every function, event, listener and
355
- * cron with its id. For tools (the CLI, docs generators) that inspect an app without running it.
356
- */
357
- export function describeModules(modules: Record<string, object>) {
358
- const ids = new Map<object, string>();
359
- const functions: RegisteredFn[] = [];
360
- const events: RegisteredEvent[] = [];
361
- const listeners: RegisteredListener[] = [];
362
- const crons: RegisteredCron[] = [];
363
-
364
- const taken = new Map<string, string>();
365
-
366
- for (const [module, ns] of Object.entries(modules)) {
367
- for (const [name, value] of Object.entries(ns)) {
368
- if (!isBranded(value) || ids.has(value)) continue;
369
- const local = value.id ?? name;
370
- if (value.id !== undefined && (typeof value.id !== "string" || !/^[A-Za-z0-9_-]+$/.test(value.id)))
371
- 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>.`);
372
- const id = `${module}.${local}`;
373
- const other = taken.get(id);
374
- 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.`);
375
- taken.set(id, name);
376
- ids.set(value, id);
377
- if (value.kind === "event") events.push({ id, module, name, event: value });
378
- else if (value.kind === "listener") listeners.push({ id, module, name, listener: value, event: value.event() });
379
- else if (value.kind === "cron") crons.push({ id, module, name, cron: value });
380
- else functions.push({ id, module, name, kind: value.kind, fn: value });
381
- }
382
- }
383
- return { ids, functions, events, listeners, crons };
384
- }
385
-
386
- function build<S extends object, Mods extends Record<string, object>, Cf = unknown>(
387
- options: RegistryOptions<Mods>,
388
- o: Overrides,
389
- ): Registry<S, Mods, Cf> {
390
- const { ids, functions, events, listeners, crons } = describeModules(options.modules);
391
-
392
- const database = o.database ?? options.database;
393
- const services = o.services ?? options.services ?? {};
394
- const config = freezeConfig(mergeConfig(options.config ?? {}, o.config)) as Frozen<Cf>;
395
- const jobsAdapter = o.adapter ?? options.jobs?.adapter ?? inProcess();
396
- const jobScope = options.jobs?.scope;
397
- 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.");
398
- // a job any adapter but inProcess() keeps runs as a scope saved earlier: rebuild it, or its roles are the ones from
399
- // back then (AshOban's actor_persister). The app's adapter, so a test registry agrees with the app it wraps.
400
- const appAdapter = options.jobs?.adapter;
401
- if (appAdapter && !runsNow(appAdapter) && !jobScope?.load)
402
- throw new Error(
403
- "[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 " +
404
- "roles (null discards the job). Add `store` to save only ids. To keep the scope as it was, `load: (saved) => saved`.",
405
- );
406
- const now = o.now ?? options.now ?? (() => new Date());
407
- const wrap = options.wrap ?? ((_c, next) => next());
408
- const maxEventDepth = options.jobs?.maxEventDepth ?? 8;
409
- checkAttempts("database transaction", options.database?.transactionAttempts);
410
- const transactionAttempts = options.database?.transactionAttempts ?? 3; // the app's, so a test's nested adapter keeps it
411
- const waitUntil = "waitUntil" in o ? o.waitUntil : options.waitUntil; // tests turn it off: listeners finish inside the test
412
- const reportRaw =
413
- o.onError ?? options.onError ?? ((e, info) => console.error(`[logic-sdk] ${info.source} failed`, e));
414
- const report = (e: unknown, info: FailureInfo) => {
415
- try {
416
- reportRaw(e, info);
417
- } catch (inner) {
418
- console.error("[logic-sdk] onError threw", inner, "while reporting", e);
419
- }
420
- };
421
-
422
- const noDatabase =
423
- "[logic-sdk] Mutations need a database: createRegistry({ database: drizzleAdapter(db) }). It needs interactive " +
424
- "transactions, so Cloudflare D1 and HTTP drivers can't run mutations.";
425
- if (!database && functions.some((f) => f.kind === "mutation")) throw new Error(noDatabase);
426
- for (const l of listeners)
427
- if (!ids.has(l.event))
428
- throw new Error(`[logic-sdk] Listener ${l.id} listens to an event that isn't registered in any module.`);
429
- jobsAdapter.check?.({ listeners, crons, database });
430
-
431
- const idOf = (x: object) => {
432
- const id = ids.get(x);
433
- if (!id)
434
- throw new Error(
435
- "[logic-sdk] This function or event isn't registered. Export it from its module's index.ts, and add the module to createRegistry({ modules }). " +
436
- "A private function (one the index doesn't export) runs only through ctx.run, from its own module.",
437
- );
438
- return id;
439
- };
440
-
441
- /** Bad input from a caller is their error. Bad input from your own code (a nested call) is a bug. */
442
- async function parseInput(schema: Schema, value: unknown, id: string, nested: boolean) {
443
- const r = await schema["~standard"].validate(value);
444
- if (!r.issues) return r.value;
445
- const issues = describeIssues(r.issues);
446
- if (nested) throw new Error(`[logic-sdk] ${id} was run with invalid input: ${JSON.stringify(issues)}`);
447
- throw new DomainError("invalid", `${id}.invalid_input`, { issues });
448
- }
449
- /** Output and event payloads are produced by our own code: invalid means a bug, not a bad request. */
450
- async function parseOwn(schema: Schema, value: unknown, what: string) {
451
- const r = await schema["~standard"].validate(value);
452
- if (r.issues) throw new Error(`[logic-sdk] ${what} is invalid: ${JSON.stringify(describeIssues(r.issues))}`);
453
- return r.value;
454
- }
455
- /** What our own code passed a mutation's ctx, checked by the time it commits: a bad value fails the commit. */
456
- function checkAtCommit(tx: TxState, schema: Schema, value: unknown, what: string, keep?: (parsed: unknown) => void) {
457
- const check = parseOwn(schema, value, what).then((parsed) => keep?.(parsed));
458
- check.catch(() => {}); // surfaced at commit; never an unhandled rejection
459
- tx.pending.push(check);
460
- }
461
-
462
- // ── ctx ──────────────────────────────────────────────────────────────────
463
- /** The frame for a call from here: its scope and signal. `invoke` adds the call to the trail. */
464
- const enter = (frame: Frame, options: RunOptions | undefined): Frame => ({
465
- ...frame,
466
- scope: options?.scope ?? frame.scope,
467
- signal: options?.signal ?? frame.signal,
468
- abortOn: options?.signal,
469
- });
470
-
471
- /** What every ctx has. `allowed`: the kinds its `run` may call. */
472
- const baseCtx = (frame: Frame, id: string, allowed: Kind[]) => ({
473
- errors: errorsFor(id),
474
- scope: frame.scope,
475
- config: config as any, // Frozen<Cf> here; each app's ctx types it from its own Config
476
- now,
477
- run: (fn: Fn, input?: unknown, options?: RunOptions) => invoke(fn, input, enter(frame, options), allowed, moduleOf(id)),
478
- });
479
- const queryCtx = (frame: Frame, id: string): QueryCtx<any> => ({
480
- ...baseCtx(frame, id, ["query"]),
481
- db: frame.tx ? frame.tx.db : database?.db,
482
- });
483
- function mutationCtx(frame: Frame, tx: TxState, id: string): MutationCtx<any> {
484
- return {
485
- ...baseCtx(frame, id, ["query", "mutation"]),
486
- db: tx.db,
487
- emit: (event, payload) => {
488
- // reserve the slot now so events keep emit order, even with async schemas
489
- const envelope = envelopeOf(event, payload, frame.scope, frame.eventDepth + 1);
490
- tx.events.push(envelope);
491
- checkAtCommit(tx, event.payload, envelope.payload, `${envelope.name} payload`, (parsed) => tx.parsed.set(envelope, parsed));
492
- },
493
- schedule: (fn, input, { at, delay, attempts = 1, replace }) => {
494
- const fnId = ids.get(fn);
495
- if (!fnId)
496
- throw new Error(
497
- "[logic-sdk] ctx.schedule needs a function its module's index.ts exports: a scheduled call waits as a name, and a worker finds the code by it. " +
498
- "A private function runs only through ctx.run.",
499
- );
500
- const seconds = at ? (at.getTime() - now().getTime()) / 1000 : (delay ?? NaN);
501
- if (!Number.isFinite(seconds) || (!at && seconds < 0))
502
- throw new Error(`[logic-sdk] ctx.schedule(${fnId}) needs an \`at\` date or a \`delay\` in seconds, 0 or more.`);
503
- checkAttempts(`ctx.schedule(${fnId})`, attempts);
504
- if (replace !== undefined) {
505
- if (!replace) throw new Error(`[logic-sdk] ctx.schedule(${fnId}) replace must be a non-empty key.`);
506
- if (!jobsAdapter.replaces)
507
- 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.`);
508
- }
509
- // due now (no delay, or an `at` already past): runs after commit like a listener, no holding needed
510
- const waits = seconds > 0;
511
- if (waits) checkHold(`ctx.schedule(${fnId})`, seconds);
512
- assertPlain(input, `${fnId} input`, "Scheduled calls wait as JSON: send an ISO string and let the schema turn it into a Date");
513
- const job: CallJob = {
514
- kind: "call",
515
- id: `${fnId}@${crypto.randomUUID()}`,
516
- fn: fnId,
517
- input: structuredClone(input),
518
- scope: storedScope(frame.scope, `the scope scheduling ${fnId}`),
519
- attempts,
520
- depth: waits ? 0 : frame.eventDepth + 1, // due now, it's the next hop of this chain; a real wait starts a new one
521
- };
522
- if (waits) job.runAt = new Date(now().getTime() + seconds * 1000).toISOString();
523
- if (replace !== undefined) {
524
- job.replace = replace;
525
- // scheduled twice in this transaction: the later one wins here too (the dropped one's input is still checked:
526
- // a bad input is a bug wherever it is)
527
- const earlier = tx.calls.findIndex((c) => replaceKeyOf(c) === replaceKeyOf(job));
528
- if (earlier >= 0) tx.calls.splice(earlier, 1);
529
- }
530
- tx.calls.push(job);
531
- // our own code passed it: a bad input is a bug, surfaced at commit like an event's payload
532
- if (fn.input) checkAtCommit(tx, fn.input, job.input, `${fnId} input`);
533
- return job.id;
534
- },
535
- };
536
- }
537
- /** An emitted event as jobs carry it: plain JSON, and copied, so what was emitted is what gets delivered. */
538
- function envelopeOf(event: EventDef, payload: unknown, scope: object, depth: number): Envelope {
539
- const name = idOf(event);
540
- // a queue carries JSON: a Date or a class instance would work in-process and break only in production
541
- assertPlain(payload, `${name} payload`, "Events travel through queues as JSON: send an ISO string and let the schema turn it into a Date");
542
- return { id: crypto.randomUUID(), name, payload: structuredClone(payload), scope: storedScope(scope, `the scope emitting ${name}`), occurredAt: now().toISOString(), depth };
543
- }
544
- /** What a job keeps of the scope it runs as: `jobs.scope.store`'s pick, as a JSON copy. */
545
- function storedScope(scope: object, what: string): object {
546
- const stored = jobScope?.store ? jobScope.store(scope) : scope;
547
- assertPlain(stored, what, "Jobs carry the scope through queues as JSON: keep it to ids (jobs.scope.store picks what's saved)");
548
- return structuredClone(stored);
549
- }
550
-
551
- const actionCtx = (frame: Frame, id: string): ActionCtx<any> => ({
552
- ...baseCtx(frame, id, ["query", "mutation", "action"]),
553
- signal: frame.signal,
554
- services,
555
- });
556
-
557
- const { toJobs, deliver, jobs, due, checkHold } = makeJobs({
558
- listeners,
559
- crons,
560
- functions,
561
- idOf,
562
- jobsAdapter,
563
- database,
564
- jobScope,
565
- maxEventDepth,
566
- now,
567
- wrap,
568
- report,
569
- runAs: (fn, input, scope, eventDepth, queued) => invoke(fn, input, enter({ scope, trail: [], eventDepth, queued }, undefined), ["query", "mutation", "action"]),
570
- handlerCtx: (scope, eventDepth, id, queued) => actionCtx({ scope, trail: [id], eventDepth, queued }, id),
571
- });
572
-
573
- // ── invoke ───────────────────────────────────────────────────────────────
574
- /** `callerModule`: set by ctx.run, so a private function (its index doesn't export it) runs as part of the module running it. */
575
- async function invoke(fn: Fn, rawInput: unknown, outer: Frame, allowed: Kind[], callerModule?: string): Promise<any> {
576
- // anything else that runs one finds it by name, and it has none: idOf throws, saying so
577
- const id = ids.get(fn) ?? (callerModule ? `${callerModule}.${fn.id ?? PRIVATE}` : idOf(fn));
578
- if (!allowed.includes(fn.kind))
579
- throw new Error(`[logic-sdk] ${id} is a ${fn.kind}; it can't be run from here (allowed: ${allowed.join(", ")}).`);
580
- const depth = outer.trail.length;
581
- // a function that runs itself, through other modules or not, never returns: stop it with the path, not run out of memory
582
- if (depth > MAX_RUN_DEPTH)
583
- throw new Error(
584
- `[logic-sdk] ctx.run nested past ${MAX_RUN_DEPTH} calls: … → ${[...outer.trail.slice(-6), id].join(" → ")}. ` +
585
- "Recurse in a plain helper that takes ctx, or make each step separate work (an event, or ctx.schedule).",
586
- );
587
- const frame: Frame = { ...outer, trail: [...outer.trail, id] };
588
-
589
- const call: Call = { id, kind: fn.kind, meta: fn.meta, input: rawInput, scope: frame.scope, depth };
590
-
591
- /** Authorize, then validate, before any transaction opens: denied or bad calls never touch the database. */
592
- const prepare = async () => {
593
- frame.abortOn?.throwIfAborted();
594
- if (fn.authorize) {
595
- // SAFETY: the registry erases each policy's scope type; the caller's scope is the app's Scope by construction
596
- if (fn.authorize(frame.scope as never) !== true) throw new DomainError("forbidden", forbiddenOf(id));
597
- }
598
- // no `input`: the function takes nothing, whatever an adapter sends (AI tools send `{}`)
599
- return fn.input ? parseInput(fn.input, rawInput, id, depth > 0) : undefined;
600
- };
601
- const execute = async (input: unknown, ctx: unknown) => {
602
- // SAFETY: the handler's types were erased when it was registered. `ctx` was built for its kind,
603
- // and `input` just passed its own schema (or it takes none).
604
- const handler = o.stubs?.get(fn) ?? fn.handler;
605
- const out = await handler(ctx as never, input as never);
606
- return fn.output ? parseOwn(fn.output, out, `${id} output`) : out;
607
- };
608
-
609
- return wrap(call, async () => {
610
- if (fn.kind === "query") return execute(await prepare(), queryCtx(frame, id));
611
- if (fn.kind === "action") return execute(await prepare(), actionCtx(frame, id));
612
-
613
- // mutation joining an open transaction: any failure dooms it, even if the caller catches
614
- if (frame.tx) {
615
- const tx = frame.tx;
616
- try {
617
- return await execute(await prepare(), mutationCtx(frame, tx, id));
618
- } catch (e) {
619
- if (!tx.doomed) {
620
- tx.doomed = true;
621
- tx.reason = e;
622
- tx.doomedBy = frame.trail.slice(tx.from);
623
- }
624
- throw e;
625
- }
626
- }
627
-
628
- // top-level mutation: open the transaction, commit, then deliver events.
629
- // A lost race (deadlock, serialization failure) re-runs it in a fresh transaction.
630
- // createRegistry checks for one, but a private mutation isn't registered, so it can only be checked here
631
- if (!database) throw new Error(noDatabase);
632
- const input = await prepare();
633
- let committed: { out: unknown; events: Envelope[]; jobs: Job[] };
634
- for (let attempt = 1; ; attempt++) {
635
- const attemptTx: { current?: TxState } = {};
636
- try {
637
- committed = await database.transaction(async (txDb) => {
638
- // fresh per attempt, so a retry never reuses events from a failed attempt
639
- const tx: TxState = {
640
- db: txDb, doomed: false, reason: undefined, from: frame.trail.length - 1, doomedBy: undefined,
641
- events: [], parsed: new Map(), calls: [], pending: [],
642
- };
643
- attemptTx.current = tx;
644
- const out = await execute(input, mutationCtx({ ...frame, tx }, tx, id));
645
- await Promise.all(tx.pending);
646
- // a nested failure was caught: a bug, so its own error, with the failure as its cause (Ecto's aborted
647
- // transaction). Retries still see a deadlock: `retryable` walks causes
648
- if (tx.doomed) throw caughtNestedFailure(id, tx);
649
- const jobs = toJobs(tx.events, tx.calls, tx.parsed);
650
- if (jobs.length) await jobsAdapter.enqueue?.(txDb, jobs);
651
- return { out, events: tx.events, jobs };
652
- });
653
- break;
654
- } catch (e) {
655
- // a lost race dooms the transaction even when a caller caught it and went on: Postgres then fails the next
656
- // statement with 25P02, or the caller throws its own error, and the race is still what to retry
657
- const doomed = attemptTx.current?.doomed ? attemptTx.current.reason : undefined;
658
- const lostRace = database.retryable?.(e) || (doomed !== undefined && database.retryable?.(doomed));
659
- if (attempt < transactionAttempts && lostRace) {
660
- // a random pause, so transactions that just deadlocked don't retry in lockstep and collide again
661
- await new Promise((r) => setTimeout(r, Math.random() * 20 * attempt));
662
- continue;
663
- }
664
- throw e;
665
- }
666
- }
667
-
668
- // committed. Nothing below may fail the caller.
669
- await afterCommit(committed.events, committed.jobs, frame.queued);
670
- return committed.out;
671
- });
672
- }
673
-
674
- async function afterCommit(emitted: Envelope[], jobs: Job[], queued: Job[] | undefined) {
675
- try {
676
- for (const e of emitted) o.record?.(e);
677
- if (!jobs.length) return;
678
- if (queued) return void queued.push(...jobs); // queued by a job: delivered once that job is settled
679
- const delivery = deliver(jobs);
680
- if (waitUntil) {
681
- try {
682
- waitUntil(delivery);
683
- return;
684
- } catch (e) {
685
- report(e, { source: "(waitUntil)" });
686
- }
687
- }
688
- await delivery;
689
- } catch (e) {
690
- report(e, { source: "(after commit)" });
691
- }
692
- }
693
-
694
- return {
695
- as: (scope) => ({
696
- scope,
697
- run: (fn: Fn, input?: unknown, options?: RunOptions) =>
698
- invoke(fn, input, enter({ scope, trail: [], eventDepth: 0 }, options), ["query", "mutation", "action"]),
699
- }),
700
- definitions: { functions, events, listeners, crons },
701
- idOf,
702
- jobs,
703
- [INTERNAL]: {
704
- options,
705
- config,
706
- derive: (more: Overrides) => build<S, Mods, Cf>(options, { ...o, ...more, config: mergeConfig(o.config, more.config) }),
707
- envelope: (event, payload, scope) => envelopeOf(event, payload, scope, 1),
708
- due,
709
- },
710
- };
711
- }
72
+ } from "./core/types.ts";
73
+ export { DomainError, isDomainError, unauthenticated, type ErrorKind } from "./core/errors.ts";
74
+ export { inProcess } from "./core/in-process.ts";
75
+ export { defaultBackoff, storedUniqueKey } from "./core/jobs.ts";
76
+ export { createRegistry, describeModules, init } from "./core/registry.ts";