durable-db 0.3.0 → 0.5.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 +177 -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 +3 -4
  9. package/dist/db/index.js +259 -26
  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-BvSFkwM9.d.ts} +106 -18
  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 +131 -1
  29. package/dist/vite/durableDb.js +782 -180
  30. package/package.json +3 -2
  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,12 +1,13 @@
1
1
  import { i as init_debug, r as debugVite } from "../debug-Cz8KzMft.js";
2
- import { a as getDevPaths, d as saveDevState, l as loadDevState, s as init_state } from "../state-OVuoHRC9.js";
2
+ import { _ as saveDevState, d as init_state, l as getDevPaths, m as removeDevServerLock, p as loadDevState, s as getDatabaseEpochs, y as writeDevServerLock } from "../state-DGYycIoJ.js";
3
3
  import { loadMigrationFiles } from "../migrations/generator.js";
4
- import { a as discoverDatabaseFiles, i as discoverActionFiles, n as parseDatabaseFile, o as readFile, r as databaseSources, t as BABEL_PARSER_PLUGINS } from "../parser-DR57GOjv.js";
4
+ import { a as discoverActionFiles, i as databaseSources, n as parseDatabaseFile, o as discoverDatabaseFiles, r as toPascalCase, s as readFile, t as BABEL_PARSER_PLUGINS } from "../parser-DyepmXzE.js";
5
5
  import * as fs from "node:fs";
6
6
  import path, * as path$1 from "node:path";
7
7
  import { parse } from "@babel/parser";
8
8
  import _generate from "@babel/generator";
9
9
  import * as t from "@babel/types";
10
+ import { findNodeAtLocation, parse as parse$1, parseTree, printParseErrorCode } from "jsonc-parser";
10
11
  //#region src/vite/modules/wrangler.ts
11
12
  init_debug();
12
13
  /**
@@ -20,167 +21,546 @@ function findWranglerConfig(projectRoot) {
20
21
  return null;
21
22
  }
22
23
  /**
23
- * Strip JSONC comments while respecting string literals.
24
- * Tracks whether we're inside a `"..."` so `//` and `/*` inside
25
- * strings (e.g. URLs) are preserved.
24
+ * Parse wrangler.jsonc content: comments and trailing commas allowed, as
25
+ * wrangler allows them. Throws on a syntax error.
26
26
  */
