@catbee/utils 2.0.0-next.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.
Files changed (122) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +102 -52
  3. package/array/index.cjs +215 -74
  4. package/array/index.d.ts +345 -2
  5. package/array/index.mjs +201 -74
  6. package/async/index.cjs +116 -39
  7. package/async/index.d.ts +292 -2
  8. package/async/index.mjs +116 -40
  9. package/cache/index.cjs +2 -2
  10. package/cache/index.d.ts +156 -2
  11. package/cache/index.mjs +3 -3
  12. package/config/index.cjs +80 -66
  13. package/config/index.d.ts +65 -3
  14. package/config/index.mjs +77 -65
  15. package/context-store/index.cjs +2 -3
  16. package/context-store/index.d.ts +193 -2
  17. package/context-store/index.mjs +2 -3
  18. package/crypto/index.cjs +55 -5
  19. package/crypto/index.d.ts +225 -2
  20. package/crypto/index.mjs +52 -7
  21. package/date/index.cjs +676 -2
  22. package/date/index.d.ts +676 -2
  23. package/date/index.mjs +665 -3
  24. package/decorator/index.cjs +2172 -0
  25. package/{decorators/decorators.utils.d.ts → decorator/index.d.ts} +58 -54
  26. package/decorator/index.mjs +2131 -0
  27. package/{dir → directory}/index.cjs +5 -4
  28. package/{dir/dir.utils.d.ts → directory/index.d.ts} +24 -21
  29. package/{dir → directory}/index.mjs +5 -4
  30. package/env/index.cjs +100 -68
  31. package/env/index.d.ts +391 -2
  32. package/env/index.mjs +100 -68
  33. package/exception/index.cjs +1 -1
  34. package/exception/index.d.ts +233 -2
  35. package/exception/index.mjs +1 -1
  36. package/fs/index.cjs +71 -37
  37. package/fs/index.d.ts +206 -2
  38. package/fs/index.mjs +65 -35
  39. package/http-status-codes/index.cjs +1 -1
  40. package/http-status-codes/index.d.ts +268 -2
  41. package/http-status-codes/index.mjs +1 -1
  42. package/id/index.cjs +1 -1
  43. package/id/index.d.ts +38 -2
  44. package/id/index.mjs +1 -1
  45. package/index.cjs +13 -13
  46. package/index.d.ts +5 -5
  47. package/index.mjs +5 -5
  48. package/logger/index.cjs +13 -15
  49. package/logger/index.d.ts +190 -2
  50. package/logger/index.mjs +14 -16
  51. package/middleware/index.cjs +1 -1
  52. package/middleware/index.d.ts +104 -2
  53. package/middleware/index.mjs +1 -1
  54. package/object/index.cjs +379 -0
  55. package/{obj/obj.utils.d.ts → object/index.d.ts} +73 -33
  56. package/object/index.mjs +360 -0
  57. package/package.json +41 -23
  58. package/performance/index.cjs +4 -4
  59. package/performance/index.d.ts +139 -2
  60. package/performance/index.mjs +4 -4
  61. package/request/index.cjs +37 -25
  62. package/request/index.d.ts +242 -3
  63. package/request/index.mjs +37 -25
  64. package/response/index.cjs +1 -1
  65. package/response/index.d.ts +319 -3
  66. package/response/index.mjs +1 -1
  67. package/server/index.cjs +249 -146
  68. package/server/index.d.ts +866 -5
  69. package/server/index.mjs +248 -144
  70. package/stream/index.cjs +1 -1
  71. package/stream/index.d.ts +91 -2
  72. package/stream/index.mjs +1 -1
  73. package/string/index.cjs +34 -1
  74. package/string/index.d.ts +146 -2
  75. package/string/index.mjs +31 -2
  76. package/type/index.cjs +19 -2
  77. package/type/index.d.ts +144 -2
  78. package/type/index.mjs +17 -3
  79. package/types/index.cjs +1 -1
  80. package/types/index.d.ts +775 -5
  81. package/types/index.mjs +1 -1
  82. package/url/index.cjs +63 -5
  83. package/url/index.d.ts +200 -2
  84. package/url/index.mjs +59 -6
  85. package/{validate → validation}/index.cjs +91 -44
  86. package/{validate/validate.utils.d.ts → validation/index.d.ts} +33 -24
  87. package/{validate → validation}/index.mjs +87 -44
  88. package/array/array.utils.d.ts +0 -191
  89. package/async/async.utils.d.ts +0 -296
  90. package/cache/cache.utils.d.ts +0 -176
  91. package/config/config.d.ts +0 -57
  92. package/context-store/context-store.utils.d.ts +0 -212
  93. package/crypto/crypto.utils.d.ts +0 -183
  94. package/date/date.utils.d.ts +0 -190
  95. package/decorators/index.cjs +0 -913
  96. package/decorators/index.d.ts +0 -25
  97. package/decorators/index.mjs +0 -872
  98. package/dir/index.d.ts +0 -25
  99. package/env/env.utils.d.ts +0 -400
  100. package/exception/exception.utils.d.ts +0 -253
  101. package/fs/fs.utils.d.ts +0 -196
  102. package/http-status-codes/http-status-codes.d.ts +0 -289
  103. package/id/id.utils.d.ts +0 -59
  104. package/logger/logger.utils.d.ts +0 -210
  105. package/middleware/middleware.utils.d.ts +0 -123
  106. package/obj/index.cjs +0 -317
  107. package/obj/index.d.ts +0 -25
  108. package/obj/index.mjs +0 -301
  109. package/performance/performance.utils.d.ts +0 -159
  110. package/request/request.utils.d.ts +0 -109
  111. package/response/response.utils.d.ts +0 -186
  112. package/server/server.builder.d.ts +0 -531
  113. package/server/server.d.ts +0 -303
  114. package/stream/stream.utils.d.ts +0 -111
  115. package/string/string.utils.d.ts +0 -124
  116. package/type/type.utils.d.ts +0 -129
  117. package/types/api-response.d.ts +0 -175
  118. package/types/common.d.ts +0 -148
  119. package/types/config.d.ts +0 -88
  120. package/types/server.d.ts +0 -291
  121. package/url/url.utils.d.ts +0 -164
  122. package/validate/index.d.ts +0 -25
