cacheable 1.10.4 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,1860 +1 @@
1
- // src/index.ts
2
- import { Hookified as Hookified2 } from "hookified";
3
- import { Keyv as Keyv2 } from "keyv";
4
-
5
- // src/hash.ts
6
- import * as crypto from "crypto";
7
- function hash(object, algorithm = "sha256") {
8
- const objectString = JSON.stringify(object);
9
- if (!crypto.getHashes().includes(algorithm)) {
10
- throw new Error(`Unsupported hash algorithm: '${algorithm}'`);
11
- }
12
- const hasher = crypto.createHash(algorithm);
13
- hasher.update(objectString);
14
- return hasher.digest("hex");
15
- }
16
- function hashToNumber(object, min = 0, max = 10, algorithm = "sha256") {
17
- const objectString = JSON.stringify(object);
18
- if (!crypto.getHashes().includes(algorithm)) {
19
- throw new Error(`Unsupported hash algorithm: '${algorithm}'`);
20
- }
21
- const hasher = crypto.createHash(algorithm);
22
- hasher.update(objectString);
23
- const hashHex = hasher.digest("hex");
24
- const hashNumber = Number.parseInt(hashHex, 16);
25
- const range = max - min + 1;
26
- return min + hashNumber % range;
27
- }
28
- function djb2Hash(string_, min = 0, max = 10) {
29
- let hash2 = 5381;
30
- for (let i = 0; i < string_.length; i++) {
31
- hash2 = hash2 * 33 ^ string_.charCodeAt(i);
32
- }
33
- const range = max - min + 1;
34
- return min + Math.abs(hash2) % range;
35
- }
36
-
37
- // src/keyv-memory.ts
38
- import { Keyv } from "keyv";
39
-
40
- // src/memory.ts
41
- import { Hookified } from "hookified";
42
-
43
- // src/memory-lru.ts
44
- var ListNode = class {
45
- value;
46
- prev = void 0;
47
- next = void 0;
48
- constructor(value) {
49
- this.value = value;
50
- }
51
- };
52
- var DoublyLinkedList = class {
53
- head = void 0;
54
- tail = void 0;
55
- nodesMap = /* @__PURE__ */ new Map();
56
- // Add a new node to the front (most recently used)
57
- addToFront(value) {
58
- const newNode = new ListNode(value);
59
- if (this.head) {
60
- newNode.next = this.head;
61
- this.head.prev = newNode;
62
- this.head = newNode;
63
- } else {
64
- this.head = this.tail = newNode;
65
- }
66
- this.nodesMap.set(value, newNode);
67
- }
68
- // Move an existing node to the front (most recently used)
69
- moveToFront(value) {
70
- const node = this.nodesMap.get(value);
71
- if (!node || this.head === node) {
72
- return;
73
- }
74
- if (node.prev) {
75
- node.prev.next = node.next;
76
- }
77
- if (node.next) {
78
- node.next.prev = node.prev;
79
- }
80
- if (node === this.tail) {
81
- this.tail = node.prev;
82
- }
83
- node.prev = void 0;
84
- node.next = this.head;
85
- if (this.head) {
86
- this.head.prev = node;
87
- }
88
- this.head = node;
89
- this.tail ??= node;
90
- }
91
- // Get the oldest node (tail)
92
- getOldest() {
93
- return this.tail ? this.tail.value : void 0;
94
- }
95
- // Remove the oldest node (tail)
96
- removeOldest() {
97
- if (!this.tail) {
98
- return void 0;
99
- }
100
- const oldValue = this.tail.value;
101
- if (this.tail.prev) {
102
- this.tail = this.tail.prev;
103
- this.tail.next = void 0;
104
- } else {
105
- this.head = this.tail = void 0;
106
- }
107
- this.nodesMap.delete(oldValue);
108
- return oldValue;
109
- }
110
- get size() {
111
- return this.nodesMap.size;
112
- }
113
- };
114
-
115
- // src/shorthand-time.ts
116
- var shorthandToMilliseconds = (shorthand) => {
117
- let milliseconds;
118
- if (shorthand === void 0) {
119
- return void 0;
120
- }
121
- if (typeof shorthand === "number") {
122
- milliseconds = shorthand;
123
- } else if (typeof shorthand === "string") {
124
- shorthand = shorthand.trim();
125
- if (Number.isNaN(Number(shorthand))) {
126
- const match = /^([\d.]+)\s*(ms|s|m|h|hr|d)$/i.exec(shorthand);
127
- if (!match) {
128
- throw new Error(
129
- `Unsupported time format: "${shorthand}". Use 'ms', 's', 'm', 'h', 'hr', or 'd'.`
130
- );
131
- }
132
- const [, value, unit] = match;
133
- const numericValue = Number.parseFloat(value);
134
- const unitLower = unit.toLowerCase();
135
- switch (unitLower) {
136
- case "ms": {
137
- milliseconds = numericValue;
138
- break;
139
- }
140
- case "s": {
141
- milliseconds = numericValue * 1e3;
142
- break;
143
- }
144
- case "m": {
145
- milliseconds = numericValue * 1e3 * 60;
146
- break;
147
- }
148
- case "h": {
149
- milliseconds = numericValue * 1e3 * 60 * 60;
150
- break;
151
- }
152
- case "hr": {
153
- milliseconds = numericValue * 1e3 * 60 * 60;
154
- break;
155
- }
156
- case "d": {
157
- milliseconds = numericValue * 1e3 * 60 * 60 * 24;
158
- break;
159
- }
160
- /* c8 ignore next 3 */
161
- default: {
162
- milliseconds = Number(shorthand);
163
- }
164
- }
165
- } else {
166
- milliseconds = Number(shorthand);
167
- }
168
- } else {
169
- throw new TypeError("Time must be a string or a number.");
170
- }
171
- return milliseconds;
172
- };
173
- var shorthandToTime = (shorthand, fromDate) => {
174
- fromDate ??= /* @__PURE__ */ new Date();
175
- const milliseconds = shorthandToMilliseconds(shorthand);
176
- if (milliseconds === void 0) {
177
- return fromDate.getTime();
178
- }
179
- return fromDate.getTime() + milliseconds;
180
- };
181
-
182
- // src/coalesce-async.ts
183
- var callbacks = /* @__PURE__ */ new Map();
184
- function hasKey(key) {
185
- return callbacks.has(key);
186
- }
187
- function addKey(key) {
188
- callbacks.set(key, []);
189
- }
190
- function removeKey(key) {
191
- callbacks.delete(key);
192
- }
193
- function addCallbackToKey(key, callback) {
194
- const stash = getCallbacksByKey(key);
195
- stash.push(callback);
196
- callbacks.set(key, stash);
197
- }
198
- function getCallbacksByKey(key) {
199
- return callbacks.get(key) ?? [];
200
- }
201
- async function enqueue(key) {
202
- return new Promise((resolve, reject) => {
203
- const callback = { resolve, reject };
204
- addCallbackToKey(key, callback);
205
- });
206
- }
207
- function dequeue(key) {
208
- const stash = getCallbacksByKey(key);
209
- removeKey(key);
210
- return stash;
211
- }
212
- function coalesce(options) {
213
- const { key, error, result } = options;
214
- for (const callback of dequeue(key)) {
215
- if (error) {
216
- callback.reject(error);
217
- } else {
218
- callback.resolve(result);
219
- }
220
- }
221
- }
222
- async function coalesceAsync(key, fnc) {
223
- if (!hasKey(key)) {
224
- addKey(key);
225
- try {
226
- const result = await Promise.resolve(fnc());
227
- coalesce({ key, result });
228
- return result;
229
- } catch (error) {
230
- coalesce({ key, error });
231
- throw error;
232
- }
233
- }
234
- return enqueue(key);
235
- }
236
-
237
- // src/wrap.ts
238
- function wrapSync(function_, options) {
239
- const { ttl, keyPrefix, cache } = options;
240
- return (...arguments_) => {
241
- let cacheKey = createWrapKey(function_, arguments_, keyPrefix);
242
- if (options.createKey) {
243
- cacheKey = options.createKey(function_, arguments_, options);
244
- }
245
- let value = cache.get(cacheKey);
246
- if (value === void 0) {
247
- try {
248
- value = function_(...arguments_);
249
- cache.set(cacheKey, value, ttl);
250
- } catch (error) {
251
- cache.emit("error", error);
252
- if (options.cacheErrors) {
253
- cache.set(cacheKey, error, ttl);
254
- }
255
- }
256
- }
257
- return value;
258
- };
259
- }
260
- async function getOrSet(key, function_, options) {
261
- const keyString = typeof key === "function" ? key(options) : key;
262
- let value = await options.cache.get(keyString);
263
- if (value === void 0) {
264
- const cacheId = options.cacheId ?? "default";
265
- const coalesceKey = `${cacheId}::${keyString}`;
266
- value = await coalesceAsync(coalesceKey, async () => {
267
- try {
268
- const result = await function_();
269
- await options.cache.set(keyString, result, options.ttl);
270
- return result;
271
- } catch (error) {
272
- options.cache.emit("error", error);
273
- if (options.cacheErrors) {
274
- await options.cache.set(keyString, error, options.ttl);
275
- }
276
- if (options.throwErrors) {
277
- throw error;
278
- }
279
- }
280
- });
281
- }
282
- return value;
283
- }
284
- function wrap(function_, options) {
285
- const { keyPrefix, cache } = options;
286
- return async (...arguments_) => {
287
- let cacheKey = createWrapKey(function_, arguments_, keyPrefix);
288
- if (options.createKey) {
289
- cacheKey = options.createKey(function_, arguments_, options);
290
- }
291
- return cache.getOrSet(
292
- cacheKey,
293
- async () => function_(...arguments_),
294
- options
295
- );
296
- };
297
- }
298
- function createWrapKey(function_, arguments_, keyPrefix) {
299
- if (!keyPrefix) {
300
- return `${function_.name}::${hash(arguments_)}`;
301
- }
302
- return `${keyPrefix}::${function_.name}::${hash(arguments_)}`;
303
- }
304
-
305
- // src/memory.ts
306
- var defaultStoreHashSize = 16;
307
- var maximumMapSize = 16777216;
308
- var CacheableMemory = class extends Hookified {
309
- _lru = new DoublyLinkedList();
310
- _storeHashSize = defaultStoreHashSize;
311
- _storeHashAlgorithm = "djb2Hash" /* djb2Hash */;
312
- // Default is djb2Hash
313
- _store = Array.from(
314
- { length: this._storeHashSize },
315
- () => /* @__PURE__ */ new Map()
316
- );
317
- _ttl;
318
- // Turned off by default
319
- _useClone = true;
320
- // Turned on by default
321
- _lruSize = 0;
322
- // Turned off by default
323
- _checkInterval = 0;
324
- // Turned off by default
325
- _interval = 0;
326
- // Turned off by default
327
- /**
328
- * @constructor
329
- * @param {CacheableMemoryOptions} [options] - The options for the CacheableMemory
330
- */
331
- constructor(options) {
332
- super();
333
- if (options?.ttl) {
334
- this.setTtl(options.ttl);
335
- }
336
- if (options?.useClone !== void 0) {
337
- this._useClone = options.useClone;
338
- }
339
- if (options?.storeHashSize && options.storeHashSize > 0) {
340
- this._storeHashSize = options.storeHashSize;
341
- }
342
- if (options?.lruSize) {
343
- if (options.lruSize > maximumMapSize) {
344
- this.emit(
345
- "error",
346
- new Error(
347
- `LRU size cannot be larger than ${maximumMapSize} due to Map limitations.`
348
- )
349
- );
350
- } else {
351
- this._lruSize = options.lruSize;
352
- }
353
- }
354
- if (options?.checkInterval) {
355
- this._checkInterval = options.checkInterval;
356
- }
357
- if (options?.storeHashAlgorithm) {
358
- this._storeHashAlgorithm = options.storeHashAlgorithm;
359
- }
360
- this._store = Array.from(
361
- { length: this._storeHashSize },
362
- () => /* @__PURE__ */ new Map()
363
- );
364
- this.startIntervalCheck();
365
- }
366
- /**
367
- * Gets the time-to-live
368
- * @returns {number|string|undefined} - The time-to-live in miliseconds or a human-readable format. If undefined, it will not have a time-to-live.
369
- */
370
- get ttl() {
371
- return this._ttl;
372
- }
373
- /**
374
- * Sets the time-to-live
375
- * @param {number|string|undefined} value - The time-to-live in miliseconds or a human-readable format (example '1s' = 1 second, '1h' = 1 hour). If undefined, it will not have a time-to-live.
376
- */
377
- set ttl(value) {
378
- this.setTtl(value);
379
- }
380
- /**
381
- * Gets whether to use clone
382
- * @returns {boolean} - If true, it will clone the value before returning it. If false, it will return the value directly. Default is true.
383
- */
384
- get useClone() {
385
- return this._useClone;
386
- }
387
- /**
388
- * Sets whether to use clone
389
- * @param {boolean} value - If true, it will clone the value before returning it. If false, it will return the value directly. Default is true.
390
- */
391
- set useClone(value) {
392
- this._useClone = value;
393
- }
394
- /**
395
- * Gets the size of the LRU cache
396
- * @returns {number} - The size of the LRU cache. If set to 0, it will not use LRU cache. Default is 0. If you are using LRU then the limit is based on Map() size 17mm.
397
- */
398
- get lruSize() {
399
- return this._lruSize;
400
- }
401
- /**
402
- * Sets the size of the LRU cache
403
- * @param {number} value - The size of the LRU cache. If set to 0, it will not use LRU cache. Default is 0. If you are using LRU then the limit is based on Map() size 17mm.
404
- */
405
- set lruSize(value) {
406
- if (value > maximumMapSize) {
407
- this.emit(
408
- "error",
409
- new Error(
410
- `LRU size cannot be larger than ${maximumMapSize} due to Map limitations.`
411
- )
412
- );
413
- return;
414
- }
415
- this._lruSize = value;
416
- if (this._lruSize === 0) {
417
- this._lru = new DoublyLinkedList();
418
- return;
419
- }
420
- this.lruResize();
421
- }
422
- /**
423
- * Gets the check interval
424
- * @returns {number} - The interval to check for expired items. If set to 0, it will not check for expired items. Default is 0.
425
- */
426
- get checkInterval() {
427
- return this._checkInterval;
428
- }
429
- /**
430
- * Sets the check interval
431
- * @param {number} value - The interval to check for expired items. If set to 0, it will not check for expired items. Default is 0.
432
- */
433
- set checkInterval(value) {
434
- this._checkInterval = value;
435
- }
436
- /**
437
- * Gets the size of the cache
438
- * @returns {number} - The size of the cache
439
- */
440
- get size() {
441
- let size = 0;
442
- for (const store of this._store) {
443
- size += store.size;
444
- }
445
- return size;
446
- }
447
- /**
448
- * Gets the number of hash stores
449
- * @returns {number} - The number of hash stores
450
- */
451
- get storeHashSize() {
452
- return this._storeHashSize;
453
- }
454
- /**
455
- * Sets the number of hash stores. This will recreate the store and all data will be cleared
456
- * @param {number} value - The number of hash stores
457
- */
458
- set storeHashSize(value) {
459
- if (value === this._storeHashSize) {
460
- return;
461
- }
462
- this._storeHashSize = value;
463
- this._store = Array.from(
464
- { length: this._storeHashSize },
465
- () => /* @__PURE__ */ new Map()
466
- );
467
- }
468
- /**
469
- * Gets the store hash algorithm
470
- * @returns {StoreHashAlgorithm | StoreHashAlgorithmFunction} - The store hash algorithm
471
- */
472
- get storeHashAlgorithm() {
473
- return this._storeHashAlgorithm;
474
- }
475
- /**
476
- * Sets the store hash algorithm. This will recreate the store and all data will be cleared
477
- * @param {StoreHashAlgorithm | StoreHashAlgorithmFunction} value - The store hash algorithm
478
- */
479
- set storeHashAlgorithm(value) {
480
- this._storeHashAlgorithm = value;
481
- }
482
- /**
483
- * Gets the keys
484
- * @returns {IterableIterator<string>} - The keys
485
- */
486
- get keys() {
487
- const keys = [];
488
- for (const store of this._store) {
489
- for (const key of store.keys()) {
490
- const item = store.get(key);
491
- if (item && this.hasExpired(item)) {
492
- store.delete(key);
493
- continue;
494
- }
495
- keys.push(key);
496
- }
497
- }
498
- return keys.values();
499
- }
500
- /**
501
- * Gets the items
502
- * @returns {IterableIterator<CacheableStoreItem>} - The items
503
- */
504
- get items() {
505
- const items = [];
506
- for (const store of this._store) {
507
- for (const item of store.values()) {
508
- if (this.hasExpired(item)) {
509
- store.delete(item.key);
510
- continue;
511
- }
512
- items.push(item);
513
- }
514
- }
515
- return items.values();
516
- }
517
- /**
518
- * Gets the store
519
- * @returns {Array<Map<string, CacheableStoreItem>>} - The store
520
- */
521
- get store() {
522
- return this._store;
523
- }
524
- /**
525
- * Gets the value of the key
526
- * @param {string} key - The key to get the value
527
- * @returns {T | undefined} - The value of the key
528
- */
529
- get(key) {
530
- const store = this.getStore(key);
531
- const item = store.get(key);
532
- if (!item) {
533
- return void 0;
534
- }
535
- if (item.expires && Date.now() > item.expires) {
536
- store.delete(key);
537
- return void 0;
538
- }
539
- this.lruMoveToFront(key);
540
- if (!this._useClone) {
541
- return item.value;
542
- }
543
- return this.clone(item.value);
544
- }
545
- /**
546
- * Gets the values of the keys
547
- * @param {string[]} keys - The keys to get the values
548
- * @returns {T[]} - The values of the keys
549
- */
550
- getMany(keys) {
551
- const result = [];
552
- for (const key of keys) {
553
- result.push(this.get(key));
554
- }
555
- return result;
556
- }
557
- /**
558
- * Gets the raw value of the key
559
- * @param {string} key - The key to get the value
560
- * @returns {CacheableStoreItem | undefined} - The raw value of the key
561
- */
562
- getRaw(key) {
563
- const store = this.getStore(key);
564
- const item = store.get(key);
565
- if (!item) {
566
- return void 0;
567
- }
568
- if (item.expires && item.expires && Date.now() > item.expires) {
569
- store.delete(key);
570
- return void 0;
571
- }
572
- this.lruMoveToFront(key);
573
- return item;
574
- }
575
- /**
576
- * Gets the raw values of the keys
577
- * @param {string[]} keys - The keys to get the values
578
- * @returns {CacheableStoreItem[]} - The raw values of the keys
579
- */
580
- getManyRaw(keys) {
581
- const result = [];
582
- for (const key of keys) {
583
- result.push(this.getRaw(key));
584
- }
585
- return result;
586
- }
587
- /**
588
- * Sets the value of the key
589
- * @param {string} key - The key to set the value
590
- * @param {any} value - The value to set
591
- * @param {number|string|SetOptions} [ttl] - Time to Live - If you set a number it is miliseconds, if you set a string it is a human-readable.
592
- * If you want to set expire directly you can do that by setting the expire property in the SetOptions.
593
- * If you set undefined, it will use the default time-to-live. If both are undefined then it will not have a time-to-live.
594
- * @returns {void}
595
- */
596
- set(key, value, ttl) {
597
- const store = this.getStore(key);
598
- let expires;
599
- if (ttl !== void 0 || this._ttl !== void 0) {
600
- if (typeof ttl === "object") {
601
- if (ttl.expire) {
602
- expires = typeof ttl.expire === "number" ? ttl.expire : ttl.expire.getTime();
603
- }
604
- if (ttl.ttl) {
605
- const finalTtl = shorthandToTime(ttl.ttl);
606
- if (finalTtl !== void 0) {
607
- expires = finalTtl;
608
- }
609
- }
610
- } else {
611
- const finalTtl = shorthandToTime(ttl ?? this._ttl);
612
- if (finalTtl !== void 0) {
613
- expires = finalTtl;
614
- }
615
- }
616
- }
617
- if (this._lruSize > 0) {
618
- if (store.has(key)) {
619
- this.lruMoveToFront(key);
620
- } else {
621
- this.lruAddToFront(key);
622
- if (this._lru.size > this._lruSize) {
623
- const oldestKey = this._lru.getOldest();
624
- if (oldestKey) {
625
- this._lru.removeOldest();
626
- this.delete(oldestKey);
627
- }
628
- }
629
- }
630
- }
631
- const item = { key, value, expires };
632
- store.set(key, item);
633
- }
634
- /**
635
- * Sets the values of the keys
636
- * @param {CacheableItem[]} items - The items to set
637
- * @returns {void}
638
- */
639
- setMany(items) {
640
- for (const item of items) {
641
- this.set(item.key, item.value, item.ttl);
642
- }
643
- }
644
- /**
645
- * Checks if the key exists
646
- * @param {string} key - The key to check
647
- * @returns {boolean} - If true, the key exists. If false, the key does not exist.
648
- */
649
- has(key) {
650
- const item = this.get(key);
651
- return Boolean(item);
652
- }
653
- /**
654
- * @function hasMany
655
- * @param {string[]} keys - The keys to check
656
- * @returns {boolean[]} - If true, the key exists. If false, the key does not exist.
657
- */
658
- hasMany(keys) {
659
- const result = [];
660
- for (const key of keys) {
661
- const item = this.get(key);
662
- result.push(Boolean(item));
663
- }
664
- return result;
665
- }
666
- /**
667
- * Take will get the key and delete the entry from cache
668
- * @param {string} key - The key to take
669
- * @returns {T | undefined} - The value of the key
670
- */
671
- take(key) {
672
- const item = this.get(key);
673
- if (!item) {
674
- return void 0;
675
- }
676
- this.delete(key);
677
- return item;
678
- }
679
- /**
680
- * TakeMany will get the keys and delete the entries from cache
681
- * @param {string[]} keys - The keys to take
682
- * @returns {T[]} - The values of the keys
683
- */
684
- takeMany(keys) {
685
- const result = [];
686
- for (const key of keys) {
687
- result.push(this.take(key));
688
- }
689
- return result;
690
- }
691
- /**
692
- * Delete the key
693
- * @param {string} key - The key to delete
694
- * @returns {void}
695
- */
696
- delete(key) {
697
- const store = this.getStore(key);
698
- store.delete(key);
699
- }
700
- /**
701
- * Delete the keys
702
- * @param {string[]} keys - The keys to delete
703
- * @returns {void}
704
- */
705
- deleteMany(keys) {
706
- for (const key of keys) {
707
- this.delete(key);
708
- }
709
- }
710
- /**
711
- * Clear the cache
712
- * @returns {void}
713
- */
714
- clear() {
715
- this._store = Array.from(
716
- { length: this._storeHashSize },
717
- () => /* @__PURE__ */ new Map()
718
- );
719
- this._lru = new DoublyLinkedList();
720
- }
721
- /**
722
- * Get the store based on the key (internal use)
723
- * @param {string} key - The key to get the store
724
- * @returns {CacheableHashStore} - The store
725
- */
726
- getStore(key) {
727
- const hash2 = this.getKeyStoreHash(key);
728
- this._store[hash2] ||= /* @__PURE__ */ new Map();
729
- return this._store[hash2];
730
- }
731
- /**
732
- * Hash the key for which store to go to (internal use)
733
- * @param {string} key - The key to hash
734
- * Available algorithms are: SHA256, SHA1, MD5, and djb2Hash.
735
- * @returns {number} - The hashed key as a number
736
- */
737
- getKeyStoreHash(key) {
738
- if (this._store.length === 1) {
739
- return 0;
740
- }
741
- if (this._storeHashAlgorithm === "djb2Hash" /* djb2Hash */) {
742
- return djb2Hash(key, 0, this._storeHashSize);
743
- }
744
- if (typeof this._storeHashAlgorithm === "function") {
745
- return this._storeHashAlgorithm(key, this._storeHashSize);
746
- }
747
- return hashToNumber(key, 0, this._storeHashSize, this._storeHashAlgorithm);
748
- }
749
- /**
750
- * Clone the value. This is for internal use
751
- * @param {any} value - The value to clone
752
- * @returns {any} - The cloned value
753
- */
754
- clone(value) {
755
- if (this.isPrimitive(value)) {
756
- return value;
757
- }
758
- return structuredClone(value);
759
- }
760
- /**
761
- * Add to the front of the LRU cache. This is for internal use
762
- * @param {string} key - The key to add to the front
763
- * @returns {void}
764
- */
765
- lruAddToFront(key) {
766
- if (this._lruSize === 0) {
767
- return;
768
- }
769
- this._lru.addToFront(key);
770
- }
771
- /**
772
- * Move to the front of the LRU cache. This is for internal use
773
- * @param {string} key - The key to move to the front
774
- * @returns {void}
775
- */
776
- lruMoveToFront(key) {
777
- if (this._lruSize === 0) {
778
- return;
779
- }
780
- this._lru.moveToFront(key);
781
- }
782
- /**
783
- * Resize the LRU cache. This is for internal use.
784
- * @returns {void}
785
- */
786
- lruResize() {
787
- while (this._lru.size > this._lruSize) {
788
- const oldestKey = this._lru.getOldest();
789
- if (oldestKey) {
790
- this._lru.removeOldest();
791
- this.delete(oldestKey);
792
- }
793
- }
794
- }
795
- /**
796
- * Check for expiration. This is for internal use
797
- * @returns {void}
798
- */
799
- checkExpiration() {
800
- for (const store of this._store) {
801
- for (const item of store.values()) {
802
- if (item.expires && Date.now() > item.expires) {
803
- store.delete(item.key);
804
- }
805
- }
806
- }
807
- }
808
- /**
809
- * Start the interval check. This is for internal use
810
- * @returns {void}
811
- */
812
- startIntervalCheck() {
813
- if (this._checkInterval > 0) {
814
- if (this._interval) {
815
- clearInterval(this._interval);
816
- }
817
- this._interval = setInterval(() => {
818
- this.checkExpiration();
819
- }, this._checkInterval).unref();
820
- }
821
- }
822
- /**
823
- * Stop the interval check. This is for internal use
824
- * @returns {void}
825
- */
826
- stopIntervalCheck() {
827
- if (this._interval) {
828
- clearInterval(this._interval);
829
- }
830
- this._interval = 0;
831
- this._checkInterval = 0;
832
- }
833
- /**
834
- * Wrap the function for caching
835
- * @param {Function} function_ - The function to wrap
836
- * @param {Object} [options] - The options to wrap
837
- * @returns {Function} - The wrapped function
838
- */
839
- wrap(function_, options) {
840
- const wrapOptions = {
841
- ttl: options?.ttl ?? this._ttl,
842
- keyPrefix: options?.keyPrefix,
843
- cache: this
844
- };
845
- return wrapSync(function_, wrapOptions);
846
- }
847
- isPrimitive(value) {
848
- const result = false;
849
- if (value === null || value === void 0) {
850
- return true;
851
- }
852
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
853
- return true;
854
- }
855
- return result;
856
- }
857
- setTtl(ttl) {
858
- if (typeof ttl === "string" || ttl === void 0) {
859
- this._ttl = ttl;
860
- } else if (ttl > 0) {
861
- this._ttl = ttl;
862
- } else {
863
- this._ttl = void 0;
864
- }
865
- }
866
- hasExpired(item) {
867
- if (item.expires && Date.now() > item.expires) {
868
- return true;
869
- }
870
- return false;
871
- }
872
- };
873
-
874
- // src/keyv-memory.ts
875
- var KeyvCacheableMemory = class {
876
- opts = {
877
- ttl: 0,
878
- useClone: true,
879
- lruSize: 0,
880
- checkInterval: 0
881
- };
882
- _defaultCache = new CacheableMemory();
883
- _nCache = /* @__PURE__ */ new Map();
884
- _namespace;
885
- constructor(options) {
886
- if (options) {
887
- this.opts = options;
888
- this._defaultCache = new CacheableMemory(options);
889
- if (options.namespace) {
890
- this._namespace = options.namespace;
891
- this._nCache.set(this._namespace, new CacheableMemory(options));
892
- }
893
- }
894
- }
895
- get namespace() {
896
- return this._namespace;
897
- }
898
- set namespace(value) {
899
- this._namespace = value;
900
- }
901
- get store() {
902
- return this.getStore(this._namespace);
903
- }
904
- async get(key) {
905
- const result = this.getStore(this._namespace).get(key);
906
- if (result) {
907
- return result;
908
- }
909
- return void 0;
910
- }
911
- async getMany(keys) {
912
- const result = this.getStore(this._namespace).getMany(keys);
913
- return result;
914
- }
915
- async set(key, value, ttl) {
916
- this.getStore(this._namespace).set(key, value, ttl);
917
- }
918
- async setMany(values) {
919
- this.getStore(this._namespace).setMany(values);
920
- }
921
- async delete(key) {
922
- this.getStore(this._namespace).delete(key);
923
- return true;
924
- }
925
- async deleteMany(key) {
926
- this.getStore(this._namespace).deleteMany(key);
927
- return true;
928
- }
929
- async clear() {
930
- this.getStore(this._namespace).clear();
931
- }
932
- async has(key) {
933
- return this.getStore(this._namespace).has(key);
934
- }
935
- on(event, listener) {
936
- this.getStore(this._namespace).on(event, listener);
937
- return this;
938
- }
939
- getStore(namespace) {
940
- if (!namespace) {
941
- return this._defaultCache;
942
- }
943
- if (!this._nCache.has(namespace)) {
944
- this._nCache.set(namespace, new CacheableMemory(this.opts));
945
- }
946
- return this._nCache.get(namespace);
947
- }
948
- };
949
- function createKeyv(options) {
950
- const store = new KeyvCacheableMemory(options);
951
- const namespace = options?.namespace;
952
- let ttl;
953
- if (options?.ttl && Number.isInteger(options.ttl)) {
954
- ttl = options?.ttl;
955
- }
956
- const keyv = new Keyv({ store, namespace, ttl });
957
- keyv.serialize = void 0;
958
- keyv.deserialize = void 0;
959
- return keyv;
960
- }
961
-
962
- // src/stats.ts
963
- var CacheableStats = class {
964
- _hits = 0;
965
- _misses = 0;
966
- _gets = 0;
967
- _sets = 0;
968
- _deletes = 0;
969
- _clears = 0;
970
- _vsize = 0;
971
- _ksize = 0;
972
- _count = 0;
973
- _enabled = false;
974
- constructor(options) {
975
- if (options?.enabled) {
976
- this._enabled = options.enabled;
977
- }
978
- }
979
- /**
980
- * @returns {boolean} - Whether the stats are enabled
981
- */
982
- get enabled() {
983
- return this._enabled;
984
- }
985
- /**
986
- * @param {boolean} enabled - Whether to enable the stats
987
- */
988
- set enabled(enabled) {
989
- this._enabled = enabled;
990
- }
991
- /**
992
- * @returns {number} - The number of hits
993
- * @readonly
994
- */
995
- get hits() {
996
- return this._hits;
997
- }
998
- /**
999
- * @returns {number} - The number of misses
1000
- * @readonly
1001
- */
1002
- get misses() {
1003
- return this._misses;
1004
- }
1005
- /**
1006
- * @returns {number} - The number of gets
1007
- * @readonly
1008
- */
1009
- get gets() {
1010
- return this._gets;
1011
- }
1012
- /**
1013
- * @returns {number} - The number of sets
1014
- * @readonly
1015
- */
1016
- get sets() {
1017
- return this._sets;
1018
- }
1019
- /**
1020
- * @returns {number} - The number of deletes
1021
- * @readonly
1022
- */
1023
- get deletes() {
1024
- return this._deletes;
1025
- }
1026
- /**
1027
- * @returns {number} - The number of clears
1028
- * @readonly
1029
- */
1030
- get clears() {
1031
- return this._clears;
1032
- }
1033
- /**
1034
- * @returns {number} - The vsize (value size) of the cache instance
1035
- * @readonly
1036
- */
1037
- get vsize() {
1038
- return this._vsize;
1039
- }
1040
- /**
1041
- * @returns {number} - The ksize (key size) of the cache instance
1042
- * @readonly
1043
- */
1044
- get ksize() {
1045
- return this._ksize;
1046
- }
1047
- /**
1048
- * @returns {number} - The count of the cache instance
1049
- * @readonly
1050
- */
1051
- get count() {
1052
- return this._count;
1053
- }
1054
- incrementHits() {
1055
- if (!this._enabled) {
1056
- return;
1057
- }
1058
- this._hits++;
1059
- }
1060
- incrementMisses() {
1061
- if (!this._enabled) {
1062
- return;
1063
- }
1064
- this._misses++;
1065
- }
1066
- incrementGets() {
1067
- if (!this._enabled) {
1068
- return;
1069
- }
1070
- this._gets++;
1071
- }
1072
- incrementSets() {
1073
- if (!this._enabled) {
1074
- return;
1075
- }
1076
- this._sets++;
1077
- }
1078
- incrementDeletes() {
1079
- if (!this._enabled) {
1080
- return;
1081
- }
1082
- this._deletes++;
1083
- }
1084
- incrementClears() {
1085
- if (!this._enabled) {
1086
- return;
1087
- }
1088
- this._clears++;
1089
- }
1090
- incrementVSize(value) {
1091
- if (!this._enabled) {
1092
- return;
1093
- }
1094
- this._vsize += this.roughSizeOfObject(value);
1095
- }
1096
- decreaseVSize(value) {
1097
- if (!this._enabled) {
1098
- return;
1099
- }
1100
- this._vsize -= this.roughSizeOfObject(value);
1101
- }
1102
- incrementKSize(key) {
1103
- if (!this._enabled) {
1104
- return;
1105
- }
1106
- this._ksize += this.roughSizeOfString(key);
1107
- }
1108
- decreaseKSize(key) {
1109
- if (!this._enabled) {
1110
- return;
1111
- }
1112
- this._ksize -= this.roughSizeOfString(key);
1113
- }
1114
- incrementCount() {
1115
- if (!this._enabled) {
1116
- return;
1117
- }
1118
- this._count++;
1119
- }
1120
- decreaseCount() {
1121
- if (!this._enabled) {
1122
- return;
1123
- }
1124
- this._count--;
1125
- }
1126
- setCount(count) {
1127
- if (!this._enabled) {
1128
- return;
1129
- }
1130
- this._count = count;
1131
- }
1132
- roughSizeOfString(value) {
1133
- return value.length * 2;
1134
- }
1135
- roughSizeOfObject(object) {
1136
- const objectList = [];
1137
- const stack = [object];
1138
- let bytes = 0;
1139
- while (stack.length > 0) {
1140
- const value = stack.pop();
1141
- if (typeof value === "boolean") {
1142
- bytes += 4;
1143
- } else if (typeof value === "string") {
1144
- bytes += value.length * 2;
1145
- } else if (typeof value === "number") {
1146
- bytes += 8;
1147
- } else if (typeof value === "object" && value !== null && !objectList.includes(value)) {
1148
- objectList.push(value);
1149
- for (const key in value) {
1150
- bytes += key.length * 2;
1151
- stack.push(value[key]);
1152
- }
1153
- }
1154
- }
1155
- return bytes;
1156
- }
1157
- reset() {
1158
- this._hits = 0;
1159
- this._misses = 0;
1160
- this._gets = 0;
1161
- this._sets = 0;
1162
- this._deletes = 0;
1163
- this._clears = 0;
1164
- this._vsize = 0;
1165
- this._ksize = 0;
1166
- this._count = 0;
1167
- }
1168
- resetStoreValues() {
1169
- this._vsize = 0;
1170
- this._ksize = 0;
1171
- this._count = 0;
1172
- }
1173
- };
1174
-
1175
- // src/ttl.ts
1176
- function getTtlFromExpires(expires) {
1177
- if (expires === void 0 || expires === null) {
1178
- return void 0;
1179
- }
1180
- const now = Date.now();
1181
- if (expires < now) {
1182
- return void 0;
1183
- }
1184
- return expires - now;
1185
- }
1186
- function getCascadingTtl(cacheableTtl, primaryTtl, secondaryTtl) {
1187
- return secondaryTtl ?? primaryTtl ?? shorthandToMilliseconds(cacheableTtl);
1188
- }
1189
- function calculateTtlFromExpiration(ttl, expires) {
1190
- const ttlFromExpires = getTtlFromExpires(expires);
1191
- const expiresFromTtl = ttl ? Date.now() + ttl : void 0;
1192
- if (ttlFromExpires === void 0) {
1193
- return ttl;
1194
- }
1195
- if (expiresFromTtl === void 0) {
1196
- return ttlFromExpires;
1197
- }
1198
- if (expires > expiresFromTtl) {
1199
- return ttl;
1200
- }
1201
- return ttlFromExpires;
1202
- }
1203
-
1204
- // src/index.ts
1205
- import { Keyv as Keyv3, KeyvHooks } from "keyv";
1206
- var CacheableHooks = /* @__PURE__ */ ((CacheableHooks2) => {
1207
- CacheableHooks2["BEFORE_SET"] = "BEFORE_SET";
1208
- CacheableHooks2["AFTER_SET"] = "AFTER_SET";
1209
- CacheableHooks2["BEFORE_SET_MANY"] = "BEFORE_SET_MANY";
1210
- CacheableHooks2["AFTER_SET_MANY"] = "AFTER_SET_MANY";
1211
- CacheableHooks2["BEFORE_GET"] = "BEFORE_GET";
1212
- CacheableHooks2["AFTER_GET"] = "AFTER_GET";
1213
- CacheableHooks2["BEFORE_GET_MANY"] = "BEFORE_GET_MANY";
1214
- CacheableHooks2["AFTER_GET_MANY"] = "AFTER_GET_MANY";
1215
- CacheableHooks2["BEFORE_SECONDARY_SETS_PRIMARY"] = "BEFORE_SECONDARY_SETS_PRIMARY";
1216
- return CacheableHooks2;
1217
- })(CacheableHooks || {});
1218
- var CacheableEvents = /* @__PURE__ */ ((CacheableEvents2) => {
1219
- CacheableEvents2["ERROR"] = "error";
1220
- return CacheableEvents2;
1221
- })(CacheableEvents || {});
1222
- var Cacheable = class extends Hookified2 {
1223
- _primary = createKeyv();
1224
- _secondary;
1225
- _nonBlocking = false;
1226
- _ttl;
1227
- _stats = new CacheableStats({ enabled: false });
1228
- _namespace;
1229
- _cacheId = Math.random().toString(36).slice(2);
1230
- /**
1231
- * Creates a new cacheable instance
1232
- * @param {CacheableOptions} [options] The options for the cacheable instance
1233
- */
1234
- constructor(options) {
1235
- super();
1236
- if (options?.primary) {
1237
- this.setPrimary(options.primary);
1238
- }
1239
- if (options?.secondary) {
1240
- this.setSecondary(options.secondary);
1241
- }
1242
- if (options?.nonBlocking) {
1243
- this._nonBlocking = options.nonBlocking;
1244
- }
1245
- if (options?.stats) {
1246
- this._stats.enabled = options.stats;
1247
- }
1248
- if (options?.ttl) {
1249
- this.setTtl(options.ttl);
1250
- }
1251
- if (options?.cacheId) {
1252
- this._cacheId = options.cacheId;
1253
- }
1254
- if (options?.namespace) {
1255
- this._namespace = options.namespace;
1256
- this._primary.namespace = this.getNameSpace();
1257
- if (this._secondary) {
1258
- this._secondary.namespace = this.getNameSpace();
1259
- }
1260
- }
1261
- }
1262
- /**
1263
- * The namespace for the cacheable instance
1264
- * @returns {string | (() => string) | undefined} The namespace for the cacheable instance
1265
- */
1266
- get namespace() {
1267
- return this._namespace;
1268
- }
1269
- /**
1270
- * Sets the namespace for the cacheable instance
1271
- * @param {string | (() => string) | undefined} namespace The namespace for the cacheable instance
1272
- * @returns {void}
1273
- */
1274
- set namespace(namespace) {
1275
- this._namespace = namespace;
1276
- this._primary.namespace = this.getNameSpace();
1277
- if (this._secondary) {
1278
- this._secondary.namespace = this.getNameSpace();
1279
- }
1280
- }
1281
- /**
1282
- * The statistics for the cacheable instance
1283
- * @returns {CacheableStats} The statistics for the cacheable instance
1284
- */
1285
- get stats() {
1286
- return this._stats;
1287
- }
1288
- /**
1289
- * The primary store for the cacheable instance
1290
- * @returns {Keyv} The primary store for the cacheable instance
1291
- */
1292
- get primary() {
1293
- return this._primary;
1294
- }
1295
- /**
1296
- * Sets the primary store for the cacheable instance
1297
- * @param {Keyv} primary The primary store for the cacheable instance
1298
- */
1299
- set primary(primary) {
1300
- this._primary = primary;
1301
- }
1302
- /**
1303
- * The secondary store for the cacheable instance
1304
- * @returns {Keyv | undefined} The secondary store for the cacheable instance
1305
- */
1306
- get secondary() {
1307
- return this._secondary;
1308
- }
1309
- /**
1310
- * Sets the secondary store for the cacheable instance. If it is set to undefined then the secondary store is disabled.
1311
- * @param {Keyv | undefined} secondary The secondary store for the cacheable instance
1312
- * @returns {void}
1313
- */
1314
- set secondary(secondary) {
1315
- this._secondary = secondary;
1316
- }
1317
- /**
1318
- * Gets whether the secondary store is non-blocking mode. It is set to false by default.
1319
- * If it is set to true then the secondary store will not block the primary store.
1320
- *
1321
- * [Learn more about non-blocking mode](https://cacheable.org/docs/cacheable/#non-blocking-operations).
1322
- *
1323
- * @returns {boolean} Whether the cacheable instance is non-blocking
1324
- */
1325
- get nonBlocking() {
1326
- return this._nonBlocking;
1327
- }
1328
- /**
1329
- * Sets whether the secondary store is non-blocking mode. It is set to false by default.
1330
- * If it is set to true then the secondary store will not block the primary store.
1331
- *
1332
- * [Learn more about non-blocking mode](https://cacheable.org/docs/cacheable/#non-blocking-operations).
1333
- *
1334
- * @param {boolean} nonBlocking Whether the cacheable instance is non-blocking
1335
- * @returns {void}
1336
- */
1337
- set nonBlocking(nonBlocking) {
1338
- this._nonBlocking = nonBlocking;
1339
- }
1340
- /**
1341
- * The time-to-live for the cacheable instance and will be used as the default value.
1342
- * can be a number in milliseconds or a human-readable format such as `1s` for 1 second or `1h` for 1 hour
1343
- * or undefined if there is no time-to-live.
1344
- *
1345
- * [Learn more about time-to-live](https://cacheable.org/docs/cacheable/#shorthand-for-time-to-live-ttl).
1346
- *
1347
- * @returns {number | string | undefined} The time-to-live for the cacheable instance in milliseconds, human-readable format or undefined
1348
- * @example
1349
- * ```typescript
1350
- * const cacheable = new Cacheable({ ttl: '1h' });
1351
- * console.log(cacheable.ttl); // 1h
1352
- * ```
1353
- */
1354
- get ttl() {
1355
- return this._ttl;
1356
- }
1357
- /**
1358
- * Sets the time-to-live for the cacheable instance and will be used as the default value.
1359
- * If you set a number it is miliseconds, if you set a string it is a human-readable
1360
- * format such as `1s` for 1 second or `1h` for 1 hour. Setting undefined means that
1361
- * there is no time-to-live.
1362
- *
1363
- * [Learn more about time-to-live](https://cacheable.org/docs/cacheable/#shorthand-for-time-to-live-ttl).
1364
- *
1365
- * @param {number | string | undefined} ttl The time-to-live for the cacheable instance
1366
- * @example
1367
- * ```typescript
1368
- * const cacheable = new Cacheable();
1369
- * cacheable.ttl = '1h'; // Set the time-to-live to 1 hour
1370
- * ```
1371
- * or setting the time-to-live in milliseconds
1372
- * ```typescript
1373
- * const cacheable = new Cacheable();
1374
- * cacheable.ttl = 3600000; // Set the time-to-live to 1 hour
1375
- * ```
1376
- */
1377
- set ttl(ttl) {
1378
- this.setTtl(ttl);
1379
- }
1380
- /**
1381
- * The cacheId for the cacheable instance. This is primarily used for the wrap function to not have conflicts.
1382
- * If it is not set then it will be a random string that is generated
1383
- * @returns {string} The cacheId for the cacheable instance
1384
- */
1385
- get cacheId() {
1386
- return this._cacheId;
1387
- }
1388
- /**
1389
- * Sets the cacheId for the cacheable instance. This is primarily used for the wrap function to not have conflicts.
1390
- * If it is not set then it will be a random string that is generated
1391
- * @param {string} cacheId The cacheId for the cacheable instance
1392
- */
1393
- set cacheId(cacheId) {
1394
- this._cacheId = cacheId;
1395
- }
1396
- /**
1397
- * Sets the primary store for the cacheable instance
1398
- * @param {Keyv | KeyvStoreAdapter} primary The primary store for the cacheable instance
1399
- * @returns {void}
1400
- */
1401
- setPrimary(primary) {
1402
- if (this.isKeyvInstance(primary)) {
1403
- this._primary = primary;
1404
- } else {
1405
- this._primary = new Keyv2(primary);
1406
- }
1407
- this._primary.on("error", (error) => {
1408
- this.emit("error" /* ERROR */, error);
1409
- });
1410
- }
1411
- /**
1412
- * Sets the secondary store for the cacheable instance. If it is set to undefined then the secondary store is disabled.
1413
- * @param {Keyv | KeyvStoreAdapter} secondary The secondary store for the cacheable instance
1414
- * @returns {void}
1415
- */
1416
- setSecondary(secondary) {
1417
- if (this.isKeyvInstance(secondary)) {
1418
- this._secondary = secondary;
1419
- } else {
1420
- this._secondary = new Keyv2(secondary);
1421
- }
1422
- this._secondary.on("error", (error) => {
1423
- this.emit("error" /* ERROR */, error);
1424
- });
1425
- }
1426
- // biome-ignore lint/suspicious/noExplicitAny: type format
1427
- isKeyvInstance(keyv) {
1428
- if (keyv instanceof Keyv2) {
1429
- return true;
1430
- }
1431
- const keyvMethods = [
1432
- "generateIterator",
1433
- "get",
1434
- "getMany",
1435
- "set",
1436
- "setMany",
1437
- "delete",
1438
- "deleteMany",
1439
- "has",
1440
- "hasMany",
1441
- "clear",
1442
- "disconnect",
1443
- "serialize",
1444
- "deserialize"
1445
- ];
1446
- return keyvMethods.every((method) => typeof keyv[method] === "function");
1447
- }
1448
- getNameSpace() {
1449
- if (typeof this._namespace === "function") {
1450
- return this._namespace();
1451
- }
1452
- return this._namespace;
1453
- }
1454
- async get(key, options = {}) {
1455
- let result;
1456
- const { raw = false } = options;
1457
- try {
1458
- await this.hook("BEFORE_GET" /* BEFORE_GET */, key);
1459
- result = await this._primary.get(key, { raw: true });
1460
- let ttl;
1461
- if (!result && this._secondary) {
1462
- const secondaryResult = await this.getSecondaryRawResults(key);
1463
- if (secondaryResult?.value) {
1464
- result = secondaryResult;
1465
- const cascadeTtl = getCascadingTtl(this._ttl, this._primary.ttl);
1466
- const expires = secondaryResult.expires ?? void 0;
1467
- ttl = calculateTtlFromExpiration(cascadeTtl, expires);
1468
- const setItem = { key, value: result.value, ttl };
1469
- await this.hook(
1470
- "BEFORE_SECONDARY_SETS_PRIMARY" /* BEFORE_SECONDARY_SETS_PRIMARY */,
1471
- setItem
1472
- );
1473
- await this._primary.set(setItem.key, setItem.value, setItem.ttl);
1474
- }
1475
- }
1476
- await this.hook("AFTER_GET" /* AFTER_GET */, { key, result, ttl });
1477
- } catch (error) {
1478
- this.emit("error" /* ERROR */, error);
1479
- }
1480
- if (this.stats.enabled) {
1481
- if (result) {
1482
- this._stats.incrementHits();
1483
- } else {
1484
- this._stats.incrementMisses();
1485
- }
1486
- this.stats.incrementGets();
1487
- }
1488
- return raw ? result : result?.value;
1489
- }
1490
- async getMany(keys, options = {}) {
1491
- let result = [];
1492
- const { raw = false } = options;
1493
- try {
1494
- await this.hook("BEFORE_GET_MANY" /* BEFORE_GET_MANY */, keys);
1495
- result = await this._primary.get(keys, { raw: true });
1496
- if (this._secondary) {
1497
- const missingKeys = [];
1498
- for (const [i, key] of keys.entries()) {
1499
- if (!result[i]) {
1500
- missingKeys.push(key);
1501
- }
1502
- }
1503
- const secondaryResults = await this.getManySecondaryRawResults(missingKeys);
1504
- for await (const [i, key] of keys.entries()) {
1505
- if (!result[i] && secondaryResults[i]) {
1506
- result[i] = secondaryResults[i];
1507
- const cascadeTtl = getCascadingTtl(this._ttl, this._primary.ttl);
1508
- let { expires } = secondaryResults[i];
1509
- if (expires === null) {
1510
- expires = void 0;
1511
- }
1512
- const ttl = calculateTtlFromExpiration(cascadeTtl, expires);
1513
- const setItem = { key, value: result[i].value, ttl };
1514
- await this.hook(
1515
- "BEFORE_SECONDARY_SETS_PRIMARY" /* BEFORE_SECONDARY_SETS_PRIMARY */,
1516
- setItem
1517
- );
1518
- await this._primary.set(setItem.key, setItem.value, setItem.ttl);
1519
- }
1520
- }
1521
- }
1522
- await this.hook("AFTER_GET_MANY" /* AFTER_GET_MANY */, { keys, result });
1523
- } catch (error) {
1524
- this.emit("error" /* ERROR */, error);
1525
- }
1526
- if (this.stats.enabled) {
1527
- for (const item of result) {
1528
- if (item) {
1529
- this._stats.incrementHits();
1530
- } else {
1531
- this._stats.incrementMisses();
1532
- }
1533
- }
1534
- this.stats.incrementGets();
1535
- }
1536
- return raw ? result : result.map((item) => item?.value);
1537
- }
1538
- /**
1539
- * Sets the value of the key. If the secondary store is set then it will also set the value in the secondary store.
1540
- * @param {string} key the key to set the value of
1541
- * @param {T} value The value to set
1542
- * @param {number | string} [ttl] set a number it is miliseconds, set a string it is a human-readable
1543
- * format such as `1s` for 1 second or `1h` for 1 hour. Setting undefined means that it will use the default time-to-live.
1544
- * @returns {boolean} Whether the value was set
1545
- */
1546
- async set(key, value, ttl) {
1547
- let result = false;
1548
- const finalTtl = shorthandToMilliseconds(ttl ?? this._ttl);
1549
- try {
1550
- const item = { key, value, ttl: finalTtl };
1551
- await this.hook("BEFORE_SET" /* BEFORE_SET */, item);
1552
- const promises = [];
1553
- promises.push(this._primary.set(item.key, item.value, item.ttl));
1554
- if (this._secondary) {
1555
- promises.push(this._secondary.set(item.key, item.value, item.ttl));
1556
- }
1557
- if (this._nonBlocking) {
1558
- result = await Promise.race(promises);
1559
- } else {
1560
- const results = await Promise.all(promises);
1561
- result = results[0];
1562
- }
1563
- await this.hook("AFTER_SET" /* AFTER_SET */, item);
1564
- } catch (error) {
1565
- this.emit("error" /* ERROR */, error);
1566
- }
1567
- if (this.stats.enabled) {
1568
- this.stats.incrementKSize(key);
1569
- this.stats.incrementCount();
1570
- this.stats.incrementVSize(value);
1571
- this.stats.incrementSets();
1572
- }
1573
- return result;
1574
- }
1575
- /**
1576
- * Sets the values of the keys. If the secondary store is set then it will also set the values in the secondary store.
1577
- * @param {CacheableItem[]} items The items to set
1578
- * @returns {boolean} Whether the values were set
1579
- */
1580
- async setMany(items) {
1581
- let result = false;
1582
- try {
1583
- await this.hook("BEFORE_SET_MANY" /* BEFORE_SET_MANY */, items);
1584
- result = await this.setManyKeyv(this._primary, items);
1585
- if (this._secondary) {
1586
- if (this._nonBlocking) {
1587
- this.setManyKeyv(this._secondary, items);
1588
- } else {
1589
- await this.setManyKeyv(this._secondary, items);
1590
- }
1591
- }
1592
- await this.hook("AFTER_SET_MANY" /* AFTER_SET_MANY */, items);
1593
- } catch (error) {
1594
- this.emit("error" /* ERROR */, error);
1595
- }
1596
- if (this.stats.enabled) {
1597
- for (const item of items) {
1598
- this.stats.incrementKSize(item.key);
1599
- this.stats.incrementCount();
1600
- this.stats.incrementVSize(item.value);
1601
- }
1602
- }
1603
- return result;
1604
- }
1605
- /**
1606
- * Takes the value of the key and deletes the key. If the key does not exist then it will return undefined.
1607
- * @param {string} key The key to take the value of
1608
- * @returns {Promise<T | undefined>} The value of the key or undefined if the key does not exist
1609
- */
1610
- async take(key) {
1611
- const result = await this.get(key);
1612
- await this.delete(key);
1613
- return result;
1614
- }
1615
- /**
1616
- * Takes the values of the keys and deletes the keys. If the key does not exist then it will return undefined.
1617
- * @param {string[]} keys The keys to take the values of
1618
- * @returns {Promise<Array<T | undefined>>} The values of the keys or undefined if the key does not exist
1619
- */
1620
- async takeMany(keys) {
1621
- const result = await this.getMany(keys);
1622
- await this.deleteMany(keys);
1623
- return result;
1624
- }
1625
- /**
1626
- * Checks if the key exists in the primary store. If it does not exist then it will check the secondary store.
1627
- * @param {string} key The key to check
1628
- * @returns {Promise<boolean>} Whether the key exists
1629
- */
1630
- async has(key) {
1631
- const promises = [];
1632
- promises.push(this._primary.has(key));
1633
- if (this._secondary) {
1634
- promises.push(this._secondary.has(key));
1635
- }
1636
- const resultAll = await Promise.all(promises);
1637
- for (const result of resultAll) {
1638
- if (result) {
1639
- return true;
1640
- }
1641
- }
1642
- return false;
1643
- }
1644
- /**
1645
- * Checks if the keys exist in the primary store. If it does not exist then it will check the secondary store.
1646
- * @param {string[]} keys The keys to check
1647
- * @returns {Promise<boolean[]>} Whether the keys exist
1648
- */
1649
- async hasMany(keys) {
1650
- const result = await this.hasManyKeyv(this._primary, keys);
1651
- const missingKeys = [];
1652
- for (const [i, key] of keys.entries()) {
1653
- if (!result[i] && this._secondary) {
1654
- missingKeys.push(key);
1655
- }
1656
- }
1657
- if (missingKeys.length > 0 && this._secondary) {
1658
- const secondary = await this.hasManyKeyv(this._secondary, keys);
1659
- for (const [i, _key] of keys.entries()) {
1660
- if (!result[i] && secondary[i]) {
1661
- result[i] = secondary[i];
1662
- }
1663
- }
1664
- }
1665
- return result;
1666
- }
1667
- /**
1668
- * Deletes the key from the primary store. If the secondary store is set then it will also delete the key from the secondary store.
1669
- * @param {string} key The key to delete
1670
- * @returns {Promise<boolean>} Whether the key was deleted
1671
- */
1672
- async delete(key) {
1673
- let result = false;
1674
- const promises = [];
1675
- if (this.stats.enabled) {
1676
- const statResult = await this._primary.get(key);
1677
- if (statResult) {
1678
- this.stats.decreaseKSize(key);
1679
- this.stats.decreaseVSize(statResult);
1680
- this.stats.decreaseCount();
1681
- this.stats.incrementDeletes();
1682
- }
1683
- }
1684
- promises.push(this._primary.delete(key));
1685
- if (this._secondary) {
1686
- promises.push(this._secondary.delete(key));
1687
- }
1688
- if (this.nonBlocking) {
1689
- result = await Promise.race(promises);
1690
- } else {
1691
- const resultAll = await Promise.all(promises);
1692
- result = resultAll[0];
1693
- }
1694
- return result;
1695
- }
1696
- /**
1697
- * Deletes the keys from the primary store. If the secondary store is set then it will also delete the keys from the secondary store.
1698
- * @param {string[]} keys The keys to delete
1699
- * @returns {Promise<boolean>} Whether the keys were deleted
1700
- */
1701
- async deleteMany(keys) {
1702
- if (this.stats.enabled) {
1703
- const statResult = await this._primary.get(keys);
1704
- for (const key of keys) {
1705
- this.stats.decreaseKSize(key);
1706
- this.stats.decreaseVSize(statResult);
1707
- this.stats.decreaseCount();
1708
- this.stats.incrementDeletes();
1709
- }
1710
- }
1711
- const result = await this.deleteManyKeyv(this._primary, keys);
1712
- if (this._secondary) {
1713
- if (this._nonBlocking) {
1714
- this.deleteManyKeyv(this._secondary, keys);
1715
- } else {
1716
- await this.deleteManyKeyv(this._secondary, keys);
1717
- }
1718
- }
1719
- return result;
1720
- }
1721
- /**
1722
- * Clears the primary store. If the secondary store is set then it will also clear the secondary store.
1723
- * @returns {Promise<void>}
1724
- */
1725
- async clear() {
1726
- const promises = [];
1727
- promises.push(this._primary.clear());
1728
- if (this._secondary) {
1729
- promises.push(this._secondary.clear());
1730
- }
1731
- await (this._nonBlocking ? Promise.race(promises) : Promise.all(promises));
1732
- if (this.stats.enabled) {
1733
- this._stats.resetStoreValues();
1734
- this._stats.incrementClears();
1735
- }
1736
- }
1737
- /**
1738
- * Disconnects the primary store. If the secondary store is set then it will also disconnect the secondary store.
1739
- * @returns {Promise<void>}
1740
- */
1741
- async disconnect() {
1742
- const promises = [];
1743
- promises.push(this._primary.disconnect());
1744
- if (this._secondary) {
1745
- promises.push(this._secondary.disconnect());
1746
- }
1747
- await (this._nonBlocking ? Promise.race(promises) : Promise.all(promises));
1748
- }
1749
- /**
1750
- * Wraps a function with caching
1751
- *
1752
- * [Learn more about wrapping functions](https://cacheable.org/docs/cacheable/#wrap--memoization-for-sync-and-async-functions).
1753
- * @param {Function} function_ The function to wrap
1754
- * @param {WrapOptions} [options] The options for the wrap function
1755
- * @returns {Function} The wrapped function
1756
- */
1757
- // biome-ignore lint/suspicious/noExplicitAny: type format
1758
- wrap(function_, options) {
1759
- const wrapOptions = {
1760
- ttl: options?.ttl ?? this._ttl,
1761
- keyPrefix: options?.keyPrefix,
1762
- cache: this,
1763
- cacheId: this._cacheId
1764
- };
1765
- return wrap(function_, wrapOptions);
1766
- }
1767
- /**
1768
- * Retrieves the value associated with the given key from the cache. If the key is not found,
1769
- * invokes the provided function to calculate the value, stores it in the cache, and then returns it.
1770
- *
1771
- * @param {GetOrSetKey} key - The key to retrieve or set in the cache. This can also be a function that returns a string key.
1772
- * If a function is provided, it will be called with the cache options to generate the key.
1773
- * @param {() => Promise<T>} function_ - The asynchronous function that computes the value to be cached if the key does not exist.
1774
- * @param {GetOrSetFunctionOptions} [options] - Optional settings for caching, such as the time to live (TTL) or whether to cache errors.
1775
- * @return {Promise<T | undefined>} - A promise that resolves to the cached or newly computed value, or undefined if an error occurs and caching is not configured for errors.
1776
- */
1777
- async getOrSet(key, function_, options) {
1778
- const getOrSetOptions = {
1779
- cache: this,
1780
- cacheId: this._cacheId,
1781
- ttl: options?.ttl ?? this._ttl,
1782
- cacheErrors: options?.cacheErrors,
1783
- throwErrors: options?.throwErrors
1784
- };
1785
- return getOrSet(key, function_, getOrSetOptions);
1786
- }
1787
- /**
1788
- * Will hash an object using the specified algorithm. The default algorithm is 'sha256'.
1789
- * @param {any} object the object to hash
1790
- * @param {string} algorithm the hash algorithm to use. The default is 'sha256'
1791
- * @returns {string} the hash of the object
1792
- */
1793
- // biome-ignore lint/suspicious/noExplicitAny: type format
1794
- hash(object, algorithm = "sha256") {
1795
- return hash(object, algorithm);
1796
- }
1797
- async getSecondaryRawResults(key) {
1798
- let result;
1799
- if (this._secondary) {
1800
- result = await this._secondary.get(key, { raw: true });
1801
- }
1802
- return result;
1803
- }
1804
- async getManySecondaryRawResults(keys) {
1805
- let result = [];
1806
- if (this._secondary) {
1807
- result = await this._secondary.get(keys, { raw: true });
1808
- }
1809
- return result;
1810
- }
1811
- async deleteManyKeyv(keyv, keys) {
1812
- const promises = [];
1813
- for (const key of keys) {
1814
- promises.push(keyv.delete(key));
1815
- }
1816
- await Promise.all(promises);
1817
- return true;
1818
- }
1819
- async setManyKeyv(keyv, items) {
1820
- const promises = [];
1821
- for (const item of items) {
1822
- const finalTtl = shorthandToMilliseconds(item.ttl ?? this._ttl);
1823
- promises.push(keyv.set(item.key, item.value, finalTtl));
1824
- }
1825
- await Promise.all(promises);
1826
- return true;
1827
- }
1828
- async hasManyKeyv(keyv, keys) {
1829
- const promises = [];
1830
- for (const key of keys) {
1831
- promises.push(keyv.has(key));
1832
- }
1833
- return Promise.all(promises);
1834
- }
1835
- setTtl(ttl) {
1836
- if (typeof ttl === "string" || ttl === void 0) {
1837
- this._ttl = ttl;
1838
- } else if (ttl > 0) {
1839
- this._ttl = ttl;
1840
- } else {
1841
- this._ttl = void 0;
1842
- }
1843
- }
1844
- };
1845
- export {
1846
- Cacheable,
1847
- CacheableEvents,
1848
- CacheableHooks,
1849
- CacheableMemory,
1850
- CacheableStats,
1851
- Keyv3 as Keyv,
1852
- KeyvCacheableMemory,
1853
- KeyvHooks,
1854
- createKeyv,
1855
- getOrSet,
1856
- shorthandToMilliseconds,
1857
- shorthandToTime,
1858
- wrap,
1859
- wrapSync
1860
- };
1
+ import{getOrSet as v,wrap as A}from"@cacheable/memoize";import{createKeyv as w}from"@cacheable/memory";import{Stats as O,calculateTtlFromExpiration as p,getCascadingTtl as u,HashAlgorithm as R,hash as M,shorthandToMilliseconds as g}from"@cacheable/utils";import{Hookified as b}from"hookified";import{Keyv as f}from"keyv";var m=(o=>(o.BEFORE_SET="BEFORE_SET",o.AFTER_SET="AFTER_SET",o.BEFORE_SET_MANY="BEFORE_SET_MANY",o.AFTER_SET_MANY="AFTER_SET_MANY",o.BEFORE_GET="BEFORE_GET",o.AFTER_GET="AFTER_GET",o.BEFORE_GET_MANY="BEFORE_GET_MANY",o.AFTER_GET_MANY="AFTER_GET_MANY",o.BEFORE_SECONDARY_SETS_PRIMARY="BEFORE_SECONDARY_SETS_PRIMARY",o))(m||{}),E=(e=>(e.ERROR="error",e.CACHE_HIT="cache:hit",e.CACHE_MISS="cache:miss",e))(E||{});import{getOrSet as D,wrap as H,wrapSync as z}from"@cacheable/memoize";import{CacheableMemory as W,createKeyv as j,KeyvCacheableMemory as q}from"@cacheable/memory";import{calculateTtlFromExpiration as L,getCascadingTtl as Q,HashAlgorithm as U,hash as X,Stats as Z,shorthandToMilliseconds as $,shorthandToTime as tt}from"@cacheable/utils";import{Keyv as st,KeyvHooks as it}from"keyv";var T=class extends b{_primary=w();_secondary;_nonBlocking=!1;_ttl;_stats=new O({enabled:!1});_namespace;_cacheId=Math.random().toString(36).slice(2);constructor(t){super(),t?.primary&&this.setPrimary(t.primary),t?.secondary&&this.setSecondary(t.secondary),t?.nonBlocking&&(this._nonBlocking=t.nonBlocking),t?.stats&&(this._stats.enabled=t.stats),t?.ttl&&this.setTtl(t.ttl),t?.cacheId&&(this._cacheId=t.cacheId),t?.namespace&&(this._namespace=t.namespace,this._primary.namespace=this.getNameSpace(),this._secondary&&(this._secondary.namespace=this.getNameSpace()))}get namespace(){return this._namespace}set namespace(t){this._namespace=t,this._primary.namespace=this.getNameSpace(),this._secondary&&(this._secondary.namespace=this.getNameSpace())}get stats(){return this._stats}get primary(){return this._primary}set primary(t){this._primary=t}get secondary(){return this._secondary}set secondary(t){this._secondary=t}get nonBlocking(){return this._nonBlocking}set nonBlocking(t){this._nonBlocking=t}get ttl(){return this._ttl}set ttl(t){this.setTtl(t)}get cacheId(){return this._cacheId}set cacheId(t){this._cacheId=t}setPrimary(t){this.isKeyvInstance(t)?this._primary=t:this._primary=new f(t),this._primary.on("error",s=>{this.emit("error",s)})}setSecondary(t){this.isKeyvInstance(t)?this._secondary=t:this._secondary=new f(t),this._secondary.on("error",s=>{this.emit("error",s)})}isKeyvInstance(t){return t instanceof f?!0:["generateIterator","get","getMany","set","setMany","delete","deleteMany","has","hasMany","clear","disconnect","serialize","deserialize"].every(e=>typeof t[e]=="function")}getNameSpace(){return typeof this._namespace=="function"?this._namespace():this._namespace}async get(t,s){return(await this.getRaw(t,s))?.value}async getRaw(t,s){let e;try{await this.hook("BEFORE_GET",t),e=await this._primary.getRaw(t);let i;e?this.emit("cache:hit",{key:t,value:e.value,store:"primary"}):this.emit("cache:miss",{key:t,store:"primary"});let n=s?.nonBlocking??this._nonBlocking;if(!e&&this._secondary){let a;n?a=await this.processSecondaryForGetRawNonBlocking(this._primary,this._secondary,t):a=await this.processSecondaryForGetRaw(this._primary,this._secondary,t),a&&(e=a.result,i=a.ttl)}await this.hook("AFTER_GET",{key:t,result:e,ttl:i})}catch(i){this.emit("error",i)}return this.stats.enabled&&(e?this._stats.incrementHits():this._stats.incrementMisses(),this.stats.incrementGets()),e}async getManyRaw(t,s){let e=[];try{await this.hook("BEFORE_GET_MANY",t),e=await this._primary.getManyRaw(t);for(let[n,a]of t.entries())e[n]?this.emit("cache:hit",{key:a,value:e[n].value,store:"primary"}):this.emit("cache:miss",{key:a,store:"primary"});let i=s?.nonBlocking??this._nonBlocking;this._secondary&&(i?await this.processSecondaryForGetManyRawNonBlocking(this._primary,this._secondary,t,e):await this.processSecondaryForGetManyRaw(this._primary,this._secondary,t,e)),await this.hook("AFTER_GET_MANY",{keys:t,result:e})}catch(i){this.emit("error",i)}if(this.stats.enabled){for(let i of e)i?this._stats.incrementHits():this._stats.incrementMisses();this.stats.incrementGets()}return e}async getMany(t,s){return(await this.getManyRaw(t,s)).map(i=>i?.value)}async set(t,s,e){let i=!1,n=g(e??this._ttl);try{let a={key:t,value:s,ttl:n};await this.hook("BEFORE_SET",a);let r=[];if(r.push(this._primary.set(a.key,a.value,a.ttl)),this._secondary&&r.push(this._secondary.set(a.key,a.value,a.ttl)),this._nonBlocking){i=await Promise.race(r);for(let c of r)c.catch(o=>{this.emit("error",o)})}else i=(await Promise.all(r))[0];await this.hook("AFTER_SET",a)}catch(a){this.emit("error",a)}return this.stats.enabled&&(this.stats.incrementKSize(t),this.stats.incrementCount(),this.stats.incrementVSize(s),this.stats.incrementSets()),i}async setMany(t){let s=!1;try{await this.hook("BEFORE_SET_MANY",t),s=await this.setManyKeyv(this._primary,t),this._secondary&&(this._nonBlocking?this.setManyKeyv(this._secondary,t).catch(e=>{this.emit("error",e)}):await this.setManyKeyv(this._secondary,t)),await this.hook("AFTER_SET_MANY",t)}catch(e){this.emit("error",e)}if(this.stats.enabled)for(let e of t)this.stats.incrementKSize(e.key),this.stats.incrementCount(),this.stats.incrementVSize(e.value);return s}async take(t){let s=await this.get(t);return await this.delete(t),s}async takeMany(t){let s=await this.getMany(t);return await this.deleteMany(t),s}async has(t){let s=[];s.push(this._primary.has(t)),this._secondary&&s.push(this._secondary.has(t));let e=await Promise.all(s);for(let i of e)if(i)return!0;return!1}async hasMany(t){let s=await this.hasManyKeyv(this._primary,t),e=[];for(let[i,n]of t.entries())!s[i]&&this._secondary&&e.push(n);if(e.length>0&&this._secondary){let i=await this.hasManyKeyv(this._secondary,t);for(let[n,a]of t.entries())!s[n]&&i[n]&&(s[n]=i[n])}return s}async delete(t){let s=!1,e=[];if(this.stats.enabled){let i=await this._primary.get(t);i&&(this.stats.decreaseKSize(t),this.stats.decreaseVSize(i),this.stats.decreaseCount(),this.stats.incrementDeletes())}if(e.push(this._primary.delete(t)),this._secondary&&e.push(this._secondary.delete(t)),this.nonBlocking){s=await Promise.race(e);for(let i of e)i.catch(n=>{this.emit("error",n)})}else s=(await Promise.all(e))[0];return s}async deleteMany(t){if(this.stats.enabled){let e=await this._primary.get(t);for(let i of t)this.stats.decreaseKSize(i),this.stats.decreaseVSize(e),this.stats.decreaseCount(),this.stats.incrementDeletes()}let s=await this._primary.deleteMany(t);return this._secondary&&(this._nonBlocking?this._secondary.deleteMany(t).catch(e=>{this.emit("error",e)}):await this._secondary.deleteMany(t)),s}async clear(){let t=[];t.push(this._primary.clear()),this._secondary&&t.push(this._secondary.clear()),await(this._nonBlocking?Promise.race(t):Promise.all(t)),this.stats.enabled&&(this._stats.resetStoreValues(),this._stats.incrementClears())}async disconnect(){let t=[];t.push(this._primary.disconnect()),this._secondary&&t.push(this._secondary.disconnect()),await(this._nonBlocking?Promise.race(t):Promise.all(t))}wrap(t,s){let e={get:async n=>this.get(n),has:async n=>this.has(n),set:async(n,a,r)=>{await this.set(n,a,r)},on:(n,a)=>{this.on(n,a)},emit:(n,...a)=>this.emit(n,...a)},i={ttl:s?.ttl??this._ttl,keyPrefix:s?.keyPrefix,createKey:s?.createKey,cacheErrors:s?.cacheErrors,cache:e,cacheId:this._cacheId,serialize:s?.serialize};return A(t,i)}async getOrSet(t,s,e){let n={cache:{get:async a=>this.get(a),has:async a=>this.has(a),set:async(a,r,c)=>{await this.set(a,r,c)},on:(a,r)=>{this.on(a,r)},emit:(a,...r)=>this.emit(a,...r)},cacheId:this._cacheId,ttl:e?.ttl??this._ttl,cacheErrors:e?.cacheErrors,throwErrors:e?.throwErrors};return v(t,s,n)}hash(t,s=R.SHA256){let e=Object.values(R).includes(s)?s:R.SHA256;return M(t,{algorithm:e})}async setManyKeyv(t,s){let e=[];for(let i of s){let n=g(i.ttl??this._ttl);e.push({key:i.key,value:i.value,ttl:n})}return await t.setMany(e),!0}async hasManyKeyv(t,s){let e=[];for(let i of s)e.push(t.has(i));return Promise.all(e)}async processSecondaryForGetRaw(t,s,e){let i=await s.getRaw(e);if(i?.value){this.emit("cache:hit",{key:e,value:i.value,store:"secondary"});let n=u(this._ttl,this._primary.ttl),a=i.expires??void 0,r=p(n,a),c={key:e,value:i.value,ttl:r};return await this.hook("BEFORE_SECONDARY_SETS_PRIMARY",c),await t.set(c.key,c.value,c.ttl),{result:i,ttl:r}}else{this.emit("cache:miss",{key:e,store:"secondary"});return}}async processSecondaryForGetRawNonBlocking(t,s,e){let i=await s.getRaw(e);if(i?.value){this.emit("cache:hit",{key:e,value:i.value,store:"secondary"});let n=u(this._ttl,this._primary.ttl),a=i.expires??void 0,r=p(n,a),c={key:e,value:i.value,ttl:r};return this.hook("BEFORE_SECONDARY_SETS_PRIMARY",c).then(async()=>{await t.set(c.key,c.value,c.ttl)}).catch(o=>{this.emit("error",o)}),{result:i,ttl:r}}else{this.emit("cache:miss",{key:e,store:"secondary"});return}}async processSecondaryForGetManyRaw(t,s,e,i){let n=[];for(let[c,o]of e.entries())i[c]||n.push(o);let a=await s.getManyRaw(n),r=0;for await(let[c,o]of e.entries())if(!i[c]){let l=a[r];if(l&&l.value!==void 0){i[c]=l,this.emit("cache:hit",{key:o,value:l.value,store:"secondary"});let d=u(this._ttl,this._primary.ttl),{expires:y}=l;y===null&&(y=void 0);let _=p(d,y),h={key:o,value:l.value,ttl:_};await this.hook("BEFORE_SECONDARY_SETS_PRIMARY",h),await t.set(h.key,h.value,h.ttl)}else this.emit("cache:miss",{key:o,store:"secondary"});r++}}async processSecondaryForGetManyRawNonBlocking(t,s,e,i){let n=[];for(let[c,o]of e.entries())i[c]||n.push(o);let a=await s.getManyRaw(n),r=0;for await(let[c,o]of e.entries())if(!i[c]){let l=a[r];if(l&&l.value!==void 0){i[c]=l,this.emit("cache:hit",{key:o,value:l.value,store:"secondary"});let d=u(this._ttl,this._primary.ttl),{expires:y}=l;y===null&&(y=void 0);let _=p(d,y),h={key:o,value:l.value,ttl:_};this.hook("BEFORE_SECONDARY_SETS_PRIMARY",h).then(async()=>{await t.set(h.key,h.value,h.ttl)}).catch(S=>{this.emit("error",S)})}else this.emit("cache:miss",{key:o,store:"secondary"});r++}}setTtl(t){typeof t=="string"||t===void 0?this._ttl=t:t>0?this._ttl=t:this._ttl=void 0}};export{T as Cacheable,E as CacheableEvents,m as CacheableHooks,W as CacheableMemory,Z as CacheableStats,U as HashAlgorithm,st as Keyv,q as KeyvCacheableMemory,it as KeyvHooks,L as calculateTtlFromExpiration,j as createKeyv,Q as getCascadingTtl,D as getOrSet,X as hash,$ as shorthandToMilliseconds,tt as shorthandToTime,H as wrap,z as wrapSync};