durable-db 0.4.0 → 0.5.1

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.
package/README.md CHANGED
@@ -807,14 +807,16 @@ The plugin needs each database's Durable Object binding and a `new_sqlite_classe
807
807
  Or let the plugin write it for you: durableDb({ patchWranglerConfig: true })
808
808
  ```
809
809
 
810
- A production build fails when the config does not match, with an error naming what is missing and what is stale.
810
+ A production build fails when the config does not match, with an error naming what is missing and what is stale. A removed database's class left in the migrations is not a failure (see the tombstones below).
811
811
 
812
812
  **Opt-in (auto-patch)**: pass `durableDb({ patchWranglerConfig: true })` and the plugin reconciles the config with the discovered databases, editing the file in place: comments, formatting and line endings stay as you wrote them, only the entries it adds or removes change.
813
813
 
814
814
  - A new database gets its binding and a `new_sqlite_classes` migration.
815
- - durable-db's own bindings (`<X>_DATABASE_DO` → `<X>DatabaseDO`) whose class is no longer a discovered database are removed: workerd refuses to start with a binding to a class the worker does not export. Other bindings, and bindings with a `script_name`, are never touched.
815
+ - durable-db's own bindings (`<X>_DATABASE_DO` → `<X>DatabaseDO`) whose class is no longer a discovered database are removed. Other bindings, and bindings with a `script_name`, are never touched.
816
816
  - A database of a mounted source (a `databasesDir` entry with a `prefix`) whose class name changed — its mount changed, or it moved into a mounted source, its file name unchanged — gets a `renamed_classes` migration, so Cloudflare moves its deployed data to the new class on deploy. That data carries its `__migrations` journal, so the old migrations directory moves with it (`migrations/reviews-feedback/` → `migrations/feedback-feedback/`). If the new directory already has migrations (say `db generate` ran under the new mount first), or several directories belong to the old class, nothing is written for that database and the plugin stops with the two ways out: `rm -r` the new directory and `mv` the old one to keep the data, or add the `deleted_classes` migration to drop it. A database moved out of a mount, or two databases of the app (`product-catalog.ts` replacing `catalog.ts`), are never paired. Local dev storage is kept per class name, so in dev a renamed database starts empty.
817
- - A removed database's class is never deleted for you (that deletes its data): a warning gives the exact `deleted_classes` migration to add, or says to drop the class from its `new_sqlite_classes` entry if it was never deployed.
817
+ - A removed database's class is never deleted for you (that deletes its data): a note gives the exact `deleted_classes` migration to add, or says to drop the class from its `new_sqlite_classes` entry if it was never deployed.
818
+
819
+ **Removing a database** (or an extension that brought one): as long as the migrations declare its class live — created, or the target of a `renamed_classes`, and not deleted or renamed away since — the generated module keeps exporting a **tombstone** of that class (`RemovedDatabaseDurableObject` from `durable-db/db`). The worker still has to export every class its migrations declare: `@cloudflare/vite-plugin` wraps each one (the dev server fails with `Class extends value undefined` without it), and Cloudflare refuses a deploy that drops a class with data. The tombstone never touches its storage; `fetch` answers `410 Gone` and the stubs' calls reject with a `RemovedDatabaseError` naming the `deleted_classes` migration that deletes it. So dev starts, deploys pass and no data is lost: re-adding the database brings its data back. To delete the class and all its data for good, add that `deleted_classes` migration yourself — the tombstone goes with it. This applies with or without `patchWranglerConfig`; without it, remove the database's binding by hand (a production build fails on a stale binding).
818
820
 
819
821
  It does this in its `config` hook, before `@cloudflare/vite-plugin` reads the file (durable-db is `enforce: 'pre'`): the Cloudflare plugin builds `dist/<worker>/wrangler.json` from the config it read and restarts a dev server when the file changes later, so a later patch would ship a build without the new binding and restart the first dev start. A change is logged:
820
822
 
@@ -0,0 +1,39 @@
1
+ import { scope } from "arktype";
2
+ //#region src/arktypeConfig.ts
3
+ const type = scope({}, { jitless: true }).type;
4
+ //#endregion
5
+ //#region src/db/actionArgs.ts
6
+ /**
7
+ * ArkType's `type`, for an action's `args` schema: jitless like
8
+ * `../arktypeConfig` (eval-free for Workers), and with an optional key
9
+ * accepting `undefined`.
10
+ *
11
+ * ArkType checks an optional key as TypeScript's `exactOptionalPropertyTypes`
12
+ * would by default: `'photoKey?': 'string'` rejects `{ photoKey: undefined }`,
13
+ * while the inferred `{ photoKey?: string }` accepts it under TypeScript's
14
+ * default settings — so `addReview({ …, photoKey: maybeKey })` type-checks and
15
+ * then fails at runtime. This scope turns ArkType's
16
+ * `exactOptionalPropertyTypes` off: an optional key, at any depth, admits
17
+ * `undefined`, and a required key stays required (`'note': 'string |
18
+ * undefined'` must be present, as TypeScript says). The validator is a plain
19
+ * object Type — `.props`, `.toJsonSchema()` and `.assert()` work as usual; in
20
+ * JSON Schema the `undefined` an optional key admits is `{ not: {} }` (a JSON
21
+ * document never holds it), so `'photoKey?': 'string'` is still a string.
22
+ *
23
+ * An `args` given as a ready `type(…)` keeps the rules of the scope that made
24
+ * it.
25
+ *
26
+ * The action transform compiles `args` with this (it is the `type` that
27
+ * `durable-db/registry` exports), for the RPC stub and the Durable Object
28
+ * alike; the untransformed `action()` and the test harness use it too.
29
+ */
30
+ const actionArgsType = scope({}, {
31
+ jitless: true,
32
+ exactOptionalPropertyTypes: false,
33
+ toJsonSchema: { fallback: { unit: (ctx) => {
34
+ if (ctx.unit === void 0) return { not: {} };
35
+ throw new Error(`${String(ctx.unit)} is not convertible to JSON Schema`);
36
+ } } }
37
+ }).type;
38
+ //#endregion
39
+ export { type as n, actionArgsType as t };
@@ -1,7 +1,7 @@
1
1
  import { t as DatabaseSource } from "../discovery-gHeLq8jk.js";
