@catbee/utils 1.0.5 → 2.0.0-next.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/LICENSE +1 -1
- package/README.md +27 -27
- package/array/array.utils.d.ts +191 -0
- package/array/index.cjs +246 -0
- package/array/index.d.ts +25 -0
- package/array/index.mjs +228 -0
- package/async/async.utils.d.ts +296 -0
- package/async/index.cjs +428 -0
- package/async/index.d.ts +25 -0
- package/async/index.mjs +407 -0
- package/cache/cache.utils.d.ts +176 -0
- package/cache/index.cjs +292 -0
- package/cache/index.d.ts +25 -0
- package/cache/index.mjs +290 -0
- package/config/config.d.ts +57 -0
- package/config/index.cjs +136 -0
- package/config/index.d.ts +26 -0
- package/config/index.mjs +131 -0
- package/context-store/context-store.utils.d.ts +212 -0
- package/context-store/index.cjs +267 -0
- package/context-store/index.d.ts +25 -0
- package/context-store/index.mjs +261 -0
- package/crypto/crypto.utils.d.ts +183 -0
- package/crypto/index.cjs +182 -0
- package/crypto/index.d.ts +25 -0
- package/crypto/index.mjs +166 -0
- package/date/date.utils.d.ts +190 -0
- package/date/index.cjs +295 -0
- package/date/index.d.ts +25 -0
- package/date/index.mjs +283 -0
- package/decorators/decorators.utils.d.ts +705 -0
- package/decorators/index.cjs +913 -0
- package/decorators/index.d.ts +25 -0
- package/decorators/index.mjs +872 -0
- package/dir/dir.utils.d.ts +216 -0
- package/dir/index.cjs +416 -0
- package/dir/index.d.ts +25 -0
- package/dir/index.mjs +389 -0
- package/env/env.utils.d.ts +400 -0
- package/env/index.cjs +761 -0
- package/env/index.d.ts +25 -0
- package/env/index.mjs +758 -0
- package/exception/exception.utils.d.ts +253 -0
- package/exception/index.cjs +362 -0
- package/exception/index.d.ts +25 -0
- package/exception/index.mjs +338 -0
- package/fs/fs.utils.d.ts +196 -0
- package/fs/index.cjs +253 -0
- package/fs/index.d.ts +25 -0
- package/fs/index.mjs +228 -0
- package/http-status-codes/http-status-codes.d.ts +289 -0
- package/http-status-codes/index.cjs +96 -0
- package/http-status-codes/index.d.ts +25 -0
- package/http-status-codes/index.mjs +94 -0
- package/id/id.utils.d.ts +59 -0
- package/id/index.cjs +62 -0
- package/id/index.d.ts +25 -0
- package/id/index.mjs +56 -0
- package/index.cjs +218 -0
- package/index.d.ts +51 -0
- package/index.mjs +51 -0
- package/logger/index.cjs +334 -0
- package/logger/index.d.ts +25 -0
- package/logger/index.mjs +313 -0
- package/logger/logger.utils.d.ts +210 -0
- package/middleware/index.cjs +177 -0
- package/middleware/index.d.ts +25 -0
- package/middleware/index.mjs +170 -0
- package/middleware/middleware.utils.d.ts +123 -0
- package/obj/index.cjs +317 -0
- package/obj/index.d.ts +25 -0
- package/obj/index.mjs +301 -0
- package/obj/obj.utils.d.ts +156 -0
- package/package.json +172 -20
- package/performance/index.cjs +231 -0
- package/performance/index.d.ts +25 -0
- package/performance/index.mjs +225 -0
- package/performance/performance.utils.d.ts +159 -0
- package/request/index.cjs +202 -0
- package/request/index.d.ts +26 -0
- package/request/index.mjs +194 -0
- package/request/request.utils.d.ts +109 -0
- package/response/index.cjs +234 -0
- package/response/index.d.ts +26 -0
- package/response/index.mjs +222 -0
- package/response/response.utils.d.ts +186 -0
- package/server/index.cjs +1627 -0
- package/server/index.d.ts +28 -0
- package/server/index.mjs +1617 -0
- package/server/server.builder.d.ts +531 -0
- package/server/server.d.ts +303 -0
- package/stream/index.cjs +151 -0
- package/stream/index.d.ts +25 -0
- package/stream/index.mjs +144 -0
- package/stream/stream.utils.d.ts +111 -0
- package/string/index.cjs +109 -0
- package/string/index.d.ts +25 -0
- package/string/index.mjs +95 -0
- package/string/string.utils.d.ts +124 -0
- package/type/index.cjs +129 -0
- package/type/index.d.ts +25 -0
- package/type/index.mjs +119 -0
- package/type/type.utils.d.ts +129 -0
- package/types/api-response.d.ts +175 -0
- package/types/common.d.ts +148 -0
- package/types/config.d.ts +88 -0
- package/types/index.cjs +34 -0
- package/types/index.d.ts +28 -0
- package/types/index.mjs +32 -0
- package/types/server.d.ts +291 -0
- package/url/index.cjs +201 -0
- package/url/index.d.ts +25 -0
- package/url/index.mjs +189 -0
- package/url/url.utils.d.ts +164 -0
- package/validate/index.cjs +212 -0
- package/validate/index.d.ts +25 -0
- package/validate/index.mjs +188 -0
- package/validate/validate.utils.d.ts +200 -0
- package/build/index.cjs +0 -7579
- package/build/index.d.ts +0 -5774
- package/build/index.mjs +0 -7274
package/async/index.mjs
ADDED
|
@@ -0,0 +1,407 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* The MIT License
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) 2025 Catbee Technologies. https://catbee.in/license
|
|
5
|
+
*
|
|
6
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
* of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
* in the Software without restriction, including without limitation the rights
|
|
9
|
+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
* copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
* furnished to do so, subject to the following conditions:
|
|
12
|
+
*
|
|
13
|
+
* The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
* copies or substantial portions of the Software.
|
|
15
|
+
*
|
|
16
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
* SOFTWARE.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import { getLogger } from '@catbee/utils/logger';
|
|
26
|
+
|
|
27
|
+
var __defProp = Object.defineProperty;
|
|
28
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
29
|
+
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
30
|
+
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
31
|
+
}) : x)(function(x) {
|
|
32
|
+
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
33
|
+
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
34
|
+
});
|
|
35
|
+
function sleep(ms) {
|
|
36
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
37
|
+
}
|
|
38
|
+
__name(sleep, "sleep");
|
|
39
|
+
function debounce(fn, delay) {
|
|
40
|
+
let timer = null;
|
|
41
|
+
let pendingArgs = null;
|
|
42
|
+
function debounced(...args) {
|
|
43
|
+
pendingArgs = args;
|
|
44
|
+
if (timer) clearTimeout(timer);
|
|
45
|
+
timer = setTimeout(() => {
|
|
46
|
+
fn(...pendingArgs);
|
|
47
|
+
timer = null;
|
|
48
|
+
}, delay);
|
|
49
|
+
}
|
|
50
|
+
__name(debounced, "debounced");
|
|
51
|
+
debounced.cancel = () => {
|
|
52
|
+
if (timer) clearTimeout(timer);
|
|
53
|
+
timer = null;
|
|
54
|
+
pendingArgs = null;
|
|
55
|
+
};
|
|
56
|
+
debounced.flush = () => {
|
|
57
|
+
if (timer) {
|
|
58
|
+
clearTimeout(timer);
|
|
59
|
+
fn(...pendingArgs);
|
|
60
|
+
timer = null;
|
|
61
|
+
pendingArgs = null;
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
return debounced;
|
|
65
|
+
}
|
|
66
|
+
__name(debounce, "debounce");
|
|
67
|
+
function throttle(fn, limit, opts = {
|
|
68
|
+
leading: true,
|
|
69
|
+
trailing: false
|
|
70
|
+
}) {
|
|
71
|
+
let lastCall = 0;
|
|
72
|
+
let timer = null;
|
|
73
|
+
let savedArgs = null;
|
|
74
|
+
return function(...args) {
|
|
75
|
+
const now = Date.now();
|
|
76
|
+
const { leading = true, trailing = false } = opts;
|
|
77
|
+
if (!lastCall && !leading) lastCall = now;
|
|
78
|
+
const remaining = limit - (now - lastCall);
|
|
79
|
+
if (remaining <= 0) {
|
|
80
|
+
if (timer) {
|
|
81
|
+
clearTimeout(timer);
|
|
82
|
+
timer = null;
|
|
83
|
+
}
|
|
84
|
+
lastCall = now;
|
|
85
|
+
fn(...args);
|
|
86
|
+
} else if (trailing) {
|
|
87
|
+
savedArgs = args;
|
|
88
|
+
if (!timer) {
|
|
89
|
+
timer = setTimeout(() => {
|
|
90
|
+
lastCall = leading ? Date.now() : 0;
|
|
91
|
+
timer = null;
|
|
92
|
+
if (savedArgs) fn(...savedArgs);
|
|
93
|
+
}, remaining);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
__name(throttle, "throttle");
|
|
99
|
+
async function retry(fn, retries = 3, delay = 500, backoff = false, onRetry) {
|
|
100
|
+
for (let i = 0; i < retries; i++) {
|
|
101
|
+
try {
|
|
102
|
+
return await fn();
|
|
103
|
+
} catch (e) {
|
|
104
|
+
if (i === retries - 1) throw e;
|
|
105
|
+
if (onRetry) onRetry(e, i + 1);
|
|
106
|
+
await sleep(backoff ? delay * Math.pow(2, i) : delay);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
throw new Error("Retry failed");
|
|
110
|
+
}
|
|
111
|
+
__name(retry, "retry");
|
|
112
|
+
function withTimeout(promise, ms, message = "Operation timed out") {
|
|
113
|
+
return new Promise((resolve, reject) => {
|
|
114
|
+
const timeoutHandle = setTimeout(() => reject(new Error(message)), ms);
|
|
115
|
+
promise.then((result) => {
|
|
116
|
+
clearTimeout(timeoutHandle);
|
|
117
|
+
resolve(result);
|
|
118
|
+
}).catch((err) => {
|
|
119
|
+
clearTimeout(timeoutHandle);
|
|
120
|
+
reject(err);
|
|
121
|
+
});
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
__name(withTimeout, "withTimeout");
|
|
125
|
+
async function runInBatches(tasks, limit) {
|
|
126
|
+
const results = [];
|
|
127
|
+
for (let i = 0; i < tasks.length; i += limit) {
|
|
128
|
+
const batch = tasks.slice(i, i + limit);
|
|
129
|
+
const batchResults = await Promise.all(batch.map((fn) => fn()));
|
|
130
|
+
results.push(...batchResults);
|
|
131
|
+
}
|
|
132
|
+
return results;
|
|
133
|
+
}
|
|
134
|
+
__name(runInBatches, "runInBatches");
|
|
135
|
+
function singletonAsync(fn, drop = false) {
|
|
136
|
+
let promise = null;
|
|
137
|
+
return async (...args) => {
|
|
138
|
+
if (!promise) {
|
|
139
|
+
promise = fn(...args).finally(() => {
|
|
140
|
+
promise = null;
|
|
141
|
+
});
|
|
142
|
+
} else if (drop) {
|
|
143
|
+
return Promise.reject(new Error("Busy: function already running"));
|
|
144
|
+
}
|
|
145
|
+
return promise;
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
__name(singletonAsync, "singletonAsync");
|
|
149
|
+
async function settleAll(tasks) {
|
|
150
|
+
return Promise.allSettled(tasks.map((task) => task()));
|
|
151
|
+
}
|
|
152
|
+
__name(settleAll, "settleAll");
|
|
153
|
+
function createTaskQueue(limit) {
|
|
154
|
+
const queue = [];
|
|
155
|
+
let activeCount = 0;
|
|
156
|
+
let paused = false;
|
|
157
|
+
const state = {
|
|
158
|
+
/**
|
|
159
|
+
* Pause task processing.
|
|
160
|
+
*/
|
|
161
|
+
pause() {
|
|
162
|
+
paused = true;
|
|
163
|
+
},
|
|
164
|
+
/**
|
|
165
|
+
* Resume task processing.
|
|
166
|
+
*/
|
|
167
|
+
resume() {
|
|
168
|
+
paused = false;
|
|
169
|
+
next();
|
|
170
|
+
}};
|
|
171
|
+
const next = /* @__PURE__ */ __name(() => {
|
|
172
|
+
if (paused || queue.length === 0 || activeCount >= limit) return;
|
|
173
|
+
const task = queue.shift();
|
|
174
|
+
activeCount++;
|
|
175
|
+
task().finally(() => {
|
|
176
|
+
activeCount--;
|
|
177
|
+
next();
|
|
178
|
+
});
|
|
179
|
+
}, "next");
|
|
180
|
+
const enqueue = /* @__PURE__ */ __name(async function(taskFn) {
|
|
181
|
+
return new Promise((resolve, reject) => {
|
|
182
|
+
queue.push(async () => {
|
|
183
|
+
try {
|
|
184
|
+
const result = await taskFn();
|
|
185
|
+
resolve(result);
|
|
186
|
+
} catch (err) {
|
|
187
|
+
reject(err);
|
|
188
|
+
}
|
|
189
|
+
});
|
|
190
|
+
next();
|
|
191
|
+
});
|
|
192
|
+
}, "enqueue");
|
|
193
|
+
enqueue.pause = state.pause;
|
|
194
|
+
enqueue.resume = state.resume;
|
|
195
|
+
Object.defineProperty(enqueue, "length", {
|
|
196
|
+
get: /* @__PURE__ */ __name(() => queue.length, "get")
|
|
197
|
+
});
|
|
198
|
+
Object.defineProperty(enqueue, "isPaused", {
|
|
199
|
+
get: /* @__PURE__ */ __name(() => paused, "get")
|
|
200
|
+
});
|
|
201
|
+
return enqueue;
|
|
202
|
+
}
|
|
203
|
+
__name(createTaskQueue, "createTaskQueue");
|
|
204
|
+
async function runInSeries(tasks) {
|
|
205
|
+
const results = [];
|
|
206
|
+
for (const task of tasks) {
|
|
207
|
+
results.push(await task());
|
|
208
|
+
}
|
|
209
|
+
return results;
|
|
210
|
+
}
|
|
211
|
+
__name(runInSeries, "runInSeries");
|
|
212
|
+
function memoizeAsync(fn, options = {}) {
|
|
213
|
+
const cache = /* @__PURE__ */ new Map();
|
|
214
|
+
const { ttl, keyFn = JSON.stringify } = options;
|
|
215
|
+
return async function(...args) {
|
|
216
|
+
const key = keyFn(args);
|
|
217
|
+
const cached = cache.get(key);
|
|
218
|
+
if (cached && (!ttl || Date.now() < cached.expires)) {
|
|
219
|
+
return cached.value;
|
|
220
|
+
}
|
|
221
|
+
const result = await fn(...args);
|
|
222
|
+
cache.set(key, {
|
|
223
|
+
value: result,
|
|
224
|
+
expires: ttl ? Date.now() + ttl : Infinity
|
|
225
|
+
});
|
|
226
|
+
return result;
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
__name(memoizeAsync, "memoizeAsync");
|
|
230
|
+
function abortable(promise, signal, abortValue = new Error("Operation aborted")) {
|
|
231
|
+
if (signal.aborted) {
|
|
232
|
+
return Promise.reject(abortValue);
|
|
233
|
+
}
|
|
234
|
+
return Promise.race([
|
|
235
|
+
promise,
|
|
236
|
+
new Promise((_, reject) => {
|
|
237
|
+
const abort = /* @__PURE__ */ __name(() => reject(abortValue), "abort");
|
|
238
|
+
signal.addEventListener("abort", abort, {
|
|
239
|
+
once: true
|
|
240
|
+
});
|
|
241
|
+
promise.finally(() => signal.removeEventListener("abort", abort));
|
|
242
|
+
})
|
|
243
|
+
]);
|
|
244
|
+
}
|
|
245
|
+
__name(abortable, "abortable");
|
|
246
|
+
function createDeferred() {
|
|
247
|
+
let resolve;
|
|
248
|
+
let reject;
|
|
249
|
+
const promise = new Promise((res, rej) => {
|
|
250
|
+
resolve = res;
|
|
251
|
+
reject = rej;
|
|
252
|
+
});
|
|
253
|
+
return [
|
|
254
|
+
promise,
|
|
255
|
+
resolve,
|
|
256
|
+
reject
|
|
257
|
+
];
|
|
258
|
+
}
|
|
259
|
+
__name(createDeferred, "createDeferred");
|
|
260
|
+
function waterfall(fns) {
|
|
261
|
+
return async (initialValue) => {
|
|
262
|
+
return fns.reduce(async (acc, fn) => fn(await acc), Promise.resolve(initialValue));
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
__name(waterfall, "waterfall");
|
|
266
|
+
function rateLimit(fn, maxCalls, interval) {
|
|
267
|
+
const calls = [];
|
|
268
|
+
return async function(...args) {
|
|
269
|
+
const now = Date.now();
|
|
270
|
+
calls.splice(0, calls.length, ...calls.filter((time) => now - time < interval));
|
|
271
|
+
if (calls.length >= maxCalls) {
|
|
272
|
+
const oldestCall = calls[0];
|
|
273
|
+
const delay = interval - (now - oldestCall);
|
|
274
|
+
await sleep(Math.max(1, delay));
|
|
275
|
+
const currentTime = Date.now();
|
|
276
|
+
calls.splice(0, calls.length, ...calls.filter((time) => currentTime - time < interval));
|
|
277
|
+
if (calls.length >= maxCalls) {
|
|
278
|
+
const nextDelay = interval - (currentTime - calls[0]);
|
|
279
|
+
await sleep(Math.max(1, nextDelay));
|
|
280
|
+
calls.splice(0, calls.length, ...calls.filter((time) => Date.now() - time < interval));
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
calls.push(Date.now());
|
|
284
|
+
return fn(...args);
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
__name(rateLimit, "rateLimit");
|
|
288
|
+
var CircuitBreakerOpenError = class extends Error {
|
|
289
|
+
static {
|
|
290
|
+
__name(this, "CircuitBreakerOpenError");
|
|
291
|
+
}
|
|
292
|
+
constructor(message = "Circuit breaker is open") {
|
|
293
|
+
super(message);
|
|
294
|
+
this.name = "CircuitBreakerOpenError";
|
|
295
|
+
}
|
|
296
|
+
};
|
|
297
|
+
var CircuitBreakerState = /* @__PURE__ */ (function(CircuitBreakerState2) {
|
|
298
|
+
CircuitBreakerState2["CLOSED"] = "CLOSED";
|
|
299
|
+
CircuitBreakerState2["OPEN"] = "OPEN";
|
|
300
|
+
CircuitBreakerState2["HALF_OPEN"] = "HALF_OPEN";
|
|
301
|
+
return CircuitBreakerState2;
|
|
302
|
+
})({});
|
|
303
|
+
function circuitBreaker(fn, options = {}) {
|
|
304
|
+
const { failureThreshold = 5, resetTimeout = 1e4, successThreshold = 1, onOpen, onClose, onHalfOpen } = options;
|
|
305
|
+
let state = "CLOSED";
|
|
306
|
+
let failureCount = 0;
|
|
307
|
+
let successCount = 0;
|
|
308
|
+
let nextAttempt = Date.now();
|
|
309
|
+
return async function(...args) {
|
|
310
|
+
if (state === "OPEN") {
|
|
311
|
+
if (Date.now() < nextAttempt) {
|
|
312
|
+
throw new CircuitBreakerOpenError();
|
|
313
|
+
}
|
|
314
|
+
state = "HALF_OPEN";
|
|
315
|
+
if (onHalfOpen) onHalfOpen();
|
|
316
|
+
}
|
|
317
|
+
try {
|
|
318
|
+
const result = await fn(...args);
|
|
319
|
+
if (state === "HALF_OPEN") {
|
|
320
|
+
successCount++;
|
|
321
|
+
if (successCount >= successThreshold) {
|
|
322
|
+
successCount = 0;
|
|
323
|
+
failureCount = 0;
|
|
324
|
+
state = "CLOSED";
|
|
325
|
+
if (onClose) onClose();
|
|
326
|
+
}
|
|
327
|
+
} else {
|
|
328
|
+
failureCount = 0;
|
|
329
|
+
}
|
|
330
|
+
return result;
|
|
331
|
+
} catch (error) {
|
|
332
|
+
failureCount++;
|
|
333
|
+
if ((state === "CLOSED" || state === "HALF_OPEN") && failureCount >= failureThreshold) {
|
|
334
|
+
state = "OPEN";
|
|
335
|
+
nextAttempt = Date.now() + resetTimeout;
|
|
336
|
+
if (onOpen) onOpen();
|
|
337
|
+
}
|
|
338
|
+
throw error;
|
|
339
|
+
}
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
__name(circuitBreaker, "circuitBreaker");
|
|
343
|
+
async function runWithConcurrency(tasks, options = {}) {
|
|
344
|
+
const { concurrency = 3, onProgress, signal } = options;
|
|
345
|
+
const results = [];
|
|
346
|
+
const totalTasks = tasks.length;
|
|
347
|
+
let completed = 0;
|
|
348
|
+
if (totalTasks === 0) return results;
|
|
349
|
+
if (signal?.aborted) {
|
|
350
|
+
throw new Error("Aborted");
|
|
351
|
+
}
|
|
352
|
+
return new Promise((resolve, reject) => {
|
|
353
|
+
let taskIndex = 0;
|
|
354
|
+
const processNext = /* @__PURE__ */ __name(async () => {
|
|
355
|
+
const currentTaskIndex = taskIndex++;
|
|
356
|
+
if (currentTaskIndex >= totalTasks) return;
|
|
357
|
+
try {
|
|
358
|
+
const result = await tasks[currentTaskIndex]();
|
|
359
|
+
if (signal?.aborted) {
|
|
360
|
+
reject(new Error("Aborted"));
|
|
361
|
+
return;
|
|
362
|
+
}
|
|
363
|
+
results[currentTaskIndex] = result;
|
|
364
|
+
completed++;
|
|
365
|
+
if (onProgress) {
|
|
366
|
+
try {
|
|
367
|
+
onProgress(completed, totalTasks);
|
|
368
|
+
} catch (err) {
|
|
369
|
+
getLogger().error({
|
|
370
|
+
err
|
|
371
|
+
}, "Error in onProgress callback");
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
} catch (error) {
|
|
375
|
+
reject(error);
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
if (completed === totalTasks) {
|
|
379
|
+
resolve(results);
|
|
380
|
+
return;
|
|
381
|
+
}
|
|
382
|
+
processNext();
|
|
383
|
+
}, "processNext");
|
|
384
|
+
const initialBatch = Math.min(concurrency, totalTasks);
|
|
385
|
+
for (let i = 0; i < initialBatch; i++) {
|
|
386
|
+
processNext();
|
|
387
|
+
}
|
|
388
|
+
if (signal) {
|
|
389
|
+
signal.addEventListener("abort", () => {
|
|
390
|
+
reject(new Error("Aborted"));
|
|
391
|
+
}, {
|
|
392
|
+
once: true
|
|
393
|
+
});
|
|
394
|
+
}
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
__name(runWithConcurrency, "runWithConcurrency");
|
|
398
|
+
function optionalRequire(name) {
|
|
399
|
+
try {
|
|
400
|
+
return __require(name);
|
|
401
|
+
} catch {
|
|
402
|
+
return null;
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
__name(optionalRequire, "optionalRequire");
|
|
406
|
+
|
|
407
|
+
export { CircuitBreakerOpenError, CircuitBreakerState, abortable, circuitBreaker, createDeferred, createTaskQueue, debounce, memoizeAsync, optionalRequire, rateLimit, retry, runInBatches, runInSeries, runWithConcurrency, settleAll, singletonAsync, sleep, throttle, waterfall, withTimeout };
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* The MIT License
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) 2025 Catbee Technologies. https://catbee.in/license
|
|
5
|
+
*
|
|
6
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
* of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
* in the Software without restriction, including without limitation the rights
|
|
9
|
+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
* copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
* furnished to do so, subject to the following conditions:
|
|
12
|
+
*
|
|
13
|
+
* The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
* copies or substantial portions of the Software.
|
|
15
|
+
*
|
|
16
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
* SOFTWARE.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Options for configuring a TTLCache instance.
|
|
27
|
+
*/
|
|
28
|
+
export interface TTLCacheOptions {
|
|
29
|
+
/** Default time-to-live in milliseconds for cache entries */
|
|
30
|
+
ttlMs?: number;
|
|
31
|
+
/** Maximum number of entries to keep in cache (uses LRU eviction policy) */
|
|
32
|
+
maxSize?: number;
|
|
33
|
+
/** Auto-cleanup interval in milliseconds (disabled if 0 or negative) */
|
|
34
|
+
autoCleanupMs?: number;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* An in-memory cache with time-to-live (TTL) support for each entry.
|
|
38
|
+
*
|
|
39
|
+
* @typeParam K - Type of the key.
|
|
40
|
+
* @typeParam V - Type of the value.
|
|
41
|
+
*
|
|
42
|
+
* @example
|
|
43
|
+
* const cache = new TTLCache<string, number>({ ttlMs: 1000 });
|
|
44
|
+
* cache.set("x", 123);
|
|
45
|
+
* const value = cache.get("x"); // 123
|
|
46
|
+
*/
|
|
47
|
+
export declare class TTLCache<K, V> {
|
|
48
|
+
private cache;
|
|
49
|
+
private ttlMs;
|
|
50
|
+
private maxSize?;
|
|
51
|
+
private cleanupInterval?;
|
|
52
|
+
/**
|
|
53
|
+
* @param options - Configuration options for the cache
|
|
54
|
+
*/
|
|
55
|
+
constructor(options?: TTLCacheOptions);
|
|
56
|
+
/**
|
|
57
|
+
* Sets a key-value pair in the cache with the default TTL.
|
|
58
|
+
*
|
|
59
|
+
* @param key - The key to set.
|
|
60
|
+
* @param value - The value to associate with the key.
|
|
61
|
+
*/
|
|
62
|
+
set(key: K, value: V): void;
|
|
63
|
+
/**
|
|
64
|
+
* Sets a key-value pair in the cache with a custom TTL.
|
|
65
|
+
*
|
|
66
|
+
* @param key - The key to set.
|
|
67
|
+
* @param value - The value to associate with the key.
|
|
68
|
+
* @param ttlMs - Time-to-live in milliseconds.
|
|
69
|
+
*/
|
|
70
|
+
setWithTTL(key: K, value: V, ttlMs: number): void;
|
|
71
|
+
/**
|
|
72
|
+
* Retrieves the value for a given key if it hasn't expired.
|
|
73
|
+
*
|
|
74
|
+
* @param key - The key to retrieve.
|
|
75
|
+
* @returns The cached value, or undefined if not found or expired.
|
|
76
|
+
*/
|
|
77
|
+
get(key: K): V | undefined;
|
|
78
|
+
/**
|
|
79
|
+
* Retrieves or computes a value if it's not in the cache or has expired.
|
|
80
|
+
*
|
|
81
|
+
* @param key - The key to retrieve
|
|
82
|
+
* @param producer - Function to generate the value if not cached
|
|
83
|
+
* @param ttlMs - Optional custom TTL for the computed value
|
|
84
|
+
* @returns The cached or computed value
|
|
85
|
+
*/
|
|
86
|
+
getOrCompute(key: K, producer: () => Promise<V>, ttlMs?: number): Promise<V>;
|
|
87
|
+
/**
|
|
88
|
+
* Checks if the key exists and hasn't expired.
|
|
89
|
+
*
|
|
90
|
+
* @param key - The key to check.
|
|
91
|
+
* @returns `true` if key exists and is valid, otherwise `false`.
|
|
92
|
+
*/
|
|
93
|
+
has(key: K): boolean;
|
|
94
|
+
/**
|
|
95
|
+
* Deletes a key from the cache.
|
|
96
|
+
*
|
|
97
|
+
* @param key - The key to delete.
|
|
98
|
+
* @returns `true` if the key existed and was removed, `false` otherwise.
|
|
99
|
+
*/
|
|
100
|
+
delete(key: K): boolean;
|
|
101
|
+
/**
|
|
102
|
+
* Clears all entries from the cache.
|
|
103
|
+
*/
|
|
104
|
+
clear(): void;
|
|
105
|
+
/**
|
|
106
|
+
* Returns the number of entries currently in the cache (includes expired entries until next access/cleanup).
|
|
107
|
+
*
|
|
108
|
+
* @returns Number of items in the cache (may include expired keys).
|
|
109
|
+
*/
|
|
110
|
+
size(): number;
|
|
111
|
+
/**
|
|
112
|
+
* Set multiple key-value pairs at once with the default TTL.
|
|
113
|
+
*
|
|
114
|
+
* @param entries - Array of [key, value] tuples to set
|
|
115
|
+
*/
|
|
116
|
+
setMany(entries: [K, V][]): void;
|
|
117
|
+
/**
|
|
118
|
+
* Get multiple values at once.
|
|
119
|
+
*
|
|
120
|
+
* @param keys - Array of keys to retrieve
|
|
121
|
+
* @returns Array of values (undefined for keys that don't exist or expired)
|
|
122
|
+
*/
|
|
123
|
+
getMany(keys: K[]): (V | undefined)[];
|
|
124
|
+
/**
|
|
125
|
+
* Removes all expired entries from the cache.
|
|
126
|
+
*
|
|
127
|
+
* @returns Number of entries removed.
|
|
128
|
+
*/
|
|
129
|
+
cleanup(): number;
|
|
130
|
+
/**
|
|
131
|
+
* Returns an iterator of all current valid [key, value] pairs.
|
|
132
|
+
*
|
|
133
|
+
* @returns IterableIterator<[K, V]>
|
|
134
|
+
*/
|
|
135
|
+
entries(): IterableIterator<[K, V]>;
|
|
136
|
+
/**
|
|
137
|
+
* Returns an iterator of all current valid keys.
|
|
138
|
+
*
|
|
139
|
+
* @returns IterableIterator<K>
|
|
140
|
+
*/
|
|
141
|
+
keys(): IterableIterator<K>;
|
|
142
|
+
/**
|
|
143
|
+
* Returns an iterator of all current valid values.
|
|
144
|
+
*
|
|
145
|
+
* @returns IterableIterator<V>
|
|
146
|
+
*/
|
|
147
|
+
values(): IterableIterator<V>;
|
|
148
|
+
/**
|
|
149
|
+
* Extends the expiration of a key by the specified time or default TTL.
|
|
150
|
+
*
|
|
151
|
+
* @param key - The key to refresh
|
|
152
|
+
* @param ttlMs - Optional new TTL in milliseconds (uses default if not specified)
|
|
153
|
+
* @returns true if the key was found and refreshed, false otherwise
|
|
154
|
+
*/
|
|
155
|
+
refresh(key: K, ttlMs?: number): boolean;
|
|
156
|
+
/**
|
|
157
|
+
* Returns a snapshot of cache stats.
|
|
158
|
+
*
|
|
159
|
+
* @returns Object containing cache statistics
|
|
160
|
+
*/
|
|
161
|
+
stats(): {
|
|
162
|
+
size: number;
|
|
163
|
+
validEntries: number;
|
|
164
|
+
expiredEntries: number;
|
|
165
|
+
maxSize: number | undefined;
|
|
166
|
+
};
|
|
167
|
+
/**
|
|
168
|
+
* Stop the auto-cleanup interval if it's running.
|
|
169
|
+
*/
|
|
170
|
+
destroy(): void;
|
|
171
|
+
/**
|
|
172
|
+
* Evict the least recently used entry from the cache.
|
|
173
|
+
* @private
|
|
174
|
+
*/
|
|
175
|
+
private evictLRU;
|
|
176
|
+
}
|