@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.
- package/LICENSE +201 -0
- package/README.md +295 -0
- package/build/esm/config.d.ts +22 -0
- package/build/esm/config.js +21 -0
- package/build/esm/config.js.map +1 -0
- package/build/esm/index.d.ts +19 -0
- package/build/esm/index.js +19 -0
- package/build/esm/index.js.map +1 -0
- package/build/esm/types/api-response.d.ts +44 -0
- package/build/esm/types/api-response.js +2 -0
- package/build/esm/types/api-response.js.map +1 -0
- package/build/esm/utils/array.utils.d.ts +105 -0
- package/build/esm/utils/array.utils.js +232 -0
- package/build/esm/utils/array.utils.js.map +1 -0
- package/build/esm/utils/async.utils.d.ts +119 -0
- package/build/esm/utils/async.utils.js +474 -0
- package/build/esm/utils/async.utils.js.map +1 -0
- package/build/esm/utils/cache.utils.d.ts +90 -0
- package/build/esm/utils/cache.utils.js +294 -0
- package/build/esm/utils/cache.utils.js.map +1 -0
- package/build/esm/utils/context-store.utils.d.ts +85 -0
- package/build/esm/utils/context-store.utils.js +99 -0
- package/build/esm/utils/context-store.utils.js.map +1 -0
- package/build/esm/utils/crypto.utils.d.ts +58 -0
- package/build/esm/utils/crypto.utils.js +76 -0
- package/build/esm/utils/crypto.utils.js.map +1 -0
- package/build/esm/utils/dir.utils.d.ts +75 -0
- package/build/esm/utils/dir.utils.js +400 -0
- package/build/esm/utils/dir.utils.js.map +1 -0
- package/build/esm/utils/env.utils.d.ts +131 -0
- package/build/esm/utils/env.utils.js +218 -0
- package/build/esm/utils/env.utils.js.map +1 -0
- package/build/esm/utils/exception.utils.d.ts +114 -0
- package/build/esm/utils/exception.utils.js +217 -0
- package/build/esm/utils/exception.utils.js.map +1 -0
- package/build/esm/utils/fs.utils.d.ts +32 -0
- package/build/esm/utils/fs.utils.js +140 -0
- package/build/esm/utils/fs.utils.js.map +1 -0
- package/build/esm/utils/http-status-codes.d.ts +357 -0
- package/build/esm/utils/http-status-codes.js +358 -0
- package/build/esm/utils/http-status-codes.js.map +1 -0
- package/build/esm/utils/id.utils.d.ts +35 -0
- package/build/esm/utils/id.utils.js +55 -0
- package/build/esm/utils/id.utils.js.map +1 -0
- package/build/esm/utils/logger.utils.d.ts +15 -0
- package/build/esm/utils/logger.utils.js +59 -0
- package/build/esm/utils/logger.utils.js.map +1 -0
- package/build/esm/utils/obj.utils.d.ts +55 -0
- package/build/esm/utils/obj.utils.js +121 -0
- package/build/esm/utils/obj.utils.js.map +1 -0
- package/build/esm/utils/response.utils.d.ts +48 -0
- package/build/esm/utils/response.utils.js +80 -0
- package/build/esm/utils/response.utils.js.map +1 -0
- package/build/esm/utils/string.utils.d.ts +37 -0
- package/build/esm/utils/string.utils.js +56 -0
- package/build/esm/utils/string.utils.js.map +1 -0
- package/build/esm/utils/url.utils.d.ts +24 -0
- package/build/esm/utils/url.utils.js +73 -0
- package/build/esm/utils/url.utils.js.map +1 -0
- package/build/esm/utils/validate.utils.d.ts +60 -0
- package/build/esm/utils/validate.utils.js +121 -0
- package/build/esm/utils/validate.utils.js.map +1 -0
- package/build/esnext/config.d.ts +22 -0
- package/build/esnext/config.js +21 -0
- package/build/esnext/config.js.map +1 -0
- package/build/esnext/index.d.ts +19 -0
- package/build/esnext/index.js +19 -0
- package/build/esnext/index.js.map +1 -0
- package/build/esnext/types/api-response.d.ts +44 -0
- package/build/esnext/types/api-response.js +2 -0
- package/build/esnext/types/api-response.js.map +1 -0
- package/build/esnext/utils/array.utils.d.ts +105 -0
- package/build/esnext/utils/array.utils.js +203 -0
- package/build/esnext/utils/array.utils.js.map +1 -0
- package/build/esnext/utils/async.utils.d.ts +119 -0
- package/build/esnext/utils/async.utils.js +291 -0
- package/build/esnext/utils/async.utils.js.map +1 -0
- package/build/esnext/utils/cache.utils.d.ts +90 -0
- package/build/esnext/utils/cache.utils.js +142 -0
- package/build/esnext/utils/cache.utils.js.map +1 -0
- package/build/esnext/utils/context-store.utils.d.ts +85 -0
- package/build/esnext/utils/context-store.utils.js +95 -0
- package/build/esnext/utils/context-store.utils.js.map +1 -0
- package/build/esnext/utils/crypto.utils.d.ts +58 -0
- package/build/esnext/utils/crypto.utils.js +72 -0
- package/build/esnext/utils/crypto.utils.js.map +1 -0
- package/build/esnext/utils/dir.utils.d.ts +75 -0
- package/build/esnext/utils/dir.utils.js +150 -0
- package/build/esnext/utils/dir.utils.js.map +1 -0
- package/build/esnext/utils/env.utils.d.ts +131 -0
- package/build/esnext/utils/env.utils.js +211 -0
- package/build/esnext/utils/env.utils.js.map +1 -0
- package/build/esnext/utils/exception.utils.d.ts +114 -0
- package/build/esnext/utils/exception.utils.js +148 -0
- package/build/esnext/utils/exception.utils.js.map +1 -0
- package/build/esnext/utils/fs.utils.d.ts +32 -0
- package/build/esnext/utils/fs.utils.js +62 -0
- package/build/esnext/utils/fs.utils.js.map +1 -0
- package/build/esnext/utils/http-status-codes.d.ts +357 -0
- package/build/esnext/utils/http-status-codes.js +358 -0
- package/build/esnext/utils/http-status-codes.js.map +1 -0
- package/build/esnext/utils/id.utils.d.ts +35 -0
- package/build/esnext/utils/id.utils.js +53 -0
- package/build/esnext/utils/id.utils.js.map +1 -0
- package/build/esnext/utils/logger.utils.d.ts +15 -0
- package/build/esnext/utils/logger.utils.js +59 -0
- package/build/esnext/utils/logger.utils.js.map +1 -0
- package/build/esnext/utils/obj.utils.d.ts +55 -0
- package/build/esnext/utils/obj.utils.js +94 -0
- package/build/esnext/utils/obj.utils.js.map +1 -0
- package/build/esnext/utils/response.utils.d.ts +48 -0
- package/build/esnext/utils/response.utils.js +58 -0
- package/build/esnext/utils/response.utils.js.map +1 -0
- package/build/esnext/utils/string.utils.d.ts +37 -0
- package/build/esnext/utils/string.utils.js +46 -0
- package/build/esnext/utils/string.utils.js.map +1 -0
- package/build/esnext/utils/url.utils.d.ts +24 -0
- package/build/esnext/utils/url.utils.js +35 -0
- package/build/esnext/utils/url.utils.js.map +1 -0
- package/build/esnext/utils/validate.utils.d.ts +60 -0
- package/build/esnext/utils/validate.utils.js +105 -0
- package/build/esnext/utils/validate.utils.js.map +1 -0
- package/build/src/config.d.ts +22 -0
- package/build/src/config.js +24 -0
- package/build/src/config.js.map +1 -0
- package/build/src/index.d.ts +19 -0
- package/build/src/index.js +35 -0
- package/build/src/index.js.map +1 -0
- package/build/src/types/api-response.d.ts +44 -0
- package/build/src/types/api-response.js +3 -0
- package/build/src/types/api-response.js.map +1 -0
- package/build/src/utils/array.utils.d.ts +105 -0
- package/build/src/utils/array.utils.js +216 -0
- package/build/src/utils/array.utils.js.map +1 -0
- package/build/src/utils/async.utils.d.ts +119 -0
- package/build/src/utils/async.utils.js +304 -0
- package/build/src/utils/async.utils.js.map +1 -0
- package/build/src/utils/cache.utils.d.ts +90 -0
- package/build/src/utils/cache.utils.js +146 -0
- package/build/src/utils/cache.utils.js.map +1 -0
- package/build/src/utils/context-store.utils.d.ts +85 -0
- package/build/src/utils/context-store.utils.js +100 -0
- package/build/src/utils/context-store.utils.js.map +1 -0
- package/build/src/utils/crypto.utils.d.ts +58 -0
- package/build/src/utils/crypto.utils.js +82 -0
- package/build/src/utils/crypto.utils.js.map +1 -0
- package/build/src/utils/dir.utils.d.ts +75 -0
- package/build/src/utils/dir.utils.js +164 -0
- package/build/src/utils/dir.utils.js.map +1 -0
- package/build/src/utils/env.utils.d.ts +131 -0
- package/build/src/utils/env.utils.js +215 -0
- package/build/src/utils/env.utils.js.map +1 -0
- package/build/src/utils/exception.utils.d.ts +114 -0
- package/build/src/utils/exception.utils.js +162 -0
- package/build/src/utils/exception.utils.js.map +1 -0
- package/build/src/utils/fs.utils.d.ts +32 -0
- package/build/src/utils/fs.utils.js +71 -0
- package/build/src/utils/fs.utils.js.map +1 -0
- package/build/src/utils/http-status-codes.d.ts +357 -0
- package/build/src/utils/http-status-codes.js +361 -0
- package/build/src/utils/http-status-codes.js.map +1 -0
- package/build/src/utils/id.utils.d.ts +35 -0
- package/build/src/utils/id.utils.js +60 -0
- package/build/src/utils/id.utils.js.map +1 -0
- package/build/src/utils/logger.utils.d.ts +15 -0
- package/build/src/utils/logger.utils.js +96 -0
- package/build/src/utils/logger.utils.js.map +1 -0
- package/build/src/utils/obj.utils.d.ts +55 -0
- package/build/src/utils/obj.utils.js +103 -0
- package/build/src/utils/obj.utils.js.map +1 -0
- package/build/src/utils/response.utils.d.ts +48 -0
- package/build/src/utils/response.utils.js +63 -0
- package/build/src/utils/response.utils.js.map +1 -0
- package/build/src/utils/string.utils.d.ts +37 -0
- package/build/src/utils/string.utils.js +54 -0
- package/build/src/utils/string.utils.js.map +1 -0
- package/build/src/utils/url.utils.d.ts +24 -0
- package/build/src/utils/url.utils.js +39 -0
- package/build/src/utils/url.utils.js.map +1 -0
- package/build/src/utils/validate.utils.d.ts +60 -0
- package/build/src/utils/validate.utils.js +115 -0
- package/build/src/utils/validate.utils.js.map +1 -0
- package/package.json +80 -0
|
@@ -0,0 +1,474 @@
|
|
|
1
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
2
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
3
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
4
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
5
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
6
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
7
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
|
+
});
|
|
9
|
+
};
|
|
10
|
+
var __generator = (this && this.__generator) || function (thisArg, body) {
|
|
11
|
+
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
|
|
12
|
+
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
|
|
13
|
+
function verb(n) { return function (v) { return step([n, v]); }; }
|
|
14
|
+
function step(op) {
|
|
15
|
+
if (f) throw new TypeError("Generator is already executing.");
|
|
16
|
+
while (g && (g = 0, op[0] && (_ = 0)), _) try {
|
|
17
|
+
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
|
|
18
|
+
if (y = 0, t) op = [op[0] & 2, t.value];
|
|
19
|
+
switch (op[0]) {
|
|
20
|
+
case 0: case 1: t = op; break;
|
|
21
|
+
case 4: _.label++; return { value: op[1], done: false };
|
|
22
|
+
case 5: _.label++; y = op[1]; op = [0]; continue;
|
|
23
|
+
case 7: op = _.ops.pop(); _.trys.pop(); continue;
|
|
24
|
+
default:
|
|
25
|
+
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
|
|
26
|
+
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
|
|
27
|
+
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
|
|
28
|
+
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
|
|
29
|
+
if (t[2]) _.ops.pop();
|
|
30
|
+
_.trys.pop(); continue;
|
|
31
|
+
}
|
|
32
|
+
op = body.call(thisArg, _);
|
|
33
|
+
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
|
|
34
|
+
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
var __read = (this && this.__read) || function (o, n) {
|
|
38
|
+
var m = typeof Symbol === "function" && o[Symbol.iterator];
|
|
39
|
+
if (!m) return o;
|
|
40
|
+
var i = m.call(o), r, ar = [], e;
|
|
41
|
+
try {
|
|
42
|
+
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
|
|
43
|
+
}
|
|
44
|
+
catch (error) { e = { error: error }; }
|
|
45
|
+
finally {
|
|
46
|
+
try {
|
|
47
|
+
if (r && !r.done && (m = i["return"])) m.call(i);
|
|
48
|
+
}
|
|
49
|
+
finally { if (e) throw e.error; }
|
|
50
|
+
}
|
|
51
|
+
return ar;
|
|
52
|
+
};
|
|
53
|
+
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
|
|
54
|
+
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
|
|
55
|
+
if (ar || !(i in from)) {
|
|
56
|
+
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
|
|
57
|
+
ar[i] = from[i];
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return to.concat(ar || Array.prototype.slice.call(from));
|
|
61
|
+
};
|
|
62
|
+
var __values = (this && this.__values) || function(o) {
|
|
63
|
+
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
|
|
64
|
+
if (m) return m.call(o);
|
|
65
|
+
if (o && typeof o.length === "number") return {
|
|
66
|
+
next: function () {
|
|
67
|
+
if (o && i >= o.length) o = void 0;
|
|
68
|
+
return { value: o && o[i++], done: !o };
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
|
|
72
|
+
};
|
|
73
|
+
/**
|
|
74
|
+
* Delays execution for a specified number of milliseconds.
|
|
75
|
+
*
|
|
76
|
+
* @param {number} ms - The number of milliseconds to sleep.
|
|
77
|
+
* @returns {Promise<void>} A Promise that resolves after the given time.
|
|
78
|
+
*/
|
|
79
|
+
export var sleep = function (ms) {
|
|
80
|
+
return new Promise(function (resolve) { return setTimeout(resolve, ms); });
|
|
81
|
+
};
|
|
82
|
+
/**
|
|
83
|
+
* Creates a debounced version of a function that delays its execution.
|
|
84
|
+
* Provides `.cancel()` and `.flush()` methods.
|
|
85
|
+
*
|
|
86
|
+
* @template T
|
|
87
|
+
* @param {T} fn - The function to debounce.
|
|
88
|
+
* @param {number} delay - Delay in milliseconds.
|
|
89
|
+
* @returns {T & { cancel: () => void; flush: () => void }} A debounced function.
|
|
90
|
+
*/
|
|
91
|
+
export function debounce(fn, delay) {
|
|
92
|
+
var timer = null;
|
|
93
|
+
var pendingArgs = null;
|
|
94
|
+
function debounced() {
|
|
95
|
+
var args = [];
|
|
96
|
+
for (var _i = 0; _i < arguments.length; _i++) {
|
|
97
|
+
args[_i] = arguments[_i];
|
|
98
|
+
}
|
|
99
|
+
pendingArgs = args;
|
|
100
|
+
if (timer)
|
|
101
|
+
clearTimeout(timer);
|
|
102
|
+
timer = setTimeout(function () {
|
|
103
|
+
fn.apply(void 0, __spreadArray([], __read(pendingArgs), false));
|
|
104
|
+
timer = null;
|
|
105
|
+
}, delay);
|
|
106
|
+
}
|
|
107
|
+
debounced.cancel = function () {
|
|
108
|
+
if (timer)
|
|
109
|
+
clearTimeout(timer);
|
|
110
|
+
timer = null;
|
|
111
|
+
pendingArgs = null;
|
|
112
|
+
};
|
|
113
|
+
debounced.flush = function () {
|
|
114
|
+
if (timer) {
|
|
115
|
+
clearTimeout(timer);
|
|
116
|
+
fn.apply(void 0, __spreadArray([], __read(pendingArgs), false));
|
|
117
|
+
timer = null;
|
|
118
|
+
pendingArgs = null;
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
return debounced;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Creates a throttled version of a function that limits its execution rate.
|
|
125
|
+
* Allows control over leading/trailing invocation.
|
|
126
|
+
*
|
|
127
|
+
* @template T
|
|
128
|
+
* @param {T} fn - The function to throttle.
|
|
129
|
+
* @param {number} limit - Minimum time between calls in milliseconds.
|
|
130
|
+
* @param {{ leading?: boolean, trailing?: boolean }} [opts] - Options for leading/trailing edge throttling.
|
|
131
|
+
* @returns {(...args: Parameters<T>) => void} A throttled function.
|
|
132
|
+
*/
|
|
133
|
+
export function throttle(fn, limit, opts) {
|
|
134
|
+
if (opts === void 0) { opts = {
|
|
135
|
+
leading: true,
|
|
136
|
+
trailing: false,
|
|
137
|
+
}; }
|
|
138
|
+
var lastCall = 0;
|
|
139
|
+
var timer = null;
|
|
140
|
+
var savedArgs = null;
|
|
141
|
+
return function () {
|
|
142
|
+
var args = [];
|
|
143
|
+
for (var _i = 0; _i < arguments.length; _i++) {
|
|
144
|
+
args[_i] = arguments[_i];
|
|
145
|
+
}
|
|
146
|
+
var now = Date.now();
|
|
147
|
+
var _a = opts.leading, leading = _a === void 0 ? true : _a, _b = opts.trailing, trailing = _b === void 0 ? false : _b;
|
|
148
|
+
if (!lastCall && !leading)
|
|
149
|
+
lastCall = now;
|
|
150
|
+
var remaining = limit - (now - lastCall);
|
|
151
|
+
if (remaining <= 0) {
|
|
152
|
+
if (timer) {
|
|
153
|
+
clearTimeout(timer);
|
|
154
|
+
timer = null;
|
|
155
|
+
}
|
|
156
|
+
lastCall = now;
|
|
157
|
+
fn.apply(void 0, __spreadArray([], __read(args), false));
|
|
158
|
+
}
|
|
159
|
+
else if (trailing) {
|
|
160
|
+
savedArgs = args;
|
|
161
|
+
if (!timer) {
|
|
162
|
+
timer = setTimeout(function () {
|
|
163
|
+
lastCall = leading ? Date.now() : 0;
|
|
164
|
+
timer = null;
|
|
165
|
+
if (savedArgs)
|
|
166
|
+
fn.apply(void 0, __spreadArray([], __read(savedArgs), false));
|
|
167
|
+
}, remaining);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Retries an asynchronous function a given number of times with optional delay/backoff.
|
|
174
|
+
*
|
|
175
|
+
* @template T
|
|
176
|
+
* @param {() => Promise<T>} fn - The async function to retry.
|
|
177
|
+
* @param {number} [retries=3] - Number of retry attempts.
|
|
178
|
+
* @param {number} [delay=500] - Delay in milliseconds between retries.
|
|
179
|
+
* @param {boolean} [backoff=false] - Use exponential backoff between attempts.
|
|
180
|
+
* @param {(error: unknown, attempt: number) => void} [onRetry] - Callback for each retry attempt.
|
|
181
|
+
* @returns {Promise<T>} The result of the async function if successful.
|
|
182
|
+
* @throws {*} The last encountered error if all retries fail.
|
|
183
|
+
*/
|
|
184
|
+
export function retry(fn_1) {
|
|
185
|
+
return __awaiter(this, arguments, void 0, function (fn, retries, delay, backoff, onRetry) {
|
|
186
|
+
var i, e_1;
|
|
187
|
+
if (retries === void 0) { retries = 3; }
|
|
188
|
+
if (delay === void 0) { delay = 500; }
|
|
189
|
+
if (backoff === void 0) { backoff = false; }
|
|
190
|
+
return __generator(this, function (_a) {
|
|
191
|
+
switch (_a.label) {
|
|
192
|
+
case 0:
|
|
193
|
+
i = 0;
|
|
194
|
+
_a.label = 1;
|
|
195
|
+
case 1:
|
|
196
|
+
if (!(i < retries)) return [3 /*break*/, 7];
|
|
197
|
+
_a.label = 2;
|
|
198
|
+
case 2:
|
|
199
|
+
_a.trys.push([2, 4, , 6]);
|
|
200
|
+
return [4 /*yield*/, fn()];
|
|
201
|
+
case 3: return [2 /*return*/, _a.sent()];
|
|
202
|
+
case 4:
|
|
203
|
+
e_1 = _a.sent();
|
|
204
|
+
if (i === retries - 1)
|
|
205
|
+
throw e_1;
|
|
206
|
+
if (onRetry)
|
|
207
|
+
onRetry(e_1, i + 1);
|
|
208
|
+
return [4 /*yield*/, sleep(backoff ? delay * Math.pow(2, i) : delay)];
|
|
209
|
+
case 5:
|
|
210
|
+
_a.sent();
|
|
211
|
+
return [3 /*break*/, 6];
|
|
212
|
+
case 6:
|
|
213
|
+
i++;
|
|
214
|
+
return [3 /*break*/, 1];
|
|
215
|
+
case 7: throw new Error("Retry failed"); // should never reach here
|
|
216
|
+
}
|
|
217
|
+
});
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
/**
|
|
221
|
+
* Wraps a promise and rejects it if it doesn't resolve within the specified timeout.
|
|
222
|
+
*
|
|
223
|
+
* @template T
|
|
224
|
+
* @param {Promise<T>} promise - The original promise.
|
|
225
|
+
* @param {number} ms - Timeout in milliseconds.
|
|
226
|
+
* @param {string} [message="Operation timed out"] - Optional timeout message.
|
|
227
|
+
* @returns {Promise<T>} A promise that resolves or rejects within the timeout.
|
|
228
|
+
*/
|
|
229
|
+
export function withTimeout(promise, ms, message) {
|
|
230
|
+
if (message === void 0) { message = "Operation timed out"; }
|
|
231
|
+
return new Promise(function (resolve, reject) {
|
|
232
|
+
var timeoutHandle = setTimeout(function () { return reject(new Error(message)); }, ms);
|
|
233
|
+
promise
|
|
234
|
+
.then(function (result) {
|
|
235
|
+
clearTimeout(timeoutHandle);
|
|
236
|
+
resolve(result);
|
|
237
|
+
})
|
|
238
|
+
.catch(function (err) {
|
|
239
|
+
clearTimeout(timeoutHandle);
|
|
240
|
+
reject(err);
|
|
241
|
+
});
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Executes async tasks in true batches.
|
|
246
|
+
* Each batch runs in parallel, but batches run sequentially.
|
|
247
|
+
* All tasks in a batch start at the same time, next batch waits for full completion.
|
|
248
|
+
* NOTE: For more granular concurrency, use a "queue" or "pooled" approach.
|
|
249
|
+
*
|
|
250
|
+
* @template T
|
|
251
|
+
* @param {Array<() => Promise<T>>} tasks - An array of functions that return Promises.
|
|
252
|
+
* @param {number} limit - Number of tasks to run in parallel per batch.
|
|
253
|
+
* @returns {Promise<T[]>} A promise that resolves to an array of resolved values.
|
|
254
|
+
*/
|
|
255
|
+
export function runInBatches(tasks, limit) {
|
|
256
|
+
return __awaiter(this, void 0, void 0, function () {
|
|
257
|
+
var results, i, batch, batchResults;
|
|
258
|
+
return __generator(this, function (_a) {
|
|
259
|
+
switch (_a.label) {
|
|
260
|
+
case 0:
|
|
261
|
+
results = [];
|
|
262
|
+
i = 0;
|
|
263
|
+
_a.label = 1;
|
|
264
|
+
case 1:
|
|
265
|
+
if (!(i < tasks.length)) return [3 /*break*/, 4];
|
|
266
|
+
batch = tasks.slice(i, i + limit);
|
|
267
|
+
return [4 /*yield*/, Promise.all(batch.map(function (fn) { return fn(); }))];
|
|
268
|
+
case 2:
|
|
269
|
+
batchResults = _a.sent();
|
|
270
|
+
results.push.apply(results, __spreadArray([], __read(batchResults), false));
|
|
271
|
+
_a.label = 3;
|
|
272
|
+
case 3:
|
|
273
|
+
i += limit;
|
|
274
|
+
return [3 /*break*/, 1];
|
|
275
|
+
case 4: return [2 /*return*/, results];
|
|
276
|
+
}
|
|
277
|
+
});
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* Wraps a function and ensures it is only called once at a time.
|
|
282
|
+
* Calls made while one is in progress will wait for the same Promise.
|
|
283
|
+
* Optionally, new calls can be dropped while in progress (drop=true).
|
|
284
|
+
*
|
|
285
|
+
* @template TArgs
|
|
286
|
+
* @template TResult
|
|
287
|
+
* @param {(...args: TArgs) => Promise<TResult>} fn - The async function to wrap.
|
|
288
|
+
* @param {boolean} [drop=false] - If true, new calls while one is pending are rejected.
|
|
289
|
+
* @returns {(...args: TArgs) => Promise<TResult>} A wrapped function with singleton behavior.
|
|
290
|
+
*/
|
|
291
|
+
export function singletonAsync(fn, drop) {
|
|
292
|
+
var _this = this;
|
|
293
|
+
if (drop === void 0) { drop = false; }
|
|
294
|
+
var promise = null;
|
|
295
|
+
return function () {
|
|
296
|
+
var args = [];
|
|
297
|
+
for (var _i = 0; _i < arguments.length; _i++) {
|
|
298
|
+
args[_i] = arguments[_i];
|
|
299
|
+
}
|
|
300
|
+
return __awaiter(_this, void 0, void 0, function () {
|
|
301
|
+
return __generator(this, function (_a) {
|
|
302
|
+
if (!promise) {
|
|
303
|
+
promise = fn.apply(void 0, __spreadArray([], __read(args), false)).finally(function () {
|
|
304
|
+
promise = null;
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
else if (drop) {
|
|
308
|
+
return [2 /*return*/, Promise.reject(new Error("Busy: function already running"))];
|
|
309
|
+
}
|
|
310
|
+
return [2 /*return*/, promise];
|
|
311
|
+
});
|
|
312
|
+
});
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* Resolves a list of async tasks in parallel, returning both resolved and rejected results.
|
|
317
|
+
*
|
|
318
|
+
* @template T
|
|
319
|
+
* @param {Array<() => Promise<T>>} tasks - Array of promise-returning functions.
|
|
320
|
+
* @returns {Promise<PromiseSettledResult<T>[]>} Results including status and value/reason.
|
|
321
|
+
*/
|
|
322
|
+
export function settleAll(tasks) {
|
|
323
|
+
return __awaiter(this, void 0, void 0, function () {
|
|
324
|
+
return __generator(this, function (_a) {
|
|
325
|
+
return [2 /*return*/, Promise.allSettled(tasks.map(function (task) { return task(); }))];
|
|
326
|
+
});
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* A simple task queue that executes async tasks with a concurrency limit.
|
|
331
|
+
* Exposes pause, resume, and queue length getters.
|
|
332
|
+
*
|
|
333
|
+
* @param {number} limit - Maximum number of concurrent tasks.
|
|
334
|
+
* @returns {function & { pause: () => void, resume: () => void, length: number, isPaused: boolean }}
|
|
335
|
+
* Enqueue function plus queue controls.
|
|
336
|
+
*/
|
|
337
|
+
export function createTaskQueue(limit) {
|
|
338
|
+
var queue = [];
|
|
339
|
+
var activeCount = 0;
|
|
340
|
+
var paused = false;
|
|
341
|
+
var state = {
|
|
342
|
+
/**
|
|
343
|
+
* Pause task processing.
|
|
344
|
+
*/
|
|
345
|
+
pause: function () {
|
|
346
|
+
paused = true;
|
|
347
|
+
},
|
|
348
|
+
/**
|
|
349
|
+
* Resume task processing.
|
|
350
|
+
*/
|
|
351
|
+
resume: function () {
|
|
352
|
+
paused = false;
|
|
353
|
+
next();
|
|
354
|
+
},
|
|
355
|
+
/**
|
|
356
|
+
* The current length of the queue.
|
|
357
|
+
* @type {number}
|
|
358
|
+
*/
|
|
359
|
+
get length() {
|
|
360
|
+
return queue.length;
|
|
361
|
+
},
|
|
362
|
+
/**
|
|
363
|
+
* Whether the queue is currently paused.
|
|
364
|
+
* @type {boolean}
|
|
365
|
+
*/
|
|
366
|
+
get isPaused() {
|
|
367
|
+
return paused;
|
|
368
|
+
},
|
|
369
|
+
};
|
|
370
|
+
var next = function () {
|
|
371
|
+
if (paused || queue.length === 0 || activeCount >= limit)
|
|
372
|
+
return;
|
|
373
|
+
var task = queue.shift();
|
|
374
|
+
activeCount++;
|
|
375
|
+
task().finally(function () {
|
|
376
|
+
activeCount--;
|
|
377
|
+
next();
|
|
378
|
+
});
|
|
379
|
+
};
|
|
380
|
+
/**
|
|
381
|
+
* Enqueues a new async task to the queue.
|
|
382
|
+
*
|
|
383
|
+
* @template T
|
|
384
|
+
* @param {() => Promise<T>} taskFn - The async task function.
|
|
385
|
+
* @returns {Promise<T>} Promise resolving when task completes.
|
|
386
|
+
*/
|
|
387
|
+
var enqueue = function (taskFn) {
|
|
388
|
+
return __awaiter(this, void 0, void 0, function () {
|
|
389
|
+
var _this = this;
|
|
390
|
+
return __generator(this, function (_a) {
|
|
391
|
+
return [2 /*return*/, new Promise(function (resolve, reject) {
|
|
392
|
+
queue.push(function () { return __awaiter(_this, void 0, void 0, function () {
|
|
393
|
+
var result, err_1;
|
|
394
|
+
return __generator(this, function (_a) {
|
|
395
|
+
switch (_a.label) {
|
|
396
|
+
case 0:
|
|
397
|
+
_a.trys.push([0, 2, , 3]);
|
|
398
|
+
return [4 /*yield*/, taskFn()];
|
|
399
|
+
case 1:
|
|
400
|
+
result = _a.sent();
|
|
401
|
+
resolve(result);
|
|
402
|
+
return [3 /*break*/, 3];
|
|
403
|
+
case 2:
|
|
404
|
+
err_1 = _a.sent();
|
|
405
|
+
reject(err_1);
|
|
406
|
+
return [3 /*break*/, 3];
|
|
407
|
+
case 3: return [2 /*return*/];
|
|
408
|
+
}
|
|
409
|
+
});
|
|
410
|
+
}); });
|
|
411
|
+
next();
|
|
412
|
+
})];
|
|
413
|
+
});
|
|
414
|
+
});
|
|
415
|
+
};
|
|
416
|
+
enqueue.pause = state.pause;
|
|
417
|
+
enqueue.resume = state.resume;
|
|
418
|
+
Object.defineProperty(enqueue, "length", {
|
|
419
|
+
get: function () { return queue.length; },
|
|
420
|
+
});
|
|
421
|
+
Object.defineProperty(enqueue, "isPaused", {
|
|
422
|
+
get: function () { return paused; },
|
|
423
|
+
});
|
|
424
|
+
return enqueue;
|
|
425
|
+
}
|
|
426
|
+
/**
|
|
427
|
+
* Executes async functions sequentially and collects results.
|
|
428
|
+
* Useful when order matters or tasks depend on each other.
|
|
429
|
+
*
|
|
430
|
+
* @template T
|
|
431
|
+
* @param {Array<() => Promise<T>>} tasks - Array of promise-returning functions.
|
|
432
|
+
* @returns {Promise<T[]>} Array of resolved values.
|
|
433
|
+
*/
|
|
434
|
+
export function runInSeries(tasks) {
|
|
435
|
+
return __awaiter(this, void 0, void 0, function () {
|
|
436
|
+
var results, tasks_1, tasks_1_1, task, _a, _b, e_2_1;
|
|
437
|
+
var e_2, _c;
|
|
438
|
+
return __generator(this, function (_d) {
|
|
439
|
+
switch (_d.label) {
|
|
440
|
+
case 0:
|
|
441
|
+
results = [];
|
|
442
|
+
_d.label = 1;
|
|
443
|
+
case 1:
|
|
444
|
+
_d.trys.push([1, 6, 7, 8]);
|
|
445
|
+
tasks_1 = __values(tasks), tasks_1_1 = tasks_1.next();
|
|
446
|
+
_d.label = 2;
|
|
447
|
+
case 2:
|
|
448
|
+
if (!!tasks_1_1.done) return [3 /*break*/, 5];
|
|
449
|
+
task = tasks_1_1.value;
|
|
450
|
+
_b = (_a = results).push;
|
|
451
|
+
return [4 /*yield*/, task()];
|
|
452
|
+
case 3:
|
|
453
|
+
_b.apply(_a, [_d.sent()]);
|
|
454
|
+
_d.label = 4;
|
|
455
|
+
case 4:
|
|
456
|
+
tasks_1_1 = tasks_1.next();
|
|
457
|
+
return [3 /*break*/, 2];
|
|
458
|
+
case 5: return [3 /*break*/, 8];
|
|
459
|
+
case 6:
|
|
460
|
+
e_2_1 = _d.sent();
|
|
461
|
+
e_2 = { error: e_2_1 };
|
|
462
|
+
return [3 /*break*/, 8];
|
|
463
|
+
case 7:
|
|
464
|
+
try {
|
|
465
|
+
if (tasks_1_1 && !tasks_1_1.done && (_c = tasks_1.return)) _c.call(tasks_1);
|
|
466
|
+
}
|
|
467
|
+
finally { if (e_2) throw e_2.error; }
|
|
468
|
+
return [7 /*endfinally*/];
|
|
469
|
+
case 8: return [2 /*return*/, results];
|
|
470
|
+
}
|
|
471
|
+
});
|
|
472
|
+
});
|
|
473
|
+
}
|
|
474
|
+
//# 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,IAAM,KAAK,GAAG,UAAC,EAAU;IAC9B,OAAA,IAAI,OAAO,CAAC,UAAC,OAAO,IAAK,OAAA,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,EAAvB,CAAuB,CAAC;AAAjD,CAAiD,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;QAAC,cAAsB;aAAtB,UAAsB,EAAtB,qBAAsB,EAAtB,IAAsB;YAAtB,yBAAsB;;QACvC,WAAW,GAAG,IAAI,CAAC;QACnB,IAAI,KAAK;YAAE,YAAY,CAAC,KAAK,CAAC,CAAC;QAC/B,KAAK,GAAG,UAAU,CAAC;YACjB,EAAE,wCAAK,WAA6B,WAAE;YACtC,KAAK,GAAG,IAAI,CAAC;QACf,CAAC,EAAE,KAAK,CAAC,CAAC;IACZ,CAAC;IAED,SAAS,CAAC,MAAM,GAAG;QACjB,IAAI,KAAK;YAAE,Y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a,SAAY,EAAC,CAAC;;;;;;;;;;;;;;;;wBAE7B,sBAAO,OAAO,EAAC;;;;CAChB","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
|