durable-db 0.7.0 → 0.9.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.
@@ -0,0 +1,24 @@
1
+ //#region src/db/describeAction.ts
2
+ /** On a compiled call site: what `registerAction()` was told. */
3
+ const ACTION_INFO = Symbol.for("durable-db.actionInfo");
4
+ /** On an untransformed action (see ./defineDatabase). */
5
+ const ACTION_TEST_META = Symbol.for("durable-db.actionTestMeta");
6
+ /** The description of an action, or undefined for anything that is not one. */
7
+ function describeAction(action) {
8
+ if (typeof action !== "function") return void 0;
9
+ const tagged = action;
10
+ const info = tagged[ACTION_INFO];
11
+ if (info) return {
12
+ database: info.database,
13
+ name: info.name,
14
+ args: info.args
15
+ };
16
+ const meta = tagged[ACTION_TEST_META];
17
+ if (meta) return {
18
+ database: null,
19
+ name: null,
20
+ args: meta.validator
21
+ };
22
+ }
23
+ //#endregion
24
+ export { describeAction as n, ACTION_INFO as t };
@@ -1,4 +1,5 @@
1
- import "./defineDatabase-COek3gjm.js";
1
+ import "./defineDatabase-BvFOZVkv.js";
2
+ import { i as OutboxSink, t as Outbox } from "./outbox-D3Q9n7Rt.js";
2
3
  import { SQLiteTableWithColumns } from "drizzle-orm/sqlite-core";
3
4
  import { CamelCasePlugin, CamelCasePlugin as CamelCasePlugin$1, CompiledQuery, Kysely, Kysely as Kysely$1, KyselyPlugin, KyselyPlugin as KyselyPlugin$1, PluginTransformQueryArgs, PluginTransformResultArgs, QueryResult, QueryResult as QueryResult$1, RootOperationNode, UnknownRow } from "kysely";
4
5
  import { DurableObject } from "cloudflare:workers";
@@ -180,6 +181,33 @@ declare abstract class SqliteDurableObject<Env = unknown> extends DurableObject<
180
181
  */
181
182
  private pitrUnavailableReason;
182
183
  constructor(ctx: DurableObjectState, env: Env);
184
+ /**
185
+ * Where the outbox delivers (`./outbox`): the generated class sets it from
186
+ * `durableDb({ outbox })`. Null: `ctx.outbox.push()` refuses, naming the option.
187
+ */
188
+ protected outboxSink: OutboxSink | null;
189
+ private outboxReady;
190
+ private ensureOutboxTable;
191
+ /**
192
+ * Runs an action with `ctx.outbox`. The messages it pushed are written when
193
+ * it resolves — in the same synchronous block as its last writes, which the
194
+ * Durable Object commits together — and the alarm that delivers them is set
195
+ * with them. A handler that throws records nothing. An action called from
196
+ * another action of this database runs on the caller's context, and so on
197
+ * its outbox.
198
+ */
199
+ protected runWithOutbox<T>(ctx: {
200
+ instanceKey: string;
201
+ outbox?: Outbox;
202
+ }, run: () => Promise<T>): Promise<T>;
203
+ /**
204
+ * Delivers the outbox: up to OUTBOX_DELIVERY_SIZE messages, oldest first, to
205
+ * the sink; what was delivered is deleted, and the alarm comes back while
206
+ * more are waiting. A delivery that throws stays in the table and is retried
207
+ * with backoff (5 s, doubling, at most 5 minutes), so a message arrives at
208
+ * least once. A subclass with an alarm of its own calls `super.alarm()`.
209
+ */
210
+ alarm(): Promise<void>;
183
211
  /**
184
212
  * Check if PITR is available on this DO's storage.
185
213
  * Result is cached after the first call.
package/dist/index.d.ts CHANGED
@@ -1,6 +1,23 @@
1
- import { l as type } from "./index-bUUlOWfP.js";
2
- import { c as DatabaseDefinition, d as InferArgs, i as ActionContext, n as Action, r as ActionConfig, s as DatabaseConfig, t as defineDatabase, u as DrizzleToKysely } from "./defineDatabase-COek3gjm.js";
1
+ import { i as Type, l as type } from "./index-bUUlOWfP.js";
2
+ import { _ as RelationMap, b as relationOf, c as DatabaseDefinition, d as InferArgs, g as Relation, h as RelatedOptions, i as ActionContext, m as RelatedExpression, n as Action, p as Related, r as ActionConfig, s as DatabaseConfig, t as defineDatabase, u as DrizzleToKysely, v as RelationType, x as relationsOf, y as Relations } from "./defineDatabase-BvFOZVkv.js";
3
+ import { a as OutboxSinkContext, i as OutboxSink, n as OutboxEnvelope, o as OutboxSinkModule, r as OutboxMessage, t as Outbox } from "./outbox-D3Q9n7Rt.js";
3
4
  import { getTenantId, hasTenantId, setTenantIdResolver } from "./context/index.js";
4
5
  import { AnySQLiteColumn, blob, foreignKey, index, integer, numeric, primaryKey, real, table, text, uniqueIndex } from "./schema.js";
5
6
  import { Kysely } from "kysely";
6
- export { type Action, type ActionConfig, type ActionContext, type AnySQLiteColumn, type DatabaseConfig, type DatabaseDefinition, type DrizzleToKysely, type InferArgs, type Kysely, blob, defineDatabase, foreignKey, getTenantId, hasTenantId, index, integer, numeric, primaryKey, real, setTenantIdResolver, table, text, type, uniqueIndex };
7
+ //#region src/db/describeAction.d.ts
8
+ interface ActionDescription {
9
+ /** The database it belongs to, as discovered (`main`); null untransformed. */
10
+ database: string | null;
11
+ /** Its export name; null untransformed. */
12
+ name: string | null;
13
+ /**
14
+ * Its compiled args schema: the `type()` of its `args` — `.toJsonSchema()`,
15
+ * `.expression`, or call it to validate. Undefined only for a call site
16
+ * registered by hand without one.
17
+ */
18
+ args: Type | undefined;
19
+ }
20
+ /** The description of an action, or undefined for anything that is not one. */
21
+ export declare function describeAction(action: unknown): ActionDescription | undefined;
22
+ //#endregion
23
+ export { type Action, type ActionConfig, type ActionContext, type ActionDescription, type AnySQLiteColumn, type DatabaseConfig, type DatabaseDefinition, type DrizzleToKysely, type InferArgs, type Kysely, type Outbox, type OutboxEnvelope, type OutboxMessage, type OutboxSink, type OutboxSinkContext, type OutboxSinkModule, type Related, RelatedExpression, type RelatedOptions, type Relation, type RelationMap, type RelationType, type Relations, blob, defineDatabase, foreignKey, getTenantId, hasTenantId, index, integer, numeric, primaryKey, real, relationOf, relationsOf, setTenantIdResolver, table, text, type, uniqueIndex };
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
+ import { d as relationOf, f as relationsOf, i as RelatedExpression, n as defineDatabase } from "./defineDatabase-CaqKQagA.js";
1
2
  import { r as type } from "./type-CUgZsZp3.js";
