logic-sdk 0.1.0 → 0.2.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 CHANGED
@@ -10,21 +10,20 @@ Write the layer between your routes and your database once, as plain declaration
10
10
  npm i logic-sdk zod
11
11
  ```
12
12
 
13
- Node 26+, Bun or Cloudflare Workers. Postgres through Drizzle for mutations.
13
+ Node 24+, Bun or Cloudflare Workers. Postgres through Drizzle for mutations.
14
14
 
15
15
  ## Quick start
16
16
 
17
- Declare your types and policies once:
17
+ Declare your types once, and who may do what:
18
18
 
19
19
  ```ts
20
20
  // src/logic.ts
21
- export const { query, mutation, action, event, on, createRegistry } =
22
- init<Config>()({
23
- policies: {
24
- public: () => true,
25
- staff: (scope) => is(scope, "agent", "owner", "admin"),
26
- },
27
- });
21
+ export const { query, mutation, action, event, on, createRegistry } = init<Config>();
22
+
23
+ // src/policies.ts: sync type guards over the scope
24
+ export const anyone = () => true;
25
+ export const member = (s: Scope): s is MemberScope => s.actor !== null;
26
+ export const staff = (s: Scope): s is StaffScope => s.actor !== null && s.actor.role !== "guest";
28
27
  ```
29
28
 
30
29
  Write a module:
@@ -35,12 +34,15 @@ export const confirm = mutation({
35
34
  description: "Confirm a pending booking",
36
35
  inputSchema: z.object({ bookingId: z.uuid() }),
37
36
  outputSchema: Booking,
38
- expose: "staff",
37
+ // Who may call it, on every call
38
+ authorize: staff,
39
+ // HTTP, oRPC and AI tools may publish it
40
+ expose: true,
39
41
 
40
42
  async execute({ bookingId }, ctx) {
41
43
  const booking = await findBooking(ctx, bookingId);
42
44
  if (booking.status !== "pending") {
43
- throw ctx.reject("not_pending");
45
+ throw ctx.errors.reject("not_pending");
44
46
  }
45
47
 
46
48
  // Another module, in the same transaction
@@ -75,9 +77,10 @@ await caller.run(bookings.confirm, { bookingId });
75
77
  - **Side effects after commit.** Mutations emit events; listeners send the email once the data is safe.
76
78
  - **Lost races retried.** Deadlocks and serialization failures re-run the mutation in a fresh transaction.
77
79
  - **Who is calling, everywhere.** The scope reaches every nested call and listener, and policies narrow its type.
78
- - **Internal by default.** Only exposed functions reach HTTP, RPC or AI tools, with a required output contract.
79
- - **Agents included.** `toAITools` gives an agent your functions, under the same policies and transactions as your API.
80
- - **Errors without HTTP.** `ctx.reject`, `ctx.conflict`, `ctx.notFound`, `ctx.deny`; adapters map them to statuses.
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
+ - **Internal by default.** Only `expose: true` functions reach HTTP, RPC or AI tools, with a required policy and output contract.
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
+ - **Errors without HTTP.** `ctx.errors.reject`, `conflict`, `notFound`, `deny`; adapters map them to statuses.
81
84
  - **Tests without mocks.** Each test is a real transaction on a real database, always rolled back.
82
85
  - **No magic.** No decorators, classes, codegen, build step or `AsyncLocalStorage`.
83
86
 
@@ -95,10 +98,10 @@ await caller.run(bookings.confirm, { bookingId });
95
98
 
96
99
  ```bash
97
100
  npm i -D @logic-sdk/cli
98
- npx logic-sdk list # every function, its kind and policy
101
+ npx logic-sdk list # every function, its kind and policy
99
102
  logic-sdk show bookings.confirm # schemas, what it runs and emits, who calls it
100
103
  logic-sdk graph --format mermaid # who runs whom, who reacts to which event
101
- logic-sdk check # module boundaries, run cycles, no network in transactions
104
+ logic-sdk check # module boundaries, run cycles, no network in transactions, can* checks
102
105
  ```
103
106
 
104
107
  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.
package/dist/ai.d.ts CHANGED
@@ -10,23 +10,36 @@ export type AIToolsOf<Mods> = UnionToIntersection<{
10
10
  [N in keyof ExposedOf<Mods[M]> & string as `${M}_${N}`]: Tool<FnIn<Mods[M][N & keyof Mods[M]]>, FnOut<Mods[M][N & keyof Mods[M]]>>;
11
11
  };
12
12
  }[keyof Mods & string]>;
13
- export interface AIToolsOptions {
14
- /** Keep only some exposed functions, e.g. `(f) => f.fn.meta?.agent !== false`. */
15
- filter?: (fn: RegisteredFn) => boolean;
13
+ export interface AIToolOptions {
16
14
  /** Unexpected (non-domain) errors. The model only sees "internal_error". Default: console.error. */
17
15
  onError?: (error: unknown) => void;
18
16
  }
17
+ export interface AIToolsOptions extends AIToolOptions {
18
+ /**
19
+ * Which exposed functions an agent may call. Required: the agent door is opt-in, so a function exposed
20
+ * for your UI doesn't become a tool by accident. E.g. `(f) => f.fn.meta?.agent === true`.
21
+ */
22
+ filter: (fn: RegisteredFn) => boolean;
23
+ }
19
24
  /**
20
- * Exposed functions as AI SDK tools, run as `caller`: an agent goes through the same policies,
21
- * validation, transactions and events as your HTTP API. Tool names are `<module>_<function>`.
25
+ * One exposed function as an AI SDK tool, run as `caller`: the agent goes through the same policy,
26
+ * validation, transaction and events as your HTTP API. You name it, like any AI SDK tool.
22
27
  *
23
28
  * ```ts
24
29
  * const caller = registry.as(await scopeFrom(request));
25
- * await generateText({ model, tools: toAITools(registry, caller), prompt });
30
+ * await generateText({ model, prompt, tools: { confirmBooking: toAITool(caller, bookings.confirm) } });
26
31
  * ```
27
32
  *
28
33
  * Domain errors reach the model (it sees the code and can react). Anything unexpected is reported
29
34
  * to `onError` and the model gets "internal_error", so internals never land in its context.
30
35
  */
31
- export declare function toAITools<S extends object, Mods extends Record<string, object>>(registry: Registry<S, Mods>, caller: Caller<S>, options?: AIToolsOptions): AIToolsOf<Mods>;
36
+ export declare function toAITool<F extends Fn<any, any, any, true>>(caller: Caller<any>, fn: F, options?: AIToolOptions): Tool<FnIn<F>, FnOut<F>>;
37
+ /**
38
+ * The exposed functions your `filter` picks, as AI SDK tools named `<module>_<function>`.
39
+ *
40
+ * ```ts
41
+ * tools: toAITools(registry, caller, { filter: (f) => f.fn.meta?.agent === true })
42
+ * ```
43
+ */
44
+ export declare function toAITools<S extends object, Mods extends Record<string, object>>(registry: Registry<S, Mods>, caller: Caller<S>, options: AIToolsOptions): Partial<AIToolsOf<Mods>>;
32
45
  export {};
package/dist/ai.js CHANGED
@@ -1,39 +1,51 @@
1
1
  import { tool } from "ai";
2
2
  import { isDomainError } from "./index.js";
3
3
  /**
4
- * Exposed functions as AI SDK tools, run as `caller`: an agent goes through the same policies,
5
- * validation, transactions and events as your HTTP API. Tool names are `<module>_<function>`.
4
+ * One exposed function as an AI SDK tool, run as `caller`: the agent goes through the same policy,
5
+ * validation, transaction and events as your HTTP API. You name it, like any AI SDK tool.
6
6
  *
7
7
  * ```ts
8
8
  * const caller = registry.as(await scopeFrom(request));
