@luxass/utils 2.2.1 → 2.3.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.
package/dist/index.d.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  import { isNotNull$1 as isNotNull, isNotNullish$1 as isNotNullish, isNotUndefined$1 as isNotUndefined, isTruthy$1 as isTruthy } from "./guards-C19fJmlu.js";
2
2
  import { clamp$1 as clamp } from "./number-C2E_sOOy.js";
3
3
  import { capitalize$1 as capitalize, dedent$1 as dedent, dedentRaw$1 as dedentRaw, formatStr$1 as formatStr, sanitizeIdentifier$1 as sanitizeIdentifier, toCamelCase$1 as toCamelCase, toKebabCase$1 as toKebabCase, toPascalCase$1 as toPascalCase, toSnakeCase$1 as toSnakeCase } from "./string-CBWIJiC0.js";
4
- import { Arrayable, Awaitable, ElementOf, InferArguments, Nullable, Nullish, Prettify, RemoveIndexSignature } from "./types-B3iMkmi_.js";
4
+ import { ElementOf, InferArguments, MaybeArray, MaybePromise, Nullable, Nullish, Prettify, RemoveIndexSignature } from "./types-QETho94V.js";
5
+ import pRetry from "p-retry";
5
6
 
6
7
  //#region src/common.d.ts
7
8
  declare class InvariantError extends Error {
@@ -20,4 +21,4 @@ declare class InvariantError extends Error {
20
21
  declare function invariant(predicate: unknown, message: string, ...positionals: unknown[]): asserts predicate;
21
22
 
22
23
  //#endregion
23
- export { Arrayable, Awaitable, ElementOf, InferArguments, InvariantError, Nullable, Nullish, Prettify, RemoveIndexSignature, capitalize, clamp, dedent, dedentRaw, formatStr, invariant, isNotNull, isNotNullish, isNotUndefined, isTruthy, sanitizeIdentifier, toCamelCase, toKebabCase, toPascalCase, toSnakeCase };
24
+ export { ElementOf, InferArguments, InvariantError, MaybeArray, MaybePromise, Nullable, Nullish, Prettify, RemoveIndexSignature, capitalize, clamp, dedent, dedentRaw, formatStr, invariant, isNotNull, isNotNullish, isNotUndefined, isTruthy, pRetry as promiseRetry, sanitizeIdentifier, toCamelCase, toKebabCase, toPascalCase, toSnakeCase };
package/dist/index.js CHANGED
@@ -2,6 +2,32 @@ import { isNotNull, isNotNullish, isNotUndefined, isTruthy } from "./guards-O1HG
2
2
  import { capitalize, dedent, dedentRaw, formatStr, sanitizeIdentifier, toCamelCase, toKebabCase, toPascalCase, toSnakeCase } from "./string-pQApOGKP.js";
3
3
  import { clamp } from "./number-BS9T5WGO.js";
4
4
 
5
+ //#region rolldown:runtime
6
+ var __create = Object.create;
7
+ var __defProp = Object.defineProperty;
8
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
9
+ var __getOwnPropNames = Object.getOwnPropertyNames;
10
+ var __getProtoOf = Object.getPrototypeOf;
11
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
12
+ var __commonJS = (cb, mod) => function() {
13
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
14
+ };
15
+ var __copyProps = (to, from, except, desc) => {
16
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
17
+ key = keys[i];
18
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
19
+ get: ((k) => from[k]).bind(null, key),
20
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
21
+ });
22
+ }
23
+ return to;
24
+ };
25
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
26
+ value: mod,
27
+ enumerable: true
28
+ }) : target, mod));
29
+
30
+ //#endregion
5
31
  //#region src/common.ts