2
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
3
  import { l as DatabaseInfo } from "../defineDatabase-zrUJrMd5.js";
4
- import "../index-CJ6Focq4.js";
4
+ import "../index-BvSFkwM9.js";
5
5
  import { Command } from "commander";
6
6
  //#region src/cli/command.d.ts
7
7
  /**
@@ -1,3 +1,3 @@
1
1
  import { a as ActionInfo, c as DatabaseDefinition, d as InferArgs, f as ParsedDatabaseFile, i as ActionContext, l as DatabaseInfo, n as Action, o as ArgsSchema, p as type, r as ActionConfig, s as DatabaseConfig, t as defineDatabase, u as DrizzleToKysely } from "../defineDatabase-zrUJrMd5.js";
2
- import { _ as CreateKyselyOptions, a as QueryResult, c as DrizzleDefaultsPlugin, d as dateSerializers, f as Migration, g as SqliteDurableObject, h as Migrations, i as KyselyPlugin, l as SchemaPlugin, m as MigrationSchemaConflictError, n as CompiledQuery, o as studio, p as MigrationAttemptInfo, r as Kysely, s as DateSerializePlugin, t as CamelCasePlugin, u as createDrizzlePlugins, v as SqlExecutor, y as createKyselyFromSql } from "../index-CJ6Focq4.js";
3
- export { type Action, type ActionConfig, type ActionContext, type ActionInfo, type ArgsSchema, CamelCasePlugin, type CompiledQuery, type CreateKyselyOptions, type DatabaseConfig, type DatabaseDefinition, type DatabaseInfo, DateSerializePlugin, DrizzleDefaultsPlugin, type DrizzleToKysely, type InferArgs, type Kysely, type KyselyPlugin, type Migration, type MigrationAttemptInfo, MigrationSchemaConflictError, type Migrations, type ParsedDatabaseFile, type QueryResult, SchemaPlugin, type SqlExecutor, SqliteDurableObject, createDrizzlePlugins, createKyselyFromSql, dateSerializers, defineDatabase, studio, type };
2
+ import { C as createKyselyFromSql, S as SqlExecutor, _ as MigrationAttemptInfo, a as QueryResult, b as SqliteDurableObject, c as DrizzleDefaultsPlugin, d as dateSerializers, f as DeleteClassMigration, g as Migration, h as removedDatabaseMessage, i as KyselyPlugin, l as SchemaPlugin, m as RemovedDatabaseError, n as CompiledQuery, o as studio, p as RemovedDatabaseDurableObject, r as Kysely, s as DateSerializePlugin, t as CamelCasePlugin, u as createDrizzlePlugins, v as MigrationSchemaConflictError, x as CreateKyselyOptions, y as Migrations } from "../index-BvSFkwM9.js";
3
+ export { type Action, type ActionConfig, type ActionContext, type ActionInfo, type ArgsSchema, CamelCasePlugin, type CompiledQuery, type CreateKyselyOptions, type DatabaseConfig, type DatabaseDefinition, type DatabaseInfo, DateSerializePlugin, type DeleteClassMigration, DrizzleDefaultsPlugin, type DrizzleToKysely, type InferArgs, type Kysely, type KyselyPlugin, type Migration, type MigrationAttemptInfo, MigrationSchemaConflictError, type Migrations, type ParsedDatabaseFile, type QueryResult, RemovedDatabaseDurableObject, RemovedDatabaseError, SchemaPlugin, type SqlExecutor, SqliteDurableObject, createDrizzlePlugins, createKyselyFromSql, dateSerializers, defineDatabase, removedDatabaseMessage, studio, type };
package/dist/db/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { i as init_debug, n as debugMigrations } from "../debug-Cz8KzMft.js";
2
- import { n as type } from "../actionArgs-1hEaDUia.js";
3
- import { n as defineDatabase } from "../defineDatabase-D_RpcKj1.js";
2
+ import { n as type } from "../actionArgs-C6B67Xnr.js";
3
+ import { n as defineDatabase } from "../defineDatabase-mrwCGeOt.js";
4
4
  import { a as createDrizzlePlugins, i as SchemaPlugin, n as DateSerializePlugin, o as dateSerializers, r as DrizzleDefaultsPlugin, t as createKyselyFromSql } from "../kysely-CYmmiwDm.js";
5
5
  import { DurableObject } from "cloudflare:workers";
6
6
  import { CamelCasePlugin } from "kysely";
@@ -625,4 +625,46 @@ var SqliteDurableObject = class extends DurableObject {
625
625
  }
626
626
  };
627
627
  //#endregion
628
- export { CamelCasePlugin, DateSerializePlugin, DrizzleDefaultsPlugin, MigrationSchemaConflictError, SchemaPlugin, SqliteDurableObject, createDrizzlePlugins, createKyselyFromSql, dateSerializers, defineDatabase, studio, type };
628
+ //#region src/db/RemovedDatabaseDurableObject.ts
629
+ /** What a call to a removed database's Durable Object answers. */
630
+ function removedDatabaseMessage(className, deleteMigration) {
631
+ return `${className} is the Durable Object of a removed database: no database defines it any more, but the wrangler migrations still declare it, so durable-db exports it as a tombstone that keeps its data untouched and answers no calls. Re-adding the database brings the data back. To delete the class — and ALL its data — for good, add this migration to wrangler.jsonc: ` + JSON.stringify(deleteMigration);
632
+ }
633
+ /** The error every RPC call to a removed database's Durable Object rejects with. */
634
+ var RemovedDatabaseError = class extends Error {
635
+ className;
636
+ deleteMigration;
637
+ constructor(className, deleteMigration) {
638
+ super(removedDatabaseMessage(className, deleteMigration));
639
+ this.className = className;
640
+ this.deleteMigration = deleteMigration;
641
+ this.name = "RemovedDatabaseError";
642
+ }
643
+ };
644
+ /**
645
+ * A tombstone for the class of a removed database. The worker must keep
646
+ * exporting every class its wrangler migrations declare (@cloudflare/vite-plugin
647
+ * wraps each one, and a deploy that drops a class with data fails), but only
648
+ * a `deleted_classes` migration drops one — and with it all its data, which
649
+ * durable-db never decides for the user. So the generated module exports this
650
+ * subclass under the old name until the database comes back or the user
651
+ * deletes the class: it never touches the storage, `fetch` answers 410 Gone
652
+ * and the RPC entry points of durable-db's stubs (`rpc`, `sys`) reject with a
653
+ * {@link RemovedDatabaseError} naming the migration that deletes it.
654
+ */
655
+ var RemovedDatabaseDurableObject = class extends DurableObject {
656
+ fetch(_request) {
657
+ return new Response(removedDatabaseMessage(this.removedClassName, this.deleteMigration), {
658
+ status: 410,
659
+ headers: { "content-type": "text/plain; charset=utf-8" }
660
+ });
661
+ }
662
+ async rpc(..._args) {
663
+ throw new RemovedDatabaseError(this.removedClassName, this.deleteMigration);
664
+ }
665
+ async sys(..._args) {
666
+ throw new RemovedDatabaseError(this.removedClassName, this.deleteMigration);
667
+ }
668
+ };
669
+ //#endregion
670
+ export { CamelCasePlugin, DateSerializePlugin, DrizzleDefaultsPlugin, MigrationSchemaConflictError, RemovedDatabaseDurableObject, RemovedDatabaseError, SchemaPlugin, SqliteDurableObject, createDrizzlePlugins, createKyselyFromSql, dateSerializers, defineDatabase, removedDatabaseMessage, studio, type };
@@ -1,4 +1,4 @@
1
- import { n as type, t as actionArgsType } from "./actionArgs-1hEaDUia.js";
1
+ import { n as type, t as actionArgsType } from "./actionArgs-C6B67Xnr.js";
2
2
  //#region src/db/defineDatabase.ts
