@cacheable/utils 1.1.0 → 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/README.md CHANGED
@@ -26,6 +26,9 @@
26
26
  * [Sleep Helper](#sleep-helper)
27
27
  * [Stats Helpers](#stats-helpers)
28
28
  * [Time to Live (TTL) Helpers](#time-to-live-ttl-helpers)
29
+ * [Run if Function Helper](#run-if-function-helper)
30
+ * [Less Than Helper](#less-than-helper)
31
+ * [Is Object Helper](#is-object-helper)
29
32
  * [How to Contribute](#how-to-contribute)
30
33
  * [License and Copyright](#license-and-copyright)
31
34
 
@@ -195,6 +198,143 @@ const secondaryTtl = 1000 * 60; // 1 minute
195
198
  const ttl = getCascadingTtl(cacheableTtl, primaryTtl, secondaryTtl);
196
199
  ```
197
200
 
201
+ # Run if Function Helper
202
+
203
+ The `runIfFn` utility function provides a convenient way to conditionally execute functions or return values based on whether the input is a function or not. This pattern is commonly used in UI libraries and configuration systems where values can be either static or computed.
204
+
205
+ ```typescript
206
+ import { runIfFn } from '@cacheable/utils';
207
+
208
+ // Static value - returns the value as-is
209
+ const staticValue = runIfFn('hello world');
210
+ console.log(staticValue); // 'hello world'
211
+
212
+ // Function with no arguments - executes the function
213
+ const dynamicValue = runIfFn(() => new Date().toISOString());
214
+ console.log(dynamicValue); // Current timestamp
215
+
216
+ // Function with arguments - executes with provided arguments
217
+ const sum = runIfFn((a: number, b: number) => a + b, 5, 10);
218
+ console.log(sum); // 15
219
+
220
+ // Complex example with conditional logic
221
+ const getConfig = (isDevelopment: boolean) => ({
222
+ apiUrl: isDevelopment ? 'http://localhost:3000' : 'https://api.example.com',
223
+ timeout: isDevelopment ? 5000 : 30000
224
+ });
225
+
226
+ const config = runIfFn(getConfig, true);
227
+ console.log(config); // { apiUrl: 'http://localhost:3000', timeout: 5000 }
228
+ ```
229
+
230
+ # Less Than Helper
231
+
232
+ The `lessThan` utility function provides a safe way to compare two values and determine if the first value is less than the second. It only performs the comparison if both values are valid numbers, returning `false` for any non-number inputs.
233
+
234
+ ```typescript
235
+ import { lessThan } from '@cacheable/utils';
236
+
237
+ // Basic number comparisons
238
+ console.log(lessThan(1, 2)); // true
239
+ console.log(lessThan(2, 1)); // false
240
+ console.log(lessThan(1, 1)); // false
241
+
242
+ // Works with negative numbers
243
+ console.log(lessThan(-1, 0)); // true
244
+ console.log(lessThan(-2, -1)); // true
245
+
246
+ // Works with decimal numbers
247
+ console.log(lessThan(1.5, 2.5)); // true
248
+ console.log(lessThan(2.7, 2.7)); // false
249
+
250
+ // Safe handling of non-number values
251
+ console.log(lessThan("1", 2)); // false
252
+ console.log(lessThan(1, "2")); // false
253
+ console.log(lessThan(null, 1)); // false
254
+ console.log(lessThan(undefined, 1)); // false
255
+ console.log(lessThan(NaN, 1)); // false
256
+
257
+ // Useful in filtering and sorting operations
258
+ const numbers = [5, 2, 8, 1, 9];
259
+ const lessThanFive = numbers.filter(n => lessThan(n, 5));
260
+ console.log(lessThanFive); // [2, 1]
261
+
262
+ // Safe comparison in conditional logic
263
+ function processValue(a?: number, b?: number) {
264
+ if (lessThan(a, b)) {
265
+ return `${a} is less than ${b}`;
266
+ }
267
+ return 'Invalid comparison or a >= b';
268
+ }
269
+ ```
270
+
271
+ This utility is particularly useful when dealing with potentially undefined or invalid numeric values, ensuring type safety in comparison operations.
272
+
273
+ # Is Object Helper
274
+
275
+ The `isObject` utility function provides a type-safe way to determine if a value is a plain object. It returns `true` for objects but `false` for arrays, `null`, functions, and primitive types. This function also serves as a TypeScript type guard.
276
+
277
+ ```typescript
278
+ import { isObject } from '@cacheable/utils';
279
+
280
+ // Basic object detection
281
+ console.log(isObject({})); // true
282
+ console.log(isObject({ name: 'John', age: 30 })); // true
283
+ console.log(isObject(Object.create(null))); // true
284
+
285
+ // Arrays are not considered objects
286
+ console.log(isObject([])); // false
287
+ console.log(isObject([1, 2, 3])); // false
288
+
289
+ // null is not considered an object (despite typeof null === 'object')
290
+ console.log(isObject(null)); // false
291
+
292
+ // Primitive types return false
293
+ console.log(isObject('string')); // false
294
+ console.log(isObject(123)); // false
295
+ console.log(isObject(true)); // false
296
+ console.log(isObject(undefined)); // false
297
+
298
+ // Functions return false
299
+ console.log(isObject(() => {})); // false
300
+ console.log(isObject(Date)); // false
301
+
302
+ // Built-in object types return true
303
+ console.log(isObject(new Date())); // true
304
+ console.log(isObject(/regex/)); // true
305
+ console.log(isObject(new Error('test'))); // true
306
+ console.log(isObject(new Map())); // true
307
+
308
+ // TypeScript type guard usage
309
+ function processValue(value: unknown) {
310
+ if (isObject<{ name: string; age: number }>(value)) {
311
+ // TypeScript now knows value is an object with name and age properties
312
+ console.log(`Name: ${value.name}, Age: ${value.age}`);
313
+ }
314
+ }
315
+
316
+ // Useful for configuration validation
317
+ function validateConfig(config: unknown) {
318
+ if (!isObject(config)) {
319
+ throw new Error('Configuration must be an object');
320
+ }
321
+
322
+ // Safe to access object properties
323
+ return config;
324
+ }
325
+
326
+ // Filtering arrays for objects only
327
+ const mixedArray = [1, 'string', {}, [], null, { valid: true }];
328
+ const objectsOnly = mixedArray.filter(isObject);
329
+ console.log(objectsOnly); // [{}', { valid: true }]
330
+ ```
331
+
332
+ This utility is particularly useful for:
333
+ - **Type validation** - Ensuring values are objects before accessing properties
334
+ - **TypeScript type guarding** - Narrowing types in conditional blocks
335
+ - **Configuration parsing** - Validating that configuration values are objects
336
+ - **Data filtering** - Separating objects from other data types
337
+
198
338
  # How to Contribute
199
339
 
200
340
  You can contribute by forking the repo and submitting a pull request. Please make sure to add tests and update the documentation. To learn more about how to contribute go to our main README [https://github.com/jaredwray/cacheable](https://github.com/jaredwray/cacheable). This will talk about how to `Open a Pull Request`, `Ask a Question`, or `Post an Issue`.
package/dist/index.cjs CHANGED
@@ -1,470 +1 @@
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
- getCascadingTtl: () => getCascadingTtl,
38
- getTtlFromExpires: () => getTtlFromExpires,
39
- hash: () => hash,
40
- hashToNumber: () => hashToNumber,
41
- shorthandToMilliseconds: () => shorthandToMilliseconds,
42
- shorthandToTime: () => shorthandToTime,
43
- sleep: () => sleep
44
- });
45
- module.exports = __toCommonJS(index_exports);
46
-
47
- // src/coalesce-async.ts
48
- var callbacks = /* @__PURE__ */ new Map();
49
- function hasKey(key) {
50
- return callbacks.has(key);
51
- }
52
- function addKey(key) {
53
- callbacks.set(key, []);
54
- }
55
- function removeKey(key) {
56
- callbacks.delete(key);
57
- }
58
- function addCallbackToKey(key, callback) {
59
- const stash = getCallbacksByKey(key);
60
- stash.push(callback);
61
- callbacks.set(key, stash);
62
- }
63
- function getCallbacksByKey(key) {
64
- return callbacks.get(key) ?? [];
65
- }
66
- async function enqueue(key) {
67
- return new Promise((resolve, reject) => {
68
- const callback = { resolve, reject };
69
- addCallbackToKey(key, callback);
70
- });
71
- }
72
- function dequeue(key) {
73
- const stash = getCallbacksByKey(key);
74
- removeKey(key);
75
- return stash;
76
- }
77
- function coalesce(options) {
78
- const { key, error, result } = options;
79
- for (const callback of dequeue(key)) {
80
- if (error) {
81
- callback.reject(error);
82
- } else {
83
- callback.resolve(result);
84
- }
85
- }
86
- }
87
- async function coalesceAsync(key, fnc) {
88
- if (!hasKey(key)) {
89
- addKey(key);
90
- try {
91
- const result = await Promise.resolve(fnc());
92
- coalesce({ key, result });
93
- return result;
94
- } catch (error) {
95
- coalesce({ key, error });
96
- throw error;
97
- }
98
- }
99
- return enqueue(key);
100
- }
101
-
102
- // src/hash.ts
103
- var crypto = __toESM(require("crypto"), 1);
104
- var HashAlgorithm = /* @__PURE__ */ ((HashAlgorithm2) => {
105
- HashAlgorithm2["SHA256"] = "sha256";
106
- HashAlgorithm2["SHA512"] = "sha512";
107
- HashAlgorithm2["MD5"] = "md5";
108
- HashAlgorithm2["DJB2"] = "djb2";
109
- return HashAlgorithm2;
110
- })(HashAlgorithm || {});
111
- function hash(object, algorithm = "sha256" /* SHA256 */) {
112
- const objectString = JSON.stringify(object);
113
- if (algorithm === "djb2" /* DJB2 */) {
114
- return djb2Hash(objectString);
115
- }
116
- if (!crypto.getHashes().includes(algorithm)) {
117
- throw new Error(`Unsupported hash algorithm: '${algorithm}'`);
118
- }
119
- const hasher = crypto.createHash(algorithm);
120
- hasher.update(objectString);
121
- return hasher.digest("hex");
122
- }
123
- function hashToNumber(object, min = 0, max = 10, algorithm = "sha256" /* SHA256 */) {
124
- const hashResult = hash(object, algorithm);
125
- const hashNumber = Number.parseInt(hashResult, 16);
126
- const range = max - min + 1;
127
- const result = min + hashNumber % range;
128
- if (result < min) {
129
- return min;
130
- }
131
- if (result > max) {
132
- return max;
133
- }
134
- return result;
135
- }
136
- function djb2Hash(string_) {
137
- let hash2 = 5381;
138
- for (let i = 0; i < string_.length; i++) {
139
- hash2 = hash2 * 33 ^ string_.charCodeAt(i);
140
- }
141
- return hash2.toString();
142
- }
143
-
144
- // src/shorthand-time.ts
145
- var shorthandToMilliseconds = (shorthand) => {
146
- let milliseconds;
147
- if (shorthand === void 0) {
148
- return void 0;
149
- }
150
- if (typeof shorthand === "number") {
151
- milliseconds = shorthand;
152
- } else if (typeof shorthand === "string") {
153
- shorthand = shorthand.trim();
154
- if (Number.isNaN(Number(shorthand))) {
155
- const match = /^([\d.]+)\s*(ms|s|m|h|hr|d)$/i.exec(shorthand);
156
- if (!match) {
157
- throw new Error(`Unsupported time format: "${shorthand}". Use 'ms', 's', 'm', 'h', 'hr', or 'd'.`);
158
- }
159
- const [, value, unit] = match;
160
- const numericValue = Number.parseFloat(value);
161
- const unitLower = unit.toLowerCase();
162
- switch (unitLower) {
163
- case "ms": {
164
- milliseconds = numericValue;
165
- break;
166
- }
167
- case "s": {
168
- milliseconds = numericValue * 1e3;
169
- break;
170
- }
171
- case "m": {
172
- milliseconds = numericValue * 1e3 * 60;
173
- break;
174
- }
175
- case "h": {
176
- milliseconds = numericValue * 1e3 * 60 * 60;
177
- break;
178
- }
179
- case "hr": {
180
- milliseconds = numericValue * 1e3 * 60 * 60;
181
- break;
182
- }
183
- case "d": {
184
- milliseconds = numericValue * 1e3 * 60 * 60 * 24;
185
- break;
186
- }
187
- /* c8 ignore next 3 */
188
- default: {
189
- milliseconds = Number(shorthand);
190
- }
191
- }
192
- } else {
193
- milliseconds = Number(shorthand);
194
- }
195
- } else {
196
- throw new TypeError("Time must be a string or a number.");
197
- }
198
- return milliseconds;
199
- };
200
- var shorthandToTime = (shorthand, fromDate) => {
201
- fromDate ??= /* @__PURE__ */ new Date();
202
- const milliseconds = shorthandToMilliseconds(shorthand);
203
- if (milliseconds === void 0) {
204
- return fromDate.getTime();
205
- }
206
- return fromDate.getTime() + milliseconds;
207
- };
208
-
209
- // src/sleep.ts
210
- var sleep = async (ms) => new Promise((resolve) => setTimeout(resolve, ms));
211
-
212
- // src/stats.ts
213
- var Stats = class {
214
- _hits = 0;
215
- _misses = 0;
216
- _gets = 0;
217
- _sets = 0;
218
- _deletes = 0;
219
- _clears = 0;
220
- _vsize = 0;
221
- _ksize = 0;
222
- _count = 0;
223
- _enabled = false;
224
- constructor(options) {
225
- if (options?.enabled) {
226
- this._enabled = options.enabled;
227
- }
228
- }
229
- /**
230
- * @returns {boolean} - Whether the stats are enabled
231
- */
232
- get enabled() {
233
- return this._enabled;
234
- }
235
- /**
236
- * @param {boolean} enabled - Whether to enable the stats
237
- */
238
- set enabled(enabled) {
239
- this._enabled = enabled;
240
- }
241
- /**
242
- * @returns {number} - The number of hits
243
- * @readonly
244
- */
245
- get hits() {
246
- return this._hits;
247
- }
248
- /**
249
- * @returns {number} - The number of misses
250
- * @readonly
251
- */
252
- get misses() {
253
- return this._misses;
254
- }
255
- /**
256
- * @returns {number} - The number of gets
257
- * @readonly
258
- */
259
- get gets() {
260
- return this._gets;
261
- }
262
- /**
263
- * @returns {number} - The number of sets
264
- * @readonly
265
- */
266
- get sets() {
267
- return this._sets;
268
- }
269
- /**
270
- * @returns {number} - The number of deletes
271
- * @readonly
272
- */
273
- get deletes() {
274
- return this._deletes;
275
- }
276
- /**
277
- * @returns {number} - The number of clears
278
- * @readonly
279
- */
280
- get clears() {
281
- return this._clears;
282
- }
283
- /**
284
- * @returns {number} - The vsize (value size) of the cache instance
285
- * @readonly
286
- */
287
- get vsize() {
288
- return this._vsize;
289
- }
290
- /**
291
- * @returns {number} - The ksize (key size) of the cache instance
292
- * @readonly
293
- */
294
- get ksize() {
295
- return this._ksize;
296
- }
297
- /**
298
- * @returns {number} - The count of the cache instance
299
- * @readonly
300
- */
301
- get count() {
302
- return this._count;
303
- }
304
- incrementHits() {
305
- if (!this._enabled) {
306
- return;
307
- }
308
- this._hits++;
309
- }
310
- incrementMisses() {
311
- if (!this._enabled) {
312
- return;
313
- }
314
- this._misses++;
315
- }
316
- incrementGets() {
317
- if (!this._enabled) {
318
- return;
319
- }
320
- this._gets++;
321
- }
322
- incrementSets() {
323
- if (!this._enabled) {
324
- return;
325
- }
326
- this._sets++;
327
- }
328
- incrementDeletes() {
329
- if (!this._enabled) {
330
- return;
331
- }
332
- this._deletes++;
333
- }
334
- incrementClears() {
335
- if (!this._enabled) {
336
- return;
337
- }
338
- this._clears++;
339
- }
340
- // eslint-disable-next-line @typescript-eslint/naming-convention
341
- incrementVSize(value) {
342
- if (!this._enabled) {
343
- return;
344
- }
345
- this._vsize += this.roughSizeOfObject(value);
346
- }
347
- // eslint-disable-next-line @typescript-eslint/naming-convention
348
- decreaseVSize(value) {
349
- if (!this._enabled) {
350
- return;
351
- }
352
- this._vsize -= this.roughSizeOfObject(value);
353
- }
354
- // eslint-disable-next-line @typescript-eslint/naming-convention
355
- incrementKSize(key) {
356
- if (!this._enabled) {
357
- return;
358
- }
359
- this._ksize += this.roughSizeOfString(key);
360
- }
361
- // eslint-disable-next-line @typescript-eslint/naming-convention
362
- decreaseKSize(key) {
363
- if (!this._enabled) {
364
- return;
365
- }
366
- this._ksize -= this.roughSizeOfString(key);
367
- }
368
- incrementCount() {
369
- if (!this._enabled) {
370
- return;
371
- }
372
- this._count++;
373
- }
374
- decreaseCount() {
375
- if (!this._enabled) {
376
- return;
377
- }
378
- this._count--;
379
- }
380
- setCount(count) {
381
- if (!this._enabled) {
382
- return;
383
- }
384
- this._count = count;
385
- }
386
- roughSizeOfString(value) {
387
- return value.length * 2;
388
- }
389
- roughSizeOfObject(object) {
390
- const objectList = [];
391
- const stack = [object];
392
- let bytes = 0;
393
- while (stack.length > 0) {
394
- const value = stack.pop();
395
- if (typeof value === "boolean") {
396
- bytes += 4;
397
- } else if (typeof value === "string") {
398
- bytes += value.length * 2;
399
- } else if (typeof value === "number") {
400
- bytes += 8;
401
- } else if (typeof value === "object" && value !== null && !objectList.includes(value)) {
402
- objectList.push(value);
403
- for (const key in value) {
404
- bytes += key.length * 2;
405
- stack.push(value[key]);
406
- }
407
- }
408
- }
409
- return bytes;
410
- }
411
- reset() {
412
- this._hits = 0;
413
- this._misses = 0;
414
- this._gets = 0;
415
- this._sets = 0;
416
- this._deletes = 0;
417
- this._clears = 0;
418
- this._vsize = 0;
419
- this._ksize = 0;
420
- this._count = 0;
421
- }
422
- resetStoreValues() {
423
- this._vsize = 0;
424
- this._ksize = 0;
425
- this._count = 0;
426
- }
427
- };
428
-
429
- // src/ttl.ts
430
- function getTtlFromExpires(expires) {
431
- if (expires === void 0 || expires === null) {
432
- return void 0;
433
- }
434
- const now = Date.now();
435
- if (expires < now) {
436
- return void 0;
437
- }
438
- return expires - now;
439
- }
440
- function getCascadingTtl(cacheableTtl, primaryTtl, secondaryTtl) {
441
- return secondaryTtl ?? primaryTtl ?? shorthandToMilliseconds(cacheableTtl);
442
- }
443
- function calculateTtlFromExpiration(ttl, expires) {
444
- const ttlFromExpires = getTtlFromExpires(expires);
445
- const expiresFromTtl = ttl ? Date.now() + ttl : void 0;
446
- if (ttlFromExpires === void 0) {
447
- return ttl;
448
- }
449
- if (expiresFromTtl === void 0) {
450
- return ttlFromExpires;
451
- }
452
- if (expires > expiresFromTtl) {
453
- return ttl;
454
- }
455
- return ttlFromExpires;
456
- }
457
- // Annotate the CommonJS export names for ESM import in node:
458
- 0 && (module.exports = {
459
- HashAlgorithm,
460
- Stats,
461
- calculateTtlFromExpiration,
462
- coalesceAsync,
463
- getCascadingTtl,
464
- getTtlFromExpires,
465
- hash,
466
- hashToNumber,
467
- shorthandToMilliseconds,
468
- shorthandToTime,
469
- sleep
470
- });
1
+ "use strict";var P=Object.create;var l=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var N=Object.getOwnPropertyNames;var A=Object.getPrototypeOf,H=Object.prototype.hasOwnProperty;var j=(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 N(e))!H.call(t,n)&&n!==r&&l(t,n,{get:()=>e[n],enumerable:!(i=C(e,n))||i.enumerable});return t};var E=(t,e,r)=>(r=t!=null?P(A(t)):{},p(e||!t||!t.__esModule?l(r,"default",{value:t,enumerable:!0}):r,t)),F=t=>p(l({},"__esModule",{value:!0}),t);var V={};j(V,{HashAlgorithm:()=>b,Stats:()=>m,calculateTtlFromExpiration:()=>O,coalesceAsync:()=>y,getCascadingTtl:()=>w,getTtlFromExpires:()=>d,hash:()=>f,hashToNumber:()=>v,isObject:()=>x,lessThan:()=>z,runIfFn:()=>S,shorthandToMilliseconds:()=>u,shorthandToTime:()=>g,sleep:()=>k});module.exports=F(V);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 K(t){return a.has(t)}function D(t){a.set(t,[])}function I(t){a.delete(t)}function J(t,e){let r=T(t);r.push(e),a.set(t,r)}function T(t){return a.get(t)??[]}async function L(t){return new Promise((e,r)=>{J(t,{resolve:e,reject:r})})}function M(t){let e=T(t);return I(t),e}function _(t){let{key:e,error:r,result:i}=t;for(let n of M(e))r?n.reject(r):n.resolve(i)}async function y(t,e){if(!K(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 L(t)}var c=E(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 $(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 $(t){let e=5381;for(let r=0;r<t.length;r++)e=e*33^t.charCodeAt(r);return e.toString()}function x(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function z(t,e){return typeof t=="number"&&typeof e=="number"?t<e:!1}function S(t,...e){return typeof t=="function"?t(...e):t}var k=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 w(t,e,r){return r??e??u(t)}function O(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,isObject,lessThan,runIfFn,shorthandToMilliseconds,shorthandToTime,sleep});
package/dist/index.d.cts CHANGED
@@ -1,3 +1,22 @@
1
+ /**
2
+ * Converts a shorthand time string or number into milliseconds.
3
+ * The shorthand can be a string like '1s', '2m', '3h', '4d', or a number representing milliseconds.
4
+ * If the input is undefined, it returns undefined.
5
+ * If the input is a string that does not match the expected format, it throws an error.
6
+ * @param shorthand - A shorthand time string or number representing milliseconds.
7
+ * @returns The equivalent time in milliseconds or undefined.
8
+ */
9
+ declare const shorthandToMilliseconds: (shorthand?: string | number) => number | undefined;
10
+ /**
11
+ * Converts a shorthand time string or number into a timestamp.
12
+ * If the shorthand is undefined, it returns the current date's timestamp.
13
+ * If the shorthand is a valid time format, it adds that duration to the current date's timestamp.
14
+ * @param shorthand - A shorthand time string or number representing milliseconds.
15
+ * @param fromDate - An optional Date object to calculate from. Defaults to the current date if not provided.
16
+ * @returns The timestamp in milliseconds since epoch.
17
+ */
18
+ declare const shorthandToTime: (shorthand?: string | number, fromDate?: Date) => number;
19
+
1
20
  /**
2
21
  * CacheableItem
3
22
  * @typedef {Object} CacheableItem
@@ -38,12 +57,12 @@ type CacheableStoreItem = {
38
57
  */
39
58
  declare function coalesceAsync<T>(
40
59
  /**
41
- * Any identifier to group requests together.
42
- */
60
+ * Any identifier to group requests together.
61
+ */
43
62
  key: string,
44
63
  /**
45
- * The function to run.
46
- */
64
+ * The function to run.
65
+ */
47
66
  fnc: () => T | PromiseLike<T>): Promise<T>;
48
67
 
49
68
  declare enum HashAlgorithm {
@@ -52,33 +71,29 @@ declare enum HashAlgorithm {
52
71
  MD5 = "md5",
53
72
  DJB2 = "djb2"
54
73
  }
74
+ type HashOptions = {
75
+ algorithm?: HashAlgorithm;
76
+ serialize?: (object: any) => string;
77
+ };
78
+ type hashToNumberOptions = HashOptions & {
79
+ min?: number;
80
+ max?: number;
81
+ };
55
82
  /**
56
83
  * Hashes an object using the specified algorithm. The default algorithm is 'sha256'.
57
84
  * @param object The object to hash
58
- * @param algorithm The hash algorithm to use
85
+ * @param options The hash options to use
59
86
  * @returns {string} The hash of the object
60
87
  */
61
- declare function hash(object: any, algorithm?: HashAlgorithm): string;
62
- declare function hashToNumber(object: any, min?: number, max?: number, algorithm?: HashAlgorithm): number;
88
+ declare function hash(object: any, options?: HashOptions): string;
89
+ declare function hashToNumber(object: any, options?: hashToNumberOptions): number;
63
90
 
64
- /**
65
- * Converts a shorthand time string or number into milliseconds.
66
- * The shorthand can be a string like '1s', '2m', '3h', '4d', or a number representing milliseconds.
67
- * If the input is undefined, it returns undefined.
68
- * If the input is a string that does not match the expected format, it throws an error.
69
- * @param shorthand - A shorthand time string or number representing milliseconds.
70
- * @returns The equivalent time in milliseconds or undefined.
71
- */
72
- declare const shorthandToMilliseconds: (shorthand?: string | number) => number | undefined;
73
- /**
74
- * Converts a shorthand time string or number into a timestamp.
75
- * If the shorthand is undefined, it returns the current date's timestamp.
76
- * If the shorthand is a valid time format, it adds that duration to the current date's timestamp.
77
- * @param shorthand - A shorthand time string or number representing milliseconds.
78
- * @param fromDate - An optional Date object to calculate from. Defaults to the current date if not provided.
79
- * @returns The timestamp in milliseconds since epoch.
80
- */
81
- declare const shorthandToTime: (shorthand?: string | number, fromDate?: Date) => number;
91
+ declare function isObject<T = Record<string, unknown>>(value: unknown): value is T;
92
+
93
+ declare function lessThan(number1?: number, number2?: number): boolean;
94
+
95
+ type Function_<P, T> = (...arguments_: P[]) => T;
96
+ declare function runIfFn<T, P>(valueOrFunction: T | Function_<P, T>, ...arguments_: P[]): T;
82
97
 
83
98
  declare const sleep: (ms: number) => Promise<unknown>;
84
99
 
@@ -192,4 +207,4 @@ declare function getCascadingTtl(cacheableTtl?: number | string, primaryTtl?: nu
192
207
  */
193
208
  declare function calculateTtlFromExpiration(ttl: number | undefined, expires: number | undefined): number | undefined;
194
209
 
195
- export { type CacheableItem, type CacheableStoreItem, HashAlgorithm, Stats, type StatsOptions, calculateTtlFromExpiration, coalesceAsync, getCascadingTtl, getTtlFromExpires, hash, hashToNumber, shorthandToMilliseconds, shorthandToTime, sleep };
210
+ export { type CacheableItem, type CacheableStoreItem, HashAlgorithm, Stats, type StatsOptions, calculateTtlFromExpiration, coalesceAsync, getCascadingTtl, getTtlFromExpires, hash, hashToNumber, isObject, lessThan, runIfFn, shorthandToMilliseconds, shorthandToTime, sleep };
package/dist/index.d.ts CHANGED
@@ -1,3 +1,22 @@
1
+ /**
2
+ * Converts a shorthand time string or number into milliseconds.
3
+ * The shorthand can be a string like '1s', '2m', '3h', '4d', or a number representing milliseconds.
4
+ * If the input is undefined, it returns undefined.
5
+ * If the input is a string that does not match the expected format, it throws an error.
6
+ * @param shorthand - A shorthand time string or number representing milliseconds.
7
+ * @returns The equivalent time in milliseconds or undefined.
8
+ */
9
+ declare const shorthandToMilliseconds: (shorthand?: string | number) => number | undefined;
10
+ /**
11
+ * Converts a shorthand time string or number into a timestamp.
12
+ * If the shorthand is undefined, it returns the current date's timestamp.
13
+ * If the shorthand is a valid time format, it adds that duration to the current date's timestamp.
14
+ * @param shorthand - A shorthand time string or number representing milliseconds.
15
+ * @param fromDate - An optional Date object to calculate from. Defaults to the current date if not provided.
16
+ * @returns The timestamp in milliseconds since epoch.
17
+ */
18
+ declare const shorthandToTime: (shorthand?: string | number, fromDate?: Date) => number;
19
+
1
20
  /**
2
21
  * CacheableItem
3
22
  * @typedef {Object} CacheableItem
@@ -38,12 +57,12 @@ type CacheableStoreItem = {
38
57
  */
39
58
  declare function coalesceAsync<T>(
40
59
  /**
41
- * Any identifier to group requests together.
42
- */
60
+ * Any identifier to group requests together.
61
+ */
43
62
  key: string,
44
63
  /**
45
- * The function to run.
46
- */
64
+ * The function to run.
65
+ */
47
66
  fnc: () => T | PromiseLike<T>): Promise<T>;
48
67
 
49
68
  declare enum HashAlgorithm {
@@ -52,33 +71,29 @@ declare enum HashAlgorithm {
52
71
  MD5 = "md5",
53
72
  DJB2 = "djb2"
54
73
  }
74
+ type HashOptions = {
75
+ algorithm?: HashAlgorithm;
76
+ serialize?: (object: any) => string;
77
+ };
78
+ type hashToNumberOptions = HashOptions & {
79
+ min?: number;
80
+ max?: number;
81
+ };
55
82
  /**
56
83
  * Hashes an object using the specified algorithm. The default algorithm is 'sha256'.
57
84
  * @param object The object to hash
58
- * @param algorithm The hash algorithm to use
85
+ * @param options The hash options to use
59
86
  * @returns {string} The hash of the object
60
87
  */
61
- declare function hash(object: any, algorithm?: HashAlgorithm): string;
62
- declare function hashToNumber(object: any, min?: number, max?: number, algorithm?: HashAlgorithm): number;
88
+ declare function hash(object: any, options?: HashOptions): string;
89
+ declare function hashToNumber(object: any, options?: hashToNumberOptions): number;
63
90
 
64
- /**
65
- * Converts a shorthand time string or number into milliseconds.
66
- * The shorthand can be a string like '1s', '2m', '3h', '4d', or a number representing milliseconds.
67
- * If the input is undefined, it returns undefined.
68
- * If the input is a string that does not match the expected format, it throws an error.
69
- * @param shorthand - A shorthand time string or number representing milliseconds.
70
- * @returns The equivalent time in milliseconds or undefined.
71
- */
72
- declare const shorthandToMilliseconds: (shorthand?: string | number) => number | undefined;
73
- /**
74
- * Converts a shorthand time string or number into a timestamp.
75
- * If the shorthand is undefined, it returns the current date's timestamp.
76
- * If the shorthand is a valid time format, it adds that duration to the current date's timestamp.
77
- * @param shorthand - A shorthand time string or number representing milliseconds.
78
- * @param fromDate - An optional Date object to calculate from. Defaults to the current date if not provided.
79
- * @returns The timestamp in milliseconds since epoch.
80
- */
81
- declare const shorthandToTime: (shorthand?: string | number, fromDate?: Date) => number;
91
+ declare function isObject<T = Record<string, unknown>>(value: unknown): value is T;
92
+
93
+ declare function lessThan(number1?: number, number2?: number): boolean;
94
+
95
+ type Function_<P, T> = (...arguments_: P[]) => T;
96
+ declare function runIfFn<T, P>(valueOrFunction: T | Function_<P, T>, ...arguments_: P[]): T;
82
97
 
83
98
  declare const sleep: (ms: number) => Promise<unknown>;
84
99
 
@@ -192,4 +207,4 @@ declare function getCascadingTtl(cacheableTtl?: number | string, primaryTtl?: nu
192
207
  */
193
208
  declare function calculateTtlFromExpiration(ttl: number | undefined, expires: number | undefined): number | undefined;
194
209
 
195
- export { type CacheableItem, type CacheableStoreItem, HashAlgorithm, Stats, type StatsOptions, calculateTtlFromExpiration, coalesceAsync, getCascadingTtl, getTtlFromExpires, hash, hashToNumber, shorthandToMilliseconds, shorthandToTime, sleep };
210
+ export { type CacheableItem, type CacheableStoreItem, HashAlgorithm, Stats, type StatsOptions, calculateTtlFromExpiration, coalesceAsync, getCascadingTtl, getTtlFromExpires, hash, hashToNumber, isObject, lessThan, runIfFn, shorthandToMilliseconds, shorthandToTime, sleep };
package/dist/index.js CHANGED
@@ -1,423 +1 @@
1
- // src/coalesce-async.ts
2
- var callbacks = /* @__PURE__ */ new Map();
3
- function hasKey(key) {
4
- return callbacks.has(key);
5
- }
6
- function addKey(key) {
7
- callbacks.set(key, []);
8
- }
9
- function removeKey(key) {
10
- callbacks.delete(key);
11
- }
12
- function addCallbackToKey(key, callback) {
13
- const stash = getCallbacksByKey(key);
14
- stash.push(callback);
15
- callbacks.set(key, stash);
16
- }
17
- function getCallbacksByKey(key) {
18
- return callbacks.get(key) ?? [];
19
- }
20
- async function enqueue(key) {
21
- return new Promise((resolve, reject) => {
22
- const callback = { resolve, reject };
23
- addCallbackToKey(key, callback);
24
- });
25
- }
26
- function dequeue(key) {
27
- const stash = getCallbacksByKey(key);
28
- removeKey(key);
29
- return stash;
30
- }
31
- function coalesce(options) {
32
- const { key, error, result } = options;
33
- for (const callback of dequeue(key)) {
34
- if (error) {
35
- callback.reject(error);
36
- } else {
37
- callback.resolve(result);
38
- }
39
- }
40
- }
41
- async function coalesceAsync(key, fnc) {
42
- if (!hasKey(key)) {
43
- addKey(key);
44
- try {
45
- const result = await Promise.resolve(fnc());
46
- coalesce({ key, result });
47
- return result;
48
- } catch (error) {
49
- coalesce({ key, error });
50
- throw error;
51
- }
52
- }
53
- return enqueue(key);
54
- }
55
-
56
- // src/hash.ts
57
- import * as crypto from "crypto";
58
- var HashAlgorithm = /* @__PURE__ */ ((HashAlgorithm2) => {
59
- HashAlgorithm2["SHA256"] = "sha256";
60
- HashAlgorithm2["SHA512"] = "sha512";
61
- HashAlgorithm2["MD5"] = "md5";
62
- HashAlgorithm2["DJB2"] = "djb2";
63
- return HashAlgorithm2;
64
- })(HashAlgorithm || {});
65
- function hash(object, algorithm = "sha256" /* SHA256 */) {
66
- const objectString = JSON.stringify(object);
67
- if (algorithm === "djb2" /* DJB2 */) {
68
- return djb2Hash(objectString);
69
- }
70
- if (!crypto.getHashes().includes(algorithm)) {
71
- throw new Error(`Unsupported hash algorithm: '${algorithm}'`);
72
- }
73
- const hasher = crypto.createHash(algorithm);
74
- hasher.update(objectString);
75
- return hasher.digest("hex");
76
- }
77
- function hashToNumber(object, min = 0, max = 10, algorithm = "sha256" /* SHA256 */) {
78
- const hashResult = hash(object, algorithm);
79
- const hashNumber = Number.parseInt(hashResult, 16);
80
- const range = max - min + 1;
81
- const result = min + hashNumber % range;
82
- if (result < min) {
83
- return min;
84
- }
85
- if (result > max) {
86
- return max;
87
- }
88
- return result;
89
- }
90
- function djb2Hash(string_) {
91
- let hash2 = 5381;
92
- for (let i = 0; i < string_.length; i++) {
93
- hash2 = hash2 * 33 ^ string_.charCodeAt(i);
94
- }
95
- return hash2.toString();
96
- }
97
-
98
- // src/shorthand-time.ts
99
- var shorthandToMilliseconds = (shorthand) => {
100
- let milliseconds;
101
- if (shorthand === void 0) {
102
- return void 0;
103
- }
104
- if (typeof shorthand === "number") {
105
- milliseconds = shorthand;
106
- } else if (typeof shorthand === "string") {
107
- shorthand = shorthand.trim();
108
- if (Number.isNaN(Number(shorthand))) {
109
- const match = /^([\d.]+)\s*(ms|s|m|h|hr|d)$/i.exec(shorthand);
110
- if (!match) {
111
- throw new Error(`Unsupported time format: "${shorthand}". Use 'ms', 's', 'm', 'h', 'hr', or 'd'.`);
112
- }
113
- const [, value, unit] = match;
114
- const numericValue = Number.parseFloat(value);
115
- const unitLower = unit.toLowerCase();
116
- switch (unitLower) {
117
- case "ms": {
118
- milliseconds = numericValue;
119
- break;
120
- }
121
- case "s": {
122
- milliseconds = numericValue * 1e3;
123
- break;
124
- }
125
- case "m": {
126
- milliseconds = numericValue * 1e3 * 60;
127
- break;
128
- }
129
- case "h": {
130
- milliseconds = numericValue * 1e3 * 60 * 60;
131
- break;
132
- }
133
- case "hr": {
134
- milliseconds = numericValue * 1e3 * 60 * 60;
135
- break;
136
- }
137
- case "d": {
138
- milliseconds = numericValue * 1e3 * 60 * 60 * 24;
139
- break;
140
- }
141
- /* c8 ignore next 3 */
142
- default: {
143
- milliseconds = Number(shorthand);
144
- }
145
- }
146
- } else {
147
- milliseconds = Number(shorthand);
148
- }
149
- } else {
150
- throw new TypeError("Time must be a string or a number.");
151
- }
152
- return milliseconds;
153
- };
154
- var shorthandToTime = (shorthand, fromDate) => {
155
- fromDate ??= /* @__PURE__ */ new Date();
156
- const milliseconds = shorthandToMilliseconds(shorthand);
157
- if (milliseconds === void 0) {
158
- return fromDate.getTime();
159
- }
160
- return fromDate.getTime() + milliseconds;
161
- };
162
-
163
- // src/sleep.ts
164
- var sleep = async (ms) => new Promise((resolve) => setTimeout(resolve, ms));
165
-
166
- // src/stats.ts
167
- var Stats = class {
168
- _hits = 0;
169
- _misses = 0;
170
- _gets = 0;
171
- _sets = 0;
172
- _deletes = 0;
173
- _clears = 0;
174
- _vsize = 0;
175
- _ksize = 0;
176
- _count = 0;
177
- _enabled = false;
178
- constructor(options) {
179
- if (options?.enabled) {
180
- this._enabled = options.enabled;
181
- }
182
- }
183
- /**
184
- * @returns {boolean} - Whether the stats are enabled
185
- */
186
- get enabled() {
187
- return this._enabled;
188
- }
189
- /**
190
- * @param {boolean} enabled - Whether to enable the stats
191
- */
192
- set enabled(enabled) {
193
- this._enabled = enabled;
194
- }
195
- /**
196
- * @returns {number} - The number of hits
197
- * @readonly
198
- */
199
- get hits() {
200
- return this._hits;
201
- }
202
- /**
203
- * @returns {number} - The number of misses
204
- * @readonly
205
- */
206
- get misses() {
207
- return this._misses;
208
- }
209
- /**
210
- * @returns {number} - The number of gets
211
- * @readonly
212
- */
213
- get gets() {
214
- return this._gets;
215
- }
216
- /**
217
- * @returns {number} - The number of sets
218
- * @readonly
219
- */
220
- get sets() {
221
- return this._sets;
222
- }
223
- /**
224
- * @returns {number} - The number of deletes
225
- * @readonly
226
- */
227
- get deletes() {
228
- return this._deletes;
229
- }
230
- /**
231
- * @returns {number} - The number of clears
232
- * @readonly
233
- */
234
- get clears() {
235
- return this._clears;
236
- }
237
- /**
238
- * @returns {number} - The vsize (value size) of the cache instance
239
- * @readonly
240
- */
241
- get vsize() {
242
- return this._vsize;
243
- }
244
- /**
245
- * @returns {number} - The ksize (key size) of the cache instance
246
- * @readonly
247
- */
248
- get ksize() {
249
- return this._ksize;
250
- }
251
- /**
252
- * @returns {number} - The count of the cache instance
253
- * @readonly
254
- */
255
- get count() {
256
- return this._count;
257
- }
258
- incrementHits() {
259
- if (!this._enabled) {
260
- return;
261
- }
262
- this._hits++;
263
- }
264
- incrementMisses() {
265
- if (!this._enabled) {
266
- return;
267
- }
268
- this._misses++;
269
- }
270
- incrementGets() {
271
- if (!this._enabled) {
272
- return;
273
- }
274
- this._gets++;
275
- }
276
- incrementSets() {
277
- if (!this._enabled) {
278
- return;
279
- }
280
- this._sets++;
281
- }
282
- incrementDeletes() {
283
- if (!this._enabled) {
284
- return;
285
- }
286
- this._deletes++;
287
- }
288
- incrementClears() {
289
- if (!this._enabled) {
290
- return;
291
- }
292
- this._clears++;
293
- }
294
- // eslint-disable-next-line @typescript-eslint/naming-convention
295
- incrementVSize(value) {
296
- if (!this._enabled) {
297
- return;
298
- }
299
- this._vsize += this.roughSizeOfObject(value);
300
- }
301
- // eslint-disable-next-line @typescript-eslint/naming-convention
302
- decreaseVSize(value) {
303
- if (!this._enabled) {
304
- return;
305
- }
306
- this._vsize -= this.roughSizeOfObject(value);
307
- }
308
- // eslint-disable-next-line @typescript-eslint/naming-convention
309
- incrementKSize(key) {
310
- if (!this._enabled) {
311
- return;
312
- }
313
- this._ksize += this.roughSizeOfString(key);
314
- }
315
- // eslint-disable-next-line @typescript-eslint/naming-convention
316
- decreaseKSize(key) {
317
- if (!this._enabled) {
318
- return;
319
- }
320
- this._ksize -= this.roughSizeOfString(key);
321
- }
322
- incrementCount() {
323
- if (!this._enabled) {
324
- return;
325
- }
326
- this._count++;
327
- }
328
- decreaseCount() {
329
- if (!this._enabled) {
330
- return;
331
- }
332
- this._count--;
333
- }
334
- setCount(count) {
335
- if (!this._enabled) {
336
- return;
337
- }
338
- this._count = count;
339
- }
340
- roughSizeOfString(value) {
341
- return value.length * 2;
342
- }
343
- roughSizeOfObject(object) {
344
- const objectList = [];
345
- const stack = [object];
346
- let bytes = 0;
347
- while (stack.length > 0) {
348
- const value = stack.pop();
349
- if (typeof value === "boolean") {
350
- bytes += 4;
351
- } else if (typeof value === "string") {
352
- bytes += value.length * 2;
353
- } else if (typeof value === "number") {
354
- bytes += 8;
355
- } else if (typeof value === "object" && value !== null && !objectList.includes(value)) {
356
- objectList.push(value);
357
- for (const key in value) {
358
- bytes += key.length * 2;
359
- stack.push(value[key]);
360
- }
361
- }
362
- }
363
- return bytes;
364
- }
365
- reset() {
366
- this._hits = 0;
367
- this._misses = 0;
368
- this._gets = 0;
369
- this._sets = 0;
370
- this._deletes = 0;
371
- this._clears = 0;
372
- this._vsize = 0;
373
- this._ksize = 0;
374
- this._count = 0;
375
- }
376
- resetStoreValues() {
377
- this._vsize = 0;
378
- this._ksize = 0;
379
- this._count = 0;
380
- }
381
- };
382
-
383
- // src/ttl.ts
384
- function getTtlFromExpires(expires) {
385
- if (expires === void 0 || expires === null) {
386
- return void 0;
387
- }
388
- const now = Date.now();
389
- if (expires < now) {
390
- return void 0;
391
- }
392
- return expires - now;
393
- }
394
- function getCascadingTtl(cacheableTtl, primaryTtl, secondaryTtl) {
395
- return secondaryTtl ?? primaryTtl ?? shorthandToMilliseconds(cacheableTtl);
396
- }
397
- function calculateTtlFromExpiration(ttl, expires) {
398
- const ttlFromExpires = getTtlFromExpires(expires);
399
- const expiresFromTtl = ttl ? Date.now() + ttl : void 0;
400
- if (ttlFromExpires === void 0) {
401
- return ttl;
402
- }
403
- if (expiresFromTtl === void 0) {
404
- return ttlFromExpires;
405
- }
406
- if (expires > expiresFromTtl) {
407
- return ttl;
408
- }
409
- return ttlFromExpires;
410
- }
411
- export {
412
- HashAlgorithm,
413
- Stats,
414
- calculateTtlFromExpiration,
415
- coalesceAsync,
416
- getCascadingTtl,
417
- getTtlFromExpires,
418
- hash,
419
- hashToNumber,
420
- shorthandToMilliseconds,
421
- shorthandToTime,
422
- sleep
423
- };
1
+ var a=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,s]=r,n=Number.parseFloat(i);switch(s.toLowerCase()){case"ms":{e=n;break}case"s":{e=n*1e3;break}case"m":{e=n*1e3*60;break}case"h":{e=n*1e3*60*60;break}case"hr":{e=n*1e3*60*60;break}case"d":{e=n*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=a(t);return r===void 0?e.getTime():e.getTime()+r};var u=new Map;function _(t){return u.has(t)}function T(t){u.set(t,[])}function y(t){u.delete(t)}function v(t,e){let r=b(t);r.push(e),u.set(t,r)}function b(t){return u.get(t)??[]}async function x(t){return new Promise((e,r)=>{v(t,{resolve:e,reject:r})})}function z(t){let e=b(t);return y(t),e}function h(t){let{key:e,error:r,result:i}=t;for(let s of z(e))r?s.reject(r):s.resolve(i)}async function S(t,e){if(!_(t)){T(t);try{let r=await Promise.resolve(e());return h({key:t,result:r}),r}catch(r){throw h({key:t,error:r}),r}}return x(t)}import*as l from"crypto";var f=(s=>(s.SHA256="sha256",s.SHA512="sha512",s.MD5="md5",s.DJB2="djb2",s))(f||{});function d(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 w(r);if(!l.getHashes().includes(e.algorithm))throw new Error(`Unsupported hash algorithm: '${e?.algorithm}'`);let i=l.createHash(e.algorithm);return i.update(r),i.digest("hex")}function k(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 s=d(t,e),n=Number.parseInt(s,16),o=i-r+1,c=r+n%o;return c<r?r:c>i?i:c}function w(t){let e=5381;for(let r=0;r<t.length;r++)e=e*33^t.charCodeAt(r);return e.toString()}function O(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function P(t,e){return typeof t=="number"&&typeof e=="number"?t<e:!1}function C(t,...e){return typeof t=="function"?t(...e):t}var N=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],s=0;for(;i.length>0;){let n=i.pop();if(typeof n=="boolean")s+=4;else if(typeof n=="string")s+=n.length*2;else if(typeof n=="number")s+=8;else if(typeof n=="object"&&n!==null&&!r.includes(n)){r.push(n);for(let o in n)s+=o.length*2,i.push(n[o])}}return s}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 p(t){if(t==null)return;let e=Date.now();if(!(t<e))return t-e}function A(t,e,r){return r??e??a(t)}function H(t,e){let r=p(e),i=t?Date.now()+t:void 0;return r===void 0?t:i===void 0?r:e&&e>i?t:r}export{f as HashAlgorithm,m as Stats,H as calculateTtlFromExpiration,S as coalesceAsync,A as getCascadingTtl,p as getTtlFromExpires,d as hash,k as hashToNumber,O as isObject,P as lessThan,C as runIfFn,a as shorthandToMilliseconds,g as shorthandToTime,N as sleep};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cacheable/utils",
3
- "version": "1.1.0",
3
+ "version": "2.0.0",
4
4
  "description": "Cacheable Utilities for Caching Libraries",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -21,18 +21,17 @@
21
21
  "license": "MIT",
22
22
  "private": false,
23
23
  "devDependencies": {
24
- "@faker-js/faker": "^9.9.0",
25
- "@keyv/redis": "^5.0.0",
26
- "@keyv/valkey": "^1.0.7",
27
- "@types/eslint": "^9.6.1",
28
- "@types/node": "^24.1.0",
24
+ "@biomejs/biome": "^2.2.2",
25
+ "@faker-js/faker": "^10.0.0",
26
+ "@keyv/redis": "^5.1.1",
27
+ "@keyv/valkey": "^1.0.8",
28
+ "@types/node": "^24.3.0",
29
29
  "@vitest/coverage-v8": "^3.2.4",
30
30
  "lru-cache": "^11.1.0",
31
31
  "rimraf": "^6.0.1",
32
32
  "tsup": "^8.5.0",
33
- "typescript": "^5.8.3",
34
- "vitest": "^3.2.4",
35
- "xo": "^1.2.1"
33
+ "typescript": "^5.9.2",
34
+ "vitest": "^3.2.4"
36
35
  },
37
36
  "keywords": [
38
37
  "cacheable",
@@ -47,10 +46,11 @@
47
46
  "LICENSE"
48
47
  ],
49
48
  "scripts": {
50
- "build": "rimraf ./dist && tsup src/index.ts --format cjs,esm --dts --clean",
49
+ "build": "rimraf ./dist && tsup src/index.ts --format cjs,esm --dts --clean --minify",
51
50
  "prepublish": "pnpm build",
52
- "test": "xo --fix && vitest run --coverage",
53
- "test:ci": "xo && vitest run --coverage",
51
+ "lint": "biome check --write --error-on-warnings",
52
+ "test": "pnpm lint && vitest run --coverage",
53
+ "test:ci": "biome check --error-on-warnings && vitest run --coverage",
54
54
  "clean": "rimraf ./dist ./coverage ./node_modules"
55
55
  }
56
56
  }