durable-db 0.1.13 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/arktypeConfig-DdIO8VV1.d.ts +6130 -0
- package/dist/{arktypeConfig-CTCJm4vA.js → arktypeConfig-DxP0OcV_.js} +1014 -1033
- package/dist/cli/bin.d.ts +1 -1
- package/dist/cli/bin.js +2 -10
- package/dist/cli/index.d.ts +40 -34
- package/dist/cli/index.js +4 -9
- package/dist/{cli-m2H7mQpa.js → cli-BUSZTS2D.js} +213 -49
- package/dist/context/index.d.ts +50 -2
- package/dist/context/index.js +119 -5
- package/dist/db/index.d.ts +4 -4
- package/dist/db/index.js +10 -12
- package/dist/{debug-DmBrUmwe.js → debug-Cz8KzMft.js} +23 -27
- package/dist/{defineDatabase-Bjws1Jkd.d.ts → defineDatabase-CHmTgZTx.d.ts} +4 -5
- package/dist/{defineDatabase-BD3k1L7d.js → defineDatabase-CHmzpzFf.js} +2 -4
- package/dist/discovery-gHeLq8jk.d.ts +11 -0
- package/dist/{index-AbdSa1Mk.d.ts → index-M4Jp_PFM.d.ts} +2 -1
- package/dist/index.d.ts +4 -4
- package/dist/index.js +5 -8
- package/dist/{kysely-BH7QZBZw.js → kysely-Be6KwFZC.js} +45 -31
- package/dist/migrations/generator.d.ts +14 -17
- package/dist/migrations/generator.js +202 -5
- package/dist/migrations/snapshot.d.ts +1 -1
- package/dist/migrations/snapshot.js +91 -3
- package/dist/{parser-CL3Nlmsy.js → parser-DR57GOjv.js} +58 -61
- package/dist/registry.d.ts +10 -11
- package/dist/registry.js +3 -5
- package/dist/schema.d.ts +5 -2
- package/dist/schema.js +6 -3
- package/dist/snapshot-CaG5xnE2.d.ts +48 -0
- package/dist/{state-DtZ70cBR.js → state-OVuoHRC9.js} +3 -5
- package/dist/testing/index.d.ts +4 -5
- package/dist/testing/index.js +6 -10
- package/dist/transport/protocol.d.ts +7 -8
- package/dist/transport/protocol.js +34 -3
- package/dist/transport/websocket.d.ts +4 -5
- package/dist/transport/websocket.js +103 -3
- package/dist/vite/durableDb.d.ts +7 -7
- package/dist/vite/durableDb.js +29 -31
- package/package.json +12 -12
- package/dist/arktypeConfig--4OgOv4U.d.ts +0 -6
- package/dist/context-kIVZbhye.js +0 -121
- package/dist/generator-KHBZaOI1.js +0 -202
- package/dist/index-BhRiKZ4j.d.ts +0 -51
- package/dist/protocol-DEubbBbR.js +0 -35
- package/dist/push-BY3lfh-R.js +0 -8
- package/dist/push-DiHH52-G.js +0 -190
- package/dist/schema-BCjqTRvV.d.ts +0 -6
- package/dist/schema-IFq7ovQq.js +0 -8
- package/dist/snapshot-DMW6j2Ix.js +0 -93
- package/dist/snapshot-DOerumb7.d.ts +0 -125
- package/dist/state-vav3VCId.js +0 -5
- package/dist/websocket-eao2rnHL.js +0 -104
|
@@ -1,11 +1,9 @@
|
|
|
1
|
-
import { t as Snapshot } from "../snapshot-
|
|
2
|
-
|
|
1
|
+
import { t as Snapshot } from "../snapshot-CaG5xnE2.js";
|
|
3
2
|
//#region src/migrations/generator.d.ts
|
|
4
|
-
|
|
5
3
|
/**
|
|
6
4
|
* Result of migration generation
|
|
7
5
|
*/
|
|
8
|
-
interface MigrationResult {
|
|
6
|
+
export interface MigrationResult {
|
|
9
7
|
/** Whether changes were detected */
|
|
10
8
|
hasChanges: boolean;
|
|
11
9
|
/** Generated SQL statements */
|
|
@@ -20,7 +18,7 @@ interface MigrationResult {
|
|
|
20
18
|
/**
|
|
21
19
|
* Options for migration generation
|
|
22
20
|
*/
|
|
23
|
-
interface GenerateMigrationOptions {
|
|
21
|
+
export interface GenerateMigrationOptions {
|
|
24
22
|
/** Directory to store migrations and snapshots */
|
|
25
23
|
migrationsDir: string;
|
|
26
24
|
/** Drizzle schema objects */
|
|
@@ -33,15 +31,15 @@ interface GenerateMigrationOptions {
|
|
|
33
31
|
/**
|
|
34
32
|
* Load the previous snapshot from the migrations directory
|
|
35
33
|
*/
|
|
36
|
-
declare function loadSnapshot(migrationsDir: string): Snapshot;
|
|
34
|
+
export declare function loadSnapshot(migrationsDir: string): Snapshot;
|
|
37
35
|
/**
|
|
38
36
|
* Save a snapshot to the migrations directory
|
|
39
37
|
*/
|
|
40
|
-
declare function saveSnapshot(migrationsDir: string, snapshot: Snapshot): void;
|
|
38
|
+
export declare function saveSnapshot(migrationsDir: string, snapshot: Snapshot): void;
|
|
41
39
|
/**
|
|
42
40
|
* Generate a timestamp-based migration name
|
|
43
41
|
*/
|
|
44
|
-
declare function generateMigrationName(suffix?: string): string;
|
|
42
|
+
export declare function generateMigrationName(suffix?: string): string;
|
|
45
43
|
/**
|
|
46
44
|
* Generate a migration from schema changes
|
|
47
45
|
*
|
|
@@ -62,18 +60,18 @@ declare function generateMigrationName(suffix?: string): string;
|
|
|
62
60
|
* }
|
|
63
61
|
* ```
|
|
64
62
|
*/
|
|
65
|
-
declare function generateMigration(options: GenerateMigrationOptions): Promise<MigrationResult>;
|
|
63
|
+
export declare function generateMigration(options: GenerateMigrationOptions): Promise<MigrationResult>;
|
|
66
64
|
/**
|
|
67
65
|
* Parse SQL content into chunks (split by breakpoints) and statements
|
|
68
66
|
*
|
|
69
67
|
* @param content - Raw SQL file content
|
|
70
68
|
* @returns Array of chunks, where each chunk is an array of SQL statements
|
|
71
69
|
*/
|
|
72
|
-
declare function parseSqlMigration(content: string): string[][];
|
|
70
|
+
export declare function parseSqlMigration(content: string): string[][];
|
|
73
71
|
/**
|
|
74
72
|
* Migration data structure for embedding in generated code
|
|
75
73
|
*/
|
|
76
|
-
interface MigrationData {
|
|
74
|
+
export interface MigrationData {
|
|
77
75
|
name: string;
|
|
78
76
|
chunks: string[][];
|
|
79
77
|
}
|
|
@@ -81,21 +79,20 @@ interface MigrationData {
|
|
|
81
79
|
* Load all migration SQL files from a directory
|
|
82
80
|
* Returns migrations sorted by name (timestamp order) with breakpoint parsing
|
|
83
81
|
*/
|
|
84
|
-
declare function loadMigrationFiles(migrationsDir: string): Map<string, string[][]>;
|
|
82
|
+
export declare function loadMigrationFiles(migrationsDir: string): Map<string, string[][]>;
|
|
85
83
|
/**
|
|
86
84
|
* Load a schema module using dynamic import
|
|
87
85
|
* Works with both ESM and CJS modules
|
|
88
86
|
*/
|
|
89
|
-
declare function loadSchemaModule(schemaPath: string, tableNames: string[]): Promise<Record<string, unknown>>;
|
|
87
|
+
export declare function loadSchemaModule(schemaPath: string, tableNames: string[]): Promise<Record<string, unknown>>;
|
|
90
88
|
/**
|
|
91
89
|
* Build schema module with esbuild and return the exports
|
|
92
90
|
* This is useful when the schema is TypeScript and needs transpilation
|
|
93
91
|
*/
|
|
94
|
-
declare function buildAndLoadSchema(schemaPath: string, tableNames: string[]): Promise<Record<string, unknown>>;
|
|
92
|
+
export declare function buildAndLoadSchema(schemaPath: string, tableNames: string[]): Promise<Record<string, unknown>>;
|
|
95
93
|
/**
|
|
96
94
|
* Generate SQL to create all tables from scratch
|
|
97
95
|
* Useful for initial setup or testing
|
|
98
96
|
*/
|
|
99
|
-
declare function generateCreateTableSQL(schema: Record<string, unknown>): Promise<string[]>;
|
|
100
|
-
//#endregion
|
|
101
|
-
export { GenerateMigrationOptions, MigrationData, MigrationResult, buildAndLoadSchema, generateCreateTableSQL, generateMigration, generateMigrationName, loadMigrationFiles, loadSchemaModule, loadSnapshot, parseSqlMigration, saveSnapshot };
|
|
97
|
+
export declare function generateCreateTableSQL(schema: Record<string, unknown>): Promise<string[]>;
|
|
98
|
+
//#endregion
|
|
@@ -1,5 +1,202 @@
|
|
|
1
|
-
import "../debug-
|
|
2
|
-
import "
|
|
3
|
-
import
|
|
4
|
-
|
|
5
|
-
|
|
1
|
+
import { i as init_debug, n as debugMigrations } from "../debug-Cz8KzMft.js";
|
|
2
|
+
import { createEmptySnapshot, generateMigrationStatements, generateSnapshotFromSchema, generateSnapshotId, snapshotsEqual } from "./snapshot.js";
|
|
3
|
+
import * as fs from "node:fs";
|
|
4
|
+
import * as path$1 from "node:path";
|
|
5
|
+
import * as os from "node:os";
|
|
6
|
+
import { pathToFileURL } from "node:url";
|
|
7
|
+
//#region src/migrations/generator.ts
|
|
8
|
+
init_debug();
|
|
9
|
+
/**
|
|
10
|
+
* Snapshot file name
|
|
11
|
+
*/
|
|
12
|
+
const SNAPSHOT_FILE = "_snapshot.json";
|
|
13
|
+
/**
|
|
14
|
+
* Load the previous snapshot from the migrations directory
|
|
15
|
+
*/
|
|
16
|
+
function loadSnapshot(migrationsDir) {
|
|
17
|
+
const snapshotPath = path$1.join(migrationsDir, SNAPSHOT_FILE);
|
|
18
|
+
if (!fs.existsSync(snapshotPath)) return createEmptySnapshot();
|
|
19
|
+
const content = fs.readFileSync(snapshotPath, "utf-8");
|
|
20
|
+
try {
|
|
21
|
+
return JSON.parse(content);
|
|
22
|
+
} catch (e) {
|
|
23
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
24
|
+
throw new Error(`[db] Failed to parse snapshot at ${snapshotPath}: ${message}. The file appears corrupt — restore from git, or delete it if you intend to re-derive migrations from scratch (only safe when the migration history matches an empty-starting-point schema).`);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Save a snapshot to the migrations directory
|
|
29
|
+
*/
|
|
30
|
+
function saveSnapshot(migrationsDir, snapshot) {
|
|
31
|
+
fs.mkdirSync(migrationsDir, { recursive: true });
|
|
32
|
+
const snapshotPath = path$1.join(migrationsDir, SNAPSHOT_FILE);
|
|
33
|
+
fs.writeFileSync(snapshotPath, JSON.stringify(snapshot, null, 2));
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Generate a timestamp-based migration name
|
|
37
|
+
*/
|
|
38
|
+
function generateMigrationName(suffix) {
|
|
39
|
+
const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[-:T]/g, "").slice(0, 14);
|
|
40
|
+
return suffix ? `${timestamp}_${suffix}` : timestamp;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Generate a migration from schema changes
|
|
44
|
+
*
|
|
45
|
+
* This compares the current schema to the stored snapshot and generates
|
|
46
|
+
* the necessary SQL statements to migrate the database.
|
|
47
|
+
*
|
|
48
|
+
* @example
|
|
49
|
+
* ```ts
|
|
50
|
+
* import { users, posts } from './schema';
|
|
51
|
+
*
|
|
52
|
+
* const result = await generateMigration({
|
|
53
|
+
* migrationsDir: './migrations',
|
|
54
|
+
* schema: { users, posts },
|
|
55
|
+
* });
|
|
56
|
+
*
|
|
57
|
+
* if (result.hasChanges) {
|
|
58
|
+
* console.log('Migration generated:', result.migrationName);
|
|
59
|
+
* }
|
|
60
|
+
* ```
|
|
61
|
+
*/
|
|
62
|
+
async function generateMigration(options) {
|
|
63
|
+
const { migrationsDir, schema, migrationName, write = true } = options;
|
|
64
|
+
const previousSnapshot = loadSnapshot(migrationsDir);
|
|
65
|
+
const newSnapshot = await generateSnapshotFromSchema(schema);
|
|
66
|
+
newSnapshot.id = generateSnapshotId();
|
|
67
|
+
newSnapshot.prevId = previousSnapshot.id;
|
|
68
|
+
if (snapshotsEqual(previousSnapshot, newSnapshot)) return {
|
|
69
|
+
hasChanges: false,
|
|
70
|
+
statements: [],
|
|
71
|
+
migrationName: null,
|
|
72
|
+
snapshot: newSnapshot,
|
|
73
|
+
previousSnapshot
|
|
74
|
+
};
|
|
75
|
+
const statements = await generateMigrationStatements(previousSnapshot, newSnapshot);
|
|
76
|
+
const name = migrationName ?? generateMigrationName("auto");
|
|
77
|
+
if (write && statements.length > 0) {
|
|
78
|
+
fs.mkdirSync(migrationsDir, { recursive: true });
|
|
79
|
+
const sqlPath = path$1.join(migrationsDir, `${name}.sql`);
|
|
80
|
+
const sqlContent = statements.map((s) => s.endsWith(";") ? s : `${s};`).join("\n\n");
|
|
81
|
+
fs.writeFileSync(sqlPath, sqlContent);
|
|
82
|
+
saveSnapshot(migrationsDir, newSnapshot);
|
|
83
|
+
debugMigrations("Generated migration: %s", name);
|
|
84
|
+
debugMigrations("Statements: %d", statements.length);
|
|
85
|
+
}
|
|
86
|
+
return {
|
|
87
|
+
hasChanges: true,
|
|
88
|
+
statements,
|
|
89
|
+
migrationName: name,
|
|
90
|
+
snapshot: newSnapshot,
|
|
91
|
+
previousSnapshot
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Breakpoint marker in SQL files
|
|
96
|
+
* Use: --> breakpoint
|
|
97
|
+
*/
|
|
98
|
+
const BREAKPOINT_MARKER = /^-->\s*breakpoint\s*$/im;
|
|
99
|
+
/**
|
|
100
|
+
* Parse SQL content into chunks (split by breakpoints) and statements
|
|
101
|
+
*
|
|
102
|
+
* @param content - Raw SQL file content
|
|
103
|
+
* @returns Array of chunks, where each chunk is an array of SQL statements
|
|
104
|
+
*/
|
|
105
|
+
function parseSqlMigration(content) {
|
|
106
|
+
return content.split(BREAKPOINT_MARKER).map((chunk) => {
|
|
107
|
+
return chunk.split("\n").filter((line) => !line.trim().startsWith("--")).join("\n").split(/;(?:\s*\n|\s*$)/).map((s) => s.trim()).filter((s) => s.length > 0);
|
|
108
|
+
}).filter((chunk) => chunk.length > 0);
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Load all migration SQL files from a directory
|
|
112
|
+
* Returns migrations sorted by name (timestamp order) with breakpoint parsing
|
|
113
|
+
*/
|
|
114
|
+
function loadMigrationFiles(migrationsDir) {
|
|
115
|
+
const migrations = /* @__PURE__ */ new Map();
|
|
116
|
+
if (!fs.existsSync(migrationsDir)) return migrations;
|
|
117
|
+
const files = fs.readdirSync(migrationsDir).filter((f) => f.endsWith(".sql")).sort();
|
|
118
|
+
for (const file of files) {
|
|
119
|
+
const name = file.replace(".sql", "");
|
|
120
|
+
const chunks = parseSqlMigration(fs.readFileSync(path$1.join(migrationsDir, file), "utf-8"));
|
|
121
|
+
if (chunks.length > 0) migrations.set(name, chunks);
|
|
122
|
+
}
|
|
123
|
+
return migrations;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Load a schema module using dynamic import
|
|
127
|
+
* Works with both ESM and CJS modules
|
|
128
|
+
*/
|
|
129
|
+
async function loadSchemaModule(schemaPath, tableNames) {
|
|
130
|
+
const fileUrl = pathToFileURL(schemaPath).href;
|
|
131
|
+
try {
|
|
132
|
+
const module = await import(fileUrl);
|
|
133
|
+
const schema = {};
|
|
134
|
+
for (const name of tableNames) if (module[name]) schema[name] = module[name];
|
|
135
|
+
else if (module.default?.[name]) schema[name] = module.default[name];
|
|
136
|
+
return schema;
|
|
137
|
+
} catch (error) {
|
|
138
|
+
throw new Error(`Failed to load schema from ${schemaPath}: ${error}`);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Where to drop the transient transpiled-schema `.mjs`. We want a
|
|
143
|
+
* directory that (a) is on the app's node_modules resolution chain
|
|
144
|
+
* so the bundle's bare imports resolve, and (b) is NOT inside the
|
|
145
|
+
* watched `src/` tree (so dev-server watchers don't react to it).
|
|
146
|
+
* The app's `node_modules/.cache/durable-db/` satisfies both; if no
|
|
147
|
+
* node_modules is found walking up from the schema, fall back to the
|
|
148
|
+
* OS temp dir (the schema bundle's externals are usually resolvable
|
|
149
|
+
* relative to cwd in that case too).
|
|
150
|
+
*/
|
|
151
|
+
function resolveTempDir(schemaPath) {
|
|
152
|
+
let dir = path$1.dirname(path$1.resolve(schemaPath));
|
|
153
|
+
while (true) {
|
|
154
|
+
if (fs.existsSync(path$1.join(dir, "node_modules"))) return path$1.join(dir, "node_modules", ".cache", "durable-db");
|
|
155
|
+
const parent = path$1.dirname(dir);
|
|
156
|
+
if (parent === dir) break;
|
|
157
|
+
dir = parent;
|
|
158
|
+
}
|
|
159
|
+
return path$1.join(os.tmpdir(), "durable-db");
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Build schema module with esbuild and return the exports
|
|
163
|
+
* This is useful when the schema is TypeScript and needs transpilation
|
|
164
|
+
*/
|
|
165
|
+
async function buildAndLoadSchema(schemaPath, tableNames) {
|
|
166
|
+
const result = await (await import("esbuild")).build({
|
|
167
|
+
entryPoints: [schemaPath],
|
|
168
|
+
bundle: true,
|
|
169
|
+
write: false,
|
|
170
|
+
format: "esm",
|
|
171
|
+
platform: "node",
|
|
172
|
+
packages: "external",
|
|
173
|
+
target: "node18"
|
|
174
|
+
});
|
|
175
|
+
if (result.outputFiles?.length !== 1) throw new Error(`Unexpected esbuild output for ${schemaPath}`);
|
|
176
|
+
const tempDir = resolveTempDir(schemaPath);
|
|
177
|
+
fs.mkdirSync(tempDir, { recursive: true });
|
|
178
|
+
const tempFile = path$1.join(tempDir, `_schema_temp_${Date.now()}.mjs`);
|
|
179
|
+
try {
|
|
180
|
+
fs.writeFileSync(tempFile, result.outputFiles[0].text);
|
|
181
|
+
const module = await import(pathToFileURL(tempFile).href);
|
|
182
|
+
const schema = {};
|
|
183
|
+
for (const name of tableNames) if (module[name]) schema[name] = module[name];
|
|
184
|
+
else if (module.default?.[name]) schema[name] = module.default[name];
|
|
185
|
+
return schema;
|
|
186
|
+
} finally {
|
|
187
|
+
try {
|
|
188
|
+
fs.unlinkSync(tempFile);
|
|
189
|
+
} catch {}
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Generate SQL to create all tables from scratch
|
|
194
|
+
* Useful for initial setup or testing
|
|
195
|
+
*/
|
|
196
|
+
async function generateCreateTableSQL(schema) {
|
|
197
|
+
const emptySnapshot = createEmptySnapshot();
|
|
198
|
+
const currentSnapshot = await generateSnapshotFromSchema(schema);
|
|
199
|
+
return generateMigrationStatements(emptySnapshot, currentSnapshot);
|
|
200
|
+
}
|
|
201
|
+
//#endregion
|
|
202
|
+
export { buildAndLoadSchema, generateCreateTableSQL, generateMigration, generateMigrationName, loadMigrationFiles, loadSchemaModule, loadSnapshot, parseSqlMigration, saveSnapshot };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as generateSnapshotId, i as generateSnapshotFromSchema, n as createEmptySnapshot, o as hashSnapshot, r as generateMigrationStatements, s as snapshotsEqual, t as Snapshot } from "../snapshot-
|
|
1
|
+
import { a as generateSnapshotId, i as generateSnapshotFromSchema, n as createEmptySnapshot, o as hashSnapshot, r as generateMigrationStatements, s as snapshotsEqual, t as Snapshot } from "../snapshot-CaG5xnE2.js";
|
|
2
2
|
export { Snapshot, createEmptySnapshot, generateMigrationStatements, generateSnapshotFromSchema, generateSnapshotId, hashSnapshot, snapshotsEqual };
|
|
@@ -1,3 +1,91 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
//#region src/migrations/snapshot.ts
|
|
3
|
+
const { generateSQLiteDrizzleJson, generateSQLiteMigration } = createRequire(import.meta.url)("drizzle-kit/api");
|
|
4
|
+
/**
|
|
5
|
+
* Create an empty snapshot (for initial migration from nothing)
|
|
6
|
+
*/
|
|
7
|
+
function createEmptySnapshot() {
|
|
8
|
+
return {
|
|
9
|
+
views: {},
|
|
10
|
+
version: "6",
|
|
11
|
+
dialect: "sqlite",
|
|
12
|
+
id: "0000000000000",
|
|
13
|
+
prevId: "",
|
|
14
|
+
tables: {},
|
|
15
|
+
enums: {},
|
|
16
|
+
_meta: {
|
|
17
|
+
tables: {},
|
|
18
|
+
columns: {}
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Generate a unique snapshot ID based on timestamp
|
|
24
|
+
*/
|
|
25
|
+
function generateSnapshotId() {
|
|
26
|
+
return Date.now().toString(36).padStart(13, "0");
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Generate a snapshot from Drizzle schema objects
|
|
30
|
+
*
|
|
31
|
+
* @param schema - Object containing Drizzle table definitions
|
|
32
|
+
* @returns Snapshot representing the current schema state
|
|
33
|
+
*
|
|
34
|
+
* @example
|
|
35
|
+
* ```ts
|
|
36
|
+
* import { users, posts } from './schema';
|
|
37
|
+
* const snapshot = await generateSnapshotFromSchema({ users, posts });
|
|
38
|
+
* ```
|
|
39
|
+
*/
|
|
40
|
+
async function generateSnapshotFromSchema(schema) {
|
|
41
|
+
return generateSQLiteDrizzleJson(schema, void 0, "snake_case");
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Generate SQL migration statements from two snapshots
|
|
45
|
+
*
|
|
46
|
+
* @param from - Previous schema state (or empty for initial migration)
|
|
47
|
+
* @param to - Target schema state
|
|
48
|
+
* @returns Array of SQL statements to migrate from `from` to `to`
|
|
49
|
+
*
|
|
50
|
+
* @example
|
|
51
|
+
* ```ts
|
|
52
|
+
* const statements = await generateMigrationStatements(prevSnapshot, newSnapshot);
|
|
53
|
+
* // ['CREATE TABLE users (...)', 'CREATE INDEX ...']
|
|
54
|
+
* ```
|
|
55
|
+
*/
|
|
56
|
+
async function generateMigrationStatements(from, to) {
|
|
57
|
+
return await generateSQLiteMigration(from, to);
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Serialize the schema-relevant parts of a snapshot for comparison/hashing.
|
|
61
|
+
* Includes tables, views, and enums so that changes to any of them are
|
|
62
|
+
* detected — previously only `tables` was considered.
|
|
63
|
+
*/
|
|
64
|
+
function serializeSchemaShape(snapshot) {
|
|
65
|
+
return JSON.stringify({
|
|
66
|
+
tables: snapshot.tables ?? {},
|
|
67
|
+
views: snapshot.views ?? {},
|
|
68
|
+
enums: snapshot.enums ?? {}
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Check if two snapshots are equivalent (no migration needed)
|
|
73
|
+
*/
|
|
74
|
+
function snapshotsEqual(a, b) {
|
|
75
|
+
return serializeSchemaShape(a) === serializeSchemaShape(b);
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Create a hash of a snapshot for quick comparison
|
|
79
|
+
*/
|
|
80
|
+
function hashSnapshot(snapshot) {
|
|
81
|
+
const content = serializeSchemaShape(snapshot);
|
|
82
|
+
let hash = 0;
|
|
83
|
+
for (let i = 0; i < content.length; i++) {
|
|
84
|
+
const char = content.charCodeAt(i);
|
|
85
|
+
hash = (hash << 5) - hash + char;
|
|
86
|
+
hash = hash & hash;
|
|
87
|
+
}
|
|
88
|
+
return Math.abs(hash).toString(36);
|
|
89
|
+
}
|
|
90
|
+
//#endregion
|
|
91
|
+
export { createEmptySnapshot, generateMigrationStatements, generateSnapshotFromSchema, generateSnapshotId, hashSnapshot, snapshotsEqual };
|
|
@@ -1,11 +1,10 @@
|
|
|
1
|
-
import { i as init_debug, t as debugCli } from "./debug-
|
|
1
|
+
import { i as init_debug, t as debugCli } from "./debug-Cz8KzMft.js";
|
|
2
2
|
import * as fs from "node:fs";
|
|
3
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";
|
|
7
7
|
import * as t from "@babel/types";
|
|
8
|
-
|
|
9
8
|
//#region src/vite/modules/aliasResolver.ts
|
|
10
9
|
init_debug();
|
|
11
10
|
/**
|
|
@@ -114,9 +113,17 @@ async function loadViteAliases(root) {
|
|
|
114
113
|
viteAliasCache.set(key, aliases);
|
|
115
114
|
return aliases;
|
|
116
115
|
}
|
|
117
|
-
|
|
118
116
|
//#endregion
|
|
119
117
|
//#region src/vite/modules/discovery.ts
|
|
118
|
+
/** The sources a `databasesDir` option names. */
|
|
119
|
+
function databaseSources(databasesDir) {
|
|
120
|
+
return typeof databasesDir === "string" ? [{ dir: databasesDir }] : databasesDir;
|
|
121
|
+
}
|
|
122
|
+
/** The name a database file gets: its basename, prefixed when its source has a prefix. */
|
|
123
|
+
function databaseName(file, prefix) {
|
|
124
|
+
const base = path$1.basename(file).replace(/\.(ts|js)$/, "");
|
|
125
|
+
return prefix ? `${prefix}-${base}` : base;
|
|
126
|
+
}
|
|
120
127
|
/**
|
|
121
128
|
* Tracks directories we've already warned about to avoid duplicate noise
|
|
122
129
|
* on repeated discovery calls (e.g. Vite HMR, multiple plugin hooks).
|
|
@@ -132,52 +139,34 @@ const warnedMissingDirs = /* @__PURE__ */ new Set();
|
|
|
132
139
|
*/
|
|
133
140
|
function discoverDatabaseFiles(options) {
|
|
134
141
|
const { projectRoot, databasesDir } = options;
|
|
135
|
-
const absoluteDir = path$1.join(projectRoot, databasesDir);
|
|
136
|
-
if (!fs.existsSync(absoluteDir)) {
|
|
137
|
-
if (!warnedMissingDirs.has(absoluteDir)) {
|
|
138
|
-
warnedMissingDirs.add(absoluteDir);
|
|
139
|
-
console.warn(`[durable-db] Databases directory not found: ${absoluteDir}. No databases will be generated. Set the 'databasesDir' plugin option if your databases live elsewhere (current: '${databasesDir}').`);
|
|
140
|
-
}
|
|
141
|
-
return [];
|
|
142
|
-
}
|
|
143
|
-
const files = fs.readdirSync(absoluteDir);
|
|
144
142
|
const results = [];
|
|
145
|
-
for (const
|
|
146
|
-
|
|
147
|
-
if (
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
143
|
+
for (const source of databaseSources(databasesDir)) {
|
|
144
|
+
const absoluteDir = path$1.resolve(projectRoot, source.dir);
|
|
145
|
+
if (!fs.existsSync(absoluteDir)) {
|
|
146
|
+
if (typeof databasesDir === "string" && !warnedMissingDirs.has(absoluteDir)) {
|
|
147
|
+
warnedMissingDirs.add(absoluteDir);
|
|
148
|
+
console.warn(`[durable-db] Databases directory not found: ${absoluteDir}. No databases will be generated. Set the 'databasesDir' plugin option if your databases live elsewhere (current: '${databasesDir}').`);
|
|
149
|
+
}
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
for (const file of fs.readdirSync(absoluteDir)) {
|
|
153
|
+
if (!file.endsWith(".ts")) continue;
|
|
154
|
+
if (file.endsWith(".d.ts")) continue;
|
|
155
|
+
if (file === "schema.ts") continue;
|
|
156
|
+
if (file.startsWith("_")) continue;
|
|
157
|
+
const absolutePath = path$1.join(absoluteDir, file);
|
|
158
|
+
results.push({
|
|
159
|
+
absolutePath,
|
|
160
|
+
relativePath: path$1.relative(projectRoot, absolutePath),
|
|
161
|
+
name: databaseName(file, source.prefix),
|
|
162
|
+
prefix: source.prefix
|
|
163
|
+
});
|
|
164
|
+
}
|
|
158
165
|
}
|
|
159
166
|
return results;
|
|
160
167
|
}
|
|
161
|
-
/**
|
|
162
|
-
* Recursively find action-defining files under the databases directory.
|
|
163
|
-
*
|
|
164
|
-
* The generated Durable Object module side-effect-imports these so every
|
|
165
|
-
* `action()` runs its `registerAction(...)` at DO startup — populating the
|
|
166
|
-
* action registry in the DO's isolate. Without this the registry is only
|
|
167
|
-
* populated by whatever the request path imported, which works in dev (one
|
|
168
|
-
* shared isolate) and via in-app navigation, but a Durable Object is a separate
|
|
169
|
-
* persistent isolate in production: a freshly deep-linked route whose action the
|
|
170
|
-
* DO never loaded throws `Unknown action "X" (was it imported?)`.
|
|
171
|
-
*
|
|
172
|
-
* Returns absolute paths of `.ts`/`.tsx` files that call `action(` (the factory
|
|
173
|
-
* invocation), excluding tests, declarations, and `_`-prefixed helpers. Helper
|
|
174
|
-
* modules without their own actions are pulled in transitively by the action
|
|
175
|
-
* files that import them, so they don't need to be listed here.
|
|
176
|
-
*/
|
|
177
168
|
function discoverActionFiles(options) {
|
|
178
169
|
const { projectRoot, databasesDir } = options;
|
|
179
|
-
const absoluteDir = path$1.join(projectRoot, databasesDir);
|
|
180
|
-
if (!fs.existsSync(absoluteDir)) return [];
|
|
181
170
|
const results = [];
|
|
182
171
|
const walk = (dir) => {
|
|
183
172
|
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
@@ -194,7 +183,10 @@ function discoverActionFiles(options) {
|
|
|
194
183
|
} catch {}
|
|
195
184
|
}
|
|
196
185
|
};
|
|
197
|
-
|
|
186
|
+
for (const source of databaseSources(databasesDir)) {
|
|
187
|
+
const absoluteDir = path$1.resolve(projectRoot, source.dir);
|
|
188
|
+
if (fs.existsSync(absoluteDir)) walk(absoluteDir);
|
|
189
|
+
}
|
|
198
190
|
return results;
|
|
199
191
|
}
|
|
200
192
|
/**
|
|
@@ -223,7 +215,6 @@ function resolveImportPath(fromFile, importSource, aliases) {
|
|
|
223
215
|
function readFile(filePath) {
|
|
224
216
|
return fs.readFileSync(filePath, "utf-8");
|
|
225
217
|
}
|
|
226
|
-
|
|
227
218
|
//#endregion
|
|
228
219
|
//#region src/vite/modules/parser.ts
|
|
229
220
|
init_debug();
|
|
@@ -294,7 +285,7 @@ function parseDatabaseFile(filePath, code, options = {}) {
|
|
|
294
285
|
const init = nodePath.node.init;
|
|
295
286
|
const id = nodePath.node.id;
|
|
296
287
|
if (isDefineDatabaseCall(init)) {
|
|
297
|
-
const dbInfo = extractDatabaseInfo(nodePath, init, filePath, result.localImports);
|
|
288
|
+
const dbInfo = extractDatabaseInfo(nodePath, init, filePath, result.localImports, options.namePrefix);
|
|
298
289
|
if (dbInfo) result.database = dbInfo;
|
|
299
290
|
if (t.isObjectPattern(id)) actionFnName = extractActionFactoryName(id);
|
|
300
291
|
}
|
|
@@ -343,7 +334,7 @@ function warnNonLiteral(filePath, key, defaultValue) {
|
|
|
343
334
|
/**
|
|
344
335
|
* Extract database configuration from a defineDatabase() call
|
|
345
336
|
*/
|
|
346
|
-
function extractDatabaseInfo(declaratorPath, callExpr, filePath, imports) {
|
|
337
|
+
function extractDatabaseInfo(declaratorPath, callExpr, filePath, imports, namePrefix) {
|
|
347
338
|
const configArg = callExpr.arguments[0];
|
|
348
339
|
if (!t.isObjectExpression(configArg)) return null;
|
|
349
340
|
let instance = "per-tenant";
|
|
@@ -354,17 +345,23 @@ function extractDatabaseInfo(declaratorPath, callExpr, filePath, imports) {
|
|
|
354
345
|
for (const prop of configArg.properties) {
|
|
355
346
|
if (!t.isObjectProperty(prop) || !t.isIdentifier(prop.key)) continue;
|
|
356
347
|
const key = prop.key.name;
|
|
357
|
-
if (key === "instance")
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
}
|
|
348
|
+
if (key === "instance") {
|
|
349
|
+
if (t.isStringLiteral(prop.value)) {
|
|
350
|
+
const value = prop.value.value;
|
|
351
|
+
if (value === "per-tenant" || value === "global") instance = value;
|
|
352
|
+
} else warnNonLiteral(filePath, "instance", "per-tenant");
|
|
353
|
+
}
|
|
354
|
+
if (key === "browsable") {
|
|
355
|
+
if (t.isBooleanLiteral(prop.value)) browsable = prop.value.value;
|
|
356
|
+
else if (t.isStringLiteral(prop.value) && prop.value.value === "development") browsable = "development";
|
|
357
|
+
else warnNonLiteral(filePath, "browsable", String(browsable));
|
|
358
|
+
}
|
|
359
|
+
if (key === "transport") {
|
|
360
|
+
if (t.isStringLiteral(prop.value)) {
|
|
361
|
+
const value = prop.value.value;
|
|
362
|
+
if (value === "rpc" || value === "websocket") transport = value;
|
|
363
|
+
} else warnNonLiteral(filePath, "transport", "rpc");
|
|
364
|
+
}
|
|
368
365
|
if (key === "schema" && t.isObjectExpression(prop.value)) {
|
|
369
366
|
for (const schemaProp of prop.value.properties) if (t.isObjectProperty(schemaProp) || t.isSpreadElement(schemaProp)) {
|
|
370
367
|
if (t.isObjectProperty(schemaProp) && t.isIdentifier(schemaProp.key)) {
|
|
@@ -376,7 +373,8 @@ function extractDatabaseInfo(declaratorPath, callExpr, filePath, imports) {
|
|
|
376
373
|
}
|
|
377
374
|
}
|
|
378
375
|
}
|
|
379
|
-
const
|
|
376
|
+
const base = path$1.basename(filePath).replace(/\.(ts|js)$/, "");
|
|
377
|
+
const name = namePrefix ? `${namePrefix}-${base}` : base;
|
|
380
378
|
return {
|
|
381
379
|
filePath,
|
|
382
380
|
name,
|
|
@@ -427,6 +425,5 @@ function toPascalCase(str) {
|
|
|
427
425
|
function toScreamingSnakeCase(str) {
|
|
428
426
|
return str.replace(/([a-z])([A-Z])/g, "$1_$2").replace(/[-]/g, "_").toUpperCase();
|
|
429
427
|
}
|
|
430
|
-
|
|
431
428
|
//#endregion
|
|
432
|
-
export {
|
|
429
|
+
export { discoverDatabaseFiles as a, loadViteAliases as c, discoverActionFiles as i, parseDatabaseFile as n, readFile as o, databaseSources as r, resolveImportPath as s, BABEL_PARSER_PLUGINS as t };
|
package/dist/registry.d.ts
CHANGED
|
@@ -1,30 +1,29 @@
|
|
|
1
|
-
import { t as type } from "./arktypeConfig
|
|
2
|
-
|
|
1
|
+
import { t as type } from "./arktypeConfig-DdIO8VV1.js";
|
|
3
2
|
//#region src/registry.d.ts
|
|
4
|
-
interface ActionDefinition {
|
|
3
|
+
export interface ActionDefinition {
|
|
5
4
|
validator: (args: unknown) => unknown;
|
|
6
5
|
handler: (db: unknown, args: unknown, ctx: unknown) => Promise<unknown>;
|
|
7
6
|
}
|
|
8
|
-
interface DoContext {
|
|
7
|
+
export interface DoContext {
|
|
9
8
|
db: unknown;
|
|
10
9
|
ctx: RpcContext;
|
|
11
10
|
dbName: string;
|
|
12
11
|
instanceKey: string;
|
|
13
12
|
}
|
|
14
|
-
interface RpcContext {
|
|
13
|
+
export interface RpcContext {
|
|
15
14
|
env: Record<string, unknown>;
|
|
16
15
|
dbName: string;
|
|
17
16
|
dbBindingNames: Record<string, string>;
|
|
18
17
|
dbTransports?: Record<string, 'rpc' | 'websocket'>;
|
|
19
18
|
instanceKey: string;
|
|
20
19
|
}
|
|
21
|
-
declare function registerAction(dbName: string, actionName: string, def: ActionDefinition): void;
|
|
22
|
-
declare function getAction(dbName: string, actionName: string): ActionDefinition | undefined;
|
|
23
|
-
declare function getDoContext(): DoContext | undefined;
|
|
24
|
-
declare function runWithDoContext<T>(store: DoContext, fn: () => T): T;
|
|
20
|
+
export declare function registerAction(dbName: string, actionName: string, def: ActionDefinition): void;
|
|
21
|
+
export declare function getAction(dbName: string, actionName: string): ActionDefinition | undefined;
|
|
22
|
+
export declare function getDoContext(): DoContext | undefined;
|
|
23
|
+
export declare function runWithDoContext<T>(store: DoContext, fn: () => T): T;
|
|
25
24
|
/**
|
|
26
25
|
* Call an action: validates args, then dispatches (direct call for same DB, RPC for cross-DB).
|
|
27
26
|
*/
|
|
28
|
-
declare function callAction(db: unknown, targetDb: string, actionName: string, args: unknown, ctx: RpcContext): Promise<unknown>;
|
|
27
|
+
export declare function callAction(db: unknown, targetDb: string, actionName: string, args: unknown, ctx: RpcContext): Promise<unknown>;
|
|
29
28
|
//#endregion
|
|
30
|
-
export {
|
|
29
|
+
export { type };
|
package/dist/registry.js
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import { t as type } from "./arktypeConfig-
|
|
2
|
-
import {
|
|
1
|
+
import { t as type } from "./arktypeConfig-DxP0OcV_.js";
|
|
2
|
+
import { WebSocketTransport } from "./transport/websocket.js";
|
|
3
3
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
4
|
-
|
|
5
4
|
//#region src/registry.ts
|
|
6
5
|
const actionsByDb = /* @__PURE__ */ new Map();
|
|
7
6
|
const als = new AsyncLocalStorage();
|
|
@@ -69,6 +68,5 @@ async function callAction(db, targetDb, actionName, args, ctx) {
|
|
|
69
68
|
const result = await stub.rpc(actionName, validated, { instanceKey: ctx.instanceKey });
|
|
70
69
|
return structuredClone(result);
|
|
71
70
|
}
|
|
72
|
-
|
|
73
71
|
//#endregion
|
|
74
|
-
export { callAction, getAction, getDoContext, registerAction, runWithDoContext, type };
|
|
72
|
+
export { callAction, getAction, getDoContext, registerAction, runWithDoContext, type };
|
package/dist/schema.d.ts
CHANGED
|
@@ -1,2 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
1
|
+
import { AnySQLiteColumn, blob, foreignKey, index, integer, numeric, primaryKey, real, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
|
|
2
|
+
//#region src/schema.d.ts
|
|
3
|
+
export declare const table: typeof sqliteTable;
|
|
4
|
+
//#endregion
|
|
5
|
+
export { type AnySQLiteColumn, blob, foreignKey, index, integer, numeric, primaryKey, real, text, uniqueIndex };
|