3
3
  /**
4
4
  * Non-enumerable property the source `action()` stashes on the function it
@@ -315,6 +315,41 @@ declare abstract class SqliteDurableObject<Env = unknown> extends DurableObject<
315
315
  webSocketError(ws: WebSocket, _error: unknown): Promise<void>;
316
316
  }
317
317
  //#endregion
318
+ //#region src/db/RemovedDatabaseDurableObject.d.ts
319
+ /** The wrangler migration entry that deletes a class — and all its data. */
320
+ interface DeleteClassMigration {
321
+ tag: string;
322
+ deleted_classes: string[];
323
+ }
324
+ /** What a call to a removed database's Durable Object answers. */
325
+ declare function removedDatabaseMessage(className: string, deleteMigration: DeleteClassMigration): string;
326
+ /** The error every RPC call to a removed database's Durable Object rejects with. */
327
+ declare class RemovedDatabaseError extends Error {
328
+ readonly className: string;
329
+ readonly deleteMigration: DeleteClassMigration;
330
+ constructor(className: string, deleteMigration: DeleteClassMigration);
331
+ }
332
+ /**
333
+ * A tombstone for the class of a removed database. The worker must keep
334
+ * exporting every class its wrangler migrations declare (@cloudflare/vite-plugin
335
+ * wraps each one, and a deploy that drops a class with data fails), but only
336
+ * a `deleted_classes` migration drops one — and with it all its data, which
337
+ * durable-db never decides for the user. So the generated module exports this
338
+ * subclass under the old name until the database comes back or the user
339
+ * deletes the class: it never touches the storage, `fetch` answers 410 Gone
340
+ * and the RPC entry points of durable-db's stubs (`rpc`, `sys`) reject with a
341
+ * {@link RemovedDatabaseError} naming the migration that deletes it.
342
+ */
343
+ declare abstract class RemovedDatabaseDurableObject<Env = unknown> extends DurableObject<Env> {
344
+ /** The removed database's class name. */
345
+ abstract readonly removedClassName: string;
346
+ /** The `deleted_classes` migration that deletes the class for good. */
347
+ abstract readonly deleteMigration: DeleteClassMigration;
348
+ fetch(_request?: Request): Response;
349
+ rpc(..._args: unknown[]): Promise<never>;
350
+ sys(..._args: unknown[]): Promise<never>;
351
+ }
352
+ //#endregion
318
353
  //#region src/db/plugins.d.ts
