@catbee/utils 2.0.0-next.0 → 2.0.0-next.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +52 -16
- package/array/index.cjs +180 -71
- package/array/index.d.ts +293 -1
- package/array/index.mjs +171 -72
- package/async/index.cjs +92 -36
- package/async/index.d.ts +275 -1
- package/async/index.mjs +92 -36
- package/cache/index.cjs +1 -1
- package/cache/index.d.ts +155 -1
- package/cache/index.mjs +2 -2
- package/config/index.cjs +78 -64
- package/config/index.d.ts +64 -2
- package/config/index.mjs +76 -64
- package/context-store/index.d.ts +192 -1
- package/crypto/index.d.ts +163 -1
- package/date/index.cjs +46 -1
- package/date/index.d.ts +190 -1
- package/date/index.mjs +45 -2
- package/decorators/index.cjs +1156 -18
- package/decorators/index.d.ts +684 -1
- package/decorators/index.mjs +1156 -18
- package/dir/index.cjs +4 -3
- package/dir/index.d.ts +195 -1
- package/dir/index.mjs +4 -3
- package/env/index.cjs +10 -26
- package/env/index.d.ts +379 -1
- package/env/index.mjs +10 -26
- package/exception/index.d.ts +232 -1
- package/fs/index.cjs +70 -36
- package/fs/index.d.ts +205 -1
- package/fs/index.mjs +64 -34
- package/http-status-codes/index.d.ts +267 -1
- package/id/index.d.ts +37 -1
- package/index.cjs +3 -3
- package/index.d.ts +1 -1
- package/index.mjs +1 -1
- package/logger/index.cjs +11 -11
- package/logger/index.d.ts +189 -1
- package/logger/index.mjs +12 -12
- package/middleware/index.d.ts +103 -1
- package/obj/index.cjs +150 -162
- package/obj/index.d.ts +136 -1
- package/obj/index.mjs +150 -162
- package/package.json +11 -11
- package/performance/index.cjs +2 -2
- package/performance/index.d.ts +138 -1
- package/performance/index.mjs +2 -2
- package/request/index.cjs +1 -1
- package/request/index.d.ts +241 -2
- package/request/index.mjs +1 -1
- package/response/index.d.ts +318 -2
- package/server/index.cjs +27 -23
- package/server/index.d.ts +785 -4
- package/server/index.mjs +28 -23
- package/stream/index.d.ts +90 -1
- package/string/index.d.ts +102 -1
- package/type/index.cjs +1 -1
- package/type/index.d.ts +107 -1
- package/type/index.mjs +1 -1
- package/types/index.d.ts +774 -4
- package/url/index.cjs +2 -4
- package/url/index.d.ts +142 -1
- package/url/index.mjs +2 -4
- package/{validate → validation}/index.cjs +89 -42
- package/{validate/validate.utils.d.ts → validation/index.d.ts} +32 -23
- package/{validate → validation}/index.mjs +85 -42
- package/array/array.utils.d.ts +0 -191
- package/async/async.utils.d.ts +0 -296
- package/cache/cache.utils.d.ts +0 -176
- package/config/config.d.ts +0 -57
- package/context-store/context-store.utils.d.ts +0 -212
- package/crypto/crypto.utils.d.ts +0 -183
- package/date/date.utils.d.ts +0 -190
- package/decorators/decorators.utils.d.ts +0 -705
- package/dir/dir.utils.d.ts +0 -216
- package/env/env.utils.d.ts +0 -400
- package/exception/exception.utils.d.ts +0 -253
- package/fs/fs.utils.d.ts +0 -196
- package/http-status-codes/http-status-codes.d.ts +0 -289
- package/id/id.utils.d.ts +0 -59
- package/logger/logger.utils.d.ts +0 -210
- package/middleware/middleware.utils.d.ts +0 -123
- package/obj/obj.utils.d.ts +0 -156
- package/performance/performance.utils.d.ts +0 -159
- package/request/request.utils.d.ts +0 -109
- package/response/response.utils.d.ts +0 -186
- package/server/server.builder.d.ts +0 -531
- package/server/server.d.ts +0 -303
- package/stream/stream.utils.d.ts +0 -111
- package/string/string.utils.d.ts +0 -124
- package/type/type.utils.d.ts +0 -129
- package/types/api-response.d.ts +0 -175
- package/types/common.d.ts +0 -148
- package/types/config.d.ts +0 -88
- package/types/server.d.ts +0 -291
- package/url/url.utils.d.ts +0 -164
- package/validate/index.d.ts +0 -25
package/async/index.cjs
CHANGED
|
@@ -45,7 +45,13 @@ function debounce(fn, delay) {
|
|
|
45
45
|
pendingArgs = args;
|
|
46
46
|
if (timer) clearTimeout(timer);
|
|
47
47
|
timer = setTimeout(() => {
|
|
48
|
-
|
|
48
|
+
try {
|
|
49
|
+
fn(...pendingArgs);
|
|
50
|
+
} catch (err) {
|
|
51
|
+
logger.getLogger().error({
|
|
52
|
+
err
|
|
53
|
+
}, "Error in debounced function");
|
|
54
|
+
}
|
|
49
55
|
timer = null;
|
|
50
56
|
}, delay);
|
|
51
57
|
}
|
|
@@ -58,7 +64,13 @@ function debounce(fn, delay) {
|
|
|
58
64
|
debounced.flush = () => {
|
|
59
65
|
if (timer) {
|
|
60
66
|
clearTimeout(timer);
|
|
61
|
-
|
|
67
|
+
try {
|
|
68
|
+
fn(...pendingArgs);
|
|
69
|
+
} catch (err) {
|
|
70
|
+
logger.getLogger().error({
|
|
71
|
+
err
|
|
72
|
+
}, "Error in debounced.flush");
|
|
73
|
+
}
|
|
62
74
|
timer = null;
|
|
63
75
|
pendingArgs = null;
|
|
64
76
|
}
|
|
@@ -84,14 +96,28 @@ function throttle(fn, limit, opts = {
|
|
|
84
96
|
timer = null;
|
|
85
97
|
}
|
|
86
98
|
lastCall = now;
|
|
87
|
-
|
|
99
|
+
try {
|
|
100
|
+
fn(...args);
|
|
101
|
+
} catch (err) {
|
|
102
|
+
logger.getLogger().error({
|
|
103
|
+
err
|
|
104
|
+
}, "Error in throttled function");
|
|
105
|
+
}
|
|
88
106
|
} else if (trailing) {
|
|
89
107
|
savedArgs = args;
|
|
90
108
|
if (!timer) {
|
|
91
109
|
timer = setTimeout(() => {
|
|
92
110
|
lastCall = leading ? Date.now() : 0;
|
|
93
111
|
timer = null;
|
|
94
|
-
if (savedArgs)
|
|
112
|
+
if (savedArgs) {
|
|
113
|
+
try {
|
|
114
|
+
fn(...savedArgs);
|
|
115
|
+
} catch (err) {
|
|
116
|
+
logger.getLogger().error({
|
|
117
|
+
err
|
|
118
|
+
}, "Error in throttled trailing call");
|
|
119
|
+
}
|
|
120
|
+
}
|
|
95
121
|
}, remaining);
|
|
96
122
|
}
|
|
97
123
|
}
|
|
@@ -142,7 +168,7 @@ function singletonAsync(fn, drop = false) {
|
|
|
142
168
|
promise = null;
|
|
143
169
|
});
|
|
144
170
|
} else if (drop) {
|
|
145
|
-
|
|
171
|
+
throw new Error("Function is already in progress");
|
|
146
172
|
}
|
|
147
173
|
return promise;
|
|
148
174
|
};
|
|
@@ -213,11 +239,19 @@ async function runInSeries(tasks) {
|
|
|
213
239
|
__name(runInSeries, "runInSeries");
|
|
214
240
|
function memoizeAsync(fn, options = {}) {
|
|
215
241
|
const cache = /* @__PURE__ */ new Map();
|
|
216
|
-
const { ttl
|
|
217
|
-
|
|
218
|
-
|
|
242
|
+
const { ttl } = options;
|
|
243
|
+
const generateKey = /* @__PURE__ */ __name((args) => {
|
|
244
|
+
try {
|
|
245
|
+
return options.keyFn?.(args) ?? JSON.stringify(args);
|
|
246
|
+
} catch {
|
|
247
|
+
logger.getLogger().warn("memoizeAsync: key generation failed, falling back to JSON.stringify");
|
|
248
|
+
return JSON.stringify(args);
|
|
249
|
+
}
|
|
250
|
+
}, "generateKey");
|
|
251
|
+
return async (...args) => {
|
|
252
|
+
const key = generateKey(args);
|
|
219
253
|
const cached = cache.get(key);
|
|
220
|
-
if (cached &&
|
|
254
|
+
if (cached && Date.now() < cached.expires) {
|
|
221
255
|
return cached.value;
|
|
222
256
|
}
|
|
223
257
|
const result = await fn(...args);
|
|
@@ -236,7 +270,10 @@ function abortable(promise, signal, abortValue = new Error("Operation aborted"))
|
|
|
236
270
|
return Promise.race([
|
|
237
271
|
promise,
|
|
238
272
|
new Promise((_, reject) => {
|
|
239
|
-
const abort = /* @__PURE__ */ __name(() =>
|
|
273
|
+
const abort = /* @__PURE__ */ __name(() => {
|
|
274
|
+
reject(abortValue);
|
|
275
|
+
signal.removeEventListener("abort", abort);
|
|
276
|
+
}, "abort");
|
|
240
277
|
signal.addEventListener("abort", abort, {
|
|
241
278
|
once: true
|
|
242
279
|
});
|
|
@@ -305,39 +342,53 @@ var CircuitBreakerState = /* @__PURE__ */ (function(CircuitBreakerState2) {
|
|
|
305
342
|
function circuitBreaker(fn, options = {}) {
|
|
306
343
|
const { failureThreshold = 5, resetTimeout = 1e4, successThreshold = 1, onOpen, onClose, onHalfOpen } = options;
|
|
307
344
|
let state = "CLOSED";
|
|
308
|
-
let
|
|
309
|
-
let
|
|
310
|
-
let
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
345
|
+
let fails = 0;
|
|
346
|
+
let halfSuccess = 0;
|
|
347
|
+
let unlockAt = 0;
|
|
348
|
+
const reset = /* @__PURE__ */ __name(() => {
|
|
349
|
+
fails = 0;
|
|
350
|
+
halfSuccess = 0;
|
|
351
|
+
state = "CLOSED";
|
|
352
|
+
onClose?.();
|
|
353
|
+
}, "reset");
|
|
354
|
+
const open = /* @__PURE__ */ __name(() => {
|
|
355
|
+
state = "OPEN";
|
|
356
|
+
unlockAt = Date.now() + resetTimeout;
|
|
357
|
+
onOpen?.();
|
|
358
|
+
}, "open");
|
|
359
|
+
const halfOpen = /* @__PURE__ */ __name(() => {
|
|
360
|
+
state = "HALF_OPEN";
|
|
361
|
+
onHalfOpen?.();
|
|
362
|
+
}, "halfOpen");
|
|
363
|
+
return async (...args) => {
|
|
364
|
+
const now = Date.now();
|
|
365
|
+
if (state === "OPEN" && now < unlockAt) {
|
|
366
|
+
throw new CircuitBreakerOpenError();
|
|
367
|
+
}
|
|
368
|
+
if (state === "OPEN" && now >= unlockAt) {
|
|
369
|
+
halfOpen();
|
|
318
370
|
}
|
|
319
371
|
try {
|
|
320
|
-
const
|
|
372
|
+
const res = await fn(...args);
|
|
321
373
|
if (state === "HALF_OPEN") {
|
|
322
|
-
|
|
323
|
-
if (
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
state = "
|
|
327
|
-
if (onClose) onClose();
|
|
374
|
+
halfSuccess++;
|
|
375
|
+
if (halfSuccess >= successThreshold) {
|
|
376
|
+
reset();
|
|
377
|
+
} else {
|
|
378
|
+
state = "HALF_OPEN";
|
|
328
379
|
}
|
|
329
380
|
} else {
|
|
330
|
-
|
|
381
|
+
fails = 0;
|
|
331
382
|
}
|
|
332
|
-
return
|
|
333
|
-
} catch (
|
|
334
|
-
|
|
335
|
-
if (
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
383
|
+
return res;
|
|
384
|
+
} catch (err) {
|
|
385
|
+
fails++;
|
|
386
|
+
if (state === "HALF_OPEN" || state === "CLOSED") {
|
|
387
|
+
if (fails >= failureThreshold) {
|
|
388
|
+
open();
|
|
389
|
+
}
|
|
339
390
|
}
|
|
340
|
-
throw
|
|
391
|
+
throw err;
|
|
341
392
|
}
|
|
342
393
|
};
|
|
343
394
|
}
|
|
@@ -353,12 +404,15 @@ async function runWithConcurrency(tasks, options = {}) {
|
|
|
353
404
|
}
|
|
354
405
|
return new Promise((resolve, reject) => {
|
|
355
406
|
let taskIndex = 0;
|
|
407
|
+
let rejected = false;
|
|
356
408
|
const processNext = /* @__PURE__ */ __name(async () => {
|
|
409
|
+
if (rejected) return;
|
|
357
410
|
const currentTaskIndex = taskIndex++;
|
|
358
411
|
if (currentTaskIndex >= totalTasks) return;
|
|
359
412
|
try {
|
|
360
413
|
const result = await tasks[currentTaskIndex]();
|
|
361
414
|
if (signal?.aborted) {
|
|
415
|
+
rejected = true;
|
|
362
416
|
reject(new Error("Aborted"));
|
|
363
417
|
return;
|
|
364
418
|
}
|
|
@@ -374,6 +428,7 @@ async function runWithConcurrency(tasks, options = {}) {
|
|
|
374
428
|
}
|
|
375
429
|
}
|
|
376
430
|
} catch (error) {
|
|
431
|
+
rejected = true;
|
|
377
432
|
reject(error);
|
|
378
433
|
return;
|
|
379
434
|
}
|
|
@@ -389,6 +444,7 @@ async function runWithConcurrency(tasks, options = {}) {
|
|
|
389
444
|
}
|
|
390
445
|
if (signal) {
|
|
391
446
|
signal.addEventListener("abort", () => {
|
|
447
|
+
rejected = true;
|
|
392
448
|
reject(new Error("Aborted"));
|
|
393
449
|
}, {
|
|
394
450
|
once: true
|
package/async/index.d.ts
CHANGED
|
@@ -22,4 +22,278 @@
|
|
|
22
22
|
* SOFTWARE.
|
|
23
23
|
*/
|
|
24
24
|
|
|
25
|
-
|
|
25
|
+
/**
|
|
26
|
+
* Delays execution for a specified number of milliseconds.
|
|
27
|
+
*
|
|
28
|
+
* @param {number} ms - The number of milliseconds to sleep.
|
|
29
|
+
* @returns {Promise<void>} A Promise that resolves after the given time.
|
|
30
|
+
*/
|
|
31
|
+
declare function sleep(ms: number): Promise<void>;
|
|
32
|
+
/**
|
|
33
|
+
* Creates a debounced version of a function that delays its execution.
|
|
34
|
+
* Provides `.cancel()` and `.flush()` methods.
|
|
35
|
+
*
|
|
36
|
+
* @template T
|
|
37
|
+
* @param {T} fn - The function to debounce.
|
|
38
|
+
* @param {number} delay - Delay in milliseconds.
|
|
39
|
+
* @returns {T & { cancel: () => void; flush: () => void }} A debounced function.
|
|
40
|
+
*/
|
|
41
|
+
declare function debounce<T extends (...args: any[]) => void>(fn: T, delay: number): {
|
|
42
|
+
(...args: Parameters<T>): void;
|
|
43
|
+
cancel(): void;
|
|
44
|
+
flush(): void;
|
|
45
|
+
} & {
|
|
46
|
+
cancel: () => void;
|
|
47
|
+
flush: () => void;
|
|
48
|
+
};
|
|
49
|
+
/**
|
|
50
|
+
* Creates a throttled version of a function that limits its execution rate.
|
|
51
|
+
* Allows control over leading/trailing invocation.
|
|
52
|
+
*
|
|
53
|
+
* @template T
|
|
54
|
+
* @param {T} fn - The function to throttle.
|
|
55
|
+
* @param {number} limit - Minimum time between calls in milliseconds.
|
|
56
|
+
* @param {{ leading?: boolean, trailing?: boolean }} [opts] - Options for leading/trailing edge throttling.
|
|
57
|
+
* @returns {(...args: Parameters<T>) => void} A throttled function.
|
|
58
|
+
*/
|
|
59
|
+
declare function throttle<T extends (...args: any[]) => void>(fn: T, limit: number, opts?: {
|
|
60
|
+
leading?: boolean;
|
|
61
|
+
trailing?: boolean;
|
|
62
|
+
}): (...args: Parameters<T>) => void;
|
|
63
|
+
/**
|
|
64
|
+
* Retries an asynchronous function a given number of times with optional delay/backoff.
|
|
65
|
+
*
|
|
66
|
+
* @template T
|
|
67
|
+
* @param {() => Promise<T>} fn - The async function to retry.
|
|
68
|
+
* @param {number} [retries=3] - Number of retry attempts.
|
|
69
|
+
* @param {number} [delay=500] - Delay in milliseconds between retries.
|
|
70
|
+
* @param {boolean} [backoff=false] - Use exponential backoff between attempts.
|
|
71
|
+
* @param {(error: unknown, attempt: number) => void} [onRetry] - Callback for each retry attempt.
|
|
72
|
+
* @returns {Promise<T>} The result of the async function if successful.
|
|
73
|
+
* @throws {*} The last encountered error if all retries fail.
|
|
74
|
+
*/
|
|
75
|
+
declare function retry<T>(fn: () => Promise<T>, retries?: number, delay?: number, backoff?: boolean, onRetry?: (error: unknown, attempt: number) => void): Promise<T>;
|
|
76
|
+
/**
|
|
77
|
+
* Wraps a promise and rejects it if it doesn't resolve within the specified timeout.
|
|
78
|
+
*
|
|
79
|
+
* @template T
|
|
80
|
+
* @param {Promise<T>} promise - The original promise.
|
|
81
|
+
* @param {number} ms - Timeout in milliseconds.
|
|
82
|
+
* @param {string} [message="Operation timed out"] - Optional timeout message.
|
|
83
|
+
* @returns {Promise<T>} A promise that resolves or rejects within the timeout.
|
|
84
|
+
*/
|
|
85
|
+
declare function withTimeout<T>(promise: Promise<T>, ms: number, message?: string): Promise<T>;
|
|
86
|
+
/**
|
|
87
|
+
* Executes async tasks in true batches.
|
|
88
|
+
* Each batch runs in parallel, but batches run sequentially.
|
|
89
|
+
* All tasks in a batch start at the same time, next batch waits for full completion.
|
|
90
|
+
* NOTE: For more granular concurrency, use a "queue" or "pooled" approach.
|
|
91
|
+
*
|
|
92
|
+
* @template T
|
|
93
|
+
* @param {Array<() => Promise<T>>} tasks - An array of functions that return Promises.
|
|
94
|
+
* @param {number} limit - Number of tasks to run in parallel per batch.
|
|
95
|
+
* @returns {Promise<T[]>} A promise that resolves to an array of resolved values.
|
|
96
|
+
*/
|
|
97
|
+
declare function runInBatches<T>(tasks: (() => Promise<T>)[], limit: number): Promise<T[]>;
|
|
98
|
+
/**
|
|
99
|
+
* Wraps a function and ensures it is only called once at a time.
|
|
100
|
+
* Calls made while one is in progress will wait for the same Promise.
|
|
101
|
+
* Optionally, new calls can be dropped while in progress (drop=true).
|
|
102
|
+
*
|
|
103
|
+
* @template TArgs
|
|
104
|
+
* @template TResult
|
|
105
|
+
* @param {(...args: TArgs) => Promise<TResult>} fn - The async function to wrap.
|
|
106
|
+
* @param {boolean} [drop=false] - If true, new calls while one is pending are rejected.
|
|
107
|
+
* @returns {(...args: TArgs) => Promise<TResult>} A wrapped function with singleton behavior.
|
|
108
|
+
*/
|
|
109
|
+
declare function singletonAsync<TArgs extends unknown[], TResult>(fn: (...args: TArgs) => Promise<TResult>, drop?: boolean): (...args: TArgs) => Promise<TResult>;
|
|
110
|
+
/**
|
|
111
|
+
* Resolves a list of async tasks in parallel, returning both resolved and rejected results.
|
|
112
|
+
*
|
|
113
|
+
* @template T
|
|
114
|
+
* @param {Array<() => Promise<T>>} tasks - Array of promise-returning functions.
|
|
115
|
+
* @returns {Promise<PromiseSettledResult<T>[]>} Results including status and value/reason.
|
|
116
|
+
*/
|
|
117
|
+
declare function settleAll<T>(tasks: (() => Promise<T>)[]): Promise<PromiseSettledResult<T>[]>;
|
|
118
|
+
interface TaskQueue {
|
|
119
|
+
<T>(taskFn: () => Promise<T>): Promise<T>;
|
|
120
|
+
pause: () => void;
|
|
121
|
+
resume: () => void;
|
|
122
|
+
readonly length: number;
|
|
123
|
+
readonly isPaused: boolean;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* A simple task queue that executes async tasks with a concurrency limit.
|
|
127
|
+
* Exposes pause, resume, and queue length getters.
|
|
128
|
+
*
|
|
129
|
+
* @param {number} limit - Maximum number of concurrent tasks.
|
|
130
|
+
* @returns {function & { pause: () => void, resume: () => void, length: number, isPaused: boolean }}
|
|
131
|
+
* Enqueue function plus queue controls.
|
|
132
|
+
*/
|
|
133
|
+
declare function createTaskQueue(limit: number): TaskQueue;
|
|
134
|
+
/**
|
|
135
|
+
* Executes async functions sequentially and collects results.
|
|
136
|
+
* Useful when order matters or tasks depend on each other.
|
|
137
|
+
*
|
|
138
|
+
* @template T
|
|
139
|
+
* @param {Array<() => Promise<T>>} tasks - Array of promise-returning functions.
|
|
140
|
+
* @returns {Promise<T[]>} Array of resolved values.
|
|
141
|
+
*/
|
|
142
|
+
declare function runInSeries<T>(tasks: (() => Promise<T>)[]): Promise<T[]>;
|
|
143
|
+
/**
|
|
144
|
+
* Memoizes an async function, caching results for repeated calls with identical arguments.
|
|
145
|
+
* Optional TTL (time-to-live) for cached entries.
|
|
146
|
+
*
|
|
147
|
+
* @template T Function return type
|
|
148
|
+
* @template Args Function arguments types
|
|
149
|
+
* @param {(...args: Args) => Promise<T>} fn - The async function to memoize
|
|
150
|
+
* @param {object} [options] - Memoization options
|
|
151
|
+
* @param {number} [options.ttl] - Cache TTL in milliseconds (optional)
|
|
152
|
+
* @param {(args: Args) => string} [options.keyFn] - Custom key generator function
|
|
153
|
+
* @returns {(...args: Args) => Promise<T>} Memoized function
|
|
154
|
+
*/
|
|
155
|
+
declare function memoizeAsync<T, Args extends any[]>(fn: (...args: Args) => Promise<T>, options?: {
|
|
156
|
+
ttl?: number;
|
|
157
|
+
keyFn?: (args: Args) => string;
|
|
158
|
+
}): (...args: Args) => Promise<T>;
|
|
159
|
+
/**
|
|
160
|
+
* Creates an abortable version of a promise that can be cancelled using an AbortController.
|
|
161
|
+
*
|
|
162
|
+
* @template T
|
|
163
|
+
* @param {Promise<T>} promise - The promise to make abortable
|
|
164
|
+
* @param {AbortSignal} signal - AbortSignal from AbortController
|
|
165
|
+
* @param {any} [abortValue] - Value to use when rejecting on abort
|
|
166
|
+
* @returns {Promise<T>} Promise that rejects if the signal is aborted
|
|
167
|
+
*/
|
|
168
|
+
declare function abortable<T>(promise: Promise<T>, signal: AbortSignal, abortValue?: any): Promise<T>;
|
|
169
|
+
/**
|
|
170
|
+
* Creates a promise with external resolve/reject functions.
|
|
171
|
+
* Useful for creating promises that can be resolved or rejected from outside.
|
|
172
|
+
*
|
|
173
|
+
* @template T
|
|
174
|
+
* @returns {[Promise<T>, (value: T | PromiseLike<T>) => void, (reason?: any) => void]}
|
|
175
|
+
* Tuple of [promise, resolve, reject]
|
|
176
|
+
*/
|
|
177
|
+
declare function createDeferred<T>(): [Promise<T>, (value: T | PromiseLike<T>) => void, (reason?: any) => void];
|
|
178
|
+
/**
|
|
179
|
+
* Chains a series of async functions, passing the result of each to the next.
|
|
180
|
+
* Similar to function composition but for async functions.
|
|
181
|
+
*
|
|
182
|
+
* @template T
|
|
183
|
+
* @param {Array<(input: any) => Promise<any>>} fns - Array of async functions to compose
|
|
184
|
+
* @returns {(input: any) => Promise<T>} Composed function
|
|
185
|
+
*/
|
|
186
|
+
declare function waterfall<T>(fns: Array<(input: any) => Promise<any>>): (initialValue: any) => Promise<T>;
|
|
187
|
+
/**
|
|
188
|
+
* Creates a rate limiter that ensures functions aren't called more than
|
|
189
|
+
* a specified number of times per interval.
|
|
190
|
+
*
|
|
191
|
+
* @template T
|
|
192
|
+
* @param {(...args: any[]) => Promise<T>} fn - Function to rate limit
|
|
193
|
+
* @param {number} maxCalls - Maximum calls allowed per interval
|
|
194
|
+
* @param {number} interval - Time interval in milliseconds
|
|
195
|
+
* @returns {(...args: any[]) => Promise<T>} Rate limited function
|
|
196
|
+
*/
|
|
197
|
+
declare function rateLimit<T>(fn: (...args: any[]) => Promise<T>, maxCalls: number, interval: number): (...args: any[]) => Promise<T>;
|
|
198
|
+
/**
|
|
199
|
+
* Circuit breaker pattern implementation for protecting against cascading failures.
|
|
200
|
+
* Tracks failures and prevents calling the function when too many failures occur.
|
|
201
|
+
*
|
|
202
|
+
* @param fn - Function to protect with circuit breaker
|
|
203
|
+
* @param options - Circuit breaker options
|
|
204
|
+
* @returns Function wrapped with circuit breaker logic
|
|
205
|
+
*
|
|
206
|
+
* @example
|
|
207
|
+
* ```typescript
|
|
208
|
+
* const protectedFetch = circuitBreaker(
|
|
209
|
+
* async (url) => {
|
|
210
|
+
* const response = await fetch(url);
|
|
211
|
+
* if (!response.ok) throw new Error(`HTTP error: ${response.status}`);
|
|
212
|
+
* return response.json();
|
|
213
|
+
* },
|
|
214
|
+
* {
|
|
215
|
+
* failureThreshold: 3,
|
|
216
|
+
* resetTimeout: 30000,
|
|
217
|
+
* onOpen: () => console.log('Circuit breaker opened'),
|
|
218
|
+
* onClose: () => console.log('Circuit breaker closed')
|
|
219
|
+
* }
|
|
220
|
+
* );
|
|
221
|
+
*
|
|
222
|
+
* // Will throw CircuitBreakerOpenError after failureThreshold consecutive failures
|
|
223
|
+
* try {
|
|
224
|
+
* const data = await protectedFetch('https://api.example.com');
|
|
225
|
+
* } catch (error) {
|
|
226
|
+
* if (error instanceof CircuitBreakerOpenError) {
|
|
227
|
+
* console.log('Service is currently unavailable, please try again later');
|
|
228
|
+
* }
|
|
229
|
+
* }
|
|
230
|
+
* ```
|
|
231
|
+
*/
|
|
232
|
+
declare class CircuitBreakerOpenError extends Error {
|
|
233
|
+
constructor(message?: string);
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* Circuit breaker states
|
|
237
|
+
*/
|
|
238
|
+
declare enum CircuitBreakerState {
|
|
239
|
+
CLOSED = "CLOSED",
|
|
240
|
+
OPEN = "OPEN",
|
|
241
|
+
HALF_OPEN = "HALF_OPEN"
|
|
242
|
+
}
|
|
243
|
+
interface CircuitBreakerOptions {
|
|
244
|
+
/** Number of consecutive failures before opening circuit (default: 5) */
|
|
245
|
+
failureThreshold?: number;
|
|
246
|
+
/** Time in milliseconds to wait before trying again (default: 10000) */
|
|
247
|
+
resetTimeout?: number;
|
|
248
|
+
/** Number of successful calls to close the circuit again (default: 1) */
|
|
249
|
+
successThreshold?: number;
|
|
250
|
+
/** Callback when circuit opens */
|
|
251
|
+
onOpen?: () => void;
|
|
252
|
+
/** Callback when circuit closes */
|
|
253
|
+
onClose?: () => void;
|
|
254
|
+
/** Callback when circuit enters half-open state */
|
|
255
|
+
onHalfOpen?: () => void;
|
|
256
|
+
}
|
|
257
|
+
declare function circuitBreaker<T, Args extends any[]>(fn: (...args: Args) => Promise<T>, options?: CircuitBreakerOptions): (...args: Args) => Promise<T>;
|
|
258
|
+
/**
|
|
259
|
+
* Run multiple async tasks with concurrency control.
|
|
260
|
+
*
|
|
261
|
+
* @param tasks - Array of async tasks to run
|
|
262
|
+
* @param options - Concurrency options
|
|
263
|
+
* @returns Promise that resolves when all tasks are complete
|
|
264
|
+
*
|
|
265
|
+
* @example
|
|
266
|
+
* ```typescript
|
|
267
|
+
* const urls = ['https://example.com/1', 'https://example.com/2', many more ];
|
|
268
|
+
*
|
|
269
|
+
* // Process up to 5 requests at a time, with progress reporting
|
|
270
|
+
* const results = await runWithConcurrency(
|
|
271
|
+
* urls.map(url => () => fetch(url).then(res => res.json())),
|
|
272
|
+
* {
|
|
273
|
+
* concurrency: 5,
|
|
274
|
+
* onProgress: (completed, total) => {
|
|
275
|
+
* console.log(`Progress: ${completed}/${total}`);
|
|
276
|
+
* }
|
|
277
|
+
* }
|
|
278
|
+
* );
|
|
279
|
+
* ```
|
|
280
|
+
*/
|
|
281
|
+
declare function runWithConcurrency<T>(tasks: Array<() => Promise<T>>, options?: {
|
|
282
|
+
/** Maximum number of tasks to run at once (default: 3) */
|
|
283
|
+
concurrency?: number;
|
|
284
|
+
/** Called whenever a task completes */
|
|
285
|
+
onProgress?: (completed: number, total: number) => void;
|
|
286
|
+
/** Abort signal to cancel execution */
|
|
287
|
+
signal?: AbortSignal;
|
|
288
|
+
}): Promise<T[]>;
|
|
289
|
+
/**
|
|
290
|
+
* Optionally requires a module, returning null if not found.
|
|
291
|
+
*
|
|
292
|
+
* @template T
|
|
293
|
+
* @param {string} name - The name of the module to require.
|
|
294
|
+
* @returns {T | null} The required module or null if not found.
|
|
295
|
+
*/
|
|
296
|
+
declare function optionalRequire<T = any>(name: string): T | null;
|
|
297
|
+
|
|
298
|
+
export { CircuitBreakerOpenError, CircuitBreakerState, abortable, circuitBreaker, createDeferred, createTaskQueue, debounce, memoizeAsync, optionalRequire, rateLimit, retry, runInBatches, runInSeries, runWithConcurrency, settleAll, singletonAsync, sleep, throttle, waterfall, withTimeout };
|
|
299
|
+
export type { CircuitBreakerOptions, TaskQueue };
|