27
- function stripJsoncComments(content) {
28
- let result = "";
29
- let i = 0;
30
- const len = content.length;
31
- while (i < len) {
32
- const ch = content[i];
33
- if (ch === "\"") {
34
- result += "\"";
35
- i++;
36
- while (i < len) {
37
- const sc = content[i];
38
- result += sc;
39
- i++;
40
- if (sc === "\\") {
41
- if (i < len) {
42
- result += content[i];
43
- i++;
44
- }
45
- } else if (sc === "\"") break;
46
- }
47
- continue;
27
+ function parseWranglerConfig(content) {
28
+ const errors = [];
29
+ const config = parse$1(content, errors, {
30
+ allowTrailingComma: true,
31
+ disallowComments: false
32
+ });
33
+ if (errors.length > 0) {
34
+ const { error, offset } = errors[0];
35
+ throw new SyntaxError(`Invalid wrangler config: ${printParseErrorCode(error)} at offset ${offset}`);
36
+ }
37
+ if (config === null || typeof config !== "object" || Array.isArray(config)) throw new SyntaxError("Invalid wrangler config: the top level is not an object");
38
+ return config;
39
+ }
40
+ const CLASS_SUFFIX = "DatabaseDO";
41
+ const BINDING_SUFFIX = "_DATABASE_DO";
42
+ /**
43
+ * Whether a binding follows durable-db's naming — class `<Pascal>DatabaseDO`,
44
+ * binding `<SCREAMING_SNAKE>_DATABASE_DO` of the same database name — and
45
+ * binds a class of this worker (no `script_name`). Only these are reconciled;
46
+ * every other binding is the user's.
47
+ */
48
+ function isDurableDbBinding(binding) {
49
+ if (binding.script_name) return false;
50
+ if (!isDurableDbClassName(binding.class_name) || !binding.name.endsWith(BINDING_SUFFIX)) return false;
51
+ const classStem = binding.class_name.slice(0, -10);
52
+ const bindingStem = binding.name.slice(0, -12);
53
+ return bindingStem.length > 0 && bindingStem.replace(/_/g, "") === classStem.toUpperCase();
54
+ }
55
+ function isDurableDbClassName(className) {
56
+ return /^[A-Z][A-Za-z0-9]*DatabaseDO$/.test(className) && className.length > 10;
57
+ }
58
+ /**
59
+ * The classes the migrations declare and have not deleted, walked in order:
60
+ * created (`new_classes`, `new_sqlite_classes`, `transferred_classes`),
61
+ * renamed, deleted.
62
+ */
63
+ function declaredClasses(migrations) {
64
+ const declared = /* @__PURE__ */ new Set();
65
+ if (!Array.isArray(migrations)) return declared;
66
+ for (const migration of migrations) {
67
+ if (migration === null || typeof migration !== "object") continue;
68
+ const list = (value) => Array.isArray(value) ? value : [];
69
+ for (const c of list(migration.new_classes)) declared.add(c);
70
+ for (const c of list(migration.new_sqlite_classes)) declared.add(c);
71
+ for (const r of list(migration.renamed_classes)) {
72
+ if (r === null || typeof r !== "object") continue;
73
+ declared.delete(r.from);
74
+ declared.add(r.to);
48
75
  }
49
- if (ch === "/" && i + 1 < len && content[i + 1] === "/") {
50
- i += 2;
51
- while (i < len && content[i] !== "\n") i++;
52
- continue;
76
+ for (const t of list(migration.transferred_classes)) if (t && typeof t === "object") declared.add(t.to);
77
+ for (const c of list(migration.deleted_classes)) declared.delete(c);
78
+ }
79
+ return declared;
80
+ }
81
+ /** The database's file name without its extension: its name without a source's prefix. */
82
+ function fileStem(db) {
83
+ return path$1.basename(db.filePath).replace(/\.(ts|js)$/, "");
84
+ }
85
+ /** The class a database would have without its source's prefix (`feedback` → `FeedbackDatabaseDO`). */
86
+ function unprefixedClassName(db) {
87
+ return toPascalCase(fileStem(db)) + CLASS_SUFFIX;
88
+ }
89
+ /** Whether the database comes from a mounted source (`<prefix>-<file>`). */
90
+ function isPrefixed(db) {
91
+ return db.name !== fileStem(db);
92
+ }
93
+ /**
94
+ * The migrations directories, next to `db`'s own, of the database whose class
95
+ * is `className` — every subdirectory whose name gives that class
96
+ * (`reviews-feedback` → `ReviewsFeedbackDatabaseDO`). Exact: no name is
97
+ * guessed, and more than one match is the caller's to refuse. Empty when `db`
98
+ * has no migrations directory configured or none matches.
99
+ */
100
+ function migrationsDirsOfClass(db, className) {
101
+ if (!db.migrationsDir) return [];
102
+ const root = path$1.dirname(db.migrationsDir);
103
+ let entries;
104
+ try {
105
+ entries = fs.readdirSync(root, { withFileTypes: true });
106
+ } catch {
107
+ return [];
108
+ }
109
+ return entries.filter((entry) => entry.isDirectory() && toPascalCase(entry.name) + CLASS_SUFFIX === className).map((entry) => path$1.join(root, entry.name)).sort();
110
+ }
111
+ /** Whether `dir` exists with anything in it. */
112
+ function hasEntries(dir) {
113
+ try {
114
+ return fs.readdirSync(dir).length > 0;
115
+ } catch {
116
+ return false;
117
+ }
118
+ }
119
+ /** The next free `v<N>` tag. */
120
+ function nextTag(migrations) {
121
+ const numbers = (Array.isArray(migrations) ? migrations : []).map((m) => {
122
+ const match = /^v(\d+)$/.exec(typeof m?.tag === "string" ? m.tag : "");
123
+ return match ? parseInt(match[1], 10) : 0;
124
+ });
125
+ return `v${numbers.length > 0 ? Math.max(...numbers) + 1 : 1}`;
126
+ }
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]
53
156
  }
54
- if (ch === "/" && i + 1 < len && content[i + 1] === "*") {
55
- i += 2;
56
- while (i < len) {
57
- if (content[i] === "*" && i + 1 < len && content[i + 1] === "/") {
58
- i += 2;
59
- break;
60
- }
61
- i++;
62
- }
63
- continue;
157
+ }));
158
+ }
159
+ /**
160
+ * What it takes for the config to match the discovered databases: bindings to
161
+ * add and remove, classes to create and rename, and classes of removed
162
+ * databases that only a hand-written `deleted_classes` migration can drop.
163
+ */
164
+ function reconcile(config, databases) {
165
+ const rawBindings = Array.isArray(config.durable_objects?.bindings) ? config.durable_objects.bindings : [];
166
+ const isBinding = (b) => b !== null && typeof b === "object" && typeof b.name === "string" && typeof b.class_name === "string";
167
+ const migrations = (Array.isArray(config.migrations) ? config.migrations : []).filter((m) => m !== null && typeof m === "object");
168
+ const discoveredClasses = new Set(databases.map((db) => db.className));
169
+ const removeBindingIndexes = [];
170
+ const removedBindings = [];
171
+ rawBindings.forEach((binding, index) => {
172
+ if (isBinding(binding) && isDurableDbBinding(binding) && !discoveredClasses.has(binding.class_name)) {
173
+ removeBindingIndexes.push(index);
174
+ removedBindings.push({
175
+ name: binding.name,
176
+ class_name: binding.class_name
177
+ });
178
+ }
179
+ });
180
+ const remaining = rawBindings.filter((binding, index) => isBinding(binding) && !removeBindingIndexes.includes(index));
181
+ const addBindings = databases.filter((db) => !remaining.some((b) => b.name === db.bindingName || b.class_name === db.className)).map((db) => ({
182
+ name: db.bindingName,
183
+ class_name: db.className
184
+ }));
185
+ const declared = declaredClasses(migrations);
186
+ const boundClasses = new Set(remaining.map((b) => b.class_name));
187
+ const stale = [...declared].filter((c) => isDurableDbClassName(c) && !discoveredClasses.has(c) && !boundClasses.has(c));
188
+ const missing = databases.filter((db) => !declared.has(db.className));
189
+ const candidatesOf = (staleClass) => missing.filter((db) => isPrefixed(db) && staleClass !== db.className && staleClass.endsWith(unprefixedClassName(db)));
190
+ const renamedClasses = [];
191
+ const migrationsMoves = /* @__PURE__ */ new Map();
192
+ const conflicts = [];
193
+ for (const staleClass of stale) {
194
+ const candidates = candidatesOf(staleClass);
195
+ if (candidates.length !== 1) continue;
196
+ const [db] = candidates;
197
+ if (stale.filter((other) => candidatesOf(other).includes(db)).length !== 1) continue;
198
+ const rename = {
199
+ from: staleClass,
200
+ to: db.className
201
+ };
202
+ const oldDirs = migrationsDirsOfClass(db, staleClass);
203
+ if (oldDirs.length > 1) conflicts.push({
204
+ ...rename,
205
+ reason: `several migrations directories belong to ${staleClass}: ${oldDirs.join(", ")}`
206
+ });
207
+ else if (oldDirs.length === 1 && hasEntries(db.migrationsDir)) conflicts.push({
208
+ ...rename,
209
+ reason: `both ${oldDirs[0]} and ${db.migrationsDir} exist`
210
+ });
211
+ else {
212
+ renamedClasses.push(rename);
213
+ if (oldDirs.length === 1) migrationsMoves.set(db.className, {
214
+ from: oldDirs[0],
215
+ to: db.migrationsDir
216
+ });
217
+ }
218
+ }
219
+ const renamedTo = new Set(renamedClasses.map((r) => r.to));
220
+ const renamedFrom = new Set(renamedClasses.map((r) => r.from));
221
+ const conflictTo = new Set(conflicts.map((c) => c.to));
222
+ const conflictFrom = new Set(conflicts.map((c) => c.from));
223
+ return {
224
+ addBindings,
225
+ removeBindingIndexes,
226
+ removedBindings,
227
+ newClasses: missing.map((db) => db.className).filter((c) => !renamedTo.has(c) && !conflictTo.has(c)),
228
+ renamedClasses,
229
+ migrationsMoves,
230
+ conflicts,
231
+ deletedClasses: stale.filter((c) => !renamedFrom.has(c) && !conflictFrom.has(c))
232
+ };
233
+ }
234
+ /** `dir` relative to the project root, for messages and commands. */
235
+ function relativeDir(projectRoot, dir) {
236
+ const relative = path$1.relative(projectRoot, dir);
237
+ return relative && !relative.startsWith("..") && !path$1.isAbsolute(relative) ? relative : dir;
238
+ }
239
+ /** A path as one shell word. */
240
+ function shellWord(value) {
241
+ return /^[\w@%+=:,./-]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
242
+ }
243
+ /** The warning for a rename refused, with both ways out. */
244
+ function renameConflictWarning(file, projectRoot, conflict, databases, tag) {
245
+ const db = databases.find((d) => d.className === conflict.to);
246
+ const newDir = db?.migrationsDir ? relativeDir(projectRoot, db.migrationsDir) : null;
247
+ const oldDirs = db ? migrationsDirsOfClass(db, conflict.from).map((dir) => relativeDir(projectRoot, dir)) : [];
248
+ const reason = conflict.reason.split(projectRoot + path$1.sep).join("");
249
+ const keep = newDir && oldDirs.length === 1 ? `rm -r ${shellWord(newDir)} && mv ${shellWord(oldDirs[0])} ${shellWord(newDir)}` : `keep exactly one migrations directory for ${conflict.from} and move it to ${newDir ?? "the new database's"}`;
250
+ return `[durable-db] ${file}: ${conflict.to} looks like ${conflict.from} under a new mount, but its data cannot move with it: ${reason}. A renamed_classes migration hands the new class the old storage and its __migrations journal, which names the migrations of the old directory — deployed with other migrations it would fail. Neither a rename nor a new class is written until you choose:\n- keep the data (when ${newDir ?? "the new directory"} was never deployed): ${keep}, then restart;\n- start empty and DELETE the old data: add ${JSON.stringify({
251
+ tag,
252
+ deleted_classes: [conflict.from]
253
+ })} to "migrations"${oldDirs.length > 0 ? ` and remove ${oldDirs.join(", ")}` : ""}.`;
254
+ }
255
+ /** The log line for a rename written, with its migrations move and what dev keeps. */
256
+ function renameLog(file, projectRoot, rename, move) {
257
+ return `[durable-db] ${file}: renamed the Durable Object class ${rename.from} to ${rename.to} (a renamed_classes migration): on deploy, Cloudflare moves its deployed data to the new class` + (move ? `, and ${relativeDir(projectRoot, move.from)} moved to ${relativeDir(projectRoot, move.to)} so its migrations still match the journal that data carries.` : ` (it has no migrations directory, so there is no deployed data to carry).`) + ` Local dev storage is kept per class name: in dev the database starts empty.`;
258
+ }
259
+ function layoutOf(content) {
260
+ const eol = content.includes("\r\n") ? "\r\n" : "\n";
261
+ const indent = /^([ \t]+)["{[]/m.exec(content)?.[1];
262
+ if (indent?.startsWith(" ")) return {
263
+ unit: " ",
264
+ eol
265
+ };
266
+ return {
267
+ unit: indent ? " ".repeat(Math.min(indent.length, 8)) : " ",
268
+ eol
269
+ };
270
+ }
271
+ /** Leading whitespace of the line holding `offset`. */
272
+ function lineIndent(text, offset) {
273
+ const start = text.lastIndexOf("\n", offset - 1) + 1;
274
+ return /^[ \t]*/.exec(text.slice(start))[0];
275
+ }
276
+ /** Whether only whitespace precedes `offset` on its line. */
277
+ function startsLine(text, offset) {
278
+ const start = text.lastIndexOf("\n", offset - 1) + 1;
279
+ return /^[ \t]*$/.test(text.slice(start, offset));
280
+ }
281
+ /** The offset of the line break ending the line holding `offset` (or the end of the text). */
282
+ function lineEnd(text, offset) {
283
+ const newline = text.indexOf("\n", offset);
284
+ const end = newline === -1 ? text.length : newline;
285
+ return end > offset && text[end - 1] === "\r" ? end - 1 : end;
286
+ }
287
+ /** Whether the rest of the line from `offset` is whitespace or a line comment. */
288
+ function restOfLineIsTrivia(text, offset) {
289
+ let i = offset;
290
+ while (i < text.length && (text[i] === " " || text[i] === " " || text[i] === "\r")) i++;
291
+ return i >= text.length || text[i] === "\n" || text[i] === "/" && text[i + 1] === "/";
292
+ }
293
+ /** The offset of the next character that is not whitespace or a comment. */
294
+ function nextSignificant(text, offset) {
295
+ let i = offset;
296
+ while (i < text.length) {
297
+ const ch = text[i];
298
+ if (ch === " " || ch === " " || ch === "\r" || ch === "\n") i++;
299
+ else if (ch === "/" && text[i + 1] === "/") while (i < text.length && text[i] !== "\n") i++;
300
+ else if (ch === "/" && text[i + 1] === "*") {
301
+ const end = text.indexOf("*/", i + 2);
302
+ i = end === -1 ? text.length : end + 2;
303
+ } else break;
304
+ }
305
+ return i;
306
+ }
307
+ /** `value` as one line of JSON in hand-written style: `{ "name": "X", "class_name": "Y" }`. */
308
+ function inlineJson(value) {
309
+ if (Array.isArray(value)) return `[${value.map(inlineJson).join(", ")}]`;
310
+ if (value !== null && typeof value === "object") {
311
+ const entries = Object.entries(value).filter(([, v]) => v !== void 0);
312
+ if (entries.length === 0) return "{}";
313
+ return `{ ${entries.map(([k, v]) => `${JSON.stringify(k)}: ${inlineJson(v)}`).join(", ")} }`;
314
+ }
315
+ return JSON.stringify(value);
316
+ }
317
+ /** `value` as pretty JSON whose continuation lines start at `indent`. */
318
+ function prettyJson(value, indent, layout) {
319
+ return JSON.stringify(value, null, layout.unit).split("\n").join(layout.eol + indent);
320
+ }
321
+ function treeOf(text) {
322
+ const root = parseTree(text, [], {
323
+ allowTrailingComma: true,
324
+ disallowComments: false
325
+ });
326
+ if (!root) throw new SyntaxError("Invalid wrangler config");
327
+ return root;
328
+ }
329
+ /**
330
+ * Append an entry to the array or object at `containerPath`: on its own line
331
+ * in the file's indentation when the container spans lines, inline when it
332
+ * is written on one line. An entry with a `key` is a property of an object.
333
+ */
334
+ function appendEntry(text, containerPath, entry, layout) {
335
+ const container = findNodeAtLocation(treeOf(text), containerPath);
336
+ if (!container || container.type !== "array" && container.type !== "object") throw new Error(`Cannot append to ${containerPath.join(".")}: not an array or object`);
337
+ const keyPrefix = entry.key !== void 0 ? `${JSON.stringify(entry.key)}: ` : "";
338
+ const children = container.children ?? [];
339
+ const containerEnd = container.offset + container.length;
340
+ const closing = containerEnd - 1;
341
+ const containerIndent = lineIndent(text, container.offset);
342
+ if (children.length === 0) {
343
+ const open = text[container.offset];
344
+ let afterContainer = containerEnd;
345
+ while (text[afterContainer] === " " || text[afterContainer] === " ") afterContainer++;
346
+ if (text[afterContainer] === ",") afterContainer++;
347
+ if (!restOfLineIsTrivia(text, afterContainer)) {
348
+ const inner = open === "[" ? keyPrefix + inlineJson(entry.value) : ` ${keyPrefix}${inlineJson(entry.value)} `;
349
+ return text.slice(0, container.offset) + open + inner + text.slice(closing);
64
350
  }
65
- result += ch;
66
- i++;
351
+ const childIndent = containerIndent + layout.unit;
352
+ const inner = layout.eol + childIndent + keyPrefix + prettyJson(entry.value, childIndent, layout) + layout.eol + containerIndent;
353
+ return text.slice(0, container.offset) + open + inner + text.slice(closing);
354
+ }
355
+ const last = children[children.length - 1];
356
+ const lastEnd = last.offset + last.length;
357
+ const afterLast = nextSignificant(text, lastEnd);
358
+ const trailingComma = text[afterLast] === ",";
359
+ const separatorEnd = trailingComma ? afterLast + 1 : lastEnd;
360
+ if (!text.slice(container.offset, closing).includes("\n")) {
361
+ const inserted = (trailingComma ? " " : ", ") + keyPrefix + inlineJson(entry.value);
362
+ return text.slice(0, separatorEnd) + inserted + text.slice(separatorEnd);
363
+ }
364
+ const childIndent = startsLine(text, last.offset) ? lineIndent(text, last.offset) : containerIndent + layout.unit;
365
+ const entryText = childIndent + keyPrefix + prettyJson(entry.value, childIndent, layout) + (trailingComma ? "," : "");
366
+ const comma = trailingComma ? "" : ",";
367
+ const end = lineEnd(text, separatorEnd);
368
+ if (closing < end) return text.slice(0, lastEnd) + comma + text.slice(lastEnd, closing).replace(/[ \t]+$/, "") + layout.eol + entryText + layout.eol + containerIndent + text.slice(closing);
369
+ return text.slice(0, lastEnd) + comma + text.slice(lastEnd, end) + layout.eol + entryText + text.slice(end);
370
+ }
371
+ /**
372
+ * Remove the array element at `elementPath`, with its own lines (and a
373
+ * comment on them) when it has lines of its own, and the comma it leaves.
374
+ */
375
+ function removeElement(text, elementPath) {
376
+ const element = findNodeAtLocation(treeOf(text), elementPath);
377
+ const array = element?.parent;
378
+ if (!element || !array || array.type !== "array") throw new Error(`Cannot remove ${elementPath.join(".")}: not an array element`);
379
+ const siblings = array.children ?? [];
380
+ const index = siblings.indexOf(element);
381
+ const elementStart = element.offset;
382
+ const elementEnd = element.offset + element.length;
383
+ if (siblings.length === 1) return text.slice(0, array.offset + 1) + text.slice(array.offset + array.length - 1);
384
+ const afterElement = nextSignificant(text, elementEnd);
385
+ const ownComma = text[afterElement] === ",";
386
+ const ownLines = startsLine(text, elementStart);
387
+ let from = ownLines ? text.lastIndexOf("\n", elementStart - 1) + 1 : elementStart;
388
+ let to = ownComma ? afterElement + 1 : elementEnd;
389
+ if (ownLines && restOfLineIsTrivia(text, to)) {
390
+ const newline = text.indexOf("\n", to);
391
+ to = newline === -1 ? text.length : newline + 1;
392
+ } else if (!ownLines) while (to < text.length && (text[to] === " " || text[to] === " ")) to++;
393
+ let commaBefore = -1;
394
+ if (!ownComma && index > 0) {
395
+ const previous = siblings[index - 1];
396
+ const candidate = nextSignificant(text, previous.offset + previous.length);
397
+ if (text[candidate] === ",") commaBefore = candidate;
398
+ if (!ownLines) from = commaBefore !== -1 ? commaBefore : from;
67
399
  }
400
+ let result = text.slice(0, from) + text.slice(to);
401
+ if (commaBefore !== -1 && commaBefore < from) result = result.slice(0, commaBefore) + result.slice(commaBefore + 1);
68
402
  return result;
69
403
  }
70
404
  /**
71
- * Parse wrangler.jsonc content (strips comments)
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.
72
407
  */
73
- function parseWranglerConfig(content) {
74
- return JSON.parse(stripJsoncComments(content));
408
+ function deletedClassesNote(file, classes, tag) {
409
+ const entry = JSON.stringify({
410
+ tag,
411
+ deleted_classes: classes
412
+ });
413
+ const list = classes.join(", ");
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.`;
75
416
  }
76
417
  /**
77
418
  * Patch wrangler config with Durable Object bindings
78
419
  *
79
- * Adds any missing DO bindings and migration entries
420
+ * Reconciles the config with the discovered databases, editing the file in
421
+ * place so its comments, formatting and trailing newline survive:
422
+ * - adds a binding and a `new_sqlite_classes` migration for each new database;
423
+ * - removes durable-db's own bindings (`<X>_DATABASE_DO` → `<X>DatabaseDO`)
424
+ * whose class is no longer discovered (the worker exports it only as a
425
+ * tombstone);
426
+ * - writes a `renamed_classes` migration when a database of a mounted source
427
+ * changed its class name unambiguously (a mount change), so its deployed
428
+ * data moves with it — and moves the old database's migrations directory
429
+ * to the new name, since that data carries the old migrations' journal;
430
+ * - refuses such a rename when the migrations cannot follow (both
431
+ * directories exist, or several old ones): neither a rename nor a new class
432
+ * is written, `conflicts` lists it and a warning gives both ways out;
433
+ * - never deletes a class (that deletes its data): a removed database's class
434
+ * stays, exported as a tombstone ({@link tombstoneClasses}), and a note
435
+ * gives the exact `deleted_classes` migration to add by hand.
436
+ * Bindings of other names, and bindings to other workers' classes
437
+ * (`script_name`), are never touched.
80
438
  */
81
439
  function patchWranglerConfig(projectRoot, databases) {
82
440
  const configPath = findWranglerConfig(projectRoot);
83
441
  if (!configPath) {
84
442
  console.warn("[db] wrangler.jsonc/json not found");
85
443
  logRequiredConfig(databases);
86
- return {
87
- modified: false,
88
- configPath: null,
89
- error: null
90
- };
444
+ return unchangedPatch(null);
91
445
  }
446
+ const file = path$1.basename(configPath);
447
+ const movedMigrations = [];
92
448
  try {
93
449
  const content = fs.readFileSync(configPath, "utf-8");
94
450
  const config = parseWranglerConfig(content);
95
- let modified = false;
96
- if (!config.durable_objects) {
97
- config.durable_objects = { bindings: [] };
98
- modified = true;
99
- }
100
- if (!config.durable_objects.bindings) {
101
- config.durable_objects.bindings = [];
102
- modified = true;
103
- }
104
- for (const db of databases) if (!config.durable_objects.bindings.some((b) => b.name === db.bindingName || b.class_name === db.className)) {
105
- config.durable_objects.bindings.push({
106
- name: db.bindingName,
107
- class_name: db.className
108
- });
109
- modified = true;
451
+ const plan = reconcile(config, databases);
452
+ const layout = layoutOf(content);
453
+ let text = content;
454
+ for (const rename of [...plan.renamedClasses]) {
455
+ const move = plan.migrationsMoves.get(rename.to);
456
+ if (!move) continue;
457
+ try {
458
+ if (fs.existsSync(move.to)) fs.rmdirSync(move.to);
459
+ fs.renameSync(move.from, move.to);
460
+ movedMigrations.push(move);
461
+ } catch (error) {
462
+ plan.renamedClasses.splice(plan.renamedClasses.indexOf(rename), 1);
463
+ plan.conflicts.push({
464
+ ...rename,
465
+ reason: `${move.from} could not be moved to ${move.to} (${error.message})`
466
+ });
467
+ }
110
468
  }
111
- if (!config.migrations) {
112
- config.migrations = [];
113
- modified = true;
469
+ for (const index of [...plan.removeBindingIndexes].sort((a, b) => b - a)) text = removeElement(text, [
470
+ "durable_objects",
471
+ "bindings",
472
+ index
473
+ ]);
474
+ if (plan.addBindings.length > 0) {
475
+ const durableObjects = config.durable_objects;
476
+ if (durableObjects === void 0) text = appendEntry(text, [], {
477
+ key: "durable_objects",
478
+ value: { bindings: plan.addBindings }
479
+ }, layout);
480
+ else if (durableObjects.bindings === void 0) text = appendEntry(text, ["durable_objects"], {
481
+ key: "bindings",
482
+ value: plan.addBindings
483
+ }, layout);
484
+ else for (const binding of plan.addBindings) text = appendEntry(text, ["durable_objects", "bindings"], { value: binding }, layout);
114
485
  }
115
- const existingClasses = new Set(config.migrations.flatMap((m) => m.new_sqlite_classes ?? []));
116
- const missingClasses = databases.map((db) => db.className).filter((c) => !existingClasses.has(c));
117
- if (missingClasses.length > 0) {
118
- const existingTagNumbers = config.migrations.map((m) => {
119
- const match = m.tag.match(/^v(\d+)$/);
120
- return match ? parseInt(match[1], 10) : 0;
121
- });
122
- const nextTagNum = existingTagNumbers.length > 0 ? Math.max(...existingTagNumbers) + 1 : 1;
123
- config.migrations.push({
124
- tag: `v${nextTagNum}`,
125
- new_sqlite_classes: missingClasses
126
- });
127
- modified = true;
486
+ const migrations = Array.isArray(config.migrations) ? config.migrations : [];
487
+ const migrationTag = plan.newClasses.length > 0 || plan.renamedClasses.length > 0 ? nextTag(migrations) : null;
488
+ if (migrationTag) {
489
+ const migration = {
490
+ tag: migrationTag,
491
+ ...plan.newClasses.length > 0 && { new_sqlite_classes: plan.newClasses },
492
+ ...plan.renamedClasses.length > 0 && { renamed_classes: plan.renamedClasses }
493
+ };
494
+ text = config.migrations === void 0 ? appendEntry(text, [], {
495
+ key: "migrations",
496
+ value: [migration]
497
+ }, layout) : appendEntry(text, ["migrations"], { value: migration }, layout);
128
498
  }
499
+ const modified = text !== content;
129
500
  if (modified) {
130
- if (contentHasComments(content)) {
131
- const backupPath = configPath + ".backup";
132
- if (!fs.existsSync(backupPath)) {
133
- fs.writeFileSync(backupPath, content, "utf-8");
134
- debugVite("Original %s contained comments that will be lost during patching. Backup saved to %s", path$1.basename(configPath), path$1.basename(backupPath));
135
- }
136
- }
137
- const newContent = JSON.stringify(config, null, 2);
138
- fs.writeFileSync(configPath, newContent, "utf-8");
139
- debugVite("Updated %s with DO bindings", path$1.basename(configPath));
501
+ fs.writeFileSync(configPath, text, "utf-8");
502
+ debugVite("Updated %s with DO bindings", file);
140
503
  }
504
+ for (const rename of plan.renamedClasses) console.log(renameLog(file, projectRoot, rename, plan.migrationsMoves.get(rename.to)));
505
+ const written = migrationTag ? [{ tag: migrationTag }] : [];
506
+ const suggested = [...migrations, ...written];
507
+ const suggestTag = () => {
508
+ const tag = nextTag(suggested);
509
+ suggested.push({ tag });
510
+ return tag;
511
+ };
512
+ if (plan.deletedClasses.length > 0) console.warn(deletedClassesNote(file, plan.deletedClasses, suggestTag()));
513
+ for (const conflict of plan.conflicts) console.warn(renameConflictWarning(file, projectRoot, conflict, databases, suggestTag()));
141
514
  return {
142
515
  modified,
143
516
  configPath,
144
- error: null
517
+ error: null,
518
+ addedBindings: plan.addBindings,
519
+ removedBindings: plan.removedBindings,
520
+ newClasses: plan.newClasses,
521
+ migrationTag,
522
+ renamedClasses: plan.renamedClasses,
523
+ movedMigrations,
524
+ conflicts: plan.conflicts,
525
+ deletedClasses: plan.deletedClasses
145
526
  };
146
527
  } catch (error) {
147
528
  debugVite("Failed to patch wrangler config: %O", error);
148
529
  logRequiredConfig(databases);
149
530
  return {
150
- modified: false,
151
- configPath,
152
- error
531
+ ...unchangedPatch(configPath, error),
532
+ movedMigrations
153
533
  };
154
534
  }
155
535
  }
536
+ /** A {@link PatchResult} that changed nothing. */
537
+ function unchangedPatch(configPath, error = null) {
538
+ return {
539
+ modified: false,
540
+ configPath,
541
+ error,
542
+ addedBindings: [],
543
+ removedBindings: [],
544
+ newClasses: [],
545
+ migrationTag: null,
546
+ renamedClasses: [],
547
+ movedMigrations: [],
548
+ conflicts: [],
549
+ deletedClasses: []
550
+ };
551
+ }
156
552
  /**
157
- * Check whether a JSONC string contains comments (outside of string literals).
158
- * Used to decide whether a backup is needed before re-serializing.
553
+ * Whether the config at `configPath` binds any of durable-db's own classes
554
+ * (the bindings {@link patchWranglerConfig} reconciles). An unreadable config
555
+ * binds none.
159
556
  */
160
- function contentHasComments(content) {
161
- let i = 0;
162
- const len = content.length;
163
- while (i < len) {
164
- const ch = content[i];
165
- if (ch === "\"") {
166
- i++;
167
- while (i < len) {
168
- if (content[i] === "\\") {
169
- i += 2;
170
- continue;
171
- }
172
- if (content[i] === "\"") {
173
- i++;
174
- break;
175
- }
176
- i++;
177
- }
178
- continue;
179
- }
180
- if (ch === "/" && i + 1 < len && (content[i + 1] === "/" || content[i + 1] === "*")) return true;
181
- i++;
557
+ function bindsDurableDbClasses(configPath) {
558
+ if (!configPath) return false;
559
+ try {
560
+ return (parseWranglerConfig(fs.readFileSync(configPath, "utf-8")).durable_objects?.bindings ?? []).some(isDurableDbBinding);
561
+ } catch {
562
+ return false;
182
563
  }
183
- return false;
184
564
  }
185
565
  /**
186
566
  * Log the required wrangler config for manual setup
@@ -200,21 +580,39 @@ function logRequiredConfig(databases) {
200
580
  });
201
581
  }
202
582
  /**
583
+ * What a failed {@link checkWranglerConfig} found, in one sentence: what is
584
+ * missing and what is stale.
585
+ */
586
+ function describeWranglerCheck(check) {
587
+ const parts = [];
588
+ if (check.missingBindings.length > 0) parts.push(`missing the binding(s) ${check.missingBindings.map((b) => b.name).join(", ")}`);
589
+ if (check.missingSqliteClasses.length > 0) parts.push(`missing a migration declaring ${check.missingSqliteClasses.join(", ")}`);
590
+ if (check.renamedClasses.length > 0) parts.push(`missing the renamed_classes migration for ${check.renamedClasses.map((r) => `${r.from} → ${r.to}`).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(", ")})`);
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(", ")})`);
593
+ return parts.join("; ");
594
+ }
595
+ /**
203
596
  * Verify (without writing) that the wrangler config contains the Durable
204
597
  * Object bindings and sqlite migration entries the discovered databases
205
- * need. Logs an actionable warning with the exact JSON to add when
206
- * something is missing.
598
+ * need, and no binding or class of a database that is gone. Logs an
599
+ * actionable warning with the exact JSON to add (or remove) when something
600
+ * is off — and, for a rename, the `mv` that moves its migrations with it.
207
601
  *
208
602
  * This is the default behavior of the Vite plugin — automatic patching
209
603
  * is opt-in via the `patchWranglerConfig` plugin option.
210
604
  */
