logic-sdk 0.6.1 → 0.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/errors.d.ts +6 -0
- package/dist/errors.js +8 -2
- package/dist/index.js +20 -11
- package/dist/types.d.ts +5 -2
- package/package.json +2 -2
- package/skills/logic-sdk/SKILL.md +2 -2
- package/src/errors.ts +11 -2
- package/src/index.ts +23 -15
- package/src/types.ts +5 -2
package/dist/errors.d.ts
CHANGED
|
@@ -14,6 +14,12 @@ export declare class DomainError extends Error {
|
|
|
14
14
|
}
|
|
15
15
|
/** `isDomainError(e)`, or with a code: `isDomainError(e, "availability.dates_unavailable")`. */
|
|
16
16
|
export declare const isDomainError: (e: unknown, code?: string) => e is DomainError;
|
|
17
|
+
/** The module part of an id: "bookings" for "bookings.confirm". */
|
|
18
|
+
export declare const moduleOf: (id: string) => string;
|
|
19
|
+
/** How an unnamed private function (one its module's index doesn't export) is named: `files.(private)`. */
|
|
20
|
+
export declare const PRIVATE = "(private)";
|
|
21
|
+
/** What a call its policy refused throws: "bookings.cancel.forbidden", and "files.forbidden" for an unnamed private function. */
|
|
22
|
+
export declare const forbiddenOf: (id: string) => string;
|
|
17
23
|
/** `ctx.errors` for one function or listener (`id` like "bookings.confirm"). */
|
|
18
24
|
export declare const errorsFor: (id: string) => Errors;
|
|
19
25
|
/** What a schema said, as JSON: `[{ message, path }]`. */
|
package/dist/errors.js
CHANGED
|
@@ -18,14 +18,20 @@ export class DomainError extends Error {
|
|
|
18
18
|
}
|
|
19
19
|
/** `isDomainError(e)`, or with a code: `isDomainError(e, "availability.dates_unavailable")`. */
|
|
20
20
|
export const isDomainError = (e, code) => e instanceof DomainError && (code === undefined || e.code === code);
|
|
21
|
+
/** The module part of an id: "bookings" for "bookings.confirm". */
|
|
22
|
+
export const moduleOf = (id) => id.slice(0, id.indexOf("."));
|
|
23
|
+
/** How an unnamed private function (one its module's index doesn't export) is named: `files.(private)`. */
|
|
24
|
+
export const PRIVATE = "(private)";
|
|
25
|
+
/** What a call its policy refused throws: "bookings.cancel.forbidden", and "files.forbidden" for an unnamed private function. */
|
|
26
|
+
export const forbiddenOf = (id) => `${id === `${moduleOf(id)}.${PRIVATE}` ? moduleOf(id) : id}.forbidden`;
|
|
21
27
|
/** `ctx.errors` for one function or listener (`id` like "bookings.confirm"). */
|
|
22
28
|
export const errorsFor = (id) => {
|
|
23
|
-
const module =
|
|
29
|
+
const module = moduleOf(id);
|
|
24
30
|
return {
|
|
25
31
|
reject: (code, details) => new DomainError("rejected", `${module}.${code}`, details),
|
|
26
32
|
conflict: (code, details) => new DomainError("conflict", `${module}.${code}`, details),
|
|
27
33
|
notFound: (code = "not_found", details) => new DomainError("not_found", `${module}.${code}`, details),
|
|
28
|
-
deny: (code, details) => new DomainError("forbidden", code ? `${module}.${code}` :
|
|
34
|
+
deny: (code, details) => new DomainError("forbidden", code ? `${module}.${code}` : forbiddenOf(id), details),
|
|
29
35
|
};
|
|
30
36
|
};
|
|
31
37
|
/** What a schema said, as JSON: `[{ message, path }]`. */
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { describeIssues, DomainError, errorsFor } from "./errors.js";
|
|
1
|
+
import { describeIssues, DomainError, errorsFor, forbiddenOf, moduleOf, PRIVATE } from "./errors.js";
|
|
2
2
|
import { inProcess, makeJobs, replaceKeyOf, runsNow } from "./jobs.js";
|
|
3
3
|
import { assertTimeZone, parseSchedule } from "./schedule.js";
|
|
4
4
|
import { BRAND, INTERNAL } from "./types.js";
|
|
@@ -186,9 +186,10 @@ function build(options, o) {
|
|
|
186
186
|
console.error("[logic-sdk] onError threw", inner, "while reporting", e);
|
|
187
187
|
}
|
|
188
188
|
};
|
|
189
|
+
const noDatabase = "[logic-sdk] Mutations need a database: createRegistry({ database: drizzleAdapter(db) }). It needs interactive " +
|
|
190
|
+
"transactions, so Cloudflare D1 and HTTP drivers can't run mutations.";
|
|
189
191
|
if (!database && functions.some((f) => f.kind === "mutation"))
|
|
190
|
-
throw new Error(
|
|
191
|
-
"transactions, so Cloudflare D1 and HTTP drivers can't run mutations.");
|
|
192
|
+
throw new Error(noDatabase);
|
|
192
193
|
for (const l of listeners)
|
|
193
194
|
if (!ids.has(l.event))
|
|
194
195
|
throw new Error(`[logic-sdk] Listener ${l.id} listens to an event that isn't registered in any module.`);
|
|
@@ -196,7 +197,8 @@ function build(options, o) {
|
|
|
196
197
|
const idOf = (x) => {
|
|
197
198
|
const id = ids.get(x);
|
|
198
199
|
if (!id)
|
|
199
|
-
throw new Error("[logic-sdk] This function or event isn't registered. Export it from its module's index.ts, and add the module to createRegistry({ modules })."
|
|
200
|
+
throw new Error("[logic-sdk] This function or event isn't registered. Export it from its module's index.ts, and add the module to createRegistry({ modules }). " +
|
|
201
|
+
"A private function (one the index doesn't export) runs only through ctx.run, from its own module.");
|
|
200
202
|
return id;
|
|
201
203
|
};
|
|
202
204
|
/** Bad input from a caller is their error. Bad input from your own code (a nested call) is a bug. */
|
|
@@ -241,7 +243,7 @@ function build(options, o) {
|
|
|
241
243
|
scope: frame.scope,
|
|
242
244
|
config: config, // Frozen<Cf> here; each app's ctx types it from its own Config
|
|
243
245
|
now,
|
|
244
|
-
run: (fn, input, options) => invoke(fn, input, enter(frame, options), allowed),
|
|
246
|
+
run: (fn, input, options) => invoke(fn, input, enter(frame, options), allowed, moduleOf(id)),
|
|
245
247
|
});
|
|
246
248
|
const queryCtx = (frame, id) => ({
|
|
247
249
|
...baseCtx(frame, id, ["query"]),
|
|
@@ -258,7 +260,10 @@ function build(options, o) {
|
|
|
258
260
|
checkAtCommit(tx, event.payload, envelope.payload, `${envelope.name} payload`, (parsed) => tx.parsed.set(envelope, parsed));
|
|
259
261
|
},
|
|
260
262
|
schedule: (fn, input, { at, delay, attempts = 1, replace }) => {
|
|
261
|
-
const fnId =
|
|
263
|
+
const fnId = ids.get(fn);
|
|
264
|
+
if (!fnId)
|
|
265
|
+
throw new Error("[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. " +
|
|
266
|
+
"A private function runs only through ctx.run.");
|
|
262
267
|
const seconds = at ? (at.getTime() - now().getTime()) / 1000 : (delay ?? NaN);
|
|
263
268
|
if (!Number.isFinite(seconds) || (!at && seconds < 0))
|
|
264
269
|
throw new Error(`[logic-sdk] ctx.schedule(${fnId}) needs an \`at\` date or a \`delay\` in seconds, 0 or more.`);
|
|
@@ -335,8 +340,10 @@ function build(options, o) {
|
|
|
335
340
|
listenerCtx: (scope, eventDepth, id, queued) => actionCtx({ scope, trail: [id], eventDepth, queued }, id),
|
|
336
341
|
});
|
|
337
342
|
// ── invoke ───────────────────────────────────────────────────────────────
|
|
338
|
-
|
|
339
|
-
|
|
343
|
+
/** `callerModule`: set by ctx.run, so a private function (its index doesn't export it) runs as part of the module running it. */
|
|
344
|
+
async function invoke(fn, rawInput, outer, allowed, callerModule) {
|
|
345
|
+
// anything else that runs one finds it by name, and it has none: idOf throws, saying so
|
|
346
|
+
const id = ids.get(fn) ?? (callerModule ? `${callerModule}.${fn.id ?? PRIVATE}` : idOf(fn));
|
|
340
347
|
if (!allowed.includes(fn.kind))
|
|
341
348
|
throw new Error(`[logic-sdk] ${id} is a ${fn.kind}; it can't be run from here (allowed: ${allowed.join(", ")}).`);
|
|
342
349
|
const depth = outer.trail.length;
|
|
@@ -352,7 +359,7 @@ function build(options, o) {
|
|
|
352
359
|
if (fn.authorize) {
|
|
353
360
|
// SAFETY: the registry erases each policy's scope type; the caller's scope is the app's Scope by construction
|
|
354
361
|
if (fn.authorize(frame.scope) !== true)
|
|
355
|
-
throw new DomainError("forbidden",
|
|
362
|
+
throw new DomainError("forbidden", forbiddenOf(id));
|
|
356
363
|
}
|
|
357
364
|
// no `input`: the function takes nothing, whatever an adapter sends (AI tools send `{}`)
|
|
358
365
|
return fn.input ? parseInput(fn.input, rawInput, id, depth > 0) : undefined;
|
|
@@ -385,11 +392,13 @@ function build(options, o) {
|
|
|
385
392
|
}
|
|
386
393
|
// top-level mutation: open the transaction, commit, then deliver events.
|
|
387
394
|
// A lost race (deadlock, serialization failure) re-runs it in a fresh transaction.
|
|
395
|
+
// createRegistry checks for one, but a private mutation isn't registered, so it can only be checked here
|
|
396
|
+
if (!database)
|
|
397
|
+
throw new Error(noDatabase);
|
|
388
398
|
const input = await prepare();
|
|
389
399
|
let committed;
|
|
390
400
|
for (let attempt = 1;; attempt++) {
|
|
391
401
|
try {
|
|
392
|
-
// SAFETY: createRegistry refuses mutations without a database that has interactive transactions
|
|
393
402
|
committed = await database.transaction(async (txDb) => {
|
|
394
403
|
// fresh per attempt, so a retry never reuses events from a failed attempt
|
|
395
404
|
const tx = { db: txDb, doomed: false, reason: undefined, events: [], parsed: new Map(), calls: [], pending: [] };
|
|
@@ -405,7 +414,7 @@ function build(options, o) {
|
|
|
405
414
|
break;
|
|
406
415
|
}
|
|
407
416
|
catch (e) {
|
|
408
|
-
if (attempt < transactionAttempts && database.retryable?.(e)) {
|
|
417
|
+
if (attempt < transactionAttempts && database.retryable?.(e)) {
|
|
409
418
|
// a random pause, so transactions that just deadlocked don't retry in lockstep and collide again
|
|
410
419
|
await new Promise((r) => setTimeout(r, Math.random() * 20 * attempt));
|
|
411
420
|
continue;
|
package/dist/types.d.ts
CHANGED
|
@@ -104,7 +104,10 @@ type FromInit<C extends Config> = {
|
|
|
104
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
|
+
/**
|
|
108
|
+
* Stable id, local to the module: `id: "send"` in `notifications` is `notifications.send`. Defaults to the export name.
|
|
109
|
+
* A private function (the index doesn't export it) is `notifications.(private)` without one.
|
|
110
|
+
*/
|
|
108
111
|
readonly id?: string;
|
|
109
112
|
/** 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
113
|
readonly input: IS;
|
|
@@ -287,7 +290,7 @@ export interface Errors {
|
|
|
287
290
|
conflict(code: string, details?: unknown): DomainError;
|
|
288
291
|
/** It doesn't exist, or isn't visible in this scope. Code defaults to `"<module>.not_found"`. */
|
|
289
292
|
notFound(code?: string, details?: unknown): DomainError;
|
|
290
|
-
/** The caller is known but may not do this. Code defaults to `"<module>.<function>.forbidden"
|
|
293
|
+
/** The caller is known but may not do this. Code defaults to `"<module>.<function>.forbidden"`, or `"<module>.forbidden"` in an unnamed private function. */
|
|
291
294
|
deny(code?: string, details?: unknown): DomainError;
|
|
292
295
|
}
|
|
293
296
|
interface BaseCtx<C extends Config, S> {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "logic-sdk",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.2",
|
|
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.6.
|
|
116
|
+
"@logic-sdk/cli": ">=0.6.2 <0.7.0"
|
|
117
117
|
},
|
|
118
118
|
"peerDependenciesMeta": {
|
|
119
119
|
"@orpc/server": {
|
|
@@ -22,7 +22,7 @@ src/
|
|
|
22
22
|
actions.ts action({...}) network calls: payments, email, AI, webhooks out
|
|
23
23
|
events.ts event({...}) things that happened
|
|
24
24
|
listeners.ts listener({...}) reacting to OTHER modules' events
|
|
25
|
-
data.ts private helpers taking ctx (findBooking(ctx, id))
|
|
25
|
+
data.ts private: helpers taking ctx (findBooking(ctx, id)), can* record checks, and functions the index doesn't export. Never imported by other modules.
|
|
26
26
|
schema.ts tables this module owns. Other modules never read them.
|
|
27
27
|
<module>.test.ts
|
|
28
28
|
```
|
|
@@ -64,7 +64,7 @@ export const cancel = mutation({
|
|
|
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
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
|
-
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.
|
|
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. When an action must write, put the mutation in `data.ts` and `ctx.run` it: the index doesn't export it, so nothing outside the module can skip the action's checks. A private function can't be scheduled, run by a cron, published or run from a test: test it through the action.
|
|
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.
|
|
70
70
|
7. **Record rules are `can*` predicates.** Load through a scoped helper, then `if (!canX(ctx.scope.actor, record)) throw ctx.errors.deny();`. `can*` is sync, its result is always used, and the same predicate feeds UI flags in list queries: `can: { cancel: canCancel(actor, b) }`. A rule that must hold at commit goes in the write's `WHERE` or a `FOR UPDATE` re-select.
|
package/src/errors.ts
CHANGED
|
@@ -29,14 +29,23 @@ export class DomainError extends Error {
|
|
|
29
29
|
export const isDomainError = (e: unknown, code?: string): e is DomainError =>
|
|
30
30
|
e instanceof DomainError && (code === undefined || e.code === code);
|
|
31
31
|
|
|
32
|
+
/** The module part of an id: "bookings" for "bookings.confirm". */
|
|
33
|
+
export const moduleOf = (id: string) => id.slice(0, id.indexOf("."));
|
|
34
|
+
|
|
35
|
+
/** How an unnamed private function (one its module's index doesn't export) is named: `files.(private)`. */
|
|
36
|
+
export const PRIVATE = "(private)";
|
|
37
|
+
|
|
38
|
+
/** What a call its policy refused throws: "bookings.cancel.forbidden", and "files.forbidden" for an unnamed private function. */
|
|
39
|
+
export const forbiddenOf = (id: string) => `${id === `${moduleOf(id)}.${PRIVATE}` ? moduleOf(id) : id}.forbidden`;
|
|
40
|
+
|
|
32
41
|
/** `ctx.errors` for one function or listener (`id` like "bookings.confirm"). */
|
|
33
42
|
export const errorsFor = (id: string): Errors => {
|
|
34
|
-
const module =
|
|
43
|
+
const module = moduleOf(id);
|
|
35
44
|
return {
|
|
36
45
|
reject: (code, details) => new DomainError("rejected", `${module}.${code}`, details),
|
|
37
46
|
conflict: (code, details) => new DomainError("conflict", `${module}.${code}`, details),
|
|
38
47
|
notFound: (code = "not_found", details) => new DomainError("not_found", `${module}.${code}`, details),
|
|
39
|
-
deny: (code, details) => new DomainError("forbidden", code ? `${module}.${code}` :
|
|
48
|
+
deny: (code, details) => new DomainError("forbidden", code ? `${module}.${code}` : forbiddenOf(id), details),
|
|
40
49
|
};
|
|
41
50
|
};
|
|
42
51
|
|
package/src/index.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { describeIssues, DomainError, errorsFor } from "./errors.ts";
|
|
1
|
+
import { describeIssues, DomainError, errorsFor, forbiddenOf, moduleOf, PRIVATE } from "./errors.ts";
|
|
2
2
|
import { inProcess, makeJobs, replaceKeyOf, runsNow } from "./jobs.ts";
|
|
3
3
|
import { assertTimeZone, parseSchedule } from "./schedule.ts";
|
|
4
4
|
import { BRAND, INTERNAL } from "./types.ts";
|
|
@@ -394,11 +394,10 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
|
|
|
394
394
|
}
|
|
395
395
|
};
|
|
396
396
|
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
);
|
|
397
|
+
const noDatabase =
|
|
398
|
+
"[logic-sdk] Mutations need a database: createRegistry({ database: drizzleAdapter(db) }). It needs interactive " +
|
|
399
|
+
"transactions, so Cloudflare D1 and HTTP drivers can't run mutations.";
|
|
400
|
+
if (!database && functions.some((f) => f.kind === "mutation")) throw new Error(noDatabase);
|
|
402
401
|
for (const l of listeners)
|
|
403
402
|
if (!ids.has(l.event))
|
|
404
403
|
throw new Error(`[logic-sdk] Listener ${l.id} listens to an event that isn't registered in any module.`);
|
|
@@ -408,7 +407,8 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
|
|
|
408
407
|
const id = ids.get(x);
|
|
409
408
|
if (!id)
|
|
410
409
|
throw new Error(
|
|
411
|
-
"[logic-sdk] This function or event isn't registered. Export it from its module's index.ts, and add the module to createRegistry({ modules })."
|
|
410
|
+
"[logic-sdk] This function or event isn't registered. Export it from its module's index.ts, and add the module to createRegistry({ modules }). " +
|
|
411
|
+
"A private function (one the index doesn't export) runs only through ctx.run, from its own module.",
|
|
412
412
|
);
|
|
413
413
|
return id;
|
|
414
414
|
};
|
|
@@ -455,7 +455,7 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
|
|
|
455
455
|
scope: frame.scope,
|
|
456
456
|
config: config as any, // Frozen<Cf> here; each app's ctx types it from its own Config
|
|
457
457
|
now,
|
|
458
|
-
run: (fn: Fn, input?: unknown, options?: RunOptions) => invoke(fn, input, enter(frame, options), allowed),
|
|
458
|
+
run: (fn: Fn, input?: unknown, options?: RunOptions) => invoke(fn, input, enter(frame, options), allowed, moduleOf(id)),
|
|
459
459
|
});
|
|
460
460
|
const queryCtx = (frame: Frame, id: string): QueryCtx<any> => ({
|
|
461
461
|
...baseCtx(frame, id, ["query"]),
|
|
@@ -472,7 +472,12 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
|
|
|
472
472
|
checkAtCommit(tx, event.payload, envelope.payload, `${envelope.name} payload`, (parsed) => tx.parsed.set(envelope, parsed));
|
|
473
473
|
},
|
|
474
474
|
schedule: (fn, input, { at, delay, attempts = 1, replace }) => {
|
|
475
|
-
const fnId =
|
|
475
|
+
const fnId = ids.get(fn);
|
|
476
|
+
if (!fnId)
|
|
477
|
+
throw new Error(
|
|
478
|
+
"[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. " +
|
|
479
|
+
"A private function runs only through ctx.run.",
|
|
480
|
+
);
|
|
476
481
|
const seconds = at ? (at.getTime() - now().getTime()) / 1000 : (delay ?? NaN);
|
|
477
482
|
if (!Number.isFinite(seconds) || (!at && seconds < 0))
|
|
478
483
|
throw new Error(`[logic-sdk] ctx.schedule(${fnId}) needs an \`at\` date or a \`delay\` in seconds, 0 or more.`);
|
|
@@ -547,8 +552,10 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
|
|
|
547
552
|
});
|
|
548
553
|
|
|
549
554
|
// ── invoke ───────────────────────────────────────────────────────────────
|
|
550
|
-
|
|
551
|
-
|
|
555
|
+
/** `callerModule`: set by ctx.run, so a private function (its index doesn't export it) runs as part of the module running it. */
|
|
556
|
+
async function invoke(fn: Fn, rawInput: unknown, outer: Frame, allowed: Kind[], callerModule?: string): Promise<any> {
|
|
557
|
+
// anything else that runs one finds it by name, and it has none: idOf throws, saying so
|
|
558
|
+
const id = ids.get(fn) ?? (callerModule ? `${callerModule}.${fn.id ?? PRIVATE}` : idOf(fn));
|
|
552
559
|
if (!allowed.includes(fn.kind))
|
|
553
560
|
throw new Error(`[logic-sdk] ${id} is a ${fn.kind}; it can't be run from here (allowed: ${allowed.join(", ")}).`);
|
|
554
561
|
const depth = outer.trail.length;
|
|
@@ -567,7 +574,7 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
|
|
|
567
574
|
frame.abortOn?.throwIfAborted();
|
|
568
575
|
if (fn.authorize) {
|
|
569
576
|
// SAFETY: the registry erases each policy's scope type; the caller's scope is the app's Scope by construction
|
|
570
|
-
if (fn.authorize(frame.scope as never) !== true) throw new DomainError("forbidden",
|
|
577
|
+
if (fn.authorize(frame.scope as never) !== true) throw new DomainError("forbidden", forbiddenOf(id));
|
|
571
578
|
}
|
|
572
579
|
// no `input`: the function takes nothing, whatever an adapter sends (AI tools send `{}`)
|
|
573
580
|
return fn.input ? parseInput(fn.input, rawInput, id, depth > 0) : undefined;
|
|
@@ -600,12 +607,13 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
|
|
|
600
607
|
|
|
601
608
|
// top-level mutation: open the transaction, commit, then deliver events.
|
|
602
609
|
// A lost race (deadlock, serialization failure) re-runs it in a fresh transaction.
|
|
610
|
+
// createRegistry checks for one, but a private mutation isn't registered, so it can only be checked here
|
|
611
|
+
if (!database) throw new Error(noDatabase);
|
|
603
612
|
const input = await prepare();
|
|
604
613
|
let committed: { out: unknown; events: Envelope[]; jobs: Job[] };
|
|
605
614
|
for (let attempt = 1; ; attempt++) {
|
|
606
615
|
try {
|
|
607
|
-
|
|
608
|
-
committed = await database!.transaction(async (txDb) => {
|
|
616
|
+
committed = await database.transaction(async (txDb) => {
|
|
609
617
|
// fresh per attempt, so a retry never reuses events from a failed attempt
|
|
610
618
|
const tx: TxState = { db: txDb, doomed: false, reason: undefined, events: [], parsed: new Map(), calls: [], pending: [] };
|
|
611
619
|
const out = await execute(input, mutationCtx({ ...frame, tx }, tx, id));
|
|
@@ -617,7 +625,7 @@ function build<S extends object, Mods extends Record<string, object>, Cf = unkno
|
|
|
617
625
|
});
|
|
618
626
|
break;
|
|
619
627
|
} catch (e) {
|
|
620
|
-
if (attempt < transactionAttempts && database
|
|
628
|
+
if (attempt < transactionAttempts && database.retryable?.(e)) {
|
|
621
629
|
// a random pause, so transactions that just deadlocked don't retry in lockstep and collide again
|
|
622
630
|
await new Promise((r) => setTimeout(r, Math.random() * 20 * attempt));
|
|
623
631
|
continue;
|
package/src/types.ts
CHANGED
|
@@ -102,7 +102,10 @@ type FromInit<C extends Config> = { readonly [types]?: { init: (config: C) => vo
|
|
|
102
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
|
+
/**
|
|
106
|
+
* Stable id, local to the module: `id: "send"` in `notifications` is `notifications.send`. Defaults to the export name.
|
|
107
|
+
* A private function (the index doesn't export it) is `notifications.(private)` without one.
|
|
108
|
+
*/
|
|
106
109
|
readonly id?: string;
|
|
107
110
|
/** 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
111
|
readonly input: IS;
|
|
@@ -291,7 +294,7 @@ export interface Errors {
|
|
|
291
294
|
conflict(code: string, details?: unknown): DomainError;
|
|
292
295
|
/** It doesn't exist, or isn't visible in this scope. Code defaults to `"<module>.not_found"`. */
|
|
293
296
|
notFound(code?: string, details?: unknown): DomainError;
|
|
294
|
-
/** The caller is known but may not do this. Code defaults to `"<module>.<function>.forbidden"
|
|
297
|
+
/** The caller is known but may not do this. Code defaults to `"<module>.<function>.forbidden"`, or `"<module>.forbidden"` in an unnamed private function. */
|
|
295
298
|
deny(code?: string, details?: unknown): DomainError;
|
|
296
299
|
}
|
|
297
300
|
interface BaseCtx<C extends Config, S> {
|