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,7 +1,7 @@
1
1
  import { t as DatabaseSource } from "../discovery-gHeLq8jk.js";
2
- import { t as Snapshot } from "../snapshot-CaG5xnE2.js";
3
- import { l as DatabaseInfo } from "../defineDatabase-IUthY3Ex.js";
4
- import "../index-BdrcuAU7.js";
2
+ import { S as parseRenameSpec, g as SchemaRenameRequiredError, h as SchemaAmbiguity, m as RenameAnswer, n as Snapshot, t as MigrationResolution, u as MigrationRisk } from "../snapshot-B9Ae2TrS.js";
3
+ import { l as DatabaseInfo } from "../defineDatabase-zrUJrMd5.js";
4
+ import "../index-CJ6Focq4.js";
5
5
  import { Command } from "commander";
6
6
  //#region src/cli/command.d.ts
7
7
  /**
@@ -35,12 +35,22 @@ export declare function createDbCommand(defaults?: DbCommandDefaults): Command;
35
35
  //#region src/cli/state.d.ts
36
36
  interface DatabaseDevState {
37
37
  /** Hash of the production snapshot when dev migrations started */
38
- prodSnapshotHash: string;
38
+ prodSnapshotHash?: string;
39
39
  /** Timestamp of last push */
40
- lastPush: string | null;
40
+ lastPush?: string | null;
41
+ /**
42
+ * This database's own dev epoch, set by `db reset --database <name>`: its
43
+ * instance keys are suffixed with it instead of the project epoch, so one
44
+ * database starts fresh while every other keeps its data. Absent → the
45
+ * project epoch ({@link DevState.epoch}) applies.
46
+ */
47
+ epoch?: string;
41
48
  }