2
3
  import "./actionArgs-DP2tQrlf.js";
3
- import { n as defineDatabase } from "./defineDatabase-595bNB6M.js";
4
4
  import { blob, foreignKey, index, integer, numeric, primaryKey, real, table, text, uniqueIndex } from "./schema.js";
5
+ import { n as describeAction } from "./describeAction-CEKfxTQ4.js";
5
6
  import { getTenantId, hasTenantId, setTenantIdResolver } from "./context/index.js";
6
- export { blob, defineDatabase, foreignKey, getTenantId, hasTenantId, index, integer, numeric, primaryKey, real, setTenantIdResolver, table, text, type, uniqueIndex };
7
+ export { RelatedExpression, blob, defineDatabase, describeAction, foreignKey, getTenantId, hasTenantId, index, integer, numeric, primaryKey, real, relationOf, relationsOf, setTenantIdResolver, table, text, type, uniqueIndex };
@@ -0,0 +1,278 @@
1
+ import { a as createRelatedPlugins, l as createDrizzlePlugins, o as DateSerializePlugin } from "./defineDatabase-CaqKQagA.js";
2
+ import { CamelCasePlugin, Kysely, SqliteDialect, SqliteQueryCompiler } from "kysely";
3
+ //#region src/db/outbox.ts
4
+ /** A sink module's default export as a sink: a deliver function, or an object with one. */
5
+ function outboxSink(module) {
6
+ if (typeof module === "function") return { deliver: module };
7
+ if (module && typeof module.deliver === "function") return module;
8
+ throw new TypeError("[db] An outbox module must default-export a deliver function, or an object with one");
9
+ }
10
+ /** Cloudflare Queues takes at most 100 messages per sendBatch. */
11
+ const QUEUE_BATCH = 100;
12
+ /** Each message to the Queue binding `binding`, as it was pushed. */
13
+ function queueOutboxSink(binding) {
14
+ return { async deliver(envelopes, { env }) {
15
+ const queue = env[binding];
16
+ if (!queue?.sendBatch) throw new Error(`[db] The outbox sends to the Queue binding ${binding}, which this worker does not have`);
17
+ for (let i = 0; i < envelopes.length; i += QUEUE_BATCH) await queue.sendBatch(envelopes.slice(i, i + QUEUE_BATCH).map((envelope) => ({ body: envelope.message })));
18
+ } };
19
+ }
20
+ const OUTBOX_TABLE = "__outbox";
21
+ const OUTBOX_DDL = `CREATE TABLE IF NOT EXISTS ${OUTBOX_TABLE} (
22
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
23
+ instance_key TEXT NOT NULL,
24
+ message TEXT NOT NULL,
25
+ recorded_at INTEGER NOT NULL,
26
+ attempts INTEGER NOT NULL DEFAULT 0,
27
+ last_error TEXT
28
+ )`;
29
+ /** The wait before retrying a failed delivery: 5 s, doubling, at most 5 minutes. */
30
+ function outboxRetryDelay(attempts) {
31
+ return Math.min(5e3 * 2 ** Math.max(0, attempts - 1), 3e5);
32
+ }
33
+ /** The tenant an instance key belongs to (its dev epoch suffix dropped); null for a global database. */
34
+ function tenantOfInstanceKey(instanceKey) {
35
+ const suffixAt = instanceKey.lastIndexOf("__dev_");
36
+ const tenant = suffixAt === -1 ? instanceKey : instanceKey.slice(0, suffixAt);
37
+ return tenant === "global" ? null : tenant;
38
+ }
39
+ /**
40
+ * The outbox of one action run: `push()` collects, and once the handler has
41
+ * resolved `take()` hands the messages over to be written. A message must be
42
+ * a JSON value; it is checked (serialized) when pushed, so a bad one fails
43
+ * the action that pushed it rather than a delivery later.
44
+ */
45
+ function createActionOutbox(sinkConfigured) {
46
+ let messages = [];
47
+ return {
48
+ push(message) {
49
+ if (!sinkConfigured) throw new Error("[db] ctx.outbox.push(): no outbox sink is configured — durableDb({ outbox: { queue: \"<QUEUE_BINDING>\" } }) or durableDb({ outbox: { module: \"./src/outbox.ts\" } })");
50
+ const json = JSON.stringify(message);
51
+ if (json === void 0) throw new TypeError("[db] ctx.outbox.push(): a message must be a JSON value");
52
+ messages.push(json);
53
+ },
54
+ take() {
55
+ const taken = messages;
56
+ messages = [];
57
+ return taken;
58
+ }
59
+ };
60
+ }
61
+ //#endregion
62
+ //#region src/db/kysely.ts
63
+ const MAX_BOUND_PARAMETERS = 100;
64
+ /**
65
+ * Kysely's SQLite compiler with identifiers quoted in backticks instead of
66
+ * double quotes. SQLite (workerd's build included) reads a double-quoted
67
+ * identifier that names no column as a string literal, so a column missing
68
+ * from the database — a schema change not yet migrated — silently selects its
69
+ * own name (`"weight_grams"` → 'weight_grams') and a WHERE on it compares two
70
+ * constants. A backtick-quoted identifier is never a literal: the query fails
71
+ * with "no such column". The migrations already quote with backticks.
72
+ */
73
+ var BacktickSqliteQueryCompiler = class extends SqliteQueryCompiler {
74
+ getLeftIdentifierWrapper() {
75
+ return "`";
76
+ }
77
+ getRightIdentifierWrapper() {
78
+ return "`";
79
+ }
80
+ sanitizeIdentifier(identifier) {
81
+ return identifier.replaceAll("`", "``");
82
+ }
83
+ };
84
+ /**
85
+ * workerd has no boolean binding type and silently stringifies JS booleans
86
+ * (storing TEXT 'true' in an INTEGER column); node:sqlite rejects them
87
+ * outright. Normalize to SQLite's 1/0 convention before the value reaches
88
+ * either. `undefined` → NULL for the same reason.
89
+ */
90
+ function normalizeParameter(value) {
91
+ if (typeof value === "boolean") return value ? 1 : 0;
92
+ if (value === void 0) return null;
93
+ return value;
94
+ }
95
+ function escapeLiteral(value) {
96
+ if (value === null || value === void 0) return "NULL";
97
+ if (typeof value === "boolean") return value ? "1" : "0";
98
+ if (typeof value === "number") {
99
+ if (!Number.isFinite(value)) throw new Error(`[db] Cannot inline non-finite number parameter (${value})`);
100
+ return String(value);
101
+ }
102
+ if (typeof value === "bigint") return value.toString();
103
+ if (typeof value === "string") {
104
+ if (value.includes("\0")) throw new Error("[db] Cannot inline a string parameter containing a NUL byte");
105
+ return `'${value.replaceAll("'", "''")}'`;
106
+ }
107
+ if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {
108
+ const bytes = value instanceof ArrayBuffer ? new Uint8Array(value) : new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
109
+ let hex = "";
110
+ for (const b of bytes) hex += b.toString(16).padStart(2, "0");
111
+ return `X'${hex}'`;
112
+ }
113
+ throw new Error(`[db] Cannot inline SQL parameter of type ${typeof value}`);
114
+ }
115
+ /**
116
+ * Replace each `?` placeholder in `sql` with the escaped literal of its
117
+ * parameter. A real scanner, not a regex: '…' string literals ('' escapes),
118
+ * "…" and `…` quoted identifiers, `--` line comments and C-style block
119
+ * comments are skipped, so a `?` inside any of them is never touched.
120
+ *
121
+ * Exported for tests.
122
+ */
123
+ function inlineParameters(sql, parameters) {
124
+ let out = "";
125
+ let p = 0;
126
+ for (let i = 0; i < sql.length; i++) {
127
+ const ch = sql[i];
128
+ if (ch === "'" || ch === "\"" || ch === "`") {
129
+ let j = i + 1;
130
+ while (j < sql.length) {
131
+ if (sql[j] === ch) {
132
+ if (sql[j + 1] === ch) {
133
+ j += 2;
134
+ continue;
135
+ }
136
+ break;
137
+ }
138
+ j++;
139
+ }
140
+ out += sql.slice(i, j + 1);
141
+ i = j;
142
+ continue;
143
+ }
144
+ if (ch === "-" && sql[i + 1] === "-") {
145
+ let j = sql.indexOf("\n", i);
146
+ if (j === -1) j = sql.length;
147
+ out += sql.slice(i, j);
148
+ i = j - 1;
149
+ continue;
150
+ }
151
+ if (ch === "/" && sql[i + 1] === "*") {
152
+ let j = sql.indexOf("*/", i + 2);
153
+ j = j === -1 ? sql.length : j + 2;
154
+ out += sql.slice(i, j);
155
+ i = j - 1;
156
+ continue;
157
+ }
158
+ if (ch === "?") {
159
+ if (p >= parameters.length) throw new Error("[db] Query has more `?` placeholders than parameters while inlining");
160
+ out += escapeLiteral(parameters[p++]);
161
+ continue;
162
+ }
163
+ out += ch;
164
+ }
165
+ if (p !== parameters.length) throw new Error(`[db] Inlined ${p} parameter(s) but the query provided ${parameters.length} — placeholder/parameter mismatch`);
166
+ return out;
167
+ }
168
+ /**
169
+ * A Kysely driver that uses Cloudflare DO SQLite storage
170
+ */
171
+ var CloudflareSqliteDriver = class {
172
+ sql;
173
+ constructor(sql) {
174
+ this.sql = sql;
175
+ }
176
+ async init() {}
177
+ async acquireConnection() {
178
+ return new CloudflareSqliteConnection(this.sql);
179
+ }
180
+ async beginTransaction(connection, settings) {
181
+ if (settings.isolationLevel) throw new Error("SQLite does not support isolation levels");
182
+ await connection.executeQuery(createCompiledQuery("BEGIN"));
183
+ }
184
+ async commitTransaction(connection) {
185
+ await connection.executeQuery(createCompiledQuery("COMMIT"));
186
+ }
187
+ async rollbackTransaction(connection) {
188
+ await connection.executeQuery(createCompiledQuery("ROLLBACK"));
189
+ }
190
+ async releaseConnection() {}
191
+ async destroy() {}
192
+ };
193
+ /**
194
+ * Helper to create a CompiledQuery object
195
+ */
196
+ function createCompiledQuery(sql, parameters = []) {
197
+ return {
198
+ sql,
199
+ parameters,
200
+ query: {
201
+ kind: "RawNode",
202
+ sqlFragments: [sql],
203
+ parameters: []
204
+ }
205
+ };
206
+ }
207
+ /**
208
+ * A Kysely connection that wraps Cloudflare's SqlStorage
209
+ */
210
+ var CloudflareSqliteConnection = class {
211
+ sql;
212
+ constructor(sql) {
213
+ this.sql = sql;
214
+ }
215
+ async executeQuery(compiledQuery) {
216
+ let queryStr = compiledQuery.sql;
217
+ let parameters = compiledQuery.parameters.map(normalizeParameter);
218
+ if (parameters.length > MAX_BOUND_PARAMETERS) {
219
+ queryStr = inlineParameters(queryStr, parameters);
220
+ parameters = [];
221
+ }
222
+ const isSelect = /^\s*(SELECT|RETURNING)/i.test(queryStr) || /\s+RETURNING\s+/i.test(queryStr);
223
+ try {
224
+ if (isSelect) return {
225
+ rows: this.sql.exec(queryStr, ...parameters).toArray(),
226
+ numAffectedRows: void 0,
227
+ insertId: void 0
228
+ };
229
+ else {
230
+ this.sql.exec(queryStr, ...parameters);
231
+ const [result] = this.sql.exec("SELECT changes() AS changes, last_insert_rowid() AS id").toArray();
232
+ const changes = result?.changes ?? 0;
233
+ const lastId = result?.id;
234
+ return {
235
+ rows: [],
236
+ numAffectedRows: BigInt(changes),
237
+ insertId: typeof lastId === "number" || typeof lastId === "bigint" ? BigInt(lastId) : void 0
238
+ };
239
+ }
240
+ } catch (error) {
241
+ throw error;
242
+ }
243
+ }
244
+ streamQuery() {
245
+ throw new Error("Streaming is not supported in Cloudflare SQLite");
246
+ }
247
+ };
248
+ /**
249
+ * Create a Kysely instance from Cloudflare SqlStorage
250
+ *
251
+ * @param sqlStorage - The Cloudflare SqlStorage instance
252
+ * @param options - Configuration options including schema for plugins
253
+ */
254
+ function createKyselyFromSql(sqlStorage, options = {}) {
255
+ const { schema, plugins = [], camelCase = true } = options;
256
+ const sqliteDialect = new SqliteDialect({ database: null });
257
+ const allPlugins = [];
258
+ const related = schema ? createRelatedPlugins(schema) : void 0;
259
+ if (related) allPlugins.push(related.capture);
260
+ if (schema) allPlugins.push(...createDrizzlePlugins(schema, camelCase));
261
+ else if (camelCase) {
262
+ allPlugins.push(new CamelCasePlugin());
263
+ allPlugins.push(new DateSerializePlugin());
264
+ } else allPlugins.push(new DateSerializePlugin());
265
+ allPlugins.push(...plugins);
266
+ if (related) allPlugins.push(related.results);
267
+ return new Kysely({
268
+ dialect: {
269
+ createAdapter: () => sqliteDialect.createAdapter(),
270
+ createDriver: () => new CloudflareSqliteDriver(sqlStorage),
271
+ createIntrospector: (db) => sqliteDialect.createIntrospector(db),
272
+ createQueryCompiler: () => new BacktickSqliteQueryCompiler()
273
+ },
274
+ plugins: allPlugins
275
+ });
276
+ }
277
+ //#endregion
278
+ export { outboxRetryDelay as a, tenantOfInstanceKey as c, createActionOutbox as i, OUTBOX_DDL as n, outboxSink as o, OUTBOX_TABLE as r, queueOutboxSink as s, createKyselyFromSql as t };
@@ -0,0 +1,41 @@
1
+ //#region src/db/outbox.d.ts
2
+ /** What a message may be: declare it once with `declare global { interface DurableDbOutbox { message: MyMessage } }`. */
3
+ declare global {
4
+ interface DurableDbOutbox {}
5
+ }
6
+ /** The message `ctx.outbox.push()` takes: `DurableDbOutbox['message']` when declared, else any JSON value. */
7
+ type OutboxMessage = DurableDbOutbox extends {
8
+ message: infer M;
9
+ } ? M : unknown;
10
+ /** What an action records messages with. */
11
+ interface Outbox {
12
+ /** Records `message` (a JSON value) for delivery after the action succeeds. */
13
+ push(message: OutboxMessage): void;
14
+ }
15
+ /** A recorded message, as the sink gets it. */
16
+ interface OutboxEnvelope<M = OutboxMessage> {
17
+ message: M;
18
+ /** The instance key of the Durable Object that recorded it. */
19
+ instanceKey: string;
20
+ /** The tenant of a per-tenant database's instance (its key without the dev epoch); null for a global database. */
21
+ tenantId: string | null;
22
+ /** When the action recorded it (ms since the epoch). */
23
+ recordedAt: number;
24
+ }
25
+ interface OutboxSinkContext<Env = unknown> {
26
+ /** The Durable Object's env: the worker's bindings. */
27
+ env: Env;
28
+ }
29
+ /** Where the outbox delivers. A delivery that throws is retried, every envelope of it. */
30
+ interface OutboxSink<Env = unknown> {
31
+ deliver(envelopes: OutboxEnvelope[], context: OutboxSinkContext<Env>): Promise<void> | void;
32
+ }
33
+ type OutboxSinkModule<Env = unknown> = OutboxSink<Env> | OutboxSink<Env>['deliver'];
34
+ /** A sink module's default export as a sink: a deliver function, or an object with one. */
35
+ declare function outboxSink<Env = unknown>(module: OutboxSinkModule<Env>): OutboxSink<Env>;
36
+ /** Each message to the Queue binding `binding`, as it was pushed. */
37
+ declare function queueOutboxSink(binding: string): OutboxSink;
38
+ /** The tenant an instance key belongs to (its dev epoch suffix dropped); null for a global database. */
39
+ declare function tenantOfInstanceKey(instanceKey: string): string | null;
40
+ //#endregion
41
+ export { OutboxSinkContext as a, queueOutboxSink as c, OutboxSink as i, tenantOfInstanceKey as l, OutboxEnvelope as n, OutboxSinkModule as o, OutboxMessage as r, outboxSink as s, Outbox as t };
@@ -1,4 +1,5 @@
1
1
  import { o as TypeParser } from "./index-bUUlOWfP.js";