211
605
  function checkWranglerConfig(projectRoot, databases) {
212
- const required = generateRequiredConfig(databases);
213
606
  const configPath = findWranglerConfig(projectRoot);
214
607
  const result = {
215
608
  configPath,
216
609
  missingBindings: [],
217
610
  missingSqliteClasses: [],
611
+ staleBindings: [],
612
+ staleClasses: [],
613
+ renamedClasses: [],
614
+ migrationsMoves: [],
615
+ conflicts: [],
218
616
  ok: true,
219
617
  tomlOnly: !configPath && fs.existsSync(path$1.join(projectRoot, "wrangler.toml"))
220
618
  };
@@ -224,49 +622,61 @@ function checkWranglerConfig(projectRoot, databases) {
224
622
  } catch (error) {
225
623
  debugVite("Failed to parse wrangler config for check: %O", error);
226
624
  }
227
- const existingBindings = config.durable_objects?.bindings ?? [];
228
- result.missingBindings = (required.durable_objects?.bindings ?? []).filter((req) => !existingBindings.some((b) => b.name === req.name || b.class_name === req.class_name));
229
- const existingClasses = new Set((config.migrations ?? []).flatMap((m) => m.new_sqlite_classes ?? []));
230
- result.missingSqliteClasses = (required.migrations?.[0]?.new_sqlite_classes ?? []).filter((c) => !existingClasses.has(c));
231
- result.ok = result.missingBindings.length === 0 && result.missingSqliteClasses.length === 0;
232
- if (!result.ok) {
625
+ const plan = reconcile(config, databases);
626
+ result.missingBindings = plan.addBindings;
627
+ result.missingSqliteClasses = plan.newClasses;
628
+ result.staleBindings = plan.removedBindings;
629
+ result.renamedClasses = plan.renamedClasses;
630
+ result.migrationsMoves = plan.renamedClasses.flatMap((r) => plan.migrationsMoves.get(r.to) ?? []);
631
+ result.conflicts = plan.conflicts;
632
+ result.staleClasses = [
633
+ ...plan.renamedClasses.map((r) => r.from),
634
+ ...plan.conflicts.map((c) => c.from),
635
+ ...plan.deletedClasses
636
+ ];
637
+ result.ok = result.missingBindings.length === 0 && result.missingSqliteClasses.length === 0 && result.staleBindings.length === 0 && plan.renamedClasses.length === 0 && plan.conflicts.length === 0;
638
+ const existingMigrations = Array.isArray(config.migrations) ? config.migrations : [];
639
+ const migration = plan.newClasses.length > 0 || plan.renamedClasses.length > 0 ? {
640
+ tag: nextTag(existingMigrations),
641
+ ...plan.newClasses.length > 0 && { new_sqlite_classes: plan.newClasses },
642
+ ...plan.renamedClasses.length > 0 && { renamed_classes: plan.renamedClasses }
643
+ } : null;
644
+ const suggested = [...existingMigrations, ...migration ? [migration] : []];
645
+ const suggestTag = () => {
646
+ const tag = nextTag(suggested);
647
+ suggested.push({ tag });
648
+ return tag;
649
+ };
650
+ const file = configPath ? path$1.basename(configPath) : "wrangler.jsonc";
651
+ if (result.missingBindings.length > 0 || migration) {
233
652
  const snippet = JSON.stringify({
234
653
  ...result.missingBindings.length > 0 && { durable_objects: { bindings: result.missingBindings } },
235
- ...result.missingSqliteClasses.length > 0 && { migrations: [{
236
- tag: "v1",
237
- new_sqlite_classes: result.missingSqliteClasses
238
- }] }
654
+ ...migration && { migrations: [migration] }
239
655
  }, null, 2);
240
656
  const hasToml = result.tomlOnly;
241
657
  const where = configPath ? path$1.basename(configPath) : hasToml ? "wrangler.toml (not supported — only wrangler.jsonc/json can be verified or patched)" : "wrangler.jsonc";
242
- 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` + (hasToml ? "" : `Or let the plugin write it for you: durableDb({ patchWranglerConfig: true })`));
658
+ const moves = result.migrationsMoves.map((move) => `mv ${shellWord(relativeDir(projectRoot, move.from))} ${shellWord(relativeDir(projectRoot, move.to))}`);
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 })`));
243
660
  }
