@cacheable/utils 2.1.0 → 2.2.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.cjs CHANGED
@@ -1 +1,637 @@
1
- "use strict";var N=Object.create;var l=Object.defineProperty;var A=Object.getOwnPropertyDescriptor;var H=Object.getOwnPropertyNames;var j=Object.getPrototypeOf,E=Object.prototype.hasOwnProperty;var M=(t,e)=>{for(var r in e)l(t,r,{get:e[r],enumerable:!0})},p=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of H(e))!E.call(t,n)&&n!==r&&l(t,n,{get:()=>e[n],enumerable:!(i=A(e,n))||i.enumerable});return t};var F=(t,e,r)=>(r=t!=null?N(j(t)):{},p(e||!t||!t.__esModule?l(r,"default",{value:t,enumerable:!0}):r,t)),K=t=>p(l({},"__esModule",{value:!0}),t);var U={};M(U,{HashAlgorithm:()=>b,Stats:()=>m,calculateTtlFromExpiration:()=>C,coalesceAsync:()=>T,getCascadingTtl:()=>P,getTtlFromExpires:()=>d,hash:()=>f,hashToNumber:()=>v,isKeyvInstance:()=>z,isObject:()=>S,lessThan:()=>k,runIfFn:()=>w,shorthandToMilliseconds:()=>u,shorthandToTime:()=>g,sleep:()=>O});module.exports=K(U);var u=t=>{let e;if(t!==void 0){if(typeof t=="number")e=t;else if(typeof t=="string")if(t=t.trim(),Number.isNaN(Number(t))){let r=/^([\d.]+)\s*(ms|s|m|h|hr|d)$/i.exec(t);if(!r)throw new Error(`Unsupported time format: "${t}". Use 'ms', 's', 'm', 'h', 'hr', or 'd'.`);let[,i,n]=r,s=Number.parseFloat(i);switch(n.toLowerCase()){case"ms":{e=s;break}case"s":{e=s*1e3;break}case"m":{e=s*1e3*60;break}case"h":{e=s*1e3*60*60;break}case"hr":{e=s*1e3*60*60;break}case"d":{e=s*1e3*60*60*24;break}default:e=Number(t)}}else e=Number(t);else throw new TypeError("Time must be a string or a number.");return e}},g=(t,e)=>{e??=new Date;let r=u(t);return r===void 0?e.getTime():e.getTime()+r};var a=new Map;function I(t){return a.has(t)}function D(t){a.set(t,[])}function J(t){a.delete(t)}function L(t,e){let r=y(t);r.push(e),a.set(t,r)}function y(t){return a.get(t)??[]}async function $(t){return new Promise((e,r)=>{L(t,{resolve:e,reject:r})})}function V(t){let e=y(t);return J(t),e}function _(t){let{key:e,error:r,result:i}=t;for(let n of V(e))r?n.reject(r):n.resolve(i)}async function T(t,e){if(!I(t)){D(t);try{let r=await Promise.resolve(e());return _({key:t,result:r}),r}catch(r){throw _({key:t,error:r}),r}}return $(t)}var c=F(require("crypto"),1),b=(n=>(n.SHA256="sha256",n.SHA512="sha512",n.MD5="md5",n.DJB2="djb2",n))(b||{});function f(t,e={algorithm:"sha256",serialize:JSON.stringify}){e?.algorithm||(e.algorithm="sha256"),e?.serialize||(e.serialize=JSON.stringify);let r=e.serialize(t);if(e?.algorithm==="djb2")return B(r);if(!c.getHashes().includes(e.algorithm))throw new Error(`Unsupported hash algorithm: '${e?.algorithm}'`);let i=c.createHash(e.algorithm);return i.update(r),i.digest("hex")}function v(t,e={min:0,max:10,algorithm:"sha256",serialize:JSON.stringify}){let r=e?.min??0,i=e?.max??10;if(r>=i)throw new Error(`Invalid range: min (${r}) must be less than max (${i})`);e?.algorithm||(e.algorithm="sha256"),e?.serialize||(e.serialize=JSON.stringify);let n=f(t,e),s=Number.parseInt(n,16),o=i-r+1,h=r+s%o;return h<r?r:h>i?i:h}function B(t){let e=5381;for(let r=0;r<t.length;r++)e=e*33^t.charCodeAt(r);return e.toString()}var x=require("keyv");function z(t){return t==null?!1:t instanceof x.Keyv?!0:["generateIterator","get","getMany","set","setMany","delete","deleteMany","has","hasMany","clear","disconnect","serialize","deserialize"].every(r=>typeof t[r]=="function")}function S(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function k(t,e){return typeof t=="number"&&typeof e=="number"?t<e:!1}function w(t,...e){return typeof t=="function"?t(...e):t}var O=async t=>new Promise(e=>setTimeout(e,t));var m=class{_hits=0;_misses=0;_gets=0;_sets=0;_deletes=0;_clears=0;_vsize=0;_ksize=0;_count=0;_enabled=!1;constructor(e){e?.enabled&&(this._enabled=e.enabled)}get enabled(){return this._enabled}set enabled(e){this._enabled=e}get hits(){return this._hits}get misses(){return this._misses}get gets(){return this._gets}get sets(){return this._sets}get deletes(){return this._deletes}get clears(){return this._clears}get vsize(){return this._vsize}get ksize(){return this._ksize}get count(){return this._count}incrementHits(){this._enabled&&this._hits++}incrementMisses(){this._enabled&&this._misses++}incrementGets(){this._enabled&&this._gets++}incrementSets(){this._enabled&&this._sets++}incrementDeletes(){this._enabled&&this._deletes++}incrementClears(){this._enabled&&this._clears++}incrementVSize(e){this._enabled&&(this._vsize+=this.roughSizeOfObject(e))}decreaseVSize(e){this._enabled&&(this._vsize-=this.roughSizeOfObject(e))}incrementKSize(e){this._enabled&&(this._ksize+=this.roughSizeOfString(e))}decreaseKSize(e){this._enabled&&(this._ksize-=this.roughSizeOfString(e))}incrementCount(){this._enabled&&this._count++}decreaseCount(){this._enabled&&this._count--}setCount(e){this._enabled&&(this._count=e)}roughSizeOfString(e){return e.length*2}roughSizeOfObject(e){let r=[],i=[e],n=0;for(;i.length>0;){let s=i.pop();if(typeof s=="boolean")n+=4;else if(typeof s=="string")n+=s.length*2;else if(typeof s=="number")n+=8;else if(typeof s=="object"&&s!==null&&!r.includes(s)){r.push(s);for(let o in s)n+=o.length*2,i.push(s[o])}}return n}reset(){this._hits=0,this._misses=0,this._gets=0,this._sets=0,this._deletes=0,this._clears=0,this._vsize=0,this._ksize=0,this._count=0}resetStoreValues(){this._vsize=0,this._ksize=0,this._count=0}};function d(t){if(t==null)return;let e=Date.now();if(!(t<e))return t-e}function P(t,e,r){return r??e??u(t)}function C(t,e){let r=d(e),i=t?Date.now()+t:void 0;return r===void 0?t:i===void 0?r:e&&e>i?t:r}0&&(module.exports={HashAlgorithm,Stats,calculateTtlFromExpiration,coalesceAsync,getCascadingTtl,getTtlFromExpires,hash,hashToNumber,isKeyvInstance,isObject,lessThan,runIfFn,shorthandToMilliseconds,shorthandToTime,sleep});
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ HashAlgorithm: () => HashAlgorithm,
34
+ Stats: () => Stats,
35
+ calculateTtlFromExpiration: () => calculateTtlFromExpiration,
36
+ coalesceAsync: () => coalesceAsync,
37
+ createWrapKey: () => createWrapKey,
38
+ getCascadingTtl: () => getCascadingTtl,
39
+ getOrSet: () => getOrSet,
40
+ getTtlFromExpires: () => getTtlFromExpires,
41
+ hash: () => hash,
42
+ hashToNumber: () => hashToNumber,
43
+ isKeyvInstance: () => isKeyvInstance,
44
+ isObject: () => isObject,
45
+ lessThan: () => lessThan,
46
+ runIfFn: () => runIfFn,
47
+ shorthandToMilliseconds: () => shorthandToMilliseconds,
48
+ shorthandToTime: () => shorthandToTime,
49
+ sleep: () => sleep,
50
+ wrap: () => wrap,
51
+ wrapSync: () => wrapSync
52
+ });
53
+ module.exports = __toCommonJS(index_exports);
54
+
55
+ // src/shorthand-time.ts
56
+ var shorthandToMilliseconds = (shorthand) => {
57
+ let milliseconds;
58
+ if (shorthand === void 0) {
59
+ return void 0;
60
+ }
61
+ if (typeof shorthand === "number") {
62
+ milliseconds = shorthand;
63
+ } else {
64
+ if (typeof shorthand !== "string") {
65
+ return void 0;
66
+ }
67
+ shorthand = shorthand.trim();
68
+ if (Number.isNaN(Number(shorthand))) {
69
+ const match = /^([\d.]+)\s*(ms|s|m|h|hr|d)$/i.exec(shorthand);
70
+ if (!match) {
71
+ throw new Error(
72
+ `Unsupported time format: "${shorthand}". Use 'ms', 's', 'm', 'h', 'hr', or 'd'.`
73
+ );
74
+ }
75
+ const [, value, unit] = match;
76
+ const numericValue = Number.parseFloat(value);
77
+ const unitLower = unit.toLowerCase();
78
+ switch (unitLower) {
79
+ case "ms": {
80
+ milliseconds = numericValue;
81
+ break;
82
+ }
83
+ case "s": {
84
+ milliseconds = numericValue * 1e3;
85
+ break;
86
+ }
87
+ case "m": {
88
+ milliseconds = numericValue * 1e3 * 60;
89
+ break;
90
+ }
91
+ case "h": {
92
+ milliseconds = numericValue * 1e3 * 60 * 60;
93
+ break;
94
+ }
95
+ case "hr": {
96
+ milliseconds = numericValue * 1e3 * 60 * 60;
97
+ break;
98
+ }
99
+ case "d": {
100
+ milliseconds = numericValue * 1e3 * 60 * 60 * 24;
101
+ break;
102
+ }
103
+ /* v8 ignore next -- @preserve */
104
+ default: {
105
+ milliseconds = Number(shorthand);
106
+ }
107
+ }
108
+ } else {
109
+ milliseconds = Number(shorthand);
110
+ }
111
+ }
112
+ return milliseconds;
113
+ };
114
+ var shorthandToTime = (shorthand, fromDate) => {
115
+ fromDate ??= /* @__PURE__ */ new Date();
116
+ const milliseconds = shorthandToMilliseconds(shorthand);
117
+ if (milliseconds === void 0) {
118
+ return fromDate.getTime();
119
+ }
120
+ return fromDate.getTime() + milliseconds;
121
+ };
122
+
123
+ // src/coalesce-async.ts
124
+ var callbacks = /* @__PURE__ */ new Map();
125
+ function hasKey(key) {
126
+ return callbacks.has(key);
127
+ }
128
+ function addKey(key) {
129
+ callbacks.set(key, []);
130
+ }
131
+ function removeKey(key) {
132
+ callbacks.delete(key);
133
+ }
134
+ function addCallbackToKey(key, callback) {
135
+ const stash = getCallbacksByKey(key);
136
+ stash.push(callback);
137
+ callbacks.set(key, stash);
138
+ }
139
+ function getCallbacksByKey(key) {
140
+ return callbacks.get(key) ?? [];
141
+ }
142
+ async function enqueue(key) {
143
+ return new Promise((resolve, reject) => {
144
+ const callback = { resolve, reject };
145
+ addCallbackToKey(key, callback);
146
+ });
147
+ }
148
+ function dequeue(key) {
149
+ const stash = getCallbacksByKey(key);
150
+ removeKey(key);
151
+ return stash;
152
+ }
153
+ function coalesce(options) {
154
+ const { key, error, result } = options;
155
+ for (const callback of dequeue(key)) {
156
+ if (error) {
157
+ callback.reject(error);
158
+ } else {
159
+ callback.resolve(result);
160
+ }
161
+ }
162
+ }
163
+ async function coalesceAsync(key, fnc) {
164
+ if (!hasKey(key)) {
165
+ addKey(key);
166
+ try {
167
+ const result = await Promise.resolve(fnc());
168
+ coalesce({ key, result });
169
+ return result;
170
+ } catch (error) {
171
+ coalesce({ key, error });
172
+ throw error;
173
+ }
174
+ }
175
+ return enqueue(key);
176
+ }
177
+
178
+ // src/hash.ts
179
+ var crypto = __toESM(require("crypto"), 1);
180
+ var HashAlgorithm = /* @__PURE__ */ ((HashAlgorithm2) => {
181
+ HashAlgorithm2["SHA256"] = "sha256";
182
+ HashAlgorithm2["SHA512"] = "sha512";
183
+ HashAlgorithm2["MD5"] = "md5";
184
+ HashAlgorithm2["DJB2"] = "djb2";
185
+ return HashAlgorithm2;
186
+ })(HashAlgorithm || {});
187
+ function hash(object, options = {
188
+ algorithm: "sha256" /* SHA256 */,
189
+ serialize: JSON.stringify
190
+ }) {
191
+ if (!options?.algorithm) {
192
+ options.algorithm = "sha256" /* SHA256 */;
193
+ }
194
+ if (!options?.serialize) {
195
+ options.serialize = JSON.stringify;
196
+ }
197
+ const objectString = options.serialize(object);
198
+ if (options?.algorithm === "djb2" /* DJB2 */) {
199
+ return djb2Hash(objectString);
200
+ }
201
+ if (!crypto.getHashes().includes(options.algorithm)) {
202
+ throw new Error(`Unsupported hash algorithm: '${options?.algorithm}'`);
203
+ }
204
+ const hasher = crypto.createHash(options.algorithm);
205
+ hasher.update(objectString);
206
+ return hasher.digest("hex");
207
+ }
208
+ function hashToNumber(object, options = {
209
+ min: 0,
210
+ max: 10,
211
+ algorithm: "sha256" /* SHA256 */,
212
+ serialize: JSON.stringify
213
+ }) {
214
+ const min = options?.min ?? 0;
215
+ const max = options?.max ?? 10;
216
+ if (min >= max) {
217
+ throw new Error(
218
+ `Invalid range: min (${min}) must be less than max (${max})`
219
+ );
220
+ }
221
+ if (!options?.algorithm) {
222
+ options.algorithm = "sha256" /* SHA256 */;
223
+ }
224
+ if (!options?.serialize) {
225
+ options.serialize = JSON.stringify;
226
+ }
227
+ const hashResult = hash(object, options);
228
+ const hashNumber = Number.parseInt(hashResult, 16);
229
+ const range = max - min + 1;
230
+ const result = min + hashNumber % range;
231
+ if (result < min) {
232
+ return min;
233
+ }
234
+ if (result > max) {
235
+ return max;
236
+ }
237
+ return result;
238
+ }
239
+ function djb2Hash(string_) {
240
+ let hash2 = 5381;
241
+ for (let i = 0; i < string_.length; i++) {
242
+ hash2 = hash2 * 33 ^ string_.charCodeAt(i);
243
+ }
244
+ return hash2.toString();
245
+ }
246
+
247
+ // src/is-keyv-instance.ts
248
+ var import_keyv = require("keyv");
249
+ function isKeyvInstance(keyv) {
250
+ if (keyv === null || keyv === void 0) {
251
+ return false;
252
+ }
253
+ if (keyv instanceof import_keyv.Keyv) {
254
+ return true;
255
+ }
256
+ const keyvMethods = [
257
+ "generateIterator",
258
+ "get",
259
+ "getMany",
260
+ "set",
261
+ "setMany",
262
+ "delete",
263
+ "deleteMany",
264
+ "has",
265
+ "hasMany",
266
+ "clear",
267
+ "disconnect",
268
+ "serialize",
269
+ "deserialize"
270
+ ];
271
+ return keyvMethods.every((method) => typeof keyv[method] === "function");
272
+ }
273
+
274
+ // src/is-object.ts
275
+ function isObject(value) {
276
+ return value !== null && typeof value === "object" && !Array.isArray(value);
277
+ }
278
+
279
+ // src/less-than.ts
280
+ function lessThan(number1, number2) {
281
+ return typeof number1 === "number" && typeof number2 === "number" ? number1 < number2 : false;
282
+ }
283
+
284
+ // src/memoize.ts
285
+ function wrapSync(function_, options) {
286
+ const { ttl, keyPrefix, cache, serialize } = options;
287
+ return (...arguments_) => {
288
+ let cacheKey = createWrapKey(function_, arguments_, {
289
+ keyPrefix,
290
+ serialize
291
+ });
292
+ if (options.createKey) {
293
+ cacheKey = options.createKey(function_, arguments_, options);
294
+ }
295
+ let value = cache.get(cacheKey);
296
+ if (value === void 0) {
297
+ try {
298
+ value = function_(...arguments_);
299
+ cache.set(cacheKey, value, ttl);
300
+ } catch (error) {
301
+ cache.emit("error", error);
302
+ if (options.cacheErrors) {
303
+ cache.set(cacheKey, error, ttl);
304
+ }
305
+ }
306
+ }
307
+ return value;
308
+ };
309
+ }
310
+ async function getOrSet(key, function_, options) {
311
+ const keyString = typeof key === "function" ? key(options) : key;
312
+ let value = await options.cache.get(keyString);
313
+ if (value === void 0) {
314
+ const cacheId = options.cacheId ?? "default";
315
+ const coalesceKey = `${cacheId}::${keyString}`;
316
+ value = await coalesceAsync(coalesceKey, async () => {
317
+ try {
318
+ const result = await function_();
319
+ await options.cache.set(keyString, result, options.ttl);
320
+ return result;
321
+ } catch (error) {
322
+ options.cache.emit("error", error);
323
+ if (options.cacheErrors) {
324
+ await options.cache.set(keyString, error, options.ttl);
325
+ }
326
+ if (options.throwErrors) {
327
+ throw error;
328
+ }
329
+ }
330
+ });
331
+ }
332
+ return value;
333
+ }
334
+ function wrap(function_, options) {
335
+ const { keyPrefix, serialize } = options;
336
+ return async (...arguments_) => {
337
+ let cacheKey = createWrapKey(function_, arguments_, {
338
+ keyPrefix,
339
+ serialize
340
+ });
341
+ if (options.createKey) {
342
+ cacheKey = options.createKey(function_, arguments_, options);
343
+ }
344
+ return getOrSet(
345
+ cacheKey,
346
+ async () => function_(...arguments_),
347
+ options
348
+ );
349
+ };
350
+ }
351
+ function createWrapKey(function_, arguments_, options) {
352
+ const { keyPrefix, serialize } = options || {};
353
+ if (!keyPrefix) {
354
+ return `${function_.name}::${hash(arguments_, { serialize })}`;
355
+ }
356
+ return `${keyPrefix}::${function_.name}::${hash(arguments_, { serialize })}`;
357
+ }
358
+
359
+ // src/run-if-fn.ts
360
+ function runIfFn(valueOrFunction, ...arguments_) {
361
+ return typeof valueOrFunction === "function" ? valueOrFunction(...arguments_) : valueOrFunction;
362
+ }
363
+
364
+ // src/sleep.ts
365
+ var sleep = async (ms) => new Promise((resolve) => setTimeout(resolve, ms));
366
+
367
+ // src/stats.ts
368
+ var Stats = class {
369
+ _hits = 0;
370
+ _misses = 0;
371
+ _gets = 0;
372
+ _sets = 0;
373
+ _deletes = 0;
374
+ _clears = 0;
375
+ _vsize = 0;
376
+ _ksize = 0;
377
+ _count = 0;
378
+ _enabled = false;
379
+ constructor(options) {
380
+ if (options?.enabled) {
381
+ this._enabled = options.enabled;
382
+ }
383
+ }
384
+ /**
385
+ * @returns {boolean} - Whether the stats are enabled
386
+ */
387
+ get enabled() {
388
+ return this._enabled;
389
+ }
390
+ /**
391
+ * @param {boolean} enabled - Whether to enable the stats
392
+ */
393
+ set enabled(enabled) {
394
+ this._enabled = enabled;
395
+ }
396
+ /**
397
+ * @returns {number} - The number of hits
398
+ * @readonly
399
+ */
400
+ get hits() {
401
+ return this._hits;
402
+ }
403
+ /**
404
+ * @returns {number} - The number of misses
405
+ * @readonly
406
+ */
407
+ get misses() {
408
+ return this._misses;
409
+ }
410
+ /**
411
+ * @returns {number} - The number of gets
412
+ * @readonly
413
+ */
414
+ get gets() {
415
+ return this._gets;
416
+ }
417
+ /**
418
+ * @returns {number} - The number of sets
419
+ * @readonly
420
+ */
421
+ get sets() {
422
+ return this._sets;
423
+ }
424
+ /**
425
+ * @returns {number} - The number of deletes
426
+ * @readonly
427
+ */
428
+ get deletes() {
429
+ return this._deletes;
430
+ }
431
+ /**
432
+ * @returns {number} - The number of clears
433
+ * @readonly
434
+ */
435
+ get clears() {
436
+ return this._clears;
437
+ }
438
+ /**
439
+ * @returns {number} - The vsize (value size) of the cache instance
440
+ * @readonly
441
+ */
442
+ get vsize() {
443
+ return this._vsize;
444
+ }
445
+ /**
446
+ * @returns {number} - The ksize (key size) of the cache instance
447
+ * @readonly
448
+ */
449
+ get ksize() {
450
+ return this._ksize;
451
+ }
452
+ /**
453
+ * @returns {number} - The count of the cache instance
454
+ * @readonly
455
+ */
456
+ get count() {
457
+ return this._count;
458
+ }
459
+ incrementHits() {
460
+ if (!this._enabled) {
461
+ return;
462
+ }
463
+ this._hits++;
464
+ }
465
+ incrementMisses() {
466
+ if (!this._enabled) {
467
+ return;
468
+ }
469
+ this._misses++;
470
+ }
471
+ incrementGets() {
472
+ if (!this._enabled) {
473
+ return;
474
+ }
475
+ this._gets++;
476
+ }
477
+ incrementSets() {
478
+ if (!this._enabled) {
479
+ return;
480
+ }
481
+ this._sets++;
482
+ }
483
+ incrementDeletes() {
484
+ if (!this._enabled) {
485
+ return;
486
+ }
487
+ this._deletes++;
488
+ }
489
+ incrementClears() {
490
+ if (!this._enabled) {
491
+ return;
492
+ }
493
+ this._clears++;
494
+ }
495
+ incrementVSize(value) {
496
+ if (!this._enabled) {
497
+ return;
498
+ }
499
+ this._vsize += this.roughSizeOfObject(value);
500
+ }
501
+ decreaseVSize(value) {
502
+ if (!this._enabled) {
503
+ return;
504
+ }
505
+ this._vsize -= this.roughSizeOfObject(value);
506
+ }
507
+ incrementKSize(key) {
508
+ if (!this._enabled) {
509
+ return;
510
+ }
511
+ this._ksize += this.roughSizeOfString(key);
512
+ }
513
+ decreaseKSize(key) {
514
+ if (!this._enabled) {
515
+ return;
516
+ }
517
+ this._ksize -= this.roughSizeOfString(key);
518
+ }
519
+ incrementCount() {
520
+ if (!this._enabled) {
521
+ return;
522
+ }
523
+ this._count++;
524
+ }
525
+ decreaseCount() {
526
+ if (!this._enabled) {
527
+ return;
528
+ }
529
+ this._count--;
530
+ }
531
+ setCount(count) {
532
+ if (!this._enabled) {
533
+ return;
534
+ }
535
+ this._count = count;
536
+ }
537
+ roughSizeOfString(value) {
538
+ return value.length * 2;
539
+ }
540
+ roughSizeOfObject(object) {
541
+ const objectList = [];
542
+ const stack = [object];
543
+ let bytes = 0;
544
+ while (stack.length > 0) {
545
+ const value = stack.pop();
546
+ if (typeof value === "boolean") {
547
+ bytes += 4;
548
+ } else if (typeof value === "string") {
549
+ bytes += value.length * 2;
550
+ } else if (typeof value === "number") {
551
+ bytes += 8;
552
+ } else {
553
+ if (value === null || value === void 0) {
554
+ bytes += 4;
555
+ continue;
556
+ }
557
+ if (objectList.includes(value)) {
558
+ continue;
559
+ }
560
+ objectList.push(value);
561
+ for (const key in value) {
562
+ bytes += key.length * 2;
563
+ stack.push(value[key]);
564
+ }
565
+ }
566
+ }
567
+ return bytes;
568
+ }
569
+ reset() {
570
+ this._hits = 0;
571
+ this._misses = 0;
572
+ this._gets = 0;
573
+ this._sets = 0;
574
+ this._deletes = 0;
575
+ this._clears = 0;
576
+ this._vsize = 0;
577
+ this._ksize = 0;
578
+ this._count = 0;
579
+ }
580
+ resetStoreValues() {
581
+ this._vsize = 0;
582
+ this._ksize = 0;
583
+ this._count = 0;
584
+ }
585
+ };
586
+
587
+ // src/ttl.ts
588
+ function getTtlFromExpires(expires) {
589
+ if (expires === void 0 || expires === null) {
590
+ return void 0;
591
+ }
592
+ const now = Date.now();
593
+ if (expires < now) {
594
+ return void 0;
595
+ }
596
+ return expires - now;
597
+ }
598
+ function getCascadingTtl(cacheableTtl, primaryTtl, secondaryTtl) {
599
+ return secondaryTtl ?? primaryTtl ?? shorthandToMilliseconds(cacheableTtl);
600
+ }
601
+ function calculateTtlFromExpiration(ttl, expires) {
602
+ const ttlFromExpires = getTtlFromExpires(expires);
603
+ const expiresFromTtl = ttl ? Date.now() + ttl : void 0;
604
+ if (ttlFromExpires === void 0) {
605
+ return ttl;
606
+ }
607
+ if (expiresFromTtl === void 0) {
608
+ return ttlFromExpires;
609
+ }
610
+ if (expires && expires > expiresFromTtl) {
611
+ return ttl;
612
+ }
613
+ return ttlFromExpires;
614
+ }
615
+ // Annotate the CommonJS export names for ESM import in node:
616
+ 0 && (module.exports = {
617
+ HashAlgorithm,
618
+ Stats,
619
+ calculateTtlFromExpiration,
620
+ coalesceAsync,
621
+ createWrapKey,
622
+ getCascadingTtl,
623
+ getOrSet,
624
+ getTtlFromExpires,
625
+ hash,
626
+ hashToNumber,
627
+ isKeyvInstance,
628
+ isObject,
629
+ lessThan,
630
+ runIfFn,
631
+ shorthandToMilliseconds,
632
+ shorthandToTime,
633
+ sleep,
634
+ wrap,
635
+ wrapSync
636
+ });
637
+ /* v8 ignore next -- @preserve */
package/dist/index.d.cts CHANGED
@@ -94,6 +94,57 @@ declare function isObject<T = Record<string, unknown>>(value: unknown): value is
94
94
 
