durable-db 0.8.0 → 0.10.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,4 @@
1
- import "./defineDatabase-By401iHp.js";
1
+ import "./defineDatabase-Bww_w_n5.js";
2
2
  import { i as OutboxSink, t as Outbox } from "./outbox-D3Q9n7Rt.js";
3
3
  import { SQLiteTableWithColumns } from "drizzle-orm/sqlite-core";
4
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";
@@ -416,6 +416,11 @@ declare class SchemaPlugin extends CamelCasePlugin {
416
416
  constructor(schema: Record<string, SQLiteTableWithColumns<any>>);
417
417
  protected snakeCase(str: string): string;
418
418
  protected camelCase(str: string): string;
419
+ /**
420
+ * The key a result row has for an identifier a query writes as `name`: it
421
+ * is snake_cased on the way in and camelCased on the way out.
422
+ */
423
+ resultKey(name: string): string;
419
424
  }
420
425
  /**
421
426
  * Plugin that handles Drizzle's defaultFn and onUpdateFn during Kysely queries.
@@ -486,6 +491,46 @@ declare class DateSerializePlugin implements KyselyPlugin {
486
491
  private transformRow;
487
492
  private shouldDeserialize;
488
493
  }
494
+ /**
495
+ * What a JSON-mode column holds, from what SQLite answered: text is parsed,
496
+ * bytes (a blob column) are read as UTF-8 first. What is no JSON — a row
497
+ * written before these columns were serialized — is answered as it is.
498
+ */
499
+ declare function parseJsonValue(value: unknown): unknown;
500
+ interface JsonPluginOptions {
501
+ /**
502
+ * The key a result row has for an identifier as a query writes it —
503
+ * SchemaPlugin's `resultKey` when the names are camelCased. Default: the
504
+ * identifier itself.
505
+ */
506
+ resultKey?: (name: string) => string;
507
+ }
508
+ /**
509
+ * The two plugins behind JSON-mode columns (`text({ mode: 'json' })`,
510
+ * `blob({ mode: 'json' })`): a value written to one is stored as its JSON, and
511
+ * one that is read comes back as the value.
512
+ *
513
+ * `write` goes before the plugin that renames identifiers and before
514
+ * DateSerializePlugin; `read` after them. In between they share which keys of
515
+ * a query's rows are JSON columns, worked out from what the query selects:
516
+ *
517
+ * - a column (`meta`, `i.meta`, `i.meta as m`) is resolved against the tables
518
+ * the query reads from — the same name in a table where it is another kind
519
+ * of column is left alone;
520
+ * - `selectAll()` / `returningAll()` are every JSON column of those tables;
521
+ * - where the source is no table of the schema (a subquery, a CTE, a raw
522
+ * query), a name goes for a JSON column when it is one in a table the query
523
+ * names (in any table, for a query that names none) and another kind of
524
+ * column in none of them.
525
+ *
526
+ * An expression (a JSON path, a function call, `related()`) is the caller's:
527
+ * it is neither serialized nor parsed. So is a value compared with a JSON
528
+ * column in a `where`.
529
+ */
530
+ declare function createJsonPlugins(schema: Record<string, Table>, options?: JsonPluginOptions): {
531
+ write: KyselyPlugin;
532
+ read: KyselyPlugin;
533
+ };
489
534
  /**
490
535
  * Create all recommended plugins for use with Drizzle schemas.
491
536
  *
@@ -494,9 +539,11 @@ declare class DateSerializePlugin implements KyselyPlugin {
494
539
  * - SchemaPlugin (extends CamelCasePlugin): schema-aware camelCase ↔ snake_case
495
540
  * - DateSerializePlugin: Date ↔ SQLite text serialization
496
541
  * - BooleanDeserializePlugin: boolean-mode columns read back as booleans
542
+ * - createJsonPlugins' two: JSON-mode columns written as JSON and read back
543
+ * as their value — only for a schema that has such a column
497
544
  *
498
545
  * When camelCase is false, SchemaPlugin is omitted.
499
546
  */
500
547
  declare function createDrizzlePlugins(schema: Record<string, SQLiteTableWithColumns<any>>, camelCase?: boolean): KyselyPlugin[];
501
548
  //#endregion
