logic-sdk 0.5.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -84,7 +84,7 @@ export const registry = createRegistry({
84
84
  export const sendConfirmation = listener({ event: () => confirmed, attempts: 3, handler });
85
85
 
86
86
  // a cron
87
- export const morningDigest = cron({ schedule: "0 8 * * MON-FRI", run: sendDigest, scope: asSystem("digest") });
87
+ export const morningDigest = cron({ schedule: "0 8 * * MON-FRI", run: () => sendDigest, scope: asSystem("digest") });
88
88
 
89
89
  // later, from a mutation, committed with it
90
90
  ctx.schedule(remindGuest, { bookingId }, { at: dayBefore(booking.checkIn) });
@@ -128,10 +128,9 @@ npm i -D @logic-sdk/cli
128
128
  npx logic-sdk list # every function, its kind and policy
129
129
  logic-sdk show bookings.confirm # schemas, what it runs and emits, who calls it
130
130
  logic-sdk graph --format mermaid # who runs whom, who reacts to which event
131
- logic-sdk check # module boundaries, run cycles, no network in transactions, can* checks
132
131
  ```
133
132
 
134
- Read-only, `--json` everywhere, exit codes for CI. The `logic-sdk` command ships with the main package and hands off to `@logic-sdk/cli`, so apps that don't use the CLI never download it.
133
+ Read-only, `--json` everywhere, exit codes for scripts. The `logic-sdk` command ships with the main package and hands off to `@logic-sdk/cli`, so apps that don't use the CLI never download it.
135
134
 
136
135
  ## Examples
137
136
 
package/bin/logic-sdk.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // `npx logic-sdk check`. The CLI itself lives in @logic-sdk/cli, so apps that never use it
2
+ // `npx logic-sdk list`. The CLI itself lives in @logic-sdk/cli, so apps that never use it
3
3
  // (a Worker, a Next.js app) don't download its parser and loader.
4
4
  const CLI = "@logic-sdk/cli";
5
5
 
@@ -10,8 +10,7 @@ interface Transactional {
10
10
  type Transaction<Db extends Transactional> = Parameters<Parameters<Db["transaction"]>[0]>[0];
11
11
  /**
12
12
  * What mutations get: the transaction minus `transaction`, since a savepoint that rolled back would still send the
13
- * events and calls made inside it. Type helpers with it: `type Tx = DrizzleTx<typeof db>`. A type-level guard;
14
- * `logic-sdk check` catches the rest.
13
+ * events and calls made inside it. Type helpers with it: `type Tx = DrizzleTx<typeof db>`. A type-level guard.
15
14
  */
16
15
  export type DrizzleTx<Db extends Transactional> = Omit<Transaction<Db>, "transaction">;
17
16
  /** What queries get: the database minus write methods. A type-level guard, not a runtime one. */
package/dist/index.d.ts CHANGED
@@ -54,7 +54,7 @@ export declare function init<C extends Config & OnlyKnownKeys<C>>(): {
54
54
  /**
55
55
  * Run a function on a schedule, as `scope` (a cron has no caller). Export it from a module, like listeners, and call
56
56
  * `registry.jobs.tick()` every minute (or from your platform's cron trigger):
57
- * `cron({ schedule: "0 9 * * 1", run: reports.sendWeekly, scope: system })`.
57
+ * `cron({ schedule: "0 9 * * 1", run: () => reports.sendWeekly, scope: system })`.
58
58
  */
59
59
  cron: <F extends Fn>(def: CronDef<ScopeOf<C>, F>) => Cron<C>;
60
60
  /**
@@ -95,8 +95,11 @@ type CronDef<S, F extends Fn> = {
95
95
  schedule: string;
96
96
  /** IANA name, like `"Europe/Madrid"`. Default UTC. Matched on the wall clock, like Laravel: mind DST at 1 to 3 am. */
97
97
  timezone?: string;
98
- /** Any query, mutation or action: it runs with its policy, validation and tracing. */
99
- run: F;
98
+ /**
99
+ * Any query, mutation or action, behind a function: `run: () => reports.sendWeekly`. It runs with its policy, validation
100
+ * and tracing. Read when the registry is built, like a listener's `event`, so no definer reads an import while files load.
101
+ */
102
+ run: () => F;
100
103
  /** Who it runs as: a cron has no caller. */
101
104
  scope: S;
102
105
  /** Tries in total, like a listener's. Default 1. */
package/dist/index.js CHANGED
@@ -28,7 +28,7 @@ export function init() {
28
28
  /**
29
29
  * Run a function on a schedule, as `scope` (a cron has no caller). Export it from a module, like listeners, and call
30
30
  * `registry.jobs.tick()` every minute (or from your platform's cron trigger):
31
- * `cron({ schedule: "0 9 * * 1", run: reports.sendWeekly, scope: system })`.
31
+ * `cron({ schedule: "0 9 * * 1", run: () => reports.sendWeekly, scope: system })`.
32
32
  */
33
33
  cron: (def) => {
34
34
  const { id, schedule, timezone, run, input, scope, attempts } = def;
@@ -52,6 +52,8 @@ export function init() {
52
52
  },
53
53
  };
54
54
  }
55
+ /** How deep `ctx.run` calls may nest. Past it, a function is running itself without end. */
56
+ const MAX_RUN_DEPTH = 64;
55
57
  function checkAttempts(what, attempts) {
56
58
  if (attempts !== undefined && !(Number.isInteger(attempts) && attempts >= 1))
57
59
  throw new Error(`[logic-sdk] ${what} attempts must be a whole number of tries, 1 or more (got ${attempts}).`);
@@ -147,7 +149,7 @@ export function describeModules(modules) {
147
149
  else if (value.kind === "listener")
148
150
  listeners.push({ id, module, name, listener: value, event: value.event() });
149
151
  else if (value.kind === "cron")
150
- crons.push({ id, module, name, cron: value });
152
+ crons.push({ id, module, name, cron: value, run: value.run() });
151
153
  else
152
154
  functions.push({ id, module, name, kind: value.kind, fn: value });
153
155
  }
@@ -221,15 +223,14 @@ function build(options, o) {
221
223
  tx.pending.push(check);
222
224
  }
223
225
  for (const c of crons) {
224
- if (!ids.has(c.cron.run))
226
+ if (!ids.has(c.run))
225
227
  throw new Error(`[logic-sdk] Cron ${c.id} runs a function that isn't registered. Export it from its module's index.ts.`);
226
228
  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");
227
229
  }
228
230
  // ── ctx ──────────────────────────────────────────────────────────────────
229
- /** The frame a call runs in: one level deeper, with this call's scope patch and signal. */
231
+ /** The frame for a call from here: its scope patch and signal. `invoke` adds the call to the trail. */
230
232
  const enter = (frame, options) => ({
231
233
  ...frame,
232
- depth: frame.depth + 1,
233
234
  scope: options?.scope ? { ...frame.scope, ...options.scope } : frame.scope,
234
235
  signal: options?.signal ?? frame.signal,
235
236
  abortOn: options?.signal,
@@ -330,15 +331,21 @@ function build(options, o) {
330
331
  now,
331
332
  wrap,
332
333
  report,
333
- runAs: (fn, input, scope, eventDepth, queued) => invoke(fn, input, enter({ scope, depth: -1, eventDepth, queued }, undefined), ["query", "mutation", "action"]),
334
- listenerCtx: (scope, eventDepth, id, queued) => actionCtx({ scope, depth: 0, eventDepth, queued }, id),
334
+ runAs: (fn, input, scope, eventDepth, queued) => invoke(fn, input, enter({ scope, trail: [], eventDepth, queued }, undefined), ["query", "mutation", "action"]),
335
+ listenerCtx: (scope, eventDepth, id, queued) => actionCtx({ scope, trail: [id], eventDepth, queued }, id),
335
336
  });
336
337
  // ── invoke ───────────────────────────────────────────────────────────────
337
- async function invoke(fn, rawInput, frame, allowed) {
338
+ async function invoke(fn, rawInput, outer, allowed) {
338
339
  const id = idOf(fn);
339
340
  if (!allowed.includes(fn.kind))
340
341
  throw new Error(`[logic-sdk] ${id} is a ${fn.kind}; it can't be run from here (allowed: ${allowed.join(", ")}).`);
341
- const call = { id, kind: fn.kind, meta: fn.meta, input: rawInput, scope: frame.scope, depth: frame.depth };
342
+ const depth = outer.trail.length;
343
+ // a function that runs itself, through other modules or not, never returns: stop it with the path, not run out of memory
344
+ if (depth > MAX_RUN_DEPTH)
345
+ throw new Error(`[logic-sdk] ctx.run nested past ${MAX_RUN_DEPTH} calls: … → ${[...outer.trail.slice(-6), id].join(" → ")}. ` +
346
+ "Recurse in a plain helper that takes ctx, or make each step separate work (an event, or ctx.schedule).");
347
+ const frame = { ...outer, trail: [...outer.trail, id] };
348
+ const call = { id, kind: fn.kind, meta: fn.meta, input: rawInput, scope: frame.scope, depth };
342
349
  /** Authorize, then validate, before any transaction opens: denied or bad calls never touch the database. */
343
350
  const prepare = async () => {
344
351
  frame.abortOn?.throwIfAborted();
@@ -348,7 +355,7 @@ function build(options, o) {
348
355
  throw new DomainError("forbidden", `${id}.forbidden`);
349
356
  }
350
357
  // no `input`: the function takes nothing, whatever an adapter sends (AI tools send `{}`)
351
- return fn.input ? parseInput(fn.input, rawInput, id, frame.depth > 0) : undefined;
358
+ return fn.input ? parseInput(fn.input, rawInput, id, depth > 0) : undefined;
352
359
  };
353
360
  const execute = async (input, ctx) => {
354
361
  // SAFETY: the handler's types were erased when it was registered. `ctx` was built for its kind,
@@ -438,7 +445,7 @@ function build(options, o) {
438
445
  return {
439
446
  as: (scope) => ({
440
447
  scope,
441
- run: (fn, input, options) => invoke(fn, input, enter({ scope, depth: -1, eventDepth: 0 }, options), ["query", "mutation", "action"]), // depth 0
448
+ run: (fn, input, options) => invoke(fn, input, enter({ scope, trail: [], eventDepth: 0 }, options), ["query", "mutation", "action"]),
442
449
  }),
443
450
  definitions: { functions, events, listeners, crons },
444
451
  idOf,
package/dist/jobs.js CHANGED
@@ -155,7 +155,7 @@ export function makeJobs(deps) {
155
155
  if (!c)
156
156
  return missing("cron", job.cron);
157
157
  return attemptOnce(async () => {
158
- await runAs(c.cron.run, c.cron.input, c.cron.scope, 0, queued);
158
+ await runAs(c.run, c.cron.input, c.cron.scope, 0, queued);
159
159
  return "done";
160
160
  });
161
161
  }
package/dist/types.d.ts CHANGED
@@ -101,13 +101,13 @@ type FromInit<C extends Config> = {
101
101
  };
102
102
  };
103
103
  /** A query, mutation or action. Call it with `caller.run(fn, input)` or `ctx.run(fn, input)`. */
104
- export interface Fn<K extends Kind = Kind, I = unknown, O = unknown, A extends boolean = boolean, C extends Config = any> {
104
+ export interface Fn<K extends Kind = Kind, I = unknown, O = unknown, A extends boolean = boolean, C extends Config = any, IS extends Schema | undefined = Schema | undefined> {
105
105
  readonly [BRAND]: K;
106
106
  readonly kind: K;
107
107
  /** Stable id, local to the module: `id: "send"` in `notifications` is `notifications.send`. Defaults to the export name. */
108
108
  readonly id?: string;
109
- /** What callers pass, validated on every call. Left out: the function takes nothing (`run(fn)`). */
110
- readonly input?: Schema;
109
+ /** What callers pass, validated on every call, as you wrote it: `fn.input.pick({ name: true })` for a form. Undefined: the function takes nothing (`run(fn)`). */
110
+ readonly input: IS;
111
111
  /** What callers get back, checked before it leaves. */
112
112
  readonly output?: Schema;
113
113
  /** Your own data about the function. Checked against `meta` in `init` where you set it, typed in `wrap`; loose here, for adapters. */
@@ -222,7 +222,8 @@ export interface Cron<C extends Config = any> extends FromInit<C> {
222
222
  readonly id?: string;
223
223
  readonly schedule: string;
224
224
  readonly timezone?: string;
225
- readonly run: Fn;
225
+ /** The function it runs, read when the registry is built, like a listener's `event`. */
226
+ readonly run: () => Fn;
226
227
  readonly input?: unknown;
227
228
  readonly scope: object;
228
229
  readonly attempts?: number;
@@ -380,7 +381,7 @@ type Def<C extends Config, K extends Kind, IS, OS, R, P, A> = {
380
381
  * instead of "No overload matches this call". Keep `output: OS` plain: `OS & Schema` makes TypeScript compare the whole
381
382
  * schema type structurally on every definition (about 10x slower to check).
382
383
  */
383
- export type Constructor<C extends Config, K extends Kind> = <IS extends Schema = NoInput, OS extends Schema | undefined = undefined, R = unknown, P extends Policy<ScopeOf<C>> = Policy<ScopeOf<C>>, A extends boolean = never>(def: Def<C, K, IS, OS, R, P, A>) => Fn<K, In<IS>, [OS] extends [Schema] ? Out<OS> : R, [A] extends [never] ? false : true, C>;
384
+ export type Constructor<C extends Config, K extends Kind> = <IS extends Schema = NoInput, OS extends Schema | undefined = undefined, R = unknown, P extends Policy<ScopeOf<C>> = Policy<ScopeOf<C>>, A extends boolean = never>(def: Def<C, K, IS, OS, R, P, A>) => Fn<K, In<IS>, [OS] extends [Schema] ? Out<OS> : R, [A] extends [never] ? false : true, C, NoInput extends IS ? undefined : IS>;
384
385
  type OtherInit = SetupError<"Defined with another init(), so it would run with this registry's scope, not its own. Define it with the init() this createRegistry came from">;
385
386
  /** `createRegistry`'s modules: a function, listener or cron defined with another `init` is an error, since it would run with this one's scope. Events have no `init`. */
386
387
  export type OwnModules<C extends Config, Mods> = {
@@ -593,6 +594,7 @@ export interface RegisteredListener extends Registered {
593
594
  }
594
595
  export interface RegisteredCron extends Registered {
595
596
  cron: Cron;
597
+ run: Fn;
596
598
  }
597
599
  /** `registry.jobs`: what you call from a queue consumer, a cron, or a script. */
598
600
  export interface Jobs {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "logic-sdk",
3
- "version": "0.5.0",
3
+ "version": "0.6.1",
4
4
  "description": "Queries, mutations, actions and events for TypeScript apps. Transactions, after-commit events and scopes, on any runtime.",
5
5
  "keywords": [
6
6
  "actions",
@@ -113,7 +113,7 @@
113
113
  "drizzle-orm": ">=1.0.0-rc.6 <2",
114
114
  "pg-boss": ">=12.39.0 <13",
115
115
  "ai": ">=7 <8",
116
- "@logic-sdk/cli": ">=0.5.0 <0.6.0"
116
+ "@logic-sdk/cli": ">=0.6.0 <0.7.0"
117
117
  },
118
118
  "peerDependenciesMeta": {
119
119
  "@orpc/server": {
@@ -63,7 +63,7 @@ export const cancel = mutation({
63
63
 
64
64
  1. **Pick the kind by what it touches.** Only reads: `query`. Writes to our database: `mutation`. Talks to the network: `action`. Reacts to another module: `listener`.
65
65
  2. **Never put side effects in a mutation or query.** No email, HTTP or payments. They don't have `services` on purpose. Emit an event and react in a listener, or write an action that runs the mutation.
66
- 3. **Call other modules only with `run(otherModule.fn, input)`.** Import them as `import * as availability from "../availability"`. Never import their `data.ts` or `schema.ts`, from a module or from routes and pages; `logic-sdk check` fails the build if you do (path aliases and `#` imports included).
66
+ 3. **Call other modules only with `run(otherModule.fn, input)`.** Import them as `import * as availability from "../availability"`. Never import their `data.ts` or `schema.ts`, from a module or from routes and pages.
67
67
  4. **Within a module, use helpers.** Shared logic is a plain function in `data.ts` taking `ctx`. `ctx.run` your own module's function only when you want its `authorize`, validation and tracing.
68
68
  5. **Always filter by `ctx.scope.accountId`** in `data.ts` helpers, writes included. Loading helpers throw `ctx.errors.notFound()`. Scope is who and where (actor, account, locale); input is what.
69
69
  6. **Authorize every function a user, client or AI tool may call.** `authorize: member` (a policy from `policies.ts`) says who may call it: sync, reads only scope, runs on every call including nested ones. Publish a function by listing it in `src/rpc.ts` (`toORPCProcedure(fn)`) or an agent's tools (`toAITool(caller, fn)`); both refuse one without `authorize`. A hand-written route or Server Action can `caller.run` anything, nothing stops it: only call functions that have `authorize` from them. Give published functions an `output` so nothing unintended leaves.
@@ -74,10 +74,10 @@ export const cancel = mutation({
74
74
  11. **Listeners must be idempotent** (record `ctx.event.id` per listener, since listeners of one event share it, and skip it if seen, when a repeat would charge or email twice). They run with the emitter's scope (or the one `jobs.scope.load` rebuilds, when the app sets it), so they run internal functions. To act as someone else on purpose, change the scope for that call: `ctx.run(fn, input, { scope: { actor: system } })`.
75
75
  12. **Time** comes from `ctx.now()`, never `new Date()`, so tests can freeze it.
76
76
  13. **Use separate `export const`s**, not functions nested in an object. Name them by verb within the module (`bookings.confirm`, not `bookings.confirmBooking`). Names are unique per module. Renaming a listener, event or function that queued jobs may still reference? Keep its id: `listener({ id: "oldName", ... })`. Put one sentence of JSDoc above each (`/** Cancel a booking and free its dates */`): editors show it on hover, and `logic-sdk list` prints it.
77
- 14. **`ctx` comes first, everywhere:** `handler(ctx, input)` in functions, `handler(ctx, payload)` in listeners, helpers `findBooking(ctx, id)`. A function that takes nothing leaves out `input`: `handler(ctx)`, called as `run(fn)`.
78
- 15. **Settings come from `ctx.config`**, never from env inside a module. Declare its shape in `init<Config>()` (`config: { orders: { maxItems: number } }`), fill it from your env at the entry (`createRegistry({ config })`), and read it in any function: `ctx.config.orders.maxItems`. Plain data only. Clients built from secrets go in `services`. Outside modules (the entry, routes, scripts), read env however you like; `logic-sdk check` fails on env reads inside modules, including through files they import.
77
+ 14. **`ctx` comes first, everywhere:** `handler(ctx, input)` in functions, `handler(ctx, payload)` in listeners, helpers `findBooking(ctx, id)`. A function that takes nothing leaves out `input`: `handler(ctx)`, called as `run(fn)`. A form's schema comes from the function it submits to (`properties.update.input.pick({ name: true })`), not from a schema the module exports.
78
+ 15. **Settings come from `ctx.config`**, never from env inside a module. Declare its shape in `init<Config>()` (`config: { orders: { maxItems: number } }`), fill it from your env at the entry (`createRegistry({ config })`), and read it in any function: `ctx.config.orders.maxItems`. Plain data only. Clients built from secrets go in `services`. Outside modules (the entry, routes, scripts), read env however you like.
79
79
  16. **Listeners that must not be lost run through a durable jobs adapter,** set once in `registry.ts`: `const database = drizzleAdapter(db)` from `logic-sdk/drizzle/pg` (SQLite: `drizzleAdapter(() => drizzle("app.db"))` from `logic-sdk/drizzle/sqlite`, the function, not a connection), then `createRegistry({ database, jobs: { adapter: databaseQueue(database), scope: { store, load } } })` (your database is the queue, like Laravel's `database` driver; export `jobsTable` from the schema and sweep from a cron trigger or `startTicking`), `outbox(database, cloudflareQueue(env.JOBS))` when another queue runs them (the queue alone works too, and can lose a job on a crash), or `pgBoss(boss)` from `logic-sdk/pg-boss` when the app runs pg-boss (`await boss.start()` in every process, `await work(registry, boss)` in the worker, `boss.stop()` on SIGTERM; tune a listener's queue and workers with `meta: { pgBoss: { queue, worker } }`, never its retries). `store` saves ids, `load` rebuilds the scope when the job runs, with today's roles (`null` discards it: check membership there). `createRegistry` requires `load` with every adapter but `inProcess()`; keep the `system` field of a system scope in both. Never pass a jobs adapter per module, and never enqueue background work by hand from a mutation: `emit` an event. A listener tries once; give it `attempts: 5` when retrying is safe, and `delay: 60` (seconds) to run it later.
80
- 17. **Scheduled work is a `cron`,** exported from the module like a listener: `cron({ schedule: "0 9 * * MON", run: fn, scope: asSystem("reports.weekly") })`, where `asSystem` builds a `System` variant of the app's `Scope` (`actor: null`, `system: name`, never built from a request) and policies grant it explicitly (`staffOrSystem`), never a fake user. With `jobs.scope`, `store` and `load` must keep the system variant: what a cron emits or schedules is stored like anything else. Five-field strings only (weekdays as names: Cloudflare numbers them from Sunday = 1), `timezone` when it isn't UTC. `run` is an existing function (it keeps its policy); never put the work in the cron itself. On Node, `startTicking(registry)` from `logic-sdk/node` ticks and sweeps (`await stop()` on SIGTERM); with pg-boss, `work(registry, boss)` ticks them; on Cloudflare, `handleScheduled` from a `"* * * * *"` trigger (weekdays as names in `wrangler.jsonc`: Cloudflare counts Sunday as 1). Test with `t.jobs.tick(at)`.
80
+ 17. **Scheduled work is a `cron`,** exported from the module like a listener: `cron({ schedule: "0 9 * * MON", run: () => fn, scope: asSystem("reports.weekly") })`, where `asSystem` builds a `System` variant of the app's `Scope` (`actor: null`, `system: name`, never built from a request) and policies grant it explicitly (`staffOrSystem`), never a fake user. With `jobs.scope`, `store` and `load` must keep the system variant: what a cron emits or schedules is stored like anything else. Five-field strings only (weekdays as names: Cloudflare numbers them from Sunday = 1), `timezone` when it isn't UTC. `run` is an existing function (it keeps its policy); never put the work in the cron itself. On Node, `startTicking(registry)` from `logic-sdk/node` ticks and sweeps (`await stop()` on SIGTERM); with pg-boss, `work(registry, boss)` ticks them; on Cloudflare, `handleScheduled` from a `"* * * * *"` trigger (weekdays as names in `wrangler.jsonc`: Cloudflare counts Sunday as 1). Test with `t.jobs.tick(at)`.
81
81
  18. **Work for later is `ctx.schedule(fn, input, { at } | { delay })`,** from a mutation only, so it commits with it (actions and listeners run a mutation that schedules). The function re-checks its reason when it runs ("still confirmed?"): there's no cancel. Like a cron's, it can run twice, mutations included, so make it idempotent (a unique key and `onConflictDoNothing()`). One try by default: add `attempts: 3` for an action that calls an API. When what it's for can change (a booking's dates), pass `replace: bookingId`: the newer call replaces the waiting one, so it doesn't run twice. It needs `jobs: { adapter: databaseQueue(database), scope: { store, load } }`, an `outbox` or `pgBoss(boss)` (rule 16); tests read `t.jobs.scheduled` and run it with `t.jobs.drain({ until })`.
82
82
 
83
83
  ## Tests
@@ -109,6 +109,6 @@ test("cancel frees the dates", async () => {
109
109
 
110
110
  ## Done means
111
111
 
112
- `tsc` passes, `logic-sdk check` passes (module boundaries, run cycles, no network in transactions, `can*` checks sync and used, no `.transaction()` or database client in modules: only `ctx.db`), and the tests pass. Every new mutation has a test for its main rule.
112
+ `tsc` passes and the tests pass. Every new mutation has a test for its main rule.
113
113
 
114
114
  Before changing a function, look it up: `logic-sdk show bookings.confirm --json` gives its schemas, policy, record checks, what it runs and emits, and who calls it. `logic-sdk graph --module bookings` shows a module's connections.
package/src/drizzle/pg.ts CHANGED
@@ -16,8 +16,7 @@ type Transaction<Db extends Transactional> = Parameters<Parameters<Db["transacti
16
16
 
17
17
  /**
18
18
  * What mutations get: the transaction minus `transaction`, since a savepoint that rolled back would still send the
19
- * events and calls made inside it. Type helpers with it: `type Tx = DrizzleTx<typeof db>`. A type-level guard;
20
- * `logic-sdk check` catches the rest.
19
+ * events and calls made inside it. Type helpers with it: `type Tx = DrizzleTx<typeof db>`. A type-level guard.
21
20
  */
22
21
  export type DrizzleTx<Db extends Transactional> = Omit<Transaction<Db>, "transaction">;
23
22
 
package/src/index.ts CHANGED
@@ -159,7 +159,7 @@ export function init<C extends Config & OnlyKnownKeys<C>>() {
159
159
  /**
160
160
  * Run a function on a schedule, as `scope` (a cron has no caller). Export it from a module, like listeners, and call
161
161
  * `registry.jobs.tick()` every minute (or from your platform's cron trigger):
162
- * `cron({ schedule: "0 9 * * 1", run: reports.sendWeekly, scope: system })`.
162
+ * `cron({ schedule: "0 9 * * 1", run: () => reports.sendWeekly, scope: system })`.
163
163
  */
164
164
  cron: <F extends Fn>(def: CronDef<ScopeOf<C>, F>): Cron<C> => {
165
165
  const { id, schedule, timezone, run, input, scope, attempts } = def;
@@ -215,14 +215,20 @@ type CronDef<S, F extends Fn> = {
215
215
  schedule: string;
216
216
  /** IANA name, like `"Europe/Madrid"`. Default UTC. Matched on the wall clock, like Laravel: mind DST at 1 to 3 am. */
217
217
  timezone?: string;
218
- /** Any query, mutation or action: it runs with its policy, validation and tracing. */
219
- run: F;
218
+ /**
219
+ * Any query, mutation or action, behind a function: `run: () => reports.sendWeekly`. It runs with its policy, validation
220
+ * and tracing. Read when the registry is built, like a listener's `event`, so no definer reads an import while files load.
221
+ */
222
+ run: () => F;
220
223
  /** Who it runs as: a cron has no caller. */
221
224
  scope: S;
222
225
  /** Tries in total, like a listener's. Default 1. */
223
226
  attempts?: number;
224
227
  } & (undefined extends FnIn<F> ? { input?: FnIn<F> } : { input: FnIn<F> });
225
228
 
229
+ /** How deep `ctx.run` calls may nest. Past it, a function is running itself without end. */
230
+ const MAX_RUN_DEPTH = 64;
231
+
226
232
  function checkAttempts(what: string, attempts: number | undefined) {
227
233
  if (attempts !== undefined && !(Number.isInteger(attempts) && attempts >= 1))
228
234
  throw new Error(`[logic-sdk] ${what} attempts must be a whole number of tries, 1 or more (got ${attempts}).`);
@@ -245,7 +251,8 @@ interface TxState {
245
251
  }
246
252
  interface Frame {
247
253
  scope: object;
248
- depth: number;
254
+ /** The calls that led here, outermost first. How many there are is the next call's depth. */
255
+ trail: readonly string[];
249
256
  /** Inherited, for actions to pass on as ctx.signal. */
250
257
  signal?: AbortSignal;
251
258
  /** Passed to this very call: checked before it starts. */
@@ -344,7 +351,7 @@ export function describeModules(modules: Record<string, object>) {
344
351
  ids.set(value, id);
345
352
  if (value.kind === "event") events.push({ id, module, name, event: value });
346
353
  else if (value.kind === "listener") listeners.push({ id, module, name, listener: value, event: value.event() });
347
- else if (value.kind === "cron") crons.push({ id, module, name, cron: value });
354
+ else if (value.kind === "cron") crons.push({ id, module, name, cron: value, run: value.run() });
348
355
  else functions.push({ id, module, name, kind: value.kind, fn: value });
349
356
  }
350
357
  }
@@ -428,16 +435,15 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
428
435
  }
429
436
 
430
437
  for (const c of crons) {
431
- if (!ids.has(c.cron.run))
438
+ if (!ids.has(c.run))
432
439
  throw new Error(`[logic-sdk] Cron ${c.id} runs a function that isn't registered. Export it from its module's index.ts.`);
433
440
  assertPlain(c.cron.input, `${c.id} input`, "Cron runs travel through queues as JSON: send an ISO string and let the schema turn it into a Date");
434
441
  }
435
442
 
436
443
  // ── ctx ──────────────────────────────────────────────────────────────────
437
- /** The frame a call runs in: one level deeper, with this call's scope patch and signal. */
444
+ /** The frame for a call from here: its scope patch and signal. `invoke` adds the call to the trail. */
438
445
  const enter = (frame: Frame, options: RunOptions | undefined): Frame => ({
439
446
  ...frame,
440
- depth: frame.depth + 1,
441
447
  scope: options?.scope ? { ...frame.scope, ...options.scope } : frame.scope,
442
448
  signal: options?.signal ?? frame.signal,
443
449
  abortOn: options?.signal,
@@ -536,17 +542,25 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
536
542
  now,
537
543
  wrap,
538
544
  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),
545
+ runAs: (fn, input, scope, eventDepth, queued) => invoke(fn, input, enter({ scope, trail: [], eventDepth, queued }, undefined), ["query", "mutation", "action"]),
546
+ listenerCtx: (scope, eventDepth, id, queued) => actionCtx({ scope, trail: [id], eventDepth, queued }, id),
541
547
  });
542
548
 
543
549
  // ── invoke ───────────────────────────────────────────────────────────────
544
- async function invoke(fn: Fn, rawInput: unknown, frame: Frame, allowed: Kind[]): Promise<any> {
550
+ async function invoke(fn: Fn, rawInput: unknown, outer: Frame, allowed: Kind[]): Promise<any> {
545
551
  const id = idOf(fn);
546
552
  if (!allowed.includes(fn.kind))
547
553
  throw new Error(`[logic-sdk] ${id} is a ${fn.kind}; it can't be run from here (allowed: ${allowed.join(", ")}).`);
554
+ const depth = outer.trail.length;
555
+ // a function that runs itself, through other modules or not, never returns: stop it with the path, not run out of memory
556
+ if (depth > MAX_RUN_DEPTH)
557
+ throw new Error(
558
+ `[logic-sdk] ctx.run nested past ${MAX_RUN_DEPTH} calls: … → ${[...outer.trail.slice(-6), id].join(" → ")}. ` +
559
+ "Recurse in a plain helper that takes ctx, or make each step separate work (an event, or ctx.schedule).",
560
+ );
561
+ const frame: Frame = { ...outer, trail: [...outer.trail, id] };
548
562
 
549
- const call: Call = { id, kind: fn.kind, meta: fn.meta, input: rawInput, scope: frame.scope, depth: frame.depth };
563
+ const call: Call = { id, kind: fn.kind, meta: fn.meta, input: rawInput, scope: frame.scope, depth };
550
564
 
551
565
  /** Authorize, then validate, before any transaction opens: denied or bad calls never touch the database. */
552
566
  const prepare = async () => {
@@ -556,7 +570,7 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
556
570
  if (fn.authorize(frame.scope as never) !== true) throw new DomainError("forbidden", `${id}.forbidden`);
557
571
  }
558
572
  // no `input`: the function takes nothing, whatever an adapter sends (AI tools send `{}`)
559
- return fn.input ? parseInput(fn.input, rawInput, id, frame.depth > 0) : undefined;
573
+ return fn.input ? parseInput(fn.input, rawInput, id, depth > 0) : undefined;
560
574
  };
561
575
  const execute = async (input: unknown, ctx: unknown) => {
562
576
  // SAFETY: the handler's types were erased when it was registered. `ctx` was built for its kind,
@@ -642,7 +656,7 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
642
656
  as: (scope) => ({
643
657
  scope,
644
658
  run: (fn: Fn, input?: unknown, options?: RunOptions) =>
645
- invoke(fn, input, enter({ scope, depth: -1, eventDepth: 0 }, options), ["query", "mutation", "action"]), // depth 0
659
+ invoke(fn, input, enter({ scope, trail: [], eventDepth: 0 }, options), ["query", "mutation", "action"]),
646
660
  }),
647
661
  definitions: { functions, events, listeners, crons },
648
662
  idOf,
package/src/jobs.ts CHANGED
@@ -204,7 +204,7 @@ export function makeJobs(deps: JobsDeps) {
204
204
  const c = cronById.get(job.cron);
205
205
  if (!c) return missing("cron", job.cron);
206
206
  return attemptOnce(async () => {
207
- await runAs(c.cron.run, c.cron.input, c.cron.scope, 0, queued);
207
+ await runAs(c.run, c.cron.input, c.cron.scope, 0, queued);
208
208
  return "done";
209
209
  });
210
210
  }
package/src/types.ts CHANGED
@@ -99,13 +99,13 @@ export const BRAND: unique symbol = Symbol.for("logic-sdk.brand");
99
99
  type FromInit<C extends Config> = { readonly [types]?: { init: (config: C) => void } };
100
100
 
101
101
  /** A query, mutation or action. Call it with `caller.run(fn, input)` or `ctx.run(fn, input)`. */
102
- export interface Fn<K extends Kind = Kind, I = unknown, O = unknown, A extends boolean = boolean, C extends Config = any> {
102
+ export interface Fn<K extends Kind = Kind, I = unknown, O = unknown, A extends boolean = boolean, C extends Config = any, IS extends Schema | undefined = Schema | undefined> {
103
103
  readonly [BRAND]: K;
104
104
  readonly kind: K;
105
105
  /** Stable id, local to the module: `id: "send"` in `notifications` is `notifications.send`. Defaults to the export name. */
106
106
  readonly id?: string;
107
- /** What callers pass, validated on every call. Left out: the function takes nothing (`run(fn)`). */
108
- readonly input?: Schema;
107
+ /** What callers pass, validated on every call, as you wrote it: `fn.input.pick({ name: true })` for a form. Undefined: the function takes nothing (`run(fn)`). */
108
+ readonly input: IS;
109
109
  /** What callers get back, checked before it leaves. */
110
110
  readonly output?: Schema;
111
111
  /** Your own data about the function. Checked against `meta` in `init` where you set it, typed in `wrap`; loose here, for adapters. */
@@ -219,7 +219,8 @@ export interface Cron<C extends Config = any> extends FromInit<C> {
219
219
  readonly id?: string;
220
220
  readonly schedule: string;
221
221
  readonly timezone?: string;
222
- readonly run: Fn;
222
+ /** The function it runs, read when the registry is built, like a listener's `event`. */
223
+ readonly run: () => Fn;
223
224
  readonly input?: unknown;
224
225
  readonly scope: object;
225
226
  readonly attempts?: number;
@@ -394,7 +395,7 @@ export type Constructor<C extends Config, K extends Kind> = <
394
395
  A extends boolean = never,
395
396
  >(
396
397
  def: Def<C, K, IS, OS, R, P, A>,
397
- ) => Fn<K, In<IS>, [OS] extends [Schema] ? Out<OS> : R, [A] extends [never] ? false : true, C>;
398
+ ) => Fn<K, In<IS>, [OS] extends [Schema] ? Out<OS> : R, [A] extends [never] ? false : true, C, NoInput extends IS ? undefined : IS>;
398
399
 
399
400
  type OtherInit = SetupError<"Defined with another init(), so it would run with this registry's scope, not its own. Define it with the init() this createRegistry came from">;
400
401
  /** `createRegistry`'s modules: a function, listener or cron defined with another `init` is an error, since it would run with this one's scope. Events have no `init`. */
@@ -623,6 +624,7 @@ export interface RegisteredListener extends Registered {
623
624
  }
624
625
  export interface RegisteredCron extends Registered {
625
626
  cron: Cron;
627
+ run: Fn;
626
628
  }
627
629
 
628
630
  /** `registry.jobs`: what you call from a queue consumer, a cron, or a script. */