@catbee/utils 0.0.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.
Files changed (183) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +295 -0
  3. package/build/esm/config.d.ts +22 -0
  4. package/build/esm/config.js +21 -0
  5. package/build/esm/config.js.map +1 -0
  6. package/build/esm/index.d.ts +19 -0
  7. package/build/esm/index.js +19 -0
  8. package/build/esm/index.js.map +1 -0
  9. package/build/esm/types/api-response.d.ts +44 -0
  10. package/build/esm/types/api-response.js +2 -0
  11. package/build/esm/types/api-response.js.map +1 -0
  12. package/build/esm/utils/array.utils.d.ts +105 -0
  13. package/build/esm/utils/array.utils.js +232 -0
  14. package/build/esm/utils/array.utils.js.map +1 -0
  15. package/build/esm/utils/async.utils.d.ts +119 -0
  16. package/build/esm/utils/async.utils.js +474 -0
  17. package/build/esm/utils/async.utils.js.map +1 -0
  18. package/build/esm/utils/cache.utils.d.ts +90 -0
  19. package/build/esm/utils/cache.utils.js +294 -0
  20. package/build/esm/utils/cache.utils.js.map +1 -0
  21. package/build/esm/utils/context-store.utils.d.ts +85 -0
  22. package/build/esm/utils/context-store.utils.js +99 -0
  23. package/build/esm/utils/context-store.utils.js.map +1 -0
  24. package/build/esm/utils/crypto.utils.d.ts +58 -0
  25. package/build/esm/utils/crypto.utils.js +76 -0
  26. package/build/esm/utils/crypto.utils.js.map +1 -0
  27. package/build/esm/utils/dir.utils.d.ts +75 -0
  28. package/build/esm/utils/dir.utils.js +400 -0
  29. package/build/esm/utils/dir.utils.js.map +1 -0
  30. package/build/esm/utils/env.utils.d.ts +131 -0
  31. package/build/esm/utils/env.utils.js +218 -0
  32. package/build/esm/utils/env.utils.js.map +1 -0
  33. package/build/esm/utils/exception.utils.d.ts +114 -0
  34. package/build/esm/utils/exception.utils.js +217 -0
  35. package/build/esm/utils/exception.utils.js.map +1 -0
  36. package/build/esm/utils/fs.utils.d.ts +32 -0
  37. package/build/esm/utils/fs.utils.js +140 -0
  38. package/build/esm/utils/fs.utils.js.map +1 -0
  39. package/build/esm/utils/http-status-codes.d.ts +357 -0
  40. package/build/esm/utils/http-status-codes.js +358 -0
  41. package/build/esm/utils/http-status-codes.js.map +1 -0
  42. package/build/esm/utils/id.utils.d.ts +35 -0
  43. package/build/esm/utils/id.utils.js +55 -0
  44. package/build/esm/utils/id.utils.js.map +1 -0
  45. package/build/esm/utils/logger.utils.d.ts +15 -0
  46. package/build/esm/utils/logger.utils.js +59 -0
  47. package/build/esm/utils/logger.utils.js.map +1 -0
  48. package/build/esm/utils/obj.utils.d.ts +55 -0
  49. package/build/esm/utils/obj.utils.js +121 -0
  50. package/build/esm/utils/obj.utils.js.map +1 -0
  51. package/build/esm/utils/response.utils.d.ts +48 -0
  52. package/build/esm/utils/response.utils.js +80 -0
  53. package/build/esm/utils/response.utils.js.map +1 -0
  54. package/build/esm/utils/string.utils.d.ts +37 -0
  55. package/build/esm/utils/string.utils.js +56 -0
  56. package/build/esm/utils/string.utils.js.map +1 -0
  57. package/build/esm/utils/url.utils.d.ts +24 -0
  58. package/build/esm/utils/url.utils.js +73 -0
  59. package/build/esm/utils/url.utils.js.map +1 -0
  60. package/build/esm/utils/validate.utils.d.ts +60 -0
  61. package/build/esm/utils/validate.utils.js +121 -0
  62. package/build/esm/utils/validate.utils.js.map +1 -0
  63. package/build/esnext/config.d.ts +22 -0
  64. package/build/esnext/config.js +21 -0
  65. package/build/esnext/config.js.map +1 -0
  66. package/build/esnext/index.d.ts +19 -0
  67. package/build/esnext/index.js +19 -0
  68. package/build/esnext/index.js.map +1 -0
  69. package/build/esnext/types/api-response.d.ts +44 -0
  70. package/build/esnext/types/api-response.js +2 -0
  71. package/build/esnext/types/api-response.js.map +1 -0
  72. package/build/esnext/utils/array.utils.d.ts +105 -0
  73. package/build/esnext/utils/array.utils.js +203 -0
  74. package/build/esnext/utils/array.utils.js.map +1 -0
  75. package/build/esnext/utils/async.utils.d.ts +119 -0
  76. package/build/esnext/utils/async.utils.js +291 -0
  77. package/build/esnext/utils/async.utils.js.map +1 -0
  78. package/build/esnext/utils/cache.utils.d.ts +90 -0
  79. package/build/esnext/utils/cache.utils.js +142 -0
  80. package/build/esnext/utils/cache.utils.js.map +1 -0
  81. package/build/esnext/utils/context-store.utils.d.ts +85 -0
  82. package/build/esnext/utils/context-store.utils.js +95 -0
  83. package/build/esnext/utils/context-store.utils.js.map +1 -0
  84. package/build/esnext/utils/crypto.utils.d.ts +58 -0
  85. package/build/esnext/utils/crypto.utils.js +72 -0
  86. package/build/esnext/utils/crypto.utils.js.map +1 -0
  87. package/build/esnext/utils/dir.utils.d.ts +75 -0
  88. package/build/esnext/utils/dir.utils.js +150 -0
  89. package/build/esnext/utils/dir.utils.js.map +1 -0
  90. package/build/esnext/utils/env.utils.d.ts +131 -0
  91. package/build/esnext/utils/env.utils.js +211 -0
  92. package/build/esnext/utils/env.utils.js.map +1 -0
  93. package/build/esnext/utils/exception.utils.d.ts +114 -0
  94. package/build/esnext/utils/exception.utils.js +148 -0
  95. package/build/esnext/utils/exception.utils.js.map +1 -0
  96. package/build/esnext/utils/fs.utils.d.ts +32 -0
  97. package/build/esnext/utils/fs.utils.js +62 -0
  98. package/build/esnext/utils/fs.utils.js.map +1 -0
  99. package/build/esnext/utils/http-status-codes.d.ts +357 -0
  100. package/build/esnext/utils/http-status-codes.js +358 -0
  101. package/build/esnext/utils/http-status-codes.js.map +1 -0
  102. package/build/esnext/utils/id.utils.d.ts +35 -0
  103. package/build/esnext/utils/id.utils.js +53 -0
  104. package/build/esnext/utils/id.utils.js.map +1 -0
  105. package/build/esnext/utils/logger.utils.d.ts +15 -0
  106. package/build/esnext/utils/logger.utils.js +59 -0
  107. package/build/esnext/utils/logger.utils.js.map +1 -0
  108. package/build/esnext/utils/obj.utils.d.ts +55 -0
  109. package/build/esnext/utils/obj.utils.js +94 -0
  110. package/build/esnext/utils/obj.utils.js.map +1 -0
  111. package/build/esnext/utils/response.utils.d.ts +48 -0
  112. package/build/esnext/utils/response.utils.js +58 -0
  113. package/build/esnext/utils/response.utils.js.map +1 -0
  114. package/build/esnext/utils/string.utils.d.ts +37 -0
  115. package/build/esnext/utils/string.utils.js +46 -0
  116. package/build/esnext/utils/string.utils.js.map +1 -0
  117. package/build/esnext/utils/url.utils.d.ts +24 -0
  118. package/build/esnext/utils/url.utils.js +35 -0
  119. package/build/esnext/utils/url.utils.js.map +1 -0
  120. package/build/esnext/utils/validate.utils.d.ts +60 -0
  121. package/build/esnext/utils/validate.utils.js +105 -0
  122. package/build/esnext/utils/validate.utils.js.map +1 -0
  123. package/build/src/config.d.ts +22 -0
  124. package/build/src/config.js +24 -0
  125. package/build/src/config.js.map +1 -0
  126. package/build/src/index.d.ts +19 -0
  127. package/build/src/index.js +35 -0
  128. package/build/src/index.js.map +1 -0
  129. package/build/src/types/api-response.d.ts +44 -0
  130. package/build/src/types/api-response.js +3 -0
  131. package/build/src/types/api-response.js.map +1 -0
  132. package/build/src/utils/array.utils.d.ts +105 -0
  133. package/build/src/utils/array.utils.js +216 -0
  134. package/build/src/utils/array.utils.js.map +1 -0
  135. package/build/src/utils/async.utils.d.ts +119 -0
  136. package/build/src/utils/async.utils.js +304 -0
  137. package/build/src/utils/async.utils.js.map +1 -0
  138. package/build/src/utils/cache.utils.d.ts +90 -0
  139. package/build/src/utils/cache.utils.js +146 -0
  140. package/build/src/utils/cache.utils.js.map +1 -0
  141. package/build/src/utils/context-store.utils.d.ts +85 -0
  142. package/build/src/utils/context-store.utils.js +100 -0
  143. package/build/src/utils/context-store.utils.js.map +1 -0
  144. package/build/src/utils/crypto.utils.d.ts +58 -0
  145. package/build/src/utils/crypto.utils.js +82 -0
  146. package/build/src/utils/crypto.utils.js.map +1 -0
  147. package/build/src/utils/dir.utils.d.ts +75 -0
  148. package/build/src/utils/dir.utils.js +164 -0
  149. package/build/src/utils/dir.utils.js.map +1 -0
  150. package/build/src/utils/env.utils.d.ts +131 -0
  151. package/build/src/utils/env.utils.js +215 -0
  152. package/build/src/utils/env.utils.js.map +1 -0
  153. package/build/src/utils/exception.utils.d.ts +114 -0
  154. package/build/src/utils/exception.utils.js +162 -0
  155. package/build/src/utils/exception.utils.js.map +1 -0
  156. package/build/src/utils/fs.utils.d.ts +32 -0
  157. package/build/src/utils/fs.utils.js +71 -0
  158. package/build/src/utils/fs.utils.js.map +1 -0
  159. package/build/src/utils/http-status-codes.d.ts +357 -0
  160. package/build/src/utils/http-status-codes.js +361 -0
  161. package/build/src/utils/http-status-codes.js.map +1 -0
  162. package/build/src/utils/id.utils.d.ts +35 -0
  163. package/build/src/utils/id.utils.js +60 -0
  164. package/build/src/utils/id.utils.js.map +1 -0
  165. package/build/src/utils/logger.utils.d.ts +15 -0
  166. package/build/src/utils/logger.utils.js +96 -0
  167. package/build/src/utils/logger.utils.js.map +1 -0
  168. package/build/src/utils/obj.utils.d.ts +55 -0
  169. package/build/src/utils/obj.utils.js +103 -0
  170. package/build/src/utils/obj.utils.js.map +1 -0
  171. package/build/src/utils/response.utils.d.ts +48 -0
  172. package/build/src/utils/response.utils.js +63 -0
  173. package/build/src/utils/response.utils.js.map +1 -0
  174. package/build/src/utils/string.utils.d.ts +37 -0
  175. package/build/src/utils/string.utils.js +54 -0
  176. package/build/src/utils/string.utils.js.map +1 -0
  177. package/build/src/utils/url.utils.d.ts +24 -0
  178. package/build/src/utils/url.utils.js +39 -0
  179. package/build/src/utils/url.utils.js.map +1 -0
  180. package/build/src/utils/validate.utils.d.ts +60 -0
  181. package/build/src/utils/validate.utils.js +115 -0
  182. package/build/src/utils/validate.utils.js.map +1 -0
  183. package/package.json +80 -0
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Delays execution for a specified number of milliseconds.
3
+ *
4
+ * @param {number} ms - The number of milliseconds to sleep.
5
+ * @returns {Promise<void>} A Promise that resolves after the given time.
6
+ */
7
+ export declare const sleep: (ms: number) => Promise<void>;
8
+ /**
9
+ * Creates a debounced version of a function that delays its execution.
10
+ * Provides `.cancel()` and `.flush()` methods.
11
+ *
12
+ * @template T
13
+ * @param {T} fn - The function to debounce.
14
+ * @param {number} delay - Delay in milliseconds.
15
+ * @returns {T & { cancel: () => void; flush: () => void }} A debounced function.
16
+ */
17
+ export declare function debounce<T extends (...args: any[]) => void>(fn: T, delay: number): {
18
+ (...args: Parameters<T>): void;
19
+ cancel(): void;
20
+ flush(): void;
21
+ } & {
22
+ cancel: () => void;
23
+ flush: () => void;
24
+ };
25
+ /**
26
+ * Creates a throttled version of a function that limits its execution rate.
27
+ * Allows control over leading/trailing invocation.
28
+ *
29
+ * @template T
30
+ * @param {T} fn - The function to throttle.
31
+ * @param {number} limit - Minimum time between calls in milliseconds.
32
+ * @param {{ leading?: boolean, trailing?: boolean }} [opts] - Options for leading/trailing edge throttling.
33
+ * @returns {(...args: Parameters<T>) => void} A throttled function.
34
+ */
35
+ export declare function throttle<T extends (...args: any[]) => void>(fn: T, limit: number, opts?: {
36
+ leading?: boolean;
37
+ trailing?: boolean;
38
+ }): (...args: Parameters<T>) => void;
39
+ /**
40
+ * Retries an asynchronous function a given number of times with optional delay/backoff.
41
+ *
42
+ * @template T
43
+ * @param {() => Promise<T>} fn - The async function to retry.
44
+ * @param {number} [retries=3] - Number of retry attempts.
45
+ * @param {number} [delay=500] - Delay in milliseconds between retries.
46
+ * @param {boolean} [backoff=false] - Use exponential backoff between attempts.
47
+ * @param {(error: unknown, attempt: number) => void} [onRetry] - Callback for each retry attempt.
48
+ * @returns {Promise<T>} The result of the async function if successful.
49
+ * @throws {*} The last encountered error if all retries fail.
50
+ */
51
+ export declare function retry<T>(fn: () => Promise<T>, retries?: number, delay?: number, backoff?: boolean, onRetry?: (error: unknown, attempt: number) => void): Promise<T>;
52
+ /**
53
+ * Wraps a promise and rejects it if it doesn't resolve within the specified timeout.
54
+ *
55
+ * @template T
56
+ * @param {Promise<T>} promise - The original promise.
57
+ * @param {number} ms - Timeout in milliseconds.
58
+ * @param {string} [message="Operation timed out"] - Optional timeout message.
59
+ * @returns {Promise<T>} A promise that resolves or rejects within the timeout.
60
+ */
61
+ export declare function withTimeout<T>(promise: Promise<T>, ms: number, message?: string): Promise<T>;
62
+ /**
63
+ * Executes async tasks in true batches.
64
+ * Each batch runs in parallel, but batches run sequentially.
65
+ * All tasks in a batch start at the same time, next batch waits for full completion.
66
+ * NOTE: For more granular concurrency, use a "queue" or "pooled" approach.
67
+ *
68
+ * @template T
69
+ * @param {Array<() => Promise<T>>} tasks - An array of functions that return Promises.
70
+ * @param {number} limit - Number of tasks to run in parallel per batch.
71
+ * @returns {Promise<T[]>} A promise that resolves to an array of resolved values.
72
+ */
73
+ export declare function runInBatches<T>(tasks: (() => Promise<T>)[], limit: number): Promise<T[]>;
74
+ /**
75
+ * Wraps a function and ensures it is only called once at a time.
76
+ * Calls made while one is in progress will wait for the same Promise.
77
+ * Optionally, new calls can be dropped while in progress (drop=true).
78
+ *
79
+ * @template TArgs
80
+ * @template TResult
81
+ * @param {(...args: TArgs) => Promise<TResult>} fn - The async function to wrap.
82
+ * @param {boolean} [drop=false] - If true, new calls while one is pending are rejected.
83
+ * @returns {(...args: TArgs) => Promise<TResult>} A wrapped function with singleton behavior.
84
+ */
85
+ export declare function singletonAsync<TArgs extends unknown[], TResult>(fn: (...args: TArgs) => Promise<TResult>, drop?: boolean): (...args: TArgs) => Promise<TResult>;
86
+ /**
87
+ * Resolves a list of async tasks in parallel, returning both resolved and rejected results.
88
+ *
89
+ * @template T
90
+ * @param {Array<() => Promise<T>>} tasks - Array of promise-returning functions.
91
+ * @returns {Promise<PromiseSettledResult<T>[]>} Results including status and value/reason.
92
+ */
93
+ export declare function settleAll<T>(tasks: (() => Promise<T>)[]): Promise<PromiseSettledResult<T>[]>;
94
+ export interface TaskQueue {
95
+ <T>(taskFn: () => Promise<T>): Promise<T>;
96
+ pause: () => void;
97
+ resume: () => void;
98
+ readonly length: number;
99
+ readonly isPaused: boolean;
100
+ }
101
+ /**
102
+ * A simple task queue that executes async tasks with a concurrency limit.
103
+ * Exposes pause, resume, and queue length getters.
104
+ *
105
+ * @param {number} limit - Maximum number of concurrent tasks.
106
+ * @returns {function & { pause: () => void, resume: () => void, length: number, isPaused: boolean }}
107
+ * Enqueue function plus queue controls.
108
+ */
109
+ export declare function createTaskQueue(limit: number): TaskQueue;
110
+ /**
111
+ * Executes async functions sequentially and collects results.
112
+ * Useful when order matters or tasks depend on each other.
113
+ *
114
+ * @template T
115
+ * @param {Array<() => Promise<T>>} tasks - Array of promise-returning functions.
116
+ * @returns {Promise<T[]>} Array of resolved values.
117
+ */
118
+ export declare function runInSeries<T>(tasks: (() => Promise<T>)[]): Promise<T[]>;
119
+ //# sourceMappingURL=async.utils.d.ts.map
@@ -0,0 +1,291 @@
1
+ /**
2
+ * Delays execution for a specified number of milliseconds.
3
+ *
4
+ * @param {number} ms - The number of milliseconds to sleep.
5
+ * @returns {Promise<void>} A Promise that resolves after the given time.
6
+ */
7
+ export const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
8
+ /**
9
+ * Creates a debounced version of a function that delays its execution.
10
+ * Provides `.cancel()` and `.flush()` methods.
11
+ *
12
+ * @template T
13
+ * @param {T} fn - The function to debounce.
14
+ * @param {number} delay - Delay in milliseconds.
15
+ * @returns {T & { cancel: () => void; flush: () => void }} A debounced function.
16
+ */
17
+ export function debounce(fn, delay) {
18
+ let timer = null;
19
+ let pendingArgs = null;
20
+ function debounced(...args) {
21
+ pendingArgs = args;
22
+ if (timer)
23
+ clearTimeout(timer);
24
+ timer = setTimeout(() => {
25
+ fn(...pendingArgs);
26
+ timer = null;
27
+ }, delay);
28
+ }
29
+ debounced.cancel = () => {
30
+ if (timer)
31
+ clearTimeout(timer);
32
+ timer = null;
33
+ pendingArgs = null;
34
+ };
35
+ debounced.flush = () => {
36
+ if (timer) {
37
+ clearTimeout(timer);
38
+ fn(...pendingArgs);
39
+ timer = null;
40
+ pendingArgs = null;
41
+ }
42
+ };
43
+ return debounced;
44
+ }
45
+ /**
46
+ * Creates a throttled version of a function that limits its execution rate.
47
+ * Allows control over leading/trailing invocation.
48
+ *
49
+ * @template T
50
+ * @param {T} fn - The function to throttle.
51
+ * @param {number} limit - Minimum time between calls in milliseconds.
52
+ * @param {{ leading?: boolean, trailing?: boolean }} [opts] - Options for leading/trailing edge throttling.
53
+ * @returns {(...args: Parameters<T>) => void} A throttled function.
54
+ */
55
+ export function throttle(fn, limit, opts = {
56
+ leading: true,
57
+ trailing: false,
58
+ }) {
59
+ let lastCall = 0;
60
+ let timer = null;
61
+ let savedArgs = null;
62
+ return function (...args) {
63
+ const now = Date.now();
64
+ const { leading = true, trailing = false } = opts;
65
+ if (!lastCall && !leading)
66
+ lastCall = now;
67
+ const remaining = limit - (now - lastCall);
68
+ if (remaining <= 0) {
69
+ if (timer) {
70
+ clearTimeout(timer);
71
+ timer = null;
72
+ }
73
+ lastCall = now;
74
+ fn(...args);
75
+ }
76
+ else if (trailing) {
77
+ savedArgs = args;
78
+ if (!timer) {
79
+ timer = setTimeout(() => {
80
+ lastCall = leading ? Date.now() : 0;
81
+ timer = null;
82
+ if (savedArgs)
83
+ fn(...savedArgs);
84
+ }, remaining);
85
+ }
86
+ }
87
+ };
88
+ }
89
+ /**
90
+ * Retries an asynchronous function a given number of times with optional delay/backoff.
91
+ *
92
+ * @template T
93
+ * @param {() => Promise<T>} fn - The async function to retry.
94
+ * @param {number} [retries=3] - Number of retry attempts.
95
+ * @param {number} [delay=500] - Delay in milliseconds between retries.
96
+ * @param {boolean} [backoff=false] - Use exponential backoff between attempts.
97
+ * @param {(error: unknown, attempt: number) => void} [onRetry] - Callback for each retry attempt.
98
+ * @returns {Promise<T>} The result of the async function if successful.
99
+ * @throws {*} The last encountered error if all retries fail.
100
+ */
101
+ export async function retry(fn, retries = 3, delay = 500, backoff = false, onRetry) {
102
+ for (let i = 0; i < retries; i++) {
103
+ try {
104
+ return await fn();
105
+ }
106
+ catch (e) {
107
+ if (i === retries - 1)
108
+ throw e;
109
+ if (onRetry)
110
+ onRetry(e, i + 1);
111
+ await sleep(backoff ? delay * Math.pow(2, i) : delay);
112
+ }
113
+ }
114
+ throw new Error("Retry failed"); // should never reach here
115
+ }
116
+ /**
117
+ * Wraps a promise and rejects it if it doesn't resolve within the specified timeout.
118
+ *
119
+ * @template T
120
+ * @param {Promise<T>} promise - The original promise.
121
+ * @param {number} ms - Timeout in milliseconds.
122
+ * @param {string} [message="Operation timed out"] - Optional timeout message.
123
+ * @returns {Promise<T>} A promise that resolves or rejects within the timeout.
124
+ */
125
+ export function withTimeout(promise, ms, message = "Operation timed out") {
126
+ return new Promise((resolve, reject) => {
127
+ const timeoutHandle = setTimeout(() => reject(new Error(message)), ms);
128
+ promise
129
+ .then((result) => {
130
+ clearTimeout(timeoutHandle);
131
+ resolve(result);
132
+ })
133
+ .catch((err) => {
134
+ clearTimeout(timeoutHandle);
135
+ reject(err);
136
+ });
137
+ });
138
+ }
139
+ /**
140
+ * Executes async tasks in true batches.
141
+ * Each batch runs in parallel, but batches run sequentially.
142
+ * All tasks in a batch start at the same time, next batch waits for full completion.
143
+ * NOTE: For more granular concurrency, use a "queue" or "pooled" approach.
144
+ *
145
+ * @template T
146
+ * @param {Array<() => Promise<T>>} tasks - An array of functions that return Promises.
147
+ * @param {number} limit - Number of tasks to run in parallel per batch.
148
+ * @returns {Promise<T[]>} A promise that resolves to an array of resolved values.
149
+ */
150
+ export async function runInBatches(tasks, limit) {
151
+ const results = [];
152
+ for (let i = 0; i < tasks.length; i += limit) {
153
+ const batch = tasks.slice(i, i + limit);
154
+ const batchResults = await Promise.all(batch.map((fn) => fn()));
155
+ results.push(...batchResults);
156
+ }
157
+ return results;
158
+ }
159
+ /**
160
+ * Wraps a function and ensures it is only called once at a time.
161
+ * Calls made while one is in progress will wait for the same Promise.
162
+ * Optionally, new calls can be dropped while in progress (drop=true).
163
+ *
164
+ * @template TArgs
165
+ * @template TResult
166
+ * @param {(...args: TArgs) => Promise<TResult>} fn - The async function to wrap.
167
+ * @param {boolean} [drop=false] - If true, new calls while one is pending are rejected.
168
+ * @returns {(...args: TArgs) => Promise<TResult>} A wrapped function with singleton behavior.
169
+ */
170
+ export function singletonAsync(fn, drop = false) {
171
+ let promise = null;
172
+ return async (...args) => {
173
+ if (!promise) {
174
+ promise = fn(...args).finally(() => {
175
+ promise = null;
176
+ });
177
+ }
178
+ else if (drop) {
179
+ return Promise.reject(new Error("Busy: function already running"));
180
+ }
181
+ return promise;
182
+ };
183
+ }
184
+ /**
185
+ * Resolves a list of async tasks in parallel, returning both resolved and rejected results.
186
+ *
187
+ * @template T
188
+ * @param {Array<() => Promise<T>>} tasks - Array of promise-returning functions.
189
+ * @returns {Promise<PromiseSettledResult<T>[]>} Results including status and value/reason.
190
+ */
191
+ export async function settleAll(tasks) {
192
+ return Promise.allSettled(tasks.map((task) => task()));
193
+ }
194
+ /**
195
+ * A simple task queue that executes async tasks with a concurrency limit.
196
+ * Exposes pause, resume, and queue length getters.
197
+ *
198
+ * @param {number} limit - Maximum number of concurrent tasks.
199
+ * @returns {function & { pause: () => void, resume: () => void, length: number, isPaused: boolean }}
200
+ * Enqueue function plus queue controls.
201
+ */
202
+ export function createTaskQueue(limit) {
203
+ const queue = [];
204
+ let activeCount = 0;
205
+ let paused = false;
206
+ const state = {
207
+ /**
208
+ * Pause task processing.
209
+ */
210
+ pause() {
211
+ paused = true;
212
+ },
213
+ /**
214
+ * Resume task processing.
215
+ */
216
+ resume() {
217
+ paused = false;
218
+ next();
219
+ },
220
+ /**
221
+ * The current length of the queue.
222
+ * @type {number}
223
+ */
224
+ get length() {
225
+ return queue.length;
226
+ },
227
+ /**
228
+ * Whether the queue is currently paused.
229
+ * @type {boolean}
230
+ */
231
+ get isPaused() {
232
+ return paused;
233
+ },
234
+ };
235
+ const next = () => {
236
+ if (paused || queue.length === 0 || activeCount >= limit)
237
+ return;
238
+ const task = queue.shift();
239
+ activeCount++;
240
+ task().finally(() => {
241
+ activeCount--;
242
+ next();
243
+ });
244
+ };
245
+ /**
246
+ * Enqueues a new async task to the queue.
247
+ *
248
+ * @template T
249
+ * @param {() => Promise<T>} taskFn - The async task function.
250
+ * @returns {Promise<T>} Promise resolving when task completes.
251
+ */
252
+ const enqueue = async function (taskFn) {
253
+ return new Promise((resolve, reject) => {
254
+ queue.push(async () => {
255
+ try {
256
+ const result = await taskFn();
257
+ resolve(result);
258
+ }
259
+ catch (err) {
260
+ reject(err);
261
+ }
262
+ });
263
+ next();
264
+ });
265
+ };
266
+ enqueue.pause = state.pause;
267
+ enqueue.resume = state.resume;
268
+ Object.defineProperty(enqueue, "length", {
269
+ get: () => queue.length,
270
+ });
271
+ Object.defineProperty(enqueue, "isPaused", {
272
+ get: () => paused,
273
+ });
274
+ return enqueue;
275
+ }
276
+ /**
277
+ * Executes async functions sequentially and collects results.
278
+ * Useful when order matters or tasks depend on each other.
279
+ *
280
+ * @template T
281
+ * @param {Array<() => Promise<T>>} tasks - Array of promise-returning functions.
282
+ * @returns {Promise<T[]>} Array of resolved values.
283
+ */
284
+ export async function runInSeries(tasks) {
285
+ const results = [];
286
+ for (const task of tasks) {
287
+ results.push(await task());
288
+ }
289
+ return results;
290
+ }
291
+ //# sourceMappingURL=async.utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"async.utils.js","sourceRoot":"","sources":["../../../src/utils/async.utils.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,MAAM,CAAC,MAAM,KAAK,GAAG,CAAC,EAAU,EAAiB,EAAE,CACjD,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC;AAEpD;;;;;;;;GAQG;AACH,MAAM,UAAU,QAAQ,CACtB,EAAK,EACL,KAAa;IAEb,IAAI,KAAK,GAA0B,IAAI,CAAC;IACxC,IAAI,WAAW,GAAyB,IAAI,CAAC;IAE7C,SAAS,SAAS,CAAC,GAAG,IAAmB;QACvC,WAAW,GAAG,IAAI,CAAC;QACnB,IAAI,KAAK;YAAE,YAAY,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AOG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAC/B,KAA2B;IAE3B,MAAM,OAAO,GAAQ,EAAE,CAAC;IACxB,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,OAAO,CAAC,IAAI,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC;IAC7B,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["/**\n * Delays execution for a specified number of milliseconds.\n *\n * @param {number} ms - The number of milliseconds to sleep.\n * @returns {Promise<void>} A Promise that resolves after the given time.\n */\nexport const sleep = (ms: number): Promise<void> =>\n new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * Creates a debounced version of a function that delays its execution.\n * Provides `.cancel()` and `.flush()` methods.\n *\n * @template T\n * @param {T} fn - The function to debounce.\n * @param {number} delay - Delay in milliseconds.\n * @returns {T & { cancel: () => void; flush: () => void }} A debounced function.\n */\nexport function debounce<T extends (...args: any[]) => void>(\n fn: T,\n delay: number,\n) {\n let timer: NodeJS.Timeout | null = null;\n let pendingArgs: Parameters<T> | null = null;\n\n function debounced(...args: Parameters<T>) {\n pendingArgs = args;\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => {\n fn(...(pendingArgs as Parameters<T>));\n timer = null;\n }, delay);\n }\n\n debounced.cancel = () => {\n if (timer) clearTimeout(timer);\n timer = null;\n pendingArgs = null;\n };\n\n debounced.flush = () => {\n if (timer) {\n clearTimeout(timer);\n fn(...(pendingArgs as Parameters<T>));\n timer = null;\n pendingArgs = null;\n }\n };\n\n return debounced as typeof debounced & {\n cancel: () => void;\n flush: () => void;\n };\n}\n\n/**\n * Creates a throttled version of a function that limits its execution rate.\n * Allows control over leading/trailing invocation.\n *\n * @template T\n * @param {T} fn - The function to throttle.\n * @param {number} limit - Minimum time between calls in milliseconds.\n * @param {{ leading?: boolean, trailing?: boolean }} [opts] - Options for leading/trailing edge throttling.\n * @returns {(...args: Parameters<T>) => void} A throttled function.\n */\nexport function throttle<T extends (...args: any[]) => void>(\n fn: T,\n limit: number,\n opts: { leading?: boolean; trailing?: boolean } = {\n leading: true,\n trailing: false,\n },\n): (...args: Parameters<T>) => void {\n let lastCall = 0;\n let timer: NodeJS.Timeout | null = null;\n let savedArgs: Parameters<T> | null = null;\n\n return function (...args: Parameters<T>) {\n const now = Date.now();\n const { leading = true, trailing = false } = opts;\n\n if (!lastCall && !leading) lastCall = now;\n\n const remaining = limit - (now - lastCall);\n\n if (remaining <= 0) {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n lastCall = now;\n fn(...args);\n } else if (trailing) {\n savedArgs = args;\n if (!timer) {\n timer = setTimeout(() => {\n lastCall = leading ? Date.now() : 0;\n timer = null;\n if (savedArgs) fn(...savedArgs);\n }, remaining);\n }\n }\n };\n}\n\n/**\n * Retries an asynchronous function a given number of times with optional delay/backoff.\n *\n * @template T\n * @param {() => Promise<T>} fn - The async function to retry.\n * @param {number} [retries=3] - Number of retry attempts.\n * @param {number} [delay=500] - Delay in milliseconds between retries.\n * @param {boolean} [backoff=false] - Use exponential backoff between attempts.\n * @param {(error: unknown, attempt: number) => void} [onRetry] - Callback for each retry attempt.\n * @returns {Promise<T>} The result of the async function if successful.\n * @throws {*} The last encountered error if all retries fail.\n */\nexport async function retry<T>(\n fn: () => Promise<T>,\n retries = 3,\n delay = 500,\n backoff = false,\n onRetry?: (error: unknown, attempt: number) => void,\n): Promise<T> {\n for (let i = 0; i < retries; i++) {\n try {\n return await fn();\n } catch (e) {\n if (i === retries - 1) throw e;\n if (onRetry) onRetry(e, i + 1);\n await sleep(backoff ? delay * Math.pow(2, i) : delay);\n }\n }\n throw new Error(\"Retry failed\"); // should never reach here\n}\n\n/**\n * Wraps a promise and rejects it if it doesn't resolve within the specified timeout.\n *\n * @template T\n * @param {Promise<T>} promise - The original promise.\n * @param {number} ms - Timeout in milliseconds.\n * @param {string} [message=\"Operation timed out\"] - Optional timeout message.\n * @returns {Promise<T>} A promise that resolves or rejects within the timeout.\n */\nexport function withTimeout<T>(\n promise: Promise<T>,\n ms: number,\n message = \"Operation timed out\",\n): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const timeoutHandle = setTimeout(() => reject(new Error(message)), ms);\n promise\n .then((result) => {\n clearTimeout(timeoutHandle);\n resolve(result);\n })\n .catch((err) => {\n clearTimeout(timeoutHandle);\n reject(err);\n });\n });\n}\n\n/**\n * Executes async tasks in true batches.\n * Each batch runs in parallel, but batches run sequentially.\n * All tasks in a batch start at the same time, next batch waits for full completion.\n * NOTE: For more granular concurrency, use a \"queue\" or \"pooled\" approach.\n *\n * @template T\n * @param {Array<() => Promise<T>>} tasks - An array of functions that return Promises.\n * @param {number} limit - Number of tasks to run in parallel per batch.\n * @returns {Promise<T[]>} A promise that resolves to an array of resolved values.\n */\nexport async function runInBatches<T>(\n tasks: (() => Promise<T>)[],\n limit: number,\n): Promise<T[]> {\n const results: T[] = [];\n for (let i = 0; i < tasks.length; i += limit) {\n const batch = tasks.slice(i, i + limit);\n const batchResults = await Promise.all(batch.map((fn) => fn()));\n results.push(...batchResults);\n }\n return results;\n}\n\n/**\n * Wraps a function and ensures it is only called once at a time.\n * Calls made while one is in progress will wait for the same Promise.\n * Optionally, new calls can be dropped while in progress (drop=true).\n *\n * @template TArgs\n * @template TResult\n * @param {(...args: TArgs) => Promise<TResult>} fn - The async function to wrap.\n * @param {boolean} [drop=false] - If true, new calls while one is pending are rejected.\n * @returns {(...args: TArgs) => Promise<TResult>} A wrapped function with singleton behavior.\n */\nexport function singletonAsync<TArgs extends unknown[], TResult>(\n fn: (...args: TArgs) => Promise<TResult>,\n drop: boolean = false,\n): (...args: TArgs) => Promise<TResult> {\n let promise: Promise<TResult> | null = null;\n\n return async (...args: TArgs) => {\n if (!promise) {\n promise = fn(...args).finally(() => {\n promise = null;\n });\n } else if (drop) {\n return Promise.reject(new Error(\"Busy: function already running\"));\n }\n return promise;\n };\n}\n\n/**\n * Resolves a list of async tasks in parallel, returning both resolved and rejected results.\n *\n * @template T\n * @param {Array<() => Promise<T>>} tasks - Array of promise-returning functions.\n * @returns {Promise<PromiseSettledResult<T>[]>} Results including status and value/reason.\n */\nexport async function settleAll<T>(\n tasks: (() => Promise<T>)[],\n): Promise<PromiseSettledResult<T>[]> {\n return Promise.allSettled(tasks.map((task) => task()));\n}\n\nexport interface TaskQueue {\n <T>(taskFn: () => Promise<T>): Promise<T>;\n pause: () => void;\n resume: () => void;\n readonly length: number;\n readonly isPaused: boolean;\n}\n\n/**\n * A simple task queue that executes async tasks with a concurrency limit.\n * Exposes pause, resume, and queue length getters.\n *\n * @param {number} limit - Maximum number of concurrent tasks.\n * @returns {function & { pause: () => void, resume: () => void, length: number, isPaused: boolean }}\n * Enqueue function plus queue controls.\n */\nexport function createTaskQueue(limit: number): TaskQueue {\n const queue: (() => Promise<void>)[] = [];\n let activeCount = 0;\n let paused = false;\n\n const state = {\n /**\n * Pause task processing.\n */\n pause() {\n paused = true;\n },\n /**\n * Resume task processing.\n */\n resume() {\n paused = false;\n next();\n },\n /**\n * The current length of the queue.\n * @type {number}\n */\n get length() {\n return queue.length;\n },\n /**\n * Whether the queue is currently paused.\n * @type {boolean}\n */\n get isPaused() {\n return paused;\n },\n };\n\n const next = () => {\n if (paused || queue.length === 0 || activeCount >= limit) return;\n const task = queue.shift()!;\n activeCount++;\n task().finally(() => {\n activeCount--;\n next();\n });\n };\n\n /**\n * Enqueues a new async task to the queue.\n *\n * @template T\n * @param {() => Promise<T>} taskFn - The async task function.\n * @returns {Promise<T>} Promise resolving when task completes.\n */\n const enqueue = async function <T>(taskFn: () => Promise<T>): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n queue.push(async () => {\n try {\n const result = await taskFn();\n resolve(result);\n } catch (err) {\n reject(err);\n }\n });\n next();\n });\n };\n\n enqueue.pause = state.pause;\n enqueue.resume = state.resume;\n Object.defineProperty(enqueue, \"length\", {\n get: () => queue.length,\n });\n Object.defineProperty(enqueue, \"isPaused\", {\n get: () => paused,\n });\n\n return enqueue as TaskQueue;\n}\n\n/**\n * Executes async functions sequentially and collects results.\n * Useful when order matters or tasks depend on each other.\n *\n * @template T\n * @param {Array<() => Promise<T>>} tasks - Array of promise-returning functions.\n * @returns {Promise<T[]>} Array of resolved values.\n */\nexport async function runInSeries<T>(\n tasks: (() => Promise<T>)[],\n): Promise<T[]> {\n const results: T[] = [];\n for (const task of tasks) {\n results.push(await task());\n }\n return results;\n}\n"]}
@@ -0,0 +1,90 @@
1
+ /**
2
+ * An in-memory cache with time-to-live (TTL) support for each entry.
3
+ *
4
+ * @typeParam K - Type of the key.
5
+ * @typeParam V - Type of the value.
6
+ *
7
+ * @example
8
+ * const cache = new TTLCache<string, number>(1000);
9
+ * cache.set("x", 123);
10
+ * const value = cache.get("x"); // 123
11
+ */
12
+ export declare class TTLCache<K, V> {
13
+ private ttlMs;
14
+ private cache;
15
+ /**
16
+ * @param ttlMs - Default time-to-live in milliseconds for cache entries.
17
+ */
18
+ constructor(ttlMs?: number);
19
+ /**
20
+ * Sets a key-value pair in the cache with the default TTL.
21
+ *
22
+ * @param key - The key to set.
23
+ * @param value - The value to associate with the key.
24
+ */
25
+ set(key: K, value: V): void;
26
+ /**
27
+ * Sets a key-value pair in the cache with a custom TTL.
28
+ *
29
+ * @param key - The key to set.
30
+ * @param value - The value to associate with the key.
31
+ * @param ttlMs - Time-to-live in milliseconds.
32
+ */
33
+ setWithTTL(key: K, value: V, ttlMs: number): void;
34
+ /**
35
+ * Retrieves the value for a given key if it hasn't expired.
36
+ *
37
+ * @param key - The key to retrieve.
38
+ * @returns The cached value, or undefined if not found or expired.
39
+ */
40
+ get(key: K): V | undefined;
41
+ /**
42
+ * Checks if the key exists and hasn't expired.
43
+ *
44
+ * @param key - The key to check.
45
+ * @returns `true` if key exists and is valid, otherwise `false`.
46
+ */
47
+ has(key: K): boolean;
48
+ /**
49
+ * Deletes a key from the cache.
50
+ *
51
+ * @param key - The key to delete.
52
+ * @returns `true` if the key existed and was removed, `false` otherwise.
53
+ */
54
+ delete(key: K): boolean;
55
+ /**
56
+ * Clears all entries from the cache.
57
+ */
58
+ clear(): void;
59
+ /**
60
+ * Returns the number of entries currently in the cache (includes expired entries until next access/cleanup).
61
+ *
62
+ * @returns Number of items in the cache (may include expired keys).
63
+ */
64
+ size(): number;
65
+ /**
66
+ * Removes all expired entries from the cache.
67
+ *
68
+ * @returns Number of entries removed.
69
+ */
70
+ cleanup(): number;
71
+ /**
72
+ * Returns an iterator of all current valid [key, value] pairs.
73
+ *
74
+ * @returns IterableIterator<[K, V]>
75
+ */
76
+ entries(): IterableIterator<[K, V]>;
77
+ /**
78
+ * Returns an iterator of all current valid keys.
79
+ *
80
+ * @returns IterableIterator<K>
81
+ */
82
+ keys(): IterableIterator<K>;
83
+ /**
84
+ * Returns an iterator of all current valid values.
85
+ *
86
+ * @returns IterableIterator<V>
87
+ */
88
+ values(): IterableIterator<V>;
89
+ }
90
+ //# sourceMappingURL=cache.utils.d.ts.map
@@ -0,0 +1,142 @@
1
+ /**
2
+ * An in-memory cache with time-to-live (TTL) support for each entry.
3
+ *
4
+ * @typeParam K - Type of the key.
5
+ * @typeParam V - Type of the value.
6
+ *
7
+ * @example
8
+ * const cache = new TTLCache<string, number>(1000);
9
+ * cache.set("x", 123);
10
+ * const value = cache.get("x"); // 123
11
+ */
12
+ export class TTLCache {
13
+ /**
14
+ * @param ttlMs - Default time-to-live in milliseconds for cache entries.
15
+ */
16
+ constructor(ttlMs = 5 * 60 * 1000) {
17
+ this.ttlMs = ttlMs;
18
+ this.cache = new Map();
19
+ }
20
+ /**
21
+ * Sets a key-value pair in the cache with the default TTL.
22
+ *
23
+ * @param key - The key to set.
24
+ * @param value - The value to associate with the key.
25
+ */
26
+ set(key, value) {
27
+ const expiresAt = Date.now() + this.ttlMs;
28
+ this.cache.set(key, { value, expiresAt });
29
+ }
30
+ /**
31
+ * Sets a key-value pair in the cache with a custom TTL.
32
+ *
33
+ * @param key - The key to set.
34
+ * @param value - The value to associate with the key.
35
+ * @param ttlMs - Time-to-live in milliseconds.
36
+ */
37
+ setWithTTL(key, value, ttlMs) {
38
+ const expiresAt = Date.now() + ttlMs;
39
+ this.cache.set(key, { value, expiresAt });
40
+ }
41
+ /**
42
+ * Retrieves the value for a given key if it hasn't expired.
43
+ *
44
+ * @param key - The key to retrieve.
45
+ * @returns The cached value, or undefined if not found or expired.
46
+ */
47
+ get(key) {
48
+ const entry = this.cache.get(key);
49
+ if (!entry)
50
+ return undefined;
51
+ if (Date.now() > entry.expiresAt) {
52
+ this.cache.delete(key);
53
+ return undefined;
54
+ }
55
+ return entry.value;
56
+ }
57
+ /**
58
+ * Checks if the key exists and hasn't expired.
59
+ *
60
+ * @param key - The key to check.
61
+ * @returns `true` if key exists and is valid, otherwise `false`.
62
+ */
63
+ has(key) {
64
+ return this.get(key) !== undefined;
65
+ }
66
+ /**
67
+ * Deletes a key from the cache.
68
+ *
69
+ * @param key - The key to delete.
70
+ * @returns `true` if the key existed and was removed, `false` otherwise.
71
+ */
72
+ delete(key) {
73
+ return this.cache.delete(key);
74
+ }
75
+ /**
76
+ * Clears all entries from the cache.
77
+ */
78
+ clear() {
79
+ this.cache.clear();
80
+ }
81
+ /**
82
+ * Returns the number of entries currently in the cache (includes expired entries until next access/cleanup).
83
+ *
84
+ * @returns Number of items in the cache (may include expired keys).
85
+ */
86
+ size() {
87
+ return this.cache.size;
88
+ }
89
+ /**
90
+ * Removes all expired entries from the cache.
91
+ *
92
+ * @returns Number of entries removed.
93
+ */
94
+ cleanup() {
95
+ let removed = 0;
96
+ const now = Date.now();
97
+ for (const [key, entry] of this.cache.entries()) {
98
+ if (now > entry.expiresAt) {
99
+ this.cache.delete(key);
100
+ removed++;
101
+ }
102
+ }
103
+ return removed;
104
+ }
105
+ /**
106
+ * Returns an iterator of all current valid [key, value] pairs.
107
+ *
108
+ * @returns IterableIterator<[K, V]>
109
+ */
110
+ *entries() {
111
+ for (const [key, entry] of this.cache.entries()) {
112
+ if (Date.now() <= entry.expiresAt) {
113
+ yield [key, entry.value];
114
+ }
115
+ }
116
+ }
117
+ /**
118
+ * Returns an iterator of all current valid keys.
119
+ *
120
+ * @returns IterableIterator<K>
121
+ */
122
+ *keys() {
123
+ for (const [key, entry] of this.cache.entries()) {
124
+ if (Date.now() <= entry.expiresAt) {
125
+ yield key;
126
+ }
127
+ }
128
+ }
129
+ /**
130
+ * Returns an iterator of all current valid values.
131
+ *
132
+ * @returns IterableIterator<V>
133
+ */
134
+ *values() {
135
+ for (const entry of this.cache.values()) {
136
+ if (Date.now() <= entry.expiresAt) {
137
+ yield entry.value;
138
+ }
139
+ }
140
+ }
141
+ }
142
+ //# sourceMappingURL=cache.utils.js.map