durable-db 0.2.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/README.md +175 -25
  2. package/dist/{arktypeConfig-DxP0OcV_.js → actionArgs-1hEaDUia.js} +35 -1
  3. package/dist/cli/bin.js +1 -1
  4. package/dist/cli/index.d.ts +204 -62
  5. package/dist/cli/index.js +4 -3
  6. package/dist/{cli-BUSZTS2D.js → cli-CVS0b2im.js} +272 -95
  7. package/dist/context/index.js +14 -8
  8. package/dist/db/index.d.ts +2 -3
  9. package/dist/db/index.js +216 -25
  10. package/dist/defineDatabase-D_RpcKj1.js +109 -0
  11. package/dist/{defineDatabase-IUthY3Ex.d.ts → defineDatabase-zrUJrMd5.d.ts} +10 -3
  12. package/dist/{index-BdrcuAU7.d.ts → index-CJ6Focq4.d.ts} +70 -17
  13. package/dist/index.d.ts +1 -2
  14. package/dist/index.js +2 -2
  15. package/dist/{kysely-Be6KwFZC.js → kysely-CYmmiwDm.js} +25 -5
  16. package/dist/migrations/generator.d.ts +1 -1
  17. package/dist/migrations/generator.js +1 -1
  18. package/dist/migrations/snapshot.d.ts +2 -2
  19. package/dist/migrations/snapshot.js +1 -91
  20. package/dist/{parser-DR57GOjv.js → parser-DyepmXzE.js} +1 -1
  21. package/dist/registry.d.ts +29 -2
  22. package/dist/registry.js +2 -2
  23. package/dist/snapshot-B9Ae2TrS.d.ts +180 -0
  24. package/dist/snapshot-D_z95s6E.js +459 -0
  25. package/dist/{state-OVuoHRC9.js → state-DGYycIoJ.js} +106 -9
  26. package/dist/testing/index.d.ts +8 -1
  27. package/dist/testing/index.js +30 -11
  28. package/dist/vite/durableDb.d.ts +130 -1
  29. package/dist/vite/durableDb.js +733 -180
  30. package/package.json +15 -14
  31. package/virtual.d.ts +4 -2
  32. package/dist/arktypeConfig-AXvobTPL.d.ts +0 -5
  33. package/dist/defineDatabase-CHmzpzFf.js +0 -70
  34. package/dist/snapshot-CaG5xnE2.d.ts +0 -48
@@ -1,5 +1,4 @@
1
- import "./arktypeConfig-AXvobTPL.js";
2
- import "./defineDatabase-IUthY3Ex.js";
1
+ import "./defineDatabase-zrUJrMd5.js";
3
2
  import { SQLiteTableWithColumns } from "drizzle-orm/sqlite-core";
4
3
  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";
5
4
  import { DurableObject } from "cloudflare:workers";
@@ -81,13 +80,14 @@ interface MigrationStatus {
81
80
  pitrAttemptsRemaining: number;
82
81
  }
83
82
  /**
84
- * Raised when a pending migration fails with "already exists": the storage
85
- * holds schema objects the `__migrations` journal doesn't track. Common
86
- * causes: migration files were renamed or regenerated after the storage was
87
- * created, the storage was written by an older version of the database, or a
88
- * previous attempt crashed partway through a chunk without PITR. Re-running
89
- * can never succeed, so this carries recovery guidance instead of the raw
90
- * SQLITE_ERROR.
83
+ * Raised when a pending migration fails with "already exists" or "duplicate
84
+ * column name": the storage holds schema objects the `__migrations` journal
85
+ * doesn't track. Common causes: dev migrations (`db push`) that `db generate`
86
+ * squashed into a production migration the dev storage cannot replay,
87
+ * migration files renamed or regenerated after the storage was created, the
88
+ * storage written by an older version of the database, or a previous attempt
89
+ * that crashed partway through a chunk without PITR. Re-running can never
90
+ * succeed, so this carries recovery guidance instead of the raw SQLITE_ERROR.
91
91
  */