502
- export { createKyselyFromSql as C, SqlExecutor as S, MigrationAttemptInfo as _, QueryResult$1 as a, SqliteDurableObject as b, DrizzleDefaultsPlugin as c, dateSerializers as d, DeleteClassMigration as f, Migration as g, removedDatabaseMessage as h, KyselyPlugin$1 as i, SchemaPlugin as l, RemovedDatabaseError as m, CompiledQuery as n, studio as o, RemovedDatabaseDurableObject as p, Kysely$1 as r, DateSerializePlugin as s, CamelCasePlugin$1 as t, createDrizzlePlugins as u, MigrationSchemaConflictError as v, CreateKyselyOptions as x, Migrations as y };
549
+ export { SqliteDurableObject as C, createKyselyFromSql as E, Migrations as S, SqlExecutor as T, RemovedDatabaseError as _, QueryResult$1 as a, MigrationAttemptInfo as b, DrizzleDefaultsPlugin as c, createDrizzlePlugins as d, createJsonPlugins as f, RemovedDatabaseDurableObject as g, DeleteClassMigration as h, KyselyPlugin$1 as i, JsonPluginOptions as l, parseJsonValue as m, CompiledQuery as n, studio as o, dateSerializers as p, Kysely$1 as r, DateSerializePlugin as s, CamelCasePlugin$1 as t, SchemaPlugin as u, removedDatabaseMessage as v, CreateKyselyOptions as w, MigrationSchemaConflictError as x, Migration as y };
package/dist/index.d.ts CHANGED
@@ -1,7 +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-By401iHp.js";
1
+ import { i as Type, l as type } from "./index-bUUlOWfP.js";
2
+ import { C as Relations, S as RelationType, T as relationsOf, _ as RelatedSpec, b as Relation, c as DatabaseDefinition, d as InferArgs, g as RelatedOptions, h as RelatedExpression, i as ActionContext, m as Related, n as Action, p as AnyRelated, r as ActionConfig, s as DatabaseConfig, t as defineDatabase, u as DrizzleToKysely, v as createRelated, w as relationOf, x as RelationMap, y as AnySchema } from "./defineDatabase-Bww_w_n5.js";
3
3
  import { a as OutboxSinkContext, i as OutboxSink, n as OutboxEnvelope, o as OutboxSinkModule, r as OutboxMessage, t as Outbox } from "./outbox-D3Q9n7Rt.js";
4
4
  import { getTenantId, hasTenantId, setTenantIdResolver } from "./context/index.js";
5
5
  import { AnySQLiteColumn, blob, foreignKey, index, integer, numeric, primaryKey, real, table, text, uniqueIndex } from "./schema.js";
6
6
  import { Kysely } from "kysely";
7
- export { type Action, type ActionConfig, type ActionContext, type AnySQLiteColumn, type DatabaseConfig, type DatabaseDefinition, type DrizzleToKysely, type InferArgs, type Kysely, type Outbox, type OutboxEnvelope, type OutboxMessage, type OutboxSink, type OutboxSinkContext, type OutboxSinkModule, 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 AnyRelated, type AnySQLiteColumn, type AnySchema, 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 RelatedSpec, type Relation, type RelationMap, type RelationType, type Relations, blob, createRelated, 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 { a as createRelated, h as relationsOf, i as RelatedExpression, m as relationOf, n as defineDatabase } from "./defineDatabase-CULpd87Z.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, createRelated, defineDatabase, describeAction, foreignKey, getTenantId, hasTenantId, index, integer, numeric, primaryKey, real, relationOf, relationsOf, setTenantIdResolver, table, text, type, uniqueIndex };
@@ -0,0 +1,279 @@
1
+ import { l as SchemaPlugin, o as createRelatedPlugins, s as DateSerializePlugin, u as createDrizzlePlugins } from "./defineDatabase-CULpd87Z.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 naming = schema && camelCase ? new SchemaPlugin(schema) : void 0;
259
+ const related = schema ? createRelatedPlugins(schema, naming ? { resultKey: (name) => naming.resultKey(name) } : {}) : void 0;
260
+ if (related) allPlugins.push(related.capture);
261
+ if (schema) allPlugins.push(...createDrizzlePlugins(schema, camelCase));
262
+ else if (camelCase) {
263
+ allPlugins.push(new CamelCasePlugin());
264
+ allPlugins.push(new DateSerializePlugin());
265
+ } else allPlugins.push(new DateSerializePlugin());
266
+ allPlugins.push(...plugins);
267
+ if (related) allPlugins.push(related.results);
268
+ return new Kysely({
269
+ dialect: {
270
+ createAdapter: () => sqliteDialect.createAdapter(),
271
+ createDriver: () => new CloudflareSqliteDriver(sqlStorage),
272
+ createIntrospector: (db) => sqliteDialect.createIntrospector(db),
273
+ createQueryCompiler: () => new BacktickSqliteQueryCompiler()
274
+ },
275
+ plugins: allPlugins
276
+ });
277
+ }
278
+ //#endregion
279
+ 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 };
@@ -332,6 +332,63 @@ function warnNonLiteral(filePath, key, defaultValue) {
332
332
  console.warn(`[durable-db] '${key}' in defineDatabase() must be a static literal for build-time analysis. Got a dynamic expression in ${path$1.basename(filePath)} — defaulting to '${defaultValue}'.`);
333
333
  }
