logic-sdk 0.2.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -9
- package/dist/ai.d.ts +2 -5
- package/dist/ai.js +7 -5
- package/dist/fetch.d.ts +2 -4
- package/dist/fetch.js +1 -2
- package/dist/index.d.ts +140 -159
- package/dist/index.js +96 -77
- package/dist/orpc.d.ts +2 -5
- package/dist/orpc.js +5 -5
- package/dist/testing.d.ts +10 -8
- package/dist/testing.js +2 -1
- package/package.json +5 -5
- package/src/ai.ts +12 -11
- package/src/drizzle.ts +1 -1
- package/src/fetch.ts +3 -6
- package/src/index.ts +249 -153
- package/src/orpc.ts +6 -7
- package/src/testing.ts +18 -15
package/README.md
CHANGED
|
@@ -32,15 +32,15 @@ Write a module:
|
|
|
32
32
|
// src/bookings/mutations.ts
|
|
33
33
|
export const confirm = mutation({
|
|
34
34
|
description: "Confirm a pending booking",
|
|
35
|
-
|
|
36
|
-
|
|
35
|
+
input: z.object({ bookingId: z.uuid() }),
|
|
36
|
+
output: Booking,
|
|
37
37
|
// Who may call it, on every call
|
|
38
38
|
authorize: staff,
|
|
39
39
|
// HTTP, oRPC and AI tools may publish it
|
|
40
40
|
expose: true,
|
|
41
41
|
|
|
42
|
-
async
|
|
43
|
-
const booking = await findBooking(ctx, bookingId);
|
|
42
|
+
async handler(ctx, input) {
|
|
43
|
+
const booking = await findBooking(ctx, input.bookingId);
|
|
44
44
|
if (booking.status !== "pending") {
|
|
45
45
|
throw ctx.errors.reject("not_pending");
|
|
46
46
|
}
|
|
@@ -49,7 +49,7 @@ export const confirm = mutation({
|
|
|
49
49
|
await ctx.run(availability.hold, rangeOf(booking));
|
|
50
50
|
|
|
51
51
|
// Delivered to listeners only after commit
|
|
52
|
-
ctx.emit(confirmed, { bookingId });
|
|
52
|
+
ctx.emit(confirmed, { bookingId: input.bookingId });
|
|
53
53
|
|
|
54
54
|
return setStatus(ctx, booking.id, "confirmed");
|
|
55
55
|
},
|
|
@@ -80,6 +80,7 @@ await caller.run(bookings.confirm, { bookingId });
|
|
|
80
80
|
- **Authorization on every call.** `authorize` runs whoever calls: HTTP, an agent, a job or another function. Record rules are sync `can*` predicates the CLI checks.
|
|
81
81
|
- **Internal by default.** Only `expose: true` functions reach HTTP, RPC or AI tools, with a required policy and output contract.
|
|
82
82
|
- **Agents included.** `toAITool` gives an agent your functions, under the same policies and transactions as your API. Opt-in, one function at a time or by `filter`.
|
|
83
|
+
- **Settings in one place.** Declare `config` once, fill it from env at the entry, read `ctx.config` anywhere. The CLI fails the build if a module reads env.
|
|
83
84
|
- **Errors without HTTP.** `ctx.errors.reject`, `conflict`, `notFound`, `deny`; adapters map them to statuses.
|
|
84
85
|
- **Tests without mocks.** Each test is a real transaction on a real database, always rolled back.
|
|
85
86
|
- **No magic.** No decorators, classes, codegen, build step or `AsyncLocalStorage`.
|
|
@@ -108,9 +109,8 @@ Read-only, `--json` everywhere, exit codes for CI. The `logic-sdk` command ships
|
|
|
108
109
|
|
|
109
110
|
## Examples
|
|
110
111
|
|
|
111
|
-
- [`examples/
|
|
112
|
-
- [`examples/
|
|
113
|
-
- [`examples/nextjs`](examples/nextjs): a Server Action and an AI agent calling the same `bookings.confirm`.
|
|
112
|
+
- [`examples/shop`](examples/shop): start here. A shop written once and run on Node, Cloudflare Workers and Next.js, with an AI assistant.
|
|
113
|
+
- [`examples/bookings`](examples/bookings): a bigger app. Six modules, Hono, Postgres, and a race test on real Postgres.
|
|
114
114
|
|
|
115
115
|
## Docs
|
|
116
116
|
|
|
@@ -123,7 +123,7 @@ bun install
|
|
|
123
123
|
bun run test # build, typecheck, lint, package checks, all tests
|
|
124
124
|
```
|
|
125
125
|
|
|
126
|
-
`packages/logic-sdk` is the library, tested with `bun test`. `examples/
|
|
126
|
+
`packages/logic-sdk` is the library, tested with `bun test`. `examples/bookings` runs on PGlite by default and on real Postgres with `DATABASE_URL` (`bun run test:pg`), which CI always sets. `examples/shop` also runs its Worker inside workerd. Decisions and their reasons are in [DESIGN.md](DESIGN.md); what's next is in [ROADMAP.md](ROADMAP.md).
|
|
127
127
|
|
|
128
128
|
## License
|
|
129
129
|
|
package/dist/ai.d.ts
CHANGED
|
@@ -1,8 +1,5 @@
|
|
|
1
1
|
import { type Tool } from "ai";
|
|
2
|
-
import { type Caller, type
|
|
3
|
-
type ExposedOf<T> = {
|
|
4
|
-
[N in keyof T as T[N] extends Fn<any, any, any, true> ? N : never]: T[N];
|
|
5
|
-
};
|
|
2
|
+
import { type Caller, type ExposedFn, type ExposedOf, type FnIn, type FnOut, type Registry, type RegisteredFn } from "./index.ts";
|
|
6
3
|
type UnionToIntersection<U> = (U extends unknown ? (u: U) => void : never) extends (i: infer I) => void ? I : never;
|
|
7
4
|
/** `{ bookings_confirm, pricing_priceStay, … }`: one AI SDK tool per exposed function, typed. */
|
|
8
5
|
export type AIToolsOf<Mods> = UnionToIntersection<{
|
|
@@ -33,7 +30,7 @@ export interface AIToolsOptions extends AIToolOptions {
|
|
|
33
30
|
* Domain errors reach the model (it sees the code and can react). Anything unexpected is reported
|
|
34
31
|
* to `onError` and the model gets "internal_error", so internals never land in its context.
|
|
35
32
|
*/
|
|
36
|
-
export declare function toAITool<F extends
|
|
33
|
+
export declare function toAITool<F extends ExposedFn>(caller: Caller<object>, fn: F, options?: AIToolOptions): Tool<FnIn<F>, FnOut<F>>;
|
|
37
34
|
/**
|
|
38
35
|
* The exposed functions your `filter` picks, as AI SDK tools named `<module>_<function>`.
|
|
39
36
|
*
|
package/dist/ai.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
import { tool } from "ai";
|
|
1
|
+
import { jsonSchema, tool } from "ai";
|
|
2
2
|
import { isDomainError } from "./index.js";
|
|
3
|
+
/** What a function without input looks like to the model: an object with nothing in it. It sends `{}`, which run ignores. */
|
|
4
|
+
const noInput = jsonSchema({ type: "object", properties: {}, additionalProperties: false });
|
|
3
5
|
/**
|
|
4
6
|
* One exposed function as an AI SDK tool, run as `caller`: the agent goes through the same policy,
|
|
5
7
|
* validation, transaction and events as your HTTP API. You name it, like any AI SDK tool.
|
|
@@ -18,11 +20,11 @@ export function toAITool(caller, fn, options = {}) {
|
|
|
18
20
|
throw new Error("[logic-sdk] toAITool needs a function with expose: true.");
|
|
19
21
|
return tool({
|
|
20
22
|
description: fn.description,
|
|
21
|
-
inputSchema: fn.
|
|
22
|
-
outputSchema: fn.
|
|
23
|
-
async execute(input) {
|
|
23
|
+
inputSchema: fn.input ?? noInput,
|
|
24
|
+
outputSchema: fn.output,
|
|
25
|
+
async execute(input, { abortSignal }) {
|
|
24
26
|
try {
|
|
25
|
-
return await caller.run(fn, input);
|
|
27
|
+
return await caller.run(fn, input, { signal: abortSignal });
|
|
26
28
|
}
|
|
27
29
|
catch (e) {
|
|
28
30
|
if (isDomainError(e))
|
package/dist/fetch.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { DomainError, type
|
|
1
|
+
import { DomainError, type ErrorKind, type Registry } from "./index.ts";
|
|
2
2
|
/**
|
|
3
3
|
* Throw from `resolveScope` when this mount is session-only and there's no valid session: the client gets 401.
|
|
4
4
|
* For mounts that also serve public functions, return a scope with no actor instead, and let policies answer 403.
|
|
@@ -9,8 +9,6 @@ export declare const statusOf: Record<ErrorKind, number>;
|
|
|
9
9
|
export interface FetchOptions<S extends object> {
|
|
10
10
|
/** Build the scope for this request (session → actor, account, locale...). */
|
|
11
11
|
resolveScope: (request: Request, ...rest: any[]) => S | Promise<S>;
|
|
12
|
-
/** Per-request caller options, e.g. `(req) => ({ signal: req.signal })`. */
|
|
13
|
-
callerOptions?: (request: Request, ...rest: any[]) => CallerOptions;
|
|
14
12
|
/** Mount point. Default "/". Functions live at `${basePath}${id}`, e.g. `/api/bookings.confirm`. */
|
|
15
13
|
basePath?: string;
|
|
16
14
|
/** Unexpected (non-domain) errors. Default: console.error. */
|
|
@@ -21,4 +19,4 @@ export interface FetchOptions<S extends object> {
|
|
|
21
19
|
* Publishes only functions with `expose: true`. POST `{base}{id}` with a JSON body (`content-type: application/json` required);
|
|
22
20
|
* queries also accept GET `?input=<json>`.
|
|
23
21
|
*/
|
|
24
|
-
export declare function toFetchHandler<S extends object>(registry: Registry<S
|
|
22
|
+
export declare function toFetchHandler<S extends object>(registry: Registry<S>, options: FetchOptions<S>): (request: Request, ...rest: any[]) => Promise<Response>;
|
package/dist/fetch.js
CHANGED
|
@@ -55,8 +55,7 @@ export function toFetchHandler(registry, options) {
|
|
|
55
55
|
}
|
|
56
56
|
try {
|
|
57
57
|
const scope = await options.resolveScope(request, ...rest);
|
|
58
|
-
|
|
59
|
-
return json({ data: await caller.run(entry.fn, input) });
|
|
58
|
+
return json({ data: await registry.as(scope).run(entry.fn, input, { signal: request.signal }) });
|
|
60
59
|
}
|
|
61
60
|
catch (e) {
|
|
62
61
|
if (isDomainError(e))
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { StandardSchemaV1 } from "@standard-schema/spec";
|
|
2
2
|
type Schema<I = any, O = any> = StandardSchemaV1<I, O>;
|
|
3
|
-
type In<S> = S extends
|
|
4
|
-
type Out<S> = S extends
|
|
3
|
+
type In<S> = S extends StandardSchemaV1<infer I, unknown> ? I : never;
|
|
4
|
+
type Out<S> = S extends StandardSchemaV1<unknown, infer O> ? O : never;
|
|
5
5
|
/** What you declare once in `init<...>()`. */
|
|
6
6
|
export interface Config {
|
|
7
7
|
/** Who and where: actor, account, locale... Must be JSON-serializable (it travels with events). */
|
|
@@ -12,6 +12,11 @@ export interface Config {
|
|
|
12
12
|
reader?: unknown;
|
|
13
13
|
/** Side-effecting services (mailer, payments...). Only actions and listeners receive them. */
|
|
14
14
|
services?: object;
|
|
15
|
+
/**
|
|
16
|
+
* Your app's settings, read as `ctx.config` in every function: base URL, limits, switches. Plain data, read-only.
|
|
17
|
+
* Build it once from your env at the entry; clients built from secrets go in `services` instead.
|
|
18
|
+
*/
|
|
19
|
+
config?: object;
|
|
15
20
|
/** The shape of `meta` on your functions (tags, rate limits, "agent may call"...). Read by `wrap` and adapters. */
|
|
16
21
|
meta?: object;
|
|
17
22
|
}
|
|
@@ -28,23 +33,38 @@ type ServicesOf<C extends Config> = C extends {
|
|
|
28
33
|
type MetaOf<C extends Config> = C extends {
|
|
29
34
|
meta: infer M;
|
|
30
35
|
} ? M : never;
|
|
36
|
+
/** Without a declared `config`, nothing may be passed or read: no silently ignored settings. */
|
|
37
|
+
type ConfigOf<C extends Config> = C extends {
|
|
38
|
+
config: infer F;
|
|
39
|
+
} ? F : Record<string, never>;
|
|
40
|
+
type Primitive = string | number | boolean | bigint | symbol | null | undefined;
|
|
41
|
+
/** Read-only all the way down: what `ctx.config` gives you. Primitives (branded ones too) stay as they are. */
|
|
42
|
+
export type Frozen<T> = T extends Primitive ? T : T extends readonly (infer U)[] ? readonly Frozen<U>[] : {
|
|
43
|
+
readonly [K in keyof T]: Frozen<T[K]>;
|
|
44
|
+
};
|
|
45
|
+
/** Any part of `T`, at any depth: what a test may override in `config`. Arrays are replaced whole, like at runtime. */
|
|
46
|
+
export type DeepPartial<T> = T extends Primitive | readonly unknown[] ? T : {
|
|
47
|
+
[K in keyof T]?: DeepPartial<T[K]>;
|
|
48
|
+
};
|
|
31
49
|
export type Kind = "query" | "mutation" | "action";
|
|
32
50
|
declare const types: unique symbol;
|
|
33
51
|
declare const BRAND: unique symbol;
|
|
34
52
|
/** A query, mutation or action. Call it with `caller.run(fn, input)` or `ctx.run(fn, input)`. */
|
|
35
|
-
export interface Fn<K extends Kind = Kind, I =
|
|
53
|
+
export interface Fn<K extends Kind = Kind, I = unknown, O = unknown, E extends boolean = boolean> {
|
|
36
54
|
readonly [BRAND]: K;
|
|
37
55
|
readonly kind: K;
|
|
38
56
|
readonly description: string;
|
|
39
|
-
|
|
40
|
-
readonly
|
|
57
|
+
/** What callers pass, validated on every call. Left out: the function takes nothing (`run(fn)`). */
|
|
58
|
+
readonly input?: Schema;
|
|
59
|
+
/** What callers get back, checked before it leaves. */
|
|
60
|
+
readonly output?: Schema;
|
|
41
61
|
/** Your own data about the function. Checked against `meta` in `init` where you set it, typed in `wrap`; loose here, for adapters. */
|
|
42
|
-
readonly meta?:
|
|
62
|
+
readonly meta?: Readonly<Record<string, unknown>>;
|
|
43
63
|
/** Who may call it (from `authorize`). Runs on every call, before validation. */
|
|
44
|
-
readonly authorize?: Policy<
|
|
45
|
-
/** `true`: adapters may publish it (HTTP, oRPC, AI tools). Requires `authorize` and `
|
|
64
|
+
readonly authorize?: Policy<never>;
|
|
65
|
+
/** `true`: adapters may publish it (HTTP, oRPC, AI tools). Requires `authorize` and `output`. */
|
|
46
66
|
readonly expose?: true;
|
|
47
|
-
readonly
|
|
67
|
+
readonly handler: (ctx: never, input: never) => Promise<unknown>;
|
|
48
68
|
/** Phantom types, never set at runtime. */
|
|
49
69
|
readonly [types]?: {
|
|
50
70
|
input: I;
|
|
@@ -52,17 +72,22 @@ export interface Fn<K extends Kind = Kind, I = any, O = any, E extends boolean =
|
|
|
52
72
|
exposed: E;
|
|
53
73
|
};
|
|
54
74
|
}
|
|
75
|
+
/** The exposed functions of one module: what adapters publish. */
|
|
76
|
+
export type ExposedOf<T> = {
|
|
77
|
+
[N in keyof T as T[N] extends Fn<Kind, unknown, unknown, true> ? N : never]: T[N];
|
|
78
|
+
};
|
|
55
79
|
/** A function with `expose: true`: adapters may publish it. */
|
|
56
|
-
export type ExposedFn<K extends Kind = Kind, I =
|
|
80
|
+
export type ExposedFn<K extends Kind = Kind, I = unknown, O = unknown> = Fn<K, I, O, true>;
|
|
57
81
|
/** What callers pass to a function. */
|
|
58
|
-
export type FnIn<F> = F extends Fn<
|
|
82
|
+
export type FnIn<F> = F extends Fn<Kind, infer I, unknown> ? I : never;
|
|
59
83
|
/** What a function returns. */
|
|
60
|
-
export type FnOut<F> = F extends Fn<
|
|
61
|
-
/** `I`: what `emit` takes. `O`: what listeners receive (after the schema's transforms and defaults). */
|
|
62
|
-
export interface EventDef<I =
|
|
84
|
+
export type FnOut<F> = F extends Fn<Kind, unknown, infer O> ? O : never;
|
|
85
|
+
/** `I`: what `emit` takes. `O`: what listeners receive (after the payload schema's transforms and defaults). */
|
|
86
|
+
export interface EventDef<I = unknown, O = I> {
|
|
63
87
|
readonly [BRAND]: "event";
|
|
64
88
|
readonly kind: "event";
|
|
65
|
-
|
|
89
|
+
/** The payload's schema, checked when emitted and again at delivery. */
|
|
90
|
+
readonly payload: Schema;
|
|
66
91
|
readonly description?: string;
|
|
67
92
|
readonly [types]?: {
|
|
68
93
|
input: I;
|
|
@@ -71,7 +96,7 @@ export interface EventDef<I = any, O = I> {
|
|
|
71
96
|
}
|
|
72
97
|
/**
|
|
73
98
|
* What a dispatcher stores and delivers. Fully JSON: `payload` is what was emitted (validated),
|
|
74
|
-
* and listeners get it parsed again by the event's schema at delivery.
|
|
99
|
+
* and listeners get it parsed again by the event's payload schema at delivery.
|
|
75
100
|
*/
|
|
76
101
|
export interface Envelope<P = unknown, S = object> {
|
|
77
102
|
id: string;
|
|
@@ -80,15 +105,30 @@ export interface Envelope<P = unknown, S = object> {
|
|
|
80
105
|
scope: S;
|
|
81
106
|
occurredAt: string;
|
|
82
107
|
}
|
|
83
|
-
export interface Listener<O =
|
|
108
|
+
export interface Listener<O = unknown> {
|
|
84
109
|
readonly [BRAND]: "listener";
|
|
85
110
|
readonly kind: "listener";
|
|
86
111
|
/** Lazy, so listeners can import other modules' barrels without import cycles. */
|
|
87
|
-
readonly event: () => EventDef<
|
|
112
|
+
readonly event: () => EventDef<unknown, O>;
|
|
88
113
|
readonly description?: string;
|
|
89
|
-
readonly
|
|
114
|
+
readonly handler: (ctx: never, payload: O) => Promise<unknown>;
|
|
115
|
+
}
|
|
116
|
+
/** What a single call may change: who it runs as (part of the scope) and when to give up. Nothing else. */
|
|
117
|
+
export interface RunOptions<S = object> {
|
|
118
|
+
/**
|
|
119
|
+
* Merged over the current scope for this call and everything it runs: `{ scope: { actor: system } }` to act as
|
|
120
|
+
* someone else on purpose, `{ scope: { locale: "es" } }` to render in another language. The callee's policy sees it.
|
|
121
|
+
*/
|
|
122
|
+
scope?: Partial<S>;
|
|
123
|
+
/**
|
|
124
|
+
* Checked before this call starts. Inside, actions get it as `ctx.signal` to pass on (`fetch(url, { signal })`).
|
|
125
|
+
* Never checked between your steps, so a caller who gives up can't leave a workflow half done.
|
|
126
|
+
*/
|
|
127
|
+
signal?: AbortSignal;
|
|
90
128
|
}
|
|
91
|
-
|
|
129
|
+
/** `run(fn, input, options?)`, or `run(fn)` for a function that takes no input. */
|
|
130
|
+
export type RunArgs<F, S> = undefined extends FnIn<F> ? [input?: FnIn<F>, options?: RunOptions<S>] : [input: FnIn<F>, options?: RunOptions<S>];
|
|
131
|
+
type Run<Allowed extends Kind, S> = <F extends Fn<Allowed>>(fn: F, ...args: RunArgs<F, S>) => Promise<FnOut<F>>;
|
|
92
132
|
/**
|
|
93
133
|
* Expected failures, namespaced to the module you're in: inside `bookings`, `ctx.errors.reject("not_pending")` has
|
|
94
134
|
* code `"bookings.not_pending"`. Throw what they return. Codes are plain strings on purpose (see the errors docs).
|
|
@@ -103,36 +143,37 @@ export interface Errors {
|
|
|
103
143
|
/** The caller is known but may not do this. Code defaults to `"<module>.<function>.forbidden"`. */
|
|
104
144
|
deny(code?: string, details?: unknown): DomainError;
|
|
105
145
|
}
|
|
106
|
-
interface BaseCtx<S> {
|
|
146
|
+
interface BaseCtx<C extends Config, S> {
|
|
107
147
|
scope: S;
|
|
148
|
+
/** Your settings from `createRegistry({ config })`. Read-only; tests override parts of it. */
|
|
149
|
+
config: Frozen<ConfigOf<C>>;
|
|
108
150
|
/** Expected failures: `throw ctx.errors.reject("not_pending")`. */
|
|
109
151
|
errors: Errors;
|
|
110
152
|
/** Current time. Fixed in tests. */
|
|
111
153
|
now: () => Date;
|
|
112
154
|
}
|
|
113
|
-
/** `S` is the scope, narrowed by the function's policy. Alias it
|
|
114
|
-
export interface QueryCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<S> {
|
|
155
|
+
/** `S` is the scope, narrowed by the function's policy. Alias it next to `init`: `type QueryCtx = QueryCtx<Config>`. */
|
|
156
|
+
export interface QueryCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C, S> {
|
|
115
157
|
db: ReaderOf<C>;
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
signal: AbortSignal | undefined;
|
|
119
|
-
with(patch: Partial<ScopeOf<C>>): QueryCtx<C>;
|
|
158
|
+
/** Call another query, with its policy, validation and output check: `await ctx.run(pricing.quote, { nights })`. */
|
|
159
|
+
run: Run<"query", ScopeOf<C>>;
|
|
120
160
|
}
|
|
121
|
-
export interface MutationCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<S> {
|
|
161
|
+
export interface MutationCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C, S> {
|
|
122
162
|
db: DbOf<C>;
|
|
123
|
-
|
|
163
|
+
/**
|
|
164
|
+
* Call a query or mutation inside this same transaction, with its policy and validation:
|
|
165
|
+
* `await ctx.run(availability.hold, { propertyId })`. If it fails, the whole transaction rolls back.
|
|
166
|
+
*/
|
|
167
|
+
run: Run<"query" | "mutation", ScopeOf<C>>;
|
|
124
168
|
/** Queue an event. Delivered to listeners only after the transaction commits. */
|
|
125
|
-
emit<I>(event: EventDef<I,
|
|
126
|
-
signal: AbortSignal | undefined;
|
|
127
|
-
with(patch: Partial<ScopeOf<C>>): MutationCtx<C>;
|
|
169
|
+
emit<I>(event: EventDef<I, unknown>, payload: I): void;
|
|
128
170
|
}
|
|
129
|
-
export interface ActionCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<S> {
|
|
171
|
+
export interface ActionCtx<C extends Config, S = ScopeOf<C>> extends BaseCtx<C, S> {
|
|
130
172
|
services: ServicesOf<C>;
|
|
131
|
-
/** Each mutation you run
|
|
132
|
-
run: Run<Kind
|
|
133
|
-
/** The caller's abort signal. Always undefined in listeners (they outlive the request). */
|
|
173
|
+
/** Call any function: `await ctx.run(bookings.confirmPaid, { bookingId })`. Each mutation you run commits on its own. */
|
|
174
|
+
run: Run<Kind, ScopeOf<C>>;
|
|
175
|
+
/** The caller's abort signal: pass it on, `fetch(url, { signal: ctx.signal })`. Always undefined in listeners (they outlive the request). */
|
|
134
176
|
signal: AbortSignal | undefined;
|
|
135
|
-
with(patch: Partial<ScopeOf<C>>): ActionCtx<C>;
|
|
136
177
|
}
|
|
137
178
|
export interface ListenerCtx<C extends Config, O = unknown> extends ActionCtx<C> {
|
|
138
179
|
event: Envelope<unknown, ScopeOf<C>> & {
|
|
@@ -141,17 +182,20 @@ export interface ListenerCtx<C extends Config, O = unknown> extends ActionCtx<C>
|
|
|
141
182
|
}
|
|
142
183
|
/**
|
|
143
184
|
* Who may call a function at all: signed in, admin, staff. Sync, reads only the scope, returns exactly `true` to allow.
|
|
144
|
-
* Write it as a type guard (`(s): s is Admin => ...`) to narrow `ctx.scope` in `
|
|
145
|
-
* Rules about one record ("only the owner may cancel") go in `
|
|
185
|
+
* Write it as a type guard (`(s): s is Admin => ...`) to narrow `ctx.scope` in `handler`.
|
|
186
|
+
* Rules about one record ("only the owner may cancel") go in `handler`, after loading it.
|
|
146
187
|
*/
|
|
147
188
|
export type Policy<S> = (scope: S) => boolean;
|
|
148
189
|
type Guarded<F, S> = F extends (scope: any) => scope is infer G ? G : S;
|
|
149
190
|
type CtxOf<C extends Config, K extends Kind, S> = K extends "query" ? QueryCtx<C, S> : K extends "mutation" ? MutationCtx<C, S> : ActionCtx<C, S>;
|
|
191
|
+
/** What a function without `input` gets: nothing. */
|
|
192
|
+
type NoInput = StandardSchemaV1<undefined, undefined>;
|
|
150
193
|
type Def<IS extends Schema, Ctx, R> = {
|
|
151
194
|
/** One sentence, shown to humans, adapters and AI tools. */
|
|
152
195
|
description: string;
|
|
153
|
-
|
|
154
|
-
|
|
196
|
+
/** What callers pass, validated on every call. Leave it out when the function takes nothing. */
|
|
197
|
+
input?: IS;
|
|
198
|
+
handler: (ctx: Ctx, input: Out<IS>) => Promise<R>;
|
|
155
199
|
};
|
|
156
200
|
type NotExposed = {
|
|
157
201
|
expose?: undefined;
|
|
@@ -163,25 +207,25 @@ type WithMeta<C extends Config> = {
|
|
|
163
207
|
meta?: MetaOf<C>;
|
|
164
208
|
};
|
|
165
209
|
type WithOutput<OS extends Schema> = {
|
|
166
|
-
|
|
210
|
+
output: OS;
|
|
167
211
|
};
|
|
168
212
|
/**
|
|
169
|
-
* `expose: true` needs `authorize` and `
|
|
213
|
+
* `expose: true` needs `authorize` and `output`: you can't publish something without saying who may call it,
|
|
170
214
|
* and what leaves your process is a contract. Internal functions may skip both; `authorize` still runs if set.
|
|
171
215
|
*/
|
|
172
216
|
interface Constructor<C extends Config, K extends Kind> {
|
|
173
|
-
<IS extends Schema, OS extends Schema, P extends Policy<ScopeOf<C>>>(def: Def<IS, CtxOf<C, K, Guarded<P, ScopeOf<C>>>, In<OS>> & WithOutput<OS> & WithMeta<C> & {
|
|
217
|
+
<IS extends Schema = NoInput, OS extends Schema = Schema, P extends Policy<ScopeOf<C>> = Policy<ScopeOf<C>>>(def: Def<IS, CtxOf<C, K, Guarded<P, ScopeOf<C>>>, In<OS>> & WithOutput<OS> & WithMeta<C> & {
|
|
174
218
|
authorize: P;
|
|
175
219
|
expose: true;
|
|
176
220
|
}): Fn<K, In<IS>, Out<OS>, true>;
|
|
177
|
-
<IS extends Schema, OS extends Schema, P extends Policy<ScopeOf<C>>>(def: Def<IS, CtxOf<C, K, Guarded<P, ScopeOf<C>>>, In<OS>> & WithOutput<OS> & WithMeta<C> & {
|
|
221
|
+
<IS extends Schema = NoInput, OS extends Schema = Schema, P extends Policy<ScopeOf<C>> = Policy<ScopeOf<C>>>(def: Def<IS, CtxOf<C, K, Guarded<P, ScopeOf<C>>>, In<OS>> & WithOutput<OS> & WithMeta<C> & {
|
|
178
222
|
authorize: P;
|
|
179
223
|
} & NotExposed): Fn<K, In<IS>, Out<OS>, false>;
|
|
180
|
-
<IS extends Schema, R, P extends Policy<ScopeOf<C>>>(def: Def<IS, CtxOf<C, K, Guarded<P, ScopeOf<C>>>, R> & WithMeta<C> & {
|
|
224
|
+
<IS extends Schema = NoInput, R = unknown, P extends Policy<ScopeOf<C>> = Policy<ScopeOf<C>>>(def: Def<IS, CtxOf<C, K, Guarded<P, ScopeOf<C>>>, R> & WithMeta<C> & {
|
|
181
225
|
authorize: P;
|
|
182
226
|
} & NotExposed): Fn<K, In<IS>, R, false>;
|
|
183
|
-
<IS extends Schema, OS extends Schema>(def: Def<IS, CtxOf<C, K, ScopeOf<C>>, In<OS>> & WithOutput<OS> & WithMeta<C> & NoPolicy & NotExposed): Fn<K, In<IS>, Out<OS>, false>;
|
|
184
|
-
<IS extends Schema, R>(def: Def<IS, CtxOf<C, K, ScopeOf<C>>, R> & WithMeta<C> & NoPolicy & NotExposed): Fn<K, In<IS>, R, false>;
|
|
227
|
+
<IS extends Schema = NoInput, OS extends Schema = Schema>(def: Def<IS, CtxOf<C, K, ScopeOf<C>>, In<OS>> & WithOutput<OS> & WithMeta<C> & NoPolicy & NotExposed): Fn<K, In<IS>, Out<OS>, false>;
|
|
228
|
+
<IS extends Schema = NoInput, R = unknown>(def: Def<IS, CtxOf<C, K, ScopeOf<C>>, R> & WithMeta<C> & NoPolicy & NotExposed): Fn<K, In<IS>, R, false>;
|
|
185
229
|
}
|
|
186
230
|
export type ErrorKind = "invalid" | "unauthenticated" | "forbidden" | "not_found" | "conflict" | "rejected";
|
|
187
231
|
/**
|
|
@@ -228,8 +272,10 @@ export interface Call<M = unknown> {
|
|
|
228
272
|
export interface RegistryOptions<Mods extends Record<string, object>> {
|
|
229
273
|
/** One entry per module: `{ bookings, availability }` with `import * as bookings from "./bookings"`. */
|
|
230
274
|
modules: Mods;
|
|
231
|
-
database?: DatabaseAdapter<
|
|
275
|
+
database?: DatabaseAdapter<unknown, unknown>;
|
|
232
276
|
services?: object;
|
|
277
|
+
/** Settings every function reads as `ctx.config`. Plain data: it's copied and frozen. */
|
|
278
|
+
config?: object;
|
|
233
279
|
events?: Dispatcher;
|
|
234
280
|
/** Wraps every call, including ones that fail validation or authorization: logging, tracing, audit. */
|
|
235
281
|
wrap?: (call: Call, next: () => Promise<unknown>) => Promise<unknown>;
|
|
@@ -256,15 +302,11 @@ export interface RegistryOptions<Mods extends Record<string, object>> {
|
|
|
256
302
|
attempts?: number;
|
|
257
303
|
};
|
|
258
304
|
}
|
|
259
|
-
|
|
260
|
-
/** Aborts the call before it starts work. Listeners never get it: they outlive the request. */
|
|
261
|
-
signal?: AbortSignal;
|
|
262
|
-
}
|
|
263
|
-
/** A registry bound to a scope: `const caller = registry.as(scope)`. */
|
|
305
|
+
/** A registry bound to who is calling: `const caller = registry.as(scope)`. */
|
|
264
306
|
export interface Caller<S extends object = object> {
|
|
265
307
|
readonly scope: S;
|
|
266
|
-
|
|
267
|
-
|
|
308
|
+
/** Run any function as this caller: `await caller.run(bookings.cancel, input, { signal: request.signal })`. */
|
|
309
|
+
run<F extends Fn>(fn: F, ...args: RunArgs<F, S>): Promise<FnOut<F>>;
|
|
268
310
|
}
|
|
269
311
|
export interface Registered {
|
|
270
312
|
id: string;
|
|
@@ -284,10 +326,14 @@ type TypedOptions<C extends Config, Mods extends Record<string, object>> = Omit<
|
|
|
284
326
|
services?: ServicesOf<C>;
|
|
285
327
|
} : {
|
|
286
328
|
services: ServicesOf<C>;
|
|
329
|
+
}) & ({} extends ConfigOf<C> ? {
|
|
330
|
+
config?: ConfigOf<C>;
|
|
331
|
+
} : {
|
|
332
|
+
config: ConfigOf<C>;
|
|
287
333
|
}) & ([DbOf<C>] extends [never] ? {
|
|
288
334
|
database?: undefined;
|
|
289
335
|
} : {
|
|
290
|
-
database: DatabaseAdapter<
|
|
336
|
+
database: DatabaseAdapter<unknown, DbOf<C>>;
|
|
291
337
|
});
|
|
292
338
|
/** Keys `Config` doesn't know are errors, so a typo like `servises` can't be silently ignored. */
|
|
293
339
|
type OnlyKnownKeys<C> = {
|
|
@@ -302,30 +348,7 @@ type OnlyKnownKeys<C> = {
|
|
|
302
348
|
*/
|
|
303
349
|
export declare function init<C extends Config & OnlyKnownKeys<C>>(): {
|
|
304
350
|
/** Create the registry once at startup: `createRegistry({ modules, database, services })`. */
|
|
305
|
-
createRegistry: <const Mods extends Record<string, object>>(options: TypedOptions<C, Mods>) =>
|
|
306
|
-
/** The modules you registered (typed), for adapters that build typed routers. */
|
|
307
|
-
modules: Mods;
|
|
308
|
-
/** Bind who is calling, once per request, job or test: `const caller = registry.as(scope)`. */
|
|
309
|
-
as: (scope: ScopeOf<C>, opts?: CallerOptions) => Caller<ScopeOf<C>>;
|
|
310
|
-
/** Everything the registry can do. Adapters read this. */
|
|
311
|
-
functions: readonly RegisteredFn[];
|
|
312
|
-
events: readonly (Registered & {
|
|
313
|
-
event: EventDef;
|
|
314
|
-
})[];
|
|
315
|
-
listeners: readonly (Registered & {
|
|
316
|
-
listener: Listener;
|
|
317
|
-
event: EventDef;
|
|
318
|
-
})[];
|
|
319
|
-
idOf: (x: object) => string;
|
|
320
|
-
/** Deliver one stored envelope to its listeners (durable dispatchers). Throws if any listener failed, so you can retry. */
|
|
321
|
-
dispatch: (envelope: Envelope) => Promise<void>;
|
|
322
|
-
/** @internal used by `logic-sdk/testing` */
|
|
323
|
-
[INTERNAL]: {
|
|
324
|
-
options: RegistryOptions<Mods>;
|
|
325
|
-
overrides: Overrides;
|
|
326
|
-
derive: (more: Overrides) => /*elided*/ any;
|
|
327
|
-
};
|
|
328
|
-
};
|
|
351
|
+
createRegistry: <const Mods extends Record<string, object>>(options: TypedOptions<C, Mods>) => Registry<ScopeOf<C>, Mods, ConfigOf<C>>;
|
|
329
352
|
/** Reads data. Can run other queries. No writes, no events, no services. */
|
|
330
353
|
query: Constructor<C, "query">;
|
|
331
354
|
/** Changes data inside one transaction. Can run queries and mutations (same transaction) and emit events. */
|
|
@@ -334,49 +357,55 @@ export declare function init<C extends Config & OnlyKnownKeys<C>>(): {
|
|
|
334
357
|
action: Constructor<C, "action">;
|
|
335
358
|
/** Something that happened. Emitted by mutations, delivered after commit. */
|
|
336
359
|
event: <S extends Schema>(def: {
|
|
337
|
-
|
|
360
|
+
payload: S;
|
|
338
361
|
description?: string;
|
|
339
362
|
}) => EventDef<In<S>, Out<S>>;
|
|
340
|
-
/** React to an event after commit, like an action. Must be idempotent. `on(() => bookings.confirmed,
|
|
341
|
-
on: <O>(event: () => EventDef<
|
|
363
|
+
/** React to an event after commit, like an action. Must be idempotent. `on(() => bookings.confirmed, async (ctx, payload) => …)` */
|
|
364
|
+
on: <O>(event: () => EventDef<unknown, O>, handler: (ctx: ListenerCtx<C, O>, payload: O) => Promise<unknown>, opts?: {
|
|
342
365
|
description?: string;
|
|
343
366
|
}) => Listener<O>;
|
|
344
367
|
};
|
|
345
368
|
declare const INTERNAL: unique symbol;
|
|
346
369
|
export interface Overrides {
|
|
347
|
-
database?: DatabaseAdapter<
|
|
370
|
+
database?: DatabaseAdapter<unknown, unknown>;
|
|
348
371
|
services?: object;
|
|
372
|
+
/** Merged over the registry's config, section by section. */
|
|
373
|
+
config?: object;
|
|
349
374
|
events?: Dispatcher;
|
|
350
375
|
now?: () => Date;
|
|
351
|
-
stubs?: Map<Fn, (
|
|
376
|
+
stubs?: Map<Fn, (ctx: never, input: never) => Promise<unknown>>;
|
|
352
377
|
record?: (envelope: Envelope) => void;
|
|
353
378
|
}
|
|
354
|
-
export
|
|
355
|
-
|
|
356
|
-
|
|
379
|
+
export interface RegisteredEvent extends Registered {
|
|
380
|
+
event: EventDef;
|
|
381
|
+
}
|
|
382
|
+
export interface RegisteredListener extends Registered {
|
|
383
|
+
listener: Listener;
|
|
384
|
+
event: EventDef;
|
|
385
|
+
}
|
|
386
|
+
/** What `createRegistry` returns. `Cf` is your config's type, so tests can override parts of it. */
|
|
387
|
+
export interface Registry<S extends object = object, Mods extends Record<string, object> = Record<string, object>, Cf = unknown> {
|
|
357
388
|
/** The modules you registered (typed), for adapters that build typed routers. */
|
|
358
|
-
modules: Mods;
|
|
389
|
+
readonly modules: Mods;
|
|
359
390
|
/** Bind who is calling, once per request, job or test: `const caller = registry.as(scope)`. */
|
|
360
|
-
as
|
|
391
|
+
as(scope: S): Caller<S>;
|
|
361
392
|
/** Everything the registry can do. Adapters read this. */
|
|
362
|
-
functions: readonly RegisteredFn[];
|
|
363
|
-
events: readonly
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
listener: Listener;
|
|
368
|
-
event: EventDef;
|
|
369
|
-
})[];
|
|
370
|
-
idOf: (x: object) => string;
|
|
393
|
+
readonly functions: readonly RegisteredFn[];
|
|
394
|
+
readonly events: readonly RegisteredEvent[];
|
|
395
|
+
readonly listeners: readonly RegisteredListener[];
|
|
396
|
+
/** `"bookings.confirm"` for a registered function or event. Throws for anything unregistered. */
|
|
397
|
+
idOf(fnOrEvent: object): string;
|
|
371
398
|
/** Deliver one stored envelope to its listeners (durable dispatchers). Throws if any listener failed, so you can retry. */
|
|
372
|
-
dispatch
|
|
399
|
+
dispatch(envelope: Envelope): Promise<void>;
|
|
373
400
|
/** @internal used by `logic-sdk/testing` */
|
|
374
|
-
[INTERNAL]: {
|
|
401
|
+
readonly [INTERNAL]: {
|
|
375
402
|
options: RegistryOptions<Mods>;
|
|
376
|
-
|
|
377
|
-
derive
|
|
403
|
+
config: Frozen<Cf>;
|
|
404
|
+
derive(more: Overrides): Registry<S, Mods, Cf>;
|
|
378
405
|
};
|
|
379
|
-
}
|
|
406
|
+
}
|
|
407
|
+
/** Create the registry once at startup. Prefer the `createRegistry` returned by `init()`: it's typed with your config. */
|
|
408
|
+
export declare function createRegistry<S extends object = object, const Mods extends Record<string, object> = Record<string, object>>(options: RegistryOptions<Mods>): Registry<S, Mods, unknown>;
|
|
380
409
|
/**
|
|
381
410
|
* What `createRegistry` finds in your modules, without a database or services: every function, event and
|
|
382
411
|
* listener with its id. For tools (the CLI, docs generators) that inspect an app without running it.
|
|
@@ -384,61 +413,13 @@ export declare function createRegistry<S extends object = object, const Mods ext
|
|
|
384
413
|
export declare function describeModules(modules: Record<string, object>): {
|
|
385
414
|
ids: Map<object, string>;
|
|
386
415
|
functions: RegisteredFn[];
|
|
387
|
-
events:
|
|
388
|
-
|
|
389
|
-
})[];
|
|
390
|
-
listeners: (Registered & {
|
|
391
|
-
listener: Listener;
|
|
392
|
-
event: EventDef;
|
|
393
|
-
})[];
|
|
394
|
-
};
|
|
395
|
-
declare function build<S extends object, Mods extends Record<string, object>>(options: RegistryOptions<Mods>, o: Overrides): {
|
|
396
|
-
/** The modules you registered (typed), for adapters that build typed routers. */
|
|
397
|
-
modules: Mods;
|
|
398
|
-
/** Bind who is calling, once per request, job or test: `const caller = registry.as(scope)`. */
|
|
399
|
-
as: (scope: S, opts?: CallerOptions) => Caller<S>;
|
|
400
|
-
/** Everything the registry can do. Adapters read this. */
|
|
401
|
-
functions: readonly RegisteredFn[];
|
|
402
|
-
events: readonly (Registered & {
|
|
403
|
-
event: EventDef;
|
|
404
|
-
})[];
|
|
405
|
-
listeners: readonly (Registered & {
|
|
406
|
-
listener: Listener;
|
|
407
|
-
event: EventDef;
|
|
408
|
-
})[];
|
|
409
|
-
idOf: (x: object) => string;
|
|
410
|
-
/** Deliver one stored envelope to its listeners (durable dispatchers). Throws if any listener failed, so you can retry. */
|
|
411
|
-
dispatch: (envelope: Envelope) => Promise<void>;
|
|
412
|
-
/** @internal used by `logic-sdk/testing` */
|
|
413
|
-
[INTERNAL]: {
|
|
414
|
-
options: RegistryOptions<Mods>;
|
|
415
|
-
overrides: Overrides;
|
|
416
|
-
derive: (more: Overrides) => /*elided*/ any;
|
|
417
|
-
};
|
|
416
|
+
events: RegisteredEvent[];
|
|
417
|
+
listeners: RegisteredListener[];
|
|
418
418
|
};
|
|
419
419
|
/** @internal */
|
|
420
|
-
export declare const internal: (registry: Registry<
|
|
421
|
-
options: RegistryOptions<
|
|
422
|
-
|
|
423
|
-
derive
|
|
424
|
-
/** The modules you registered (typed), for adapters that build typed routers. */
|
|
425
|
-
modules: any;
|
|
426
|
-
/** Bind who is calling, once per request, job or test: `const caller = registry.as(scope)`. */
|
|
427
|
-
as: (scope: any, opts?: CallerOptions) => Caller<any>;
|
|
428
|
-
/** Everything the registry can do. Adapters read this. */
|
|
429
|
-
functions: readonly RegisteredFn[];
|
|
430
|
-
events: readonly (Registered & {
|
|
431
|
-
event: EventDef;
|
|
432
|
-
})[];
|
|
433
|
-
listeners: readonly (Registered & {
|
|
434
|
-
listener: Listener;
|
|
435
|
-
event: EventDef;
|
|
436
|
-
})[];
|
|
437
|
-
idOf: (x: object) => string;
|
|
438
|
-
/** Deliver one stored envelope to its listeners (durable dispatchers). Throws if any listener failed, so you can retry. */
|
|
439
|
-
dispatch: (envelope: Envelope) => Promise<void>;
|
|
440
|
-
/** @internal used by `logic-sdk/testing` */
|
|
441
|
-
[INTERNAL]: /*elided*/ any;
|
|
442
|
-
};
|
|
420
|
+
export declare const internal: <S extends object, Mods extends Record<string, object>, Cf>(registry: Registry<S, Mods, Cf>) => {
|
|
421
|
+
options: RegistryOptions<Mods>;
|
|
422
|
+
config: Frozen<Cf>;
|
|
423
|
+
derive(more: Overrides): Registry<S, Mods, Cf>;
|
|
443
424
|
};
|
|
444
425
|
export {};
|