@catbee/utils 1.0.5 → 2.0.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +27 -27
  3. package/array/array.utils.d.ts +191 -0
  4. package/array/index.cjs +246 -0
  5. package/array/index.d.ts +25 -0
  6. package/array/index.mjs +228 -0
  7. package/async/async.utils.d.ts +296 -0
  8. package/async/index.cjs +428 -0
  9. package/async/index.d.ts +25 -0
  10. package/async/index.mjs +407 -0
  11. package/cache/cache.utils.d.ts +176 -0
  12. package/cache/index.cjs +292 -0
  13. package/cache/index.d.ts +25 -0
  14. package/cache/index.mjs +290 -0
  15. package/config/config.d.ts +57 -0
  16. package/config/index.cjs +136 -0
  17. package/config/index.d.ts +26 -0
  18. package/config/index.mjs +131 -0
  19. package/context-store/context-store.utils.d.ts +212 -0
  20. package/context-store/index.cjs +267 -0
  21. package/context-store/index.d.ts +25 -0
  22. package/context-store/index.mjs +261 -0
  23. package/crypto/crypto.utils.d.ts +183 -0
  24. package/crypto/index.cjs +182 -0
  25. package/crypto/index.d.ts +25 -0
  26. package/crypto/index.mjs +166 -0
  27. package/date/date.utils.d.ts +190 -0
  28. package/date/index.cjs +295 -0
  29. package/date/index.d.ts +25 -0
  30. package/date/index.mjs +283 -0
  31. package/decorators/decorators.utils.d.ts +705 -0
  32. package/decorators/index.cjs +913 -0
  33. package/decorators/index.d.ts +25 -0
  34. package/decorators/index.mjs +872 -0
  35. package/dir/dir.utils.d.ts +216 -0
  36. package/dir/index.cjs +416 -0
  37. package/dir/index.d.ts +25 -0
  38. package/dir/index.mjs +389 -0
  39. package/env/env.utils.d.ts +400 -0
  40. package/env/index.cjs +761 -0
  41. package/env/index.d.ts +25 -0
  42. package/env/index.mjs +758 -0
  43. package/exception/exception.utils.d.ts +253 -0
  44. package/exception/index.cjs +362 -0
  45. package/exception/index.d.ts +25 -0
  46. package/exception/index.mjs +338 -0
  47. package/fs/fs.utils.d.ts +196 -0
  48. package/fs/index.cjs +253 -0
  49. package/fs/index.d.ts +25 -0
  50. package/fs/index.mjs +228 -0
  51. package/http-status-codes/http-status-codes.d.ts +289 -0
  52. package/http-status-codes/index.cjs +96 -0
  53. package/http-status-codes/index.d.ts +25 -0
  54. package/http-status-codes/index.mjs +94 -0
  55. package/id/id.utils.d.ts +59 -0
  56. package/id/index.cjs +62 -0
  57. package/id/index.d.ts +25 -0
  58. package/id/index.mjs +56 -0
  59. package/index.cjs +218 -0
  60. package/index.d.ts +51 -0
  61. package/index.mjs +51 -0
  62. package/logger/index.cjs +334 -0
  63. package/logger/index.d.ts +25 -0
  64. package/logger/index.mjs +313 -0
  65. package/logger/logger.utils.d.ts +210 -0
  66. package/middleware/index.cjs +177 -0
  67. package/middleware/index.d.ts +25 -0
  68. package/middleware/index.mjs +170 -0
  69. package/middleware/middleware.utils.d.ts +123 -0
  70. package/obj/index.cjs +317 -0
  71. package/obj/index.d.ts +25 -0
  72. package/obj/index.mjs +301 -0
  73. package/obj/obj.utils.d.ts +156 -0
  74. package/package.json +172 -20
  75. package/performance/index.cjs +231 -0
  76. package/performance/index.d.ts +25 -0
  77. package/performance/index.mjs +225 -0
  78. package/performance/performance.utils.d.ts +159 -0
  79. package/request/index.cjs +202 -0
  80. package/request/index.d.ts +26 -0
  81. package/request/index.mjs +194 -0
  82. package/request/request.utils.d.ts +109 -0
  83. package/response/index.cjs +234 -0
  84. package/response/index.d.ts +26 -0
  85. package/response/index.mjs +222 -0
  86. package/response/response.utils.d.ts +186 -0
  87. package/server/index.cjs +1627 -0
  88. package/server/index.d.ts +28 -0
  89. package/server/index.mjs +1617 -0
  90. package/server/server.builder.d.ts +531 -0
  91. package/server/server.d.ts +303 -0
  92. package/stream/index.cjs +151 -0
  93. package/stream/index.d.ts +25 -0
  94. package/stream/index.mjs +144 -0
  95. package/stream/stream.utils.d.ts +111 -0
  96. package/string/index.cjs +109 -0
  97. package/string/index.d.ts +25 -0
  98. package/string/index.mjs +95 -0
  99. package/string/string.utils.d.ts +124 -0
  100. package/type/index.cjs +129 -0
  101. package/type/index.d.ts +25 -0
  102. package/type/index.mjs +119 -0
  103. package/type/type.utils.d.ts +129 -0
  104. package/types/api-response.d.ts +175 -0
  105. package/types/common.d.ts +148 -0
  106. package/types/config.d.ts +88 -0
  107. package/types/index.cjs +34 -0
  108. package/types/index.d.ts +28 -0
  109. package/types/index.mjs +32 -0
  110. package/types/server.d.ts +291 -0
  111. package/url/index.cjs +201 -0
  112. package/url/index.d.ts +25 -0
  113. package/url/index.mjs +189 -0
  114. package/url/url.utils.d.ts +164 -0
  115. package/validate/index.cjs +212 -0
  116. package/validate/index.d.ts +25 -0
  117. package/validate/index.mjs +188 -0
  118. package/validate/validate.utils.d.ts +200 -0
  119. package/build/index.cjs +0 -7579
  120. package/build/index.d.ts +0 -5774
  121. package/build/index.mjs +0 -7274
