durable-db 0.0.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.
Files changed (46) hide show
  1. package/README.md +1052 -0
  2. package/dist/cli/bin.d.ts +1 -0
  3. package/dist/cli/bin.js +18 -0
  4. package/dist/cli/index.d.ts +330 -0
  5. package/dist/cli/index.js +9 -0
  6. package/dist/cli-Cr9686BF.js +630 -0
  7. package/dist/context/index.d.ts +2 -0
  8. package/dist/context/index.js +5 -0
  9. package/dist/context-BuIiIQ6K.js +103 -0
  10. package/dist/db/index.d.ts +3 -0
  11. package/dist/db/index.js +760 -0
  12. package/dist/debug-BZJbKybf.js +49 -0
  13. package/dist/defineDatabase-CONf4xFC.js +54 -0
  14. package/dist/defineDatabase-jBv90-Pk.d.ts +188 -0
  15. package/dist/generator-BUPP9scJ.js +180 -0
  16. package/dist/index-BFM5d0FP.d.ts +328 -0
  17. package/dist/index-CqVMaMYY.d.ts +65 -0
  18. package/dist/index.d.ts +6 -0
  19. package/dist/index.js +8 -0
  20. package/dist/migrations/generator.d.ts +101 -0
  21. package/dist/migrations/generator.js +5 -0
  22. package/dist/migrations/snapshot.d.ts +2 -0
  23. package/dist/migrations/snapshot.js +3 -0
  24. package/dist/parser-CbX54Flt.js +293 -0
  25. package/dist/protocol-g_plhPOY.js +35 -0
  26. package/dist/push-BgQ5cnfH.js +184 -0
  27. package/dist/push-BkkaslPd.js +8 -0
  28. package/dist/registry.d.ts +28 -0
  29. package/dist/registry.js +72 -0
  30. package/dist/schema-BOtrGnzM.js +8 -0
  31. package/dist/schema-CpzTOfZ6.d.ts +6 -0
  32. package/dist/schema.d.ts +2 -0
  33. package/dist/schema.js +3 -0
  34. package/dist/snapshot-C162qYoA.d.ts +125 -0
  35. package/dist/snapshot-D170nL7i.js +93 -0
  36. package/dist/state-BCcvNN-M.js +5 -0
  37. package/dist/state-FOEjpgJ6.js +203 -0
  38. package/dist/transport/protocol.d.ts +27 -0
  39. package/dist/transport/protocol.js +3 -0
  40. package/dist/transport/websocket.d.ts +31 -0
  41. package/dist/transport/websocket.js +3 -0
  42. package/dist/vite/durableDb.d.ts +20 -0
  43. package/dist/vite/durableDb.js +933 -0
  44. package/dist/websocket-Dx1fqwnF.js +104 -0
  45. package/package.json +114 -0
  46. package/virtual.d.ts +15 -0
