logic-sdk 0.4.0 → 0.6.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.
Files changed (58) hide show
  1. package/README.md +40 -15
  2. package/bin/logic-sdk.js +1 -1
  3. package/dist/ai.d.ts +16 -26
  4. package/dist/ai.js +8 -21
  5. package/dist/cloudflare.d.ts +55 -0
  6. package/dist/cloudflare.js +85 -0
  7. package/dist/drizzle/pg.d.ts +236 -0
  8. package/dist/drizzle/pg.js +67 -0
  9. package/dist/drizzle/sqlite.d.ts +242 -0
  10. package/dist/drizzle/sqlite.js +194 -0
  11. package/dist/errors.d.ts +33 -0
  12. package/dist/errors.js +45 -0
  13. package/dist/fetch.d.ts +15 -18
  14. package/dist/fetch.js +18 -55
  15. package/dist/index.d.ts +78 -379
  16. package/dist/index.js +240 -186
  17. package/dist/jobs.d.ts +44 -0
  18. package/dist/jobs.js +252 -0
  19. package/dist/node.d.ts +26 -0
  20. package/dist/node.js +76 -0
  21. package/dist/orpc.d.ts +10 -17
  22. package/dist/orpc.js +19 -28
  23. package/dist/pg-boss.d.ts +55 -0
  24. package/dist/pg-boss.js +211 -0
  25. package/dist/postgres.d.ts +28 -0
  26. package/dist/postgres.js +82 -0
  27. package/dist/schedule.d.ts +23 -0
  28. package/dist/schedule.js +109 -0
  29. package/dist/sqlite.d.ts +9 -0
  30. package/dist/sqlite.js +65 -0
  31. package/dist/stored-jobs.d.ts +64 -0
  32. package/dist/stored-jobs.js +188 -0
  33. package/dist/testing.d.ts +50 -14
  34. package/dist/testing.js +198 -46
  35. package/dist/types.d.ts +655 -0
  36. package/dist/types.js +6 -0
  37. package/package.json +45 -7
  38. package/skills/logic-sdk/SKILL.md +114 -0
  39. package/src/ai.ts +23 -46
  40. package/src/cloudflare.ts +107 -0
  41. package/src/drizzle/pg.ts +110 -0
  42. package/src/drizzle/sqlite.ts +236 -0
  43. package/src/errors.ts +59 -0
  44. package/src/fetch.ts +17 -65
  45. package/src/index.ts +404 -564
  46. package/src/jobs.ts +296 -0
  47. package/src/node.ts +99 -0
  48. package/src/orpc.ts +24 -42
  49. package/src/pg-boss.ts +242 -0
  50. package/src/postgres.ts +90 -0
  51. package/src/schedule.ts +129 -0
  52. package/src/sqlite.ts +74 -0
  53. package/src/stored-jobs.ts +260 -0
  54. package/src/testing.ts +252 -55
  55. package/src/types.ts +685 -0
  56. package/dist/drizzle.d.ts +0 -18
  57. package/dist/drizzle.js +0 -23
  58. package/src/drizzle.ts +0 -39
