@ingram-tech/nk-db 1.5.0 → 2.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/README.md +81 -26
- package/dist/id-drizzle.d.ts +47 -31
- package/dist/id-drizzle.d.ts.map +1 -1
- package/dist/id-drizzle.js +5 -2
- package/dist/id-drizzle.js.map +1 -1
- package/dist/id-sql.d.ts +8 -0
- package/dist/id-sql.d.ts.map +1 -0
- package/dist/id-sql.js +31 -0
- package/dist/id-sql.js.map +1 -0
- package/dist/id.d.ts +18 -131
- package/dist/id.d.ts.map +1 -1
- package/dist/id.js +17 -200
- package/dist/id.js.map +1 -1
- package/dist/pglite/index.d.ts +8 -0
- package/dist/pglite/index.d.ts.map +1 -1
- package/dist/pglite/index.js +3 -0
- package/dist/pglite/index.js.map +1 -1
- package/package.json +16 -8
- package/src/coerce.ts +50 -0
- package/src/drizzle.ts +51 -0
- package/src/errors.ts +35 -0
- package/src/id-drizzle.ts +130 -0
- package/src/id-sql.ts +32 -0
- package/src/id.ts +21 -0
- package/src/index.ts +27 -0
- package/src/keys.ts +78 -0
- package/src/migrate-bin.ts +87 -0
- package/src/migrate.ts +454 -0
- package/src/pglite/dev.ts +63 -0
- package/src/pglite/index.ts +255 -0
- package/src/pglite/reset.ts +31 -0
- package/src/pool.ts +148 -0
- package/src/queries.ts +244 -0
- package/src/rls.ts +90 -0
package/dist/id.js
CHANGED
|
@@ -1,204 +1,21 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
* (
|
|
4
|
-
*
|
|
5
|
-
*
|
|
2
|
+
* `@ingram-tech/nk-db/id` — the fleet's id codec, now published standalone as
|
|
3
|
+
* [`id758`](https://github.com/ingram-technologies/id758). This subpath stays
|
|
4
|
+
* as the nextkit-facing entry point: it re-exports the whole `id758` surface
|
|
5
|
+
* plus the names nextkit sites adopted before the extraction, so nothing that
|
|
6
|
+
* imports from here needs to change. New code may import `id758` directly.
|
|
6
7
|
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
* Node 19+, Bun, Deno, edge runtimes and browsers), not `node:crypto`. That is
|
|
10
|
-
* load-bearing, not incidental — a `node:crypto` import here makes every module
|
|
11
|
-
* that touches an id node-only, which in practice means a Drizzle `schema.ts`
|
|
12
|
-
* cannot encode/decode without dragging `node:crypto` into client bundles, and
|
|
13
|
-
* sites end up dependency-injecting the codec to route around it. Keep the
|
|
14
|
-
* import list empty.
|
|
15
|
-
*
|
|
16
|
-
* When a service has a non-JS twin of this codec (e.g. a Python API), keep its
|
|
17
|
-
* byte → string vectors identical to the ones in `id.test.ts`, so a stored
|
|
18
|
-
* UUIDv7 and a prefixed base58 id are the same encoding of the same 16 bytes.
|
|
19
|
-
* That cross-impl contract is the most important property of this file — keep
|
|
20
|
-
* the vectors in lockstep.
|
|
21
|
-
*
|
|
22
|
-
* Store the hyphenated UUIDv7 at rest (uuid columns stay native and time-ordered
|
|
23
|
-
* for index locality) and use {@link toPrefixedId} to skin it as a prefixed
|
|
24
|
-
* base58 id for the wire / display, {@link fromPrefixedId} to recover it.
|
|
25
|
-
* {@link base58Id} mints a fresh one directly; {@link createIdRegistry} builds a
|
|
26
|
-
* typed, prefix-validated set of helpers for a project's entities.
|
|
27
|
-
*/
|
|
28
|
-
/**
|
|
29
|
-
* Mint a **UUIDv7** (RFC 9562): a 48-bit Unix-ms timestamp prefix + random tail,
|
|
30
|
-
* version `7`, variant `10`. UUID-shaped (drops straight into a `uuid` column)
|
|
31
|
-
* while staying time-ordered for index locality. Used as Better Auth's
|
|
32
|
-
* `advanced.database.generateId`. Node/Bun's `randomUUID` is v4-only, so we lay
|
|
33
|
-
* the bytes out by hand.
|
|
34
|
-
*/
|
|
35
|
-
export const uuidGenerateId = () => {
|
|
36
|
-
const bytes = crypto.getRandomValues(new Uint8Array(16));
|
|
37
|
-
const ts = Date.now();
|
|
38
|
-
bytes[0] = Math.floor(ts / 2 ** 40) & 0xff;
|
|
39
|
-
bytes[1] = Math.floor(ts / 2 ** 32) & 0xff;
|
|
40
|
-
bytes[2] = Math.floor(ts / 2 ** 24) & 0xff;
|
|
41
|
-
bytes[3] = Math.floor(ts / 2 ** 16) & 0xff;
|
|
42
|
-
bytes[4] = Math.floor(ts / 2 ** 8) & 0xff;
|
|
43
|
-
bytes[5] = ts & 0xff;
|
|
44
|
-
bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x70; // version 7
|
|
45
|
-
bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80; // variant 10
|
|
46
|
-
return bytesToUuid(bytes); // mint site
|
|
47
|
-
};
|
|
48
|
-
const B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
|
|
49
|
-
// ceil(128 / log2(58)): a 16-byte value never needs more than 22 digits. We
|
|
50
|
-
// left-pad to it so every body is uniform width and sorts lexically ==
|
|
51
|
-
// chronologically (UUIDv7's ms-timestamp prefix lives in the high bytes).
|
|
52
|
-
const WIDTH = 22;
|
|
53
|
-
// A bare base58 body: 22 chars, Bitcoin alphabet (no 0 / I / O / l).
|
|
54
|
-
const BODY = "[1-9A-HJ-NP-Za-km-z]{22}";
|
|
55
|
-
/** Big-endian base58 (Bitcoin alphabet) of 16 bytes, left-padded to `WIDTH`. */
|
|
56
|
-
function encode58(bytes) {
|
|
57
|
-
let n = 0n;
|
|
58
|
-
for (const b of bytes)
|
|
59
|
-
n = (n << 8n) | BigInt(b);
|
|
60
|
-
let out = "";
|
|
61
|
-
while (n > 0n) {
|
|
62
|
-
out = B58.charAt(Number(n % 58n)) + out;
|
|
63
|
-
n /= 58n;
|
|
64
|
-
}
|
|
65
|
-
return out.padStart(WIDTH, B58.charAt(0));
|
|
66
|
-
}
|
|
67
|
-
/** Inverse of {@link encode58}: a base58 body back to 16 bytes. */
|
|
68
|
-
function decode58(body) {
|
|
69
|
-
let n = 0n;
|
|
70
|
-
for (const ch of body) {
|
|
71
|
-
const v = B58.indexOf(ch);
|
|
72
|
-
if (v < 0)
|
|
73
|
-
throw new Error(`invalid base58 char: ${ch}`);
|
|
74
|
-
n = n * 58n + BigInt(v);
|
|
75
|
-
}
|
|
76
|
-
// 58^22 slightly exceeds 2^128, so a high-range 22-char body can overflow 16
|
|
77
|
-
// bytes; silently truncating would alias two distinct wire ids to one UUID.
|
|
78
|
-
if (n >= 1n << 128n)
|
|
79
|
-
throw new Error(`base58 value out of uuid range: ${body}`);
|
|
80
|
-
const bytes = new Uint8Array(16);
|
|
81
|
-
for (let i = 15; i >= 0; i--) {
|
|
82
|
-
bytes[i] = Number(n & 0xffn);
|
|
83
|
-
n >>= 8n;
|
|
84
|
-
}
|
|
85
|
-
return bytes;
|
|
86
|
-
}
|
|
87
|
-
/** A hyphenated UUID string → its 16 raw bytes. */
|
|
88
|
-
function uuidToBytes(uuid) {
|
|
89
|
-
const hex = uuid.replace(/-/g, "");
|
|
90
|
-
if (!/^[0-9a-fA-F]{32}$/.test(hex))
|
|
91
|
-
throw new Error(`not a uuid: ${uuid}`);
|
|
92
|
-
const bytes = new Uint8Array(16);
|
|
93
|
-
for (let i = 0; i < 16; i++) {
|
|
94
|
-
bytes[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
|
95
|
-
}
|
|
96
|
-
return bytes;
|
|
97
|
-
}
|
|
98
|
-
/** 16 raw bytes → a canonical hyphenated UUID string. */
|
|
99
|
-
function bytesToUuid(bytes) {
|
|
100
|
-
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
101
|
-
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
102
|
-
}
|
|
103
|
-
/** Skin a stored hyphenated UUIDv7 as a prefixed base58 id, e.g. `team_…`. */
|
|
104
|
-
export function toPrefixedId(uuid, prefix) {
|
|
105
|
-
return `${prefix}_${encode58(uuidToBytes(uuid))}`;
|
|
106
|
-
}
|
|
107
|
-
/** Inverse of {@link toPrefixedId}: recover the hyphenated UUIDv7. */
|
|
108
|
-
export function fromPrefixedId(id) {
|
|
109
|
-
const body = id.slice(id.indexOf("_") + 1);
|
|
110
|
-
return bytesToUuid(decode58(body));
|
|
111
|
-
}
|
|
112
|
-
/** Mint a fresh prefixed base58 id (UUIDv7 core), for text-id sites / API parity. */
|
|
113
|
-
export function base58Id(prefix) {
|
|
114
|
-
return toPrefixedId(uuidGenerateId(), prefix);
|
|
115
|
-
}
|
|
116
|
-
// Any RFC 9562 version (1-8): sites mint v7, but migrated rows are often v4.
|
|
117
|
-
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
118
|
-
/**
|
|
119
|
-
* Whether `value` is a hyphenated uuid — the sanctioned string→{@link Uuid}
|
|
120
|
-
* bless: narrowing through the shape check is never a blind cast. Use at trust
|
|
121
|
-
* boundaries (env/config, external payloads, `crypto.randomUUID()`).
|
|
122
|
-
*/
|
|
123
|
-
export const isUuid = (value) => typeof value === "string" && UUID_RE.test(value);
|
|
124
|
-
/** The throwing {@link isUuid}: bless a string you require to be a uuid. */
|
|
125
|
-
export function asUuid(value) {
|
|
126
|
-
if (!isUuid(value))
|
|
127
|
-
throw new Error(`not a uuid: ${value}`);
|
|
128
|
-
return value;
|
|
129
|
-
}
|
|
130
|
-
function makeHelper(prefix) {
|
|
131
|
-
// Prefixes are developer-controlled identifier constants, never user input.
|
|
132
|
-
const matcher = new RegExp(`^${prefix}_${BODY}$`);
|
|
133
|
-
// The brands are erased at runtime; these casts are the sole mint sites.
|
|
134
|
-
return {
|
|
135
|
-
prefix,
|
|
136
|
-
mint: () => base58Id(prefix),
|
|
137
|
-
encode: (uuid) => toPrefixedId(uuid, prefix),
|
|
138
|
-
decode: (id) => {
|
|
139
|
-
if (!matcher.test(id))
|
|
140
|
-
throw new Error(`not a ${prefix}_ id: ${id}`);
|
|
141
|
-
return fromPrefixedId(id);
|
|
142
|
-
},
|
|
143
|
-
decodeOrNull: (id) => (matcher.test(id) ? fromPrefixedId(id) : null),
|
|
144
|
-
is: (id) => matcher.test(id),
|
|
145
|
-
};
|
|
146
|
-
}
|
|
147
|
-
/**
|
|
148
|
-
* Build a typed, prefix-validated id registry for a project's entities — one
|
|
149
|
-
* place to declare every prefix instead of hand-rolling encode/decode wrappers:
|
|
150
|
-
*
|
|
151
|
-
* ```ts
|
|
152
|
-
* const ids = createIdRegistry({ org: "org", agent: "agt", session: "cs" });
|
|
153
|
-
* ids.org.mint(); // "org_3k9…"
|
|
154
|
-
* ids.org.encode(uuid); // "org_…"
|
|
155
|
-
* ids.org.decode("org_…"); // uuid — throws on a wrong / missing prefix
|
|
156
|
-
* ids.agent.is(someId); // boolean
|
|
157
|
-
* ```
|
|
158
|
-
*/
|
|
159
|
-
export function createIdRegistry(prefixes) {
|
|
160
|
-
const reg = {};
|
|
161
|
-
for (const [key, prefix] of Object.entries(prefixes)) {
|
|
162
|
-
reg[key] = makeHelper(prefix);
|
|
163
|
-
}
|
|
164
|
-
return reg;
|
|
165
|
-
}
|
|
166
|
-
/**
|
|
167
|
-
* Which entity a prefixed id belongs to, or `null` if no helper in `registry`
|
|
168
|
-
* recognises it (a raw uuid, a sentinel, a foreign prefix).
|
|
169
|
-
*
|
|
170
|
-
* A public id is **self-describing**: its prefix names its entity, so resolving
|
|
171
|
-
* one needs no surrounding context. That is the property behind every
|
|
172
|
-
* entity-agnostic decode — a polymorphic FK whose target is named by a sibling
|
|
173
|
-
* `*_type` column, a raw-SQL binding that only has a value, a webhook payload.
|
|
174
|
-
* The inverse does **not** hold: a bare uuid carries no entity, so encoding
|
|
175
|
-
* always needs to know which entity you meant.
|
|
176
|
-
*
|
|
177
|
-
* Standalone rather than a registry method: the registry is keyed by entity
|
|
178
|
-
* name, so a method would collide with an entity literally called `entityOf`.
|
|
179
|
-
*/
|
|
180
|
-
export function entityOf(registry, value) {
|
|
181
|
-
// Cheap reject: every prefixed id has one, and raw uuids never do.
|
|
182
|
-
if (!value.includes("_"))
|
|
183
|
-
return null;
|
|
184
|
-
for (const entity of Object.keys(registry)) {
|
|
185
|
-
if (registry[entity].is(value))
|
|
186
|
-
return entity;
|
|
187
|
-
}
|
|
188
|
-
return null;
|
|
189
|
-
}
|
|
190
|
-
/**
|
|
191
|
-
* Decode a prefixed id belonging to **any** entity in `registry` (see
|
|
192
|
-
* {@link entityOf}), for the boundaries that can't name one: polymorphic FKs,
|
|
193
|
-
* raw-SQL id bindings, generic audit/event payloads.
|
|
194
|
-
*
|
|
195
|
-
* Tolerant by design — a value no helper recognises is returned unchanged, so an
|
|
196
|
-
* already-decoded uuid passes straight through and this is safe to apply to a
|
|
197
|
-
* value that may or may not be skinned. Use a helper's `decode`/`decodeOrNull`
|
|
198
|
-
* when you know the entity and want a wrong prefix rejected.
|
|
8
|
+
* Like `id758` itself, this module must stay isomorphic (no node-only imports):
|
|
9
|
+
* it is pulled into Drizzle schemas, client components and edge runtimes.
|
|
199
10
|
*/
|
|
200
|
-
export
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
11
|
+
export * from "id758";
|
|
12
|
+
import { decodeId, encodeId, mintId, uuidv7 } from "id758";
|
|
13
|
+
/** @deprecated Use `uuidv7` from `id758`. */
|
|
14
|
+
export const uuidGenerateId = uuidv7;
|
|
15
|
+
/** @deprecated Use `encodeId` from `id758`. */
|
|
16
|
+
export const toPrefixedId = encodeId;
|
|
17
|
+
/** @deprecated Use `decodeId` from `id758`. */
|
|
18
|
+
export const fromPrefixedId = decodeId;
|
|
19
|
+
/** @deprecated Use `mintId` from `id758`. */
|
|
20
|
+
export const base58Id = mintId;
|
|
204
21
|
//# sourceMappingURL=id.js.map
|
package/dist/id.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"id.js","sourceRoot":"","sources":["../src/id.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"id.js","sourceRoot":"","sources":["../src/id.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,cAAc,OAAO,CAAC;AACtB,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,OAAO,CAAC;AAE3D,6CAA6C;AAC7C,MAAM,CAAC,MAAM,cAAc,GAAG,MAAM,CAAC;AACrC,+CAA+C;AAC/C,MAAM,CAAC,MAAM,YAAY,GAAG,QAAQ,CAAC;AACrC,+CAA+C;AAC/C,MAAM,CAAC,MAAM,cAAc,GAAG,QAAQ,CAAC;AACvC,6CAA6C;AAC7C,MAAM,CAAC,MAAM,QAAQ,GAAG,MAAM,CAAC"}
|
package/dist/pglite/index.d.ts
CHANGED
|
@@ -31,6 +31,14 @@ export interface PgliteServerOptions {
|
|
|
31
31
|
/** Journal table schema. Default `drizzle`. */
|
|
32
32
|
schema?: string;
|
|
33
33
|
}>;
|
|
34
|
+
/**
|
|
35
|
+
* Install the id codec's Postgres functions (`id758_encode` / `id758_decode`,
|
|
36
|
+
* see `@ingram-tech/nk-db/id/sql`) before any migration runs. Default `true`:
|
|
37
|
+
* the script is idempotent and costs nothing, and having it in dev/test means
|
|
38
|
+
* a query can use the functions before — or without — the site journaling
|
|
39
|
+
* them. Set `false` to boot exactly what the migrations declare.
|
|
40
|
+
*/
|
|
41
|
+
id758?: boolean;
|
|
34
42
|
/** Override how the primary `migrationsFolder` is applied (e.g. raw-SQL apps).
|
|
35
43
|
* `dependencyMigrations` still run first, before this. */
|
|
36
44
|
migrate?: (db: PGlite) => Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/pglite/index.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,MAAM,EAAE,KAAK,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAC/D,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","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,eAAO,MAAM,cAAc,aACjB,mBAAmB,GAAG;IAAE,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAA;CAAE,KACpD,OAAO,CAAC,IAAI,CAgCd,CAAC;AAEF,MAAM,WAAW,MAAM;IACtB,2EAA2E;IAC3E,IAAI,EAAE,IAAI,CAAC;IACX,WAAW,EAAE,MAAM,CAAC;IACpB,iEAAiE;IACjE,KAAK,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IAC3B,4DAA4D;IAC5D,KAAK,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAC3B;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,eAAO,MAAM,YAAY,aACf,mBAAmB,KAC1B,OAAO,CAAC,MAAM,CAiBhB,CAAC"}
|
package/dist/pglite/index.js
CHANGED
|
@@ -12,6 +12,7 @@ import { rm } from "node:fs/promises";
|
|
|
12
12
|
import { createServer } from "node:net";
|
|
13
13
|
import { PGlite } from "@electric-sql/pglite";
|
|
14
14
|
import { PGLiteSocketServer } from "@electric-sql/pglite-socket";
|
|
15
|
+
import { ID758_SQL } from "id758/sql";
|
|
15
16
|
import { resetPublicTables } from "./reset.js";
|
|
16
17
|
/** Ask the OS for a currently-free TCP port (bind :0, read it back, release).
|
|
17
18
|
* Used so the test harness never collides with a dev Postgres on 5432. */
|
|
@@ -74,6 +75,8 @@ export const createPgliteServer = async (options = {}) => {
|
|
|
74
75
|
// until a --fresh wipe). A custom `migrate` must be idempotent the same way.
|
|
75
76
|
// Dependency chains (e.g. nk-auth's tables) go first so the app's own
|
|
76
77
|
// migrations can reference them by FK.
|
|
78
|
+
if (options.id758 !== false)
|
|
79
|
+
await db.exec(ID758_SQL);
|
|
77
80
|
await applyDependencyMigrations(db, options.dependencyMigrations ?? []);
|
|
78
81
|
await (options.migrate ?? defaultMigrate(migrationsFolder))(db);
|
|
79
82
|
const server = new PGLiteSocketServer({ db, host, port });
|
package/dist/pglite/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/pglite/index.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,iFAAiF;AACjF,uEAAuE;AACvE,iFAAiF;AACjF,sBAAsB;AACtB,EAAE;AACF,8EAA8E;AAC9E,8EAA8E;AAC9E,2CAA2C;AAE3C,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,EAAE,EAAE,MAAM,kBAAkB,CAAC;AACtC,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AACxC,OAAO,EAAE,MAAM,EAAmB,MAAM,sBAAsB,CAAC;AAC/D,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/pglite/index.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,iFAAiF;AACjF,uEAAuE;AACvE,iFAAiF;AACjF,sBAAsB;AACtB,EAAE;AACF,8EAA8E;AAC9E,8EAA8E;AAC9E,2CAA2C;AAE3C,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,EAAE,EAAE,MAAM,kBAAkB,CAAC;AACtC,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AACxC,OAAO,EAAE,MAAM,EAAmB,MAAM,sBAAsB,CAAC;AAC/D,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACjE,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAEtC,OAAO,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AA4D/C;2EAC2E;AAC3E,MAAM,QAAQ,GAAG,CAAC,IAAY,EAAmB,EAAE,CAClD,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;IAC/B,MAAM,GAAG,GAAG,YAAY,EAAE,CAAC;IAC3B,GAAG,CAAC,IAAI,CAAC,OA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: one TLS-aware pg pool, raw-SQL helpers, Drizzle wiring, and a PGlite (no-Docker) dev/test harness for Next.js sites.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -13,7 +13,10 @@
|
|
|
13
13
|
"access": "public"
|
|
14
14
|
},
|
|
15
15
|
"files": [
|
|
16
|
-
"dist"
|
|
16
|
+
"dist",
|
|
17
|
+
"src",
|
|
18
|
+
"!src/**/*.test.ts",
|
|
19
|
+
"!src/**/*.test.tsx"
|
|
17
20
|
],
|
|
18
21
|
"bin": {
|
|
19
22
|
"nk-pglite-dev": "./dist/pglite/dev.js",
|
|
@@ -32,6 +35,10 @@
|
|
|
32
35
|
"types": "./dist/id-drizzle.d.ts",
|
|
33
36
|
"default": "./dist/id-drizzle.js"
|
|
34
37
|
},
|
|
38
|
+
"./id/sql": {
|
|
39
|
+
"types": "./dist/id-sql.d.ts",
|
|
40
|
+
"default": "./dist/id-sql.js"
|
|
41
|
+
},
|
|
35
42
|
"./migrate": {
|
|
36
43
|
"types": "./dist/migrate.d.ts",
|
|
37
44
|
"default": "./dist/migrate.js"
|
|
@@ -51,6 +58,7 @@
|
|
|
51
58
|
"test": "vitest run"
|
|
52
59
|
},
|
|
53
60
|
"dependencies": {
|
|
61
|
+
"id758": "^1.1.0",
|
|
54
62
|
"zod": "^4.4.3"
|
|
55
63
|
},
|
|
56
64
|
"peerDependencies": {
|
|
@@ -68,13 +76,13 @@
|
|
|
68
76
|
}
|
|
69
77
|
},
|
|
70
78
|
"devDependencies": {
|
|
71
|
-
"@electric-sql/pglite": "^0.5.
|
|
72
|
-
"@electric-sql/pglite-socket": "^0.2.
|
|
73
|
-
"@ingram-tech/nk-dev": "0.
|
|
74
|
-
"@types/node": "^26.
|
|
75
|
-
"@types/pg": "^8.
|
|
79
|
+
"@electric-sql/pglite": "^0.5.5",
|
|
80
|
+
"@electric-sql/pglite-socket": "^0.2.8",
|
|
81
|
+
"@ingram-tech/nk-dev": "0.12.0",
|
|
82
|
+
"@types/node": "^26.2.0",
|
|
83
|
+
"@types/pg": "^8.23.1",
|
|
76
84
|
"drizzle-orm": "^0.45.2",
|
|
77
|
-
"pg": "^8.
|
|
85
|
+
"pg": "^8.23.0",
|
|
78
86
|
"typescript": "^7.0.2",
|
|
79
87
|
"vitest": "^4.1.10"
|
|
80
88
|
}
|
package/src/coerce.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// Coerce Postgres value representations back to the JS types app code expects.
|
|
2
|
+
//
|
|
3
|
+
// Why these exist: `pg` (and Drizzle on top of it) surfaces some columns in a
|
|
4
|
+
// form a strict response/validation schema rejects — `numeric` as a string (to
|
|
5
|
+
// avoid losing precision), and `timestamp(..., { mode: "string" })` as Postgres'
|
|
6
|
+
// own text form ("2026-06-21 18:22:08.331494+00", space separator, short
|
|
7
|
+
// offset). Neither satisfies a schema expecting `z.number()` / strict
|
|
8
|
+
// `z.iso.datetime()`.
|
|
9
|
+
//
|
|
10
|
+
// Use these at the read/response boundary when handing Drizzle/`pg` rows to such
|
|
11
|
+
// a schema. They are presentation coercions, not domain math — keep money
|
|
12
|
+
// arithmetic on the string/decimal value, and only convert for output.
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Normalize a Postgres timestamp string to a strict ISO-8601 UTC string
|
|
16
|
+
* ("2026-06-21T18:22:08.331Z"), the form `z.iso.datetime()` (no offset) accepts.
|
|
17
|
+
*
|
|
18
|
+
* `Date` parses both Postgres' space-separated form and the `+00:00` offset
|
|
19
|
+
* form to the same instant, and `.toISOString()` emits the canonical `T…Z`.
|
|
20
|
+
* An offset-less value (a `timestamp` *without* time zone column) is treated
|
|
21
|
+
* as UTC — `new Date()` alone would read it in the server's local zone, so the
|
|
22
|
+
* same row would shift by host timezone. `null` passes through.
|
|
23
|
+
*/
|
|
24
|
+
export function pgTimestampToIso(value: string): string;
|
|
25
|
+
export function pgTimestampToIso(value: null): null;
|
|
26
|
+
export function pgTimestampToIso(value: string | null): string | null;
|
|
27
|
+
export function pgTimestampToIso(value: string | null): string | null {
|
|
28
|
+
if (value === null) return null;
|
|
29
|
+
// Postgres text forms: "YYYY-MM-DD HH:MM:SS[.ffffff]" with an optional
|
|
30
|
+
// trailing offset like "+00", "+05:30" or "Z". A time with no offset gets
|
|
31
|
+
// UTC appended; a date-only value already parses as UTC per the Date spec.
|
|
32
|
+
const needsUtcMarker =
|
|
33
|
+
/\d{2}:\d{2}/.test(value) && !/(?:[+-]\d{2}(?::?\d{2})?|Z)$/i.test(value);
|
|
34
|
+
return new Date(needsUtcMarker ? `${value}Z` : value).toISOString();
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Coerce a Postgres `numeric` value (which `pg`/Drizzle return as a string to
|
|
39
|
+
* preserve arbitrary precision) to a JS number, for schemas that expect
|
|
40
|
+
* `z.number()`. `null` passes through.
|
|
41
|
+
*
|
|
42
|
+
* Lossy for values outside `Number`'s safe range — only use at the response
|
|
43
|
+
* boundary, never for money math (keep that on the string/decimal value).
|
|
44
|
+
*/
|
|
45
|
+
export function pgNumericToNumber(value: string): number;
|
|
46
|
+
export function pgNumericToNumber(value: null): null;
|
|
47
|
+
export function pgNumericToNumber(value: string | null): number | null;
|
|
48
|
+
export function pgNumericToNumber(value: string | null): number | null {
|
|
49
|
+
return value === null ? null : Number(value);
|
|
50
|
+
}
|
package/src/drizzle.ts
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { sql } from "drizzle-orm";
|
|
2
|
+
import { drizzle, type NodePgDatabase } from "drizzle-orm/node-postgres";
|
|
3
|
+
import type { Pool } from "pg";
|
|
4
|
+
import { type RlsClaims, type RlsOptions, resolveRlsConfig } from "./rls.js";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Build the Drizzle instance on the shared pool. This is the default query path
|
|
8
|
+
* for app tables — schema-first, with `drizzle-kit` generating the migrations
|
|
9
|
+
* (kills the hand-written-SQL drift). It rides the same `pg.Pool` that backs the
|
|
10
|
+
* raw helpers and Better Auth, so there's still exactly one pool per process.
|
|
11
|
+
*
|
|
12
|
+
* import * as schema from "./schema";
|
|
13
|
+
* export const pool = createPool();
|
|
14
|
+
* export const db = createDb(pool, schema);
|
|
15
|
+
*/
|
|
16
|
+
export const createDb = <TSchema extends Record<string, unknown>>(
|
|
17
|
+
pool: Pool,
|
|
18
|
+
schema: TSchema,
|
|
19
|
+
): NodePgDatabase<TSchema> => drizzle(pool, { schema });
|
|
20
|
+
|
|
21
|
+
/** The transaction handle Drizzle hands its `db.transaction(fn)` callback. */
|
|
22
|
+
type DrizzleTx<TSchema extends Record<string, unknown>> = Parameters<
|
|
23
|
+
Parameters<NodePgDatabase<TSchema>["transaction"]>[0]
|
|
24
|
+
>[0];
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Run `fn` inside a Drizzle transaction **scoped to a user**, so RLS policies
|
|
28
|
+
* apply on a direct connection. It sets `request.jwt.claims` +
|
|
29
|
+
* `SET LOCAL ROLE` (default `authenticated`) as the first statement, so existing
|
|
30
|
+
* `auth.uid()` policies fire unchanged; the `tx` passed to `fn` is a normal
|
|
31
|
+
* Drizzle transaction (full query builder + `tx.execute`). Use for user-facing
|
|
32
|
+
* reads/writes; use plain `db` for service-role paths. The connection role must
|
|
33
|
+
* not bypass RLS for the rows touched — see `rls.ts`.
|
|
34
|
+
*
|
|
35
|
+
* const notes = await withRlsTransaction(db, { sub: user.id }, (tx) =>
|
|
36
|
+
* tx.select().from(schema.notes),
|
|
37
|
+
* );
|
|
38
|
+
*/
|
|
39
|
+
export const withRlsTransaction = <TSchema extends Record<string, unknown>, T>(
|
|
40
|
+
db: NodePgDatabase<TSchema>,
|
|
41
|
+
claims: RlsClaims,
|
|
42
|
+
fn: (tx: DrizzleTx<TSchema>) => Promise<T>,
|
|
43
|
+
options: RlsOptions = {},
|
|
44
|
+
): Promise<T> =>
|
|
45
|
+
db.transaction(async (tx) => {
|
|
46
|
+
const { role, claimsSetting, claimsJson } = resolveRlsConfig(claims, options);
|
|
47
|
+
await tx.execute(
|
|
48
|
+
sql`select set_config(${claimsSetting}, ${claimsJson}, true), set_config('role', ${role}, true)`,
|
|
49
|
+
);
|
|
50
|
+
return fn(tx);
|
|
51
|
+
});
|
package/src/errors.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// Inspect Postgres driver errors by SQLSTATE without hand-rolling the `.cause`
|
|
2
|
+
// chain walk at every call site. `pg` puts the SQLSTATE on `error.code`, but
|
|
3
|
+
// wrappers (Drizzle, our own helpers) often re-throw with the original error
|
|
4
|
+
// nested under `.cause`, so a flat `err.code === …` check silently misses it.
|
|
5
|
+
|
|
6
|
+
/** SQLSTATE `23505` — `unique_violation`. */
|
|
7
|
+
export const PG_UNIQUE_VIOLATION = "23505";
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* True when `error`, or anything in its `.cause` chain, is a Postgres error
|
|
11
|
+
* whose SQLSTATE equals `code`.
|
|
12
|
+
*
|
|
13
|
+
* Prefer `INSERT … ON CONFLICT` over catch-and-branch where you can (it avoids
|
|
14
|
+
* the pooled-connection-destroy footgun — see `docs/db-package.md`), but use
|
|
15
|
+
* this for the cases that genuinely must inspect the failure.
|
|
16
|
+
*/
|
|
17
|
+
export const isPgError = (error: unknown, code: string): boolean => {
|
|
18
|
+
let current: unknown = error;
|
|
19
|
+
// Depth cap: a cyclic `.cause` chain (err.cause = err) must not hang.
|
|
20
|
+
for (
|
|
21
|
+
let depth = 0;
|
|
22
|
+
depth < 32 && current !== null && current !== undefined;
|
|
23
|
+
depth++
|
|
24
|
+
) {
|
|
25
|
+
if (typeof current === "object" && "code" in current && current.code === code) {
|
|
26
|
+
return true;
|
|
27
|
+
}
|
|
28
|
+
current = current instanceof Error ? current.cause : undefined;
|
|
29
|
+
}
|
|
30
|
+
return false;
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
/** Convenience for the most common check: a `23505` unique violation. */
|
|
34
|
+
export const isUniqueViolation = (error: unknown): boolean =>
|
|
35
|
+
isPgError(error, PG_UNIQUE_VIOLATION);
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { type AnyColumn, sql, type SQL } from "drizzle-orm";
|
|
2
|
+
import { customType } from "drizzle-orm/pg-core";
|
|
3
|
+
import { decodeAnyId, type Id, type IdHelper } from "./id.js";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Drizzle bindings for the id codec (`@ingram-tech/nk-db/id/drizzle`).
|
|
7
|
+
*
|
|
8
|
+
* Deliberately a separate subpath from the package root: this is imported by a
|
|
9
|
+
* site's `schema.ts`, so it pulls only `drizzle-orm` and the (isomorphic) codec
|
|
10
|
+
* — never `pg`, the pool, or the RLS helpers that the root export carries.
|
|
11
|
+
*
|
|
12
|
+
* The invariant these bindings hold: **application code only ever sees public
|
|
13
|
+
* ids**. A column declared with `idColumn` decodes a public id to its raw uuid
|
|
14
|
+
* on the way *into* Postgres and encodes the uuid on the way *out*, so a row
|
|
15
|
+
* read through Drizzle carries `inv_…`, a `where eq(invoices.id, "inv_…")`
|
|
16
|
+
* just works, and nothing above the schema converts by hand. Raw SQL crosses
|
|
17
|
+
* the same boundary with `id758_encode` / `id758_decode` in the query (see
|
|
18
|
+
* `@ingram-tech/nk-db/id/sql`) or with {@link IdColumnBindings.encodedId} /
|
|
19
|
+
* {@link IdColumnBindings.sqlUuid} here.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
type IdColumnBindings<K extends string> = {
|
|
23
|
+
/**
|
|
24
|
+
* A `uuid` column that speaks public ids. Its TypeScript type is the
|
|
25
|
+
* entity's branded `Id<E>`, so an invoice id can't be handed to an account
|
|
26
|
+
* column.
|
|
27
|
+
*
|
|
28
|
+
* - `toDriver` (insert/update `SET` values **and** WHERE-clause comparison
|
|
29
|
+
* values: `eq`, `inArray`, …) decodes the public id to its uuid. Tolerant:
|
|
30
|
+
* a raw uuid passes through unchanged, so a value minted by the database
|
|
31
|
+
* or by Better Auth's `generateId` still inserts.
|
|
32
|
+
* - `fromDriver` (every selected value, including `returning()` and the
|
|
33
|
+
* relational `db.query`) encodes the uuid, so a read yields `inv_…`.
|
|
34
|
+
*
|
|
35
|
+
* `dataType` is unchanged (`uuid`), so this is a TypeScript-only mapping: no
|
|
36
|
+
* DDL, no migration, and `drizzle-kit generate` reports no schema diff.
|
|
37
|
+
*/
|
|
38
|
+
idColumn: <E extends K>(
|
|
39
|
+
entity: E,
|
|
40
|
+
) => ReturnType<typeof customType<IdColumnConfig<Id<E>>>>;
|
|
41
|
+
/**
|
|
42
|
+
* A `uuid` column for a **polymorphic** FK — an `entity_id` whose target is
|
|
43
|
+
* named by a sibling `*_type` column — where no single-entity codec applies.
|
|
44
|
+
* Decodes a public id of any entity in the registry (ids are
|
|
45
|
+
* self-describing) on the way in; reads stay raw uuids, because a column
|
|
46
|
+
* cannot see its sibling to know which prefix to put back. Encode such a
|
|
47
|
+
* value in the query with {@link IdColumnBindings.encodedId} once the type
|
|
48
|
+
* is known, or with `entityOf` in code.
|
|
49
|
+
*
|
|
50
|
+
* The same blindness means it accepts an id of the *wrong* entity. Where
|
|
51
|
+
* both halves are in hand, check them (`entityOf(registry, id) ===
|
|
52
|
+
* expectedType`) before writing, or the row is silently mislabelled.
|
|
53
|
+
*/
|
|
54
|
+
polymorphicIdColumn: ReturnType<typeof customType<IdColumnConfig<string>>>;
|
|
55
|
+
/**
|
|
56
|
+
* A raw-SQL selection of a uuid column or expression as the entity's public
|
|
57
|
+
* id, for the queries the column layer cannot reach (a `sql` select, an
|
|
58
|
+
* aggregate, a polymorphic column whose type this row has resolved):
|
|
59
|
+
* `db.select({ id: encodedId("invoice", invoices.id) })`. Emits
|
|
60
|
+
* `id758_encode('inv', …)`, so the database must have the functions
|
|
61
|
+
* (`@ingram-tech/nk-db/id/sql`).
|
|
62
|
+
*/
|
|
63
|
+
encodedId: <E extends K>(entity: E, column: AnyColumn | SQL) => SQL<Id<E>>;
|
|
64
|
+
/**
|
|
65
|
+
* Bind an id into raw SQL as a `uuid`. Raw SQL and RPC args bypass the column
|
|
66
|
+
* layer entirely, so this is the sanctioned binding for them:
|
|
67
|
+
* `sql\`select f(${sqlUuid(id)})\``. Needs no entity because ids are
|
|
68
|
+
* self-describing; a raw uuid passes through, and null/undefined binds as
|
|
69
|
+
* `null::uuid`. Decodes in JS, so it needs nothing installed in the
|
|
70
|
+
* database — the SQL-side alternative is `id758_decode(${id})`.
|
|
71
|
+
*/
|
|
72
|
+
sqlUuid: (value: string | null | undefined) => SQL;
|
|
73
|
+
/**
|
|
74
|
+
* Bind a list of ids as a `uuid[]`, for RPCs taking a `uuid[]` arg. Built
|
|
75
|
+
* element-wise on purpose: pg binds a JS array as `text[]`, and
|
|
76
|
+
* `text[]::uuid[]` is not a legal direct cast (SQLSTATE 42846).
|
|
77
|
+
*/
|
|
78
|
+
sqlUuidArray: (values: readonly string[]) => SQL;
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
type IdColumnConfig<TData extends string> = { data: TData; driverData: string };
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Build the Drizzle id bindings for a site's registry:
|
|
85
|
+
*
|
|
86
|
+
* ```ts
|
|
87
|
+
* // ids.ts
|
|
88
|
+
* export const ids = createIdRegistry({ invoice: "inv", account: "acct" });
|
|
89
|
+
* export const { idColumn, polymorphicIdColumn, encodedId, sqlUuid } =
|
|
90
|
+
* createIdColumns(ids);
|
|
91
|
+
*
|
|
92
|
+
* // schema.ts
|
|
93
|
+
* export const invoices = pgTable("invoices", {
|
|
94
|
+
* id: idColumn("invoice")().primaryKey(), // Id<"invoice">, "inv_…" in and out
|
|
95
|
+
* account_id: idColumn("account")().notNull(),
|
|
96
|
+
* });
|
|
97
|
+
* ```
|
|
98
|
+
*/
|
|
99
|
+
export function createIdColumns<K extends string>(
|
|
100
|
+
registry: Record<K, IdHelper>,
|
|
101
|
+
): IdColumnBindings<K> {
|
|
102
|
+
const decodeAny = (value: string) => decodeAnyId(registry, value);
|
|
103
|
+
|
|
104
|
+
const sqlUuid = (value: string | null | undefined): SQL =>
|
|
105
|
+
sql`${value == null ? null : decodeAny(value)}::uuid`;
|
|
106
|
+
|
|
107
|
+
return {
|
|
108
|
+
idColumn: <E extends K>(entity: E) =>
|
|
109
|
+
customType<IdColumnConfig<Id<E>>>({
|
|
110
|
+
dataType: () => "uuid",
|
|
111
|
+
toDriver: (value) =>
|
|
112
|
+
typeof value === "string"
|
|
113
|
+
? (registry[entity].decodeOrNull(value) ?? value)
|
|
114
|
+
: value,
|
|
115
|
+
fromDriver: (value) => registry[entity].encode(value) as Id<E>,
|
|
116
|
+
}),
|
|
117
|
+
polymorphicIdColumn: customType<IdColumnConfig<string>>({
|
|
118
|
+
dataType: () => "uuid",
|
|
119
|
+
toDriver: (value) => (typeof value === "string" ? decodeAny(value) : value),
|
|
120
|
+
}),
|
|
121
|
+
encodedId: <E extends K>(entity: E, column: AnyColumn | SQL) =>
|
|
122
|
+
sql<Id<E>>`id758_encode(${registry[entity].prefix}, ${column})`,
|
|
123
|
+
sqlUuid,
|
|
124
|
+
sqlUuidArray: (values) =>
|
|
125
|
+
sql`array[${sql.join(
|
|
126
|
+
values.map((value) => sqlUuid(value)),
|
|
127
|
+
sql`, `,
|
|
128
|
+
)}]::uuid[]`,
|
|
129
|
+
};
|
|
130
|
+
}
|