@goodbyenjn/utils 1.3.1 → 26.1.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.
@@ -0,0 +1,1082 @@
1
+ import { Dr as t, F as isFunction, Nn as e$4, On as e, P as isPromiseLike, Pn as e$3, Sn as e$2, Tn as e$7, bn as e$6, gn as e$1, hn as e$5 } from "./chunk-267b337b.js";
2
+
3
+ //#region rolldown:runtime
4
+ var __create = Object.create;
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7
+ var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __getProtoOf = Object.getPrototypeOf;
9
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
10
+ var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
14
+ key = keys[i];
15
+ if (!__hasOwnProp.call(to, key) && key !== except) {
16
+ __defProp(to, key, {
17
+ get: ((k) => from[k]).bind(null, key),
18
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
19
+ });
20
+ }
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
31
+ //#region node_modules/.pnpm/safe-stable-stringify@2.5.0/node_modules/safe-stable-stringify/index.js
32
+ var require_safe_stable_stringify = /* @__PURE__ */ __commonJSMin(((exports, module) => {
33
+ const { hasOwnProperty } = Object.prototype;
34
+ const stringify = configure();
35
+ stringify.configure = configure;
36
+ stringify.stringify = stringify;
37
+ stringify.default = stringify;
38
+ exports.stringify = stringify;
39
+ exports.configure = configure;
40
+ module.exports = stringify;
41
+ const strEscapeSequencesRegExp = /[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;
42
+ function strEscape(str) {
43
+ if (str.length < 5e3 && !strEscapeSequencesRegExp.test(str)) return `"${str}"`;
44
+ return JSON.stringify(str);
45
+ }
46
+ function sort(array, comparator) {
47
+ if (array.length > 200 || comparator) return array.sort(comparator);
48
+ for (let i = 1; i < array.length; i++) {
49
+ const currentValue = array[i];
50
+ let position = i;
51
+ while (position !== 0 && array[position - 1] > currentValue) {
52
+ array[position] = array[position - 1];
53
+ position--;
54
+ }
55
+ array[position] = currentValue;
56
+ }
57
+ return array;
58
+ }
59
+ const typedArrayPrototypeGetSymbolToStringTag = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array())), Symbol.toStringTag).get;
60
+ function isTypedArrayWithEntries(value) {
61
+ return typedArrayPrototypeGetSymbolToStringTag.call(value) !== void 0 && value.length !== 0;
62
+ }
63
+ function stringifyTypedArray(array, separator, maximumBreadth) {
64
+ if (array.length < maximumBreadth) maximumBreadth = array.length;
65
+ const whitespace = separator === "," ? "" : " ";
66
+ let res = `"0":${whitespace}${array[0]}`;
67
+ for (let i = 1; i < maximumBreadth; i++) res += `${separator}"${i}":${whitespace}${array[i]}`;
68
+ return res;
69
+ }
70
+ function getCircularValueOption(options) {
71
+ if (hasOwnProperty.call(options, "circularValue")) {
72
+ const circularValue = options.circularValue;
73
+ if (typeof circularValue === "string") return `"${circularValue}"`;
74
+ if (circularValue == null) return circularValue;
75
+ if (circularValue === Error || circularValue === TypeError) return { toString() {
76
+ throw new TypeError("Converting circular structure to JSON");
77
+ } };
78
+ throw new TypeError("The \"circularValue\" argument must be of type string or the value null or undefined");
79
+ }
80
+ return "\"[Circular]\"";
81
+ }
82
+ function getDeterministicOption(options) {
83
+ let value;
84
+ if (hasOwnProperty.call(options, "deterministic")) {
85
+ value = options.deterministic;
86
+ if (typeof value !== "boolean" && typeof value !== "function") throw new TypeError("The \"deterministic\" argument must be of type boolean or comparator function");
87
+ }
88
+ return value === void 0 ? true : value;
89
+ }
90
+ function getBooleanOption(options, key) {
91
+ let value;
92
+ if (hasOwnProperty.call(options, key)) {
93
+ value = options[key];
94
+ if (typeof value !== "boolean") throw new TypeError(`The "${key}" argument must be of type boolean`);
95
+ }
96
+ return value === void 0 ? true : value;
97
+ }
98
+ function getPositiveIntegerOption(options, key) {
99
+ let value;
100
+ if (hasOwnProperty.call(options, key)) {
101
+ value = options[key];
102
+ if (typeof value !== "number") throw new TypeError(`The "${key}" argument must be of type number`);
103
+ if (!Number.isInteger(value)) throw new TypeError(`The "${key}" argument must be an integer`);
104
+ if (value < 1) throw new RangeError(`The "${key}" argument must be >= 1`);
105
+ }
106
+ return value === void 0 ? Infinity : value;
107
+ }
108
+ function getItemCount(number) {
109
+ if (number === 1) return "1 item";
110
+ return `${number} items`;
111
+ }
112
+ function getUniqueReplacerSet(replacerArray) {
113
+ const replacerSet = /* @__PURE__ */ new Set();
114
+ for (const value of replacerArray) if (typeof value === "string" || typeof value === "number") replacerSet.add(String(value));
115
+ return replacerSet;
116
+ }
117
+ function getStrictOption(options) {
118
+ if (hasOwnProperty.call(options, "strict")) {
119
+ const value = options.strict;
120
+ if (typeof value !== "boolean") throw new TypeError("The \"strict\" argument must be of type boolean");
121
+ if (value) return (value$1) => {
122
+ let message = `Object can not safely be stringified. Received type ${typeof value$1}`;
123
+ if (typeof value$1 !== "function") message += ` (${value$1.toString()})`;
124
+ throw new Error(message);
125
+ };
126
+ }
127
+ }
128
+ function configure(options) {
129
+ options = { ...options };
130
+ const fail = getStrictOption(options);
131
+ if (fail) {
132
+ if (options.bigint === void 0) options.bigint = false;
133
+ if (!("circularValue" in options)) options.circularValue = Error;
134
+ }
135
+ const circularValue = getCircularValueOption(options);
136
+ const bigint = getBooleanOption(options, "bigint");
137
+ const deterministic = getDeterministicOption(options);
138
+ const comparator = typeof deterministic === "function" ? deterministic : void 0;
139
+ const maximumDepth = getPositiveIntegerOption(options, "maximumDepth");
140
+ const maximumBreadth = getPositiveIntegerOption(options, "maximumBreadth");
141
+ function stringifyFnReplacer(key, parent, stack, replacer, spacer, indentation) {
142
+ let value = parent[key];
143
+ if (typeof value === "object" && value !== null && typeof value.toJSON === "function") value = value.toJSON(key);
144
+ value = replacer.call(parent, key, value);
145
+ switch (typeof value) {
146
+ case "string": return strEscape(value);
147
+ case "object": {
148
+ if (value === null) return "null";
149
+ if (stack.indexOf(value) !== -1) return circularValue;
150
+ let res = "";
151
+ let join$1 = ",";
152
+ const originalIndentation = indentation;
153
+ if (Array.isArray(value)) {
154
+ if (value.length === 0) return "[]";
155
+ if (maximumDepth < stack.length + 1) return "\"[Array]\"";
156
+ stack.push(value);
157
+ if (spacer !== "") {
158
+ indentation += spacer;
159
+ res += `\n${indentation}`;
160
+ join$1 = `,\n${indentation}`;
161
+ }
162
+ const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
163
+ let i = 0;
164
+ for (; i < maximumValuesToStringify - 1; i++) {
165
+ const tmp$1 = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation);
166
+ res += tmp$1 !== void 0 ? tmp$1 : "null";
167
+ res += join$1;
168
+ }
169
+ const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation);
170
+ res += tmp !== void 0 ? tmp : "null";
171
+ if (value.length - 1 > maximumBreadth) {
172
+ const removedKeys = value.length - maximumBreadth - 1;
173
+ res += `${join$1}"... ${getItemCount(removedKeys)} not stringified"`;
174
+ }
175
+ if (spacer !== "") res += `\n${originalIndentation}`;
176
+ stack.pop();
177
+ return `[${res}]`;
178
+ }
179
+ let keys = Object.keys(value);
180
+ const keyLength = keys.length;
181
+ if (keyLength === 0) return "{}";
182
+ if (maximumDepth < stack.length + 1) return "\"[Object]\"";
183
+ let whitespace = "";
184
+ let separator = "";
185
+ if (spacer !== "") {
186
+ indentation += spacer;
187
+ join$1 = `,\n${indentation}`;
188
+ whitespace = " ";
189
+ }
190
+ const maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth);
191
+ if (deterministic && !isTypedArrayWithEntries(value)) keys = sort(keys, comparator);
192
+ stack.push(value);
193
+ for (let i = 0; i < maximumPropertiesToStringify; i++) {
194
+ const key$1 = keys[i];
195
+ const tmp = stringifyFnReplacer(key$1, value, stack, replacer, spacer, indentation);
196
+ if (tmp !== void 0) {
197
+ res += `${separator}${strEscape(key$1)}:${whitespace}${tmp}`;
198
+ separator = join$1;
199
+ }
200
+ }
201
+ if (keyLength > maximumBreadth) {
202
+ const removedKeys = keyLength - maximumBreadth;
203
+ res += `${separator}"...":${whitespace}"${getItemCount(removedKeys)} not stringified"`;
204
+ separator = join$1;
205
+ }
206
+ if (spacer !== "" && separator.length > 1) res = `\n${indentation}${res}\n${originalIndentation}`;
207
+ stack.pop();
208
+ return `{${res}}`;
209
+ }
210
+ case "number": return isFinite(value) ? String(value) : fail ? fail(value) : "null";
211
+ case "boolean": return value === true ? "true" : "false";
212
+ case "undefined": return;
213
+ case "bigint": if (bigint) return String(value);
214
+ default: return fail ? fail(value) : void 0;
215
+ }
216
+ }
217
+ function stringifyArrayReplacer(key, value, stack, replacer, spacer, indentation) {
218
+ if (typeof value === "object" && value !== null && typeof value.toJSON === "function") value = value.toJSON(key);
219
+ switch (typeof value) {
220
+ case "string": return strEscape(value);
221
+ case "object": {
222
+ if (value === null) return "null";
223
+ if (stack.indexOf(value) !== -1) return circularValue;
224
+ const originalIndentation = indentation;
225
+ let res = "";
226
+ let join$1 = ",";
227
+ if (Array.isArray(value)) {
228
+ if (value.length === 0) return "[]";
229
+ if (maximumDepth < stack.length + 1) return "\"[Array]\"";
230
+ stack.push(value);
231
+ if (spacer !== "") {
232
+ indentation += spacer;
233
+ res += `\n${indentation}`;
234
+ join$1 = `,\n${indentation}`;
235
+ }
236
+ const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
237
+ let i = 0;
238
+ for (; i < maximumValuesToStringify - 1; i++) {
239
+ const tmp$1 = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation);
240
+ res += tmp$1 !== void 0 ? tmp$1 : "null";
241
+ res += join$1;
242
+ }
243
+ const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation);
244
+ res += tmp !== void 0 ? tmp : "null";
245
+ if (value.length - 1 > maximumBreadth) {
246
+ const removedKeys = value.length - maximumBreadth - 1;
247
+ res += `${join$1}"... ${getItemCount(removedKeys)} not stringified"`;
248
+ }
249
+ if (spacer !== "") res += `\n${originalIndentation}`;
250
+ stack.pop();
251
+ return `[${res}]`;
252
+ }
253
+ stack.push(value);
254
+ let whitespace = "";
255
+ if (spacer !== "") {
256
+ indentation += spacer;
257
+ join$1 = `,\n${indentation}`;
258
+ whitespace = " ";
259
+ }
260
+ let separator = "";
261
+ for (const key$1 of replacer) {
262
+ const tmp = stringifyArrayReplacer(key$1, value[key$1], stack, replacer, spacer, indentation);
263
+ if (tmp !== void 0) {
264
+ res += `${separator}${strEscape(key$1)}:${whitespace}${tmp}`;
265
+ separator = join$1;
266
+ }
267
+ }
268
+ if (spacer !== "" && separator.length > 1) res = `\n${indentation}${res}\n${originalIndentation}`;
269
+ stack.pop();
270
+ return `{${res}}`;
271
+ }
272
+ case "number": return isFinite(value) ? String(value) : fail ? fail(value) : "null";
273
+ case "boolean": return value === true ? "true" : "false";
274
+ case "undefined": return;
275
+ case "bigint": if (bigint) return String(value);
276
+ default: return fail ? fail(value) : void 0;
277
+ }
278
+ }
279
+ function stringifyIndent(key, value, stack, spacer, indentation) {
280
+ switch (typeof value) {
281
+ case "string": return strEscape(value);
282
+ case "object": {
283
+ if (value === null) return "null";
284
+ if (typeof value.toJSON === "function") {
285
+ value = value.toJSON(key);
286
+ if (typeof value !== "object") return stringifyIndent(key, value, stack, spacer, indentation);
287
+ if (value === null) return "null";
288
+ }
289
+ if (stack.indexOf(value) !== -1) return circularValue;
290
+ const originalIndentation = indentation;
291
+ if (Array.isArray(value)) {
292
+ if (value.length === 0) return "[]";
293
+ if (maximumDepth < stack.length + 1) return "\"[Array]\"";
294
+ stack.push(value);
295
+ indentation += spacer;
296
+ let res$1 = `\n${indentation}`;
297
+ const join$2 = `,\n${indentation}`;
298
+ const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
299
+ let i = 0;
300
+ for (; i < maximumValuesToStringify - 1; i++) {
301
+ const tmp$1 = stringifyIndent(String(i), value[i], stack, spacer, indentation);
302
+ res$1 += tmp$1 !== void 0 ? tmp$1 : "null";
303
+ res$1 += join$2;
304
+ }
305
+ const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation);
306
+ res$1 += tmp !== void 0 ? tmp : "null";
307
+ if (value.length - 1 > maximumBreadth) {
308
+ const removedKeys = value.length - maximumBreadth - 1;
309
+ res$1 += `${join$2}"... ${getItemCount(removedKeys)} not stringified"`;
310
+ }
311
+ res$1 += `\n${originalIndentation}`;
312
+ stack.pop();
313
+ return `[${res$1}]`;
314
+ }
315
+ let keys = Object.keys(value);
316
+ const keyLength = keys.length;
317
+ if (keyLength === 0) return "{}";
318
+ if (maximumDepth < stack.length + 1) return "\"[Object]\"";
319
+ indentation += spacer;
320
+ const join$1 = `,\n${indentation}`;
321
+ let res = "";
322
+ let separator = "";
323
+ let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth);
324
+ if (isTypedArrayWithEntries(value)) {
325
+ res += stringifyTypedArray(value, join$1, maximumBreadth);
326
+ keys = keys.slice(value.length);
327
+ maximumPropertiesToStringify -= value.length;
328
+ separator = join$1;
329
+ }
330
+ if (deterministic) keys = sort(keys, comparator);
331
+ stack.push(value);
332
+ for (let i = 0; i < maximumPropertiesToStringify; i++) {
333
+ const key$1 = keys[i];
334
+ const tmp = stringifyIndent(key$1, value[key$1], stack, spacer, indentation);
335
+ if (tmp !== void 0) {
336
+ res += `${separator}${strEscape(key$1)}: ${tmp}`;
337
+ separator = join$1;
338
+ }
339
+ }
340
+ if (keyLength > maximumBreadth) {
341
+ const removedKeys = keyLength - maximumBreadth;
342
+ res += `${separator}"...": "${getItemCount(removedKeys)} not stringified"`;
343
+ separator = join$1;
344
+ }
345
+ if (separator !== "") res = `\n${indentation}${res}\n${originalIndentation}`;
346
+ stack.pop();
347
+ return `{${res}}`;
348
+ }
349
+ case "number": return isFinite(value) ? String(value) : fail ? fail(value) : "null";
350
+ case "boolean": return value === true ? "true" : "false";
351
+ case "undefined": return;
352
+ case "bigint": if (bigint) return String(value);
353
+ default: return fail ? fail(value) : void 0;
354
+ }
355
+ }
356
+ function stringifySimple(key, value, stack) {
357
+ switch (typeof value) {
358
+ case "string": return strEscape(value);
359
+ case "object": {
360
+ if (value === null) return "null";
361
+ if (typeof value.toJSON === "function") {
362
+ value = value.toJSON(key);
363
+ if (typeof value !== "object") return stringifySimple(key, value, stack);
364
+ if (value === null) return "null";
365
+ }
366
+ if (stack.indexOf(value) !== -1) return circularValue;
367
+ let res = "";
368
+ const hasLength = value.length !== void 0;
369
+ if (hasLength && Array.isArray(value)) {
370
+ if (value.length === 0) return "[]";
371
+ if (maximumDepth < stack.length + 1) return "\"[Array]\"";
372
+ stack.push(value);
373
+ const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
374
+ let i = 0;
375
+ for (; i < maximumValuesToStringify - 1; i++) {
376
+ const tmp$1 = stringifySimple(String(i), value[i], stack);
377
+ res += tmp$1 !== void 0 ? tmp$1 : "null";
378
+ res += ",";
379
+ }
380
+ const tmp = stringifySimple(String(i), value[i], stack);
381
+ res += tmp !== void 0 ? tmp : "null";
382
+ if (value.length - 1 > maximumBreadth) {
383
+ const removedKeys = value.length - maximumBreadth - 1;
384
+ res += `,"... ${getItemCount(removedKeys)} not stringified"`;
385
+ }
386
+ stack.pop();
387
+ return `[${res}]`;
388
+ }
389
+ let keys = Object.keys(value);
390
+ const keyLength = keys.length;
391
+ if (keyLength === 0) return "{}";
392
+ if (maximumDepth < stack.length + 1) return "\"[Object]\"";
393
+ let separator = "";
394
+ let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth);
395
+ if (hasLength && isTypedArrayWithEntries(value)) {
396
+ res += stringifyTypedArray(value, ",", maximumBreadth);
397
+ keys = keys.slice(value.length);
398
+ maximumPropertiesToStringify -= value.length;
399
+ separator = ",";
400
+ }
401
+ if (deterministic) keys = sort(keys, comparator);
402
+ stack.push(value);
403
+ for (let i = 0; i < maximumPropertiesToStringify; i++) {
404
+ const key$1 = keys[i];
405
+ const tmp = stringifySimple(key$1, value[key$1], stack);
406
+ if (tmp !== void 0) {
407
+ res += `${separator}${strEscape(key$1)}:${tmp}`;
408
+ separator = ",";
409
+ }
410
+ }
411
+ if (keyLength > maximumBreadth) {
412
+ const removedKeys = keyLength - maximumBreadth;
413
+ res += `${separator}"...":"${getItemCount(removedKeys)} not stringified"`;
414
+ }
415
+ stack.pop();
416
+ return `{${res}}`;
417
+ }
418
+ case "number": return isFinite(value) ? String(value) : fail ? fail(value) : "null";
419
+ case "boolean": return value === true ? "true" : "false";
420
+ case "undefined": return;
421
+ case "bigint": if (bigint) return String(value);
422
+ default: return fail ? fail(value) : void 0;
423
+ }
424
+ }
425
+ function stringify$1(value, replacer, space) {
426
+ if (arguments.length > 1) {
427
+ let spacer = "";
428
+ if (typeof space === "number") spacer = " ".repeat(Math.min(space, 10));
429
+ else if (typeof space === "string") spacer = space.slice(0, 10);
430
+ if (replacer != null) {
431
+ if (typeof replacer === "function") return stringifyFnReplacer("", { "": value }, [], replacer, spacer, "");
432
+ if (Array.isArray(replacer)) return stringifyArrayReplacer("", value, [], getUniqueReplacerSet(replacer), spacer, "");
433
+ }
434
+ if (spacer.length !== 0) return stringifyIndent("", value, [], spacer, "");
435
+ }
436
+ return stringifySimple("", value, []);
437
+ }
438
+ return stringify$1;
439
+ }
440
+ }));
441
+
442
+ //#endregion
443
+ //#region node_modules/.pnpm/safe-stable-stringify@2.5.0/node_modules/safe-stable-stringify/esm/wrapper.js
444
+ var import_safe_stable_stringify = /* @__PURE__ */ __toESM(require_safe_stable_stringify(), 1);
445
+ const configure = import_safe_stable_stringify.configure;
446
+
447
+ //#endregion
448
+ //#region src/result/error.ts
449
+ const prepare = (message, contexts, error) => {
450
+ let e$8;
451
+ let emsg;
452
+ if (e(error)) {
453
+ e$8 = error;
454
+ emsg = error.message;
455
+ } else if (e$1(error) || e$2(error) || e$3(error) || e$4(error) || e$5(error)) emsg = error.toString();
456
+ else if (error === void 0) emsg = "";
457
+ else if (error === null) emsg = "null";
458
+ else emsg = stringify(error);
459
+ const ctxs = contexts.reverse().concat(emsg || []);
460
+ let msg = "";
461
+ if (message) msg = message;
462
+ else while (ctxs.length > 0) {
463
+ msg = ctxs.shift();
464
+ if (msg) break;
465
+ }
466
+ const ctx = ctxs.map((line, index) => ` ${index}: ${line}`).join("\n");
467
+ const display = `
468
+ Message:
469
+ ${msg || "<empty message>"}
470
+
471
+ Context:
472
+ ${ctx.trim() || "<empty context>"}
473
+ `.trim();
474
+ return {
475
+ message: msg,
476
+ contexts: ctxs,
477
+ error: e$8,
478
+ display,
479
+ options: e$8 ? { cause: e$8 } : void 0
480
+ };
481
+ };
482
+ var ResultError = class ResultError extends Error {
483
+ static isResultError(value) {
484
+ return value instanceof ResultError;
485
+ }
486
+ #message;
487
+ #contexts;
488
+ #display;
489
+ constructor(message, error, contexts, caller = ResultError) {
490
+ const prepared = prepare(message, contexts, error);
491
+ super(`
492
+
493
+ ${prepared.display}
494
+
495
+ Stack trace:`, prepared.options);
496
+ Error.captureStackTrace(this, caller || this.constructor);
497
+ this.#message = prepared.message;
498
+ this.#contexts = prepared.contexts;
499
+ this.#display = prepared.display;
500
+ }
501
+ get msg() {
502
+ return this.#message;
503
+ }
504
+ get ctx() {
505
+ return this.#contexts.slice();
506
+ }
507
+ toString() {
508
+ return this.#display;
509
+ }
510
+ };
511
+
512
+ //#endregion
513
+ //#region src/result/helper.ts
514
+ function safeTry(body, self) {
515
+ const yieldErr = body.call(self).next();
516
+ if (isPromiseLike(yieldErr)) return yieldErr.then((res) => res.value);
517
+ return yieldErr.value;
518
+ }
519
+
520
+ //#endregion
521
+ //#region src/result/result.ts
522
+ const never = void 0;
523
+ const transformError = (error, onThrow) => {
524
+ if (!onThrow) return error;
525
+ if (onThrow === Error) return normalizeError(error, transformError);
526
+ return onThrow(error);
527
+ };
528
+ var Result = class Result {
529
+ static ok(value) {
530
+ return new Result(true, never, value);
531
+ }
532
+ static err(error) {
533
+ return new Result(false, error, never);
534
+ }
535
+ static fromCallable(callable, onThrow) {
536
+ try {
537
+ if (!isFunction(callable)) {
538
+ const error = /* @__PURE__ */ new TypeError("Provided argument is not callable");
539
+ return this.err(transformError(error, onThrow));
540
+ }
541
+ const data = callable();
542
+ if (!isPromiseLike(data)) return this.ok(data);
543
+ return data.then((value) => this.ok(value), (error) => this.err(transformError(error, onThrow)));
544
+ } catch (error) {
545
+ return this.err(transformError(error, onThrow));
546
+ }
547
+ }
548
+ static toSafeCallable(callable, onThrow) {
549
+ return (...args) => {
550
+ return this.fromCallable(() => callable(...args), onThrow);
551
+ };
552
+ }
553
+ static all(results) {
554
+ const values = [];
555
+ for (const result of results) {
556
+ if (result.isErr()) return this.err(result.#error);
557
+ values.push(result.#value);
558
+ }
559
+ return this.ok(values);
560
+ }
561
+ #ok;
562
+ #value;
563
+ #error;
564
+ #contexts = [];
565
+ constructor(ok$1, error, value) {
566
+ this.#ok = ok$1;
567
+ this.#error = error;
568
+ this.#value = value;
569
+ }
570
+ /**
571
+ * Check if `Result` is `OK`
572
+ */
573
+ isOk() {
574
+ return this.#ok;
575
+ }
576
+ /**
577
+ * Check if `Result` is `OK` and the value matches the predicate
578
+ */
579
+ isOkAnd(predicate) {
580
+ return this.isOk() && predicate(this.#value);
581
+ }
582
+ /**
583
+ * Check if `Result` is `Err`
584
+ */
585
+ isErr() {
586
+ return !this.#ok;
587
+ }
588
+ /**
589
+ * Check if `Result` is `Err` and the error matches the predicate
590
+ */
591
+ isErrAnd(predicate) {
592
+ return this.isErr() && predicate(this.#error);
593
+ }
594
+ /**
595
+ * Maps `Result<T, E>` to `Result<U, E>`
596
+ */
597
+ map(fn) {
598
+ return this.isErr() ? this : Result.ok(fn(this.#value));
599
+ }
600
+ /**
601
+ * Maps `Result<T, E>` to `Result<T, F>`
602
+ */
603
+ mapErr(fn) {
604
+ return this.isOk() ? this : Result.err(fn(this.#error));
605
+ }
606
+ and(result) {
607
+ return this.isErr() ? this : result;
608
+ }
609
+ andThen(fn) {
610
+ return this.isErr() ? this : fn(this.#value);
611
+ }
612
+ or(result) {
613
+ return this.isOk() ? this : result;
614
+ }
615
+ orElse(fn) {
616
+ return this.isOk() ? this : fn(this.#error);
617
+ }
618
+ /**
619
+ * Calls the function with the value if `Result` is `Ok` and returns the result unchanged
620
+ */
621
+ inspect(fn) {
622
+ try {
623
+ this.isOk() && fn(this.#value);
624
+ } catch {}
625
+ return this;
626
+ }
627
+ /**
628
+ * Calls the function with the error if `Result` is `Err` and returns the result unchanged
629
+ */
630
+ inspectErr(fn) {
631
+ try {
632
+ this.isErr() && fn(this.#error);
633
+ } catch {}
634
+ return this;
635
+ }
636
+ /**
637
+ * Unwrap the `Ok` value, or throw an error if `Result` is `Err`
638
+ */
639
+ unwrap(message) {
640
+ if (this.isErr()) throw new ResultError(message !== null ? message ?? "Called unwrap on an Err value" : void 0, this.#error, this.#contexts, this.unwrap);
641
+ return this.#value;
642
+ }
643
+ /**
644
+ * Unwrap the `Err` value, or throw an error if `Result` is `Ok`
645
+ */
646
+ unwrapErr(message) {
647
+ if (this.isOk()) throw new ResultError(message !== null ? message ?? "Called unwrapErr on an Ok value" : void 0, this.#error, this.#contexts, this.unwrapErr);
648
+ return this.#error;
649
+ }
650
+ /**
651
+ * Unwrap the `Ok` value, or return the provided value if `Result` is `Err`
652
+ */
653
+ unwrapOr(defaultValue) {
654
+ return this.isOk() ? this.#value : defaultValue;
655
+ }
656
+ /**
657
+ * Unwrap the `Ok` value, or compute it from a function if `Result` is `Err`
658
+ */
659
+ unwrapOrElse(defaultValueGetter) {
660
+ return this.isOk() ? this.#value : defaultValueGetter(this.#error);
661
+ }
662
+ /**
663
+ * Matches the `Result` variant and executes the corresponding function
664
+ */
665
+ match(ok$1, err$1) {
666
+ return this.isOk() ? ok$1(this.#value) : err$1(this.#error);
667
+ }
668
+ /**
669
+ * Returns an iterable object that yields the `Ok` value and `Err` value
670
+ */
671
+ iter() {
672
+ if (this.isOk()) return [
673
+ true,
674
+ never,
675
+ this.#value
676
+ ];
677
+ else return [
678
+ false,
679
+ this.#error,
680
+ never
681
+ ];
682
+ }
683
+ *[Symbol.iterator]() {
684
+ if (this.isOk()) return this.#value;
685
+ const self = this;
686
+ yield self;
687
+ return self;
688
+ }
689
+ context(context) {
690
+ this.#contexts.push(context);
691
+ return this;
692
+ }
693
+ toString() {
694
+ if (this.isErr()) return new ResultError(void 0, this.#error, this.#contexts).toString();
695
+ return `Ok(${stringify(this.#value)})`;
696
+ }
697
+ };
698
+ const ok = Result.ok;
699
+ const err = Result.err;
700
+
701
+ //#endregion
702
+ //#region src/common/json.ts
703
+ const stringify = configure({ bigint: true });
704
+ const safeParse = (text, reviver) => {
705
+ const fn = () => {
706
+ return JSON.parse(text, reviver);
707
+ };
708
+ return Result.fromCallable(fn, Error).context(`Failed to parse JSON string: ${text.length > 100 ? text.slice(0, 100) + "..." : text}`);
709
+ };
710
+ const unsafeParse = (text, reviver) => {
711
+ const result = safeParse(text, reviver);
712
+ if (result.isErr()) return void 0;
713
+ return result.unwrap(null);
714
+ };
715
+
716
+ //#endregion
717
+ //#region src/common/error.ts
718
+ const normalizeError = (error, caller) => {
719
+ if (e(error)) return error;
720
+ let message;
721
+ if (e$1(error) || e$2(error) || e$3(error) || e$4(error) || e$5(error)) message = error.toString();
722
+ else if (error === void 0) message = "undefined";
723
+ else if (error === null) message = "null";
724
+ else message = stringify(error);
725
+ const e$8 = new Error(message);
726
+ Error.captureStackTrace(e$8, caller || normalizeError);
727
+ return e$8;
728
+ };
729
+ const getErrorMessage = (error, message = "Unknown error") => error instanceof Error ? error.message : message;
730
+
731
+ //#endregion
732
+ //#region src/common/math.ts
733
+ /**
734
+ * @example
735
+ * ```
736
+ * const value = linear(0.5, [0, 2]) // value: 1
737
+ * ```
738
+ */
739
+ const linear = (value, range) => {
740
+ const [min, max] = range;
741
+ const interpolation = t(value, {
742
+ min: 0,
743
+ max: 1
744
+ });
745
+ return min + (max - min) * interpolation;
746
+ };
747
+ /**
748
+ * @example
749
+ * ```
750
+ * const value = scale(0.5, [0, 1], [200, 400]) // value: 300
751
+ * ```
752
+ */
753
+ const scale = (value, inRange, outRange) => {
754
+ const [inMin, inMax] = inRange;
755
+ const [outMin, outMax] = outRange;
756
+ return linear((value - inMin) / (inMax - inMin), [outMin, outMax]);
757
+ };
758
+
759
+ //#endregion
760
+ //#region src/common/parse.ts
761
+ const parseKey = (input, raw = input) => {
762
+ if (input.length === 0) return {
763
+ value: "",
764
+ end: 0
765
+ };
766
+ else if (/^\s/.test(input)) {
767
+ const { value: value$1, end: end$1 } = parseKey(input.slice(1), raw);
768
+ return {
769
+ value: value$1,
770
+ end: end$1 + 1
771
+ };
772
+ }
773
+ let value = "";
774
+ let end = 0;
775
+ if (input[0] === "'" || input[0] === "\"") {
776
+ const slice = input.slice(1);
777
+ const index = slice.indexOf(input[0]);
778
+ if (index === -1 || !slice.slice(index + 1).startsWith("=")) throw new Error(`Failed to parse key from input: ${raw}`);
779
+ value = slice.slice(0, index);
780
+ end = 1 + index + 2;
781
+ } else {
782
+ for (const char of input) {
783
+ if (char === "=") break;
784
+ end += 1;
785
+ }
786
+ value = input.slice(0, end);
787
+ end += 1;
788
+ }
789
+ return {
790
+ value,
791
+ end
792
+ };
793
+ };
794
+ const parseValue = (input, raw = input) => {
795
+ if (input.length === 0) return {
796
+ value: "",
797
+ end: 0
798
+ };
799
+ let value = "";
800
+ let end = 0;
801
+ if (input[0] === "'" || input[0] === "\"") {
802
+ const slice = input.slice(1);
803
+ const index = slice.indexOf(input[0]);
804
+ if (index === -1 || slice.slice(index + 1).length !== 0 && !/^\s/.test(slice.slice(index + 1))) throw new Error(`Failed to parse value from input: ${raw}`);
805
+ value = slice.slice(0, index);
806
+ end = 1 + index + 1;
807
+ } else {
808
+ for (const char of input) {
809
+ if (/\s/.test(char)) break;
810
+ end += 1;
811
+ }
812
+ value = input.slice(0, end);
813
+ end += 1;
814
+ }
815
+ return {
816
+ value,
817
+ end
818
+ };
819
+ };
820
+ const parseKeyValuePairs = (input) => {
821
+ const pairs = {};
822
+ let offset = 0;
823
+ while (offset < input.length) {
824
+ const key = parseKey(input.slice(offset), input);
825
+ offset += key.end;
826
+ const value = parseValue(input.slice(offset), input);
827
+ offset += value.end;
828
+ pairs[key.value] = value.value;
829
+ if (/^\s*$/.test(input.slice(offset))) break;
830
+ }
831
+ return pairs;
832
+ };
833
+ const parseValueToBoolean = (value, defaultValue) => {
834
+ const str = String(value).trim().toLowerCase();
835
+ if (/^(?:y|yes|true|1|on)$/.test(str)) return true;
836
+ if (/^(?:n|no|false|0|off)$/.test(str)) return false;
837
+ return defaultValue;
838
+ };
839
+
840
+ //#endregion
841
+ //#region src/common/promise.ts
842
+ const sleep = (ms, callback) => new Promise((resolve) => {
843
+ setTimeout(async () => {
844
+ await callback?.();
845
+ resolve();
846
+ }, ms);
847
+ });
848
+ const createSingleton = (fn) => {
849
+ let p;
850
+ const wrapper = () => {
851
+ if (!p) p = fn();
852
+ return p;
853
+ };
854
+ wrapper.reset = async () => {
855
+ const prev = p;
856
+ p = void 0;
857
+ if (prev) await prev;
858
+ };
859
+ return wrapper;
860
+ };
861
+ /**
862
+ * @example
863
+ * ```
864
+ * const lock = createLock()
865
+ *
866
+ * lock.run(async () => {
867
+ * await doSomething()
868
+ * })
869
+ *
870
+ * // in anther context:
871
+ * await lock.wait() // it will wait all tasking finished
872
+ * ```
873
+ */
874
+ const createLock = () => {
875
+ const locks = [];
876
+ return {
877
+ async run(fn) {
878
+ const p = fn();
879
+ locks.push(p);
880
+ try {
881
+ return await p;
882
+ } finally {
883
+ const index = locks.indexOf(p);
884
+ if (index >= 0) locks.splice(index, 1);
885
+ }
886
+ },
887
+ async wait() {
888
+ await Promise.allSettled(locks);
889
+ },
890
+ isWaiting() {
891
+ return locks.length > 0;
892
+ },
893
+ clear() {
894
+ locks.length = 0;
895
+ }
896
+ };
897
+ };
898
+ const createPromiseWithResolvers = () => {
899
+ if (isFunction(Promise.withResolvers)) return Promise.withResolvers();
900
+ let resolve;
901
+ let reject;
902
+ return {
903
+ promise: new Promise((_resolve, _reject) => {
904
+ resolve = _resolve;
905
+ reject = _reject;
906
+ }),
907
+ resolve,
908
+ reject
909
+ };
910
+ };
911
+
912
+ //#endregion
913
+ //#region src/common/string.ts
914
+ const REGEXP_WHITESPACE = /^\s*$/;
915
+ const addPrefix = (prefix, str) => {
916
+ if (str.startsWith(prefix)) return str;
917
+ return prefix + str;
918
+ };
919
+ const addSuffix = (suffix, str) => {
920
+ if (str.endsWith(suffix)) return str;
921
+ return str + suffix;
922
+ };
923
+ const removePrefix = (prefix, str) => {
924
+ if (!str.startsWith(prefix)) return str;
925
+ return str.slice(prefix.length);
926
+ };
927
+ const removeSuffix = (suffix, str) => {
928
+ if (!str.endsWith(suffix)) return str;
929
+ return str.slice(0, -suffix.length);
930
+ };
931
+ const join = (separator, ...paths) => {
932
+ let pathname = "";
933
+ for (const path of paths) {
934
+ const part = removeSuffix(separator, removePrefix(separator, path));
935
+ if (part) pathname += pathname ? separator + part : part;
936
+ }
937
+ return pathname;
938
+ };
939
+ const split = (separator, path) => {
940
+ const paths = [];
941
+ let part = "";
942
+ for (const char of path) if (char === separator) {
943
+ part && paths.push(part);
944
+ part = "";
945
+ } else part += char;
946
+ part && paths.push(part);
947
+ return paths;
948
+ };
949
+ const toForwardSlash = (str) => str.replace(/\\/g, "/");
950
+ const joinWithSlash = (...paths) => join("/", ...paths);
951
+ const splitWithSlash = (path) => split("/", path);
952
+ const concatTemplateStrings = (template$1, values) => template$1.reduce((acc, part, index) => acc + part + (values[index] ?? ""), "");
953
+ function unindent(template$1, ...values) {
954
+ const lines = (e$1(template$1) ? template$1 : concatTemplateStrings(template$1, values)).split("\n");
955
+ const whitespaceLines = lines.map((line) => REGEXP_WHITESPACE.test(line));
956
+ const commonIndent = lines.reduce((min, line, idx) => {
957
+ if (whitespaceLines[idx]) return min;
958
+ const indent = line.match(/^\s*/)?.[0].length;
959
+ return indent === void 0 ? min : Math.min(min, indent);
960
+ }, Number.POSITIVE_INFINITY);
961
+ let emptyLinesHead = 0;
962
+ while (emptyLinesHead < lines.length && whitespaceLines[emptyLinesHead]) emptyLinesHead += 1;
963
+ let emptyLinesTail = 0;
964
+ while (emptyLinesTail < lines.length && whitespaceLines[lines.length - emptyLinesTail - 1]) emptyLinesTail += 1;
965
+ return lines.slice(emptyLinesHead, lines.length - emptyLinesTail).map((line) => line.slice(commonIndent)).join("\n");
966
+ }
967
+ function template(str, ...args) {
968
+ const [firstArg, fallback] = args;
969
+ if (e$6(firstArg)) {
970
+ const mapping = firstArg;
971
+ return str.replace(/\{(\w+)\}/g, (_, key) => mapping[key] || ((isFunction(fallback) ? fallback(key) : fallback) ?? key));
972
+ } else return str.replace(/\{(\d+)\}/g, (_, key) => {
973
+ const index = Number(key);
974
+ if (Number.isNaN(index)) return key;
975
+ return args[index];
976
+ });
977
+ }
978
+
979
+ //#endregion
980
+ //#region src/common/shell.ts
981
+ const REGEXP_NULL_CHAR = /\x00+/g;
982
+ const REGEXP_SAFE_CHARS = /^[A-Za-z0-9,:=_./-]+$/;
983
+ const REGEXP_SINGLE_QUOTES = /'+/g;
984
+ const noop = () => {};
985
+ const pipeToStdout = (chunk) => process.stdout.write(chunk);
986
+ const pipeToStderr = (chunk) => process.stderr.write(chunk);
987
+ async function $(cmd, ...values) {
988
+ const { spawn } = await import("node:child_process");
989
+ const [command, options] = e$1(cmd) ? [cmd, values[0] || {}] : [concatTemplateStrings(cmd, values), {}];
990
+ const stdio = [
991
+ "inherit",
992
+ "pipe",
993
+ "pipe"
994
+ ];
995
+ let onStdin = noop;
996
+ if (options.onStdin !== void 0) {
997
+ stdio[0] = "pipe";
998
+ if (isFunction(options.onStdin)) onStdin = options.onStdin;
999
+ else {
1000
+ const chunk = options.onStdin;
1001
+ onStdin = (stdin) => stdin.write(chunk);
1002
+ }
1003
+ }
1004
+ const onStdout = options.onStdout === "ignore" ? noop : options.onStdout === "print" ? pipeToStdout : options.onStdout || noop;
1005
+ const onStderr = options.onStderr === "ignore" ? noop : options.onStderr === "print" ? pipeToStderr : options.onStderr || noop;
1006
+ const fn = async () => {
1007
+ const { promise, reject, resolve } = createPromiseWithResolvers();
1008
+ const child = spawn(command, {
1009
+ shell: true,
1010
+ stdio
1011
+ });
1012
+ if (stdio[0] === "pipe" && child.stdin) {
1013
+ await onStdin(child.stdin);
1014
+ child.stdin?.end();
1015
+ }
1016
+ let stdout = "";
1017
+ let stderr = "";
1018
+ child.stdout?.on("data", (data) => {
1019
+ const chunk = data.toString();
1020
+ stdout += chunk;
1021
+ onStdout(chunk);
1022
+ });
1023
+ child.stderr?.on("data", (data) => {
1024
+ const chunk = data.toString();
1025
+ stderr += chunk;
1026
+ onStderr(chunk);
1027
+ });
1028
+ child.on("error", reject);
1029
+ child.on("close", (code) => {
1030
+ if (code === 0) resolve({
1031
+ stdout: stdout.trim(),
1032
+ stderr: stderr.trim()
1033
+ });
1034
+ else reject(/* @__PURE__ */ new Error(`Command exited with code ${code}`));
1035
+ });
1036
+ return await promise;
1037
+ };
1038
+ return (await Result.fromCallable(fn, Error)).context(`Failed to execute command: ${cmd}`);
1039
+ }
1040
+ const quoteShellArg = (arg) => {
1041
+ if (!arg) return "''";
1042
+ const cleaned = String(arg).replace(REGEXP_NULL_CHAR, "");
1043
+ if (REGEXP_SAFE_CHARS.exec(cleaned)?.[0].length === cleaned.length) return cleaned;
1044
+ return `'${cleaned.replace(REGEXP_SINGLE_QUOTES, (matched) => matched.length === 1 ? `'\\''` : `'"${matched}"'`)}'`.replace(/^''/, "").replace(/''$/, "");
1045
+ };
1046
+
1047
+ //#endregion
1048
+ //#region src/common/throttle.ts
1049
+ const wrap = (fn, wait, options) => {
1050
+ const { leading, trailing } = options;
1051
+ let timerId;
1052
+ const wrapped = (...args) => {
1053
+ if (e$7(timerId)) return;
1054
+ timerId = globalThis.setTimeout(() => {
1055
+ timerId = void 0;
1056
+ trailing && fn(...args);
1057
+ }, wait);
1058
+ leading && fn(...args);
1059
+ };
1060
+ wrapped.cancel = () => {
1061
+ if (e$7(timerId)) globalThis.clearTimeout(timerId);
1062
+ timerId = void 0;
1063
+ };
1064
+ return wrapped;
1065
+ };
1066
+ const debounce = (fn, wait = 0, options = {}) => {
1067
+ const { leading = false, trailing = true } = options;
1068
+ return wrap(fn, wait, {
1069
+ leading,
1070
+ trailing
1071
+ });
1072
+ };
1073
+ const throttle = (fn, wait = 0, options = {}) => {
1074
+ const { leading = true, trailing = true } = options;
1075
+ return wrap(fn, wait, {
1076
+ leading,
1077
+ trailing
1078
+ });
1079
+ };
1080
+
1081
+ //#endregion
1082
+ export { Result as A, linear as C, safeParse as D, normalizeError as E, __commonJSMin as F, __toESM as I, ok as M, safeTry as N, stringify as O, ResultError as P, parseValueToBoolean as S, getErrorMessage as T, createLock as _, addPrefix as a, sleep as b, join as c, removeSuffix as d, split as f, unindent as g, toForwardSlash as h, quoteShellArg as i, err as j, unsafeParse as k, joinWithSlash as l, template as m, throttle as n, addSuffix as o, splitWithSlash as p, $ as r, concatTemplateStrings as s, debounce as t, removePrefix as u, createPromiseWithResolvers as v, scale as w, parseKeyValuePairs as x, createSingleton as y };