2
+ import { t as Outbox } from "./outbox-D3Q9n7Rt.js";
2
3
  //#region src/db/actionArgs.d.ts
3
4
  /**
4
5
  * `type` (durable-db/type: ArkType's definitions and types), for an
@@ -29,6 +30,10 @@ declare const actionArgsType: TypeParser;
29
30
  export interface ActionDefinition {
30
31
  validator: (args: unknown) => unknown;
31
32
  handler: (db: unknown, args: unknown, ctx: unknown) => Promise<unknown>;
33
+ /** The compiled args schema (a `type()`), for `describeAction()`. */
34
+ args?: unknown;
35
+ /** The call site the build compiled this action to: `describeAction()` reads the description from it. */
36
+ stub?: object;
32
37
  }
33
38
  export interface DoContext {
34
39
  db: unknown;
@@ -42,9 +47,22 @@ export interface RpcContext {
42
47
  dbBindingNames: Record<string, string>;
43
48
  dbTransports?: Record<string, 'rpc' | 'websocket'>;
44
49
  instanceKey: string;
50
+ /** The action run's outbox (`runWithOutbox`); an action called from another of the same database shares it. */
51
+ outbox?: Outbox;
45
52
  }
46
53
  export declare function registerAction(dbName: string, actionName: string, def: ActionDefinition): void;
47
54
  export declare function getAction(dbName: string, actionName: string): ActionDefinition | undefined;
55
+ /**
56
+ * Registers an action every database has: `stub.rpc(actionName, args)` runs it
57
+ * in whichever Durable Object is called, with that database's `db` and the
58
+ * action context — for a library that works on any schema (a query executor,
59
+ * an exporter). A database's own action of the same name wins; give a shared
60
+ * action a name no export can have (`"graph:run"`).
61
+ *
62
+ * Opt-in: nothing is registered unless a module calls this, and the module
63
+ * has to be loaded in the Durable Object's isolate (the worker's entry is).
64
+ */
65
+ export declare function registerSharedAction(actionName: string, def: ActionDefinition): void;
48
66
  export declare function getDoContext(): DoContext | undefined;
49
67
  export declare function runWithDoContext<T>(store: DoContext, fn: () => T): T;
50
68
  /**
package/dist/registry.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { r as type } from "./type-CUgZsZp3.js";
2
2
  import { t as actionArgsType } from "./actionArgs-DP2tQrlf.js";
3
+ import { t as ACTION_INFO } from "./describeAction-CEKfxTQ4.js";
3
4
  import { WebSocketTransport } from "./transport/websocket.js";
4
5
  import { AsyncLocalStorage } from "node:async_hooks";
5
6
  //#region src/registry.ts
@@ -23,9 +24,36 @@ function registerAction(dbName, actionName, def) {
23
24
  actionsByDb.set(dbName, dbMap);
24
25
  }
25
26
  dbMap.set(actionName, def);
27
+ if (def.stub) Object.defineProperty(def.stub, ACTION_INFO, {
28
+ value: {
29
+ database: dbName,
30
+ name: actionName,
31
+ args: def.args
32
+ },
33
+ enumerable: false,
34
+ configurable: true
35
+ });
26
36
  }
27
37
  function getAction(dbName, actionName) {
28
- return actionsByDb.get(dbName)?.get(actionName);
38
+ return actionsByDb.get(dbName)?.get(actionName) ?? sharedActions().get(actionName);
39
+ }
40
+ const SHARED_ACTIONS = Symbol.for("durable-db.sharedActions");
41
+ function sharedActions() {
42
+ const store = globalThis;
43
+ return store[SHARED_ACTIONS] ??= /* @__PURE__ */ new Map();
44
+ }
45
+ /**
46
+ * Registers an action every database has: `stub.rpc(actionName, args)` runs it
47
+ * in whichever Durable Object is called, with that database's `db` and the
48
+ * action context — for a library that works on any schema (a query executor,
49
+ * an exporter). A database's own action of the same name wins; give a shared
50
+ * action a name no export can have (`"graph:run"`).
51
+ *
52
+ * Opt-in: nothing is registered unless a module calls this, and the module
53
+ * has to be loaded in the Durable Object's isolate (the worker's entry is).
54
+ */
55
+ function registerSharedAction(actionName, def) {
56
+ sharedActions().set(actionName, def);
29
57
  }