@@ -0,0 +1,428 @@
1
+ /*
2
+ * The MIT License
3
+ *
4
+ * Copyright (c) 2025 Catbee Technologies. https://catbee.in/license
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+
25
+ 'use strict';
26
+
27
+ var logger = require('@catbee/utils/logger');
28
+
29
+ var __defProp = Object.defineProperty;
30
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
31
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
32
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
33
+ }) : x)(function(x) {
34
+ if (typeof require !== "undefined") return require.apply(this, arguments);
35
+ throw Error('Dynamic require of "' + x + '" is not supported');
36
+ });
37
+ function sleep(ms) {
38
+ return new Promise((resolve) => setTimeout(resolve, ms));
39
+ }
40
+ __name(sleep, "sleep");
41
+ function debounce(fn, delay) {
42
+ let timer = null;
43
+ let pendingArgs = null;
44
+ function debounced(...args) {
45
+ pendingArgs = args;
46
+ if (timer) clearTimeout(timer);
47
+ timer = setTimeout(() => {
48
+ fn(...pendingArgs);
49
+ timer = null;
50
+ }, delay);
51
+ }
52
+ __name(debounced, "debounced");
53
+ debounced.cancel = () => {
54
+ if (timer) clearTimeout(timer);
55
+ timer = null;
56
+ pendingArgs = null;
57
+ };
58
+ debounced.flush = () => {
59
+ if (timer) {
60
+ clearTimeout(timer);
61
+ fn(...pendingArgs);
62
+ timer = null;
63
+ pendingArgs = null;
64
+ }
65
+ };
66
+ return debounced;
67
+ }
68
+ __name(debounce, "debounce");
69
+ function throttle(fn, limit, opts = {
70
+ leading: true,
71
+ trailing: false
72
+ }) {
73
+ let lastCall = 0;
74
+ let timer = null;
75
+ let savedArgs = null;
76
+ return function(...args) {
77
+ const now = Date.now();
78
+ const { leading = true, trailing = false } = opts;
79
+ if (!lastCall && !leading) 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
+ } else if (trailing) {
89
+ savedArgs = args;
90
+ if (!timer) {
91
+ timer = setTimeout(() => {
92
+ lastCall = leading ? Date.now() : 0;
93
+ timer = null;
94
+ if (savedArgs) fn(...savedArgs);
95
+ }, remaining);
96
+ }
97
+ }
98
+ };
99
+ }
100
+ __name(throttle, "throttle");
101
+ 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
+ } catch (e) {
106
+ if (i === retries - 1) throw e;
107
+ if (onRetry) onRetry(e, i + 1);
108
+ await sleep(backoff ? delay * Math.pow(2, i) : delay);
109
+ }
110
+ }
111
+ throw new Error("Retry failed");
112
+ }
113
+ __name(retry, "retry");
114
+ function withTimeout(promise, ms, message = "Operation timed out") {
115
+ return new Promise((resolve, reject) => {
116
+ const timeoutHandle = setTimeout(() => reject(new Error(message)), ms);
117
+ promise.then((result) => {
118
+ clearTimeout(timeoutHandle);
119
+ resolve(result);
120
+ }).catch((err) => {
121
+ clearTimeout(timeoutHandle);
122
+ reject(err);
123
+ });
124
+ });
125
+ }
126
+ __name(withTimeout, "withTimeout");
127
+ async function runInBatches(tasks, limit) {
128
+ const results = [];
129
+ for (let i = 0; i < tasks.length; i += limit) {
130
+ const batch = tasks.slice(i, i + limit);
131
+ const batchResults = await Promise.all(batch.map((fn) => fn()));
132
+ results.push(...batchResults);
133
+ }
134
+ return results;
135
+ }
136
+ __name(runInBatches, "runInBatches");
137
+ function singletonAsync(fn, drop = false) {
138
+ let promise = null;
139
+ return async (...args) => {
140
+ if (!promise) {
141
+ promise = fn(...args).finally(() => {
142
+ promise = null;
143
+ });
144
+ } else if (drop) {
145
+ return Promise.reject(new Error("Busy: function already running"));
146
+ }
147
+ return promise;
148
+ };
149
+ }
150
+ __name(singletonAsync, "singletonAsync");
151
+ async function settleAll(tasks) {
152
+ return Promise.allSettled(tasks.map((task) => task()));
153
+ }
154
+ __name(settleAll, "settleAll");
155
+ function createTaskQueue(limit) {
156
+ const queue = [];
157
+ let activeCount = 0;
158
+ let paused = false;
159
+ const state = {
160
+ /**
161
+ * Pause task processing.
162
+ */
163
+ pause() {
164
+ paused = true;
165
+ },
166
+ /**
167
+ * Resume task processing.
168
+ */
169
+ resume() {
170
+ paused = false;
171
+ next();
172
+ }};
173
+ const next = /* @__PURE__ */ __name(() => {
174
+ if (paused || queue.length === 0 || activeCount >= limit) return;
175
+ const task = queue.shift();
176
+ activeCount++;
177
+ task().finally(() => {
178
+ activeCount--;
179
+ next();
180
+ });
181
+ }, "next");
182
+ const enqueue = /* @__PURE__ */ __name(async function(taskFn) {
183
+ return new Promise((resolve, reject) => {
184
+ queue.push(async () => {
185
+ try {
186
+ const result = await taskFn();
187
+ resolve(result);
188
+ } catch (err) {
189
+ reject(err);
190
+ }
191
+ });
192
+ next();
193
+ });
194
+ }, "enqueue");
195
+ enqueue.pause = state.pause;
196
+ enqueue.resume = state.resume;
197
+ Object.defineProperty(enqueue, "length", {
198
+ get: /* @__PURE__ */ __name(() => queue.length, "get")
199
+ });
200
+ Object.defineProperty(enqueue, "isPaused", {
201
+ get: /* @__PURE__ */ __name(() => paused, "get")
202
+ });
203
+ return enqueue;
204
+ }
205
+ __name(createTaskQueue, "createTaskQueue");
206
+ async function runInSeries(tasks) {
207
+ const results = [];
208
+ for (const task of tasks) {
209
+ results.push(await task());
210
+ }
211
+ return results;
212
+ }
213
+ __name(runInSeries, "runInSeries");
214
+ function memoizeAsync(fn, options = {}) {
215
+ const cache = /* @__PURE__ */ new Map();
216
+ const { ttl, keyFn = JSON.stringify } = options;
217
+ return async function(...args) {
218
+ const key = keyFn(args);
219
+ const cached = cache.get(key);
220
+ if (cached && (!ttl || Date.now() < cached.expires)) {
221
+ return cached.value;
222
+ }
223
+ const result = await fn(...args);
224
+ cache.set(key, {
225
+ value: result,
226
+ expires: ttl ? Date.now() + ttl : Infinity
227
+ });
228
+ return result;
229
+ };
230
+ }
231
+ __name(memoizeAsync, "memoizeAsync");
232
+ function abortable(promise, signal, abortValue = new Error("Operation aborted")) {
233
+ if (signal.aborted) {
234
+ return Promise.reject(abortValue);
235
+ }
236
+ return Promise.race([
237
+ promise,
238
+ new Promise((_, reject) => {
239
+ const abort = /* @__PURE__ */ __name(() => reject(abortValue), "abort");
240
+ signal.addEventListener("abort", abort, {
241
+ once: true
242
+ });
243
+ promise.finally(() => signal.removeEventListener("abort", abort));
244
+ })
245
+ ]);
246
+ }
247
+ __name(abortable, "abortable");
248
+ function createDeferred() {
249
+ let resolve;
250
+ let reject;
251
+ const promise = new Promise((res, rej) => {
252
+ resolve = res;
253
+ reject = rej;
254
+ });
255
+ return [
256
+ promise,
257
+ resolve,
258
+ reject
259
+ ];
260
+ }
261
+ __name(createDeferred, "createDeferred");
262
+ function waterfall(fns) {
263
+ return async (initialValue) => {
264
+ return fns.reduce(async (acc, fn) => fn(await acc), Promise.resolve(initialValue));
265
+ };
266
+ }
267
+ __name(waterfall, "waterfall");
268
+ function rateLimit(fn, maxCalls, interval) {
269
+ const calls = [];
270
+ return async function(...args) {
271
+ const now = Date.now();
272
+ calls.splice(0, calls.length, ...calls.filter((time) => now - time < interval));
273
+ if (calls.length >= maxCalls) {
274
+ const oldestCall = calls[0];
275
+ const delay = interval - (now - oldestCall);
276
+ await sleep(Math.max(1, delay));
277
+ const currentTime = Date.now();
278
+ calls.splice(0, calls.length, ...calls.filter((time) => currentTime - time < interval));
279
+ if (calls.length >= maxCalls) {
280
+ const nextDelay = interval - (currentTime - calls[0]);
281
+ await sleep(Math.max(1, nextDelay));
282
+ calls.splice(0, calls.length, ...calls.filter((time) => Date.now() - time < interval));
283
+ }
284
+ }
285
+ calls.push(Date.now());
286
+ return fn(...args);
287
+ };
288
+ }
289
+ __name(rateLimit, "rateLimit");
290
+ var CircuitBreakerOpenError = class extends Error {
291
+ static {
292
+ __name(this, "CircuitBreakerOpenError");
293
+ }
294
+ constructor(message = "Circuit breaker is open") {
295
+ super(message);
296
+ this.name = "CircuitBreakerOpenError";
297
+ }
298
+ };
299
+ var CircuitBreakerState = /* @__PURE__ */ (function(CircuitBreakerState2) {
300
+ CircuitBreakerState2["CLOSED"] = "CLOSED";
301
+ CircuitBreakerState2["OPEN"] = "OPEN";
302
+ CircuitBreakerState2["HALF_OPEN"] = "HALF_OPEN";
303
+ return CircuitBreakerState2;
304
+ })({});
305
+ function circuitBreaker(fn, options = {}) {
306
+ const { failureThreshold = 5, resetTimeout = 1e4, successThreshold = 1, onOpen, onClose, onHalfOpen } = options;
307
+ let state = "CLOSED";
308
+ let failureCount = 0;
309
+ let successCount = 0;
310
+ let nextAttempt = Date.now();
311
+ return async function(...args) {
312
+ if (state === "OPEN") {
313
+ if (Date.now() < nextAttempt) {
314
+ throw new CircuitBreakerOpenError();
315
+ }
316
+ state = "HALF_OPEN";
317
+ if (onHalfOpen) onHalfOpen();
318
+ }
319
+ try {
320
+ const result = await fn(...args);
321
+ if (state === "HALF_OPEN") {
322
+ successCount++;
323
+ if (successCount >= successThreshold) {
324
+ successCount = 0;
325
+ failureCount = 0;
326
+ state = "CLOSED";
327
+ if (onClose) onClose();
328
+ }
329
+ } else {
330
+ failureCount = 0;
331
+ }
332
+ return result;
333
+ } catch (error) {
334
+ failureCount++;
335
+ if ((state === "CLOSED" || state === "HALF_OPEN") && failureCount >= failureThreshold) {
336
+ state = "OPEN";
337
+ nextAttempt = Date.now() + resetTimeout;
338
+ if (onOpen) onOpen();
339
+ }
340
+ throw error;
341
+ }
342
+ };
343
+ }
344
+ __name(circuitBreaker, "circuitBreaker");
345
+ async function runWithConcurrency(tasks, options = {}) {
346
+ const { concurrency = 3, onProgress, signal } = options;
347
+ const results = [];
348
+ const totalTasks = tasks.length;
349
+ let completed = 0;
350
+ if (totalTasks === 0) return results;
351
+ if (signal?.aborted) {
352
+ throw new Error("Aborted");
353
+ }
354
+ return new Promise((resolve, reject) => {
355
+ let taskIndex = 0;
356
+ const processNext = /* @__PURE__ */ __name(async () => {
357
+ const currentTaskIndex = taskIndex++;
358
+ if (currentTaskIndex >= totalTasks) return;
359
+ try {
360
+ const result = await tasks[currentTaskIndex]();
361
+ if (signal?.aborted) {
362
+ reject(new Error("Aborted"));
363
+ return;
364
+ }
365
+ results[currentTaskIndex] = result;
366
+ completed++;
367
+ if (onProgress) {
368
+ try {
369
+ onProgress(completed, totalTasks);
370
+ } catch (err) {
371
+ logger.getLogger().error({
372
+ err
373
+ }, "Error in onProgress callback");
374
+ }
375
+ }
376
+ } catch (error) {
377
+ reject(error);
378
+ return;
379
+ }
380
+ if (completed === totalTasks) {
381
+ resolve(results);
382
+ return;
383
+ }
384
+ processNext();
385
+ }, "processNext");
386
+ const initialBatch = Math.min(concurrency, totalTasks);
387
+ for (let i = 0; i < initialBatch; i++) {
388
+ processNext();
389
+ }
390
+ if (signal) {
391
+ signal.addEventListener("abort", () => {
392
+ reject(new Error("Aborted"));
393
+ }, {
394
+ once: true
395
+ });
396
+ }
397
+ });
398
+ }
399
+ __name(runWithConcurrency, "runWithConcurrency");
400
+ function optionalRequire(name) {
401
+ try {
402
+ return __require(name);
403
+ } catch {
404
+ return null;
405
+ }
406
+ }
407
+ __name(optionalRequire, "optionalRequire");
408
+
409
+ exports.CircuitBreakerOpenError = CircuitBreakerOpenError;
410
+ exports.CircuitBreakerState = CircuitBreakerState;
411
+ exports.abortable = abortable;
412
+ exports.circuitBreaker = circuitBreaker;
413
+ exports.createDeferred = createDeferred;
414
+ exports.createTaskQueue = createTaskQueue;
415
+ exports.debounce = debounce;
416
+ exports.memoizeAsync = memoizeAsync;
417
+ exports.optionalRequire = optionalRequire;
418
+ exports.rateLimit = rateLimit;
419
+ exports.retry = retry;
420
+ exports.runInBatches = runInBatches;
421
+ exports.runInSeries = runInSeries;
422
+ exports.runWithConcurrency = runWithConcurrency;
423
+ exports.settleAll = settleAll;
424
+ exports.singletonAsync = singletonAsync;
425
+ exports.sleep = sleep;
426
+ exports.throttle = throttle;
427
+ exports.waterfall = waterfall;
428
+ exports.withTimeout = withTimeout;
@@ -0,0 +1,25 @@
1
+ /*
2
+ * The MIT License
3
+ *
4
+ * Copyright (c) 2025 Catbee Technologies. https://catbee.in/license
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+
25
+ export * from './async.utils';