@jini-ai/db 0.3.4 → 0.3.6

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/CHANGELOG.md CHANGED
@@ -1,3 +1,11 @@
1
+ ## 0.3.6 — 2026-10-22
2
+
3
+ - 2026-10-22: Security queue fixes, testing helper reads os.userInfo() only when PGUSER is unset, complexity refactors, coverage.
4
+
5
+ ## 0.3.5 — 2026-10-16
6
+
7
+ - Store copy lets the host exclude retained restore tables from the catalog, emptiness check and copy (b0b13de4); copy only builds indexes for tables it created (d748cf67).
8
+
1
9
  ## 0.3.4 — 2026-10-13
2
10
 
3
11
  - Vault SQL repo imports `@jini-ai/platform/secrets/credential-sets/contracts`; requires @jini-ai/platform >=0.5.6 (credential-sets/contracts); publish platform first.
package/NOTICE.md CHANGED
@@ -25,3 +25,6 @@
25
25
  text); a CancelRequest closes its connection; GSSENC requests are answered `N` like SSL.
26
26
  9. Removed: hex `inspect` dumps, `EventTarget` events, debug `console.log` (replaced by an optional `log`
27
27
  callback), TCP host/port options, stats beyond connections/queued.
28
+ 10. **Injectable listener** (2026-10-21): an optional `createServer` option (default `node:net`'s) and
29
+ structural `SocketServerClient`/`SocketServerListener` types, so tests script a client socket's events
30
+ without module mocks. Behaviour with the default is unchanged.
@@ -35,15 +35,15 @@ export function outsideTransactionOf(kernel) {
35
35
  * @throws {StorageOpError} the ledger cannot be read, or holds no rows.
36
36
  */
37
37
  export async function verifyLedgerReadBack(kernel, ledgerTable) {
38
- let steps;
38
+ let anyStep;
39
39
  try {
40
- const [row] = await kernel.query(sql `SELECT count(*)::int AS n FROM ${sql.table(ledgerTable)}`);
41
- steps = row?.n ?? 0;
40
+ // One row when the ledger holds any step, none when it is empty: no count to null-check.
41
+ anyStep = await kernel.query(sql `SELECT 1 AS present FROM ${sql.table(ledgerTable)} LIMIT 1`);
42
42
  }
43
43
  catch (err) {
44
44
  throw new StorageOpError(`the migration ledger ${ledgerTable} cannot be read back: ${err.message}`);
45
45
  }
46
- if (steps === 0)
46
+ if (anyStep.length === 0)
47
47
  throw new StorageOpError(`the migration ledger ${ledgerTable} is empty after compacting`);
48
48
  }
49
49
  //# sourceMappingURL=ops.js.map
@@ -25,7 +25,7 @@ class PgliteConnection {
25
25
  ...(result.affectedRows !== undefined ? { numAffectedRows: BigInt(result.affectedRows) } : {}),
26
26
  };
27
27
  }
28
- // eslint-disable-next-line require-yield -- the interface requires a generator; PGlite has no cursor API here
28
+ // eslint-disable-next-line require-yield, sonarjs/generator-without-yield -- the interface requires a generator; PGlite has no cursor API here
29
29
  async *streamQuery() {
30
30
  throw new Error("streaming queries are not supported on PGlite");
31
31
  }
@@ -1,5 +1,5 @@
1
1
  import { sql } from "kysely";
2
- const squash = (text) => (text ?? "").replace(/\s+/g, " ").trim();
2
+ const squash = (text) => text.replace(/\s+/g, " ").trim();
3
3
  /** Every user table's shape (internal and `sqlite_`/`pg_` tables excluded), keyed by table name. */
4
4
  export async function readSchemaShape(kernel, optional = {}) {
5
5
  const exclude = new Set(optional.exclude ?? []);
@@ -9,7 +9,8 @@ export async function readSchemaShape(kernel, optional = {}) {
9
9
  return shape;
10
10
  }
11
11
  async function sqliteShape(kernel) {
12
- const objects = await kernel.query(sql `SELECT type, name, tbl_name, sql FROM sqlite_schema WHERE substr(name, 1, 7) <> 'sqlite_' ORDER BY type, name`);
12
+ // An auto-index (UNIQUE/PRIMARY KEY in the table text) has no SQL of its own: read it as ''.
13
+ const objects = await kernel.query(sql `SELECT type, name, tbl_name, coalesce(sql, '') AS sql FROM sqlite_schema WHERE substr(name, 1, 7) <> 'sqlite_' ORDER BY type, name`);
13
14
  const tables = {};
14
15
  const others = [];
15
16
  for (const object of objects) {
@@ -18,16 +19,7 @@ async function sqliteShape(kernel) {
18
19
  if (object.type !== "table")
19
20
  continue;
20
21
  const columns = await kernel.query(sql `SELECT name, type, "notnull", dflt_value, pk FROM pragma_table_info(${object.name}) ORDER BY cid`);
21
- const indexes = await kernel.query(sql `SELECT name, "unique", origin, partial FROM pragma_index_list(${object.name}) ORDER BY name`);
22
- const indexTexts = [];
23
- for (const index of indexes) {
24
- const cols = await kernel.query(sql `SELECT name FROM pragma_index_info(${index.name}) ORDER BY seqno`);
25
- const definition = objects.find((o) => o.type === "index" && o.name === index.name)?.sql;
26
- const where = index.partial ? ` WHERE ${squash(definition).replace(/^.*? WHERE /i, "")}` : "";
27
- // Auto-named indexes (UNIQUE/PRIMARY KEY in the table text) are identified by what they cover.
28
- const label = index.origin === "c" ? index.name : `(${index.origin})`;
29
- indexTexts.push(`${label} ${index.unique ? "UNIQUE " : ""}(${cols.map((c) => c.name).join(", ")})${where}`);
30
- }
22
+ const indexTexts = await sqliteIndexTexts({ kernel, tableName: object.name, objects });
31
23
  const fks = await kernel.query(sql `SELECT id, "table", "from", "to", on_update, on_delete FROM pragma_foreign_key_list(${object.name}) ORDER BY id, seq`);
32
24
  const byId = new Map();
33
25
  for (const fk of fks)
@@ -46,6 +38,21 @@ async function sqliteShape(kernel) {
46
38
  }
47
39
  return { tables, others: others.sort() };
48
40
  }
41
+ async function sqliteIndexTexts({ kernel, tableName, objects }, _optional = {}) {
42
+ const indexes = await kernel.query(sql `SELECT name, "unique", origin, partial FROM pragma_index_list(${tableName}) ORDER BY name`);
43
+ const indexTexts = [];
44
+ for (const index of indexes) {
45
+ const cols = await kernel.query(sql `SELECT name FROM pragma_index_info(${index.name}) ORDER BY seqno`);
46
+ // Only a CREATE INDEX can be partial, so a partial index always has its own sqlite_schema row.
47
+ const where = index.partial
48
+ ? ` WHERE ${squash(objects.find((o) => o.type === "index" && o.name === index.name).sql).replace(/^.*? WHERE /i, "")}`
49
+ : "";
50
+ // Auto-named indexes (UNIQUE/PRIMARY KEY in the table text) are identified by what they cover.
51
+ const label = index.origin === "c" ? index.name : `(${index.origin})`;
52
+ indexTexts.push(`${label} ${index.unique ? "UNIQUE " : ""}(${cols.map((c) => c.name).join(", ")})${where}`);
53
+ }
54
+ return indexTexts;
55
+ }
49
56
  async function postgresShape(kernel) {
50
57
  const columns = await kernel.query(sql `SELECT c.table_name, c.column_name, c.data_type, c.is_nullable, c.column_default
51
58
  FROM information_schema.columns c
@@ -6,8 +6,9 @@ import type { StorageKernel } from "./port.js";
6
6
  *
7
7
  * Same dialect on both sides, so nothing is translated: rows travel as each column's text form and
8
8
  * the target's own input functions read them back (jsonb, tsvector, bytea, arrays alike). Unlike the
9
- * SQLite transfer (`copy-engine.ts`) nothing is excluded: a move is the switch, so logins and sealed
10
- * credentials go too (still sealed with the same site key).
9
+ * SQLite transfer (`copy-engine.ts`) nothing is excluded by default: a move is the switch, so logins
10
+ * and sealed credentials go too (still sealed with the same site key). Hosts may exclude retained
11
+ * restore artifacts through the scope; those tables stay untouched on both sides.
11
12
  *
12
13
  * - Tables the migrations do not create (a plugin's `p_<id>__*` tables, `_plugin_*` bookkeeping) are
13
14
  * created on the target from the source's own catalog: columns, identity, constraints, indexes.
@@ -27,6 +28,11 @@ export interface StoreCopyScope {
27
28
  schema: string;
28
29
  name: string;
29
30
  }[];
31
+ /** True leaves a table out of the catalog, emptiness checks, copy, constraints and indexes. */
32
+ readonly excludeTable?: (required: {
33
+ schema: string;
34
+ name: string;
35
+ }, optional?: {}) => boolean;
30
36
  }
31
37
  /** The migration ledgers: compared, never copied. */
32
38
  /** Rows per source read / target insert (fewer for a wide table, to stay under the bind limit). */
@@ -15,7 +15,7 @@ const tableRef = (table) => sql.table(qualified(table));
15
15
  /** `"schema"."table"` as text, for functions that take a relation name (`pg_get_serial_sequence`). */
16
16
  const quotedName = (table) => [table.schema, table.name].map((part) => `"${part.replace(/"/g, '""')}"`).join(".");
17
17
  const isLedger = (table, scope) => scope.ledgers.some((l) => l.schema === table.schema && l.name === table.name);
18
- /** Every base table in the moved schemas, with columns and primary key, in a stable order. */
18
+ /** Every non-excluded base table in the moved schemas, with columns and primary key, in a stable order. */
19
19
  async function readCatalogInternal(kernel, scope) {
20
20
  const schemas = sql.join(scope.schemas.map((s) => sql.lit(s)));
21
21
  const columns = await kernel.query(sql `
@@ -56,17 +56,18 @@ async function readCatalogInternal(kernel, scope) {
56
56
  }
57
57
  for (const row of keys)
58
58
  tables.get(`${row.schema}.${row.table}`)?.primaryKey.push(row.column);
59
- return [...tables.values()];
59
+ return [...tables.values()].filter((table) => !scope.excludeTable?.(table));
60
60
  }
61
61
  async function readConstraints(kernel, scope) {
62
- return kernel.query(sql `
62
+ return (await kernel.query(sql `
63
63
  SELECT n.nspname AS schema, c.relname AS table, con.conname AS name, con.contype::text AS type,
64
64
  pg_get_constraintdef(con.oid) AS definition
65
65
  FROM pg_constraint con
66
66
  JOIN pg_class c ON c.oid = con.conrelid
67
67
  JOIN pg_namespace n ON n.oid = c.relnamespace
68
68
  WHERE n.nspname IN (${sql.join(scope.schemas.map((s) => sql.lit(s)))}) AND con.contype IN ('p', 'u', 'c', 'f', 'x')
69
- ORDER BY n.nspname, c.relname, con.conname`);
69
+ ORDER BY n.nspname, c.relname, con.conname`))
70
+ .filter((constraint) => !scope.excludeTable?.({ schema: constraint.schema, name: constraint.table }));
70
71
  }
71
72
  /** Indexes that are not a constraint's own (those come back with the constraint). */
72
73
  async function readIndexes(kernel, scope) {
@@ -107,8 +108,9 @@ async function assertLedgersAgreeInternal(source, target, scope) {
107
108
  }
108
109
  function columnDdl(column) {
109
110
  let ddl = sql `${sql.ref(column.name)} ${sql.raw(column.type)}`;
111
+ // Postgres stores every generated column's expression in pg_attrdef, so `expression` is set here.
110
112
  if (column.generated)
111
- return sql `${ddl} GENERATED ALWAYS AS (${sql.raw(column.expression ?? "NULL")}) STORED`;
113
+ return sql `${ddl} GENERATED ALWAYS AS (${sql.raw(column.expression)}) STORED`;
112
114
  if (column.identity !== "")
113
115
  ddl = sql `${ddl} GENERATED ${sql.raw(column.identity === "a" ? "ALWAYS" : "BY DEFAULT")} AS IDENTITY`;
114
116
  if (column.notNull)
@@ -157,6 +159,20 @@ async function fingerprint(kernel, table) {
157
159
  FROM (SELECT ${key} AS k FROM ${tableRef(table)}) keyed`);
158
160
  return `${row.n}:${row.sum}`;
159
161
  }
162
+ async function addConstraints({ target, constraints }, _optional = {}) {
163
+ for (const constraint of constraints) {
164
+ await target.execute(sql `ALTER TABLE ${tableRef({ schema: constraint.schema, name: constraint.table })} ADD CONSTRAINT ${sql.ref(constraint.name)} ${sql.raw(constraint.definition)}`);
165
+ }
166
+ }
167
+ async function advanceIdentityCounters({ target, tables }, _optional = {}) {
168
+ // Identity counters past the copied ids, or the first insert after the move collides.
169
+ for (const table of tables) {
170
+ for (const column of table.columns.filter((c) => c.identity !== "")) {
171
+ await target.execute(sql `SELECT setval(pg_get_serial_sequence(${quotedName(table)}, ${column.name}),
172
+ COALESCE((SELECT max(${sql.ref(column.name)}) FROM ${tableRef(table)}), 0) + 1, false)`);
173
+ }
174
+ }
175
+ }
160
176
  /**
161
177
  * Copies every table of `source` into `target` (see this file's header). Call it with both at head
162
178
  * and the target empty ({@link nonEmptyTables}); the ledgers are checked here first.
@@ -202,9 +218,7 @@ async function copyPgStoreInternal(source, target, scope, optional = {}) {
202
218
  await target.execute(sql `CREATE TABLE ${tableRef(table)} (${sql.join(table.columns.map(columnDdl))})`);
203
219
  }
204
220
  const createdConstraints = sourceConstraints.filter((c) => createdIds.has(`${c.schema}.${c.table}`));
205
- for (const constraint of createdConstraints.filter((c) => c.type !== "f")) {
206
- await target.execute(sql `ALTER TABLE ${tableRef({ schema: constraint.schema, name: constraint.table })} ADD CONSTRAINT ${sql.ref(constraint.name)} ${sql.raw(constraint.definition)}`);
207
- }
221
+ await addConstraints({ target, constraints: createdConstraints.filter((c) => c.type !== "f") });
208
222
  for (const index of sourceIndexes.filter((i) => createdIds.has(`${i.schema}.${i.table}`))) {
209
223
  await target.execute(sql.raw(index.definition));
210
224
  }
@@ -213,16 +227,8 @@ async function copyPgStoreInternal(source, target, scope, optional = {}) {
213
227
  const rows = await copyRows(source, target, table);
214
228
  report.push({ table: qualified(table), rows, created: createdIds.has(qualified(table)) });
215
229
  }
216
- for (const fk of [...foreignKeys, ...createdConstraints.filter((c) => c.type === "f")]) {
217
- await target.execute(sql `ALTER TABLE ${tableRef({ schema: fk.schema, name: fk.table })} ADD CONSTRAINT ${sql.ref(fk.name)} ${sql.raw(fk.definition)}`);
218
- }
219
- // Identity counters past the copied ids, or the first insert after the move collides.
220
- for (const table of sourceTables) {
221
- for (const column of table.columns.filter((c) => c.identity !== "")) {
222
- await target.execute(sql `SELECT setval(pg_get_serial_sequence(${quotedName(table)}, ${column.name}),
223
- COALESCE((SELECT max(${sql.ref(column.name)}) FROM ${tableRef(table)}), 0) + 1, false)`);
224
- }
225
- }
230
+ await addConstraints({ target, constraints: [...foreignKeys, ...createdConstraints.filter((c) => c.type === "f")] });
231
+ await advanceIdentityCounters({ target, tables: sourceTables });
226
232
  for (const table of sourceTables) {
227
233
  const [a, b] = [await fingerprint(source, table), await fingerprint(target, table)];
228
234
  if (a !== b)
@@ -39,6 +39,62 @@ export declare class PgliteOwnerLockedError extends Error {
39
39
  /** Undefined while the other starter's lock has no pid in it yet. */
40
40
  pid: number | undefined);
41
41
  }
42
+ /**
43
+ * The filesystem calls the owner makes on its lock file, socket dir and socket. Defaults to
44
+ * `node:fs`; a test passes a fake to reach the races and errno paths a real filesystem cannot be
45
+ * made to produce on demand (another starter renaming the lock mid-reap, EIO on a hard link).
46
+ */
47
+ export interface OwnerFsPort {
48
+ openSync(path: string, flags: "r"): number;
49
+ fstatSync(fd: number): {
50
+ ino: number;
51
+ mtimeMs: number;
52
+ };
53
+ readFileSync(fd: number, encoding: "utf8"): string;
54
+ closeSync(fd: number): void;
55
+ writeFileSync(path: string, data: string, options: {
56
+ flag: "wx";
57
+ mode: number;
58
+ }): void;
59
+ linkSync(existingPath: string, newPath: string): void;
60
+ rmSync(path: string, options: {
61
+ force: true;
62
+ }): void;
63
+ renameSync(oldPath: string, newPath: string): void;
64
+ mkdirSync(path: string, options: {
65
+ recursive?: boolean;
66
+ mode: number;
67
+ }): unknown;
68
+ rmdirSync(path: string): void;
69
+ statSync(path: string): {
70
+ ino: number;
71
+ mode: number;
72
+ };
73
+ lstatSync(path: string): {
74
+ isDirectory(): boolean;
75
+ isSymbolicLink(): boolean;
76
+ uid: number;
77
+ mode: number;
78
+ };
79
+ chmodSync(path: string, mode: number): void;
80
+ existsSync(path: string): boolean;
81
+ unlinkSync(path: string): void;
82
+ }
83
+ /** The process facts the owner reads: its own pid and uid, the home dir, the clock, and other pids' liveness. */
84
+ export interface OwnerProcessPort {
85
+ readonly pid: number;
86
+ /** Undefined where the platform has no uids (Windows). */
87
+ uid(): number | undefined;
88
+ homedir(): string;
89
+ nowMs(): number;
90
+ /** `process.kill(pid, 0)`: throws ESRCH for a dead pid, EPERM for another user's live one. */
91
+ kill(pid: number, signal: 0): void;
92
+ }
93
+ /** Optional ports for the owner's filesystem and process access; both default to Node's own. */
94
+ export interface OwnerPorts {
95
+ fs?: OwnerFsPort;
96
+ proc?: OwnerProcessPort;
97
+ }
42
98
  /**
43
99
  * The owner THIS process runs for `dataDir`, if any: how an in-process caller (duplicating the site
44
100
  * it serves) reaches {@link PgliteOwner.runExclusive} without a second open.
@@ -56,6 +112,7 @@ export declare function defaultPgliteSocketDir(required: {
56
112
  runDirName: string;
57
113
  }, optional?: {
58
114
  home?: string;
115
+ proc?: OwnerProcessPort;
59
116
  }): string;
60
117
  /** Throws unless `socketPath` fits in `sun_path`. */
61
118
  export declare function assertSocketPathFits(socketPath: string): void;
@@ -69,7 +126,7 @@ export declare function assertSocketPathFits(socketPath: string): void;
69
126
  */
70
127
  export declare function ensurePrivateDir(dir: string, optional?: {
71
128
  privateParent?: boolean;
72
- }): void;
129
+ } & OwnerPorts): void;
73
130
  /**
74
131
  * Takes the data dir's owner lock: created atomically with our pid in it. A lock whose pid is dead
75
132
  * (or that has had no pid for {@link EMPTY_LOCK_STALE_MS}) is taken over; a live one — including
@@ -80,7 +137,7 @@ export declare function ensurePrivateDir(dir: string, optional?: {
80
137
  export declare function acquireOwnerLock(required: {
81
138
  dataDir: string;
82
139
  lockFileName: string;
83
- }): () => void;
140
+ }, optional?: OwnerPorts): () => void;
84
141
  /**
85
142
  * Opens `dataDir` (creating it on first use — initdb takes several seconds) and serves it on a
86
143
  * private Unix socket.
@@ -91,6 +148,7 @@ export declare function acquireOwnerLock(required: {
91
148
  * @param required.runDirName names the default socket dir; see {@link defaultPgliteSocketDir}.
92
149
  * @param optional.socketDir default {@link defaultPgliteSocketDir}.
93
150
  * @param optional.idleInTransactionTimeoutMs default 30 s; see `PgliteSocketServer`.
151
+ * @param optional.fs / optional.proc see {@link OwnerPorts}; default Node's own.
94
152
  * @throws PgliteOwnerLockedError when another live owner holds `dataDir`.
95
153
  */
96
154
  export declare function startPgliteOwner(required: {
@@ -103,5 +161,5 @@ export declare function startPgliteOwner(required: {
103
161
  idleInTransactionTimeoutMs?: number;
104
162
  maxConnections?: number;
105
163
  log?: (message: string) => void;
106
- }): Promise<PgliteOwner>;
164
+ } & OwnerPorts): Promise<PgliteOwner>;
107
165
  //# sourceMappingURL=owner.d.ts.map