334
334
  /**
335
+ * Whether a database was given a schema discovery could read: tables listed
336
+ * in the call, or a const the schema module exports.
337
+ */
338
+ function declaresSchema(db) {
339
+ return !!db.schemaExport || db.schemaTableNames.length > 0;
340
+ }
341
+ /** `x as const`, `x satisfies T`, `x!`: the expression itself. */
342
+ function unwrapExpression(node) {
343
+ let current = node;
344
+ while (t.isTSAsExpression(current) || t.isTSSatisfiesExpression(current) || t.isTSNonNullExpression(current)) current = current.expression;
345
+ return current;
346
+ }
347
+ /** `{ users, posts }`: the tables by name, and the module they are imported from. */
348
+ function listedTables(object, imports) {
349
+ const declared = {
350
+ schemaImport: null,
351
+ schemaExport: null,
352
+ schemaTableNames: []
353
+ };
354
+ for (const schemaProp of object.properties) if (t.isObjectProperty(schemaProp) && t.isIdentifier(schemaProp.key)) {
355
+ const tableName = schemaProp.key.name;
356
+ declared.schemaTableNames.push(tableName);
357
+ const importInfo = imports.get(tableName);
358
+ if (importInfo && !declared.schemaImport) declared.schemaImport = importInfo.source;
359
+ }
360
+ return declared;
361
+ }
362
+ /**
363
+ * The schema of a defineDatabase() call. Three shapes can be read:
364
+ *
365
+ * defineDatabase({ schema: { users, posts } }) // the tables, listed
366
+ * const schema = { users, posts }; // … or listed in a const of this file
367
+ * import { schema } from './schema'; // a const the schema module exports,
368
+ * defineDatabase({ schema }) // shared with whoever else needs the tables
369
+ *
370
+ * An imported const is not followed into its module here: it is recorded as
371
+ * the export to import (`schemaExport`), and whoever needs the tables loads it.
372
+ */
373
+ function extractSchema(declaratorPath, value, filePath, imports) {
374
+ const node = unwrapExpression(value);
375
+ if (t.isObjectExpression(node)) return listedTables(node, imports);
376
+ if (t.isIdentifier(node)) {
377
+ const imported = imports.get(node.name);
378
+ if (imported && imported.imported !== "*") return {
379
+ schemaImport: imported.source,
380
+ schemaExport: imported.imported,
381
+ schemaTableNames: []
382
+ };
383
+ const binding = imported ? void 0 : declaratorPath.scope.getBinding(node.name);
384
+ const init = binding?.path.isVariableDeclarator() ? binding.path.node.init : null;
385
+ const local = init ? unwrapExpression(init) : null;
386
+ if (binding?.constant && t.isObjectExpression(local)) return listedTables(local, imports);
387
+ }
388
+ console.warn(`[durable-db] 'schema' in defineDatabase() is read at build time: list the tables ({ schema: { users, posts } }) or pass a const the schema module exports (import { schema } from './schema'). ${path$1.basename(filePath)} passes something else, so its database gets no schema — no migrations, no column mapping.`);
389
+ return null;
390
+ }
391
+ /**
335
392
  * Extract database configuration from a defineDatabase() call
336
393
  */
