@nowledge/hawdb-bun 0.0.0-stage → 0.31.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/src/index.ts ADDED
@@ -0,0 +1,956 @@
1
+ /*
2
+ * Copyright 2026 Nowledge
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ import { CString, openNativeLibrary, type NativeLibrary, type NativePointer } from "./native.ts";
18
+ import { parseLosslessJson, stringifyParameters } from "./json.ts";
19
+ import { resolvePrebuiltLibrary } from "./platform.ts";
20
+
21
+ export {
22
+ PLATFORM_PACKAGES,
23
+ UnsupportedPlatformError,
24
+ platformPackageName,
25
+ resolvePrebuiltLibrary,
26
+ selectPlatformPackage,
27
+ type PlatformPackage,
28
+ } from "./platform.ts";
29
+
30
+ const encoder = new TextEncoder();
31
+ const databaseConstructorToken = Symbol("HawDB Database constructor");
32
+
33
+ export type TaggedHawDBValue =
34
+ | { $decimal: string }
35
+ | { $uuid: string }
36
+ | { $date: string }
37
+ | { $localtime: string }
38
+ | { $localdatetime: string }
39
+ | { $datetime: string }
40
+ | { $duration: string }
41
+ | { $vector: number[] };
42
+
43
+ export type HawDBValue =
44
+ | null
45
+ | boolean
46
+ | number
47
+ | bigint
48
+ | string
49
+ | Uint8Array
50
+ | TaggedHawDBValue
51
+ | HawDBValue[]
52
+ | { [key: string]: HawDBValue };
53
+
54
+ export type HawDBParameter = HawDBValue;
55
+
56
+ /** WAL synchronization policy; see the C ABI `hawdb_open` documentation. */
57
+ export type Durability = "sync_on_every_write" | "sync_on_checkpoint";
58
+
59
+ /**
60
+ * Options for `HawDBLibrary.open`. Each key mirrors one `hawdb_open` option;
61
+ * an absent or `undefined` key keeps the native default (power-loss-safe
62
+ * `sync_on_every_write`, no row ceiling, a 64 MiB read payload budget and the
63
+ * monotonic-append fast path off). The native library validates every value.
64
+ */
65
+ export interface OpenOptions {
66
+ readOnly?: boolean;
67
+ durability?: Durability;
68
+ /** Host-wide read row ceiling; `0` and `null` mean no row ceiling. */
69
+ maxReadResultRows?: number | bigint | null;
70
+ /** Host-wide read result payload budget in bytes; must be positive. */
71
+ maxReadResultPayloadBytes?: number | bigint;
72
+ relationalMonotonicAppendFastPath?: boolean;
73
+ }
74
+
75
+ const openOptionKeys: Record<keyof OpenOptions, string> = {
76
+ readOnly: "read_only",
77
+ durability: "durability",
78
+ maxReadResultRows: "max_read_result_rows",
79
+ maxReadResultPayloadBytes: "max_read_result_payload_bytes",
80
+ relationalMonotonicAppendFastPath: "relational_monotonic_append_fast_path",
81
+ };
82
+
83
+ function nativeOpenOptions(options: OpenOptions): Record<string, HawDBParameter> {
84
+ if (options === null || typeof options !== "object" || Array.isArray(options)) {
85
+ throw new TypeError("HawDB open options must be an object");
86
+ }
87
+ const native: Record<string, HawDBParameter> = {};
88
+ for (const key of Object.keys(options)) {
89
+ if (!Object.hasOwn(openOptionKeys, key)) {
90
+ throw new HawDBError(
91
+ "invalid_argument",
92
+ `unknown HawDB open option "${key}"; supported options are ${Object.keys(openOptionKeys).join(", ")}`,
93
+ );
94
+ }
95
+ const value = (options as Record<string, unknown>)[key];
96
+ if (value !== undefined) {
97
+ native[openOptionKeys[key as keyof OpenOptions]] = value as HawDBParameter;
98
+ }
99
+ }
100
+ return native;
101
+ }
102
+
103
+ /** An unsigned 64-bit count: `number` when safe, otherwise `bigint`. */
104
+ export type Count = number | bigint;
105
+
106
+ /** `database.backup` result; `library.restore` returns the same fields. */
107
+ export interface BackupReport {
108
+ generation: Count;
109
+ checkpoint_commit_epoch: Count;
110
+ file_count: Count;
111
+ total_bytes: Count;
112
+ manifest_checksum: Count;
113
+ }
114
+
115
+ export type RestoreReport = BackupReport;
116
+
117
+ /** `database.scrub` result. */
118
+ export interface ScrubReport {
119
+ generation: Count;
120
+ checked_file_count: Count;
121
+ checked_bytes: Count;
122
+ sha256_verified_file_count: Count;
123
+ wal_record_count: Count;
124
+ wal_bytes: Count;
125
+ }
126
+
127
+ /** `database.export` result; see docs/LOGICAL_DUMP.md. */
128
+ export interface ExportReport {
129
+ dump_format_version: number;
130
+ persistent_format_version: number;
131
+ hawdb_version: string;
132
+ branch: string | null;
133
+ commit_epoch: Count;
134
+ table_count: Count;
135
+ table_row_count: Count;
136
+ node_count: Count;
137
+ relationship_count: Count;
138
+ file_count: Count;
139
+ total_bytes: Count;
140
+ manifest_sha256: string;
141
+ }
142
+
143
+ /** `library.import` result; see docs/LOGICAL_DUMP.md. */
144
+ export interface ImportReport {
145
+ dump_format_version: number;
146
+ source_hawdb_version: string;
147
+ source_persistent_format_version: number;
148
+ persistent_format_version: number;
149
+ table_count: Count;
150
+ table_row_count: Count;
151
+ node_count: Count;
152
+ relationship_count: Count;
153
+ file_count: Count;
154
+ total_bytes: Count;
155
+ manifest_sha256: string;
156
+ }
157
+
158
+ /** `library.verifyDump` result; see docs/LOGICAL_DUMP.md. */
159
+ export interface VerifyReport {
160
+ dump_format_version: number;
161
+ source_hawdb_version: string;
162
+ source_persistent_format_version: number;
163
+ branch: string | null;
164
+ commit_epoch: Count;
165
+ table_count: Count;
166
+ table_row_count: Count;
167
+ node_count: Count;
168
+ relationship_count: Count;
169
+ file_count: Count;
170
+ total_bytes: Count;
171
+ manifest_sha256: string;
172
+ }
173
+
174
+ /** The fields a report must carry: unsigned counts, and optionally strings. */
175
+ type ReportFields = readonly string[] | { counts: readonly string[]; strings: readonly string[] };
176
+
177
+ function parseReport<T>(text: string | null, fields: ReportFields): T {
178
+ if (text === null) {
179
+ throw new HawDBError("ffi", "HawDB call returned no report");
180
+ }
181
+ const counts = Array.isArray(fields) ? fields : (fields as { counts: readonly string[] }).counts;
182
+ const strings = Array.isArray(fields) ? [] : (fields as { strings: readonly string[] }).strings;
183
+ const report = parseLosslessJson(text);
184
+ if (
185
+ report === null ||
186
+ Array.isArray(report) ||
187
+ typeof report !== "object" ||
188
+ !counts.every((field) => typeof report[field] === "number" || typeof report[field] === "bigint") ||
189
+ !strings.every((field) => typeof report[field] === "string")
190
+ ) {
191
+ throw new TypeError("HawDB returned a malformed report");
192
+ }
193
+ return report as T;
194
+ }
195
+
196
+ const backupReportFields = [
197
+ "generation",
198
+ "checkpoint_commit_epoch",
199
+ "file_count",
200
+ "total_bytes",
201
+ "manifest_checksum",
202
+ ] as const;
203
+ const scrubReportFields = [
204
+ "generation",
205
+ "checked_file_count",
206
+ "checked_bytes",
207
+ "sha256_verified_file_count",
208
+ "wal_record_count",
209
+ "wal_bytes",
210
+ ] as const;
211
+ const exportReportFields = {
212
+ counts: [
213
+ "dump_format_version",
214
+ "persistent_format_version",
215
+ "commit_epoch",
216
+ "table_count",
217
+ "table_row_count",
218
+ "node_count",
219
+ "relationship_count",
220
+ "file_count",
221
+ "total_bytes",
222
+ ],
223
+ strings: ["hawdb_version", "manifest_sha256"],
224
+ } as const;
225
+ const verifyReportFields = {
226
+ counts: [
227
+ "dump_format_version",
228
+ "source_persistent_format_version",
229
+ "commit_epoch",
230
+ "table_count",
231
+ "table_row_count",
232
+ "node_count",
233
+ "relationship_count",
234
+ "file_count",
235
+ "total_bytes",
236
+ ],
237
+ strings: ["source_hawdb_version", "manifest_sha256"],
238
+ } as const;
239
+ const importReportFields = {
240
+ counts: [
241
+ "dump_format_version",
242
+ "source_persistent_format_version",
243
+ "persistent_format_version",
244
+ "table_count",
245
+ "table_row_count",
246
+ "node_count",
247
+ "relationship_count",
248
+ "file_count",
249
+ "total_bytes",
250
+ ],
251
+ strings: ["source_hawdb_version", "manifest_sha256"],
252
+ } as const;
253
+
254
+ export class QueryResult {
255
+ constructor(
256
+ public readonly columns: string[],
257
+ public readonly rows: HawDBValue[][],
258
+ ) {}
259
+
260
+ dicts(): Array<Record<string, HawDBValue>> {
261
+ return this.rows.map((row) =>
262
+ Object.fromEntries(this.columns.map((column, index) => [column, row[index] ?? null])),
263
+ );
264
+ }
265
+ }
266
+
267
+ export class HawDBError extends Error {
268
+ public readonly details: Record<string, unknown>;
269
+
270
+ constructor(
271
+ public readonly kind: string,
272
+ message: string,
273
+ details: Record<string, unknown> = {},
274
+ ) {
275
+ super(message);
276
+ this.name = "HawDBError";
277
+ this.details = details;
278
+ }
279
+ }
280
+
281
+ function outputBuffer(): BigUint64Array {
282
+ // HawdbBuffer is { char *ptr; uintptr_t len }. Bun is 64-bit on every
283
+ // supported host, and BigUint64Array supplies the required alignment.
284
+ return new BigUint64Array(2);
285
+ }
286
+
287
+ function decodeBase64(encoded: string): Uint8Array {
288
+ const binary = atob(encoded);
289
+ return Uint8Array.from(binary, (character) => character.charCodeAt(0));
290
+ }
291
+
292
+ function normalizeValue(value: unknown): HawDBValue {
293
+ if (
294
+ value === null ||
295
+ typeof value === "boolean" ||
296
+ typeof value === "number" ||
297
+ typeof value === "bigint" ||
298
+ typeof value === "string"
299
+ ) {
300
+ return value;
301
+ }
302
+ if (Array.isArray(value)) {
303
+ return value.map(normalizeValue);
304
+ }
305
+ if (typeof value !== "object") {
306
+ throw new TypeError("HawDB returned an unsupported JSON value");
307
+ }
308
+ const entries = Object.entries(value);
309
+ if (entries.length === 1 && entries[0][0] === "$binary" && typeof entries[0][1] === "string") {
310
+ return decodeBase64(entries[0][1]);
311
+ }
312
+ return Object.fromEntries(entries.map(([key, child]) => [key, normalizeValue(child)]));
313
+ }
314
+
315
+ function parseResult(text: string): QueryResult {
316
+ const envelope = parseLosslessJson(text);
317
+ if (envelope === null || Array.isArray(envelope) || typeof envelope !== "object") {
318
+ throw new TypeError("HawDB returned a malformed result envelope");
319
+ }
320
+ const columns = envelope.columns;
321
+ const rows = envelope.rows;
322
+ if (!Array.isArray(columns) || !Array.isArray(rows)) {
323
+ throw new TypeError("HawDB returned a malformed result envelope");
324
+ }
325
+ const normalizedColumns = columns.map((column) => {
326
+ if (typeof column !== "string") {
327
+ throw new TypeError("HawDB returned a malformed result envelope");
328
+ }
329
+ return column;
330
+ });
331
+ const normalizedRows = rows.map((row) => {
332
+ if (!Array.isArray(row) || row.length !== normalizedColumns.length) {
333
+ throw new TypeError("HawDB returned a malformed result envelope");
334
+ }
335
+ return row.map(normalizeValue);
336
+ });
337
+ return new QueryResult(normalizedColumns, normalizedRows);
338
+ }
339
+
340
+ export class HawDBLibrary {
341
+ private readonly native: NativeLibrary;
342
+ private readonly finalizer: FinalizationRegistry<NativePointer>;
343
+ private readonly handles = new Map<NativePointer, symbol>();
344
+ private closed = false;
345
+
346
+ private constructor(path: string) {
347
+ this.native = openNativeLibrary(path);
348
+ this.finalizer = new FinalizationRegistry((handle) => {
349
+ if (!this.closed) {
350
+ this.native.symbols.hawdb_close(handle);
351
+ this.handles.delete(handle);
352
+ }
353
+ });
354
+ }
355
+
356
+ static load(path: string): HawDBLibrary {
357
+ if (path.length === 0) {
358
+ throw new TypeError("HawDB shared-library path must not be empty");
359
+ }
360
+ return new HawDBLibrary(path);
361
+ }
362
+
363
+ private assertOpen(): void {
364
+ if (this.closed) {
365
+ throw new HawDBError("closed", "HawDB shared library is closed");
366
+ }
367
+ }
368
+
369
+ private takeBuffer(buffer: BigUint64Array): string | null {
370
+ const address = buffer[0];
371
+ const length = buffer[1];
372
+ if (address === 0n) {
373
+ if (length !== 0n) {
374
+ throw new TypeError("HawDB returned a NULL buffer with a non-zero length");
375
+ }
376
+ return null;
377
+ }
378
+ try {
379
+ if (length > BigInt(Number.MAX_SAFE_INTEGER)) {
380
+ throw new RangeError("HawDB returned a buffer too large for JavaScript");
381
+ }
382
+ return String(new CString(address, 0, Number(length)));
383
+ } finally {
384
+ this.native.symbols.hawdb_buffer_free(buffer);
385
+ }
386
+ }
387
+
388
+ private errorFrom(buffer: BigUint64Array, fallback: string): HawDBError {
389
+ const text = this.takeBuffer(buffer);
390
+ if (text === null) {
391
+ return new HawDBError("ffi", fallback);
392
+ }
393
+ try {
394
+ const value = parseLosslessJson(text);
395
+ if (value !== null && !Array.isArray(value) && typeof value === "object") {
396
+ const kind = typeof value.kind === "string" ? value.kind : "ffi";
397
+ const message = typeof value.message === "string" ? value.message : fallback;
398
+ return new HawDBError(kind, message, value as Record<string, unknown>);
399
+ }
400
+ } catch {
401
+ // Preserve the native payload below when an older library did not return JSON.
402
+ }
403
+ return new HawDBError("ffi", text);
404
+ }
405
+
406
+ private opened(handle: NativePointer | null): Database {
407
+ if (!handle) {
408
+ throw new HawDBError("ffi", "HawDB returned a NULL database without an error");
409
+ }
410
+ const database = new Database(this, handle, databaseConstructorToken);
411
+ this.handles.set(handle, Symbol("HawDB database lifetime"));
412
+ this.finalizer.register(database, handle, database);
413
+ return database;
414
+ }
415
+
416
+ open(path: string, options: OpenOptions = {}): Database {
417
+ this.assertOpen();
418
+ if (path.length === 0) {
419
+ throw new TypeError("HawDB database path must not be empty");
420
+ }
421
+ const pathBytes = encoder.encode(path);
422
+ const optionsBytes = encoder.encode(stringifyParameters(nativeOpenOptions(options)));
423
+ const error = outputBuffer();
424
+ this.assertOpen();
425
+ const handle = this.native.symbols.hawdb_open(
426
+ pathBytes,
427
+ pathBytes,
428
+ optionsBytes,
429
+ optionsBytes,
430
+ error,
431
+ );
432
+ if (!handle) {
433
+ throw this.errorFrom(error, "HawDB open failed");
434
+ }
435
+ const unexpected = this.takeBuffer(error);
436
+ if (unexpected !== null) {
437
+ this.native.symbols.hawdb_close(handle);
438
+ throw new HawDBError("ffi", `HawDB open succeeded with an error payload: ${unexpected}`);
439
+ }
440
+ return this.opened(handle);
441
+ }
442
+
443
+ openInMemory(): Database {
444
+ this.assertOpen();
445
+ const error = outputBuffer();
446
+ const handle = this.native.symbols.hawdb_open_in_memory(error);
447
+ if (!handle) {
448
+ throw this.errorFrom(error, "HawDB in-memory open failed");
449
+ }
450
+ const unexpected = this.takeBuffer(error);
451
+ if (unexpected !== null) {
452
+ this.native.symbols.hawdb_close(handle);
453
+ throw new HawDBError("ffi", `HawDB in-memory open succeeded with an error payload: ${unexpected}`);
454
+ }
455
+ return this.opened(handle);
456
+ }
457
+
458
+ version(): string {
459
+ this.assertOpen();
460
+ const output = outputBuffer();
461
+ this.native.symbols.hawdb_version(output);
462
+ const version = this.takeBuffer(output);
463
+ if (version === null) {
464
+ throw new HawDBError("ffi", "HawDB returned no version string");
465
+ }
466
+ return version;
467
+ }
468
+
469
+ query(
470
+ handle: NativePointer,
471
+ sql: boolean,
472
+ statement: string,
473
+ parameters: Record<string, HawDBParameter> | HawDBParameter[],
474
+ transaction = false,
475
+ ): QueryResult {
476
+ this.assertOpen();
477
+ const lifetime = this.handles.get(handle);
478
+ if (lifetime === undefined) {
479
+ throw new HawDBError("invalid_handle", "HawDB database handle is not live");
480
+ }
481
+ if (statement.length === 0) {
482
+ throw new TypeError("HawDB statement must not be empty");
483
+ }
484
+ const statementBytes = encoder.encode(statement);
485
+ const parameterBytes = encoder.encode(stringifyParameters(parameters));
486
+ const result = outputBuffer();
487
+ const error = outputBuffer();
488
+ const symbols = this.native.symbols;
489
+ const call = transaction
490
+ ? sql
491
+ ? symbols.hawdb_transaction_query_sql
492
+ : symbols.hawdb_transaction_query
493
+ : sql
494
+ ? symbols.hawdb_query_sql
495
+ : symbols.hawdb_query;
496
+ // Getters may close this database and open another at the same address.
497
+ this.assertOpen();
498
+ if (this.handles.get(handle) !== lifetime) {
499
+ throw new HawDBError("invalid_handle", "HawDB database handle is not live");
500
+ }
501
+ const ok = call(
502
+ handle,
503
+ statementBytes,
504
+ statementBytes,
505
+ parameterBytes,
506
+ parameterBytes,
507
+ result,
508
+ error,
509
+ );
510
+ if (!ok) {
511
+ this.takeBuffer(result);
512
+ throw this.errorFrom(error, "HawDB query failed");
513
+ }
514
+ const unexpected = this.takeBuffer(error);
515
+ const text = this.takeBuffer(result);
516
+ if (unexpected !== null) {
517
+ throw new HawDBError("ffi", `HawDB query succeeded with an error payload: ${unexpected}`);
518
+ }
519
+ if (text === null) {
520
+ throw new HawDBError("ffi", "HawDB query returned no result payload");
521
+ }
522
+ return parseResult(text);
523
+ }
524
+
525
+ /** The engine-wide persistent format version of the loaded library. */
526
+ formatVersion(): number {
527
+ this.assertOpen();
528
+ return this.native.symbols.hawdb_format_version();
529
+ }
530
+
531
+ /** The newest logical dump format version the loaded library reads. */
532
+ dumpFormatVersion(): number {
533
+ this.assertOpen();
534
+ return this.native.symbols.hawdb_dump_format_version();
535
+ }
536
+
537
+ /** Begin, commit or roll back the handle's transaction. */
538
+ transactionControl(handle: NativePointer, action: "begin" | "commit" | "rollback"): void {
539
+ this.assertOpen();
540
+ if (!this.handles.has(handle)) {
541
+ throw new HawDBError("invalid_handle", "HawDB database handle is not live");
542
+ }
543
+ const result = outputBuffer();
544
+ const error = outputBuffer();
545
+ const symbols = this.native.symbols;
546
+ const ok =
547
+ action === "begin"
548
+ ? symbols.hawdb_begin_transaction(handle, error)
549
+ : action === "commit"
550
+ ? symbols.hawdb_commit_transaction(handle, result, error)
551
+ : symbols.hawdb_rollback_transaction(handle, error);
552
+ // The commit envelope carries no rows a caller needs; release it.
553
+ this.takeBuffer(result);
554
+ if (!ok) {
555
+ throw this.errorFrom(error, `HawDB transaction ${action} failed`);
556
+ }
557
+ const unexpected = this.takeBuffer(error);
558
+ if (unexpected !== null) {
559
+ throw new HawDBError("ffi", `HawDB transaction ${action} succeeded with an error payload: ${unexpected}`);
560
+ }
561
+ }
562
+
563
+ private report<T>(
564
+ fields: ReportFields,
565
+ action: string,
566
+ call: (report: BigUint64Array, error: BigUint64Array) => boolean,
567
+ ): T {
568
+ const report = outputBuffer();
569
+ const error = outputBuffer();
570
+ const ok = call(report, error);
571
+ if (!ok) {
572
+ this.takeBuffer(report);
573
+ throw this.errorFrom(error, `HawDB ${action} failed`);
574
+ }
575
+ const unexpected = this.takeBuffer(error);
576
+ const text = this.takeBuffer(report);
577
+ if (unexpected !== null) {
578
+ throw new HawDBError("ffi", `HawDB ${action} succeeded with an error payload: ${unexpected}`);
579
+ }
580
+ return parseReport<T>(text, fields);
581
+ }
582
+
583
+ private liveLifetime(handle: NativePointer): symbol {
584
+ this.assertOpen();
585
+ const lifetime = this.handles.get(handle);
586
+ if (lifetime === undefined) {
587
+ throw new HawDBError("invalid_handle", "HawDB database handle is not live");
588
+ }
589
+ return lifetime;
590
+ }
591
+
592
+ // Converting a path can run its toString/Symbol.toPrimitive, which may close
593
+ // this database, open another at the same address, or unload the library.
594
+ // Recheck the library and the lifetime token, not only the address, after
595
+ // every argument has been converted and immediately before native dispatch.
596
+ private assertStillLive(handle: NativePointer, lifetime: symbol): void {
597
+ this.assertOpen();
598
+ if (this.handles.get(handle) !== lifetime) {
599
+ throw new HawDBError("invalid_handle", "HawDB database handle is not live");
600
+ }
601
+ }
602
+
603
+ backup(handle: NativePointer, destination: string): BackupReport {
604
+ const lifetime = this.liveLifetime(handle);
605
+ const destinationBytes = encoder.encode(destination);
606
+ if (destinationBytes.length === 0) {
607
+ throw new TypeError("HawDB backup destination must not be empty");
608
+ }
609
+ this.assertStillLive(handle, lifetime);
610
+ return this.report(backupReportFields, "backup", (report, error) =>
611
+ this.native.symbols.hawdb_backup(handle, destinationBytes, destinationBytes, report, error),
612
+ );
613
+ }
614
+
615
+ scrub(handle: NativePointer): ScrubReport {
616
+ this.liveLifetime(handle);
617
+ return this.report(scrubReportFields, "scrub", (report, error) =>
618
+ this.native.symbols.hawdb_scrub(handle, report, error),
619
+ );
620
+ }
621
+
622
+ /**
623
+ * Restore the backup directory `backup` into `destination`, a directory
624
+ * that must not exist yet. The backup is verified before anything is
625
+ * written; open the result with `open`. Needs no open database.
626
+ */
627
+ restore(backup: string, destination: string): RestoreReport {
628
+ this.assertOpen();
629
+ const backupBytes = encoder.encode(backup);
630
+ const destinationBytes = encoder.encode(destination);
631
+ if (backupBytes.length === 0 || destinationBytes.length === 0) {
632
+ throw new TypeError("HawDB restore paths must not be empty");
633
+ }
634
+ // Path conversion may have unloaded the library.
635
+ this.assertOpen();
636
+ return this.report(backupReportFields, "restore", (report, error) =>
637
+ this.native.symbols.hawdb_restore(
638
+ backupBytes,
639
+ backupBytes,
640
+ destinationBytes,
641
+ destinationBytes,
642
+ report,
643
+ error,
644
+ ),
645
+ );
646
+ }
647
+
648
+ exportDatabase(handle: NativePointer, destination: string): ExportReport {
649
+ const lifetime = this.liveLifetime(handle);
650
+ const destinationBytes = encoder.encode(destination);
651
+ if (destinationBytes.length === 0) {
652
+ throw new TypeError("HawDB export destination must not be empty");
653
+ }
654
+ this.assertStillLive(handle, lifetime);
655
+ return this.report<ExportReport>(exportReportFields, "export", (report, error) =>
656
+ this.native.symbols.hawdb_export(handle, destinationBytes, destinationBytes, report, error),
657
+ );
658
+ }
659
+
660
+ /**
661
+ * Build a new database at `destination`, which must not exist yet, from the
662
+ * logical dump at `source`. Nothing is published unless every file
663
+ * verifies; open the result with `open`. Needs no open database.
664
+ */
665
+ import(source: string, destination: string): ImportReport {
666
+ this.assertOpen();
667
+ const sourceBytes = encoder.encode(source);
668
+ const destinationBytes = encoder.encode(destination);
669
+ if (sourceBytes.length === 0 || destinationBytes.length === 0) {
670
+ throw new TypeError("HawDB import paths must not be empty");
671
+ }
672
+ // Path conversion may have unloaded the library.
673
+ this.assertOpen();
674
+ return this.report<ImportReport>(importReportFields, "import", (report, error) =>
675
+ this.native.symbols.hawdb_import(
676
+ sourceBytes,
677
+ sourceBytes,
678
+ destinationBytes,
679
+ destinationBytes,
680
+ report,
681
+ error,
682
+ ),
683
+ );
684
+ }
685
+
686
+ /**
687
+ * Verify the logical dump at `path` against its manifest without writing
688
+ * anything. Damage throws a `storage_integrity` `HawDBError`.
689
+ */
690
+ verifyDump(path: string): VerifyReport {
691
+ this.assertOpen();
692
+ const pathBytes = encoder.encode(path);
693
+ if (pathBytes.length === 0) {
694
+ throw new TypeError("HawDB dump path must not be empty");
695
+ }
696
+ // Path conversion may have unloaded the library.
697
+ this.assertOpen();
698
+ return this.report<VerifyReport>(verifyReportFields, "verify", (report, error) =>
699
+ this.native.symbols.hawdb_verify_dump(pathBytes, pathBytes, report, error),
700
+ );
701
+ }
702
+
703
+ /**
704
+ * Reconcile an `export` or `import` that threw `publish_outcome_unknown`:
705
+ * the complete result may already be at `destination`, so keep it. This
706
+ * makes its name durable and is safe to repeat; then check an export with
707
+ * `verifyDump` or open an import. A missing destination means the
708
+ * publication did not survive and the call can be run again.
709
+ */
710
+ confirmDumpPublication(destination: string): void {
711
+ this.assertOpen();
712
+ const destinationBytes = encoder.encode(destination);
713
+ if (destinationBytes.length === 0) {
714
+ throw new TypeError("HawDB dump destination must not be empty");
715
+ }
716
+ this.assertOpen();
717
+ const error = outputBuffer();
718
+ if (
719
+ !this.native.symbols.hawdb_confirm_dump_publication(
720
+ destinationBytes,
721
+ destinationBytes,
722
+ error,
723
+ )
724
+ ) {
725
+ throw this.errorFrom(error, "HawDB confirm dump publication failed");
726
+ }
727
+ const unexpected = this.takeBuffer(error);
728
+ if (unexpected !== null) {
729
+ throw new HawDBError(
730
+ "ffi",
731
+ `HawDB confirm dump publication succeeded with an error payload: ${unexpected}`,
732
+ );
733
+ }
734
+ }
735
+
736
+ closeDatabase(database: Database, handle: NativePointer): void {
737
+ this.finalizer.unregister(database);
738
+ if (!this.closed && this.handles.delete(handle)) {
739
+ this.native.symbols.hawdb_close(handle);
740
+ }
741
+ }
742
+
743
+ close(): void {
744
+ if (this.closed) return;
745
+ if (this.handles.size !== 0) {
746
+ throw new HawDBError(
747
+ "database_in_use",
748
+ `cannot close HawDB shared library with ${this.handles.size} live database handle(s)`,
749
+ );
750
+ }
751
+ this.native.close();
752
+ this.closed = true;
753
+ }
754
+
755
+ [Symbol.dispose](): void {
756
+ this.close();
757
+ }
758
+ }
759
+
760
+ /**
761
+ * Statements of one `Database.transaction` callback. Valid only while the
762
+ * callback runs; afterwards every call throws `no_transaction`.
763
+ */
764
+ export class Transaction {
765
+ private active = true;
766
+
767
+ constructor(
768
+ private readonly library: HawDBLibrary,
769
+ private readonly handle: () => NativePointer,
770
+ token: typeof databaseConstructorToken,
771
+ ) {
772
+ if (token !== databaseConstructorToken) {
773
+ throw new TypeError("Transactions must be created by Database.transaction");
774
+ }
775
+ }
776
+
777
+ private liveHandle(): NativePointer {
778
+ if (!this.active) {
779
+ throw new HawDBError("no_transaction", "HawDB transaction has already finished");
780
+ }
781
+ return this.handle();
782
+ }
783
+
784
+ finish(): void {
785
+ this.active = false;
786
+ }
787
+
788
+ query(cypher: string, parameters: Record<string, HawDBParameter> = {}): QueryResult {
789
+ if (Array.isArray(parameters) || parameters === null || typeof parameters !== "object") {
790
+ throw new TypeError("Cypher parameters must be an object");
791
+ }
792
+ return this.library.query(this.liveHandle(), false, cypher, parameters, true);
793
+ }
794
+
795
+ querySQL(sql: string, parameters: HawDBParameter[] = []): QueryResult {
796
+ if (!Array.isArray(parameters)) {
797
+ throw new TypeError("SQL parameters must be an array");
798
+ }
799
+ return this.library.query(this.liveHandle(), true, sql, parameters, true);
800
+ }
801
+
802
+ exec(cypher: string, parameters: Record<string, HawDBParameter> = {}): void {
803
+ this.query(cypher, parameters);
804
+ }
805
+ }
806
+
807
+ function isThenable(value: unknown): boolean {
808
+ return (
809
+ value !== null &&
810
+ (typeof value === "object" || typeof value === "function") &&
811
+ typeof (value as { then?: unknown }).then === "function"
812
+ );
813
+ }
814
+
815
+ export class Database {
816
+ private handle: NativePointer | null;
817
+ private transactionOpen = false;
818
+
819
+ constructor(
820
+ private readonly library: HawDBLibrary,
821
+ handle: NativePointer,
822
+ token: typeof databaseConstructorToken,
823
+ ) {
824
+ if (token !== databaseConstructorToken) {
825
+ throw new TypeError("Database handles must be created by HawDBLibrary");
826
+ }
827
+ this.handle = handle;
828
+ }
829
+
830
+ private liveHandle(): NativePointer {
831
+ if (this.handle === null) {
832
+ throw new HawDBError("closed", "HawDB database is closed");
833
+ }
834
+ return this.handle;
835
+ }
836
+
837
+ query(
838
+ cypher: string,
839
+ parameters: Record<string, HawDBParameter> = {},
840
+ ): QueryResult {
841
+ if (Array.isArray(parameters) || parameters === null || typeof parameters !== "object") {
842
+ throw new TypeError("Cypher parameters must be an object");
843
+ }
844
+ return this.library.query(this.liveHandle(), false, cypher, parameters);
845
+ }
846
+
847
+ querySQL(sql: string, parameters: HawDBParameter[] = []): QueryResult {
848
+ if (!Array.isArray(parameters)) {
849
+ throw new TypeError("SQL parameters must be an array");
850
+ }
851
+ return this.library.query(this.liveHandle(), true, sql, parameters);
852
+ }
853
+
854
+ exec(cypher: string, parameters: Record<string, HawDBParameter> = {}): void {
855
+ this.query(cypher, parameters);
856
+ }
857
+
858
+ /**
859
+ * Run `body` as one atomic transaction. Its statements run through the
860
+ * `Transaction` argument and commit together when `body` returns; if
861
+ * `body` throws, every statement is rolled back and the error is
862
+ * rethrown. `body` must be synchronous: a returned promise rolls the
863
+ * transaction back and throws. Returns `body`'s result.
864
+ *
865
+ * The commit is all or nothing, never partial. A commit refused before
866
+ * publication (for example a write conflict) publishes nothing, but an
867
+ * error raised while publishing, or a crash before `transaction` returns,
868
+ * leaves the outcome unknown: after a reopen the whole transaction may be
869
+ * committed. Reconcile or retry idempotently rather than rerunning blindly.
870
+ */
871
+ transaction<T>(body: (transaction: Transaction) => T): T {
872
+ if (typeof body !== "function") {
873
+ throw new TypeError("HawDB transaction body must be a function");
874
+ }
875
+ const handle = this.liveHandle();
876
+ if (this.transactionOpen) {
877
+ throw new HawDBError("transaction_open", "a HawDB transaction is already open on this database");
878
+ }
879
+ this.library.transactionControl(handle, "begin");
880
+ this.transactionOpen = true;
881
+ const transaction = new Transaction(this.library, () => this.liveHandle(), databaseConstructorToken);
882
+ let result: T;
883
+ try {
884
+ result = body(transaction);
885
+ if (isThenable(result)) {
886
+ throw new TypeError("HawDB transaction bodies must be synchronous; the transaction was rolled back");
887
+ }
888
+ } catch (error) {
889
+ transaction.finish();
890
+ this.transactionOpen = false;
891
+ try {
892
+ this.library.transactionControl(handle, "rollback");
893
+ } catch {
894
+ // The original error explains the failure; the transaction is closed either way.
895
+ }
896
+ throw error;
897
+ }
898
+ transaction.finish();
899
+ this.transactionOpen = false;
900
+ this.library.transactionControl(handle, "commit");
901
+ return result;
902
+ }
903
+
904
+ /**
905
+ * Write a consistent, self-verifying backup of this open database to
906
+ * `destination`, a directory that must not exist yet. The database stays
907
+ * open; the backup holds everything committed before the call.
908
+ */
909
+ backup(destination: string): BackupReport {
910
+ return this.library.backup(this.liveHandle(), destination);
911
+ }
912
+
913
+ /**
914
+ * Verify every durable file and the WAL against their checksums. Damage
915
+ * throws a `HawDBError`, after which this handle refuses statements until
916
+ * it is closed and the database reopened or restored.
917
+ */
918
+ scrub(): ScrubReport {
919
+ return this.library.scrub(this.liveHandle());
920
+ }
921
+
922
+ /**
923
+ * Write this database's current snapshot as a logical dump directory at
924
+ * `destination`, which must not exist yet. The dump outlives the storage
925
+ * format: a later library imports it with `library.import`.
926
+ */
927
+ export(destination: string): ExportReport {
928
+ return this.library.exportDatabase(this.liveHandle(), destination);
929
+ }
930
+
931
+ close(): void {
932
+ const handle = this.handle;
933
+ if (handle === null) return;
934
+ if (this.transactionOpen) {
935
+ throw new HawDBError(
936
+ "transaction_open",
937
+ "cannot close a HawDB database inside its transaction; return or throw from the transaction body first",
938
+ );
939
+ }
940
+ this.handle = null;
941
+ this.library.closeDatabase(this, handle);
942
+ }
943
+
944
+ [Symbol.dispose](): void {
945
+ this.close();
946
+ }
947
+ }
948
+
949
+ /**
950
+ * Load the HawDB C ABI. With a path, map exactly that library. Without one,
951
+ * map the library from the installed `@nowledge/hawdb-ffi-<platform>` package
952
+ * selected for this host.
953
+ */
954
+ export function loadHawDB(path?: string): HawDBLibrary {
955
+ return HawDBLibrary.load(path === undefined ? resolvePrebuiltLibrary() : path);
956
+ }