319
354
  /**
320
355
  * Schema-aware CamelCasePlugin that uses Drizzle schema for column name mapping.
@@ -414,4 +449,4 @@ declare class DateSerializePlugin implements KyselyPlugin {
414
449
  */
415
450
  declare function createDrizzlePlugins(schema: Record<string, SQLiteTableWithColumns<any>>, camelCase?: boolean): KyselyPlugin[];
416
451
  //#endregion
417
- export { CreateKyselyOptions as _, QueryResult$1 as a, DrizzleDefaultsPlugin as c, dateSerializers as d, Migration as f, SqliteDurableObject as g, Migrations as h, KyselyPlugin$1 as i, SchemaPlugin as l, MigrationSchemaConflictError as m, CompiledQuery as n, studio as o, MigrationAttemptInfo as p, Kysely$1 as r, DateSerializePlugin as s, CamelCasePlugin$1 as t, createDrizzlePlugins as u, SqlExecutor as v, createKyselyFromSql as y };
452
+ export { createKyselyFromSql as C, SqlExecutor as S, MigrationAttemptInfo as _, QueryResult$1 as a, SqliteDurableObject as b, DrizzleDefaultsPlugin as c, dateSerializers as d, DeleteClassMigration as f, Migration as g, removedDatabaseMessage as h, KyselyPlugin$1 as i, SchemaPlugin as l, RemovedDatabaseError as m, CompiledQuery as n, studio as o, RemovedDatabaseDurableObject as p, Kysely$1 as r, DateSerializePlugin as s, CamelCasePlugin$1 as t, createDrizzlePlugins as u, MigrationSchemaConflictError as v, CreateKyselyOptions as x, Migrations as y };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { n as type } from "./actionArgs-1hEaDUia.js";
2
- import { n as defineDatabase } from "./defineDatabase-D_RpcKj1.js";
1
+ import { n as type } from "./actionArgs-C6B67Xnr.js";
2
+ import { n as defineDatabase } from "./defineDatabase-mrwCGeOt.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 };
package/dist/registry.js CHANGED
@@ -1,4 +1,4 @@
1
- import { n as type, t as actionArgsType } from "./actionArgs-1hEaDUia.js";
1
+ import { n as type, t as actionArgsType } from "./actionArgs-C6B67Xnr.js";
2
2
  import { WebSocketTransport } from "./transport/websocket.js";