661
+ if (result.staleBindings.length > 0 || plan.conflicts.length > 0) {
662
+ const lines = [];
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)`);
664
+ const item = (warning) => warning.replace(`[durable-db] ${file}: `, "");
665
+ for (const conflict of plan.conflicts) lines.push(item(renameConflictWarning(file, projectRoot, conflict, databases, suggestTag())));
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 })`));
667
+ }
668
+ if (plan.deletedClasses.length > 0) console.warn(deletedClassesNote(file, plan.deletedClasses, suggestTag()));
244
669
  return result;
245
670
  }
246
- /**
247
- * Generate the required wrangler config as a string
248
- * Useful for displaying to users or tests
249
- */
250
- function generateRequiredConfig(databases) {
251
- return {
252
- durable_objects: { bindings: databases.map((db) => ({
253
- name: db.bindingName,
254
- class_name: db.className
255
- })) },
256
- migrations: [{
257
- tag: "v1",
258
- new_sqlite_classes: databases.map((db) => db.className)
259
- }]
260
- };
261
- }
262
671
  //#endregion
263
672
  //#region src/vite/modules/generator.ts
264
673
  const generate = typeof _generate === "function" ? _generate : _generate.default;
265
674
  /**
266
- * Virtual module (served by the Vite plugin) exporting `applyDevEpoch(key)`.
267
- * In dev it suffixes instance keys with the current dev epoch so `db reset`
268
- * (which bumps the epoch) yields fresh DO instances; in production builds it
269
- * is the identity function.
675
+ * Virtual module (served by the Vite plugin) exporting
676
+ * `applyDevEpoch(key, dbName)`. In dev it suffixes instance keys with the
677
+ * database's dev epoch so `db reset` (which bumps the project epoch, or with
678
+ * `--database` that database's own) yields fresh DO instances; in production
679
+ * builds it is the identity function.
270
680
  */
