@catbee/utils 1.1.0 → 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.
Files changed (121) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +27 -27
  3. package/array/array.utils.d.ts +191 -0
  4. package/array/index.cjs +246 -0
  5. package/array/index.d.ts +25 -0
  6. package/array/index.mjs +228 -0
  7. package/async/async.utils.d.ts +296 -0
  8. package/async/index.cjs +428 -0
  9. package/async/index.d.ts +25 -0
  10. package/async/index.mjs +407 -0
  11. package/cache/cache.utils.d.ts +176 -0
  12. package/cache/index.cjs +292 -0
  13. package/cache/index.d.ts +25 -0
  14. package/cache/index.mjs +290 -0
  15. package/config/config.d.ts +57 -0
  16. package/config/index.cjs +136 -0
  17. package/config/index.d.ts +26 -0
  18. package/config/index.mjs +131 -0
  19. package/context-store/context-store.utils.d.ts +212 -0
  20. package/context-store/index.cjs +267 -0
  21. package/context-store/index.d.ts +25 -0
  22. package/context-store/index.mjs +261 -0
  23. package/crypto/crypto.utils.d.ts +183 -0
  24. package/crypto/index.cjs +182 -0
  25. package/crypto/index.d.ts +25 -0
  26. package/crypto/index.mjs +166 -0
  27. package/date/date.utils.d.ts +190 -0
  28. package/date/index.cjs +295 -0
  29. package/date/index.d.ts +25 -0
  30. package/date/index.mjs +283 -0
  31. package/decorators/decorators.utils.d.ts +705 -0
  32. package/decorators/index.cjs +913 -0
  33. package/decorators/index.d.ts +25 -0
  34. package/decorators/index.mjs +872 -0
  35. package/dir/dir.utils.d.ts +216 -0
  36. package/dir/index.cjs +416 -0
  37. package/dir/index.d.ts +25 -0
  38. package/dir/index.mjs +389 -0
  39. package/env/env.utils.d.ts +400 -0
  40. package/env/index.cjs +761 -0
  41. package/env/index.d.ts +25 -0
  42. package/env/index.mjs +758 -0
  43. package/exception/exception.utils.d.ts +253 -0
  44. package/exception/index.cjs +362 -0
  45. package/exception/index.d.ts +25 -0
  46. package/exception/index.mjs +338 -0
  47. package/fs/fs.utils.d.ts +196 -0
  48. package/fs/index.cjs +253 -0
  49. package/fs/index.d.ts +25 -0
  50. package/fs/index.mjs +228 -0
  51. package/http-status-codes/http-status-codes.d.ts +289 -0
  52. package/http-status-codes/index.cjs +96 -0
  53. package/http-status-codes/index.d.ts +25 -0
  54. package/http-status-codes/index.mjs +94 -0
  55. package/id/id.utils.d.ts +59 -0
  56. package/id/index.cjs +62 -0
  57. package/id/index.d.ts +25 -0
  58. package/id/index.mjs +56 -0
  59. package/index.cjs +218 -0
  60. package/index.d.ts +51 -0
  61. package/index.mjs +51 -0
  62. package/logger/index.cjs +334 -0
  63. package/logger/index.d.ts +25 -0
  64. package/logger/index.mjs +313 -0
  65. package/logger/logger.utils.d.ts +210 -0
  66. package/middleware/index.cjs +177 -0
  67. package/middleware/index.d.ts +25 -0
  68. package/middleware/index.mjs +170 -0
  69. package/middleware/middleware.utils.d.ts +123 -0
  70. package/obj/index.cjs +317 -0
  71. package/obj/index.d.ts +25 -0
  72. package/obj/index.mjs +301 -0
  73. package/obj/obj.utils.d.ts +156 -0
  74. package/package.json +171 -19
  75. package/performance/index.cjs +231 -0
  76. package/performance/index.d.ts +25 -0
  77. package/performance/index.mjs +225 -0
  78. package/performance/performance.utils.d.ts +159 -0
  79. package/request/index.cjs +202 -0
  80. package/request/index.d.ts +26 -0
  81. package/request/index.mjs +194 -0
  82. package/request/request.utils.d.ts +109 -0
  83. package/response/index.cjs +234 -0
  84. package/response/index.d.ts +26 -0
  85. package/response/index.mjs +222 -0
  86. package/response/response.utils.d.ts +186 -0
  87. package/server/index.cjs +1627 -0
  88. package/server/index.d.ts +28 -0
  89. package/server/index.mjs +1617 -0
  90. package/server/server.builder.d.ts +531 -0
  91. package/server/server.d.ts +303 -0
  92. package/stream/index.cjs +151 -0
  93. package/stream/index.d.ts +25 -0
  94. package/stream/index.mjs +144 -0
  95. package/stream/stream.utils.d.ts +111 -0
  96. package/string/index.cjs +109 -0
  97. package/string/index.d.ts +25 -0
  98. package/string/index.mjs +95 -0
  99. package/string/string.utils.d.ts +124 -0
  100. package/type/index.cjs +129 -0
  101. package/type/index.d.ts +25 -0
  102. package/type/index.mjs +119 -0
  103. package/type/type.utils.d.ts +129 -0
  104. package/types/api-response.d.ts +175 -0
  105. package/types/common.d.ts +148 -0
  106. package/types/config.d.ts +88 -0
  107. package/types/index.cjs +34 -0
  108. package/types/index.d.ts +28 -0
  109. package/types/index.mjs +32 -0
  110. package/types/server.d.ts +291 -0
  111. package/url/index.cjs +201 -0
  112. package/url/index.d.ts +25 -0
  113. package/url/index.mjs +189 -0
  114. package/url/url.utils.d.ts +164 -0
  115. package/validate/index.cjs +212 -0
  116. package/validate/index.d.ts +25 -0
  117. package/validate/index.mjs +188 -0
  118. package/validate/validate.utils.d.ts +200 -0
  119. package/build/index.cjs +0 -7694
  120. package/build/index.d.ts +0 -5792
  121. package/build/index.mjs +0 -7386
