durable-db 0.9.0 → 0.11.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 +74 -6
- package/dist/cli/bin.js +1 -1
- package/dist/cli/index.d.ts +17 -2
- package/dist/cli/index.js +3 -2
- package/dist/{cli-CVS0b2im.js → cli-5KmSf8wx.js} +37 -7
- package/dist/db/index.d.ts +3 -3
- package/dist/db/index.js +3 -3
- package/dist/{defineDatabase-BvFOZVkv.d.ts → defineDatabase-BE7YRtLh.d.ts} +52 -7
- package/dist/{defineDatabase-CaqKQagA.js → defineDatabase-Cb5sMNg0.js} +459 -26
- package/dist/{index-DoxI1p4-.d.ts → index-CUkSkt7G.d.ts} +49 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/{kysely-D8JQ4v8n.js → kysely-q97dtmaQ.js} +3 -2
- package/dist/{parser-DyepmXzE.js → parser-mUnAtllk.js} +65 -15
- package/dist/testing/index.js +14 -4
- package/dist/vite/durableDb.d.ts +1 -1
- package/dist/vite/durableDb.js +21 -4
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import "./defineDatabase-
|
|
1
|
+
import "./defineDatabase-BE7YRtLh.js";
|
|
2
2
|
import { i as OutboxSink, t as Outbox } from "./outbox-D3Q9n7Rt.js";
|
|
3
3
|
import { SQLiteTableWithColumns } from "drizzle-orm/sqlite-core";
|
|
4
4
|
import { CamelCasePlugin, CamelCasePlugin as CamelCasePlugin$1, CompiledQuery, Kysely, Kysely as Kysely$1, KyselyPlugin, KyselyPlugin as KyselyPlugin$1, PluginTransformQueryArgs, PluginTransformResultArgs, QueryResult, QueryResult as QueryResult$1, RootOperationNode, UnknownRow } from "kysely";
|
|
@@ -416,6 +416,11 @@ declare class SchemaPlugin extends CamelCasePlugin {
|
|
|
416
416
|
constructor(schema: Record<string, SQLiteTableWithColumns<any>>);
|
|
417
417
|
protected snakeCase(str: string): string;
|
|
418
418
|
protected camelCase(str: string): string;
|
|
419
|
+
/**
|
|
420
|
+
* The key a result row has for an identifier a query writes as `name`: it
|
|
421
|
+
* is snake_cased on the way in and camelCased on the way out.
|
|
422
|
+
*/
|
|
423
|
+
resultKey(name: string): string;
|
|
419
424
|
}
|
|
420
425
|
/**
|
|
421
426
|
* Plugin that handles Drizzle's defaultFn and onUpdateFn during Kysely queries.
|
|
@@ -486,6 +491,46 @@ declare class DateSerializePlugin implements KyselyPlugin {
|
|
|
486
491
|
private transformRow;
|
|
487
492
|
private shouldDeserialize;
|
|
488
493
|
}
|
|
494
|
+
/**
|
|
495
|
+
* What a JSON-mode column holds, from what SQLite answered: text is parsed,
|
|
496
|
+
* bytes (a blob column) are read as UTF-8 first. What is no JSON — a row
|
|
497
|
+
* written before these columns were serialized — is answered as it is.
|
|
498
|
+
*/
|
|
499
|
+
declare function parseJsonValue(value: unknown): unknown;
|
|
500
|
+
interface JsonPluginOptions {
|
|
501
|
+
/**
|
|
502
|
+
* The key a result row has for an identifier as a query writes it —
|
|
503
|
+
* SchemaPlugin's `resultKey` when the names are camelCased. Default: the
|
|
504
|
+
* identifier itself.
|
|
505
|
+
*/
|
|
506
|
+
resultKey?: (name: string) => string;
|
|
507
|
+
}
|
|
508
|
+
/**
|
|
509
|
+
* The two plugins behind JSON-mode columns (`text({ mode: 'json' })`,
|
|
510
|
+
* `blob({ mode: 'json' })`): a value written to one is stored as its JSON, and
|
|
511
|
+
* one that is read comes back as the value.
|
|
512
|
+
*
|
|
513
|
+
* `write` goes before the plugin that renames identifiers and before
|
|
514
|
+
* DateSerializePlugin; `read` after them. In between they share which keys of
|
|
515
|
+
* a query's rows are JSON columns, worked out from what the query selects:
|
|
516
|
+
*
|
|
517
|
+
* - a column (`meta`, `i.meta`, `i.meta as m`) is resolved against the tables
|
|
518
|
+
* the query reads from — the same name in a table where it is another kind
|
|
519
|
+
* of column is left alone;
|
|
520
|
+
* - `selectAll()` / `returningAll()` are every JSON column of those tables;
|
|
521
|
+
* - where the source is no table of the schema (a subquery, a CTE, a raw
|
|
522
|
+
* query), a name goes for a JSON column when it is one in a table the query
|
|
523
|
+
* names (in any table, for a query that names none) and another kind of
|
|
524
|
+
* column in none of them.
|
|
525
|
+
*
|
|
526
|
+
* An expression (a JSON path, a function call, `related()`) is the caller's:
|
|
527
|
+
* it is neither serialized nor parsed. So is a value compared with a JSON
|
|
528
|
+
* column in a `where`.
|
|
529
|
+
*/
|
|
530
|
+
declare function createJsonPlugins(schema: Record<string, Table>, options?: JsonPluginOptions): {
|
|
531
|
+
write: KyselyPlugin;
|
|
532
|
+
read: KyselyPlugin;
|
|
533
|
+
};
|
|
489
534
|
/**
|
|
490
535
|
* Create all recommended plugins for use with Drizzle schemas.
|
|
491
536
|
*
|
|
@@ -494,9 +539,11 @@ declare class DateSerializePlugin implements KyselyPlugin {
|
|
|
494
539
|
* - SchemaPlugin (extends CamelCasePlugin): schema-aware camelCase ↔ snake_case
|
|
495
540
|
* - DateSerializePlugin: Date ↔ SQLite text serialization
|
|
496
541
|
* - BooleanDeserializePlugin: boolean-mode columns read back as booleans
|
|
542
|
+
* - createJsonPlugins' two: JSON-mode columns written as JSON and read back
|
|
543
|
+
* as their value — only for a schema that has such a column
|
|
497
544
|
*
|
|
498
545
|
* When camelCase is false, SchemaPlugin is omitted.
|
|
499
546
|
*/
|
|
500
547
|
declare function createDrizzlePlugins(schema: Record<string, SQLiteTableWithColumns<any>>, camelCase?: boolean): KyselyPlugin[];
|
|
501
548
|
//#endregion
|
|
502
|
-
export {
|
|
549
|
+
export { SqliteDurableObject as C, createKyselyFromSql as E, Migrations as S, SqlExecutor as T, RemovedDatabaseError as _, QueryResult$1 as a, MigrationAttemptInfo as b, DrizzleDefaultsPlugin as c, createDrizzlePlugins as d, createJsonPlugins as f, RemovedDatabaseDurableObject as g, DeleteClassMigration as h, KyselyPlugin$1 as i, JsonPluginOptions as l, parseJsonValue as m, CompiledQuery as n, studio as o, dateSerializers as p, Kysely$1 as r, DateSerializePlugin as s, CamelCasePlugin$1 as t, SchemaPlugin as u, removedDatabaseMessage as v, CreateKyselyOptions as w, MigrationSchemaConflictError as x, Migration as y };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { i as Type, l as type } from "./index-bUUlOWfP.js";
|
|
2
|
-
import {
|
|
2
|
+
import { C as RelationType, E as relationsOf, S as RelationMap, T as relationOf, _ as RelatedSpec, b as AnySchema, c as DatabaseDefinition, d as InferArgs, g as RelatedOptions, h as RelatedExpression, i as ActionContext, m as Related, n as Action, p as AnyRelated, r as ActionConfig, s as DatabaseConfig, t as defineDatabase, u as DrizzleToKysely, v as RelatedWhere, w as Relations, x as Relation, y as createRelated } from "./defineDatabase-BE7YRtLh.js";
|
|
3
3
|
import { a as OutboxSinkContext, i as OutboxSink, n as OutboxEnvelope, o as OutboxSinkModule, r as OutboxMessage, t as Outbox } from "./outbox-D3Q9n7Rt.js";
|
|
4
4
|
import { getTenantId, hasTenantId, setTenantIdResolver } from "./context/index.js";
|
|
5
5
|
import { AnySQLiteColumn, blob, foreignKey, index, integer, numeric, primaryKey, real, table, text, uniqueIndex } from "./schema.js";
|
|
@@ -20,4 +20,4 @@ interface ActionDescription {
|
|
|
20
20
|
/** The description of an action, or undefined for anything that is not one. */
|
|
21
21
|
export declare function describeAction(action: unknown): ActionDescription | undefined;
|
|
22
22
|
//#endregion
|
|
23
|
-
export { type Action, type ActionConfig, type ActionContext, type ActionDescription, type AnySQLiteColumn, type DatabaseConfig, type DatabaseDefinition, type DrizzleToKysely, type InferArgs, type Kysely, type Outbox, type OutboxEnvelope, type OutboxMessage, type OutboxSink, type OutboxSinkContext, type OutboxSinkModule, type Related, RelatedExpression, type RelatedOptions, type Relation, type RelationMap, type RelationType, type Relations, blob, defineDatabase, foreignKey, getTenantId, hasTenantId, index, integer, numeric, primaryKey, real, relationOf, relationsOf, setTenantIdResolver, table, text, type, uniqueIndex };
|
|
23
|
+
export { type Action, type ActionConfig, type ActionContext, type ActionDescription, type AnyRelated, type AnySQLiteColumn, type AnySchema, type DatabaseConfig, type DatabaseDefinition, type DrizzleToKysely, type InferArgs, type Kysely, type Outbox, type OutboxEnvelope, type OutboxMessage, type OutboxSink, type OutboxSinkContext, type OutboxSinkModule, type Related, RelatedExpression, type RelatedOptions, type RelatedSpec, type RelatedWhere, type Relation, type RelationMap, type RelationType, type Relations, blob, createRelated, defineDatabase, foreignKey, getTenantId, hasTenantId, index, integer, numeric, primaryKey, real, relationOf, relationsOf, setTenantIdResolver, table, text, type, uniqueIndex };
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { a as createRelated, h as relationsOf, i as RelatedExpression, m as relationOf, n as defineDatabase } from "./defineDatabase-Cb5sMNg0.js";
|
|
2
2
|
import { r as type } from "./type-CUgZsZp3.js";
|
|
3
3
|
import "./actionArgs-DP2tQrlf.js";
|
|
4
4
|
import { blob, foreignKey, index, integer, numeric, primaryKey, real, table, text, uniqueIndex } from "./schema.js";
|
|
5
5
|
import { n as describeAction } from "./describeAction-CEKfxTQ4.js";
|
|
6
6
|
import { getTenantId, hasTenantId, setTenantIdResolver } from "./context/index.js";
|
|
7
|
-
export { RelatedExpression, blob, defineDatabase, describeAction, foreignKey, getTenantId, hasTenantId, index, integer, numeric, primaryKey, real, relationOf, relationsOf, setTenantIdResolver, table, text, type, uniqueIndex };
|
|
7
|
+
export { RelatedExpression, blob, createRelated, defineDatabase, describeAction, foreignKey, getTenantId, hasTenantId, index, integer, numeric, primaryKey, real, relationOf, relationsOf, setTenantIdResolver, table, text, type, uniqueIndex };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { l as SchemaPlugin, o as createRelatedPlugins, s as DateSerializePlugin, u as createDrizzlePlugins } from "./defineDatabase-Cb5sMNg0.js";
|
|
2
2
|
import { CamelCasePlugin, Kysely, SqliteDialect, SqliteQueryCompiler } from "kysely";
|
|
3
3
|
//#region src/db/outbox.ts
|
|
4
4
|
/** A sink module's default export as a sink: a deliver function, or an object with one. */
|
|
@@ -255,7 +255,8 @@ function createKyselyFromSql(sqlStorage, options = {}) {
|
|
|
255
255
|
const { schema, plugins = [], camelCase = true } = options;
|
|
256
256
|
const sqliteDialect = new SqliteDialect({ database: null });
|
|
257
257
|
const allPlugins = [];
|
|
258
|
-
const
|
|
258
|
+
const naming = schema && camelCase ? new SchemaPlugin(schema) : void 0;
|
|
259
|
+
const related = schema ? createRelatedPlugins(schema, naming ? { resultKey: (name) => naming.resultKey(name) } : {}) : void 0;
|
|
259
260
|
if (related) allPlugins.push(related.capture);
|
|
260
261
|
if (schema) allPlugins.push(...createDrizzlePlugins(schema, camelCase));
|
|
261
262
|
else if (camelCase) {
|
|
@@ -332,6 +332,63 @@ function warnNonLiteral(filePath, key, defaultValue) {
|
|
|
332
332
|
console.warn(`[durable-db] '${key}' in defineDatabase() must be a static literal for build-time analysis. Got a dynamic expression in ${path$1.basename(filePath)} — defaulting to '${defaultValue}'.`);
|
|
333
333
|
}
|
|
334
334
|
/**
|
|
335
|
+
* Whether a database was given a schema discovery could read: tables listed
|
|
336
|
+
* in the call, or a const the schema module exports.
|
|
337
|
+
*/
|
|
338
|
+
function declaresSchema(db) {
|
|
339
|
+
return !!db.schemaExport || db.schemaTableNames.length > 0;
|
|
340
|
+
}
|
|
341
|
+
/** `x as const`, `x satisfies T`, `x!`: the expression itself. */
|
|
342
|
+
function unwrapExpression(node) {
|
|
343
|
+
let current = node;
|
|
344
|
+
while (t.isTSAsExpression(current) || t.isTSSatisfiesExpression(current) || t.isTSNonNullExpression(current)) current = current.expression;
|
|
345
|
+
return current;
|
|
346
|
+
}
|
|
347
|
+
/** `{ users, posts }`: the tables by name, and the module they are imported from. */
|
|
348
|
+
function listedTables(object, imports) {
|
|
349
|
+
const declared = {
|
|
350
|
+
schemaImport: null,
|
|
351
|
+
schemaExport: null,
|
|
352
|
+
schemaTableNames: []
|
|
353
|
+
};
|
|
354
|
+
for (const schemaProp of object.properties) if (t.isObjectProperty(schemaProp) && t.isIdentifier(schemaProp.key)) {
|
|
355
|
+
const tableName = schemaProp.key.name;
|
|
356
|
+
declared.schemaTableNames.push(tableName);
|
|
357
|
+
const importInfo = imports.get(tableName);
|
|
358
|
+
if (importInfo && !declared.schemaImport) declared.schemaImport = importInfo.source;
|
|
359
|
+
}
|
|
360
|
+
return declared;
|
|
361
|
+
}
|
|
362
|
+
/**
|
|
363
|
+
* The schema of a defineDatabase() call. Three shapes can be read:
|
|
364
|
+
*
|
|
365
|
+
* defineDatabase({ schema: { users, posts } }) // the tables, listed
|
|
366
|
+
* const schema = { users, posts }; // … or listed in a const of this file
|
|
367
|
+
* import { schema } from './schema'; // a const the schema module exports,
|
|
368
|
+
* defineDatabase({ schema }) // shared with whoever else needs the tables
|
|
369
|
+
*
|
|
370
|
+
* An imported const is not followed into its module here: it is recorded as
|
|
371
|
+
* the export to import (`schemaExport`), and whoever needs the tables loads it.
|
|
372
|
+
*/
|
|
373
|
+
function extractSchema(declaratorPath, value, filePath, imports) {
|
|
374
|
+
const node = unwrapExpression(value);
|
|
375
|
+
if (t.isObjectExpression(node)) return listedTables(node, imports);
|
|
376
|
+
if (t.isIdentifier(node)) {
|
|
377
|
+
const imported = imports.get(node.name);
|
|
378
|
+
if (imported && imported.imported !== "*") return {
|
|
379
|
+
schemaImport: imported.source,
|
|
380
|
+
schemaExport: imported.imported,
|
|
381
|
+
schemaTableNames: []
|
|
382
|
+
};
|
|
383
|
+
const binding = imported ? void 0 : declaratorPath.scope.getBinding(node.name);
|
|
384
|
+
const init = binding?.path.isVariableDeclarator() ? binding.path.node.init : null;
|
|
385
|
+
const local = init ? unwrapExpression(init) : null;
|
|
386
|
+
if (binding?.constant && t.isObjectExpression(local)) return listedTables(local, imports);
|
|
387
|
+
}
|
|
388
|
+
console.warn(`[durable-db] 'schema' in defineDatabase() is read at build time: list the tables ({ schema: { users, posts } }) or pass a const the schema module exports (import { schema } from './schema'). ${path$1.basename(filePath)} passes something else, so its database gets no schema — no migrations, no column mapping.`);
|
|
389
|
+
return null;
|
|
390
|
+
}
|
|
391
|
+
/**
|
|
335
392
|
* Extract database configuration from a defineDatabase() call
|
|
336
393
|
*/
|
|
337
394
|
function extractDatabaseInfo(declaratorPath, callExpr, filePath, imports, namePrefix) {
|
|
@@ -340,8 +397,11 @@ function extractDatabaseInfo(declaratorPath, callExpr, filePath, imports, namePr
|
|
|
340
397
|
let instance = "per-tenant";
|
|
341
398
|
let browsable = false;
|
|
342
399
|
let transport = "rpc";
|
|
343
|
-
let
|
|
344
|
-
|
|
400
|
+
let schema = {
|
|
401
|
+
schemaImport: null,
|
|
402
|
+
schemaExport: null,
|
|
403
|
+
schemaTableNames: []
|
|
404
|
+
};
|
|
345
405
|
for (const prop of configArg.properties) {
|
|
346
406
|
if (!t.isObjectProperty(prop) || !t.isIdentifier(prop.key)) continue;
|
|
347
407
|
const key = prop.key.name;
|
|
@@ -362,16 +422,7 @@ function extractDatabaseInfo(declaratorPath, callExpr, filePath, imports, namePr
|
|
|
362
422
|
if (value === "rpc" || value === "websocket") transport = value;
|
|
363
423
|
} else warnNonLiteral(filePath, "transport", "rpc");
|
|
364
424
|
}
|
|
365
|
-
if (key === "schema"
|
|
366
|
-
for (const schemaProp of prop.value.properties) if (t.isObjectProperty(schemaProp) || t.isSpreadElement(schemaProp)) {
|
|
367
|
-
if (t.isObjectProperty(schemaProp) && t.isIdentifier(schemaProp.key)) {
|
|
368
|
-
const tableName = schemaProp.key.name;
|
|
369
|
-
schemaTableNames.push(tableName);
|
|
370
|
-
const importInfo = imports.get(tableName);
|
|
371
|
-
if (importInfo && !schemaImport) schemaImport = importInfo.source;
|
|
372
|
-
}
|
|
373
|
-
}
|
|
374
|
-
}
|
|
425
|
+
if (key === "schema") schema = extractSchema(declaratorPath, prop.value, filePath, imports) ?? schema;
|
|
375
426
|
}
|
|
376
427
|
const base = path$1.basename(filePath).replace(/\.(ts|js)$/, "");
|
|
377
428
|
const name = namePrefix ? `${namePrefix}-${base}` : base;
|
|
@@ -384,8 +435,7 @@ function extractDatabaseInfo(declaratorPath, callExpr, filePath, imports, namePr
|
|
|
384
435
|
browsable,
|
|
385
436
|
transport,
|
|
386
437
|
migrationsDir: "",
|
|
387
|
-
|
|
388
|
-
schemaTableNames
|
|
438
|
+
...schema
|
|
389
439
|
};
|
|
390
440
|
}
|
|
391
441
|
/**
|
|
@@ -426,4 +476,4 @@ function toScreamingSnakeCase(str) {
|
|
|
426
476
|
return str.replace(/([a-z])([A-Z])/g, "$1_$2").replace(/[-]/g, "_").toUpperCase();
|
|
427
477
|
}
|
|
428
478
|
//#endregion
|
|
429
|
-
export {
|
|
479
|
+
export { databaseSources as a, readFile as c, toPascalCase as i, resolveImportPath as l, declaresSchema as n, discoverActionFiles as o, parseDatabaseFile as r, discoverDatabaseFiles as s, BABEL_PARSER_PLUGINS as t, loadViteAliases as u };
|
package/dist/testing/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { r as liveTestDatabases, t as ACTION_TEST_META } from "../defineDatabase-
|
|
1
|
+
import { r as liveTestDatabases, t as ACTION_TEST_META } from "../defineDatabase-Cb5sMNg0.js";
|
|
2
2
|
import { r as type } from "../type-CUgZsZp3.js";
|
|
3
3
|
import "../actionArgs-DP2tQrlf.js";
|
|
4
4
|
import { setTenantIdResolver } from "../context/index.js";
|
|
5
|
-
import { c as tenantOfInstanceKey, i as createActionOutbox, t as createKyselyFromSql } from "../kysely-
|
|
5
|
+
import { c as tenantOfInstanceKey, i as createActionOutbox, t as createKyselyFromSql } from "../kysely-q97dtmaQ.js";
|
|
6
6
|
import { i as generateSnapshotFromSchema, n as createEmptySnapshot, r as generateMigrationStatements } from "../snapshot-D_z95s6E.js";
|
|
7
7
|
import { createRequire } from "node:module";
|
|
8
8
|
//#region src/testing/index.ts
|
|
@@ -13,11 +13,21 @@ const loadSqlite = () => createRequire(import.meta.url)("node:sqlite");
|
|
|
13
13
|
*/
|
|
14
14
|
function sqlStorageShim(sqlite) {
|
|
15
15
|
const isReader = (sql) => /^\s*(SELECT|PRAGMA|WITH)/i.test(sql) || /\bRETURNING\b/i.test(sql);
|
|
16
|
-
const normalize = (p) => typeof p === "boolean" ? p ? 1 : 0 : p === void 0 ? null : p;
|
|
16
|
+
const normalize = (p) => typeof p === "boolean" ? p ? 1 : 0 : p === void 0 ? null : p instanceof ArrayBuffer ? new Uint8Array(p) : p;
|
|
17
|
+
const asStored = (row) => {
|
|
18
|
+
if (typeof row !== "object" || row === null) return row;
|
|
19
|
+
let out;
|
|
20
|
+
for (const [key, value] of Object.entries(row)) {
|
|
21
|
+
if (!(value instanceof Uint8Array)) continue;
|
|
22
|
+
out ??= { ...row };
|
|
23
|
+
out[key] = value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength);
|
|
24
|
+
}
|
|
25
|
+
return out ?? row;
|
|
26
|
+
};
|
|
17
27
|
return { exec(query, ...bindings) {
|
|
18
28
|
const stmt = sqlite.prepare(query);
|
|
19
29
|
const params = bindings.map(normalize);
|
|
20
|
-
const rows = isReader(query) ? stmt.all(...params) : (stmt.run(...params), []);
|
|
30
|
+
const rows = isReader(query) ? stmt.all(...params).map(asStored) : (stmt.run(...params), []);
|
|
21
31
|
return { toArray: () => rows };
|
|
22
32
|
} };
|
|
23
33
|
}
|
package/dist/vite/durableDb.d.ts
CHANGED
package/dist/vite/durableDb.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { i as init_debug, r as debugVite } from "../debug-Cz8KzMft.js";
|
|
2
2
|
import { _ as saveDevState, d as init_state, l as getDevPaths, m as removeDevServerLock, p as loadDevState, s as getDatabaseEpochs, y as writeDevServerLock } from "../state-DGYycIoJ.js";
|
|
3
3
|
import { loadMigrationFiles } from "../migrations/generator.js";
|
|
4
|
-
import { a as
|
|
4
|
+
import { a as databaseSources, c as readFile, i as toPascalCase, n as declaresSchema, o as discoverActionFiles, r as parseDatabaseFile, s as discoverDatabaseFiles, t as BABEL_PARSER_PLUGINS } from "../parser-mUnAtllk.js";
|
|
5
5
|
import * as fs from "node:fs";
|
|
6
6
|
import path, * as path$1 from "node:path";
|
|
7
7
|
import { parse } from "@babel/parser";
|
|
@@ -745,8 +745,12 @@ function schemaLocalName(db, tableName) {
|
|
|
745
745
|
const safe = (s) => s.replace(/[^A-Za-z0-9_$]/g, "_");
|
|
746
746
|
return `__schema_${safe(db.name)}_${safe(tableName)}`;
|
|
747
747
|
}
|
|
748
|
+
/** The schema as one object, when the schema module exports it whole (`schemaExport`). */
|
|
749
|
+
function schemaConstLocalName(db) {
|
|
750
|
+
return `__schema_${db.name.replace(/[^A-Za-z0-9_$]/g, "_")}`;
|
|
751
|
+
}
|
|
748
752
|
function hasSchema(db) {
|
|
749
|
-
return !!db.schemaImport && db
|
|
753
|
+
return !!db.schemaImport && declaresSchema(db);
|
|
750
754
|
}
|
|
751
755
|
/**
|
|
752
756
|
* Import declaration bringing a database's schema tables into the generated
|
|
@@ -759,13 +763,26 @@ function hasSchema(db) {
|
|
|
759
763
|
*/
|
|
760
764
|
function buildSchemaImport(db) {
|
|
761
765
|
const source = db.schemaImport.startsWith(".") ? path.resolve(path.dirname(db.filePath), db.schemaImport) : db.schemaImport;
|
|
766
|
+
if (db.schemaExport) return createNamedImport([{
|
|
767
|
+
imported: db.schemaExport,
|
|
768
|
+
local: schemaConstLocalName(db)
|
|
769
|
+
}], source);
|
|
762
770
|
return createNamedImport(db.schemaTableNames.map((tableName) => ({
|
|
763
771
|
imported: tableName,
|
|
764
772
|
local: schemaLocalName(db, tableName)
|
|
765
773
|
})), source);
|
|
766
774
|
}
|
|
775
|
+
/**
|
|
776
|
+
* The schema in the generated module: the const the schema module exports —
|
|
777
|
+
* the very object the app's own code holds —, or the listed tables under
|
|
778
|
+
* their names.
|
|
779
|
+
*/
|
|
780
|
+
function buildSchemaExpression(db) {
|
|
781
|
+
if (db.schemaExport) return t.identifier(schemaConstLocalName(db));
|
|
782
|
+
return t.objectExpression(db.schemaTableNames.map((tableName) => t.objectProperty(t.identifier(tableName), t.identifier(schemaLocalName(db, tableName)))));
|
|
783
|
+
}
|
|
767
784
|
function buildSchemaProperty(db) {
|
|
768
|
-
return t.classProperty(t.identifier("schema"),
|
|
785
|
+
return t.classProperty(t.identifier("schema"), buildSchemaExpression(db));
|
|
769
786
|
}
|
|
770
787
|
function buildDbTransportsObject(databases) {
|
|
771
788
|
const properties = databases.map((db) => t.objectProperty(t.stringLiteral(db.name), t.stringLiteral(db.transport)));
|
|
@@ -836,7 +853,7 @@ function generateDatabasesModule(databases) {
|
|
|
836
853
|
t.objectProperty(t.identifier("bindingName"), t.stringLiteral(db.bindingName)),
|
|
837
854
|
t.objectProperty(t.identifier("className"), t.stringLiteral(db.className)),
|
|
838
855
|
t.objectProperty(t.identifier("instance"), t.stringLiteral(db.instance)),
|
|
839
|
-
t.objectProperty(t.identifier("schema"), hasSchema(db) ?
|
|
856
|
+
t.objectProperty(t.identifier("schema"), hasSchema(db) ? buildSchemaExpression(db) : t.objectExpression([]))
|
|
840
857
|
]));
|
|
841
858
|
const program = t.program([...databases.filter(hasSchema).map(buildSchemaImport), t.exportNamedDeclaration(t.variableDeclaration("const", [t.variableDeclarator(t.identifier("databases"), t.arrayExpression(entries))]))]);
|
|
842
859
|
return generateCode(t.file(program));
|