271
681
  const DEV_EPOCH_IMPORT = "virtual:durable-db/__devEpoch";
272
682
  const ARKTYPE_LOCAL = "__ddType";
@@ -368,13 +778,22 @@ function generateWithMap(ast, sourceFileName) {
368
778
  comments: true
369
779
  });
370
780
  }
371
- 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 = []) {
372
787
  const bindingNamesExpr = buildBindingNamesObject(databases);
373
788
  const dbTransportsExpr = buildDbTransportsObject(databases);
374
789
  const anyBrowsable = databases.some((db) => db.browsable === true || db.browsable === "development" && isDev);
375
790
  const anyWebSocket = databases.some((db) => db.transport === "websocket");
376
791
  const imports = [
377
- createNamedImport(["SqliteDurableObject", "type"], "durable-db/db"),
792
+ createNamedImport([
793
+ "SqliteDurableObject",
794
+ "type",
795
+ ...tombstones.length > 0 ? ["RemovedDatabaseDurableObject"] : []
796
+ ], "durable-db/db"),
378
797
  createNamedImport(["getAction", "runWithDoContext"], registryImport),
379
798
  ...actionFiles.map((file) => t.importDeclaration([], t.stringLiteral(file))),
380
799
  ...databases.filter(hasSchema).map(buildSchemaImport)
@@ -383,10 +802,20 @@ function generateDurableObjectsModule(databases, registryImport, isDev = false,
383
802
  if (anyWebSocket) imports.push(createNamedImport(["decodeRequest", "encodeResponse"], "durable-db/transport/protocol"));
384
803
  const statements = [...imports];
385
804
  for (const db of databases) statements.push(...buildDurableObjectStatements(db, bindingNamesExpr, dbTransportsExpr, isDev));
805
+ for (const tombstone of tombstones) statements.push(buildTombstoneStatement(tombstone));
386
806
  const program = t.program(statements);
387
807
  return generateCode(t.file(program));
388
808
  }
389
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
+ /**
390
819
  * Build an async method that calls this.ensureMigrations() then super.<name>(...args).
391
820
  */
392
821
  function buildMigrationGuardMethod(name, params) {
@@ -406,6 +835,7 @@ function buildMigrationGuardMethod(name, params) {
406
835
  * When not browsable:
407
836
  * export class ClassName extends SqliteDurableObject {
408
837
  * migrations = {...};
838
+ * databaseName = "name";
409
839
  * async rpc(...) { ... }
410
840
  * }
411
841
  */
@@ -413,7 +843,12 @@ function buildDurableObjectStatements(db, bindingNamesExpr, dbTransportsExpr, is
413
843
  const isBrowsable = db.browsable === true || db.browsable === "development" && isDev;
414
844
  const rpcMethod = buildRpcMethod(db, bindingNamesExpr, dbTransportsExpr);
415
845
  const migrationsProperty = t.classProperty(t.identifier("migrations"), buildMigrationsObject(db.migrations));
416
- const dataProperties = hasSchema(db) ? [migrationsProperty, buildSchemaProperty(db)] : [migrationsProperty];
846
+ const databaseNameProperty = t.classProperty(t.identifier("databaseName"), t.stringLiteral(db.name));
847
+ const dataProperties = hasSchema(db) ? [
848
+ migrationsProperty,
849
+ databaseNameProperty,
850
+ buildSchemaProperty(db)
851
+ ] : [migrationsProperty, databaseNameProperty];
417
852
  const classMethods = [rpcMethod, buildSysMethod()];
418
853
  if (db.transport === "websocket") classMethods.push(buildWebSocketMessageMethod(db, bindingNamesExpr, dbTransportsExpr));
419
854
  if (!isBrowsable) {
@@ -606,12 +1041,13 @@ function buildDoShortPath(config) {
606
1041
  ]))]))];
