@noego/sqlego 0.0.0-stage → 0.0.1-dev.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/index.js ADDED
@@ -0,0 +1,751 @@
1
+ // src/client.ts
2
+ import { spawn } from "node:child_process";
3
+ import { closeSync, openSync, readFileSync as readFileSync2, rmSync, writeSync, existsSync as existsSync3 } from "node:fs";
4
+ import net from "node:net";
5
+ import path3 from "node:path";
6
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
7
+
8
+ // node_modules/@noego/trust/dist/index.js
9
+ function ok(value) {
10
+ return { ok: true, value };
11
+ }
12
+ function err(error) {
13
+ return { ok: false, error };
14
+ }
15
+ function tryResult(fn, onError) {
16
+ try {
17
+ return ok(fn());
18
+ } catch (cause) {
19
+ return err(onError(cause));
20
+ }
21
+ }
22
+ async function tryResultAsync(fn, onError) {
23
+ try {
24
+ return ok(await fn());
25
+ } catch (cause) {
26
+ return err(onError(cause));
27
+ }
28
+ }
29
+ function pick(table, kind) {
30
+ if (typeof kind !== "string" || !Object.prototype.hasOwnProperty.call(table, kind))
31
+ return;
32
+ return table[kind];
33
+ }
34
+ function decide(result, handlers) {
35
+ if (result.ok)
36
+ return result;
37
+ const handler = pick(handlers, result.error?.kind);
38
+ return handler === undefined ? result : ok(handler(result.error));
39
+ }
40
+ function translate(result, mappers) {
41
+ if (result.ok)
42
+ return result;
43
+ const mapper = pick(mappers, result.error?.kind);
44
+ return mapper === undefined ? result : err(mapper(result.error));
45
+ }
46
+ var Result = { ok, err };
47
+ var Trust = { try: tryResult, tryAsync: tryResultAsync, decide, translate };
48
+
49
+ // src/protocol.ts
50
+ var PROTOCOL_VERSION = 1;
51
+ function toJson(value, indent) {
52
+ const encoded = Trust.try(() => JSON.stringify(value, replaceBigInt, indent), (cause) => ({ kind: "encode-failed", message: errorMessage(cause) }));
53
+ if (!encoded.ok)
54
+ return encoded;
55
+ if (typeof encoded.value !== "string")
56
+ return Result.err({ kind: "encode-failed", message: `${typeof value} has no JSON form` });
57
+ return Result.ok(encoded.value);
58
+ }
59
+ function encodeFrame(message) {
60
+ const json = toJson(message);
61
+ if (!json.ok)
62
+ return json;
63
+ return Result.ok(`${json.value}
64
+ `);
65
+ }
66
+ function fromJson(text) {
67
+ return Trust.try(() => JSON.parse(text), (cause) => ({ kind: "invalid", message: `not JSON: ${errorMessage(cause)}` }));
68
+ }
69
+ var invalid = (message) => Result.err({ kind: "invalid", message });
70
+ function fieldsOf(input) {
71
+ return typeof input === "object" && input !== null && !Array.isArray(input) ? input : null;
72
+ }
73
+ var ERROR_CODES = ["sqlite", "bad-request", "protocol-mismatch", "shutting-down", "encode-failed"];
74
+ function parseErrorCode(input) {
75
+ const code = ERROR_CODES.find((known) => known === input);
76
+ return code === undefined ? invalid(`unknown error code ${String(input)}`) : Result.ok(code);
77
+ }
78
+ function parseResponse(input) {
79
+ const fields = fieldsOf(input);
80
+ if (!fields)
81
+ return invalid("a response must be a JSON object");
82
+ const id = fields.id;
83
+ if (typeof id !== "number")
84
+ return invalid("a response needs a numeric id");
85
+ if (fields.ok === true) {
86
+ const response = { id, ok: true, result: fields.result };
87
+ return Result.ok(response);
88
+ }
89
+ if (fields.ok !== false)
90
+ return invalid("a response needs ok: true or false");
91
+ const error = fieldsOf(fields.error);
92
+ if (!error || typeof error.message !== "string")
93
+ return invalid("a failed response needs error.code and error.message");
94
+ const code = parseErrorCode(error.code);
95
+ if (!code.ok)
96
+ return code;
97
+ const response = { id, ok: false, error: { code: code.value, message: error.message } };
98
+ return Result.ok(response);
99
+ }
100
+ function parseRow(input) {
101
+ const fields = fieldsOf(input);
102
+ if (!fields)
103
+ return invalid("a row must be an object");
104
+ const row = { ...fields };
105
+ return Result.ok(row);
106
+ }
107
+ function parseRows(input) {
108
+ if (!Array.isArray(input))
109
+ return invalid("rows must be an array");
110
+ const rows = [];
111
+ for (const [index, item] of input.entries()) {
112
+ const row = parseRow(item);
113
+ if (!row.ok)
114
+ return invalid(`rows[${index}]: ${row.error.message}`);
115
+ rows.push(row.value);
116
+ }
117
+ return Result.ok(rows);
118
+ }
119
+ function parseQueryResult(input) {
120
+ const fields = fieldsOf(input);
121
+ if (!fields)
122
+ return invalid("a query result must be an object");
123
+ const rows = parseRows(fields.rows);
124
+ if (!rows.ok)
125
+ return rows;
126
+ const result = { rows: rows.value };
127
+ return Result.ok(result);
128
+ }
129
+ function parseRunResult(input) {
130
+ const fields = fieldsOf(input);
131
+ if (!fields || typeof fields.changes !== "number")
132
+ return invalid("a run result needs changes (number)");
133
+ const rowid = fields.lastInsertRowid;
134
+ if (typeof rowid !== "number" && typeof rowid !== "bigint")
135
+ return invalid("a run result needs lastInsertRowid (number)");
136
+ const result = { changes: fields.changes, lastInsertRowid: rowid };
137
+ return Result.ok(result);
138
+ }
139
+ function parseBatchResult(input) {
140
+ const fields = fieldsOf(input);
141
+ if (!fields || !Array.isArray(fields.results))
142
+ return invalid("a batch result needs a results array");
143
+ const results = [];
144
+ for (const [index, item] of fields.results.entries()) {
145
+ const shaped = fieldsOf(item);
146
+ const parsed = shaped && "rows" in shaped ? parseQueryResult(item) : parseRunResult(item);
147
+ if (!parsed.ok)
148
+ return invalid(`results[${index}]: ${parsed.error.message}`);
149
+ results.push(parsed.value);
150
+ }
151
+ const result = { results };
152
+ return Result.ok(result);
153
+ }
154
+ function parseHelloResult(input) {
155
+ const fields = fieldsOf(input);
156
+ if (!fields || typeof fields.serverVersion !== "string" || typeof fields.protocol !== "number" || typeof fields.file !== "string" || typeof fields.pid !== "number") {
157
+ return invalid("a hello result needs serverVersion, protocol, file and pid");
158
+ }
159
+ const result = { serverVersion: fields.serverVersion, protocol: fields.protocol, file: fields.file, pid: fields.pid };
160
+ return Result.ok(result);
161
+ }
162
+ function parseStatusResult(input) {
163
+ const f = fieldsOf(input);
164
+ if (!f || typeof f.file !== "string" || typeof f.socket !== "string" || typeof f.pid !== "number" || typeof f.serverVersion !== "string" || typeof f.protocol !== "number" || typeof f.clients !== "number" || typeof f.uptimeMs !== "number" || f.idleMs !== null && typeof f.idleMs !== "number" || typeof f.idleTimeoutMs !== "number" || typeof f.requestsServed !== "number") {
165
+ return invalid("a status result is missing a field or has one of the wrong type");
166
+ }
167
+ const result = {
168
+ file: f.file,
169
+ socket: f.socket,
170
+ pid: f.pid,
171
+ serverVersion: f.serverVersion,
172
+ protocol: f.protocol,
173
+ clients: f.clients,
174
+ uptimeMs: f.uptimeMs,
175
+ idleMs: f.idleMs,
176
+ idleTimeoutMs: f.idleTimeoutMs,
177
+ requestsServed: f.requestsServed
178
+ };
179
+ return Result.ok(result);
180
+ }
181
+ function parseStopResult(input) {
182
+ const fields = fieldsOf(input);
183
+ if (!fields || fields.stopping !== true)
184
+ return invalid("a stop result needs stopping: true");
185
+ return Result.ok({ stopping: true });
186
+ }
187
+ function errnoCode(cause) {
188
+ if (typeof cause === "object" && cause !== null && "code" in cause)
189
+ return cause.code;
190
+ return;
191
+ }
192
+ function errorMessage(cause) {
193
+ return cause instanceof Error ? cause.message : String(cause);
194
+ }
195
+ function splitFrames(buffer) {
196
+ const lines = buffer.split(`
197
+ `);
198
+ const rest = lines.pop() ?? "";
199
+ return { frames: lines.filter((line) => line.length > 0), rest };
200
+ }
201
+ function replaceBigInt(_key, value) {
202
+ return typeof value === "bigint" ? Number(value) : value;
203
+ }
204
+
205
+ // src/paths.ts
206
+ import { createHash } from "node:crypto";
207
+ import { mkdirSync, realpathSync, existsSync } from "node:fs";
208
+ import { tmpdir } from "node:os";
209
+ import path from "node:path";
210
+ function resolveRuntimeDirectory() {
211
+ const configured = process.env.SQLEGO_RUNTIME_DIR;
212
+ const directory = configured && configured.length > 0 ? configured : path.join(tmpdir(), "sqlego");
213
+ const created = Trust.try(() => mkdirSync(directory, { recursive: true }), (cause) => ({ kind: "runtime-directory", message: `cannot create sqlego runtime directory ${directory}: ${errorMessage(cause)}` }));
214
+ if (!created.ok)
215
+ return created;
216
+ return Result.ok(directory);
217
+ }
218
+ function resolveCanonicalFile(file) {
219
+ return Trust.try(() => {
220
+ const absolute = path.resolve(file);
221
+ const missing = [];
222
+ let existing = absolute;
223
+ while (!existsSync(existing)) {
224
+ missing.unshift(path.basename(existing));
225
+ const parent = path.dirname(existing);
226
+ if (parent === existing)
227
+ break;
228
+ existing = parent;
229
+ }
230
+ return path.join(realpathSync(existing), ...missing);
231
+ }, (cause) => ({ kind: "canonical-path", message: `cannot resolve ${file}: ${errorMessage(cause)}` }));
232
+ }
233
+ var MAX_SOCKET_PATH_BYTES = 100;
234
+ function resolvePaths(file) {
235
+ const canonical = resolveCanonicalFile(file);
236
+ if (!canonical.ok)
237
+ return canonical;
238
+ const directory = resolveRuntimeDirectory();
239
+ if (!directory.ok)
240
+ return directory;
241
+ const derived = Trust.try(() => {
242
+ const key = createHash("sha1").update(canonical.value).digest("hex").slice(0, 16);
243
+ const socket = path.join(directory.value, `${key}.sock`);
244
+ return { key, socket, socketBytes: Buffer.byteLength(socket) };
245
+ }, (cause) => ({ kind: "hash-failed", message: `cannot hash ${canonical.value}: ${errorMessage(cause)}` }));
246
+ if (!derived.ok)
247
+ return derived;
248
+ const { key, socket, socketBytes } = derived.value;
249
+ if (socketBytes > MAX_SOCKET_PATH_BYTES) {
250
+ return Result.err({
251
+ kind: "socket-path-too-long",
252
+ message: `sqlego runtime directory too deep for a Unix socket (${socketBytes} bytes > ${MAX_SOCKET_PATH_BYTES}): ${socket}. ` + "Point SQLEGO_RUNTIME_DIR at a shorter path."
253
+ });
254
+ }
255
+ const paths = Object.freeze({
256
+ file: canonical.value,
257
+ key,
258
+ socket,
259
+ lock: path.join(directory.value, `${key}.lock`),
260
+ meta: path.join(directory.value, `${key}.json`)
261
+ });
262
+ return Result.ok(paths);
263
+ }
264
+ function runtimeDirectory() {
265
+ const directory = resolveRuntimeDirectory();
266
+ if (directory.ok)
267
+ return directory.value;
268
+ throw new Error(directory.error.message);
269
+ }
270
+ function canonicalFile(file) {
271
+ const canonical = resolveCanonicalFile(file);
272
+ if (canonical.ok)
273
+ return canonical.value;
274
+ throw new Error(canonical.error.message);
275
+ }
276
+ function pathsFor(file) {
277
+ const paths = resolvePaths(file);
278
+ if (paths.ok)
279
+ return paths.value;
280
+ throw new Error(paths.error.message);
281
+ }
282
+ function isProcessAlive(pid) {
283
+ const probe = Trust.try(() => process.kill(pid, 0), (cause) => errnoCode(cause) === "EPERM" ? { kind: "not-permitted" } : { kind: "no-such-process" });
284
+ if (probe.ok)
285
+ return true;
286
+ if (probe.error.kind === "not-permitted")
287
+ return true;
288
+ if (probe.error.kind === "no-such-process")
289
+ return false;
290
+ const unhandled = probe.error;
291
+ return unhandled;
292
+ }
293
+
294
+ // src/version.ts
295
+ import { createHash as createHash2 } from "node:crypto";
296
+ import { existsSync as existsSync2, readdirSync, readFileSync } from "node:fs";
297
+ import path2 from "node:path";
298
+ import { fileURLToPath } from "node:url";
299
+ // package.json
300
+ var package_default = {
301
+ name: "@noego/sqlego",
302
+ version: "0.0.1-dev.0",
303
+ description: "One owner process per SQLite file. Clients (CLI, Node, Bun) pass SQL over a local socket; the server boots on demand and exits when idle.",
304
+ type: "module",
305
+ license: "ISC",
306
+ author: "Shavauhn Gabay",
307
+ bin: {
308
+ sqlego: "./bin/sqlego"
309
+ },
310
+ main: "./dist/index.js",
311
+ types: "./dist/index.d.ts",
312
+ exports: {
313
+ ".": {
314
+ types: "./dist/index.d.ts",
315
+ bun: "./src/index.ts",
316
+ import: "./dist/index.js",
317
+ default: "./dist/index.js"
318
+ },
319
+ "./package.json": "./package.json"
320
+ },
321
+ files: [
322
+ "src",
323
+ "dist",
324
+ "bin",
325
+ "README.md"
326
+ ],
327
+ scripts: {
328
+ prepare: "bun scripts/build.ts all",
329
+ build: "bun scripts/build.ts all",
330
+ "build:lib": "bun scripts/build.ts lib",
331
+ "build:bin": "bun scripts/build.ts bin",
332
+ typecheck: "bunx tsc --noEmit",
333
+ trust: "trust check src",
334
+ test: "bun test"
335
+ },
336
+ devDependencies: {
337
+ "@types/bun": "^1.2.0",
338
+ "@types/node": "^22.0.0",
339
+ typescript: "^5.6.0"
340
+ },
341
+ dependencies: {
342
+ "@noego/trust": "0.5.0-dev.0"
343
+ }
344
+ };
345
+
346
+ // src/version.ts
347
+ function sourceBuildId(sourceDirectory) {
348
+ if (!existsSync2(sourceDirectory))
349
+ return Result.ok("source");
350
+ return Trust.try(() => {
351
+ const hash = createHash2("sha1");
352
+ for (const name of readdirSync(sourceDirectory).filter((entry) => entry.endsWith(".ts")).sort()) {
353
+ hash.update(name);
354
+ hash.update(readFileSync(path2.join(sourceDirectory, name)));
355
+ }
356
+ return hash.digest("hex").slice(0, 12);
357
+ }, (cause) => ({ kind: "source-unreadable", message: `cannot hash sources in ${sourceDirectory}: ${errorMessage(cause)}` }));
358
+ }
359
+ function resolveBuildId() {
360
+ if ("c91af7f0abe9".length > 0)
361
+ return "c91af7f0abe9";
362
+ const directory = Trust.try(() => path2.dirname(fileURLToPath(import.meta.url)), (cause) => ({ kind: "module-path", message: errorMessage(cause) }));
363
+ if (!directory.ok)
364
+ return decideUnknownBuild(directory.error.kind);
365
+ const id = sourceBuildId(directory.value);
366
+ if (!id.ok)
367
+ return decideUnknownBuild(id.error.kind);
368
+ return id.value;
369
+ }
370
+ function decideUnknownBuild(kind) {
371
+ switch (kind) {
372
+ case "module-path":
373
+ return "source";
374
+ case "source-unreadable":
375
+ return "source";
376
+ default: {
377
+ const unhandled = kind;
378
+ return unhandled;
379
+ }
380
+ }
381
+ }
382
+ var BUILD_ID = resolveBuildId();
383
+ var VERSION = process.env.SQLEGO_VERSION_OVERRIDE || `${package_default.version}+${BUILD_ID}`;
384
+
385
+ // src/client.ts
386
+ class SqlegoClientError extends Error {
387
+ code;
388
+ constructor(code, message) {
389
+ super(message);
390
+ this.code = code;
391
+ }
392
+ }
393
+ var STOP_TIMEOUT_MS = 1000;
394
+ function unwrap(outcome) {
395
+ if (outcome.ok)
396
+ return outcome.value;
397
+ throw new SqlegoClientError(outcome.error.kind, outcome.error.message);
398
+ }
399
+ function callerRows(rows) {
400
+ return rows;
401
+ }
402
+
403
+ class SqlegoClient {
404
+ paths;
405
+ socket = null;
406
+ buffer = "";
407
+ nextId = 1;
408
+ pending = new Map;
409
+ hello = null;
410
+ spawnFailure = null;
411
+ options;
412
+ constructor(paths, options) {
413
+ this.paths = paths;
414
+ this.options = options;
415
+ }
416
+ static async connect(file, options = {}) {
417
+ const paths = resolvePaths(file);
418
+ if (!paths.ok) {
419
+ throw new Error(paths.error.message);
420
+ }
421
+ const client = new SqlegoClient(paths.value, options);
422
+ unwrap(await client.open());
423
+ return client;
424
+ }
425
+ get server() {
426
+ if (this.hello)
427
+ return this.hello;
428
+ return unwrap(Result.err({ kind: "not-connected", message: "client is not connected" }));
429
+ }
430
+ async query(sql, params) {
431
+ const result = unwrap(await this.call({ op: "query", sql, params }, parseQueryResult));
432
+ return callerRows(result.rows);
433
+ }
434
+ async run(sql, params) {
435
+ return unwrap(await this.call({ op: "run", sql, params }, parseRunResult));
436
+ }
437
+ async batch(statements) {
438
+ const result = unwrap(await this.call({ op: "batch", statements }, parseBatchResult));
439
+ return result.results;
440
+ }
441
+ async status() {
442
+ return unwrap(await this.call({ op: "status" }, parseStatusResult));
443
+ }
444
+ async stop() {
445
+ unwrap(await this.stopServer());
446
+ }
447
+ async close() {
448
+ const socket = this.socket;
449
+ this.socket = null;
450
+ if (!socket || socket.destroyed)
451
+ return;
452
+ await new Promise((resolve) => endSocket(socket, resolve));
453
+ }
454
+ async stopServer() {
455
+ const stopped = await this.call({ op: "stop" }, parseStopResult, STOP_TIMEOUT_MS);
456
+ if (!stopped.ok) {
457
+ switch (stopped.error.kind) {
458
+ case "closed":
459
+ case "not-connected":
460
+ case "socket":
461
+ case "request-timeout":
462
+ break;
463
+ default:
464
+ return stopped;
465
+ }
466
+ }
467
+ await this.close();
468
+ return Result.ok(undefined);
469
+ }
470
+ async open() {
471
+ const deadline = Date.now() + (this.options.connectTimeoutMs ?? 1e4);
472
+ const socket = await this.connectOrSpawn(deadline);
473
+ if (!socket.ok)
474
+ return socket;
475
+ const attached = this.attach(socket.value);
476
+ if (!attached.ok)
477
+ return attached;
478
+ const hello = await this.call({ op: "hello", clientVersion: VERSION, protocol: PROTOCOL_VERSION }, parseHelloResult);
479
+ if (!hello.ok)
480
+ return hello;
481
+ if (hello.value.serverVersion === VERSION || this.options.spawn === false) {
482
+ this.hello = hello.value;
483
+ return Result.ok(undefined);
484
+ }
485
+ const stopped = await this.stopServer();
486
+ if (!stopped.ok)
487
+ return stopped;
488
+ await this.waitForExit(hello.value.pid, deadline);
489
+ const fresh = await this.connectOrSpawn(deadline);
490
+ if (!fresh.ok)
491
+ return fresh;
492
+ const reattached = this.attach(fresh.value);
493
+ if (!reattached.ok)
494
+ return reattached;
495
+ const freshHello = await this.call({ op: "hello", clientVersion: VERSION, protocol: PROTOCOL_VERSION }, parseHelloResult);
496
+ if (!freshHello.ok)
497
+ return freshHello;
498
+ this.hello = freshHello.value;
499
+ return Result.ok(undefined);
500
+ }
501
+ async connectOrSpawn(deadline) {
502
+ const first = await tryConnect(this.paths.socket);
503
+ if (first)
504
+ return Result.ok(first);
505
+ if (this.options.spawn === false) {
506
+ return Result.err({ kind: "not-running", message: `no sqlego server for ${this.paths.file}` });
507
+ }
508
+ const claimed = this.claimLock();
509
+ if (!claimed.ok)
510
+ return claimed;
511
+ if (claimed.value) {
512
+ const spawned = this.spawnServer();
513
+ if (!spawned.ok)
514
+ return spawned;
515
+ }
516
+ while (Date.now() < deadline) {
517
+ const socket = await tryConnect(this.paths.socket);
518
+ if (socket)
519
+ return Result.ok(socket);
520
+ await sleep(25);
521
+ }
522
+ const cause = this.spawnFailure ? ` (${this.spawnFailure})` : "";
523
+ return Result.err({ kind: "connect-timeout", message: `no sqlego server became reachable for ${this.paths.file}${cause}` });
524
+ }
525
+ claimLock() {
526
+ const lock = this.paths.lock;
527
+ for (let attempt = 0;attempt < 2; attempt += 1) {
528
+ const created = Trust.try(() => {
529
+ const fd = openSync(lock, "wx");
530
+ writeSync(fd, String(process.pid));
531
+ closeSync(fd);
532
+ }, (cause) => errnoCode(cause) === "EEXIST" ? { kind: "lock-held", message: `${lock} exists` } : { kind: "lock-failed", message: `cannot create ${lock}: ${errorMessage(cause)}` });
533
+ if (created.ok)
534
+ return Result.ok(true);
535
+ if (created.error.kind === "lock-failed")
536
+ return Result.err({ kind: "lock-failed", message: created.error.message });
537
+ if (created.error.kind === "lock-held") {
538
+ const holder = Trust.try(() => Number(readFileSync2(lock, "utf8").trim()), (cause) => ({ kind: "lock-unreadable", message: errorMessage(cause) }));
539
+ if (holder.ok) {
540
+ if (Number.isFinite(holder.value) && holder.value > 0 && isProcessAlive(holder.value))
541
+ return Result.ok(false);
542
+ } else if (holder.error.kind === "lock-unreadable") {}
543
+ const removed = Trust.try(() => rmSync(lock, { force: true }), (cause) => ({ kind: "lock-failed", message: `cannot remove stale ${lock}: ${errorMessage(cause)}` }));
544
+ if (!removed.ok)
545
+ return removed;
546
+ }
547
+ }
548
+ return Result.ok(false);
549
+ }
550
+ spawnServer() {
551
+ const [command, ...args] = this.options.serverCommand ?? defaultServerCommand();
552
+ const pragmaArgs = (this.options.serverPragmas ?? []).flatMap((pragma) => ["--pragma", pragma]);
553
+ return Trust.try(() => {
554
+ const child = spawn(command, [...args, "serve", this.paths.file, "--idle-ms", String(this.options.idleTimeoutMs ?? 30000), ...pragmaArgs], {
555
+ detached: true,
556
+ stdio: ["ignore", "ignore", "pipe"],
557
+ env: { ...process.env, SQLEGO_CLAIMED_BY: String(process.pid) }
558
+ });
559
+ let stderr = "";
560
+ child.stderr?.on("data", (chunk) => {
561
+ if (stderr.length < 2000)
562
+ stderr += chunk.toString();
563
+ });
564
+ const stderrPipe = child.stderr;
565
+ if (typeof stderrPipe === "object" && stderrPipe !== null && "unref" in stderrPipe && typeof stderrPipe.unref === "function") {
566
+ stderrPipe.unref();
567
+ }
568
+ child.on("error", (error) => this.onSpawnError(command, error));
569
+ child.on("exit", (code, signal) => {
570
+ if (!this.hello)
571
+ this.spawnFailure = `server exited before listening (code ${code}, signal ${signal})${stderr ? `: ${stderr.trim()}` : ""}`;
572
+ });
573
+ child.unref();
574
+ }, (cause) => ({ kind: "spawn-failed", message: `spawn ${command} failed: ${errorMessage(cause)}` }));
575
+ }
576
+ onSpawnError(command, error) {
577
+ this.spawnFailure = `spawn ${command} failed: ${error.message}`;
578
+ const released = Trust.try(() => rmSync(this.paths.lock, { force: true }), (cause) => ({ kind: "lock-failed", message: errorMessage(cause) }));
579
+ if (!released.ok && released.error.kind === "lock-failed")
580
+ this.spawnFailure += `; lock not released: ${released.error.message}`;
581
+ }
582
+ attach(socket) {
583
+ this.socket = socket;
584
+ this.buffer = "";
585
+ return Trust.try(() => {
586
+ socket.setEncoding("utf8");
587
+ socket.on("data", (chunk) => this.onData(chunk));
588
+ socket.on("end", () => socket.destroy());
589
+ socket.on("close", () => this.onClose(socket));
590
+ socket.on("error", (error) => this.settleAll({ kind: "socket", message: error.message }));
591
+ }, (cause) => ({ kind: "socket", message: errorMessage(cause) }));
592
+ }
593
+ onClose(socket) {
594
+ if (this.socket === socket)
595
+ this.socket = null;
596
+ this.settleAll({ kind: "closed", message: "connection closed" });
597
+ }
598
+ onData(chunk) {
599
+ const { frames, rest } = splitFrames(this.buffer + chunk);
600
+ this.buffer = rest;
601
+ for (const frame of frames) {
602
+ const json = fromJson(frame);
603
+ const parsed = json.ok ? parseResponse(json.value) : json;
604
+ if (!parsed.ok) {
605
+ if (parsed.error.kind === "invalid") {
606
+ this.buffer = "";
607
+ this.settleAll({ kind: "protocol", message: `malformed frame from server: ${parsed.error.message}` });
608
+ this.socket?.destroy();
609
+ }
610
+ return;
611
+ }
612
+ const response = parsed.value;
613
+ const waiter = this.pending.get(response.id);
614
+ if (!waiter)
615
+ continue;
616
+ this.pending.delete(response.id);
617
+ clearTimeout(waiter.timer);
618
+ waiter.settle(response.ok ? Result.ok(response.result) : Result.err({ kind: response.error.code, message: response.error.message }));
619
+ }
620
+ }
621
+ async call(body, parse, timeoutMs) {
622
+ const reply = await this.request(body, timeoutMs);
623
+ if (!reply.ok)
624
+ return reply;
625
+ const parsed = parse(reply.value);
626
+ if (parsed.ok)
627
+ return parsed;
628
+ if (parsed.error.kind === "invalid") {
629
+ return Result.err({ kind: "protocol", message: `unexpected ${body.op} reply: ${parsed.error.message}` });
630
+ }
631
+ const unhandled = parsed.error.kind;
632
+ return unhandled;
633
+ }
634
+ request(body, timeoutMs = this.options.requestTimeoutMs ?? 60000) {
635
+ const socket = this.socket;
636
+ if (!socket || socket.destroyed) {
637
+ return Promise.resolve(Result.err({ kind: "not-connected", message: "client is not connected" }));
638
+ }
639
+ const id = this.nextId++;
640
+ const frame = encodeFrame({ id, ...body });
641
+ if (!frame.ok)
642
+ return Promise.resolve(frame);
643
+ return new Promise((settle) => {
644
+ const timer = setTimeout(() => {
645
+ this.pending.delete(id);
646
+ settle(Result.err({ kind: "request-timeout", message: `request ${id} (${body.op}) timed out` }));
647
+ }, timeoutMs);
648
+ this.pending.set(id, { settle, timer });
649
+ const written = Trust.try(() => socket.write(frame.value), (cause) => ({ kind: "socket", message: errorMessage(cause) }));
650
+ if (!written.ok) {
651
+ this.pending.delete(id);
652
+ clearTimeout(timer);
653
+ settle(written);
654
+ }
655
+ });
656
+ }
657
+ settleAll(failure) {
658
+ for (const waiter of this.pending.values()) {
659
+ clearTimeout(waiter.timer);
660
+ waiter.settle(Result.err(failure));
661
+ }
662
+ this.pending.clear();
663
+ }
664
+ async waitForExit(pid, deadline) {
665
+ while (Date.now() < deadline && isProcessAlive(pid))
666
+ await sleep(25);
667
+ }
668
+ }
669
+ function defaultServerCommand() {
670
+ const configured = process.env.SQLEGO_BIN;
671
+ if (configured && configured.length > 0)
672
+ return [configured];
673
+ const entry = process.argv[1] ?? "";
674
+ const located = Trust.try(() => path3.dirname(fileURLToPath2(import.meta.url)), (cause) => ({ kind: "module-path", message: errorMessage(cause) }));
675
+ let here = null;
676
+ if (located.ok)
677
+ here = located.value;
678
+ else if (located.error.kind === "module-path")
679
+ here = null;
680
+ if (process.versions.bun) {
681
+ if (entry.endsWith("cli.ts"))
682
+ return [process.execPath, entry];
683
+ if (entry.endsWith(".ts") && here !== null) {
684
+ const cli = path3.join(here, "cli.ts");
685
+ if (existsSync3(cli))
686
+ return [process.execPath, cli];
687
+ }
688
+ if (!entry.endsWith(".js") && !entry.endsWith(".ts"))
689
+ return [process.execPath];
690
+ }
691
+ if (here !== null) {
692
+ const local = path3.join(here, "..", "bin", "sqlego");
693
+ if (existsSync3(local))
694
+ return [local];
695
+ }
696
+ return ["sqlego"];
697
+ }
698
+ function tryConnect(socketPath) {
699
+ return new Promise((resolve) => {
700
+ const started = Trust.try(() => {
701
+ const socket = new net.Socket;
702
+ socket.once("connect", () => resolve(connected(socket)));
703
+ socket.once("error", () => {
704
+ socket.destroy();
705
+ resolve(null);
706
+ });
707
+ socket.connect(socketPath);
708
+ }, (cause) => ({ kind: "connect-failed", message: errorMessage(cause) }));
709
+ if (!started.ok && started.error.kind === "connect-failed")
710
+ resolve(null);
711
+ });
712
+ }
713
+ function connected(socket) {
714
+ const detached = Trust.try(() => socket.removeAllListeners("error"), (cause) => ({ kind: "listener-cleanup", message: errorMessage(cause) }));
715
+ if (detached.ok)
716
+ return socket;
717
+ if (detached.error.kind === "listener-cleanup")
718
+ socket.destroy();
719
+ return null;
720
+ }
721
+ function endSocket(socket, resolve) {
722
+ const ended = Trust.try(() => {
723
+ const done = () => {
724
+ clearTimeout(guard);
725
+ resolve();
726
+ };
727
+ const guard = setTimeout(() => {
728
+ socket.destroy();
729
+ done();
730
+ }, 500);
731
+ socket.once("close", done);
732
+ socket.end();
733
+ }, (cause) => ({ kind: "end-failed", message: errorMessage(cause) }));
734
+ if (!ended.ok && ended.error.kind === "end-failed") {
735
+ socket.destroy();
736
+ resolve();
737
+ }
738
+ }
739
+ function sleep(ms) {
740
+ return new Promise((resolve) => setTimeout(resolve, ms));
741
+ }
742
+ export {
743
+ PROTOCOL_VERSION,
744
+ SqlegoClient,
745
+ SqlegoClientError,
746
+ VERSION,
747
+ canonicalFile,
748
+ defaultServerCommand,
749
+ pathsFor,
750
+ runtimeDirectory
751
+ };