6
32
  var InvariantError = class extends Error {
7
33
  constructor(message, ...positionals) {
@@ -24,4 +50,270 @@ function invariant(predicate, message, ...positionals) {
24
50
  }
25
51
 
26
52
  //#endregion
27
- export { InvariantError, capitalize, clamp, dedent, dedentRaw, formatStr, invariant, isNotNull, isNotNullish, isNotUndefined, isTruthy, sanitizeIdentifier, toCamelCase, toKebabCase, toPascalCase, toSnakeCase };
53
+ //#region node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry_operation.js
54
+ var require_retry_operation = __commonJS({ "node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry_operation.js"(exports, module) {
55
+ function RetryOperation$1(timeouts, options) {
56
+ if (typeof options === "boolean") options = { forever: options };
57
+ this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));
58
+ this._timeouts = timeouts;
59
+ this._options = options || {};
60
+ this._maxRetryTime = options && options.maxRetryTime || Infinity;
61
+ this._fn = null;
62
+ this._errors = [];
63
+ this._attempts = 1;
64
+ this._operationTimeout = null;
65
+ this._operationTimeoutCb = null;
66
+ this._timeout = null;
67
+ this._operationStart = null;
68
+ this._timer = null;
69
+ if (this._options.forever) this._cachedTimeouts = this._timeouts.slice(0);
70
+ }
71
+ module.exports = RetryOperation$1;
72
+ RetryOperation$1.prototype.reset = function() {
73
+ this._attempts = 1;
74
+ this._timeouts = this._originalTimeouts.slice(0);
75
+ };
76
+ RetryOperation$1.prototype.stop = function() {
77
+ if (this._timeout) clearTimeout(this._timeout);
78
+ if (this._timer) clearTimeout(this._timer);
79
+ this._timeouts = [];
80
+ this._cachedTimeouts = null;
81
+ };
82
+ RetryOperation$1.prototype.retry = function(err) {
83
+ if (this._timeout) clearTimeout(this._timeout);
84
+ if (!err) return false;
85
+ var currentTime = new Date().getTime();
86
+ if (err && currentTime - this._operationStart >= this._maxRetryTime) {
87
+ this._errors.push(err);
88
+ this._errors.unshift(new Error("RetryOperation timeout occurred"));
89
+ return false;
90
+ }
91
+ this._errors.push(err);
92
+ var timeout = this._timeouts.shift();
93
+ if (timeout === void 0) if (this._cachedTimeouts) {
94
+ this._errors.splice(0, this._errors.length - 1);
95
+ timeout = this._cachedTimeouts.slice(-1);
96
+ } else return false;
97
+ var self = this;
98
+ this._timer = setTimeout(function() {
99
+ self._attempts++;
100
+ if (self._operationTimeoutCb) {
101
+ self._timeout = setTimeout(function() {
102
+ self._operationTimeoutCb(self._attempts);
103
+ }, self._operationTimeout);
104
+ if (self._options.unref) self._timeout.unref();
105
+ }
106
+ self._fn(self._attempts);
107
+ }, timeout);
108
+ if (this._options.unref) this._timer.unref();
109
+ return true;
110
+ };
111
+ RetryOperation$1.prototype.attempt = function(fn, timeoutOps) {
112
+ this._fn = fn;
113
+ if (timeoutOps) {
114
+ if (timeoutOps.timeout) this._operationTimeout = timeoutOps.timeout;
115
+ if (timeoutOps.cb) this._operationTimeoutCb = timeoutOps.cb;
116
+ }
117
+ var self = this;
118
+ if (this._operationTimeoutCb) this._timeout = setTimeout(function() {
119
+ self._operationTimeoutCb();
120
+ }, self._operationTimeout);
121
+ this._operationStart = new Date().getTime();
122
+ this._fn(this._attempts);
123
+ };
124
+ RetryOperation$1.prototype.try = function(fn) {
125
+ console.log("Using RetryOperation.try() is deprecated");
126
+ this.attempt(fn);
127
+ };
128
+ RetryOperation$1.prototype.start = function(fn) {
129
+ console.log("Using RetryOperation.start() is deprecated");
130
+ this.attempt(fn);
131
+ };
132
+ RetryOperation$1.prototype.start = RetryOperation$1.prototype.try;
133
+ RetryOperation$1.prototype.errors = function() {
134
+ return this._errors;
135
+ };
136
+ RetryOperation$1.prototype.attempts = function() {
137
+ return this._attempts;
138
+ };
139
+ RetryOperation$1.prototype.mainError = function() {
140
+ if (this._errors.length === 0) return null;
141
+ var counts = {};
142
+ var mainError = null;
143
+ var mainErrorCount = 0;
144
+ for (var i = 0; i < this._errors.length; i++) {
145
+ var error = this._errors[i];
146
+ var message = error.message;
147
+ var count = (counts[message] || 0) + 1;
148
+ counts[message] = count;
149
+ if (count >= mainErrorCount) {
150
+ mainError = error;
151
+ mainErrorCount = count;
152
+ }
153
+ }
154
+ return mainError;
155
+ };
156
+ } });
157
+
158
+ //#endregion
159
+ //#region node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry.js
160
+ var require_retry$1 = __commonJS({ "node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry.js"(exports) {
161
+ var RetryOperation = require_retry_operation();
162
+ exports.operation = function(options) {
163
+ var timeouts = exports.timeouts(options);
164
+ return new RetryOperation(timeouts, {
165
+ forever: options && (options.forever || options.retries === Infinity),
166
+ unref: options && options.unref,
167
+ maxRetryTime: options && options.maxRetryTime
168
+ });
169
+ };
170
+ exports.timeouts = function(options) {
171
+ if (options instanceof Array) return [].concat(options);
172
+ var opts = {
173
+ retries: 10,
174
+ factor: 2,
175
+ minTimeout: 1 * 1e3,
176
+ maxTimeout: Infinity,
177
+ randomize: false
178
+ };
179
+ for (var key in options) opts[key] = options[key];
180
+ if (opts.minTimeout > opts.maxTimeout) throw new Error("minTimeout is greater than maxTimeout");
181
+ var timeouts = [];
182
+ for (var i = 0; i < opts.retries; i++) timeouts.push(this.createTimeout(i, opts));
183
+ if (options && options.forever && !timeouts.length) timeouts.push(this.createTimeout(i, opts));
184
+ timeouts.sort(function(a, b) {
185
+ return a - b;
186
+ });
187
+ return timeouts;
188
+ };
189
+ exports.createTimeout = function(attempt, opts) {
190
+ var random = opts.randomize ? Math.random() + 1 : 1;
191
+ var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt));
192
+ timeout = Math.min(timeout, opts.maxTimeout);
193
+ return timeout;
194
+ };
195
+ exports.wrap = function(obj, options, methods) {
196
+ if (options instanceof Array) {
197
+ methods = options;
198
+ options = null;
199
+ }
200
+ if (!methods) {
201
+ methods = [];
202
+ for (var key in obj) if (typeof obj[key] === "function") methods.push(key);
203
+ }
204
+ for (var i = 0; i < methods.length; i++) {
205
+ var method = methods[i];
206
+ var original = obj[method];
207
+ obj[method] = function retryWrapper(original$1) {
208
+ var op = exports.operation(options);
209
+ var args = Array.prototype.slice.call(arguments, 1);
210
+ var callback = args.pop();
211
+ args.push(function(err) {
212
+ if (op.retry(err)) return;
213
+ if (err) arguments[0] = op.mainError();
214
+ callback.apply(this, arguments);
215
+ });
216
+ op.attempt(function() {
217
+ original$1.apply(obj, args);
218
+ });
219
+ }.bind(obj, original);
220
+ obj[method].options = options;
221
+ }
222
+ };
223
+ } });
224
+
225
+ //#endregion
226
+ //#region node_modules/.pnpm/retry@0.13.1/node_modules/retry/index.js
227
+ var require_retry = __commonJS({ "node_modules/.pnpm/retry@0.13.1/node_modules/retry/index.js"(exports, module) {
228
+ module.exports = require_retry$1();
229
+ } });
230
+
231
+ //#endregion
232
+ //#region node_modules/.pnpm/is-network-error@1.1.0/node_modules/is-network-error/index.js
233
+ const objectToString = Object.prototype.toString;
234
+ const isError = (value) => objectToString.call(value) === "[object Error]";
235
+ const errorMessages = new Set([
236
+ "network error",
237
+ "Failed to fetch",
238
+ "NetworkError when attempting to fetch resource.",
239
+ "The Internet connection appears to be offline.",
240
+ "Load failed",
241
+ "Network request failed",
242
+ "fetch failed",
243
+ "terminated"
244
+ ]);
245
+ function isNetworkError(error) {
246
+ const isValid = error && isError(error) && error.name === "TypeError" && typeof error.message === "string";
247
+ if (!isValid) return false;
248
+ if (error.message === "Load failed") return error.stack === void 0;
249
+ return errorMessages.has(error.message);
250
+ }
251
+
252
+ //#endregion
253
+ //#region node_modules/.pnpm/p-retry@6.2.1/node_modules/p-retry/index.js
254
+ var import_retry = __toESM(require_retry(), 1);
255
+ var AbortError = class extends Error {
256
+ constructor(message) {
257
+ super();
258
+ if (message instanceof Error) {
259
+ this.originalError = message;
260
+ ({message} = message);
261
+ } else {
262
+ this.originalError = new Error(message);
263
+ this.originalError.stack = this.stack;
264
+ }
265
+ this.name = "AbortError";
266
+ this.message = message;
267
+ }
268
+ };
269
+ const decorateErrorWithCounts = (error, attemptNumber, options) => {
270
+ const retriesLeft = options.retries - (attemptNumber - 1);
271
+ error.attemptNumber = attemptNumber;
272
+ error.retriesLeft = retriesLeft;
273
+ return error;
274
+ };
275
+ async function pRetry(input, options) {
276
+ return new Promise((resolve, reject) => {
277
+ options = { ...options };
278
+ options.onFailedAttempt ??= () => {};
279
+ options.shouldRetry ??= () => true;
280
+ options.retries ??= 10;
281
+ const operation = import_retry.default.operation(options);
282
+ const abortHandler = () => {
283
+ operation.stop();
284
+ reject(options.signal?.reason);
285
+ };
286
+ if (options.signal && !options.signal.aborted) options.signal.addEventListener("abort", abortHandler, { once: true });
287
+ const cleanUp = () => {
288
+ options.signal?.removeEventListener("abort", abortHandler);
289
+ operation.stop();
290
+ };
291
+ operation.attempt(async (attemptNumber) => {
292
+ try {
293
+ const result = await input(attemptNumber);
294
+ cleanUp();
295
+ resolve(result);
296
+ } catch (error) {
297
+ try {
298
+ if (!(error instanceof Error)) throw new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`);
299
+ if (error instanceof AbortError) throw error.originalError;
300
+ if (error instanceof TypeError && !isNetworkError(error)) throw error;
301
+ decorateErrorWithCounts(error, attemptNumber, options);
302
+ if (!await options.shouldRetry(error)) {
303
+ operation.stop();
304
+ reject(error);
305
+ }
306
+ await options.onFailedAttempt(error);
307
+ if (!operation.retry(error)) throw operation.mainError();
308
+ } catch (finalError) {
309
+ decorateErrorWithCounts(finalError, attemptNumber, options);
310
+ cleanUp();
311
+ reject(finalError);
312
+ }
313
+ }
314
+ });
315
+ });
316
+ }
317
+
318
+ //#endregion
319
+ export { InvariantError, capitalize, clamp, dedent, dedentRaw, formatStr, invariant, isNotNull, isNotNullish, isNotUndefined, isTruthy, pRetry as promiseRetry, sanitizeIdentifier, toCamelCase, toKebabCase, toPascalCase, toSnakeCase };
@@ -1,16 +1,4 @@
1
1
  //#region src/types.d.ts
2
- /**
3
- * Whatever type, or Promise of that type
4
- * @param T - Type
5
- * @returns T or Promise<T>
6
- *
7
- * @example
8
- * ```ts
9
- * type A = Awaitable<string>
10
- * // string | Promise<string>
11
- * ```
12
- */
13
- type Awaitable<T> = T | PromiseLike<T>;
14
2
  /**
15
3
  * Whatever type, or null
16
4
  * @param T - Type
@@ -36,9 +24,13 @@ type Nullable<T> = T | null;
36
24
  */
37
25
  type Nullish<T> = T | null | undefined;
38
26
  /**
39
- * Array, or not yet
27
+ * A type that can be an array or a single value.
28
+ */
29
+ type MaybeArray<T> = T | T[];
30
+ /**
31
+ * A type that can be a value or a promise.
40
32
  */
41
- type Arrayable<T> = T | Array<T>;
33
+ type MaybePromise<T> = T | Promise<T>;
42
34
  /**
43
35
  * Infers the element type of an array
44
36
  * @param T - Array type
@@ -92,4 +84,4 @@ type Prettify<T> = { [K in keyof T]: T[K] } & {};
92
84
  type RemoveIndexSignature<T> = { [K in keyof T as {} extends Record<K, 1> ? never : K]: T[K] };
93
85
 
94
86
  //#endregion
95
- export { Arrayable, Awaitable, ElementOf, InferArguments, Nullable, Nullish, Prettify, RemoveIndexSignature };
87
+ export { ElementOf, InferArguments, MaybeArray, MaybePromise, Nullable, Nullish, Prettify, RemoveIndexSignature };
package/dist/types.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { Arrayable, Awaitable, ElementOf, InferArguments, Nullable, Nullish, Prettify, RemoveIndexSignature } from "./types-B3iMkmi_.js";
2
- export { Arrayable, Awaitable, ElementOf, InferArguments, Nullable, Nullish, Prettify, RemoveIndexSignature };
1
+ import { ElementOf, InferArguments, MaybeArray, MaybePromise, Nullable, Nullish, Prettify, RemoveIndexSignature } from "./types-QETho94V.js";
2
+ export { ElementOf, InferArguments, MaybeArray, MaybePromise, Nullable, Nullish, Prettify, RemoveIndexSignature };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@luxass/utils",
3
- "version": "2.2.1",
3
+ "version": "2.3.0",
4
4
  "description": "A collection of utilities for JavaScript/TypeScript",
5
5
  "type": "module",
6
6
  "author": {
@@ -38,6 +38,9 @@
38
38
  "engines": {
39
39
  "node": ">=20"
40
40
  },
41
+ "dependencies": {
42
+ "p-retry": "^6.2.1"
43
+ },
41
44
  "devDependencies": {
42
45
  "@luxass/eslint-config": "^4.18.1",
43
46
  "@types/node": "^22.15.2",