30
58
  function getOrThrow(dbName, actionName) {
31
59
  const entry = getAction(dbName, actionName);
@@ -140,4 +168,4 @@ function flushCalls(namespace, instanceKey, byKey) {
140
168
  });
141
169
  }
142
170
  //#endregion
143
- export { batchedRpc, cachedArgsSchema, callAction, getAction, getDoContext, registerAction, runWithDoContext, actionArgsType as type };
171
+ export { batchedRpc, cachedArgsSchema, callAction, getAction, getDoContext, registerAction, registerSharedAction, runWithDoContext, actionArgsType as type };
package/dist/schema.d.ts CHANGED
@@ -1,5 +1,18 @@
1
- import { AnySQLiteColumn, blob, foreignKey, index, integer, numeric, primaryKey, real, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
1
+ import { AnySQLiteColumn as AnySQLiteColumn$1, UpdateDeleteAction, blob, foreignKey, index, integer, numeric, primaryKey, real, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
2
+ import { ColumnBuilderBaseConfig, ColumnBuilderExtraConfig, ColumnDataType } from "drizzle-orm";
2
3
  //#region src/schema.d.ts
4
+ declare module 'drizzle-orm/sqlite-core/columns/common' {
5
+ interface SQLiteColumnBuilder<T extends ColumnBuilderBaseConfig<ColumnDataType, string> = ColumnBuilderBaseConfig<ColumnDataType, string>, TRuntimeConfig extends object = object, TTypeConfig extends object = object, TExtraConfig extends ColumnBuilderExtraConfig = object> {
6
+ references<C extends AnySQLiteColumn>(ref: () => C, actions?: {
7
+ onUpdate?: UpdateDeleteAction;
8
+ onDelete?: UpdateDeleteAction;
9
+ }): this & {
10
+ _: {
11
+ references: C;
12
+ };
13
+ };
14
+ }
15
+ }
3
16
  export declare const table: typeof sqliteTable;
4
17
  //#endregion
5
- export { type AnySQLiteColumn, blob, foreignKey, index, integer, numeric, primaryKey, real, text, uniqueIndex };
18
+ export { type AnySQLiteColumn$1 as AnySQLiteColumn, blob, foreignKey, index, integer, numeric, primaryKey, real, text, uniqueIndex };
@@ -1,3 +1,4 @@
1
+ import { i as OutboxSink, n as OutboxEnvelope } from "../outbox-D3Q9n7Rt.js";
1
2
  import { SQLiteTableWithColumns } from "drizzle-orm/sqlite-core";
2
3
  import { Kysely } from "kysely";
3
4
  import { DatabaseSync } from "node:sqlite";
@@ -20,6 +21,14 @@ export interface CreateTestDatabaseOptions {
20
21
  * that reads the tenant id.
21
22
  */
22
23
  tenantId?: string;
24
+ /**
25
+ * Delivers what an action pushed to `ctx.outbox`, after the action
26
+ * succeeds, as the Durable Object's sink would (awaited before `run()`
27
+ * returns). Every envelope is also kept in {@link TestDatabase.outbox}.
28
+ */
29
+ outbox?: OutboxSink['deliver'];
30
+ /** The `ctx.env` handlers see. Defaults to `{}`. */
31
+ env?: Record<string, unknown>;
23
32
  }
24
33
  export interface TestDatabase<TSchema = any> {
25
34
  /** The Kysely instance, for direct seeding and assertions. */
@@ -36,6 +45,8 @@ export interface TestDatabase<TSchema = any> {
36
45
  run<TArgs, TResult>(action: (args: TArgs) => Promise<TResult>, args: TArgs): Promise<TResult>;
37
46
  /** The raw `node:sqlite` handle, for escape-hatch SQL. */
38
47
  sqlite: DatabaseSync;
48
+ /** Every message the actions run here pushed to `ctx.outbox` (successful ones only), oldest first. */
49
+ outbox: OutboxEnvelope[];
39
50
  /**
40
51
  * Close the database, stop routing direct action calls to it and clear the
41
52
  * tenant resolver.
@@ -1,8 +1,8 @@
1
+ import { r as liveTestDatabases, t as ACTION_TEST_META } from "../defineDatabase-CaqKQagA.js";
1
2
  import { r as type } from "../type-CUgZsZp3.js";
2
3
  import "../actionArgs-DP2tQrlf.js";
3
- import { r as liveTestDatabases, t as ACTION_TEST_META } from "../defineDatabase-595bNB6M.js";
4
4
  import { setTenantIdResolver } from "../context/index.js";
5
- import { t as createKyselyFromSql } from "../kysely-BZNv9gpz.js";
5
+ import { c as tenantOfInstanceKey, i as createActionOutbox, t as createKyselyFromSql } from "../kysely-D8JQ4v8n.js";
6
6
  import { i as generateSnapshotFromSchema, n as createEmptySnapshot, r as generateMigrationStatements } from "../snapshot-D_z95s6E.js";
7
7
  import { createRequire } from "node:module";
8
8
  //#region src/testing/index.ts
@@ -42,7 +42,8 @@ async function deriveStatements(schema) {
42
42
  * ```
43
43
  */
44
44
  async function createTestDatabase(options) {
45
- const { schema, statements, tenantId = "test" } = options;
45
+ const { schema, statements, tenantId = "test", env = {} } = options;
46
+ const recorded = [];
46
47
  const { DatabaseSync } = loadSqlite();
47
48
  const sqlite = new DatabaseSync(":memory:");
48
49
  const db = createKyselyFromSql(sqlStorageShim(sqlite), { schema });
@@ -54,7 +55,23 @@ async function createTestDatabase(options) {
54
55
  if (!meta) throw new Error("createTestDatabase().run() was given a function that is not a durable-db action (no test metadata). Pass an export created by `action({ … })`.");
55
56
  const validated = meta.validator(args);
56
57
  if (validated instanceof type.errors) throw new Error(`Invalid args for action: ${validated.summary}`);
57
- return await meta.handler(db, validated);
58
+ const outbox = createActionOutbox(true);
59
+ const result = await meta.handler(db, validated, {
60
+ env,
61
+ instanceKey: tenantId,
62
+ outbox
63
+ });
64
+ const envelopes = outbox.take().map((message) => ({
65
+ message: JSON.parse(message),
66
+ instanceKey: tenantId,
67
+ tenantId: tenantOfInstanceKey(tenantId),
68
+ recordedAt: Date.now()
69
+ }));
70
+ if (envelopes.length > 0) {
71
+ recorded.push(...envelopes);
72
+ await options.outbox?.(envelopes, { env });
73
+ }
74
+ return result;
58
75
  }
59
76
  const live = {
60
77
  tables: new Set(Object.values(schema)),
@@ -75,6 +92,7 @@ async function createTestDatabase(options) {
75
92
  db,
76
93
  run,
77
94
  sqlite,
95
+ outbox: recorded,
78
96
  destroy() {
79
97
  const registry = liveTestDatabases();
80
98
  const index = registry.indexOf(live);
@@ -1,6 +1,7 @@
1
1
  import { t as DatabaseSource } from "../discovery-gHeLq8jk.js";
2
- import "../index-DOoXuKtZ.js";
2
+ import "../index-DoxI1p4-.js";
3
3
  import { Plugin } from "vite";
4
+ import "@babel/types";
4
5
  //#region src/vite/modules/wrangler.d.ts
5
6
  /** A Durable Object binding as wrangler.jsonc declares it. */
6
7
  interface DurableObjectBinding {
@@ -78,6 +79,14 @@ interface PatchResult {
78
79
  deletedClasses: string[];
79
80
  }
80
81
  //#endregion
82
+ //#region src/vite/modules/generator.d.ts
83
+ /** Where the outbox delivers: a Queue binding, or a module whose default export is the sink. */
84
+ type OutboxOption = {
85
+ queue: string;
86
+ } | {
87
+ module: string;
88
+ };
89
+ //#endregion
81
90
  //#region src/vite/modules/syncWrangler.d.ts
82
91
  interface SyncWranglerConfigOptions {
83
92
  /** Project root (where wrangler.jsonc/json lives). */
@@ -147,6 +156,15 @@ export interface DurableDbOptions {
147
156
  * start. A change is logged (`durable-db updated wrangler.jsonc (…)`).
148
157
  */
149
158
  patchWranglerConfig?: boolean;
159
+ /**
160
+ * Where `ctx.outbox.push(message)` delivers, after the action succeeds:
161
+ * `{ queue: 'MY_QUEUE' }` sends each message to that Queue binding as it is;
162
+ * `{ module: './src/outbox.ts' }` imports a module (a path from the project
163
+ * root, or a package specifier) whose default export delivers them — a
164
+ * function `(envelopes, { env }) => …`, or an object with `deliver`. Without
165
+ * it, `ctx.outbox.push()` throws naming this option.
166
+ */
167
+ outbox?: OutboxOption;
150
168
  }
151
169
  export declare function durableDb(options?: DurableDbOptions): Plugin;
152
170
  /** @deprecated Renamed to {@link durableDb}. */
@@ -154,4 +172,4 @@ export declare const databasePlugin: typeof durableDb;
154
172
  /** @deprecated Renamed to {@link DurableDbOptions}. */
155
173
  export type DatabasePluginOptions = DurableDbOptions;
156
174
  //#endregion
157
- export { type DatabaseSource, type SyncWranglerConfigOptions, type SyncWranglerConfigResult, durableDb as default };
175
+ export { type DatabaseSource, type OutboxOption, type SyncWranglerConfigOptions, type SyncWranglerConfigResult, durableDb as default };