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,1134 @@
1
+ import { r as type } from "./type-CUgZsZp3.js";
2
+ import { t as actionArgsType } from "./actionArgs-DP2tQrlf.js";
3
+ import { Table, getTableColumns, getTableName, is, isSQLWrapper } from "drizzle-orm";
4
+ import { SQLiteSyncDialect, getTableConfig } from "drizzle-orm/sqlite-core";
5
+ import { AliasNode, CamelCasePlugin, ColumnNode, ColumnUpdateNode, DeleteQueryNode, IdentifierNode, InsertQueryNode, PrimitiveValueListNode, ReferenceNode, SelectAllNode, SelectQueryNode, TableNode, UpdateQueryNode, ValueListNode, ValueNode, ValuesNode, sql } from "kysely";
6
+ import { toCamelCase, toSnakeCase } from "drizzle-orm/casing";
7
+ //#region src/db/relations.ts
8
+ const registries = /* @__PURE__ */ new WeakMap();
9
+ function forwardName(column) {
10
+ if (column.length > 2 && column.endsWith("Id")) return column.slice(0, -2);
11
+ if (column.length > 3 && column.endsWith("_id")) return column.slice(0, -3);
12
+ return column;
13
+ }
14
+ const capitalize = (value) => value.charAt(0).toUpperCase() + value.slice(1);
15
+ function propertyOf(table, column) {
16
+ for (const [property, candidate] of Object.entries(getTableColumns(table))) if (candidate === column) return property;
17
+ }
18
+ function build(schema) {
19
+ const keys = /* @__PURE__ */ new Map();
20
+ for (const [key, table] of Object.entries(schema)) keys.set(table, key);
21
+ const found = [];
22
+ for (const [key, table] of Object.entries(schema)) for (const foreignKey of getTableConfig(table).foreignKeys) {
23
+ const { columns, foreignTable, foreignColumns } = foreignKey.reference();
24
+ if (columns.length !== 1 || foreignColumns.length !== 1) continue;
25
+ const target = keys.get(foreignTable);
26
+ const column = propertyOf(table, columns[0]);
27
+ const foreign = target === void 0 ? void 0 : propertyOf(foreignTable, foreignColumns[0]);
28
+ if (target === void 0 || column === void 0 || foreign === void 0) continue;
29
+ found.push({
30
+ table: key,
31
+ column,
32
+ target,
33
+ foreign,
34
+ nullable: !columns[0].notNull
35
+ });
36
+ }
37
+ const registry = {
38
+ relations: {},
39
+ conflicts: /* @__PURE__ */ new Map()
40
+ };
41
+ for (const key of Object.keys(schema)) registry.relations[key] = {};
42
+ const claims = /* @__PURE__ */ new Map();
43
+ const add = (relation, from) => {
44
+ const claim = `${relation.table}.${relation.name}`;
45
+ const earlier = claims.get(claim);
46
+ if (earlier === void 0) {
47
+ claims.set(claim, from);
48
+ registry.relations[relation.table][relation.name] = relation;
49
+ return;
50
+ }
51
+ delete registry.relations[relation.table][relation.name];
52
+ let ofTable = registry.conflicts.get(relation.table);
53
+ if (!ofTable) registry.conflicts.set(relation.table, ofTable = /* @__PURE__ */ new Map());
54
+ const claimed = ofTable.get(relation.name) ?? [earlier];
55
+ claimed.push(from);
56
+ ofTable.set(relation.name, claimed);
57
+ };
58
+ for (const edge of found) {
59
+ const from = `${edge.table}.${edge.column} → ${edge.target}.${edge.foreign}`;
60
+ const forward = forwardName(edge.column);
61
+ add({
62
+ kind: "one",
63
+ name: forward,
64
+ table: edge.table,
65
+ target: edge.target,
66
+ local: edge.column,
67
+ foreign: edge.foreign,
68
+ nullable: edge.nullable
69
+ }, from);
70
+ add({
71
+ kind: "many",
72
+ name: found.filter((other) => other.table === edge.table && other.target === edge.target).length > 1 ? `${edge.table}As${capitalize(forward)}` : edge.table,
73
+ table: edge.target,
74
+ target: edge.table,
75
+ local: edge.foreign,
76
+ foreign: edge.column,
77
+ nullable: false
78
+ }, from);
79
+ }
80
+ return registry;
81
+ }
82
+ function registryOf(schema) {
83
+ let registry = registries.get(schema);
84
+ if (!registry) registries.set(schema, registry = build(schema));
85
+ return registry;
86
+ }
87
+ /**
88
+ * The relations a schema's foreign keys declare, per table. Read the first
89
+ * time it is asked for (a foreign key's target is a callback, so every table
90
+ * of the schema exists by then) and kept.
91
+ */
92
+ function relationsOf(schema) {
93
+ return registryOf(schema).relations;
94
+ }
95
+ /** One relation of a table, or an error that says what there is. */
96
+ function relationOf(schema, table, name) {
97
+ const registry = registryOf(schema);
98
+ const ofTable = registry.relations[table];
99
+ if (!ofTable) throw new Error(`[durable-db] "${table}" is not a table of this database's schema (its tables: ${Object.keys(schema).join(", ") || "none"}).`);
100
+ const relation = ofTable[name];
101
+ if (relation) return relation;
102
+ const claimed = registry.conflicts.get(table)?.get(name);
103
+ if (claimed) throw new Error(`[durable-db] "${table}" has ${claimed.length} relations that would be named "${name}" (${claimed.join("; ")}): rename a column so each gets a name of its own.`);
104
+ const names = Object.keys(ofTable);
105
+ throw new Error(`[durable-db] "${table}" has no relation "${name}". ` + (names.length > 0 ? `Its relations: ${names.join(", ")}.` : "No foreign key leads to or from it: a relation is a column with .references(() => other.column)."));
106
+ }
107
+ //#endregion
108
+ //#region src/db/plugins.ts
109
+ /**
110
+ * Schema-aware CamelCasePlugin that uses Drizzle schema for column name mapping.
111
+ *
112
+ * Extends CamelCasePlugin to handle non-standard column names that don't follow
113
+ * simple camelCase ↔ snake_case conversion. For example, a JS property `userId`
114
+ * mapped to SQL column `user_identifier` would be handled correctly.
115
+ *
116
+ * Falls back to standard CamelCasePlugin behavior for columns not in the schema.
117
+ */
118
+ var SchemaPlugin = class extends CamelCasePlugin {
119
+ jsToSql;
120
+ sqlToJs;
121
+ constructor(schema) {
122
+ super();
123
+ this.jsToSql = /* @__PURE__ */ new Map();
124
+ this.sqlToJs = /* @__PURE__ */ new Map();
125
+ for (const [schemaKey, table] of Object.entries(schema)) {
126
+ const tableConfig = getTableConfig(table);
127
+ const sqlTableName = tableConfig.name;
128
+ if (schemaKey !== sqlTableName) {
129
+ this.jsToSql.set(schemaKey, sqlTableName);
130
+ this.sqlToJs.set(sqlTableName, schemaKey);
131
+ }
132
+ const sqlColumnNames = new Set(tableConfig.columns.map((c) => c.name));
133
+ for (const [propertyName, value] of Object.entries(table)) if (value && typeof value === "object" && "name" in value && typeof value.name === "string" && sqlColumnNames.has(value.name) && propertyName !== value.name) {
134
+ this.jsToSql.set(propertyName, value.name);
135
+ this.sqlToJs.set(value.name, propertyName);
136
+ }
137
+ }
138
+ }
139
+ snakeCase(str) {
140
+ return this.jsToSql.get(str) ?? super.snakeCase(str);
141
+ }
142
+ camelCase(str) {
143
+ return this.sqlToJs.get(str) ?? super.camelCase(str);
144
+ }
145
+ /**
146
+ * The key a result row has for an identifier a query writes as `name`: it
147
+ * is snake_cased on the way in and camelCased on the way out.
148
+ */
149
+ resultKey(name) {
150
+ return this.camelCase(this.snakeCase(name));
151
+ }
152
+ };
153
+ function getKyselyTableName(node) {
154
+ if (node && TableNode.is(node)) return node.table.identifier.name;
155
+ return null;
156
+ }
157
+ /** A binary value: an ArrayBuffer or a view of one (a Uint8Array, a Buffer). */
158
+ function isBinary(value) {
159
+ return value instanceof ArrayBuffer || ArrayBuffer.isView(value);
160
+ }
161
+ function getKyselyColumnName(node) {
162
+ if (!node) return null;
163
+ if (ColumnNode.is(node)) return node.column.name;
164
+ if (ColumnUpdateNode.is(node) && node.column) return getKyselyColumnName(node.column);
165
+ return null;
166
+ }
167
+ function convertDrizzleSql(drizzleSql) {
168
+ return drizzleSql.sql.split("?").reduce((acc, part, index) => {
169
+ const param = index < drizzleSql.params.length ? drizzleSql.params[index] : "";
170
+ return acc + part + param;
171
+ }, "");
172
+ }
173
+ function createValueNode(val) {
174
+ if (isSQLWrapper(val)) {
175
+ const drizzleSql = new SQLiteSyncDialect().sqlToQuery(val);
176
+ return sql.raw(convertDrizzleSql(drizzleSql)).toOperationNode();
177
+ }
178
+ return ValueNode.create(val);
179
+ }
180
+ function extractDefaults(schemas) {
181
+ const defaults = /* @__PURE__ */ new Map();
182
+ for (const schema of Object.values(schemas)) {
183
+ const tableName = toCamelCase(getTableName(schema));
184
+ const columns = getTableColumns(schema);
185
+ const tableDefaults = {};
186
+ for (const column of Object.values(columns)) {
187
+ const { defaultFn, onUpdateFn, name } = column;
188
+ if (defaultFn || onUpdateFn) tableDefaults[name] = {
189
+ defaultFn,
190
+ onUpdateFn
191
+ };
192
+ }
193
+ if (Object.keys(tableDefaults).length > 0) defaults.set(tableName, tableDefaults);
194
+ }
195
+ return defaults;
196
+ }
197
+ /**
198
+ * Plugin that handles Drizzle's defaultFn and onUpdateFn during Kysely queries.
199
+ *
200
+ * On INSERT: auto-populates columns that have a defaultFn but weren't provided,
201
+ * and resolves DefaultInsertValueNode markers to actual values.
202
+ *
203
+ * On UPDATE: auto-adds column updates for columns with onUpdateFn that weren't
204
+ * already included in the SET clause.
205
+ */
206
+ var DrizzleDefaultsPlugin = class {
207
+ defaults;
208
+ constructor(drizzleSchemas) {
209
+ this.defaults = extractDefaults(drizzleSchemas);
210
+ }
211
+ transformInsertQuery(node) {
212
+ const tableName = getKyselyTableName(node.into);
213
+ if (!tableName) return node;
214
+ const tableDefaults = this.defaults.get(tableName);
215
+ if (!tableDefaults) return node;
216
+ if (!node.values || !ValuesNode.is(node.values)) return node;
217
+ const providedColumns = node.columns ?? [];
218
+ const providedColumnNames = providedColumns.map((col) => col.column.name);
219
+ const missingDefaults = Object.entries(tableDefaults).filter(([colName, { defaultFn }]) => defaultFn && !providedColumnNames.includes(colName)).map(([colName, { defaultFn }]) => ({
220
+ name: colName,
221
+ defaultFn
222
+ }));
223
+ const newColumns = [...providedColumns, ...missingDefaults.map(({ name }) => ColumnNode.create(name))];
224
+ const newRows = node.values.values.map((rowNode) => {
225
+ if (missingDefaults.length === 0 && PrimitiveValueListNode.is(rowNode)) return rowNode;
226
+ let originalValues;
227
+ if (PrimitiveValueListNode.is(rowNode)) originalValues = rowNode.values.map((val) => ValueNode.create(val));
228
+ else if (ValueListNode.is(rowNode)) originalValues = [...rowNode.values];
229
+ else throw new Error("Unsupported row node type in insert query");
230
+ const processedValues = originalValues.map((val, idx) => {
231
+ if (val.kind === "DefaultInsertValueNode") {
232
+ const colName = providedColumns[idx].column.name;
233
+ const colDef = tableDefaults[colName];
234
+ if (colDef?.defaultFn) return createValueNode(colDef.defaultFn());
235
+ }
236
+ return val;
237
+ });
238
+ const missingValues = missingDefaults.map(({ defaultFn }) => createValueNode(defaultFn()));
239
+ return ValueListNode.create([...processedValues, ...missingValues]);
240
+ });
241
+ return InsertQueryNode.cloneWith(node, {
242
+ columns: newColumns,
243
+ values: ValuesNode.create(newRows)
244
+ });
245
+ }
246
+ transformUpdateQuery(node) {
247
+ const tableName = getKyselyTableName(node.table);
248
+ if (!tableName) return node;
249
+ const tableDefaults = this.defaults.get(tableName);
250
+ if (!tableDefaults) return node;
251
+ const existingUpdates = new Set(node.updates?.map(getKyselyColumnName) || []);
252
+ const newUpdates = node.updates ? [...node.updates] : [];
253
+ for (const [colName, { onUpdateFn }] of Object.entries(tableDefaults)) {
254
+ if (!onUpdateFn || existingUpdates.has(colName)) continue;
255
+ newUpdates.push(ColumnUpdateNode.create(ColumnNode.create(colName), createValueNode(onUpdateFn())));
256
+ }
257
+ if (newUpdates.length === (node.updates?.length || 0)) return node;
258
+ return {
259
+ ...node,
260
+ updates: newUpdates
261
+ };
262
+ }
263
+ transformQuery(args) {
264
+ const { node } = args;
265
+ switch (node.kind) {
266
+ case "InsertQueryNode": return this.transformInsertQuery(node);
267
+ case "UpdateQueryNode": return this.transformUpdateQuery(node);
268
+ default: return node;
269
+ }
270
+ }
271
+ async transformResult(args) {
272
+ return args.result;
273
+ }
274
+ };
275
+ /**
276
+ * Date serialization helpers for SQLite
277
+ * SQLite stores dates as TEXT in ISO format (without timezone)
278
+ */
279
+ const dateSerializers = {
280
+ /**
281
+ * Serialize a Date to SQLite format
282
+ * Converts to ISO string, removes timezone info
283
+ */
284
+ serialize(value) {
285
+ return value.toISOString().replace("T", " ").slice(0, 19);
286
+ },
287
+ /**
288
+ * Deserialize a SQLite date string to Date
289
+ * Parses assuming UTC timezone
290
+ */
291
+ deserialize(value) {
292
+ const normalized = value.replace(" ", "T");
293
+ if (/(?:Z|[+-]\d{2}:?\d{2})$/.test(normalized)) return new Date(normalized);
294
+ return /* @__PURE__ */ new Date(normalized + "Z");
295
+ },
296
+ /**
297
+ * Check if a string looks like an ISO date
298
+ */
299
+ isDateString(value) {
300
+ return /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}/.test(value);
301
+ },
302
+ /**
303
+ * Check if a string matches exactly the format produced by serialize()
304
+ * (and SQLite's CURRENT_TIMESTAMP): `YYYY-MM-DD HH:MM:SS`.
305
+ *
306
+ * The read path only deserializes strings in this exact format. Anything
307
+ * else — full ISO strings with a 'T' separator, timezone, or milliseconds —
308
+ * was stored by the user as a plain string and must round-trip verbatim.
309
+ */
310
+ isSerializedDateString(value) {
311
+ return /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(value);
312
+ }
313
+ };
314
+ /**
315
+ * Collect the names of columns that Drizzle declares as date-typed
316
+ * (e.g. `integer({ mode: 'timestamp' })`). Includes both the SQL column
317
+ * name and the JS property name, since result rows may be seen in either
318
+ * form depending on where this plugin sits relative to CamelCasePlugin.
319
+ */
320
+ function collectDateColumnNames(schema) {
321
+ const dateColumns = /* @__PURE__ */ new Set();
322
+ for (const table of Object.values(schema)) {
323
+ const columns = getTableColumns(table);
324
+ for (const [propertyName, column] of Object.entries(columns)) if (column.dataType === "date") {
325
+ dateColumns.add(column.name);
326
+ dateColumns.add(propertyName);
327
+ dateColumns.add(toSnakeCase(propertyName));
328
+ }
329
+ }
330
+ return dateColumns;
331
+ }
332
+ /**
333
+ * Plugin that serializes/deserializes Date objects for SQLite
334
+ *
335
+ * On query: Converts Date objects to ISO strings
336
+ * On result: Converts stored date strings back to Date objects — but only
337
+ * for values in the exact format the write path produces, and (when a schema
338
+ * is provided) only for columns Drizzle declares as date-typed. Plain text
339
+ * columns holding date-looking strings round-trip verbatim.
340
+ */
341
+ var DateSerializePlugin = class {
342
+ /**
343
+ * Names of date-typed columns (SQL and JS forms) when constructed with a
344
+ * schema; null means "no schema available", which falls back to matching
345
+ * on value format alone.
346
+ */
347
+ dateColumns;
348
+ constructor(schema) {
349
+ this.dateColumns = schema ? collectDateColumnNames(schema) : null;
350
+ }
351
+ transformQuery(args) {
352
+ return this.transformNode(args.node);
353
+ }
354
+ transformNode(node) {
355
+ if (node === null || node === void 0) return node;
356
+ if (node instanceof Date) return dateSerializers.serialize(node);
357
+ if (isBinary(node)) return node;
358
+ if (Array.isArray(node)) return node.map((item) => this.transformNode(item));
359
+ if (typeof node === "object") {
360
+ const result = {};
361
+ for (const [key, value] of Object.entries(node)) result[key] = this.transformNode(value);
362
+ return result;
363
+ }
364
+ return node;
365
+ }
366
+ async transformResult(args) {
367
+ return {
368
+ ...args.result,
369
+ rows: args.result.rows.map((row) => this.transformRow(row))
370
+ };
371
+ }
372
+ transformRow(row) {
373
+ const result = {};
374
+ for (const [key, value] of Object.entries(row)) if (typeof value === "string" && this.shouldDeserialize(key, value)) result[key] = dateSerializers.deserialize(value);
375
+ else result[key] = value;
376
+ return result;
377
+ }
378
+ shouldDeserialize(key, value) {
379
+ if (this.dateColumns && !this.dateColumns.has(key)) return false;
380
+ return dateSerializers.isSerializedDateString(value);
381
+ }
382
+ };
383
+ /**
384
+ * Collect the names of columns Drizzle declares as boolean-typed
385
+ * (`integer({ mode: 'boolean' })`). Mirrors collectDateColumnNames: covers
386
+ * the SQL column name, the JS property name, and the snake_cased property
387
+ * name, so it works on either side of the CamelCasePlugin.
388
+ */
389
+ function collectBooleanColumnNames(schema) {
390
+ const booleanColumns = /* @__PURE__ */ new Set();
391
+ for (const table of Object.values(schema)) {
392
+ const columns = getTableColumns(table);
393
+ for (const [propertyName, column] of Object.entries(columns)) if (column.dataType === "boolean") {
394
+ booleanColumns.add(column.name);
395
+ booleanColumns.add(propertyName);
396
+ booleanColumns.add(toSnakeCase(propertyName));
397
+ }
398
+ }
399
+ return booleanColumns;
400
+ }
401
+ /**
402
+ * Plugin that deserializes boolean-mode columns on read.
403
+ *
404
+ * SQLite stores booleans as INTEGER 1/0 (the write side is normalized in the
405
+ * driver — see normalizeParameter in kysely.ts), so schema-declared boolean
406
+ * columns come back as numbers and must be mapped to real booleans. Legacy
407
+ * rows written before the driver normalization existed carry TEXT
408
+ * 'true'/'false' — those are mapped too, so old data keeps reading correctly.
409
+ * Anything unrecognized round-trips verbatim rather than being guessed at.
410
+ */
411
+ var BooleanDeserializePlugin = class {
412
+ booleanColumns;
413
+ constructor(schema) {
414
+ this.booleanColumns = collectBooleanColumnNames(schema);
415
+ }
416
+ transformQuery(args) {
417
+ return args.node;
418
+ }
419
+ async transformResult(args) {
420
+ if (this.booleanColumns.size === 0) return args.result;
421
+ return {
422
+ ...args.result,
423
+ rows: args.result.rows.map((row) => this.transformRow(row))
424
+ };
425
+ }
426
+ transformRow(row) {
427
+ const result = {};
428
+ for (const [key, value] of Object.entries(row)) result[key] = this.booleanColumns.has(key) ? this.toBoolean(value) : value;
429
+ return result;
430
+ }
431
+ toBoolean(value) {
432
+ if (value === null || value === void 0 || typeof value === "boolean") return value;
433
+ if (typeof value === "number") return value !== 0;
434
+ if (typeof value === "bigint") return value !== 0n;
435
+ if (value === "true" || value === "1") return true;
436
+ if (value === "false" || value === "0") return false;
437
+ return value;
438
+ }
439
+ };
440
+ /**
441
+ * The JSON-mode columns of a schema, table by table. A table is found under
442
+ * its schema key and its SQL name; a column under its property name, its name
443
+ * and its snake_cased property name, like collectDateColumnNames — so a
444
+ * lookup works on either side of the CamelCasePlugin.
445
+ */
446
+ function collectJsonTables(schema) {
447
+ const tables = /* @__PURE__ */ new Map();
448
+ for (const [schemaKey, table] of Object.entries(schema)) {
449
+ const facts = {
450
+ json: /* @__PURE__ */ new Map(),
451
+ plain: /* @__PURE__ */ new Set()
452
+ };
453
+ for (const [propertyName, column] of Object.entries(getTableColumns(table))) {
454
+ const names = [
455
+ propertyName,
456
+ column.name,
457
+ toSnakeCase(propertyName)
458
+ ];
459
+ if (column.dataType === "json") {
460
+ const storage = column.getSQLType() === "blob" ? "blob" : "text";
461
+ for (const name of names) facts.json.set(name, storage);
462
+ } else for (const name of names) facts.plain.add(name);
463
+ }
464
+ const tableName = getTableName(table);
465
+ for (const name of [
466
+ schemaKey,
467
+ tableName,
468
+ toCamelCase(tableName)
469
+ ]) if (!tables.has(name)) tables.set(name, facts);
470
+ }
471
+ return tables;
472
+ }
473
+ function hasJsonColumn(schema) {
474
+ return Object.values(schema).some((table) => Object.values(getTableColumns(table)).some((column) => column.dataType === "json"));
475
+ }
476
+ /**
477
+ * What a JSON-mode column stores for a value: its JSON text, as UTF-8 bytes
478
+ * in a blob column. A string is JSON too (`"text"`), so it reads back as the
479
+ * string it was.
480
+ */
481
+ function serializeJsonValue(value, storage) {
482
+ if (value === null || value === void 0) return value;
483
+ const json = JSON.stringify(value);
484
+ if (json === void 0) return value;
485
+ return storage === "blob" ? new TextEncoder().encode(json) : json;
486
+ }
487
+ /**
488
+ * What a JSON-mode column holds, from what SQLite answered: text is parsed,
489
+ * bytes (a blob column) are read as UTF-8 first. What is no JSON — a row
490
+ * written before these columns were serialized — is answered as it is.
491
+ */
492
+ function parseJsonValue(value) {
493
+ let text = value;
494
+ if (isBinary(value)) try {
495
+ text = new TextDecoder("utf-8", { fatal: true }).decode(value);
496
+ } catch {
497
+ return value;
498
+ }
499
+ if (typeof text !== "string") return value;
500
+ try {
501
+ return JSON.parse(text);
502
+ } catch {
503
+ return value;
504
+ }
505
+ }
506
+ /** The table a node names: `invoices`, or the one behind `invoices as i`. */
507
+ function tableNameOf(node) {
508
+ if (!node) return null;
509
+ if (TableNode.is(node)) return node.table.identifier.name;
510
+ if (AliasNode.is(node) && TableNode.is(node.node)) return node.node.table.identifier.name;
511
+ return null;
512
+ }
513
+ /** The column a node names: `meta`, or the one in `i.meta`. */
514
+ function columnNameOf(node) {
515
+ if (!node) return null;
516
+ if (ColumnNode.is(node)) return node.column.name;
517
+ if (ReferenceNode.is(node) && ColumnNode.is(node.column)) return node.column.column.name;
518
+ return null;
519
+ }
520
+ /** Every table a query names, however deep — never walking the values it carries. */
521
+ function walkTables(node, visit) {
522
+ if (Array.isArray(node)) {
523
+ for (const item of node) walkTables(item, visit);
524
+ return;
525
+ }
526
+ if (typeof node !== "object" || node === null) return;
527
+ const kind = node.kind;
528
+ if (typeof kind !== "string" || kind === "ValueNode" || kind === "PrimitiveValueListNode") return;
529
+ if (TableNode.is(node)) {
530
+ visit(node.table.identifier.name);
531
+ return;
532
+ }
533
+ for (const value of Object.values(node)) walkTables(value, visit);
534
+ }
535
+ /** The names that are a JSON-mode column in one of `tables` and another kind of column in none. */
536
+ function jsonNamesAmong(tables) {
537
+ const json = /* @__PURE__ */ new Set();
538
+ const plain = /* @__PURE__ */ new Set();
539
+ for (const facts of new Set(tables)) {
540
+ for (const name of facts.json.keys()) json.add(name);
541
+ for (const name of facts.plain) plain.add(name);
542
+ }
543
+ for (const name of plain) json.delete(name);
544
+ return json;
545
+ }
546
+ /**
547
+ * The two plugins behind JSON-mode columns (`text({ mode: 'json' })`,
548
+ * `blob({ mode: 'json' })`): a value written to one is stored as its JSON, and
549
+ * one that is read comes back as the value.
550
+ *
551
+ * `write` goes before the plugin that renames identifiers and before
552
+ * DateSerializePlugin; `read` after them. In between they share which keys of
553
+ * a query's rows are JSON columns, worked out from what the query selects:
554
+ *
555
+ * - a column (`meta`, `i.meta`, `i.meta as m`) is resolved against the tables
556
+ * the query reads from — the same name in a table where it is another kind
557
+ * of column is left alone;
558
+ * - `selectAll()` / `returningAll()` are every JSON column of those tables;
559
+ * - where the source is no table of the schema (a subquery, a CTE, a raw
560
+ * query), a name goes for a JSON column when it is one in a table the query
561
+ * names (in any table, for a query that names none) and another kind of
562
+ * column in none of them.
563
+ *
564
+ * An expression (a JSON path, a function call, `related()`) is the caller's:
565
+ * it is neither serialized nor parsed. So is a value compared with a JSON
566
+ * column in a `where`.
567
+ */
568
+ function createJsonPlugins(schema, options = {}) {
569
+ const tables = collectJsonTables(schema);
570
+ const resultKey = options.resultKey ?? ((name) => name);
571
+ const selected = /* @__PURE__ */ new WeakMap();
572
+ let everywhere;
573
+ const writeValue = (facts, column, node) => {
574
+ const storage = column === null ? void 0 : facts.json.get(column);
575
+ if (!storage || !ValueNode.is(node)) return node;
576
+ return Object.freeze({
577
+ ...node,
578
+ value: serializeJsonValue(node.value, storage)
579
+ });
580
+ };
581
+ const writeUpdates = (facts, updates) => updates.map((update) => {
582
+ const value = writeValue(facts, columnNameOf(update.column), update.value);
583
+ return value === update.value ? update : Object.freeze({
584
+ ...update,
585
+ value
586
+ });
587
+ });
588
+ const writeInsert = (node) => {
589
+ const facts = tables.get(tableNameOf(node.into) ?? "");
590
+ if (!facts || facts.json.size === 0) return node;
591
+ let out = node;
592
+ if (node.columns && node.values && ValuesNode.is(node.values)) {
593
+ const storages = node.columns.map((column) => facts.json.get(column.column.name));
594
+ if (storages.some((storage) => storage !== void 0)) {
595
+ const rows = node.values.values.map((row) => {
596
+ if (PrimitiveValueListNode.is(row)) return PrimitiveValueListNode.create(row.values.map((value, i) => storages[i] ? serializeJsonValue(value, storages[i]) : value));
597
+ if (ValueListNode.is(row)) return ValueListNode.create(row.values.map((value, i) => {
598
+ const storage = storages[i];
599
+ if (!storage || !ValueNode.is(value)) return value;
600
+ return Object.freeze({
601
+ ...value,
602
+ value: serializeJsonValue(value.value, storage)
603
+ });
604
+ }));
605
+ return row;
606
+ });
607
+ out = InsertQueryNode.cloneWith(out, { values: ValuesNode.create(rows) });
608
+ }
609
+ }
610
+ if (node.onConflict?.updates) out = InsertQueryNode.cloneWith(out, { onConflict: Object.freeze({
611
+ ...node.onConflict,
612
+ updates: writeUpdates(facts, node.onConflict.updates)
613
+ }) });
614
+ return out;
615
+ };
616
+ const writeUpdate = (node) => {
617
+ const facts = tables.get(tableNameOf(node.table) ?? "");
618
+ if (!facts || facts.json.size === 0 || !node.updates) return node;
619
+ return Object.freeze({
620
+ ...node,
621
+ updates: writeUpdates(facts, node.updates)
622
+ });
623
+ };
624
+ const fallbackFor = (root) => {
625
+ const named = /* @__PURE__ */ new Set();
626
+ let any = false;
627
+ walkTables(root, (name) => {
628
+ any = true;
629
+ const facts = tables.get(name);
630
+ if (facts) named.add(facts);
631
+ });
632
+ if (any) return jsonNamesAmong(named);
633
+ return everywhere ??= jsonNamesAmong(tables.values());
634
+ };
635
+ const scopeOf = (root, sources) => {
636
+ let fallback;
637
+ const scope = {
638
+ sources: /* @__PURE__ */ new Map(),
639
+ opaque: false,
640
+ fallback: () => fallback ??= fallbackFor(root)
641
+ };
642
+ for (const node of sources) {
643
+ if (!node) continue;
644
+ if (TableNode.is(node)) {
645
+ const name = node.table.identifier.name;
646
+ scope.sources.set(name, tables.get(name) ?? null);
647
+ } else if (AliasNode.is(node) && IdentifierNode.is(node.alias)) {
648
+ const table = TableNode.is(node.node) ? tables.get(node.node.table.identifier.name) : void 0;
649
+ scope.sources.set(node.alias.name, table ?? null);
650
+ } else scope.opaque = true;
651
+ }
652
+ return scope;
653
+ };
654
+ const isJson = (scope, qualifier, column) => {
655
+ if (qualifier !== null) {
656
+ const facts = scope.sources.get(qualifier);
657
+ return facts ? facts.json.has(column) : scope.fallback().has(column);
658
+ }
659
+ let json = false;
660
+ for (const facts of scope.sources.values()) {
661
+ if (!facts) continue;
662
+ if (facts.plain.has(column)) return false;
663
+ if (facts.json.has(column)) json = true;
664
+ }
665
+ return json || scope.fallback().has(column);
666
+ };
667
+ const keysOf = (root) => {
668
+ const keys = /* @__PURE__ */ new Set();
669
+ const addAll = (names) => {
670
+ for (const name of names) {
671
+ keys.add(name);
672
+ keys.add(resultKey(name));
673
+ }
674
+ };
675
+ let scope;
676
+ let selections;
677
+ if (SelectQueryNode.is(root)) {
678
+ scope = scopeOf(root, [...root.from?.froms ?? [], ...(root.joins ?? []).map((join) => join.table)]);
679
+ selections = root.selections;
680
+ } else if (InsertQueryNode.is(root)) {
681
+ scope = scopeOf(root, [root.into]);
682
+ selections = root.returning?.selections;
683
+ } else if (UpdateQueryNode.is(root)) {
684
+ scope = scopeOf(root, [
685
+ root.table,
686
+ ...root.from?.froms ?? [],
687
+ ...(root.joins ?? []).map((join) => join.table)
688
+ ]);
689
+ selections = root.returning?.selections;
690
+ } else if (DeleteQueryNode.is(root)) {
691
+ scope = scopeOf(root, [
692
+ ...root.from.froms,
693
+ ...(root.joins ?? []).map((join) => join.table),
694
+ ...root.using?.tables ?? []
695
+ ]);
696
+ selections = root.returning?.selections;
697
+ } else if (root.kind === "RawNode") {
698
+ addAll(fallbackFor(root));
699
+ return keys.size > 0 ? keys : void 0;
700
+ } else return;
701
+ if (!selections) return void 0;
702
+ const unknown = scope.opaque || [...scope.sources.values()].some((facts) => facts === null);
703
+ for (const { selection } of selections) if (SelectAllNode.is(selection)) {
704
+ addAll(jsonNamesAmong([...scope.sources.values()].filter((facts) => facts !== null)));
705
+ if (unknown) addAll(scope.fallback());
706
+ } else if (ReferenceNode.is(selection)) {
707
+ const qualifier = tableNameOf(selection.table);
708
+ if (SelectAllNode.is(selection.column)) {
709
+ const facts = qualifier === null ? void 0 : scope.sources.get(qualifier);
710
+ addAll(facts ? facts.json.keys() : scope.fallback());
711
+ } else if (isJson(scope, qualifier, selection.column.column.name)) keys.add(resultKey(selection.column.column.name));
712
+ } else if (ColumnNode.is(selection)) {
713
+ if (isJson(scope, null, selection.column.name)) keys.add(resultKey(selection.column.name));
714
+ } else if (AliasNode.is(selection) && IdentifierNode.is(selection.alias)) {
715
+ const aliased = selection.node;
716
+ const column = ReferenceNode.is(aliased) || ColumnNode.is(aliased) ? columnNameOf(aliased) : null;
717
+ const qualifier = ReferenceNode.is(aliased) ? tableNameOf(aliased.table) : null;
718
+ if (column !== null && isJson(scope, qualifier, column)) keys.add(resultKey(selection.alias.name));
719
+ }
720
+ return keys.size > 0 ? keys : void 0;
721
+ };
722
+ return {
723
+ write: {
724
+ transformQuery({ node, queryId }) {
725
+ const keys = keysOf(node);
726
+ if (keys) selected.set(queryId, keys);
727
+ if (InsertQueryNode.is(node)) return writeInsert(node);
728
+ if (UpdateQueryNode.is(node)) return writeUpdate(node);
729
+ return node;
730
+ },
731
+ async transformResult({ result }) {
732
+ return result;
733
+ }
734
+ },
735
+ read: {
736
+ transformQuery({ node }) {
737
+ return node;
738
+ },
739
+ async transformResult({ result, queryId }) {
740
+ const keys = selected.get(queryId);
741
+ if (!keys || result.rows.length === 0) return result;
742
+ const rows = result.rows.map((row) => {
743
+ let out;
744
+ for (const key of keys) {
745
+ const value = row[key];
746
+ if (value === void 0 || value === null) continue;
747
+ const parsed = parseJsonValue(value);
748
+ if (parsed !== value) (out ??= { ...row })[key] = parsed;
749
+ }
750
+ return out ?? row;
751
+ });
752
+ return {
753
+ ...result,
754
+ rows
755
+ };
756
+ }
757
+ }
758
+ };
759
+ }
760
+ /**
761
+ * Validate that a schema object is shaped like a record of Drizzle tables.
762
+ *
763
+ * Throws a descriptive error pointing at the offending key when the schema
764
+ * is not a plain object or when any value isn't a Drizzle `Table`. This
765
+ * catches the common foot-guns (passing a Drizzle relations helper, a plain
766
+ * column builder, or `undefined` because of a missing import) before Kysely
767
+ * plugins crash with an unhelpful stack deep inside their constructors.
768
+ */
769
+ function assertValidSchema(schema) {
770
+ if (schema === null || typeof schema !== "object" || Array.isArray(schema)) throw new Error(`[db] Invalid schema: expected a record of Drizzle tables (e.g. { users, posts }), got ${Array.isArray(schema) ? "array" : schema === null ? "null" : typeof schema}.`);
771
+ for (const [key, value] of Object.entries(schema)) if (!is(value, Table)) throw new Error(`[db] Invalid schema: '${key}' is not a Drizzle table (got ${value === null ? "null" : value === void 0 ? "undefined" : typeof value}). Make sure every value is defined with table() from 'durable-db/schema'.`);
772
+ }
773
+ /**
774
+ * Create all recommended plugins for use with Drizzle schemas.
775
+ *
776
+ * Includes:
777
+ * - DrizzleDefaultsPlugin: auto-populates defaultFn/onUpdateFn values
778
+ * - SchemaPlugin (extends CamelCasePlugin): schema-aware camelCase ↔ snake_case
779
+ * - DateSerializePlugin: Date ↔ SQLite text serialization
780
+ * - BooleanDeserializePlugin: boolean-mode columns read back as booleans
781
+ * - createJsonPlugins' two: JSON-mode columns written as JSON and read back
782
+ * as their value — only for a schema that has such a column
783
+ *
784
+ * When camelCase is false, SchemaPlugin is omitted.
785
+ */
786
+ function createDrizzlePlugins(schema, camelCase = true) {
787
+ assertValidSchema(schema);
788
+ const tables = schema;
789
+ const schemaPlugin = camelCase ? new SchemaPlugin(schema) : void 0;
790
+ const json = hasJsonColumn(tables) ? createJsonPlugins(tables, schemaPlugin ? { resultKey: (name) => schemaPlugin.resultKey(name) } : {}) : void 0;
791
+ const plugins = [];
792
+ plugins.push(new DrizzleDefaultsPlugin(tables));
793
+ if (json) plugins.push(json.write);
794
+ if (schemaPlugin) plugins.push(schemaPlugin);
795
+ plugins.push(new DateSerializePlugin(tables));
796
+ plugins.push(new BooleanDeserializePlugin(tables));
797
+ if (json) plugins.push(json.read);
798
+ return plugins;
799
+ }
800
+ //#endregion
801
+ //#region src/db/related.ts
802
+ const RELATED = Symbol.for("durable-db.related");
803
+ const specs = /* @__PURE__ */ new WeakMap();
804
+ function metaOf(spec) {
805
+ return {
806
+ target: spec.relation.target,
807
+ with: new Map(spec.with.map((nested) => [nested.alias, metaOf(nested)]))
808
+ };
809
+ }
810
+ function render(spec, outer, depth) {
811
+ const { relation } = spec;
812
+ const row = `_r${depth}`;
813
+ const pairs = spec.columns.map((column) => sql`${sql.lit(column)}, ${sql.ref(`${row}.${column}`)}`);
814
+ for (const nested of spec.with) pairs.push(sql`${sql.lit(nested.alias)}, json(${render(nested, row, depth + 1)})`);
815
+ const object = sql`json_object(${sql.join(pairs)})`;
816
+ const target = sql.table(relation.target);
817
+ const matches = (alias) => sql`${sql.ref(`${alias}.${relation.foreign}`)} = ${sql.ref(`${outer}.${relation.local}`)}`;
818
+ if (relation.kind === "one") return sql`(select ${object} from ${target} as ${sql.ref(row)} where ${matches(row)} limit 1)`;
819
+ if (spec.orderBy.length === 0 && spec.limit === void 0) return sql`(select json_group_array(${object}) from ${target} as ${sql.ref(row)} where ${matches(row)})`;
820
+ const inner = `_s${depth}`;
821
+ const order = spec.orderBy.length === 0 ? sql`` : sql` order by ${sql.join(spec.orderBy.map(([column, direction]) => sql`${sql.ref(`${inner}.${column}`)} ${sql.raw(direction)}`))}`;
822
+ const limit = spec.limit === void 0 ? sql`` : sql` limit ${sql.lit(spec.limit)}`;
823
+ return sql`(select json_group_array(${object}) from (select * from ${target} as ${sql.ref(inner)} where ${matches(inner)}${order}${limit}) as ${sql.ref(row)})`;
824
+ }
825
+ /**
826
+ * A relation as a selection: what `related()` returns. `table` is the table
827
+ * it is a relation of (so `with` takes only the related table's own), `alias`
828
+ * the key it is answered under — the relation's name, until `.as()` says
829
+ * another.
830
+ */
831
+ var RelatedExpression = class RelatedExpression {
832
+ table;
833
+ alias;
834
+ constructor(spec) {
835
+ this.table = spec.relation.table;
836
+ this.alias = spec.alias;
837
+ specs.set(this, spec);
838
+ }
839
+ /**
840
+ * The same relation, answered under `name` instead of its own:
841
+ * `related('customers', 'invoices', { columns: ['id'], limit: 1 }).as('latest')`.
842
+ * A new expression — this one keeps its name.
843
+ */
844
+ as(name) {
845
+ const spec = specs.get(this);
846
+ if (typeof name !== "string" || name === "") throw new TypeError(`[durable-db] related('${spec.relation.table}', '${spec.relation.name}').as() takes the name to answer it under.`);
847
+ return new RelatedExpression({
848
+ ...spec,
849
+ alias: name
850
+ });
851
+ }
852
+ get expression() {
853
+ return render(specs.get(this), this.table, 1);
854
+ }
855
+ toOperationNode() {
856
+ const spec = specs.get(this);
857
+ const marked = {
858
+ ...AliasNode.create(render(spec, this.table, 1).toOperationNode(), IdentifierNode.create(this.alias)),
859
+ [RELATED]: metaOf(spec)
860
+ };
861
+ return Object.freeze(marked);
862
+ }
863
+ };
864
+ function specOf(schema, table, name, arg) {
865
+ const relation = relationOf(schema, table, name);
866
+ const where = `[durable-db] related('${table}', '${name}')`;
867
+ const options = Array.isArray(arg) ? { columns: arg } : arg;
868
+ if (typeof options !== "object" || options === null) throw new TypeError(`${where} takes the columns to read: ['id', …], or { columns, with, orderBy, limit }.`);
869
+ const known = getTableColumns(schema[relation.target]);
870
+ const column = (key, what) => {
871
+ if (typeof key !== "string" || !Object.hasOwn(known, key)) throw new TypeError(`${where}: ${what} "${String(key)}" is not a column of "${relation.target}". Its columns: ${Object.keys(known).join(", ")}.`);
872
+ return key;
873
+ };
874
+ if (options.columns !== void 0 && !Array.isArray(options.columns)) throw new TypeError(`${where}: columns is a list of column names.`);
875
+ const columns = [...new Set((options.columns ?? []).map((key) => column(key, "the column")))];
876
+ for (const key of columns) if (known[key].getSQLType() === "blob") throw new TypeError(`${where}: "${key}" is a blob, and a relation is read as JSON, which holds none — read it in a query of its own.`);
877
+ const nested = options.with ?? [];
878
+ if (!Array.isArray(nested)) throw new TypeError(`${where}: with is a list of relations: [related('${relation.target}', …)].`);
879
+ const names = new Set(columns);
880
+ const inner = [];
881
+ for (const item of nested) {
882
+ const spec = item instanceof RelatedExpression ? specs.get(item) : void 0;
883
+ if (!spec) throw new TypeError(`${where}: with is a list of relations: [related('${relation.target}', …)].`);
884
+ if (spec.schema !== schema || spec.relation.table !== relation.target) {
885
+ const other = spec.schema === schema ? "" : " of another database";
886
+ throw new TypeError(`${where}: with takes relations of "${relation.target}", and "${spec.relation.name}" is one of "${spec.relation.table}"${other}.`);
887
+ }
888
+ if (names.has(spec.alias)) throw new TypeError(`${where}: "${spec.alias}" is there twice — as a column and a relation, or two relations under one name.`);
889
+ names.add(spec.alias);
890
+ inner.push(spec);
891
+ }
892
+ if (names.size === 0) throw new TypeError(`${where} reads nothing: name the columns to read.`);
893
+ const orderBy = [];
894
+ for (const [key, direction] of Object.entries(options.orderBy ?? {})) {
895
+ if (direction === void 0) continue;
896
+ if (direction !== "asc" && direction !== "desc") throw new TypeError(`${where}: orderBy.${key} is 'asc' or 'desc'.`);
897
+ orderBy.push([column(key, "orderBy"), direction]);
898
+ }
899
+ const { limit } = options;
900
+ if (limit !== void 0 && (!Number.isSafeInteger(limit) || limit < 0)) throw new TypeError(`${where}: limit is a whole number, 0 or more.`);
901
+ if (relation.kind === "one" && (orderBy.length > 0 || limit !== void 0)) throw new TypeError(`${where} leads to one row: orderBy and limit are for a relation that leads to many.`);
902
+ return {
903
+ schema,
904
+ relation,
905
+ alias: relation.name,
906
+ columns,
907
+ with: inner,
908
+ orderBy,
909
+ limit
910
+ };
911
+ }
912
+ /**
913
+ * `related` for a schema: what `defineDatabase()` hands out, and the way to
914
+ * it for code that is handed a schema — typed by the schema's tables, or by
915
+ * strings (`AnyRelated`) when its type names none.
916
+ */
917
+ function createRelated(schema) {
918
+ const related = (table, relation, arg) => new RelatedExpression(specOf(schema, table, relation, arg));
919
+ return related;
920
+ }
921
+ function isMarked(node) {
922
+ return typeof node === "object" && node !== null && node[RELATED] !== void 0;
923
+ }
924
+ /** The relations among what a query selects (or returns): each by the key its rows carry it under. */
925
+ function relationsIn(node) {
926
+ const root = node;
927
+ let found;
928
+ for (const item of [...root.selections ?? [], ...root.returning?.selections ?? []]) {
929
+ const selected = item.selection;
930
+ if (!isMarked(selected)) continue;
931
+ found ??= /* @__PURE__ */ new Map();
932
+ found.set(selected.alias.name, selected[RELATED]);
933
+ }
934
+ return found;
935
+ }
936
+ function toBoolean(value) {
937
+ if (typeof value === "number") return value !== 0;
938
+ if (value === "true" || value === "1") return true;
939
+ if (value === "false" || value === "0") return false;
940
+ return value;
941
+ }
942
+ /**
943
+ * The two plugins behind `related()`. `capture` goes first — it reads the
944
+ * query as the builder made it, marks and all — and `results` last, when the
945
+ * row's keys are the schema's again.
946
+ */
947
+ function createRelatedPlugins(schema, options = {}) {
948
+ const resultKey = options.resultKey ?? ((name) => name);
949
+ const selected = /* @__PURE__ */ new WeakMap();
950
+ const kinds = /* @__PURE__ */ new Map();
951
+ const kindsOf = (table) => {
952
+ let kind = kinds.get(table);
953
+ if (!kind) {
954
+ kind = {
955
+ dates: /* @__PURE__ */ new Set(),
956
+ booleans: /* @__PURE__ */ new Set(),
957
+ jsons: /* @__PURE__ */ new Set()
958
+ };
959
+ const target = schema[table];
960
+ const columns = target ? getTableColumns(target) : {};
961
+ for (const [key, column] of Object.entries(columns)) if (column.dataType === "date") kind.dates.add(key);
962
+ else if (column.dataType === "boolean") kind.booleans.add(key);
963
+ else if (column.dataType === "json") kind.jsons.add(key);
964
+ kinds.set(table, kind);
965
+ }
966
+ return kind;
967
+ };
968
+ const revive = (value, meta) => {
969
+ if (Array.isArray(value)) return value.map((item) => revive(item, meta));
970
+ if (typeof value !== "object" || value === null) return value;
971
+ const { dates, booleans, jsons } = kindsOf(meta.target);
972
+ const row = value;
973
+ for (const [key, item] of Object.entries(row)) {
974
+ const nested = meta.with.get(key);
975
+ if (nested) row[key] = revive(item, nested);
976
+ else if (dates.has(key)) {
977
+ if (typeof item === "string" && dateSerializers.isSerializedDateString(item)) row[key] = dateSerializers.deserialize(item);
978
+ } else if (booleans.has(key)) row[key] = toBoolean(item);
979
+ else if (jsons.has(key)) row[key] = parseJsonValue(item);
980
+ }
981
+ return row;
982
+ };
983
+ return {
984
+ capture: {
985
+ transformQuery({ node, queryId }) {
986
+ const found = relationsIn(node);
987
+ if (found) selected.set(queryId, found);
988
+ return node;
989
+ },
990
+ async transformResult({ result }) {
991
+ return result;
992
+ }
993
+ },
994
+ results: {
995
+ transformQuery({ node }) {
996
+ return node;
997
+ },
998
+ async transformResult({ result, queryId }) {
999
+ const relations = selected.get(queryId);
1000
+ if (!relations) return result;
1001
+ const rows = result.rows.map((row) => {
1002
+ const out = { ...row };
1003
+ for (const [alias, meta] of relations) {
1004
+ const key = resultKey(alias);
1005
+ if (key !== alias && Object.hasOwn(out, key)) {
1006
+ out[alias] = out[key];
1007
+ delete out[key];
1008
+ }
1009
+ const raw = out[alias];
1010
+ if (typeof raw === "string") out[alias] = revive(JSON.parse(raw), meta);
1011
+ }
1012
+ return out;
1013
+ });
1014
+ return {
1015
+ ...result,
1016
+ rows
1017
+ };
1018
+ }
1019
+ }
1020
+ };
1021
+ }
1022
+ //#endregion
1023
+ //#region src/db/defineDatabase.ts
1024
+ /**
1025
+ * Non-enumerable property the source `action()` stashes on the function it
1026
+ * returns, carrying the original `{ args, handler }` config plus the compiled
1027
+ * arktype validator. The production Vite transform replaces `action()`
1028
+ * call-sites entirely, so this only ever exists in the UNTRANSFORMED world —
1029
+ * i.e. tests. The `durable-db/testing` harness reads it to run a handler
1030
+ * against a real in-memory database. See src/testing/index.ts.
1031
+ */
1032
+ const ACTION_TEST_META = Symbol.for("durable-db.actionTestMeta");
1033
+ /**
1034
+ * Where the live test databases are listed, newest last. On `globalThis`, not
1035
+ * module state: a test run can load `durable-db` (the app's actions) and
1036
+ * `durable-db/testing` as separate module copies.
1037
+ */
1038
+ const LIVE_TEST_DATABASES = Symbol.for("durable-db.liveTestDatabases");
1039
+ /** The live test databases (created on first use). */
1040
+ function liveTestDatabases() {
1041
+ const store = globalThis;
1042
+ return store[LIVE_TEST_DATABASES] ??= [];
1043
+ }
1044
+ /** The newest live test database holding every table of `schema`, if any. */
1045
+ function testDatabaseFor(schema) {
1046
+ const tables = Object.values(schema);
1047
+ if (tables.length === 0) return void 0;
1048
+ const live = globalThis[LIVE_TEST_DATABASES];
1049
+ if (!live) return void 0;
1050
+ for (let i = live.length - 1; i >= 0; i--) if (tables.every((table) => live[i].tables.has(table))) return live[i];
1051
+ }
1052
+ /** `createTestDatabase({ schema: { a, b } })` for this database, for messages. */
1053
+ function testDatabaseHint(schema) {
1054
+ const names = Object.keys(schema);
1055
+ return `createTestDatabase({ schema: { ${names.length > 0 ? names.join(", ") : "…"} } })`;
1056
+ }
1057
+ /**
1058
+ * Define a database with its schema and migrations.
1059
+ *
1060
+ * This function is transformed at build time by the durable-db Vite plugin.
1061
+ * At runtime, the actions returned will be RPC stubs that call into the
1062
+ * generated Durable Object.
1063
+ *
1064
+ * Outside the build — code under test calling an action directly — an action
1065
+ * runs against the test database `createTestDatabase()` created for its
1066
+ * database's tables (the newest one, when there are several); without one it
1067
+ * throws.
1068
+ *
1069
+ * @example
1070
+ * ```ts
1071
+ * import { defineDatabase } from 'durable-db';
1072
+ * import { users, posts } from './schema';
1073
+ *
1074
+ * export const { action } = defineDatabase({
1075
+ * schema: { users, posts },
1076
+ * });
1077
+ *
1078
+ * export const createUser = action({
1079
+ * args: { name: 'string', email: 'string.email' },
1080
+ * handler: async (db, args) => {
1081
+ * return db.insertInto('users').values({
1082
+ * id: crypto.randomUUID(),
1083
+ * name: args.name,
1084
+ * email: args.email
1085
+ * }).returningAll().executeTakeFirst();
1086
+ * },
1087
+ * });
1088
+ * ```
1089
+ */
1090
+ function defineDatabase(config) {
1091
+ const schema = config?.schema ?? {};
1092
+ const action = (actionConfig) => {
1093
+ const validator = actionArgsType(actionConfig.args);
1094
+ const argsDefinition = actionConfig.args;
1095
+ const argKeys = argsDefinition !== null && typeof argsDefinition === "object" ? Object.keys(argsDefinition) : null;
1096
+ const argsHint = argKeys ? ` (args: ${argKeys.length > 0 ? `{ ${argKeys.join(", ")} }` : "{}"})` : "";
1097
+ const actionFn = async (args) => {
1098
+ const testDatabase = testDatabaseFor(schema);
1099
+ if (testDatabase) return await testDatabase.run(actionFn, args);
1100
+ const result = validator(args);
1101
+ if (result instanceof type.errors) throw new Error(`Invalid args for action${argsHint}: ${result.summary}`);
1102
+ throw new Error(`Action${argsHint} called without transformation: action() call sites are transformed by the build; in tests, create the database with ${testDatabaseHint(schema)} and call the action, or use db.run(action, args).`);
1103
+ };
1104
+ Object.defineProperty(actionFn, ACTION_TEST_META, {
1105
+ value: {
1106
+ args: actionConfig.args,
1107
+ handler: actionConfig.handler,
1108
+ validator,
1109
+ schema
1110
+ },
1111
+ enumerable: false,
1112
+ configurable: true
1113
+ });
1114
+ return actionFn;
1115
+ };
1116
+ const destroyDatabase = async () => {
1117
+ const testDatabase = testDatabaseFor(schema);
1118
+ if (testDatabase) {
1119
+ testDatabase.clear();
1120
+ return;
1121
+ }
1122
+ throw new Error(`destroyDatabase() called without transformation: it is transformed by the build; in tests, create the database with ${testDatabaseHint(schema)} first.`);
1123
+ };
1124
+ return {
1125
+ action,
1126
+ destroyDatabase,
1127
+ related: createRelated(schema),
1128
+ get relations() {
1129
+ return relationsOf(schema);
1130
+ }
1131
+ };
1132
+ }
1133
+ //#endregion
1134
+ export { createRelated as a, DrizzleDefaultsPlugin as c, createJsonPlugins as d, dateSerializers as f, relationsOf as h, RelatedExpression as i, SchemaPlugin as l, relationOf as m, defineDatabase as n, createRelatedPlugins as o, parseJsonValue as p, liveTestDatabases as r, DateSerializePlugin as s, ACTION_TEST_META as t, createDrizzlePlugins as u };