@@ -0,0 +1,228 @@
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 { getValueByPath } from '@catbee/utils/obj';
26
+
27
+ var __defProp = Object.defineProperty;
28
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
29
+ function chunk(array, size) {
30
+ if (!Array.isArray(array)) throw new TypeError("Expected an array");
31
+ if (array.length === 0) return [];
32
+ if (!Number.isInteger(size) || size <= 0) throw new Error("Chunk size must be a positive integer");
33
+ const result = [];
34
+ for (let i = 0; i < array.length; i += size) {
35
+ result.push(array.slice(i, i + size));
36
+ }
37
+ return result;
38
+ }
39
+ __name(chunk, "chunk");
40
+ function unique(array, keyFn) {
41
+ if (!Array.isArray(array) || array.length === 0) return [];
42
+ if (!keyFn) return Array.from(new Set(array));
43
+ const seen = /* @__PURE__ */ new Set();
44
+ return array.filter((item) => {
45
+ const key = keyFn(item);
46
+ if (seen.has(key)) return false;
47
+ seen.add(key);
48
+ return true;
49
+ });
50
+ }
51
+ __name(unique, "unique");
52
+ function flattenDeep(array) {
53
+ if (!Array.isArray(array)) return [];
54
+ const result = [];
55
+ for (const val of array) {
56
+ if (Array.isArray(val)) {
57
+ result.push(...flattenDeep(val));
58
+ } else {
59
+ result.push(val);
60
+ }
61
+ }
62
+ return result;
63
+ }
64
+ __name(flattenDeep, "flattenDeep");
65
+ function random(array) {
66
+ if (!Array.isArray(array) || array.length === 0) return void 0;
67
+ const idx = Math.floor(Math.random() * array.length);
68
+ return array[idx];
69
+ }
70
+ __name(random, "random");
71
+ function groupBy(array, keyOrFn) {
72
+ if (!Array.isArray(array) || array.length === 0) return {};
73
+ const keyFn = typeof keyOrFn === "function" ? keyOrFn : (item) => item[keyOrFn];
74
+ return array.reduce((acc, item) => {
75
+ const key = keyFn(item);
76
+ if (!acc[key]) acc[key] = [];
77
+ acc[key].push(item);
78
+ return acc;
79
+ }, {});
80
+ }
81
+ __name(groupBy, "groupBy");
82
+ function shuffle(array) {
83
+ if (!Array.isArray(array)) throw new TypeError("Expected an array");
84
+ const copy = array.slice();
85
+ for (let i = copy.length - 1; i > 0; i--) {
86
+ const j = Math.floor(Math.random() * (i + 1));
87
+ [copy[i], copy[j]] = [
88
+ copy[j],
89
+ copy[i]
90
+ ];
91
+ }
92
+ return copy;
93
+ }
94
+ __name(shuffle, "shuffle");
95
+ function pluck(array, key) {
96
+ if (!Array.isArray(array)) return [];
97
+ return array.map((item) => item[key]);
98
+ }
99
+ __name(pluck, "pluck");
100
+ function difference(a, b) {
101
+ if (!Array.isArray(a) || !Array.isArray(b)) return [];
102
+ const setB = new Set(b);
103
+ return a.filter((item) => !setB.has(item));
104
+ }
105
+ __name(difference, "difference");
106
+ function intersect(a, b) {
107
+ if (!Array.isArray(a) || !Array.isArray(b)) return [];
108
+ const setB = new Set(b);
109
+ return a.filter((item) => setB.has(item));
110
+ }
111
+ __name(intersect, "intersect");
112
+ function mergeSort(array, key, direction = "asc") {
113
+ if (!Array.isArray(array)) throw new TypeError("Expected array");
114
+ if (array.length <= 1) return array.slice();
115
+ const keyFn = typeof key === "function" ? key : (item) => getValueByPath(item, key);
116
+ const compare = /* @__PURE__ */ __name((a, b) => {
117
+ const aVal = keyFn(a);
118
+ const bVal = keyFn(b);
119
+ if (aVal === bVal) return 0;
120
+ if (aVal == null) return direction === "asc" ? 1 : -1;
121
+ if (bVal == null) return direction === "asc" ? -1 : 1;
122
+ return direction === "asc" ? aVal < bVal ? -1 : 1 : aVal > bVal ? -1 : 1;
123
+ }, "compare");
124
+ const merge = /* @__PURE__ */ __name((left, right) => {
125
+ const result = [];
126
+ let i = 0, j = 0;
127
+ while (i < left.length && j < right.length) {
128
+ if (compare(left[i], right[j]) <= 0) result.push(left[i++]);
129
+ else result.push(right[j++]);
130
+ }
131
+ return result.concat(left.slice(i)).concat(right.slice(j));
132
+ }, "merge");
133
+ const sort = /* @__PURE__ */ __name((arr) => {
134
+ if (arr.length <= 1) return arr;
135
+ const mid = Math.floor(arr.length / 2);
136
+ const left = sort(arr.slice(0, mid));
137
+ const right = sort(arr.slice(mid));
138
+ return merge(left, right);
139
+ }, "sort");
140
+ return sort(array);
141
+ }
142
+ __name(mergeSort, "mergeSort");
143
+ function zip(...arrays) {
144
+ if (arrays.length === 0) return [];
145
+ if (arrays.some((arr) => !Array.isArray(arr))) {
146
+ throw new TypeError("All arguments must be arrays");
147
+ }
148
+ const minLength = Math.min(...arrays.map((arr) => arr.length));
149
+ const result = [];
150
+ for (let i = 0; i < minLength; i++) {
151
+ result.push(arrays.map((arr) => arr[i]));
152
+ }
153
+ return result;
154
+ }
155
+ __name(zip, "zip");
156
+ function partition(array, predicate) {
157
+ if (!Array.isArray(array)) return [
158
+ [],
159
+ []
160
+ ];
161
+ return array.reduce(([pass, fail], item, index) => {
162
+ return predicate(item, index, array) ? [
163
+ [
164
+ ...pass,
165
+ item
166
+ ],
167
+ fail
168
+ ] : [
169
+ pass,
170
+ [
171
+ ...fail,
172
+ item
173
+ ]
174
+ ];
175
+ }, [
176
+ [],
177
+ []
178
+ ]);
179
+ }
180
+ __name(partition, "partition");
181
+ function range(start, end, step = 1) {
182
+ if (!Number.isFinite(start) || !Number.isFinite(end) || !Number.isFinite(step)) {
183
+ throw new TypeError("Arguments must be finite numbers");
184
+ }
185
+ if (step === 0) throw new Error("Step cannot be zero");
186
+ const isAscending = step > 0;
187
+ if (isAscending && start >= end || !isAscending && start <= end) {
188
+ return [];
189
+ }
190
+ const length = Math.max(Math.ceil((end - start) / step), 0);
191
+ const result = new Array(length);
192
+ for (let i = 0, value = start; i < length; i++, value += step) {
193
+ result[i] = value;
194
+ }
195
+ return result;
196
+ }
197
+ __name(range, "range");
198
+ function take(array, n = 1) {
199
+ if (!Array.isArray(array) || n <= 0) return [];
200
+ return array.slice(0, n);
201
+ }
202
+ __name(take, "take");
203
+ function takeWhile(array, predicate) {
204
+ if (!Array.isArray(array)) return [];
205
+ const result = [];
206
+ for (let i = 0; i < array.length; i++) {
207
+ if (!predicate(array[i], i)) break;
208
+ result.push(array[i]);
209
+ }
210
+ return result;
211
+ }
212
+ __name(takeWhile, "takeWhile");
213
+ function compact(array) {
214
+ if (!Array.isArray(array)) return [];
215
+ return array.filter(Boolean);
216
+ }
217
+ __name(compact, "compact");
218
+ function countBy(array, keyFn) {
219
+ if (!Array.isArray(array)) return {};
220
+ return array.reduce((acc, item) => {
221
+ const key = String(keyFn(item));
222
+ acc[key] = (acc[key] || 0) + 1;
223
+ return acc;
224
+ }, {});
225
+ }
226
+ __name(countBy, "countBy");
227
+
228
+ export { chunk, compact, countBy, difference, flattenDeep, groupBy, intersect, mergeSort, partition, pluck, random, range, shuffle, take, takeWhile, unique, zip };
@@ -0,0 +1,296 @@
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
+ * 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
+ export 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
+ export 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
+ export 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
+ export 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
+ export 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
+ export 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
+ export 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
+ export declare function settleAll<T>(tasks: (() => Promise<T>)[]): Promise<PromiseSettledResult<T>[]>;
118
+ export 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
+ export 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
+ export 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
+ export 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
+ export 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
+ export 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
+ export 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
+ export 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
+ export declare class CircuitBreakerOpenError extends Error {
233
+ constructor(message?: string);
234
+ }
235
+ /**
236
+ * Circuit breaker states
237
+ */
238
+ export declare enum CircuitBreakerState {
239
+ CLOSED = "CLOSED",
240
+ OPEN = "OPEN",
241
+ HALF_OPEN = "HALF_OPEN"
242
+ }
243
+ export 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
+ export 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
+ export 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
+ export declare function optionalRequire<T = any>(name: string): T | null;