keyv 6.0.0-alpha.3 → 6.0.0-beta.1

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,1351 @@
1
+ import { Hookified, IEventEmitter } from "hookified";
2
+
3
+ //#region src/capabilities.d.ts
4
+ type MethodType = "sync" | "async" | "none";
5
+ type KeyvStorageMethod = {
6
+ exists: boolean;
7
+ methodType: MethodType;
8
+ };
9
+ declare const keyvMethodNames: readonly ["get", "set", "delete", "clear", "has", "getMany", "setMany", "deleteMany", "hasMany", "disconnect", "getRaw", "getManyRaw", "setRaw", "setManyRaw", "iterator"];
10
+ declare const keyvPropertyNames: readonly ["hooks", "stats"];
11
+ type KeyvMethods = Record<(typeof keyvMethodNames)[number], KeyvStorageMethod>;
12
+ type KeyvProperties = Record<(typeof keyvPropertyNames)[number], boolean>;
13
+ type KeyvCapability = {
14
+ compatible: boolean;
15
+ methods: KeyvMethods;
16
+ properties: KeyvProperties;
17
+ };
18
+ declare const keyvStorageMethodNames: readonly ["get", "getMany", "has", "hasMany", "set", "setMany", "delete", "deleteMany", "clear", "disconnect", "iterator"];
19
+ type KeyvStorageMethods = Record<(typeof keyvStorageMethodNames)[number], KeyvStorageMethod>;
20
+ type KeyvStorageCapability = {
21
+ compatible: boolean;
22
+ store: "mapLike" | "keyvStorage" | "asyncMap" | "none";
23
+ methods: KeyvStorageMethods;
24
+ };
25
+ declare const keyvCompressionMethodNames: readonly ["compress", "decompress"];
26
+ type KeyvCompressionMethods = Record<(typeof keyvCompressionMethodNames)[number], KeyvStorageMethod>;
27
+ type KeyvCompressionCapability = {
28
+ compatible: boolean;
29
+ methods: KeyvCompressionMethods;
30
+ };
31
+ declare const keyvSerializationMethodNames: readonly ["stringify", "parse"];
32
+ type KeyvSerializationMethods = Record<(typeof keyvSerializationMethodNames)[number], KeyvStorageMethod>;
33
+ type KeyvSerializationCapability = {
34
+ compatible: boolean;
35
+ methods: KeyvSerializationMethods;
36
+ };
37
+ declare const keyvEncryptionMethodNames: readonly ["encrypt", "decrypt"];
38
+ type KeyvEncryptionMethods = Record<(typeof keyvEncryptionMethodNames)[number], KeyvStorageMethod>;
39
+ type KeyvEncryptionCapability = {
40
+ compatible: boolean;
41
+ methods: KeyvEncryptionMethods;
42
+ };
43
+ /**
44
+ * Detect whether an object implements the full Keyv interface
45
+ * @param obj - The object to check
46
+ * @returns A {@link KeyvCapability} where `compatible` is `true` only when all required capabilities are present
47
+ * @example
48
+ * ```typescript
49
+ * import Keyv, { detectKeyv } from 'keyv';
50
+ *
51
+ * const result = detectKeyv(new Keyv());
52
+ * result.compatible; // true — all capabilities present
53
+ * result.methods.get.exists; // true
54
+ * result.methods.get.methodType; // "async"
55
+ *
56
+ * const partial = detectKeyv(new Map());
57
+ * partial.compatible; // false — missing getMany, setMany, hooks, stats, etc.
58
+ * partial.methods.get.exists; // true
59
+ * ```
60
+ */
61
+ declare function detectKeyv(obj: unknown): KeyvCapability;
62
+ /**
63
+ * Detect whether an object implements the Keyv storage adapter interface
64
+ * @param obj - The object to check
65
+ * @returns A {@link KeyvStorageCapability} where:
66
+ * - `compatible` is `true` when the object is a valid storage adapter (`"keyvStorage"`, `"mapLike"`, or `"asyncMap"`)
67
+ * - `store` indicates the detected store type: `"keyvStorage"`, `"mapLike"`, `"asyncMap"`, or `"none"`
68
+ * - `methods` maps each method name to `{ exists, methodType }`
69
+ * @example
70
+ * ```typescript
71
+ * import { detectKeyvStorage } from 'keyv';
72
+ *
73
+ * const map = detectKeyvStorage(new Map());
74
+ * map.compatible; // true
75
+ * map.store; // "mapLike"
76
+ * map.methods.get.exists; // true
77
+ * map.methods.get.methodType; // "sync"
78
+ *
79
+ * const adapter = detectKeyvStorage(asyncAdapter);
80
+ * adapter.compatible; // true
81
+ * adapter.store; // "keyvStorage"
82
+ * adapter.methods.get.methodType; // "async"
83
+ * ```
84
+ */
85
+ declare function detectKeyvStorage(obj: unknown): KeyvStorageCapability;
86
+ /**
87
+ * Detect whether an object implements the Keyv compression adapter interface
88
+ * @param obj - The object to check
89
+ * @returns A {@link KeyvCompressionCapability} where `compatible` is `true` when both `compress` and `decompress` methods are present
90
+ * @example
91
+ * ```typescript
92
+ * import { detectKeyvCompression } from 'keyv';
93
+ *
94
+ * detectKeyvCompression({ compress: (d) => d, decompress: (d) => d });
95
+ * // { compatible: true, methods: { compress: { exists: true, methodType: "sync" }, decompress: { exists: true, methodType: "sync" } } }
96
+ * ```
97
+ */
98
+ declare function detectKeyvCompression(obj: unknown): KeyvCompressionCapability;
99
+ /**
100
+ * Detect whether an object implements the Keyv serialization adapter interface
101
+ * @param obj - The object to check
102
+ * @returns A {@link KeyvSerializationCapability} where `compatible` is `true` when both `stringify` and `parse` methods are present
103
+ * @example
104
+ * ```typescript
105
+ * import { detectKeyvSerialization } from 'keyv';
106
+ *
107
+ * detectKeyvSerialization(JSON);
108
+ * // { compatible: true, methods: { stringify: { exists: true, methodType: "sync" }, parse: { exists: true, methodType: "sync" } } }
109
+ * ```
110
+ */
111
+ declare function detectKeyvSerialization(obj: unknown): KeyvSerializationCapability;
112
+ /**
113
+ * Detect whether an object implements the Keyv encryption adapter interface
114
+ * @param obj - The object to check
115
+ * @returns A {@link KeyvEncryptionCapability} where `compatible` is `true` when both `encrypt` and `decrypt` methods are present
116
+ * @example
117
+ * ```typescript
118
+ * import { detectKeyvEncryption } from 'keyv';
119
+ *
120
+ * detectKeyvEncryption({ encrypt: (d) => d, decrypt: (d) => d });
121
+ * // { compatible: true, methods: { encrypt: { exists: true, methodType: "sync" }, decrypt: { exists: true, methodType: "sync" } } }
122
+ * ```
123
+ */
124
+ declare function detectKeyvEncryption(obj: unknown): KeyvEncryptionCapability;
125
+ //#endregion
126
+ //#region src/sanitize.d.ts
127
+ /**
128
+ * Which dangerous-pattern categories to detect and strip.
129
+ * Each defaults to `true` when the parent scope is enabled.
130
+ */
131
+ type KeyvSanitizePatterns = {
132
+ /**
133
+ * Detect and strip SQL injection patterns: semicolons (`;`), SQL comments (`--` and `/*`).
134
+ * @default false
135
+ */
136
+ sql: boolean;
137
+ /**
138
+ * Detect and strip MongoDB operator patterns: leading `$`, `{$` sequences.
139
+ * @default false
140
+ */
141
+ mongo: boolean;
142
+ /**
143
+ * Detect and strip dangerous control sequences: null bytes (`\0`), carriage returns (`\r`), newlines (`\n`).
144
+ * @default false
145
+ */
146
+ escape: boolean;
147
+ /**
148
+ * Detect and strip path traversal patterns: `../` and `..\\` sequences.
149
+ * @default false
150
+ */
151
+ path: boolean;
152
+ };
153
+ /**
154
+ * Options for configuring sanitization pattern categories.
155
+ * All categories default to `true` when the parent scope is enabled.
156
+ */
157
+ type KeyvSanitizePatternsOptions = {
158
+ /**
159
+ * Detect and strip SQL injection patterns: semicolons (`;`), SQL comments (`--` and `/*`).
160
+ * @default true
161
+ */
162
+ sql?: boolean;
163
+ /**
164
+ * Detect and strip MongoDB operator patterns: leading `$`, `{$` sequences.
165
+ * @default true
166
+ */
167
+ mongo?: boolean;
168
+ /**
169
+ * Detect and strip dangerous control sequences: null bytes (`\0`), carriage returns (`\r`), newlines (`\n`).
170
+ * @default true
171
+ */
172
+ escape?: boolean;
173
+ /**
174
+ * Detect and strip path traversal patterns: `../` and `..\\` sequences.
175
+ * @default true
176
+ */
177
+ path?: boolean;
178
+ };
179
+ /**
180
+ * Controls what gets sanitized and with which patterns.
181
+ */
182
+ type KeyvSanitizeOptions = {
183
+ /**
184
+ * Sanitize keys. Pass `true` for all pattern categories, `false` to skip,
185
+ * or a `KeyvSanitizePatternOptions` object for granular control.
186
+ * @default false
187
+ */
188
+ keys?: boolean | KeyvSanitizePatternsOptions;
189
+ /**
190
+ * Sanitize namespace strings. Pass `true` for all pattern categories, `false` to skip,
191
+ * or a `KeyvSanitizePatternOptions` object for granular control.
192
+ * @default false
193
+ */
194
+ namespace?: boolean | KeyvSanitizePatternsOptions;
195
+ };
196
+ /**
197
+ * Adapter interface for key and namespace sanitization.
198
+ * Implement this to provide custom sanitization logic to Keyv.
199
+ */
200
+ type KeyvSanitizeAdapter = {
201
+ /** Whether any sanitization is currently enabled. */readonly enabled: boolean; /** The key sanitization pattern configuration. */
202
+ readonly keys: KeyvSanitizePatterns; /** The namespace sanitization pattern configuration. */
203
+ readonly namespace: KeyvSanitizePatterns; /** Sanitize a single key. */
204
+ cleanKey(key: string): string; /** Sanitize an array of keys. */
205
+ cleanKeys(keys: string[]): string[]; /** Sanitize a namespace string. */
206
+ cleanNamespace(ns: string): string;
207
+ };
208
+ /**
209
+ * Encapsulates key and namespace sanitization with an LRU result cache.
210
+ */
211
+ declare class KeyvSanitize implements KeyvSanitizeAdapter {
212
+ private _keys;
213
+ private _namespace;
214
+ private _keyPatterns;
215
+ private _namespacePatterns;
216
+ private _enabled;
217
+ private _cacheKeys;
218
+ private _cacheNamespaces;
219
+ private _cacheMax;
220
+ constructor(options?: KeyvSanitizeOptions);
221
+ /**
222
+ * The key sanitization pattern configuration.
223
+ */
224
+ get keys(): KeyvSanitizePatterns;
225
+ /**
226
+ * Whether any sanitization pattern (keys or namespace) is enabled.
227
+ */
228
+ get enabled(): boolean;
229
+ /**
230
+ * The namespace sanitization pattern configuration.
231
+ */
232
+ get namespace(): KeyvSanitizePatterns;
233
+ /**
234
+ * Update the sanitization configuration. Recompiles patterns and clears the cache.
235
+ */
236
+ updateOptions(options: KeyvSanitizeOptions): void;
237
+ /**
238
+ * Sanitize a single key. Uses an LRU cache for repeated lookups.
239
+ */
240
+ cleanKey(key: string): string;
241
+ /**
242
+ * Sanitize an array of keys.
243
+ */
244
+ cleanKeys(keys: string[]): string[];
245
+ /**
246
+ * Sanitize a namespace string. Uses an LRU cache for repeated lookups.
247
+ */
248
+ cleanNamespace(ns: string): string;
249
+ /**
250
+ * Clear the LRU caches.
251
+ */
252
+ clearCache(): void;
253
+ private resolvePatterns;
254
+ }
255
+ //#endregion
256
+ //#region src/stats.d.ts
257
+ /**
258
+ * Structure of a telemetry event emitted by Keyv.
259
+ */
260
+ type KeyvTelemetryEvent = {
261
+ /** The event type (e.g. "hit", "miss", "set", "delete", "error"). */event: string; /** The cache key involved, if applicable. */
262
+ key?: string; /** The namespace of the Keyv instance. */
263
+ namespace?: string; /** Unix timestamp in milliseconds when the event occurred. */
264
+ timestamp: number;
265
+ };
266
+ type KeyvStatsOptions = {
267
+ /**
268
+ * Enable or disable stats tracking.
269
+ * @default false
270
+ */
271
+ enabled?: boolean;
272
+ /**
273
+ * Maximum number of entries per event-type LRU map.
274
+ * @default 1000
275
+ */
276
+ maxEntries?: number;
277
+ /**
278
+ * The event emitter (e.g. a Keyv instance) to subscribe to for telemetry events.
279
+ * If provided, KeyvStats will automatically subscribe on construction.
280
+ */
281
+ emitter?: IEventEmitter;
282
+ };
283
+ declare class KeyvStats {
284
+ private _hits;
285
+ private _misses;
286
+ private _sets;
287
+ private _deletes;
288
+ private _errors;
289
+ private _maxEntries;
290
+ private _enabled;
291
+ private readonly hitKeysMap;
292
+ private readonly missKeysMap;
293
+ private readonly setKeysMap;
294
+ private readonly deleteKeysMap;
295
+ private readonly errorKeysMap;
296
+ private _emitter?;
297
+ private readonly _listeners;
298
+ constructor(options?: KeyvStatsOptions);
299
+ /**
300
+ * Total number of cache hits.
301
+ */
302
+ get hits(): number;
303
+ /**
304
+ * Total number of cache misses.
305
+ */
306
+ get misses(): number;
307
+ /**
308
+ * Total number of cache sets.
309
+ */
310
+ get sets(): number;
311
+ /**
312
+ * Total number of cache deletes.
313
+ */
314
+ get deletes(): number;
315
+ /**
316
+ * Total number of cache errors.
317
+ */
318
+ get errors(): number;
319
+ /**
320
+ * LRU-bounded map of key to hit count.
321
+ */
322
+ get hitKeys(): Map<string, number>;
323
+ /**
324
+ * LRU-bounded map of key to miss count.
325
+ */
326
+ get missKeys(): Map<string, number>;
327
+ /**
328
+ * LRU-bounded map of key to set count.
329
+ */
330
+ get setKeys(): Map<string, number>;
331
+ /**
332
+ * LRU-bounded map of key to delete count.
333
+ */
334
+ get deleteKeys(): Map<string, number>;
335
+ /**
336
+ * LRU-bounded map of key to error count.
337
+ */
338
+ get errorKeys(): Map<string, number>;
339
+ /**
340
+ * Maximum number of entries per event-type LRU map.
341
+ * @default 1000
342
+ */
343
+ get maxEntries(): number;
344
+ /**
345
+ * Set the maximum number of entries per event-type LRU map.
346
+ * @param {number} value the new maximum entries
347
+ */
348
+ set maxEntries(value: number);
349
+ /**
350
+ * Whether stats tracking is enabled.
351
+ * @default false
352
+ */
353
+ get enabled(): boolean;
354
+ /**
355
+ * Enable or disable stats tracking. If false it will unsubscribe from the events
356
+ * @param {boolean} value true to enable, false to disable
357
+ */
358
+ set enabled(value: boolean);
359
+ /**
360
+ * Build a composite key from a telemetry event.
361
+ * Format: "namespace:key" if namespace is present, otherwise just "key".
362
+ */
363
+ buildKeyEventName(event: KeyvTelemetryEvent): string;
364
+ /**
365
+ * Increment the count for a key in an LRU-bounded map.
366
+ * Deletes and re-inserts to maintain LRU order, evicts the oldest entry when full.
367
+ */
368
+ incrementKeys(map: Map<string, number>, compositeKey: string): void;
369
+ /**
370
+ * Subscribe to telemetry events from an emitter (e.g. a Keyv instance).
371
+ * Automatically increments the corresponding stat counters and LRU key maps on each event.
372
+ * @param {IEventEmitter} emitter the event emitter to subscribe to
373
+ */
374
+ subscribe(emitter: IEventEmitter): void;
375
+ /**
376
+ * Unsubscribe from the currently subscribed emitter, removing all telemetry event listeners.
377
+ */
378
+ unsubscribe(): void;
379
+ /**
380
+ * Reset all counters and LRU key maps to their initial state.
381
+ */
382
+ reset(): void;
383
+ }
384
+ //#endregion
385
+ //#region src/types/keyv.d.ts
386
+ /**
387
+ * A Map or any Map-like object. Used as a flexible input type for stores.
388
+ */
389
+ type KeyvMapAny = Map<any, any> | any;
390
+ /**
391
+ * The envelope structure used to store values in Keyv.
392
+ * Wraps the actual value with an optional expiration timestamp.
393
+ */
394
+ type KeyvValue<Value> = {
395
+ /** The stored value. */value?: Value; /** Absolute expiration timestamp in milliseconds since epoch, or `undefined` for no expiry. */
396
+ expires?: number | undefined;
397
+ };
398
+ /** @deprecated Use `KeyvValue` instead. */
399
+ type DeserializedData<Value> = KeyvValue<Value>;
400
+ /**
401
+ * Events emitted by Keyv for error handling and telemetry.
402
+ */
403
+ declare enum KeyvEvents {
404
+ /** Emitted when an error occurs in a store operation. */
405
+ ERROR = "error",
406
+ /** Emitted for informational messages. */
407
+ INFO = "info",
408
+ /** Emitted for warning messages. */
409
+ WARN = "warn",
410
+ /** Telemetry: cache hit. */
411
+ STAT_HIT = "stat:hit",
412
+ /** Telemetry: cache miss. */
413
+ STAT_MISS = "stat:miss",
414
+ /** Telemetry: value set. */
415
+ STAT_SET = "stat:set",
416
+ /** Telemetry: value deleted. */
417
+ STAT_DELETE = "stat:delete",
418
+ /** Telemetry: operation error. */
419
+ STAT_ERROR = "stat:error"
420
+ }
421
+ /**
422
+ * Hook names for intercepting Keyv operations.
423
+ * Register hooks via `keyv.on(KeyvHooks.BEFORE_SET, callback)` to run logic before/after operations.
424
+ */
425
+ declare enum KeyvHooks {
426
+ /** @deprecated Use BEFORE_SET instead */
427
+ PRE_SET = "preSet",
428
+ /** @deprecated Use AFTER_SET instead */
429
+ POST_SET = "postSet",
430
+ /** @deprecated Use BEFORE_GET instead */
431
+ PRE_GET = "preGet",
432
+ /** @deprecated Use AFTER_GET instead */
433
+ POST_GET = "postGet",
434
+ /** @deprecated Use BEFORE_GET_MANY instead */
435
+ PRE_GET_MANY = "preGetMany",
436
+ /** @deprecated Use AFTER_GET_MANY instead */
437
+ POST_GET_MANY = "postGetMany",
438
+ /** @deprecated Use BEFORE_GET_RAW instead */
439
+ PRE_GET_RAW = "preGetRaw",
440
+ /** @deprecated Use AFTER_GET_RAW instead */
441
+ POST_GET_RAW = "postGetRaw",
442
+ /** @deprecated Use BEFORE_GET_MANY_RAW instead */
443
+ PRE_GET_MANY_RAW = "preGetManyRaw",
444
+ /** @deprecated Use AFTER_GET_MANY_RAW instead */
445
+ POST_GET_MANY_RAW = "postGetManyRaw",
446
+ /** @deprecated Use BEFORE_SET_RAW instead */
447
+ PRE_SET_RAW = "preSetRaw",
448
+ /** @deprecated Use AFTER_SET_RAW instead */
449
+ POST_SET_RAW = "postSetRaw",
450
+ /** @deprecated Use BEFORE_SET_MANY_RAW instead */
451
+ PRE_SET_MANY_RAW = "preSetManyRaw",
452
+ /** @deprecated Use AFTER_SET_MANY_RAW instead */
453
+ POST_SET_MANY_RAW = "postSetManyRaw",
454
+ /** @deprecated Use BEFORE_SET_MANY instead */
455
+ PRE_SET_MANY = "preSetMany",
456
+ /** @deprecated Use AFTER_SET_MANY instead */
457
+ POST_SET_MANY = "postSetMany",
458
+ /** @deprecated Use BEFORE_DELETE instead */
459
+ PRE_DELETE = "preDelete",
460
+ /** @deprecated Use AFTER_DELETE instead */
461
+ POST_DELETE = "postDelete",
462
+ /** @deprecated Use BEFORE_DELETE_MANY instead */
463
+ PRE_DELETE_MANY = "preDeleteMany",
464
+ /** @deprecated Use AFTER_DELETE_MANY instead */
465
+ POST_DELETE_MANY = "postDeleteMany",
466
+ BEFORE_SET = "before:set",
467
+ AFTER_SET = "after:set",
468
+ BEFORE_GET = "before:get",
469
+ AFTER_GET = "after:get",
470
+ BEFORE_GET_MANY = "before:getMany",
471
+ AFTER_GET_MANY = "after:getMany",
472
+ BEFORE_GET_RAW = "before:getRaw",
473
+ AFTER_GET_RAW = "after:getRaw",
474
+ BEFORE_GET_MANY_RAW = "before:getManyRaw",
475
+ AFTER_GET_MANY_RAW = "after:getManyRaw",
476
+ BEFORE_SET_RAW = "before:setRaw",
477
+ AFTER_SET_RAW = "after:setRaw",
478
+ BEFORE_SET_MANY = "before:setMany",
479
+ AFTER_SET_MANY = "after:setMany",
480
+ BEFORE_SET_MANY_RAW = "before:setManyRaw",
481
+ AFTER_SET_MANY_RAW = "after:setManyRaw",
482
+ BEFORE_DELETE = "before:delete",
483
+ AFTER_DELETE = "after:delete",
484
+ BEFORE_DELETE_MANY = "before:deleteMany",
485
+ AFTER_DELETE_MANY = "after:deleteMany",
486
+ BEFORE_HAS = "before:has",
487
+ AFTER_HAS = "after:has",
488
+ BEFORE_HAS_MANY = "before:hasMany",
489
+ AFTER_HAS_MANY = "after:hasMany",
490
+ BEFORE_CLEAR = "before:clear",
491
+ AFTER_CLEAR = "after:clear",
492
+ BEFORE_DISCONNECT = "before:disconnect",
493
+ AFTER_DISCONNECT = "after:disconnect"
494
+ }
495
+ /**
496
+ * Represents a key-value entry with an optional TTL, used for batch operations like `setMany`.
497
+ */
498
+ type KeyvEntry<Value = any> = {
499
+ /**
500
+ * Key to set.
501
+ */
502
+ key: string;
503
+ /**
504
+ * Value to set.
505
+ */
506
+ value: Value;
507
+ /**
508
+ * Time to live in milliseconds.
509
+ */
510
+ ttl?: number;
511
+ };
512
+ /**
513
+ * Configuration options for the Keyv constructor.
514
+ */
515
+ type KeyvOptions = {
516
+ /**
517
+ * Namespace for the current instance.
518
+ * @default undefined
519
+ */
520
+ namespace?: string;
521
+ /**
522
+ * A custom serialization adapter with stringify and parse methods.
523
+ * @default KeyvJsonSerializer (built-in)
524
+ */
525
+ serialization?: KeyvSerializationAdapter | false;
526
+ /**
527
+ * The storage adapter instance to be used by Keyv.
528
+ * @default new Map() - in-memory store
529
+ */
530
+ store?: KeyvStorageAdapter | Map<any, any> | any;
531
+ /**
532
+ * Default TTL in milliseconds. Can be overridden by specifying a TTL on `.set()`.
533
+ * @default undefined
534
+ */
535
+ ttl?: number;
536
+ /**
537
+ * Enable compression option
538
+ * @default undefined
539
+ */
540
+ compression?: KeyvCompressionAdapter | any;
541
+ /**
542
+ * Enable or disable statistics (default is false)
543
+ * @default false
544
+ */
545
+ stats?: boolean;
546
+ /**
547
+ * Will throw on all errors if this is enabled to true. By default, errors
548
+ * will only throw if there are no listeners to the error event.
549
+ * This maps to hookified's `throwOnEmitError` under the hood.
550
+ * @default false
551
+ */
552
+ throwOnErrors?: boolean;
553
+ /**
554
+ * Enable sanitization of keys and namespaces by detecting dangerous patterns
555
+ * for SQL, MongoDB, or filesystem-based storage backends. Pass a `KeyvSanitizeOptions`
556
+ * object for granular control over targets and patterns.
557
+ * @default undefined
558
+ */
559
+ sanitize?: KeyvSanitizeOptions;
560
+ /**
561
+ * Enable encryption of stored values. Pass a `KeyvEncryptionAdapter` with
562
+ * `encrypt` and `decrypt` methods.
563
+ * @default undefined
564
+ */
565
+ encryption?: KeyvEncryptionAdapter;
566
+ /**
567
+ * When true, Keyv checks expiry on get/getMany/has/hasMany at its layer.
568
+ * When false (default), trusts the storage adapter to handle expiry.
569
+ * @default false
570
+ */
571
+ checkExpired?: boolean;
572
+ };
573
+ //#endregion
574
+ //#region src/types/adapters.d.ts
575
+ /**
576
+ * Adapter interface for custom serialization.
577
+ * Implement `stringify` and `parse` to control how values are serialized to/from strings.
578
+ */
579
+ type KeyvSerializationAdapter = {
580
+ /** Converts a value to a string representation. */stringify: (object: unknown) => string | Promise<string>; /** Parses a string back into its original value. */
581
+ parse: <T>(data: string) => T | Promise<T>;
582
+ };
583
+ /**
584
+ * Adapter interface for compression.
585
+ * Implement `compress` and `decompress` to add compression to stored values.
586
+ */
587
+ type KeyvCompressionAdapter = {
588
+ /** Compresses a string value. */compress(value: string): Promise<string>; /** Decompresses a string value back to its original form. */
589
+ decompress(value: string): Promise<string>;
590
+ };
591
+ /**
592
+ * Adapter interface for encryption.
593
+ * Implement `encrypt` and `decrypt` to add encryption to stored values.
594
+ */
595
+ type KeyvEncryptionAdapter = {
596
+ /** Encrypts a string value. */encrypt: (data: string) => string | Promise<string>; /** Decrypts a string value back to its original form. */
597
+ decrypt: (data: string) => string | Promise<string>;
598
+ };
599
+ type KeyvStorageGetResult<Value> = KeyvValue<Value> | string | undefined;
600
+ /**
601
+ * Interface that all Keyv storage adapters must implement.
602
+ * Adapters handle the actual persistence of key-value pairs.
603
+ */
604
+ type KeyvStorageAdapter = {
605
+ /** Optional namespace for key isolation. */namespace?: string | undefined; /** Detected capabilities of the underlying store. */
606
+ capabilities?: KeyvStorageCapability; /** Retrieves a value by key. */
607
+ get<Value>(key: string): Promise<KeyvStorageGetResult<Value>>; /** Stores a value with a key and optional TTL in milliseconds. */
608
+ set(key: string, value: unknown, ttl?: number): Promise<boolean>; /** Stores multiple entries at once. */
609
+ setMany<Value>(values: KeyvEntry<Value>[]): Promise<boolean[] | undefined>; /** Deletes a key from the store. */
610
+ delete(key: string): Promise<boolean>; /** Clears all entries from the store (respects namespace if set). */
611
+ clear(): Promise<void>; /** Checks if a key exists in the store. */
612
+ has(key: string): Promise<boolean>; /** Checks if multiple keys exist in the store. */
613
+ hasMany(keys: string[]): Promise<boolean[]>; /** Retrieves multiple values by keys. */
614
+ getMany<Value>(keys: string[]): Promise<Array<KeyvStorageGetResult<Value | undefined>>>; /** Disconnects from the store and releases resources. */
615
+ disconnect?(): Promise<void>; /** Deletes multiple keys from the store. */
616
+ deleteMany(key: string[]): Promise<boolean[]>; /** Returns an async iterator over all key-value pairs. */
617
+ iterator?<Value>(): AsyncGenerator<Array<string | Awaited<Value> | undefined>, void>;
618
+ } & IEventEmitter;
619
+ /**
620
+ * @deprecated Use `KeyvStorageAdapter` instead.
621
+ */
622
+ type KeyvStoreAdapter = KeyvStorageAdapter;
623
+ /**
624
+ * @deprecated Use `KeyvCompressionAdapter` instead.
625
+ */
626
+ type KeyvCompression = KeyvCompressionAdapter;
627
+ //#endregion
628
+ //#region src/adapters/bridge.d.ts
629
+ /**
630
+ * Configuration options for KeyvBridgeAdapter.
631
+ */
632
+ type KeyvBridgeAdapterOptions = {
633
+ /**
634
+ * The namespace to use for keys.
635
+ * When set, all keys will be prefixed with the namespace followed by the key separator.
636
+ */
637
+ namespace?: string;
638
+ /**
639
+ * The separator used between namespace and key. Defaults to ":".
640
+ */
641
+ keySeparator?: string;
642
+ };
643
+ /**
644
+ * Interface for a promise-based store that can be used with KeyvBridgeAdapter.
645
+ * The store must implement get, set, delete, and clear as async operations.
646
+ * Optional methods (has, hasMany, getMany, setMany, deleteMany, iterator, disconnect)
647
+ * will be delegated to the store if present, otherwise fallback implementations are used.
648
+ */
649
+ type KeyvBridgeStore = {
650
+ /** Store configuration/options (e.g. dialect, url) */opts?: any; /** Retrieves a value by key */
651
+ get(key: string): Promise<any>; /** Sets a value with a key and optional TTL */
652
+ set(key: string, value: any, ttl?: number): Promise<any>; /** Deletes a key from the store */
653
+ delete(key: string): Promise<boolean>; /** Clears all entries from the store */
654
+ clear(): Promise<void>; /** Checks if a key exists in the store */
655
+ has?(key: string): Promise<boolean>; /** Checks if multiple keys exist in the store */
656
+ hasMany?(keys: string[]): Promise<boolean[]>; /** Retrieves multiple values by keys */
657
+ getMany?(keys: string[]): Promise<any[]>; /** Sets multiple entries at once */
658
+ setMany?(entries: any[]): Promise<any>; /** Deletes multiple keys at once */
659
+ deleteMany?(keys: string[]): Promise<boolean | boolean[]>; /** Iterates over all entries, optionally filtered by namespace */
660
+ iterator?(namespace?: string): AsyncGenerator<any>; /** Disconnects from the store */
661
+ disconnect?(): Promise<void>; /** Subscribe to events (e.g. error events from v5 adapters) */
662
+ on?(event: string, listener: (...args: any[]) => void): any;
663
+ };
664
+ /**
665
+ * Data structure returned when parsing a prefixed key.
666
+ */
667
+ type KeyPrefixData = {
668
+ /** The namespace extracted from the key, if present */namespace?: string; /** The key without the namespace prefix */
669
+ key: string;
670
+ };
671
+ /**
672
+ * A bridge storage adapter for Keyv that wraps any promise-based store.
673
+ *
674
+ * This class provides a unified interface for using various async stores
675
+ * with Keyv, handling namespace prefixing, TTL-based expiration, and batch operations.
676
+ * If the underlying store implements optional methods (has, hasMany, getMany, etc.),
677
+ * the bridge will delegate to them. Otherwise, it falls back to using primitives.
678
+ *
679
+ * @example
680
+ * ```typescript
681
+ * // Using with a promise-based store
682
+ * const bridge = new KeyvBridgeAdapter(myAsyncStore, { namespace: 'cache' });
683
+ *
684
+ * // Using with Keyv
685
+ * const keyv = new Keyv({ store: new KeyvBridgeAdapter(myAsyncStore) });
686
+ * ```
687
+ */
688
+ declare class KeyvBridgeAdapter extends Hookified implements KeyvStorageAdapter {
689
+ private _store;
690
+ private _namespace?;
691
+ private _keySeparator;
692
+ private readonly _capabilities;
693
+ /**
694
+ * Creates a new KeyvBridgeAdapter instance.
695
+ * @param store - The underlying promise-based store to bridge
696
+ * @param options - Configuration options for the adapter
697
+ */
698
+ constructor(store: KeyvBridgeStore, options?: KeyvBridgeAdapterOptions);
699
+ /**
700
+ * Gets the underlying store instance.
701
+ */
702
+ get store(): KeyvBridgeStore;
703
+ /**
704
+ * Sets the underlying store instance.
705
+ */
706
+ set store(store: KeyvBridgeStore);
707
+ /**
708
+ * Gets the detected capabilities of the underlying store.
709
+ */
710
+ get capabilities(): KeyvStorageCapability;
711
+ /**
712
+ * Gets the current key separator used between namespace and key.
713
+ */
714
+ get keySeparator(): string;
715
+ /**
716
+ * Sets the key separator used between namespace and key.
717
+ */
718
+ set keySeparator(separator: string);
719
+ /**
720
+ * Gets the current namespace.
721
+ */
722
+ get namespace(): string | undefined;
723
+ /**
724
+ * Sets the namespace.
725
+ */
726
+ set namespace(namespace: string | undefined);
727
+ /**
728
+ * Creates a prefixed key by combining the namespace and key with the separator.
729
+ * @param key - The base key
730
+ * @param namespace - Optional namespace to prefix the key with
731
+ * @returns The prefixed key if namespace is provided, otherwise the original key
732
+ */
733
+ getKeyPrefix(key: string, namespace?: string): string;
734
+ /**
735
+ * Parses a prefixed key to extract the namespace and original key.
736
+ * @param key - The prefixed key to parse
737
+ * @returns An object containing the namespace (if present) and the original key
738
+ */
739
+ getKeyPrefixData(key: string): KeyPrefixData;
740
+ /**
741
+ * Retrieves a value from the store by key.
742
+ * Automatically handles namespace prefixing and TTL expiration.
743
+ * @param key - The key to retrieve
744
+ * @returns The stored data, or undefined if not found or expired
745
+ */
746
+ get<T>(key: string): Promise<KeyvStorageGetResult<T>>;
747
+ /**
748
+ * Retrieves multiple values from the store by their keys.
749
+ * Delegates to the store's native getMany if available.
750
+ * @param keys - Array of keys to retrieve
751
+ * @returns Array of stored data in the same order as the input keys
752
+ */
753
+ getMany<T>(keys: string[]): Promise<Array<KeyvStorageGetResult<T | undefined>>>;
754
+ /**
755
+ * Stores a value in the store with an optional TTL.
756
+ * @param key - The key to store the value under
757
+ * @param value - The value to store
758
+ * @param ttl - Optional time-to-live in milliseconds
759
+ * @returns Always returns true indicating success
760
+ */
761
+ set(key: string, value: any, ttl?: number): Promise<boolean>;
762
+ /**
763
+ * Stores multiple entries in the store at once.
764
+ * Delegates to the store's native setMany if available, otherwise loops over set.
765
+ * @param entries - Array of entries containing key, value, and optional TTL
766
+ */
767
+ setMany<Value>(entries: KeyvEntry<Value>[]): Promise<boolean[] | undefined>;
768
+ /**
769
+ * Checks if a key exists in the store and is not expired.
770
+ * Delegates to the store's native has if available.
771
+ * @param key - The key to check
772
+ * @returns True if the key exists and is not expired, false otherwise
773
+ */
774
+ has(key: string): Promise<boolean>;
775
+ /**
776
+ * Checks if multiple keys exist in the store and are not expired.
777
+ * Delegates to the store's native hasMany if available.
778
+ * @param keys - Array of keys to check
779
+ * @returns Array of booleans indicating existence for each key
780
+ */
781
+ hasMany(keys: string[]): Promise<boolean[]>;
782
+ /**
783
+ * Deletes a value from the store by key.
784
+ * @param key - The key to delete
785
+ * @returns True if the key was deleted, false otherwise
786
+ */
787
+ delete(key: string): Promise<boolean>;
788
+ /**
789
+ * Deletes multiple keys from the store at once.
790
+ * Delegates to the store's native deleteMany if available.
791
+ * @param keys - Array of keys to delete
792
+ * @returns Array of booleans indicating success for each key
793
+ */
794
+ deleteMany(keys: string[]): Promise<boolean[]>;
795
+ /**
796
+ * Clears entries from the store. If a namespace is set and the store supports
797
+ * iteration, only entries within that namespace are removed. Otherwise, the
798
+ * entire store is cleared.
799
+ */
800
+ clear(): Promise<void>;
801
+ /**
802
+ * Creates an async iterator for iterating over store entries.
803
+ * If the underlying store does not support iteration, returns an empty generator.
804
+ * @returns An async generator yielding [key, value] pairs
805
+ */
806
+ iterator<Value>(): AsyncGenerator<Array<string | Awaited<Value> | undefined>, void>;
807
+ /**
808
+ * Disconnects from the underlying store.
809
+ * No-op if the store does not support disconnect.
810
+ */
811
+ disconnect(): Promise<void>;
812
+ }
813
+ //#endregion
814
+ //#region src/keyv.d.ts
815
+ declare class Keyv<GenericValue = any> extends Hookified {
816
+ /**
817
+ * Stats manager for tracking cache operation metrics (hits, misses, sets, deletes, errors).
818
+ * @default this is disabled.
819
+ */
820
+ private _stats;
821
+ /**
822
+ * Default time to live in milliseconds. Can be overridden per-key via {@link set}.
823
+ */
824
+ private _ttl?;
825
+ /**
826
+ * Key prefix namespace used to isolate keys across different Keyv instances sharing the same store.
827
+ */
828
+ private _namespace?;
829
+ /**
830
+ * The underlying storage adapter. Defaults to an in-memory {@link Map}.
831
+ */
832
+ private _store;
833
+ /**
834
+ * Pluggable serialization adapter with `stringify` and `parse` methods.
835
+ * When `undefined`, the built-in {@link KeyvJsonSerializer} is used.
836
+ */
837
+ private _serialization;
838
+ /**
839
+ * Pluggable compression adapter with `compress` and `decompress` methods.
840
+ */
841
+ private _compression;
842
+ /**
843
+ * Pluggable encryption adapter with `encrypt` and `decrypt` methods.
844
+ */
845
+ private _encryption;
846
+ /**
847
+ * Sanitization handler for keys and namespaces. By default it is disabled.
848
+ */
849
+ private _sanitize;
850
+ /**
851
+ * When true, Keyv checks expiry at its layer on get/getMany/has/hasMany.
852
+ */
853
+ private _checkExpired;
854
+ /**
855
+ * Keyv Constructor
856
+ * @param {KeyvStorageAdapter | KeyvOptions | Map<any, any> | any} store to be provided or just the options
857
+ * @param {Omit<KeyvOptions, 'store'>} [options] if you provide the store you can then provide the Keyv Options
858
+ */
859
+ constructor(store?: KeyvStorageAdapter | KeyvOptions | KeyvMapAny, options?: Omit<KeyvOptions, "store">);
860
+ /**
861
+ * Keyv Constructor
862
+ * @param {KeyvOptions} options to be provided
863
+ */
864
+ constructor(options?: KeyvOptions);
865
+ /**
866
+ * Get the current storage adapter.
867
+ * @returns {KeyvStorageAdapter} The current storage adapter.
868
+ */
869
+ get store(): KeyvStorageAdapter;
870
+ /**
871
+ * Set the storage adapter.
872
+ * @param {KeyvStorageAdapter | Map<any, any> | any} store The storage adapter to set.
873
+ */
874
+ set store(store: KeyvStorageAdapter | KeyvMapAny);
875
+ /**
876
+ * Get the current compression adapter.
877
+ * @returns {KeyvCompressionAdapter | undefined} The current compression adapter.
878
+ */
879
+ get compression(): KeyvCompressionAdapter | undefined;
880
+ /**
881
+ * Set the compression adapter.
882
+ * @param {KeyvCompressionAdapter | undefined} compress The compression adapter to set.
883
+ */
884
+ set compression(compress: KeyvCompressionAdapter | undefined);
885
+ /**
886
+ * Get the current encryption adapter.
887
+ * @returns {KeyvEncryptionAdapter | undefined} The current encryption adapter.
888
+ */
889
+ get encryption(): KeyvEncryptionAdapter | undefined;
890
+ /**
891
+ * Set the encryption adapter.
892
+ * @param {KeyvEncryptionAdapter | undefined} encryption The encryption adapter to set.
893
+ */
894
+ set encryption(encryption: KeyvEncryptionAdapter | undefined);
895
+ /**
896
+ * Get the current namespace.
897
+ * @returns {string | undefined} The current namespace.
898
+ */
899
+ get namespace(): string | undefined;
900
+ /**
901
+ * Set the current namespace.
902
+ * @param {string | undefined} namespace The namespace to set.
903
+ */
904
+ set namespace(namespace: string | undefined);
905
+ /**
906
+ * Get the current TTL.
907
+ * @returns {number} The current TTL in milliseconds.
908
+ */
909
+ get ttl(): number | undefined;
910
+ /**
911
+ * Set the current TTL.
912
+ * @param {number} ttl The TTL to set in milliseconds.
913
+ */
914
+ set ttl(ttl: number | undefined);
915
+ /**
916
+ * Get the current serialization adapter. If `undefined`, serialization is not enabled.
917
+ * @returns {KeyvSerializationAdapter | undefined} The current serialization adapter.
918
+ */
919
+ get serialization(): KeyvSerializationAdapter | undefined;
920
+ /**
921
+ * Set the current serialization adapter. Pass a `KeyvSerializationAdapter` to enable
922
+ * custom serialization, or `undefined` to disable serialization entirely.
923
+ * @param {KeyvSerializationAdapter | undefined} serialization The serialization adapter to set.
924
+ */
925
+ set serialization(serialization: KeyvSerializationAdapter | false | undefined);
926
+ /**
927
+ * Get the current throwOnErrors value. When enabled, all errors with throw. By default, errors
928
+ * will only throw if there are no listeners to the error event.
929
+ * @return {boolean} The current throwOnErrors value.
930
+ */
931
+ get throwOnErrors(): boolean;
932
+ /**
933
+ * Set the current throwOnErrors value. When enabled, all errors will throw. By default, errors
934
+ * will only throw if there are no listeners to the error event.
935
+ * @param {boolean} value The throwOnErrors value to set.
936
+ */
937
+ set throwOnErrors(value: boolean);
938
+ /**
939
+ * Get the current sanitize adapter. Sanitization is disabled by default. To
940
+ * enable it `sanitize.keys` or `sanitize.namespace` to true or set KeyvSanitizePatterns
941
+ * to each.
942
+ * @returns {KeyvSanitizeAdapter} The current sanitize adapter.
943
+ */
944
+ get sanitize(): KeyvSanitizeAdapter;
945
+ /**
946
+ * Set the sanitize adapter directly and will run sanitization on namespace.
947
+ * @param {KeyvSanitizeAdapter} value The sanitize adapter to use.
948
+ */
949
+ set sanitize(value: KeyvSanitizeAdapter);
950
+ /**
951
+ * Get the stats. This is just for this instance
952
+ * @returns {KeyvStats} The current stats.
953
+ */
954
+ get stats(): KeyvStats;
955
+ /**
956
+ * When true, Keyv checks expiry at its layer on get/getMany/has/hasMany.
957
+ * When false (default), trusts the storage adapter.
958
+ */
959
+ get checkExpired(): boolean;
960
+ /**
961
+ * Set the stats. When setting a new instance it will unsubscribe the old listeners
962
+ * and subscribe the new instance.
963
+ * @param {KeyvStats} stats The stats instance to set.
964
+ */
965
+ set stats(stats: KeyvStats);
966
+ /**
967
+ * Resolves a store to a fully-compliant KeyvStorageAdapter using a 3-tier detection chain:
968
+ * 1. If the store already implements the full KeyvStorageAdapter interface, use it directly.
969
+ * 2. If the store is map-like (synchronous get/set/delete/has), wrap it in KeyvMemoryAdapter.
970
+ * 3. If the store has async get/set/delete/clear, wrap it in KeyvBridgeAdapter.
971
+ * 4. Otherwise, emit an error and fall back to a default in-memory KeyvMemoryAdapter.
972
+ *
973
+ * NOTE: this is used for internal but provided public for custom adapter testing
974
+ * @param {unknown} store The store to resolve.
975
+ * @returns {KeyvStorageAdapter} A fully-compliant storage adapter.
976
+ */
977
+ resolveStore(store: any): KeyvStorageAdapter;
978
+ /**
979
+ * Sets the storage adapter by resolving it via {@link resolveStore}, then wires up
980
+ * error forwarding and namespace propagation.
981
+ * @param {KeyvStorageAdapter | Map<any, any> | any} store The storage adapter to set.
982
+ */
983
+ setStore(store: KeyvStorageAdapter | KeyvMapAny): void;
984
+ /**
985
+ * Sets the TTL, treating zero and negative values as undefined (no TTL).
986
+ * @param {number | undefined} ttl The TTL to set in milliseconds.
987
+ */
988
+ setTtl(ttl?: number): void;
989
+ /**
990
+ * Get the Value of a Key
991
+ * @param {string | string[]} key passing in a single key or multiple as an array
992
+ */
993
+ get<Value = GenericValue>(key: string): Promise<Value | undefined>;
994
+ get<Value = GenericValue>(key: string[]): Promise<Array<Value | undefined>>;
995
+ /**
996
+ * Get many values of keys
997
+ * @param {string[]} keys passing in a single key or multiple as an array
998
+ */
999
+ getMany<Value = GenericValue>(keys: string[]): Promise<Array<Value | undefined>>;
1000
+ /**
1001
+ * Get the raw value of a key. This is the replacement for setting raw to true in the get() method.
1002
+ * @param {string} key the key to get
1003
+ * @returns {Promise<KeyvStorageGetResult<Value>>} will return a KeyvStorageGetResult<Value> or undefined
1004
+ * if the key does not exist or is expired.
1005
+ */
1006
+ getRaw<Value = GenericValue>(key: string): Promise<KeyvStorageGetResult<Value>>;
1007
+ /**
1008
+ * Get the raw values of many keys. This is the replacement for setting raw to true in the getMany() method.
1009
+ * @param {string[]} keys the keys to get
1010
+ * @returns {Promise<Array<KeyvStorageGetResult<Value>>>} will return an array of KeyvStorageGetResult<Value> or undefined if the key does not exist or is expired.
1011
+ */
1012
+ getManyRaw<Value = GenericValue>(keys: string[]): Promise<Array<KeyvStorageGetResult<Value>>>;
1013
+ /**
1014
+ * Set an item to the store
1015
+ * @param {string | Array<KeyvEntry<Value>>} key the key to use. If you pass in an array of KeyvEntry it will set many items
1016
+ * @param {Value} value the value of the key
1017
+ * @param {number} [ttl] time to live in milliseconds
1018
+ * @returns {boolean} if it sets then it will return a true. On failure will return false.
1019
+ */
1020
+ set<Value = GenericValue>(key: string, value: Value, ttl?: number): Promise<boolean>;
1021
+ /**
1022
+ * Set many items to the store
1023
+ * @param {Array<KeyvEntry<Value>>} entries the entries to set
1024
+ * @returns {boolean[]} will return an array of booleans if it sets then it will return a true. On failure will return false.
1025
+ */
1026
+ setMany<Value = GenericValue>(entries: KeyvEntry<Value>[]): Promise<boolean[]>;
1027
+ /**
1028
+ * Set a raw value to the store without wrapping or serialization. This is the write-side counterpart to getRaw().
1029
+ * The value should be a KeyvValue object with { value, expires? }. If you need TTL-based expiration,
1030
+ * set `expires` on the value directly (e.g. `{ value: 'bar', expires: Date.now() + 60000 }`).
1031
+ * The store-level TTL is derived automatically from `value.expires`.
1032
+ * @param {string} key the key to set
1033
+ * @param {KeyvValue<Value>} value the raw value envelope to store
1034
+ * @returns {boolean} if it sets then it will return a true. On failure will return false.
1035
+ */
1036
+ setRaw<Value = GenericValue>(key: string, value: KeyvValue<Value>): Promise<boolean>;
1037
+ /**
1038
+ * Set many raw values to the store without wrapping or serialization. This is the write-side counterpart to getManyRaw().
1039
+ * Each entry's value should be a KeyvValue object with { value, expires? }. If you need TTL-based expiration,
1040
+ * set `expires` on each value directly. The store-level TTL is derived automatically from `value.expires`.
1041
+ * @param {KeyvEntry<KeyvValue<Value>>[]} entries the raw entries to set
1042
+ * @returns {boolean[]} will return an array of booleans if it sets then it will return a true. On failure will return false.
1043
+ */
1044
+ setManyRaw<Value = GenericValue>(entries: KeyvEntry<KeyvValue<Value>>[]): Promise<boolean[]>;
1045
+ /**
1046
+ * Delete an Entry
1047
+ * @param {string} key the key to be deleted
1048
+ * @returns {boolean} will return true if item is deleted. false if there is an error
1049
+ */
1050
+ delete(key: string): Promise<boolean>;
1051
+ /**
1052
+ * Delete multiple Entries
1053
+ * @param {string[]} keys the keys to be deleted
1054
+ * @returns {boolean[]} will return array of booleans for each key
1055
+ */
1056
+ delete(keys: string[]): Promise<boolean[]>;
1057
+ /**
1058
+ * Delete many items from the store
1059
+ * @param {string[]} keys the keys to be deleted
1060
+ * @returns {boolean[]} array of booleans indicating success for each key
1061
+ */
1062
+ deleteMany(keys: string[]): Promise<boolean[]>;
1063
+ /**
1064
+ * Has a key.
1065
+ * @param {string} key the key to check
1066
+ * @returns {boolean} will return true if the key exists
1067
+ */
1068
+ has(key: string[]): Promise<boolean[]>;
1069
+ has(key: string): Promise<boolean>;
1070
+ /**
1071
+ * Check if many keys exist
1072
+ * @param {string[]} keys the keys to check
1073
+ * @returns {boolean[]} will return an array of booleans if the keys exist
1074
+ */
1075
+ hasMany(keys: string[]): Promise<boolean[]>;
1076
+ /**
1077
+ * Clear the store
1078
+ * @returns {void}
1079
+ */
1080
+ clear(): Promise<void>;
1081
+ /**
1082
+ * Will disconnect the store. This is only available if the store has a disconnect method
1083
+ * @returns {Promise<void>}
1084
+ */
1085
+ disconnect(): Promise<void>;
1086
+ /**
1087
+ * Iterate over all key-value pairs in the store. Automatically deserializes values,
1088
+ * filters out expired entries, and deletes them from the store.
1089
+ * @returns {AsyncGenerator<Array<string | unknown>, void>} An async generator yielding `[key, value]` pairs.
1090
+ */
1091
+ iterator(): AsyncGenerator<[string, any], void>;
1092
+ /**
1093
+ * Encodes a value for storage. Pipeline: serialize → compress → encrypt.
1094
+ * If serialization is not configured, returns the data as-is.
1095
+ * @param {KeyvValue<T>} data The value envelope to encode.
1096
+ * @returns {Promise<unknown>} The encoded value, or the original data on failure.
1097
+ */
1098
+ encode<T>(data: KeyvValue<T>): Promise<unknown>;
1099
+ /**
1100
+ * Decodes a stored value. Pipeline: decrypt → decompress → deserialize (reverse of encode).
1101
+ * If serialization is not configured, returns the data as a KeyvValue or undefined for strings.
1102
+ * @param {unknown} data The raw data from the store.
1103
+ * @returns {Promise<KeyvValue<T> | undefined>} The decoded value envelope, or undefined on failure.
1104
+ */
1105
+ decode<T>(data: unknown): Promise<KeyvValue<T> | undefined>;
1106
+ /**
1107
+ * Deserializes raw data from the store, checks for expiry, and deletes expired keys.
1108
+ * Accepts a single key/value or arrays. Returns an array of decoded KeyvValue objects
1109
+ * (undefined for missing or expired entries).
1110
+ * @param {string | string[]} keys the key(s) to process
1111
+ * @param {unknown | unknown[]} rawData the raw data from the store
1112
+ * @returns {Promise<Array<KeyvValue<Value> | undefined>>} decoded values with expired entries removed
1113
+ */
1114
+ decodeWithExpire<Value>(keys: string | string[], rawData: unknown | unknown[]): Promise<Array<KeyvValue<Value> | undefined>>;
1115
+ /**
1116
+ * Fires a hook under its new name and also under the deprecated alias (if any),
1117
+ * so that integrations still subscribing to the old PRE_/POST_ names keep working.
1118
+ */
1119
+ private hookWithDeprecated;
1120
+ /**
1121
+ * Emit a telemetry event for cache operations.
1122
+ * @param {KeyvEvents} event the telemetry event type
1123
+ * @param {string | string[]} [key] the cache key or keys (emits one event per key)
1124
+ */
1125
+ private emitTelemetry;
1126
+ /**
1127
+ * Merges the overloaded constructor arguments into a single KeyvOptions object.
1128
+ */
1129
+ private static resolveOptions;
1130
+ /**
1131
+ * Initializes the serialization adapter from options.
1132
+ */
1133
+ private initSerialization;
1134
+ /**
1135
+ * Initializes the sanitization handler from options.
1136
+ */
1137
+ private initSanitize;
1138
+ /**
1139
+ * Initializes the stats manager from options.
1140
+ */
1141
+ private initStats;
1142
+ /**
1143
+ * Initializes the namespace, applying sanitization if enabled.
1144
+ */
1145
+ private initNamespace;
1146
+ }
1147
+ //#endregion
1148
+ //#region src/adapters/memory.d.ts
1149
+ /**
1150
+ * Configuration options for KeyvMemoryAdapter.
1151
+ */
1152
+ type KeyvMemoryAdapterOptions = {
1153
+ /**
1154
+ * The namespace to use for keys.
1155
+ * When set, all keys will be prefixed with the namespace followed by the key separator.
1156
+ */
1157
+ namespace?: string;
1158
+ /**
1159
+ * The separator used between namespace and key. Defaults to ":".
1160
+ */
1161
+ keySeparator?: string;
1162
+ };
1163
+ /**
1164
+ * Interface for a Map-like store that can be used with KeyvMemoryAdapter.
1165
+ * This allows any object implementing these methods to be used as the underlying storage.
1166
+ * Compatible with Map, QuickLRU, lru.min, and other LRU cache implementations.
1167
+ */
1168
+ type KeyvMapType = {
1169
+ /** Retrieves a value by key */get: (key: string) => any; /** Sets a value with a key. Additional parameters (like TTL) vary by implementation. */
1170
+ set: (key: string, value: any, ...args: any[]) => any; /** Deletes a key from the store */
1171
+ delete: (key: string) => boolean; /** Clears all entries from the store */
1172
+ clear: () => void; /** Checks if a key exists in the store */
1173
+ has: (key: string) => boolean;
1174
+ };
1175
+ /**
1176
+ * An in-memory storage adapter for Keyv that wraps any Map-like object.
1177
+ *
1178
+ * This class provides a unified interface for using various Map-like stores
1179
+ * with Keyv, handling namespace prefixing, TTL-based expiration, and batch operations.
1180
+ *
1181
+ * @example
1182
+ * ```typescript
1183
+ * // Using with a standard Map
1184
+ * const store = new KeyvMemoryAdapter(new Map(), { namespace: 'cache' });
1185
+ *
1186
+ * // Using with a custom store
1187
+ * const customStore = new KeyvMemoryAdapter(myCustomMapLikeStore, {
1188
+ * namespace: 'tenant-123',
1189
+ * keySeparator: ':'
1190
+ * });
1191
+ * ```
1192
+ */
1193
+ declare class KeyvMemoryAdapter extends Hookified implements KeyvStorageAdapter {
1194
+ private _store;
1195
+ private _namespace?;
1196
+ private _keySeparator;
1197
+ private readonly _capabilities;
1198
+ /**
1199
+ * Creates a new KeyvMemoryAdapter instance.
1200
+ * @param store - The underlying Map or Map-like object to use for storage
1201
+ * @param options - Configuration options for the store
1202
+ */
1203
+ constructor(store: KeyvMapType, options?: KeyvMemoryAdapterOptions);
1204
+ /**
1205
+ * Gets the detected capabilities of the underlying store.
1206
+ */
1207
+ get capabilities(): KeyvStorageCapability;
1208
+ /**
1209
+ * Gets the underlying store instance.
1210
+ */
1211
+ get store(): KeyvMapType;
1212
+ /**
1213
+ * Sets the underlying store instance.
1214
+ */
1215
+ set store(store: KeyvMapType);
1216
+ /**
1217
+ * Gets the current key separator used between namespace and key.
1218
+ */
1219
+ get keySeparator(): string;
1220
+ /**
1221
+ * Sets the key separator used between namespace and key.
1222
+ */
1223
+ set keySeparator(separator: string);
1224
+ /**
1225
+ * Gets the current namespace.
1226
+ */
1227
+ get namespace(): string | undefined;
1228
+ /**
1229
+ * Sets the namespace.
1230
+ */
1231
+ set namespace(namespace: string | undefined);
1232
+ /**
1233
+ * Creates a prefixed key by combining the namespace and key with the separator.
1234
+ * @param key - The base key
1235
+ * @param namespace - Optional namespace to prefix the key with
1236
+ * @returns The prefixed key if namespace is provided, otherwise the original key
1237
+ */
1238
+ getKeyPrefix(key: string, namespace?: string): string;
1239
+ /**
1240
+ * Parses a prefixed key to extract the namespace and original key.
1241
+ * @param key - The prefixed key to parse
1242
+ * @returns An object containing the namespace (if present) and the original key
1243
+ */
1244
+ getKeyPrefixData(key: string): {
1245
+ namespace: string;
1246
+ key: string;
1247
+ } | {
1248
+ key: string;
1249
+ namespace?: undefined;
1250
+ };
1251
+ /**
1252
+ * Retrieves a value from the store by key.
1253
+ * Automatically handles namespace prefixing and TTL expiration.
1254
+ * @param key - The key to retrieve
1255
+ * @returns The stored data, or undefined if not found or expired
1256
+ */
1257
+ get<T>(key: string): Promise<KeyvStorageGetResult<T>>;
1258
+ /**
1259
+ * Stores a value in the store with an optional TTL.
1260
+ * @param key - The key to store the value under
1261
+ * @param value - The value to store
1262
+ * @param ttl - Optional time-to-live in milliseconds
1263
+ * @returns Always returns true indicating success
1264
+ */
1265
+ set(key: string, value: any, ttl?: number): Promise<boolean>;
1266
+ /**
1267
+ * Stores multiple entries in the store at once.
1268
+ * @param entries - Array of entries containing key, value, and optional TTL
1269
+ */
1270
+ setMany<Value>(entries: KeyvEntry<Value>[]): Promise<boolean[] | undefined>;
1271
+ /**
1272
+ * Deletes a value from the store by key.
1273
+ * @param key - The key to delete
1274
+ * @returns True if the key was deleted, false otherwise
1275
+ */
1276
+ delete(key: string): Promise<boolean>;
1277
+ /**
1278
+ * Clears entries from the store. If a namespace is set, only entries
1279
+ * within that namespace are removed. Otherwise, the entire store is cleared.
1280
+ * NOTE: if there is no `keys()` then we just do a full clear.
1281
+ */
1282
+ clear(): Promise<void>;
1283
+ /**
1284
+ * Checks if a key exists in the store and is not expired.
1285
+ * @param key - The key to check
1286
+ * @returns True if the key exists and is not expired, false otherwise
1287
+ */
1288
+ has(key: string): Promise<boolean>;
1289
+ /**
1290
+ * Checks if multiple keys exist in the store and are not expired.
1291
+ * @param keys - Array of keys to check
1292
+ * @returns Array of booleans indicating existence for each key
1293
+ */
1294
+ hasMany(keys: string[]): Promise<boolean[]>;
1295
+ /**
1296
+ * Retrieves multiple values from the store by their keys.
1297
+ * @param keys - Array of keys to retrieve
1298
+ * @returns Array of stored data in the same order as the input keys
1299
+ */
1300
+ getMany<T>(keys: string[]): Promise<Array<KeyvStorageGetResult<T | undefined>>>;
1301
+ /**
1302
+ * Deletes multiple keys from the store at once.
1303
+ * @param keys - Array of keys to delete
1304
+ * @returns Array of booleans indicating success for each key
1305
+ */
1306
+ deleteMany(keys: string[]): Promise<boolean[]>;
1307
+ /**
1308
+ * Creates an async iterator for iterating over store entries.
1309
+ * If the underlying store does not support iteration, returns an empty generator.
1310
+ * @returns {AsyncGenerator<Array<string | Awaited<Value> | undefined>, void>} An async generator yielding [key, value] pairs
1311
+ */
1312
+ iterator<Value>(): AsyncGenerator<Array<string | Awaited<Value> | undefined>, void>;
1313
+ /**
1314
+ * No-op disconnect for in-memory stores.
1315
+ */
1316
+ disconnect(): Promise<void>;
1317
+ }
1318
+ /**
1319
+ * Creates a Keyv instance with a memory adapter optimized for in-memory storage.
1320
+ *
1321
+ * This factory function configures Keyv to bypass serialization/deserialization
1322
+ * and key prefixing, resulting in faster performance for in-memory use cases
1323
+ * where data doesn't need to be persisted or transmitted.
1324
+ *
1325
+ * @param store - The underlying Map or Map-like object to use for storage
1326
+ * @param options - Configuration options for the memory adapter
1327
+ * @returns A configured Keyv instance with optimized settings for in-memory storage
1328
+ *
1329
+ * @example
1330
+ * ```typescript
1331
+ * // Create a simple in-memory cache
1332
+ * const cache = createKeyv(new Map());
1333
+ * await cache.set('user:1', { name: 'John' });
1334
+ *
1335
+ * // Create with namespace for multi-tenant scenarios
1336
+ * const tenantCache = createKeyv(new Map(), {
1337
+ * namespace: 'tenant-123',
1338
+ * keySeparator: ':'
1339
+ * });
1340
+ * ```
1341
+ */
1342
+ declare function createKeyv(store: KeyvMapType, options?: KeyvMemoryAdapterOptions): Keyv<any>;
1343
+ //#endregion
1344
+ //#region src/json-serializer.d.ts
1345
+ declare class KeyvJsonSerializer implements KeyvSerializationAdapter {
1346
+ stringify(object: unknown): string;
1347
+ parse<T>(data: string): T;
1348
+ }
1349
+ declare const jsonSerializer: KeyvJsonSerializer;
1350
+ //#endregion
1351
+ export { type DeserializedData, Keyv, Keyv as default, KeyvBridgeAdapter, type KeyvBridgeAdapterOptions, type KeyvBridgeStore, type KeyvCapability, type KeyvCompression, type KeyvCompressionAdapter, type KeyvCompressionCapability, type KeyvCompressionMethods, type KeyvEncryptionAdapter, type KeyvEncryptionCapability, type KeyvEncryptionMethods, type KeyvEntry, KeyvEvents, KeyvHooks, KeyvJsonSerializer, type KeyvMapAny, type KeyvMapType, KeyvMemoryAdapter, type KeyvMemoryAdapterOptions, type KeyvMethods, type KeyvOptions, type KeyvProperties, KeyvSanitize, type KeyvSanitizeAdapter, type KeyvSanitizeOptions, type KeyvSanitizePatterns, type KeyvSerializationAdapter, type KeyvSerializationCapability, type KeyvSerializationMethods, KeyvStats, type KeyvStatsOptions, type KeyvStorageAdapter, type KeyvStorageCapability, type KeyvStorageGetResult, type KeyvStorageMethod, type KeyvStorageMethods, type KeyvStoreAdapter, type KeyvTelemetryEvent, type KeyvValue, type MethodType, createKeyv, detectKeyv, detectKeyvCompression, detectKeyvEncryption, detectKeyvSerialization, detectKeyvStorage, jsonSerializer };