@palbase/backend 2.0.2 → 4.0.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/dist/chunk-EG7TTYHY.js +235 -0
- package/dist/chunk-EG7TTYHY.js.map +1 -0
- package/dist/chunk-WUQO76NW.js +101 -0
- package/dist/chunk-WUQO76NW.js.map +1 -0
- package/dist/db/env.cjs +19 -0
- package/dist/db/env.cjs.map +1 -0
- package/dist/db/env.d.cts +45 -0
- package/dist/db/env.d.ts +45 -0
- package/dist/db/env.js +1 -0
- package/dist/db/env.js.map +1 -0
- package/dist/db/index.cjs +143 -231
- package/dist/db/index.cjs.map +1 -1
- package/dist/db/index.d.cts +4 -20
- package/dist/db/index.d.ts +4 -20
- package/dist/db/index.js +13 -233
- package/dist/db/index.js.map +1 -1
- package/dist/{endpoint-Djk5L6G2.d.ts → endpoint-2d_DpASt.d.cts} +94 -96
- package/dist/{endpoint-BlcY2xNA.d.cts → endpoint-2d_DpASt.d.ts} +94 -96
- package/dist/index-DZW9CjiY.d.ts +463 -0
- package/dist/index-DzRFS3Tl.d.cts +463 -0
- package/dist/index.cjs +557 -60
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +278 -161
- package/dist/index.d.ts +278 -161
- package/dist/index.js +343 -12
- package/dist/index.js.map +1 -1
- package/dist/test/index.cjs +57 -2
- package/dist/test/index.cjs.map +1 -1
- package/dist/test/index.d.cts +1 -2
- package/dist/test/index.d.ts +1 -2
- package/dist/test/index.js +10 -2
- package/dist/test/index.js.map +1 -1
- package/docs/README.md +33 -12
- package/docs/background.md +19 -13
- package/docs/database.md +70 -17
- package/docs/endpoints.md +103 -79
- package/docs/errors.md +37 -31
- package/docs/events.md +25 -17
- package/docs/getting-started.md +38 -18
- package/docs/llms-full.txt +758 -267
- package/docs/llms.txt +3 -1
- package/docs/migrations.md +98 -0
- package/docs/resources.md +94 -0
- package/docs/routing.md +54 -27
- package/docs/schema.md +163 -42
- package/docs/services.md +17 -14
- package/package.json +12 -2
- package/dist/chunk-4J3F32SH.js +0 -96
- package/dist/chunk-4J3F32SH.js.map +0 -1
- package/dist/chunk-L36JLUPO.js +0 -97
- package/dist/chunk-L36JLUPO.js.map +0 -1
- package/dist/schema-BqfEhIC0.d.cts +0 -133
- package/dist/schema-BqfEhIC0.d.ts +0 -133
package/dist/chunk-4J3F32SH.js
DELETED
|
@@ -1,96 +0,0 @@
|
|
|
1
|
-
// src/db/schema.ts
|
|
2
|
-
function table(name, columns) {
|
|
3
|
-
return { name, columns };
|
|
4
|
-
}
|
|
5
|
-
function defineSchema(tables) {
|
|
6
|
-
return { tables };
|
|
7
|
-
}
|
|
8
|
-
|
|
9
|
-
// src/db/columns.ts
|
|
10
|
-
var ColumnBuilder = class _ColumnBuilder {
|
|
11
|
-
_def;
|
|
12
|
-
constructor(type, existingDef) {
|
|
13
|
-
this._def = existingDef ?? {
|
|
14
|
-
type,
|
|
15
|
-
nullable: false,
|
|
16
|
-
primaryKey: false
|
|
17
|
-
};
|
|
18
|
-
}
|
|
19
|
-
/** Mark this column as the primary key. */
|
|
20
|
-
primaryKey() {
|
|
21
|
-
this._def.primaryKey = true;
|
|
22
|
-
return new _ColumnBuilder(this._def.type, this._def);
|
|
23
|
-
}
|
|
24
|
-
/** Mark this column as NOT NULL (default). */
|
|
25
|
-
notNull() {
|
|
26
|
-
this._def.nullable = false;
|
|
27
|
-
return new _ColumnBuilder(this._def.type, this._def);
|
|
28
|
-
}
|
|
29
|
-
/** Allow NULL values. */
|
|
30
|
-
nullable() {
|
|
31
|
-
this._def.nullable = true;
|
|
32
|
-
return new _ColumnBuilder(this._def.type, this._def);
|
|
33
|
-
}
|
|
34
|
-
/** Set a default value. */
|
|
35
|
-
default(value) {
|
|
36
|
-
this._def.defaultValue = value;
|
|
37
|
-
return new _ColumnBuilder(this._def.type, this._def);
|
|
38
|
-
}
|
|
39
|
-
/** UUID: generate a random default (gen_random_uuid()). */
|
|
40
|
-
defaultRandom() {
|
|
41
|
-
this._def.defaultRandom = true;
|
|
42
|
-
return new _ColumnBuilder(this._def.type, this._def);
|
|
43
|
-
}
|
|
44
|
-
/** Timestamp: default to now(). */
|
|
45
|
-
defaultNow() {
|
|
46
|
-
this._def.defaultNow = true;
|
|
47
|
-
return new _ColumnBuilder(this._def.type, this._def);
|
|
48
|
-
}
|
|
49
|
-
/** Add a foreign key reference. */
|
|
50
|
-
references(table2, column) {
|
|
51
|
-
this._def.references = { table: table2, column };
|
|
52
|
-
return new _ColumnBuilder(this._def.type, this._def);
|
|
53
|
-
}
|
|
54
|
-
/** Set the ON DELETE action for a foreign key reference. */
|
|
55
|
-
onDelete(action) {
|
|
56
|
-
this._def.onDeleteAction = action;
|
|
57
|
-
return new _ColumnBuilder(this._def.type, this._def);
|
|
58
|
-
}
|
|
59
|
-
};
|
|
60
|
-
function uuid() {
|
|
61
|
-
return new ColumnBuilder("uuid");
|
|
62
|
-
}
|
|
63
|
-
function text() {
|
|
64
|
-
return new ColumnBuilder("text");
|
|
65
|
-
}
|
|
66
|
-
function integer() {
|
|
67
|
-
return new ColumnBuilder("integer");
|
|
68
|
-
}
|
|
69
|
-
function boolean() {
|
|
70
|
-
return new ColumnBuilder("boolean");
|
|
71
|
-
}
|
|
72
|
-
function timestamp() {
|
|
73
|
-
return new ColumnBuilder("timestamp");
|
|
74
|
-
}
|
|
75
|
-
function jsonb() {
|
|
76
|
-
return new ColumnBuilder("jsonb");
|
|
77
|
-
}
|
|
78
|
-
function enumType(name, values) {
|
|
79
|
-
const builder = new ColumnBuilder("enum");
|
|
80
|
-
builder._def.enumName = name;
|
|
81
|
-
builder._def.enumValues = [...values];
|
|
82
|
-
return builder;
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
export {
|
|
86
|
-
table,
|
|
87
|
-
defineSchema,
|
|
88
|
-
uuid,
|
|
89
|
-
text,
|
|
90
|
-
integer,
|
|
91
|
-
boolean,
|
|
92
|
-
timestamp,
|
|
93
|
-
jsonb,
|
|
94
|
-
enumType
|
|
95
|
-
};
|
|
96
|
-
//# sourceMappingURL=chunk-4J3F32SH.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/db/schema.ts","../src/db/columns.ts"],"sourcesContent":["import type { ColumnBuilder } from \"./columns.js\";\n\n/**\n * A table definition with its columns.\n *\n * The `C` type parameter preserves the precise per-column phantom types so\n * that downstream mapped types (InsertShape, RowShape) can discriminate on\n * them. The default `Record<string, ColumnBuilder>` keeps all existing call\n * sites that use `TableDef` without a type argument (generator.ts, etc.)\n * compiling unchanged.\n */\nexport interface TableDef<\n C extends Record<string, ColumnBuilder> = Record<string, ColumnBuilder>,\n> {\n name: string;\n columns: C;\n}\n\n/**\n * A schema definition containing multiple tables.\n *\n * The `T` type parameter preserves the exact `TableDef<...>` type for each\n * table so that `SchemaDef[\"tables\"][\"rooms\"]` resolves to the precise\n * `TableDef<{ id: ColumnBuilder<'uuid', false, true, never>; ... }>`.\n */\nexport interface SchemaDef<\n T extends Record<string, TableDef> = Record<string, TableDef>,\n> {\n tables: T;\n}\n\n/**\n * Define a table with a name and columns.\n *\n * The generic parameter `C` preserves each column's phantom type params so\n * that `InsertShape<T>` and `RowShape<T>` can derive precise TypeScript types\n * from the column builders. The runtime return shape is identical to before —\n * only the static type is widened.\n */\nexport function table<C extends Record<string, ColumnBuilder>>(\n name: string,\n columns: C,\n): TableDef<C> {\n return { name, columns };\n}\n\n/** Define a schema containing multiple tables. */\nexport function defineSchema<T extends Record<string, TableDef>>(\n tables: T,\n): SchemaDef<T> {\n return { tables };\n}\n","/** On delete action for foreign key references. */\nexport type OnDeleteAction = 'cascade' | 'set null' | 'restrict' | 'no action';\n\n/** Column type identifiers. */\nexport type ColumnType = 'uuid' | 'text' | 'integer' | 'boolean' | 'timestamp' | 'jsonb' | 'enum';\n\n/** Base column definition shared by all column types. */\nexport interface ColumnDef {\n type: ColumnType;\n nullable: boolean;\n primaryKey: boolean;\n defaultValue?: unknown;\n defaultRandom?: boolean;\n defaultNow?: boolean;\n references?: { table: string; column: string };\n onDeleteAction?: OnDeleteAction;\n enumName?: string;\n enumValues?: string[];\n}\n\n// Phantom brand symbols — never have runtime values; exist only to force\n// TypeScript's structural type system to distinguish ColumnBuilder instances\n// with different type-param combinations. Without these, TS sees all\n// ColumnBuilder<K,...> as structurally identical and the first branch of\n// ColValue matches everything.\ndeclare const __colKind: unique symbol;\ndeclare const __colNullable: unique symbol;\ndeclare const __colHasDefault: unique symbol;\ndeclare const __colEnumValues: unique symbol;\n\n/**\n * Fluent column builder with phantom type params:\n * K — ColumnType literal (e.g. \"text\", \"integer\")\n * N — boolean: true when nullable() has been called last (false = NOT NULL)\n * D — boolean: true when a default has been set\n * E — enum value union (never for non-enum columns)\n *\n * All four params have defaults so bare `ColumnBuilder` (no args) still\n * satisfies `Record<string, ColumnBuilder>` in schema.ts without modification.\n *\n * The four `declare readonly` brand fields carry the phantom types into the\n * structural shape so that conditional types like ColValue<C> can discriminate\n * on K without requiring runtime values on those fields.\n */\nexport class ColumnBuilder<\n K extends ColumnType = ColumnType,\n N extends boolean = boolean,\n D extends boolean = boolean,\n E = unknown,\n> {\n // These fields exist only in the type layer (declared, never initialised at\n // runtime — TypeScript allows declared class members without an initializer\n // in strict mode as long as they're never read at runtime).\n declare readonly [__colKind]: K;\n declare readonly [__colNullable]: N;\n declare readonly [__colHasDefault]: D;\n declare readonly [__colEnumValues]: E;\n\n readonly _def: ColumnDef;\n\n constructor(type: K, existingDef?: ColumnDef) {\n this._def = existingDef ?? {\n type,\n nullable: false,\n primaryKey: false,\n };\n }\n\n /** Mark this column as the primary key. */\n primaryKey(): ColumnBuilder<K, N, D, E> {\n this._def.primaryKey = true;\n return new ColumnBuilder<K, N, D, E>(this._def.type as K, this._def);\n }\n\n /** Mark this column as NOT NULL (default). */\n notNull(): ColumnBuilder<K, false, D, E> {\n this._def.nullable = false;\n return new ColumnBuilder<K, false, D, E>(this._def.type as K, this._def);\n }\n\n /** Allow NULL values. */\n nullable(): ColumnBuilder<K, true, D, E> {\n this._def.nullable = true;\n return new ColumnBuilder<K, true, D, E>(this._def.type as K, this._def);\n }\n\n /** Set a default value. */\n default(value: unknown): ColumnBuilder<K, N, true, E> {\n this._def.defaultValue = value;\n return new ColumnBuilder<K, N, true, E>(this._def.type as K, this._def);\n }\n\n /** UUID: generate a random default (gen_random_uuid()). */\n defaultRandom(): ColumnBuilder<K, N, true, E> {\n this._def.defaultRandom = true;\n return new ColumnBuilder<K, N, true, E>(this._def.type as K, this._def);\n }\n\n /** Timestamp: default to now(). */\n defaultNow(): ColumnBuilder<K, N, true, E> {\n this._def.defaultNow = true;\n return new ColumnBuilder<K, N, true, E>(this._def.type as K, this._def);\n }\n\n /** Add a foreign key reference. */\n references(table: string, column: string): ColumnBuilder<K, N, D, E> {\n this._def.references = { table, column };\n return new ColumnBuilder<K, N, D, E>(this._def.type as K, this._def);\n }\n\n /** Set the ON DELETE action for a foreign key reference. */\n onDelete(action: OnDeleteAction): ColumnBuilder<K, N, D, E> {\n this._def.onDeleteAction = action;\n return new ColumnBuilder<K, N, D, E>(this._def.type as K, this._def);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Type extractors — imported by Task 2 to derive insert/row shapes.\n// ---------------------------------------------------------------------------\n\n/**\n * Extracts the TypeScript value type for a column, respecting nullability.\n * - \"uuid\" | \"text\" | \"timestamp\" → string (or string | null when N = true)\n * - \"integer\" → number\n * - \"boolean\" → boolean\n * - \"jsonb\" → unknown (opaque JSON)\n * - \"enum\" → E (the union of literal values)\n */\nexport type ColValue<C> =\n C extends ColumnBuilder<'uuid' | 'text' | 'timestamp', infer N, infer _D, infer _E>\n ? N extends true\n ? string | null\n : string\n : C extends ColumnBuilder<'integer', infer N, infer _D, infer _E>\n ? N extends true\n ? number | null\n : number\n : C extends ColumnBuilder<'boolean', infer N, infer _D, infer _E>\n ? N extends true\n ? boolean | null\n : boolean\n : C extends ColumnBuilder<'jsonb', infer _N, infer _D, infer _E>\n ? unknown\n : C extends ColumnBuilder<'enum', infer N, infer _D, infer E>\n ? N extends true\n ? E | null\n : E\n : never;\n\n/**\n * True when a column is optional on INSERT:\n * - nullable columns (N = true) — the DB allows NULL so the field may be omitted\n * - columns with a default (D = true) — the DB fills in the value when absent\n */\nexport type ColIsOptionalOnInsert<C> =\n C extends ColumnBuilder<infer _K, true, infer _D, infer _E>\n ? true\n : C extends ColumnBuilder<infer _K, infer _N, true, infer _E>\n ? true\n : false;\n\n// ---------------------------------------------------------------------------\n// Factory functions\n// ---------------------------------------------------------------------------\n\n/** Create a UUID column. */\nexport function uuid(): ColumnBuilder<'uuid', false, false, never> {\n return new ColumnBuilder('uuid');\n}\n\n/** Create a TEXT column. */\nexport function text(): ColumnBuilder<'text', false, false, never> {\n return new ColumnBuilder('text');\n}\n\n/** Create an INTEGER column. */\nexport function integer(): ColumnBuilder<'integer', false, false, never> {\n return new ColumnBuilder('integer');\n}\n\n/** Create a BOOLEAN column. */\nexport function boolean(): ColumnBuilder<'boolean', false, false, never> {\n return new ColumnBuilder('boolean');\n}\n\n/** Create a TIMESTAMP column. */\nexport function timestamp(): ColumnBuilder<'timestamp', false, false, never> {\n return new ColumnBuilder('timestamp');\n}\n\n/** Create a JSONB column. */\nexport function jsonb(): ColumnBuilder<'jsonb', false, false, never> {\n return new ColumnBuilder('jsonb');\n}\n\n/**\n * Create an ENUM column.\n * @param name The PostgreSQL enum type name (used in DDL).\n * @param values A readonly tuple of valid string values — kept `const` so the\n * union `V[number]` is as narrow as possible.\n */\nexport function enumType<const V extends readonly string[]>(\n name: string,\n values: V,\n): ColumnBuilder<'enum', false, false, V[number]> {\n const builder = new ColumnBuilder<'enum', false, false, V[number]>('enum');\n builder._def.enumName = name;\n builder._def.enumValues = [...values];\n return builder;\n}\n"],"mappings":";AAuCO,SAAS,MACd,MACA,SACa;AACb,SAAO,EAAE,MAAM,QAAQ;AACzB;AAGO,SAAS,aACd,QACc;AACd,SAAO,EAAE,OAAO;AAClB;;;ACPO,IAAM,gBAAN,MAAM,eAKX;AAAA,EASS;AAAA,EAET,YAAY,MAAS,aAAyB;AAC5C,SAAK,OAAO,eAAe;AAAA,MACzB;AAAA,MACA,UAAU;AAAA,MACV,YAAY;AAAA,IACd;AAAA,EACF;AAAA;AAAA,EAGA,aAAwC;AACtC,SAAK,KAAK,aAAa;AACvB,WAAO,IAAI,eAA0B,KAAK,KAAK,MAAW,KAAK,IAAI;AAAA,EACrE;AAAA;AAAA,EAGA,UAAyC;AACvC,SAAK,KAAK,WAAW;AACrB,WAAO,IAAI,eAA8B,KAAK,KAAK,MAAW,KAAK,IAAI;AAAA,EACzE;AAAA;AAAA,EAGA,WAAyC;AACvC,SAAK,KAAK,WAAW;AACrB,WAAO,IAAI,eAA6B,KAAK,KAAK,MAAW,KAAK,IAAI;AAAA,EACxE;AAAA;AAAA,EAGA,QAAQ,OAA8C;AACpD,SAAK,KAAK,eAAe;AACzB,WAAO,IAAI,eAA6B,KAAK,KAAK,MAAW,KAAK,IAAI;AAAA,EACxE;AAAA;AAAA,EAGA,gBAA8C;AAC5C,SAAK,KAAK,gBAAgB;AAC1B,WAAO,IAAI,eAA6B,KAAK,KAAK,MAAW,KAAK,IAAI;AAAA,EACxE;AAAA;AAAA,EAGA,aAA2C;AACzC,SAAK,KAAK,aAAa;AACvB,WAAO,IAAI,eAA6B,KAAK,KAAK,MAAW,KAAK,IAAI;AAAA,EACxE;AAAA;AAAA,EAGA,WAAWA,QAAe,QAA2C;AACnE,SAAK,KAAK,aAAa,EAAE,OAAAA,QAAO,OAAO;AACvC,WAAO,IAAI,eAA0B,KAAK,KAAK,MAAW,KAAK,IAAI;AAAA,EACrE;AAAA;AAAA,EAGA,SAAS,QAAmD;AAC1D,SAAK,KAAK,iBAAiB;AAC3B,WAAO,IAAI,eAA0B,KAAK,KAAK,MAAW,KAAK,IAAI;AAAA,EACrE;AACF;AAoDO,SAAS,OAAmD;AACjE,SAAO,IAAI,cAAc,MAAM;AACjC;AAGO,SAAS,OAAmD;AACjE,SAAO,IAAI,cAAc,MAAM;AACjC;AAGO,SAAS,UAAyD;AACvE,SAAO,IAAI,cAAc,SAAS;AACpC;AAGO,SAAS,UAAyD;AACvE,SAAO,IAAI,cAAc,SAAS;AACpC;AAGO,SAAS,YAA6D;AAC3E,SAAO,IAAI,cAAc,WAAW;AACtC;AAGO,SAAS,QAAqD;AACnE,SAAO,IAAI,cAAc,OAAO;AAClC;AAQO,SAAS,SACd,MACA,QACgD;AAChD,QAAM,UAAU,IAAI,cAA+C,MAAM;AACzE,UAAQ,KAAK,WAAW;AACxB,UAAQ,KAAK,aAAa,CAAC,GAAG,MAAM;AACpC,SAAO;AACT;","names":["table"]}
|
package/dist/chunk-L36JLUPO.js
DELETED
|
@@ -1,97 +0,0 @@
|
|
|
1
|
-
// src/db/typed-db.ts
|
|
2
|
-
function makeTypedTable(name, raw) {
|
|
3
|
-
return {
|
|
4
|
-
insert: (data) => raw.insert(name, data),
|
|
5
|
-
update: (id, data) => raw.update(name, id, data),
|
|
6
|
-
delete: (id) => raw.delete(name, id),
|
|
7
|
-
findById: (id) => raw.findById(name, id),
|
|
8
|
-
findMany: (query) => raw.findMany(name, query)
|
|
9
|
-
};
|
|
10
|
-
}
|
|
11
|
-
function makeTypedDB(schema, raw) {
|
|
12
|
-
function buildTables(client) {
|
|
13
|
-
const tables = {};
|
|
14
|
-
for (const key of Object.keys(schema.tables)) {
|
|
15
|
-
const tableDef = schema.tables[key];
|
|
16
|
-
if (tableDef !== void 0) {
|
|
17
|
-
tables[key] = makeTypedTable(tableDef.name, client);
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
return tables;
|
|
21
|
-
}
|
|
22
|
-
const result = {
|
|
23
|
-
tables: buildTables(raw),
|
|
24
|
-
transaction: (fn) => raw.transaction((rawTx) => fn({ tables: buildTables(rawTx) }))
|
|
25
|
-
};
|
|
26
|
-
return result;
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
// src/runtime.ts
|
|
30
|
-
import { AsyncLocalStorage } from "async_hooks";
|
|
31
|
-
var __requestALS = new AsyncLocalStorage();
|
|
32
|
-
var runtime = null;
|
|
33
|
-
function __setRuntime(services) {
|
|
34
|
-
runtime = services;
|
|
35
|
-
}
|
|
36
|
-
function __runWithRuntime(services, fn) {
|
|
37
|
-
return __requestALS.run({ runtime: services }, fn);
|
|
38
|
-
}
|
|
39
|
-
function __getRuntime() {
|
|
40
|
-
const scoped = __requestALS.getStore();
|
|
41
|
-
if (scoped) return scoped.runtime;
|
|
42
|
-
if (runtime === null) {
|
|
43
|
-
throw new Error(
|
|
44
|
-
"Palbase services accessed outside a request scope. The Database/Documents/\u2026 singletons are only available inside an endpoint handler (or after the runtime has called __runWithRuntime / __setRuntime)."
|
|
45
|
-
);
|
|
46
|
-
}
|
|
47
|
-
return runtime;
|
|
48
|
-
}
|
|
49
|
-
function makeServiceProxy(key) {
|
|
50
|
-
const handler = {
|
|
51
|
-
get(_target, prop, receiver) {
|
|
52
|
-
const client = __getRuntime()[key];
|
|
53
|
-
const value = Reflect.get(client, prop, receiver);
|
|
54
|
-
return typeof value === "function" ? value.bind(client) : value;
|
|
55
|
-
}
|
|
56
|
-
};
|
|
57
|
-
return new Proxy({}, handler);
|
|
58
|
-
}
|
|
59
|
-
var Database = makeServiceProxy("Database");
|
|
60
|
-
var Documents = makeServiceProxy("Documents");
|
|
61
|
-
var Storage = makeServiceProxy("Storage");
|
|
62
|
-
var Cache = makeServiceProxy("Cache");
|
|
63
|
-
var Queue = makeServiceProxy("Queue");
|
|
64
|
-
var Log = makeServiceProxy("Log");
|
|
65
|
-
var Notifications = makeServiceProxy("Notifications");
|
|
66
|
-
var Flags = makeServiceProxy("Flags");
|
|
67
|
-
function typedDatabase(schema) {
|
|
68
|
-
const typed = makeTypedDB(schema, Database);
|
|
69
|
-
const rawOps = {
|
|
70
|
-
query: (sql, params) => Database.query(sql, params),
|
|
71
|
-
insert: (table, data) => Database.insert(table, data),
|
|
72
|
-
update: (table, id, data) => Database.update(table, id, data),
|
|
73
|
-
delete: (table, id) => Database.delete(table, id),
|
|
74
|
-
findById: (table, id) => Database.findById(table, id),
|
|
75
|
-
findMany: (table, q) => Database.findMany(table, q),
|
|
76
|
-
transaction: (fn) => Database.transaction(fn)
|
|
77
|
-
};
|
|
78
|
-
return Object.assign(rawOps, typed);
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
export {
|
|
82
|
-
makeTypedDB,
|
|
83
|
-
__requestALS,
|
|
84
|
-
__setRuntime,
|
|
85
|
-
__runWithRuntime,
|
|
86
|
-
__getRuntime,
|
|
87
|
-
Database,
|
|
88
|
-
Documents,
|
|
89
|
-
Storage,
|
|
90
|
-
Cache,
|
|
91
|
-
Queue,
|
|
92
|
-
Log,
|
|
93
|
-
Notifications,
|
|
94
|
-
Flags,
|
|
95
|
-
typedDatabase
|
|
96
|
-
};
|
|
97
|
-
//# sourceMappingURL=chunk-L36JLUPO.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/db/typed-db.ts","../src/runtime.ts"],"sourcesContent":["/**\n * typed-db.ts — Task 2: TypedDB schema-derived insert/row shapes.\n *\n * Derives INSERT and full-row TypeScript types from a `defineSchema()` result\n * and wraps the untyped runtime `DBClient` with a typed facade.\n *\n * No value-any. No `as unknown as X`. The two narrow `as` casts in\n * `makeTypedTable` are safe because:\n * - `data as Record<string, unknown>`: InsertShape<T> maps string keys to\n * typed values; all value types are subsets of `unknown`, so the cast is\n * structurally sound.\n * - `result as RowShape<T>`: The runtime DBClient returns `Record<string,\n * unknown>` which is the erased form of the typed row; we're narrowing back\n * to the precise shape that the schema declared.\n * Both casts are narrowing only (not widening) and correctness is guaranteed\n * by the schema the caller provides.\n */\n\nimport type { ColValue, ColIsOptionalOnInsert, ColumnBuilder } from \"./columns.js\";\nimport type { TableDef, SchemaDef } from \"./schema.js\";\nimport type { DBClient, TxClient } from \"../endpoint.js\";\n\n// ---------------------------------------------------------------------------\n// Key discriminators — split a column map into required vs optional keys.\n// ---------------------------------------------------------------------------\n\n/** Keys of C whose columns are required on INSERT (not nullable, no default). */\ntype RequiredKeys<C> = {\n [K in keyof C]: ColIsOptionalOnInsert<C[K]> extends true ? never : K;\n}[keyof C];\n\n/** Keys of C whose columns are optional on INSERT (nullable or has a default). */\ntype OptionalKeys<C> = {\n [K in keyof C]: ColIsOptionalOnInsert<C[K]> extends true ? K : never;\n}[keyof C];\n\n// ---------------------------------------------------------------------------\n// Public shape types — exported so callers can reference them directly.\n// ---------------------------------------------------------------------------\n\n/**\n * The TypeScript type for an INSERT payload for table `T`.\n * - Required: columns that are NOT NULL and have no DB-level default.\n * - Optional: columns that are nullable or carry a default.\n *\n * When all columns are optional, `RequiredKeys<C>` resolves to `never` and\n * the first part becomes `{}`, which is a neutral element for `&`.\n */\nexport type InsertShape<T extends TableDef> = {\n [K in RequiredKeys<T[\"columns\"]>]: ColValue<T[\"columns\"][K]>;\n} & {\n [K in OptionalKeys<T[\"columns\"]>]?: ColValue<T[\"columns\"][K]>;\n};\n\n/**\n * The TypeScript type for a full row returned by the DB for table `T`.\n * Every column is present; nullable columns resolve to `T | null`.\n */\nexport type RowShape<T extends TableDef> = {\n [K in keyof T[\"columns\"]]: ColValue<T[\"columns\"][K]>;\n};\n\n// ---------------------------------------------------------------------------\n// TypedTable + TypedDB interfaces.\n// ---------------------------------------------------------------------------\n\n/** A typed table accessor that mirrors the runtime DBClient surface. */\nexport interface TypedTable<T extends TableDef> {\n insert(data: InsertShape<T>): Promise<RowShape<T>>;\n update(id: string, data: Partial<InsertShape<T>>): Promise<RowShape<T>>;\n delete(id: string): Promise<void>;\n findById(id: string): Promise<RowShape<T> | null>;\n findMany(query?: Partial<RowShape<T>>): Promise<RowShape<T>[]>;\n}\n\n/** A typed DB facade covering all tables declared in schema `S`. */\nexport interface TypedDB<S extends SchemaDef> {\n tables: {\n [K in keyof S[\"tables\"]]: TypedTable<S[\"tables\"][K]>;\n };\n transaction<T>(fn: (tx: TypedTx<S>) => Promise<T>): Promise<T>;\n}\n\n/** Transaction-scoped typed facade: same typed tables, no nested transaction. */\nexport interface TypedTx<S extends SchemaDef> {\n tables: {\n [K in keyof S[\"tables\"]]: TypedTable<S[\"tables\"][K]>;\n };\n}\n\n// ---------------------------------------------------------------------------\n// Runtime factory.\n// ---------------------------------------------------------------------------\n\n/**\n * Builds a typed table accessor that delegates every call to `raw` using the\n * runtime table name string. Two narrow `as` casts bridge the mapped-type\n * shapes to/from `Record<string, unknown>` — see module-level doc comment.\n *\n * The `raw` param is typed `TxClient` (the op surface shared by `DBClient` and\n * the transaction-scoped client) because this only ever calls the five\n * insert/update/delete/findById/findMany ops — never `transaction`. This lets\n * the same factory wrap both the top-level db and a tx without any cast.\n */\nfunction makeTypedTable<T extends TableDef<Record<string, ColumnBuilder>>>(\n name: string,\n raw: TxClient,\n): TypedTable<T> {\n return {\n insert: (data: InsertShape<T>) =>\n raw.insert(name, data as Record<string, unknown>) as Promise<RowShape<T>>,\n\n update: (id: string, data: Partial<InsertShape<T>>) =>\n raw.update(name, id, data as Record<string, unknown>) as Promise<RowShape<T>>,\n\n delete: (id: string) => raw.delete(name, id),\n\n findById: (id: string) =>\n raw.findById(name, id) as Promise<RowShape<T> | null>,\n\n findMany: (query?: Partial<RowShape<T>>) =>\n raw.findMany(name, query as Record<string, unknown> | undefined) as Promise<RowShape<T>[]>,\n };\n}\n\n/**\n * Wraps a raw `DBClient` with the type-safe `TypedDB<S>` facade derived from\n * the provided schema. No behavior change — all calls delegate to `raw` with\n * the table name as a plain string.\n *\n * `buildTables` is the reusable factory that wraps any op-bearing client\n * (`TxClient` — the surface shared by `DBClient` and the transaction-scoped\n * client) into the typed tables map. It is used both for the top-level db\n * (wrapping `raw`) and inside `transaction`, where it wraps the raw `TxClient`\n * the runtime yields so the callback sees the same typed `.tables` API.\n *\n * `transaction` delegates straight to `raw.transaction`; the two narrow\n * `as TypedTx<S>` / `as TypedDB<S>` casts are single structural narrowings\n * from the dynamically-built tables object to the precise mapped type (TS\n * cannot infer through `Object.keys` iteration) — see module-level doc comment.\n */\nexport function makeTypedDB<S extends SchemaDef>(\n schema: S,\n raw: DBClient,\n): TypedDB<S> {\n function buildTables(client: TxClient): Record<string, TypedTable<TableDef>> {\n const tables = {} as Record<string, TypedTable<TableDef>>;\n for (const key of Object.keys(schema.tables)) {\n const tableDef = schema.tables[key];\n if (tableDef !== undefined) {\n tables[key] = makeTypedTable(tableDef.name, client);\n }\n }\n return tables;\n }\n\n const result = {\n tables: buildTables(raw),\n transaction: <T>(fn: (tx: TypedTx<S>) => Promise<T>): Promise<T> =>\n raw.transaction((rawTx) => fn({ tables: buildTables(rawTx) } as TypedTx<S>)),\n };\n\n // Narrow cast: `result.tables` is structurally identical to\n // TypedDB<S>[\"tables\"] — each key maps to a TypedTable for the matching\n // TableDef. TS cannot infer the mapped-type result through Object.keys\n // iteration, so a single `as` bridges the gap.\n return result as TypedDB<S>;\n}\n","/**\n * runtime.ts — request-scoped service singletons.\n *\n * The backend SDK no longer threads a `ctx` god-object through every handler.\n * Instead, endpoint authors import PascalCase service singletons directly:\n *\n * import { Database, Documents, Cache } from \"@palbase/backend\";\n *\n * export default defineEndpoint({\n * method: \"POST\",\n * handler: async (req) => {\n * const row = await Database.insert(\"todos\", { title: req.input.title });\n * return row;\n * },\n * });\n *\n * The singletons are thin Proxies. Every property access forwards to the live\n * client for the CURRENT request scope, resolved through {@link __getRuntime}.\n *\n * # Request-scope resolution (persistent app-server)\n *\n * The runtime is a long-running Node process that serves many concurrent\n * requests on one event loop (NOT a fresh subprocess per request). A single\n * module-global slot would let one in-flight request's services bleed into\n * another's. So the services are carried in an {@link AsyncLocalStorage} store\n * ({@link __requestALS}) that the runtime sets per request with\n * {@link __runWithRuntime}; every async continuation of that request reads its\n * own store. `__getRuntime` reads the ALS store first; the module-global slot\n * (set by {@link __setRuntime}) is only a fallback for callers that run OUTSIDE\n * an ALS scope (dev-server, unit tests, the legacy single-shot path). Because\n * each `br-<ref>` pod is single-tenant, there is no cross-tenant leakage; the\n * ALS store is what prevents cross-REQUEST leakage within the shared process.\n *\n * The seam that makes `import { Database } from \"@palbase/backend\"` resolve to\n * the runtime-injected client: `@palbase/backend` is marked esbuild-EXTERNAL\n * when the tenant bundle is built, and the package is installed globally in the\n * pod (NODE_PATH=/usr/local/lib/node_modules). So worker.js's\n * `require('@palbase/backend')` and the bundle's `import` resolve to ONE shared\n * module instance — the ALS store and `__setRuntime` slot on that instance are\n * visible to the singletons the bundle imported.\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport type {\n DBClient,\n CacheClient,\n QueueClient,\n Logger,\n PalbaseDocsClient,\n} from \"./endpoint.js\";\nimport type {\n PalbaseStorageClient,\n PalbaseNotificationsClient,\n PalbaseFlagsClient,\n} from \"./clients.js\";\nimport type { SchemaDef } from \"./db/schema.js\";\nimport type { TypedDB } from \"./db/typed-db.js\";\nimport { makeTypedDB } from \"./db/typed-db.js\";\n\n/** The set of live clients the runtime injects per request scope.\n *\n * EXCLUDED on purpose: Realtime, Functions, CMS, Links, Analytics, Auth. They\n * are not exposed as backend handler singletons (auth lives on the client SDK;\n * the rest are out of scope for backend endpoints). */\nexport interface RuntimeServices {\n Database: DBClient;\n Documents: PalbaseDocsClient;\n Storage: PalbaseStorageClient;\n Cache: CacheClient;\n Queue: QueueClient;\n Log: Logger;\n Notifications: PalbaseNotificationsClient;\n Flags: PalbaseFlagsClient;\n}\n\n/**\n * Per-request store. The persistent runtime runs each request inside\n * {@link __runWithRuntime}, so every async continuation of that request reads\n * its OWN `runtime` (and any other request-scoped fields the runtime adds).\n *\n * Exported with a `__` prefix so the runtime (worker.js) shares the SAME ALS\n * instance across the one module instance — two ALS instances would silently\n * not see each other's stores. NOT part of the public author-facing API.\n */\nexport const __requestALS = new AsyncLocalStorage<{ runtime: RuntimeServices }>();\n\n/** Process-global fallback slot. Used only OUTSIDE an ALS scope (dev-server,\n * unit tests, legacy single-shot worker). Inside the persistent server every\n * request runs in {@link __requestALS}, which takes precedence. */\nlet runtime: RuntimeServices | null = null;\n\n/** Install the live clients in the process-global fallback slot.\n *\n * Persistent-server requests should use {@link __runWithRuntime} instead; this\n * remains for dev-server / tests / the legacy single-shot path that run without\n * an ALS scope. NOT part of the public author-facing API. */\nexport function __setRuntime(services: RuntimeServices): void {\n runtime = services;\n}\n\n/** Run `fn` with `services` bound as the request-scoped runtime.\n *\n * The persistent worker calls this once per request so concurrent requests\n * never share a services slot. NOT part of the public author-facing API. */\nexport function __runWithRuntime<T>(services: RuntimeServices, fn: () => T): T {\n return __requestALS.run({ runtime: services }, fn);\n}\n\n/** Read the live clients, throwing if accessed outside a request scope.\n *\n * Resolves the ALS store first (persistent server, per-request), then the\n * process-global fallback (dev-server / tests). NOT part of the public\n * author-facing API — used by the runtime and the singleton Proxies. */\nexport function __getRuntime(): RuntimeServices {\n const scoped = __requestALS.getStore();\n if (scoped) return scoped.runtime;\n if (runtime === null) {\n throw new Error(\n \"Palbase services accessed outside a request scope. The Database/Documents/… \" +\n \"singletons are only available inside an endpoint handler (or after the \" +\n \"runtime has called __runWithRuntime / __setRuntime).\",\n );\n }\n return runtime;\n}\n\n/**\n * Build a Proxy singleton that forwards every property access to the live\n * client named `key` on the current runtime.\n *\n * The single `as RuntimeServices[K]` is the only contained cast in the surface:\n * `Reflect.get` on a typed object returns `unknown` for a `string | symbol`\n * key, but `prop` is constrained to keys of the client interface at the call\n * sites (the exported singletons are typed below), so the forward is sound.\n */\nfunction makeServiceProxy<K extends keyof RuntimeServices>(key: K): RuntimeServices[K] {\n const handler: ProxyHandler<RuntimeServices[K]> = {\n get(_target, prop, receiver) {\n const client = __getRuntime()[key];\n const value = Reflect.get(client as object, prop, receiver) as unknown;\n // Bind methods to their owning client so `this` stays correct when the\n // author destructures or calls `Database.query(...)`.\n return typeof value === \"function\" ? value.bind(client) : value;\n },\n };\n // The Proxy target is irrelevant (all access goes through `get`); the cast\n // names the surface type the singleton presents to authors.\n return new Proxy({} as RuntimeServices[K], handler);\n}\n\n/** The project's own Postgres (pgx, schema `env_<envId>`). Typed CRUD +\n * `query`/`transaction`. For a typed `.tables.<name>` API, wrap with\n * {@link typedDatabase}. */\nexport const Database: DBClient = makeServiceProxy(\"Database\");\n\n/** Firestore-like document client (PalDocs). */\nexport const Documents: PalbaseDocsClient = makeServiceProxy(\"Documents\");\n\n/** Object storage client (buckets, signed URLs). */\nexport const Storage: PalbaseStorageClient = makeServiceProxy(\"Storage\");\n\n/** JSON-typed cache (get/set/incr/getOrSet). */\nexport const Cache: CacheClient = makeServiceProxy(\"Cache\");\n\n/** Background job queue. */\nexport const Queue: QueueClient = makeServiceProxy(\"Queue\");\n\n/** Structured logger. */\nexport const Log: Logger = makeServiceProxy(\"Log\");\n\n/** Push / email / SMS / in-app notifications. */\nexport const Notifications: PalbaseNotificationsClient = makeServiceProxy(\"Notifications\");\n\n/** Feature flags. */\nexport const Flags: PalbaseFlagsClient = makeServiceProxy(\"Flags\");\n\n/**\n * Type the `Database` singleton against a `defineSchema()` result, returning a\n * facade with a typed `.tables.<name>.insert(...)` API alongside the raw\n * `query`/`transaction` ops.\n *\n * const Db = typedDatabase(schema);\n * const todo = await Db.tables.todos.insert({ title: \"x\" });\n *\n * This is per-endpoint (not global module augmentation), so one endpoint's\n * tables never leak into another's `Database` type.\n */\nexport function typedDatabase<TSchema extends SchemaDef>(\n schema: TSchema,\n): TypedDB<TSchema> & DBClient {\n // makeTypedDB wraps the raw DBClient with the typed `.tables` facade (and a\n // typed `transaction`). The full `& DBClient` surface also needs the raw ops\n // (query/insert/update/delete/findById/findMany), which we delegate straight\n // to the `Database` singleton — every call goes through its runtime Proxy.\n const typed = makeTypedDB(schema, Database);\n const rawOps: DBClient = {\n query: (sql, params) => Database.query(sql, params),\n insert: (table, data) => Database.insert(table, data),\n update: (table, id, data) => Database.update(table, id, data),\n delete: (table, id) => Database.delete(table, id),\n findById: (table, id) => Database.findById(table, id),\n findMany: (table, q) => Database.findMany(table, q),\n transaction: (fn) => Database.transaction(fn),\n };\n // typed.transaction (typed-tx) intentionally overrides rawOps.transaction so\n // the callback sees the typed `.tables` API.\n return Object.assign(rawOps, typed);\n}\n"],"mappings":";AAwGA,SAAS,eACP,MACA,KACe;AACf,SAAO;AAAA,IACL,QAAQ,CAAC,SACP,IAAI,OAAO,MAAM,IAA+B;AAAA,IAElD,QAAQ,CAAC,IAAY,SACnB,IAAI,OAAO,MAAM,IAAI,IAA+B;AAAA,IAEtD,QAAQ,CAAC,OAAe,IAAI,OAAO,MAAM,EAAE;AAAA,IAE3C,UAAU,CAAC,OACT,IAAI,SAAS,MAAM,EAAE;AAAA,IAEvB,UAAU,CAAC,UACT,IAAI,SAAS,MAAM,KAA4C;AAAA,EACnE;AACF;AAkBO,SAAS,YACd,QACA,KACY;AACZ,WAAS,YAAY,QAAwD;AAC3E,UAAM,SAAS,CAAC;AAChB,eAAW,OAAO,OAAO,KAAK,OAAO,MAAM,GAAG;AAC5C,YAAM,WAAW,OAAO,OAAO,GAAG;AAClC,UAAI,aAAa,QAAW;AAC1B,eAAO,GAAG,IAAI,eAAe,SAAS,MAAM,MAAM;AAAA,MACpD;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAEA,QAAM,SAAS;AAAA,IACb,QAAQ,YAAY,GAAG;AAAA,IACvB,aAAa,CAAI,OACf,IAAI,YAAY,CAAC,UAAU,GAAG,EAAE,QAAQ,YAAY,KAAK,EAAE,CAAe,CAAC;AAAA,EAC/E;AAMA,SAAO;AACT;;;AC7HA,SAAS,yBAAyB;AA2C3B,IAAM,eAAe,IAAI,kBAAgD;AAKhF,IAAI,UAAkC;AAO/B,SAAS,aAAa,UAAiC;AAC5D,YAAU;AACZ;AAMO,SAAS,iBAAoB,UAA2B,IAAgB;AAC7E,SAAO,aAAa,IAAI,EAAE,SAAS,SAAS,GAAG,EAAE;AACnD;AAOO,SAAS,eAAgC;AAC9C,QAAM,SAAS,aAAa,SAAS;AACrC,MAAI,OAAQ,QAAO,OAAO;AAC1B,MAAI,YAAY,MAAM;AACpB,UAAM,IAAI;AAAA,MACR;AAAA,IAGF;AAAA,EACF;AACA,SAAO;AACT;AAWA,SAAS,iBAAkD,KAA4B;AACrF,QAAM,UAA4C;AAAA,IAChD,IAAI,SAAS,MAAM,UAAU;AAC3B,YAAM,SAAS,aAAa,EAAE,GAAG;AACjC,YAAM,QAAQ,QAAQ,IAAI,QAAkB,MAAM,QAAQ;AAG1D,aAAO,OAAO,UAAU,aAAa,MAAM,KAAK,MAAM,IAAI;AAAA,IAC5D;AAAA,EACF;AAGA,SAAO,IAAI,MAAM,CAAC,GAAyB,OAAO;AACpD;AAKO,IAAM,WAAqB,iBAAiB,UAAU;AAGtD,IAAM,YAA+B,iBAAiB,WAAW;AAGjE,IAAM,UAAgC,iBAAiB,SAAS;AAGhE,IAAM,QAAqB,iBAAiB,OAAO;AAGnD,IAAM,QAAqB,iBAAiB,OAAO;AAGnD,IAAM,MAAc,iBAAiB,KAAK;AAG1C,IAAM,gBAA4C,iBAAiB,eAAe;AAGlF,IAAM,QAA4B,iBAAiB,OAAO;AAa1D,SAAS,cACd,QAC6B;AAK7B,QAAM,QAAQ,YAAY,QAAQ,QAAQ;AAC1C,QAAM,SAAmB;AAAA,IACvB,OAAO,CAAC,KAAK,WAAW,SAAS,MAAM,KAAK,MAAM;AAAA,IAClD,QAAQ,CAAC,OAAO,SAAS,SAAS,OAAO,OAAO,IAAI;AAAA,IACpD,QAAQ,CAAC,OAAO,IAAI,SAAS,SAAS,OAAO,OAAO,IAAI,IAAI;AAAA,IAC5D,QAAQ,CAAC,OAAO,OAAO,SAAS,OAAO,OAAO,EAAE;AAAA,IAChD,UAAU,CAAC,OAAO,OAAO,SAAS,SAAS,OAAO,EAAE;AAAA,IACpD,UAAU,CAAC,OAAO,MAAM,SAAS,SAAS,OAAO,CAAC;AAAA,IAClD,aAAa,CAAC,OAAO,SAAS,YAAY,EAAE;AAAA,EAC9C;AAGA,SAAO,OAAO,OAAO,QAAQ,KAAK;AACpC;","names":[]}
|
|
@@ -1,133 +0,0 @@
|
|
|
1
|
-
/** On delete action for foreign key references. */
|
|
2
|
-
type OnDeleteAction = 'cascade' | 'set null' | 'restrict' | 'no action';
|
|
3
|
-
/** Column type identifiers. */
|
|
4
|
-
type ColumnType = 'uuid' | 'text' | 'integer' | 'boolean' | 'timestamp' | 'jsonb' | 'enum';
|
|
5
|
-
/** Base column definition shared by all column types. */
|
|
6
|
-
interface ColumnDef {
|
|
7
|
-
type: ColumnType;
|
|
8
|
-
nullable: boolean;
|
|
9
|
-
primaryKey: boolean;
|
|
10
|
-
defaultValue?: unknown;
|
|
11
|
-
defaultRandom?: boolean;
|
|
12
|
-
defaultNow?: boolean;
|
|
13
|
-
references?: {
|
|
14
|
-
table: string;
|
|
15
|
-
column: string;
|
|
16
|
-
};
|
|
17
|
-
onDeleteAction?: OnDeleteAction;
|
|
18
|
-
enumName?: string;
|
|
19
|
-
enumValues?: string[];
|
|
20
|
-
}
|
|
21
|
-
declare const __colKind: unique symbol;
|
|
22
|
-
declare const __colNullable: unique symbol;
|
|
23
|
-
declare const __colHasDefault: unique symbol;
|
|
24
|
-
declare const __colEnumValues: unique symbol;
|
|
25
|
-
/**
|
|
26
|
-
* Fluent column builder with phantom type params:
|
|
27
|
-
* K — ColumnType literal (e.g. "text", "integer")
|
|
28
|
-
* N — boolean: true when nullable() has been called last (false = NOT NULL)
|
|
29
|
-
* D — boolean: true when a default has been set
|
|
30
|
-
* E — enum value union (never for non-enum columns)
|
|
31
|
-
*
|
|
32
|
-
* All four params have defaults so bare `ColumnBuilder` (no args) still
|
|
33
|
-
* satisfies `Record<string, ColumnBuilder>` in schema.ts without modification.
|
|
34
|
-
*
|
|
35
|
-
* The four `declare readonly` brand fields carry the phantom types into the
|
|
36
|
-
* structural shape so that conditional types like ColValue<C> can discriminate
|
|
37
|
-
* on K without requiring runtime values on those fields.
|
|
38
|
-
*/
|
|
39
|
-
declare class ColumnBuilder<K extends ColumnType = ColumnType, N extends boolean = boolean, D extends boolean = boolean, E = unknown> {
|
|
40
|
-
readonly [__colKind]: K;
|
|
41
|
-
readonly [__colNullable]: N;
|
|
42
|
-
readonly [__colHasDefault]: D;
|
|
43
|
-
readonly [__colEnumValues]: E;
|
|
44
|
-
readonly _def: ColumnDef;
|
|
45
|
-
constructor(type: K, existingDef?: ColumnDef);
|
|
46
|
-
/** Mark this column as the primary key. */
|
|
47
|
-
primaryKey(): ColumnBuilder<K, N, D, E>;
|
|
48
|
-
/** Mark this column as NOT NULL (default). */
|
|
49
|
-
notNull(): ColumnBuilder<K, false, D, E>;
|
|
50
|
-
/** Allow NULL values. */
|
|
51
|
-
nullable(): ColumnBuilder<K, true, D, E>;
|
|
52
|
-
/** Set a default value. */
|
|
53
|
-
default(value: unknown): ColumnBuilder<K, N, true, E>;
|
|
54
|
-
/** UUID: generate a random default (gen_random_uuid()). */
|
|
55
|
-
defaultRandom(): ColumnBuilder<K, N, true, E>;
|
|
56
|
-
/** Timestamp: default to now(). */
|
|
57
|
-
defaultNow(): ColumnBuilder<K, N, true, E>;
|
|
58
|
-
/** Add a foreign key reference. */
|
|
59
|
-
references(table: string, column: string): ColumnBuilder<K, N, D, E>;
|
|
60
|
-
/** Set the ON DELETE action for a foreign key reference. */
|
|
61
|
-
onDelete(action: OnDeleteAction): ColumnBuilder<K, N, D, E>;
|
|
62
|
-
}
|
|
63
|
-
/**
|
|
64
|
-
* Extracts the TypeScript value type for a column, respecting nullability.
|
|
65
|
-
* - "uuid" | "text" | "timestamp" → string (or string | null when N = true)
|
|
66
|
-
* - "integer" → number
|
|
67
|
-
* - "boolean" → boolean
|
|
68
|
-
* - "jsonb" → unknown (opaque JSON)
|
|
69
|
-
* - "enum" → E (the union of literal values)
|
|
70
|
-
*/
|
|
71
|
-
type ColValue<C> = C extends ColumnBuilder<'uuid' | 'text' | 'timestamp', infer N, infer _D, infer _E> ? N extends true ? string | null : string : C extends ColumnBuilder<'integer', infer N, infer _D, infer _E> ? N extends true ? number | null : number : C extends ColumnBuilder<'boolean', infer N, infer _D, infer _E> ? N extends true ? boolean | null : boolean : C extends ColumnBuilder<'jsonb', infer _N, infer _D, infer _E> ? unknown : C extends ColumnBuilder<'enum', infer N, infer _D, infer E> ? N extends true ? E | null : E : never;
|
|
72
|
-
/**
|
|
73
|
-
* True when a column is optional on INSERT:
|
|
74
|
-
* - nullable columns (N = true) — the DB allows NULL so the field may be omitted
|
|
75
|
-
* - columns with a default (D = true) — the DB fills in the value when absent
|
|
76
|
-
*/
|
|
77
|
-
type ColIsOptionalOnInsert<C> = C extends ColumnBuilder<infer _K, true, infer _D, infer _E> ? true : C extends ColumnBuilder<infer _K, infer _N, true, infer _E> ? true : false;
|
|
78
|
-
/** Create a UUID column. */
|
|
79
|
-
declare function uuid(): ColumnBuilder<'uuid', false, false, never>;
|
|
80
|
-
/** Create a TEXT column. */
|
|
81
|
-
declare function text(): ColumnBuilder<'text', false, false, never>;
|
|
82
|
-
/** Create an INTEGER column. */
|
|
83
|
-
declare function integer(): ColumnBuilder<'integer', false, false, never>;
|
|
84
|
-
/** Create a BOOLEAN column. */
|
|
85
|
-
declare function boolean(): ColumnBuilder<'boolean', false, false, never>;
|
|
86
|
-
/** Create a TIMESTAMP column. */
|
|
87
|
-
declare function timestamp(): ColumnBuilder<'timestamp', false, false, never>;
|
|
88
|
-
/** Create a JSONB column. */
|
|
89
|
-
declare function jsonb(): ColumnBuilder<'jsonb', false, false, never>;
|
|
90
|
-
/**
|
|
91
|
-
* Create an ENUM column.
|
|
92
|
-
* @param name The PostgreSQL enum type name (used in DDL).
|
|
93
|
-
* @param values A readonly tuple of valid string values — kept `const` so the
|
|
94
|
-
* union `V[number]` is as narrow as possible.
|
|
95
|
-
*/
|
|
96
|
-
declare function enumType<const V extends readonly string[]>(name: string, values: V): ColumnBuilder<'enum', false, false, V[number]>;
|
|
97
|
-
|
|
98
|
-
/**
|
|
99
|
-
* A table definition with its columns.
|
|
100
|
-
*
|
|
101
|
-
* The `C` type parameter preserves the precise per-column phantom types so
|
|
102
|
-
* that downstream mapped types (InsertShape, RowShape) can discriminate on
|
|
103
|
-
* them. The default `Record<string, ColumnBuilder>` keeps all existing call
|
|
104
|
-
* sites that use `TableDef` without a type argument (generator.ts, etc.)
|
|
105
|
-
* compiling unchanged.
|
|
106
|
-
*/
|
|
107
|
-
interface TableDef<C extends Record<string, ColumnBuilder> = Record<string, ColumnBuilder>> {
|
|
108
|
-
name: string;
|
|
109
|
-
columns: C;
|
|
110
|
-
}
|
|
111
|
-
/**
|
|
112
|
-
* A schema definition containing multiple tables.
|
|
113
|
-
*
|
|
114
|
-
* The `T` type parameter preserves the exact `TableDef<...>` type for each
|
|
115
|
-
* table so that `SchemaDef["tables"]["rooms"]` resolves to the precise
|
|
116
|
-
* `TableDef<{ id: ColumnBuilder<'uuid', false, true, never>; ... }>`.
|
|
117
|
-
*/
|
|
118
|
-
interface SchemaDef<T extends Record<string, TableDef> = Record<string, TableDef>> {
|
|
119
|
-
tables: T;
|
|
120
|
-
}
|
|
121
|
-
/**
|
|
122
|
-
* Define a table with a name and columns.
|
|
123
|
-
*
|
|
124
|
-
* The generic parameter `C` preserves each column's phantom type params so
|
|
125
|
-
* that `InsertShape<T>` and `RowShape<T>` can derive precise TypeScript types
|
|
126
|
-
* from the column builders. The runtime return shape is identical to before —
|
|
127
|
-
* only the static type is widened.
|
|
128
|
-
*/
|
|
129
|
-
declare function table<C extends Record<string, ColumnBuilder>>(name: string, columns: C): TableDef<C>;
|
|
130
|
-
/** Define a schema containing multiple tables. */
|
|
131
|
-
declare function defineSchema<T extends Record<string, TableDef>>(tables: T): SchemaDef<T>;
|
|
132
|
-
|
|
133
|
-
export { type ColIsOptionalOnInsert as C, type OnDeleteAction as O, type SchemaDef as S, type TableDef as T, type ColValue as a, ColumnBuilder as b, type ColumnDef as c, type ColumnType as d, boolean as e, defineSchema as f, enumType as g, text as h, integer as i, jsonb as j, timestamp as k, table as t, uuid as u };
|
|
@@ -1,133 +0,0 @@
|
|
|
1
|
-
/** On delete action for foreign key references. */
|
|
2
|
-
type OnDeleteAction = 'cascade' | 'set null' | 'restrict' | 'no action';
|
|
3
|
-
/** Column type identifiers. */
|
|
4
|
-
type ColumnType = 'uuid' | 'text' | 'integer' | 'boolean' | 'timestamp' | 'jsonb' | 'enum';
|
|
5
|
-
/** Base column definition shared by all column types. */
|
|
6
|
-
interface ColumnDef {
|
|
7
|
-
type: ColumnType;
|
|
8
|
-
nullable: boolean;
|
|
9
|
-
primaryKey: boolean;
|
|
10
|
-
defaultValue?: unknown;
|
|
11
|
-
defaultRandom?: boolean;
|
|
12
|
-
defaultNow?: boolean;
|
|
13
|
-
references?: {
|
|
14
|
-
table: string;
|
|
15
|
-
column: string;
|
|
16
|
-
};
|
|
17
|
-
onDeleteAction?: OnDeleteAction;
|
|
18
|
-
enumName?: string;
|
|
19
|
-
enumValues?: string[];
|
|
20
|
-
}
|
|
21
|
-
declare const __colKind: unique symbol;
|
|
22
|
-
declare const __colNullable: unique symbol;
|
|
23
|
-
declare const __colHasDefault: unique symbol;
|
|
24
|
-
declare const __colEnumValues: unique symbol;
|
|
25
|
-
/**
|
|
26
|
-
* Fluent column builder with phantom type params:
|
|
27
|
-
* K — ColumnType literal (e.g. "text", "integer")
|
|
28
|
-
* N — boolean: true when nullable() has been called last (false = NOT NULL)
|
|
29
|
-
* D — boolean: true when a default has been set
|
|
30
|
-
* E — enum value union (never for non-enum columns)
|
|
31
|
-
*
|
|
32
|
-
* All four params have defaults so bare `ColumnBuilder` (no args) still
|
|
33
|
-
* satisfies `Record<string, ColumnBuilder>` in schema.ts without modification.
|
|
34
|
-
*
|
|
35
|
-
* The four `declare readonly` brand fields carry the phantom types into the
|
|
36
|
-
* structural shape so that conditional types like ColValue<C> can discriminate
|
|
37
|
-
* on K without requiring runtime values on those fields.
|
|
38
|
-
*/
|
|
39
|
-
declare class ColumnBuilder<K extends ColumnType = ColumnType, N extends boolean = boolean, D extends boolean = boolean, E = unknown> {
|
|
40
|
-
readonly [__colKind]: K;
|
|
41
|
-
readonly [__colNullable]: N;
|
|
42
|
-
readonly [__colHasDefault]: D;
|
|
43
|
-
readonly [__colEnumValues]: E;
|
|
44
|
-
readonly _def: ColumnDef;
|
|
45
|
-
constructor(type: K, existingDef?: ColumnDef);
|
|
46
|
-
/** Mark this column as the primary key. */
|
|
47
|
-
primaryKey(): ColumnBuilder<K, N, D, E>;
|
|
48
|
-
/** Mark this column as NOT NULL (default). */
|
|
49
|
-
notNull(): ColumnBuilder<K, false, D, E>;
|
|
50
|
-
/** Allow NULL values. */
|
|
51
|
-
nullable(): ColumnBuilder<K, true, D, E>;
|
|
52
|
-
/** Set a default value. */
|
|
53
|
-
default(value: unknown): ColumnBuilder<K, N, true, E>;
|
|
54
|
-
/** UUID: generate a random default (gen_random_uuid()). */
|
|
55
|
-
defaultRandom(): ColumnBuilder<K, N, true, E>;
|
|
56
|
-
/** Timestamp: default to now(). */
|
|
57
|
-
defaultNow(): ColumnBuilder<K, N, true, E>;
|
|
58
|
-
/** Add a foreign key reference. */
|
|
59
|
-
references(table: string, column: string): ColumnBuilder<K, N, D, E>;
|
|
60
|
-
/** Set the ON DELETE action for a foreign key reference. */
|
|
61
|
-
onDelete(action: OnDeleteAction): ColumnBuilder<K, N, D, E>;
|
|
62
|
-
}
|
|
63
|
-
/**
|
|
64
|
-
* Extracts the TypeScript value type for a column, respecting nullability.
|
|
65
|
-
* - "uuid" | "text" | "timestamp" → string (or string | null when N = true)
|
|
66
|
-
* - "integer" → number
|
|
67
|
-
* - "boolean" → boolean
|
|
68
|
-
* - "jsonb" → unknown (opaque JSON)
|
|
69
|
-
* - "enum" → E (the union of literal values)
|
|
70
|
-
*/
|
|
71
|
-
type ColValue<C> = C extends ColumnBuilder<'uuid' | 'text' | 'timestamp', infer N, infer _D, infer _E> ? N extends true ? string | null : string : C extends ColumnBuilder<'integer', infer N, infer _D, infer _E> ? N extends true ? number | null : number : C extends ColumnBuilder<'boolean', infer N, infer _D, infer _E> ? N extends true ? boolean | null : boolean : C extends ColumnBuilder<'jsonb', infer _N, infer _D, infer _E> ? unknown : C extends ColumnBuilder<'enum', infer N, infer _D, infer E> ? N extends true ? E | null : E : never;
|
|
72
|
-
/**
|
|
73
|
-
* True when a column is optional on INSERT:
|
|
74
|
-
* - nullable columns (N = true) — the DB allows NULL so the field may be omitted
|
|
75
|
-
* - columns with a default (D = true) — the DB fills in the value when absent
|
|
76
|
-
*/
|
|
77
|
-
type ColIsOptionalOnInsert<C> = C extends ColumnBuilder<infer _K, true, infer _D, infer _E> ? true : C extends ColumnBuilder<infer _K, infer _N, true, infer _E> ? true : false;
|
|
78
|
-
/** Create a UUID column. */
|
|
79
|
-
declare function uuid(): ColumnBuilder<'uuid', false, false, never>;
|
|
80
|
-
/** Create a TEXT column. */
|
|
81
|
-
declare function text(): ColumnBuilder<'text', false, false, never>;
|
|
82
|
-
/** Create an INTEGER column. */
|
|
83
|
-
declare function integer(): ColumnBuilder<'integer', false, false, never>;
|
|
84
|
-
/** Create a BOOLEAN column. */
|
|
85
|
-
declare function boolean(): ColumnBuilder<'boolean', false, false, never>;
|
|
86
|
-
/** Create a TIMESTAMP column. */
|
|
87
|
-
declare function timestamp(): ColumnBuilder<'timestamp', false, false, never>;
|
|
88
|
-
/** Create a JSONB column. */
|
|
89
|
-
declare function jsonb(): ColumnBuilder<'jsonb', false, false, never>;
|
|
90
|
-
/**
|
|
91
|
-
* Create an ENUM column.
|
|
92
|
-
* @param name The PostgreSQL enum type name (used in DDL).
|
|
93
|
-
* @param values A readonly tuple of valid string values — kept `const` so the
|
|
94
|
-
* union `V[number]` is as narrow as possible.
|
|
95
|
-
*/
|
|
96
|
-
declare function enumType<const V extends readonly string[]>(name: string, values: V): ColumnBuilder<'enum', false, false, V[number]>;
|
|
97
|
-
|
|
98
|
-
/**
|
|
99
|
-
* A table definition with its columns.
|
|
100
|
-
*
|
|
101
|
-
* The `C` type parameter preserves the precise per-column phantom types so
|
|
102
|
-
* that downstream mapped types (InsertShape, RowShape) can discriminate on
|
|
103
|
-
* them. The default `Record<string, ColumnBuilder>` keeps all existing call
|
|
104
|
-
* sites that use `TableDef` without a type argument (generator.ts, etc.)
|
|
105
|
-
* compiling unchanged.
|
|
106
|
-
*/
|
|
107
|
-
interface TableDef<C extends Record<string, ColumnBuilder> = Record<string, ColumnBuilder>> {
|
|
108
|
-
name: string;
|
|
109
|
-
columns: C;
|
|
110
|
-
}
|
|
111
|
-
/**
|
|
112
|
-
* A schema definition containing multiple tables.
|
|
113
|
-
*
|
|
114
|
-
* The `T` type parameter preserves the exact `TableDef<...>` type for each
|
|
115
|
-
* table so that `SchemaDef["tables"]["rooms"]` resolves to the precise
|
|
116
|
-
* `TableDef<{ id: ColumnBuilder<'uuid', false, true, never>; ... }>`.
|
|
117
|
-
*/
|
|
118
|
-
interface SchemaDef<T extends Record<string, TableDef> = Record<string, TableDef>> {
|
|
119
|
-
tables: T;
|
|
120
|
-
}
|
|
121
|
-
/**
|
|
122
|
-
* Define a table with a name and columns.
|
|
123
|
-
*
|
|
124
|
-
* The generic parameter `C` preserves each column's phantom type params so
|
|
125
|
-
* that `InsertShape<T>` and `RowShape<T>` can derive precise TypeScript types
|
|
126
|
-
* from the column builders. The runtime return shape is identical to before —
|
|
127
|
-
* only the static type is widened.
|
|
128
|
-
*/
|
|
129
|
-
declare function table<C extends Record<string, ColumnBuilder>>(name: string, columns: C): TableDef<C>;
|
|
130
|
-
/** Define a schema containing multiple tables. */
|
|
131
|
-
declare function defineSchema<T extends Record<string, TableDef>>(tables: T): SchemaDef<T>;
|
|
132
|
-
|
|
133
|
-
export { type ColIsOptionalOnInsert as C, type OnDeleteAction as O, type SchemaDef as S, type TableDef as T, type ColValue as a, ColumnBuilder as b, type ColumnDef as c, type ColumnType as d, boolean as e, defineSchema as f, enumType as g, text as h, integer as i, jsonb as j, timestamp as k, table as t, uuid as u };
|