@harperfast/rocksdb-js 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.
@@ -0,0 +1,1152 @@
1
+ import { ExtendedIterable } from "@harperfast/extended-iterable";
2
+
3
+ //#region src/encoding.d.ts
4
+ type Key = Key[] | string | symbol | number | boolean | Uint8Array | Buffer | null;
5
+ interface BufferWithDataView extends Buffer {
6
+ dataView: DataView;
7
+ start: number;
8
+ end: number;
9
+ }
10
+ type EncoderFunction = new (options?: any) => Encoder;
11
+ interface Encoder {
12
+ copyBuffers?: boolean;
13
+ decode?: (buffer: BufferWithDataView, options?: {
14
+ end: number;
15
+ }) => any;
16
+ encode?: (value: any, mode?: number) => Buffer;
17
+ Encoder?: EncoderFunction;
18
+ freezeData?: boolean;
19
+ needsStableBuffer?: boolean;
20
+ randomAccessStructure?: boolean;
21
+ readKey?: (buffer: Buffer, start: number, end: number, inSequence?: boolean) => any;
22
+ structuredClone?: boolean;
23
+ structures?: any[];
24
+ useFloat32?: boolean;
25
+ writeKey?: (key: any, target: Buffer, position: number, inSequence?: boolean) => number;
26
+ }
27
+ type Encoding = "binary" | "ordered-binary" | "msgpack" | false;
28
+ type KeyEncoding = "binary" | "ordered-binary" | "uint32";
29
+ type ReadKeyFunction<T> = (source: BufferWithDataView, start: number, end?: number) => T;
30
+ type WriteKeyFunction = (key: Key, target: BufferWithDataView, start: number) => number;
31
+ //#endregion
32
+ //#region src/dbi-iterator.d.ts
33
+ interface DBIteratorValue<T> {
34
+ key: Key;
35
+ value: T;
36
+ }
37
+ /**
38
+ * Wraps an iterator, namely the `NativeIterator` class, and decodes the key
39
+ * and value.
40
+ */
41
+ declare class DBIterator<T> implements Iterator<DBIteratorValue<T>> {
42
+ #private;
43
+ iterator: Iterator<DBIteratorValue<T>>;
44
+ store: Store;
45
+ constructor(iterator: Iterator<DBIteratorValue<T>>, store: Store, options?: IteratorOptions & T);
46
+ [Symbol.iterator](): Iterator<DBIteratorValue<T>>;
47
+ next(...[_value]: [] | [any]): IteratorResult<DBIteratorValue<T>>;
48
+ return(value?: any): IteratorResult<DBIteratorValue<T>, any>;
49
+ throw(err: unknown): IteratorResult<DBIteratorValue<T>, any>;
50
+ }
51
+ //#endregion
52
+ //#region src/store.d.ts
53
+ type Context = NativeDatabase | NativeTransaction;
54
+ /**
55
+ * Options for the `Store` class.
56
+ */
57
+ interface StoreOptions extends Omit<NativeDatabaseOptions, "mode" | "transactionLogRetentionMs"> {
58
+ decoder?: Encoder | null;
59
+ encoder?: Encoder | null;
60
+ encoding?: Encoding;
61
+ freezeData?: boolean;
62
+ keyEncoder?: {
63
+ readKey?: ReadKeyFunction<Key>;
64
+ writeKey?: WriteKeyFunction;
65
+ };
66
+ keyEncoding?: KeyEncoding;
67
+ maxKeySize?: number;
68
+ pessimistic?: boolean;
69
+ /**
70
+ * If `true`, the encoder will use a random access structure.
71
+ */
72
+ randomAccessStructure?: boolean;
73
+ sharedStructuresKey?: symbol;
74
+ /**
75
+ * A string containing the amount of time or the number of milliseconds to
76
+ * retain transaction logs before purging.
77
+ *
78
+ * @default '3d' (3 days)
79
+ */
80
+ transactionLogRetention?: number | string;
81
+ }
82
+ /**
83
+ * Options for the `getUserSharedBuffer()` method.
84
+ */
85
+ type UserSharedBufferOptions = {
86
+ callback?: UserSharedBufferCallback;
87
+ };
88
+ /**
89
+ * The return type of `getUserSharedBuffer()`.
90
+ */
91
+ type ArrayBufferWithNotify = ArrayBuffer & {
92
+ cancel: () => void;
93
+ notify: () => void;
94
+ };
95
+ /**
96
+ * A store wraps the `NativeDatabase` binding and database settings so that a
97
+ * single database instance can be shared between the main `RocksDatabase`
98
+ * instance and the `Transaction` instance.
99
+ *
100
+ * This store should not be shared between `RocksDatabase` instances.
101
+ */
102
+ declare class Store {
103
+ /**
104
+ * The database instance.
105
+ */
106
+ db: NativeDatabase;
107
+ /**
108
+ * The decoder instance. This is commonly the same as the `encoder`
109
+ * instance.
110
+ */
111
+ decoder: Encoder | null;
112
+ /**
113
+ * Whether the decoder copies the buffer when encoding values.
114
+ */
115
+ decoderCopies: boolean;
116
+ /**
117
+ * Whether to disable the write ahead log.
118
+ */
119
+ disableWAL: boolean;
120
+ /**
121
+ * Reusable buffer for encoding values using `writeKey()` when the custom
122
+ * encoder does not provide a `encode()` method.
123
+ */
124
+ encodeBuffer: BufferWithDataView;
125
+ /**
126
+ * The encoder instance.
127
+ */
128
+ encoder: Encoder | null;
129
+ /**
130
+ * The encoding used to encode values. Defaults to `'msgpack'` in
131
+ * `RocksDatabase.open()`.
132
+ */
133
+ encoding: Encoding | null;
134
+ /**
135
+ * Encoder specific option used to signal that the data should be frozen.
136
+ */
137
+ freezeData: boolean;
138
+ /**
139
+ * Reusable buffer for encoding keys.
140
+ */
141
+ keyBuffer: BufferWithDataView;
142
+ /**
143
+ * The key encoding to use for keys. Defaults to `'ordered-binary'`.
144
+ */
145
+ keyEncoding: KeyEncoding;
146
+ /**
147
+ * The maximum key size.
148
+ */
149
+ maxKeySize: number;
150
+ /**
151
+ * The name of the store (e.g. the column family). Defaults to `'default'`.
152
+ */
153
+ name: string;
154
+ /**
155
+ * Whether to disable the block cache.
156
+ */
157
+ noBlockCache?: boolean;
158
+ /**
159
+ * The number of threads to use for parallel operations. This is a RocksDB
160
+ * option.
161
+ */
162
+ parallelismThreads: number;
163
+ /**
164
+ * The path to the database.
165
+ */
166
+ path: string;
167
+ /**
168
+ * Whether to use pessimistic locking for transactions. When `true`,
169
+ * transactions will fail as soon as a conflict is detected. When `false`,
170
+ * transactions will only fail when `commit()` is called.
171
+ */
172
+ pessimistic: boolean;
173
+ /**
174
+ * Encoder specific flag used to signal that the encoder should use a random
175
+ * access structure.
176
+ */
177
+ randomAccessStructure: boolean;
178
+ /**
179
+ * The function used to encode keys.
180
+ */
181
+ readKey: ReadKeyFunction<Key>;
182
+ /**
183
+ * The key used to store shared structures.
184
+ */
185
+ sharedStructuresKey?: symbol;
186
+ /**
187
+ * The threshold for the transaction log file's last modified time to be
188
+ * older than the retention period before it is rotated to the next sequence
189
+ * number. A threshold of 0 means ignore age check.
190
+ */
191
+ transactionLogMaxAgeThreshold?: number;
192
+ /**
193
+ * The maximum size of a transaction log before it is rotated to the next
194
+ * sequence number.
195
+ */
196
+ transactionLogMaxSize?: number;
197
+ /**
198
+ * A string containing the amount of time or the number of milliseconds to
199
+ * retain transaction logs before purging.
200
+ *
201
+ * @default '3d' (3 days)
202
+ */
203
+ transactionLogRetention?: number | string;
204
+ /**
205
+ * The path to the transaction logs directory.
206
+ */
207
+ transactionLogsPath?: string;
208
+ /**
209
+ * The function used to encode keys using the shared `keyBuffer`.
210
+ */
211
+ writeKey: WriteKeyFunction;
212
+ /**
213
+ * Initializes the store with a new `NativeDatabase` instance.
214
+ *
215
+ * @param path - The path to the database.
216
+ * @param options - The options for the store.
217
+ */
218
+ constructor(path: string, options?: StoreOptions);
219
+ /**
220
+ * Closes the database.
221
+ */
222
+ close(): void;
223
+ /**
224
+ * Decodes a key from the database.
225
+ *
226
+ * @param key - The key to decode.
227
+ * @returns The decoded key.
228
+ */
229
+ decodeKey(key: Buffer): Key;
230
+ /**
231
+ * Decodes a value from the database.
232
+ *
233
+ * @param value - The value to decode.
234
+ * @returns The decoded value.
235
+ */
236
+ decodeValue(value: BufferWithDataView): any;
237
+ /**
238
+ * Encodes a key for the database.
239
+ *
240
+ * @param key - The key to encode.
241
+ * @returns The encoded key.
242
+ */
243
+ encodeKey(key: Key): BufferWithDataView;
244
+ /**
245
+ * Encodes a value for the database.
246
+ *
247
+ * @param value - The value to encode.
248
+ * @returns The encoded value.
249
+ */
250
+ encodeValue(value: any): BufferWithDataView | Uint8Array;
251
+ get(context: NativeDatabase | NativeTransaction, key: Key, alwaysCreateNewBuffer?: boolean, txnId?: number): any | undefined;
252
+ getCount(context: NativeDatabase | NativeTransaction, options?: RangeOptions): number;
253
+ getRange(context: NativeDatabase | NativeTransaction, options?: IteratorOptions & DBITransactional): ExtendedIterable<DBIteratorValue<any>>;
254
+ getSync(context: NativeDatabase | NativeTransaction, key: Key, alwaysCreateNewBuffer?: boolean, options?: GetOptions & DBITransactional): any | undefined;
255
+ /**
256
+ * Checks if the data method options object contains a transaction ID and
257
+ * returns it.
258
+ */
259
+ getTxnId(options?: DBITransactional | unknown): number | undefined;
260
+ /**
261
+ * Gets or creates a buffer that can be shared across worker threads.
262
+ *
263
+ * @param key - The key to get or create the buffer for.
264
+ * @param defaultBuffer - The default buffer to copy and use if the buffer
265
+ * does not exist.
266
+ * @param [options] - The options for the buffer.
267
+ * @param [options.callback] - A optional callback is called when `notify()`
268
+ * on the returned buffer is called.
269
+ * @returns An `ArrayBuffer` that is internally backed by a rocksdb-js
270
+ * managed buffer. The buffer also has `notify()` and `cancel()` methods
271
+ * that can be used to notify the specified `options.callback`.
272
+ */
273
+ getUserSharedBuffer(key: Key, defaultBuffer: ArrayBuffer, options?: UserSharedBufferOptions): ArrayBufferWithNotify;
274
+ /**
275
+ * Checks if a lock exists.
276
+ * @param key The lock key.
277
+ * @returns `true` if the lock exists, `false` otherwise
278
+ */
279
+ hasLock(key: Key): boolean;
280
+ /**
281
+ * Checks if the database is open.
282
+ *
283
+ * @returns `true` if the database is open, `false` otherwise.
284
+ */
285
+ isOpen(): boolean;
286
+ /**
287
+ * Lists all transaction log names.
288
+ *
289
+ * @returns an array of transaction log names.
290
+ */
291
+ listLogs(): string[];
292
+ /**
293
+ * Opens the database. This must be called before any database operations
294
+ * are performed.
295
+ */
296
+ open(): boolean;
297
+ putSync(context: NativeDatabase | NativeTransaction, key: Key, value: any, options?: PutOptions & DBITransactional): void;
298
+ removeSync(context: NativeDatabase | NativeTransaction, key: Key, options?: DBITransactional | undefined): void;
299
+ /**
300
+ * Attempts to acquire a lock for a given key. If the lock is available,
301
+ * the function returns `true` and the optional callback is never called.
302
+ * If the lock is not available, the function returns `false` and the
303
+ * callback is queued until the lock is released.
304
+ *
305
+ * @param key - The key to lock.
306
+ * @param onUnlocked - A callback to call when the lock is released.
307
+ * @returns `true` if the lock was acquired, `false` otherwise.
308
+ */
309
+ tryLock(key: Key, onUnlocked?: () => void): boolean;
310
+ /**
311
+ * Releases the lock on the given key and calls any queued `onUnlocked`
312
+ * callback handlers.
313
+ *
314
+ * @param key - The key to unlock.
315
+ */
316
+ unlock(key: Key): void;
317
+ /**
318
+ * Gets or creates a transaction log instance.
319
+ *
320
+ * @param context - The context to use for the transaction log.
321
+ * @param name - The name of the transaction log.
322
+ * @returns The transaction log.
323
+ */
324
+ useLog(context: NativeDatabase | NativeTransaction, name: string | number): TransactionLog;
325
+ /**
326
+ * Acquires a lock on the given key and calls the callback.
327
+ *
328
+ * @param key - The key to lock.
329
+ * @param callback - The callback to call when the lock is acquired.
330
+ * @returns A promise that resolves when the lock is acquired.
331
+ */
332
+ withLock(key: Key, callback: () => void | Promise<void>): Promise<void>;
333
+ }
334
+ interface GetOptions {
335
+ /**
336
+ * Whether to skip decoding the value.
337
+ *
338
+ * @default false
339
+ */
340
+ skipDecode?: boolean;
341
+ }
342
+ interface PutOptions {
343
+ append?: boolean;
344
+ instructedWrite?: boolean;
345
+ noDupData?: boolean;
346
+ noOverwrite?: boolean;
347
+ }
348
+ //#endregion
349
+ //#region src/load-binding.d.ts
350
+ type TransactionOptions = {
351
+ /**
352
+ * Whether to disable snapshots.
353
+ *
354
+ * @default false
355
+ */
356
+ disableSnapshot?: boolean;
357
+ };
358
+ type NativeTransaction = {
359
+ id: number;
360
+ new (context: NativeDatabase, options?: TransactionOptions): NativeTransaction;
361
+ abort(): void;
362
+ commit(resolve: () => void, reject: (err: Error) => void): void;
363
+ commitSync(): void;
364
+ get(keyLengthOrKeyBuffer: number | Buffer, resolve: (value: Buffer) => void, reject: (err: Error) => void): number;
365
+ getCount(options?: RangeOptions): number;
366
+ getSync(keyLengthOrKeyBuffer: number | Buffer): Buffer | number | undefined;
367
+ getTimestamp(): number;
368
+ putSync(key: Key, value: Buffer | Uint8Array, txnId?: number): void;
369
+ removeSync(key: Key): void;
370
+ setTimestamp(timestamp?: number): void;
371
+ useLog(name: string | number): TransactionLog;
372
+ };
373
+ type LogBuffer = Buffer & {
374
+ dataView: DataView;
375
+ logId: number;
376
+ size: number;
377
+ };
378
+ type TransactionLogQueryOptions = {
379
+ start?: number;
380
+ end?: number;
381
+ exactStart?: boolean;
382
+ startFromLastFlushed?: boolean;
383
+ readUncommitted?: boolean;
384
+ exclusiveStart?: boolean;
385
+ };
386
+ type TransactionEntry = {
387
+ timestamp: number;
388
+ data: Buffer;
389
+ endTxn: boolean;
390
+ };
391
+ type TransactionLog = {
392
+ new (name: string): TransactionLog;
393
+ addEntry(data: Buffer | Uint8Array, txnId?: number): void;
394
+ query(options?: TransactionLogQueryOptions): IterableIterator<TransactionEntry>;
395
+ _getLastFlushed(): number;
396
+ _getLastCommittedPosition(): Buffer;
397
+ _getMemoryMapOfFile(sequenceId: number): LogBuffer | undefined;
398
+ getLogFileSize(sequenceId?: number): number;
399
+ _getLastCommittedPosition(): Buffer;
400
+ _findPosition(timestamp: number): number;
401
+ _lastCommittedPosition: Float64Array;
402
+ _logBuffers: Map<number, WeakRef<LogBuffer>>;
403
+ _currentLogBuffer: LogBuffer;
404
+ };
405
+ type NativeDatabaseMode = "optimistic" | "pessimistic";
406
+ type NativeDatabaseOptions = {
407
+ disableWAL?: boolean;
408
+ mode?: NativeDatabaseMode;
409
+ name?: string;
410
+ noBlockCache?: boolean;
411
+ parallelismThreads?: number;
412
+ transactionLogMaxAgeThreshold?: number;
413
+ transactionLogMaxSize?: number;
414
+ transactionLogRetentionMs?: number;
415
+ transactionLogsPath?: string;
416
+ };
417
+ type ResolveCallback<T> = (value: T) => void;
418
+ type RejectCallback = (err: Error) => void;
419
+ type UserSharedBufferCallback = () => void;
420
+ type PurgeLogsOptions = {
421
+ destroy?: boolean;
422
+ name?: string;
423
+ };
424
+ type NativeDatabase = {
425
+ new (): NativeDatabase;
426
+ addListener(event: string, callback: (...args: any[]) => void): void;
427
+ clear(resolve: ResolveCallback<void>, reject: RejectCallback): void;
428
+ clearSync(): void;
429
+ close(): void;
430
+ drop(resolve: ResolveCallback<void>, reject: RejectCallback): void;
431
+ dropSync(): void;
432
+ flush(resolve: ResolveCallback<void>, reject: RejectCallback): void;
433
+ flushSync(): void;
434
+ notify(event: string | BufferWithDataView, args?: any[]): boolean;
435
+ get(keyLengthOrKeyBuffer: number | Buffer, resolve: ResolveCallback<Buffer>, reject: RejectCallback, txnId?: number): number;
436
+ getCount(options?: RangeOptions, txnId?: number): number;
437
+ getDBIntProperty(propertyName: string): number;
438
+ getDBProperty(propertyName: string): string;
439
+ getMonotonicTimestamp(): number;
440
+ getOldestSnapshotTimestamp(): number;
441
+ getSync(keyLengthOrKeyBuffer: number | Buffer, flags: number, txnId?: number): Buffer;
442
+ getUserSharedBuffer(key: BufferWithDataView, defaultBuffer: ArrayBuffer, callback?: UserSharedBufferCallback): ArrayBuffer;
443
+ hasLock(key: BufferWithDataView): boolean;
444
+ listeners(event: string | BufferWithDataView): number;
445
+ listLogs(): string[];
446
+ opened: boolean;
447
+ open(path: string, options?: NativeDatabaseOptions): void;
448
+ purgeLogs(options?: PurgeLogsOptions): string[];
449
+ putSync(key: BufferWithDataView, value: any, txnId?: number): void;
450
+ removeListener(event: string | BufferWithDataView, callback: () => void): boolean;
451
+ removeSync(key: BufferWithDataView, txnId?: number): void;
452
+ setDefaultKeyBuffer(buffer: Buffer | Uint8Array | null): void;
453
+ setDefaultValueBuffer(buffer: Buffer | Uint8Array | null): void;
454
+ tryLock(key: BufferWithDataView, callback?: () => void): boolean;
455
+ unlock(key: BufferWithDataView): void;
456
+ useLog(name: string): TransactionLog;
457
+ withLock(key: BufferWithDataView, callback: () => void | Promise<void>): Promise<void>;
458
+ };
459
+ type RocksDatabaseConfig = {
460
+ blockCacheSize?: number;
461
+ };
462
+ declare const constants: {
463
+ TRANSACTION_LOG_TOKEN: number;
464
+ TRANSACTION_LOG_FILE_HEADER_SIZE: number;
465
+ TRANSACTION_LOG_ENTRY_HEADER_SIZE: number;
466
+ ONLY_IF_IN_MEMORY_CACHE_FLAG: number;
467
+ NOT_IN_MEMORY_CACHE_FLAG: number;
468
+ ALWAYS_CREATE_NEW_BUFFER_FLAG: number;
469
+ };
470
+ declare const NativeDatabase: NativeDatabase;
471
+ declare const NativeTransaction: NativeTransaction;
472
+ declare const TransactionLog: TransactionLog;
473
+ declare const shutdown: () => void;
474
+ //#endregion
475
+ //#region src/transaction.d.ts
476
+ /**
477
+ * Provides transaction level operations to a transaction callback.
478
+ */
479
+ declare class Transaction extends DBI {
480
+ #private;
481
+ /**
482
+ * Create a new transaction.
483
+ *
484
+ * @param store - The base store interface for this transaction.
485
+ * @param options - The options for the transaction.
486
+ */
487
+ constructor(store: Store, options?: TransactionOptions);
488
+ /**
489
+ * Abort the transaction.
490
+ */
491
+ abort(): void;
492
+ /**
493
+ * Commit the transaction.
494
+ */
495
+ commit(): Promise<void>;
496
+ /**
497
+ * Commit the transaction synchronously.
498
+ */
499
+ commitSync(): void;
500
+ /**
501
+ * Returns the transaction start timestamp in seconds. Defaults to the time at which
502
+ * the transaction was created.
503
+ *
504
+ * @returns The transaction start timestamp in seconds.
505
+ */
506
+ getTimestamp(): number;
507
+ /**
508
+ * Get the transaction id.
509
+ */
510
+ get id(): number;
511
+ /**
512
+ * Set the transaction start timestamp in seconds.
513
+ *
514
+ * @param timestamp - The timestamp to set in seconds.
515
+ */
516
+ setTimestamp(timestamp?: number): void;
517
+ }
518
+ //#endregion
519
+ //#region src/util.d.ts
520
+ type MaybePromise<T> = T | Promise<T>;
521
+ //#endregion
522
+ //#region src/dbi.d.ts
523
+ interface RocksDBOptions {
524
+ /**
525
+ * When `true`, RocksDB will do some enhancements for prefetching the data.
526
+ * Defaults to `true`. Note that RocksDB defaults this to `false`.
527
+ */
528
+ adaptiveReadahead?: boolean;
529
+ /**
530
+ * When `true`, RocksDB will prefetch some data async and apply it if reads
531
+ * are sequential and its internal automatic prefetching. Defaults to
532
+ * `true`. Note that RocksDB defaults this to `false`.
533
+ */
534
+ asyncIO?: boolean;
535
+ /**
536
+ * When `true`, RocksDB will auto-tune the readahead size during scans
537
+ * internally based on the block cache data when block caching is enabled,
538
+ * an end key (e.g. upper bound) is set, and prefix is the same as the start
539
+ * key. Defaults to `true`.
540
+ */
541
+ autoReadaheadSize?: boolean;
542
+ /**
543
+ * When `true`, after the iterator is closed, a background job is scheduled
544
+ * to flush the job queue and delete obsolete files. Defaults to `true`.
545
+ * Note that RocksDB defaults this to `false`.
546
+ */
547
+ backgroundPurgeOnIteratorCleanup?: boolean;
548
+ /**
549
+ * When `true`, the iterator will fill the block cache. Filling the block
550
+ * cache is not desirable for bulk scans and could impact eviction order.
551
+ * Defaults to `false`. Note that RocksDB defaults this to `true`.
552
+ */
553
+ fillCache?: boolean;
554
+ /**
555
+ * The RocksDB readahead size. RocksDB does auto-readahead for iterators
556
+ * when there is more than two reads for a table file. The readahead
557
+ * starts at 8KB and doubles on every additional read up to 256KB. This
558
+ * option can help if most of the range scans are large and if a larger
559
+ * readahead than that enabled by auto-readahead is needed. Using a large
560
+ * readahead size (> 2MB) can typically improve the performance of forward
561
+ * iteration on spinning disks. Defaults to `0`.
562
+ */
563
+ readaheadSize?: number;
564
+ /**
565
+ * When `true`, creates a "tailing iterator" which is a special iterator
566
+ * that has a view of the complete database including newly added data and
567
+ * is optimized for sequential reads. This will return records that were
568
+ * inserted into the database after the creation of the iterator. Defaults
569
+ * to `false`.
570
+ */
571
+ tailing?: boolean;
572
+ }
573
+ interface RangeOptions extends RocksDBOptions {
574
+ /**
575
+ * The range end key, otherwise known as the "upper bound". Defaults to
576
+ * the last key in the database.
577
+ */
578
+ end?: Key | Uint8Array;
579
+ /**
580
+ * When `true`, the iterator will exclude the first key if it matches the start key.
581
+ * Defaults to `false`.
582
+ */
583
+ exclusiveStart?: boolean;
584
+ /**
585
+ * When `true`, the iterator will include the last key if it matches the end
586
+ * key. Defaults to `false`.
587
+ */
588
+ inclusiveEnd?: boolean;
589
+ /**
590
+ * The range start key, otherwise known as the "lower bound". Defaults to
591
+ * the first key in the database.
592
+ */
593
+ start?: Key | Uint8Array;
594
+ }
595
+ interface IteratorOptions extends RangeOptions {
596
+ /**
597
+ * A specific key to match which may result in zero, one, or many values.
598
+ */
599
+ key?: Key;
600
+ /**
601
+ * When `true`, only returns the number of values for the given query.
602
+ */
603
+ onlyCount?: boolean;
604
+ /**
605
+ * When `true`, the iterator will iterate in reverse order. Defaults to
606
+ * `false`.
607
+ */
608
+ reverse?: boolean;
609
+ /**
610
+ * When `true`, decodes and returns the value. When `false`, the value is
611
+ * omitted. Defaults to `true`.
612
+ */
613
+ values?: boolean;
614
+ /**
615
+ * When `true`, the iterator will only return the values.
616
+ */
617
+ valuesOnly?: boolean;
618
+ }
619
+ interface DBITransactional {
620
+ transaction?: Transaction;
621
+ }
622
+ /**
623
+ * The base class for all database operations. This base class is shared by
624
+ * `RocksDatabase` and `Transaction`.
625
+ *
626
+ * This class is not meant to be used directly.
627
+ */
628
+ declare class DBI<T extends DBITransactional | unknown = unknown> {
629
+ #private;
630
+ /**
631
+ * The database store instance. The store instance is tied to the database
632
+ * instance and shared with transaction instances.
633
+ */
634
+ store: Store;
635
+ /**
636
+ * Initializes the DBI context.
637
+ *
638
+ * @param store - The store instance.
639
+ * @param transaction - The transaction instance.
640
+ */
641
+ constructor(store: Store, transaction?: NativeTransaction);
642
+ /**
643
+ * Adds a listener for the given key.
644
+ *
645
+ * @param event - The event name to add the listener for.
646
+ * @param callback - The callback to add.
647
+ */
648
+ addListener(event: string, callback: (...args: any[]) => void): this;
649
+ /**
650
+ * Retrieves the value for the given key, then returns the decoded value.
651
+ */
652
+ get(key: Key, options?: GetOptions & T): MaybePromise<any | undefined>;
653
+ /**
654
+ * Retrieves the binary data for the given key. This is just like `get()`,
655
+ * but bypasses the decoder.
656
+ *
657
+ * Note: Used by HDBreplication.
658
+ */
659
+ getBinary(key: Key, options?: GetOptions & T): MaybePromise<Buffer | undefined>;
660
+ /**
661
+ * Synchronously retrieves the binary data for the given key.
662
+ */
663
+ getBinarySync(key: Key, options?: GetOptions & T): Buffer | undefined;
664
+ /**
665
+ * Retrieves the binary data for the given key using a preallocated,
666
+ * reusable buffer. Data in the buffer is only valid until the next get
667
+ * operation (including cursor operations).
668
+ *
669
+ * Note: The reusable buffer slightly differs from a typical buffer:
670
+ * - `.length` is set to the size of the value
671
+ * - `.byteLength` is set to the size of the full allocated memory area for
672
+ * the buffer (usually much larger).
673
+ */
674
+ getBinaryFast(key: Key, options?: GetOptions & T): MaybePromise<Buffer | undefined>;
675
+ /**
676
+ * Synchronously retrieves the binary data for the given key using a
677
+ * preallocated, reusable buffer. Data in the buffer is only valid until the
678
+ * next get operation (including cursor operations).
679
+ */
680
+ getBinaryFastSync(key: Key, options?: GetOptions & T): Buffer | undefined;
681
+ /**
682
+ * Retrieves all keys within a range.
683
+ */
684
+ getKeys(options?: IteratorOptions & T): any | undefined;
685
+ /**
686
+ * Retrieves the number of keys within a range.
687
+ *
688
+ * @param options - The range options.
689
+ * @returns The number of keys within the range.
690
+ *
691
+ * @example
692
+ * ```typescript
693
+ * const total = db.getKeysCount();
694
+ * const range = db.getKeysCount({ start: 'a', end: 'z' });
695
+ * ```
696
+ */
697
+ getKeysCount(options?: RangeOptions & T): number;
698
+ /**
699
+ * Retrieves a range of keys and their values.
700
+ *
701
+ * @param options - The iterator options.
702
+ * @returns A range iterable.
703
+ *
704
+ * @example
705
+ * ```typescript
706
+ * for (const { key, value } of db.getRange()) {
707
+ * console.log({ key, value });
708
+ * }
709
+ *
710
+ * for (const { key, value } of db.getRange({ start: 'a', end: 'z' })) {
711
+ * console.log({ key, value });
712
+ * }
713
+ * ```
714
+ */
715
+ getRange(options?: IteratorOptions & T): any | undefined;
716
+ /**
717
+ * Synchronously retrieves the value for the given key, then returns the
718
+ * decoded value.
719
+ */
720
+ getSync(key: Key, options?: GetOptions & T): any | undefined;
721
+ /**
722
+ * Gets the number of listeners for the given key.
723
+ *
724
+ * @param event - The event name to get the listeners for.
725
+ * @returns The number of listeners for the given key.
726
+ */
727
+ listeners(event: string | BufferWithDataView): number;
728
+ /**
729
+ * Notifies an event for the given key.
730
+ *
731
+ * @param event - The event name to emit the event for.
732
+ * @param args - The arguments to emit.
733
+ * @returns `true` if there were listeners, `false` otherwise.
734
+ */
735
+ notify(event: string, ...args: any[]): boolean;
736
+ /**
737
+ * Alias for `removeListener()`.
738
+ *
739
+ * @param event - The event name to remove the listener for.
740
+ * @param callback - The callback to remove.
741
+ */
742
+ off(event: string, callback: (...args: any[]) => void): this;
743
+ /**
744
+ * Alias for `addListener()`.
745
+ *
746
+ * @param event - The event name to add the listener for.
747
+ * @param callback - The callback to add.
748
+ */
749
+ on(event: string, callback: (...args: any[]) => void): this;
750
+ /**
751
+ * Adds a one-time listener, then automatically removes it.
752
+ *
753
+ * @param event - The event name to add the listener for.
754
+ * @param callback - The callback to add.
755
+ */
756
+ once(event: string, callback: (...args: any[]) => void): this;
757
+ /**
758
+ * Stores a value for the given key.
759
+ *
760
+ * @param key - The key to store the value for.
761
+ * @param value - The value to store.
762
+ * @param options - The put options.
763
+ * @returns The key and value.
764
+ *
765
+ * @example
766
+ * ```typescript
767
+ * await db.put('a', 'b');
768
+ * ```
769
+ */
770
+ put(key: Key, value: any, options?: PutOptions & T): Promise<void>;
771
+ /**
772
+ * Synchronously stores a value for the given key.
773
+ *
774
+ * @param key - The key to store the value for.
775
+ * @param value - The value to store.
776
+ * @param options - The put options.
777
+ * @returns The key and value.
778
+ *
779
+ * @example
780
+ * ```typescript
781
+ * db.putSync('a', 'b');
782
+ * ```
783
+ */
784
+ putSync(key: Key, value: any, options?: PutOptions & T): void;
785
+ /**
786
+ * Removes a value for the given key. If the key does not exist, it will
787
+ * not error.
788
+ *
789
+ * @param key - The key to remove the value for.
790
+ * @param options - The remove options.
791
+ * @returns The key and value.
792
+ *
793
+ * @example
794
+ * ```typescript
795
+ * await db.remove('a');
796
+ * ```
797
+ */
798
+ remove(key: Key, options?: T): Promise<void>;
799
+ /**
800
+ * Removes a value for the given key. If the key does not exist, it will
801
+ * not error.
802
+ *
803
+ * @param key - The key to remove the value for.
804
+ * @param options - The remove options.
805
+ * @returns The key and value.
806
+ *
807
+ * @example
808
+ * ```typescript
809
+ * db.removeSync('a');
810
+ * ```
811
+ */
812
+ removeSync(key: Key, options?: T): void;
813
+ /**
814
+ * Removes an event listener. You must specify the exact same callback that was
815
+ * used in `addListener()`.
816
+ *
817
+ * @param event - The event name to remove the listener for.
818
+ * @param callback - The callback to remove.
819
+ */
820
+ removeListener(event: string, callback: () => void): boolean;
821
+ /**
822
+ * Get or create a transaction log instance.
823
+ *
824
+ * @param name - The name of the transaction log.
825
+ * @returns The transaction log.
826
+ */
827
+ useLog(name: string | number): TransactionLog;
828
+ }
829
+ //#endregion
830
+ //#region src/database.d.ts
831
+ interface RocksDatabaseOptions extends StoreOptions {
832
+ /**
833
+ * The column family name.
834
+ *
835
+ * @default 'default'
836
+ */
837
+ name?: string;
838
+ }
839
+ /**
840
+ * The main class for interacting with a RocksDB database.
841
+ *
842
+ * Before using this class, you must open the database first.
843
+ *
844
+ * @example
845
+ * ```typescript
846
+ * const db = RocksDatabase.open('/path/to/database');
847
+ * await db.put('key', 'value');
848
+ * const value = await db.get('key');
849
+ * db.close();
850
+ * ```
851
+ */
852
+ declare class RocksDatabase extends DBI<DBITransactional> {
853
+ constructor(pathOrStore: string | Store, options?: RocksDatabaseOptions);
854
+ /**
855
+ * Removes all data from the database asynchronously.
856
+ *
857
+ * @example
858
+ * ```typescript
859
+ * const db = RocksDatabase.open('/path/to/database');
860
+ * await db.clear();
861
+ * ```
862
+ */
863
+ clear(): Promise<void>;
864
+ /**
865
+ * Removes all entries from the database synchronously.
866
+ *
867
+ * @example
868
+ * ```typescript
869
+ * const db = RocksDatabase.open('/path/to/database');
870
+ * db.clearSync();
871
+ * ```
872
+ */
873
+ clearSync(): void;
874
+ /**
875
+ * Closes the database.
876
+ *
877
+ * @example
878
+ * ```typescript
879
+ * const db = RocksDatabase.open('/path/to/database');
880
+ * db.close();
881
+ * ```
882
+ */
883
+ close(): void;
884
+ /**
885
+ * Set global database settings.
886
+ *
887
+ * @param options - The options for the database.
888
+ *
889
+ * @example
890
+ * ```typescript
891
+ * RocksDatabase.config({ blockCacheSize: 1024 * 1024 });
892
+ * ```
893
+ */
894
+ static config(options: RocksDatabaseConfig): void;
895
+ drop(): Promise<void>;
896
+ dropSync(): void;
897
+ get encoder(): Encoder | null;
898
+ /**
899
+ * Returns the current timestamp as a monotonically increasing timestamp in
900
+ * milliseconds represented as a decimal number.
901
+ *
902
+ * @returns The current monotonic timestamp in milliseconds.
903
+ */
904
+ getMonotonicTimestamp(): number;
905
+ /**
906
+ * Returns a number representing a unix timestamp of the oldest unreleased
907
+ * snapshot.
908
+ *
909
+ * @returns The oldest snapshot timestamp.
910
+ */
911
+ getOldestSnapshotTimestamp(): number;
912
+ /**
913
+ * Gets a RocksDB database property as a string.
914
+ *
915
+ * @param propertyName - The name of the property to retrieve (e.g., 'rocksdb.levelstats').
916
+ * @returns The property value as a string.
917
+ *
918
+ * @example
919
+ * ```typescript
920
+ * const db = RocksDatabase.open('/path/to/database');
921
+ * const levelStats = db.getDBProperty('rocksdb.levelstats');
922
+ * const stats = db.getDBProperty('rocksdb.stats');
923
+ * ```
924
+ */
925
+ getDBProperty(propertyName: string): string;
926
+ /**
927
+ * Gets a RocksDB database property as an integer.
928
+ *
929
+ * @param propertyName - The name of the property to retrieve (e.g., 'rocksdb.num-blob-files').
930
+ * @returns The property value as a number.
931
+ *
932
+ * @example
933
+ * ```typescript
934
+ * const db = RocksDatabase.open('/path/to/database');
935
+ * const blobFiles = db.getDBIntProperty('rocksdb.num-blob-files');
936
+ * const numKeys = db.getDBIntProperty('rocksdb.estimate-num-keys');
937
+ * ```
938
+ */
939
+ getDBIntProperty(propertyName: string): number;
940
+ /**
941
+ * Flushes the underlying database by performing a commit or clearing any buffered operations.
942
+ *
943
+ * @return {void} Does not return a value.
944
+ */
945
+ flush(): Promise<void>;
946
+ /**
947
+ * Synchronously flushes the underlying database by performing a commit or clearing any buffered operations.
948
+ *
949
+ * @return {void} Does not return a value.
950
+ */
951
+ flushSync(): void;
952
+ getStats(): {
953
+ free: {};
954
+ root: {};
955
+ };
956
+ /**
957
+ * Gets or creates a buffer that can be shared across worker threads.
958
+ *
959
+ * @param key - The key to get or create the buffer for.
960
+ * @param defaultBuffer - The default buffer to copy and use if the buffer
961
+ * does not exist.
962
+ * @param [options] - The options for the buffer.
963
+ * @param [options.callback] - A optional callback that receives
964
+ * key-specific events.
965
+ * @returns An `ArrayBuffer` that is internally backed by a shared block of
966
+ * memory. The buffer also has `notify()` and `cancel()` methods that can be
967
+ * used to notify the specified `options.callback`.
968
+ *
969
+ * @example
970
+ * ```typescript
971
+ * const db = RocksDatabase.open('/path/to/database');
972
+ * const buffer = db.getUserSharedBuffer('foo', new ArrayBuffer(10));
973
+ */
974
+ getUserSharedBuffer(key: Key, defaultBuffer: ArrayBuffer, options?: UserSharedBufferOptions): ArrayBufferWithNotify;
975
+ /**
976
+ * Returns whether the database has a lock for the given key.
977
+ *
978
+ * @param key - The key to check.
979
+ * @returns `true` if the database has a lock for the given key, `false`
980
+ * otherwise.
981
+ *
982
+ * @example
983
+ * ```typescript
984
+ * const db = RocksDatabase.open('/path/to/database');
985
+ * db.hasLock('foo'); // false
986
+ * db.tryLock('foo', () => {});
987
+ * db.hasLock('foo'); // true
988
+ * ```
989
+ */
990
+ hasLock(key: Key): boolean;
991
+ ifNoExists(_key: Key): Promise<void>;
992
+ /**
993
+ * Returns whether the database is open.
994
+ *
995
+ * @returns `true` if the database is open, `false` otherwise.
996
+ */
997
+ isOpen(): boolean;
998
+ /**
999
+ * Lists all transaction log names.
1000
+ *
1001
+ * @returns an array of transaction log names.
1002
+ */
1003
+ listLogs(): string[];
1004
+ /**
1005
+ * Sugar method for opening a database.
1006
+ *
1007
+ * @param pathOrStore - The filesystem path to the database or a custom store.
1008
+ * @param options - The options for the database.
1009
+ * @returns A new RocksDatabase instance.
1010
+ *
1011
+ * @example
1012
+ * ```typescript
1013
+ * const db = RocksDatabase.open('/path/to/database');
1014
+ * ```
1015
+ */
1016
+ static open(pathOrStore: string | Store, options?: RocksDatabaseOptions): RocksDatabase;
1017
+ /**
1018
+ * Opens the database. This function returns immediately if the database is
1019
+ * already open.
1020
+ *
1021
+ * @returns A new RocksDatabase instance.
1022
+ *
1023
+ * @example
1024
+ * ```typescript
1025
+ * const db = new RocksDatabase('/path/to/database');
1026
+ * db.open();
1027
+ * ```
1028
+ */
1029
+ open(): RocksDatabase;
1030
+ /**
1031
+ * Returns the path to the database.
1032
+ */
1033
+ get path(): string;
1034
+ /**
1035
+ * Purges transaction logs.
1036
+ */
1037
+ purgeLogs(options?: PurgeLogsOptions): string[];
1038
+ /**
1039
+ * Executes all operations in the callback as a single transaction.
1040
+ *
1041
+ * @param callback - A async function that receives the transaction as an argument.
1042
+ * @returns A promise that resolves the `callback` return value.
1043
+ *
1044
+ * @example
1045
+ * ```typescript
1046
+ * const db = RocksDatabase.open('/path/to/database');
1047
+ * await db.transaction(async (txn) => {
1048
+ * await txn.put('key', 'value');
1049
+ * });
1050
+ * ```
1051
+ */
1052
+ transaction<T>(callback: (txn: Transaction) => T | PromiseLike<T>, options?: TransactionOptions): Promise<T | PromiseLike<T>>;
1053
+ /**
1054
+ * Executes all operations in the callback as a single transaction.
1055
+ *
1056
+ * @param callback - A function that receives the transaction as an
1057
+ * argument. If the callback return promise-like value, it is awaited
1058
+ * before committing the transaction. Otherwise, the callback is treated as
1059
+ * synchronous.
1060
+ * @returns The `callback` return value.
1061
+ *
1062
+ * @example
1063
+ * ```typescript
1064
+ * const db = RocksDatabase.open('/path/to/database');
1065
+ * await db.transaction(async (txn) => {
1066
+ * await txn.put('key', 'value');
1067
+ * });
1068
+ * ```
1069
+ */
1070
+ transactionSync<T>(callback: (txn: Transaction) => T | PromiseLike<T>, options?: TransactionOptions): T | PromiseLike<T> | undefined;
1071
+ /**
1072
+ * Attempts to acquire a lock for a given key. If the lock is available,
1073
+ * the function returns `true` and the optional callback is never called.
1074
+ * If the lock is not available, the function returns `false` and the
1075
+ * callback is queued until the lock is released.
1076
+ *
1077
+ * @param key - The key to lock.
1078
+ * @param onUnlocked - A callback to call when the lock is released.
1079
+ *
1080
+ * @example
1081
+ * ```typescript
1082
+ * const db = RocksDatabase.open('/path/to/database');
1083
+ * db.tryLock('foo', () => {
1084
+ * console.log('lock acquired');
1085
+ * });
1086
+ * ```
1087
+ * @returns `true` if the lock was acquired, `false` otherwise.
1088
+ */
1089
+ tryLock(key: Key, onUnlocked?: () => void): boolean;
1090
+ /**
1091
+ * Releases the lock on the given key and calls any queued `onUnlocked`
1092
+ * callback handlers.
1093
+ *
1094
+ * @param key - The key to unlock.
1095
+ * @returns `true` if the lock was released or `false` if the lock did not
1096
+ * exist.
1097
+ *
1098
+ * @example
1099
+ * ```typescript
1100
+ * const db = RocksDatabase.open('/path/to/database');
1101
+ * db.tryLock('foo', () => {});
1102
+ * db.unlock('foo'); // returns `true`
1103
+ * db.unlock('foo'); // already unlocked, returns `false`
1104
+ * ```
1105
+ */
1106
+ unlock(key: Key): void;
1107
+ /**
1108
+ * Excecutes a function using a thread-safe lock to ensure mutual
1109
+ * exclusion.
1110
+ *
1111
+ * @param callback - A callback to call when the lock is acquired.
1112
+ * @returns A promise that resolves when the lock is acquired.
1113
+ *
1114
+ * @example
1115
+ * ```typescript
1116
+ * const db = RocksDatabase.open('/path/to/database');
1117
+ * await db.withLock(async (waited) => {
1118
+ * console.log('lock acquired', waited);
1119
+ * });
1120
+ * ```
1121
+ */
1122
+ withLock(key: Key, callback: () => void | Promise<void>): Promise<void> | undefined;
1123
+ }
1124
+ //#endregion
1125
+ //#region src/parse-transaction-log.d.ts
1126
+ interface LogEntry {
1127
+ data: Buffer;
1128
+ flags: number;
1129
+ length: number;
1130
+ timestamp?: number;
1131
+ }
1132
+ interface TransactionLog$1 {
1133
+ entries: LogEntry[];
1134
+ timestamp: number;
1135
+ size: number;
1136
+ version: number;
1137
+ }
1138
+ /**
1139
+ * Loads an entire transaction log file into memory.
1140
+ * @param path - The path to the transaction log file.
1141
+ * @returns The transaction log.
1142
+ */
1143
+ declare function parseTransactionLog(path: string): TransactionLog$1;
1144
+ //#endregion
1145
+ //#region src/index.d.ts
1146
+ declare const versions: {
1147
+ rocksdb: string;
1148
+ "rocksdb-js": string;
1149
+ };
1150
+ //#endregion
1151
+ export { type Context, DBIterator, type Key, RocksDatabase, type RocksDatabaseOptions, Store, Transaction, type TransactionEntry, TransactionLog, constants, parseTransactionLog, shutdown, versions };
1152
+ //# sourceMappingURL=index.d.mts.map