@olivia-db/client 0.0.0-stage → 0.1.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/native.js ADDED
@@ -0,0 +1,1200 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ /**
3
+ * Client of OliviaDB's native protocol (`native-protocol.md` of the specification repository),
4
+ * for Node.js: one long-lived connection (TCP, TLS or a Unix socket) carrying many requests at
5
+ * once. Reads are answered as rows: each node's stored key component and value bytes,
6
+ * described by type descriptors the connection receives once; a field is decoded only when it
7
+ * is read (`node.str(f)`, `node.int(f)`, `node.decimal(f)`, ...). Writes are acknowledged with
8
+ * the HTTP API's JSON answer; agent memory and state stay on HTTP (`OliviaDbClient`).
9
+ *
10
+ * const db = await NativeClient.connectTls("localhost", 7655, "token", apiKey, { caFile: "oliviadb-ca.pem" });
11
+ * const rows = await db.get("Customer/C1", { tree: "true" });
12
+ * for (const n of rows.nodes()) {
13
+ * const f = n.desc.field("amount");
14
+ * if (f) console.log(n.desc.typeName, n.decimal(f));
15
+ * }
16
+ * db.close();
17
+ *
18
+ * `Rows.toJson` gives a result as the HTTP API's JSON answer (for debugging and the contract
19
+ * tests, which compare the two). Failures reject with OliviaDbError (an error frame: the HTTP
20
+ * status and problem document) or NativeProtocolError.
21
+ */
22
+ import * as net from "node:net";
23
+ import * as tls from "node:tls";
24
+ import { readFileSync } from "node:fs";
25
+ import { OliviaDbError } from "./index.js";
26
+ const HEADER = 10;
27
+ const MORE = 0x02;
28
+ const OP = {
29
+ HELLO: 0x01,
30
+ READY: 0x02,
31
+ AUTH: 0x03,
32
+ AUTH_OK: 0x04,
33
+ REQUEST: 0x10,
34
+ DESCRIBE: 0x11,
35
+ ROWS: 0x12,
36
+ JSON: 0x13,
37
+ ERROR: 0x14,
38
+ CHANGE: 0x15,
39
+ END: 0x16,
40
+ UNDESCRIBE: 0x17,
41
+ CANCEL: 0x20,
42
+ };
43
+ /** A frame the server sent that this client cannot read (a protocol error). */
44
+ export class NativeProtocolError extends Error {
45
+ }
46
+ const utf8 = new TextDecoder("utf-8", { fatal: true });
47
+ const enc = new TextEncoder();
48
+ function text(b) {
49
+ try {
50
+ return utf8.decode(b);
51
+ }
52
+ catch {
53
+ throw new NativeProtocolError("a string that is not UTF-8");
54
+ }
55
+ }
56
+ // ---- body fields (spec section 2: big-endian integers, LEB128 varints) ----
57
+ class Rd {
58
+ p;
59
+ b;
60
+ constructor(b, p = 0) {
61
+ this.b = b;
62
+ this.p = p;
63
+ }
64
+ take(n) {
65
+ if (n < 0 || this.p + n > this.b.length)
66
+ throw new NativeProtocolError("a frame shorter than its fields");
67
+ const s = this.b.subarray(this.p, this.p + n);
68
+ this.p += n;
69
+ return s;
70
+ }
71
+ u8() {
72
+ return this.take(1)[0];
73
+ }
74
+ u16() {
75
+ const s = this.take(2);
76
+ return (s[0] << 8) | s[1];
77
+ }
78
+ u32() {
79
+ const s = this.take(4);
80
+ return new DataView(s.buffer, s.byteOffset, 4).getUint32(0);
81
+ }
82
+ u64() {
83
+ const s = this.take(8);
84
+ return new DataView(s.buffer, s.byteOffset, 8).getBigUint64(0);
85
+ }
86
+ varint() {
87
+ let v = 0n;
88
+ for (let i = 0; i < 10; i++) {
89
+ const x = this.u8();
90
+ v |= BigInt(x & 0x7f) << BigInt(7 * i);
91
+ if ((x & 0x80) === 0)
92
+ return Number(v);
93
+ }
94
+ throw new NativeProtocolError("a varint longer than 10 bytes");
95
+ }
96
+ lp() {
97
+ return this.take(this.varint());
98
+ }
99
+ str() {
100
+ return text(this.lp());
101
+ }
102
+ done() {
103
+ return this.p === this.b.length;
104
+ }
105
+ }
106
+ function putVarint(out, v) {
107
+ let x = BigInt(v);
108
+ while (x >= 0x80n) {
109
+ out.push(Number(x & 0x7fn) | 0x80);
110
+ x >>= 7n;
111
+ }
112
+ out.push(Number(x));
113
+ }
114
+ function putLp(out, b) {
115
+ putVarint(out, b.length);
116
+ for (const x of b)
117
+ out.push(x);
118
+ }
119
+ function frame(op, stream, body) {
120
+ const f = new Uint8Array(HEADER + body.length);
121
+ const d = new DataView(f.buffer);
122
+ d.setUint32(0, HEADER - 4 + body.length);
123
+ f[4] = op;
124
+ f[5] = 0;
125
+ d.setUint32(6, stream);
126
+ f.set(body, HEADER);
127
+ return f;
128
+ }
129
+ function hex(b) {
130
+ return Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
131
+ }
132
+ export function parseType(t) {
133
+ const bad = () => new NativeProtocolError(`type ${t}`);
134
+ if (t.startsWith("string("))
135
+ return { kind: "string" };
136
+ if (t.startsWith("bytes(") && t.endsWith(")")) {
137
+ const n = Number(t.slice(6, -1));
138
+ if (!Number.isInteger(n))
139
+ throw bad();
140
+ return { kind: "bytes", length: n };
141
+ }
142
+ if (t.startsWith("decimal(") && t.endsWith(")")) {
143
+ const s = Number((t.slice(8, -1).split(",")[1] ?? "0").trim());
144
+ if (!Number.isInteger(s))
145
+ throw bad();
146
+ return { kind: "decimal", scale: s };
147
+ }
148
+ if (t.startsWith("int"))
149
+ return { kind: "int", signed: true };
150
+ if (t.startsWith("uint"))
151
+ return { kind: "int", signed: false };
152
+ switch (t) {
153
+ case "date":
154
+ case "timestamp":
155
+ case "bool":
156
+ case "float64":
157
+ case "text":
158
+ return { kind: t };
159
+ }
160
+ let v;
161
+ try {
162
+ v = JSON.parse(t);
163
+ }
164
+ catch {
165
+ throw bad();
166
+ }
167
+ if (v && typeof v === "object") {
168
+ const o = v;
169
+ if (Array.isArray(o.enum)) {
170
+ return {
171
+ kind: "enum",
172
+ members: o.enum.map((m) => [typeof m.name === "string" ? m.name : "", typeof m.value === "string" ? m.value : ""]),
173
+ };
174
+ }
175
+ if ("ref" in o)
176
+ return { kind: "ref" };
177
+ }
178
+ throw bad();
179
+ }
180
+ /** A type descriptor (spec section 5). */
181
+ export class Desc {
182
+ strs;
183
+ layout;
184
+ typePath;
185
+ bucket;
186
+ ordinal;
187
+ key;
188
+ fixed;
189
+ fields;
190
+ defaults;
191
+ children;
192
+ constructor(layout, typePath, bucket, ordinal, key, fixed, fields, defaults, children) {
193
+ this.layout = layout;
194
+ this.typePath = typePath;
195
+ this.bucket = bucket;
196
+ this.ordinal = ordinal;
197
+ this.key = key;
198
+ this.fixed = fixed;
199
+ this.fields = fields;
200
+ this.defaults = defaults;
201
+ this.children = children;
202
+ // Fixed string(n) fields outside variant cases, by offset (spec section 6.3).
203
+ this.strs = fields
204
+ .filter((f) => !f.caseOf && !f.tail && f.type.kind === "string")
205
+ .map((f) => [f.offset, f.length])
206
+ .sort((a, b) => a[0] - b[0] || a[1] - b[1]);
207
+ }
208
+ /** The node type's name (the last segment of its type path). */
209
+ get typeName() {
210
+ return this.typePath.slice(this.typePath.lastIndexOf("/") + 1);
211
+ }
212
+ /** The aggregate's name. */
213
+ get aggregate() {
214
+ return this.typePath.split("/")[0];
215
+ }
216
+ /** A field by name, to read it from nodes of this descriptor. */
217
+ field(name) {
218
+ return this.fields.find((f) => f.name === name);
219
+ }
220
+ }
221
+ function readField(r) {
222
+ return {
223
+ number: r.varint(),
224
+ name: r.str(),
225
+ type: parseType(r.str()),
226
+ tail: r.u8() === 1,
227
+ offset: r.varint(),
228
+ length: r.varint(),
229
+ scale: r.u8(),
230
+ shown: r.u8(),
231
+ };
232
+ }
233
+ function describe(body) {
234
+ const r = new Rd(body);
235
+ const id = r.varint();
236
+ const layout = `sha256:${hex(r.take(32))}`;
237
+ r.str();
238
+ const typePath = r.str();
239
+ r.u16();
240
+ const bucket = r.u8();
241
+ const ordinal = r.u8() === 1;
242
+ const key = [];
243
+ for (let i = r.varint(); i > 0; i--) {
244
+ const name = r.str();
245
+ const type = parseType(r.str());
246
+ const descending = r.u8() === 1;
247
+ const coll = r.str();
248
+ if (coll !== "" && coll !== "binary") {
249
+ throw new NativeProtocolError(`key collation ${coll}: this client reads binary collations only`);
250
+ }
251
+ key.push({ name, type, descending });
252
+ }
253
+ const fixed = r.varint();
254
+ const fields = [];
255
+ for (let i = r.varint(); i > 0; i--)
256
+ fields.push(readField(r));
257
+ for (let i = r.varint(); i > 0; i--) {
258
+ const disc = r.varint();
259
+ const values = [];
260
+ for (let j = r.varint(); j > 0; j--)
261
+ values.push(r.str());
262
+ for (let j = r.varint(); j > 0; j--)
263
+ fields.push({ ...readField(r), caseOf: { disc, values } });
264
+ }
265
+ const defaults = [];
266
+ for (let i = r.varint(); i > 0; i--) {
267
+ const f = readField(r);
268
+ defaults.push([f, r.lp().slice()]);
269
+ }
270
+ const children = new Map();
271
+ for (let i = r.varint(); i > 0; i--) {
272
+ const c = r.u16();
273
+ children.set(c, r.str());
274
+ }
275
+ return [id, new Desc(layout, typePath, bucket, ordinal, key, fixed, fields, defaults, children)];
276
+ }
277
+ // ---- values ----
278
+ function beInt(b, signed) {
279
+ let v = 0n;
280
+ for (const x of b)
281
+ v = (v << 8n) | BigInt(x);
282
+ if (signed && b.length > 0 && b[0] & 0x80)
283
+ v -= 1n << BigInt(8 * b.length);
284
+ return v;
285
+ }
286
+ /** A packed decimal's unscaled value; undefined when the bytes are not packed decimal. */
287
+ function packed(b) {
288
+ let v = 0n;
289
+ for (let i = 0; i < b.length; i++) {
290
+ const hi = b[i] >> 4;
291
+ const lo = b[i] & 15;
292
+ if (hi > 9)
293
+ return undefined;
294
+ v = v * 10n + BigInt(hi);
295
+ if (i + 1 < b.length) {
296
+ if (lo > 9)
297
+ return undefined;
298
+ v = v * 10n + BigInt(lo);
299
+ }
300
+ else {
301
+ if (lo === 0xc || lo === 0xf || lo === 0xa || lo === 0xe)
302
+ return v;
303
+ if (lo === 0xd || lo === 0xb)
304
+ return -v;
305
+ return undefined;
306
+ }
307
+ }
308
+ return undefined;
309
+ }
310
+ /** A decimal's text with `scale` digits after the point. */
311
+ export function decimalText(unscaled, scale) {
312
+ const digits = (unscaled < 0n ? -unscaled : unscaled).toString();
313
+ let body = digits;
314
+ if (scale > 0) {
315
+ const d = digits.padStart(scale + 1, "0");
316
+ body = `${d.slice(0, d.length - scale)}.${d.slice(d.length - scale)}`;
317
+ }
318
+ return unscaled < 0n ? `-${body}` : body;
319
+ }
320
+ function civil(z0) {
321
+ const z = z0 + 719468;
322
+ const era = Math.floor(z / 146097);
323
+ const doe = z - era * 146097;
324
+ const yoe = Math.floor((doe - Math.floor(doe / 1460) + Math.floor(doe / 36524) - Math.floor(doe / 146096)) / 365);
325
+ const doy = doe - (365 * yoe + Math.floor(yoe / 4) - Math.floor(yoe / 100));
326
+ const mp = Math.floor((5 * doy + 2) / 153);
327
+ const d = doy - Math.floor((153 * mp + 2) / 5) + 1;
328
+ const m = mp < 10 ? mp + 3 : mp - 9;
329
+ return [yoe + era * 400 + (m <= 2 ? 1 : 0), m, d];
330
+ }
331
+ const p2 = (n, w = 2) => n.toString().padStart(w, "0");
332
+ /** `YYYY-MM-DD` of days since 1970-01-01. */
333
+ export function dateText(days) {
334
+ const [y, m, d] = civil(days);
335
+ return `${p2(y, 4)}-${p2(m)}-${p2(d)}`;
336
+ }
337
+ /** `YYYY-MM-DDTHH:MM:SS.ffffffZ` of microseconds since the epoch. */
338
+ export function timestampText(us) {
339
+ const day = 86400000000n;
340
+ let days = us / day;
341
+ let rem = us % day;
342
+ if (rem < 0n) {
343
+ rem += day;
344
+ days -= 1n;
345
+ }
346
+ return `${dateText(Number(days))}T${p2(rem / 3600000000n)}:${p2((rem / 60000000n) % 60n)}:${p2((rem / 1000000n) % 60n)}.${p2(rem % 1000000n, 6)}Z`;
347
+ }
348
+ function intJson(v) {
349
+ const a = v < 0n ? -v : v;
350
+ return a < 1n << 53n ? Number(v) : v.toString();
351
+ }
352
+ function stripPad(s) {
353
+ return s.replace(/ +$/, "");
354
+ }
355
+ // ---- nodes ----
356
+ /** One node of a result: its bytes are views into the frame it came in. */
357
+ export class Node {
358
+ desc;
359
+ depth;
360
+ /** The node's own key component, as stored (`path-keys.md`). */
361
+ key;
362
+ /** The value as received: layout bytes, with the fixed strings trimmed (`trim`). */
363
+ data;
364
+ /** Per fixed string: layout offset, n, offset in data, trimmed length. */
365
+ trim;
366
+ masks;
367
+ /** The granted child listings (a tree read), by type name. */
368
+ lists;
369
+ /** LOOKUP: the indexed node's path. */
370
+ hit;
371
+ /** SEARCH: the parent path and the score. */
372
+ parent;
373
+ score;
374
+ constructor(desc, depth, key, data, trim, masks, lists, hit, parent, score) {
375
+ this.desc = desc;
376
+ this.depth = depth;
377
+ this.key = key;
378
+ this.data = data;
379
+ this.trim = trim;
380
+ this.masks = masks;
381
+ this.lists = lists;
382
+ this.hit = hit;
383
+ this.parent = parent;
384
+ this.score = score;
385
+ }
386
+ span(off, len) {
387
+ if (this.trim.length === 0)
388
+ return off + len <= this.data.length ? this.data.subarray(off, off + len) : undefined;
389
+ const t = this.trim.find((x) => x[0] === off && x[1] === len);
390
+ if (t)
391
+ return this.data.subarray(t[2], t[2] + t[3]);
392
+ const at = this.wireAt(off);
393
+ return at !== undefined && at + len <= this.data.length ? this.data.subarray(at, at + len) : undefined;
394
+ }
395
+ wireAt(off) {
396
+ let at = off;
397
+ for (const [lo, n, wo, k] of this.trim) {
398
+ if (lo + n <= off)
399
+ at = off - (lo + n) + wo + k;
400
+ else if (lo < off)
401
+ return undefined;
402
+ }
403
+ return at;
404
+ }
405
+ tails() {
406
+ const out = [];
407
+ let p = this.wireAt(this.desc.fixed);
408
+ if (p === undefined)
409
+ return out;
410
+ const d = this.data;
411
+ while (p < d.length) {
412
+ let n = 0;
413
+ for (let i = 0; i < 10 && p < d.length; i++) {
414
+ const x = d[p++];
415
+ n += (x & 0x7f) * 2 ** (7 * i);
416
+ if ((x & 0x80) === 0)
417
+ break;
418
+ }
419
+ out.push(d.subarray(p, Math.min(p + n, d.length)));
420
+ p += n;
421
+ }
422
+ return out;
423
+ }
424
+ present(f) {
425
+ if (!f.caseOf)
426
+ return true;
427
+ const c = f.caseOf;
428
+ const x = this.desc.fields.find((y) => y.number === c.disc);
429
+ if (!x)
430
+ return false;
431
+ const b = this.span(x.offset, x.length);
432
+ if (!b)
433
+ return false;
434
+ try {
435
+ return c.values.includes(stripPad(utf8.decode(b)));
436
+ }
437
+ catch {
438
+ return false;
439
+ }
440
+ }
441
+ bytesOf(f) {
442
+ if (f.shown !== 1 || !this.present(f))
443
+ return undefined;
444
+ if (f.tail)
445
+ return this.tails()[f.offset];
446
+ return this.span(f.offset, f.length);
447
+ }
448
+ /** A string, text, enum member or reference field (fixed strings without their padding);
449
+ * a masked field's masked text. Undefined: hidden, or not in this node's variant case. */
450
+ str(f) {
451
+ if (f.shown === 2)
452
+ return this.masks.find(([n]) => n === f.number)?.[1];
453
+ const b = this.bytesOf(f);
454
+ if (!b)
455
+ return undefined;
456
+ let s;
457
+ try {
458
+ s = utf8.decode(b);
459
+ }
460
+ catch {
461
+ return undefined;
462
+ }
463
+ return f.tail ? s : stripPad(s);
464
+ }
465
+ /** An integer field. */
466
+ int(f) {
467
+ if (f.type.kind !== "int")
468
+ return undefined;
469
+ const b = this.bytesOf(f);
470
+ return b && beInt(b, f.type.signed);
471
+ }
472
+ /** A decimal field: the unscaled value and the scale. */
473
+ decimal(f) {
474
+ if (f.type.kind !== "decimal")
475
+ return undefined;
476
+ const b = this.bytesOf(f);
477
+ const v = b && packed(b);
478
+ return v === undefined ? undefined : { unscaled: v, scale: f.type.scale };
479
+ }
480
+ /** A timestamp field: microseconds since 1970-01-01T00:00:00Z. */
481
+ timestamp(f) {
482
+ if (f.type.kind !== "timestamp")
483
+ return undefined;
484
+ const b = this.bytesOf(f);
485
+ return b && beInt(b, true);
486
+ }
487
+ /** A date field: days since 1970-01-01. */
488
+ date(f) {
489
+ if (f.type.kind !== "date")
490
+ return undefined;
491
+ const b = this.bytesOf(f);
492
+ return b && Number(beInt(b, true));
493
+ }
494
+ /** A field's value as the HTTP API's JSON shows it. */
495
+ json(f) {
496
+ if (f.shown === 2)
497
+ return this.str(f);
498
+ const b = this.bytesOf(f);
499
+ if (!b)
500
+ return undefined;
501
+ const t = f.type;
502
+ switch (t.kind) {
503
+ case "string":
504
+ case "text":
505
+ case "ref":
506
+ return this.str(f);
507
+ case "bytes":
508
+ return hex(b);
509
+ case "int":
510
+ return intJson(beInt(b, t.signed));
511
+ case "decimal": {
512
+ const v = packed(b);
513
+ return v === undefined ? undefined : decimalText(v, t.scale);
514
+ }
515
+ case "date":
516
+ return dateText(Number(beInt(b, true)));
517
+ case "timestamp":
518
+ return timestampText(beInt(b, true));
519
+ case "bool":
520
+ return b[0] === 1;
521
+ case "float64": {
522
+ if (b.length !== 8)
523
+ return undefined;
524
+ const x = new DataView(b.buffer, b.byteOffset, 8).getFloat64(0);
525
+ return Number.isFinite(x) ? x : null;
526
+ }
527
+ case "enum": {
528
+ let s;
529
+ try {
530
+ s = stripPad(utf8.decode(b));
531
+ }
532
+ catch {
533
+ return undefined;
534
+ }
535
+ return t.members.find(([, v]) => v === s)?.[0] ?? s;
536
+ }
537
+ }
538
+ }
539
+ /** The node's key parts, decoded from its component (`path-keys.md`, format 2). */
540
+ keyParts() {
541
+ const p = { at: 2 + this.desc.bucket };
542
+ return this.desc.key.map((k) => keyPart(this.key, p, k.type, k.descending));
543
+ }
544
+ /** The ordinal of a twin, as hexadecimal (`~` in paths). */
545
+ ordinal() {
546
+ if (!this.desc.ordinal)
547
+ return undefined;
548
+ const p = { at: 2 + this.desc.bucket };
549
+ for (const k of this.desc.key)
550
+ keyPart(this.key, p, k.type, k.descending);
551
+ return hex(this.key.subarray(p.at, Math.max(p.at, this.key.length - 1)));
552
+ }
553
+ /** The node's level as a path segment (`key,key~ordinal`, percent-encoded). */
554
+ segment() {
555
+ const parts = this.keyParts();
556
+ let s = this.desc.key.map((k, i) => pct(keyText(k.type, parts[i]))).join(",");
557
+ const o = this.ordinal();
558
+ if (o !== undefined)
559
+ s += `~${o}`;
560
+ return s;
561
+ }
562
+ keyJson() {
563
+ const parts = this.keyParts();
564
+ const m = {};
565
+ this.desc.key.forEach((k, i) => (m[k.name] = keyValueJson(k.type, parts[i])));
566
+ const o = this.ordinal();
567
+ if (o !== undefined)
568
+ m["~"] = o;
569
+ return m;
570
+ }
571
+ /** The node as the HTTP API's JSON shows it, under `parent` (a path, "" for a root). */
572
+ toJson(parent, defaults) {
573
+ const fields = {};
574
+ for (const f of this.desc.fields) {
575
+ const v = this.json(f);
576
+ if (v !== undefined)
577
+ fields[f.name] = v;
578
+ }
579
+ if (defaults) {
580
+ for (const [f, b] of this.desc.defaults) {
581
+ if (f.shown === 1) {
582
+ if (f.tail)
583
+ fields[f.name] = "";
584
+ else {
585
+ const n = new Node(this.desc, 0, new Uint8Array(), b, [], [], undefined, undefined, undefined, undefined);
586
+ fields[f.name] = n.json({ ...f, offset: 0 }) ?? null;
587
+ }
588
+ }
589
+ else if (f.shown === 2) {
590
+ fields[f.name] = new TextDecoder().decode(b);
591
+ }
592
+ }
593
+ }
594
+ const seg = this.segment();
595
+ const path = parent === "" ? `${this.desc.aggregate}/${seg}` : `${parent}/${this.desc.typeName}/${seg}`;
596
+ return { fields, key: this.keyJson(), layout: this.desc.layout, path, type: this.desc.typeName };
597
+ }
598
+ }
599
+ function pct(s) {
600
+ let o = "";
601
+ for (const c of enc.encode(s)) {
602
+ const ch = String.fromCharCode(c);
603
+ if (/[A-Za-z0-9]/.test(ch) || "-._:".includes(ch))
604
+ o += ch;
605
+ else
606
+ o += `%${c.toString(16).toUpperCase().padStart(2, "0")}`;
607
+ }
608
+ return o;
609
+ }
610
+ function keyValueJson(t, v) {
611
+ if (t.kind === "enum" && typeof v === "string")
612
+ return t.members.find(([, x]) => x === v)?.[0] ?? v;
613
+ if (typeof v === "bigint") {
614
+ if (t.kind === "decimal")
615
+ return decimalText(v, t.scale);
616
+ if (t.kind === "date")
617
+ return dateText(Number(v));
618
+ if (t.kind === "timestamp")
619
+ return timestampText(v);
620
+ return intJson(v);
621
+ }
622
+ if (typeof v === "number")
623
+ return Number.isFinite(v) ? v : null;
624
+ if (v instanceof Uint8Array)
625
+ return hex(v);
626
+ return v;
627
+ }
628
+ function keyText(t, v) {
629
+ const j = keyValueJson(t, v);
630
+ return typeof j === "string" ? j : JSON.stringify(j);
631
+ }
632
+ /** One key part from a component (`path-keys.md`, format 2, "Part encodings"). */
633
+ function keyPart(b, p, t, desc) {
634
+ const by = (i) => {
635
+ if (i >= b.length)
636
+ throw new NativeProtocolError("a key part shorter than its encoding");
637
+ return desc ? ~b[i] & 0xff : b[i];
638
+ };
639
+ switch (t.kind) {
640
+ case "int":
641
+ case "decimal":
642
+ case "date":
643
+ case "timestamp": {
644
+ const h = by(p.at);
645
+ const n = h >= 0x80 ? h - 0x80 : 0x80 - h;
646
+ let m = 0n;
647
+ for (let i = 0; i < n; i++) {
648
+ const x = by(p.at + 1 + i);
649
+ m = (m << 8n) | BigInt(h >= 0x80 ? x : ~x & 0xff);
650
+ }
651
+ p.at += 1 + n;
652
+ return h >= 0x80 ? m : -m;
653
+ }
654
+ case "float64": {
655
+ let k = 0n;
656
+ for (let i = 0; i < 8; i++)
657
+ k = (k << 8n) | BigInt(by(p.at + i));
658
+ p.at += 8;
659
+ const bits = k >> 63n === 1n ? k & ~(1n << 63n) : ~k & ((1n << 64n) - 1n);
660
+ const dv = new DataView(new ArrayBuffer(8));
661
+ dv.setBigUint64(0, bits);
662
+ return dv.getFloat64(0);
663
+ }
664
+ case "bool":
665
+ return by(p.at++) !== 0;
666
+ case "bytes": {
667
+ const v = new Uint8Array(t.length);
668
+ for (let i = 0; i < t.length; i++)
669
+ v[i] = by(p.at + i);
670
+ p.at += t.length;
671
+ return v;
672
+ }
673
+ case "string":
674
+ case "text":
675
+ case "enum": {
676
+ // Escaped (0x00 as 0x00 0xFF), ended by 0x00 0x01.
677
+ const v = [];
678
+ for (;;) {
679
+ const x = by(p.at);
680
+ if (x === 0) {
681
+ const y = by(p.at + 1);
682
+ p.at += 2;
683
+ if (y === 0x01)
684
+ break;
685
+ v.push(0);
686
+ }
687
+ else {
688
+ v.push(x);
689
+ p.at += 1;
690
+ }
691
+ }
692
+ return text(Uint8Array.from(v));
693
+ }
694
+ default:
695
+ throw new NativeProtocolError("a reference as a key part");
696
+ }
697
+ }
698
+ function entry(r, descs) {
699
+ const id = r.varint();
700
+ if (id === 0)
701
+ return { path: r.str(), hitPath: r.str() };
702
+ const desc = descs.get(id);
703
+ if (!desc)
704
+ throw new NativeProtocolError(`descriptor ${id} not held (protocol error P10)`);
705
+ const depth = r.varint();
706
+ const key = r.lp();
707
+ const data = r.lp();
708
+ const trim = trimmed(desc, data);
709
+ const nf = r.u8();
710
+ let lists;
711
+ if (nf & 1) {
712
+ lists = [];
713
+ for (let n = r.varint(); n > 0; n--)
714
+ lists.push(desc.children.get(r.u16()) ?? "");
715
+ }
716
+ const masks = [];
717
+ if (nf & 2)
718
+ for (let n = r.varint(); n > 0; n--)
719
+ masks.push([r.varint(), r.str()]);
720
+ const parent = nf & 4 ? r.str() : undefined;
721
+ let score;
722
+ if (nf & 8) {
723
+ const dv = new DataView(new ArrayBuffer(4));
724
+ dv.setUint32(0, r.u32());
725
+ score = dv.getFloat32(0);
726
+ }
727
+ const hit = nf & 16 ? r.str() : undefined;
728
+ return { node: new Node(desc, depth, key, data, trim, masks, lists, hit, parent, score) };
729
+ }
730
+ /** Where a value's trimmed fixed strings are (spec section 6.3). */
731
+ export function trimmed(desc, data) {
732
+ const bad = (m) => new NativeProtocolError(`${m} (protocol error P13)`);
733
+ const out = [];
734
+ let p = 0;
735
+ let end = 0;
736
+ for (const [off, n] of desc.strs) {
737
+ p += off - end;
738
+ let k = 0;
739
+ for (let i = 0;; i++) {
740
+ if (i === 10)
741
+ throw bad("a varint longer than 10 bytes");
742
+ if (p >= data.length)
743
+ throw bad("a value that ends before a fixed string");
744
+ const x = data[p++];
745
+ k += (x & 0x7f) * 2 ** (7 * i);
746
+ if ((x & 0x80) === 0)
747
+ break;
748
+ }
749
+ if (k > n)
750
+ throw bad("a trimmed length above the field's");
751
+ if (p + k > data.length)
752
+ throw bad("a value that ends inside a fixed string");
753
+ out.push([off, n, p, k]);
754
+ p += k;
755
+ end = off + n;
756
+ }
757
+ if (data.length < p + Math.max(0, desc.fixed - end))
758
+ throw bad("a value that ends inside the fixed area");
759
+ return out;
760
+ }
761
+ // ---- results ----
762
+ function head(b) {
763
+ const r = new Rd(b);
764
+ const f = r.u8();
765
+ const version = f & 1 ? r.u64() : undefined;
766
+ const next = f & 2 ? r.str() : undefined;
767
+ const base = f & 4 ? r.str() : undefined;
768
+ const applied = f & 8 ? { through: r.u64(), caughtUp: r.u8() === 1 } : undefined;
769
+ const tokens = f & 16 ? r.u64() : undefined;
770
+ return { at: r.p, version, next, base, applied, tokens };
771
+ }
772
+ /** A read's answer: its frames as received, nodes read from them on demand. */
773
+ export class Rows {
774
+ frames = [];
775
+ version;
776
+ /** A listing page's `after` for the next page. */
777
+ next;
778
+ /** The path of the depth-0 nodes' parent. */
779
+ base = "";
780
+ appliedThrough;
781
+ tokens;
782
+ /** Every entry (node, or LOOKUP's path-only entry) in order. */
783
+ *entries() {
784
+ for (const [b, descs] of this.frames) {
785
+ const r = new Rd(b, head(b).at);
786
+ while (!r.done())
787
+ yield entry(r, descs);
788
+ }
789
+ }
790
+ /** The nodes, in order (pre-order for a tree). */
791
+ nodes() {
792
+ const out = [];
793
+ for (const e of this.entries())
794
+ if ("node" in e)
795
+ out.push(e.node);
796
+ return out;
797
+ }
798
+ /** The answer as the HTTP API's JSON for a GET of a node (`listing` false) or a listing. */
799
+ toJson(listing) {
800
+ const paths = [];
801
+ const stack = [];
802
+ const tops = [];
803
+ const attach = () => {
804
+ const [done, tn] = stack.pop();
805
+ const p = stack[stack.length - 1];
806
+ if (!p) {
807
+ tops.push(done);
808
+ return;
809
+ }
810
+ const ch = (p[0].children ??= {});
811
+ (ch[tn] ??= []).push(done);
812
+ };
813
+ for (const n of this.nodes()) {
814
+ const parent = n.depth === 0 ? (n.parent ?? this.base) : paths[n.depth - 1];
815
+ const v = n.toJson(parent, true);
816
+ paths.length = n.depth;
817
+ paths.push(String(v.path));
818
+ while (stack.length > n.depth)
819
+ attach();
820
+ if (n.lists && n.lists.length > 0)
821
+ v.children = Object.fromEntries(n.lists.map((t) => [t, []]));
822
+ stack.push([v, n.desc.typeName]);
823
+ }
824
+ while (stack.length > 0)
825
+ attach();
826
+ const version = this.version === undefined ? null : intJson(this.version);
827
+ if (listing)
828
+ return { next: this.next ?? null, nodes: tops, version };
829
+ const v = tops.pop();
830
+ if (!v)
831
+ throw new NativeProtocolError("a node read without its node");
832
+ v.version = version;
833
+ return v;
834
+ }
835
+ }
836
+ class Queue {
837
+ items = [];
838
+ waiting = [];
839
+ push(v) {
840
+ const w = this.waiting.shift();
841
+ if (w)
842
+ w(v);
843
+ else
844
+ this.items.push(v);
845
+ }
846
+ take() {
847
+ const v = this.items.shift();
848
+ if (v !== undefined)
849
+ return Promise.resolve(v);
850
+ return new Promise((r) => this.waiting.push(r));
851
+ }
852
+ }
853
+ function problem(body) {
854
+ const r = new Rd(body);
855
+ const st = r.u16();
856
+ let p;
857
+ try {
858
+ p = JSON.parse(text(r.lp()));
859
+ }
860
+ catch (e) {
861
+ throw new NativeProtocolError(String(e));
862
+ }
863
+ const s = typeof p.status === "number" && p.status !== 0 ? p.status : st;
864
+ return new OliviaDbError(s, p);
865
+ }
866
+ const ALPN = "oliviadb/1";
867
+ /** A native-protocol connection. Concurrent requests share it, each on its own stream. */
868
+ export class NativeClient {
869
+ streams = new Map();
870
+ nextStream = 3;
871
+ descs = new Map();
872
+ buf = new Uint8Array(0);
873
+ closedWhy;
874
+ handshake = new Queue();
875
+ sock;
876
+ constructor(sock) {
877
+ this.sock = sock;
878
+ sock.setNoDelay?.(true);
879
+ sock.on("data", (d) => this.onData(d));
880
+ sock.on("error", (e) => this.onClose(e.message));
881
+ sock.on("close", () => this.onClose("the server closed the connection"));
882
+ }
883
+ /** Connects over plain TCP (the server serves plain text on loopback only, unless configured
884
+ * otherwise) and authenticates with `scheme` (`token` or `bearer`) and the credential the
885
+ * HTTP Authorization header would carry. */
886
+ static connectTcp(host, port, scheme, credential) {
887
+ return NativeClient.start(net.connect({ host, port }), "connect", scheme, credential);
888
+ }
889
+ /** Connects over TLS (spec `native-protocol.md` section 1): TLS from the first byte, ALPN
890
+ * `oliviadb/1` offered and required, the certificate chain verified against the platform's
891
+ * roots (`tls.getCACertificates("system")`, Node 22.15 and later; earlier Node versions use
892
+ * Node's own roots) or `options.caFile` / `options.ca`, and the server name
893
+ * (`options.serverName`, else `host`) verified against the certificate. Other `options` are
894
+ * passed to `node:tls`. */
895
+ static async connectTls(host, port, scheme, credential, options = {}) {
896
+ const { caFile, serverName, ...rest } = options;
897
+ let ca = rest.ca;
898
+ if (ca === undefined && caFile !== undefined)
899
+ ca = readFileSync(caFile, "utf8");
900
+ if (ca === undefined) {
901
+ const sys = tls.getCACertificates;
902
+ if (sys)
903
+ ca = sys("system");
904
+ }
905
+ const name = serverName ?? rest.servername ?? host;
906
+ const sock = tls.connect({
907
+ ...rest,
908
+ host,
909
+ port,
910
+ ca,
911
+ servername: name,
912
+ ALPNProtocols: [ALPN],
913
+ rejectUnauthorized: true,
914
+ checkServerIdentity: (_h, cert) => tls.checkServerIdentity(name, cert),
915
+ });
916
+ try {
917
+ await new Promise((res, rej) => {
918
+ sock.once("secureConnect", () => res());
919
+ sock.once("error", (e) => rej(new Error(`${host}:${port}: TLS handshake: ${e.message}`)));
920
+ });
921
+ }
922
+ catch (e) {
923
+ sock.destroy();
924
+ throw e;
925
+ }
926
+ if (sock.alpnProtocol !== ALPN) {
927
+ sock.destroy();
928
+ throw new Error(`${host}:${port}: the server selected ALPN ${sock.alpnProtocol || "none"}, not ${ALPN}`);
929
+ }
930
+ return NativeClient.start(sock, null, scheme, credential);
931
+ }
932
+ /** Connects over a Unix socket. */
933
+ static connectUnix(path, scheme, credential) {
934
+ return NativeClient.start(net.connect({ path }), "connect", scheme, credential);
935
+ }
936
+ static async start(sock, ready, scheme, credential) {
937
+ if (ready !== null) {
938
+ await new Promise((res, rej) => {
939
+ sock.once(ready, () => res());
940
+ sock.once("error", rej);
941
+ });
942
+ }
943
+ const c = new NativeClient(sock);
944
+ // HELLO and AUTH together (spec section 3), then READY and AUTH_OK.
945
+ const hello = [0, 1, 0, 1];
946
+ putVarint(hello, 1);
947
+ putLp(hello, enc.encode("client"));
948
+ putLp(hello, enc.encode("oliviadb-js 0.1.0"));
949
+ const auth = [];
950
+ putLp(auth, enc.encode(scheme));
951
+ putLp(auth, enc.encode(credential));
952
+ sock.write(frame(OP.HELLO, 1, hello));
953
+ sock.write(frame(OP.AUTH, 1, auth));
954
+ for (const want of [OP.READY, OP.AUTH_OK]) {
955
+ const [o, body] = await c.handshake.take();
956
+ if (o === -1) {
957
+ sock.destroy();
958
+ throw new Error(`closed during the handshake: ${text(body)}`);
959
+ }
960
+ if (o === OP.ERROR) {
961
+ sock.destroy();
962
+ throw problem(body);
963
+ }
964
+ if (o !== want) {
965
+ sock.destroy();
966
+ throw new NativeProtocolError(`opcode 0x${o.toString(16).padStart(2, "0")} in the handshake`);
967
+ }
968
+ }
969
+ c.handshake = undefined;
970
+ return c;
971
+ }
972
+ onData(d) {
973
+ const b = new Uint8Array(this.buf.length + d.length);
974
+ b.set(this.buf);
975
+ b.set(d, this.buf.length);
976
+ let p = 0;
977
+ try {
978
+ while (b.length - p >= 4) {
979
+ const len = new DataView(b.buffer, b.byteOffset + p, 4).getUint32(0);
980
+ if (len < 6)
981
+ throw new NativeProtocolError("a frame shorter than its header");
982
+ if (b.length - p < 4 + len)
983
+ break;
984
+ const op = b[p + 4];
985
+ const flags = b[p + 5];
986
+ const stream = new DataView(b.buffer, b.byteOffset + p + 6, 4).getUint32(0);
987
+ const body = b.slice(p + HEADER, p + 4 + len);
988
+ p += 4 + len;
989
+ this.dispatch(op, flags, stream, body);
990
+ }
991
+ }
992
+ catch (e) {
993
+ this.sock.destroy();
994
+ this.onClose(String(e instanceof Error ? e.message : e));
995
+ return;
996
+ }
997
+ this.buf = b.slice(p);
998
+ }
999
+ /** Frames to their streams, descriptors kept in arrival order. */
1000
+ dispatch(op, flags, stream, body) {
1001
+ if (this.handshake) {
1002
+ this.handshake.push([op, body]);
1003
+ return;
1004
+ }
1005
+ if (op === OP.DESCRIBE) {
1006
+ const [id, d] = describe(body);
1007
+ const m = new Map(this.descs);
1008
+ m.set(id, d);
1009
+ this.descs = m;
1010
+ }
1011
+ else if (op === OP.UNDESCRIBE) {
1012
+ const m = new Map(this.descs);
1013
+ m.delete(new Rd(body).varint());
1014
+ this.descs = m;
1015
+ }
1016
+ else {
1017
+ this.streams.get(stream)?.push({ op, flags, body, descs: this.descs });
1018
+ }
1019
+ }
1020
+ onClose(why) {
1021
+ if (this.closedWhy !== undefined)
1022
+ return;
1023
+ this.closedWhy = why;
1024
+ this.handshake?.push([-1, enc.encode(why)]);
1025
+ for (const q of this.streams.values())
1026
+ q.push({ closed: why });
1027
+ }
1028
+ send(route, path, params, body) {
1029
+ const s = this.nextStream;
1030
+ this.nextStream += 2;
1031
+ const q = new Queue();
1032
+ this.streams.set(s, q);
1033
+ if (this.closedWhy !== undefined) {
1034
+ q.push({ closed: this.closedWhy });
1035
+ return [s, q];
1036
+ }
1037
+ const b = [route];
1038
+ putLp(b, enc.encode(path));
1039
+ const keys = Object.keys(params).sort();
1040
+ putVarint(b, keys.length);
1041
+ for (const k of keys) {
1042
+ putLp(b, enc.encode(k));
1043
+ putLp(b, enc.encode(params[k]));
1044
+ }
1045
+ putLp(b, body);
1046
+ this.sock.write(frame(OP.REQUEST, s, b));
1047
+ return [s, q];
1048
+ }
1049
+ async rows(route, path, params, body) {
1050
+ const [s, q] = this.send(route, path, params, body);
1051
+ try {
1052
+ const rows = new Rows();
1053
+ for (;;) {
1054
+ const r = await q.take();
1055
+ if ("closed" in r)
1056
+ throw new Error(r.closed);
1057
+ if (r.op === OP.ROWS) {
1058
+ const h = head(r.body);
1059
+ if (h.base !== undefined)
1060
+ rows.base = h.base;
1061
+ rows.frames.push([r.body, r.descs]);
1062
+ if ((r.flags & MORE) === 0) {
1063
+ rows.version = h.version;
1064
+ rows.next = h.next;
1065
+ rows.appliedThrough = h.applied;
1066
+ rows.tokens = h.tokens;
1067
+ return rows;
1068
+ }
1069
+ }
1070
+ else if (r.op === OP.ERROR) {
1071
+ throw problem(r.body);
1072
+ }
1073
+ else {
1074
+ throw new NativeProtocolError(`opcode 0x${r.op.toString(16)} in a result`);
1075
+ }
1076
+ }
1077
+ }
1078
+ finally {
1079
+ this.streams.delete(s);
1080
+ }
1081
+ }
1082
+ /** `GET /v1/aggregates/{path}` (a node, `tree=true` with `each`, or a listing page). */
1083
+ get(path, params = {}) {
1084
+ return this.rows(0x01, path, params, new Uint8Array());
1085
+ }
1086
+ /** `GET /v1/lookup/{index}`. */
1087
+ lookup(index, params = {}) {
1088
+ return this.rows(0x02, index, params, new Uint8Array());
1089
+ }
1090
+ /** `POST /v1/search/{aggregate}` with the HTTP body. */
1091
+ search(aggregate, body) {
1092
+ return this.rows(0x03, aggregate, {}, enc.encode(JSON.stringify(body)));
1093
+ }
1094
+ async json(route, path, params, body) {
1095
+ const [s, q] = this.send(route, path, params, enc.encode(JSON.stringify(body)));
1096
+ try {
1097
+ const r = await q.take();
1098
+ if ("closed" in r)
1099
+ throw new Error(r.closed);
1100
+ if (r.op === OP.JSON) {
1101
+ const d = new Rd(r.body);
1102
+ const st = d.u16();
1103
+ return [st, JSON.parse(text(d.lp()))];
1104
+ }
1105
+ if (r.op === OP.ERROR)
1106
+ throw problem(r.body);
1107
+ throw new NativeProtocolError(`opcode 0x${r.op.toString(16)} for a write`);
1108
+ }
1109
+ finally {
1110
+ this.streams.delete(s);
1111
+ }
1112
+ }
1113
+ /** `POST /v1/txn`: the HTTP route's status and answer. */
1114
+ txn(body) {
1115
+ return this.json(0x04, "", {}, body);
1116
+ }
1117
+ /** `POST`, `PATCH` or `DELETE /v1/aggregates/{path}`: the status and the JSON answer. */
1118
+ write(method, path, body) {
1119
+ return this.json(0x05, path, { method }, body);
1120
+ }
1121
+ /** The change stream of native aggregates under `paths`, from a position (`start`, `now` or
1122
+ * a record's): its records as they come, until the iteration stops (the stream is then
1123
+ * cancelled). */
1124
+ async *changes(paths, from) {
1125
+ const [s, q] = this.send(0x06, "", { path: paths.join(" "), from }, new Uint8Array());
1126
+ try {
1127
+ for (;;) {
1128
+ const r = await q.take();
1129
+ if ("closed" in r)
1130
+ throw new Error(r.closed);
1131
+ if (r.op === OP.CHANGE)
1132
+ yield new Change(r.body, r.descs);
1133
+ else if (r.op === OP.END)
1134
+ return;
1135
+ else if (r.op === OP.ERROR)
1136
+ throw problem(r.body);
1137
+ else
1138
+ throw new NativeProtocolError(`opcode 0x${r.op.toString(16)} in a change stream`);
1139
+ }
1140
+ }
1141
+ finally {
1142
+ const c = new Uint8Array(4);
1143
+ new DataView(c.buffer).setUint32(0, s);
1144
+ if (this.closedWhy === undefined)
1145
+ this.sock.write(frame(OP.CANCEL, 0, c));
1146
+ this.streams.delete(s);
1147
+ }
1148
+ }
1149
+ close() {
1150
+ this.sock.destroy();
1151
+ }
1152
+ }
1153
+ /** One change record. */
1154
+ export class Change {
1155
+ body;
1156
+ descs;
1157
+ constructor(body, descs) {
1158
+ this.body = body;
1159
+ this.descs = descs;
1160
+ }
1161
+ /** The record as the HTTP change stream's JSON object. */
1162
+ toJson() {
1163
+ const r = new Rd(this.body);
1164
+ const cflags = r.u8();
1165
+ const position = r.str();
1166
+ const version = r.u64();
1167
+ const op = { 1: "insert", 2: "replace", 3: "delete" }[r.u8()];
1168
+ if (!op)
1169
+ throw new NativeProtocolError("change op");
1170
+ const id = hex(r.take(16));
1171
+ const parent = r.str();
1172
+ const sides = [];
1173
+ for (const bit of [1, 2]) {
1174
+ if (cflags & bit) {
1175
+ const e = entry(r, this.descs);
1176
+ if (!("node" in e))
1177
+ throw new NativeProtocolError("an entry in a change");
1178
+ sides.push([bit, e.node.toJson(parent, false), e.node.desc]);
1179
+ }
1180
+ }
1181
+ const last = sides[sides.length - 1];
1182
+ if (!last)
1183
+ throw new NativeProtocolError("a change without a node");
1184
+ const [, lv, ld] = last;
1185
+ const rec = {
1186
+ key: id,
1187
+ position,
1188
+ collection: ld.aggregate,
1189
+ path: lv.path,
1190
+ type: ld.typeName,
1191
+ node_key: lv.key,
1192
+ op,
1193
+ version: intJson(version),
1194
+ layout: lv.layout,
1195
+ };
1196
+ for (const [bit, v] of sides)
1197
+ rec[bit === 1 ? "before" : "after"] = v.fields;
1198
+ return rec;
1199
+ }
1200
+ }