durable-db 0.1.7 → 0.1.9
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/dist/cli/bin.js +5 -5
- package/dist/cli/index.d.ts +1 -1
- package/dist/cli/index.js +5 -5
- package/dist/{cli-CjxrMYk5.js → cli-BCgiaUy_.js} +9 -9
- package/dist/context/index.js +2 -2
- package/dist/{context-Cwe1IsnH.js → context-DbGqDnBa.js} +1 -1
- package/dist/db/index.d.ts +1 -1
- package/dist/db/index.js +17 -3
- package/dist/{generator-DyrLOnPS.js → generator-KHBZaOI1.js} +10 -10
- package/dist/{index-NJ7kT_a5.d.ts → index-AbdSa1Mk.d.ts} +14 -1
- package/dist/index.js +2 -2
- package/dist/{kysely-yPsCWEvR.js → kysely-BH7QZBZw.js} +150 -1
- package/dist/migrations/generator.js +1 -1
- package/dist/{parser-CzKUWwk1.js → parser-CL3Nlmsy.js} +15 -15
- package/dist/push-BY3lfh-R.js +8 -0
- package/dist/{push-CAgrAjKM.js → push-DiHH52-G.js} +6 -6
- package/dist/{state-B4v8ICj8.js → state-DtZ70cBR.js} +14 -14
- package/dist/{state-BfYEMzuB.js → state-vav3VCId.js} +1 -1
- package/dist/testing/index.js +3 -3
- package/dist/vite/durableDb.js +59 -26
- package/package.json +1 -1
- package/dist/push-D0zsn0Ge.js +0 -8
package/dist/cli/bin.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import "../debug-DmBrUmwe.js";
|
|
3
|
-
import "../state-
|
|
3
|
+
import "../state-DtZ70cBR.js";
|
|
4
4
|
import "../snapshot-DMW6j2Ix.js";
|
|
5
|
-
import "../generator-
|
|
6
|
-
import "../parser-
|
|
7
|
-
import "../push-
|
|
8
|
-
import { n as registerDbCommands } from "../cli-
|
|
5
|
+
import "../generator-KHBZaOI1.js";
|
|
6
|
+
import "../parser-CL3Nlmsy.js";
|
|
7
|
+
import "../push-DiHH52-G.js";
|
|
8
|
+
import { n as registerDbCommands } from "../cli-BCgiaUy_.js";
|
|
9
9
|
import { Command } from "commander";
|
|
10
10
|
|
|
11
11
|
//#region src/cli/bin.ts
|
package/dist/cli/index.d.ts
CHANGED
package/dist/cli/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import "../debug-DmBrUmwe.js";
|
|
2
|
-
import { _ as saveDevState, a as generateEpoch, c as getDevPaths, f as loadDevMigrations, l as getInstanceKey, m as loadDevState, s as getDevEpoch } from "../state-
|
|
2
|
+
import { _ as saveDevState, a as generateEpoch, c as getDevPaths, f as loadDevMigrations, l as getInstanceKey, m as loadDevState, s as getDevEpoch } from "../state-DtZ70cBR.js";
|
|
3
3
|
import "../snapshot-DMW6j2Ix.js";
|
|
4
|
-
import "../generator-
|
|
5
|
-
import "../parser-
|
|
6
|
-
import { a as loadSchema, i as discoverDatabases, n as pushOne, o as reportCliError, r as diffSchema, t as push } from "../push-
|
|
7
|
-
import { a as resetAndPush, c as generate, i as reset, l as generateOne, n as registerDbCommands, o as formatStatus, r as validate, s as status, t as createDbCommand } from "../cli-
|
|
4
|
+
import "../generator-KHBZaOI1.js";
|
|
5
|
+
import "../parser-CL3Nlmsy.js";
|
|
6
|
+
import { a as loadSchema, i as discoverDatabases, n as pushOne, o as reportCliError, r as diffSchema, t as push } from "../push-DiHH52-G.js";
|
|
7
|
+
import { a as resetAndPush, c as generate, i as reset, l as generateOne, n as registerDbCommands, o as formatStatus, r as validate, s as status, t as createDbCommand } from "../cli-BCgiaUy_.js";
|
|
8
8
|
|
|
9
9
|
export { createDbCommand, diffSchema, discoverDatabases, formatStatus, generate, generateEpoch, generateOne, getDevEpoch, getDevPaths, getInstanceKey, loadDevMigrations, loadDevState, loadSchema, push, pushOne, registerDbCommands, reportCliError, reset, resetAndPush, saveDevState, status, validate };
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { i as init_debug, t as debugCli } from "./debug-DmBrUmwe.js";
|
|
2
|
-
import { _ as saveDevState, a as generateEpoch, c as getDevPaths, d as init_state, f as loadDevMigrations, m as loadDevState, t as clearDatabaseDevState } from "./state-
|
|
2
|
+
import { _ as saveDevState, a as generateEpoch, c as getDevPaths, d as init_state, f as loadDevMigrations, m as loadDevState, t as clearDatabaseDevState } from "./state-DtZ70cBR.js";
|
|
3
3
|
import { a as hashSnapshot } from "./snapshot-DMW6j2Ix.js";
|
|
4
|
-
import { a as loadMigrationFiles, i as generateMigrationName, l as saveSnapshot, n as generateCreateTableSQL, s as loadSnapshot, t as buildAndLoadSchema } from "./generator-
|
|
5
|
-
import { o as resolveImportPath, s as loadViteAliases } from "./parser-
|
|
6
|
-
import { a as loadSchema, i as discoverDatabases, o as reportCliError, r as diffSchema, t as push } from "./push-
|
|
4
|
+
import { a as loadMigrationFiles, i as generateMigrationName, l as saveSnapshot, n as generateCreateTableSQL, s as loadSnapshot, t as buildAndLoadSchema } from "./generator-KHBZaOI1.js";
|
|
5
|
+
import { o as resolveImportPath, s as loadViteAliases } from "./parser-CL3Nlmsy.js";
|
|
6
|
+
import { a as loadSchema, i as discoverDatabases, o as reportCliError, r as diffSchema, t as push } from "./push-DiHH52-G.js";
|
|
7
7
|
import * as fs from "node:fs";
|
|
8
|
-
import * as path from "node:path";
|
|
8
|
+
import * as path$1 from "node:path";
|
|
9
9
|
import { Command } from "commander";
|
|
10
10
|
|
|
11
11
|
//#region src/cli/generate.ts
|
|
@@ -69,7 +69,7 @@ async function generateDatabase(db, customName, projectRoot) {
|
|
|
69
69
|
}
|
|
70
70
|
const migrationName = generateMigrationName(customName ?? "migration");
|
|
71
71
|
fs.mkdirSync(db.migrationsDir, { recursive: true });
|
|
72
|
-
const migrationPath = path.join(db.migrationsDir, `${migrationName}.sql`);
|
|
72
|
+
const migrationPath = path$1.join(db.migrationsDir, `${migrationName}.sql`);
|
|
73
73
|
const sqlContent = diff.statements.map((s) => s.endsWith(";") ? s : `${s};`).join("\n\n");
|
|
74
74
|
fs.writeFileSync(migrationPath, sqlContent);
|
|
75
75
|
const newSnapshot = {
|
|
@@ -206,7 +206,7 @@ init_debug();
|
|
|
206
206
|
* Both `wrangler dev` and the Cloudflare Vite plugin use this layout.
|
|
207
207
|
*/
|
|
208
208
|
function localDoStorageDir(projectRoot) {
|
|
209
|
-
return path.join(projectRoot, ".wrangler", "state", "v3", "do");
|
|
209
|
+
return path$1.join(projectRoot, ".wrangler", "state", "v3", "do");
|
|
210
210
|
}
|
|
211
211
|
/**
|
|
212
212
|
* Delete workerd's persisted Durable Object storage.
|
|
@@ -236,7 +236,7 @@ function clearLocalDoStorage(projectRoot, className) {
|
|
|
236
236
|
}
|
|
237
237
|
const cleared = [];
|
|
238
238
|
for (const entry of fs.readdirSync(doDir)) if (entry.includes(className)) {
|
|
239
|
-
const dir = path.join(doDir, entry);
|
|
239
|
+
const dir = path$1.join(doDir, entry);
|
|
240
240
|
fs.rmSync(dir, {
|
|
241
241
|
recursive: true,
|
|
242
242
|
force: true
|
|
@@ -322,7 +322,7 @@ async function reset(ctx = {}, options = {}) {
|
|
|
322
322
|
* Convenience function that combines reset + push
|
|
323
323
|
*/
|
|
324
324
|
async function resetAndPush(ctx = {}, options = {}) {
|
|
325
|
-
const { push: push$1 } = await import("./push-
|
|
325
|
+
const { push: push$1 } = await import("./push-BY3lfh-R.js");
|
|
326
326
|
return {
|
|
327
327
|
reset: await reset(ctx, options),
|
|
328
328
|
push: await push$1(ctx)
|
package/dist/context/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import "../debug-DmBrUmwe.js";
|
|
2
|
-
import "../state-
|
|
3
|
-
import { a as setTenantIdResolver, i as hasTenantId, n as getInstanceKey, r as getTenantId, t as getDevInstanceKeySuffix } from "../context-
|
|
2
|
+
import "../state-DtZ70cBR.js";
|
|
3
|
+
import { a as setTenantIdResolver, i as hasTenantId, n as getInstanceKey, r as getTenantId, t as getDevInstanceKeySuffix } from "../context-DbGqDnBa.js";
|
|
4
4
|
|
|
5
5
|
export { getDevInstanceKeySuffix, getInstanceKey, getTenantId, hasTenantId, setTenantIdResolver };
|
package/dist/db/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import { t as type } from "../arktypeConfig--4OgOv4U.js";
|
|
2
2
|
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-Bjws1Jkd.js";
|
|
3
|
-
import { _ as CreateKyselyOptions, a as QueryResult, c as DrizzleDefaultsPlugin, d as dateSerializers, f as Migration, g as SqliteDurableObject, h as Migrations, i as KyselyPlugin, l as SchemaPlugin, m as MigrationSchemaConflictError, n as CompiledQuery, o as studio, p as MigrationAttemptInfo, r as Kysely, s as DateSerializePlugin, t as CamelCasePlugin, u as createDrizzlePlugins, v as SqlExecutor, y as createKyselyFromSql } from "../index-
|
|
3
|
+
import { _ as CreateKyselyOptions, a as QueryResult, c as DrizzleDefaultsPlugin, d as dateSerializers, f as Migration, g as SqliteDurableObject, h as Migrations, i as KyselyPlugin, l as SchemaPlugin, m as MigrationSchemaConflictError, n as CompiledQuery, o as studio, p as MigrationAttemptInfo, r as Kysely, s as DateSerializePlugin, t as CamelCasePlugin, u as createDrizzlePlugins, v as SqlExecutor, y as createKyselyFromSql } from "../index-AbdSa1Mk.js";
|
|
4
4
|
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
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { i as init_debug, n as debugMigrations } from "../debug-DmBrUmwe.js";
|
|
2
2
|
import { t as type } from "../arktypeConfig-CTCJm4vA.js";
|
|
3
3
|
import { n as defineDatabase } from "../defineDatabase-BD3k1L7d.js";
|
|
4
|
-
import { a as createDrizzlePlugins, i as SchemaPlugin, n as DateSerializePlugin, o as dateSerializers, r as DrizzleDefaultsPlugin, t as createKyselyFromSql } from "../kysely-
|
|
4
|
+
import { a as createDrizzlePlugins, i as SchemaPlugin, n as DateSerializePlugin, o as dateSerializers, r as DrizzleDefaultsPlugin, t as createKyselyFromSql } from "../kysely-BH7QZBZw.js";
|
|
5
5
|
import { DurableObject } from "cloudflare:workers";
|
|
6
6
|
import { CamelCasePlugin } from "kysely";
|
|
7
7
|
import { studio } from "@outerbase/browsable-durable-object";
|
|
@@ -69,10 +69,25 @@ function formatStatementForLog(statement, max = 120) {
|
|
|
69
69
|
* ```
|
|
70
70
|
*/
|
|
71
71
|
var SqliteDurableObject = class extends DurableObject {
|
|
72
|
+
/**
|
|
73
|
+
* Optional Drizzle schema (the same object passed to `defineDatabase`).
|
|
74
|
+
* When set — the generated Durable Object populates it — the Kysely
|
|
75
|
+
* instance is built with the full schema-aware plugin chain
|
|
76
|
+
* (createDrizzlePlugins: defaults, exact column mapping, date and boolean
|
|
77
|
+
* deserialization). Without it only the schema-less plugins apply.
|
|
78
|
+
*
|
|
79
|
+
* Subclass field initializers run after this constructor, so `db` is built
|
|
80
|
+
* lazily on first access rather than in the constructor.
|
|
81
|
+
*/
|
|
82
|
+
schema;
|
|
83
|
+
_db;
|
|
72
84
|
/**
|
|
73
85
|
* The Kysely database instance - available after migrations run
|
|
74
86
|
*/
|
|
75
|
-
db
|
|
87
|
+
get db() {
|
|
88
|
+
if (!this._db) this._db = createKyselyFromSql(this.sql, this.schema ? { schema: this.schema } : {});
|
|
89
|
+
return this._db;
|
|
90
|
+
}
|
|
76
91
|
/**
|
|
77
92
|
* Raw SQLite storage access
|
|
78
93
|
*/
|
|
@@ -95,7 +110,6 @@ var SqliteDurableObject = class extends DurableObject {
|
|
|
95
110
|
constructor(ctx, env) {
|
|
96
111
|
super(ctx, env);
|
|
97
112
|
this.sql = ctx.storage.sql;
|
|
98
|
-
this.db = createKyselyFromSql(this.sql);
|
|
99
113
|
}
|
|
100
114
|
/**
|
|
101
115
|
* Check if PITR is available on this DO's storage.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { i as init_debug, n as debugMigrations } from "./debug-DmBrUmwe.js";
|
|
2
2
|
import { i as generateSnapshotId, n as generateMigrationStatements, o as snapshotsEqual, r as generateSnapshotFromSchema, t as createEmptySnapshot } from "./snapshot-DMW6j2Ix.js";
|
|
3
3
|
import * as fs from "node:fs";
|
|
4
|
-
import * as path from "node:path";
|
|
4
|
+
import * as path$1 from "node:path";
|
|
5
5
|
import * as os from "node:os";
|
|
6
6
|
import { pathToFileURL } from "node:url";
|
|
7
7
|
|
|
@@ -15,7 +15,7 @@ const SNAPSHOT_FILE = "_snapshot.json";
|
|
|
15
15
|
* Load the previous snapshot from the migrations directory
|
|
16
16
|
*/
|
|
17
17
|
function loadSnapshot(migrationsDir) {
|
|
18
|
-
const snapshotPath = path.join(migrationsDir, SNAPSHOT_FILE);
|
|
18
|
+
const snapshotPath = path$1.join(migrationsDir, SNAPSHOT_FILE);
|
|
19
19
|
if (!fs.existsSync(snapshotPath)) return createEmptySnapshot();
|
|
20
20
|
const content = fs.readFileSync(snapshotPath, "utf-8");
|
|
21
21
|
try {
|
|
@@ -30,7 +30,7 @@ function loadSnapshot(migrationsDir) {
|
|
|
30
30
|
*/
|
|
31
31
|
function saveSnapshot(migrationsDir, snapshot) {
|
|
32
32
|
fs.mkdirSync(migrationsDir, { recursive: true });
|
|
33
|
-
const snapshotPath = path.join(migrationsDir, SNAPSHOT_FILE);
|
|
33
|
+
const snapshotPath = path$1.join(migrationsDir, SNAPSHOT_FILE);
|
|
34
34
|
fs.writeFileSync(snapshotPath, JSON.stringify(snapshot, null, 2));
|
|
35
35
|
}
|
|
36
36
|
/**
|
|
@@ -77,7 +77,7 @@ async function generateMigration(options) {
|
|
|
77
77
|
const name = migrationName ?? generateMigrationName("auto");
|
|
78
78
|
if (write && statements.length > 0) {
|
|
79
79
|
fs.mkdirSync(migrationsDir, { recursive: true });
|
|
80
|
-
const sqlPath = path.join(migrationsDir, `${name}.sql`);
|
|
80
|
+
const sqlPath = path$1.join(migrationsDir, `${name}.sql`);
|
|
81
81
|
const sqlContent = statements.map((s) => s.endsWith(";") ? s : `${s};`).join("\n\n");
|
|
82
82
|
fs.writeFileSync(sqlPath, sqlContent);
|
|
83
83
|
saveSnapshot(migrationsDir, newSnapshot);
|
|
@@ -118,7 +118,7 @@ function loadMigrationFiles(migrationsDir) {
|
|
|
118
118
|
const files = fs.readdirSync(migrationsDir).filter((f) => f.endsWith(".sql")).sort();
|
|
119
119
|
for (const file of files) {
|
|
120
120
|
const name = file.replace(".sql", "");
|
|
121
|
-
const chunks = parseSqlMigration(fs.readFileSync(path.join(migrationsDir, file), "utf-8"));
|
|
121
|
+
const chunks = parseSqlMigration(fs.readFileSync(path$1.join(migrationsDir, file), "utf-8"));
|
|
122
122
|
if (chunks.length > 0) migrations.set(name, chunks);
|
|
123
123
|
}
|
|
124
124
|
return migrations;
|
|
@@ -150,14 +150,14 @@ async function loadSchemaModule(schemaPath, tableNames) {
|
|
|
150
150
|
* relative to cwd in that case too).
|
|
151
151
|
*/
|
|
152
152
|
function resolveTempDir(schemaPath) {
|
|
153
|
-
let dir = path.dirname(path.resolve(schemaPath));
|
|
153
|
+
let dir = path$1.dirname(path$1.resolve(schemaPath));
|
|
154
154
|
while (true) {
|
|
155
|
-
if (fs.existsSync(path.join(dir, "node_modules"))) return path.join(dir, "node_modules", ".cache", "durable-db");
|
|
156
|
-
const parent = path.dirname(dir);
|
|
155
|
+
if (fs.existsSync(path$1.join(dir, "node_modules"))) return path$1.join(dir, "node_modules", ".cache", "durable-db");
|
|
156
|
+
const parent = path$1.dirname(dir);
|
|
157
157
|
if (parent === dir) break;
|
|
158
158
|
dir = parent;
|
|
159
159
|
}
|
|
160
|
-
return path.join(os.tmpdir(), "durable-db");
|
|
160
|
+
return path$1.join(os.tmpdir(), "durable-db");
|
|
161
161
|
}
|
|
162
162
|
/**
|
|
163
163
|
* Build schema module with esbuild and return the exports
|
|
@@ -176,7 +176,7 @@ async function buildAndLoadSchema(schemaPath, tableNames) {
|
|
|
176
176
|
if (result.outputFiles?.length !== 1) throw new Error(`Unexpected esbuild output for ${schemaPath}`);
|
|
177
177
|
const tempDir = resolveTempDir(schemaPath);
|
|
178
178
|
fs.mkdirSync(tempDir, { recursive: true });
|
|
179
|
-
const tempFile = path.join(tempDir, `_schema_temp_${Date.now()}.mjs`);
|
|
179
|
+
const tempFile = path$1.join(tempDir, `_schema_temp_${Date.now()}.mjs`);
|
|
180
180
|
try {
|
|
181
181
|
fs.writeFileSync(tempFile, result.outputFiles[0].text);
|
|
182
182
|
const module = await import(pathToFileURL(tempFile).href);
|
|
@@ -129,10 +129,22 @@ declare abstract class SqliteDurableObject<Env = unknown> extends DurableObject<
|
|
|
129
129
|
* Override this with your migrations object
|
|
130
130
|
*/
|
|
131
131
|
abstract migrations: Migrations;
|
|
132
|
+
/**
|
|
133
|
+
* Optional Drizzle schema (the same object passed to `defineDatabase`).
|
|
134
|
+
* When set — the generated Durable Object populates it — the Kysely
|
|
135
|
+
* instance is built with the full schema-aware plugin chain
|
|
136
|
+
* (createDrizzlePlugins: defaults, exact column mapping, date and boolean
|
|
137
|
+
* deserialization). Without it only the schema-less plugins apply.
|
|
138
|
+
*
|
|
139
|
+
* Subclass field initializers run after this constructor, so `db` is built
|
|
140
|
+
* lazily on first access rather than in the constructor.
|
|
141
|
+
*/
|
|
142
|
+
schema?: Record<string, SQLiteTableWithColumns<any>>;
|
|
143
|
+
private _db;
|
|
132
144
|
/**
|
|
133
145
|
* The Kysely database instance - available after migrations run
|
|
134
146
|
*/
|
|
135
|
-
protected db: Kysely<any>;
|
|
147
|
+
protected get db(): Kysely<any>;
|
|
136
148
|
/**
|
|
137
149
|
* Raw SQLite storage access
|
|
138
150
|
*/
|
|
@@ -342,6 +354,7 @@ declare class DateSerializePlugin implements KyselyPlugin {
|
|
|
342
354
|
* - DrizzleDefaultsPlugin: auto-populates defaultFn/onUpdateFn values
|
|
343
355
|
* - SchemaPlugin (extends CamelCasePlugin): schema-aware camelCase ↔ snake_case
|
|
344
356
|
* - DateSerializePlugin: Date ↔ SQLite text serialization
|
|
357
|
+
* - BooleanDeserializePlugin: boolean-mode columns read back as booleans
|
|
345
358
|
*
|
|
346
359
|
* When camelCase is false, SchemaPlugin is omitted.
|
|
347
360
|
*/
|
package/dist/index.js
CHANGED
|
@@ -2,7 +2,7 @@ import "./debug-DmBrUmwe.js";
|
|
|
2
2
|
import { t as type } from "./arktypeConfig-CTCJm4vA.js";
|
|
3
3
|
import { n as defineDatabase } from "./defineDatabase-BD3k1L7d.js";
|
|
4
4
|
import { a as numeric, c as table, i as integer, l as text, n as foreignKey, o as primaryKey, r as index, s as real, t as blob, u as uniqueIndex } from "./schema-IFq7ovQq.js";
|
|
5
|
-
import "./state-
|
|
6
|
-
import { a as setTenantIdResolver, i as hasTenantId, r as getTenantId } from "./context-
|
|
5
|
+
import "./state-DtZ70cBR.js";
|
|
6
|
+
import { a as setTenantIdResolver, i as hasTenantId, r as getTenantId } from "./context-DbGqDnBa.js";
|
|
7
7
|
|
|
8
8
|
export { blob, defineDatabase, foreignKey, getTenantId, hasTenantId, index, integer, numeric, primaryKey, real, setTenantIdResolver, table, text, type, uniqueIndex };
|
|
@@ -247,6 +247,63 @@ var DateSerializePlugin = class {
|
|
|
247
247
|
}
|
|
248
248
|
};
|
|
249
249
|
/**
|
|
250
|
+
* Collect the names of columns Drizzle declares as boolean-typed
|
|
251
|
+
* (`integer({ mode: 'boolean' })`). Mirrors collectDateColumnNames: covers
|
|
252
|
+
* the SQL column name, the JS property name, and the snake_cased property
|
|
253
|
+
* name, so it works on either side of the CamelCasePlugin.
|
|
254
|
+
*/
|
|
255
|
+
function collectBooleanColumnNames(schema) {
|
|
256
|
+
const booleanColumns = /* @__PURE__ */ new Set();
|
|
257
|
+
for (const table of Object.values(schema)) {
|
|
258
|
+
const columns = getTableColumns(table);
|
|
259
|
+
for (const [propertyName, column] of Object.entries(columns)) if (column.dataType === "boolean") {
|
|
260
|
+
booleanColumns.add(column.name);
|
|
261
|
+
booleanColumns.add(propertyName);
|
|
262
|
+
booleanColumns.add(toSnakeCase(propertyName));
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
return booleanColumns;
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Plugin that deserializes boolean-mode columns on read.
|
|
269
|
+
*
|
|
270
|
+
* SQLite stores booleans as INTEGER 1/0 (the write side is normalized in the
|
|
271
|
+
* driver — see normalizeParameter in kysely.ts), so schema-declared boolean
|
|
272
|
+
* columns come back as numbers and must be mapped to real booleans. Legacy
|
|
273
|
+
* rows written before the driver normalization existed carry TEXT
|
|
274
|
+
* 'true'/'false' — those are mapped too, so old data keeps reading correctly.
|
|
275
|
+
* Anything unrecognized round-trips verbatim rather than being guessed at.
|
|
276
|
+
*/
|
|
277
|
+
var BooleanDeserializePlugin = class {
|
|
278
|
+
booleanColumns;
|
|
279
|
+
constructor(schema) {
|
|
280
|
+
this.booleanColumns = collectBooleanColumnNames(schema);
|
|
281
|
+
}
|
|
282
|
+
transformQuery(args) {
|
|
283
|
+
return args.node;
|
|
284
|
+
}
|
|
285
|
+
async transformResult(args) {
|
|
286
|
+
if (this.booleanColumns.size === 0) return args.result;
|
|
287
|
+
return {
|
|
288
|
+
...args.result,
|
|
289
|
+
rows: args.result.rows.map((row) => this.transformRow(row))
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
transformRow(row) {
|
|
293
|
+
const result = {};
|
|
294
|
+
for (const [key, value] of Object.entries(row)) result[key] = this.booleanColumns.has(key) ? this.toBoolean(value) : value;
|
|
295
|
+
return result;
|
|
296
|
+
}
|
|
297
|
+
toBoolean(value) {
|
|
298
|
+
if (value === null || value === void 0 || typeof value === "boolean") return value;
|
|
299
|
+
if (typeof value === "number") return value !== 0;
|
|
300
|
+
if (typeof value === "bigint") return value !== 0n;
|
|
301
|
+
if (value === "true" || value === "1") return true;
|
|
302
|
+
if (value === "false" || value === "0") return false;
|
|
303
|
+
return value;
|
|
304
|
+
}
|
|
305
|
+
};
|
|
306
|
+
/**
|
|
250
307
|
* Validate that a schema object is shaped like a record of Drizzle tables.
|
|
251
308
|
*
|
|
252
309
|
* Throws a descriptive error pointing at the offending key when the schema
|
|
@@ -269,6 +326,7 @@ function assertValidSchema(schema) {
|
|
|
269
326
|
* - DrizzleDefaultsPlugin: auto-populates defaultFn/onUpdateFn values
|
|
270
327
|
* - SchemaPlugin (extends CamelCasePlugin): schema-aware camelCase ↔ snake_case
|
|
271
328
|
* - DateSerializePlugin: Date ↔ SQLite text serialization
|
|
329
|
+
* - BooleanDeserializePlugin: boolean-mode columns read back as booleans
|
|
272
330
|
*
|
|
273
331
|
* When camelCase is false, SchemaPlugin is omitted.
|
|
274
332
|
*/
|
|
@@ -278,11 +336,97 @@ function createDrizzlePlugins(schema, camelCase = true) {
|
|
|
278
336
|
plugins.push(new DrizzleDefaultsPlugin(schema));
|
|
279
337
|
if (camelCase) plugins.push(new SchemaPlugin(schema));
|
|
280
338
|
plugins.push(new DateSerializePlugin(schema));
|
|
339
|
+
plugins.push(new BooleanDeserializePlugin(schema));
|
|
281
340
|
return plugins;
|
|
282
341
|
}
|
|
283
342
|
|
|
284
343
|
//#endregion
|
|
285
344
|
//#region src/db/kysely.ts
|
|
345
|
+
const MAX_BOUND_PARAMETERS = 100;
|
|
346
|
+
/**
|
|
347
|
+
* workerd has no boolean binding type and silently stringifies JS booleans
|
|
348
|
+
* (storing TEXT 'true' in an INTEGER column); node:sqlite rejects them
|
|
349
|
+
* outright. Normalize to SQLite's 1/0 convention before the value reaches
|
|
350
|
+
* either. `undefined` → NULL for the same reason.
|
|
351
|
+
*/
|
|
352
|
+
function normalizeParameter(value) {
|
|
353
|
+
if (typeof value === "boolean") return value ? 1 : 0;
|
|
354
|
+
if (value === void 0) return null;
|
|
355
|
+
return value;
|
|
356
|
+
}
|
|
357
|
+
function escapeLiteral(value) {
|
|
358
|
+
if (value === null || value === void 0) return "NULL";
|
|
359
|
+
if (typeof value === "boolean") return value ? "1" : "0";
|
|
360
|
+
if (typeof value === "number") {
|
|
361
|
+
if (!Number.isFinite(value)) throw new Error(`[db] Cannot inline non-finite number parameter (${value})`);
|
|
362
|
+
return String(value);
|
|
363
|
+
}
|
|
364
|
+
if (typeof value === "bigint") return value.toString();
|
|
365
|
+
if (typeof value === "string") {
|
|
366
|
+
if (value.includes("\0")) throw new Error("[db] Cannot inline a string parameter containing a NUL byte");
|
|
367
|
+
return `'${value.replaceAll("'", "''")}'`;
|
|
368
|
+
}
|
|
369
|
+
if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {
|
|
370
|
+
const bytes = value instanceof ArrayBuffer ? new Uint8Array(value) : new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
|
|
371
|
+
let hex = "";
|
|
372
|
+
for (const b of bytes) hex += b.toString(16).padStart(2, "0");
|
|
373
|
+
return `X'${hex}'`;
|
|
374
|
+
}
|
|
375
|
+
throw new Error(`[db] Cannot inline SQL parameter of type ${typeof value}`);
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* Replace each `?` placeholder in `sql` with the escaped literal of its
|
|
379
|
+
* parameter. A real scanner, not a regex: '…' string literals ('' escapes),
|
|
380
|
+
* "…" quoted identifiers, `--` line comments and C-style block comments are
|
|
381
|
+
* skipped, so a `?` inside any of them is never touched.
|
|
382
|
+
*
|
|
383
|
+
* Exported for tests.
|
|
384
|
+
*/
|
|
385
|
+
function inlineParameters(sql$1, parameters) {
|
|
386
|
+
let out = "";
|
|
387
|
+
let p = 0;
|
|
388
|
+
for (let i = 0; i < sql$1.length; i++) {
|
|
389
|
+
const ch = sql$1[i];
|
|
390
|
+
if (ch === "'" || ch === "\"") {
|
|
391
|
+
let j = i + 1;
|
|
392
|
+
while (j < sql$1.length) {
|
|
393
|
+
if (sql$1[j] === ch) {
|
|
394
|
+
if (sql$1[j + 1] === ch) {
|
|
395
|
+
j += 2;
|
|
396
|
+
continue;
|
|
397
|
+
}
|
|
398
|
+
break;
|
|
399
|
+
}
|
|
400
|
+
j++;
|
|
401
|
+
}
|
|
402
|
+
out += sql$1.slice(i, j + 1);
|
|
403
|
+
i = j;
|
|
404
|
+
continue;
|
|
405
|
+
}
|
|
406
|
+
if (ch === "-" && sql$1[i + 1] === "-") {
|
|
407
|
+
let j = sql$1.indexOf("\n", i);
|
|
408
|
+
if (j === -1) j = sql$1.length;
|
|
409
|
+
out += sql$1.slice(i, j);
|
|
410
|
+
i = j - 1;
|
|
411
|
+
continue;
|
|
412
|
+
}
|
|
413
|
+
if (ch === "/" && sql$1[i + 1] === "*") {
|
|
414
|
+
let j = sql$1.indexOf("*/", i + 2);
|
|
415
|
+
j = j === -1 ? sql$1.length : j + 2;
|
|
416
|
+
out += sql$1.slice(i, j);
|
|
417
|
+
i = j - 1;
|
|
418
|
+
continue;
|
|
419
|
+
}
|
|
420
|
+
if (ch === "?") {
|
|
421
|
+
if (p >= parameters.length) throw new Error("[db] Query has more `?` placeholders than parameters while inlining");
|
|
422
|
+
out += escapeLiteral(parameters[p++]);
|
|
423
|
+
continue;
|
|
424
|
+
}
|
|
425
|
+
out += ch;
|
|
426
|
+
}
|
|
427
|
+
if (p !== parameters.length) throw new Error(`[db] Inlined ${p} parameter(s) but the query provided ${parameters.length} — placeholder/parameter mismatch`);
|
|
428
|
+
return out;
|
|
429
|
+
}
|
|
286
430
|
/**
|
|
287
431
|
* A Kysely driver that uses Cloudflare DO SQLite storage
|
|
288
432
|
*/
|
|
@@ -331,7 +475,12 @@ var CloudflareSqliteConnection = class {
|
|
|
331
475
|
this.sql = sql$1;
|
|
332
476
|
}
|
|
333
477
|
async executeQuery(compiledQuery) {
|
|
334
|
-
|
|
478
|
+
let queryStr = compiledQuery.sql;
|
|
479
|
+
let parameters = compiledQuery.parameters.map(normalizeParameter);
|
|
480
|
+
if (parameters.length > MAX_BOUND_PARAMETERS) {
|
|
481
|
+
queryStr = inlineParameters(queryStr, parameters);
|
|
482
|
+
parameters = [];
|
|
483
|
+
}
|
|
335
484
|
const isSelect = /^\s*(SELECT|RETURNING)/i.test(queryStr) || /\s+RETURNING\s+/i.test(queryStr);
|
|
336
485
|
try {
|
|
337
486
|
if (isSelect) return {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import "../debug-DmBrUmwe.js";
|
|
2
2
|
import "../snapshot-DMW6j2Ix.js";
|
|
3
|
-
import { a as loadMigrationFiles, c as parseSqlMigration, i as generateMigrationName, l as saveSnapshot, n as generateCreateTableSQL, o as loadSchemaModule, r as generateMigration, s as loadSnapshot, t as buildAndLoadSchema } from "../generator-
|
|
3
|
+
import { a as loadMigrationFiles, c as parseSqlMigration, i as generateMigrationName, l as saveSnapshot, n as generateCreateTableSQL, o as loadSchemaModule, r as generateMigration, s as loadSnapshot, t as buildAndLoadSchema } from "../generator-KHBZaOI1.js";
|
|
4
4
|
|
|
5
5
|
export { buildAndLoadSchema, generateCreateTableSQL, generateMigration, generateMigrationName, loadMigrationFiles, loadSchemaModule, loadSnapshot, parseSqlMigration, saveSnapshot };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { i as init_debug, t as debugCli } from "./debug-DmBrUmwe.js";
|
|
2
2
|
import * as fs from "node:fs";
|
|
3
|
-
import * as path from "node:path";
|
|
3
|
+
import * as path$1 from "node:path";
|
|
4
4
|
import { parse } from "@babel/parser";
|
|
5
5
|
import _traverse from "@babel/traverse";
|
|
6
6
|
import _generate from "@babel/generator";
|
|
@@ -48,7 +48,7 @@ function resolveFileCandidate(candidate) {
|
|
|
48
48
|
"index.js",
|
|
49
49
|
"index.jsx"
|
|
50
50
|
]) {
|
|
51
|
-
const indexPath = path.join(candidate, indexFile);
|
|
51
|
+
const indexPath = path$1.join(candidate, indexFile);
|
|
52
52
|
if (fs.existsSync(indexPath)) return indexPath;
|
|
53
53
|
}
|
|
54
54
|
return null;
|
|
@@ -78,7 +78,7 @@ function applyAliases(importSource, aliases) {
|
|
|
78
78
|
for (const entry of aliases) {
|
|
79
79
|
if (!matchesAlias(entry.find, importSource)) continue;
|
|
80
80
|
const replaced = importSource.replace(entry.find, entry.replacement);
|
|
81
|
-
if (!path.isAbsolute(replaced)) continue;
|
|
81
|
+
if (!path$1.isAbsolute(replaced)) continue;
|
|
82
82
|
const resolved = resolveFileCandidate(replaced);
|
|
83
83
|
if (resolved) return resolved;
|
|
84
84
|
}
|
|
@@ -96,7 +96,7 @@ const viteAliasCache = /* @__PURE__ */ new Map();
|
|
|
96
96
|
* resolution, which never needs aliases anyway.
|
|
97
97
|
*/
|
|
98
98
|
async function loadViteAliases(root) {
|
|
99
|
-
const key = path.resolve(root);
|
|
99
|
+
const key = path$1.resolve(root);
|
|
100
100
|
const cached = viteAliasCache.get(key);
|
|
101
101
|
if (cached) return cached;
|
|
102
102
|
let aliases = [];
|
|
@@ -132,7 +132,7 @@ const warnedMissingDirs = /* @__PURE__ */ new Set();
|
|
|
132
132
|
*/
|
|
133
133
|
function discoverDatabaseFiles(options) {
|
|
134
134
|
const { projectRoot, databasesDir } = options;
|
|
135
|
-
const absoluteDir = path.join(projectRoot, databasesDir);
|
|
135
|
+
const absoluteDir = path$1.join(projectRoot, databasesDir);
|
|
136
136
|
if (!fs.existsSync(absoluteDir)) {
|
|
137
137
|
if (!warnedMissingDirs.has(absoluteDir)) {
|
|
138
138
|
warnedMissingDirs.add(absoluteDir);
|
|
@@ -147,9 +147,9 @@ function discoverDatabaseFiles(options) {
|
|
|
147
147
|
if (file.endsWith(".d.ts")) continue;
|
|
148
148
|
if (file === "schema.ts") continue;
|
|
149
149
|
if (file.startsWith("_")) continue;
|
|
150
|
-
const absolutePath = path.join(absoluteDir, file);
|
|
151
|
-
const relativePath = path.join(databasesDir, file);
|
|
152
|
-
const name = path.basename(file, ".ts");
|
|
150
|
+
const absolutePath = path$1.join(absoluteDir, file);
|
|
151
|
+
const relativePath = path$1.join(databasesDir, file);
|
|
152
|
+
const name = path$1.basename(file, ".ts");
|
|
153
153
|
results.push({
|
|
154
154
|
absolutePath,
|
|
155
155
|
relativePath,
|
|
@@ -176,13 +176,13 @@ function discoverDatabaseFiles(options) {
|
|
|
176
176
|
*/
|
|
177
177
|
function discoverActionFiles(options) {
|
|
178
178
|
const { projectRoot, databasesDir } = options;
|
|
179
|
-
const absoluteDir = path.join(projectRoot, databasesDir);
|
|
179
|
+
const absoluteDir = path$1.join(projectRoot, databasesDir);
|
|
180
180
|
if (!fs.existsSync(absoluteDir)) return [];
|
|
181
181
|
const results = [];
|
|
182
182
|
const walk = (dir) => {
|
|
183
183
|
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
184
184
|
if (entry.name.startsWith("_") || entry.name === "node_modules") continue;
|
|
185
|
-
const full = path.join(dir, entry.name);
|
|
185
|
+
const full = path$1.join(dir, entry.name);
|
|
186
186
|
if (entry.isDirectory()) {
|
|
187
187
|
walk(full);
|
|
188
188
|
continue;
|
|
@@ -212,8 +212,8 @@ function discoverActionFiles(options) {
|
|
|
212
212
|
*/
|
|
213
213
|
function resolveImportPath(fromFile, importSource, aliases) {
|
|
214
214
|
if (importSource.startsWith(".")) {
|
|
215
|
-
const dir = path.dirname(fromFile);
|
|
216
|
-
return resolveFileCandidate(path.resolve(dir, importSource));
|
|
215
|
+
const dir = path$1.dirname(fromFile);
|
|
216
|
+
return resolveFileCandidate(path$1.resolve(dir, importSource));
|
|
217
217
|
}
|
|
218
218
|
return applyAliases(importSource, aliases);
|
|
219
219
|
}
|
|
@@ -269,7 +269,7 @@ function parseDatabaseFile(filePath, code, options = {}) {
|
|
|
269
269
|
localImports: /* @__PURE__ */ new Map()
|
|
270
270
|
};
|
|
271
271
|
let actionFnName = null;
|
|
272
|
-
let currentDatabaseName = path.basename(filePath).replace(/\.(ts|js)$/, "");
|
|
272
|
+
let currentDatabaseName = path$1.basename(filePath).replace(/\.(ts|js)$/, "");
|
|
273
273
|
traverse(ast, {
|
|
274
274
|
ImportDeclaration(nodePath) {
|
|
275
275
|
const source = nodePath.node.source.value;
|
|
@@ -338,7 +338,7 @@ function extractActionFactoryName(pattern) {
|
|
|
338
338
|
* that can't be statically analyzed.
|
|
339
339
|
*/
|
|
340
340
|
function warnNonLiteral(filePath, key, defaultValue) {
|
|
341
|
-
console.warn(`[durable-db] '${key}' in defineDatabase() must be a static literal for build-time analysis. Got a dynamic expression in ${path.basename(filePath)} — defaulting to '${defaultValue}'.`);
|
|
341
|
+
console.warn(`[durable-db] '${key}' in defineDatabase() must be a static literal for build-time analysis. Got a dynamic expression in ${path$1.basename(filePath)} — defaulting to '${defaultValue}'.`);
|
|
342
342
|
}
|
|
343
343
|
/**
|
|
344
344
|
* Extract database configuration from a defineDatabase() call
|
|
@@ -376,7 +376,7 @@ function extractDatabaseInfo(declaratorPath, callExpr, filePath, imports) {
|
|
|
376
376
|
}
|
|
377
377
|
}
|
|
378
378
|
}
|
|
379
|
-
const name = path.basename(filePath).replace(/\.(ts|js)$/, "");
|
|
379
|
+
const name = path$1.basename(filePath).replace(/\.(ts|js)$/, "");
|
|
380
380
|
return {
|
|
381
381
|
filePath,
|
|
382
382
|
name,
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { i as init_debug, t as debugCli } from "./debug-DmBrUmwe.js";
|
|
2
|
-
import { d as init_state, f as loadDevMigrations, h as saveDevMigration, n as clearDevMigrations } from "./state-
|
|
2
|
+
import { d as init_state, f as loadDevMigrations, h as saveDevMigration, n as clearDevMigrations } from "./state-DtZ70cBR.js";
|
|
3
3
|
import { n as generateMigrationStatements, o as snapshotsEqual, r as generateSnapshotFromSchema } from "./snapshot-DMW6j2Ix.js";
|
|
4
|
-
import { s as loadSnapshot, t as buildAndLoadSchema } from "./generator-
|
|
5
|
-
import { a as readFile, i as discoverDatabaseFiles, n as parseDatabaseFile, o as resolveImportPath, s as loadViteAliases } from "./parser-
|
|
6
|
-
import * as path from "node:path";
|
|
4
|
+
import { s as loadSnapshot, t as buildAndLoadSchema } from "./generator-KHBZaOI1.js";
|
|
5
|
+
import { a as readFile, i as discoverDatabaseFiles, n as parseDatabaseFile, o as resolveImportPath, s as loadViteAliases } from "./parser-CL3Nlmsy.js";
|
|
6
|
+
import * as path$1 from "node:path";
|
|
7
7
|
import * as crypto from "node:crypto";
|
|
8
8
|
|
|
9
9
|
//#region src/cli/shared.ts
|
|
@@ -38,7 +38,7 @@ function discoverDatabases(opts) {
|
|
|
38
38
|
const parsed = parseDatabaseFile(file.absolutePath, code);
|
|
39
39
|
if (!parsed.database) continue;
|
|
40
40
|
if (database && parsed.database.name !== database) continue;
|
|
41
|
-
parsed.database.migrationsDir = path.resolve(projectRoot, migrationsDir, parsed.database.name);
|
|
41
|
+
parsed.database.migrationsDir = path$1.resolve(projectRoot, migrationsDir, parsed.database.name);
|
|
42
42
|
databases.push(parsed.database);
|
|
43
43
|
}
|
|
44
44
|
return databases;
|
|
@@ -62,7 +62,7 @@ async function loadSchema(db, projectRoot) {
|
|
|
62
62
|
debugCli("Skipping %s: no schema defined", db.name);
|
|
63
63
|
return null;
|
|
64
64
|
}
|
|
65
|
-
if (!db.schemaImport) throw new Error(`[db] Database '${db.name}' declares ${db.schemaTableNames.length} schema table(s) (${db.schemaTableNames.join(", ")}) but none of them are imported from a schema module. Tables defined inline in ${path.basename(db.filePath)} cannot be loaded for migration generation — move them to a schema file (e.g. src/databases/schema.ts) and import them.`);
|
|
65
|
+
if (!db.schemaImport) throw new Error(`[db] Database '${db.name}' declares ${db.schemaTableNames.length} schema table(s) (${db.schemaTableNames.join(", ")}) but none of them are imported from a schema module. Tables defined inline in ${path$1.basename(db.filePath)} cannot be loaded for migration generation — move them to a schema file (e.g. src/databases/schema.ts) and import them.`);
|
|
66
66
|
const aliases = projectRoot ? await loadViteAliases(projectRoot) : void 0;
|
|
67
67
|
const schemaPath = resolveImportPath(db.filePath, db.schemaImport, aliases);
|
|
68
68
|
if (!schemaPath) throw new Error(`[db] Database '${db.name}': could not resolve schema import '${db.schemaImport}' from ${db.filePath}.` + (db.schemaImport.startsWith(".") ? "" : ` '${db.schemaImport}' looks like an alias — ensure it's defined in the project's Vite config (resolve.alias / tsconfig paths wired into Vite).`));
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { a as __esmMin, i as init_debug, o as __export, t as debugCli } from "./debug-DmBrUmwe.js";
|
|
2
2
|
import * as fs from "node:fs";
|
|
3
|
-
import * as path from "node:path";
|
|
3
|
+
import * as path$1 from "node:path";
|
|
4
4
|
|
|
5
5
|
//#region src/cli/state.ts
|
|
6
6
|
var state_exports = /* @__PURE__ */ __export({
|
|
@@ -26,25 +26,25 @@ var state_exports = /* @__PURE__ */ __export({
|
|
|
26
26
|
*/
|
|
27
27
|
function findNodeModules(projectRoot) {
|
|
28
28
|
let current = projectRoot;
|
|
29
|
-
while (current !== path.dirname(current)) {
|
|
30
|
-
const nodeModules = path.join(current, "node_modules");
|
|
29
|
+
while (current !== path$1.dirname(current)) {
|
|
30
|
+
const nodeModules = path$1.join(current, "node_modules");
|
|
31
31
|
if (fs.existsSync(nodeModules)) return nodeModules;
|
|
32
|
-
current = path.dirname(current);
|
|
32
|
+
current = path$1.dirname(current);
|
|
33
33
|
}
|
|
34
|
-
return path.join(projectRoot, "node_modules");
|
|
34
|
+
return path$1.join(projectRoot, "node_modules");
|
|
35
35
|
}
|
|
36
36
|
/**
|
|
37
37
|
* Get all dev-related paths for a project
|
|
38
38
|
*/
|
|
39
39
|
function getDevPaths(projectRoot) {
|
|
40
40
|
const nodeModules = findNodeModules(projectRoot);
|
|
41
|
-
const cacheDir = path.join(nodeModules, CACHE_DIR_NAME);
|
|
41
|
+
const cacheDir = path$1.join(nodeModules, CACHE_DIR_NAME);
|
|
42
42
|
return {
|
|
43
43
|
cacheDir,
|
|
44
|
-
stateFile: path.join(cacheDir, STATE_FILE_NAME),
|
|
45
|
-
databaseDir: (dbName) => path.join(cacheDir, "databases", dbName),
|
|
46
|
-
migrationsDir: (dbName) => path.join(cacheDir, "databases", dbName, DEV_MIGRATIONS_DIR),
|
|
47
|
-
snapshotFile: (dbName) => path.join(cacheDir, "databases", dbName, DEV_SNAPSHOT_FILE)
|
|
44
|
+
stateFile: path$1.join(cacheDir, STATE_FILE_NAME),
|
|
45
|
+
databaseDir: (dbName) => path$1.join(cacheDir, "databases", dbName),
|
|
46
|
+
migrationsDir: (dbName) => path$1.join(cacheDir, "databases", dbName, DEV_MIGRATIONS_DIR),
|
|
47
|
+
snapshotFile: (dbName) => path$1.join(cacheDir, "databases", dbName, DEV_SNAPSHOT_FILE)
|
|
48
48
|
};
|
|
49
49
|
}
|
|
50
50
|
/**
|
|
@@ -81,7 +81,7 @@ function loadDevState(projectRoot) {
|
|
|
81
81
|
*/
|
|
82
82
|
function saveDevState(projectRoot, state) {
|
|
83
83
|
const paths = getDevPaths(projectRoot);
|
|
84
|
-
fs.mkdirSync(path.dirname(paths.stateFile), { recursive: true });
|
|
84
|
+
fs.mkdirSync(path$1.dirname(paths.stateFile), { recursive: true });
|
|
85
85
|
fs.writeFileSync(paths.stateFile, JSON.stringify(state, null, 2));
|
|
86
86
|
}
|
|
87
87
|
/**
|
|
@@ -112,7 +112,7 @@ function loadDevMigrations(projectRoot, dbName) {
|
|
|
112
112
|
const files = fs.readdirSync(migrationsDir).filter((f) => f.endsWith(".sql")).sort();
|
|
113
113
|
for (const file of files) {
|
|
114
114
|
const name = file.replace(".sql", "");
|
|
115
|
-
const chunks = parseSqlMigration(fs.readFileSync(path.join(migrationsDir, file), "utf-8"));
|
|
115
|
+
const chunks = parseSqlMigration(fs.readFileSync(path$1.join(migrationsDir, file), "utf-8"));
|
|
116
116
|
if (chunks.length > 0) migrations.set(name, chunks);
|
|
117
117
|
}
|
|
118
118
|
return migrations;
|
|
@@ -123,7 +123,7 @@ function loadDevMigrations(projectRoot, dbName) {
|
|
|
123
123
|
function saveDevMigration(projectRoot, dbName, name, statements) {
|
|
124
124
|
const migrationsDir = getDevPaths(projectRoot).migrationsDir(dbName);
|
|
125
125
|
fs.mkdirSync(migrationsDir, { recursive: true });
|
|
126
|
-
const filePath = path.join(migrationsDir, `${name}.sql`);
|
|
126
|
+
const filePath = path$1.join(migrationsDir, `${name}.sql`);
|
|
127
127
|
const content = statements.map((s) => s.endsWith(";") ? s : `${s};`).join("\n\n");
|
|
128
128
|
fs.writeFileSync(filePath, content);
|
|
129
129
|
return name;
|
|
@@ -166,7 +166,7 @@ function loadDevSnapshot(projectRoot, dbName) {
|
|
|
166
166
|
*/
|
|
167
167
|
function saveDevSnapshot(projectRoot, dbName, snapshot) {
|
|
168
168
|
const snapshotFile = getDevPaths(projectRoot).snapshotFile(dbName);
|
|
169
|
-
fs.mkdirSync(path.dirname(snapshotFile), { recursive: true });
|
|
169
|
+
fs.mkdirSync(path$1.dirname(snapshotFile), { recursive: true });
|
|
170
170
|
fs.writeFileSync(snapshotFile, JSON.stringify(snapshot, null, 2));
|
|
171
171
|
}
|
|
172
172
|
/**
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import "./debug-DmBrUmwe.js";
|
|
2
|
-
import { _ as saveDevState, a as generateEpoch, c as getDevPaths, d as init_state, f as loadDevMigrations, g as saveDevSnapshot, h as saveDevMigration, i as findNodeModules, l as getInstanceKey, m as loadDevState, n as clearDevMigrations, o as getDatabaseDevState, p as loadDevSnapshot, r as createEmptyDevState, s as getDevEpoch, t as clearDatabaseDevState, u as hasProdSnapshotChanged } from "./state-
|
|
2
|
+
import { _ as saveDevState, a as generateEpoch, c as getDevPaths, d as init_state, f as loadDevMigrations, g as saveDevSnapshot, h as saveDevMigration, i as findNodeModules, l as getInstanceKey, m as loadDevState, n as clearDevMigrations, o as getDatabaseDevState, p as loadDevSnapshot, r as createEmptyDevState, s as getDevEpoch, t as clearDatabaseDevState, u as hasProdSnapshotChanged } from "./state-DtZ70cBR.js";
|
|
3
3
|
|
|
4
4
|
init_state();
|
|
5
5
|
export { loadDevMigrations };
|
package/dist/testing/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import "../debug-DmBrUmwe.js";
|
|
2
2
|
import { t as type } from "../arktypeConfig-CTCJm4vA.js";
|
|
3
3
|
import { t as ACTION_TEST_META } from "../defineDatabase-BD3k1L7d.js";
|
|
4
|
-
import "../state-
|
|
5
|
-
import { a as setTenantIdResolver } from "../context-
|
|
6
|
-
import { t as createKyselyFromSql } from "../kysely-
|
|
4
|
+
import "../state-DtZ70cBR.js";
|
|
5
|
+
import { a as setTenantIdResolver } from "../context-DbGqDnBa.js";
|
|
6
|
+
import { t as createKyselyFromSql } from "../kysely-BH7QZBZw.js";
|
|
7
7
|
import { n as generateMigrationStatements, r as generateSnapshotFromSchema, t as createEmptySnapshot } from "../snapshot-DMW6j2Ix.js";
|
|
8
8
|
import { createRequire } from "node:module";
|
|
9
9
|
|
package/dist/vite/durableDb.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { i as init_debug, r as debugVite } from "../debug-DmBrUmwe.js";
|
|
2
|
-
import { _ as saveDevState, c as getDevPaths, d as init_state, m as loadDevState } from "../state-
|
|
2
|
+
import { _ as saveDevState, c as getDevPaths, d as init_state, m as loadDevState } from "../state-DtZ70cBR.js";
|
|
3
3
|
import "../snapshot-DMW6j2Ix.js";
|
|
4
|
-
import { a as loadMigrationFiles } from "../generator-
|
|
5
|
-
import { a as readFile, i as discoverDatabaseFiles, n as parseDatabaseFile, r as discoverActionFiles, t as BABEL_PARSER_PLUGINS } from "../parser-
|
|
4
|
+
import { a as loadMigrationFiles } from "../generator-KHBZaOI1.js";
|
|
5
|
+
import { a as readFile, i as discoverDatabaseFiles, n as parseDatabaseFile, r as discoverActionFiles, t as BABEL_PARSER_PLUGINS } from "../parser-CL3Nlmsy.js";
|
|
6
6
|
import * as fs from "node:fs";
|
|
7
|
-
import * as path from "node:path";
|
|
7
|
+
import * as path$1 from "node:path";
|
|
8
|
+
import path from "node:path";
|
|
8
9
|
import { parse } from "@babel/parser";
|
|
9
10
|
import _generate from "@babel/generator";
|
|
10
11
|
import * as t from "@babel/types";
|
|
@@ -16,7 +17,7 @@ init_debug();
|
|
|
16
17
|
*/
|
|
17
18
|
function findWranglerConfig(projectRoot) {
|
|
18
19
|
for (const candidate of ["wrangler.jsonc", "wrangler.json"]) {
|
|
19
|
-
const configPath = path.join(projectRoot, candidate);
|
|
20
|
+
const configPath = path$1.join(projectRoot, candidate);
|
|
20
21
|
if (fs.existsSync(configPath)) return configPath;
|
|
21
22
|
}
|
|
22
23
|
return null;
|
|
@@ -133,12 +134,12 @@ function patchWranglerConfig(projectRoot, databases) {
|
|
|
133
134
|
const backupPath = configPath + ".backup";
|
|
134
135
|
if (!fs.existsSync(backupPath)) {
|
|
135
136
|
fs.writeFileSync(backupPath, content, "utf-8");
|
|
136
|
-
debugVite("Original %s contained comments that will be lost during patching. Backup saved to %s", path.basename(configPath), path.basename(backupPath));
|
|
137
|
+
debugVite("Original %s contained comments that will be lost during patching. Backup saved to %s", path$1.basename(configPath), path$1.basename(backupPath));
|
|
137
138
|
}
|
|
138
139
|
}
|
|
139
140
|
const newContent = JSON.stringify(config, null, 2);
|
|
140
141
|
fs.writeFileSync(configPath, newContent, "utf-8");
|
|
141
|
-
debugVite("Updated %s with DO bindings", path.basename(configPath));
|
|
142
|
+
debugVite("Updated %s with DO bindings", path$1.basename(configPath));
|
|
142
143
|
}
|
|
143
144
|
return {
|
|
144
145
|
modified,
|
|
@@ -218,7 +219,7 @@ function checkWranglerConfig(projectRoot, databases) {
|
|
|
218
219
|
missingBindings: [],
|
|
219
220
|
missingSqliteClasses: [],
|
|
220
221
|
ok: true,
|
|
221
|
-
tomlOnly: !configPath && fs.existsSync(path.join(projectRoot, "wrangler.toml"))
|
|
222
|
+
tomlOnly: !configPath && fs.existsSync(path$1.join(projectRoot, "wrangler.toml"))
|
|
222
223
|
};
|
|
223
224
|
let config = {};
|
|
224
225
|
if (configPath) try {
|
|
@@ -240,7 +241,7 @@ function checkWranglerConfig(projectRoot, databases) {
|
|
|
240
241
|
}] }
|
|
241
242
|
}, null, 2);
|
|
242
243
|
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
|
+
const where = configPath ? path$1.basename(configPath) : hasToml ? "wrangler.toml (not supported — only wrangler.jsonc/json can be verified or patched)" : "wrangler.jsonc";
|
|
244
245
|
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
|
}
|
|
246
247
|
return result;
|
|
@@ -326,6 +327,36 @@ function buildBindingNamesObject(databases) {
|
|
|
326
327
|
const properties = databases.map((db) => t.objectProperty(t.stringLiteral(db.name), t.stringLiteral(db.bindingName)));
|
|
327
328
|
return t.objectExpression(properties);
|
|
328
329
|
}
|
|
330
|
+
/**
|
|
331
|
+
* Local identifier for a schema table imported into the generated module —
|
|
332
|
+
* aliased so it can never collide with anything else in scope.
|
|
333
|
+
*/
|
|
334
|
+
function schemaLocalName(db, tableName) {
|
|
335
|
+
const safe = (s) => s.replace(/[^A-Za-z0-9_$]/g, "_");
|
|
336
|
+
return `__schema_${safe(db.name)}_${safe(tableName)}`;
|
|
337
|
+
}
|
|
338
|
+
function hasSchema(db) {
|
|
339
|
+
return !!db.schemaImport && db.schemaTableNames.length > 0;
|
|
340
|
+
}
|
|
341
|
+
/**
|
|
342
|
+
* Import declaration bringing a database's schema tables into the generated
|
|
343
|
+
* module, so the DO class can carry `schema = { … }` and build its Kysely with
|
|
344
|
+
* the full schema-aware plugin chain (exact column mapping, defaults, date and
|
|
345
|
+
* boolean deserialization) — the same plugins app code gets everywhere else.
|
|
346
|
+
* Relative specifiers are resolved against the database file (the generated
|
|
347
|
+
* module lives at a virtual id, not next to the user's code); aliases and
|
|
348
|
+
* package specifiers pass through for Vite to resolve.
|
|
349
|
+
*/
|
|
350
|
+
function buildSchemaImport(db) {
|
|
351
|
+
const source = db.schemaImport.startsWith(".") ? path.resolve(path.dirname(db.filePath), db.schemaImport) : db.schemaImport;
|
|
352
|
+
return createNamedImport(db.schemaTableNames.map((tableName) => ({
|
|
353
|
+
imported: tableName,
|
|
354
|
+
local: schemaLocalName(db, tableName)
|
|
355
|
+
})), source);
|
|
356
|
+
}
|
|
357
|
+
function buildSchemaProperty(db) {
|
|
358
|
+
return t.classProperty(t.identifier("schema"), t.objectExpression(db.schemaTableNames.map((tableName) => t.objectProperty(t.identifier(tableName), t.identifier(schemaLocalName(db, tableName))))));
|
|
359
|
+
}
|
|
329
360
|
function buildDbTransportsObject(databases) {
|
|
330
361
|
const properties = databases.map((db) => t.objectProperty(t.stringLiteral(db.name), t.stringLiteral(db.transport)));
|
|
331
362
|
return t.objectExpression(properties);
|
|
@@ -348,7 +379,8 @@ function generateDurableObjectsModule(databases, registryImport, isDev = false,
|
|
|
348
379
|
const imports = [
|
|
349
380
|
createNamedImport(["SqliteDurableObject", "type"], "durable-db/db"),
|
|
350
381
|
createNamedImport(["getAction", "runWithDoContext"], registryImport),
|
|
351
|
-
...actionFiles.map((file) => t.importDeclaration([], t.stringLiteral(file)))
|
|
382
|
+
...actionFiles.map((file) => t.importDeclaration([], t.stringLiteral(file))),
|
|
383
|
+
...databases.filter(hasSchema).map(buildSchemaImport)
|
|
352
384
|
];
|
|
353
385
|
if (anyBrowsable) imports.push(createNamedImport(["Browsable"], "@outerbase/browsable-durable-object"));
|
|
354
386
|
if (anyWebSocket) imports.push(createNamedImport(["decodeRequest", "encodeResponse"], "durable-db/transport/protocol"));
|
|
@@ -384,14 +416,15 @@ function buildDurableObjectStatements(db, bindingNamesExpr, dbTransportsExpr, is
|
|
|
384
416
|
const isBrowsable = db.browsable === true || db.browsable === "development" && isDev;
|
|
385
417
|
const rpcMethod = buildRpcMethod(db, bindingNamesExpr, dbTransportsExpr);
|
|
386
418
|
const migrationsProperty = t.classProperty(t.identifier("migrations"), buildMigrationsObject(db.migrations));
|
|
419
|
+
const dataProperties = hasSchema(db) ? [migrationsProperty, buildSchemaProperty(db)] : [migrationsProperty];
|
|
387
420
|
const classMethods = [rpcMethod, buildSysMethod()];
|
|
388
421
|
if (db.transport === "websocket") classMethods.push(buildWebSocketMessageMethod(db, bindingNamesExpr, dbTransportsExpr));
|
|
389
422
|
if (!isBrowsable) {
|
|
390
|
-
const classDecl$1 = t.classDeclaration(t.identifier(db.className), t.identifier("SqliteDurableObject"), t.classBody([
|
|
423
|
+
const classDecl$1 = t.classDeclaration(t.identifier(db.className), t.identifier("SqliteDurableObject"), t.classBody([...dataProperties, ...classMethods]));
|
|
391
424
|
return [t.exportNamedDeclaration(classDecl$1)];
|
|
392
425
|
}
|
|
393
426
|
const baseName = `_${db.className}_Base`;
|
|
394
|
-
const innerClass = t.classExpression(null, t.identifier("SqliteDurableObject"), t.classBody([
|
|
427
|
+
const innerClass = t.classExpression(null, t.identifier("SqliteDurableObject"), t.classBody([...dataProperties]));
|
|
395
428
|
const browsableWrapped = t.callExpression(t.callExpression(t.identifier("Browsable"), []), [innerClass]);
|
|
396
429
|
const baseDecl = t.variableDeclaration("const", [t.variableDeclarator(t.identifier(baseName), browsableWrapped)]);
|
|
397
430
|
const classDecl = t.classDeclaration(t.identifier(db.className), t.identifier(baseName), t.classBody([
|
|
@@ -800,25 +833,25 @@ var PluginState = class {
|
|
|
800
833
|
return Date.now() <= this.selfDevStateWriteUntil;
|
|
801
834
|
}
|
|
802
835
|
registerDatabaseFile(filePath, dbName) {
|
|
803
|
-
const abs = path.normalize(filePath);
|
|
836
|
+
const abs = path$1.normalize(filePath);
|
|
804
837
|
this.databaseFilePaths.set(abs, dbName);
|
|
805
838
|
if (this.projectRoot) {
|
|
806
|
-
const rel = path.relative(this.projectRoot, abs);
|
|
807
|
-
this.databaseFilePaths.set(path.normalize(rel), dbName);
|
|
839
|
+
const rel = path$1.relative(this.projectRoot, abs);
|
|
840
|
+
this.databaseFilePaths.set(path$1.normalize(rel), dbName);
|
|
808
841
|
}
|
|
809
842
|
}
|
|
810
843
|
getDatabaseNameForPath(filePath) {
|
|
811
|
-
const normalized = path.normalize(filePath);
|
|
844
|
+
const normalized = path$1.normalize(filePath);
|
|
812
845
|
const direct = this.databaseFilePaths.get(normalized);
|
|
813
846
|
if (direct) return direct;
|
|
814
847
|
if (this.projectRoot) {
|
|
815
|
-
const rel = path.relative(this.projectRoot, normalized);
|
|
816
|
-
return this.databaseFilePaths.get(path.normalize(rel));
|
|
848
|
+
const rel = path$1.relative(this.projectRoot, normalized);
|
|
849
|
+
return this.databaseFilePaths.get(path$1.normalize(rel));
|
|
817
850
|
}
|
|
818
851
|
}
|
|
819
852
|
registerAction(action, dbName, sourceFile) {
|
|
820
853
|
action.databaseName = dbName;
|
|
821
|
-
action.sourceFile = path.relative(this.projectRoot, sourceFile);
|
|
854
|
+
action.sourceFile = path$1.relative(this.projectRoot, sourceFile);
|
|
822
855
|
this.actions.set(`${dbName}:${action.exportName}`, action);
|
|
823
856
|
}
|
|
824
857
|
reset() {
|
|
@@ -843,7 +876,7 @@ var PluginState = class {
|
|
|
843
876
|
const code = readFile(file.absolutePath);
|
|
844
877
|
const parsed = parseDatabaseFile(file.absolutePath, code, { aliases: this.aliases });
|
|
845
878
|
if (parsed.database) {
|
|
846
|
-
parsed.database.migrationsDir = path.resolve(this.projectRoot, this.options.migrationsDir, parsed.database.name);
|
|
879
|
+
parsed.database.migrationsDir = path$1.resolve(this.projectRoot, this.options.migrationsDir, parsed.database.name);
|
|
847
880
|
this.databases.set(parsed.database.name, parsed.database);
|
|
848
881
|
this.registerDatabaseFile(file.absolutePath, parsed.database.name);
|
|
849
882
|
await this.loadMigrations(parsed.database);
|
|
@@ -855,7 +888,7 @@ var PluginState = class {
|
|
|
855
888
|
if (this.options.patchWranglerConfig) patchWranglerConfig(this.projectRoot, databases);
|
|
856
889
|
else {
|
|
857
890
|
const check = checkWranglerConfig(this.projectRoot, databases);
|
|
858
|
-
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 }).`);
|
|
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 }).`);
|
|
859
892
|
}
|
|
860
893
|
}
|
|
861
894
|
this.initialized = true;
|
|
@@ -865,7 +898,7 @@ var PluginState = class {
|
|
|
865
898
|
const isDev = this.config.command === "serve";
|
|
866
899
|
db.migrations = loadMigrationFiles(migrationsDir);
|
|
867
900
|
if (isDev) try {
|
|
868
|
-
const { loadDevMigrations } = await import("../state-
|
|
901
|
+
const { loadDevMigrations } = await import("../state-vav3VCId.js");
|
|
869
902
|
const devMigrations = loadDevMigrations(this.projectRoot, db.name);
|
|
870
903
|
for (const [name, chunks] of devMigrations) db.migrations.set(`_dev_${name}`, chunks);
|
|
871
904
|
if (devMigrations.size > 0) debugVite("Loaded %d dev migration(s) for %s", devMigrations.size, db.name);
|
|
@@ -916,7 +949,7 @@ async function findImportedDatabase(resolve, state, imports, importer) {
|
|
|
916
949
|
if (info.imported !== "action") continue;
|
|
917
950
|
const resolved = await resolve(info.source, importer);
|
|
918
951
|
if (resolved) {
|
|
919
|
-
const cleanId = path.normalize(resolved.id.replace(/^\0+/, "").split("?", 1)[0]);
|
|
952
|
+
const cleanId = path$1.normalize(resolved.id.replace(/^\0+/, "").split("?", 1)[0]);
|
|
920
953
|
const dbName = state.getDatabaseNameForPath(cleanId);
|
|
921
954
|
if (dbName) return dbName;
|
|
922
955
|
}
|
|
@@ -941,9 +974,9 @@ function durableDb(options = {}) {
|
|
|
941
974
|
configureServer(server) {
|
|
942
975
|
state.devServer = server;
|
|
943
976
|
state.reset();
|
|
944
|
-
const absoluteDbDir = path.join(state.projectRoot, state.options.databasesDir);
|
|
977
|
+
const absoluteDbDir = path$1.join(state.projectRoot, state.options.databasesDir);
|
|
945
978
|
server.watcher.on("change", (file) => {
|
|
946
|
-
const normalized = path.normalize(file);
|
|
979
|
+
const normalized = path$1.normalize(file);
|
|
947
980
|
if (normalized.startsWith(absoluteDbDir) && /\.tsx?$/.test(normalized)) state.invalidateDOModule();
|
|
948
981
|
});
|
|
949
982
|
const devPaths = getDevPaths(state.projectRoot);
|
|
@@ -1012,7 +1045,7 @@ function durableDb(options = {}) {
|
|
|
1012
1045
|
if (id.startsWith("\0") || id.includes("node_modules")) return null;
|
|
1013
1046
|
if (!/\.tsx?$/.test(id)) return null;
|
|
1014
1047
|
await state.initialize();
|
|
1015
|
-
const cleanId = path.normalize(id.split("?", 1)[0]);
|
|
1048
|
+
const cleanId = path$1.normalize(id.split("?", 1)[0]);
|
|
1016
1049
|
const dbNameForPath = state.getDatabaseNameForPath(cleanId);
|
|
1017
1050
|
if (dbNameForPath) {
|
|
1018
1051
|
const database$1 = state.databases.get(dbNameForPath);
|
package/package.json
CHANGED
package/dist/push-D0zsn0Ge.js
DELETED