9
- * await generateText({ model, tools: toAITools(registry, caller), prompt });
9
+ * await generateText({ model, prompt, tools: { confirmBooking: toAITool(caller, bookings.confirm) } });
10
10
  * ```
11
11
  *
12
12
  * Domain errors reach the model (it sees the code and can react). Anything unexpected is reported
13
13
  * to `onError` and the model gets "internal_error", so internals never land in its context.
14
14
  */
15
- export function toAITools(registry, caller, options = {}) {
15
+ export function toAITool(caller, fn, options = {}) {
16
16
  const onError = options.onError ?? ((e) => console.error("[logic-sdk] tool failed unexpectedly", e));
17
+ if (fn.expose !== true)
18
+ throw new Error("[logic-sdk] toAITool needs a function with expose: true.");
19
+ return tool({
20
+ description: fn.description,
21
+ inputSchema: fn.inputSchema,
22
+ outputSchema: fn.outputSchema,
23
+ async execute(input) {
24
+ try {
25
+ return await caller.run(fn, input);
26
+ }
27
+ catch (e) {
28
+ if (isDomainError(e))
29
+ throw e;
30
+ onError(e);
31
+ throw new Error("internal_error");
32
+ }
33
+ },
34
+ });
35
+ }
36
+ /**
37
+ * The exposed functions your `filter` picks, as AI SDK tools named `<module>_<function>`.
38
+ *
39
+ * ```ts
40
+ * tools: toAITools(registry, caller, { filter: (f) => f.fn.meta?.agent === true })
41
+ * ```
42
+ */
43
+ export function toAITools(registry, caller, options) {
44
+ if (typeof options?.filter !== "function")
45
+ throw new Error("[logic-sdk] toAITools needs a filter: the agent door is opt-in. E.g. { filter: (f) => f.fn.meta?.agent === true }");
17
46
  const tools = {};
18
- for (const f of registry.functions) {
19
- if (!f.exposed || (options.filter && !options.filter(f)))
20
- continue;
21
- tools[`${f.module}_${f.name}`] = tool({
22
- description: f.fn.description,
23
- inputSchema: f.fn.inputSchema,
24
- outputSchema: f.fn.outputSchema,
25
- async execute(input) {
26
- try {
27
- return await caller.run(f.fn, input);
28
- }
29
- catch (e) {
30
- if (isDomainError(e))
31
- throw e;
32
- onError(e);
33
- throw new Error("internal_error");
34
- }
35
- },
36
- });
37
- }
47
+ for (const f of registry.functions)
48
+ if (f.exposed && options.filter(f))
49
+ tools[`${f.module}_${f.name}`] = toAITool(caller, f.fn, options);
38
50
  return tools;
39
51
  }
package/dist/fetch.d.ts CHANGED
@@ -1,4 +1,9 @@
1
- import { type CallerOptions, type ErrorKind, type Registry } from "./index.ts";
1
+ import { DomainError, type CallerOptions, type ErrorKind, type Registry } from "./index.ts";
2
+ /**
3
+ * Throw from `resolveScope` when this mount is session-only and there's no valid session: the client gets 401.
4
+ * For mounts that also serve public functions, return a scope with no actor instead, and let policies answer 403.
5
+ */
6
+ export declare const unauthenticated: (code?: string, details?: unknown) => DomainError;
2
7
  /** Error kind → HTTP status. The only place statuses exist: core errors know nothing about HTTP. */
3
8
  export declare const statusOf: Record<ErrorKind, number>;
4
9
  export interface FetchOptions<S extends object> {
@@ -13,8 +18,7 @@ export interface FetchOptions<S extends object> {
13
18
  }
14
19
  /**
15
20
  * A web-standard handler (Workers, Bun, Node via Hono or srvx, SvelteKit, Next route handlers...).
16
- * Publishes only functions with `expose`. POST `{base}{id}` with a JSON body (`content-type: application/json` required);
21
+ * Publishes only functions with `expose: true`. POST `{base}{id}` with a JSON body (`content-type: application/json` required);
17
22
  * queries also accept GET `?input=<json>`.
18
- * GET `{base}` lists what's exposed.
19
23
  */
20
24
  export declare function toFetchHandler<S extends object>(registry: Registry<S, any>, options: FetchOptions<S>): (request: Request, ...rest: any[]) => Promise<Response>;
package/dist/fetch.js CHANGED
@@ -1,4 +1,9 @@
1
- import { isDomainError } from "./index.js";
1
+ import { DomainError, isDomainError } from "./index.js";
2
+ /**
3
+ * Throw from `resolveScope` when this mount is session-only and there's no valid session: the client gets 401.
4
+ * For mounts that also serve public functions, return a scope with no actor instead, and let policies answer 403.
5
+ */
6
+ export const unauthenticated = (code = "unauthenticated", details) => new DomainError("unauthenticated", code, details);
2
7
  /** Error kind → HTTP status. The only place statuses exist: core errors know nothing about HTTP. */
3
8
  export const statusOf = {
4
9
  invalid: 400,
@@ -11,9 +16,8 @@ export const statusOf = {
11
16
  const json = (body, status = 200) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
12
17
  /**
13
18
  * A web-standard handler (Workers, Bun, Node via Hono or srvx, SvelteKit, Next route handlers...).
14
- * Publishes only functions with `expose`. POST `{base}{id}` with a JSON body (`content-type: application/json` required);
19
+ * Publishes only functions with `expose: true`. POST `{base}{id}` with a JSON body (`content-type: application/json` required);
15
20
  * queries also accept GET `?input=<json>`.
16
- * GET `{base}` lists what's exposed.
17
21
  */
18
22
  export function toFetchHandler(registry, options) {
19
23
  const base = (options.basePath ?? "/").replace(/\/?$/, "/");
@@ -24,10 +28,6 @@ export function toFetchHandler(registry, options) {
24
28
  if (!path.startsWith(base))
25
29
  return json({ error: { kind: "not_found", code: "route_not_found" } }, 404);
26
30
  const id = path.slice(base.length);
27
- if (id === "" && request.method === "GET")
28
- return json({
29
- functions: [...exposed.values()].map((f) => ({ id: f.id, kind: f.kind, description: f.fn.description })),
30
- });
31
31
  const entry = exposed.get(id);
32
32
  if (!entry)
33
33
  return json({ error: { kind: "not_found", code: "function_not_found" } }, 404);
package/dist/index.d.ts CHANGED
@@ -2,7 +2,6 @@ import type { StandardSchemaV1 } from "@standard-schema/spec";
2
2
  type Schema<I = any, O = any> = StandardSchemaV1<I, O>;
3
3
  type In<S> = S extends Schema<infer I, any> ? I : never;
4
4
  type Out<S> = S extends Schema<any, infer O> ? O : never;
5
- type Awaitable<T> = T | Promise<T>;
6
5
  /** What you declare once in `init<...>()`. */
7
6
  export interface Config {
8
7
  /** Who and where: actor, account, locale... Must be JSON-serializable (it travels with events). */
@@ -41,8 +40,10 @@ export interface Fn<K extends Kind = Kind, I = any, O = any, E extends boolean =
41
40
  readonly outputSchema?: Schema;
42
41
  /** Your own data about the function. Checked against `meta` in `init` where you set it, typed in `wrap`; loose here, for adapters. */
43
42
  readonly meta?: any;
44
- /** Set when the function is exposed: who may call it. Runs on every call. */
45
- readonly check?: (scope: any, input: any) => Awaitable<boolean>;
43
+ /** Who may call it (from `authorize`). Runs on every call, before validation. */
44
+ readonly authorize?: Policy<any>;
45
+ /** `true`: adapters may publish it (HTTP, oRPC, AI tools). Requires `authorize` and `outputSchema`. */
46
+ readonly expose?: true;
46
47
  readonly execute: (input: any, ctx: any) => Promise<any>;
47
48
  /** Phantom types, never set at runtime. */
48
49
  readonly [types]?: {
@@ -51,7 +52,7 @@ export interface Fn<K extends Kind = Kind, I = any, O = any, E extends boolean =
51
52
  exposed: E;
52
53
  };
53
54
  }
54
- /** A function with `expose`: adapters publish it. */
55
+ /** A function with `expose: true`: adapters may publish it. */
55
56
  export type ExposedFn<K extends Kind = Kind, I = any, O = any> = Fn<K, I, O, true>;
56
57
  /** What callers pass to a function. */
57
58
  export type FnIn<F> = F extends Fn<any, infer I, any> ? I : never;
@@ -89,11 +90,11 @@ export interface Listener<O = any> {
89
90
  }
90
91
  type Run<Allowed extends Kind> = <F extends Fn<Allowed>>(fn: F, input: FnIn<F>) => Promise<FnOut<F>>;
91
92
  /**
92
- * Expected failures, namespaced to the module you're in: inside `bookings`, `ctx.reject("not_pending")` has
93
+ * Expected failures, namespaced to the module you're in: inside `bookings`, `ctx.errors.reject("not_pending")` has
93
94
  * code `"bookings.not_pending"`. Throw what they return. Codes are plain strings on purpose (see the errors docs).
94
95
  */
95
- interface Fail {
96
- /** A business rule said no, and trying again won't help. `throw ctx.reject("not_pending", { status })` */
96
+ export interface Errors {
97
+ /** A business rule said no, and trying again won't help. `throw ctx.errors.reject("not_pending", { status })` */
97
98
  reject(code: string, details?: unknown): DomainError;
98
99
  /** Someone else got there first, or it already exists. Refreshing and retrying may work. */
99
100
  conflict(code: string, details?: unknown): DomainError;
@@ -102,8 +103,10 @@ interface Fail {
102
103
  /** The caller is known but may not do this. Code defaults to `"<module>.<function>.forbidden"`. */
103
104
  deny(code?: string, details?: unknown): DomainError;
104
105
  }
105
- interface BaseCtx<S> extends Fail {
106
+ interface BaseCtx<S> {
106
107
  scope: S;
108
+ /** Expected failures: `throw ctx.errors.reject("not_pending")`. */
109
+ errors: Errors;
107
110
  /** Current time. Fixed in tests. */
108
111
  now: () => Date;
109
112
  }
@@ -136,13 +139,13 @@ export interface ListenerCtx<C extends Config, O = unknown> extends ActionCtx<C>
136
139
  payload: O;
137
140
  };
138
141
  }
139
- /** Who may call an exposed function. Write it as a type guard (`(s): s is Staff => ...`) to narrow `scope` in `execute`. */
142
+ /**
143
+ * 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 `execute`.
145
+ * Rules about one record ("only the owner may cancel") go in `execute`, after loading it.
146
+ */
140
147
  export type Policy<S> = (scope: S) => boolean;
141
148
  type Guarded<F, S> = F extends (scope: any) => scope is infer G ? G : S;
142
- type Inline<C extends Config, IS extends Schema> = (scope: ScopeOf<C>, input: Out<IS>) => Awaitable<boolean>;
143
- /** A policy name from `init`, or an inline check that also sees the input. */
144
- type Exposure<C extends Config, P, IS extends Schema> = (keyof P & string) | Inline<C, IS>;
145
- type ScopeFor<C extends Config, P, E> = E extends keyof P ? Guarded<P[E], ScopeOf<C>> : ScopeOf<C>;
146
149
  type CtxOf<C extends Config, K extends Kind, S> = K extends "query" ? QueryCtx<C, S> : K extends "mutation" ? MutationCtx<C, S> : ActionCtx<C, S>;
147
150
  type Def<IS extends Schema, Ctx, R> = {
148
151
  /** One sentence, shown to humans, adapters and AI tools. */
@@ -150,22 +153,35 @@ type Def<IS extends Schema, Ctx, R> = {
150
153
  inputSchema: IS;
151
154
  execute: (input: Out<IS>, ctx: Ctx) => Promise<R>;
152
155
  };
153
- type Internal = {
156
+ type NotExposed = {
154
157
  expose?: undefined;
155
158
  };
159
+ type NoPolicy = {
160
+ authorize?: undefined;
161
+ };
156
162
  type WithMeta<C extends Config> = {
157
163
  meta?: MetaOf<C>;
158
164
  };
159
165
  type WithOutput<OS extends Schema> = {
160
166
  outputSchema: OS;
161
167
  };
162
- /** Exposed functions must declare `outputSchema`: what leaves your process is a contract. Internal ones may skip it. */
163
- interface Constructor<C extends Config, K extends Kind, P> {
164
- <IS extends Schema, OS extends Schema, const E extends Exposure<C, P, IS>>(def: Def<IS, CtxOf<C, K, ScopeFor<C, P, E>>, In<OS>> & WithOutput<OS> & WithMeta<C> & {
165
- expose: E;
168
+ /**
169
+ * `expose: true` needs `authorize` and `outputSchema`: you can't publish something without saying who may call it,
170
+ * and what leaves your process is a contract. Internal functions may skip both; `authorize` still runs if set.
171
+ */
172
+ 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> & {
174
+ authorize: P;
175
+ expose: true;
166
176
  }): Fn<K, In<IS>, Out<OS>, true>;
167
- <IS extends Schema, OS extends Schema>(def: Def<IS, CtxOf<C, K, ScopeOf<C>>, In<OS>> & WithOutput<OS> & WithMeta<C> & Internal): Fn<K, In<IS>, Out<OS>, false>;
168
- <IS extends Schema, R>(def: Def<IS, CtxOf<C, K, ScopeOf<C>>, R> & WithMeta<C> & Internal): Fn<K, In<IS>, R, false>;
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> & {
178
+ authorize: P;
179
+ } & 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> & {
181
+ authorize: P;
182
+ } & 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>;
169
185
  }
170
186
  export type ErrorKind = "invalid" | "unauthenticated" | "forbidden" | "not_found" | "conflict" | "rejected";
171
187
  /**
@@ -179,8 +195,6 @@ export declare class DomainError extends Error {
179
195
  readonly details: unknown;
180
196
  constructor(kind: ErrorKind, code: string, details?: unknown);
181
197
  }
182
- /** For the edge (`resolveScope`): no valid session. Inside modules, use `ctx.deny()`. */
183
- export declare const unauthenticated: (code?: string, details?: unknown) => DomainError;
184
198
  /** `isDomainError(e)`, or with a code: `isDomainError(e, "availability.dates_unavailable")`. */
185
199
  export declare const isDomainError: (e: unknown, code?: string) => e is DomainError;
186
200
  export interface DatabaseAdapter<Db = unknown, Tx = Db> {
@@ -260,7 +274,7 @@ export interface Registered {
260
274
  export interface RegisteredFn extends Registered {
261
275
  fn: Fn;
262
276
  kind: Kind;
263
- /** Has `expose`: adapters publish it. */
277
+ /** Has `expose: true`: adapters may publish it. */
264
278
  exposed: boolean;
265
279
  }
266
280
  type TypedOptions<C extends Config, Mods extends Record<string, object>> = Omit<RegistryOptions<Mods>, "wrap"> & {
@@ -275,28 +289,18 @@ type TypedOptions<C extends Config, Mods extends Record<string, object>> = Omit<
275
289
  } : {
276
290
  database: DatabaseAdapter<any, DbOf<C>>;
277
291
  });
292
+ /** Keys `Config` doesn't know are errors, so a typo like `servises` can't be silently ignored. */
293
+ type OnlyKnownKeys<C> = {
294
+ [K in Exclude<keyof C, keyof Config>]: never;
295
+ };
278
296
  /**
279
- * Typed constructors for your app. Curried so policy names are inferred while `Config` is explicit:
297
+ * Typed constructors for your app:
280
298
  *
281
299
  * ```ts