package/async/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /*
2
2
  * The MIT License
3
3
  *
4
- * Copyright (c) 2025 Catbee Technologies. https://catbee.in/license
4
+ * Copyright (c) 2026 Catbee Technologies. https://catbee.in/license
5
5
  *
6
6
  * Permission is hereby granted, free of charge, to any person obtaining a copy
7
7
  * of this software and associated documentation files (the "Software"), to deal
@@ -22,4 +22,294 @@
22
22
  * SOFTWARE.
23
23
  */
24
24
 
25
- export * from './async.utils';
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
+ * Races promises and returns the first fulfilled value with its index.
299
+ * If all promises reject, the last rejection is thrown.
300
+ *
301
+ * @template T
302
+ * @param {Promise<T>[]} promises - Array of promises.
303
+ * @returns {Promise<{ value: T; index: number }>} First fulfilled value with index.
304
+ *
305
+ * @example
306
+ * const result = await raceWithValue([fetchA(), fetchB(), fetchC()]);
307
+ * console.log(result.value, result.index); // First fulfilled promise result
308
+ */
309
+ declare function raceWithValue<T>(promises: Promise<T>[]): Promise<{
310
+ value: T;
311
+ index: number;
312
+ }>;
313
+
314
+ export { CircuitBreakerOpenError, CircuitBreakerState, abortable, circuitBreaker, createDeferred, createTaskQueue, debounce, memoizeAsync, optionalRequire, raceWithValue, rateLimit, retry, runInBatches, runInSeries, runWithConcurrency, settleAll, singletonAsync, sleep, throttle, waterfall, withTimeout };
315
+ export type { CircuitBreakerOptions, TaskQueue };
package/async/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  /*
2
2
  * The MIT License
3
3
  *
4
- * Copyright (c) 2025 Catbee Technologies. https://catbee.in/license
4
+ * Copyright (c) 2026 Catbee Technologies. https://catbee.in/license
5
5
  *
6
6
  * Permission is hereby granted, free of charge, to any person obtaining a copy
7
7
  * of this software and associated documentation files (the "Software"), to deal
@@ -43,7 +43,13 @@ function debounce(fn, delay) {
43
43
  pendingArgs = args;
44
44
  if (timer) clearTimeout(timer);
45
45
  timer = setTimeout(() => {
46
- fn(...pendingArgs);
46
+ try {
47
+ fn(...pendingArgs);
48
+ } catch (err) {
49
+ getLogger().error({
50
+ err
51
+ }, "Error in debounced function");
52
+ }
47
53
  timer = null;
48
54
  }, delay);
49
55
  }
@@ -56,7 +62,13 @@ function debounce(fn, delay) {
56
62
  debounced.flush = () => {
57
63
  if (timer) {
58
64
  clearTimeout(timer);
59
- fn(...pendingArgs);
65
+ try {
66
+ fn(...pendingArgs);
67
+ } catch (err) {
68
+ getLogger().error({
69
+ err
70
+ }, "Error in debounced.flush");
71
+ }
60
72
  timer = null;
61
73
  pendingArgs = null;
62
74
  }
@@ -64,10 +76,11 @@ function debounce(fn, delay) {
64
76
  return debounced;
65
77
  }
66
78
  __name(debounce, "debounce");
67
- function throttle(fn, limit, opts = {
79
+ var DEFAULT_THROTTLE_OPTS = {
68
80
  leading: true,
69
81
  trailing: false
70
- }) {
82
+ };
83
+ function throttle(fn, limit, opts = DEFAULT_THROTTLE_OPTS) {
71
84
  let lastCall = 0;
72
85
  let timer = null;
73
86
  let savedArgs = null;
@@ -82,14 +95,28 @@ function throttle(fn, limit, opts = {
82
95
  timer = null;
83
96
  }
84
97
  lastCall = now;
85
- fn(...args);
98
+ try {
99
+ fn(...args);
100
+ } catch (err) {
101
+ getLogger().error({
102
+ err
103
+ }, "Error in throttled function");
104
+ }
86
105
  } else if (trailing) {
87
106
  savedArgs = args;
88
107
  if (!timer) {
89
108
  timer = setTimeout(() => {
90
109
  lastCall = leading ? Date.now() : 0;
91
110
  timer = null;
92
- if (savedArgs) fn(...savedArgs);
111
+ if (savedArgs) {
112
+ try {
113
+ fn(...savedArgs);
114
+ } catch (err) {
115
+ getLogger().error({
116
+ err
117
+ }, "Error in throttled trailing call");
118
+ }
119
+ }
93
120
  }, remaining);
94
121
  }
95
122
  }
@@ -140,7 +167,7 @@ function singletonAsync(fn, drop = false) {
140
167
  promise = null;
141
168
  });
142
169
  } else if (drop) {
143
- return Promise.reject(new Error("Busy: function already running"));
170
+ throw new Error("Function is already in progress");
144
171
  }
145
172
  return promise;
146
173
  };
@@ -211,11 +238,19 @@ async function runInSeries(tasks) {
211
238
  __name(runInSeries, "runInSeries");
212
239
  function memoizeAsync(fn, options = {}) {
213
240
  const cache = /* @__PURE__ */ new Map();
