durable-db 0.7.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +164 -0
- package/dist/cli/index.d.ts +2 -2
- package/dist/db/index.d.ts +4 -3
- package/dist/db/index.js +280 -8
- package/dist/defineDatabase-BvFOZVkv.d.ts +377 -0
- package/dist/defineDatabase-CaqKQagA.js +767 -0
- package/dist/describeAction-CEKfxTQ4.js +24 -0
- package/dist/{index-DOoXuKtZ.d.ts → index-DoxI1p4-.d.ts} +29 -1
- package/dist/index.d.ts +20 -3
- package/dist/index.js +3 -2
- package/dist/kysely-D8JQ4v8n.js +278 -0
- package/dist/outbox-D3Q9n7Rt.d.ts +41 -0
- package/dist/registry.d.ts +18 -0
- package/dist/registry.js +30 -2
- package/dist/schema.d.ts +15 -2
- package/dist/testing/index.d.ts +11 -0
- package/dist/testing/index.js +22 -4
- package/dist/vite/durableDb.d.ts +20 -2
- package/dist/vite/durableDb.js +73 -17
- package/package.json +1 -1
- package/virtual.d.ts +12 -0
- package/dist/defineDatabase-595bNB6M.js +0 -110
- package/dist/defineDatabase-COek3gjm.d.ts +0 -192
- package/dist/kysely-BZNv9gpz.js +0 -572
package/dist/vite/durableDb.js
CHANGED
|
@@ -781,12 +781,13 @@ function generateWithMap(ast, sourceFileName) {
|
|
|
781
781
|
comments: true
|
|
782
782
|
});
|
|
783
783
|
}
|
|
784
|
+
const OUTBOX_LOCAL = "__ddOutbox";
|
|
784
785
|
/**
|
|
785
786
|
* The module the worker re-exports its Durable Objects from: a class per
|
|
786
787
|
* database, plus a tombstone per class of a removed database the wrangler
|
|
787
788
|
* migrations still declare (`tombstones`, from `tombstoneClasses()`).
|
|
788
789
|
*/
|
|
789
|
-
function generateDurableObjectsModule(databases, registryImport, isDev = false, actionFiles = [], tombstones = []) {
|
|
790
|
+
function generateDurableObjectsModule(databases, registryImport, isDev = false, actionFiles = [], tombstones = [], outbox = null) {
|
|
790
791
|
const bindingNamesExpr = buildBindingNamesObject(databases);
|
|
791
792
|
const dbTransportsExpr = buildDbTransportsObject(databases);
|
|
792
793
|
const anyBrowsable = databases.some((db) => db.browsable === true || db.browsable === "development" && isDev);
|
|
@@ -803,13 +804,44 @@ function generateDurableObjectsModule(databases, registryImport, isDev = false,
|
|
|
803
804
|
];
|
|
804
805
|
if (anyBrowsable) imports.push(createNamedImport(["Browsable"], "@outerbase/browsable-durable-object"));
|
|
805
806
|
if (anyWebSocket) imports.push(createNamedImport(["decodeRequest", "encodeResponse"], "durable-db/transport/protocol"));
|
|
806
|
-
const
|
|
807
|
-
|
|
807
|
+
const outboxStatements = [];
|
|
808
|
+
if (outbox) {
|
|
809
|
+
if ("queue" in outbox) {
|
|
810
|
+
imports.push(createNamedImport(["queueOutboxSink"], "durable-db/db"));
|
|
811
|
+
outboxStatements.push(t.variableDeclaration("const", [t.variableDeclarator(t.identifier(OUTBOX_LOCAL), t.callExpression(t.identifier("queueOutboxSink"), [t.stringLiteral(outbox.queue)]))]));
|
|
812
|
+
} else {
|
|
813
|
+
imports.push(createNamedImport(["outboxSink"], "durable-db/db"));
|
|
814
|
+
imports.push(t.importDeclaration([t.importDefaultSpecifier(t.identifier(`${OUTBOX_LOCAL}Module`))], t.stringLiteral(outbox.module)));
|
|
815
|
+
outboxStatements.push(t.variableDeclaration("const", [t.variableDeclarator(t.identifier(OUTBOX_LOCAL), t.callExpression(t.identifier("outboxSink"), [t.identifier(`${OUTBOX_LOCAL}Module`)]))]));
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
const statements = [...imports, ...outboxStatements];
|
|
819
|
+
for (const db of databases) statements.push(...buildDurableObjectStatements(db, bindingNamesExpr, dbTransportsExpr, isDev, outbox !== null));
|
|
808
820
|
for (const tombstone of tombstones) statements.push(buildTombstoneStatement(tombstone));
|
|
809
821
|
const program = t.program(statements);
|
|
810
822
|
return generateCode(t.file(program));
|
|
811
823
|
}
|
|
812
824
|
/**
|
|
825
|
+
* `virtual:durable-db/__databases`: what the plugin discovered, for a library
|
|
826
|
+
* that needs to know which database a table belongs to —
|
|
827
|
+
*
|
|
828
|
+
* export const databases = [{ name, bindingName, className, instance, schema: { <table>: <the table> } }];
|
|
829
|
+
*
|
|
830
|
+
* The tables are imported from the schema module, as the Durable Object
|
|
831
|
+
* classes import them: the same objects the app's own code holds.
|
|
832
|
+
*/
|
|
833
|
+
function generateDatabasesModule(databases) {
|
|
834
|
+
const entries = databases.map((db) => t.objectExpression([
|
|
835
|
+
t.objectProperty(t.identifier("name"), t.stringLiteral(db.name)),
|
|
836
|
+
t.objectProperty(t.identifier("bindingName"), t.stringLiteral(db.bindingName)),
|
|
837
|
+
t.objectProperty(t.identifier("className"), t.stringLiteral(db.className)),
|
|
838
|
+
t.objectProperty(t.identifier("instance"), t.stringLiteral(db.instance)),
|
|
839
|
+
t.objectProperty(t.identifier("schema"), hasSchema(db) ? buildSchemaProperty(db).value : t.objectExpression([]))
|
|
840
|
+
]));
|
|
841
|
+
const program = t.program([...databases.filter(hasSchema).map(buildSchemaImport), t.exportNamedDeclaration(t.variableDeclaration("const", [t.variableDeclarator(t.identifier("databases"), t.arrayExpression(entries))]))]);
|
|
842
|
+
return generateCode(t.file(program));
|
|
843
|
+
}
|
|
844
|
+
/**
|
|
813
845
|
* `export class <Old>DatabaseDO extends RemovedDatabaseDurableObject { … }`:
|
|
814
846
|
* the class of a removed database, kept so the worker still exports every
|
|
815
847
|
* class its migrations declare — its storage untouched, every call refused.
|
|
@@ -842,7 +874,7 @@ function buildMigrationGuardMethod(name, params) {
|
|
|
842
874
|
* async rpc(...) { ... }
|
|
843
875
|
* }
|
|
844
876
|
*/
|
|
845
|
-
function buildDurableObjectStatements(db, bindingNamesExpr, dbTransportsExpr, isDev) {
|
|
877
|
+
function buildDurableObjectStatements(db, bindingNamesExpr, dbTransportsExpr, isDev, hasOutbox = false) {
|
|
846
878
|
const isBrowsable = db.browsable === true || db.browsable === "development" && isDev;
|
|
847
879
|
const rpcMethod = buildRpcMethod(db, bindingNamesExpr, dbTransportsExpr);
|
|
848
880
|
const migrationsProperty = t.classProperty(t.identifier("migrations"), buildMigrationsObject(db.migrations));
|
|
@@ -852,6 +884,7 @@ function buildDurableObjectStatements(db, bindingNamesExpr, dbTransportsExpr, is
|
|
|
852
884
|
databaseNameProperty,
|
|
853
885
|
buildSchemaProperty(db)
|
|
854
886
|
] : [migrationsProperty, databaseNameProperty];
|
|
887
|
+
if (hasOutbox) dataProperties.push(t.classProperty(t.identifier("outboxSink"), t.identifier(OUTBOX_LOCAL)));
|
|
855
888
|
const classMethods = [rpcMethod, buildSysMethod()];
|
|
856
889
|
if (db.transport === "websocket") classMethods.push(buildWebSocketMessageMethod(db, bindingNamesExpr, dbTransportsExpr));
|
|
857
890
|
if (!isBrowsable) {
|
|
@@ -908,6 +941,17 @@ function buildSysMethod() {
|
|
|
908
941
|
}, true)], [t.identifier("command")])]))]);
|
|
909
942
|
return t.classMethod("method", t.identifier("sys"), [t.identifier("command")], body, false, false, false, true);
|
|
910
943
|
}
|
|
944
|
+
/**
|
|
945
|
+
* `this.runWithOutbox(ctx, async () => entry.handler(this.db, validated, ctx))`:
|
|
946
|
+
* the handler with `ctx.outbox`, its messages written when it resolves.
|
|
947
|
+
*/
|
|
948
|
+
function buildOutboxHandlerCall() {
|
|
949
|
+
return t.callExpression(t.memberExpression(t.thisExpression(), t.identifier("runWithOutbox")), [t.identifier("ctx"), t.arrowFunctionExpression([], t.callExpression(t.memberExpression(t.identifier("entry"), t.identifier("handler")), [
|
|
950
|
+
t.memberExpression(t.thisExpression(), t.identifier("db")),
|
|
951
|
+
t.identifier("validated"),
|
|
952
|
+
t.identifier("ctx")
|
|
953
|
+
]), true)]);
|
|
954
|
+
}
|
|
911
955
|
function buildRpcMethod(db, bindingNamesExpr, dbTransportsExpr) {
|
|
912
956
|
const dbNameLiteral = t.stringLiteral(db.name);
|
|
913
957
|
const body = t.blockStatement([
|
|
@@ -941,11 +985,7 @@ function buildRpcMethod(db, bindingNamesExpr, dbTransportsExpr) {
|
|
|
941
985
|
t.objectProperty(t.identifier("ctx"), t.identifier("ctx")),
|
|
942
986
|
t.objectProperty(t.identifier("dbName"), dbNameLiteral),
|
|
943
987
|
t.objectProperty(t.identifier("instanceKey"), t.memberExpression(t.identifier("ctx"), t.identifier("instanceKey")))
|
|
944
|
-
]), t.arrowFunctionExpression([],
|
|
945
|
-
t.memberExpression(t.thisExpression(), t.identifier("db")),
|
|
946
|
-
t.identifier("validated"),
|
|
947
|
-
t.identifier("ctx")
|
|
948
|
-
]), true)]))
|
|
988
|
+
]), t.arrowFunctionExpression([], buildOutboxHandlerCall(), true)]))
|
|
949
989
|
]);
|
|
950
990
|
return t.classMethod("method", t.identifier("rpc"), [
|
|
951
991
|
t.identifier("method"),
|
|
@@ -1012,11 +1052,7 @@ function buildWebSocketMessageMethod(db, bindingNamesExpr, dbTransportsExpr) {
|
|
|
1012
1052
|
t.objectProperty(t.identifier("ctx"), t.identifier("ctx")),
|
|
1013
1053
|
t.objectProperty(t.identifier("dbName"), dbNameLiteral),
|
|
1014
1054
|
t.objectProperty(t.identifier("instanceKey"), t.memberExpression(t.identifier("ctx"), t.identifier("instanceKey")))
|
|
1015
|
-
]), t.arrowFunctionExpression([],
|
|
1016
|
-
t.memberExpression(t.thisExpression(), t.identifier("db")),
|
|
1017
|
-
t.identifier("validated"),
|
|
1018
|
-
t.identifier("ctx")
|
|
1019
|
-
]), true)])))]),
|
|
1055
|
+
]), t.arrowFunctionExpression([], buildOutboxHandlerCall(), true)])))]),
|
|
1020
1056
|
wsSendResponse([
|
|
1021
1057
|
t.objectProperty(t.identifier("id"), t.identifier("id"), false, true),
|
|
1022
1058
|
t.objectProperty(t.identifier("ok"), t.booleanLiteral(true)),
|
|
@@ -1126,7 +1162,12 @@ function applyActionTransforms(body, ctx) {
|
|
|
1126
1162
|
replaced.push(t.expressionStatement(t.callExpression(t.identifier("registerAction"), [
|
|
1127
1163
|
t.stringLiteral(dbName),
|
|
1128
1164
|
t.stringLiteral(exportName),
|
|
1129
|
-
t.objectExpression([
|
|
1165
|
+
t.objectExpression([
|
|
1166
|
+
t.objectProperty(t.identifier("validator"), t.arrowFunctionExpression([t.identifier("args")], t.callExpression(validatorId, [t.identifier("args")]))),
|
|
1167
|
+
t.objectProperty(t.identifier("handler"), handlerId),
|
|
1168
|
+
t.objectProperty(t.identifier("args"), validatorId),
|
|
1169
|
+
t.objectProperty(t.identifier("stub"), t.identifier(exportName))
|
|
1170
|
+
])
|
|
1130
1171
|
])));
|
|
1131
1172
|
const funcDecl = t.functionDeclaration(t.identifier(exportName), [t.identifier("args")], t.blockStatement(buildStubBodyStatements({
|
|
1132
1173
|
action,
|
|
@@ -1313,6 +1354,9 @@ const DURABLE_OBJECTS_ID = "durable-db/__durableObjects";
|
|
|
1313
1354
|
const VIRTUAL_DO_MODULE_ID = "\0virtual:durable-db/__durableObjects.js";
|
|
1314
1355
|
const DEV_EPOCH_ID = "durable-db/__devEpoch";
|
|
1315
1356
|
const VIRTUAL_DEV_EPOCH_MODULE_ID = "\0virtual:durable-db/__devEpoch.js";
|
|
1357
|
+
/** The discovered databases, for whoever imports it (nothing of durable-db's does). */
|
|
1358
|
+
const DATABASES_ID = "durable-db/__databases";
|
|
1359
|
+
const VIRTUAL_DATABASES_MODULE_ID = "\0virtual:durable-db/__databases.js";
|
|
1316
1360
|
/** Old org-prefixed spelling, still resolved for compatibility. */
|
|
1317
1361
|
const LEGACY_ID_PREFIX = "eagerpatch/";
|
|
1318
1362
|
/** Match a virtual id in all accepted spellings (`virtual:` optional, legacy prefix). */
|
|
@@ -1496,6 +1540,7 @@ var PluginState = class {
|
|
|
1496
1540
|
}
|
|
1497
1541
|
invalidateDOModule() {
|
|
1498
1542
|
this.invalidateVirtualModule(VIRTUAL_DO_MODULE_ID);
|
|
1543
|
+
this.invalidateVirtualModule(VIRTUAL_DATABASES_MODULE_ID);
|
|
1499
1544
|
}
|
|
1500
1545
|
invalidateDevEpochModule() {
|
|
1501
1546
|
this.invalidateVirtualModule(VIRTUAL_DEV_EPOCH_MODULE_ID);
|
|
@@ -1545,13 +1590,19 @@ async function findImportedDatabase(resolve, state, imports, importer) {
|
|
|
1545
1590
|
}
|
|
1546
1591
|
return null;
|
|
1547
1592
|
}
|
|
1593
|
+
/** A relative sink module resolves from the project root; a package specifier or an absolute path stays as it is. */
|
|
1594
|
+
function resolveOutbox(outbox, projectRoot) {
|
|
1595
|
+
if (!outbox || "queue" in outbox) return outbox;
|
|
1596
|
+
return outbox.module.startsWith(".") ? { module: path$1.resolve(projectRoot, outbox.module).split(path$1.sep).join("/") } : outbox;
|
|
1597
|
+
}
|
|
1548
1598
|
function durableDb(options = {}) {
|
|
1549
1599
|
const state = new PluginState({
|
|
1550
1600
|
contextImport: options.contextImport ?? "durable-db/context",
|
|
1551
1601
|
registryImport: options.registryImport ?? "durable-db/registry",
|
|
1552
1602
|
databasesDir: options.databasesDir ?? "src/databases",
|
|
1553
1603
|
migrationsDir: options.migrationsDir ?? "migrations",
|
|
1554
|
-
patchWranglerConfig: options.patchWranglerConfig ?? false
|
|
1604
|
+
patchWranglerConfig: options.patchWranglerConfig ?? false,
|
|
1605
|
+
outbox: options.outbox ?? null
|
|
1555
1606
|
});
|
|
1556
1607
|
return {
|
|
1557
1608
|
name: "durable-db",
|
|
@@ -1618,6 +1669,7 @@ function durableDb(options = {}) {
|
|
|
1618
1669
|
resolveId(id) {
|
|
1619
1670
|
if (matchesVirtualId(id, DURABLE_OBJECTS_ID)) return VIRTUAL_DO_MODULE_ID;
|
|
1620
1671
|
if (matchesVirtualId(id, DEV_EPOCH_ID)) return VIRTUAL_DEV_EPOCH_MODULE_ID;
|
|
1672
|
+
if (matchesVirtualId(id, DATABASES_ID)) return VIRTUAL_DATABASES_MODULE_ID;
|
|
1621
1673
|
return null;
|
|
1622
1674
|
},
|
|
1623
1675
|
async load(id) {
|
|
@@ -1636,6 +1688,10 @@ function durableDb(options = {}) {
|
|
|
1636
1688
|
}
|
|
1637
1689
|
return { code: generateDevEpochModule(epoch, databaseEpochs) };
|
|
1638
1690
|
}
|
|
1691
|
+
if (id === VIRTUAL_DATABASES_MODULE_ID) {
|
|
1692
|
+
await state.initialize();
|
|
1693
|
+
return { code: generateDatabasesModule(Array.from(state.databases.values())) };
|
|
1694
|
+
}
|
|
1639
1695
|
if (id !== VIRTUAL_DO_MODULE_ID) return null;
|
|
1640
1696
|
await state.initialize();
|
|
1641
1697
|
const isDev = state.config.command === "serve";
|
|
@@ -1644,7 +1700,7 @@ function durableDb(options = {}) {
|
|
|
1644
1700
|
databasesDir: state.options.databasesDir
|
|
1645
1701
|
});
|
|
1646
1702
|
const databases = Array.from(state.databases.values());
|
|
1647
|
-
return { code: generateDurableObjectsModule(databases, state.options.registryImport, isDev, actionFiles, tombstoneClasses(state.projectRoot, databases)) };
|
|
1703
|
+
return { code: generateDurableObjectsModule(databases, state.options.registryImport, isDev, actionFiles, tombstoneClasses(state.projectRoot, databases), resolveOutbox(state.options.outbox, state.projectRoot)) };
|
|
1648
1704
|
},
|
|
1649
1705
|
async transform(code, id) {
|
|
1650
1706
|
if (/[\\/]drizzle-orm[\\/]/.test(id)) return {
|
package/package.json
CHANGED
package/virtual.d.ts
CHANGED
|
@@ -13,5 +13,17 @@ declare module "virtual:durable-db/__devEpoch" {
|
|
|
13
13
|
export function applyDevEpoch(key: string, dbName?: string): string;
|
|
14
14
|
}
|
|
15
15
|
|
|
16
|
+
// The databases the plugin discovered, each with its tables (the schema
|
|
17
|
+
// module's own objects) — for a library that maps a table to its database.
|
|
18
|
+
declare module "virtual:durable-db/__databases" {
|
|
19
|
+
export const databases: ReadonlyArray<{
|
|
20
|
+
name: string;
|
|
21
|
+
bindingName: string;
|
|
22
|
+
className: string;
|
|
23
|
+
instance: 'per-tenant' | 'global';
|
|
24
|
+
schema: Record<string, unknown>;
|
|
25
|
+
}>;
|
|
26
|
+
}
|
|
27
|
+
|
|
16
28
|
/** @deprecated Use "virtual:durable-db/__durableObjects" instead. */
|
|
17
29
|
declare module "virtual:eagerpatch/durable-db/__durableObjects";
|
|
@@ -1,110 +0,0 @@
|
|
|
1
|
-
import { r as type } from "./type-CUgZsZp3.js";
|
|
2
|
-
import { t as actionArgsType } from "./actionArgs-DP2tQrlf.js";
|
|
3
|
-
//#region src/db/defineDatabase.ts
|
|
4
|
-
/**
|
|
5
|
-
* Non-enumerable property the source `action()` stashes on the function it
|
|
6
|
-
* returns, carrying the original `{ args, handler }` config plus the compiled
|
|
7
|
-
* arktype validator. The production Vite transform replaces `action()`
|
|
8
|
-
* call-sites entirely, so this only ever exists in the UNTRANSFORMED world —
|
|
9
|
-
* i.e. tests. The `durable-db/testing` harness reads it to run a handler
|
|
10
|
-
* against a real in-memory database. See src/testing/index.ts.
|
|
11
|
-
*/
|
|
12
|
-
const ACTION_TEST_META = Symbol.for("durable-db.actionTestMeta");
|
|
13
|
-
/**
|
|
14
|
-
* Where the live test databases are listed, newest last. On `globalThis`, not
|
|
15
|
-
* module state: a test run can load `durable-db` (the app's actions) and
|
|
16
|
-
* `durable-db/testing` as separate module copies.
|
|
17
|
-
*/
|
|
18
|
-
const LIVE_TEST_DATABASES = Symbol.for("durable-db.liveTestDatabases");
|
|
19
|
-
/** The live test databases (created on first use). */
|
|
20
|
-
function liveTestDatabases() {
|
|
21
|
-
const store = globalThis;
|
|
22
|
-
return store[LIVE_TEST_DATABASES] ??= [];
|
|
23
|
-
}
|
|
24
|
-
/** The newest live test database holding every table of `schema`, if any. */
|
|
25
|
-
function testDatabaseFor(schema) {
|
|
26
|
-
const tables = Object.values(schema);
|
|
27
|
-
if (tables.length === 0) return void 0;
|
|
28
|
-
const live = globalThis[LIVE_TEST_DATABASES];
|
|
29
|
-
if (!live) return void 0;
|
|
30
|
-
for (let i = live.length - 1; i >= 0; i--) if (tables.every((table) => live[i].tables.has(table))) return live[i];
|
|
31
|
-
}
|
|
32
|
-
/** `createTestDatabase({ schema: { a, b } })` for this database, for messages. */
|
|
33
|
-
function testDatabaseHint(schema) {
|
|
34
|
-
const names = Object.keys(schema);
|
|
35
|
-
return `createTestDatabase({ schema: { ${names.length > 0 ? names.join(", ") : "…"} } })`;
|
|
36
|
-
}
|
|
37
|
-
/**
|
|
38
|
-
* Define a database with its schema and migrations.
|
|
39
|
-
*
|
|
40
|
-
* This function is transformed at build time by the durable-db Vite plugin.
|
|
41
|
-
* At runtime, the actions returned will be RPC stubs that call into the
|
|
42
|
-
* generated Durable Object.
|
|
43
|
-
*
|
|
44
|
-
* Outside the build — code under test calling an action directly — an action
|
|
45
|
-
* runs against the test database `createTestDatabase()` created for its
|
|
46
|
-
* database's tables (the newest one, when there are several); without one it
|
|
47
|
-
* throws.
|
|
48
|
-
*
|
|
49
|
-
* @example
|
|
50
|
-
* ```ts
|
|
51
|
-
* import { defineDatabase } from 'durable-db';
|
|
52
|
-
* import { users, posts } from './schema';
|
|
53
|
-
*
|
|
54
|
-
* export const { action } = defineDatabase({
|
|
55
|
-
* schema: { users, posts },
|
|
56
|
-
* });
|
|
57
|
-
*
|
|
58
|
-
* export const createUser = action({
|
|
59
|
-
* args: { name: 'string', email: 'string.email' },
|
|
60
|
-
* handler: async (db, args) => {
|
|
61
|
-
* return db.insertInto('users').values({
|
|
62
|
-
* id: crypto.randomUUID(),
|
|
63
|
-
* name: args.name,
|
|
64
|
-
* email: args.email
|
|
65
|
-
* }).returningAll().executeTakeFirst();
|
|
66
|
-
* },
|
|
67
|
-
* });
|
|
68
|
-
* ```
|
|
69
|
-
*/
|
|
70
|
-
function defineDatabase(config) {
|
|
71
|
-
const schema = config?.schema ?? {};
|
|
72
|
-
const action = (actionConfig) => {
|
|
73
|
-
const validator = actionArgsType(actionConfig.args);
|
|
74
|
-
const argsDefinition = actionConfig.args;
|
|
75
|
-
const argKeys = argsDefinition !== null && typeof argsDefinition === "object" ? Object.keys(argsDefinition) : null;
|
|
76
|
-
const argsHint = argKeys ? ` (args: ${argKeys.length > 0 ? `{ ${argKeys.join(", ")} }` : "{}"})` : "";
|
|
77
|
-
const actionFn = async (args) => {
|
|
78
|
-
const testDatabase = testDatabaseFor(schema);
|
|
79
|
-
if (testDatabase) return await testDatabase.run(actionFn, args);
|
|
80
|
-
const result = validator(args);
|
|
81
|
-
if (result instanceof type.errors) throw new Error(`Invalid args for action${argsHint}: ${result.summary}`);
|
|
82
|
-
throw new Error(`Action${argsHint} called without transformation: action() call sites are transformed by the build; in tests, create the database with ${testDatabaseHint(schema)} and call the action, or use db.run(action, args).`);
|
|
83
|
-
};
|
|
84
|
-
Object.defineProperty(actionFn, ACTION_TEST_META, {
|
|
85
|
-
value: {
|
|
86
|
-
args: actionConfig.args,
|
|
87
|
-
handler: actionConfig.handler,
|
|
88
|
-
validator,
|
|
89
|
-
schema
|
|
90
|
-
},
|
|
91
|
-
enumerable: false,
|
|
92
|
-
configurable: true
|
|
93
|
-
});
|
|
94
|
-
return actionFn;
|
|
95
|
-
};
|
|
96
|
-
const destroyDatabase = async () => {
|
|
97
|
-
const testDatabase = testDatabaseFor(schema);
|
|
98
|
-
if (testDatabase) {
|
|
99
|
-
testDatabase.clear();
|
|
100
|
-
return;
|
|
101
|
-
}
|
|
102
|
-
throw new Error(`destroyDatabase() called without transformation: it is transformed by the build; in tests, create the database with ${testDatabaseHint(schema)} first.`);
|
|
103
|
-
};
|
|
104
|
-
return {
|
|
105
|
-
action,
|
|
106
|
-
destroyDatabase
|
|
107
|
-
};
|
|
108
|
-
}
|
|
109
|
-
//#endregion
|
|
110
|
-
export { defineDatabase as n, liveTestDatabases as r, ACTION_TEST_META as t };
|
|
@@ -1,192 +0,0 @@
|
|
|
1
|
-
import "./index-bUUlOWfP.js";
|
|
2
|
-
import { type } from "arktype";
|
|
3
|
-
import { SQLiteTableWithColumns } from "drizzle-orm/sqlite-core";
|
|
4
|
-
import { Kysely } from "kysely";
|
|
5
|
-
import { Kyselify } from "drizzle-orm/kysely";
|
|
6
|
-
//#region src/db/types.d.ts
|
|
7
|
-
/**
|
|
8
|
-
* Base type for ArkType schema definitions.
|
|
9
|
-
* This represents any valid arktype definition object.
|
|
10
|
-
*/
|
|
11
|
-
type ArgsSchema = Record<string, unknown>;
|
|
12
|
-
/**
|
|
13
|
-
* Configuration for defineDatabase
|
|
14
|
-
*/
|
|
15
|
-
interface DatabaseConfig<TSchema extends Record<string, SQLiteTableWithColumns<any>>> {
|
|
16
|
-
/** Drizzle schema tables */
|
|
17
|
-
schema: TSchema;
|
|
18
|
-
/** Instance strategy - 'per-tenant' (default) or 'global' */
|
|
19
|
-
instance?: 'per-tenant' | 'global';
|
|
20
|
-
/** Enable Outerbase Studio browsable SQL endpoint on this DO.
|
|
21
|
-
* - true: always enabled
|
|
22
|
-
* - false: always disabled (default)
|
|
23
|
-
* - 'development': enabled only in dev mode */
|
|
24
|
-
browsable?: boolean | 'development';
|
|
25
|
-
/** Transport for action stubs: 'rpc' (default) or 'websocket'.
|
|
26
|
-
* WebSocket uses Cloudflare's 20:1 message billing ratio for cheaper high-volume calls. */
|
|
27
|
-
transport?: 'rpc' | 'websocket';
|
|
28
|
-
}
|
|
29
|
-
/**
|
|
30
|
-
* Convert a Drizzle schema to Kysely database types using drizzle-kysely
|
|
31
|
-
*/
|
|
32
|
-
type DrizzleToKysely<TSchema extends Record<string, SQLiteTableWithColumns<any>>> = { [K in keyof TSchema]: TSchema[K] extends SQLiteTableWithColumns<any> ? Kyselify<TSchema[K]> : never; };
|
|
33
|
-
/**
|
|
34
|
-
* ArkType helpers – mirror Ark's own API:
|
|
35
|
-
* - arkType.validate<Def> → definition shape with DSL validation/autocomplete
|
|
36
|
-
* - arkType.infer<Def> → inferred output type
|
|
37
|
-
*/
|
|
38
|
-
type ArkDef<Def> = type.validate<Def>;
|
|
39
|
-
type InferArgs<Def> = type.infer<Def>;
|
|
40
|
-
/**
|
|
41
|
-
* Context passed to action handlers
|
|
42
|
-
*/
|
|
43
|
-
interface ActionContext<TEnv = unknown> {
|
|
44
|
-
/** Environment bindings (DO bindings, KV, etc.) */
|
|
45
|
-
env: TEnv;
|
|
46
|
-
/**
|
|
47
|
-
* The instance key used to address this Durable Object.
|
|
48
|
-
* For per-tenant databases, this is the tenant ID.
|
|
49
|
-
* For global databases, this is 'global'.
|
|
50
|
-
*/
|
|
51
|
-
instanceKey: string;
|
|
52
|
-
}
|
|
53
|
-
/**
|
|
54
|
-
* Configuration for an action
|
|
55
|
-
*
|
|
56
|
-
* `Def` is "the ArkType definition" – whatever you'd normally pass to `type(...)`:
|
|
57
|
-
* { name: "string", email: "string.email" }
|
|
58
|
-
* unions, tuples, ranges, etc. all work.
|
|
59
|
-
*/
|
|
60
|
-
interface ActionConfig<Def, TResult, TSchema extends Record<string, SQLiteTableWithColumns<any>>, TEnv = unknown> {
|
|
61
|
-
/**
|
|
62
|
-
* ArkType definition for args.
|
|
63
|
-
* Typed as `arkType.validate<Def>` so you get the SAME DSL autocomplete
|
|
64
|
-
* as when you do `type(Def)` directly.
|
|
65
|
-
*/
|
|
66
|
-
args: ArkDef<Def>;
|
|
67
|
-
/**
|
|
68
|
-
* The action handler
|
|
69
|
-
*/
|
|
70
|
-
handler: (db: Kysely<DrizzleToKysely<TSchema>>, args: InferArgs<Def>, ctx: ActionContext<TEnv>) => Promise<TResult>;
|
|
71
|
-
}
|
|
72
|
-
/**
|
|
73
|
-
* An action function that can be called from routes or other actions
|
|
74
|
-
*/
|
|
75
|
-
type Action<TArgs, TResult> = (args: TArgs) => Promise<TResult>;
|
|
76
|
-
/**
|
|
77
|
-
* Return type of defineDatabase
|
|
78
|
-
*/
|
|
79
|
-
interface DatabaseDefinition<TSchema extends Record<string, SQLiteTableWithColumns<any>>> {
|
|
80
|
-
/**
|
|
81
|
-
* Define an action that runs within the database context
|
|
82
|
-
*
|
|
83
|
-
* NOTE: the `const Def` *here* is crucial – it matches ArkType's own
|
|
84
|
-
* `<const def>(def: type.validate<def>)` pattern and is what makes
|
|
85
|
-
* `"string.email"` etc. behave properly.
|
|
86
|
-
*/
|
|
87
|
-
action: <const Def, TResult, TEnv = unknown>(config: ActionConfig<Def, TResult, TSchema, TEnv>) => Action<InferArgs<Def>, TResult>;
|
|
88
|
-
/**
|
|
89
|
-
* Destroy the database instance, clearing all data via `ctx.storage.deleteAll()`.
|
|
90
|
-
* The next action call will re-run migrations and start fresh.
|
|
91
|
-
*
|
|
92
|
-
* For per-tenant databases, targets the current tenant (via `getTenantId()`).
|
|
93
|
-
* For global databases, targets the single shared instance.
|
|
94
|
-
*/
|
|
95
|
-
destroyDatabase: () => Promise<void>;
|
|
96
|
-
}
|
|
97
|
-
/**
|
|
98
|
-
* Information about a parsed database file
|
|
99
|
-
*/
|
|
100
|
-
interface DatabaseInfo {
|
|
101
|
-
/** File path to the database definition file */
|
|
102
|
-
filePath: string;
|
|
103
|
-
/** Database name derived from filename */
|
|
104
|
-
name: string;
|
|
105
|
-
/** Class name for the Durable Object */
|
|
106
|
-
className: string;
|
|
107
|
-
/** Binding name for wrangler config */
|
|
108
|
-
bindingName: string;
|
|
109
|
-
/** Instance strategy */
|
|
110
|
-
instance: 'per-tenant' | 'global';
|
|
111
|
-
/** Path to migrations directory */
|
|
112
|
-
migrationsDir: string;
|
|
113
|
-
/** Schema import source (relative path) */
|
|
114
|
-
schemaImport: string | null;
|
|
115
|
-
/** Names of schema tables */
|
|
116
|
-
schemaTableNames: string[];
|
|
117
|
-
/** Whether the DO should expose a browsable SQL endpoint */
|
|
118
|
-
browsable: boolean | 'development';
|
|
119
|
-
/** Transport for action stubs */
|
|
120
|
-
transport: 'rpc' | 'websocket';
|
|
121
|
-
/** Loaded migrations - Map of name -> chunks (each chunk is array of SQL statements) */
|
|
122
|
-
migrations?: Map<string, string[][]>;
|
|
123
|
-
}
|
|
124
|
-
/**
|
|
125
|
-
* Information about a parsed action
|
|
126
|
-
*/
|
|
127
|
-
interface ActionInfo {
|
|
128
|
-
/** Export name of the action */
|
|
129
|
-
exportName: string;
|
|
130
|
-
/** The args schema (as source code string for codegen) */
|
|
131
|
-
argsSchemaSource: string;
|
|
132
|
-
/** The handler function (as source code string for codegen) */
|
|
133
|
-
handlerSource: string;
|
|
134
|
-
/** The database this action belongs to */
|
|
135
|
-
databaseName: string;
|
|
136
|
-
/** File where the action is defined */
|
|
137
|
-
sourceFile: string;
|
|
138
|
-
}
|
|
139
|
-
/**
|
|
140
|
-
* Result of parsing a database file
|
|
141
|
-
*/
|
|
142
|
-
interface ParsedDatabaseFile {
|
|
143
|
-
/** Absolute file path */
|
|
144
|
-
filePath: string;
|
|
145
|
-
/** Database configuration if this file has defineDatabase */
|
|
146
|
-
database: DatabaseInfo | null;
|
|
147
|
-
/** Actions defined in this file */
|
|
148
|
-
actions: ActionInfo[];
|
|
149
|
-
/** Local imports (for dependency resolution) */
|
|
150
|
-
localImports: Map<string, {
|
|
151
|
-
source: string;
|
|
152
|
-
imported: string;
|
|
153
|
-
}>;
|
|
154
|
-
}
|
|
155
|
-
//#endregion
|
|
156
|
-
//#region src/db/defineDatabase.d.ts
|
|
157
|
-
/**
|
|
158
|
-
* Define a database with its schema and migrations.
|
|
159
|
-
*
|
|
160
|
-
* This function is transformed at build time by the durable-db Vite plugin.
|
|
161
|
-
* At runtime, the actions returned will be RPC stubs that call into the
|
|
162
|
-
* generated Durable Object.
|
|
163
|
-
*
|
|
164
|
-
* Outside the build — code under test calling an action directly — an action
|
|
165
|
-
* runs against the test database `createTestDatabase()` created for its
|
|
166
|
-
* database's tables (the newest one, when there are several); without one it
|
|
167
|
-
* throws.
|
|
168
|
-
*
|
|
169
|
-
* @example
|
|
170
|
-
* ```ts
|
|
171
|
-
* import { defineDatabase } from 'durable-db';
|
|
172
|
-
* import { users, posts } from './schema';
|
|
173
|
-
*
|
|
174
|
-
* export const { action } = defineDatabase({
|
|
175
|
-
* schema: { users, posts },
|
|
176
|
-
* });
|
|
177
|
-
*
|
|
178
|
-
* export const createUser = action({
|
|
179
|
-
* args: { name: 'string', email: 'string.email' },
|
|
180
|
-
* handler: async (db, args) => {
|
|
181
|
-
* return db.insertInto('users').values({
|
|
182
|
-
* id: crypto.randomUUID(),
|
|
183
|
-
* name: args.name,
|
|
184
|
-
* email: args.email
|
|
185
|
-
* }).returningAll().executeTakeFirst();
|
|
186
|
-
* },
|
|
187
|
-
* });
|
|
188
|
-
* ```
|
|
189
|
-
*/
|
|
190
|
-
declare function defineDatabase<TSchema extends Record<string, SQLiteTableWithColumns<any>>>(config: DatabaseConfig<TSchema>): DatabaseDefinition<TSchema>;
|
|
191
|
-
//#endregion
|
|
192
|
-
export { ActionInfo as a, DatabaseDefinition as c, InferArgs as d, ParsedDatabaseFile as f, ActionContext as i, DatabaseInfo as l, Action as n, ArgsSchema as o, ActionConfig as r, DatabaseConfig as s, defineDatabase as t, DrizzleToKysely as u };
|