@hakodb/client 0.5.12

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/client.ts ADDED
@@ -0,0 +1,1123 @@
1
+ import { loadNativeBindings, type NativeBindings, type WatchCallback } from './native';
2
+
3
+ // 1. UPDATED: Recursive Type Definitions to support Nested Maps and Arrays
4
+ // export type Primitive = string | number | boolean | null | Uint8Array | Date | HakoDocData | Array<any>;
5
+ export type Primitive =
6
+ | string
7
+ | number
8
+ | boolean
9
+ | null
10
+ | Uint8Array
11
+ | Date
12
+ | HakoReference
13
+ | { [key: string]: Primitive }
14
+ | Primitive[];
15
+
16
+
17
+ export type HakoDocData = { [key: string]: Primitive };
18
+
19
+ const SERVER_TIMESTAMP_SENTINEL = "__FL_SERVER_TIMESTAMP__";
20
+
21
+ export class HakoReference {
22
+ constructor(public readonly collection: string, public readonly id: string) {}
23
+ }
24
+
25
+ export enum DurabilityMode {
26
+ Always = 0,
27
+ Interval = 1,
28
+ Manual = 2,
29
+ OnCommit = 3,
30
+ }
31
+
32
+ export enum CloudSyncMode {
33
+ Server = 0,
34
+ Client = 1,
35
+ }
36
+
37
+ export interface HakoClientOptions {
38
+ libraryPath?: string;
39
+ native?: NativeBindings;
40
+ config?: HakoConfig;
41
+ }
42
+
43
+ // 2. FIXED: Added 'in' to the interface to match the Query class
44
+ export interface QueryConstraint {
45
+ field: string;
46
+ op: '==' | '!=' | '>' | '>=' | '<' | '<=' | 'match' | 'matchPrefix' | 'contains' | 'startsWith' | 'in' | 'not-in' | 'array-contains' | 'array-contains-any';
47
+ value: any; // Use any because 'in' takes an array
48
+ }
49
+
50
+ export interface QueryOrder {
51
+ field: string;
52
+ ascending: boolean;
53
+ }
54
+
55
+ export type Unsubscribe = () => Promise<void>;
56
+
57
+ /**
58
+ * Advanced Configuration Builder
59
+ */
60
+ export class HakoConfig {
61
+ private _handle: unknown;
62
+ private _native: NativeBindings;
63
+
64
+ constructor(native: NativeBindings) {
65
+ this._native = native;
66
+ this._handle = native.configNew();
67
+ }
68
+
69
+ /** Reuse these bindings instead of loading the DLL twice in one process
70
+ * (koffi rejects duplicate type registration on a second load). */
71
+ getNativeBindings(): NativeBindings {
72
+ return this._native;
73
+ }
74
+
75
+ setDurability(mode: DurabilityMode): this {
76
+ this._native.configSetDurability(this._handle, mode);
77
+ return this;
78
+ }
79
+
80
+ setEncryptionKey(key: string): this {
81
+ this._native.configSetEncryptionKey(this._handle, key);
82
+ return this;
83
+ }
84
+
85
+ setAuditLog(enabled: boolean, path: string | null = null): this {
86
+ this._native.configSetAuditLog(this._handle, enabled, path);
87
+ return this;
88
+ }
89
+
90
+ setQueryWorkers(count: number): this {
91
+ this._native.configSetQueryWorkers(this._handle, count);
92
+ return this;
93
+ }
94
+
95
+ setMemoryLimits(mmapBytes: number, maxInlinedBytes: number): this {
96
+ this._native.configSetMemoryLimits(this._handle, mmapBytes, maxInlinedBytes);
97
+ return this;
98
+ }
99
+
100
+ setStorageTuning(pageSize: number, threshold: number, groupCommitMaxOps: number): this {
101
+ this._native.configSetStorageTuning(this._handle, pageSize, threshold, groupCommitMaxOps);
102
+ return this;
103
+ }
104
+
105
+ setEncryptedCollections(collections: string[]): this {
106
+ ensureOk(this._native.configSetEncryptedCollections(this._handle, JSON.stringify(collections)), this._native, 'setEncryptedCollections');
107
+ return this;
108
+ }
109
+
110
+ setBlobThreshold(thresholdBytes: number): this {
111
+ this._native.configSetBlobThreshold(this._handle, thresholdBytes);
112
+ return this;
113
+ }
114
+
115
+ setCompression(enabled: boolean, level: number = 3): this {
116
+ this._native.configSetCompression(this._handle, enabled, level);
117
+ return this;
118
+ }
119
+
120
+ getHandle(): unknown {
121
+ return this._handle;
122
+ }
123
+ }
124
+
125
+ function ensureOk(code: number, native: NativeBindings, ctx: string): void {
126
+ if (code !== 0) {
127
+ throw new Error(`${ctx}: ${native.lastError()}`);
128
+ }
129
+ }
130
+
131
+ function parseDocJson(json: string | null): HakoDocData {
132
+ if (!json) return {};
133
+ return JSON.parse(json) as HakoDocData;
134
+ }
135
+
136
+ function parseQueryRows(json: string | null): HakoDocData[] {
137
+ if (!json) return [];
138
+ const parsed = JSON.parse(json);
139
+ return Array.isArray(parsed) ? (parsed as HakoDocData[]) : [];
140
+ }
141
+
142
+ /**
143
+ * Recursive field inserter (v0.5.9)
144
+ */
145
+ function insertField(native: NativeBindings, handle: unknown, key: string, value: Primitive): void {
146
+ if (value === SERVER_TIMESTAMP_SENTINEL) {
147
+ ensureOk(native.docInsertServerTimestamp(handle, key), native, 'serverTimestamp');
148
+ return;
149
+ }
150
+ if (value instanceof Date) {
151
+ native.docInsertTimestamp(handle, key, BigInt(value.getTime()) * 1000n);
152
+ return;
153
+ }
154
+ if (value instanceof Uint8Array) {
155
+ ensureOk(native.docInsertBin(handle, key, value), native, 'insertBin');
156
+ return;
157
+ }
158
+ if (value instanceof HakoReference) {
159
+ ensureOk(native.docInsertReference(handle, key, value.collection, value.id), native, 'insertReference');
160
+ return;
161
+ }
162
+
163
+ if (Array.isArray(value)) {
164
+ const arrHandle = native.arrayNew();
165
+ for (const item of value) {
166
+ if (typeof item === 'string') native.arrayAppendStr(arrHandle, item);
167
+ else if (typeof item === 'number') native.arrayAppendInt(arrHandle, item);
168
+ else if (typeof item === 'object' && item !== null) {
169
+ const tempDoc = toNativeDoc(native, item as HakoDocData);
170
+ native.arrayAppendDoc(arrHandle, tempDoc);
171
+ native.docFree(tempDoc); // FFI copies data into the array
172
+ }
173
+ }
174
+ // ownership transfers to parent doc handle
175
+ ensureOk(native.docInsertArray(handle, key, arrHandle), native, 'insertArray');
176
+ return;
177
+ }
178
+
179
+ if (typeof value === 'object' && value !== null) {
180
+ const childDocHandle = toNativeDoc(native, value as HakoDocData);
181
+ ensureOk(native.docInsertDoc(handle, key, childDocHandle), native, 'insertDoc');
182
+ native.docFree(childDocHandle); // FFI copies data into the parent
183
+ return;
184
+ }
185
+
186
+ // Primitives (string, number, bool, null)
187
+ if (typeof value === 'string') {
188
+ ensureOk(native.docInsertStr(handle, key, value), native, 'insertStr');
189
+ } else if (typeof value === 'number') {
190
+ if (Number.isInteger(value)) ensureOk(native.docInsertInt(handle, key, value), native, 'insertInt');
191
+ else ensureOk(native.docInsertFloat(handle, key, value), native, 'insertFloat');
192
+ } else if (typeof value === 'boolean') {
193
+ ensureOk(native.docInsertBool(handle, key, value), native, 'insertBool');
194
+ } else if (value === null) {
195
+ ensureOk(native.docInsertNull(handle, key), native, 'insertNull');
196
+ }
197
+ }
198
+
199
+ function toNativeDoc(native: NativeBindings, data: HakoDocData): unknown {
200
+ const doc = native.docNew();
201
+ if (!doc) throw new Error(`docNew failed: ${native.lastError()}`);
202
+ try {
203
+ for (const [key, value] of Object.entries(data)) {
204
+ insertField(native, doc, key, value);
205
+ }
206
+ return doc;
207
+ } catch (err) {
208
+ native.docFree(doc);
209
+ throw err;
210
+ }
211
+ }
212
+
213
+ export class DocumentSnapshot {
214
+ constructor(
215
+ public readonly id: string,
216
+ public readonly exists: boolean,
217
+ private readonly payload?: HakoDocData,
218
+ public readonly _nativeHandle?: unknown
219
+ ) { }
220
+
221
+ data(): HakoDocData | undefined {
222
+ return this.payload;
223
+ }
224
+ }
225
+
226
+ /**
227
+ * One raw page: pinned storage bytes per row (v0.8.3+). Decode nothing
228
+ * up front — resolve() only rows you touch, page with
229
+ * Query.startAfterRaw() (no decode at all). Free when done; rows die
230
+ * with the page.
231
+ */
232
+ export class RawQuerySnapshot {
233
+ private freed = false;
234
+
235
+ constructor(
236
+ private readonly client: HakoClient,
237
+ private readonly collection: string,
238
+ private readonly handle: unknown
239
+ ) { }
240
+
241
+ get count(): number {
242
+ return this.client.nativeBindings().rawResultCount(this.handle);
243
+ }
244
+
245
+ /** Decode + inflate one row. Prefer resolving only rows you touch. */
246
+ async resolve(index: number): Promise<HakoDocData | undefined> {
247
+ const native = this.client.nativeBindings();
248
+ const doc = native.rawDocToDoc(this.client.engineHandle(), this.rawHandleAt(index), this.collection);
249
+ if (!doc) return undefined;
250
+ try {
251
+ return parseDocJson(native.docToJson(doc));
252
+ } finally {
253
+ native.docFree(doc);
254
+ }
255
+ }
256
+
257
+ /** Borrowed native raw handle. Valid until free(). Internal. */
258
+ rawHandleAt(index: number): unknown {
259
+ return this.client.nativeBindings().rawResultGet(this.handle, index);
260
+ }
261
+
262
+ free(): void {
263
+ if (!this.freed) {
264
+ this.freed = true;
265
+ this.client.nativeBindings().rawResultFree(this.handle);
266
+ }
267
+ }
268
+ }
269
+
270
+ /**
271
+ * One borrowed row (v0.8.11+): lazy numeric/bool pulls with no decode
272
+ * and no JSON. Strings stay on resolve() (no backend memory reads).
273
+ * Free when done.
274
+ */
275
+ export class ViewDocSnapshot {
276
+ private freed = false;
277
+
278
+ constructor(
279
+ private readonly client: HakoClient,
280
+ private readonly collection: string,
281
+ private readonly docId: string,
282
+ private readonly handle: unknown
283
+ ) { }
284
+
285
+ get id(): string {
286
+ return this.docId;
287
+ }
288
+
289
+ get fieldCount(): number {
290
+ return this.client.nativeBindings().viewFieldCount(this.handle);
291
+ }
292
+
293
+ has(field: string): boolean {
294
+ return this.client.nativeBindings().viewHasField(this.handle, field);
295
+ }
296
+
297
+ getInt(field: string): number | bigint | null {
298
+ return this.client.nativeBindings().viewGetInt(this.handle, field);
299
+ }
300
+
301
+ getFloat(field: string): number | null {
302
+ return this.client.nativeBindings().viewGetFloat(this.handle, field);
303
+ }
304
+
305
+ getBool(field: string): boolean | null {
306
+ return this.client.nativeBindings().viewGetBool(this.handle, field);
307
+ }
308
+
309
+ /** Full decode + inflate. Prefer pulls for sparse reads. */
310
+ async resolve(): Promise<HakoDocData | undefined> {
311
+ const native = this.client.nativeBindings();
312
+ const doc = native.viewToDoc(this.handle, this.docId);
313
+ if (!doc) return undefined;
314
+ try {
315
+ return parseDocJson(native.docToJson(doc));
316
+ } finally {
317
+ native.docFree(doc);
318
+ }
319
+ }
320
+
321
+ free(): void {
322
+ if (!this.freed) {
323
+ this.freed = true;
324
+ this.client.nativeBindings().viewFree(this.handle);
325
+ }
326
+ }
327
+ }
328
+
329
+ export class HakoClient {
330
+ private readonly native: NativeBindings;
331
+ private readonly engine: unknown;
332
+ private isClosed = false;
333
+
334
+ private constructor(native: NativeBindings, engine: unknown) {
335
+ this.native = native;
336
+ this.engine = engine;
337
+ }
338
+
339
+ static async open(path: string, options?: HakoClientOptions): Promise<HakoClient> {
340
+ const native = options?.native
341
+ ?? options?.config?.getNativeBindings()
342
+ ?? (await loadNativeBindings(options?.libraryPath));
343
+
344
+ let engine: unknown;
345
+ if (options?.config) {
346
+ engine = native.engineOpenWithConfig(path, options.config.getHandle());
347
+ } else {
348
+ engine = native.engineOpen(path);
349
+ }
350
+
351
+ if (!engine) {
352
+ throw new Error(`Failed to open HakoDB: ${native.lastError()}`);
353
+ }
354
+ return new HakoClient(native, engine);
355
+ }
356
+
357
+ static serverTimestamp(): any {
358
+ return SERVER_TIMESTAMP_SENTINEL;
359
+ }
360
+
361
+ static async createConfig(libraryPath?: string): Promise<HakoConfig> {
362
+ const native = await loadNativeBindings(libraryPath);
363
+ return new HakoConfig(native);
364
+ }
365
+
366
+ collection(name: string): CollectionReference {
367
+ this.assertOpen();
368
+ return new CollectionReference(this, name);
369
+ }
370
+
371
+ batch(): WriteBatch {
372
+ this.assertOpen();
373
+ return new WriteBatch(this);
374
+ }
375
+
376
+ async listCollections(): Promise<string[]> {
377
+ this.assertOpen();
378
+ const json = this.native.engineListCollections(this.engine);
379
+ return json ? JSON.parse(json) : [];
380
+ }
381
+
382
+ createNetSyncer(name: string, roomKey: string): NetSyncer {
383
+ this.assertOpen();
384
+ const handle = this.native.netSyncerNew(this.engine, name, roomKey);
385
+ if (!handle) {
386
+ throw new Error(`netSyncerNew failed: ${this.native.lastError()}`);
387
+ }
388
+ return new NetSyncer(this.native, handle);
389
+ }
390
+
391
+ createCloudSync(
392
+ mode: CloudSyncMode,
393
+ clientId: string | null = null,
394
+ roomName: string | null = null,
395
+ roomKey: string | null = null,
396
+ authToken: string | null = null
397
+ ): CloudSync {
398
+ this.assertOpen();
399
+ const handle = this.native.cloudSyncNew(this.engine, mode, clientId, roomName, roomKey, authToken);
400
+ if (!handle) {
401
+ throw new Error(`cloudSyncNew failed: ${this.native.lastError()}`);
402
+ }
403
+ return new CloudSync(this.native, handle);
404
+ }
405
+
406
+ /**
407
+ * Creates a room-agnostic cloud SERVER ("big cloud server storage"). It is
408
+ * not bound to any room: clients choose their room (and this server) and the
409
+ * server accepts and persists any (roomName, roomKey) pair, storing each
410
+ * room's collections under its own storage prefix and relaying sync only to
411
+ * the members of that room.
412
+ */
413
+ createCloudSyncServer(serverId: string | null = null, authToken: string | null = null): CloudSync {
414
+ this.assertOpen();
415
+ const handle = this.native.cloudSyncServerNew(this.engine, serverId, authToken);
416
+ if (!handle) {
417
+ throw new Error(`cloudSyncServerNew failed: ${this.native.lastError()}`);
418
+ }
419
+ return new CloudSync(this.native, handle);
420
+ }
421
+
422
+ /**
423
+ * Creates an offline-first cloud CLIENT bound to a room of the caller's
424
+ * choosing. The client picks the room (roomName + roomKey) and later picks
425
+ * the server via `CloudSync.start()`.
426
+ */
427
+ createCloudSyncClient(
428
+ clientId: string | null = null,
429
+ roomName: string | null = null,
430
+ roomKey: string | null = null,
431
+ authToken: string | null = null
432
+ ): CloudSync {
433
+ this.assertOpen();
434
+ const handle = this.native.cloudSyncClientNew(this.engine, clientId, roomName, roomKey, authToken);
435
+ if (!handle) {
436
+ throw new Error(`cloudSyncClientNew failed: ${this.native.lastError()}`);
437
+ }
438
+ return new CloudSync(this.native, handle);
439
+ }
440
+
441
+ isIndexesReady(): boolean {
442
+ this.assertOpen();
443
+ return this.native.engineIsIndexesReady(this.engine);
444
+ }
445
+
446
+ async compact(): Promise<void> {
447
+ this.assertOpen();
448
+ ensureOk(this.native.engineCompact(this.engine), this.native, 'engineCompact');
449
+ }
450
+
451
+ async getStats(): Promise<Record<string, unknown>> {
452
+ this.assertOpen();
453
+ const raw = this.native.engineGetStats(this.engine);
454
+ return raw ? JSON.parse(raw) : {};
455
+ }
456
+
457
+ async getAuditLog(): Promise<unknown[]> {
458
+ this.assertOpen();
459
+ const raw = this.native.engineGetAuditLog(this.engine);
460
+ return raw ? JSON.parse(raw) : [];
461
+ }
462
+
463
+ async snapshotIndices(): Promise<void> {
464
+ this.assertOpen();
465
+ ensureOk(this.native.engineSnapshotIndices(this.engine), this.native, 'engineSnapshotIndices');
466
+ }
467
+
468
+ async listIndexes(collection: string | null = null): Promise<unknown> {
469
+ this.assertOpen();
470
+ const raw = this.native.engineListIndexes(this.engine, collection);
471
+ return raw ? JSON.parse(raw) : null;
472
+ }
473
+
474
+ async patch(collection: string, docId: string, data: HakoDocData): Promise<void> {
475
+ this.assertOpen();
476
+ const updates = toNativeDoc(this.native, data);
477
+ try {
478
+ ensureOk(this.native.enginePatch(this.engine, collection, docId, updates), this.native, 'enginePatch');
479
+ } finally {
480
+ this.native.docFree(updates);
481
+ }
482
+ }
483
+
484
+ async insertSubDoc(col: string, id: string, subCol: string, subId: string, data: HakoDocData): Promise<void> {
485
+ this.assertOpen();
486
+ const doc = toNativeDoc(this.native, data);
487
+ try {
488
+ ensureOk(this.native.engineInsertSubDoc(this.engine, col, id, subCol, subId, doc), this.native, 'engineInsertSubDoc');
489
+ } finally {
490
+ this.native.docFree(doc);
491
+ }
492
+ }
493
+
494
+ async getByReference(doc: DocumentSnapshot, fieldKey: string): Promise<DocumentSnapshot | null> {
495
+ this.assertOpen();
496
+ if (!doc._nativeHandle) return null;
497
+ const target = this.native.engineGetByRef(this.engine, doc._nativeHandle, fieldKey);
498
+ if (!target) return null;
499
+ const json = this.native.docToJson(target);
500
+ this.native.docFree(target);
501
+ return new DocumentSnapshot(fieldKey, true, parseDocJson(json));
502
+ }
503
+
504
+ async createCompositeIndex(collection: string, fields: { field: string; desc?: boolean }[]): Promise<number> {
505
+ this.assertOpen();
506
+ const id = this.native.engineCreateIndex(this.engine, collection, JSON.stringify(fields.map(f => ({ field: f.field, desc: !!f.desc }))));
507
+ if (id === 0) throw new Error(`engineCreateIndex failed: ${this.native.lastError()}`);
508
+ return id;
509
+ }
510
+
511
+ async runTransaction<T>(fn: (tx: Transaction) => Promise<T>): Promise<T> {
512
+ this.assertOpen();
513
+ const tx = new Transaction(this.native, this.engine);
514
+ try {
515
+ const result = await fn(tx);
516
+ ensureOk(this.native.transactionCommit(this.engine, tx.handle), this.native, 'transactionCommit');
517
+ return result;
518
+ } finally {
519
+ tx.dispose();
520
+ }
521
+ }
522
+
523
+ async backup(destinationPath: string): Promise<void> {
524
+ this.assertOpen();
525
+ ensureOk(this.native.engineBackup(this.engine, destinationPath), this.native, 'engineBackup');
526
+ }
527
+
528
+ async close(): Promise<void> {
529
+ if (this.isClosed) return;
530
+ this.native.engineFree(this.engine);
531
+ this.isClosed = true;
532
+ }
533
+
534
+ async set(collection: string, docId: string, data: HakoDocData): Promise<void> {
535
+ this.assertOpen();
536
+ const doc = toNativeDoc(this.native, data);
537
+ try {
538
+ ensureOk(this.native.engineInsert(this.engine, collection, docId, doc), this.native, 'engineInsert');
539
+ } finally {
540
+ this.native.docFree(doc);
541
+ }
542
+ }
543
+
544
+ async get(collection: string, docId: string): Promise<DocumentSnapshot> {
545
+ this.assertOpen();
546
+ const doc = this.native.engineGet(this.engine, collection, docId);
547
+ if (!doc) return new DocumentSnapshot(docId, false);
548
+
549
+ const json = this.native.docToJson(doc);
550
+ // Keep 'doc' handle for startAfter. Native memory management should be handled
551
+ // by engineFree or manual free if the user keeps thousands of snapshots.
552
+ return new DocumentSnapshot(docId, true, parseDocJson(json), doc);
553
+ }
554
+
555
+ /**
556
+ * Borrowed point view (v0.8.11+): lazy numeric/bool pulls with no decode
557
+ * and no JSON. Returns null when missing. Free the snapshot when done.
558
+ */
559
+ async viewDoc(collection: string, docId: string): Promise<ViewDocSnapshot | null> {
560
+ this.assertOpen();
561
+ const view = this.native.viewGet(this.engine, collection, docId);
562
+ if (!view) return null;
563
+ return new ViewDocSnapshot(this, collection, docId, view);
564
+ }
565
+
566
+ async delete(collection: string, docId: string): Promise<void> {
567
+ this.assertOpen();
568
+ ensureOk(this.native.engineDelete(this.engine, collection, docId), this.native, 'engineDelete');
569
+ }
570
+
571
+ /** Local-only delete: never leaves this device (no sync tailer or handshake transmits it). */
572
+ async deleteLocal(collection: string, docId: string): Promise<void> {
573
+ this.assertOpen();
574
+ ensureOk(this.native.engineDeleteLocal(this.engine, collection, docId), this.native, 'engineDeleteLocal');
575
+ }
576
+
577
+ /** Mark a collection local-only (never syncs) or rejoin it with `local=false`. */
578
+ async setCollectionLocal(collection: string, local: boolean): Promise<void> {
579
+ this.assertOpen();
580
+ ensureOk(this.native.engineSetCollectionLocal(this.engine, collection, local ? 1 : 0), this.native, 'engineSetCollectionLocal');
581
+ }
582
+
583
+ /** Opt a key back into replication (future ops only). */
584
+ async replicateKey(collection: string, docId: string): Promise<void> {
585
+ this.assertOpen();
586
+ ensureOk(this.native.engineReplicateKey(this.engine, collection, docId), this.native, 'engineReplicateKey');
587
+ }
588
+
589
+ /** Opt a whole collection back into replication. */
590
+ async replicateCollection(collection: string): Promise<void> {
591
+ this.assertOpen();
592
+ ensureOk(this.native.engineReplicateCollection(this.engine, collection), this.native, 'engineReplicateCollection');
593
+ }
594
+
595
+ /** Vacuum: purge tombstones (never replicates); next handshake pulls peer state. */
596
+ async vacuumCollection(collection: string): Promise<number> {
597
+ this.assertOpen();
598
+ const n = this.native.engineVacuumCollection(this.engine, collection);
599
+ if (n < 0) throw new Error(`engineVacuumCollection failed: ${this.native.lastError()}`);
600
+ return n;
601
+ }
602
+
603
+ nativeBindings(): NativeBindings { return this.native; }
604
+ engineHandle(): unknown { return this.engine; }
605
+
606
+ private assertOpen(): void {
607
+ if (this.isClosed) throw new Error('HakoClient is already closed');
608
+ }
609
+ }
610
+
611
+ export class NetSyncer {
612
+ private closed = false;
613
+
614
+ constructor(private readonly native: NativeBindings, private readonly handle: unknown) {}
615
+
616
+ async start(port: number): Promise<void> {
617
+ ensureOk(this.native.netSyncerStart(this.handle, port), this.native, 'netSyncerStart');
618
+ }
619
+
620
+ /**
621
+ * Discovery transports: 0 = mDNS (desktop default), 1 = UDP broadcast
622
+ * (mobile default, no multicast), 2 = both (mixed groups). Takes effect
623
+ * at start(). Mirrors the CLI `--discovery` flag.
624
+ */
625
+ async setDiscoveryMode(mode: 0 | 1 | 2): Promise<void> {
626
+ ensureOk(this.native.netSyncerSetDiscovery(this.handle, mode), this.native, 'netSyncerSetDiscovery');
627
+ }
628
+
629
+ async status<T = unknown>(): Promise<T | null> {
630
+ const raw = this.native.netSyncerStatus(this.handle);
631
+ return raw ? (JSON.parse(raw) as T) : null;
632
+ }
633
+
634
+ async close(): Promise<void> {
635
+ if (this.closed) return;
636
+ this.native.netSyncerFree(this.handle);
637
+ this.closed = true;
638
+ }
639
+ }
640
+
641
+ export class CloudSync {
642
+ private closed = false;
643
+
644
+ constructor(private readonly native: NativeBindings, private readonly handle: unknown) {}
645
+
646
+ async start(address: string): Promise<void> {
647
+ ensureOk(this.native.cloudSyncStart(this.handle, address), this.native, 'cloudSyncStart');
648
+ }
649
+
650
+ async status<T = unknown>(): Promise<T | null> {
651
+ const raw = this.native.cloudSyncStatus(this.handle);
652
+ return raw ? (JSON.parse(raw) as T) : null;
653
+ }
654
+
655
+ stop(): void {
656
+ if (this.closed) return;
657
+ this.native.cloudSyncStop(this.handle);
658
+ }
659
+
660
+ close(): void {
661
+ this.stop();
662
+ this.native.cloudSyncFree(this.handle);
663
+ this.closed = true;
664
+ }
665
+ }
666
+
667
+ export class Transaction {
668
+ private disposed = false;
669
+
670
+ constructor(
671
+ private readonly native: NativeBindings,
672
+ private readonly engine: unknown,
673
+ readonly handle: unknown = native.transactionBegin(engine)
674
+ ) {
675
+ if (!handle) throw new Error(`transactionBegin failed: ${native.lastError()}`);
676
+ }
677
+
678
+ async get(collection: string, docId: string): Promise<DocumentSnapshot> {
679
+ this.ensureActive();
680
+ const doc = this.native.transactionGet(this.engine, this.handle, collection, docId);
681
+ if (!doc) return new DocumentSnapshot(docId, false);
682
+ const json = this.native.docToJson(doc);
683
+ this.native.docFree(doc);
684
+ return new DocumentSnapshot(docId, true, parseDocJson(json));
685
+ }
686
+
687
+ set(collection: string, docId: string, data: HakoDocData): this {
688
+ this.ensureActive();
689
+ const doc = toNativeDoc(this.native, data);
690
+ try {
691
+ ensureOk(this.native.transactionSet(this.handle, collection, docId, doc), this.native, 'transactionSet');
692
+ } finally {
693
+ this.native.docFree(doc);
694
+ }
695
+ return this;
696
+ }
697
+
698
+ dispose(): void {
699
+ if (this.disposed) return;
700
+ this.native.transactionFree(this.handle);
701
+ this.disposed = true;
702
+ }
703
+
704
+ private ensureActive(): void {
705
+ if (this.disposed) throw new Error('Transaction has already been committed/disposed');
706
+ }
707
+ }
708
+
709
+ export class CollectionReference {
710
+ constructor(private readonly client: HakoClient, private readonly name: string) { }
711
+
712
+ doc(id: string): DocumentReference {
713
+ return new DocumentReference(this.client, this.name, id);
714
+ }
715
+
716
+ onSnapshot(callback: (snapshot: HakoDocData[]) => void): Unsubscribe {
717
+ return new Query(this.client, this.name).onSnapshot(callback);
718
+ }
719
+
720
+ // 3. FIXED: Updated 'op' signature to include 'in'
721
+ where(field: string, op: '==' | '!=' | '>' | '>=' | '<' | '<=' | 'match' | 'matchPrefix' | 'contains' | 'startsWith' | 'in' | 'not-in' | 'array-contains' | 'array-contains-any', value: any): Query {
722
+ return new Query(this.client, this.name).where(field, op, value);
723
+ }
724
+
725
+ orderBy(field: string, direction: 'asc' | 'desc' = 'asc'): Query {
726
+ return new Query(this.client, this.name).orderBy(field, direction);
727
+ }
728
+
729
+ limit(max: number): Query {
730
+ return new Query(this.client, this.name).limit(max);
731
+ }
732
+
733
+ select(...fields: string[]): Query {
734
+ return new Query(this.client, this.name).select(...fields);
735
+ }
736
+
737
+ async get(): Promise<HakoDocData[]> {
738
+ return new Query(this.client, this.name).get();
739
+ }
740
+
741
+ async count(): Promise<number> {
742
+ return new Query(this.client, this.name).count();
743
+ }
744
+
745
+ async createIndex(field: string): Promise<void> {
746
+ ensureOk(this.client.nativeBindings().createSimpleIndex(this.client.engineHandle(), this.name, field), this.client.nativeBindings(), 'createIndex');
747
+ }
748
+
749
+ async createFtsIndex(field: string): Promise<void> {
750
+ ensureOk(this.client.nativeBindings().createFtsIndex(this.client.engineHandle(), this.name, field), this.client.nativeBindings(), 'createFtsIndex');
751
+ }
752
+
753
+ async createCompositeIndex(fields: { field: string; desc?: boolean }[]): Promise<number> {
754
+ return this.client.createCompositeIndex(this.name, fields);
755
+ }
756
+ }
757
+
758
+ export class DocumentReference {
759
+ constructor(private readonly client: HakoClient, readonly _collection: string, readonly _id: string) { }
760
+
761
+ async set(data: HakoDocData): Promise<void> {
762
+ await this.client.set(this._collection, this._id, data);
763
+ }
764
+
765
+ async update(data: HakoDocData): Promise<void> {
766
+ await this.client.patch(this._collection, this._id, data);
767
+ }
768
+
769
+ async get(): Promise<DocumentSnapshot> {
770
+ return this.client.get(this._collection, this._id);
771
+ }
772
+
773
+ async delete(): Promise<void> {
774
+ await this.client.delete(this._collection, this._id);
775
+ }
776
+
777
+ async getByReference(fieldKey: string): Promise<DocumentSnapshot | null> {
778
+ const snap = await this.get();
779
+ if (!snap.exists) return null;
780
+ return this.client.getByReference(snap, fieldKey);
781
+ }
782
+ }
783
+
784
+ export class Query {
785
+ private _startAfterSnapshot?: DocumentSnapshot;
786
+ private _startAtSnapshot?: DocumentSnapshot;
787
+ private _endAtSnapshot?: DocumentSnapshot;
788
+ private _endBeforeSnapshot?: DocumentSnapshot;
789
+ private _startAfterRawAnchor?: { snap: RawQuerySnapshot; index: number };
790
+ private readonly filters: QueryConstraint[] = [];
791
+ private readonly orFilters: QueryConstraint[] = [];
792
+ private order?: QueryOrder;
793
+ private queryLimit?: number;
794
+ private queryOffset?: number;
795
+ private projection: string[] = [];
796
+ private deferBlobsDef = false;
797
+
798
+ constructor(private readonly client: HakoClient, private readonly collection: string) { }
799
+
800
+ where(field: string, op: '==' | '!=' | '>' | '>=' | '<' | '<=' | 'match' | 'matchPrefix' | 'contains' | 'startsWith' | 'in' | 'not-in' | 'array-contains' | 'array-contains-any', value: any): Query {
801
+ this.filters.push({ field, op, value });
802
+ return this;
803
+ }
804
+
805
+ orWhere(field: string, op: '==' | '!=' | '>' | '>=' | '<' | '<=' | 'match' | 'matchPrefix' | 'contains' | 'startsWith', value: any): Query {
806
+ this.orFilters.push({ field, op, value });
807
+ return this;
808
+ }
809
+
810
+ startAfter(snapshot: DocumentSnapshot): Query {
811
+ this._startAfterSnapshot = snapshot;
812
+ return this;
813
+ }
814
+
815
+ /** Keyset anchor from a raw row — no decode. Prefer one anchor kind. */
816
+ startAfterRaw(snap: RawQuerySnapshot, index: number): Query {
817
+ this._startAfterRawAnchor = { snap, index };
818
+ return this;
819
+ }
820
+
821
+ startAt(snapshot: DocumentSnapshot): Query {
822
+ this._startAtSnapshot = snapshot;
823
+ return this;
824
+ }
825
+
826
+ endAt(snapshot: DocumentSnapshot): Query {
827
+ this._endAtSnapshot = snapshot;
828
+ return this;
829
+ }
830
+
831
+ endBefore(snapshot: DocumentSnapshot): Query {
832
+ this._endBeforeSnapshot = snapshot;
833
+ return this;
834
+ }
835
+
836
+ orderBy(field: string, direction: 'asc' | 'desc' = 'asc'): Query {
837
+ this.order = { field, ascending: direction === 'asc' };
838
+ return this;
839
+ }
840
+
841
+ limit(max: number): Query {
842
+ this.queryLimit = max;
843
+ return this;
844
+ }
845
+
846
+ offset(skip: number): Query {
847
+ this.queryOffset = skip;
848
+ return this;
849
+ }
850
+
851
+ select(...fields: string[]): Query {
852
+ this.projection = fields;
853
+ return this;
854
+ }
855
+
856
+ deferBlobs(defer = true): Query {
857
+ this.deferBlobsDef = defer;
858
+ return this;
859
+ }
860
+
861
+ private prepareNativeQuery(): unknown {
862
+ const native = this.client.nativeBindings();
863
+ const handle = native.queryNew(this.collection);
864
+ if (!handle) throw new Error(`queryNew failed: ${native.lastError()}`);
865
+
866
+ try {
867
+ for (const filter of this.filters) {
868
+ switch (filter.op) {
869
+ case '==':
870
+ if (typeof filter.value === 'string') {
871
+ ensureOk(native.queryWhereEqStr(handle, filter.field, filter.value), native, 'queryWhereEqStr');
872
+ } else if (typeof filter.value === 'boolean') {
873
+ ensureOk(native.queryWhereEqBool(handle, filter.field, filter.value), native, 'queryWhereEqBool');
874
+ } else {
875
+ ensureOk(native.queryWhereEqInt(handle, filter.field, filter.value), native, 'queryWhereEqInt');
876
+ }
877
+ break;
878
+ case '!=':
879
+ case '>':
880
+ case '>=':
881
+ case '<':
882
+ case '<=':
883
+ if (typeof filter.value === 'string') {
884
+ if (filter.op === '!=') ensureOk(native.queryWhereNeStr(handle, filter.field, filter.value), native, 'queryWhereNeStr');
885
+ else if (filter.op === '>') ensureOk(native.queryWhereGtStr(handle, filter.field, filter.value), native, 'queryWhereGtStr');
886
+ else if (filter.op === '>=') ensureOk(native.queryWhereGteStr(handle, filter.field, filter.value), native, 'queryWhereGteStr');
887
+ else if (filter.op === '<') ensureOk(native.queryWhereLtStr(handle, filter.field, filter.value), native, 'queryWhereLtStr');
888
+ else ensureOk(native.queryWhereLteStr(handle, filter.field, filter.value), native, 'queryWhereLteStr');
889
+ } else {
890
+ if (filter.op === '!=') ensureOk(native.queryWhereNeInt(handle, filter.field, filter.value), native, 'queryWhereNeInt');
891
+ else if (filter.op === '>') ensureOk(native.queryWhereGtInt(handle, filter.field, filter.value), native, 'queryWhereGtInt');
892
+ else if (filter.op === '>=') ensureOk(native.queryWhereGteInt(handle, filter.field, filter.value), native, 'queryWhereGteInt');
893
+ else if (filter.op === '<') ensureOk(native.queryWhereLtInt(handle, filter.field, filter.value), native, 'queryWhereLtInt');
894
+ else ensureOk(native.queryWhereLteInt(handle, filter.field, filter.value), native, 'queryWhereLteInt');
895
+ }
896
+ break;
897
+ case 'match':
898
+ ensureOk(native.queryWhereMatch(handle, filter.field, String(filter.value)), native, 'queryWhereMatch');
899
+ break;
900
+ case 'matchPrefix':
901
+ ensureOk(native.queryWhereMatchPrefix(handle, filter.field, String(filter.value)), native, 'queryWhereMatchPrefix');
902
+ break;
903
+ case 'contains':
904
+ ensureOk(native.queryWhereContains(handle, filter.field, String(filter.value)), native, 'queryWhereContains');
905
+ break;
906
+ case 'startsWith':
907
+ ensureOk(native.queryWhereStartsWith(handle, filter.field, String(filter.value)), native, 'queryWhereStartsWith');
908
+ break;
909
+ case 'in':
910
+ case 'not-in':
911
+ case 'array-contains-any':
912
+ const arr = native.arrayNew();
913
+ (filter.value as any[]).forEach(v => {
914
+ if (typeof v === 'string') native.arrayAppendStr(arr, v);
915
+ else native.arrayAppendInt(arr, v);
916
+ });
917
+ if (filter.op === 'in') ensureOk(native.queryWhereIn(handle, filter.field, arr), native, 'queryWhereIn');
918
+ else if (filter.op === 'not-in') ensureOk(native.queryWhereNotIn(handle, filter.field, arr), native, 'queryWhereNotIn');
919
+ else ensureOk(native.queryWhereArrayContainsAny(handle, filter.field, arr), native, 'queryWhereArrayContainsAny');
920
+ break;
921
+ case 'array-contains':
922
+ if (typeof filter.value === 'string') ensureOk(native.queryWhereArrayContainsStr(handle, filter.field, filter.value), native, 'queryWhereArrayContainsStr');
923
+ else ensureOk(native.queryWhereArrayContainsInt(handle, filter.field, filter.value), native, 'queryWhereArrayContainsInt');
924
+ break;
925
+ }
926
+ }
927
+
928
+ for (const filter of this.orFilters) {
929
+ if (typeof filter.value === 'string') {
930
+ ensureOk(native.queryWhereOrStr(handle, filter.field, filter.value), native, 'queryWhereOrStr');
931
+ } else {
932
+ ensureOk(native.queryWhereOrInt(handle, filter.field, filter.value), native, 'queryWhereOrInt');
933
+ }
934
+ }
935
+
936
+ if (this._startAtSnapshot?._nativeHandle) {
937
+ ensureOk(native.queryStartAt(handle, this._startAtSnapshot._nativeHandle), native, 'queryStartAt');
938
+ }
939
+ if (this._startAfterSnapshot?._nativeHandle) {
940
+ ensureOk(native.queryStartAfter(handle, this._startAfterSnapshot._nativeHandle), native, 'queryStartAfter');
941
+ }
942
+ if (this._startAfterRawAnchor) {
943
+ ensureOk(native.queryStartAfterRaw(handle, this._startAfterRawAnchor.snap.rawHandleAt(this._startAfterRawAnchor.index)), native, 'queryStartAfterRaw');
944
+ }
945
+ if (this._endAtSnapshot?._nativeHandle) {
946
+ ensureOk(native.queryEndAt(handle, this._endAtSnapshot._nativeHandle), native, 'queryEndAt');
947
+ }
948
+ if (this._endBeforeSnapshot?._nativeHandle) {
949
+ ensureOk(native.queryEndBefore(handle, this._endBeforeSnapshot._nativeHandle), native, 'queryEndBefore');
950
+ }
951
+
952
+ if (this.order) ensureOk(native.queryOrderBy(handle, this.order.field, this.order.ascending), native, 'queryOrderBy');
953
+ if (this.queryLimit !== undefined) ensureOk(native.queryLimit(handle, this.queryLimit), native, 'queryLimit');
954
+ if (this.queryOffset !== undefined) ensureOk(native.queryOffset(handle, this.queryOffset), native, 'queryOffset');
955
+ for (const field of this.projection) ensureOk(native.querySelectField(handle, field), native, 'querySelectField');
956
+ if (this.deferBlobsDef) ensureOk(native.queryDeferBlobs(handle, true), native, 'queryDeferBlobs');
957
+
958
+ return handle;
959
+ } catch (err) {
960
+ native.queryFree(handle);
961
+ throw err;
962
+ }
963
+ }
964
+
965
+ async get(): Promise<HakoDocData[]> {
966
+ const native = this.client.nativeBindings();
967
+ const handle = this.prepareNativeQuery();
968
+ try {
969
+ return parseQueryRows(native.queryExecute(this.client.engineHandle(), handle));
970
+ } finally {
971
+ native.queryFree(handle);
972
+ }
973
+ }
974
+
975
+ /**
976
+ * Raw page: no decode, no JSON. Walk it with count/resolve, page with
977
+ * startAfterRaw, free when done. Scan-many/touch-few is the shape this
978
+ * pays for; resolving every row costs the same as get().
979
+ */
980
+ async getRaw(): Promise<RawQuerySnapshot> {
981
+ const native = this.client.nativeBindings();
982
+ const handle = this.prepareNativeQuery();
983
+ try {
984
+ const rs = native.queryExecuteRaw(this.client.engineHandle(), handle);
985
+ if (!rs) throw new Error(`queryExecuteRaw failed: ${native.lastError()}`);
986
+ return new RawQuerySnapshot(this.client, this.collection, rs);
987
+ } finally {
988
+ native.queryFree(handle);
989
+ }
990
+ }
991
+
992
+ async delete(): Promise<number> {
993
+ const native = this.client.nativeBindings();
994
+ const handle = this.prepareNativeQuery();
995
+ try {
996
+ const n = native.queryDelete(this.client.engineHandle(), handle);
997
+ if (n < 0) throw new Error(`queryDelete failed: ${native.lastError()}`);
998
+ return n;
999
+ } finally {
1000
+ native.queryFree(handle);
1001
+ }
1002
+ }
1003
+
1004
+ /** Local-only mass delete: matched docs never leave this device. */
1005
+ async deleteLocal(): Promise<number> {
1006
+ const native = this.client.nativeBindings();
1007
+ const handle = this.prepareNativeQuery();
1008
+ try {
1009
+ const n = native.queryDeleteLocal(this.client.engineHandle(), handle);
1010
+ if (n < 0) throw new Error(`queryDeleteLocal failed: ${native.lastError()}`);
1011
+ return n;
1012
+ } finally {
1013
+ native.queryFree(handle);
1014
+ }
1015
+ }
1016
+
1017
+ async patch(data: HakoDocData): Promise<number> {
1018
+ const native = this.client.nativeBindings();
1019
+ const handle = this.prepareNativeQuery();
1020
+ const patchDoc = toNativeDoc(native, data);
1021
+ try {
1022
+ const n = native.queryPatch(this.client.engineHandle(), handle, patchDoc);
1023
+ if (n < 0) throw new Error(`queryPatch failed: ${native.lastError()}`);
1024
+ return n;
1025
+ } finally {
1026
+ native.docFree(patchDoc);
1027
+ native.queryFree(handle);
1028
+ }
1029
+ }
1030
+
1031
+ async count(): Promise<number> {
1032
+ const native = this.client.nativeBindings();
1033
+ const handle = this.prepareNativeQuery();
1034
+ try {
1035
+ ensureOk(native.queryAggregateCount(handle), native, 'queryAggregateCount');
1036
+ const json = native.queryExecuteAggregation(this.client.engineHandle(), handle);
1037
+ return json ? (JSON.parse(json).count || 0) : 0;
1038
+ } finally {
1039
+ native.queryFree(handle);
1040
+ }
1041
+ }
1042
+
1043
+ async sum(field: string): Promise<number> {
1044
+ const native = this.client.nativeBindings();
1045
+ const handle = this.prepareNativeQuery();
1046
+ try {
1047
+ ensureOk(native.queryAggregateSum(handle, field), native, 'queryAggregateSum');
1048
+ const json = native.queryExecuteAggregation(this.client.engineHandle(), handle);
1049
+ return json ? (JSON.parse(json)[`sum_${field}`] || 0) : 0;
1050
+ } finally {
1051
+ native.queryFree(handle);
1052
+ }
1053
+ }
1054
+
1055
+ async avg(field: string): Promise<number> {
1056
+ const native = this.client.nativeBindings();
1057
+ const handle = this.prepareNativeQuery();
1058
+ try {
1059
+ ensureOk(native.queryAggregateAvg(handle, field), native, 'queryAggregateAvg');
1060
+ const json = native.queryExecuteAggregation(this.client.engineHandle(), handle);
1061
+ return json ? (JSON.parse(json)[`avg_${field}`] || 0) : 0;
1062
+ } finally {
1063
+ native.queryFree(handle);
1064
+ }
1065
+ }
1066
+
1067
+ onSnapshot(callback: (snapshot: HakoDocData[]) => void): Unsubscribe {
1068
+ const native = this.client.nativeBindings();
1069
+ const internalWatcher: WatchCallback = async () => {
1070
+ const data = await this.get();
1071
+ callback(data);
1072
+ };
1073
+ const watchHandle = native.engineWatch(this.client.engineHandle(), this.collection, internalWatcher);
1074
+ this.get().then(callback);
1075
+ return async () => { native.watchFree(watchHandle); };
1076
+ }
1077
+ }
1078
+
1079
+ export class WriteBatch {
1080
+ private readonly native: NativeBindings;
1081
+ private readonly handle: unknown;
1082
+ private committed = false;
1083
+
1084
+ constructor(private readonly client: HakoClient) {
1085
+ this.native = client.nativeBindings();
1086
+ this.handle = this.native.batchNew();
1087
+ if (!this.handle) throw new Error(`batchNew failed: ${this.native.lastError()}`);
1088
+ }
1089
+
1090
+ set(docRef: DocumentReference, data: HakoDocData): WriteBatch {
1091
+ this.ensureActive();
1092
+ const doc = toNativeDoc(this.native, data);
1093
+ try {
1094
+ ensureOk(this.native.batchSet(this.handle, docRef._collection, docRef._id, doc), this.native, 'batchSet');
1095
+ return this;
1096
+ } finally {
1097
+ this.native.docFree(doc);
1098
+ }
1099
+ }
1100
+
1101
+ delete(docRef: DocumentReference): WriteBatch {
1102
+ this.ensureActive();
1103
+ ensureOk(this.native.batchDelete(this.handle, docRef._collection, docRef._id), this.native, 'batchDelete');
1104
+ return this;
1105
+ }
1106
+
1107
+ async commit(): Promise<void> {
1108
+ this.ensureActive();
1109
+ ensureOk(this.native.batchCommit(this.client.engineHandle(), this.handle), this.native, 'batchCommit');
1110
+ this.native.batchFree(this.handle);
1111
+ this.committed = true;
1112
+ }
1113
+
1114
+ dispose(): void {
1115
+ if (this.committed) return;
1116
+ this.native.batchFree(this.handle);
1117
+ this.committed = true;
1118
+ }
1119
+
1120
+ private ensureActive(): void {
1121
+ if (this.committed) throw new Error('WriteBatch is already committed/disposed');
1122
+ }
1123
+ }