214
- const { ttl, keyFn = JSON.stringify } = options;
215
- return async function(...args) {
216
- const key = keyFn(args);
241
+ const { ttl } = options;
242
+ const generateKey = /* @__PURE__ */ __name((args) => {
243
+ try {
244
+ return options.keyFn?.(args) ?? JSON.stringify(args);
245
+ } catch {
246
+ getLogger().warn("memoizeAsync: key generation failed, falling back to JSON.stringify");
247
+ return JSON.stringify(args);
248
+ }
249
+ }, "generateKey");
250
+ return async (...args) => {
251
+ const key = generateKey(args);
217
252
  const cached = cache.get(key);
218
- if (cached && (!ttl || Date.now() < cached.expires)) {
253
+ if (cached && Date.now() < cached.expires) {
219
254
  return cached.value;
220
255
  }
221
256
  const result = await fn(...args);
@@ -234,7 +269,10 @@ function abortable(promise, signal, abortValue = new Error("Operation aborted"))
234
269
  return Promise.race([
235
270
  promise,
236
271
  new Promise((_, reject) => {
237
- const abort = /* @__PURE__ */ __name(() => reject(abortValue), "abort");
272
+ const abort = /* @__PURE__ */ __name(() => {
273
+ reject(abortValue);
274
+ signal.removeEventListener("abort", abort);
275
+ }, "abort");
238
276
  signal.addEventListener("abort", abort, {
239
277
  once: true
240
278
  });
@@ -303,39 +341,53 @@ var CircuitBreakerState = /* @__PURE__ */ (function(CircuitBreakerState2) {
303
341
  function circuitBreaker(fn, options = {}) {
304
342
  const { failureThreshold = 5, resetTimeout = 1e4, successThreshold = 1, onOpen, onClose, onHalfOpen } = options;
305
343
  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();
344
+ let fails = 0;
345
+ let halfSuccess = 0;
346
+ let unlockAt = 0;
347
+ const reset = /* @__PURE__ */ __name(() => {
348
+ fails = 0;
349
+ halfSuccess = 0;
350
+ state = "CLOSED";
351
+ onClose?.();
352
+ }, "reset");
353
+ const open = /* @__PURE__ */ __name(() => {
354
+ state = "OPEN";
355
+ unlockAt = Date.now() + resetTimeout;
356
+ onOpen?.();
357
+ }, "open");
358
+ const halfOpen = /* @__PURE__ */ __name(() => {
359
+ state = "HALF_OPEN";
360
+ onHalfOpen?.();
361
+ }, "halfOpen");
362
+ return async (...args) => {
363
+ const now = Date.now();
364
+ if (state === "OPEN" && now < unlockAt) {
365
+ throw new CircuitBreakerOpenError();
366
+ }
367
+ if (state === "OPEN" && now >= unlockAt) {
368
+ halfOpen();
316
369
  }
317
370
  try {
318
- const result = await fn(...args);
371
+ const res = await fn(...args);
319
372
  if (state === "HALF_OPEN") {
320
- successCount++;
321
- if (successCount >= successThreshold) {
322
- successCount = 0;
323
- failureCount = 0;
324
- state = "CLOSED";
325
- if (onClose) onClose();
373
+ halfSuccess++;
374
+ if (halfSuccess >= successThreshold) {
375
+ reset();
376
+ } else {
377
+ state = "HALF_OPEN";
326
378
  }
327
379
  } else {
328
- failureCount = 0;
380
+ fails = 0;
329
381
  }
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();
382
+ return res;
383
+ } catch (err) {
384
+ fails++;
385
+ if (state === "HALF_OPEN" || state === "CLOSED") {
386
+ if (fails >= failureThreshold) {
387
+ open();
388
+ }
337
389
  }
338
- throw error;
390
+ throw err;
339
391
  }
340
392
  };
341
393
  }
@@ -351,12 +403,15 @@ async function runWithConcurrency(tasks, options = {}) {
351
403
  }
352
404
  return new Promise((resolve, reject) => {
353
405
  let taskIndex = 0;
406
+ let rejected = false;
354
407
  const processNext = /* @__PURE__ */ __name(async () => {
408
+ if (rejected) return;
355
409
  const currentTaskIndex = taskIndex++;
356
410
  if (currentTaskIndex >= totalTasks) return;
357
411
  try {
358
412
  const result = await tasks[currentTaskIndex]();
359
413
  if (signal?.aborted) {
414
+ rejected = true;
360
415
  reject(new Error("Aborted"));
361
416
  return;
362
417
  }
@@ -372,6 +427,7 @@ async function runWithConcurrency(tasks, options = {}) {
372
427
  }
373
428
  }
374
429
  } catch (error) {
430
+ rejected = true;
375
431
  reject(error);
376
432
  return;
377
433
  }
@@ -387,6 +443,7 @@ async function runWithConcurrency(tasks, options = {}) {
387
443
  }
388
444
  if (signal) {
389
445
  signal.addEventListener("abort", () => {
446
+ rejected = true;
390
447
  reject(new Error("Aborted"));
391
448
  }, {
392
449
  once: true
@@ -403,5 +460,24 @@ function optionalRequire(name) {
403
460
  }
404
461
  }
405
462
  __name(optionalRequire, "optionalRequire");
463
+ async function raceWithValue(promises) {
464
+ return new Promise((resolve, reject) => {
465
+ let rejectedCount = 0;
466
+ let lastError;
467
+ promises.forEach((p, index) => {
468
+ p.then((value) => resolve({
469
+ value,
470
+ index
471
+ })).catch((err) => {
472
+ rejectedCount++;
473
+ lastError = err;
474
+ if (rejectedCount === promises.length) {
475
+ reject(lastError);
476
+ }
477
+ });
478
+ });
479
+ });
480
+ }
481
+ __name(raceWithValue, "raceWithValue");
406
482
 
407
- export { CircuitBreakerOpenError, CircuitBreakerState, abortable, circuitBreaker, createDeferred, createTaskQueue, debounce, memoizeAsync, optionalRequire, rateLimit, retry, runInBatches, runInSeries, runWithConcurrency, settleAll, singletonAsync, sleep, throttle, waterfall, withTimeout };
483
+ export { CircuitBreakerOpenError, CircuitBreakerState, abortable, circuitBreaker, createDeferred, createTaskQueue, debounce, memoizeAsync, optionalRequire, raceWithValue, rateLimit, retry, runInBatches, runInSeries, runWithConcurrency, settleAll, singletonAsync, sleep, throttle, waterfall, withTimeout };
package/cache/index.cjs CHANGED
@@ -1,7 +1,7 @@
1
1
  /*
2
2
  * The MIT License
3
3
  *
4
- * Copyright (c) 2025 Catbee Technologies. https://catbee.in/license
4
+ * Copyright (c) 2026 Catbee Technologies. https://catbee.in/license
5
5
  *
6
6
  * Permission is hereby granted, free of charge, to any person obtaining a copy
7
7
  * of this software and associated documentation files (the "Software"), to deal
@@ -40,7 +40,7 @@ var TTLCache = class {
40
40
  * @param options - Configuration options for the cache
41
41
  */
42
42
  constructor(options = {}) {
43
- this.ttlMs = options.ttlMs ?? config.defaultCatbeeConfig.cache.defaultTtl;
43
+ this.ttlMs = options.ttlMs ?? config.getCatbeeGlobalConfig().cache.defaultTtl;
44
44
  this.maxSize = options.maxSize;
45
45
  const autoCleanupMs = options.autoCleanupMs;
46
46
  if (autoCleanupMs && autoCleanupMs > 0) {