logic-sdk 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +126 -2
- package/bin/logic-sdk.js +14 -0
- package/dist/ai.d.ts +32 -0
- package/dist/ai.js +39 -0
- package/dist/drizzle.d.ts +18 -0
- package/dist/drizzle.js +23 -0
- package/dist/fetch.d.ts +20 -0
- package/dist/fetch.js +68 -0
- package/dist/index.d.ts +440 -0
- package/dist/index.js +374 -0
- package/dist/orpc.d.ts +31 -0
- package/dist/orpc.js +46 -0
- package/dist/testing.d.ts +29 -0
- package/dist/testing.js +61 -0
- package/package.json +106 -4
- package/src/ai.ts +64 -0
- package/src/drizzle.ts +39 -0
- package/src/fetch.ts +81 -0
- package/src/index.ts +719 -0
- package/src/orpc.ts +65 -0
- package/src/testing.ts +88 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Franco Romano Losada
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,127 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Logic SDK
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**Business logic for TypeScript apps, as queries, mutations, actions and events.**
|
|
4
|
+
|
|
5
|
+
Write the layer between your routes and your database once, as plain declarations. Call it from an HTTP route, a Server Action, a queue worker, a script, a test or an AI agent: same rules, same transaction, same events.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm i logic-sdk zod
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Node 26+, Bun or Cloudflare Workers. Postgres through Drizzle for mutations.
|
|
14
|
+
|
|
15
|
+
## Quick start
|
|
16
|
+
|
|
17
|
+
Declare your types and policies once:
|
|
18
|
+
|
|
19
|
+
```ts
|
|
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
|
+
});
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Write a module:
|
|
31
|
+
|
|
32
|
+
```ts
|
|
33
|
+
// src/bookings/mutations.ts
|
|
34
|
+
export const confirm = mutation({
|
|
35
|
+
description: "Confirm a pending booking",
|
|
36
|
+
inputSchema: z.object({ bookingId: z.uuid() }),
|
|
37
|
+
outputSchema: Booking,
|
|
38
|
+
expose: "staff",
|
|
39
|
+
|
|
40
|
+
async execute({ bookingId }, ctx) {
|
|
41
|
+
const booking = await findBooking(ctx, bookingId);
|
|
42
|
+
if (booking.status !== "pending") {
|
|
43
|
+
throw ctx.reject("not_pending");
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// Another module, in the same transaction
|
|
47
|
+
await ctx.run(availability.hold, rangeOf(booking));
|
|
48
|
+
|
|
49
|
+
// Delivered to listeners only after commit
|
|
50
|
+
ctx.emit(confirmed, { bookingId });
|
|
51
|
+
|
|
52
|
+
return setStatus(ctx, booking.id, "confirmed");
|
|
53
|
+
},
|
|
54
|
+
});
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Register your modules and call them from anywhere:
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
// src/registry.ts
|
|
61
|
+
export const registry = createRegistry({
|
|
62
|
+
modules: { bookings, availability },
|
|
63
|
+
database: drizzleAdapter(db),
|
|
64
|
+
services: { mailer, payments },
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
// a route, a job, a script, a test
|
|
68
|
+
const caller = registry.as({ actor, accountId });
|
|
69
|
+
await caller.run(bookings.confirm, { bookingId });
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## What you get
|
|
73
|
+
|
|
74
|
+
- **One transaction across modules.** A failure anywhere rolls back everything, even if someone catches it.
|
|
75
|
+
- **Side effects after commit.** Mutations emit events; listeners send the email once the data is safe.
|
|
76
|
+
- **Lost races retried.** Deadlocks and serialization failures re-run the mutation in a fresh transaction.
|
|
77
|
+
- **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.
|
|
81
|
+
- **Tests without mocks.** Each test is a real transaction on a real database, always rolled back.
|
|
82
|
+
- **No magic.** No decorators, classes, codegen, build step or `AsyncLocalStorage`.
|
|
83
|
+
|
|
84
|
+
## Adapters
|
|
85
|
+
|
|
86
|
+
| Import | |
|
|
87
|
+
|---|---|
|
|
88
|
+
| `logic-sdk/drizzle` | The database adapter |
|
|
89
|
+
| `logic-sdk/fetch` | A web-standard HTTP handler for exposed functions |
|
|
90
|
+
| `logic-sdk/orpc` | A typed oRPC v2 router and client |
|
|
91
|
+
| `logic-sdk/ai` | AI SDK tools: agents run your functions with the same rules |
|
|
92
|
+
| `logic-sdk/testing` | Rolled-back test transactions, stubs, frozen time |
|
|
93
|
+
|
|
94
|
+
## CLI
|
|
95
|
+
|
|
96
|
+
```bash
|
|
97
|
+
npm i -D @logic-sdk/cli
|
|
98
|
+
npx logic-sdk list # every function, its kind and policy
|
|
99
|
+
logic-sdk show bookings.confirm # schemas, what it runs and emits, who calls it
|
|
100
|
+
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
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
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.
|
|
105
|
+
|
|
106
|
+
## Examples
|
|
107
|
+
|
|
108
|
+
- [`examples/node`](examples/node): a bookings app. Six modules, Hono, Postgres, and a race test on real Postgres.
|
|
109
|
+
- [`examples/workers`](examples/workers): a link shortener on Cloudflare Workers, Hyperdrive and `waitUntil`.
|
|
110
|
+
- [`examples/nextjs`](examples/nextjs): a Server Action and an AI agent calling the same `bookings.confirm`.
|
|
111
|
+
|
|
112
|
+
## Docs
|
|
113
|
+
|
|
114
|
+
The docs site lives in [`apps/web`](apps/web) (`bun run --filter web dev`). Start with the [introduction](apps/web/docs/index.mdx) and the [quickstart](apps/web/docs/02-quickstart.mdx). [`AGENTS.md`](AGENTS.md) is the short version for coding agents.
|
|
115
|
+
|
|
116
|
+
## Repository
|
|
117
|
+
|
|
118
|
+
```bash
|
|
119
|
+
bun install
|
|
120
|
+
bun run test # build, typecheck, lint, package checks, all tests
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
`packages/logic-sdk` is the library, tested with `bun test`. `examples/node` runs on PGlite by default and on real Postgres with `DATABASE_URL` (`bun run test:pg`), which CI always sets. `examples/workers` runs inside workerd. Decisions and their reasons are in [DESIGN.md](DESIGN.md); what's next is in [ROADMAP.md](ROADMAP.md).
|
|
124
|
+
|
|
125
|
+
## License
|
|
126
|
+
|
|
127
|
+
MIT
|
package/bin/logic-sdk.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// `npx logic-sdk check`. The CLI itself lives in @logic-sdk/cli, so apps that never use it
|
|
3
|
+
// (a Worker, a Next.js app) don't download its parser and loader.
|
|
4
|
+
const CLI = "@logic-sdk/cli";
|
|
5
|
+
|
|
6
|
+
let cli;
|
|
7
|
+
try {
|
|
8
|
+
cli = await import(CLI);
|
|
9
|
+
} catch (error) {
|
|
10
|
+
if (error?.code !== "ERR_MODULE_NOT_FOUND" || !String(error.message).includes(CLI)) throw error;
|
|
11
|
+
console.error(`The logic-sdk CLI isn't installed in this project. Add it with:\n\n npm i -D ${CLI}\n`);
|
|
12
|
+
process.exit(1);
|
|
13
|
+
}
|
|
14
|
+
await cli.main(process.argv.slice(2));
|
package/dist/ai.d.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { type Tool } from "ai";
|
|
2
|
+
import { type Caller, type Fn, type FnIn, type FnOut, type Registry, type RegisteredFn } from "./index.ts";
|
|
3
|
+
type ExposedOf<T> = {
|
|
4
|
+
[N in keyof T as T[N] extends Fn<any, any, any, true> ? N : never]: T[N];
|
|
5
|
+
};
|
|
6
|
+
type UnionToIntersection<U> = (U extends unknown ? (u: U) => void : never) extends (i: infer I) => void ? I : never;
|
|
7
|
+
/** `{ bookings_confirm, pricing_priceStay, … }`: one AI SDK tool per exposed function, typed. */
|
|
8
|
+
export type AIToolsOf<Mods> = UnionToIntersection<{
|
|
9
|
+
[M in keyof Mods & string]: {
|
|
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
|
+
};
|
|
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;
|
|
16
|
+
/** Unexpected (non-domain) errors. The model only sees "internal_error". Default: console.error. */
|
|
17
|
+
onError?: (error: unknown) => void;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
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>`.
|
|
22
|
+
*
|
|
23
|
+
* ```ts
|
|
24
|
+
* const caller = registry.as(await scopeFrom(request));
|
|
25
|
+
* await generateText({ model, tools: toAITools(registry, caller), prompt });
|
|
26
|
+
* ```
|
|
27
|
+
*
|
|
28
|
+
* Domain errors reach the model (it sees the code and can react). Anything unexpected is reported
|
|
29
|
+
* to `onError` and the model gets "internal_error", so internals never land in its context.
|
|
30
|
+
*/
|
|
31
|
+
export declare function toAITools<S extends object, Mods extends Record<string, object>>(registry: Registry<S, Mods>, caller: Caller<S>, options?: AIToolsOptions): AIToolsOf<Mods>;
|
|
32
|
+
export {};
|
package/dist/ai.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { tool } from "ai";
|
|
2
|
+
import { isDomainError } from "./index.js";
|
|
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>`.
|
|
6
|
+
*
|
|
7
|
+
* ```ts
|
|
8
|
+
* const caller = registry.as(await scopeFrom(request));
|
|
9
|
+
* await generateText({ model, tools: toAITools(registry, caller), prompt });
|
|
10
|
+
* ```
|
|
11
|
+
*
|
|
12
|
+
* Domain errors reach the model (it sees the code and can react). Anything unexpected is reported
|
|
13
|
+
* to `onError` and the model gets "internal_error", so internals never land in its context.
|
|
14
|
+
*/
|
|
15
|
+
export function toAITools(registry, caller, options = {}) {
|
|
16
|
+
const onError = options.onError ?? ((e) => console.error("[logic-sdk] tool failed unexpectedly", e));
|
|
17
|
+
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
|
+
}
|
|
38
|
+
return tools;
|
|
39
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { DatabaseAdapter } from "./index.ts";
|
|
2
|
+
/** Anything with Drizzle's `transaction(fn)`: a database or a transaction (nested = savepoint). */
|
|
3
|
+
interface Transactional {
|
|
4
|
+
transaction<T>(fn: (tx: any) => Promise<T>, config?: any): Promise<T>;
|
|
5
|
+
}
|
|
6
|
+
/** The transaction type of a Drizzle database: `type Tx = DrizzleTx<typeof db>`. */
|
|
7
|
+
export type DrizzleTx<Db extends Transactional> = Parameters<Parameters<Db["transaction"]>[0]>[0];
|
|
8
|
+
/** What queries get: the database minus write methods. A type-level guard, not a runtime one. */
|
|
9
|
+
export type DrizzleReader<Db> = Omit<Db, "insert" | "update" | "delete" | "execute" | "transaction" | "batch" | "run" | "refreshMaterializedView">;
|
|
10
|
+
/**
|
|
11
|
+
* Use a Drizzle database for mutations. Needs a driver with interactive transactions
|
|
12
|
+
* (node-postgres, postgres.js, PGlite, Neon websocket, Hyperdrive, better-sqlite3, libsql...).
|
|
13
|
+
* Not D1 or HTTP drivers.
|
|
14
|
+
*/
|
|
15
|
+
export declare function drizzleAdapter<Db extends Transactional>(db: Db): DatabaseAdapter<Db, DrizzleTx<Db>>;
|
|
16
|
+
/** The SQLSTATE of a driver error, also when Drizzle wraps it (`DrizzleQueryError.cause`). Use it to map constraints. */
|
|
17
|
+
export declare function sqlState(error: unknown): string | undefined;
|
|
18
|
+
export {};
|
package/dist/drizzle.js
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Use a Drizzle database for mutations. Needs a driver with interactive transactions
|
|
3
|
+
* (node-postgres, postgres.js, PGlite, Neon websocket, Hyperdrive, better-sqlite3, libsql...).
|
|
4
|
+
* Not D1 or HTTP drivers.
|
|
5
|
+
*/
|
|
6
|
+
export function drizzleAdapter(db) {
|
|
7
|
+
return {
|
|
8
|
+
db,
|
|
9
|
+
transactions: "interactive",
|
|
10
|
+
transaction: (fn) => db.transaction(fn),
|
|
11
|
+
nest: (tx) => drizzleAdapter(tx),
|
|
12
|
+
retryable: (e) => RETRYABLE.has(sqlState(e) ?? ""),
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
/** Postgres: serialization_failure, deadlock_detected. The transaction lost a race; running it again is the fix. */
|
|
16
|
+
const RETRYABLE = new Set(["40001", "40P01"]);
|
|
17
|
+
/** The SQLSTATE of a driver error, also when Drizzle wraps it (`DrizzleQueryError.cause`). Use it to map constraints. */
|
|
18
|
+
export function sqlState(error) {
|
|
19
|
+
for (let e = error, i = 0; e && i < 5; e = e.cause, i++)
|
|
20
|
+
if (typeof e.code === "string")
|
|
21
|
+
return e.code;
|
|
22
|
+
return undefined;
|
|
23
|
+
}
|
package/dist/fetch.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type CallerOptions, type ErrorKind, type Registry } from "./index.ts";
|
|
2
|
+
/** Error kind → HTTP status. The only place statuses exist: core errors know nothing about HTTP. */
|
|
3
|
+
export declare const statusOf: Record<ErrorKind, number>;
|
|
4
|
+
export interface FetchOptions<S extends object> {
|
|
5
|
+
/** Build the scope for this request (session → actor, account, locale...). */
|
|
6
|
+
resolveScope: (request: Request, ...rest: any[]) => S | Promise<S>;
|
|
7
|
+
/** Per-request caller options, e.g. `(req) => ({ signal: req.signal })`. */
|
|
8
|
+
callerOptions?: (request: Request, ...rest: any[]) => CallerOptions;
|
|
9
|
+
/** Mount point. Default "/". Functions live at `${basePath}${id}`, e.g. `/api/bookings.confirm`. */
|
|
10
|
+
basePath?: string;
|
|
11
|
+
/** Unexpected (non-domain) errors. Default: console.error. */
|
|
12
|
+
onError?: (error: unknown) => void;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* 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);
|
|
17
|
+
* queries also accept GET `?input=<json>`.
|
|
18
|
+
* GET `{base}` lists what's exposed.
|
|
19
|
+
*/
|
|
20
|
+
export declare function toFetchHandler<S extends object>(registry: Registry<S, any>, options: FetchOptions<S>): (request: Request, ...rest: any[]) => Promise<Response>;
|
package/dist/fetch.js
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { isDomainError } from "./index.js";
|
|
2
|
+
/** Error kind → HTTP status. The only place statuses exist: core errors know nothing about HTTP. */
|
|
3
|
+
export const statusOf = {
|
|
4
|
+
invalid: 400,
|
|
5
|
+
unauthenticated: 401,
|
|
6
|
+
forbidden: 403,
|
|
7
|
+
not_found: 404,
|
|
8
|
+
conflict: 409,
|
|
9
|
+
rejected: 422,
|
|
10
|
+
};
|
|
11
|
+
const json = (body, status = 200) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
12
|
+
/**
|
|
13
|
+
* 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);
|
|
15
|
+
* queries also accept GET `?input=<json>`.
|
|
16
|
+
* GET `{base}` lists what's exposed.
|
|
17
|
+
*/
|
|
18
|
+
export function toFetchHandler(registry, options) {
|
|
19
|
+
const base = (options.basePath ?? "/").replace(/\/?$/, "/");
|
|
20
|
+
const exposed = new Map(registry.functions.filter((f) => f.exposed).map((f) => [f.id, f]));
|
|
21
|
+
const onError = options.onError ?? ((e) => console.error("[logic-sdk] unexpected error", e));
|
|
22
|
+
return async (request, ...rest) => {
|
|
23
|
+
const path = new URL(request.url).pathname;
|
|
24
|
+
if (!path.startsWith(base))
|
|
25
|
+
return json({ error: { kind: "not_found", code: "route_not_found" } }, 404);
|
|
26
|
+
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
|
+
const entry = exposed.get(id);
|
|
32
|
+
if (!entry)
|
|
33
|
+
return json({ error: { kind: "not_found", code: "function_not_found" } }, 404);
|
|
34
|
+
let input;
|
|
35
|
+
try {
|
|
36
|
+
if (request.method === "POST") {
|
|
37
|
+
// JSON only: blocks cross-site "simple" form posts (CSRF) because they can't send this content type without a preflight
|
|
38
|
+
if (!(request.headers.get("content-type") ?? "").toLowerCase().startsWith("application/json"))
|
|
39
|
+
return json({ error: { kind: "invalid", code: "unsupported_media_type" } }, 415);
|
|
40
|
+
const text = await request.text();
|
|
41
|
+
input = text ? JSON.parse(text) : undefined;
|
|
42
|
+
}
|
|
43
|
+
else if (request.method === "GET" && entry.kind === "query") {
|
|
44
|
+
const raw = new URL(request.url).searchParams.get("input");
|
|
45
|
+
input = raw ? JSON.parse(raw) : undefined;
|
|
46
|
+
}
|
|
47
|
+
else {
|
|
48
|
+
const res = json({ error: { kind: "invalid", code: "method_not_allowed" } }, 405);
|
|
49
|
+
res.headers.set("allow", entry.kind === "query" ? "GET, POST" : "POST");
|
|
50
|
+
return res;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
return json({ error: { kind: "invalid", code: "malformed_json" } }, 400);
|
|
55
|
+
}
|
|
56
|
+
try {
|
|
57
|
+
const scope = await options.resolveScope(request, ...rest);
|
|
58
|
+
const caller = registry.as(scope, options.callerOptions?.(request, ...rest));
|
|
59
|
+
return json({ data: await caller.run(entry.fn, input) });
|
|
60
|
+
}
|
|
61
|
+
catch (e) {
|
|
62
|
+
if (isDomainError(e))
|
|
63
|
+
return json({ error: { kind: e.kind, code: e.code, details: e.details } }, statusOf[e.kind]);
|
|
64
|
+
onError(e);
|
|
65
|
+
return json({ error: { kind: "internal", code: "internal_error" } }, 500);
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
}
|