@@ -0,0 +1,293 @@
1
+ import { i as init_debug } from "./debug-BZJbKybf.js";
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ import { parse } from "@babel/parser";
5
+ import _traverse from "@babel/traverse";
6
+ import _generate from "@babel/generator";
7
+ import * as t from "@babel/types";
8
+
9
+ //#region src/vite/modules/discovery.ts
10
+ /**
11
+ * Tracks directories we've already warned about to avoid duplicate noise
12
+ * on repeated discovery calls (e.g. Vite HMR, multiple plugin hooks).
13
+ */
14
+ const warnedMissingDirs = /* @__PURE__ */ new Set();
15
+ /**
16
+ * Discover database files in the configured directory
17
+ *
18
+ * Looks for .ts files in the databases directory, excluding:
19
+ * - .d.ts files
20
+ * - schema.ts (schema-only files)
21
+ * - Files starting with _ (private helpers)
22
+ */
23
+ function discoverDatabaseFiles(options) {
24
+ const { projectRoot, databasesDir } = options;
25
+ const absoluteDir = path.join(projectRoot, databasesDir);
26
+ if (!fs.existsSync(absoluteDir)) {
27
+ if (!warnedMissingDirs.has(absoluteDir)) {
28
+ warnedMissingDirs.add(absoluteDir);
29
+ 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}').`);
30
+ }
31
+ return [];
32
+ }
33
+ const files = fs.readdirSync(absoluteDir);
34
+ const results = [];
35
+ for (const file of files) {
36
+ if (!file.endsWith(".ts")) continue;
37
+ if (file.endsWith(".d.ts")) continue;
38
+ if (file === "schema.ts") continue;
39
+ if (file.startsWith("_")) continue;
40
+ const absolutePath = path.join(absoluteDir, file);
41
+ const relativePath = path.join(databasesDir, file);
42
+ const name = path.basename(file, ".ts");
43
+ results.push({
44
+ absolutePath,
45
+ relativePath,
46
+ name
47
+ });
48
+ }
49
+ return results;
50
+ }
51
+ /**
52
+ * Resolve a relative import path to an absolute path
53
+ *
54
+ * Tries various extensions and index files
55
+ */
56
+ function resolveImportPath(fromFile, importSource) {
57
+ if (!importSource.startsWith(".")) return null;
58
+ const dir = path.dirname(fromFile);
59
+ const resolved = path.resolve(dir, importSource);
60
+ if (fs.existsSync(resolved) && fs.statSync(resolved).isFile()) return resolved;
61
+ for (const ext of [
62
+ ".ts",
63
+ ".tsx",
64
+ ".js",
65
+ ".jsx"
66
+ ]) {
67
+ const withExt = resolved + ext;
68
+ if (fs.existsSync(withExt)) return withExt;
69
+ }
70
+ for (const indexFile of [
71
+ "index.ts",
72
+ "index.tsx",
73
+ "index.js",
74
+ "index.jsx"
75
+ ]) {
76
+ const indexPath = path.join(resolved, indexFile);
77
+ if (fs.existsSync(indexPath)) return indexPath;
78
+ }
79
+ return null;
80
+ }
81
+ /**
82
+ * Read file contents
83
+ */
84
+ function readFile(filePath) {
85
+ return fs.readFileSync(filePath, "utf-8");
86
+ }
87
+
88
+ //#endregion
89
+ //#region src/vite/modules/parser.ts
90
+ init_debug();
91
+ const traverse = typeof _traverse === "function" ? _traverse : _traverse.default;
92
+ const generate = typeof _generate === "function" ? _generate : _generate.default;
93
+ /**
94
+ * Shared Babel parser plugins used across all parsing in the Vite plugin.
95
+ * Ensures consistent syntax support (TypeScript, JSX, decorators, etc.).
96
+ */
97
+ const BABEL_PARSER_PLUGINS = [
98
+ "typescript",
99
+ "jsx",
100
+ "topLevelAwait",
101
+ "decorators-legacy",
102
+ "classProperties"
103
+ ];
104
+ /**
105
+ * Parse a TypeScript/JavaScript file into an AST
106
+ */
107
+ function parseCode(code) {
108
+ return parse(code, {
109
+ sourceType: "module",
110
+ plugins: BABEL_PARSER_PLUGINS
111
+ });
112
+ }
113
+ /**
114
+ * Generate source code from an AST node
115
+ */
116
+ function generateCode(node) {
117
+ return generate(node).code;
118
+ }
119
+ /**
120
+ * Parse a database file and extract database/action information
121
+ *
122
+ * This uses clean AST traversal - no regexes
123
+ */
124
+ function parseDatabaseFile(filePath, code) {
125
+ const ast = parseCode(code);
126
+ const result = {
127
+ filePath,
128
+ database: null,
129
+ actions: [],
130
+ localImports: /* @__PURE__ */ new Map()
131
+ };
132
+ let actionFnName = null;
133
+ let currentDatabaseName = path.basename(filePath).replace(/\.(ts|js)$/, "");
134
+ traverse(ast, {
135
+ ImportDeclaration(nodePath) {
136
+ const source = nodePath.node.source.value;
137
+ for (const specifier of nodePath.node.specifiers) if (t.isImportSpecifier(specifier)) {
138
+ const imported = t.isIdentifier(specifier.imported) ? specifier.imported.name : specifier.imported.value;
139
+ const localName = specifier.local.name;
140
+ result.localImports.set(localName, {
141
+ source,
142
+ imported
143
+ });
144
+ if (imported === "action" && source.startsWith(".")) actionFnName = localName;
145
+ } else if (t.isImportDefaultSpecifier(specifier)) result.localImports.set(specifier.local.name, {
146
+ source,
147
+ imported: "default"
148
+ });
149
+ else if (t.isImportNamespaceSpecifier(specifier)) result.localImports.set(specifier.local.name, {
150
+ source,
151
+ imported: "*"
152
+ });
153
+ },
154
+ VariableDeclarator(nodePath) {
155
+ const init = nodePath.node.init;
156
+ const id = nodePath.node.id;
157
+ if (isDefineDatabaseCall(init)) {
158
+ const dbInfo = extractDatabaseInfo(nodePath, init, filePath, result.localImports);
159
+ if (dbInfo) result.database = dbInfo;
160
+ if (t.isObjectPattern(id)) actionFnName = extractActionFactoryName(id);
161
+ }
162
+ if (actionFnName && isActionCall(init, actionFnName)) {
163
+ const actionInfo = extractActionInfo(nodePath, init, currentDatabaseName, filePath);
164
+ if (actionInfo) result.actions.push(actionInfo);
165
+ }
166
+ }
167
+ });
168
+ return result;
169
+ }
170
+ /**
171
+ * Check if a node is a defineDatabase() call
172
+ */
173
+ function isDefineDatabaseCall(node) {
174
+ return t.isCallExpression(node) && t.isIdentifier(node.callee) && node.callee.name === "defineDatabase";
175
+ }
176
+ /**
177
+ * Check if a node is an action() call with the given factory name
178
+ */
179
+ function isActionCall(node, actionFnName) {
180
+ return t.isCallExpression(node) && t.isIdentifier(node.callee) && node.callee.name === actionFnName;
181
+ }
182
+ /**
183
+ * Extract the 'action' variable name from destructuring pattern
184
+ * const { action } = defineDatabase(...)
185
+ * ^^^^^^^
186
+ */
187
+ function extractActionFactoryName(pattern) {
188
+ for (const prop of pattern.properties) {
189
+ if (t.isRestElement(prop)) continue;
190
+ if (t.isObjectProperty(prop) && t.isIdentifier(prop.key) && prop.key.name === "action") {
191
+ if (t.isIdentifier(prop.value)) return prop.value.name;
192
+ return "action";
193
+ }
194
+ }
195
+ return null;
196
+ }
197
+ /**
198
+ * Warn when a defineDatabase() config property uses a non-literal value
199
+ * that can't be statically analyzed.
200
+ */
201
+ function warnNonLiteral(filePath, key, defaultValue) {
202
+ 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}'.`);
203
+ }
204
+ /**
205
+ * Extract database configuration from a defineDatabase() call
206
+ */
207
+ function extractDatabaseInfo(declaratorPath, callExpr, filePath, imports) {
208
+ const configArg = callExpr.arguments[0];
209
+ if (!t.isObjectExpression(configArg)) return null;
210
+ let instance = "per-tenant";
211
+ let browsable = false;
212
+ let transport = "rpc";
213
+ let schemaImport = null;
214
+ const schemaTableNames = [];
215
+ for (const prop of configArg.properties) {
216
+ if (!t.isObjectProperty(prop) || !t.isIdentifier(prop.key)) continue;
217
+ const key = prop.key.name;
218
+ if (key === "instance") if (t.isStringLiteral(prop.value)) {
219
+ const value = prop.value.value;
220
+ if (value === "per-tenant" || value === "global") instance = value;
221
+ } else warnNonLiteral(filePath, "instance", "per-tenant");
222
+ if (key === "browsable") if (t.isBooleanLiteral(prop.value)) browsable = prop.value.value;
223
+ else if (t.isStringLiteral(prop.value) && prop.value.value === "development") browsable = "development";
224
+ else warnNonLiteral(filePath, "browsable", String(browsable));
225
+ if (key === "transport") if (t.isStringLiteral(prop.value)) {
226
+ const value = prop.value.value;
227
+ if (value === "rpc" || value === "websocket") transport = value;
228
+ } else warnNonLiteral(filePath, "transport", "rpc");
229
+ if (key === "schema" && t.isObjectExpression(prop.value)) {
230
+ for (const schemaProp of prop.value.properties) if (t.isObjectProperty(schemaProp) || t.isSpreadElement(schemaProp)) {
231
+ if (t.isObjectProperty(schemaProp) && t.isIdentifier(schemaProp.key)) {
232
+ const tableName = schemaProp.key.name;
233
+ schemaTableNames.push(tableName);
234
+ const importInfo = imports.get(tableName);
235
+ if (importInfo && !schemaImport) schemaImport = importInfo.source;
236
+ }
237
+ }
238
+ }
239
+ }
240
+ const name = path.basename(filePath).replace(/\.(ts|js)$/, "");
241
+ return {
242
+ filePath,
243
+ name,
244
+ className: toPascalCase(name) + "DatabaseDO",
245
+ bindingName: toScreamingSnakeCase(name) + "_DATABASE_DO",
246
+ instance,
247
+ browsable,
248
+ transport,
249
+ migrationsDir: "",
250
+ schemaImport,
251
+ schemaTableNames
252
+ };
253
+ }
254
+ /**
255
+ * Extract action information from an action() call
256
+ */
257
+ function extractActionInfo(declaratorPath, callExpr, databaseName, filePath) {
258
+ const id = declaratorPath.node.id;
259
+ if (!t.isIdentifier(id)) return null;
260
+ const exportName = id.name;
261
+ const configArg = callExpr.arguments[0];
262
+ if (!t.isObjectExpression(configArg)) return null;
263
+ let argsSchemaSource = "{}";
264
+ let handlerSource = "async () => {}";
265
+ for (const prop of configArg.properties) {
266
+ if (!t.isObjectProperty(prop) || !t.isIdentifier(prop.key)) continue;
267
+ const key = prop.key.name;
268
+ if (key === "args") argsSchemaSource = generateCode(prop.value);
269
+ if (key === "handler") handlerSource = generateCode(prop.value);
270
+ }
271
+ return {
272
+ exportName,
273
+ argsSchemaSource,
274
+ handlerSource,
275
+ databaseName,
276
+ sourceFile: filePath
277
+ };
278
+ }
279
+ /**
280
+ * Convert a string to PascalCase
281
+ */
282
+ function toPascalCase(str) {
283
+ return str.split(/[-_]/).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
284
+ }
285
+ /**
286
+ * Convert a string to SCREAMING_SNAKE_CASE
287
+ */
288
+ function toScreamingSnakeCase(str) {
289
+ return str.replace(/([a-z])([A-Z])/g, "$1_$2").replace(/[-]/g, "_").toUpperCase();
290
+ }
291
+
292
+ //#endregion
293
+ export { resolveImportPath as a, readFile as i, parseDatabaseFile as n, discoverDatabaseFiles as r, BABEL_PARSER_PLUGINS as t };
@@ -0,0 +1,35 @@
1
+ //#region src/transport/protocol.ts
2
+ function encodeRequest(req) {
3
+ return JSON.stringify(req);
4
+ }
5
+ function decodeRequest(data) {
6
+ const parsed = JSON.parse(data);
7
+ if (typeof parsed !== "object" || parsed === null) throw new Error(`Invalid WsActionRequest: expected object, got ${parsed === null ? "null" : typeof parsed}`);
8
+ const obj = parsed;
9
+ for (const field of [
10
+ "id",
11
+ "action",
12
+ "instanceKey"
13
+ ]) if (typeof obj[field] !== "string") throw new Error(`Invalid WsActionRequest: '${field}' must be a string, got ${describeType(obj[field])}`);
14
+ return obj;
15
+ }
16
+ function encodeResponse(res) {
17
+ return JSON.stringify(res);
18
+ }
19
+ function decodeResponse(data) {
20
+ const parsed = JSON.parse(data);
21
+ if (typeof parsed !== "object" || parsed === null) throw new Error(`Invalid WsActionResponse: expected object, got ${parsed === null ? "null" : typeof parsed}`);
22
+ const obj = parsed;
23
+ if (typeof obj.id !== "string") throw new Error(`Invalid WsActionResponse: 'id' must be a string, got ${describeType(obj.id)}`);
24
+ if (typeof obj.ok !== "boolean") throw new Error(`Invalid WsActionResponse: 'ok' must be a boolean, got ${describeType(obj.ok)}`);
25
+ if (!obj.ok && typeof obj.error !== "string") throw new Error(`Invalid WsActionResponse: 'error' must be a string when ok=false, got ${describeType(obj.error)}`);
26
+ return obj;
27
+ }
28
+ function describeType(value) {
29
+ if (value === null) return "null";
30
+ if (Array.isArray(value)) return "array";
31
+ return typeof value;
32
+ }
33
+
34
+ //#endregion
35
+ export { encodeResponse as i, decodeResponse as n, encodeRequest as r, decodeRequest as t };
@@ -0,0 +1,184 @@
1
+ import { i as init_debug, t as debugCli } from "./debug-BZJbKybf.js";
2
+ import { d as init_state, f as loadDevMigrations, h as saveDevMigration, n as clearDevMigrations } from "./state-FOEjpgJ6.js";
3
+ import { n as generateMigrationStatements, o as snapshotsEqual, r as generateSnapshotFromSchema } from "./snapshot-D170nL7i.js";
4
+ import { s as loadSnapshot, t as buildAndLoadSchema } from "./generator-BUPP9scJ.js";
5
+ import { a as resolveImportPath, i as readFile, n as parseDatabaseFile, r as discoverDatabaseFiles } from "./parser-CbX54Flt.js";
6
+ import * as path from "node:path";
7
+ import * as crypto from "node:crypto";
8
+
9
+ //#region src/cli/shared.ts
10
+ init_debug();
11
+ /**
12
+ * Print a caught error to stderr. Always shows the message; when verbose
13
+ * (flag or `DEBUG=*`) is set, also prints the stack so users can diagnose
14
+ * unexpected failures without patching the CLI.
15
+ */
16
+ function reportCliError(error, verbose = false) {
17
+ const showStack = verbose || Boolean(process.env.DEBUG);
18
+ if (error instanceof Error) {
19
+ console.error("Error:", error.message);
20
+ if (showStack && error.stack) console.error(error.stack);
21
+ return;
22
+ }
23
+ console.error("Error:", error);
24
+ }
25
+ /**
26
+ * Discover database files, parse them, and resolve migrationsDir.
27
+ * Returns parsed DatabaseInfo[] with migrationsDir already set.
28
+ */
29
+ function discoverDatabases(opts) {
30
+ const { projectRoot, databasesDir, migrationsDir, database } = opts;
31
+ const files = discoverDatabaseFiles({
32
+ projectRoot,
33
+ databasesDir
34
+ });
35
+ const databases = [];
36
+ for (const file of files) {
37
+ const code = readFile(file.absolutePath);
38
+ const parsed = parseDatabaseFile(file.absolutePath, code);
39
+ if (!parsed.database) continue;
40
+ if (database && parsed.database.name !== database) continue;
41
+ parsed.database.migrationsDir = path.resolve(projectRoot, migrationsDir, parsed.database.name);
42
+ databases.push(parsed.database);
43
+ }
44
+ return databases;
45
+ }
46
+ /**
47
+ * Load and validate schema for a database.
48
+ *
49
+ * Returns null only when the database genuinely declares no schema tables.
50
+ * Every other failure mode (inline tables, unresolvable import, build error,
51
+ * missing exports) throws — silently skipping a database is how a typo in
52
+ * schema.ts becomes "why is my migration empty" 20 minutes later, or worse,
53
+ * a generated migration that DROPs tables that still exist in production.
54
+ */
55
+ async function loadSchema(db) {
56
+ if (db.schemaTableNames.length === 0) {
57
+ debugCli("Skipping %s: no schema defined", db.name);
58
+ return null;
59
+ }
60
+ 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.`);
61
+ const schemaPath = resolveImportPath(db.filePath, db.schemaImport);
62
+ if (!schemaPath) throw new Error(`[db] Database '${db.name}': could not resolve schema import '${db.schemaImport}' from ${db.filePath}.`);
63
+ let schema;
64
+ try {
65
+ schema = await buildAndLoadSchema(schemaPath, db.schemaTableNames);
66
+ } catch (error) {
67
+ const message = error instanceof Error ? error.message : String(error);
68
+ debugCli("Failed to load schema for %s: %O", db.name, error);
69
+ throw new Error(`[db] Could not build schema for database '${db.name}' (${schemaPath}): ${message}`, { cause: error });
70
+ }
71
+ const missing = db.schemaTableNames.filter((name) => !(name in schema));
72
+ if (missing.length > 0) throw new Error(`[db] Database '${db.name}': schema module ${schemaPath} does not export: ${missing.join(", ")}. Every table referenced in defineDatabase({ schema }) must be exported from the same schema module.`);
73
+ return schema;
74
+ }
75
+ /**
76
+ * Diff a schema against the production snapshot in migrationsDir.
77
+ * Returns whether there are changes, the SQL statements, and both snapshots.
78
+ */
79
+ async function diffSchema(schema, migrationsDir) {
80
+ const prodSnapshot = loadSnapshot(migrationsDir);
81
+ const currentSnapshot = await generateSnapshotFromSchema(schema);
82
+ if (snapshotsEqual(prodSnapshot, currentSnapshot)) return {
83
+ hasChanges: false,
84
+ statements: [],
85
+ prodSnapshot,
86
+ currentSnapshot
87
+ };
88
+ const statements = await generateMigrationStatements(prodSnapshot, currentSnapshot);
89
+ return {
90
+ hasChanges: statements.length > 0,
91
+ statements,
92
+ prodSnapshot,
93
+ currentSnapshot
94
+ };
95
+ }
96
+
97
+ //#endregion
98
+ //#region src/cli/push.ts
99
+ init_state();
100
+ init_debug();
101
+ /**
102
+ * Push schema changes to dev migrations
103
+ *
104
+ * This command:
105
+ * 1. Discovers all databases in the project
106
+ * 2. For each database, diffs production snapshot against current schema
107
+ * 3. If changes detected, generates a single squashed dev migration
108
+ * 4. Uses content-hash naming so the same schema always produces the same
109
+ * migration name — the DO skips it if already applied
110
+ *
111
+ * Dev migrations are stored in node_modules/.cache/durable-db/
112
+ * and are ephemeral - they're cleared when running `db:generate` or `db:reset`
113
+ */
114
+ async function push(ctx = {}) {
115
+ const { projectRoot = process.cwd(), databasesDir = "src/databases", migrationsDir = "migrations" } = ctx;
116
+ const results = [];
117
+ const databases = discoverDatabases({
118
+ projectRoot,
119
+ databasesDir,
120
+ migrationsDir
121
+ });
122
+ if (databases.length === 0) {
123
+ debugCli("No databases found");
124
+ return results;
125
+ }
126
+ for (const db of databases) {
127
+ const result = await pushDatabase(projectRoot, db);
128
+ results.push(result);
129
+ }
130
+ return results;
131
+ }
132
+ /**
133
+ * Push a single database
134
+ *
135
+ * Always diffs from the production snapshot to the current schema,
136
+ * producing a single squashed dev migration with a deterministic
137
+ * content-hash name.
138
+ */
139
+ async function pushDatabase(projectRoot, db) {
140
+ const result = {
141
+ database: db.name,
142
+ hasChanges: false,
143
+ statements: [],
144
+ migrationName: null
145
+ };
146
+ const schema = await loadSchema(db);
147
+ if (!schema) return result;
148
+ const diff = await diffSchema(schema, db.migrationsDir);
149
+ if (!diff.hasChanges) {
150
+ debugCli("No changes for %s", db.name);
151
+ return result;
152
+ }
153
+ const safeStatements = diff.statements.map((s) => s.replace(/\bCREATE TABLE\b(?!\s+IF\s+NOT\s+EXISTS)/gi, "CREATE TABLE IF NOT EXISTS").replace(/\bCREATE INDEX\b(?!\s+IF\s+NOT\s+EXISTS)/gi, "CREATE INDEX IF NOT EXISTS").replace(/\bCREATE UNIQUE INDEX\b(?!\s+IF\s+NOT\s+EXISTS)/gi, "CREATE UNIQUE INDEX IF NOT EXISTS"));
154
+ const migrationName = `dev_${crypto.createHash("sha256").update(safeStatements.join("\n")).digest("hex").slice(0, 8)}`;
155
+ if (loadDevMigrations(projectRoot, db.name).has(migrationName)) {
156
+ debugCli("Migration %s already exists for %s, skipping", migrationName, db.name);
157
+ return result;
158
+ }
159
+ clearDevMigrations(projectRoot, db.name);
160
+ saveDevMigration(projectRoot, db.name, migrationName, safeStatements);
161
+ result.hasChanges = true;
162
+ result.statements = diff.statements;
163
+ result.migrationName = migrationName;
164
+ debugCli("Generated %s for %s (%d statements)", migrationName, db.name, diff.statements.length);
165
+ return result;
166
+ }
167
+ /**
168
+ * Push a single database by name
169
+ * Useful when you only want to push one specific database
170
+ */
171
+ async function pushOne(ctx = {}, dbName) {
172
+ const { projectRoot = process.cwd(), databasesDir = "src/databases", migrationsDir = "migrations" } = ctx;
173
+ const databases = discoverDatabases({
174
+ projectRoot,
175
+ databasesDir,
176
+ migrationsDir,
177
+ database: dbName
178
+ });
179
+ if (databases.length === 0) return null;
180
+ return await pushDatabase(projectRoot, databases[0]);
181
+ }
182
+
183
+ //#endregion
184
+ export { loadSchema as a, discoverDatabases as i, pushOne as n, reportCliError as o, diffSchema as r, push as t };
@@ -0,0 +1,8 @@
1
+ import "./debug-BZJbKybf.js";
2
+ import "./state-FOEjpgJ6.js";
3
+ import "./snapshot-D170nL7i.js";
4
+ import "./generator-BUPP9scJ.js";
5
+ import "./parser-CbX54Flt.js";
6
+ import { n as pushOne, t as push } from "./push-BgQ5cnfH.js";
7
+
8
+ export { push };
@@ -0,0 +1,28 @@
1
+ //#region src/registry.d.ts
2
+ interface ActionDefinition {
3
+ validator: (args: unknown) => unknown;
4
+ handler: (db: unknown, args: unknown, ctx: unknown) => Promise<unknown>;
5
+ }
6
+ interface DoContext {
7
+ db: unknown;
8
+ ctx: RpcContext;
9
+ dbName: string;
10
+ instanceKey: string;
11
+ }
12
+ interface RpcContext {
13
+ env: Record<string, unknown>;
14
+ dbName: string;
15
+ dbBindingNames: Record<string, string>;
16
+ dbTransports?: Record<string, 'rpc' | 'websocket'>;
17
+ instanceKey: string;
18
+ }
19
+ declare function registerAction(dbName: string, actionName: string, def: ActionDefinition): void;
20
+ declare function getAction(dbName: string, actionName: string): ActionDefinition | undefined;
21
+ declare function getDoContext(): DoContext | undefined;
22
+ declare function runWithDoContext<T>(store: DoContext, fn: () => T): T;
23
+ /**
24
+ * Call an action: validates args, then dispatches (direct call for same DB, RPC for cross-DB).
25
+ */
26
+ declare function callAction(db: unknown, targetDb: string, actionName: string, args: unknown, ctx: RpcContext): Promise<unknown>;
27
+ //#endregion
28
+ export { ActionDefinition, DoContext, RpcContext, callAction, getAction, getDoContext, registerAction, runWithDoContext };
@@ -0,0 +1,72 @@
1
+ import { n as WebSocketTransport } from "./websocket-Dx1fqwnF.js";
2
+ import { type } from "arktype";
3
+ import { AsyncLocalStorage } from "node:async_hooks";
4
+
5
+ //#region src/registry.ts
6
+ const actionsByDb = /* @__PURE__ */ new Map();
7
+ const als = new AsyncLocalStorage();
8
+ const wsTransportCache = /* @__PURE__ */ new Map();
9
+ function getOrCreateWsTransport(bindingName, instanceKey, stub) {
10
+ const cacheKey = `${bindingName}:${instanceKey}`;
11
+ let transport = wsTransportCache.get(cacheKey);
12
+ if (!transport) {
13
+ transport = new WebSocketTransport(stub);
14
+ wsTransportCache.set(cacheKey, transport);
15
+ }
16
+ return transport;
17
+ }
18
+ function registerAction(dbName, actionName, def) {
19
+ let dbMap = actionsByDb.get(dbName);
20
+ if (!dbMap) {
21
+ dbMap = /* @__PURE__ */ new Map();
22
+ actionsByDb.set(dbName, dbMap);
23
+ }
24
+ dbMap.set(actionName, def);
25
+ }
26
+ function getAction(dbName, actionName) {
27
+ return actionsByDb.get(dbName)?.get(actionName);
28
+ }
29
+ function getOrThrow(dbName, actionName) {
30
+ const entry = getAction(dbName, actionName);
31
+ if (!entry) {
32
+ const dbMap = actionsByDb.get(dbName);
33
+ if (!dbMap) {
34
+ const knownDbs = Array.from(actionsByDb.keys());
35
+ const dbList = knownDbs.length > 0 ? knownDbs.join(", ") : "(none registered)";
36
+ throw new Error(`[db] Action not registered: ${dbName}/${actionName} — database '${dbName}' has no registered actions. Known databases: ${dbList}.`);
37
+ }
38
+ const knownActions = Array.from(dbMap.keys());
39
+ const actionList = knownActions.length > 0 ? knownActions.join(", ") : "(none)";
40
+ throw new Error(`[db] Action not registered: ${dbName}/${actionName}. Actions registered on '${dbName}': ${actionList}.`);
41
+ }
42
+ return entry;
43
+ }
44
+ function getDoContext() {
45
+ return als.getStore();
46
+ }
47
+ function runWithDoContext(store, fn) {
48
+ return als.run(store, fn);
49
+ }
50
+ /**
51
+ * Call an action: validates args, then dispatches (direct call for same DB, RPC for cross-DB).
52
+ */
53
+ async function callAction(db, targetDb, actionName, args, ctx) {
54
+ const entry = getOrThrow(targetDb, actionName);
55
+ const validated = entry.validator(args);
56
+ if (validated instanceof type.errors) throw new Error(`[db] Invalid args for ${targetDb}/${actionName}: ${validated.summary}`);
57
+ if (ctx.dbName === targetDb) return entry.handler(db, validated, ctx);
58
+ const bindingName = ctx.dbBindingNames[targetDb];
59
+ if (!bindingName) {
60
+ const known = Object.keys(ctx.dbBindingNames);
61
+ const knownList = known.length > 0 ? known.join(", ") : "(none)";
62
+ throw new Error(`[db] Missing binding for db: ${targetDb}. Known database bindings: ${knownList}. This usually means the Vite plugin didn't discover '${targetDb}.ts' in your databases directory.`);
63
+ }
64
+ const binding = ctx.env[bindingName];
65
+ const id = binding.idFromName(ctx.instanceKey);
66
+ const stub = binding.get(id);
67
+ if (ctx.dbTransports?.[targetDb] === "websocket") return getOrCreateWsTransport(bindingName, ctx.instanceKey, stub).call(actionName, validated, ctx.instanceKey);
68
+ return stub.rpc(actionName, validated, { instanceKey: ctx.instanceKey });
69
+ }
70
+
71
+ //#endregion
72
+ export { callAction, getAction, getDoContext, registerAction, runWithDoContext };
@@ -0,0 +1,8 @@
1
+ import { blob, foreignKey, index, integer, numeric, primaryKey, real, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
2
+ import { toSnakeCase } from "drizzle-orm/casing";
3
+
4
+ //#region src/schema.ts
5
+ const table = ((name, columns, extraConfig) => sqliteTable(toSnakeCase(name), columns, extraConfig));
6
+
7
+ //#endregion
8
+ export { numeric as a, table as c, integer as i, text as l, foreignKey as n, primaryKey as o, index as r, real as s, blob as t, uniqueIndex as u };
@@ -0,0 +1,6 @@
1
+ import { AnySQLiteColumn, blob, foreignKey, index, integer, numeric, primaryKey, real, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
2
+
3
+ //#region src/schema.d.ts
4
+ declare const table: typeof sqliteTable;
5
+ //#endregion
6
+ export { integer as a, real as c, uniqueIndex as d, index as i, table as l, blob as n, numeric as o, foreignKey as r, primaryKey as s, AnySQLiteColumn as t, text as u };
@@ -0,0 +1,2 @@
1
+ import { a as integer, c as real, d as uniqueIndex, i as index, l as table, n as blob, o as numeric, r as foreignKey, s as primaryKey, t as AnySQLiteColumn, u as text } from "./schema-CpzTOfZ6.js";
2
+ export { AnySQLiteColumn, blob, foreignKey, index, integer, numeric, primaryKey, real, table, text, uniqueIndex };
package/dist/schema.js ADDED
@@ -0,0 +1,3 @@
1
+ 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-BOtrGnzM.js";
2
+
3
+ export { blob, foreignKey, index, integer, numeric, primaryKey, real, table, text, uniqueIndex };