337
394
  function extractDatabaseInfo(declaratorPath, callExpr, filePath, imports, namePrefix) {
@@ -340,8 +397,11 @@ function extractDatabaseInfo(declaratorPath, callExpr, filePath, imports, namePr
340
397
  let instance = "per-tenant";
341
398
  let browsable = false;
342
399
  let transport = "rpc";
343
- let schemaImport = null;
344
- const schemaTableNames = [];
400
+ let schema = {
401
+ schemaImport: null,
402
+ schemaExport: null,
403
+ schemaTableNames: []
404
+ };
345
405
  for (const prop of configArg.properties) {
346
406
  if (!t.isObjectProperty(prop) || !t.isIdentifier(prop.key)) continue;
347
407
  const key = prop.key.name;
@@ -362,16 +422,7 @@ function extractDatabaseInfo(declaratorPath, callExpr, filePath, imports, namePr
362
422
  if (value === "rpc" || value === "websocket") transport = value;
363
423
  } else warnNonLiteral(filePath, "transport", "rpc");
364
424
  }
365
- if (key === "schema" && t.isObjectExpression(prop.value)) {
366
- for (const schemaProp of prop.value.properties) if (t.isObjectProperty(schemaProp) || t.isSpreadElement(schemaProp)) {
367
- if (t.isObjectProperty(schemaProp) && t.isIdentifier(schemaProp.key)) {
368
- const tableName = schemaProp.key.name;
369
- schemaTableNames.push(tableName);
370
- const importInfo = imports.get(tableName);
371
- if (importInfo && !schemaImport) schemaImport = importInfo.source;
372
- }
373
- }
374
- }
425
+ if (key === "schema") schema = extractSchema(declaratorPath, prop.value, filePath, imports) ?? schema;
375
426
  }
376
427
  const base = path$1.basename(filePath).replace(/\.(ts|js)$/, "");
377
428
  const name = namePrefix ? `${namePrefix}-${base}` : base;
@@ -384,8 +435,7 @@ function extractDatabaseInfo(declaratorPath, callExpr, filePath, imports, namePr
384
435
  browsable,
385
436
  transport,
386
437
  migrationsDir: "",
387
- schemaImport,
388
- schemaTableNames
438
+ ...schema
389
439
  };
390
440
  }
391
441
  /**
@@ -426,4 +476,4 @@ function toScreamingSnakeCase(str) {
426
476
  return str.replace(/([a-z])([A-Z])/g, "$1_$2").replace(/[-]/g, "_").toUpperCase();
427
477
  }
428
478
  //#endregion
429
- export { discoverActionFiles as a, resolveImportPath as c, databaseSources as i, loadViteAliases as l, parseDatabaseFile as n, discoverDatabaseFiles as o, toPascalCase as r, readFile as s, BABEL_PARSER_PLUGINS as t };
479
+ export { databaseSources as a, readFile as c, toPascalCase as i, resolveImportPath as l, declaresSchema as n, discoverActionFiles as o, parseDatabaseFile as r, discoverDatabaseFiles as s, BABEL_PARSER_PLUGINS as t, loadViteAliases as u };
@@ -30,6 +30,10 @@ declare const actionArgsType: TypeParser;
30
30
  export interface ActionDefinition {
31
31
  validator: (args: unknown) => unknown;
32
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;
33
37
  }
34
38
  export interface DoContext {
35
39
  db: unknown;
@@ -48,6 +52,17 @@ export interface RpcContext {
48
52
  }
49
53
  export declare function registerAction(dbName: string, actionName: string, def: ActionDefinition): void;
50
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;
51
66
  export declare function getDoContext(): DoContext | undefined;
52
67
  export declare function runWithDoContext<T>(store: DoContext, fn: () => T): T;
53
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,8 +1,8 @@
1
+ import { r as liveTestDatabases, t as ACTION_TEST_META } from "../defineDatabase-CULpd87Z.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 { l as createActionOutbox, p as tenantOfInstanceKey, t as createKyselyFromSql } from "../kysely-DvAoap5h.js";
5
+ import { c as tenantOfInstanceKey, i as createActionOutbox, t as createKyselyFromSql } from "../kysely-DCQRqT62.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
@@ -13,11 +13,21 @@ const loadSqlite = () => createRequire(import.meta.url)("node:sqlite");
13
13
  */
14
14
  function sqlStorageShim(sqlite) {
15
15
  const isReader = (sql) => /^\s*(SELECT|PRAGMA|WITH)/i.test(sql) || /\bRETURNING\b/i.test(sql);
16
- const normalize = (p) => typeof p === "boolean" ? p ? 1 : 0 : p === void 0 ? null : p;
16
+ const normalize = (p) => typeof p === "boolean" ? p ? 1 : 0 : p === void 0 ? null : p instanceof ArrayBuffer ? new Uint8Array(p) : p;
17
+ const asStored = (row) => {
18
+ if (typeof row !== "object" || row === null) return row;
19
+ let out;
20
+ for (const [key, value] of Object.entries(row)) {
21
+ if (!(value instanceof Uint8Array)) continue;
22
+ out ??= { ...row };
23
+ out[key] = value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength);
24
+ }
25
+ return out ?? row;
26
+ };
17
27
  return { exec(query, ...bindings) {
18
28
  const stmt = sqlite.prepare(query);
19
29
  const params = bindings.map(normalize);
20
- const rows = isReader(query) ? stmt.all(...params) : (stmt.run(...params), []);
30
+ const rows = isReader(query) ? stmt.all(...params).map(asStored) : (stmt.run(...params), []);
21
31
  return { toArray: () => rows };
22
32
  } };
23
33
  }