@noego/sqlego 0.0.0-stage → 0.0.1-dev.1

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/src/paths.ts ADDED
@@ -0,0 +1,154 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { mkdirSync, realpathSync, existsSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import path from 'node:path';
5
+ import { Result, Trust } from '@noego/trust';
6
+ import { errnoCode, errorMessage } from './protocol.ts';
7
+
8
+ /**
9
+ * Where a file's socket, lock, and meta live. Never beside the database:
10
+ * Unix socket paths cap at 104 bytes on macOS and application-support paths
11
+ * already exceed that. The runtime dir is short and per-user.
12
+ *
13
+ * Override with SQLEGO_RUNTIME_DIR (tests use a scratch dir).
14
+ */
15
+ export function resolveRuntimeDirectory() {
16
+ const configured = process.env.SQLEGO_RUNTIME_DIR;
17
+ const directory = configured && configured.length > 0 ? configured : path.join(tmpdir(), 'sqlego');
18
+ const created = Trust.try(
19
+ () => mkdirSync(directory, { recursive: true }),
20
+ (cause) => ({ kind: 'runtime-directory', message: `cannot create sqlego runtime directory ${directory}: ${errorMessage(cause)}` }),
21
+ );
22
+ if (!created.ok) return created;
23
+ return Result.ok(directory);
24
+ }
25
+
26
+ /** Canonical absolute path of the database; the identity every client and server agree on. */
27
+ export function resolveCanonicalFile(file: string) {
28
+ // path.resolve reads process.cwd() for a relative path, which throws when
29
+ // the working directory was removed; realpathSync is I/O.
30
+ return Trust.try(
31
+ () => {
32
+ const absolute = path.resolve(file);
33
+ // Resolve symlinks on the longest existing ancestor, then re-append the
34
+ // rest, so the identity is the same before and after the directory is
35
+ // created (macOS: /tmp and /var are symlinks into /private).
36
+ const missing: string[] = [];
37
+ let existing = absolute;
38
+ while (!existsSync(existing)) {
39
+ missing.unshift(path.basename(existing));
40
+ const parent = path.dirname(existing);
41
+ if (parent === existing) break;
42
+ existing = parent;
43
+ }
44
+ return path.join(realpathSync(existing), ...missing);
45
+ },
46
+ (cause) => ({ kind: 'canonical-path', message: `cannot resolve ${file}: ${errorMessage(cause)}` }),
47
+ );
48
+ }
49
+
50
+ export type FilePaths = Readonly<{
51
+ file: string;
52
+ key: string;
53
+ socket: string;
54
+ lock: string;
55
+ meta: string;
56
+ }>;
57
+
58
+ /** macOS caps `sun_path` at 104 bytes (Linux 108); leave headroom. */
59
+ const MAX_SOCKET_PATH_BYTES = 100;
60
+
61
+ export function resolvePaths(file: string) {
62
+ const canonical = resolveCanonicalFile(file);
63
+ if (!canonical.ok) return canonical;
64
+ const directory = resolveRuntimeDirectory();
65
+ if (!directory.ok) return directory;
66
+ const derived = Trust.try(
67
+ () => {
68
+ const key = createHash('sha1').update(canonical.value).digest('hex').slice(0, 16);
69
+ const socket = path.join(directory.value, `${key}.sock`);
70
+ return { key, socket, socketBytes: Buffer.byteLength(socket) };
71
+ },
72
+ (cause) => ({ kind: 'hash-failed', message: `cannot hash ${canonical.value}: ${errorMessage(cause)}` }),
73
+ );
74
+ if (!derived.ok) return derived;
75
+ const { key, socket, socketBytes } = derived.value;
76
+ if (socketBytes > MAX_SOCKET_PATH_BYTES) {
77
+ return Result.err({
78
+ kind: 'socket-path-too-long',
79
+ message: `sqlego runtime directory too deep for a Unix socket (${socketBytes} bytes > ${MAX_SOCKET_PATH_BYTES}): ${socket}. `
80
+ + 'Point SQLEGO_RUNTIME_DIR at a shorter path.',
81
+ });
82
+ }
83
+ const paths: FilePaths = Object.freeze({
84
+ file: canonical.value,
85
+ key,
86
+ socket,
87
+ lock: path.join(directory.value, `${key}.lock`),
88
+ meta: path.join(directory.value, `${key}.json`),
89
+ });
90
+ return Result.ok(paths);
91
+ }
92
+
93
+ /** Public, exception-based form of `resolveRuntimeDirectory`. */
94
+ export function runtimeDirectory(): string {
95
+ const directory = resolveRuntimeDirectory();
96
+ if (directory.ok) return directory.value;
97
+ //trust:accept public API contract: the exported path helpers throw an Error
98
+ throw new Error(directory.error.message);
99
+ }
100
+
101
+ /** Public, exception-based form of `resolveCanonicalFile`. */
102
+ export function canonicalFile(file: string): string {
103
+ const canonical = resolveCanonicalFile(file);
104
+ if (canonical.ok) return canonical.value;
105
+ //trust:accept public API contract: the exported path helpers throw an Error
106
+ throw new Error(canonical.error.message);
107
+ }
108
+
109
+ /** Public, exception-based form of `resolvePaths`. */
110
+ export function pathsFor(file: string): FilePaths {
111
+ const paths = resolvePaths(file);
112
+ if (paths.ok) return paths.value;
113
+ //trust:accept public API contract: the exported path helpers throw an Error
114
+ throw new Error(paths.error.message);
115
+ }
116
+
117
+ /** Written by the server once it is listening; read by `sqlego ls` and status. */
118
+ export type ServerMeta = Readonly<{
119
+ file: string;
120
+ socket: string;
121
+ pid: number;
122
+ serverVersion: string;
123
+ startedAt: number;
124
+ }>;
125
+
126
+ /** A meta file's parsed JSON; another process wrote it, so every field is checked. */
127
+ //trust:validator_function
128
+ export function parseServerMeta(input: unknown) {
129
+ const fields = typeof input === 'object' && input !== null && !Array.isArray(input) ? (input as Readonly<Record<string, unknown>>) : null;
130
+ if (
131
+ !fields
132
+ || typeof fields.file !== 'string' || typeof fields.socket !== 'string' || typeof fields.pid !== 'number'
133
+ || typeof fields.serverVersion !== 'string' || typeof fields.startedAt !== 'number'
134
+ ) {
135
+ return Result.err({ kind: 'invalid' as const, message: 'server meta needs file, socket, pid, serverVersion and startedAt' });
136
+ }
137
+ const meta: ServerMeta = {
138
+ file: fields.file, socket: fields.socket, pid: fields.pid, serverVersion: fields.serverVersion, startedAt: fields.startedAt,
139
+ };
140
+ return Result.ok(meta);
141
+ }
142
+
143
+ /** Signal 0 probes without signalling: EPERM means alive but not ours, anything else means gone. */
144
+ export function isProcessAlive(pid: number): boolean {
145
+ const probe = Trust.try(
146
+ () => process.kill(pid, 0),
147
+ (cause) => (errnoCode(cause) === 'EPERM' ? { kind: 'not-permitted' as const } : { kind: 'no-such-process' as const }),
148
+ );
149
+ if (probe.ok) return true;
150
+ if (probe.error.kind === 'not-permitted') return true;
151
+ if (probe.error.kind === 'no-such-process') return false;
152
+ const unhandled: never = probe.error;
153
+ return unhandled;
154
+ }
@@ -0,0 +1,477 @@
1
+ /**
2
+ * sqlego wire protocol: newline-delimited JSON over a local socket.
3
+ *
4
+ * One request per line, one response per line, correlated by `id`. The server
5
+ * executes requests in arrival order on its single connection to the file, so
6
+ * two clients' statements interleave at statement (or batch) granularity and
7
+ * never contend for SQLite's write lock.
8
+ *
9
+ * Transactions over the wire are leased, never bare: `begin` opens one bound
10
+ * to the client's socket, `query`/`run` carry its `txId`, and `commit` or
11
+ * `rollback` ends it. The server rolls it back on its own when the socket
12
+ * closes, when no request arrives within the lease, or when it has been open
13
+ * longer than the server's hard cap, so a client can never hold the file's
14
+ * only writer hostage. Transaction-control SQL (`BEGIN`, `COMMIT`, ...) is
15
+ * refused as plain `query`/`run`; savepoints are allowed inside a transaction.
16
+ */
17
+
18
+ import { Result, Trust } from '@noego/trust';
19
+
20
+ export const PROTOCOL_VERSION = 2;
21
+
22
+ export type SqlParams = ReadonlyArray<SqlValue> | Readonly<Record<string, SqlValue>>;
23
+ export type SqlValue = string | number | bigint | boolean | null | Uint8Array;
24
+ export type SqlRow = Record<string, unknown>;
25
+
26
+ export type Statement = Readonly<{
27
+ sql: string;
28
+ params?: SqlParams;
29
+ /** `query` returns rows; `run` returns the change count. Default `run`. */
30
+ mode?: 'query' | 'run';
31
+ }>;
32
+
33
+ export type TransactionMode = 'deferred' | 'immediate';
34
+
35
+ export type Request =
36
+ | { id: number; op: 'hello'; clientVersion: string; protocol: number }
37
+ | { id: number; op: 'query'; sql: string; params?: SqlParams; txId?: number }
38
+ | { id: number; op: 'run'; sql: string; params?: SqlParams; txId?: number }
39
+ | { id: number; op: 'batch'; statements: readonly Statement[] }
40
+ | { id: number; op: 'begin'; mode?: TransactionMode; leaseMs?: number }
41
+ | { id: number; op: 'commit'; txId: number }
42
+ | { id: number; op: 'rollback'; txId: number }
43
+ | { id: number; op: 'status' }
44
+ | { id: number; op: 'stop' };
45
+
46
+ export type RunResult = Readonly<{ changes: number; lastInsertRowid: number | bigint }>;
47
+ export type QueryResult = Readonly<{ rows: SqlRow[] }>;
48
+ export type BatchResult = Readonly<{ results: ReadonlyArray<RunResult | QueryResult> }>;
49
+ /** The lease the server granted (its own cap applies) and the hard cap on the transaction's life. */
50
+ export type BeginResult = Readonly<{ txId: number; leaseMs: number; maxDurationMs: number }>;
51
+ export type TransactionEndResult = Readonly<{ txId: number }>;
52
+
53
+ /** The open transaction as `status` reports it. */
54
+ export type TransactionStatus = Readonly<{
55
+ txId: number;
56
+ /** How long it has been open. */
57
+ ageMs: number;
58
+ /** Since its last request. */
59
+ idleMs: number;
60
+ leaseMs: number;
61
+ maxDurationMs: number;
62
+ /** Requests from other clients waiting for it to end. */
63
+ queued: number;
64
+ }>;
65
+
66
+ export type HelloResult = Readonly<{
67
+ serverVersion: string;
68
+ protocol: number;
69
+ file: string;
70
+ pid: number;
71
+ }>;
72
+
73
+ export type StatusResult = Readonly<{
74
+ file: string;
75
+ socket: string;
76
+ pid: number;
77
+ serverVersion: string;
78
+ protocol: number;
79
+ clients: number;
80
+ uptimeMs: number;
81
+ idleMs: number | null;
82
+ idleTimeoutMs: number;
83
+ requestsServed: number;
84
+ transaction: TransactionStatus | null;
85
+ }>;
86
+
87
+ export type ErrorCode =
88
+ | 'sqlite'
89
+ | 'bad-request'
90
+ | 'protocol-mismatch'
91
+ | 'shutting-down'
92
+ /** The server could not serialize a result (a value JSON cannot hold). */
93
+ | 'encode-failed'
94
+ /** The transaction was rolled back by the server: lease ran out, hard cap hit, or SQLite aborted it. */
95
+ | 'tx-expired'
96
+ /** No such open transaction on this connection (wrong id, already ended, or a second `begin`). */
97
+ | 'tx-invalid'
98
+ /** Another client's transaction kept the request waiting past the server's queue limit. */
99
+ | 'tx-busy';
100
+
101
+ export type Response =
102
+ | { id: number; ok: true; result: unknown }
103
+ | { id: number; ok: false; error: { code: ErrorCode; message: string } };
104
+
105
+ /**
106
+ * JSON text of a value. `JSON.stringify` is declared `string` but returns
107
+ * `undefined` for `undefined`, a function or a symbol, and throws on a cycle
108
+ * or a `toJSON` that throws; both are this one failure.
109
+ */
110
+ export function toJson(value: unknown, indent?: number) {
111
+ const encoded = Trust.try(
112
+ (): unknown => JSON.stringify(value, replaceBigInt, indent),
113
+ (cause) => ({ kind: 'encode-failed' as const, message: errorMessage(cause) }),
114
+ );
115
+ if (!encoded.ok) return encoded;
116
+ if (typeof encoded.value !== 'string') return Result.err({ kind: 'encode-failed', message: `${typeof value} has no JSON form` });
117
+ return Result.ok(encoded.value);
118
+ }
119
+
120
+ /** One frame: the message's JSON and the newline that ends it. */
121
+ export function encodeFrame(message: Request | Response) {
122
+ const json = toJson(message);
123
+ if (!json.ok) return json;
124
+ return Result.ok(`${json.value}\n`);
125
+ }
126
+
127
+ /** Parses JSON text into `unknown`; what it holds is for a validator to decide. */
128
+ export function fromJson(text: string) {
129
+ return Trust.try(
130
+ (): unknown => JSON.parse(text),
131
+ (cause) => ({ kind: 'invalid' as const, message: `not JSON: ${errorMessage(cause)}` }),
132
+ );
133
+ }
134
+
135
+ /* ------------------------------------------------------------------------ *
136
+ * Validators. Everything that crosses a process boundary (a frame, a file,
137
+ * a command-line argument) arrives as `unknown` and becomes typed only here.
138
+ * Each returns Err<{ kind: 'invalid' }> naming the first thing that is wrong;
139
+ * callers translate that into their own failure (bad-request, protocol, ...).
140
+ * ------------------------------------------------------------------------ */
141
+
142
+ type Fields = Readonly<Record<string, unknown>>;
143
+ type Invalid = Readonly<{ kind: 'invalid'; message: string }>;
144
+
145
+ const invalid = (message: string) => Result.err<Invalid>({ kind: 'invalid', message });
146
+
147
+ /** The own fields of a plain JSON object, each still `unknown`; null for anything else. */
148
+ //trust:validator_function
149
+ function fieldsOf(input: unknown): Fields | null {
150
+ return typeof input === 'object' && input !== null && !Array.isArray(input) ? (input as Fields) : null;
151
+ }
152
+
153
+ /** A value that survives JSON and SQLite binding: string, number, boolean or null. */
154
+ //trust:validator_function
155
+ export function parseSqlValue(input: unknown) {
156
+ if (input === null || typeof input === 'string' || typeof input === 'number' || typeof input === 'boolean') {
157
+ return Result.ok<SqlValue>(input);
158
+ }
159
+ return invalid(`a SQL value must be a string, number, boolean or null, not ${Array.isArray(input) ? 'an array' : typeof input}`);
160
+ }
161
+
162
+ /** Positional (`[...]`) or named (`{ name: value }`) parameters. */
163
+ //trust:validator_function
164
+ export function parseSqlParams(input: unknown) {
165
+ if (Array.isArray(input)) {
166
+ const values: SqlValue[] = [];
167
+ for (const [index, item] of input.entries()) {
168
+ const value = parseSqlValue(item);
169
+ if (!value.ok) return invalid(`params[${index}]: ${value.error.message}`);
170
+ values.push(value.value);
171
+ }
172
+ return Result.ok<SqlParams>(values);
173
+ }
174
+ const fields = fieldsOf(input);
175
+ if (!fields) return invalid('params must be an array or an object');
176
+ const named: Record<string, SqlValue> = {};
177
+ for (const [name, item] of Object.entries(fields)) {
178
+ const value = parseSqlValue(item);
179
+ if (!value.ok) return invalid(`params.${name}: ${value.error.message}`);
180
+ named[name] = value.value;
181
+ }
182
+ return Result.ok<SqlParams>(named);
183
+ }
184
+
185
+ /** `params` when present; absent (`undefined`) is allowed. */
186
+ //trust:validator_function
187
+ function parseOptionalParams(input: unknown) {
188
+ if (input === undefined) return Result.ok<SqlParams | undefined>(undefined);
189
+ return parseSqlParams(input);
190
+ }
191
+
192
+ //trust:validator_function
193
+ function parseStatement(input: unknown, at: string) {
194
+ const fields = fieldsOf(input);
195
+ if (!fields) return invalid(`${at} must be an object`);
196
+ if (typeof fields.sql !== 'string') return invalid(`${at}.sql must be a string`);
197
+ const mode = fields.mode;
198
+ if (mode !== undefined && mode !== 'query' && mode !== 'run') return invalid(`${at}.mode must be "query" or "run"`);
199
+ const params = parseOptionalParams(fields.params);
200
+ if (!params.ok) return invalid(`${at}.${params.error.message}`);
201
+ const statement: Statement = { sql: fields.sql, params: params.value, mode };
202
+ return Result.ok(statement);
203
+ }
204
+
205
+ /**
206
+ * A request frame. The failure carries the request's `id` when it had a
207
+ * numeric one, so the server can answer the request that was malformed.
208
+ */
209
+ //trust:validator_function
210
+ export function parseRequest(input: unknown) {
211
+ const reject = (id: number, message: string) => Result.err({ kind: 'invalid' as const, id, message });
212
+ const fields = fieldsOf(input);
213
+ if (!fields) return reject(-1, 'a request must be a JSON object');
214
+ const id = fields.id;
215
+ if (typeof id !== 'number') return reject(-1, 'a request needs a numeric id');
216
+ switch (fields.op) {
217
+ case 'hello': {
218
+ if (typeof fields.clientVersion !== 'string' || typeof fields.protocol !== 'number') {
219
+ return reject(id, 'hello needs clientVersion (string) and protocol (number)');
220
+ }
221
+ const request: Request = { id, op: 'hello', clientVersion: fields.clientVersion, protocol: fields.protocol };
222
+ return Result.ok(request);
223
+ }
224
+ case 'query':
225
+ case 'run': {
226
+ if (typeof fields.sql !== 'string') return reject(id, `${fields.op} needs sql (string)`);
227
+ const params = parseOptionalParams(fields.params);
228
+ if (!params.ok) return reject(id, params.error.message);
229
+ const txId = fields.txId;
230
+ if (txId !== undefined && typeof txId !== 'number') return reject(id, 'txId must be a number');
231
+ const request: Request = { id, op: fields.op, sql: fields.sql, params: params.value, txId };
232
+ return Result.ok(request);
233
+ }
234
+ case 'begin': {
235
+ const mode = fields.mode;
236
+ if (mode !== undefined && mode !== 'deferred' && mode !== 'immediate') return reject(id, 'begin mode must be "deferred" or "immediate"');
237
+ const leaseMs = fields.leaseMs;
238
+ if (leaseMs !== undefined && (typeof leaseMs !== 'number' || !(leaseMs > 0))) return reject(id, 'leaseMs must be a positive number');
239
+ const request: Request = { id, op: 'begin', mode, leaseMs };
240
+ return Result.ok(request);
241
+ }
242
+ case 'commit':
243
+ case 'rollback': {
244
+ if (typeof fields.txId !== 'number') return reject(id, `${fields.op} needs txId (number)`);
245
+ const request: Request = { id, op: fields.op, txId: fields.txId };
246
+ return Result.ok(request);
247
+ }
248
+ case 'batch': {
249
+ if (!Array.isArray(fields.statements)) return reject(id, 'batch needs a statements array');
250
+ const statements: Statement[] = [];
251
+ for (const [index, item] of fields.statements.entries()) {
252
+ const statement = parseStatement(item, `statements[${index}]`);
253
+ if (!statement.ok) return reject(id, statement.error.message);
254
+ statements.push(statement.value);
255
+ }
256
+ const request: Request = { id, op: 'batch', statements };
257
+ return Result.ok(request);
258
+ }
259
+ case 'status':
260
+ case 'stop': {
261
+ const request: Request = { id, op: fields.op };
262
+ return Result.ok(request);
263
+ }
264
+ default:
265
+ return reject(id, `unknown op ${String(fields.op)}`);
266
+ }
267
+ }
268
+
269
+ const ERROR_CODES: readonly ErrorCode[] = [
270
+ 'sqlite', 'bad-request', 'protocol-mismatch', 'shutting-down', 'encode-failed', 'tx-expired', 'tx-invalid', 'tx-busy',
271
+ ];
272
+
273
+ //trust:validator_function
274
+ function parseErrorCode(input: unknown) {
275
+ const code = ERROR_CODES.find((known) => known === input);
276
+ return code === undefined ? invalid(`unknown error code ${String(input)}`) : Result.ok(code);
277
+ }
278
+
279
+ /** A response frame; `result` stays `unknown` until the parser for its op has seen it. */
280
+ //trust:validator_function
281
+ export function parseResponse(input: unknown) {
282
+ const fields = fieldsOf(input);
283
+ if (!fields) return invalid('a response must be a JSON object');
284
+ const id = fields.id;
285
+ if (typeof id !== 'number') return invalid('a response needs a numeric id');
286
+ if (fields.ok === true) {
287
+ const response: Response = { id, ok: true, result: fields.result };
288
+ return Result.ok(response);
289
+ }
290
+ if (fields.ok !== false) return invalid('a response needs ok: true or false');
291
+ const error = fieldsOf(fields.error);
292
+ if (!error || typeof error.message !== 'string') return invalid('a failed response needs error.code and error.message');
293
+ const code = parseErrorCode(error.code);
294
+ if (!code.ok) return code;
295
+ const response: Response = { id, ok: false, error: { code: code.value, message: error.message } };
296
+ return Result.ok(response);
297
+ }
298
+
299
+ //trust:validator_function
300
+ export function parseRow(input: unknown) {
301
+ const fields = fieldsOf(input);
302
+ if (!fields) return invalid('a row must be an object');
303
+ const row: SqlRow = { ...fields };
304
+ return Result.ok(row);
305
+ }
306
+
307
+ //trust:validator_function
308
+ export function parseRows(input: unknown) {
309
+ if (!Array.isArray(input)) return invalid('rows must be an array');
310
+ const rows: SqlRow[] = [];
311
+ for (const [index, item] of input.entries()) {
312
+ const row = parseRow(item);
313
+ if (!row.ok) return invalid(`rows[${index}]: ${row.error.message}`);
314
+ rows.push(row.value);
315
+ }
316
+ return Result.ok(rows);
317
+ }
318
+
319
+ //trust:validator_function
320
+ export function parseQueryResult(input: unknown) {
321
+ const fields = fieldsOf(input);
322
+ if (!fields) return invalid('a query result must be an object');
323
+ const rows = parseRows(fields.rows);
324
+ if (!rows.ok) return rows;
325
+ const result: QueryResult = { rows: rows.value };
326
+ return Result.ok(result);
327
+ }
328
+
329
+ //trust:validator_function
330
+ export function parseRunResult(input: unknown) {
331
+ const fields = fieldsOf(input);
332
+ if (!fields || typeof fields.changes !== 'number') return invalid('a run result needs changes (number)');
333
+ const rowid = fields.lastInsertRowid;
334
+ if (typeof rowid !== 'number' && typeof rowid !== 'bigint') return invalid('a run result needs lastInsertRowid (number)');
335
+ const result: RunResult = { changes: fields.changes, lastInsertRowid: rowid };
336
+ return Result.ok(result);
337
+ }
338
+
339
+ //trust:validator_function
340
+ export function parseBatchResult(input: unknown) {
341
+ const fields = fieldsOf(input);
342
+ if (!fields || !Array.isArray(fields.results)) return invalid('a batch result needs a results array');
343
+ const results: Array<RunResult | QueryResult> = [];
344
+ for (const [index, item] of fields.results.entries()) {
345
+ const shaped = fieldsOf(item);
346
+ const parsed = shaped && 'rows' in shaped ? parseQueryResult(item) : parseRunResult(item);
347
+ if (!parsed.ok) return invalid(`results[${index}]: ${parsed.error.message}`);
348
+ results.push(parsed.value);
349
+ }
350
+ const result: BatchResult = { results };
351
+ return Result.ok(result);
352
+ }
353
+
354
+ //trust:validator_function
355
+ export function parseHelloResult(input: unknown) {
356
+ const fields = fieldsOf(input);
357
+ if (
358
+ !fields
359
+ || typeof fields.serverVersion !== 'string' || typeof fields.protocol !== 'number'
360
+ || typeof fields.file !== 'string' || typeof fields.pid !== 'number'
361
+ ) {
362
+ return invalid('a hello result needs serverVersion, protocol, file and pid');
363
+ }
364
+ const result: HelloResult = { serverVersion: fields.serverVersion, protocol: fields.protocol, file: fields.file, pid: fields.pid };
365
+ return Result.ok(result);
366
+ }
367
+
368
+ //trust:validator_function
369
+ export function parseBeginResult(input: unknown) {
370
+ const f = fieldsOf(input);
371
+ if (!f || typeof f.txId !== 'number' || typeof f.leaseMs !== 'number' || typeof f.maxDurationMs !== 'number') {
372
+ return invalid('a begin result needs txId, leaseMs and maxDurationMs (numbers)');
373
+ }
374
+ const result: BeginResult = { txId: f.txId, leaseMs: f.leaseMs, maxDurationMs: f.maxDurationMs };
375
+ return Result.ok(result);
376
+ }
377
+
378
+ //trust:validator_function
379
+ export function parseTransactionEndResult(input: unknown) {
380
+ const f = fieldsOf(input);
381
+ if (!f || typeof f.txId !== 'number') return invalid('a commit/rollback result needs txId (number)');
382
+ const result: TransactionEndResult = { txId: f.txId };
383
+ return Result.ok(result);
384
+ }
385
+
386
+ //trust:validator_function
387
+ function parseTransactionStatus(input: unknown) {
388
+ if (input === null) return Result.ok<TransactionStatus | null>(null);
389
+ const f = fieldsOf(input);
390
+ if (
391
+ !f || typeof f.txId !== 'number' || typeof f.ageMs !== 'number' || typeof f.idleMs !== 'number'
392
+ || typeof f.leaseMs !== 'number' || typeof f.maxDurationMs !== 'number' || typeof f.queued !== 'number'
393
+ ) {
394
+ return invalid('status.transaction must be null or carry txId, ageMs, idleMs, leaseMs, maxDurationMs and queued');
395
+ }
396
+ const status: TransactionStatus = {
397
+ txId: f.txId, ageMs: f.ageMs, idleMs: f.idleMs, leaseMs: f.leaseMs, maxDurationMs: f.maxDurationMs, queued: f.queued,
398
+ };
399
+ return Result.ok<TransactionStatus | null>(status);
400
+ }
401
+
402
+ //trust:validator_function
403
+ export function parseStatusResult(input: unknown) {
404
+ const f = fieldsOf(input);
405
+ if (
406
+ !f
407
+ || typeof f.file !== 'string' || typeof f.socket !== 'string' || typeof f.pid !== 'number'
408
+ || typeof f.serverVersion !== 'string' || typeof f.protocol !== 'number' || typeof f.clients !== 'number'
409
+ || typeof f.uptimeMs !== 'number' || (f.idleMs !== null && typeof f.idleMs !== 'number')
410
+ || typeof f.idleTimeoutMs !== 'number' || typeof f.requestsServed !== 'number'
411
+ ) {
412
+ return invalid('a status result is missing a field or has one of the wrong type');
413
+ }
414
+ const transaction = parseTransactionStatus(f.transaction);
415
+ if (!transaction.ok) return transaction;
416
+ const result: StatusResult = {
417
+ file: f.file, socket: f.socket, pid: f.pid, serverVersion: f.serverVersion, protocol: f.protocol,
418
+ clients: f.clients, uptimeMs: f.uptimeMs, idleMs: f.idleMs, idleTimeoutMs: f.idleTimeoutMs, requestsServed: f.requestsServed,
419
+ transaction: transaction.value,
420
+ };
421
+ return Result.ok(result);
422
+ }
423
+
424
+ /**
425
+ * The transaction-control statement a SQL text starts with, or null. Leading
426
+ * whitespace and comments are skipped so `/* x *\/ BEGIN` is still seen.
427
+ * `ROLLBACK TO` (a savepoint) is told apart from a bare `ROLLBACK`.
428
+ */
429
+ export function transactionControl(sql: string): 'begin' | 'commit' | 'rollback' | 'savepoint' | 'release' | 'rollback-to' | null {
430
+ const body = sql.replace(/^(?:\s+|--[^\n]*\n?|\/\*[\s\S]*?\*\/)+/, '');
431
+ const match = /^(BEGIN|START|COMMIT|END|ROLLBACK|SAVEPOINT|RELEASE)\b(\s+TRANSACTION\b)?(\s+TO\b)?/i.exec(body);
432
+ if (!match) return null;
433
+ switch (match[1].toUpperCase()) {
434
+ case 'BEGIN':
435
+ case 'START': return 'begin';
436
+ case 'COMMIT':
437
+ case 'END': return 'commit';
438
+ case 'ROLLBACK': return match[3] ? 'rollback-to' : 'rollback';
439
+ case 'SAVEPOINT': return 'savepoint';
440
+ default: return 'release';
441
+ }
442
+ }
443
+
444
+ //trust:validator_function
445
+ export function parseStopResult(input: unknown) {
446
+ const fields = fieldsOf(input);
447
+ if (!fields || fields.stopping !== true) return invalid('a stop result needs stopping: true');
448
+ return Result.ok({ stopping: true as const });
449
+ }
450
+
451
+ /**
452
+ * The `code` of a thrown Node error (`EEXIST`, `EPERM`, ...), or undefined.
453
+ * Read through `in` on `unknown`, so nothing about the error is assumed.
454
+ */
455
+ export function errnoCode(cause: unknown): unknown {
456
+ if (typeof cause === 'object' && cause !== null && 'code' in cause) return cause.code;
457
+ return undefined;
458
+ }
459
+
460
+ /** The message of a caught value, whatever was thrown. */
461
+ export function errorMessage(cause: unknown): string {
462
+ return cause instanceof Error ? cause.message : String(cause);
463
+ }
464
+
465
+ /**
466
+ * Splits accumulated socket bytes into complete frames; returns the frames
467
+ * and the unterminated remainder to carry into the next chunk.
468
+ */
469
+ export function splitFrames(buffer: string): { frames: string[]; rest: string } {
470
+ const lines = buffer.split('\n');
471
+ const rest = lines.pop() ?? '';
472
+ return { frames: lines.filter((line) => line.length > 0), rest };
473
+ }
474
+
475
+ function replaceBigInt(_key: string, value: unknown): unknown {
476
+ return typeof value === 'bigint' ? Number(value) : value;
477
+ }