durable-db 0.0.1 → 0.0.3
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 +22 -2
- package/dist/cli/index.d.ts +1 -1
- package/dist/db/index.d.ts +2 -2
- package/dist/db/index.js +50 -9
- package/dist/{index-BFM5d0FP.d.ts → index-CU9edk9Q.d.ts} +22 -1
- package/dist/vite/durableDb.d.ts +7 -0
- package/dist/vite/durableDb.js +96 -4
- package/package.json +9 -10
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
Zero-configuration database abstraction for Cloudflare Durable Objects with SQLite.
|
|
4
4
|
|
|
5
|
-
Define your schema with [Drizzle](https://orm.drizzle.team/), query with [Kysely](https://kysely.dev/), validate with [ArkType](https://arktype.io/) -- and let the Vite plugin handle the rest: Durable Object class generation, RPC stubs, migration embedding, and wrangler config patching.
|
|
5
|
+
Define your schema with [Drizzle](https://orm.drizzle.team/), query with [Kysely](https://kysely.dev/), validate with [ArkType](https://arktype.io/) -- and let the Vite plugin handle the rest: Durable Object class generation, RPC stubs, migration embedding, and wrangler config verification (with opt-in auto-patching).
|
|
6
6
|
|
|
7
7
|
## Table of Contents
|
|
8
8
|
|
|
@@ -693,6 +693,7 @@ durableDb({
|
|
|
693
693
|
| `migrationsDir` | `string` | `'migrations'` | Directory for production migrations, relative to project root. Each database gets a subdirectory (e.g. `migrations/main/`) |
|
|
694
694
|
| `contextImport` | `string` | `'durable-db/context'` | Import path for the context module (for framework integrations) |
|
|
695
695
|
| `registryImport` | `string` | `'durable-db/registry'` | Import path for the action registry module (for framework integrations) |
|
|
696
|
+
| `patchWranglerConfig` | `boolean` | `false` | Write missing DO bindings and sqlite migration entries to `wrangler.jsonc` automatically. Off by default — the plugin only verifies the config and logs the exact JSON to add. Only `wrangler.jsonc`/`wrangler.json` are supported (not `wrangler.toml`) |
|
|
696
697
|
|
|
697
698
|
### What the plugin does
|
|
698
699
|
|
|
@@ -701,9 +702,28 @@ durableDb({
|
|
|
701
702
|
3. **Migration Loading**: Loads production migrations from disk; in dev mode also loads dev migrations from cache
|
|
702
703
|
4. **Code Generation**: Produces a virtual module (`virtual:durable-db/__durableObjects`) containing Durable Object classes with embedded migrations and RPC dispatch methods, plus a `virtual:durable-db/__devEpoch` module that suffixes DO instance keys with the dev epoch (identity in production builds)
|
|
703
704
|
5. **Action Transform**: Replaces `action()` call-sites with RPC stubs + `registerAction()` calls so actions can be called like regular functions from your worker. This applies to actions in separate files *and* actions defined in the database file itself
|
|
704
|
-
6. **Wrangler
|
|
705
|
+
6. **Wrangler Verification**: Checks that `wrangler.jsonc` contains the required Durable Object bindings and SQLite migration entries, and logs the exact JSON to add when something is missing. With `patchWranglerConfig: true`, writes them for you instead
|
|
705
706
|
7. **HMR**: Watches database files and invalidates the virtual module on change
|
|
706
707
|
|
|
708
|
+
### Wrangler config: verify vs. patch
|
|
709
|
+
|
|
710
|
+
The plugin needs each database's Durable Object binding and a `new_sqlite_classes` migration entry in your wrangler config.
|
|
711
|
+
|
|
712
|
+
**Default (verify-only)**: your config is never modified. On startup the plugin checks for missing entries and logs the exact JSON to add, e.g.:
|
|
713
|
+
|
|
714
|
+
```
|
|
715
|
+
[durable-db] wrangler.jsonc is missing Durable Object config for your database(s). Add this:
|
|
716
|
+
{
|
|
717
|
+
"durable_objects": { "bindings": [{ "name": "MAIN_DATABASE_DO", "class_name": "MainDatabaseDO" }] },
|
|
718
|
+
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["MainDatabaseDO"] }]
|
|
719
|
+
}
|
|
720
|
+
Or let the plugin write it for you: durableDb({ patchWranglerConfig: true })
|
|
721
|
+
```
|
|
722
|
+
|
|
723
|
+
**Opt-in (auto-patch)**: pass `durableDb({ patchWranglerConfig: true })` and the plugin writes the missing entries for you. If your `wrangler.jsonc` contains comments, the original is backed up to `wrangler.jsonc.backup` first (re-serializing strips comments).
|
|
724
|
+
|
|
725
|
+
> ⚠️ Only `wrangler.jsonc` / `wrangler.json` are supported. If your project uses `wrangler.toml`, the plugin can't verify or patch it — it will print the required config and you add the TOML equivalent yourself.
|
|
726
|
+
|
|
707
727
|
### Generated Class Naming
|
|
708
728
|
|
|
709
729
|
For each `defineDatabase()` call, the plugin generates a class based on the filename:
|
package/dist/cli/index.d.ts
CHANGED
package/dist/db/index.d.ts
CHANGED
|
@@ -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, r as ActionConfig, s as DatabaseConfig, t as defineDatabase, u as DrizzleToKysely } from "../defineDatabase-jBv90-Pk.js";
|
|
2
|
-
import { _ as
|
|
3
|
-
export { Action, ActionConfig, ActionContext, ActionInfo, ArgsSchema, CamelCasePlugin, CompiledQuery, CreateKyselyOptions, DatabaseConfig, DatabaseDefinition, DatabaseInfo, DateSerializePlugin, DrizzleDefaultsPlugin, DrizzleToKysely, InferArgs, Kysely, KyselyPlugin, Migration, MigrationAttemptInfo, Migrations, ParsedDatabaseFile, QueryResult, SchemaPlugin, SqlExecutor, SqliteDurableObject, createDrizzlePlugins, createKyselyFromSql, dateSerializers, defineDatabase, studio, type };
|
|
2
|
+
import { _ as Migrations, a as QueryResult, b as createKyselyFromSql, c as DateSerializePlugin, d as createDrizzlePlugins, f as dateSerializers, g as MigrationSchemaConflictError, h as MigrationAttemptInfo, i as KyselyPlugin, l as DrizzleDefaultsPlugin, m as Migration, n as CompiledQuery, o as studio, p as CreateKyselyOptions, r as Kysely, s as type, t as CamelCasePlugin, u as SchemaPlugin, v as SqlExecutor, y as SqliteDurableObject } from "../index-CU9edk9Q.js";
|
|
3
|
+
export { Action, ActionConfig, ActionContext, ActionInfo, ArgsSchema, CamelCasePlugin, CompiledQuery, CreateKyselyOptions, DatabaseConfig, DatabaseDefinition, DatabaseInfo, DateSerializePlugin, DrizzleDefaultsPlugin, DrizzleToKysely, InferArgs, Kysely, KyselyPlugin, Migration, MigrationAttemptInfo, MigrationSchemaConflictError, Migrations, ParsedDatabaseFile, QueryResult, SchemaPlugin, SqlExecutor, SqliteDurableObject, createDrizzlePlugins, createKyselyFromSql, dateSerializers, defineDatabase, studio, type };
|
package/dist/db/index.js
CHANGED
|
@@ -394,6 +394,21 @@ function createKyselyFromSql(sqlStorage, options = {}) {
|
|
|
394
394
|
*/
|
|
395
395
|
const MAX_PITR_ATTEMPTS = 3;
|
|
396
396
|
/**
|
|
397
|
+
* Raised when a pending migration fails with "already exists": the storage
|
|
398
|
+
* holds schema objects the `__migrations` journal doesn't track. Common
|
|
399
|
+
* causes: migration files were renamed or regenerated after the storage was
|
|
400
|
+
* created, the storage was written by an older version of the database, or a
|
|
401
|
+
* previous attempt crashed partway through a chunk without PITR. Re-running
|
|
402
|
+
* can never succeed, so this carries recovery guidance instead of the raw
|
|
403
|
+
* SQLITE_ERROR.
|
|
404
|
+
*/
|
|
405
|
+
var MigrationSchemaConflictError = class extends Error {
|
|
406
|
+
constructor(message, options) {
|
|
407
|
+
super(message, options);
|
|
408
|
+
this.name = "MigrationSchemaConflictError";
|
|
409
|
+
}
|
|
410
|
+
};
|
|
411
|
+
/**
|
|
397
412
|
* Truncate a SQL statement for logging. Collapses whitespace so multi-line
|
|
398
413
|
* statements render on one log line.
|
|
399
414
|
*/
|
|
@@ -573,17 +588,24 @@ var SqliteDurableObject = class extends DurableObject {
|
|
|
573
588
|
this.sql.exec(`
|
|
574
589
|
UPDATE __migration_attempts SET last_error = ? WHERE id = 'current'
|
|
575
590
|
`, errorMessage);
|
|
576
|
-
|
|
577
|
-
const remaining = Math.max(0, MAX_PITR_ATTEMPTS + 1 - attempts.attemptCount);
|
|
578
|
-
const pendingNames = Array.from(new Set(pending.map((p) => p.name))).join(", ");
|
|
579
|
-
console.error(`[database] Migration failed (attempt ${attempts.attemptCount}/${MAX_PITR_ATTEMPTS + 1}, ${remaining} PITR-protected retries remaining). Restoring to pre-migration bookmark. Pending: ${pendingNames || "(none)"}.`, error);
|
|
591
|
+
let restoreScheduled = false;
|
|
580
592
|
try {
|
|
581
593
|
await this.ctx.storage.onNextSessionRestoreBookmark(bookmark);
|
|
582
|
-
|
|
594
|
+
restoreScheduled = true;
|
|
583
595
|
} catch (pitrErr) {
|
|
584
596
|
const pitrMessage = pitrErr instanceof Error ? pitrErr.message : String(pitrErr);
|
|
585
|
-
if (
|
|
586
|
-
|
|
597
|
+
if (/does not (?:implement|support) point-in-time recovery/i.test(pitrMessage)) {
|
|
598
|
+
this.pitrAvailable = false;
|
|
599
|
+
this.pitrUnavailableReason = pitrMessage;
|
|
600
|
+
debugMigrations("PITR restore unsupported by this storage backend; disabling PITR (%s)", pitrMessage);
|
|
601
|
+
} else console.error(`[database] PITR restore failed (${pitrMessage}). Propagating the original migration error instead so you can fix the root cause.`);
|
|
602
|
+
}
|
|
603
|
+
if (restoreScheduled) {
|
|
604
|
+
const attempts = this.getMigrationAttempts();
|
|
605
|
+
const remaining = Math.max(0, MAX_PITR_ATTEMPTS + 1 - attempts.attemptCount);
|
|
606
|
+
const pendingNames = Array.from(new Set(pending.map((p) => p.name))).join(", ");
|
|
607
|
+
console.error(`[database] Migration failed (attempt ${attempts.attemptCount}/${MAX_PITR_ATTEMPTS + 1}, ${remaining} PITR-protected retries remaining). Restoring to pre-migration bookmark. Pending: ${pendingNames || "(none)"}.`, error);
|
|
608
|
+
this.ctx.abort("Restoring to pre-migration bookmark");
|
|
587
609
|
}
|
|
588
610
|
}
|
|
589
611
|
throw error;
|
|
@@ -634,11 +656,30 @@ var SqliteDurableObject = class extends DurableObject {
|
|
|
634
656
|
} catch (error) {
|
|
635
657
|
const location = currentStatement !== null ? ` stmt ${currentIndex}: ${formatStatementForLog(currentStatement)}` : " (while recording chunk as applied)";
|
|
636
658
|
console.error(`[database] Migration chunk failed: ${name}[${chunkIndex}]${location}`, error);
|
|
637
|
-
throw error;
|
|
659
|
+
throw this.toSchemaConflictError(error, name, chunkIndex) ?? error;
|
|
638
660
|
}
|
|
639
661
|
}
|
|
640
662
|
}
|
|
641
663
|
/**
|
|
664
|
+
* Translate an "already exists" failure on a pending migration into a
|
|
665
|
+
* {@link MigrationSchemaConflictError}. A chunk is only executed when the
|
|
666
|
+
* journal has no row for it, so "already exists" means storage and journal
|
|
667
|
+
* disagree about what has been applied — retrying can never succeed, and
|
|
668
|
+
* the raw SQLITE_ERROR doesn't tell the user how to get unstuck.
|
|
669
|
+
* Returns null when the error isn't this case.
|
|
670
|
+
*/
|
|
671
|
+
toSchemaConflictError(error, name, chunkIndex) {
|
|
672
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
673
|
+
if (!/already exists/i.test(message)) return null;
|
|
674
|
+
let journalNames = [];
|
|
675
|
+
try {
|
|
676
|
+
journalNames = this.sql.exec("SELECT DISTINCT name FROM __migrations").toArray().map((row) => row.name);
|
|
677
|
+
} catch {}
|
|
678
|
+
const known = new Set(Object.keys(this.migrations));
|
|
679
|
+
const untracked = journalNames.filter((n) => !known.has(n));
|
|
680
|
+
return new MigrationSchemaConflictError(`Migration "${name}" (chunk ${chunkIndex}) tried to create a schema object that already exists in storage, but the __migrations journal has no record of this migration being applied. ${untracked.length > 0 ? `The journal records migrations this build doesn't know about (${untracked.join(", ")}), which usually means the migration files were renamed or regenerated after this database's storage was created.` : "This usually means the storage was created by migrations under different names (renamed or regenerated migration files), by an older version of this database, or that a previous attempt crashed partway through a chunk."} To recover in local dev, run \`db reset\` to rotate to a fresh database (add --purge-local-storage to also delete the orphaned instance data, or wipe .wrangler/state yourself). In production, restore the original migration names, or baseline the journal by inserting rows into __migrations for the migrations whose schema is already present. Original error: ${message}`, { cause: error });
|
|
681
|
+
}
|
|
682
|
+
/**
|
|
642
683
|
* Manually restore the DO to a specific PITR bookmark.
|
|
643
684
|
* The DO will restart on next access with the restored state.
|
|
644
685
|
*/
|
|
@@ -757,4 +798,4 @@ var SqliteDurableObject = class extends DurableObject {
|
|
|
757
798
|
};
|
|
758
799
|
|
|
759
800
|
//#endregion
|
|
760
|
-
export { CamelCasePlugin, DateSerializePlugin, DrizzleDefaultsPlugin, SchemaPlugin, SqliteDurableObject, createDrizzlePlugins, createKyselyFromSql, dateSerializers, defineDatabase, studio, type };
|
|
801
|
+
export { CamelCasePlugin, DateSerializePlugin, DrizzleDefaultsPlugin, MigrationSchemaConflictError, SchemaPlugin, SqliteDurableObject, createDrizzlePlugins, createKyselyFromSql, dateSerializers, defineDatabase, studio, type };
|
|
@@ -78,6 +78,18 @@ interface MigrationStatus {
|
|
|
78
78
|
*/
|
|
79
79
|
pitrAttemptsRemaining: number;
|
|
80
80
|
}
|
|
81
|
+
/**
|
|
82
|
+
* Raised when a pending migration fails with "already exists": the storage
|
|
83
|
+
* holds schema objects the `__migrations` journal doesn't track. Common
|
|
84
|
+
* causes: migration files were renamed or regenerated after the storage was
|
|
85
|
+
* created, the storage was written by an older version of the database, or a
|
|
86
|
+
* previous attempt crashed partway through a chunk without PITR. Re-running
|
|
87
|
+
* can never succeed, so this carries recovery guidance instead of the raw
|
|
88
|
+
* SQLITE_ERROR.
|
|
89
|
+
*/
|
|
90
|
+
declare class MigrationSchemaConflictError extends Error {
|
|
91
|
+
constructor(message: string, options?: ErrorOptions);
|
|
92
|
+
}
|
|
81
93
|
/**
|
|
82
94
|
* Base class for SQLite Durable Objects with migration support
|
|
83
95
|
*
|
|
@@ -179,6 +191,15 @@ declare abstract class SqliteDurableObject<Env = unknown> extends DurableObject<
|
|
|
179
191
|
* Apply a list of pending migration chunks.
|
|
180
192
|
*/
|
|
181
193
|
private applyMigrations;
|
|
194
|
+
/**
|
|
195
|
+
* Translate an "already exists" failure on a pending migration into a
|
|
196
|
+
* {@link MigrationSchemaConflictError}. A chunk is only executed when the
|
|
197
|
+
* journal has no row for it, so "already exists" means storage and journal
|
|
198
|
+
* disagree about what has been applied — retrying can never succeed, and
|
|
199
|
+
* the raw SQLITE_ERROR doesn't tell the user how to get unstuck.
|
|
200
|
+
* Returns null when the error isn't this case.
|
|
201
|
+
*/
|
|
202
|
+
private toSchemaConflictError;
|
|
182
203
|
/**
|
|
183
204
|
* Manually restore the DO to a specific PITR bookmark.
|
|
184
205
|
* The DO will restart on next access with the restored state.
|
|
@@ -325,4 +346,4 @@ declare class DateSerializePlugin implements KyselyPlugin {
|
|
|
325
346
|
*/
|
|
326
347
|
declare function createDrizzlePlugins(schema: Record<string, SQLiteTableWithColumns<any>>, camelCase?: boolean): KyselyPlugin[];
|
|
327
348
|
//#endregion
|
|
328
|
-
export {
|
|
349
|
+
export { Migrations as _, QueryResult$1 as a, createKyselyFromSql as b, DateSerializePlugin as c, createDrizzlePlugins as d, dateSerializers as f, MigrationSchemaConflictError as g, MigrationAttemptInfo as h, KyselyPlugin$1 as i, DrizzleDefaultsPlugin as l, Migration as m, CompiledQuery as n, studio as o, CreateKyselyOptions as p, Kysely$1 as r, type$1 as s, CamelCasePlugin$1 as t, SchemaPlugin as u, SqlExecutor as v, SqliteDurableObject as y };
|
package/dist/vite/durableDb.d.ts
CHANGED
|
@@ -10,6 +10,13 @@ interface DurableDbOptions {
|
|
|
10
10
|
databasesDir?: string;
|
|
11
11
|
/** Directory for production migrations, relative to project root. Default: 'migrations' */
|
|
12
12
|
migrationsDir?: string;
|
|
13
|
+
/**
|
|
14
|
+
* Write missing Durable Object bindings and sqlite migration entries to
|
|
15
|
+
* wrangler.jsonc/json automatically. When false (the default), the plugin
|
|
16
|
+
* only verifies the config and logs the exact JSON to add when something
|
|
17
|
+
* is missing — your config file is never modified.
|
|
18
|
+
*/
|
|
19
|
+
patchWranglerConfig?: boolean;
|
|
13
20
|
}
|
|
14
21
|
declare function durableDb(options?: DurableDbOptions): Plugin;
|
|
15
22
|
/** @deprecated Renamed to {@link durableDb}. */
|
package/dist/vite/durableDb.js
CHANGED
|
@@ -201,6 +201,66 @@ function logRequiredConfig(databases) {
|
|
|
201
201
|
migrations
|
|
202
202
|
});
|
|
203
203
|
}
|
|
204
|
+
/**
|
|
205
|
+
* Verify (without writing) that the wrangler config contains the Durable
|
|
206
|
+
* Object bindings and sqlite migration entries the discovered databases
|
|
207
|
+
* need. Logs an actionable warning with the exact JSON to add when
|
|
208
|
+
* something is missing.
|
|
209
|
+
*
|
|
210
|
+
* This is the default behavior of the Vite plugin — automatic patching
|
|
211
|
+
* is opt-in via the `patchWranglerConfig` plugin option.
|
|
212
|
+
*/
|
|
213
|
+
function checkWranglerConfig(projectRoot, databases) {
|
|
214
|
+
const required = generateRequiredConfig(databases);
|
|
215
|
+
const configPath = findWranglerConfig(projectRoot);
|
|
216
|
+
const result = {
|
|
217
|
+
configPath,
|
|
218
|
+
missingBindings: [],
|
|
219
|
+
missingSqliteClasses: [],
|
|
220
|
+
ok: true,
|
|
221
|
+
tomlOnly: !configPath && fs.existsSync(path.join(projectRoot, "wrangler.toml"))
|
|
222
|
+
};
|
|
223
|
+
let config = {};
|
|
224
|
+
if (configPath) try {
|
|
225
|
+
config = parseWranglerConfig(fs.readFileSync(configPath, "utf-8"));
|
|
226
|
+
} catch (error) {
|
|
227
|
+
debugVite("Failed to parse wrangler config for check: %O", error);
|
|
228
|
+
}
|
|
229
|
+
const existingBindings = config.durable_objects?.bindings ?? [];
|
|
230
|
+
result.missingBindings = (required.durable_objects?.bindings ?? []).filter((req) => !existingBindings.some((b) => b.name === req.name || b.class_name === req.class_name));
|
|
231
|
+
const existingClasses = new Set((config.migrations ?? []).flatMap((m) => m.new_sqlite_classes ?? []));
|
|
232
|
+
result.missingSqliteClasses = (required.migrations?.[0]?.new_sqlite_classes ?? []).filter((c) => !existingClasses.has(c));
|
|
233
|
+
result.ok = result.missingBindings.length === 0 && result.missingSqliteClasses.length === 0;
|
|
234
|
+
if (!result.ok) {
|
|
235
|
+
const snippet = JSON.stringify({
|
|
236
|
+
...result.missingBindings.length > 0 && { durable_objects: { bindings: result.missingBindings } },
|
|
237
|
+
...result.missingSqliteClasses.length > 0 && { migrations: [{
|
|
238
|
+
tag: "v1",
|
|
239
|
+
new_sqlite_classes: result.missingSqliteClasses
|
|
240
|
+
}] }
|
|
241
|
+
}, null, 2);
|
|
242
|
+
const hasToml = result.tomlOnly;
|
|
243
|
+
const where = configPath ? path.basename(configPath) : hasToml ? "wrangler.toml (not supported — only wrangler.jsonc/json can be verified or patched)" : "wrangler.jsonc";
|
|
244
|
+
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 })`));
|
|
245
|
+
}
|
|
246
|
+
return result;
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* Generate the required wrangler config as a string
|
|
250
|
+
* Useful for displaying to users or tests
|
|
251
|
+
*/
|
|
252
|
+
function generateRequiredConfig(databases) {
|
|
253
|
+
return {
|
|
254
|
+
durable_objects: { bindings: databases.map((db) => ({
|
|
255
|
+
name: db.bindingName,
|
|
256
|
+
class_name: db.className
|
|
257
|
+
})) },
|
|
258
|
+
migrations: [{
|
|
259
|
+
tag: "v1",
|
|
260
|
+
new_sqlite_classes: databases.map((db) => db.className)
|
|
261
|
+
}]
|
|
262
|
+
};
|
|
263
|
+
}
|
|
204
264
|
|
|
205
265
|
//#endregion
|
|
206
266
|
//#region src/vite/modules/generator.ts
|
|
@@ -693,9 +753,24 @@ var PluginState = class {
|
|
|
693
753
|
projectRoot = "";
|
|
694
754
|
config;
|
|
695
755
|
devServer = null;
|
|
756
|
+
selfDevStateWriteUntil = 0;
|
|
696
757
|
constructor(options) {
|
|
697
758
|
this.options = options;
|
|
698
759
|
}
|
|
760
|
+
/**
|
|
761
|
+
* Mark an imminent write to the dev cache made by the plugin itself
|
|
762
|
+
* (persisting a freshly minted epoch on first run). The cache watcher
|
|
763
|
+
* ignores events inside this window — without it, the plugin's own
|
|
764
|
+
* bootstrap write would trigger a full reload on the very first dev-server
|
|
765
|
+
* run, before any client (or the Cloudflare worker's hot channel
|
|
766
|
+
* WebSocket) is connected.
|
|
767
|
+
*/
|
|
768
|
+
markSelfDevStateWrite() {
|
|
769
|
+
this.selfDevStateWriteUntil = Date.now() + 1500;
|
|
770
|
+
}
|
|
771
|
+
isWithinSelfDevStateWriteWindow() {
|
|
772
|
+
return Date.now() <= this.selfDevStateWriteUntil;
|
|
773
|
+
}
|
|
699
774
|
registerDatabaseFile(filePath, dbName) {
|
|
700
775
|
const abs = path.normalize(filePath);
|
|
701
776
|
this.databaseFilePaths.set(abs, dbName);
|
|
@@ -748,7 +823,12 @@ var PluginState = class {
|
|
|
748
823
|
}
|
|
749
824
|
if (this.databases.size > 0) {
|
|
750
825
|
debugVite("Found %d database(s)", this.databases.size);
|
|
751
|
-
|
|
826
|
+
const databases = Array.from(this.databases.values());
|
|
827
|
+
if (this.options.patchWranglerConfig) patchWranglerConfig(this.projectRoot, databases);
|
|
828
|
+
else {
|
|
829
|
+
const check = checkWranglerConfig(this.projectRoot, databases);
|
|
830
|
+
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.basename(check.configPath) : "wrangler.jsonc"}, or opt in to automatic patching with durableDb({ patchWranglerConfig: true }).`);
|
|
831
|
+
}
|
|
752
832
|
}
|
|
753
833
|
this.initialized = true;
|
|
754
834
|
}
|
|
@@ -795,7 +875,11 @@ var PluginState = class {
|
|
|
795
875
|
triggerFullReload() {
|
|
796
876
|
if (!this.devServer) return;
|
|
797
877
|
const environments = this.devServer.environments;
|
|
798
|
-
if (environments) for (const env of Object.
|
|
878
|
+
if (environments) for (const [name, env] of Object.entries(environments)) try {
|
|
879
|
+
env.hot?.send({ type: "full-reload" });
|
|
880
|
+
} catch (error) {
|
|
881
|
+
debugVite("Skipped full-reload for environment %s (hot channel not ready): %O", name, error);
|
|
882
|
+
}
|
|
799
883
|
else this.devServer.ws.send({ type: "full-reload" });
|
|
800
884
|
}
|
|
801
885
|
};
|
|
@@ -816,7 +900,8 @@ function durableDb(options = {}) {
|
|
|
816
900
|
contextImport: options.contextImport ?? "durable-db/context",
|
|
817
901
|
registryImport: options.registryImport ?? "durable-db/registry",
|
|
818
902
|
databasesDir: options.databasesDir ?? "src/databases",
|
|
819
|
-
migrationsDir: options.migrationsDir ?? "migrations"
|
|
903
|
+
migrationsDir: options.migrationsDir ?? "migrations",
|
|
904
|
+
patchWranglerConfig: options.patchWranglerConfig ?? false
|
|
820
905
|
});
|
|
821
906
|
return {
|
|
822
907
|
name: "durable-db",
|
|
@@ -837,6 +922,10 @@ function durableDb(options = {}) {
|
|
|
837
922
|
fs.mkdirSync(devPaths.cacheDir, { recursive: true });
|
|
838
923
|
let reloadTimer = null;
|
|
839
924
|
const onDevStateChange = () => {
|
|
925
|
+
if (state.isWithinSelfDevStateWriteWindow()) {
|
|
926
|
+
debugVite("Ignoring dev cache event caused by the plugin itself");
|
|
927
|
+
return;
|
|
928
|
+
}
|
|
840
929
|
if (reloadTimer) clearTimeout(reloadTimer);
|
|
841
930
|
reloadTimer = setTimeout(() => {
|
|
842
931
|
debugVite("Dev state changed; reloading durable-db modules");
|
|
@@ -869,7 +958,10 @@ function durableDb(options = {}) {
|
|
|
869
958
|
let epoch = null;
|
|
870
959
|
if (isDev$1) {
|
|
871
960
|
const devState = loadDevState(state.projectRoot);
|
|
872
|
-
if (!fs.existsSync(getDevPaths(state.projectRoot).stateFile))
|
|
961
|
+
if (!fs.existsSync(getDevPaths(state.projectRoot).stateFile)) {
|
|
962
|
+
state.markSelfDevStateWrite();
|
|
963
|
+
saveDevState(state.projectRoot, devState);
|
|
964
|
+
}
|
|
873
965
|
epoch = devState.epoch;
|
|
874
966
|
}
|
|
875
967
|
return { code: generateDevEpochModule(epoch) };
|
package/package.json
CHANGED
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "durable-db",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.3",
|
|
4
4
|
"repository": {
|
|
5
5
|
"type": "git",
|
|
6
6
|
"url": "https://github.com/eagerpatch/durable-db.git"
|
|
7
7
|
},
|
|
8
8
|
"type": "module",
|
|
9
|
-
"packageManager": "pnpm@10.2.1",
|
|
10
9
|
"bin": {
|
|
11
10
|
"db": "./dist/cli/bin.js"
|
|
12
11
|
},
|
|
@@ -66,13 +65,6 @@
|
|
|
66
65
|
"publishConfig": {
|
|
67
66
|
"access": "public"
|
|
68
67
|
},
|
|
69
|
-
"scripts": {
|
|
70
|
-
"build": "tsdown",
|
|
71
|
-
"dev": "tsdown --watch",
|
|
72
|
-
"test": "vitest",
|
|
73
|
-
"test:run": "vitest run",
|
|
74
|
-
"changeset": "changeset"
|
|
75
|
-
},
|
|
76
68
|
"dependencies": {
|
|
77
69
|
"@babel/generator": "^7.0.0",
|
|
78
70
|
"@babel/parser": "^7.0.0",
|
|
@@ -110,5 +102,12 @@
|
|
|
110
102
|
"typescript": "^5.7.0",
|
|
111
103
|
"vite": "^7.0.0",
|
|
112
104
|
"vitest": "^2.1.0"
|
|
105
|
+
},
|
|
106
|
+
"scripts": {
|
|
107
|
+
"build": "tsdown",
|
|
108
|
+
"dev": "tsdown --watch",
|
|
109
|
+
"test": "vitest",
|
|
110
|
+
"test:run": "vitest run",
|
|
111
|
+
"changeset": "changeset"
|
|
113
112
|
}
|
|
114
|
-
}
|
|
113
|
+
}
|