@noego/sqlego 0.1.2-dev.1 → 0.1.2-dev.3

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 CHANGED
@@ -1,8 +1,9 @@
1
1
  // src/client.ts
2
2
  import { spawn } from "node:child_process";
3
3
  import { closeSync, openSync, readdirSync as readdirSync2, readFileSync as readFileSync2, rmSync, writeSync, existsSync as existsSync3 } from "node:fs";
4
+ import { createRequire } from "node:module";
4
5
  import net from "node:net";
5
- import path3 from "node:path";
6
+ import path4 from "node:path";
6
7
  import { fileURLToPath as fileURLToPath2 } from "node:url";
7
8
 
8
9
  // node_modules/@noego/trust/dist/index.js
@@ -46,6 +47,49 @@ function translate(result, mappers) {
46
47
  var Result = { ok, err };
47
48
  var Trust = { try: tryResult, tryAsync: tryResultAsync, decide, translate };
48
49
 
50
+ // src/binary.ts
51
+ import path from "node:path";
52
+ var SUPPORTED_PLATFORMS = ["darwin-arm64", "darwin-x64", "linux-x64", "linux-arm64", "win32-x64"];
53
+ function platformPackageName(platform = process.platform, arch = process.arch) {
54
+ return `@noego/sqlego-${platform}-${arch}`;
55
+ }
56
+ function binaryFileName(platform = process.platform) {
57
+ return platform === "win32" ? "sqlego.exe" : "sqlego";
58
+ }
59
+ function localBinaryName(platform = process.platform, arch = process.arch) {
60
+ return `sqlego-${platform}-${arch}${platform === "win32" ? ".exe" : ""}`;
61
+ }
62
+ function unpackedAsarPath(file) {
63
+ return file.replace(/([\\/])app\.asar(?=[\\/])/, "$1app.asar.unpacked");
64
+ }
65
+ function locateServerBinary(lookup) {
66
+ if (lookup.configured !== undefined && lookup.configured.length > 0)
67
+ return Result.ok(lookup.configured);
68
+ const name = platformPackageName(lookup.platform, lookup.arch);
69
+ const manifest = lookup.resolvePackageJson(name);
70
+ const looked = [];
71
+ if (manifest !== null) {
72
+ const fromPackage = unpackedAsarPath(path.join(path.dirname(manifest), binaryFileName(lookup.platform)));
73
+ if (lookup.exists(fromPackage))
74
+ return Result.ok(fromPackage);
75
+ looked.push(fromPackage);
76
+ }
77
+ if (lookup.localBinDirectory !== null) {
78
+ const local = unpackedAsarPath(path.join(lookup.localBinDirectory, localBinaryName(lookup.platform, lookup.arch)));
79
+ if (lookup.exists(local))
80
+ return Result.ok(local);
81
+ looked.push(local);
82
+ }
83
+ const key = `${lookup.platform}-${lookup.arch}`;
84
+ const supported = SUPPORTED_PLATFORMS.includes(key);
85
+ const reason = !supported ? `sqlego publishes no server binary for ${key} (supported: ${SUPPORTED_PLATFORMS.join(", ")})` : manifest === null ? `the package ${name} is not installed (npm installs it as an optional dependency of @noego/sqlego; it is skipped by --omit=optional / --no-optional, and on a platform that does not match)` : `the package ${name} is installed but has no binary`;
86
+ const where = looked.length > 0 ? `; looked in ${looked.join(", ")}` : "";
87
+ return Result.err({
88
+ kind: "binary-missing",
89
+ message: `no sqlego server binary for ${key}: ${reason}${where}. Reinstall without --omit=optional, or set SQLEGO_BIN to the path of a sqlego binary.`
90
+ });
91
+ }
92
+
49
93
  // src/protocol.ts
50
94
  var PROTOCOL_VERSION = 3;
51
95
  var INT64_MIN = -9223372036854775808n;
@@ -232,8 +276,8 @@ function parseResponse(input) {
232
276
  if (typeof id !== "number")
233
277
  return invalid("a response needs a numeric id");
234
278
  if (fields.ok === true) {
235
- const response = { id, ok: true, result: fields.result };
236
- return Result.ok(response);
279
+ const response2 = { id, ok: true, result: fields.result };
280
+ return Result.ok(response2);
237
281
  }
238
282
  if (fields.ok !== false)
239
283
  return invalid("a response needs ok: true or false");
@@ -347,10 +391,13 @@ function parseExecResult(input) {
347
391
  return Result.ok(result);
348
392
  }
349
393
  function parsePragmas(input) {
394
+ return parseStringList(input, "pragmas");
395
+ }
396
+ function parseStringList(input, name) {
350
397
  if (input === undefined)
351
398
  return Result.ok([]);
352
399
  if (!Array.isArray(input) || !input.every((item) => typeof item === "string")) {
353
- return invalid("pragmas must be an array of strings");
400
+ return invalid(`${name} must be an array of strings`);
354
401
  }
355
402
  return Result.ok([...input]);
356
403
  }
@@ -362,7 +409,10 @@ function parseHelloResult(input) {
362
409
  const pragmas = parsePragmas(fields.pragmas);
363
410
  if (!pragmas.ok)
364
411
  return pragmas;
365
- const result = { serverVersion: fields.serverVersion, protocol: fields.protocol, file: fields.file, pid: fields.pid, pragmas: pragmas.value };
412
+ const capabilities = parseStringList(fields.capabilities, "capabilities");
413
+ if (!capabilities.ok)
414
+ return capabilities;
415
+ const result = { serverVersion: fields.serverVersion, protocol: fields.protocol, file: fields.file, pid: fields.pid, pragmas: pragmas.value, capabilities: capabilities.value };
366
416
  return Result.ok(result);
367
417
  }
368
418
  function parseBeginResult(input) {
@@ -416,6 +466,9 @@ function parseStatusResult(input) {
416
466
  const pragmas = parsePragmas(f.pragmas);
417
467
  if (!pragmas.ok)
418
468
  return pragmas;
469
+ const capabilities = parseStringList(f.capabilities, "capabilities");
470
+ if (!capabilities.ok)
471
+ return capabilities;
419
472
  const files = f.files === undefined ? 1 : f.files;
420
473
  if (typeof files !== "number")
421
474
  return invalid("status.files must be a number");
@@ -432,7 +485,8 @@ function parseStatusResult(input) {
432
485
  idleMs: f.idleMs,
433
486
  idleTimeoutMs: f.idleTimeoutMs,
434
487
  requestsServed: f.requestsServed,
435
- transaction: transaction.value
488
+ transaction: transaction.value,
489
+ capabilities: capabilities.value
436
490
  };
437
491
  return Result.ok(result);
438
492
  }
@@ -472,10 +526,10 @@ function replaceBigInt(_key, value) {
472
526
  import { createHash } from "node:crypto";
473
527
  import { mkdirSync, realpathSync, existsSync } from "node:fs";
474
528
  import { tmpdir } from "node:os";
475
- import path from "node:path";
529
+ import path2 from "node:path";
476
530
  function resolveRuntimeDirectory() {
477
531
  const configured = process.env.SQLEGO_RUNTIME_DIR;
478
- const directory = configured && configured.length > 0 ? configured : path.join(tmpdir(), "sqlego");
532
+ const directory = configured && configured.length > 0 ? configured : path2.join(tmpdir(), "sqlego");
479
533
  const created = Trust.try(() => mkdirSync(directory, { recursive: true }), (cause) => ({ kind: "runtime-directory", message: `cannot create sqlego runtime directory ${directory}: ${errorMessage(cause)}` }));
480
534
  if (!created.ok)
481
535
  return created;
@@ -483,17 +537,17 @@ function resolveRuntimeDirectory() {
483
537
  }
484
538
  function resolveCanonicalFile(file) {
485
539
  return Trust.try(() => {
486
- const absolute = path.resolve(file);
540
+ const absolute = path2.resolve(file);
487
541
  const missing = [];
488
542
  let existing = absolute;
489
543
  while (!existsSync(existing)) {
490
- missing.unshift(path.basename(existing));
491
- const parent = path.dirname(existing);
544
+ missing.unshift(path2.basename(existing));
545
+ const parent = path2.dirname(existing);
492
546
  if (parent === existing)
493
547
  break;
494
548
  existing = parent;
495
549
  }
496
- return path.join(realpathSync(existing), ...missing);
550
+ return path2.join(realpathSync(existing), ...missing);
497
551
  }, (cause) => ({ kind: "canonical-path", message: `cannot resolve ${file}: ${errorMessage(cause)}` }));
498
552
  }
499
553
  var MAX_SOCKET_PATH_BYTES = 100;
@@ -509,10 +563,10 @@ function resolvePaths(file) {
509
563
  if (!directory.ok)
510
564
  return directory;
511
565
  const derived = Trust.try(() => {
512
- const key = createHash("sha1").update(canonical.value).digest("hex").slice(0, 16);
566
+ const key2 = createHash("sha1").update(canonical.value).digest("hex").slice(0, 16);
513
567
  const scope = createHash("sha1").update(directory.value.toLowerCase()).digest("hex").slice(0, 8);
514
- const socket = USES_NAMED_PIPES ? `\\\\.\\pipe\\sqlego-${scope}-${key}` : path.join(directory.value, `${key}.sock`);
515
- return { key, socket, socketBytes: Buffer.byteLength(socket) };
568
+ const socket2 = USES_NAMED_PIPES ? `\\\\.\\pipe\\sqlego-${scope}-${key2}` : path2.join(directory.value, `${key2}.sock`);
569
+ return { key: key2, socket: socket2, socketBytes: Buffer.byteLength(socket2) };
516
570
  }, (cause) => ({ kind: "hash-failed", message: `cannot hash ${canonical.value}: ${errorMessage(cause)}` }));
517
571
  if (!derived.ok)
518
572
  return derived;
@@ -527,8 +581,8 @@ function resolvePaths(file) {
527
581
  file: canonical.value,
528
582
  key,
529
583
  socket,
530
- lock: path.join(directory.value, `${key}.lock`),
531
- meta: path.join(directory.value, `${key}.json`)
584
+ lock: path2.join(directory.value, `${key}.lock`),
585
+ meta: path2.join(directory.value, `${key}.json`)
532
586
  });
533
587
  return Result.ok(paths);
534
588
  }
@@ -579,12 +633,12 @@ function isProcessAlive(pid) {
579
633
  // src/version.ts
580
634
  import { createHash as createHash2 } from "node:crypto";
581
635
  import { existsSync as existsSync2, readdirSync, readFileSync } from "node:fs";
582
- import path2 from "node:path";
636
+ import path3 from "node:path";
583
637
  import { fileURLToPath } from "node:url";
584
638
  // package.json
585
639
  var package_default = {
586
640
  name: "@noego/sqlego",
587
- version: "0.1.2-dev.1",
641
+ version: "0.1.2-dev.3",
588
642
  description: "One owner per SQLite file, many files per owner process. Clients (CLI, Node, Bun) pass SQL over a local socket (Unix) or named pipe (Windows); the owner starts on demand and exits when idle.",
589
643
  type: "module",
590
644
  license: "ISC",
@@ -611,7 +665,7 @@ var package_default = {
611
665
  files: [
612
666
  "src",
613
667
  "dist",
614
- "bin",
668
+ "bin/sqlego.cjs",
615
669
  "README.md"
616
670
  ],
617
671
  scripts: {
@@ -621,6 +675,7 @@ var package_default = {
621
675
  "build:lib": "bun scripts/build.ts lib",
622
676
  "build:bin": "bun scripts/build.ts bin",
623
677
  "build:bin:all": "bun scripts/build.ts bin:all",
678
+ release: "bun scripts/release.ts",
624
679
  typecheck: "bunx tsc --noEmit",
625
680
  trust: "trust check src",
626
681
  test: "bun test"
@@ -632,6 +687,13 @@ var package_default = {
632
687
  },
633
688
  dependencies: {
634
689
  "@noego/trust": "0.5.0-dev.0"
690
+ },
691
+ optionalDependencies: {
692
+ "@noego/sqlego-darwin-arm64": "0.1.2-dev.3",
693
+ "@noego/sqlego-darwin-x64": "0.1.2-dev.3",
694
+ "@noego/sqlego-linux-x64": "0.1.2-dev.3",
695
+ "@noego/sqlego-linux-arm64": "0.1.2-dev.3",
696
+ "@noego/sqlego-win32-x64": "0.1.2-dev.3"
635
697
  }
636
698
  };
637
699
 
@@ -643,15 +705,15 @@ function sourceBuildId(sourceDirectory) {
643
705
  const hash = createHash2("sha1");
644
706
  for (const name of readdirSync(sourceDirectory).filter((entry) => entry.endsWith(".ts")).sort()) {
645
707
  hash.update(name);
646
- hash.update(readFileSync(path2.join(sourceDirectory, name)));
708
+ hash.update(readFileSync(path3.join(sourceDirectory, name)));
647
709
  }
648
710
  return hash.digest("hex").slice(0, 12);
649
711
  }, (cause) => ({ kind: "source-unreadable", message: `cannot hash sources in ${sourceDirectory}: ${errorMessage(cause)}` }));
650
712
  }
651
713
  function resolveBuildId() {
652
- if ("e0ab394649fb".length > 0)
653
- return "e0ab394649fb";
654
- const directory = Trust.try(() => path2.dirname(fileURLToPath(import.meta.url)), (cause) => ({ kind: "module-path", message: errorMessage(cause) }));
714
+ if ("4c867ea8aaf4".length > 0)
715
+ return "4c867ea8aaf4";
716
+ const directory = Trust.try(() => path3.dirname(fileURLToPath(import.meta.url)), (cause) => ({ kind: "module-path", message: errorMessage(cause) }));
655
717
  if (!directory.ok)
656
718
  return decideUnknownBuild(directory.error.kind);
657
719
  const id = sourceBuildId(directory.value);
@@ -727,6 +789,17 @@ class SqlegoClient {
727
789
  return this.hello;
728
790
  return unwrap(Result.err({ kind: "not-connected", message: "client is not connected" }));
729
791
  }
792
+ async enableDetachedPlain() {
793
+ if (!this.server.capabilities.includes("detached-plain"))
794
+ return false;
795
+ this.hello = unwrap(await this.call({
796
+ op: "hello",
797
+ clientVersion: VERSION,
798
+ protocol: PROTOCOL_VERSION,
799
+ features: ["detached-plain"]
800
+ }, parseHelloResult));
801
+ return this.hello.capabilities.includes("detached-plain");
802
+ }
730
803
  async query(sql, params) {
731
804
  const result = unwrap(await this.call({ op: "query", sql, params }, parseQueryResult));
732
805
  return callerRows(result.rows);
@@ -880,7 +953,7 @@ class SqlegoClient {
880
953
  return Number.isFinite(configured) && configured >= 0 ? Math.floor(configured) : DEFAULT_MAX_OWNERS;
881
954
  }
882
955
  spawnLockPath() {
883
- return path3.join(path3.dirname(this.paths.lock), "spawn.lock");
956
+ return path4.join(path4.dirname(this.paths.lock), "spawn.lock");
884
957
  }
885
958
  async placeFile(deadline) {
886
959
  const budget = this.ownerBudget();
@@ -923,7 +996,7 @@ class SqlegoClient {
923
996
  return Result.err({ kind: "connect-timeout", message: `no sqlego owner took on ${this.paths.file}${why}` });
924
997
  }
925
998
  currentOwners() {
926
- const directory = path3.dirname(this.paths.lock);
999
+ const directory = path4.dirname(this.paths.lock);
927
1000
  const names = Trust.try(() => readdirSync2(directory), (cause) => ({ kind: "runtime-directory", message: `cannot list sqlego owners in ${directory}: ${errorMessage(cause)}` }));
928
1001
  if (!names.ok)
929
1002
  return names;
@@ -931,7 +1004,7 @@ class SqlegoClient {
931
1004
  for (const name of names.value) {
932
1005
  if (!name.endsWith(".json"))
933
1006
  continue;
934
- const text = Trust.try(() => readFileSync2(path3.join(directory, name), "utf8"), () => ({ kind: "invalid", message: "unreadable" }));
1007
+ const text = Trust.try(() => readFileSync2(path4.join(directory, name), "utf8"), () => ({ kind: "invalid", message: "unreadable" }));
935
1008
  const json = text.ok ? fromJson(text.value) : text;
936
1009
  const meta = json.ok ? parseServerMeta(json.value) : json;
937
1010
  if (meta.ok) {
@@ -967,7 +1040,10 @@ class SqlegoClient {
967
1040
  }
968
1041
  }
969
1042
  spawnServer() {
970
- const [command, ...args] = this.options.serverCommand ?? defaultServerCommand();
1043
+ const resolved = this.options.serverCommand ? Result.ok(this.options.serverCommand) : resolveServerCommand();
1044
+ if (!resolved.ok)
1045
+ return resolved;
1046
+ const [command, ...args] = resolved.value;
971
1047
  const pragmaArgs = (this.options.serverPragmas ?? []).flatMap((pragma) => ["--pragma", pragma]);
972
1048
  return Trust.try(() => {
973
1049
  const child = spawn(command, [...args, "serve", this.paths.file, "--idle-ms", String(this.options.idleTimeoutMs ?? 30000), ...pragmaArgs], {
@@ -1160,40 +1236,56 @@ function savepointName(name) {
1160
1236
  return name;
1161
1237
  return unwrap(Result.err({ kind: "bad-request", message: `savepoint name must be an identifier (letters, digits, _), not "${name}"` }));
1162
1238
  }
1163
- function platformBinaryNames(platform = process.platform, arch = process.arch) {
1164
- const suffix = platform === "win32" ? ".exe" : "";
1165
- return [`sqlego${suffix}`, `sqlego-${platform}-${arch}${suffix}`];
1166
- }
1167
- function defaultServerCommand() {
1239
+ function resolveServerCommand() {
1168
1240
  const configured = process.env.SQLEGO_BIN;
1169
1241
  if (configured && configured.length > 0)
1170
- return [configured];
1171
- const entry = process.argv[1] ?? "";
1172
- const located = Trust.try(() => path3.dirname(fileURLToPath2(import.meta.url)), (cause) => ({ kind: "module-path", message: errorMessage(cause) }));
1242
+ return Result.ok([configured]);
1243
+ const located = Trust.try(() => path4.dirname(fileURLToPath2(import.meta.url)), (cause) => ({ kind: "module-path", message: errorMessage(cause) }));
1173
1244
  let here = null;
1174
1245
  if (located.ok)
1175
1246
  here = located.value;
1176
1247
  else if (located.error.kind === "module-path")
1177
1248
  here = null;
1178
1249
  if (process.versions.bun) {
1250
+ const entry = process.argv[1] ?? "";
1251
+ if (path4.basename(process.execPath).startsWith("sqlego"))
1252
+ return Result.ok([process.execPath]);
1179
1253
  if (entry.endsWith("cli.ts"))
1180
- return [process.execPath, entry];
1254
+ return Result.ok([process.execPath, entry]);
1181
1255
  if (entry.endsWith(".ts") && here !== null) {
1182
- const cli = path3.join(here, "cli.ts");
1256
+ const cli = path4.join(here, "cli.ts");
1183
1257
  if (existsSync3(cli))
1184
- return [process.execPath, cli];
1185
- }
1186
- if (!entry.endsWith(".js") && !entry.endsWith(".ts"))
1187
- return [process.execPath];
1188
- }
1189
- if (here !== null) {
1190
- for (const name of platformBinaryNames()) {
1191
- const local = path3.join(here, "..", "bin", name);
1192
- if (existsSync3(local))
1193
- return [local];
1258
+ return Result.ok([process.execPath, cli]);
1194
1259
  }
1195
1260
  }
1196
- return ["sqlego"];
1261
+ const binary = locateServerBinary({
1262
+ platform: process.platform,
1263
+ arch: process.arch,
1264
+ configured: undefined,
1265
+ resolvePackageJson: (name) => resolvePackageJson(name, here),
1266
+ exists: existsSync3,
1267
+ localBinDirectory: here === null ? null : path4.join(here, "..", "bin")
1268
+ });
1269
+ if (!binary.ok)
1270
+ return binary;
1271
+ return Result.ok([binary.value]);
1272
+ }
1273
+ function defaultServerCommand() {
1274
+ const command = resolveServerCommand();
1275
+ if (command.ok)
1276
+ return command.value;
1277
+ throw new Error(command.error.message);
1278
+ }
1279
+ function resolvePackageJson(name, here) {
1280
+ if (here === null)
1281
+ return null;
1282
+ const resolved = Trust.try(() => createRequire(path4.join(here, "index.js")).resolve(`${name}/package.json`), (cause) => ({ kind: "not-installed", message: errorMessage(cause) }));
1283
+ if (resolved.ok)
1284
+ return typeof resolved.value === "string" ? resolved.value : null;
1285
+ if (resolved.error.kind === "not-installed")
1286
+ return null;
1287
+ const unhandled = resolved.error.kind;
1288
+ return unhandled;
1197
1289
  }
1198
1290
  var probeFailed = (message) => Result.err({ kind: "probe-failed", message });
1199
1291
  function oneShot(socketPath, body, parse, timeoutMs) {
@@ -1248,8 +1340,8 @@ function parseOneShotReply(line, parse) {
1248
1340
  if (!response.ok) {
1249
1341
  if (response.error.kind === "invalid")
1250
1342
  return probeFailed(`malformed reply: ${response.error.message}`);
1251
- const unhandled = response.error.kind;
1252
- return unhandled;
1343
+ const unhandled2 = response.error.kind;
1344
+ return unhandled2;
1253
1345
  }
1254
1346
  if (!response.value.ok)
1255
1347
  return probeFailed(`${response.value.error.code}: ${response.value.error.message}`);
@@ -1306,17 +1398,22 @@ function sleep(ms) {
1306
1398
  return new Promise((resolve) => setTimeout(resolve, ms));
1307
1399
  }
1308
1400
  export {
1309
- DEFAULT_MAX_OWNERS,
1310
- PROTOCOL_VERSION,
1311
- SqlegoClient,
1312
- SqlegoClientError,
1313
- SqlegoTransaction,
1314
- USES_NAMED_PIPES,
1315
- VERSION,
1316
- canonicalFile,
1317
- defaultServerCommand,
1318
- isNamedPipe,
1401
+ unpackedAsarPath,
1402
+ runtimeDirectory,
1403
+ platformPackageName,
1319
1404
  pathsFor,
1320
- platformBinaryNames,
1321
- runtimeDirectory
1405
+ locateServerBinary,
1406
+ localBinaryName,
1407
+ isNamedPipe,
1408
+ defaultServerCommand,
1409
+ canonicalFile,
1410
+ binaryFileName,
1411
+ VERSION,
1412
+ USES_NAMED_PIPES,
1413
+ SqlegoTransaction,
1414
+ SqlegoClientError,
1415
+ SqlegoClient,
1416
+ SUPPORTED_PLATFORMS,
1417
+ PROTOCOL_VERSION,
1418
+ DEFAULT_MAX_OWNERS
1322
1419
  };
@@ -2,9 +2,9 @@
2
2
  * sqlego wire protocol: newline-delimited JSON over a local socket.
3
3
  *
4
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.
5
+ * serializes writer requests on one connection per file. WAL files also have
6
+ * a readonly connection: sockets opting into detached-plain can read committed
7
+ * data without waiting for the writer's open transaction.
8
8
  *
9
9
  * Transactions over the wire are leased, never bare: `begin` opens one bound
10
10
  * to the client's socket, `query`/`run` carry its `txId`, and `commit` or
@@ -51,6 +51,7 @@ export type Request = {
51
51
  op: 'hello';
52
52
  clientVersion: string;
53
53
  protocol: number;
54
+ features?: readonly string[];
54
55
  } | {
55
56
  id: number;
56
57
  op: 'query';
@@ -187,6 +188,7 @@ export type HelloResult = Readonly<{
187
188
  pid: number;
188
189
  /** The pragmas the owner applied on open (its defaults, or its `--pragma` list). */
189
190
  pragmas: readonly string[];
191
+ capabilities: readonly string[];
190
192
  }>;
191
193
  export type StatusResult = Readonly<{
192
194
  file: string;
@@ -195,6 +197,7 @@ export type StatusResult = Readonly<{
195
197
  serverVersion: string;
196
198
  protocol: number;
197
199
  pragmas: readonly string[];
200
+ capabilities: readonly string[];
198
201
  /** Files this owner process serves, this one included. */
199
202
  files: number;
200
203
  clients: number;
@@ -232,25 +235,25 @@ export type Response = {
232
235
  * `undefined` for `undefined`, a function or a symbol, and throws on a cycle
233
236
  * or a `toJSON` that throws; both are this one failure.
234
237
  */
235
- export declare function toJson(value: unknown, indent?: number): import("@noego/trust").Err<{
238
+ export declare function toJson(value: unknown, indent?: number): import("@noego/trust").Ok<string> | import("@noego/trust").Err<{
236
239
  kind: "encode-failed";
237
240
  message: string;
238
- }> | import("@noego/trust").Ok<string>;
241
+ }>;
239
242
  /** One frame: the message's JSON and the newline that ends it. */
240
- export declare function encodeFrame(message: Request | Response): import("@noego/trust").Err<{
243
+ export declare function encodeFrame(message: Request | Response): import("@noego/trust").Ok<string> | import("@noego/trust").Err<{
241
244
  kind: "encode-failed";
242
245
  message: string;
243
- }> | import("@noego/trust").Ok<string>;
246
+ }>;
244
247
  /**
245
248
  * One request frame with its parameters in wire form: every `bigint` and
246
249
  * `Uint8Array` parameter becomes its tag; other values go as they are (the
247
250
  * server validates them). A `bigint` outside the signed 64-bit range is a
248
251
  * `bad-request` here, before anything is sent.
249
252
  */
250
- export declare function encodeRequestFrame(request: Request): import("@noego/trust").Err<{
253
+ export declare function encodeRequestFrame(request: Request): import("@noego/trust").Ok<string> | import("@noego/trust").Err<{
251
254
  kind: "encode-failed";
252
255
  message: string;
253
- }> | import("@noego/trust").Ok<string> | import("@noego/trust").Err<{
256
+ }> | import("@noego/trust").Err<{
254
257
  kind: "bad-request";
255
258
  message: string;
256
259
  }>;
@@ -375,6 +378,7 @@ export declare function parseHelloResult(input: unknown): import("@noego/trust")
375
378
  pid: number;
376
379
  /** The pragmas the owner applied on open (its defaults, or its `--pragma` list). */
377
380
  pragmas: readonly string[];
381
+ capabilities: readonly string[];
378
382
  }>>;
379
383
  export declare function parseBeginResult(input: unknown): import("@noego/trust").Err<Readonly<{
380
384
  kind: "invalid";
@@ -408,6 +412,7 @@ export declare function parseStatusResult(input: unknown): import("@noego/trust"
408
412
  serverVersion: string;
409
413
  protocol: number;
410
414
  pragmas: readonly string[];
415
+ capabilities: readonly string[];
411
416
  /** Files this owner process serves, this one included. */
412
417
  files: number;
413
418
  clients: number;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noego/sqlego",
3
- "version": "0.1.2-dev.1",
3
+ "version": "0.1.2-dev.3",
4
4
  "description": "One owner per SQLite file, many files per owner process. Clients (CLI, Node, Bun) pass SQL over a local socket (Unix) or named pipe (Windows); the owner starts on demand and exits when idle.",
5
5
  "type": "module",
6
6
  "license": "ISC",
@@ -27,7 +27,7 @@
27
27
  "files": [
28
28
  "src",
29
29
  "dist",
30
- "bin",
30
+ "bin/sqlego.cjs",
31
31
  "README.md"
32
32
  ],
33
33
  "scripts": {
@@ -37,6 +37,7 @@
37
37
  "build:lib": "bun scripts/build.ts lib",
38
38
  "build:bin": "bun scripts/build.ts bin",
39
39
  "build:bin:all": "bun scripts/build.ts bin:all",
40
+ "release": "bun scripts/release.ts",
40
41
  "typecheck": "bunx tsc --noEmit",
41
42
  "trust": "trust check src",
42
43
  "test": "bun test"
@@ -48,5 +49,12 @@
48
49
  },
49
50
  "dependencies": {
50
51
  "@noego/trust": "0.5.0-dev.0"
52
+ },
53
+ "optionalDependencies": {
54
+ "@noego/sqlego-darwin-arm64": "0.1.2-dev.3",
55
+ "@noego/sqlego-darwin-x64": "0.1.2-dev.3",
56
+ "@noego/sqlego-linux-x64": "0.1.2-dev.3",
57
+ "@noego/sqlego-linux-arm64": "0.1.2-dev.3",
58
+ "@noego/sqlego-win32-x64": "0.1.2-dev.3"
51
59
  }
52
60
  }
package/src/binary.ts ADDED
@@ -0,0 +1,89 @@
1
+ import path from 'node:path';
2
+ import { Result } from '@noego/trust';
3
+
4
+ /**
5
+ * Where the compiled `sqlego` server binary lives. Pure: every input that
6
+ * touches the outside world (environment, module resolution, the file
7
+ * system) is passed in, so the lookup order can be tested for any platform.
8
+ *
9
+ * Order:
10
+ * 1. `SQLEGO_BIN`, when set.
11
+ * 2. The platform package `@noego/sqlego-<platform>-<arch>`, an optional
12
+ * dependency of `@noego/sqlego` that npm installs only on its own os/cpu.
13
+ * 3. A local build, `bin/sqlego-<platform>-<arch>[.exe]` next to the package
14
+ * (a source checkout after `bun run build`).
15
+ * Only the host's platform name is ever looked for, so a binary built for
16
+ * another platform is never chosen. A path inside an Electron `app.asar`
17
+ * archive is rewritten to `app.asar.unpacked`, where an executable can run.
18
+ */
19
+
20
+ /** The platforms a server binary is published for, as Node names them. */
21
+ export const SUPPORTED_PLATFORMS: readonly string[] = ['darwin-arm64', 'darwin-x64', 'linux-x64', 'linux-arm64', 'win32-x64'];
22
+
23
+ export type BinaryLookup = Readonly<{
24
+ platform: string;
25
+ arch: string;
26
+ /** `process.env.SQLEGO_BIN`. */
27
+ configured: string | undefined;
28
+ /** Absolute path of a package's `package.json`, or null when it is not installed. */
29
+ resolvePackageJson: (name: string) => string | null;
30
+ exists: (file: string) => boolean;
31
+ /** The package's own `bin/` directory, or null when it cannot be located. */
32
+ localBinDirectory: string | null;
33
+ }>;
34
+
35
+ export type BinaryMissing = Readonly<{ kind: 'binary-missing'; message: string }>;
36
+
37
+ /** `@noego/sqlego-<platform>-<arch>`: the package holding this platform's binary. */
38
+ export function platformPackageName(platform: string = process.platform, arch: string = process.arch): string {
39
+ return `@noego/sqlego-${platform}-${arch}`;
40
+ }
41
+
42
+ /** The binary's file name inside its platform package. */
43
+ export function binaryFileName(platform: string = process.platform): string {
44
+ return platform === 'win32' ? 'sqlego.exe' : 'sqlego';
45
+ }
46
+
47
+ /** The binary's file name in a local `bin/` build: platform-qualified, so a foreign build is never mistaken for the host's. */
48
+ export function localBinaryName(platform: string = process.platform, arch: string = process.arch): string {
49
+ return `sqlego-${platform}-${arch}${platform === 'win32' ? '.exe' : ''}`;
50
+ }
51
+
52
+ /**
53
+ * Electron packs `node_modules` into `app.asar`, a read-only archive no
54
+ * executable can be started from; packaging tools unpack native files to
55
+ * `app.asar.unpacked` beside it. A path through `app.asar` is rewritten to
56
+ * the unpacked twin; any other path is returned unchanged.
57
+ */
58
+ export function unpackedAsarPath(file: string): string {
59
+ return file.replace(/([\\/])app\.asar(?=[\\/])/, '$1app.asar.unpacked');
60
+ }
61
+
62
+ export function locateServerBinary(lookup: BinaryLookup): Result<string, BinaryMissing> {
63
+ if (lookup.configured !== undefined && lookup.configured.length > 0) return Result.ok(lookup.configured);
64
+ const name = platformPackageName(lookup.platform, lookup.arch);
65
+ const manifest = lookup.resolvePackageJson(name);
66
+ const looked: string[] = [];
67
+ if (manifest !== null) {
68
+ const fromPackage = unpackedAsarPath(path.join(path.dirname(manifest), binaryFileName(lookup.platform)));
69
+ if (lookup.exists(fromPackage)) return Result.ok(fromPackage);
70
+ looked.push(fromPackage);
71
+ }
72
+ if (lookup.localBinDirectory !== null) {
73
+ const local = unpackedAsarPath(path.join(lookup.localBinDirectory, localBinaryName(lookup.platform, lookup.arch)));
74
+ if (lookup.exists(local)) return Result.ok(local);
75
+ looked.push(local);
76
+ }
77
+ const key = `${lookup.platform}-${lookup.arch}`;
78
+ const supported = SUPPORTED_PLATFORMS.includes(key);
79
+ const reason = !supported
80
+ ? `sqlego publishes no server binary for ${key} (supported: ${SUPPORTED_PLATFORMS.join(', ')})`
81
+ : manifest === null
82
+ ? `the package ${name} is not installed (npm installs it as an optional dependency of @noego/sqlego; it is skipped by --omit=optional / --no-optional, and on a platform that does not match)`
83
+ : `the package ${name} is installed but has no binary`;
84
+ const where = looked.length > 0 ? `; looked in ${looked.join(', ')}` : '';
85
+ return Result.err({
86
+ kind: 'binary-missing',
87
+ message: `no sqlego server binary for ${key}: ${reason}${where}. Reinstall without --omit=optional, or set SQLEGO_BIN to the path of a sqlego binary.`,
88
+ });
89
+ }