durable-db 0.0.4 → 0.1.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/cli/bin.js +7 -7
- package/dist/cli/index.d.ts +9 -4
- package/dist/cli/index.js +7 -7
- package/dist/{cli-AzoPlqMA.js → cli-BtEsZzHF.js} +13 -12
- package/dist/context/index.d.ts +1 -1
- package/dist/context/index.js +3 -3
- package/dist/{context-BcWMofTp.js → context-NjS9iv2J.js} +2 -2
- package/dist/db/index.d.ts +2 -2
- package/dist/db/index.js +5 -386
- package/dist/{defineDatabase-B8do9yYZ.d.ts → defineDatabase-B8KJ1xYJ.d.ts} +1 -1
- package/dist/{defineDatabase-C91B-LMQ.js → defineDatabase-DXA53pG3.js} +20 -2
- package/dist/{generator-B4yBWHRz.js → generator-BVwDQvKA.js} +2 -2
- package/dist/{index-nm3-NwUh.d.ts → index-C5C4vaBs.d.ts} +19 -17
- package/dist/index.d.ts +3 -3
- package/dist/index.js +6 -6
- package/dist/kysely-yPsCWEvR.js +388 -0
- package/dist/migrations/generator.d.ts +1 -1
- package/dist/migrations/generator.js +3 -3
- package/dist/migrations/snapshot.d.ts +1 -1
- package/dist/migrations/snapshot.js +1 -1
- package/dist/{parser-qOiKNcYc.js → parser-B05psK1k.js} +129 -29
- package/dist/push-BW7sodiO.js +8 -0
- package/dist/{push-BymAOkB9.js → push-gXPr9k-l.js} +15 -9
- package/dist/registry.js +2 -2
- package/dist/schema.d.ts +1 -1
- package/dist/schema.js +1 -1
- package/dist/{state-DDHYOyvD.js → state-CMRjqCDw.js} +1 -1
- package/dist/{state-BUCIODvB.js → state-DCXcGtiu.js} +2 -2
- package/dist/testing/index.d.ts +57 -0
- package/dist/testing/index.js +72 -0
- package/dist/transport/protocol.js +1 -1
- package/dist/transport/websocket.js +1 -1
- package/dist/vite/durableDb.js +17 -9
- package/dist/{websocket-Cwc7933g.js → websocket-eao2rnHL.js} +1 -1
- package/package.json +5 -1
- package/dist/push-CT2aX_AM.js +0 -8
- /package/dist/{debug-BZJbKybf.js → debug-DzvNVBs5.js} +0 -0
- /package/dist/{index-DN2vKPw_.d.ts → index-DaDdJ_cg.d.ts} +0 -0
- /package/dist/{out-CuoxKfaH.js → out-on886o85.js} +0 -0
- /package/dist/{protocol-v7B4_9xU.js → protocol-DEubbBbR.js} +0 -0
- /package/dist/{schema-ou5L5I9Y.js → schema-IFq7ovQq.js} +0 -0
- /package/dist/{schema-CjGvnsaZ.d.ts → schema-suxWBY7-.d.ts} +0 -0
- /package/dist/{snapshot-CgEvcMZb.js → snapshot-DMW6j2Ix.js} +0 -0
- /package/dist/{snapshot-oD3wAJF2.d.ts → snapshot-DOerumb7.d.ts} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { i as init_debug } from "./debug-
|
|
1
|
+
import { i as init_debug, t as debugCli } from "./debug-DzvNVBs5.js";
|
|
2
2
|
import * as fs from "node:fs";
|
|
3
3
|
import * as path from "node:path";
|
|
4
4
|
import { parse } from "@babel/parser";
|
|
@@ -6,6 +6,116 @@ import _traverse from "@babel/traverse";
|
|
|
6
6
|
import _generate from "@babel/generator";
|
|
7
7
|
import * as t from "@babel/types";
|
|
8
8
|
|
|
9
|
+
//#region src/vite/modules/aliasResolver.ts
|
|
10
|
+
init_debug();
|
|
11
|
+
/**
|
|
12
|
+
* Import resolution for database files, driven by **Vite's** resolved config.
|
|
13
|
+
*
|
|
14
|
+
* The relative-import resolver only understands paths that start with `.`. Apps
|
|
15
|
+
* frequently import their schema / action factory through an alias instead
|
|
16
|
+
* (e.g. `@/databases/schema`, `~/foo`). Those aliases are NOT owned by
|
|
17
|
+
* durable-db — they come from the project's Vite config (`resolve.alias`),
|
|
18
|
+
* which is where tooling like rwsdk wires tsconfig `paths` (including aliases
|
|
19
|
+
* declared in a base tsconfig the app `extends`). So Vite's resolved config is
|
|
20
|
+
* the single source of truth for aliases.
|
|
21
|
+
*
|
|
22
|
+
* Two contexts consume this:
|
|
23
|
+
* - The **Vite plugin** captures `config.resolve.alias` in `configResolved` and
|
|
24
|
+
* passes it down (the plugin's action-file transform also defers to Vite's own
|
|
25
|
+
* resolver via `this.resolve(...)`, the most faithful resolution).
|
|
26
|
+
* - The **CLI** runs standalone, so it loads the project's Vite config with
|
|
27
|
+
* `resolveConfig(...)` and reads `config.resolve.alias` (cached per root).
|
|
28
|
+
*/
|
|
29
|
+
/**
|
|
30
|
+
* Probe a candidate path for a real file, trying the same extensions and index
|
|
31
|
+
* files the relative resolver uses. Shared between relative resolution and
|
|
32
|
+
* alias resolution so both code paths behave identically.
|
|
33
|
+
*/
|
|
34
|
+
function resolveFileCandidate(candidate) {
|
|
35
|
+
if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) return candidate;
|
|
36
|
+
for (const ext of [
|
|
37
|
+
".ts",
|
|
38
|
+
".tsx",
|
|
39
|
+
".js",
|
|
40
|
+
".jsx"
|
|
41
|
+
]) {
|
|
42
|
+
const withExt = candidate + ext;
|
|
43
|
+
if (fs.existsSync(withExt)) return withExt;
|
|
44
|
+
}
|
|
45
|
+
for (const indexFile of [
|
|
46
|
+
"index.ts",
|
|
47
|
+
"index.tsx",
|
|
48
|
+
"index.js",
|
|
49
|
+
"index.jsx"
|
|
50
|
+
]) {
|
|
51
|
+
const indexPath = path.join(candidate, indexFile);
|
|
52
|
+
if (fs.existsSync(indexPath)) return indexPath;
|
|
53
|
+
}
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Whether a Vite alias entry's `find` matches an import specifier. Mirrors
|
|
58
|
+
* `@rollup/plugin-alias` (which Vite uses): RegExp `find` is tested; string
|
|
59
|
+
* `find` matches an exact specifier or a `find/`-prefixed one.
|
|
60
|
+
*/
|
|
61
|
+
function matchesAlias(find, importee) {
|
|
62
|
+
if (find instanceof RegExp) return find.test(importee);
|
|
63
|
+
if (importee.length < find.length) return false;
|
|
64
|
+
if (importee === find) return true;
|
|
65
|
+
return importee.startsWith(find) && importee[find.length] === "/";
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Resolve an import specifier through Vite's `resolve.alias` entries.
|
|
69
|
+
*
|
|
70
|
+
* Rewrites the specifier with the first matching alias (mirroring Vite/rollup
|
|
71
|
+
* semantics), then runs the shared extension / index-file probing to land on a
|
|
72
|
+
* real file. Returns `null` when no alias matches or nothing resolves to a real
|
|
73
|
+
* file. Replacements are expected to be absolute (Vite normalizes them so);
|
|
74
|
+
* non-absolute replacements are skipped rather than resolved against `cwd`.
|
|
75
|
+
*/
|
|
76
|
+
function applyAliases(importSource, aliases) {
|
|
77
|
+
if (!aliases || aliases.length === 0) return null;
|
|
78
|
+
for (const entry of aliases) {
|
|
79
|
+
if (!matchesAlias(entry.find, importSource)) continue;
|
|
80
|
+
const replaced = importSource.replace(entry.find, entry.replacement);
|
|
81
|
+
if (!path.isAbsolute(replaced)) continue;
|
|
82
|
+
const resolved = resolveFileCandidate(replaced);
|
|
83
|
+
if (resolved) return resolved;
|
|
84
|
+
}
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Cache of resolved `resolve.alias` arrays keyed by absolute project root, so a
|
|
89
|
+
* single CLI run doesn't reload the (relatively expensive) Vite config.
|
|
90
|
+
*/
|
|
91
|
+
const viteAliasCache = /* @__PURE__ */ new Map();
|
|
92
|
+
/**
|
|
93
|
+
* Load the project's Vite config and return its resolved `resolve.alias`
|
|
94
|
+
* entries (the source of truth for aliases). Cached per root. Returns `[]` when
|
|
95
|
+
* the config can't be loaded — callers then fall back to relative-only
|
|
96
|
+
* resolution, which never needs aliases anyway.
|
|
97
|
+
*/
|
|
98
|
+
async function loadViteAliases(root) {
|
|
99
|
+
const key = path.resolve(root);
|
|
100
|
+
const cached = viteAliasCache.get(key);
|
|
101
|
+
if (cached) return cached;
|
|
102
|
+
let aliases = [];
|
|
103
|
+
try {
|
|
104
|
+
const { resolveConfig } = await import("vite");
|
|
105
|
+
aliases = (await resolveConfig({
|
|
106
|
+
root: key,
|
|
107
|
+
configFile: void 0,
|
|
108
|
+
logLevel: "silent"
|
|
109
|
+
}, "build")).resolve.alias ?? [];
|
|
110
|
+
} catch (error) {
|
|
111
|
+
debugCli("Could not load Vite config for alias resolution in %s: %O", key, error);
|
|
112
|
+
aliases = [];
|
|
113
|
+
}
|
|
114
|
+
viteAliasCache.set(key, aliases);
|
|
115
|
+
return aliases;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
//#endregion
|
|
9
119
|
//#region src/vite/modules/discovery.ts
|
|
10
120
|
/**
|
|
11
121
|
* Tracks directories we've already warned about to avoid duplicate noise
|
|
@@ -49,34 +159,24 @@ function discoverDatabaseFiles(options) {
|
|
|
49
159
|
return results;
|
|
50
160
|
}
|
|
51
161
|
/**
|
|
52
|
-
* Resolve
|
|
162
|
+
* Resolve an import path to an absolute path.
|
|
53
163
|
*
|
|
54
|
-
*
|
|
164
|
+
* Relative imports (starting with `.`) are the fast path — resolved directly
|
|
165
|
+
* against the importing file's directory. Non-relative imports are resolved
|
|
166
|
+
* through the project's Vite `resolve.alias` entries (e.g. `@/databases/schema`,
|
|
167
|
+
* `~/foo`); bare package imports that match no alias resolve to `null`. Both
|
|
168
|
+
* paths use the same extension / index file probing.
|
|
169
|
+
*
|
|
170
|
+
* `aliases` is the resolved Vite alias array — the source of truth for aliases.
|
|
171
|
+
* Callers in a standalone (no-plugin) context obtain it via `loadViteAliases()`;
|
|
172
|
+
* when omitted, only relative imports resolve.
|
|
55
173
|
*/
|
|
56
|
-
function resolveImportPath(fromFile, importSource) {
|
|
57
|
-
if (
|
|
58
|
-
|
|
59
|
-
|
|
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;
|
|
174
|
+
function resolveImportPath(fromFile, importSource, aliases) {
|
|
175
|
+
if (importSource.startsWith(".")) {
|
|
176
|
+
const dir = path.dirname(fromFile);
|
|
177
|
+
return resolveFileCandidate(path.resolve(dir, importSource));
|
|
78
178
|
}
|
|
79
|
-
return
|
|
179
|
+
return applyAliases(importSource, aliases);
|
|
80
180
|
}
|
|
81
181
|
/**
|
|
82
182
|
* Read file contents
|
|
@@ -121,7 +221,7 @@ function generateCode(node) {
|
|
|
121
221
|
*
|
|
122
222
|
* This uses clean AST traversal - no regexes
|
|
123
223
|
*/
|
|
124
|
-
function parseDatabaseFile(filePath, code) {
|
|
224
|
+
function parseDatabaseFile(filePath, code, options = {}) {
|
|
125
225
|
const ast = parseCode(code);
|
|
126
226
|
const result = {
|
|
127
227
|
filePath,
|
|
@@ -141,7 +241,7 @@ function parseDatabaseFile(filePath, code) {
|
|
|
141
241
|
source,
|
|
142
242
|
imported
|
|
143
243
|
});
|
|
144
|
-
if (imported === "action" && source.startsWith(".")) actionFnName = localName;
|
|
244
|
+
if (imported === "action" && (source.startsWith(".") || applyAliases(source, options.aliases) !== null)) actionFnName = localName;
|
|
145
245
|
} else if (t.isImportDefaultSpecifier(specifier)) result.localImports.set(specifier.local.name, {
|
|
146
246
|
source,
|
|
147
247
|
imported: "default"
|
|
@@ -290,4 +390,4 @@ function toScreamingSnakeCase(str) {
|
|
|
290
390
|
}
|
|
291
391
|
|
|
292
392
|
//#endregion
|
|
293
|
-
export { resolveImportPath as a, readFile as i, parseDatabaseFile as n, discoverDatabaseFiles as r, BABEL_PARSER_PLUGINS as t };
|
|
393
|
+
export { resolveImportPath as a, readFile as i, parseDatabaseFile as n, loadViteAliases as o, discoverDatabaseFiles as r, BABEL_PARSER_PLUGINS as t };
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { i as init_debug, t as debugCli } from "./debug-
|
|
2
|
-
import { d as init_state, f as loadDevMigrations, h as saveDevMigration, n as clearDevMigrations } from "./state-
|
|
3
|
-
import { n as generateMigrationStatements, o as snapshotsEqual, r as generateSnapshotFromSchema } from "./snapshot-
|
|
4
|
-
import { s as loadSnapshot, t as buildAndLoadSchema } from "./generator-
|
|
5
|
-
import { a as resolveImportPath, i as readFile, n as parseDatabaseFile, r as discoverDatabaseFiles } from "./parser-
|
|
1
|
+
import { i as init_debug, t as debugCli } from "./debug-DzvNVBs5.js";
|
|
2
|
+
import { d as init_state, f as loadDevMigrations, h as saveDevMigration, n as clearDevMigrations } from "./state-CMRjqCDw.js";
|
|
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-BVwDQvKA.js";
|
|
5
|
+
import { a as resolveImportPath, i as readFile, n as parseDatabaseFile, o as loadViteAliases, r as discoverDatabaseFiles } from "./parser-B05psK1k.js";
|
|
6
6
|
import * as path from "node:path";
|
|
7
7
|
import * as crypto from "node:crypto";
|
|
8
8
|
|
|
@@ -51,15 +51,21 @@ function discoverDatabases(opts) {
|
|
|
51
51
|
* missing exports) throws — silently skipping a database is how a typo in
|
|
52
52
|
* schema.ts becomes "why is my migration empty" 20 minutes later, or worse,
|
|
53
53
|
* a generated migration that DROPs tables that still exist in production.
|
|
54
|
+
*
|
|
55
|
+
* `projectRoot` enables alias resolution for non-relative schema imports
|
|
56
|
+
* (e.g. `@/databases/schema`): the project's Vite `resolve.alias` is loaded
|
|
57
|
+
* (cached) and used as the source of truth. Omit it to resolve relative
|
|
58
|
+
* imports only.
|
|
54
59
|
*/
|
|
55
|
-
async function loadSchema(db) {
|
|
60
|
+
async function loadSchema(db, projectRoot) {
|
|
56
61
|
if (db.schemaTableNames.length === 0) {
|
|
57
62
|
debugCli("Skipping %s: no schema defined", db.name);
|
|
58
63
|
return null;
|
|
59
64
|
}
|
|
60
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.`);
|
|
61
|
-
const
|
|
62
|
-
|
|
66
|
+
const aliases = projectRoot ? await loadViteAliases(projectRoot) : void 0;
|
|
67
|
+
const schemaPath = resolveImportPath(db.filePath, db.schemaImport, aliases);
|
|
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).`));
|
|
63
69
|
let schema;
|
|
64
70
|
try {
|
|
65
71
|
schema = await buildAndLoadSchema(schemaPath, db.schemaTableNames);
|
|
@@ -143,7 +149,7 @@ async function pushDatabase(projectRoot, db) {
|
|
|
143
149
|
statements: [],
|
|
144
150
|
migrationName: null
|
|
145
151
|
};
|
|
146
|
-
const schema = await loadSchema(db);
|
|
152
|
+
const schema = await loadSchema(db, projectRoot);
|
|
147
153
|
if (!schema) return result;
|
|
148
154
|
const diff = await diffSchema(schema, db.migrationsDir);
|
|
149
155
|
if (!diff.hasChanges) {
|
package/dist/registry.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as type } from "./out-
|
|
2
|
-
import { n as WebSocketTransport } from "./websocket-
|
|
1
|
+
import { t as type } from "./out-on886o85.js";
|
|
2
|
+
import { n as WebSocketTransport } from "./websocket-eao2rnHL.js";
|
|
3
3
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
4
4
|
|
|
5
5
|
//#region src/registry.ts
|
package/dist/schema.d.ts
CHANGED
|
@@ -1,2 +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-
|
|
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-suxWBY7-.js";
|
|
2
2
|
export { AnySQLiteColumn, blob, foreignKey, index, integer, numeric, primaryKey, real, table, text, uniqueIndex };
|
package/dist/schema.js
CHANGED
|
@@ -1,3 +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-
|
|
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-IFq7ovQq.js";
|
|
2
2
|
|
|
3
3
|
export { blob, foreignKey, index, integer, numeric, primaryKey, real, table, text, uniqueIndex };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as __esmMin, i as init_debug, o as __export, t as debugCli } from "./debug-
|
|
1
|
+
import { a as __esmMin, i as init_debug, o as __export, t as debugCli } from "./debug-DzvNVBs5.js";
|
|
2
2
|
import * as fs from "node:fs";
|
|
3
3
|
import * as path from "node:path";
|
|
4
4
|
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import "./debug-
|
|
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-
|
|
1
|
+
import "./debug-DzvNVBs5.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-CMRjqCDw.js";
|
|
3
3
|
|
|
4
4
|
init_state();
|
|
5
5
|
export { loadDevMigrations };
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { SQLiteTableWithColumns } from "drizzle-orm/sqlite-core";
|
|
2
|
+
import { Kysely } from "kysely";
|
|
3
|
+
import { DatabaseSync } from "node:sqlite";
|
|
4
|
+
|
|
5
|
+
//#region src/testing/index.d.ts
|
|
6
|
+
type Schema = Record<string, SQLiteTableWithColumns<any>>;
|
|
7
|
+
interface CreateTestDatabaseOptions {
|
|
8
|
+
/**
|
|
9
|
+
* The drizzle schema (the same object passed to `defineDatabase({ schema })`).
|
|
10
|
+
* Tables are created from it automatically.
|
|
11
|
+
*/
|
|
12
|
+
schema: Schema;
|
|
13
|
+
/**
|
|
14
|
+
* Explicit `CREATE TABLE …` (and index) statements to apply instead of
|
|
15
|
+
* deriving them from `schema`. Useful to pin a known DDL or test a migration.
|
|
16
|
+
*/
|
|
17
|
+
statements?: string[];
|
|
18
|
+
/**
|
|
19
|
+
* Tenant id handlers see via `getTenantId()`. Defaults to `'test'`. The
|
|
20
|
+
* in-memory db is a single shared store regardless — this only affects code
|
|
21
|
+
* that reads the tenant id.
|
|
22
|
+
*/
|
|
23
|
+
tenantId?: string;
|
|
24
|
+
}
|
|
25
|
+
interface TestDatabase<TSchema = any> {
|
|
26
|
+
/** The Kysely instance, for direct seeding and assertions. */
|
|
27
|
+
db: Kysely<TSchema>;
|
|
28
|
+
/**
|
|
29
|
+
* Run an `action()` the way production does: validate `args` with the
|
|
30
|
+
* action's arktype schema, then invoke its handler against {@link db}.
|
|
31
|
+
* Throws the same "Invalid args" error as production on a bad payload.
|
|
32
|
+
*/
|
|
33
|
+
run<TArgs, TResult>(action: (args: TArgs) => Promise<TResult>, args: TArgs): Promise<TResult>;
|
|
34
|
+
/** The raw `node:sqlite` handle, for escape-hatch SQL. */
|
|
35
|
+
sqlite: DatabaseSync;
|
|
36
|
+
/** Close the database and clear the tenant resolver. */
|
|
37
|
+
destroy(): void;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Spin up an isolated in-memory database for a `defineDatabase` schema and run
|
|
41
|
+
* its actions against it.
|
|
42
|
+
*
|
|
43
|
+
* @example
|
|
44
|
+
* ```ts
|
|
45
|
+
* import { createTestDatabase } from 'durable-db/testing';
|
|
46
|
+
* import { settings, shipments } from '../src/databases/schema';
|
|
47
|
+
* import { upsertShipment, listShipments } from '../src/databases/actions';
|
|
48
|
+
*
|
|
49
|
+
* const t = await createTestDatabase({ schema: { settings, shipments } });
|
|
50
|
+
* await t.run(upsertShipment, { orderId: 'gid://…/1', status: 'booked', … });
|
|
51
|
+
* expect(await t.run(listShipments, {})).toHaveLength(1);
|
|
52
|
+
* t.destroy();
|
|
53
|
+
* ```
|
|
54
|
+
*/
|
|
55
|
+
declare function createTestDatabase<TSchema = any>(options: CreateTestDatabaseOptions): Promise<TestDatabase<TSchema>>;
|
|
56
|
+
//#endregion
|
|
57
|
+
export { CreateTestDatabaseOptions, TestDatabase, createTestDatabase };
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import "../debug-DzvNVBs5.js";
|
|
2
|
+
import { t as type } from "../out-on886o85.js";
|
|
3
|
+
import { t as ACTION_TEST_META } from "../defineDatabase-DXA53pG3.js";
|
|
4
|
+
import "../state-CMRjqCDw.js";
|
|
5
|
+
import { a as setTenantIdResolver } from "../context-NjS9iv2J.js";
|
|
6
|
+
import { t as createKyselyFromSql } from "../kysely-yPsCWEvR.js";
|
|
7
|
+
import { n as generateMigrationStatements, r as generateSnapshotFromSchema, t as createEmptySnapshot } from "../snapshot-DMW6j2Ix.js";
|
|
8
|
+
import { createRequire } from "node:module";
|
|
9
|
+
|
|
10
|
+
//#region src/testing/index.ts
|
|
11
|
+
const loadSqlite = () => createRequire(import.meta.url)("node:sqlite");
|
|
12
|
+
/**
|
|
13
|
+
* A `SqlStorage`-shaped shim over a synchronous `node:sqlite` connection — the
|
|
14
|
+
* minimal surface `createKyselyFromSql` drives (`exec(sql, …params).toArray()`).
|
|
15
|
+
*/
|
|
16
|
+
function sqlStorageShim(sqlite) {
|
|
17
|
+
const isReader = (sql) => /^\s*(SELECT|PRAGMA|WITH)/i.test(sql) || /\bRETURNING\b/i.test(sql);
|
|
18
|
+
const normalize = (p) => typeof p === "boolean" ? p ? 1 : 0 : p === void 0 ? null : p;
|
|
19
|
+
return { exec(query, ...bindings) {
|
|
20
|
+
const stmt = sqlite.prepare(query);
|
|
21
|
+
const params = bindings.map(normalize);
|
|
22
|
+
const rows = isReader(query) ? stmt.all(...params) : (stmt.run(...params), []);
|
|
23
|
+
return { toArray: () => rows };
|
|
24
|
+
} };
|
|
25
|
+
}
|
|
26
|
+
async function deriveStatements(schema) {
|
|
27
|
+
const snapshot = await generateSnapshotFromSchema(schema);
|
|
28
|
+
return generateMigrationStatements(createEmptySnapshot(), snapshot);
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Spin up an isolated in-memory database for a `defineDatabase` schema and run
|
|
32
|
+
* its actions against it.
|
|
33
|
+
*
|
|
34
|
+
* @example
|
|
35
|
+
* ```ts
|
|
36
|
+
* import { createTestDatabase } from 'durable-db/testing';
|
|
37
|
+
* import { settings, shipments } from '../src/databases/schema';
|
|
38
|
+
* import { upsertShipment, listShipments } from '../src/databases/actions';
|
|
39
|
+
*
|
|
40
|
+
* const t = await createTestDatabase({ schema: { settings, shipments } });
|
|
41
|
+
* await t.run(upsertShipment, { orderId: 'gid://…/1', status: 'booked', … });
|
|
42
|
+
* expect(await t.run(listShipments, {})).toHaveLength(1);
|
|
43
|
+
* t.destroy();
|
|
44
|
+
* ```
|
|
45
|
+
*/
|
|
46
|
+
async function createTestDatabase(options) {
|
|
47
|
+
const { schema, statements, tenantId = "test" } = options;
|
|
48
|
+
const { DatabaseSync } = loadSqlite();
|
|
49
|
+
const sqlite = new DatabaseSync(":memory:");
|
|
50
|
+
const db = createKyselyFromSql(sqlStorageShim(sqlite), { schema });
|
|
51
|
+
const ddl = statements ?? await deriveStatements(schema);
|
|
52
|
+
for (const stmt of ddl) sqlite.exec(stmt);
|
|
53
|
+
setTenantIdResolver(() => tenantId);
|
|
54
|
+
return {
|
|
55
|
+
db,
|
|
56
|
+
async run(action, args) {
|
|
57
|
+
const meta = action[ACTION_TEST_META];
|
|
58
|
+
if (!meta) throw new Error("createTestDatabase().run() was given a function that is not a durable-db action (no test metadata). Pass an export created by `action({ … })`.");
|
|
59
|
+
const validated = meta.validator(args);
|
|
60
|
+
if (validated instanceof type.errors) throw new Error(`Invalid args for action: ${validated.summary}`);
|
|
61
|
+
return await meta.handler(db, validated);
|
|
62
|
+
},
|
|
63
|
+
sqlite,
|
|
64
|
+
destroy() {
|
|
65
|
+
setTenantIdResolver(null);
|
|
66
|
+
sqlite.close();
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
//#endregion
|
|
72
|
+
export { createTestDatabase };
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { i as encodeResponse, n as decodeResponse, r as encodeRequest, t as decodeRequest } from "../protocol-
|
|
1
|
+
import { i as encodeResponse, n as decodeResponse, r as encodeRequest, t as decodeRequest } from "../protocol-DEubbBbR.js";
|
|
2
2
|
|
|
3
3
|
export { decodeRequest, decodeResponse, encodeRequest, encodeResponse };
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { n as WebSocketTransport, t as DEFAULT_WS_REQUEST_TIMEOUT_MS } from "../websocket-
|
|
1
|
+
import { n as WebSocketTransport, t as DEFAULT_WS_REQUEST_TIMEOUT_MS } from "../websocket-eao2rnHL.js";
|
|
2
2
|
|
|
3
3
|
export { DEFAULT_WS_REQUEST_TIMEOUT_MS, WebSocketTransport };
|
package/dist/vite/durableDb.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { i as init_debug, r as debugVite } from "../debug-
|
|
2
|
-
import { _ as saveDevState, c as getDevPaths, d as init_state, m as loadDevState } from "../state-
|
|
3
|
-
import "../snapshot-
|
|
4
|
-
import { a as loadMigrationFiles } from "../generator-
|
|
5
|
-
import { i as readFile, n as parseDatabaseFile, r as discoverDatabaseFiles, t as BABEL_PARSER_PLUGINS } from "../parser-
|
|
1
|
+
import { i as init_debug, r as debugVite } from "../debug-DzvNVBs5.js";
|
|
2
|
+
import { _ as saveDevState, c as getDevPaths, d as init_state, m as loadDevState } from "../state-CMRjqCDw.js";
|
|
3
|
+
import "../snapshot-DMW6j2Ix.js";
|
|
4
|
+
import { a as loadMigrationFiles } from "../generator-BVwDQvKA.js";
|
|
5
|
+
import { i as readFile, n as parseDatabaseFile, r as discoverDatabaseFiles, t as BABEL_PARSER_PLUGINS } from "../parser-B05psK1k.js";
|
|
6
6
|
import * as fs from "node:fs";
|
|
7
7
|
import * as path from "node:path";
|
|
8
8
|
import { parse } from "@babel/parser";
|
|
@@ -753,6 +753,14 @@ var PluginState = class {
|
|
|
753
753
|
projectRoot = "";
|
|
754
754
|
config;
|
|
755
755
|
devServer = null;
|
|
756
|
+
/**
|
|
757
|
+
* Vite's resolved `resolve.alias` entries (the source of truth for aliases,
|
|
758
|
+
* including tsconfig `paths` wired in by frameworks like rwsdk). Passed to the
|
|
759
|
+
* parser so an `action` factory imported through an alias is recognized.
|
|
760
|
+
*/
|
|
761
|
+
get aliases() {
|
|
762
|
+
return this.config?.resolve?.alias ?? [];
|
|
763
|
+
}
|
|
756
764
|
selfDevStateWriteUntil = 0;
|
|
757
765
|
constructor(options) {
|
|
758
766
|
this.options = options;
|
|
@@ -813,7 +821,7 @@ var PluginState = class {
|
|
|
813
821
|
});
|
|
814
822
|
for (const file of files) {
|
|
815
823
|
const code = readFile(file.absolutePath);
|
|
816
|
-
const parsed = parseDatabaseFile(file.absolutePath, code);
|
|
824
|
+
const parsed = parseDatabaseFile(file.absolutePath, code, { aliases: this.aliases });
|
|
817
825
|
if (parsed.database) {
|
|
818
826
|
parsed.database.migrationsDir = path.resolve(this.projectRoot, this.options.migrationsDir, parsed.database.name);
|
|
819
827
|
this.databases.set(parsed.database.name, parsed.database);
|
|
@@ -837,7 +845,7 @@ var PluginState = class {
|
|
|
837
845
|
const isDev = this.config.command === "serve";
|
|
838
846
|
db.migrations = loadMigrationFiles(migrationsDir);
|
|
839
847
|
if (isDev) try {
|
|
840
|
-
const { loadDevMigrations } = await import("../state-
|
|
848
|
+
const { loadDevMigrations } = await import("../state-DCXcGtiu.js");
|
|
841
849
|
const devMigrations = loadDevMigrations(this.projectRoot, db.name);
|
|
842
850
|
for (const [name, chunks] of devMigrations) db.migrations.set(`_dev_${name}`, chunks);
|
|
843
851
|
if (devMigrations.size > 0) debugVite("Loaded %d dev migration(s) for %s", devMigrations.size, db.name);
|
|
@@ -980,7 +988,7 @@ function durableDb(options = {}) {
|
|
|
980
988
|
if (dbNameForPath) {
|
|
981
989
|
const database$1 = state.databases.get(dbNameForPath);
|
|
982
990
|
if (!database$1) return null;
|
|
983
|
-
const parsed$1 = parseDatabaseFile(cleanId, code);
|
|
991
|
+
const parsed$1 = parseDatabaseFile(cleanId, code, { aliases: state.aliases });
|
|
984
992
|
for (const action of parsed$1.actions) state.registerAction(action, dbNameForPath, cleanId);
|
|
985
993
|
const result$1 = transformDatabaseFile({
|
|
986
994
|
code,
|
|
@@ -993,7 +1001,7 @@ function durableDb(options = {}) {
|
|
|
993
1001
|
if (result$1 && parsed$1.actions.length > 0 && state.config.command === "serve") state.invalidateDOModule();
|
|
994
1002
|
return result$1;
|
|
995
1003
|
}
|
|
996
|
-
const parsed = parseDatabaseFile(cleanId, code);
|
|
1004
|
+
const parsed = parseDatabaseFile(cleanId, code, { aliases: state.aliases });
|
|
997
1005
|
if (parsed.actions.length === 0) return null;
|
|
998
1006
|
const importedDbName = await findImportedDatabase(this.resolve.bind(this), state, parsed.localImports, cleanId);
|
|
999
1007
|
if (!importedDbName) return null;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as decodeResponse, r as encodeRequest } from "./protocol-
|
|
1
|
+
import { n as decodeResponse, r as encodeRequest } from "./protocol-DEubbBbR.js";
|
|
2
2
|
|
|
3
3
|
//#region src/transport/websocket.ts
|
|
4
4
|
/** Default timeout (ms) after which a pending WebSocket request rejects. */
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "durable-db",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.1.1",
|
|
4
4
|
"repository": {
|
|
5
5
|
"type": "git",
|
|
6
6
|
"url": "https://github.com/eagerpatch/durable-db.git"
|
|
@@ -54,6 +54,10 @@
|
|
|
54
54
|
"types": "./dist/cli/index.d.ts",
|
|
55
55
|
"import": "./dist/cli/index.js"
|
|
56
56
|
},
|
|
57
|
+
"./testing": {
|
|
58
|
+
"types": "./dist/testing/index.d.ts",
|
|
59
|
+
"import": "./dist/testing/index.js"
|
|
60
|
+
},
|
|
57
61
|
"./virtual": {
|
|
58
62
|
"types": "./virtual.d.ts"
|
|
59
63
|
}
|
package/dist/push-CT2aX_AM.js
DELETED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|