95
95
  declare function lessThan(number1?: number, number2?: number): boolean;
96
96
 
97
+ type CacheInstance = {
98
+ get: (key: string) => Promise<any | undefined>;
99
+ has: (key: string) => Promise<boolean>;
100
+ set: (key: string, value: any, ttl?: number | string) => Promise<void>;
101
+ on: (event: string, listener: (...args: any[]) => void) => void;
102
+ emit: (event: string, ...args: any[]) => boolean;
103
+ };
104
+ type CacheSyncInstance = {
105
+ get: (key: string) => any | undefined;
106
+ has: (key: string) => boolean;
107
+ set: (key: string, value: any, ttl?: number | string) => void;
108
+ on: (event: string, listener: (...args: any[]) => void) => void;
109
+ emit: (event: string, ...args: any[]) => boolean;
110
+ };
111
+ type GetOrSetKey = string | ((options?: GetOrSetOptions) => string);
112
+ type GetOrSetFunctionOptions = {
113
+ ttl?: number | string;
114
+ cacheErrors?: boolean;
115
+ throwErrors?: boolean;
116
+ };
117
+ type GetOrSetOptions = GetOrSetFunctionOptions & {
118
+ cacheId?: string;
119
+ cache: CacheInstance;
120
+ };
121
+ type CreateWrapKey = (function_: AnyFunction, arguments_: any[], options?: WrapFunctionOptions) => string;
122
+ type WrapFunctionOptions = {
123
+ ttl?: number | string;
124
+ keyPrefix?: string;
125
+ createKey?: CreateWrapKey;
126
+ cacheErrors?: boolean;
127
+ cacheId?: string;
128
+ serialize?: (object: any) => string;
129
+ };
130
+ type WrapOptions = WrapFunctionOptions & {
131
+ cache: CacheInstance;
132
+ serialize?: (object: any) => string;
133
+ };
134
+ type WrapSyncOptions = WrapFunctionOptions & {
135
+ cache: CacheSyncInstance;
136
+ serialize?: (object: any) => string;
137
+ };
138
+ type AnyFunction = (...arguments_: any[]) => any;
139
+ declare function wrapSync<T>(function_: AnyFunction, options: WrapSyncOptions): AnyFunction;
140
+ declare function getOrSet<T>(key: GetOrSetKey, function_: () => Promise<T>, options: GetOrSetOptions): Promise<T | undefined>;
141
+ declare function wrap<T>(function_: AnyFunction, options: WrapOptions): AnyFunction;
142
+ type CreateWrapKeyOptions = {
143
+ keyPrefix?: string;
144
+ serialize?: (object: any) => string;
145
+ };
146
+ declare function createWrapKey(function_: AnyFunction, arguments_: any[], options?: CreateWrapKeyOptions): string;
147
+
97
148
  type Function_<P, T> = (...arguments_: P[]) => T;