92
92
  declare class MigrationSchemaConflictError extends Error {
93
93
  constructor(message: string, options?: ErrorOptions);
@@ -150,10 +150,24 @@ declare abstract class SqliteDurableObject<Env = unknown> extends DurableObject<
150
150
  * Raw SQLite storage access
151
151
  */
152
152
  protected sql: SqlStorage;
153
+ /**
154
+ * The name `db` commands know this database by (its file name, prefixed by
155
+ * its mount for a mounted source), used in recovery hints. The generated
156
+ * Durable Object sets it; a hand-written subclass that does not gets a
157
+ * best-effort name derived from its class name (`<PascalCase(name)>DatabaseDO`).
158
+ */
159
+ protected databaseName?: string;
153
160
  /**
154
161
  * Whether migrations have been run for this instance
155
162
  */
156
163
  private migrationsApplied;
164
+ /**
165
+ * The migration run in flight, shared by every caller that arrives while it
166
+ * runs. `runMigrations()` reads the pending list and then awaits (the PITR
167
+ * probe and bookmark) before it applies anything, so two first calls racing
168
+ * on a boolean flag would both apply the same `CREATE TABLE`s.
169
+ */
170
+ private migrating;
157
171
  /**
158
172
  * Cached result of PITR availability check (null = not yet checked)
159
173
  */
@@ -178,7 +192,8 @@ declare abstract class SqliteDurableObject<Env = unknown> extends DurableObject<
178
192
  */
179
193
  protected resetMigrationState(): void;
180
194
  /**
181
- * Ensure migrations are applied before any operation
195
+ * Ensure migrations are applied before any operation. Concurrent first
196
+ * calls share one migration run (a failed run is retried by the next call).
182
197
  */
183
198
  protected ensureMigrations(): Promise<void>;
184
199
  /**
@@ -197,21 +212,59 @@ declare abstract class SqliteDurableObject<Env = unknown> extends DurableObject<
197
212
  * After MAX_PITR_ATTEMPTS, stop restoring and let the error propagate
198
213
  */
199
214
  private runMigrations;
215
+ /**
216
+ * Record pending production migrations whose every statement was already
217
+ * applied by this storage's dev migrations, without executing them.
218
+ *
219
+ * The dev loop is `db push` (a squashed dev migration `_dev_<hash>`, applied
220
+ * by the running dev server) and then `db generate`, which writes the same
221
+ * statements as a production migration and drops the dev one. The dev
222
+ * storage has the schema but its journal only knows the dev name, so the
223
+ * production migration would run again and fail ("duplicate column name",
224
+ * "already exists") on every request. Only a storage that applied dev
225
+ * migrations has the statements table, so this never runs in production.
226
+ *
227
+ * A migration with any chunk already applied, or with a statement no dev
228
+ * migration ran, is left pending. Returns the chunks still to execute.
229
+ */
230
+ private settleMigrationsAppliedInDev;
231
+ /**
232
+ * The statements of pending dev migrations that an earlier dev migration of
233
+ * this storage already ran (normalized), by pending dev migration.
234
+ *
235
+ * `db push` always diffs from the production snapshot, so after a second
236
+ * schema change the new squashed dev migration holds the previous one's
237
+ * statements again — `ADD weight_grams` next to the new `ADD color_code` —
238
+ * and this storage applied them with the previous one. An earlier dev
239
+ * migration's statements are skipped only when the pending one contains
240
+ * every statement that migration ran: then it is the same change, squashed
241
+ * again. A statement the pending migration shares with an earlier one only
242
+ * in part (a table rebuilt differently) still runs, and a conflict is
243
+ * reported as one.
244
+ */
245
+ private statementsRepeatedFromEarlierPushes;
246
+ /**
247
+ * The statements this storage's dev migrations applied (normalized →
248
+ * the dev migration that ran it), or null when it never ran one.
249
+ */
250
+ private readDevStatements;
200
251
  /**
201
252
  * Collect pending migration chunks that haven't been applied yet.
202
253
  */
203
254
  private collectPendingMigrations;
204
255
  /**
205
- * Apply a list of pending migration chunks.
256
+ * Apply a list of pending migration chunks, skipping the statements of a
257
+ * dev migration that earlier dev migrations already ran (`repeated`, see
258
+ * {@link statementsRepeatedFromEarlierPushes}).
206
259
  */
207
260
  private applyMigrations;
208
261
  /**
209
- * Translate an "already exists" failure on a pending migration into a
210
- * {@link MigrationSchemaConflictError}. A chunk is only executed when the
211
- * journal has no row for it, so "already exists" means storage and journal
212
- * disagree about what has been applied — retrying can never succeed, and
213
- * the raw SQLITE_ERROR doesn't tell the user how to get unstuck.
214
- * Returns null when the error isn't this case.
262
+ * Translate an "already exists" or "duplicate column name" failure on a
263
+ * pending migration into a {@link MigrationSchemaConflictError}. A chunk is
264
+ * only executed when the journal has no row for it, so either error means
265
+ * storage and journal disagree about what has been applied — retrying can
266
+ * never succeed, and the raw SQLITE_ERROR doesn't tell the user how to get
267
+ * unstuck. Returns null when the error isn't this case.
215
268
  */
216
269
  private toSchemaConflictError;
217
270
  /**
package/dist/index.d.ts CHANGED
@@ -1,5 +1,4 @@
1
- import { t as type } from "./arktypeConfig-AXvobTPL.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-IUthY3Ex.js";
1
+ import { c as DatabaseDefinition, d as InferArgs, i as ActionContext, n as Action, p as type, r as ActionConfig, s as DatabaseConfig, t as defineDatabase, u as DrizzleToKysely } from "./defineDatabase-zrUJrMd5.js";
3
2
  import { getTenantId, hasTenantId, setTenantIdResolver } from "./context/index.js";
4
3
  import { AnySQLiteColumn, blob, foreignKey, index, integer, numeric, primaryKey, real, table, text, uniqueIndex } from "./schema.js";
5
4
  import { Kysely } from "kysely";
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { t as type } from "./arktypeConfig-DxP0OcV_.js";
2
- import { n as defineDatabase } from "./defineDatabase-CHmzpzFf.js";
1
+ import { n as type } from "./actionArgs-1hEaDUia.js";
2
+ import { n as defineDatabase } from "./defineDatabase-D_RpcKj1.js";
3
3
  import { blob, foreignKey, index, integer, numeric, primaryKey, real, table, text, uniqueIndex } from "./schema.js";
4
4
  import { getTenantId, hasTenantId, setTenantIdResolver } from "./context/index.js";
5
5
  export { blob, defineDatabase, foreignKey, getTenantId, hasTenantId, index, integer, numeric, primaryKey, real, setTenantIdResolver, table, text, type, uniqueIndex };
@@ -1,6 +1,6 @@
1
1
  import { SQLiteSyncDialect, getTableConfig } from "drizzle-orm/sqlite-core";
2
2
  import { toCamelCase, toSnakeCase } from "drizzle-orm/casing";
3
- import { CamelCasePlugin, ColumnNode, ColumnUpdateNode, InsertQueryNode, Kysely, PrimitiveValueListNode, SqliteDialect, TableNode, ValueListNode, ValueNode, ValuesNode, sql } from "kysely";
3
+ import { CamelCasePlugin, ColumnNode, ColumnUpdateNode, InsertQueryNode, Kysely, PrimitiveValueListNode, SqliteDialect, SqliteQueryCompiler, TableNode, ValueListNode, ValueNode, ValuesNode, sql } from "kysely";
4
4
  import { Table, getTableColumns, getTableName, is, isSQLWrapper } from "drizzle-orm";
5
5
  //#region src/db/plugins.ts
6
6
  /**
@@ -359,6 +359,26 @@ function createDrizzlePlugins(schema, camelCase = true) {
359
359
  //#region src/db/kysely.ts
360
360
  const MAX_BOUND_PARAMETERS = 100;
361
361
  /**
362
+ * Kysely's SQLite compiler with identifiers quoted in backticks instead of
363
+ * double quotes. SQLite (workerd's build included) reads a double-quoted
364
+ * identifier that names no column as a string literal, so a column missing
365
+ * from the database — a schema change not yet migrated — silently selects its
366
+ * own name (`"weight_grams"` → 'weight_grams') and a WHERE on it compares two
367
+ * constants. A backtick-quoted identifier is never a literal: the query fails
368
+ * with "no such column". The migrations already quote with backticks.
369
+ */
370
+ var BacktickSqliteQueryCompiler = class extends SqliteQueryCompiler {
371
+ getLeftIdentifierWrapper() {
372
+ return "`";
373
+ }
374
+ getRightIdentifierWrapper() {
375
+ return "`";
376
+ }
377
+ sanitizeIdentifier(identifier) {
378
+ return identifier.replaceAll("`", "``");
379
+ }
380
+ };
381
+ /**
362
382
  * workerd has no boolean binding type and silently stringifies JS booleans
363
383
  * (storing TEXT 'true' in an INTEGER column); node:sqlite rejects them
364
384
  * outright. Normalize to SQLite's 1/0 convention before the value reaches
@@ -392,8 +412,8 @@ function escapeLiteral(value) {
392
412
  /**
393
413
  * Replace each `?` placeholder in `sql` with the escaped literal of its
394
414
  * parameter. A real scanner, not a regex: '…' string literals ('' escapes),
395
- * "…" quoted identifiers, `--` line comments and C-style block comments are
396
- * skipped, so a `?` inside any of them is never touched.
415
+ * "…" and `…` quoted identifiers, `--` line comments and C-style block
416
+ * comments are skipped, so a `?` inside any of them is never touched.
397
417
  *
398
418
  * Exported for tests.
399
419
  */
@@ -402,7 +422,7 @@ function inlineParameters(sql, parameters) {
402
422
  let p = 0;
403
423
  for (let i = 0; i < sql.length; i++) {
404
424
  const ch = sql[i];
405
- if (ch === "'" || ch === "\"") {
425
+ if (ch === "'" || ch === "\"" || ch === "`") {
406
426
  let j = i + 1;
407
427
  while (j < sql.length) {
408
428
  if (sql[j] === ch) {
@@ -542,7 +562,7 @@ function createKyselyFromSql(sqlStorage, options = {}) {
542
562
  createAdapter: () => sqliteDialect.createAdapter(),
543
563
  createDriver: () => new CloudflareSqliteDriver(sqlStorage),
544
564
  createIntrospector: (db) => sqliteDialect.createIntrospector(db),
545
- createQueryCompiler: () => sqliteDialect.createQueryCompiler()
565
+ createQueryCompiler: () => new BacktickSqliteQueryCompiler()
546
566
  },
547
567
  plugins: allPlugins
548
568
  });
@@ -1,4 +1,4 @@
1
- import { t as Snapshot } from "../snapshot-CaG5xnE2.js";
1
+ import { n as Snapshot } from "../snapshot-B9Ae2TrS.js";
2
2
  //#region src/migrations/generator.d.ts
3
3
  /**
4
4
  * Result of migration generation
@@ -1,5 +1,5 @@
1
1
  import { i as init_debug, n as debugMigrations } from "../debug-Cz8KzMft.js";
2
- import { createEmptySnapshot, generateMigrationStatements, generateSnapshotFromSchema, generateSnapshotId, snapshotsEqual } from "./snapshot.js";
2
+ import { a as generateSnapshotId, i as generateSnapshotFromSchema, n as createEmptySnapshot, r as generateMigrationStatements, s as snapshotsEqual } from "../snapshot-D_z95s6E.js";
3
3
  import * as fs from "node:fs";
4
4
  import * as path$1 from "node:path";
5
5
  import * as os from "node:os";
@@ -1,2 +1,2 @@
1
- import { a as generateSnapshotId, i as generateSnapshotFromSchema, n as createEmptySnapshot, o as hashSnapshot, r as generateMigrationStatements, s as snapshotsEqual, t as Snapshot } from "../snapshot-CaG5xnE2.js";
2
- export { Snapshot, createEmptySnapshot, generateMigrationStatements, generateSnapshotFromSchema, generateSnapshotId, hashSnapshot, snapshotsEqual };
1
+ import { C as renamesFromStatements, S as parseRenameSpec, _ as applyRenames, a as generateMigrationStatements, b as findAmbiguities, c as hashSnapshot, d as MigrationRiskKind, f as NOT_NULL_WITHOUT_DEFAULT_HINT, g as SchemaRenameRequiredError, h as SchemaAmbiguity, i as createEmptySnapshot, l as snapshotsEqual, m as RenameAnswer, n as Snapshot, o as generateSnapshotFromSchema, p as analyzeMigrationRisks, r as canPrompt, s as generateSnapshotId, t as MigrationResolution, u as MigrationRisk, v as describeAmbiguity, w as unusedRenames, x as formatRename, y as exampleRenames } from "../snapshot-B9Ae2TrS.js";
2
+ export { MigrationResolution, type MigrationRisk, type MigrationRiskKind, NOT_NULL_WITHOUT_DEFAULT_HINT, type RenameAnswer, type SchemaAmbiguity, SchemaRenameRequiredError, Snapshot, analyzeMigrationRisks, applyRenames, canPrompt, createEmptySnapshot, describeAmbiguity, exampleRenames, findAmbiguities, formatRename, generateMigrationStatements, generateSnapshotFromSchema, generateSnapshotId, hashSnapshot, parseRenameSpec, renamesFromStatements, snapshotsEqual, unusedRenames };
@@ -1,91 +1 @@
1
- import { createRequire } from "node:module";
2
- //#region src/migrations/snapshot.ts
3
- const { generateSQLiteDrizzleJson, generateSQLiteMigration } = createRequire(import.meta.url)("drizzle-kit/api");
4
- /**
5
- * Create an empty snapshot (for initial migration from nothing)
6
- */
7
- function createEmptySnapshot() {
8
- return {
9
- views: {},
10
- version: "6",
11
- dialect: "sqlite",
12
- id: "0000000000000",
13
- prevId: "",
14
- tables: {},
15
- enums: {},
16
- _meta: {
17
- tables: {},
18
- columns: {}
19
- }
20
- };
21
- }
22
- /**
23
- * Generate a unique snapshot ID based on timestamp
24
- */
25
- function generateSnapshotId() {
26
- return Date.now().toString(36).padStart(13, "0");
27
- }
28
- /**
29
- * Generate a snapshot from Drizzle schema objects
30
- *
31
- * @param schema - Object containing Drizzle table definitions
32
- * @returns Snapshot representing the current schema state
33
- *
34
- * @example
35
- * ```ts
36
- * import { users, posts } from './schema';
37
- * const snapshot = await generateSnapshotFromSchema({ users, posts });
38
- * ```
39
- */
40
- async function generateSnapshotFromSchema(schema) {
41
- return generateSQLiteDrizzleJson(schema, void 0, "snake_case");
42
- }
43
- /**
44
- * Generate SQL migration statements from two snapshots
45
- *
46
- * @param from - Previous schema state (or empty for initial migration)
47
- * @param to - Target schema state
48
- * @returns Array of SQL statements to migrate from `from` to `to`
49
- *
50
- * @example
51
- * ```ts
52
- * const statements = await generateMigrationStatements(prevSnapshot, newSnapshot);
53
- * // ['CREATE TABLE users (...)', 'CREATE INDEX ...']
54
- * ```
55
- */
56
- async function generateMigrationStatements(from, to) {
57
- return await generateSQLiteMigration(from, to);
58
- }
59
- /**
60
- * Serialize the schema-relevant parts of a snapshot for comparison/hashing.
61
- * Includes tables, views, and enums so that changes to any of them are
62
- * detected — previously only `tables` was considered.
63
- */
64
- function serializeSchemaShape(snapshot) {
65
- return JSON.stringify({
66
- tables: snapshot.tables ?? {},
67
- views: snapshot.views ?? {},
68
- enums: snapshot.enums ?? {}
69
- });
70
- }
71
- /**
72
- * Check if two snapshots are equivalent (no migration needed)
73
- */
74
- function snapshotsEqual(a, b) {
75
- return serializeSchemaShape(a) === serializeSchemaShape(b);
76
- }
77
- /**
78
- * Create a hash of a snapshot for quick comparison
79
- */
80
- function hashSnapshot(snapshot) {
81
- const content = serializeSchemaShape(snapshot);
82
- let hash = 0;
83
- for (let i = 0; i < content.length; i++) {
84
- const char = content.charCodeAt(i);
85
- hash = (hash << 5) - hash + char;
86
- hash = hash & hash;
87
- }
88
- return Math.abs(hash).toString(36);
89
- }
90
- //#endregion
91
- export { createEmptySnapshot, generateMigrationStatements, generateSnapshotFromSchema, generateSnapshotId, hashSnapshot, snapshotsEqual };
1
+ export { c as NOT_NULL_WITHOUT_DEFAULT_HINT, u as SchemaRenameRequiredError, l as analyzeMigrationRisks, d as applyRenames, t as canPrompt, n as createEmptySnapshot, f as describeAmbiguity, p as exampleRenames, m as findAmbiguities, h as formatRename, r as generateMigrationStatements, i as generateSnapshotFromSchema, a as generateSnapshotId, o as hashSnapshot, g as parseRenameSpec, _ as renamesFromStatements, s as snapshotsEqual, v as unusedRenames } from "../snapshot-D_z95s6E.js";
@@ -426,4 +426,4 @@ function toScreamingSnakeCase(str) {
426
426
  return str.replace(/([a-z])([A-Z])/g, "$1_$2").replace(/[-]/g, "_").toUpperCase();
427
427
  }
428
428
  //#endregion
429
- export { discoverDatabaseFiles as a, loadViteAliases as c, discoverActionFiles as i, parseDatabaseFile as n, readFile as o, databaseSources as r, resolveImportPath as s, BABEL_PARSER_PLUGINS as t };
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 };
@@ -1,4 +1,31 @@
1
- import { t as type } from "./arktypeConfig-AXvobTPL.js";
1
+ import { type } from "arktype";
2
+ //#region src/db/actionArgs.d.ts
3
+ /**
4
+ * ArkType's `type`, for an action's `args` schema: jitless like
5
+ * `../arktypeConfig` (eval-free for Workers), and with an optional key
6
+ * accepting `undefined`.
7
+ *
8
+ * ArkType checks an optional key as TypeScript's `exactOptionalPropertyTypes`
9
+ * would by default: `'photoKey?': 'string'` rejects `{ photoKey: undefined }`,
10
+ * while the inferred `{ photoKey?: string }` accepts it under TypeScript's
11
+ * default settings — so `addReview({ …, photoKey: maybeKey })` type-checks and
12
+ * then fails at runtime. This scope turns ArkType's
13
+ * `exactOptionalPropertyTypes` off: an optional key, at any depth, admits
14
+ * `undefined`, and a required key stays required (`'note': 'string |
15
+ * undefined'` must be present, as TypeScript says). The validator is a plain
16
+ * object Type — `.props`, `.toJsonSchema()` and `.assert()` work as usual; in
17
+ * JSON Schema the `undefined` an optional key admits is `{ not: {} }` (a JSON
18
+ * document never holds it), so `'photoKey?': 'string'` is still a string.
19
+ *
20
+ * An `args` given as a ready `type(…)` keeps the rules of the scope that made
21
+ * it.
22
+ *
23
+ * The action transform compiles `args` with this (it is the `type` that
24
+ * `durable-db/registry` exports), for the RPC stub and the Durable Object
25
+ * alike; the untransformed `action()` and the test harness use it too.
26
+ */
27
+ declare const actionArgsType: typeof type;
28
+ //#endregion
2
29
  //#region src/registry.d.ts
3
30
  export interface ActionDefinition {
4
31
  validator: (args: unknown) => unknown;
@@ -26,4 +53,4 @@ export declare function runWithDoContext<T>(store: DoContext, fn: () => T): T;
26
53
  */
27
54
  export declare function callAction(db: unknown, targetDb: string, actionName: string, args: unknown, ctx: RpcContext): Promise<unknown>;
28
55
  //#endregion
29
- export { type };
56
+ export { actionArgsType as type };
package/dist/registry.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as type } from "./arktypeConfig-DxP0OcV_.js";
1
+ import { n as type, t as actionArgsType } from "./actionArgs-1hEaDUia.js";
2
2
  import { WebSocketTransport } from "./transport/websocket.js";
3
3
  import { AsyncLocalStorage } from "node:async_hooks";
4
4
  //#region src/registry.ts
@@ -69,4 +69,4 @@ async function callAction(db, targetDb, actionName, args, ctx) {
69
69
  return structuredClone(result);
70
70
  }
71
71
  //#endregion
72
- export { callAction, getAction, getDoContext, registerAction, runWithDoContext, type };
72
+ export { callAction, getAction, getDoContext, registerAction, runWithDoContext, actionArgsType as type };
@@ -0,0 +1,180 @@
1
+ import { DrizzleSQLiteSnapshotJSON } from "drizzle-kit/api";
2
+ //#region src/migrations/renames.d.ts
3
+ type Snapshot$2 = DrizzleSQLiteSnapshotJSON;
4
+ /** One answer to drizzle-kit's "created or renamed?" question. */
5
+ type RenameAnswer = {
6
+ kind: 'table';
7
+ from: string;
8
+ to: string;
9
+ } | {
10
+ kind: 'column';
11
+ table: string;
12
+ from: string;
13
+ to: string;
14
+ };
15
+ /**
16
+ * Parse a rename answer as typed on the command line:
17
+ * `<table>.<old>=<new>` renames a column, `<old>=<new>` a table. Names are the
18
+ * SQL names (snake_case, as in the migration files); a camelCase property name
19
+ * is accepted too and converted the way durable-db's schema does.
20
+ */
21
+ declare function parseRenameSpec(spec: string): RenameAnswer;
22
+ declare function formatRename(answer: RenameAnswer): string;
23
+ /**
24
+ * A place where drizzle-kit would ask "created or renamed?": a table (or
25
+ * view) set, or one table's columns, with both new and vanished names.
26
+ */
27
+ interface SchemaAmbiguity {
28
+ kind: 'table' | 'column' | 'view';
29
+ /** The table, for a column ambiguity. */
30
+ table?: string;
31
+ /** Names only in the new schema. */
32
+ created: string[];
33
+ /** Names only in the old schema. */
34
+ deleted: string[];
35
+ }
36
+ /** Every question drizzle-kit would ask to diff `prev` → `cur`. */
37
+ declare function findAmbiguities(prevSnapshot: Snapshot$2, curSnapshot: Snapshot$2): SchemaAmbiguity[];
38
+ /** One line per ambiguity: `products: summary added, description removed`. */
39
+ declare function describeAmbiguity(ambiguity: SchemaAmbiguity): string;
40
+ /** Example `--rename` answers for an ambiguity (each new name from the first vanished one). */
41
+ declare function exampleRenames(ambiguity: SchemaAmbiguity): string[];
42
+ /**
43
+ * The diff needs answers drizzle-kit can only ask for in a terminal: no TTY,
44
+ * or a caller that asked for no prompts, and no `--rename` / `--no-renames`
45
+ * answer for these.
46
+ */
47
+ declare class SchemaRenameRequiredError extends Error {
48
+ readonly ambiguities: SchemaAmbiguity[];
49
+ /** Set by the CLI to the database the diff belongs to. */
50
+ database?: string;
51
+ constructor(ambiguities: SchemaAmbiguity[]);
52
+ /** Name the database the diff belongs to (in the message too). */
53
+ forDatabase(database: string): this;
54
+ /**
55
+ * The message, naming the command to re-run (`lagerverk db generate`, `db push`…).
56
+ */
57
+ describe(command?: string): string;
58
+ }
59
+ interface AppliedRenames {
60
+ /** `prev` with the renames applied (a copy). */
61
+ snapshot: Snapshot$2;
62
+ /** The `ALTER TABLE … RENAME` statements, in drizzle-kit's own format. */
63
+ statements: string[];
64
+ /** The answers that applied here, normalized to the snapshot's names. */
65
+ applied: RenameAnswer[];
66
+ }
67
+ /**
68
+ * Apply rename answers to `prev`, as SQLite's `ALTER TABLE … RENAME` does
69
+ * (references in indexes, keys and foreign keys follow the new name). An
70
+ * answer applies when its old name exists only in `prev` and its new name
71
+ * only in `cur`; answers that match nothing here are left out of `applied`
72
+ * (the caller decides whether an unused answer is an error — with several
73
+ * databases, an answer usually belongs to one of them).
74
+ */
75
+ declare function applyRenames(prevSnapshot: Snapshot$2, curSnapshot: Snapshot$2, answers: RenameAnswer[]): AppliedRenames;
76
+ /**
77
+ * The answers no diff used — an answer that matches no pending change is a
78
+ * typo or a stale flag, worth an error rather than silence. `performed` are
79
+ * the renames the generated statements carry ({@link renamesFromStatements}).
80
+ */
81
+ declare function unusedRenames(answers: RenameAnswer[], performed: RenameAnswer[]): RenameAnswer[];
82
+ /**
83
+ * The renames a statement list performs (drizzle-kit's own, after an
84
+ * interactive answer, or durable-db's). drizzle-kit's table recreation
85
+ * (`__new_<table>` renamed back) is not a rename.
86
+ */
87
+ declare function renamesFromStatements(statements: string[]): RenameAnswer[];
88
+ //#endregion
89
+ //#region src/migrations/risks.d.ts
90
+ type Snapshot$1 = DrizzleSQLiteSnapshotJSON;
91
+ type MigrationRiskKind = 'add-not-null-without-default' | 'set-not-null' | 'drop-column' | 'drop-table';
92
+ interface MigrationRisk {
93
+ kind: MigrationRiskKind;
94
+ /** `error`: fails on every table that has rows. `warning`: loses data, or may fail. */
95
+ severity: 'error' | 'warning';
96
+ table: string;
97
+ column?: string;
98
+ message: string;
99
+ }
100
+ /** The remedy `db generate` prints when it refuses a NOT NULL column without a default. */
101
+ declare const NOT_NULL_WITHOUT_DEFAULT_HINT = "fails on every table that has rows: add .default(...) or add it nullable and backfill";
102
+ /**
103
+ * What the change `prev` → `cur` risks on a database that has rows, given the
104
+ * renames it performs (pass {@link renamesFromStatements} of the generated
105
+ * SQL, so interactive answers count too).
106
+ */
107
+ declare function analyzeMigrationRisks(prevSnapshot: Snapshot$1, curSnapshot: Snapshot$1, renames?: RenameAnswer[]): MigrationRisk[];
108
+ //#endregion
109
+ //#region src/migrations/snapshot.d.ts
110
+ type Snapshot = DrizzleSQLiteSnapshotJSON;
111
+ /**
112
+ * How to answer drizzle-kit's "created or renamed?" questions — asked when a
113
+ * table (or a table's columns) has both a new and a vanished name.
114
+ */
115
+ interface MigrationResolution {
116
+ /**
117
+ * Renames, as `RenameAnswer`s or `<table>.<old>=<new>` / `<old>=<new>`
118
+ * strings. Applied before drizzle-kit diffs, so it never asks about them.
119
+ */
120
+ renames?: Array<RenameAnswer | string>;
121
+ /**
122
+ * Answer every remaining question with "create": the vanished column/table
123
+ * is dropped (its data is lost) and the new one created.
124
+ */
125
+ noRenames?: boolean;
126
+ /**
127
+ * Whether drizzle-kit may prompt for what is still unanswered. Default:
128
+ * when stdin and stdout are TTYs. Without prompts an unanswered question
129
+ * throws {@link SchemaRenameRequiredError} (instead of drizzle-kit's bare
130
+ * "Interactive prompts require a TTY terminal").
131
+ */
132
+ interactive?: boolean;
133
+ }
134
+ /** Whether drizzle-kit's prompts can run (it checks the same). */
135
+ declare function canPrompt(): boolean;
136
+ /**
137
+ * Create an empty snapshot (for initial migration from nothing)
138
+ */
139
+ declare function createEmptySnapshot(): Snapshot;
140
+ /**
141
+ * Generate a unique snapshot ID based on timestamp
142
+ */
143
+ declare function generateSnapshotId(): string;
144
+ /**
145
+ * Generate a snapshot from Drizzle schema objects
146
+ *
147
+ * @param schema - Object containing Drizzle table definitions
148
+ * @returns Snapshot representing the current schema state
149
+ *
150
+ * @example
151
+ * ```ts
152
+ * import { users, posts } from './schema';
153
+ * const snapshot = await generateSnapshotFromSchema({ users, posts });
154
+ * ```
155
+ */
156
+ declare function generateSnapshotFromSchema(schema: Record<string, unknown>): Promise<any>;
157
+ /**
158
+ * Generate SQL migration statements from two snapshots
159
+ *
160
+ * @param from - Previous schema state (or empty for initial migration)
161
+ * @param to - Target schema state
162
+ * @returns Array of SQL statements to migrate from `from` to `to`
163
+ *
164
+ * @example
165
+ * ```ts
166
+ * const statements = await generateMigrationStatements(prevSnapshot, newSnapshot);
167
+ * // ['CREATE TABLE users (...)', 'CREATE INDEX ...']
168
+ * ```
169
+ */
170
+ declare function generateMigrationStatements(from: Snapshot, to: Snapshot, resolution?: MigrationResolution): Promise<string[]>;
171
+ /**
172
+ * Check if two snapshots are equivalent (no migration needed)
173
+ */
174
+ declare function snapshotsEqual(a: Snapshot, b: Snapshot): boolean;
175
+ /**
176
+ * Create a hash of a snapshot for quick comparison
177
+ */
178
+ declare function hashSnapshot(snapshot: Snapshot): string;
179
+ //#endregion
180
+ export { renamesFromStatements as C, parseRenameSpec as S, applyRenames as _, generateMigrationStatements as a, findAmbiguities as b, hashSnapshot as c, MigrationRiskKind as d, NOT_NULL_WITHOUT_DEFAULT_HINT as f, SchemaRenameRequiredError as g, SchemaAmbiguity as h, createEmptySnapshot as i, snapshotsEqual as l, RenameAnswer as m, Snapshot as n, generateSnapshotFromSchema as o, analyzeMigrationRisks as p, canPrompt as r, generateSnapshotId as s, MigrationResolution as t, MigrationRisk as u, describeAmbiguity as v, unusedRenames as w, formatRename as x, exampleRenames as y };