@@ -0,0 +1,236 @@
1
+ import { sql, type SQL } from "drizzle-orm";
2
+ import { index, integer, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
3
+ import type { DatabaseAdapter, Job, ReadWrite, SqlDatabase } from "../index.ts";
4
+ import { causes } from "../errors.ts";
5
+
6
+ export { databaseQueue, jobsSchema, outbox, type DatabaseQueueOptions, type OutboxOptions, type StoredJobs } from "../sqlite.ts";
7
+
8
+ /** A Drizzle database on a synchronous SQLite driver: node:sqlite, bun:sqlite, better-sqlite3. */
9
+ interface SyncSqlite {
10
+ all<T>(query: SQL): T[];
11
+ run(query: SQL): unknown;
12
+ $client: { close(): unknown };
13
+ }
14
+
15
+ /** What mutations get: a connection of their own, inside the transaction the adapter opened. */
16
+ export type DrizzleTx<Db> = Omit<Db, "transaction" | "$client">;
17
+
18
+ /** What queries get: the reading connection, minus write methods. SQLite refuses a write on it too (`query_only`). */
19
+ export type DrizzleReader<Db> = Omit<Db, "insert" | "update" | "delete" | "run" | "transaction" | "batch" | "$client">;
20
+
21
+ /** Your database in `Config`: `db: DrizzleDb<ReturnType<typeof open>>`, where `open` is what `drizzleAdapter` gets. */
22
+ export type DrizzleDb<Db> = ReadWrite<DrizzleReader<Db>, DrizzleTx<Db>>;
23
+
24
+ export type DrizzleAdapterOptions = Pick<DatabaseAdapter, "transactionAttempts">;
25
+
26
+ /** Milliseconds to wait for another writer before failing. Rails' default `timeout`. */
27
+ const BUSY_TIMEOUT = 5000;
28
+
29
+ /**
30
+ * Use SQLite on a disk for mutations, through Drizzle on a synchronous driver, set up like Rails: WAL, and
31
+ * `BEGIN IMMEDIATE`. `open` opens a connection: one stays to read, and each transaction gets its own, closed when it
32
+ * ends, so a write that arrives late is refused instead of landing outside it. Call this once per process.
33
+ *
34
+ * ```ts
35
+ * const database = drizzleAdapter(() => drizzle("app.db"));
36
+ * ```
37
+ */
38
+ export function drizzleAdapter<Db extends SyncSqlite>(
39
+ open: () => Db,
40
+ options: DrizzleAdapterOptions = {},
41
+ ): SqlDatabase<DrizzleReader<Db>, DrizzleTx<Db>> {
42
+ const reader = open();
43
+ checkOpen(open, reader);
44
+ exec(reader, `PRAGMA busy_timeout = ${BUSY_TIMEOUT}`); // in WAL a read only waits while a crash is being recovered
45
+ exec(reader, "PRAGMA query_only = ON");
46
+
47
+ const takeTurn = turns();
48
+ const transaction = <T>(fn: (tx: DrizzleTx<Db>) => Promise<T>) =>
49
+ takeTurn(async (restartClock) => {
50
+ const tx = await begin(open, restartClock);
51
+ try {
52
+ const out = await fn(tx);
53
+ exec(tx, "COMMIT");
54
+ return out;
55
+ } catch (e) {
56
+ undo(tx, "ROLLBACK");
57
+ throw e;
58
+ } finally {
59
+ tx.$client.close();
60
+ }
61
+ });
62
+
63
+ return {
64
+ db: reader,
65
+ transactionAttempts: options.transactionAttempts,
66
+ transaction,
67
+ nest: (tx) => savepoints(tx),
68
+ retryable: isBusy,
69
+ // on a transaction, inside it. On the database, a transaction of its own that waits its turn, like any write
70
+ query: async (client: Pick<SyncSqlite, "all">, text, params) =>
71
+ client === reader ? transaction(async (tx) => rowsOf(tx, text, params)) : rowsOf(client, text, params),
72
+ };
73
+ }
74
+
75
+ /** Transactions inside a transaction, as savepoints: the test registry's. */
76
+ function savepoints<Tx extends Pick<SyncSqlite, "all" | "run">>(tx: Tx): SqlDatabase<Tx, Tx> {
77
+ const takeTurn = turns();
78
+ return {
79
+ db: tx,
80
+ transaction: (fn) =>
81
+ takeTurn(async () => {
82
+ exec(tx, "SAVEPOINT logic_sdk");
83
+ try {
84
+ const out = await fn(tx);
85
+ exec(tx, "RELEASE logic_sdk");
86
+ return out;
87
+ } catch (e) {
88
+ undo(tx, "ROLLBACK TO logic_sdk", "RELEASE logic_sdk"); // rolling back to a savepoint keeps it
89
+ throw e;
90
+ }
91
+ }),
92
+ nest: savepoints,
93
+ query: async (client, text, params) => rowsOf(client, text, params),
94
+ };
95
+ }
96
+
97
+ const exec = (db: Pick<SyncSqlite, "run">, text: string) => db.run(sql.raw(text));
98
+
99
+ /** SQL text with `?` parameters as a Drizzle query. */
100
+ const toSql = (text: string, params: unknown[]) =>
101
+ sql.join(text.split("?").flatMap((part, i) => (i ? [sql.param(params[i - 1]), sql.raw(part)] : [sql.raw(part)])));
102
+
103
+ const rowsOf = (db: Pick<SyncSqlite, "all">, text: string, params: unknown[]) =>
104
+ db.all<Record<string, unknown>>(toSql(text, params));
105
+
106
+ /** SQLite rolls some failures back by itself (a full disk, `RAISE(ROLLBACK)`): then there's nothing to undo, and the error that did it is the one to report. */
107
+ function undo(db: Pick<SyncSqlite, "run">, ...statements: string[]) {
108
+ try {
109
+ for (const statement of statements) exec(db, statement);
110
+ } catch {}
111
+ }
112
+
113
+ /** Refused at startup: either mistake would otherwise show up later, as missing writes or a closed connection. */
114
+ function checkOpen<Db extends SyncSqlite>(open: () => Db, reader: Db) {
115
+ const another = open();
116
+ if (another.$client === reader.$client)
117
+ throw new Error('[logic-sdk] drizzleAdapter needs a function that opens a new connection each time: drizzleAdapter(() => drizzle("app.db")).');
118
+ const [main] = another.all<{ file: string }>(sql`PRAGMA database_list`);
119
+ another.$client.close();
120
+ if (!main?.file)
121
+ throw new Error("[logic-sdk] drizzleAdapter needs SQLite on a disk: an in-memory database is a different one on each connection. Use a temporary file in tests.");
122
+ }
123
+
124
+ /**
125
+ * A new connection that holds the write lock. Another process may have it: we wait here, with the event loop free,
126
+ * since waiting inside SQLite stops the whole process on a synchronous driver (Rails' busy handler, for the same reason).
127
+ */
128
+ async function begin<Db extends SyncSqlite>(open: () => Db, restartClock: () => void): Promise<Db> {
129
+ const deadline = Date.now() + BUSY_TIMEOUT;
130
+ for (;;) {
131
+ restartClock(); // those behind us in line time how long we hold the lock, not how long another process does
132
+ let tx: Db | undefined;
133
+ try {
134
+ tx = open();
135
+ exec(tx, "PRAGMA busy_timeout = 0");
136
+ exec(tx, "PRAGMA journal_mode = WAL"); // here, not at startup: processes starting together would find it locked
137
+ exec(tx, "BEGIN IMMEDIATE");
138
+ return tx;
139
+ } catch (e) {
140
+ tx?.$client.close();
141
+ if (!isBusy(e) || Date.now() >= deadline) throw e;
142
+ }
143
+ await new Promise((resolve) => setTimeout(resolve, 1 + Math.random() * 4));
144
+ }
145
+ }
146
+
147
+ /**
148
+ * One at a time, in order, since SQLite has one writer. Waiting in a line that moves is fine, however long. It fails
149
+ * when the transaction ahead has held the lock for 5 seconds: often one that waits for a call behind it, forever.
150
+ */
151
+ function turns() {
152
+ let last = Promise.resolve();
153
+ let startedAt = 0;
154
+ const restartClock = () => {
155
+ startedAt = Date.now();
156
+ };
157
+ return async <T>(work: (restartClock: () => void) => Promise<T>): Promise<T> => {
158
+ const arrived = Date.now();
159
+ const ahead = last;
160
+ const done = Promise.withResolvers<void>();
161
+ last = ahead.then(() => done.promise);
162
+ try {
163
+ const giveUpAt = () => Math.max(arrived, startedAt) + BUSY_TIMEOUT;
164
+ while (!(await settlesBy(ahead, giveUpAt()))) {
165
+ // the one ahead may have changed while we waited: the line moved
166
+ if (Date.now() >= giveUpAt()) throw new Error(HELD);
167
+ }
168
+ restartClock();
169
+ return await work(restartClock);
170
+ } finally {
171
+ done.resolve();
172
+ }
173
+ };
174
+ }
175
+
176
+ const HELD =
177
+ "[logic-sdk] Waited 5 seconds for a transaction in this process, and SQLite writes one at a time. Does a mutation await registry.as(scope).run instead of ctx.run, or do slow work that belongs in an action? In tests, is a t.begin() still open?";
178
+
179
+ /** Whether `promise` settles by then. The timer is cleared, so a process with nothing else to do can exit. */
180
+ const settlesBy = (promise: Promise<void>, time: number) =>
181
+ new Promise<boolean>((resolve) => {
182
+ const timer = setTimeout(() => resolve(false), time - Date.now());
183
+ void promise.then(() => {
184
+ clearTimeout(timer);
185
+ resolve(true);
186
+ });
187
+ });
188
+
189
+ /** SQLITE_BUSY, also when Drizzle wraps it: someone else is writing. Laravel matches the same message. */
190
+ function isBusy(error: unknown): boolean {
191
+ for (const e of causes(error))
192
+ if (("code" in e && e.code === "SQLITE_BUSY") || (e instanceof Error && /database is locked/.test(e.message))) return true;
193
+ return false;
194
+ }
195
+
196
+ const now = sql`(cast(unixepoch('subsec') * 1000 as integer))`;
197
+
198
+ /**
199
+ * The table behind `databaseQueue` and `outbox` (SQLite), Laravel's `jobs`. Re-export it from your schema so
200
+ * drizzle-kit adds it to your migrations: `export { jobsTable } from "logic-sdk/drizzle/sqlite";`. One row per pending
201
+ * job; done rows are deleted, failed ones stay so you can query them and `retry` them.
202
+ */
203
+ export const jobsTable = sqliteTable(
204
+ "logic_jobs",
205
+ {
206
+ /** The job id: `<listener id>@<event id>`, `<cron id>@<minute>`, or `<function id>@<uuid>`. */
207
+ id: text("id").primaryKey(),
208
+ job: text("job", { mode: "json" }).$type<Job>().notNull(),
209
+ /** `failed`: out of attempts, or a rule said no. Retrying is your call (`registry.jobs.retry(id)`). */
210
+ status: text("status").$type<"pending" | "failed">().notNull().default("pending"),
211
+ /** Incremented when a runner claims it, so a crash still uses an attempt. */
212
+ attempts: integer("attempts").notNull().default(0),
213
+ /** Due from then on. While claimed: when the lease ends and a sweep may take it over. */
214
+ availableAt: integer("available_at", { mode: "timestamp_ms" }).notNull().default(now),
215
+ /** The claim that owns it: a new one each time it's claimed, like SQS's receipt handle. Only it can finish the job. */
216
+ receipt: text("receipt"),
217
+ /** The last failure, with its stack. */
218
+ lastError: text("last_error"),
219
+ failedAt: integer("failed_at", { mode: "timestamp_ms" }),
220
+ /** A scheduled call's `replace` key, `<function id>@<key>`: a newer call with it replaces this row while it waits. */
221
+ replaceKey: text("replace_key"),
222
+ createdAt: integer("created_at", { mode: "timestamp_ms" }).notNull().default(now),
223
+ },
224
+ (t) => [
225
+ index("logic_jobs_due").on(t.availableAt).where(sql`${t.status} = 'pending'`),
226
+ // one waiting call per key: a claimed row (attempts > 0) has started, so a newer one doesn't touch it
227
+ uniqueIndex("logic_jobs_replace").on(t.replaceKey).where(sql`status = 'pending' and attempts = 0`),
228
+ ],
229
+ );
230
+
231
+ /** The cron runs already ticked, so a minute ticked twice runs once. Re-export it next to `jobsTable` when you have crons. */
232
+ export const cronRunsTable = sqliteTable("logic_cron_runs", {
233
+ /** The cron job's id, `<cron id>@<minute>`. */
234
+ id: text("id").primaryKey(),
235
+ ranAt: integer("ran_at", { mode: "timestamp_ms" }).notNull().default(now),
236
+ });
package/src/errors.ts ADDED
@@ -0,0 +1,59 @@
1
+ import type { StandardSchemaV1 } from "@standard-schema/spec";
2
+ import type { Errors } from "./types.ts";
3
+
4
+ /* ────────────────────────────────────────────────────────────────────────────
5
+ * Errors
6
+ * ──────────────────────────────────────────────────────────────────────────── */
7
+
8
+ export type ErrorKind = "invalid" | "unauthenticated" | "forbidden" | "not_found" | "conflict" | "rejected";
9
+
10
+ /**
11
+ * An expected failure: a `kind` (a small fixed set), a namespaced `code` and optional `details`. No HTTP here;
12
+ * adapters map kinds to statuses. Anything else thrown (including invalid output or event payloads, which are
13
+ * bugs) is unexpected: adapters answer 500 and report it.
14
+ */
15
+ export class DomainError extends Error {
16
+ readonly kind: ErrorKind;
17
+ readonly code: string;
18
+ readonly details: unknown;
19
+ constructor(kind: ErrorKind, code: string, details?: unknown) {
20
+ // the details are in the message too: logs and AI tool errors (which show only the message) stay useful
21
+ super(details === undefined ? code : `${code} ${JSON.stringify(details)}`);
22
+ this.name = "DomainError";
23
+ this.kind = kind;
24
+ this.code = code;
25
+ this.details = details;
26
+ }
27
+ }
28
+ /** `isDomainError(e)`, or with a code: `isDomainError(e, "availability.dates_unavailable")`. */
29
+ export const isDomainError = (e: unknown, code?: string): e is DomainError =>
30
+ e instanceof DomainError && (code === undefined || e.code === code);
31
+
32
+ /** `ctx.errors` for one function or listener (`id` like "bookings.confirm"). */
33
+ export const errorsFor = (id: string): Errors => {
34
+ const module = id.slice(0, id.indexOf("."));
35
+ return {
36
+ reject: (code, details) => new DomainError("rejected", `${module}.${code}`, details),
37
+ conflict: (code, details) => new DomainError("conflict", `${module}.${code}`, details),
38
+ notFound: (code = "not_found", details) => new DomainError("not_found", `${module}.${code}`, details),
39
+ deny: (code, details) => new DomainError("forbidden", code ? `${module}.${code}` : `${id}.forbidden`, details),
40
+ };
41
+ };
42
+
43
+ /** What a schema said, as JSON: `[{ message, path }]`. */
44
+ export const describeIssues = (issues: readonly StandardSchemaV1.Issue[]) =>
45
+ issues.map((i) => ({ message: i.message, path: i.path?.map((p) => (typeof p === "object" ? p.key : p)) }));
46
+
47
+ /** A payload that stopped matching its event's schema (a deploy changed it while it waited): delivering again won't help. */
48
+ export class StalePayload extends Error {}
49
+
50
+ /**
51
+ * Throw where there's no valid session, outside your functions (a route, a middleware): `toResponse` makes it a 401.
52
+ * Inside a function, a policy answers instead (a scope with no actor, then `forbidden`).
53
+ */
54
+ export const unauthenticated = (code = "unauthenticated", details?: unknown) => new DomainError("unauthenticated", code, details);
55
+
56
+ /** An error and the ones it wraps (`cause`), five deep at most: a driver's error usually arrives wrapped by the ORM. */
57
+ export function* causes(error: unknown): Generator<object> {
58
+ for (let e = error, i = 0; typeof e === "object" && e !== null && i < 5; e = "cause" in e ? e.cause : undefined, i++) yield e;
59
+ }
package/src/fetch.ts CHANGED
@@ -1,11 +1,4 @@
1
- import { DomainError, isDomainError, 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);
1
+ import { isDomainError, type ErrorKind } from "./index.ts";
9
2
 
10
3
  /** Error kind → HTTP status. The only place statuses exist: core errors know nothing about HTTP. */
11
4
  export const statusOf: Record<ErrorKind, number> = {
@@ -17,63 +10,22 @@ export const statusOf: Record<ErrorKind, number> = {
17
10
  rejected: 422,
18
11
  };
19
12
 
20
- export interface FetchOptions<S extends object> {
21
- /** Build the scope for this request (session → actor, account, locale...). */
22
- resolveScope: (request: Request, ...rest: any[]) => S | Promise<S>;
23
- /** Mount point. Default "/". Functions live at `${basePath}${id}`, e.g. `/api/bookings.confirm`. */
24
- basePath?: string;
25
- /** Unexpected (non-domain) errors. Default: console.error. */
26
- onError?: (error: unknown) => void;
27
- }
28
-
29
- const json = (body: unknown, status = 200) =>
30
- new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
31
-
32
13
  /**
33
- * A web-standard handler (Workers, Bun, Node via Hono or srvx, SvelteKit, Next route handlers...).
34
- * Publishes only functions with `expose: true`. POST `{base}{id}` with a JSON body (`content-type: application/json` required);
35
- * queries also accept GET `?input=<json>`.
14
+ * A domain error as a JSON response, `{ error: { kind, code, details } }` with its status, for your own routes
15
+ * (Hono, Next route handlers, anything web-standard). Anything else is thrown again, so your framework makes the 500
16
+ * and logs it, and its message never reaches the client.
17
+ *
18
+ * ```ts
19
+ * app.post("/orders", async (c) => {
20
+ * try {
21
+ * return c.json(await c.var.caller.run(orders.place, await c.req.json()), 201);
22
+ * } catch (e) {
23
+ * return toResponse(e);
24
+ * }
25
+ * });
26
+ * ```
36
27
  */
37
- export function toFetchHandler<S extends object>(registry: Registry<S>, options: FetchOptions<S>) {
38
- const base = (options.basePath ?? "/").replace(/\/?$/, "/");
39
- const exposed = new Map(registry.functions.filter((f) => f.exposed).map((f) => [f.id, f]));
40
- const onError = options.onError ?? ((e) => console.error("[logic-sdk] unexpected error", e));
41
-
42
- return async (request: Request, ...rest: any[]): Promise<Response> => {
43
- const path = new URL(request.url).pathname;
44
- if (!path.startsWith(base)) return json({ error: { kind: "not_found", code: "route_not_found" } }, 404);
45
- const id = path.slice(base.length);
46
-
47
- const entry = exposed.get(id);
48
- if (!entry) return json({ error: { kind: "not_found", code: "function_not_found" } }, 404);
49
-
50
- let input: unknown;
51
- try {
52
- if (request.method === "POST") {
53
- // JSON only: blocks cross-site "simple" form posts (CSRF) because they can't send this content type without a preflight
54
- if (!(request.headers.get("content-type") ?? "").toLowerCase().startsWith("application/json"))
55
- return json({ error: { kind: "invalid", code: "unsupported_media_type" } }, 415);
56
- const text = await request.text();
57
- input = text ? JSON.parse(text) : undefined;
58
- } else if (request.method === "GET" && entry.kind === "query") {
59
- const raw = new URL(request.url).searchParams.get("input");
60
- input = raw ? JSON.parse(raw) : undefined;
61
- } else {
62
- const res = json({ error: { kind: "invalid", code: "method_not_allowed" } }, 405);
63
- res.headers.set("allow", entry.kind === "query" ? "GET, POST" : "POST");
64
- return res;
65
- }
66
- } catch {
67
- return json({ error: { kind: "invalid", code: "malformed_json" } }, 400);
68
- }
69
-
70
- try {
71
- const scope = await options.resolveScope(request, ...rest);
72
- return json({ data: await registry.as(scope).run(entry.fn, input, { signal: request.signal }) });
73
- } catch (e) {
74
- if (isDomainError(e)) return json({ error: { kind: e.kind, code: e.code, details: e.details } }, statusOf[e.kind]);
75
- onError(e);
76
- return json({ error: { kind: "internal", code: "internal_error" } }, 500);
77
- }
78
- };
28
+ export function toResponse(error: unknown): Response {
29
+ if (!isDomainError(error)) throw error;
30
+ return Response.json({ error: { kind: error.kind, code: error.code, details: error.details } }, { status: statusOf[error.kind] });
79
31
  }