607
1042
  }
608
1043
  /**
609
- * Build `applyDevEpoch(<baseKey>)` — instance keys always pass through the
610
- * dev-epoch helper so `db reset` can rotate to fresh DO instances in dev.
1044
+ * Build `applyDevEpoch(<baseKey>, "<dbName>")` — instance keys always pass
1045
+ * through the dev-epoch helper so `db reset` can rotate to fresh DO instances
1046
+ * in dev; the database name picks its own epoch after `db reset --database`.
611
1047
  */
612
1048
  function buildInstanceKeyExpr(database) {
613
1049
  const baseKeyExpr = database.instance === "global" ? t.stringLiteral("global") : t.callExpression(t.identifier("getTenantId"), []);
614
- return t.callExpression(t.identifier("applyDevEpoch"), [baseKeyExpr]);
1050
+ return t.callExpression(t.identifier("applyDevEpoch"), [baseKeyExpr, t.stringLiteral(database.name)]);
615
1051
  }
616
1052
  function buildStubBodyStatements(config) {
617
1053
  const { action, database } = config;
@@ -765,6 +1201,102 @@ function isDefineDatabaseCallNode(node) {
765
1201
  return t.isCallExpression(node) && t.isIdentifier(node.callee) && node.callee.name === "defineDatabase";
766
1202
  }
767
1203
  //#endregion
1204
+ //#region src/vite/modules/syncWrangler.ts
1205
+ init_debug();
1206
+ /**
1207
+ * Discover the databases and reconcile wrangler.jsonc/json with them — before
1208
+ * anything reads the config. The Vite plugin runs this in its `config` hook
1209
+ * (with `patchWranglerConfig: true`), ahead of @cloudflare/vite-plugin, which
1210
+ * reads the worker config in its own `config` hook and emits the build's
1211
+ * `wrangler.json` from that copy: patched any later, a build ships the
1212
+ * previous bindings, and a dev server restarts while it starts. CLIs that want
1213
+ * the file settled before Vite starts can call it themselves; a refused rename
1214
+ * is in `conflicts` (the plugin stops on it).
1215
+ *
1216
+ * When a database file does not parse, nothing is written: the patch is
1217
+ * computed from the complete set of databases or not at all (a partial set
1218
+ * would read as databases removed). The plugin reports the parse error when
1219
+ * it loads the file. A missing config file is reported by the patcher.
1220
+ */
1221
+ function syncWranglerConfig(options) {
1222
+ const { projectRoot, databasesDir = "src/databases", migrationsDir = "migrations" } = options;
1223
+ const { databases, unparsable } = discoverDatabaseInfos(projectRoot, databasesDir, migrationsDir);
1224
+ if (unparsable.length > 0) {
1225
+ debugVite("Not syncing wrangler config: %s did not parse", unparsable.join(", "));
1226
+ return {
1227
+ ...unchangedPatch(findWranglerConfig(projectRoot)),
1228
+ databases: databases.map((db) => db.name),
1229
+ unparsable,
1230
+ changes: []
1231
+ };
1232
+ }
1233
+ return reconcileWranglerConfig(projectRoot, databases, options.log);
1234
+ }
1235
+ /**
1236
+ * {@link patchWranglerConfig} for databases already parsed, logging one line
1237
+ * when the file changed: `durable-db updated wrangler.jsonc (…)`. An app
1238
+ * without databases is left alone unless its config still binds durable-db
1239
+ * classes (a database removed: its binding goes).
1240
+ */
1241
+ function reconcileWranglerConfig(projectRoot, databases, log = (message) => console.log(message)) {
1242
+ const names = databases.map((db) => db.name);
1243
+ if (databases.length === 0) {
1244
+ const configPath = findWranglerConfig(projectRoot);
1245
+ if (!bindsDurableDbClasses(configPath)) return {
1246
+ ...unchangedPatch(configPath),
1247
+ databases: names,
1248
+ unparsable: [],
1249
+ changes: []
1250
+ };
1251
+ }
1252
+ const patch = patchWranglerConfig(projectRoot, databases);
1253
+ const changes = describePatch(patch);
1254
+ if (patch.modified && patch.configPath && log) log(`durable-db updated ${path$1.basename(patch.configPath)}` + (changes.length > 0 ? ` (${changes.join("; ")})` : ""));
1255
+ return {
1256
+ ...patch,
1257
+ databases: names,
1258
+ unparsable: [],
1259
+ changes
1260
+ };
1261
+ }
1262
+ /**
1263
+ * Parse every database file in the sources, each database with its
1264
+ * migrations directory (`<migrationsDir>/<name>`, as the plugin sets it); the
1265
+ * files that fail to parse are listed apart.
1266
+ */
1267
+ function discoverDatabaseInfos(projectRoot, databasesDir, migrationsDir = "migrations") {
1268
+ const databases = [];
1269
+ const unparsable = [];
1270
+ for (const file of discoverDatabaseFiles({
1271
+ projectRoot,
1272
+ databasesDir
1273
+ })) try {
1274
+ const parsed = parseDatabaseFile(file.absolutePath, readFile(file.absolutePath), { namePrefix: file.prefix });
1275
+ if (parsed.database) {
1276
+ parsed.database.migrationsDir = path$1.resolve(projectRoot, migrationsDir, parsed.database.name);
1277
+ databases.push(parsed.database);
1278
+ }
1279
+ } catch (error) {
1280
+ debugVite("Could not parse %s while syncing wrangler config: %O", file.relativePath, error);
1281
+ unparsable.push(file.relativePath);
1282
+ }
1283
+ return {
1284
+ databases,
1285
+ unparsable
1286
+ };
1287
+ }
1288
+ /** `Durable Objects: +AUDIT_DATABASE_DO → AuditDatabaseDO`, `migration v2: AuditDatabaseDO`. */
1289
+ function describePatch(patch) {
1290
+ const changes = [];
1291
+ const bindings = [...patch.addedBindings.map((b) => `+${b.name} → ${b.class_name}`), ...patch.removedBindings.map((b) => `-${b.name} → ${b.class_name}`)];
1292
+ if (bindings.length > 0) changes.push(`Durable Objects: ${bindings.join(", ")}`);
1293
+ if (patch.migrationTag) {
1294
+ const classes = [...patch.newClasses, ...patch.renamedClasses.map((r) => `${r.from} → ${r.to}`)];
1295
+ changes.push(`migration ${patch.migrationTag}: ${classes.join(", ")}`);
1296
+ }
1297
+ return changes;
1298
+ }
1299
+ //#endregion
768
1300
  //#region src/vite/durableDb.ts
769
1301
  init_debug();
770
1302
  init_state();
@@ -780,19 +1312,57 @@ function matchesVirtualId(id, canonicalId) {
780
1312
  }
781
1313
  /**
782
1314
  * Generate the __devEpoch virtual module. Action stubs route every DO
783
- * instance key through `applyDevEpoch()`:
784
- * - dev: suffixes keys with the current epoch (`<key>__dev_<epoch>`), so a
785
- * `db reset` epoch bump rotates every database to a fresh DO instance
1315
+ * instance key through `applyDevEpoch(key, dbName)`:
1316
+ * - dev: suffixes keys with the database's epoch (`<key>__dev_<epoch>`) — its
1317
+ * own after `db reset --database <name>`, else the project epoch — so a
1318
+ * `db reset` rotates the reset database(s) to fresh DO instances
786
1319
  * - production builds: identity function, zero overhead beyond the call
787
1320
  */
788
- function generateDevEpochModule(epoch) {
1321
+ function generateDevEpochModule(epoch, databaseEpochs = {}) {
789
1322
  return [
790
1323
  `export const devEpoch = ${JSON.stringify(epoch)};`,
791
- `export function applyDevEpoch(key) {`,
792
- ` return devEpoch ? \`\${key}__dev_\${devEpoch}\` : key;`,
1324
+ `export const devEpochs = ${JSON.stringify(epoch ? databaseEpochs : {})};`,
1325
+ `export function applyDevEpoch(key, dbName) {`,
1326
+ ` const epoch = (dbName != null && Object.prototype.hasOwnProperty.call(devEpochs, dbName) ? devEpochs[dbName] : null) ?? devEpoch;`,
1327
+ ` return epoch ? \`\${key}__dev_\${epoch}\` : key;`,
793
1328
  `}`
794
1329
  ].join("\n");
795
1330
  }
1331
+ /**
1332
+ * Cheap pre-check for `transform`: only code that defines a database
1333
+ * (`defineDatabase`, which `destroyDatabase` comes from) or imports an
1334
+ * `action` factory can be rewritten — every other module skips the Babel
1335
+ * parse, so a syntax error in an unrelated file is reported by the compiler
1336
+ * that owns it, not as a durable-db error. A superset, not analysis: the
1337
+ * parser still decides.
1338
+ *
1339
+ * The parser takes an action factory from two places: destructuring a
1340
+ * `defineDatabase()` call (DATABASE_DEFINITION), or an import specifier
1341
+ * named `action` in any import declaration (ACTION_IMPORT). The clause
1342
+ * before the braces may hold anything but the module specifier — a default
1343
+ * binding (`import main, { action }`), `type`, comments, line breaks — so
1344
+ * the gap between `import` and `{` excludes only what cannot occur in it: a
1345
+ * quote (the `from` string, or a side-effect import), `;`, `{` and `}`.
1346
+ */
1347
+ const DATABASE_DEFINITION = /\b(?:defineDatabase|destroyDatabase)\b/;
1348
+ const ACTION_IMPORT = /\bimport\b[^;'"`{}]*\{[^}]*\baction\b[^}]*\}/;
1349
+ function mayDefineDatabaseCode(code) {
1350
+ return DATABASE_DEFINITION.test(code) || ACTION_IMPORT.test(code);
1351
+ }
1352
+ /** Identifies a set of databases, for {@link PluginState.wranglerReconciledFor}. */
1353
+ function wranglerKey(databaseNames) {
1354
+ return [...databaseNames].sort().join("\n");
1355
+ }
1356
+ /**
1357
+ * A refused rename leaves the database's class undeclared: deployed, its data
1358
+ * would be stranded or meet migrations its journal does not know; in dev the
1359
+ * class would not get SQLite storage. Stop until the user chooses (the
1360
+ * patcher's warning gives both ways out).
1361
+ */
1362
+ function stopOnRenameConflicts(conflicts) {
1363
+ if (conflicts.length === 0) return;
1364
+ throw new Error(`[durable-db] ${conflicts.map((c) => `${c.from} → ${c.to}`).join(", ")}: a renamed database's migrations cannot move with its data (${conflicts.map((c) => c.reason).join("; ")}). Keep the data or delete it as the warning above says, then restart.`);
1365
+ }
796
1366
  var PluginState = class {
797
1367
  options;
798
1368
  databases = /* @__PURE__ */ new Map();
@@ -800,6 +1370,13 @@ var PluginState = class {
800
1370
  databaseFilePaths = /* @__PURE__ */ new Map();
801
1371
  initialized = false;
802
1372
  initPromise = null;
1373
+ /**
1374
+ * The databases wrangler.jsonc was last reconciled with (sorted names), so
1375
+ * an initialization reconciles only when they changed — the `config` hook
1376
+ * has already settled the file for the databases on disk at startup.
1377
+ * Survives `reset()`.
1378
+ */
1379
+ wranglerReconciledFor = null;
803
1380
  projectRoot = "";
804
1381
  config;
805
1382
  devServer = null;
@@ -879,18 +1456,21 @@ var PluginState = class {
879
1456
  parsed.database.migrationsDir = path$1.resolve(this.projectRoot, this.options.migrationsDir, parsed.database.name);
880
1457
  this.databases.set(parsed.database.name, parsed.database);
881
1458
  this.registerDatabaseFile(file.absolutePath, parsed.database.name);
882
- await this.loadMigrations(parsed.database);
883
1459
  }
884
1460
  }
885
- if (this.databases.size > 0) {
886
- debugVite("Found %d database(s)", this.databases.size);
887
- const databases = Array.from(this.databases.values());
888
- if (this.options.patchWranglerConfig) patchWranglerConfig(this.projectRoot, databases);
889
- else {
890
- const check = checkWranglerConfig(this.projectRoot, databases);
891
- if (!check.ok && !check.tomlOnly && this.config.command === "build") throw new Error(`[durable-db] wrangler config is missing Durable Object bindings/migrations for discovered database(s) — deploying this build would ship a worker without them. Add the JSON from the warning above to ${check.configPath ? path$1.basename(check.configPath) : "wrangler.jsonc"}, or opt in to automatic patching with durableDb({ patchWranglerConfig: true }).`);
1461
+ const databases = Array.from(this.databases.values());
1462
+ debugVite("Found %d database(s)", databases.length);
1463
+ if (this.options.patchWranglerConfig) {
1464
+ const reconciledFor = wranglerKey(databases.map((db) => db.name));
1465
+ if (reconciledFor !== this.wranglerReconciledFor) {
1466
+ stopOnRenameConflicts(reconcileWranglerConfig(this.projectRoot, databases).conflicts);
1467
+ this.wranglerReconciledFor = reconciledFor;
892
1468
  }
1469
+ } else if (databases.length > 0) {
1470
+ const check = checkWranglerConfig(this.projectRoot, databases);
1471
+ if (!check.ok && !check.tomlOnly && this.config.command === "build") throw new Error(`[durable-db] ${check.configPath ? path$1.basename(check.configPath) : "wrangler.jsonc"} does not match the discovered database(s): it is ${describeWranglerCheck(check)}. Deploying this build would ship a worker whose Durable Objects do not match it. Make the changes the warning above gives, or opt in to automatic patching with durableDb({ patchWranglerConfig: true }).`);
893
1472
  }
1473
+ for (const database of this.databases.values()) await this.loadMigrations(database);
894
1474
  this.initialized = true;
895
1475
  }
896
1476
  async loadMigrations(db) {
@@ -898,7 +1478,7 @@ var PluginState = class {
898
1478
  const isDev = this.config.command === "serve";
899
1479
  db.migrations = loadMigrationFiles(migrationsDir);
900
1480
  if (isDev) try {
901
- const { loadDevMigrations } = await import("../state-OVuoHRC9.js").then((n) => (n.s(), n.f));
1481
+ const { loadDevMigrations } = await import("../state-DGYycIoJ.js").then((n) => (n.d(), n.v));
902
1482
  const devMigrations = loadDevMigrations(this.projectRoot, db.name);
903
1483
  for (const [name, chunks] of devMigrations) db.migrations.set(`_dev_${name}`, chunks);
904
1484
  if (devMigrations.size > 0) debugVite("Loaded %d dev migration(s) for %s", devMigrations.size, db.name);
@@ -967,6 +1547,16 @@ function durableDb(options = {}) {
967
1547
  return {
968
1548
  name: "durable-db",
969
1549
  enforce: "pre",
1550
+ config(userConfig) {
1551
+ if (!state.options.patchWranglerConfig) return;
1552
+ const sync = syncWranglerConfig({
1553
+ projectRoot: path$1.resolve(userConfig.root ?? process.cwd()),
1554
+ databasesDir: state.options.databasesDir,
1555
+ migrationsDir: state.options.migrationsDir
1556
+ });
1557
+ stopOnRenameConflicts(sync.conflicts);
1558
+ if (sync.unparsable.length === 0) state.wranglerReconciledFor = wranglerKey(sync.databases);
1559
+ },
970
1560
  configResolved(config) {
971
1561
  state.config = config;
972
1562
  state.projectRoot = config.root;
@@ -974,6 +1564,12 @@ function durableDb(options = {}) {
974
1564
  configureServer(server) {
975
1565
  state.devServer = server;
976
1566
  state.reset();
1567
+ try {
1568
+ const lockToken = writeDevServerLock(state.projectRoot);
1569
+ server.httpServer?.once("close", () => removeDevServerLock(state.projectRoot, lockToken));
1570
+ } catch (error) {
1571
+ debugVite("Could not write the dev-server lock: %O", error);
1572
+ }
977
1573
  const absoluteDbDirs = databaseSources(state.options.databasesDir).map((source) => path$1.resolve(state.projectRoot, source.dir));
978
1574
  server.watcher.on("change", (file) => {
979
1575
  const normalized = path$1.normalize(file);
@@ -982,7 +1578,9 @@ function durableDb(options = {}) {
982
1578
  const devPaths = getDevPaths(state.projectRoot);
983
1579
  fs.mkdirSync(devPaths.cacheDir, { recursive: true });
984
1580
  let reloadTimer = null;
985
- const onDevStateChange = () => {
1581
+ const cacheDirName = path$1.basename(devPaths.cacheDir);
1582
+ const onDevStateChange = (_event, filename) => {
1583
+ if (typeof filename === "string" && (path$1.basename(filename) === "dev-server.json" || filename === cacheDirName)) return;
986
1584
  if (state.isWithinSelfDevStateWriteWindow()) {
987
1585
  debugVite("Ignoring dev cache event caused by the plugin itself");
988
1586
  return;
@@ -1017,6 +1615,7 @@ function durableDb(options = {}) {
1017
1615
  if (id === VIRTUAL_DEV_EPOCH_MODULE_ID) {
1018
1616
  const isDev = state.config.command === "serve";
1019
1617
  let epoch = null;
1618
+ let databaseEpochs = {};
1020
1619
  if (isDev) {
1021
1620
  const devState = loadDevState(state.projectRoot);
1022
1621
  if (!fs.existsSync(getDevPaths(state.projectRoot).stateFile)) {
@@ -1024,8 +1623,9 @@ function durableDb(options = {}) {
1024
1623
  saveDevState(state.projectRoot, devState);
1025
1624
  }
1026
1625
  epoch = devState.epoch;
1626
+ databaseEpochs = getDatabaseEpochs(devState);
1027
1627
  }
1028
- return { code: generateDevEpochModule(epoch) };
1628
+ return { code: generateDevEpochModule(epoch, databaseEpochs) };
1029
1629
  }
1030
1630
  if (id !== VIRTUAL_DO_MODULE_ID) return null;
1031
1631
  await state.initialize();
@@ -1034,7 +1634,8 @@ function durableDb(options = {}) {
1034
1634
  projectRoot: state.projectRoot,
1035
1635
  databasesDir: state.options.databasesDir
1036
1636
  });
1037
- 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)) };
1038
1639
  },
1039
1640
  async transform(code, id) {
1040
1641
  if (/[\\/]drizzle-orm[\\/]/.test(id)) return {
@@ -1044,6 +1645,7 @@ function durableDb(options = {}) {
1044
1645
  };
1045
1646
  if (id.startsWith("\0") || id.includes("node_modules")) return null;
1046
1647
  if (!/\.tsx?$/.test(id)) return null;
1648
+ if (!mayDefineDatabaseCode(code)) return null;
1047
1649
  await state.initialize();
1048
1650
  const cleanId = path$1.normalize(id.split("?", 1)[0]);
1049
1651
  const dbNameForPath = state.getDatabaseNameForPath(cleanId);
@@ -1096,4 +1698,4 @@ function durableDb(options = {}) {
1096
1698
  /** @deprecated Renamed to {@link durableDb}. */
1097
1699
  const databasePlugin = durableDb;
1098
1700
  //#endregion
1099
- export { databasePlugin, durableDb as default, durableDb };
1701
+ export { databasePlugin, durableDb as default, durableDb, syncWranglerConfig };