42
49
  interface DevState {
43
- /** Epoch for instance key suffixing - bump this to reset all dev DBs */
50
+ /**
51
+ * Project epoch for instance key suffixing — bump this to reset every dev
52
+ * database. A database with its own `databases[name].epoch` uses that one.
53
+ */
44
54
  epoch: string;
45
55
  /** Per-database state */
46
56
  databases: Record<string, DatabaseDevState>;
@@ -73,6 +83,13 @@ export declare function loadDevState(projectRoot: string): DevState;
73
83
  * Save the dev state to disk
74
84
  */
75
85
  export declare function saveDevState(projectRoot: string, state: DevState): void;
86
+ /**
87
+ * The dev epoch a database's instance keys are suffixed with: its own epoch
88
+ * (after `db reset --database <name>`), else the project epoch.
89
+ */
90
+ export declare function getDatabaseEpoch(state: DevState, dbName: string): string;
91
+ /** Every database that has its own dev epoch, by name. */
92
+ export declare function getDatabaseEpochs(state: DevState): Record<string, string>;
76
93
  /**
77
94
  * Load dev migrations for a database
78
95
  */
@@ -81,24 +98,133 @@ export declare function loadDevMigrations(projectRoot: string, dbName: string):
81
98
  * Get the dev epoch for instance key suffixing
82
99
  * Returns null in production or if no dev state exists
83
100
  */
84
- export declare function getDevEpoch(projectRoot: string): string | null;
101
+ export declare function getDevEpoch(projectRoot: string, dbName?: string): string | null;
85
102
  /**
86
103
  * Get a database instance key with optional dev epoch suffix
87
104
  */
88
105
  export declare function getInstanceKey(baseKey: string, epoch: string | null): string;
106
+ /** What the Vite plugin records about a running dev server. */
107
+ interface DevServerLock {
108
+ /** The dev server's process id. */
109
+ pid: number;
110
+ /** Identifies the server instance that wrote the lock (a restart writes a new one). */
111
+ token: string;
112
+ /** ISO timestamp. */
113
+ startedAt: string;
114
+ }
115
+ /**
116
+ * The dev server running for this project, from the lock the Vite plugin
117
+ * writes — null when there is none, or its process is gone (a crashed or
118
+ * killed server never removed its lock).
119
+ */
120
+ export declare function runningDevServer(projectRoot: string): DevServerLock | null;
121
+ //#endregion
122
+ //#region src/cli/shared.d.ts
123
+ /**
124
+ * Print a caught error to stderr. Always shows the message; when verbose
125
+ * (flag or `DEBUG=*`) is set, also prints the stack so users can diagnose
126
+ * unexpected failures without patching the CLI.
127
+ */
128
+ export declare function reportCliError(error: unknown, verbose?: boolean): void;
129
+ interface DiscoverOptions {
130
+ projectRoot: string;
131
+ /** A directory, or several with name prefixes — see DiscoveryOptions. */
132
+ databasesDir: string | DatabaseSource[];
133
+ migrationsDir: string;
134
+ /** Only return databases matching this name */
135
+ database?: string;
136
+ }
137
+ interface DiffResult {
138
+ hasChanges: boolean;
139
+ statements: string[];
140
+ prodSnapshot: Snapshot;
141
+ currentSnapshot: Snapshot;
142
+ /** What the statements risk on a database that has rows (see analyzeMigrationRisks). */
143
+ risks: MigrationRisk[];
144
+ }
145
+ /** A `--database` filter that names no discovered database. */
146
+ export declare class UnknownDatabaseError extends Error {
147
+ readonly database: string;
148
+ readonly known: string[];
149
+ constructor(database: string, known: string[]);
150
+ }
151
+ /**
152
+ * The databases a command works on: every discovered one, or the one a
153
+ * `--database` filter names — an unknown name throws
154
+ * {@link UnknownDatabaseError} listing the valid ones, instead of quietly
155
+ * matching nothing ("No databases found.", exit 0).
156
+ */
157
+ export declare function selectDatabases(opts: DiscoverOptions): DatabaseInfo[];
158
+ /**
159
+ * Discover database files, parse them, and resolve migrationsDir.
160
+ * Returns parsed DatabaseInfo[] with migrationsDir already set.
161
+ */
162
+ export declare function discoverDatabases(opts: DiscoverOptions): DatabaseInfo[];
163
+ /**
164
+ * Load and validate schema for a database.
165
+ *
166
+ * Returns null only when the database genuinely declares no schema tables.
167
+ * Every other failure mode (inline tables, unresolvable import, build error,
168
+ * missing exports) throws — silently skipping a database is how a typo in
169
+ * schema.ts becomes "why is my migration empty" 20 minutes later, or worse,
170
+ * a generated migration that DROPs tables that still exist in production.
171
+ *
172
+ * `projectRoot` enables alias resolution for non-relative schema imports
173
+ * (e.g. `@/databases/schema`): the project's Vite `resolve.alias` is loaded
174
+ * (cached) and used as the source of truth. Omit it to resolve relative
175
+ * imports only.
176
+ */
177
+ export declare function loadSchema(db: DatabaseInfo, projectRoot?: string): Promise<Record<string, unknown> | null>;
178
+ /**
179
+ * Diff a schema against the production snapshot in migrationsDir.
180
+ * Returns whether there are changes, the SQL statements, both snapshots and
181
+ * what the statements risk on a database with rows. `resolution` answers
182
+ * drizzle-kit's rename questions (see MigrationResolution); an unanswered
183
+ * one without a terminal throws SchemaRenameRequiredError.
184
+ */
185
+ export declare function diffSchema(schema: Record<string, unknown>, migrationsDir: string, resolution?: MigrationResolution): Promise<DiffResult>;
186
+ /** How push/generate answer drizzle-kit's rename questions (see MigrationResolution). */
187
+ interface RenameResolutionOptions {
188
+ /** `<table>.<old>=<new>` (column) / `<old>=<new>` (table) answers, or parsed ones. */
189
+ renames?: Array<string | RenameAnswer>;
190
+ /** Answer every remaining question with "create" (the vanished one is dropped). */
191
+ noRenames?: boolean;
192
+ /** Whether drizzle-kit may prompt. Default: when stdin and stdout are TTYs. */
193
+ interactive?: boolean;
194
+ }
195
+ interface DatabaseDiff {
196
+ db: DatabaseInfo;
197
+ /** null when the database declares no schema tables. */
198
+ diff: DiffResult | null;
199
+ }
200
+ /**
201
+ * Diff every database before anything is written, so a refusal (an unanswered
202
+ * rename, an unused `--rename`, an unsafe statement) leaves every file as it
203
+ * was. A rename answer applies to the database(s) where it matches; one that
204
+ * matches no pending change anywhere is an error.
205
+ */
206
+ export declare function diffDatabases(projectRoot: string, databases: DatabaseInfo[], resolution?: RenameResolutionOptions): Promise<DatabaseDiff[]>;
89
207
  //#endregion
90
208
  //#region src/cli/push.d.ts
91
- interface PushContext {
209
+ interface PushContext extends RenameResolutionOptions {
92
210
  projectRoot?: string;
93
211
  databasesDir?: string | DatabaseSource[];
94
212
  migrationsDir?: string;
95
213
  verbose?: boolean;
214
+ /** Only push this database (an unknown name throws UnknownDatabaseError). */
215
+ database?: string;
96
216
  }
97
217
  interface PushResult {
98
218
  database: string;
99
219
  hasChanges: boolean;
100
220
  statements: string[];
101
221
  migrationName: string | null;
222
+ /**
223
+ * What the pending change risks on a database that has rows — a NOT NULL
224
+ * column without a default fails the dev migration on every table with
225
+ * rows (and `db generate` refuses it), a dropped column/table loses data.
226
+ */
227
+ warnings: string[];
102
228
  }
103
229
  /**
104
230
  * Push schema changes to dev migrations
@@ -127,11 +253,17 @@ interface GenerateContext {
127
253
  migrationsDir?: string;
128
254
  verbose?: boolean;
129
255
  }
130
- interface GenerateOptions {
256
+ interface GenerateOptions extends RenameResolutionOptions {
131
257
  /** Custom migration name suffix (e.g., 'add_user_bio') */
132
258
  name?: string;
133
- /** Only generate for this database */
259
+ /** Only generate for this database (an unknown name throws UnknownDatabaseError) */
134
260
  database?: string;
261
+ /**
262
+ * Write the migration even when a statement fails on every table that has
263
+ * rows (a NOT NULL column without a default) — e.g. a table known to be
264
+ * empty in every tenant.
265
+ */
266
+ force?: boolean;
135
267
  }
136
268
  interface GenerateResult {
137
269
  database: string;
@@ -139,6 +271,27 @@ interface GenerateResult {
139
271
  statements: string[];
140
272
  migrationName: string | null;
141
273
  migrationPath: string | null;
274
+ /**
275
+ * What the migration risks on a database that has rows: dropped columns and
276
+ * tables (data loss), columns made NOT NULL, and — with `force` — the
277
+ * statements that fail on every table with rows.
278
+ */
279
+ warnings: string[];
280
+ }
281
+ /**
282
+ * `db generate` refuses a migration that fails on every table that has rows.
283
+ * Per-tenant databases migrate lazily, so the failure would surface after the
284
+ * deploy, once per tenant with data, each of them broken until a fixed
285
+ * migration ships — and `db validate` cannot catch it: it replays migrations
286
+ * on an empty database.
287
+ */
288
+ export declare class UnsafeMigrationError extends Error {
289
+ readonly risks: Array<MigrationRisk & {
290
+ database: string;
291
+ }>;
292
+ constructor(risks: Array<MigrationRisk & {
293
+ database: string;
294
+ }>);
142
295
  }
143
296
  /**
144
297
  * Generate production migrations from schema changes
@@ -166,7 +319,11 @@ interface ResetContext {
166
319
  verbose?: boolean;
167
320
  }
168
321
  interface ResetOptions {
169
- /** Only reset this database */
322
+ /**
323
+ * Only reset this database: it gets its own new dev epoch (fresh instances
324
+ * for it alone — every other database keeps its data). An unknown name
325
+ * throws UnknownDatabaseError.
326
+ */
170
327
  database?: string;
171
328
  /** Don't bump the epoch (only clear dev migrations) */
172
329
  keepEpoch?: boolean;
@@ -175,12 +332,24 @@ interface ResetOptions {
175
332
  *
176
333
  * Not needed for a fresh start — the epoch bump already rotates every
177
334
  * database to a brand-new DO instance. This only reclaims the disk space
178
- * of the orphaned instances, and requires the dev server to be stopped.
335
+ * of the orphaned instances, and refuses while a dev server runs (workerd
336
+ * keeps the deleted files open: every database request fails until it
337
+ * restarts) unless `force` is set.
179
338
  */
180
339
  purgeLocalStorage?: boolean;
340
+ /** Purge even when a dev server appears to be running. */
341
+ force?: boolean;
342
+ }
343
+ /** `--purge-local-storage` while the project's dev server runs. */
344
+ export declare class DevServerRunningError extends Error {
345
+ readonly pid: number;
346
+ constructor(pid: number);
181
347
  }
182
348
  interface ResetResult {
183
- /** New epoch value (null if keepEpoch was true) */
349
+ /**
350
+ * New epoch value (null if keepEpoch was true) — the project's, or with
351
+ * `database` that database's own.
352
+ */
184
353
  newEpoch: string | null;
185
354
  /** Databases that were reset */
186
355
  databases: string[];
@@ -219,6 +388,8 @@ interface StatusContext {
219
388
  databasesDir?: string | DatabaseSource[];
220
389
  migrationsDir?: string;
221
390
  verbose?: boolean;
391
+ /** Only report this database (an unknown name throws UnknownDatabaseError). */
392
+ database?: string;
222
393
  }
223
394
  interface DatabaseStatus {
224
395
  name: string;
@@ -232,7 +403,17 @@ interface DatabaseStatus {
232
403
  pendingStatements: string[];
233
404
  /** Whether prod snapshot changed (needs reset) */
234
405
  prodSnapshotChanged: boolean;
235
- /** Current dev epoch */
406
+ /**
407
+ * The schema changed in a way drizzle-kit cannot diff without asking
408
+ * whether a new name is a rename (status never prompts): the questions.
409
+ * `hasUncommittedChanges` is true and `pendingStatements` empty.
410
+ */
411
+ needsRenameResolution: SchemaAmbiguity[];
412
+ /** The schema changed but the pending SQL could not be computed: why. */
413
+ pendingError: string | null;
414
+ /** What the pending change risks on a database with rows (see `db generate`). */
415
+ warnings: string[];
416
+ /** This database's dev epoch (its own after `db reset --database`, else the project's) */
236
417
  epoch: string;
237
418
  /** Last push timestamp */
238
419
  lastPush: string | null;
@@ -283,6 +464,14 @@ interface ValidateResult {
283
464
  schemaDiffs: string[];
284
465
  migrationCount: number;
285
466
  includesDevMigrations: boolean;
467
+ /**
468
+ * What the schema change not yet in a migration (production snapshot →
469
+ * current schema) risks on a database that has rows: a NOT NULL column
470
+ * without a default (`db generate` refuses it), dropped columns/tables,
471
+ * names that may be renames. Warnings only — the replay runs on an empty
472
+ * database and cannot know which committed migrations already ran where.
473
+ */
474
+ pendingWarnings: string[];
286
475
  }
287
476
  /**
288
477
  * Dry-run all migrations against a local in-memory SQLite to catch errors
@@ -291,51 +480,4 @@ interface ValidateResult {
291
480
  */
292
481
  export declare function validate(ctx?: ValidateContext): Promise<ValidateResult[]>;
293
482
  //#endregion
294
- //#region src/cli/shared.d.ts
295
- /**
296
- * Print a caught error to stderr. Always shows the message; when verbose
297
- * (flag or `DEBUG=*`) is set, also prints the stack so users can diagnose
298
- * unexpected failures without patching the CLI.
299
- */
300
- export declare function reportCliError(error: unknown, verbose?: boolean): void;
301
- interface DiscoverOptions {
302
- projectRoot: string;
303
- /** A directory, or several with name prefixes — see DiscoveryOptions. */
304
- databasesDir: string | DatabaseSource[];
305
- migrationsDir: string;
306
- /** Only return databases matching this name */
307
- database?: string;
308
- }
309
- interface DiffResult {
310
- hasChanges: boolean;
311
- statements: string[];
312
- prodSnapshot: Snapshot;
313
- currentSnapshot: Snapshot;
314
- }
315
- /**
316
- * Discover database files, parse them, and resolve migrationsDir.
317
- * Returns parsed DatabaseInfo[] with migrationsDir already set.
318
- */
319
- export declare function discoverDatabases(opts: DiscoverOptions): DatabaseInfo[];
320
- /**
321
- * Load and validate schema for a database.
322
- *
323
- * Returns null only when the database genuinely declares no schema tables.
324
- * Every other failure mode (inline tables, unresolvable import, build error,
325
- * missing exports) throws — silently skipping a database is how a typo in
326
- * schema.ts becomes "why is my migration empty" 20 minutes later, or worse,
327
- * a generated migration that DROPs tables that still exist in production.
328
- *
329
- * `projectRoot` enables alias resolution for non-relative schema imports
330
- * (e.g. `@/databases/schema`): the project's Vite `resolve.alias` is loaded
331
- * (cached) and used as the source of truth. Omit it to resolve relative
332
- * imports only.
333
- */
334
- export declare function loadSchema(db: DatabaseInfo, projectRoot?: string): Promise<Record<string, unknown> | null>;
335
- /**
336
- * Diff a schema against the production snapshot in migrationsDir.
337
- * Returns whether there are changes, the SQL statements, and both snapshots.
338
- */
339
- export declare function diffSchema(schema: Record<string, unknown>, migrationsDir: string): Promise<DiffResult>;
340
- //#endregion
341
- export type { DatabaseDevState, DatabaseSource, DatabaseStatus, DbCommandDefaults, DevPaths, DevState, DiffResult, DiscoverOptions, GenerateContext, GenerateOptions, GenerateResult, PushContext, PushResult, ResetContext, ResetOptions, ResetResult, StatusContext, StatusResult, ValidateContext, ValidateError, ValidateResult };
483
+ export { type DatabaseDevState, type DatabaseDiff, type DatabaseSource, type DatabaseStatus, type DbCommandDefaults, type DevPaths, type DevServerLock, type DevState, type DiffResult, type DiscoverOptions, type GenerateContext, type GenerateOptions, type GenerateResult, type MigrationRisk, type PushContext, type PushResult, type RenameAnswer, type RenameResolutionOptions, type ResetContext, type ResetOptions, type ResetResult, type SchemaAmbiguity, SchemaRenameRequiredError, type StatusContext, type StatusResult, type ValidateContext, type ValidateError, type ValidateResult, parseRenameSpec };
package/dist/cli/index.js CHANGED
@@ -1,4 +1,5 @@
1
- import { a as getDevPaths, c as loadDevMigrations, d as saveDevState, i as getDevEpoch, l as loadDevState, o as getInstanceKey, r as generateEpoch, s as init_state } from "../state-OVuoHRC9.js";
2
- import { a as resetAndPush, c as generate, d as pushOne, f as diffSchema, h as reportCliError, i as reset, l as generateOne, m as loadSchema, n as registerDbCommands, o as formatStatus, p as discoverDatabases, r as validate, s as status, t as createDbCommand, u as push } from "../cli-BUSZTS2D.js";
1
+ import { _ as saveDevState, a as generateEpoch, c as getDevEpoch, d as init_state, f as loadDevMigrations, h as runningDevServer, l as getDevPaths, o as getDatabaseEpoch, p as loadDevState, s as getDatabaseEpochs, u as getInstanceKey } from "../state-DGYycIoJ.js";
2
+ import { g as parseRenameSpec, u as SchemaRenameRequiredError } from "../snapshot-D_z95s6E.js";
3
+ import { _ as discoverDatabases, a as reset, b as selectDatabases, c as status, d as generateOne, f as push, g as diffSchema, h as diffDatabases, i as DevServerRunningError, l as UnsafeMigrationError, m as UnknownDatabaseError, n as registerDbCommands, o as resetAndPush, p as pushOne, r as validate, s as formatStatus, t as createDbCommand, u as generate, v as loadSchema, y as reportCliError } from "../cli-CVS0b2im.js";
3
4
  init_state();
4
- export { createDbCommand, diffSchema, discoverDatabases, formatStatus, generate, generateEpoch, generateOne, getDevEpoch, getDevPaths, getInstanceKey, loadDevMigrations, loadDevState, loadSchema, push, pushOne, registerDbCommands, reportCliError, reset, resetAndPush, saveDevState, status, validate };
5
+ export { DevServerRunningError, SchemaRenameRequiredError, UnknownDatabaseError, UnsafeMigrationError, createDbCommand, diffDatabases, diffSchema, discoverDatabases, formatStatus, generate, generateEpoch, generateOne, getDatabaseEpoch, getDatabaseEpochs, getDevEpoch, getDevPaths, getInstanceKey, loadDevMigrations, loadDevState, loadSchema, parseRenameSpec, push, pushOne, registerDbCommands, reportCliError, reset, resetAndPush, runningDevServer, saveDevState, selectDatabases, status, validate };