282
- * export const { query, mutation, action, event, on, createRegistry } = init<Config>()({
283
- * policies: { public: () => true, staff: (s): s is Staff => isStaff(s) },
284
- * });
300
+ * export const { query, mutation, action, event, on, createRegistry } = init<Config>();
285
301
  * ```
286
302
  */
287
- /** Keys `Config` doesn't know are errors, so a typo like `servises` can't be silently ignored. */
288
- type OnlyKnownKeys<C> = {
289
- [K in Exclude<keyof C, keyof Config>]: never;
290
- };
291
- export declare function init<C extends Config & OnlyKnownKeys<C>>(): Init<C>;
292
- interface Init<C extends Config> {
293
- (): Constructors<C, {}>;
294
- <P extends Record<string, Policy<ScopeOf<C>>>>(options: {
295
- policies: P;
296
- }): Constructors<C, P>;
297
- }
298
- type Constructors<C extends Config, P> = ReturnType<typeof constructors<C, P>>;
299
- declare function constructors<C extends Config, P>(policies: Record<string, Policy<any>>): {
303
+ export declare function init<C extends Config & OnlyKnownKeys<C>>(): {
300
304
  /** Create the registry once at startup: `createRegistry({ modules, database, services })`. */
301
305
  createRegistry: <const Mods extends Record<string, object>>(options: TypedOptions<C, Mods>) => {
302
306
  /** The modules you registered (typed), for adapters that build typed routers. */
@@ -323,11 +327,11 @@ declare function constructors<C extends Config, P>(policies: Record<string, Poli
323
327
  };
324
328
  };
325
329
  /** Reads data. Can run other queries. No writes, no events, no services. */
326
- query: Constructor<C, "query", P>;
330
+ query: Constructor<C, "query">;
327
331
  /** Changes data inside one transaction. Can run queries and mutations (same transaction) and emit events. */
328
- mutation: Constructor<C, "mutation", P>;
332
+ mutation: Constructor<C, "mutation">;
329
333
  /** Talks to the outside world (payments, email, AI). No transaction; each mutation it runs commits on its own. */
330
- action: Constructor<C, "action", P>;
334
+ action: Constructor<C, "action">;
331
335
  /** Something that happened. Emitted by mutations, delivered after commit. */
332
336
  event: <S extends Schema>(def: {
333
337
  schema: S;
package/dist/index.js CHANGED
@@ -17,12 +17,10 @@ export class DomainError extends Error {
17
17
  this.details = details;
18
18
  }
19
19
  }
20
- /** For the edge (`resolveScope`): no valid session. Inside modules, use `ctx.deny()`. */
21
- export const unauthenticated = (code = "unauthenticated", details) => new DomainError("unauthenticated", code, details);
22
20
  /** `isDomainError(e)`, or with a code: `isDomainError(e, "availability.dates_unavailable")`. */
23
21
  export const isDomainError = (e, code) => e instanceof DomainError && (code === undefined || e.code === code);
24
- /** `ctx.reject` and friends for one function or listener (`id` like "bookings.confirm"). */
25
- const failFor = (id) => {
22
+ /** `ctx.errors` for one function or listener (`id` like "bookings.confirm"). */
23
+ const errorsFor = (id) => {
26
24
  const module = id.slice(0, id.indexOf("."));
27
25
  return {
28
26
  reject: (code, details) => new DomainError("rejected", `${module}.${code}`, details),
@@ -38,20 +36,28 @@ export const inProcess = () => ({
38
36
  await dispatch(e);
39
37
  },
40
38
  });
39
+ /**
40
+ * Typed constructors for your app:
41
+ *
42
+ * ```ts
43
+ * export const { query, mutation, action, event, on, createRegistry } = init<Config>();
44
+ * ```
45
+ */
41
46
  export function init() {
42
- return ((options) => constructors(options?.policies ?? {}));
47
+ return constructors();
43
48
  }
44
- function constructors(policies) {
45
- const make = (kind) => ({ expose, ...def }) => {
46
- let check;
47
- if (typeof expose === "function")
48
- check = expose;
49
- else if (expose !== undefined) {
50
- check = policies[expose];
51
- if (!check)
52
- throw new Error(`[logic-sdk] Unknown policy "${expose}". Define it in init()({ policies }).`);
53
- }
54
- return Object.freeze({ [BRAND]: kind, kind, outputSchema: undefined, ...def, check });
49
+ function constructors() {
50
+ const make = (kind) => (def) => {
51
+ const where = def?.description ? `"${def.description}"` : `a ${kind}`;
52
+ if (def.authorize !== undefined && typeof def.authorize !== "function")
53
+ throw new Error(`[logic-sdk] authorize on ${where} must be a policy function, like \`authorize: member\`.`);
54
+ if (def.expose !== undefined && def.expose !== true)
55
+ throw new Error(`[logic-sdk] expose on ${where} must be \`true\` or left out.`);
56
+ if (def.expose && !def.authorize)
57
+ throw new Error(`[logic-sdk] ${where} has expose: true but no authorize. Say who may call it.`);
58
+ if (def.expose && !def.outputSchema)
59
+ throw new Error(`[logic-sdk] ${where} has expose: true but no outputSchema. Say what callers may see.`);
60
+ return Object.freeze({ [BRAND]: kind, kind, outputSchema: undefined, ...def });
55
61
  };