3
3
  import { AsyncLocalStorage } from "node:async_hooks";
4
4
  //#region src/registry.ts
@@ -1,5 +1,5 @@
1
- import { n as type } from "../actionArgs-1hEaDUia.js";
2
- import { r as liveTestDatabases, t as ACTION_TEST_META } from "../defineDatabase-D_RpcKj1.js";
1
+ import { n as type } from "../actionArgs-C6B67Xnr.js";
2
+ import { r as liveTestDatabases, t as ACTION_TEST_META } from "../defineDatabase-mrwCGeOt.js";
3
3
  import { setTenantIdResolver } from "../context/index.js";
4
4
  import { t as createKyselyFromSql } from "../kysely-CYmmiwDm.js";
5
5
  import { i as generateSnapshotFromSchema, n as createEmptySnapshot, r as generateMigrationStatements } from "../snapshot-D_z95s6E.js";
@@ -1,5 +1,5 @@
1
1
  import { t as DatabaseSource } from "../discovery-gHeLq8jk.js";
2
- import "../index-CJ6Focq4.js";
2
+ import "../index-BvSFkwM9.js";
3
3
  import { Plugin } from "vite";
4
4
  //#region src/vite/modules/wrangler.d.ts
5
5
  /** A Durable Object binding as wrangler.jsonc declares it. */
