@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,304 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.sleep = void 0;
4
+ exports.debounce = debounce;
5
+ exports.throttle = throttle;
6
+ exports.retry = retry;
7
+ exports.withTimeout = withTimeout;
8
+ exports.runInBatches = runInBatches;
9
+ exports.singletonAsync = singletonAsync;
10
+ exports.settleAll = settleAll;
11
+ exports.createTaskQueue = createTaskQueue;
12
+ exports.runInSeries = runInSeries;
13
+ /**
14
+ * Delays execution for a specified number of milliseconds.
15
+ *
16
+ * @param {number} ms - The number of milliseconds to sleep.
17
+ * @returns {Promise<void>} A Promise that resolves after the given time.
18
+ */
19
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
20
+ exports.sleep = sleep;
21
+ /**
22
+ * Creates a debounced version of a function that delays its execution.
23
+ * Provides `.cancel()` and `.flush()` methods.
24
+ *
25
+ * @template T
26
+ * @param {T} fn - The function to debounce.
27
+ * @param {number} delay - Delay in milliseconds.
28
+ * @returns {T & { cancel: () => void; flush: () => void }} A debounced function.
29
+ */
30
+ function debounce(fn, delay) {
31
+ let timer = null;
32
+ let pendingArgs = null;
33
+ function debounced(...args) {
34
+ pendingArgs = args;
35
+ if (timer)
36
+ clearTimeout(timer);
37
+ timer = setTimeout(() => {
38
+ fn(...pendingArgs);
39
+ timer = null;
40
+ }, delay);
41
+ }
42
+ debounced.cancel = () => {
43
+ if (timer)
44
+ clearTimeout(timer);
45
+ timer = null;
46
+ pendingArgs = null;
47
+ };
48
+ debounced.flush = () => {
49
+ if (timer) {
50
+ clearTimeout(timer);
51
+ fn(...pendingArgs);
52
+ timer = null;
53
+ pendingArgs = null;
54
+ }
55
+ };
56
+ return debounced;
57
+ }
58
+ /**
59
+ * Creates a throttled version of a function that limits its execution rate.
60
+ * Allows control over leading/trailing invocation.
61
+ *
62
+ * @template T
63
+ * @param {T} fn - The function to throttle.
64
+ * @param {number} limit - Minimum time between calls in milliseconds.
65
+ * @param {{ leading?: boolean, trailing?: boolean }} [opts] - Options for leading/trailing edge throttling.
66
+ * @returns {(...args: Parameters<T>) => void} A throttled function.
67
+ */
68
+ function throttle(fn, limit, opts = {
69
+ leading: true,
70
+ trailing: false,
71
+ }) {
72
+ let lastCall = 0;
73
+ let timer = null;
74
+ let savedArgs = null;
75
+ return function (...args) {
76
+ const now = Date.now();
77
+ const { leading = true, trailing = false } = opts;
78
+ if (!lastCall && !leading)
79
+ lastCall = now;
80
+ const remaining = limit - (now - lastCall);
81
+ if (remaining <= 0) {
82
+ if (timer) {
83
+ clearTimeout(timer);
84
+ timer = null;
85
+ }
86
+ lastCall = now;
87
+ fn(...args);
88
+ }
89
+ else if (trailing) {
90
+ savedArgs = args;
91
+ if (!timer) {
92
+ timer = setTimeout(() => {
93
+ lastCall = leading ? Date.now() : 0;
94
+ timer = null;
95
+ if (savedArgs)
96
+ fn(...savedArgs);
97
+ }, remaining);
98
+ }
99
+ }
100
+ };
101
+ }
102
+ /**
103
+ * Retries an asynchronous function a given number of times with optional delay/backoff.
104
+ *
105
+ * @template T
106
+ * @param {() => Promise<T>} fn - The async function to retry.
107
+ * @param {number} [retries=3] - Number of retry attempts.
108
+ * @param {number} [delay=500] - Delay in milliseconds between retries.
109
+ * @param {boolean} [backoff=false] - Use exponential backoff between attempts.
110
+ * @param {(error: unknown, attempt: number) => void} [onRetry] - Callback for each retry attempt.
111
+ * @returns {Promise<T>} The result of the async function if successful.
112
+ * @throws {*} The last encountered error if all retries fail.
113
+ */
114
+ async function retry(fn, retries = 3, delay = 500, backoff = false, onRetry) {
115
+ for (let i = 0; i < retries; i++) {
116
+ try {
117
+ return await fn();
118
+ }
119
+ catch (e) {
120
+ if (i === retries - 1)
121
+ throw e;
122
+ if (onRetry)
123
+ onRetry(e, i + 1);
124
+ await (0, exports.sleep)(backoff ? delay * Math.pow(2, i) : delay);
125
+ }
126
+ }
127
+ throw new Error("Retry failed"); // should never reach here
128
+ }
129
+ /**
130
+ * Wraps a promise and rejects it if it doesn't resolve within the specified timeout.
131
+ *
132
+ * @template T
133
+ * @param {Promise<T>} promise - The original promise.
134
+ * @param {number} ms - Timeout in milliseconds.
135
+ * @param {string} [message="Operation timed out"] - Optional timeout message.
136
+ * @returns {Promise<T>} A promise that resolves or rejects within the timeout.
137
+ */
138
+ function withTimeout(promise, ms, message = "Operation timed out") {
139
+ return new Promise((resolve, reject) => {
140
+ const timeoutHandle = setTimeout(() => reject(new Error(message)), ms);
141
+ promise
142
+ .then((result) => {
143
+ clearTimeout(timeoutHandle);
144
+ resolve(result);
145
+ })
146
+ .catch((err) => {
147
+ clearTimeout(timeoutHandle);
148
+ reject(err);
149
+ });
150
+ });
151
+ }
152
+ /**
153
+ * Executes async tasks in true batches.
154
+ * Each batch runs in parallel, but batches run sequentially.
155
+ * All tasks in a batch start at the same time, next batch waits for full completion.
156
+ * NOTE: For more granular concurrency, use a "queue" or "pooled" approach.
157
+ *
158
+ * @template T
159
+ * @param {Array<() => Promise<T>>} tasks - An array of functions that return Promises.
160
+ * @param {number} limit - Number of tasks to run in parallel per batch.
161
+ * @returns {Promise<T[]>} A promise that resolves to an array of resolved values.
162
+ */
163
+ async function runInBatches(tasks, limit) {
164
+ const results = [];
165
+ for (let i = 0; i < tasks.length; i += limit) {
166
+ const batch = tasks.slice(i, i + limit);
167
+ const batchResults = await Promise.all(batch.map((fn) => fn()));
168
+ results.push(...batchResults);
169
+ }
170
+ return results;
171
+ }
172
+ /**
173
+ * Wraps a function and ensures it is only called once at a time.
174
+ * Calls made while one is in progress will wait for the same Promise.
175
+ * Optionally, new calls can be dropped while in progress (drop=true).
176
+ *
177
+ * @template TArgs
178
+ * @template TResult
179
+ * @param {(...args: TArgs) => Promise<TResult>} fn - The async function to wrap.
180
+ * @param {boolean} [drop=false] - If true, new calls while one is pending are rejected.
181
+ * @returns {(...args: TArgs) => Promise<TResult>} A wrapped function with singleton behavior.
182
+ */
183
+ function singletonAsync(fn, drop = false) {
184
+ let promise = null;
185
+ return async (...args) => {
186
+ if (!promise) {
187
+ promise = fn(...args).finally(() => {
188
+ promise = null;
189
+ });
190
+ }
191
+ else if (drop) {
192
+ return Promise.reject(new Error("Busy: function already running"));
193
+ }
194
+ return promise;
195
+ };
196
+ }
197
+ /**
198
+ * Resolves a list of async tasks in parallel, returning both resolved and rejected results.
199
+ *
200
+ * @template T
201
+ * @param {Array<() => Promise<T>>} tasks - Array of promise-returning functions.
202
+ * @returns {Promise<PromiseSettledResult<T>[]>} Results including status and value/reason.
203
+ */
204
+ async function settleAll(tasks) {
205
+ return Promise.allSettled(tasks.map((task) => task()));
206
+ }
207
+ /**
208
+ * A simple task queue that executes async tasks with a concurrency limit.
209
+ * Exposes pause, resume, and queue length getters.
210
+ *
211
+ * @param {number} limit - Maximum number of concurrent tasks.
212
+ * @returns {function & { pause: () => void, resume: () => void, length: number, isPaused: boolean }}
213
+ * Enqueue function plus queue controls.
214
+ */
215
+ function createTaskQueue(limit) {
216
+ const queue = [];
217
+ let activeCount = 0;
218
+ let paused = false;
219
+ const state = {
220
+ /**
221
+ * Pause task processing.
222
+ */
223
+ pause() {
224
+ paused = true;
225
+ },
226
+ /**
227
+ * Resume task processing.
228
+ */
229
+ resume() {
230
+ paused = false;
231
+ next();
232
+ },
233
+ /**
234
+ * The current length of the queue.
235
+ * @type {number}
236
+ */
237
+ get length() {
238
+ return queue.length;
239
+ },
240
+ /**
241
+ * Whether the queue is currently paused.
242
+ * @type {boolean}
243
+ */
244
+ get isPaused() {
245
+ return paused;
246
+ },
247
+ };
248
+ const next = () => {
249
+ if (paused || queue.length === 0 || activeCount >= limit)
250
+ return;
251
+ const task = queue.shift();
252
+ activeCount++;
253
+ task().finally(() => {
254
+ activeCount--;
255
+ next();
256
+ });
257
+ };
258
+ /**
259
+ * Enqueues a new async task to the queue.
260
+ *
261
+ * @template T
262
+ * @param {() => Promise<T>} taskFn - The async task function.
263
+ * @returns {Promise<T>} Promise resolving when task completes.
264
+ */
265
+ const enqueue = async function (taskFn) {
266
+ return new Promise((resolve, reject) => {
267
+ queue.push(async () => {
268
+ try {
269
+ const result = await taskFn();
270
+ resolve(result);
271
+ }
272
+ catch (err) {
273
+ reject(err);
274
+ }
275
+ });
276
+ next();
277
+ });
278
+ };
279
+ enqueue.pause = state.pause;
280
+ enqueue.resume = state.resume;
281
+ Object.defineProperty(enqueue, "length", {
282
+ get: () => queue.length,
283
+ });
284
+ Object.defineProperty(enqueue, "isPaused", {
285
+ get: () => paused,
286
+ });
287
+ return enqueue;
288
+ }
289
+ /**
290
+ * Executes async functions sequentially and collects results.
291
+ * Useful when order matters or tasks depend on each other.
292
+ *
293
+ * @template T
294
+ * @param {Array<() => Promise<T>>} tasks - Array of promise-returning functions.
295
+ * @returns {Promise<T[]>} Array of resolved values.
296
+ */
297
+ async function runInSeries(tasks) {
298
+ const results = [];
299
+ for (const task of tasks) {
300
+ results.push(await task());
301
+ }
302
+ return results;
303
+ }
304
+ //# sourceMappingURL=async.utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"async.utils.js","sourceRoot":"","sources":["../../../src/utils/async.utils.ts"],"names":[],"mappings":";;;AAkBA,4BAmCC;AAYD,4BAsCC;AAcD,sBAiBC;AAWD,kCAiBC;AAaD,oCAWC;AAaD,wCAgBC;AASD,8BAIC;AAkBD,0CA4EC;AAUD,kCAQC;AApVD;;;;;GAKG;AACI,MAAM,KAAK,GAAG,CAAC,EAAU,EAAiB,EAAE,CACjD,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC;AADvC,QAAA,KAAK,SACkC;AAEpD;;;;;;;;GAQG;AACH,SAAgB,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,CAAC,KAAK,CAAC,CAAC;QAC/B,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE;YACtB,EAAE,CAAC,GAAI,WAA6B,CAAC,CAAC;YACtC,KAAK,GAAG,IAAI,CAAC;QACf,CAAC,EAAE,KAAK,CAAC,CAAC;IACZ,CAAC;IAED,SAAS,CAAC,MAAM,GAAG,GAAG,EAAE;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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,146 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TTLCache = void 0;
4
+ /**
5
+ * An in-memory cache with time-to-live (TTL) support for each entry.
6
+ *
7
+ * @typeParam K - Type of the key.
8
+ * @typeParam V - Type of the value.
9
+ *
10
+ * @example
11
+ * const cache = new TTLCache<string, number>(1000);
12
+ * cache.set("x", 123);
13
+ * const value = cache.get("x"); // 123
14
+ */
15
+ class TTLCache {
16
+ /**
17
+ * @param ttlMs - Default time-to-live in milliseconds for cache entries.
18
+ */
19
+ constructor(ttlMs = 5 * 60 * 1000) {
20
+ this.ttlMs = ttlMs;
21
+ this.cache = new Map();
22
+ }
23
+ /**
24
+ * Sets a key-value pair in the cache with the default TTL.
25
+ *
26
+ * @param key - The key to set.
27
+ * @param value - The value to associate with the key.
28
+ */
29
+ set(key, value) {
30
+ const expiresAt = Date.now() + this.ttlMs;
31
+ this.cache.set(key, { value, expiresAt });
32
+ }
33
+ /**
34
+ * Sets a key-value pair in the cache with a custom TTL.
35
+ *
36
+ * @param key - The key to set.
37
+ * @param value - The value to associate with the key.
38
+ * @param ttlMs - Time-to-live in milliseconds.
39
+ */
40
+ setWithTTL(key, value, ttlMs) {
41
+ const expiresAt = Date.now() + ttlMs;
42
+ this.cache.set(key, { value, expiresAt });
43
+ }
44
+ /**
45
+ * Retrieves the value for a given key if it hasn't expired.
46
+ *
47
+ * @param key - The key to retrieve.
48
+ * @returns The cached value, or undefined if not found or expired.
49
+ */
50
+ get(key) {
51
+ const entry = this.cache.get(key);
52
+ if (!entry)
53
+ return undefined;
54
+ if (Date.now() > entry.expiresAt) {
55
+ this.cache.delete(key);
56
+ return undefined;
57
+ }
58
+ return entry.value;
59
+ }
60
+ /**
61
+ * Checks if the key exists and hasn't expired.
62
+ *
63
+ * @param key - The key to check.
64
+ * @returns `true` if key exists and is valid, otherwise `false`.
65
+ */
66
+ has(key) {
67
+ return this.get(key) !== undefined;
68
+ }
69
+ /**
70
+ * Deletes a key from the cache.
71
+ *
72
+ * @param key - The key to delete.
73
+ * @returns `true` if the key existed and was removed, `false` otherwise.
74
+ */
75
+ delete(key) {
76
+ return this.cache.delete(key);
77
+ }
78
+ /**
79
+ * Clears all entries from the cache.
80
+ */
81
+ clear() {
82
+ this.cache.clear();
83
+ }
84
+ /**
85
+ * Returns the number of entries currently in the cache (includes expired entries until next access/cleanup).
86
+ *
87
+ * @returns Number of items in the cache (may include expired keys).
88
+ */
89
+ size() {
90
+ return this.cache.size;
91
+ }
92
+ /**
93
+ * Removes all expired entries from the cache.
94
+ *
95
+ * @returns Number of entries removed.
96
+ */
97
+ cleanup() {
98
+ let removed = 0;
99
+ const now = Date.now();
100
+ for (const [key, entry] of this.cache.entries()) {
101
+ if (now > entry.expiresAt) {
102
+ this.cache.delete(key);
103
+ removed++;
104
+ }
105
+ }
106
+ return removed;
107
+ }
108
+ /**
109
+ * Returns an iterator of all current valid [key, value] pairs.
110
+ *
111
+ * @returns IterableIterator<[K, V]>
112
+ */
113
+ *entries() {
114
+ for (const [key, entry] of this.cache.entries()) {
115
+ if (Date.now() <= entry.expiresAt) {
116
+ yield [key, entry.value];
117
+ }
118
+ }
119
+ }
120
+ /**
121
+ * Returns an iterator of all current valid keys.
122
+ *
123
+ * @returns IterableIterator<K>
124
+ */
125
+ *keys() {
126
+ for (const [key, entry] of this.cache.entries()) {
127
+ if (Date.now() <= entry.expiresAt) {
128
+ yield key;
129
+ }
130
+ }
131
+ }
132
+ /**
133
+ * Returns an iterator of all current valid values.
134
+ *
135
+ * @returns IterableIterator<V>
136
+ */
137
+ *values() {
138
+ for (const entry of this.cache.values()) {
139
+ if (Date.now() <= entry.expiresAt) {
140
+ yield entry.value;
141
+ }
142
+ }
143
+ }
144
+ }
145
+ exports.TTLCache = TTLCache;
146
+ //# sourceMappingURL=cache.utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache.utils.js","sourceRoot":"","sources":["../../../src/utils/cache.utils.ts"],"names":[],"mappings":";;;AAQA;;;;;;;;;;GAUG;AACH,MAAa,QAAQ;IAGnB;;OAEG;IACH,YAAoB,QAAgB,CAAC,GAAG,EAAE,GAAG,IAAI;QAA7B,UAAK,GAAL,KAAK,CAAwB;QALzC,UAAK,GAAG,IAAI,GAAG,EAAoB,CAAC;IAKQ,CAAC;IAErD;;;;;OAKG;IACH,GAAG,CAAC,GAAM,EAAE,KAAQ;QAClB,MAAM,SAAS,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC;QAC1C,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC;IAC5C,CAAC;IAED;;;;;;OAMG;IACH,UAAU,CAAC,GAAM,EAAE,KAAQ,EAAE,KAAa;QACxC,MAAM,SAAS,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC;QACrC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC;IAC5C,CAAC;IAED;;;;;OAKG;IACH,GAAG,CAAC,GAAM;QACR,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAClC,IAAI,CAAC,KAAK;YAAE,OAAO,SAAS,CAAC;QAC7B,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC,SAAS,EAAE,CAAC;YACjC,IAA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AAC;IACH,CAAC;IAED;;;;OAIG;IACH,CAAC,IAAI;QACH,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,EAAE,CAAC;YAChD,IAAI,IAAI,CAAC,GAAG,EAAE,IAAI,KAAK,CAAC,SAAS,EAAE,CAAC;gBAClC,MAAM,GAAG,CAAC;YACZ,CAAC;QACH,CAAC;IACH,CAAC;IAED;;;;OAIG;IACH,CAAC,MAAM;QACL,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,EAAE,CAAC;YACxC,IAAI,IAAI,CAAC,GAAG,EAAE,IAAI,KAAK,CAAC,SAAS,EAAE,CAAC;gBAClC,MAAM,KAAK,CAAC,KAAK,CAAC;YACpB,CAAC;QACH,CAAC;IACH,CAAC;CACF;AA1ID,4BA0IC","sourcesContent":["/**\n * Represents a cached entry with a value and an expiration timestamp.\n */\ntype CacheEntry<T> = {\n value: T;\n expiresAt: number;\n};\n\n/**\n * An in-memory cache with time-to-live (TTL) support for each entry.\n *\n * @typeParam K - Type of the key.\n * @typeParam V - Type of the value.\n *\n * @example\n * const cache = new TTLCache<string, number>(1000);\n * cache.set(\"x\", 123);\n * const value = cache.get(\"x\"); // 123\n */\nexport class TTLCache<K, V> {\n private cache = new Map<K, CacheEntry<V>>();\n\n /**\n * @param ttlMs - Default time-to-live in milliseconds for cache entries.\n */\n constructor(private ttlMs: number = 5 * 60 * 1000) {}\n\n /**\n * Sets a key-value pair in the cache with the default TTL.\n *\n * @param key - The key to set.\n * @param value - The value to associate with the key.\n */\n set(key: K, value: V): void {\n const expiresAt = Date.now() + this.ttlMs;\n this.cache.set(key, { value, expiresAt });\n }\n\n /**\n * Sets a key-value pair in the cache with a custom TTL.\n *\n * @param key - The key to set.\n * @param value - The value to associate with the key.\n * @param ttlMs - Time-to-live in milliseconds.\n */\n setWithTTL(key: K, value: V, ttlMs: number): void {\n const expiresAt = Date.now() + ttlMs;\n this.cache.set(key, { value, expiresAt });\n }\n\n /**\n * Retrieves the value for a given key if it hasn't expired.\n *\n * @param key - The key to retrieve.\n * @returns The cached value, or undefined if not found or expired.\n */\n get(key: K): V | undefined {\n const entry = this.cache.get(key);\n if (!entry) return undefined;\n if (Date.now() > entry.expiresAt) {\n this.cache.delete(key);\n return undefined;\n }\n return entry.value;\n }\n\n /**\n * Checks if the key exists and hasn't expired.\n *\n * @param key - The key to check.\n * @returns `true` if key exists and is valid, otherwise `false`.\n */\n has(key: K): boolean {\n return this.get(key) !== undefined;\n }\n\n /**\n * Deletes a key from the cache.\n *\n * @param key - The key to delete.\n * @returns `true` if the key existed and was removed, `false` otherwise.\n */\n delete(key: K): boolean {\n return this.cache.delete(key);\n }\n\n /**\n * Clears all entries from the cache.\n */\n clear(): void {\n this.cache.clear();\n }\n\n /**\n * Returns the number of entries currently in the cache (includes expired entries until next access/cleanup).\n *\n * @returns Number of items in the cache (may include expired keys).\n */\n size(): number {\n return this.cache.size;\n }\n\n /**\n * Removes all expired entries from the cache.\n *\n * @returns Number of entries removed.\n */\n cleanup(): number {\n let removed = 0;\n const now = Date.now();\n for (const [key, entry] of this.cache.entries()) {\n if (now > entry.expiresAt) {\n this.cache.delete(key);\n removed++;\n }\n }\n return removed;\n }\n\n /**\n * Returns an iterator of all current valid [key, value] pairs.\n *\n * @returns IterableIterator<[K, V]>\n */\n *entries(): IterableIterator<[K, V]> {\n for (const [key, entry] of this.cache.entries()) {\n if (Date.now() <= entry.expiresAt) {\n yield [key, entry.value];\n }\n }\n }\n\n /**\n * Returns an iterator of all current valid keys.\n *\n * @returns IterableIterator<K>\n */\n *keys(): IterableIterator<K> {\n for (const [key, entry] of this.cache.entries()) {\n if (Date.now() <= entry.expiresAt) {\n yield key;\n }\n }\n }\n\n /**\n * Returns an iterator of all current valid values.\n *\n * @returns IterableIterator<V>\n */\n *values(): IterableIterator<V> {\n for (const entry of this.cache.values()) {\n if (Date.now() <= entry.expiresAt) {\n yield entry.value;\n }\n }\n }\n}\n"]}
@@ -0,0 +1,85 @@
1
+ import { AsyncLocalStorage } from "async_hooks";
2
+ /**
3
+ * Type representing the store object used in AsyncLocalStorage.
4
+ * Keys must be unique symbols to ensure isolation and prevent collisions.
5
+ */
6
+ export interface Store {
7
+ [key: symbol]: unknown;
8
+ }
9
+ /**
10
+ * Predefined symbols used as keys in AsyncLocalStorage.
11
+ * Add new symbols here to avoid duplication.
12
+ */
13
+ export declare const StoreKeys: {
14
+ LOGGER: symbol;
15
+ REQUEST_ID: symbol;
16
+ };
17
+ /**
18
+ * Retrieves the current request ID from the async context, if available.
19
+ *
20
+ * @returns {string | undefined} The request ID string or undefined if not present in the current context.
21
+ */
22
+ export declare function getRequestId(): string | undefined;
23
+ /**
24
+ * ContextStore manages per-request scoped context using AsyncLocalStorage.
25
+ * It allows storing and retrieving data across async calls (e.g., request ID, logger).
26
+ *
27
+ * Example (Express middleware):
28
+ * ```
29
+ * // Middleware to initialize context and logger
30
+ * app.use((req, res, next) => {
31
+ * const requestId = req.headers["x-request-id"]?.toString() || crypto.randomUUID();
32
+ * ContextStore.run({ [StoreKeys.REQUEST_ID]: requestId }, () => {
33
+ * ContextStore.set(StoreKeys.LOGGER, getLogger().child({ reqId: requestId }));
34
+ * next();
35
+ * });
36
+ * });
37
+ * ```
38
+ */
39
+ export declare class ContextStore {
40
+ /**
41
+ * The underlying AsyncLocalStorage instance for context.
42
+ * @private
43
+ */
44
+ private static readonly storage;
45
+ /**
46
+ * Returns the raw AsyncLocalStorage instance for advanced access.
47
+ *
48
+ * @returns {AsyncLocalStorage<Store>} The AsyncLocalStorage instance.
49
+ */
50
+ static getInstance(): AsyncLocalStorage<Store>;
51
+ /**
52
+ * Retrieves a value from the async context store by symbol key.
53
+ *
54
+ * @typeParam T - The expected return type of the value.
55
+ * @param {symbol} key - Unique symbol used as the store key.
56
+ * @returns {T | undefined} The value found (typed) or undefined if not present.
57
+ */
58
+ static get<T>(key: symbol): T | undefined;
59
+ /**
60
+ * Sets a value in the current context store by symbol key.
61
+ *
62
+ * @typeParam T - The value type to set.
63
+ * @param {symbol} key - Unique symbol key.
64
+ * @param {T} value - Value to set in context.
65
+ * @throws {Error} If called outside an active context (not within a .run call or in the wrong async boundaries).
66
+ */
67
+ static set<T>(key: symbol, value: T): void;
68
+ /**
69
+ * Retrieves the entire context store object for the current async context.
70
+ *
71
+ * @returns {Store | undefined} The current store object or undefined if called outside a context.
72
+ */
73
+ static getAll(): Store | undefined;
74
+ /**
75
+ * Initializes a new async context and executes a callback within it.
76
+ * This must be called at the beginning of a request or logical async flow.
77
+ *
78
+ * @typeParam T - The callback's return type.
79
+ * @param {Store} store - The initial key-value store object.
80
+ * @param {() => T} callback - The function to run within the new context.
81
+ * @returns {T} The result of the callback function.
82
+ */
83
+ static run<T>(store: Store, callback: () => T): T;
84
+ }
85
+ //# sourceMappingURL=context-store.utils.d.ts.map