56
62
  return {
57
63
  /** Create the registry once at startup: `createRegistry({ modules, database, services })`. */
@@ -106,7 +112,7 @@ export function describeModules(modules) {
106
112
  listeners.push({ id, module, name, listener, event: listener.event() });
107
113
  }
108
114
  else
109
- functions.push({ id, module, name, kind, fn: value, exposed: typeof value.check === "function" });
115
+ functions.push({ id, module, name, kind, fn: value, exposed: value.expose === true });
110
116
  }
111
117
  }
112
118
  return { ids, functions, events, listeners };
@@ -138,14 +144,18 @@ function build(options, o) {
138
144
  const idOf = (x) => {
139
145
  const id = ids.get(x);
140
146
  if (!id)
141
- throw new Error("[logic-sdk] This function or event isn't registered. Add its module to createRegistry({ modules }).");
147
+ 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 }).");
142
148
  return id;
143
149
  };
144
- async function parseInput(schema, value, code) {
150
+ /** Bad input from a caller is their error. Bad input from your own code (a nested call) is a bug. */
151
+ async function parseInput(schema, value, id, nested) {
145
152
  const r = await schema["~standard"].validate(value);
146
- if (r.issues)
147
- throw new DomainError("invalid", code, { issues: describeIssues(r.issues) });
148
- return r.value;
153
+ if (!r.issues)
154
+ return r.value;
155
+ const issues = describeIssues(r.issues);
156
+ if (nested)
157
+ throw new Error(`[logic-sdk] ${id} was run with invalid input: ${JSON.stringify(issues)}`);
158
+ throw new DomainError("invalid", `${id}.invalid_input`, { issues });
149
159
  }
150
160
  /** Output and event payloads are produced by our own code: invalid means a bug, not a bad request. */
151
161
  async function parseOwn(schema, value, what) {
@@ -195,7 +205,7 @@ function build(options, o) {
195
205
  const rescope = (frame, patch) => ({ ...frame, scope: { ...frame.scope, ...patch } });
196
206
  function queryCtx(frame, id) {
197
207
  return {
198
- ...failFor(id),
208
+ errors: errorsFor(id),
199
209
  scope: frame.scope,
200
210
  now,
201
211
  signal: frame.opts.signal,
@@ -207,7 +217,7 @@ function build(options, o) {
207
217
  function mutationCtx(frame, id) {
208
218
  const tx = frame.tx;
209
219
  return {
210
- ...failFor(id),
220
+ errors: errorsFor(id),
211
221
  scope: frame.scope,
212
222
  now,
213
223
  signal: frame.opts.signal,
@@ -234,7 +244,7 @@ function build(options, o) {
234
244
  }
235
245
  function actionCtx(frame, id) {
236
246
  return {
237
- ...failFor(id),
247
+ errors: errorsFor(id),
238
248
  scope: frame.scope,
239
249
  now,
240
250
  signal: frame.opts.signal,
@@ -249,13 +259,17 @@ function build(options, o) {
249
259
  if (!allowed.includes(fn.kind))
250
260
  throw new Error(`[logic-sdk] ${id} is a ${fn.kind}; it can't be run from here (allowed: ${allowed.join(", ")}).`);
251
261
  const call = { id, kind: fn.kind, meta: fn.meta, input: rawInput, scope: frame.scope, depth: frame.depth };
252
- /** Validate and check before any transaction opens: bad or denied calls never touch the database. */
262
+ /** Authorize, then validate, before any transaction opens: denied or bad calls never touch the database. */
253
263
  const prepare = async () => {
254
264
  frame.opts.signal?.throwIfAborted();
255
- const input = await parseInput(fn.inputSchema, rawInput, `${id}.invalid_input`);
256
- if (fn.check && !(await fn.check(frame.scope, input)))
257
- throw new DomainError("forbidden", `${id}.forbidden`);
258
- return input;
265
+ if (fn.authorize) {
266
+ const allowed = fn.authorize(frame.scope);
267
+ if (allowed instanceof Promise || typeof allowed?.then === "function")
268
+ throw new Error(`[logic-sdk] The policy on ${id} returned a Promise. Policies are sync and read only the scope.`);
269
+ if (allowed !== true)
270
+ throw new DomainError("forbidden", `${id}.forbidden`);
271
+ }
272
+ return parseInput(fn.inputSchema, rawInput, id, frame.depth > 0);
259
273
  };
260
274
  const execute = async (input, ctx) => {
261
275
  const stub = o.stubs?.get(fn);
package/dist/orpc.d.ts CHANGED
@@ -6,7 +6,7 @@ export type ORPCContext<S extends object> = {
6
6
  caller: Caller<S>;
7
7
  };
8
8
  type ProcedureOf<S extends object, F> = F extends Fn<any, infer I, infer O, true> ? Procedure<ORPCContext<S>, ORPCContext<S>, StandardSchemaV1<I, I>, StandardSchemaV1<O, O>, {}> : never;
9
- /** `{ bookings: { confirm, cancel, … } }`: only functions with `expose`. */
9
+ /** `{ bookings: { confirm, cancel, … } }`: only functions with `expose: true`. */
10
10
  export type ORPCRouterOf<S extends object, Mods> = {
11
11
  [M in keyof Mods as {} extends ExposedOf<Mods[M]> ? never : M]: {
12
12
  [N in keyof ExposedOf<Mods[M]>]: ProcedureOf<S, Mods[M][N & keyof Mods[M]]>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "logic-sdk",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
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",
@@ -77,15 +77,15 @@
77
77
  "access": "public"
78
78
  },
79
79
  "engines": {
80
- "node": ">=26"
80
+ "node": ">=24"
81
81
  },
82
82
  "dependencies": {
83
83
  "@standard-schema/spec": "^1.1.0"
84
84
  },
85
85
  "peerDependencies": {
86
- "@orpc/server": ">=2.0.0-beta.51",
87
- "ai": ">=7",
88
- "@logic-sdk/cli": ">=0.1.0"
86
+ "@orpc/server": ">=2.0.0-beta.51 <3",
87
+ "ai": ">=7 <8",
88
+ "@logic-sdk/cli": ">=0.2.0 <0.3.0"
89
89
  },
90
90
  "peerDependenciesMeta": {
91
91
  "@orpc/server": {
package/src/ai.ts CHANGED
@@ -16,49 +16,69 @@ export type AIToolsOf<Mods> = UnionToIntersection<
16
16
  }[keyof Mods & string]
17
17
  >;
18
18
 
19
- export interface AIToolsOptions {
20
- /** Keep only some exposed functions, e.g. `(f) => f.fn.meta?.agent !== false`. */
21
- filter?: (fn: RegisteredFn) => boolean;
19
+ export interface AIToolOptions {
22
20
  /** Unexpected (non-domain) errors. The model only sees "internal_error". Default: console.error. */
23
21
  onError?: (error: unknown) => void;
24
22
  }
23
+ export interface AIToolsOptions extends AIToolOptions {
24
+ /**
25
+ * Which exposed functions an agent may call. Required: the agent door is opt-in, so a function exposed
26
+ * for your UI doesn't become a tool by accident. E.g. `(f) => f.fn.meta?.agent === true`.
27
+ */
28
+ filter: (fn: RegisteredFn) => boolean;
29
+ }
25
30
 
26
31
  /**
27
- * Exposed functions as AI SDK tools, run as `caller`: an agent goes through the same policies,
28
- * validation, transactions and events as your HTTP API. Tool names are `<module>_<function>`.
32
+ * One exposed function as an AI SDK tool, run as `caller`: the agent goes through the same policy,
33
+ * validation, transaction and events as your HTTP API. You name it, like any AI SDK tool.
29
34
  *
30
35
  * ```ts
31
36
  * const caller = registry.as(await scopeFrom(request));
32
- * await generateText({ model, tools: toAITools(registry, caller), prompt });
37
+ * await generateText({ model, prompt, tools: { confirmBooking: toAITool(caller, bookings.confirm) } });
33
38
  * ```
34
39
  *
35
40
  * Domain errors reach the model (it sees the code and can react). Anything unexpected is reported
36
41
  * to `onError` and the model gets "internal_error", so internals never land in its context.
37
42
  */
43
+ export function toAITool<F extends Fn<any, any, any, true>>(
44
+ caller: Caller<any>,
45
+ fn: F,
46
+ options: AIToolOptions = {},
47
+ ): Tool<FnIn<F>, FnOut<F>> {
48
+ const onError = options.onError ?? ((e) => console.error("[logic-sdk] tool failed unexpectedly", e));
49
+ if (fn.expose !== true) throw new Error("[logic-sdk] toAITool needs a function with expose: true.");
50
+ return tool({
51
+ description: fn.description,
52
+ inputSchema: fn.inputSchema as FlexibleSchema,
53
+ outputSchema: fn.outputSchema as FlexibleSchema,
54
+ async execute(input) {
55
+ try {
56
+ return await caller.run(fn, input);
57
+ } catch (e) {
58
+ if (isDomainError(e)) throw e;
59
+ onError(e);
60
+ throw new Error("internal_error");
61
+ }
62
+ },
63
+ }) as Tool<FnIn<F>, FnOut<F>>;
64
+ }
65
+
66
+ /**
67
+ * The exposed functions your `filter` picks, as AI SDK tools named `<module>_<function>`.
68
+ *
69
+ * ```ts
70
+ * tools: toAITools(registry, caller, { filter: (f) => f.fn.meta?.agent === true })
71
+ * ```
72
+ */
38
73
  export function toAITools<S extends object, Mods extends Record<string, object>>(
39
74
  registry: Registry<S, Mods>,
40
75
  caller: Caller<S>,
41
- options: AIToolsOptions = {},
42
- ): AIToolsOf<Mods> {
43
- const onError = options.onError ?? ((e) => console.error("[logic-sdk] tool failed unexpectedly", e));
76
+ options: AIToolsOptions,
77
+ ): Partial<AIToolsOf<Mods>> {
78
+ if (typeof options?.filter !== "function")
79
+ throw new Error("[logic-sdk] toAITools needs a filter: the agent door is opt-in. E.g. { filter: (f) => f.fn.meta?.agent === true }");
44
80
  const tools: Record<string, Tool> = {};
45
-
46
- for (const f of registry.functions) {
47
- if (!f.exposed || (options.filter && !options.filter(f))) continue;
48
- tools[`${f.module}_${f.name}`] = tool({
49
- description: f.fn.description,
50
- inputSchema: f.fn.inputSchema as FlexibleSchema,
51
- outputSchema: f.fn.outputSchema as FlexibleSchema,
52
- async execute(input) {
53
- try {
54
- return await caller.run(f.fn, input);
55
- } catch (e) {
56
- if (isDomainError(e)) throw e;
57
- onError(e);
58
- throw new Error("internal_error");
59
- }
60
- },
61
- });
62
- }
63
- return tools as AIToolsOf<Mods>;
81
+ for (const f of registry.functions)
82
+ if (f.exposed && options.filter(f)) tools[`${f.module}_${f.name}`] = toAITool(caller, f.fn as Fn<any, any, any, true>, options);
83
+ return tools as Partial<AIToolsOf<Mods>>;
64
84
  }
package/src/fetch.ts CHANGED
@@ -1,4 +1,11 @@
1
- import { isDomainError, type CallerOptions, type ErrorKind, type Registry } from "./index.ts";
1
+ import { DomainError, isDomainError, type CallerOptions, type ErrorKind, type Registry } from "./index.ts";
2
+
3
+ /**
4
+ * Throw from `resolveScope` when this mount is session-only and there's no valid session: the client gets 401.
5
+ * For mounts that also serve public functions, return a scope with no actor instead, and let policies answer 403.
6
+ */
7
+ export const unauthenticated = (code = "unauthenticated", details?: unknown) =>
8
+ new DomainError("unauthenticated", code, details);
2
9
 
3
10
  /** Error kind → HTTP status. The only place statuses exist: core errors know nothing about HTTP. */
4
11
  export const statusOf: Record<ErrorKind, number> = {
@@ -26,9 +33,8 @@ const json = (body: unknown, status = 200) =>
26
33
 
27
34
  /**
28
35
  * A web-standard handler (Workers, Bun, Node via Hono or srvx, SvelteKit, Next route handlers...).
29
- * Publishes only functions with `expose`. POST `{base}{id}` with a JSON body (`content-type: application/json` required);
36
+ * Publishes only functions with `expose: true`. POST `{base}{id}` with a JSON body (`content-type: application/json` required);
30
37
  * queries also accept GET `?input=<json>`.
31
- * GET `{base}` lists what's exposed.
32
38
  */
33
39
  export function toFetchHandler<S extends object>(registry: Registry<S, any>, options: FetchOptions<S>) {
34
40
  const base = (options.basePath ?? "/").replace(/\/?$/, "/");
@@ -40,11 +46,6 @@ export function toFetchHandler<S extends object>(registry: Registry<S, any>, opt
40
46
  if (!path.startsWith(base)) return json({ error: { kind: "not_found", code: "route_not_found" } }, 404);
41
47
  const id = path.slice(base.length);
42
48
 
43
- if (id === "" && request.method === "GET")
44
- return json({
45
- functions: [...exposed.values()].map((f) => ({ id: f.id, kind: f.kind, description: f.fn.description })),
46
- });
47
-
48
49
  const entry = exposed.get(id);
49
50
  if (!entry) return json({ error: { kind: "not_found", code: "function_not_found" } }, 404);
50
51
 
package/src/index.ts CHANGED
@@ -7,7 +7,6 @@ import type { StandardSchemaV1 } from "@standard-schema/spec";
7
7
  type Schema<I = any, O = any> = StandardSchemaV1<I, O>;
8
8
  type In<S> = S extends Schema<infer I, any> ? I : never;
9
9
  type Out<S> = S extends Schema<any, infer O> ? O : never;
10
- type Awaitable<T> = T | Promise<T>;
11
10
 
12
11
  /** What you declare once in `init<...>()`. */
13
12
  export interface Config {
@@ -42,13 +41,15 @@ export interface Fn<K extends Kind = Kind, I = any, O = any, E extends boolean =
42
41
  readonly outputSchema?: Schema;
43
42
  /** Your own data about the function. Checked against `meta` in `init` where you set it, typed in `wrap`; loose here, for adapters. */
44
43
  readonly meta?: any;
45
- /** Set when the function is exposed: who may call it. Runs on every call. */
46
- readonly check?: (scope: any, input: any) => Awaitable<boolean>;
44
+ /** Who may call it (from `authorize`). Runs on every call, before validation. */
45
+ readonly authorize?: Policy<any>;
46
+ /** `true`: adapters may publish it (HTTP, oRPC, AI tools). Requires `authorize` and `outputSchema`. */
47
+ readonly expose?: true;
47
48
  readonly execute: (input: any, ctx: any) => Promise<any>;
48
49
  /** Phantom types, never set at runtime. */
49
50
  readonly [types]?: { input: I; output: O; exposed: E };
50
51
  }
51
- /** A function with `expose`: adapters publish it. */
52
+ /** A function with `expose: true`: adapters may publish it. */
52
53
  export type ExposedFn<K extends Kind = Kind, I = any, O = any> = Fn<K, I, O, true>;
53
54
  /** What callers pass to a function. */
54
55
  export type FnIn<F> = F extends Fn<any, infer I, any> ? I : never;
@@ -88,11 +89,11 @@ export interface Listener<O = any> {
88
89
  type Run<Allowed extends Kind> = <F extends Fn<Allowed>>(fn: F, input: FnIn<F>) => Promise<FnOut<F>>;
89
90
 
90
91
  /**
91
- * Expected failures, namespaced to the module you're in: inside `bookings`, `ctx.reject("not_pending")` has
92
+ * Expected failures, namespaced to the module you're in: inside `bookings`, `ctx.errors.reject("not_pending")` has
92
93
  * code `"bookings.not_pending"`. Throw what they return. Codes are plain strings on purpose (see the errors docs).
93
94
  */
94
- interface Fail {
95
- /** A business rule said no, and trying again won't help. `throw ctx.reject("not_pending", { status })` */
95
+ export interface Errors {
96
+ /** A business rule said no, and trying again won't help. `throw ctx.errors.reject("not_pending", { status })` */
96
97
  reject(code: string, details?: unknown): DomainError;
97
98
  /** Someone else got there first, or it already exists. Refreshing and retrying may work. */
98
99
  conflict(code: string, details?: unknown): DomainError;
@@ -101,8 +102,10 @@ interface Fail {
101
102
  /** The caller is known but may not do this. Code defaults to `"<module>.<function>.forbidden"`. */
102
103
  deny(code?: string, details?: unknown): DomainError;
103
104
  }
104
- interface BaseCtx<S> extends Fail {
105
+ interface BaseCtx<S> {
105
106
  scope: S;
107
+ /** Expected failures: `throw ctx.errors.reject("not_pending")`. */
108
+ errors: Errors;
106
109
  /** Current time. Fixed in tests. */
107
110
  now: () => Date;
108
111
  }
@@ -134,13 +137,13 @@ export interface ListenerCtx<C extends Config, O = unknown> extends ActionCtx<C>
134
137
  event: Envelope<unknown, ScopeOf<C>> & { payload: O };
135
138
  }
136
139
 
137
- /** Who may call an exposed function. Write it as a type guard (`(s): s is Staff => ...`) to narrow `scope` in `execute`. */
140
+ /**
141
+ * Who may call a function at all: signed in, admin, staff. Sync, reads only the scope, returns exactly `true` to allow.
142
+ * Write it as a type guard (`(s): s is Admin => ...`) to narrow `ctx.scope` in `execute`.
143
+ * Rules about one record ("only the owner may cancel") go in `execute`, after loading it.
144
+ */
138
145
  export type Policy<S> = (scope: S) => boolean;
139
146
  type Guarded<F, S> = F extends (scope: any) => scope is infer G ? G : S;
140
- type Inline<C extends Config, IS extends Schema> = (scope: ScopeOf<C>, input: Out<IS>) => Awaitable<boolean>;
141
- /** A policy name from `init`, or an inline check that also sees the input. */
142
- type Exposure<C extends Config, P, IS extends Schema> = (keyof P & string) | Inline<C, IS>;
143
- type ScopeFor<C extends Config, P, E> = E extends keyof P ? Guarded<P[E], ScopeOf<C>> : ScopeOf<C>;
144
147
  type CtxOf<C extends Config, K extends Kind, S> = K extends "query"
145
148
  ? QueryCtx<C, S>
146
149
  : K extends "mutation"
@@ -153,19 +156,31 @@ type Def<IS extends Schema, Ctx, R> = {
153
156
  inputSchema: IS;
154
157
  execute: (input: Out<IS>, ctx: Ctx) => Promise<R>;
155
158
  };
156
- type Internal = { expose?: undefined };
159
+ type NotExposed = { expose?: undefined };
160
+ type NoPolicy = { authorize?: undefined };
157
161
  type WithMeta<C extends Config> = { meta?: MetaOf<C> };
158
162
  type WithOutput<OS extends Schema> = { outputSchema: OS };
159
163
 
160
- /** Exposed functions must declare `outputSchema`: what leaves your process is a contract. Internal ones may skip it. */
161
- interface Constructor<C extends Config, K extends Kind, P> {
162
- <IS extends Schema, OS extends Schema, const E extends Exposure<C, P, IS>>(
163
- def: Def<IS, CtxOf<C, K, ScopeFor<C, P, E>>, In<OS>> & WithOutput<OS> & WithMeta<C> & { expose: E },
164
+ /**
165
+ * `expose: true` needs `authorize` and `outputSchema`: you can't publish something without saying who may call it,
166
+ * and what leaves your process is a contract. Internal functions may skip both; `authorize` still runs if set.
167
+ */
168
+ interface Constructor<C extends Config, K extends Kind> {
169
+ <IS extends Schema, OS extends Schema, P extends Policy<ScopeOf<C>>>(
170
+ def: Def<IS, CtxOf<C, K, Guarded<P, ScopeOf<C>>>, In<OS>> &
171
+ WithOutput<OS> &
172
+ WithMeta<C> & { authorize: P; expose: true },
164
173
  ): Fn<K, In<IS>, Out<OS>, true>;
174
+ <IS extends Schema, OS extends Schema, P extends Policy<ScopeOf<C>>>(
175
+ def: Def<IS, CtxOf<C, K, Guarded<P, ScopeOf<C>>>, In<OS>> & WithOutput<OS> & WithMeta<C> & { authorize: P } & NotExposed,
176
+ ): Fn<K, In<IS>, Out<OS>, false>;
177
+ <IS extends Schema, R, P extends Policy<ScopeOf<C>>>(
178
+ def: Def<IS, CtxOf<C, K, Guarded<P, ScopeOf<C>>>, R> & WithMeta<C> & { authorize: P } & NotExposed,
179
+ ): Fn<K, In<IS>, R, false>;
165
180
  <IS extends Schema, OS extends Schema>(
166
- def: Def<IS, CtxOf<C, K, ScopeOf<C>>, In<OS>> & WithOutput<OS> & WithMeta<C> & Internal,
181
+ def: Def<IS, CtxOf<C, K, ScopeOf<C>>, In<OS>> & WithOutput<OS> & WithMeta<C> & NoPolicy & NotExposed,
167
182
  ): Fn<K, In<IS>, Out<OS>, false>;
168
- <IS extends Schema, R>(def: Def<IS, CtxOf<C, K, ScopeOf<C>>, R> & WithMeta<C> & Internal): Fn<K, In<IS>, R, false>;
183
+ <IS extends Schema, R>(def: Def<IS, CtxOf<C, K, ScopeOf<C>>, R> & WithMeta<C> & NoPolicy & NotExposed): Fn<K, In<IS>, R, false>;
169
184
  }
170
185
 
171
186
  /* ────────────────────────────────────────────────────────────────────────────
@@ -192,15 +207,12 @@ export class DomainError extends Error {
192
207
  this.details = details;
193
208
  }
194
209
  }
195
- /** For the edge (`resolveScope`): no valid session. Inside modules, use `ctx.deny()`. */
196
- export const unauthenticated = (code = "unauthenticated", details?: unknown) =>
197
- new DomainError("unauthenticated", code, details);
198
210
  /** `isDomainError(e)`, or with a code: `isDomainError(e, "availability.dates_unavailable")`. */
199
211
  export const isDomainError = (e: unknown, code?: string): e is DomainError =>
200
212
  e instanceof DomainError && (code === undefined || e.code === code);
201
213
 
202
- /** `ctx.reject` and friends for one function or listener (`id` like "bookings.confirm"). */
203
- const failFor = (id: string): Fail => {
214
+ /** `ctx.errors` for one function or listener (`id` like "bookings.confirm"). */
215
+ const errorsFor = (id: string): Errors => {
204
216
  const module = id.slice(0, id.indexOf("."));
205
217
  return {
206
218
  reject: (code, details) => new DomainError("rejected", `${module}.${code}`, details),
@@ -297,7 +309,7 @@ export interface Registered {
297
309
  export interface RegisteredFn extends Registered {
298
310
  fn: Fn;
299
311
  kind: Kind;
300
- /** Has `expose`: adapters publish it. */
312
+ /** Has `expose: true`: adapters may publish it. */
301
313
  exposed: boolean;
302
314
  }
303
315
 
@@ -312,39 +324,34 @@ type TypedOptions<C extends Config, Mods extends Record<string, object>> = Omit<
312
324
  ({} extends ServicesOf<C> ? { services?: ServicesOf<C> } : { services: ServicesOf<C> }) &
313
325
  ([DbOf<C>] extends [never] ? { database?: undefined } : { database: DatabaseAdapter<any, DbOf<C>> });
314
326
 
327
+ /** Keys `Config` doesn't know are errors, so a typo like `servises` can't be silently ignored. */
328
+ type OnlyKnownKeys<C> = { [K in Exclude<keyof C, keyof Config>]: never };
329
+
315
330
  /**
316
- * Typed constructors for your app. Curried so policy names are inferred while `Config` is explicit:
331
+ * Typed constructors for your app:
317
332
  *
318
333
  * ```ts
319
- * export const { query, mutation, action, event, on, createRegistry } = init<Config>()({
320
- * policies: { public: () => true, staff: (s): s is Staff => isStaff(s) },
321
- * });
334
+ * export const { query, mutation, action, event, on, createRegistry } = init<Config>();
322
335
  * ```
323
336
  */
324
- /** Keys `Config` doesn't know are errors, so a typo like `servises` can't be silently ignored. */
325
- type OnlyKnownKeys<C> = { [K in Exclude<keyof C, keyof Config>]: never };
326
-
327
- export function init<C extends Config & OnlyKnownKeys<C>>(): Init<C> {
328
- return ((options?: { policies?: Record<string, Policy<any>> }) => constructors<C, {}>(options?.policies ?? {})) as Init<C>;
329
- }
330
-
331
- interface Init<C extends Config> {
332
- (): Constructors<C, {}>;
333
- <P extends Record<string, Policy<ScopeOf<C>>>>(options: { policies: P }): Constructors<C, P>;
337
+ export function init<C extends Config & OnlyKnownKeys<C>>() {
338
+ return constructors<C>();
334
339
  }
335
- type Constructors<C extends Config, P> = ReturnType<typeof constructors<C, P>>;
336
340
 
337
- function constructors<C extends Config, P>(policies: Record<string, Policy<any>>) {
341
+ function constructors<C extends Config>() {
338
342
  const make =
339
343
  <K extends Kind>(kind: K) =>
340
- ({ expose, ...def }: any): any => {
341
- let check: Fn["check"];
342
- if (typeof expose === "function") check = expose;
343
- else if (expose !== undefined) {
344
- check = policies[expose];
345
- if (!check) throw new Error(`[logic-sdk] Unknown policy "${expose}". Define it in init()({ policies }).`);
346
- }
347
- return Object.freeze({ [BRAND]: kind, kind, outputSchema: undefined, ...def, check });
344
+ (def: any): any => {
345
+ const where = def?.description ? `"${def.description}"` : `a ${kind}`;
346
+ if (def.authorize !== undefined && typeof def.authorize !== "function")
347
+ throw new Error(`[logic-sdk] authorize on ${where} must be a policy function, like \`authorize: member\`.`);
348
+ if (def.expose !== undefined && def.expose !== true)
349
+ throw new Error(`[logic-sdk] expose on ${where} must be \`true\` or left out.`);
350
+ if (def.expose && !def.authorize)
351
+ throw new Error(`[logic-sdk] ${where} has expose: true but no authorize. Say who may call it.`);
352
+ if (def.expose && !def.outputSchema)
353
+ throw new Error(`[logic-sdk] ${where} has expose: true but no outputSchema. Say what callers may see.`);
354
+ return Object.freeze({ [BRAND]: kind, kind, outputSchema: undefined, ...def });
348
355
  };
349
356
 
350
357
  return {
@@ -352,11 +359,11 @@ function constructors<C extends Config, P>(policies: Record<string, Policy<any>>
352
359
  createRegistry: <const Mods extends Record<string, object>>(options: TypedOptions<C, Mods>) =>
353
360
  build<ScopeOf<C>, Mods>(options as RegistryOptions<Mods>, {}), // meta in wrap is typed by MetaOf<C>; the values come from typed defs
354
361
  /** Reads data. Can run other queries. No writes, no events, no services. */
355
- query: make("query") as Constructor<C, "query", P>,
362
+ query: make("query") as Constructor<C, "query">,
356
363
  /** Changes data inside one transaction. Can run queries and mutations (same transaction) and emit events. */
357
- mutation: make("mutation") as Constructor<C, "mutation", P>,
364
+ mutation: make("mutation") as Constructor<C, "mutation">,
358
365
  /** Talks to the outside world (payments, email, AI). No transaction; each mutation it runs commits on its own. */
359
- action: make("action") as Constructor<C, "action", P>,
366
+ action: make("action") as Constructor<C, "action">,
360
367
  /** Something that happened. Emitted by mutations, delivered after commit. */
361
368
  event: <S extends Schema>(def: { schema: S; description?: string }): EventDef<In<S>, Out<S>> =>
362
369
  Object.freeze({ [BRAND]: "event" as const, kind: "event" as const, ...def }),
@@ -439,7 +446,7 @@ export function describeModules(modules: Record<string, object>) {
439
446
  else if (kind === "listener") {
440
447
  const listener = value as Listener;
441
448
  listeners.push({ id, module, name, listener, event: listener.event() });
442
- } else functions.push({ id, module, name, kind, fn: value as Fn, exposed: typeof (value as Fn).check === "function" });
449
+ } else functions.push({ id, module, name, kind, fn: value as Fn, exposed: (value as Fn).expose === true });
443
450
  }
444
451
  }
445
452
  return { ids, functions, events, listeners };
@@ -476,14 +483,20 @@ function build<S extends object, Mods extends Record<string, object>>(options: R
476
483
 
477
484
  const idOf = (x: object) => {
478
485
  const id = ids.get(x);
479
- if (!id) throw new Error("[logic-sdk] This function or event isn't registered. Add its module to createRegistry({ modules }).");
486
+ if (!id)
487
+ throw new Error(
488
+ "[logic-sdk] This function or event isn't registered. Export it from its module's index.ts, and add the module to createRegistry({ modules }).",
489
+ );
480
490
  return id;
481
491
  };
482
492
 
483
- async function parseInput(schema: Schema, value: unknown, code: string) {
493
+ /** Bad input from a caller is their error. Bad input from your own code (a nested call) is a bug. */
494
+ async function parseInput(schema: Schema, value: unknown, id: string, nested: boolean) {
484
495
  const r = await schema["~standard"].validate(value);
485
- if (r.issues) throw new DomainError("invalid", code, { issues: describeIssues(r.issues) });
486
- return r.value;
496
+ if (!r.issues) return r.value;
497
+ const issues = describeIssues(r.issues);
498
+ if (nested) throw new Error(`[logic-sdk] ${id} was run with invalid input: ${JSON.stringify(issues)}`);
499
+ throw new DomainError("invalid", `${id}.invalid_input`, { issues });
487
500
  }
488
501
  /** Output and event payloads are produced by our own code: invalid means a bug, not a bad request. */
489
502
  async function parseOwn(schema: Schema, value: unknown, what: string) {
@@ -539,7 +552,7 @@ function build<S extends object, Mods extends Record<string, object>>(options: R
539
552
 
540
553
  function queryCtx(frame: Frame, id: string): QueryCtx<any> {
541
554
  return {
542
- ...failFor(id),
555
+ errors: errorsFor(id),
543
556
  scope: frame.scope,
544
557
  now,
545
558
  signal: frame.opts.signal,
@@ -551,7 +564,7 @@ function build<S extends object, Mods extends Record<string, object>>(options: R
551
564
  function mutationCtx(frame: Frame, id: string): MutationCtx<any> {
552
565
  const tx = frame.tx!;
553
566
  return {
554
- ...failFor(id),
567
+ errors: errorsFor(id),
555
568
  scope: frame.scope,
556
569
  now,
557
570
  signal: frame.opts.signal,
@@ -578,7 +591,7 @@ function build<S extends object, Mods extends Record<string, object>>(options: R
578
591
  }
579
592
  function actionCtx(frame: Frame, id: string): ActionCtx<any> {
580
593
  return {
581
- ...failFor(id),
594
+ errors: errorsFor(id),
582
595
  scope: frame.scope,
583
596
  now,
584
597
  signal: frame.opts.signal,
@@ -596,12 +609,16 @@ function build<S extends object, Mods extends Record<string, object>>(options: R
596
609
 
597
610
  const call: Call = { id, kind: fn.kind, meta: fn.meta, input: rawInput, scope: frame.scope, depth: frame.depth };
598
611
 
599
- /** Validate and check before any transaction opens: bad or denied calls never touch the database. */
612
+ /** Authorize, then validate, before any transaction opens: denied or bad calls never touch the database. */
600
613
  const prepare = async () => {
601
614
  frame.opts.signal?.throwIfAborted();
602
- const input = await parseInput(fn.inputSchema, rawInput, `${id}.invalid_input`);
603
- if (fn.check && !(await fn.check(frame.scope, input))) throw new DomainError("forbidden", `${id}.forbidden`);
604
- return input;
615
+ if (fn.authorize) {
616
+ const allowed: unknown = fn.authorize(frame.scope);
617
+ if (allowed instanceof Promise || typeof (allowed as any)?.then === "function")
618
+ throw new Error(`[logic-sdk] The policy on ${id} returned a Promise. Policies are sync and read only the scope.`);
619
+ if (allowed !== true) throw new DomainError("forbidden", `${id}.forbidden`);
620
+ }
621
+ return parseInput(fn.inputSchema, rawInput, id, frame.depth > 0);
605
622
  };
606
623
  const execute = async (input: unknown, ctx: unknown) => {
607
624
  const stub = o.stubs?.get(fn);
package/src/orpc.ts CHANGED
@@ -10,7 +10,7 @@ type ProcedureOf<S extends object, F> =
10
10
  ? Procedure<ORPCContext<S>, ORPCContext<S>, StandardSchemaV1<I, I>, StandardSchemaV1<O, O>, {}>
11
11
  : never;
12
12
 
13
- /** `{ bookings: { confirm, cancel, … } }`: only functions with `expose`. */
13
+ /** `{ bookings: { confirm, cancel, … } }`: only functions with `expose: true`. */
14
14
  export type ORPCRouterOf<S extends object, Mods> = {
15
15
  [M in keyof Mods as {} extends ExposedOf<Mods[M]> ? never : M]: {
16
16
  [N in keyof ExposedOf<Mods[M]>]: ProcedureOf<S, Mods[M][N & keyof Mods[M]]>;