@@ -47,8 +47,8 @@ interface PatchResult {
47
47
  addedBindings: DurableObjectBinding[];
48
48
  /**
49
49
  * durable-db's own bindings (`<X>_DATABASE_DO` → `<X>DatabaseDO`) removed
50
- * because their class is no longer a discovered database — the worker no
51
- * longer exports it, and workerd refuses to start with a binding to it.
50
+ * because their class is no longer a discovered database (the worker
51
+ * exports it only as a tombstone, see {@link tombstoneClasses}).
52
52
  */
53
53
  removedBindings: DurableObjectBinding[];
54
54
  /** Classes added to a `new_sqlite_classes` migration. */
@@ -72,7 +72,8 @@ interface PatchResult {
72
72
  /**
73
73
  * Classes of databases that are gone, still declared by the migrations.
74
74
  * Deleting a class deletes its data, so the `deleted_classes` migration is
75
- * never written automatically — a warning gives the exact entry to add.
75
+ * never written automatically: the worker exports a tombstone of the class
76
+ * ({@link tombstoneClasses}) and a note gives the exact entry to add.
76
77
  */
77
78
  deletedClasses: string[];
78
79
  }
@@ -125,6 +125,38 @@ function nextTag(migrations) {
125
125
  return `v${numbers.length > 0 ? Math.max(...numbers) + 1 : 1}`;
126
126
  }
127
127
  /**
128
+ * The classes of removed databases the worker must still export: of
129
+ * durable-db's naming, declared live by wrangler.jsonc's migrations (created
130
+ * or renamed to, and not deleted or renamed away since), defined by none of
131
+ * `databases`. @cloudflare/vite-plugin wraps every class the config names and
132
+ * Cloudflare refuses a deploy that drops a class with data, but only a
133
+ * `deleted_classes` migration drops one — deleting its data, which durable-db
134
+ * never decides for the user. So the generated module exports a tombstone of
135
+ * each (`RemovedDatabaseDurableObject`): storage untouched, every call
136
+ * refused. Read like the reconciliation reads the config: wrangler.jsonc/json
137
+ * only; none when there is no such file or it does not parse.
138
+ */
139
+ function tombstoneClasses(projectRoot, databases) {
140
+ const configPath = findWranglerConfig(projectRoot);
141
+ if (!configPath) return [];
142
+ let config;
143
+ try {
144
+ config = parseWranglerConfig(fs.readFileSync(configPath, "utf-8"));
145
+ } catch (error) {
146
+ debugVite("Failed to parse wrangler config for tombstones: %O", error);
147
+ return [];
148
+ }
149
+ const discovered = new Set(databases.map((db) => db.className));
150
+ const tag = nextTag(config.migrations);
151
+ return [...declaredClasses(config.migrations)].filter((className) => isDurableDbClassName(className) && !discovered.has(className)).map((className) => ({
152
+ className,
153
+ deleteMigration: {
154
+ tag,
155
+ deleted_classes: [className]
156
+ }
157
+ }));
158
+ }
159
+ /**
128
160
  * What it takes for the config to match the discovered databases: bindings to
129
161
  * add and remove, classes to create and rename, and classes of removed
130
162
  * databases that only a hand-written `deleted_classes` migration can drop.
@@ -369,14 +401,18 @@ function removeElement(text, elementPath) {
369
401
  if (commaBefore !== -1 && commaBefore < from) result = result.slice(0, commaBefore) + result.slice(commaBefore + 1);
370
402
  return result;
371
403
  }
372
- /** The warning for classes whose `deleted_classes` migration only the user may write. */
373
- function deletedClassesWarning(file, classes, tag) {
404
+ /**
405
+ * The note for classes whose `deleted_classes` migration only the user may
406
+ * write: the worker exports them as tombstones meanwhile, so nothing fails.
407
+ */
408
+ function deletedClassesNote(file, classes, tag) {
374
409
  const entry = JSON.stringify({
375
410
  tag,
376
411
  deleted_classes: classes
377
412
  });
378
413
  const list = classes.join(", ");
379
- return `[durable-db] ${file}: ${list} ${classes.length === 1 ? "is" : "are"} no longer a discovered database, but the migrations still declare ${classes.length === 1 ? "it" : "them"}. If ${classes.length === 1 ? "it was" : "they were"} deployed, Cloudflare keeps ${classes.length === 1 ? "its" : "their"} data and refuses a worker that no longer exports ${classes.length === 1 ? "the class" : "the classes"}. To delete ${classes.length === 1 ? "it" : "them"} — and ALL ${classes.length === 1 ? "its" : "their"} data — add this migration to "migrations" yourself:\n ${entry}\nIf ${classes.length === 1 ? "it was" : "they were"} never deployed, remove ${list} from ${classes.length === 1 ? "its" : "their"} new_sqlite_classes entry instead. To keep the data, restore the database.`;
414
+ const one = classes.length === 1;
415
+ return `[durable-db] note: ${file}: ${list} ${one ? "is" : "are"} no longer a discovered database, but the migrations still declare ${one ? "it" : "them"}. The worker exports ${one ? "it" : "them"} as ${one ? "a tombstone" : "tombstones"} that keep${one ? "s" : ""} ${one ? "its" : "their"} data untouched and refuse${one ? "s" : ""} every call (410 Gone), so dev starts and deploys pass; restoring the database brings the data back. To delete ${one ? "it" : "them"} — and ALL ${one ? "its" : "their"} data — add this migration to "migrations" yourself:\n ${entry}\nIf ${one ? "it was" : "they were"} never deployed, remove ${list} from ${one ? "its" : "their"} new_sqlite_classes entry instead.`;
380
416
  }
381
417
  /**
382
418
  * Patch wrangler config with Durable Object bindings
@@ -385,8 +421,8 @@ function deletedClassesWarning(file, classes, tag) {
385
421
  * place so its comments, formatting and trailing newline survive:
386
422
  * - adds a binding and a `new_sqlite_classes` migration for each new database;
387
423
  * - removes durable-db's own bindings (`<X>_DATABASE_DO` → `<X>DatabaseDO`)
388
- * whose class is no longer discovered — a binding to a class the worker no
389
- * longer exports keeps workerd from starting;
424
+ * whose class is no longer discovered (the worker exports it only as a
425
+ * tombstone);
390
426
  * - writes a `renamed_classes` migration when a database of a mounted source
391
427
  * changed its class name unambiguously (a mount change), so its deployed
392
428
  * data moves with it — and moves the old database's migrations directory
@@ -395,7 +431,8 @@ function deletedClassesWarning(file, classes, tag) {
395
431
  * directories exist, or several old ones): neither a rename nor a new class
396
432
  * is written, `conflicts` lists it and a warning gives both ways out;
397
433
  * - never deletes a class (that deletes its data): a removed database's class
398
- * gets a warning with the exact `deleted_classes` migration to add by hand.
434
+ * stays, exported as a tombstone ({@link tombstoneClasses}), and a note
435
+ * gives the exact `deleted_classes` migration to add by hand.
399
436
  * Bindings of other names, and bindings to other workers' classes
400
437
  * (`script_name`), are never touched.
401
438
  */
@@ -472,7 +509,7 @@ function patchWranglerConfig(projectRoot, databases) {
472
509
  suggested.push({ tag });
473
510
  return tag;
474
511
  };
475
- if (plan.deletedClasses.length > 0) console.warn(deletedClassesWarning(file, plan.deletedClasses, suggestTag()));
512
+ if (plan.deletedClasses.length > 0) console.warn(deletedClassesNote(file, plan.deletedClasses, suggestTag()));
476
513
  for (const conflict of plan.conflicts) console.warn(renameConflictWarning(file, projectRoot, conflict, databases, suggestTag()));
477
514
  return {
478
515
  modified,
@@ -551,9 +588,7 @@ function describeWranglerCheck(check) {
551
588
  if (check.missingBindings.length > 0) parts.push(`missing the binding(s) ${check.missingBindings.map((b) => b.name).join(", ")}`);
552
589
  if (check.missingSqliteClasses.length > 0) parts.push(`missing a migration declaring ${check.missingSqliteClasses.join(", ")}`);
553
590
  if (check.renamedClasses.length > 0) parts.push(`missing the renamed_classes migration for ${check.renamedClasses.map((r) => `${r.from} → ${r.to}`).join(", ")}`);
554
- if (check.staleBindings.length > 0) parts.push(`binding class(es) the worker no longer exports (${check.staleBindings.map((b) => b.class_name).join(", ")})`);
555
- const deleted = check.staleClasses.filter((c) => !check.renamedClasses.some((r) => r.from === c) && !check.conflicts.some((r) => r.from === c));
556
- if (deleted.length > 0) parts.push(`declaring class(es) of database(s) that no longer exist (${deleted.join(", ")})`);
591
+ if (check.staleBindings.length > 0) parts.push(`binding class(es) of database(s) that no longer exist (${check.staleBindings.map((b) => b.class_name).join(", ")})`);
557
592
  if (check.conflicts.length > 0) parts.push(`holding renamed database(s) whose migrations cannot follow (${check.conflicts.map((c) => `${c.from} → ${c.to}`).join(", ")})`);
558
593
  return parts.join("; ");
559
594
  }
@@ -599,7 +634,7 @@ function checkWranglerConfig(projectRoot, databases) {
599
634
  ...plan.conflicts.map((c) => c.from),
600
635
  ...plan.deletedClasses
601
636
  ];
602
- result.ok = result.missingBindings.length === 0 && result.missingSqliteClasses.length === 0 && result.staleBindings.length === 0 && result.staleClasses.length === 0;
637
+ result.ok = result.missingBindings.length === 0 && result.missingSqliteClasses.length === 0 && result.staleBindings.length === 0 && plan.renamedClasses.length === 0 && plan.conflicts.length === 0;
603
638
  const existingMigrations = Array.isArray(config.migrations) ? config.migrations : [];
604
639
  const migration = plan.newClasses.length > 0 || plan.renamedClasses.length > 0 ? {
605
640
  tag: nextTag(existingMigrations),
@@ -623,14 +658,14 @@ function checkWranglerConfig(projectRoot, databases) {
623
658
  const moves = result.migrationsMoves.map((move) => `mv ${shellWord(relativeDir(projectRoot, move.from))} ${shellWord(relativeDir(projectRoot, move.to))}`);
624
659
  console.warn(`[durable-db] ${where} is missing Durable Object config for your database(s). Add ${hasToml ? "the equivalent of " : ""}this${configPath || hasToml ? "" : " to a new wrangler.jsonc"}:\n${snippet}\n` + (plan.renamedClasses.length > 0 ? "renamed_classes hands each new class the old one's deployed data (the same database under a new mount)" + (moves.length > 0 ? `, and that data's __migrations journal names the old migrations — move them with it:\n` + moves.map((move) => ` ${move}`).join("\n") + "\n" : ".\n") : "") + (hasToml ? "" : `Or let the plugin write it for you: durableDb({ patchWranglerConfig: true })`));
625
660
  }
626
- if (result.staleBindings.length > 0 || plan.deletedClasses.length > 0 || plan.conflicts.length > 0) {
661
+ if (result.staleBindings.length > 0 || plan.conflicts.length > 0) {
627
662
  const lines = [];
628
- if (result.staleBindings.length > 0) lines.push(`remove the Durable Object binding(s) ${result.staleBindings.map((b) => `${b.name} (${b.class_name})`).join(", ")}: the worker no longer exports ${result.staleBindings.length === 1 ? "that class" : "those classes"}, and workerd refuses to start with a binding to it`);
663
+ if (result.staleBindings.length > 0) lines.push(`remove the Durable Object binding(s) ${result.staleBindings.map((b) => `${b.name} (${b.class_name})`).join(", ")}: no database defines ${result.staleBindings.length === 1 ? "that class" : "those classes"} any more (the worker exports ${result.staleBindings.length === 1 ? "it" : "them"} only as a tombstone)`);
629
664
  const item = (warning) => warning.replace(`[durable-db] ${file}: `, "");
630
- if (plan.deletedClasses.length > 0) lines.push(item(deletedClassesWarning(file, plan.deletedClasses, suggestTag())));
631
665
  for (const conflict of plan.conflicts) lines.push(item(renameConflictWarning(file, projectRoot, conflict, databases, suggestTag())));
632
666
  console.warn(`[durable-db] ${file} declares Durable Objects of database(s) that no longer exist:\n` + lines.map((line) => `- ${line}`).join("\n") + (plan.conflicts.length > 0 ? "" : `\nOr let the plugin reconcile the bindings for you: durableDb({ patchWranglerConfig: true })`));
633
667
  }
668
+ if (plan.deletedClasses.length > 0) console.warn(deletedClassesNote(file, plan.deletedClasses, suggestTag()));
634
669
  return result;
635
670
  }
636
671
  //#endregion
@@ -743,13 +778,22 @@ function generateWithMap(ast, sourceFileName) {
743
778
  comments: true
744
779
  });
745
780
  }
746
- function generateDurableObjectsModule(databases, registryImport, isDev = false, actionFiles = []) {
781
+ /**
782
+ * The module the worker re-exports its Durable Objects from: a class per
783
+ * database, plus a tombstone per class of a removed database the wrangler
784
+ * migrations still declare (`tombstones`, from `tombstoneClasses()`).
785
+ */
786
+ function generateDurableObjectsModule(databases, registryImport, isDev = false, actionFiles = [], tombstones = []) {
747
787
  const bindingNamesExpr = buildBindingNamesObject(databases);
748
788
  const dbTransportsExpr = buildDbTransportsObject(databases);
749
789
  const anyBrowsable = databases.some((db) => db.browsable === true || db.browsable === "development" && isDev);
750
790
  const anyWebSocket = databases.some((db) => db.transport === "websocket");
751
791
  const imports = [
752
- createNamedImport(["SqliteDurableObject", "type"], "durable-db/db"),
792
+ createNamedImport([
793
+ "SqliteDurableObject",
794
+ "type",
795
+ ...tombstones.length > 0 ? ["RemovedDatabaseDurableObject"] : []
796
+ ], "durable-db/db"),
753
797
  createNamedImport(["getAction", "runWithDoContext"], registryImport),
754
798
  ...actionFiles.map((file) => t.importDeclaration([], t.stringLiteral(file))),
755
799
  ...databases.filter(hasSchema).map(buildSchemaImport)
@@ -758,10 +802,20 @@ function generateDurableObjectsModule(databases, registryImport, isDev = false,
758
802
  if (anyWebSocket) imports.push(createNamedImport(["decodeRequest", "encodeResponse"], "durable-db/transport/protocol"));
759
803
  const statements = [...imports];
760
804
  for (const db of databases) statements.push(...buildDurableObjectStatements(db, bindingNamesExpr, dbTransportsExpr, isDev));
805
+ for (const tombstone of tombstones) statements.push(buildTombstoneStatement(tombstone));
761
806
  const program = t.program(statements);
762
807
  return generateCode(t.file(program));
763
808
  }
764
809
  /**
810
+ * `export class <Old>DatabaseDO extends RemovedDatabaseDurableObject { … }`:
811
+ * the class of a removed database, kept so the worker still exports every
812
+ * class its migrations declare — its storage untouched, every call refused.
813
+ */
814
+ function buildTombstoneStatement(tombstone) {
815
+ const classDecl = t.classDeclaration(t.identifier(tombstone.className), t.identifier("RemovedDatabaseDurableObject"), t.classBody([t.classProperty(t.identifier("removedClassName"), t.stringLiteral(tombstone.className)), t.classProperty(t.identifier("deleteMigration"), t.valueToNode(tombstone.deleteMigration))]));
816
+ return t.exportNamedDeclaration(classDecl);
817
+ }
818
+ /**
765
819
  * Build an async method that calls this.ensureMigrations() then super.<name>(...args).
766
820
  */
767
821
  function buildMigrationGuardMethod(name, params) {
@@ -1580,7 +1634,8 @@ function durableDb(options = {}) {
1580
1634
  projectRoot: state.projectRoot,
1581
1635
  databasesDir: state.options.databasesDir
1582
1636
  });
1583
- return { code: generateDurableObjectsModule(Array.from(state.databases.values()), state.options.registryImport, isDev, actionFiles) };
1637
+ const databases = Array.from(state.databases.values());
1638
+ return { code: generateDurableObjectsModule(databases, state.options.registryImport, isDev, actionFiles, tombstoneClasses(state.projectRoot, databases)) };
1584
1639
  },
1585
1640
  async transform(code, id) {
1586
1641
  if (/[\\/]drizzle-orm[\\/]/.test(id)) return {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "durable-db",
3
- "version": "0.4.0",
3
+ "version": "0.5.1",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/eagerpatch/durable-db.git"