98
149
  declare function runIfFn<T, P>(valueOrFunction: T | Function_<P, T>, ...arguments_: P[]): T;
99
150
 
@@ -209,4 +260,4 @@ declare function getCascadingTtl(cacheableTtl?: number | string, primaryTtl?: nu
209
260
  */
210
261
  declare function calculateTtlFromExpiration(ttl: number | undefined, expires: number | undefined): number | undefined;
211
262
 
212
- export { type CacheableItem, type CacheableStoreItem, HashAlgorithm, Stats, type StatsOptions, calculateTtlFromExpiration, coalesceAsync, getCascadingTtl, getTtlFromExpires, hash, hashToNumber, isKeyvInstance, isObject, lessThan, runIfFn, shorthandToMilliseconds, shorthandToTime, sleep };
263
+ export { type AnyFunction, type CacheInstance, type CacheSyncInstance, type CacheableItem, type CacheableStoreItem, type CreateWrapKey, type CreateWrapKeyOptions, type GetOrSetFunctionOptions, type GetOrSetKey, type GetOrSetOptions, HashAlgorithm, Stats, type StatsOptions, type WrapFunctionOptions, type WrapOptions, type WrapSyncOptions, calculateTtlFromExpiration, coalesceAsync, createWrapKey, getCascadingTtl, getOrSet, getTtlFromExpires, hash, hashToNumber, isKeyvInstance, isObject, lessThan, runIfFn, shorthandToMilliseconds, shorthandToTime, sleep, wrap, wrapSync };