@goodbyenjn/utils 26.3.0 → 26.4.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.
@@ -1,35 +1,8 @@
1
- import { Dr as t, F as isFunction, Fn as e$6, Nn as e$4, On as e, P as isPromiseLike, Pn as e$3, Sn as e$2, Tn as e$8, bn as e$7, gn as e$1, hn as e$5 } from "./chunk-b970a8d0.js";
1
+ import { i as __toESM, t as __commonJSMin } from "./chunk-7ffde8d4.js";
2
+ import { Dt as isBoolean, Et as isBigInt, Gr as isFunction, Gt as isString, It as isNonNullish, Kt as isSymbol, Nt as isError, Tt as isArray, Vt as isPlainObject, Wr as isPromiseLike, p as clamp, zt as isNumber } from "./chunk-b61db0a7.js";
2
3
 
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
4
  //#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) => {
5
+ var require_safe_stable_stringify = __commonJSMin(((exports, module) => {
33
6
  const { hasOwnProperty } = Object.prototype;
34
7
  const stringify = configure();
35
8
  stringify.configure = configure;
@@ -110,7 +83,7 @@ var require_safe_stable_stringify = /* @__PURE__ */ __commonJSMin(((exports, mod
110
83
  return `${number} items`;
111
84
  }
112
85
  function getUniqueReplacerSet(replacerArray) {
113
- const replacerSet = /* @__PURE__ */ new Set();
86
+ const replacerSet = new Set();
114
87
  for (const value of replacerArray) if (typeof value === "string" || typeof value === "number") replacerSet.add(String(value));
115
88
  return replacerSet;
116
89
  }
@@ -118,9 +91,9 @@ var require_safe_stable_stringify = /* @__PURE__ */ __commonJSMin(((exports, mod
118
91
  if (hasOwnProperty.call(options, "strict")) {
119
92
  const value = options.strict;
120
93
  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()})`;
94
+ if (value) return (value) => {
95
+ let message = `Object can not safely be stringified. Received type ${typeof value}`;
96
+ if (typeof value !== "function") message += ` (${value.toString()})`;
124
97
  throw new Error(message);
125
98
  };
126
99
  }
@@ -148,7 +121,7 @@ var require_safe_stable_stringify = /* @__PURE__ */ __commonJSMin(((exports, mod
148
121
  if (value === null) return "null";
149
122
  if (stack.indexOf(value) !== -1) return circularValue;
150
123
  let res = "";
151
- let join$1 = ",";
124
+ let join = ",";
152
125
  const originalIndentation = indentation;
153
126
  if (Array.isArray(value)) {
154
127
  if (value.length === 0) return "[]";
@@ -157,20 +130,20 @@ var require_safe_stable_stringify = /* @__PURE__ */ __commonJSMin(((exports, mod
157
130
  if (spacer !== "") {
158
131
  indentation += spacer;
159
132
  res += `\n${indentation}`;
160
- join$1 = `,\n${indentation}`;
133
+ join = `,\n${indentation}`;
161
134
  }
162
135
  const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
163
136
  let i = 0;
164
137
  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;
138
+ const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation);
139
+ res += tmp !== void 0 ? tmp : "null";
140
+ res += join;
168
141
  }
169
142
  const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation);
170
143
  res += tmp !== void 0 ? tmp : "null";
171
144
  if (value.length - 1 > maximumBreadth) {
172
145
  const removedKeys = value.length - maximumBreadth - 1;
173
- res += `${join$1}"... ${getItemCount(removedKeys)} not stringified"`;
146
+ res += `${join}"... ${getItemCount(removedKeys)} not stringified"`;
174
147
  }
175
148
  if (spacer !== "") res += `\n${originalIndentation}`;
176
149
  stack.pop();
@@ -184,24 +157,24 @@ var require_safe_stable_stringify = /* @__PURE__ */ __commonJSMin(((exports, mod
184
157
  let separator = "";
185
158
  if (spacer !== "") {
186
159
  indentation += spacer;
187
- join$1 = `,\n${indentation}`;
160
+ join = `,\n${indentation}`;
188
161
  whitespace = " ";
189
162
  }
190
163
  const maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth);
191
164
  if (deterministic && !isTypedArrayWithEntries(value)) keys = sort(keys, comparator);
192
165
  stack.push(value);
193
166
  for (let i = 0; i < maximumPropertiesToStringify; i++) {
194
- const key$1 = keys[i];
195
- const tmp = stringifyFnReplacer(key$1, value, stack, replacer, spacer, indentation);
167
+ const key = keys[i];
168
+ const tmp = stringifyFnReplacer(key, value, stack, replacer, spacer, indentation);
196
169
  if (tmp !== void 0) {
197
- res += `${separator}${strEscape(key$1)}:${whitespace}${tmp}`;
198
- separator = join$1;
170
+ res += `${separator}${strEscape(key)}:${whitespace}${tmp}`;
171
+ separator = join;
199
172
  }
200
173
  }
201
174
  if (keyLength > maximumBreadth) {
202
175
  const removedKeys = keyLength - maximumBreadth;
203
176
  res += `${separator}"...":${whitespace}"${getItemCount(removedKeys)} not stringified"`;
204
- separator = join$1;
177
+ separator = join;
205
178
  }
206
179
  if (spacer !== "" && separator.length > 1) res = `\n${indentation}${res}\n${originalIndentation}`;
207
180
  stack.pop();
@@ -223,7 +196,7 @@ var require_safe_stable_stringify = /* @__PURE__ */ __commonJSMin(((exports, mod
223
196
  if (stack.indexOf(value) !== -1) return circularValue;
224
197
  const originalIndentation = indentation;
225
198
  let res = "";
226
- let join$1 = ",";
199
+ let join = ",";
227
200
  if (Array.isArray(value)) {
228
201
  if (value.length === 0) return "[]";
229
202
  if (maximumDepth < stack.length + 1) return "\"[Array]\"";
@@ -231,20 +204,20 @@ var require_safe_stable_stringify = /* @__PURE__ */ __commonJSMin(((exports, mod
231
204
  if (spacer !== "") {
232
205
  indentation += spacer;
233
206
  res += `\n${indentation}`;
234
- join$1 = `,\n${indentation}`;
207
+ join = `,\n${indentation}`;
235
208
  }
236
209
  const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
237
210
  let i = 0;
238
211
  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;
212
+ const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation);
213
+ res += tmp !== void 0 ? tmp : "null";
214
+ res += join;
242
215
  }
243
216
  const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation);
244
217
  res += tmp !== void 0 ? tmp : "null";
245
218
  if (value.length - 1 > maximumBreadth) {
246
219
  const removedKeys = value.length - maximumBreadth - 1;
247
- res += `${join$1}"... ${getItemCount(removedKeys)} not stringified"`;
220
+ res += `${join}"... ${getItemCount(removedKeys)} not stringified"`;
248
221
  }
249
222
  if (spacer !== "") res += `\n${originalIndentation}`;
250
223
  stack.pop();
@@ -254,15 +227,15 @@ var require_safe_stable_stringify = /* @__PURE__ */ __commonJSMin(((exports, mod
254
227
  let whitespace = "";
255
228
  if (spacer !== "") {
256
229
  indentation += spacer;
257
- join$1 = `,\n${indentation}`;
230
+ join = `,\n${indentation}`;
258
231
  whitespace = " ";
259
232
  }
260
233
  let separator = "";
261
- for (const key$1 of replacer) {
262
- const tmp = stringifyArrayReplacer(key$1, value[key$1], stack, replacer, spacer, indentation);
234
+ for (const key of replacer) {
235
+ const tmp = stringifyArrayReplacer(key, value[key], stack, replacer, spacer, indentation);
263
236
  if (tmp !== void 0) {
264
- res += `${separator}${strEscape(key$1)}:${whitespace}${tmp}`;
265
- separator = join$1;
237
+ res += `${separator}${strEscape(key)}:${whitespace}${tmp}`;
238
+ separator = join;
266
239
  }
267
240
  }
268
241
  if (spacer !== "" && separator.length > 1) res = `\n${indentation}${res}\n${originalIndentation}`;
@@ -293,54 +266,54 @@ var require_safe_stable_stringify = /* @__PURE__ */ __commonJSMin(((exports, mod
293
266
  if (maximumDepth < stack.length + 1) return "\"[Array]\"";
294
267
  stack.push(value);
295
268
  indentation += spacer;
296
- let res$1 = `\n${indentation}`;
297
- const join$2 = `,\n${indentation}`;
269
+ let res = `\n${indentation}`;
270
+ const join = `,\n${indentation}`;
298
271
  const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
299
272
  let i = 0;
300
273
  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;
274
+ const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation);
275
+ res += tmp !== void 0 ? tmp : "null";
276
+ res += join;
304
277
  }
305
278
  const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation);
306
- res$1 += tmp !== void 0 ? tmp : "null";
279
+ res += tmp !== void 0 ? tmp : "null";
307
280
  if (value.length - 1 > maximumBreadth) {
308
281
  const removedKeys = value.length - maximumBreadth - 1;
309
- res$1 += `${join$2}"... ${getItemCount(removedKeys)} not stringified"`;
282
+ res += `${join}"... ${getItemCount(removedKeys)} not stringified"`;
310
283
  }
311
- res$1 += `\n${originalIndentation}`;
284
+ res += `\n${originalIndentation}`;
312
285
  stack.pop();
313
- return `[${res$1}]`;
286
+ return `[${res}]`;
314
287
  }
315
288
  let keys = Object.keys(value);
316
289
  const keyLength = keys.length;
317
290
  if (keyLength === 0) return "{}";
318
291
  if (maximumDepth < stack.length + 1) return "\"[Object]\"";
319
292
  indentation += spacer;
320
- const join$1 = `,\n${indentation}`;
293
+ const join = `,\n${indentation}`;
321
294
  let res = "";
322
295
  let separator = "";
323
296
  let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth);
324
297
  if (isTypedArrayWithEntries(value)) {
325
- res += stringifyTypedArray(value, join$1, maximumBreadth);
298
+ res += stringifyTypedArray(value, join, maximumBreadth);
326
299
  keys = keys.slice(value.length);
327
300
  maximumPropertiesToStringify -= value.length;
328
- separator = join$1;
301
+ separator = join;
329
302
  }
330
303
  if (deterministic) keys = sort(keys, comparator);
331
304
  stack.push(value);
332
305
  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);
306
+ const key = keys[i];
307
+ const tmp = stringifyIndent(key, value[key], stack, spacer, indentation);
335
308
  if (tmp !== void 0) {
336
- res += `${separator}${strEscape(key$1)}: ${tmp}`;
337
- separator = join$1;
309
+ res += `${separator}${strEscape(key)}: ${tmp}`;
310
+ separator = join;
338
311
  }
339
312
  }
340
313
  if (keyLength > maximumBreadth) {
341
314
  const removedKeys = keyLength - maximumBreadth;
342
315
  res += `${separator}"...": "${getItemCount(removedKeys)} not stringified"`;
343
- separator = join$1;
316
+ separator = join;
344
317
  }
345
318
  if (separator !== "") res = `\n${indentation}${res}\n${originalIndentation}`;
346
319
  stack.pop();
@@ -373,8 +346,8 @@ var require_safe_stable_stringify = /* @__PURE__ */ __commonJSMin(((exports, mod
373
346
  const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
374
347
  let i = 0;
375
348
  for (; i < maximumValuesToStringify - 1; i++) {
376
- const tmp$1 = stringifySimple(String(i), value[i], stack);
377
- res += tmp$1 !== void 0 ? tmp$1 : "null";
349
+ const tmp = stringifySimple(String(i), value[i], stack);
350
+ res += tmp !== void 0 ? tmp : "null";
378
351
  res += ",";
379
352
  }
380
353
  const tmp = stringifySimple(String(i), value[i], stack);
@@ -401,10 +374,10 @@ var require_safe_stable_stringify = /* @__PURE__ */ __commonJSMin(((exports, mod
401
374
  if (deterministic) keys = sort(keys, comparator);
402
375
  stack.push(value);
403
376
  for (let i = 0; i < maximumPropertiesToStringify; i++) {
404
- const key$1 = keys[i];
405
- const tmp = stringifySimple(key$1, value[key$1], stack);
377
+ const key = keys[i];
378
+ const tmp = stringifySimple(key, value[key], stack);
406
379
  if (tmp !== void 0) {
407
- res += `${separator}${strEscape(key$1)}:${tmp}`;
380
+ res += `${separator}${strEscape(key)}:${tmp}`;
408
381
  separator = ",";
409
382
  }
410
383
  }
@@ -422,7 +395,7 @@ var require_safe_stable_stringify = /* @__PURE__ */ __commonJSMin(((exports, mod
422
395
  default: return fail ? fail(value) : void 0;
423
396
  }
424
397
  }
425
- function stringify$1(value, replacer, space) {
398
+ function stringify(value, replacer, space) {
426
399
  if (arguments.length > 1) {
427
400
  let spacer = "";
428
401
  if (typeof space === "number") spacer = " ".repeat(Math.min(space, 10));
@@ -435,88 +408,74 @@ var require_safe_stable_stringify = /* @__PURE__ */ __commonJSMin(((exports, mod
435
408
  }
436
409
  return stringifySimple("", value, []);
437
410
  }
438
- return stringify$1;
411
+ return stringify;
439
412
  }
440
413
  }));
441
414
 
442
415
  //#endregion
443
416
  //#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);
417
+ var import_safe_stable_stringify = __toESM(require_safe_stable_stringify(), 1);
445
418
  const configure = import_safe_stable_stringify.configure;
446
419
 
447
420
  //#endregion
448
421
  //#region src/result/error.ts
449
- const prepare = (message, contexts, error) => {
450
- let e$9;
451
- let emsg;
452
- if (e(error)) {
453
- e$9 = 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 = `
422
+ const prepare = (result, msg) => {
423
+ const cause = result["error"];
424
+ const reason = cause === void 0 ? "" : getErrorMessage(cause);
425
+ const contexts = result["contexts"].reverse().concat(reason || []);
426
+ let message = "";
427
+ if (msg) message = msg;
428
+ else while (contexts.length > 0) {
429
+ message = contexts.shift();
430
+ if (message) break;
431
+ }
432
+ const ctx = contexts.map((line, index) => ` ${index}: ${line}`).join("\n");
433
+ const formatted = `
468
434
  Message:
469
- ${msg || "<empty message>"}
470
-
435
+ ${message || "<empty message>"}
471
436
  Context:
472
437
  ${ctx.trim() || "<empty context>"}
473
438
  `.trim();
439
+ const options = isError(cause) ? { cause } : void 0;
474
440
  return {
475
- message: msg,
476
- contexts: ctxs,
477
- error: e$9,
478
- display,
479
- options: e$9 ? { cause: e$9 } : void 0
441
+ message,
442
+ contexts,
443
+ formatted,
444
+ options
480
445
  };
481
446
  };
482
447
  var ResultError = class ResultError extends Error {
483
- static isResultError(value) {
448
+ static is(value) {
484
449
  return value instanceof ResultError;
485
450
  }
486
- #message;
487
- #contexts;
488
- #display;
489
- constructor(message, error, contexts, caller = ResultError) {
490
- const prepared = prepare(message, contexts, error);
451
+ static fmt(result, message) {
452
+ return prepare(result, message).formatted;
453
+ }
454
+ #msg;
455
+ #ctx;
456
+ #formatted;
457
+ constructor(result, message, caller = ResultError) {
458
+ const prepared = prepare(result, message);
491
459
  super(`
492
-
493
- ${prepared.display}
494
-
460
+ --------------------
461
+ ${prepared.formatted}
495
462
  Stack trace:`, prepared.options);
496
463
  Error.captureStackTrace(this, caller || this.constructor);
497
- this.#message = prepared.message;
498
- this.#contexts = prepared.contexts;
499
- this.#display = prepared.display;
464
+ this.#msg = prepared.message;
465
+ this.#ctx = prepared.contexts;
466
+ this.#formatted = prepared.formatted;
500
467
  }
501
468
  get msg() {
502
- return this.#message;
469
+ return this.#msg;
503
470
  }
504
- get ctx() {
505
- return this.#contexts.slice();
471
+ get contexts() {
472
+ return this.#ctx;
506
473
  }
507
474
  toString() {
508
- return this.#display;
475
+ return this.#formatted;
509
476
  }
510
477
  };
511
478
 
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
479
  //#endregion
521
480
  //#region src/result/result.ts
522
481
  const never = void 0;
@@ -526,174 +485,147 @@ const transformError = (error, onThrow) => {
526
485
  return onThrow(error);
527
486
  };
528
487
  var Result = class Result {
488
+ static is(value) {
489
+ return value instanceof Result;
490
+ }
529
491
  static ok(value) {
530
492
  return new Result(true, never, value);
531
493
  }
532
494
  static err(error) {
533
495
  return new Result(false, error, never);
534
496
  }
535
- static fromCallable(callable, onThrow) {
497
+ static try(fnOrPromise, onThrow) {
498
+ if (!isFunction(fnOrPromise) && !isPromiseLike(fnOrPromise)) {
499
+ const error = new TypeError("Argument must be a function or a promise");
500
+ return this.err(transformError(error, onThrow));
501
+ }
502
+ if (isPromiseLike(fnOrPromise)) return fnOrPromise.then((value) => this.ok(value), (error) => this.err(transformError(error, onThrow)));
536
503
  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();
504
+ const data = fnOrPromise();
542
505
  if (!isPromiseLike(data)) return this.ok(data);
543
506
  return data.then((value) => this.ok(value), (error) => this.err(transformError(error, onThrow)));
544
507
  } catch (error) {
545
508
  return this.err(transformError(error, onThrow));
546
509
  }
547
510
  }
548
- static toSafeCallable(callable, onThrow) {
511
+ static wrap(fn, onThrow) {
549
512
  return (...args) => {
550
- return this.fromCallable(() => callable(...args), onThrow);
513
+ return this.try(() => fn(...args), onThrow);
551
514
  };
552
515
  }
553
516
  static all(results) {
554
517
  const values = [];
555
518
  for (const result of results) {
556
- if (result.isErr()) return this.err(result.#error);
557
- values.push(result.#value);
519
+ if (result.isErr()) return this.err(result.error);
520
+ values.push(result.value);
558
521
  }
559
522
  return this.ok(values);
560
523
  }
561
- #ok;
562
- #value;
563
- #error;
524
+ static gen(body, self) {
525
+ const next = body.call(self).next();
526
+ const handle = (result) => {
527
+ if (!result.done) return result.value;
528
+ return result.value instanceof Result ? result.value : this.ok(result.value);
529
+ };
530
+ if (isPromiseLike(next)) return next.then(handle);
531
+ return handle(next);
532
+ }
533
+ ok;
534
+ value;
535
+ error;
564
536
  #contexts = [];
565
- constructor(ok$1, error, value) {
566
- this.#ok = ok$1;
567
- this.#error = error;
568
- this.#value = value;
537
+ get contexts() {
538
+ return this.#contexts;
539
+ }
540
+ constructor(ok, error, value) {
541
+ this.ok = ok;
542
+ this.error = error;
543
+ this.value = value;
569
544
  }
570
- /**
571
- * Check if `Result` is `OK`
572
- */
573
545
  isOk() {
574
- return this.#ok;
546
+ return this.ok;
575
547
  }
576
- /**
577
- * Check if `Result` is `OK` and the value matches the predicate
578
- */
579
548
  isOkAnd(predicate) {
580
- return this.isOk() && predicate(this.#value);
549
+ return this.isOk() && predicate(this.value);
581
550
  }
582
- /**
583
- * Check if `Result` is `Err`
584
- */
585
551
  isErr() {
586
- return !this.#ok;
552
+ return !this.ok;
587
553
  }
588
- /**
589
- * Check if `Result` is `Err` and the error matches the predicate
590
- */
591
554
  isErrAnd(predicate) {
592
- return this.isErr() && predicate(this.#error);
555
+ return this.isErr() && predicate(this.error);
593
556
  }
594
- /**
595
- * Maps `Result<T, E>` to `Result<U, E>`
596
- */
597
557
  map(fn) {
598
- return this.isErr() ? this : Result.ok(fn(this.#value));
558
+ if (this.isErr()) return this;
559
+ const result = fn(this.value);
560
+ return isPromiseLike(result) ? result.then(Result.ok) : Result.ok(result);
599
561
  }
600
- /**
601
- * Maps `Result<T, E>` to `Result<T, F>`
602
- */
603
562
  mapErr(fn) {
604
- return this.isOk() ? this : Result.err(fn(this.#error));
563
+ if (this.isOk()) return this;
564
+ const result = fn(this.error);
565
+ return isPromiseLike(result) ? result.then(Result.err) : Result.err(result);
605
566
  }
606
567
  and(result) {
607
568
  return this.isErr() ? this : result;
608
569
  }
609
570
  andThen(fn) {
610
- return this.isErr() ? this : fn(this.#value);
571
+ return this.isErr() ? this : fn(this.value);
611
572
  }
612
573
  or(result) {
613
574
  return this.isOk() ? this : result;
614
575
  }
615
576
  orElse(fn) {
616
- return this.isOk() ? this : fn(this.#error);
577
+ return this.isOk() ? this : fn(this.error);
617
578
  }
618
- /**
619
- * Calls the function with the value if `Result` is `Ok` and returns the result unchanged
620
- */
621
579
  inspect(fn) {
622
580
  try {
623
- this.isOk() && fn(this.#value);
581
+ this.isOk() && fn(this.value);
624
582
  } catch {}
625
583
  return this;
626
584
  }
627
- /**
628
- * Calls the function with the error if `Result` is `Err` and returns the result unchanged
629
- */
630
585
  inspectErr(fn) {
631
586
  try {
632
- this.isErr() && fn(this.#error);
587
+ this.isErr() && fn(this.error);
633
588
  } catch {}
634
589
  return this;
635
590
  }
636
- /**
637
- * Unwrap the `Ok` value, or throw an error if `Result` is `Err`
638
- */
639
591
  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;
592
+ if (this.isErr()) throw new ResultError(this, message !== null ? message ?? "Called `unwrap` on an `Err` value" : void 0, this.unwrap);
593
+ return this.value;
642
594
  }
643
- /**
644
- * Unwrap the `Err` value, or throw an error if `Result` is `Ok`
645
- */
646
595
  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;
596
+ if (this.isOk()) throw new ResultError(this, message !== null ? message ?? "Called `unwrapErr` on an `Ok` value" : void 0, this.unwrapErr);
597
+ return this.error;
649
598
  }
650
- /**
651
- * Unwrap the `Ok` value, or return the provided value if `Result` is `Err`
652
- */
653
599
  unwrapOr(defaultValue) {
654
- return this.isOk() ? this.#value : defaultValue;
600
+ return this.isOk() ? this.value : defaultValue;
655
601
  }
656
- /**
657
- * Unwrap the `Ok` value, or compute it from a function if `Result` is `Err`
658
- */
659
602
  unwrapOrElse(defaultValueGetter) {
660
- return this.isOk() ? this.#value : defaultValueGetter(this.#error);
603
+ return this.isOk() ? this.value : defaultValueGetter(this.error);
661
604
  }
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);
605
+ match(ok, err) {
606
+ return this.isOk() ? ok(this.value) : err(this.error);
667
607
  }
668
- /**
669
- * Returns an iterable object that yields the `Ok` value and `Err` value
670
- */
671
608
  iter() {
672
609
  if (this.isOk()) return [
673
610
  true,
674
611
  never,
675
- this.#value
612
+ this.value
676
613
  ];
677
614
  else return [
678
615
  false,
679
- this.#error,
616
+ this.error,
680
617
  never
681
618
  ];
682
619
  }
683
620
  *[Symbol.iterator]() {
684
- if (this.isOk()) return this.#value;
685
- const self = this;
686
- yield self;
687
- return self;
621
+ if (this.isOk()) return this.value;
622
+ yield this;
623
+ return this;
688
624
  }
689
625
  context(context) {
690
626
  this.#contexts.push(context);
691
627
  return this;
692
628
  }
693
- toString() {
694
- if (this.isErr()) return new ResultError(void 0, this.#error, this.#contexts).toString();
695
- return `Ok(${stringify(this.#value)})`;
696
- }
697
629
  };
698
630
  const ok = Result.ok;
699
631
  const err = Result.err;
@@ -702,10 +634,7 @@ const err = Result.err;
702
634
  //#region src/common/json.ts
703
635
  const stringify = configure({ bigint: true });
704
636
  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}`);
637
+ return Result.wrap(JSON.parse, Error)(text, reviver).context(`Failed to parse JSON string: ${text.length > 100 ? text.slice(0, 100) + "..." : text}`);
709
638
  };
710
639
  const unsafeParse = (text, reviver) => {
711
640
  const result = safeParse(text, reviver);
@@ -716,40 +645,32 @@ const unsafeParse = (text, reviver) => {
716
645
  //#endregion
717
646
  //#region src/common/error.ts
718
647
  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$9 = new Error(message);
726
- Error.captureStackTrace(e$9, caller || normalizeError);
727
- return e$9;
648
+ if (isError(error)) return error;
649
+ const e = new Error(getErrorMessage(error));
650
+ Error.captureStackTrace(e, caller || normalizeError);
651
+ return e;
652
+ };
653
+ const getErrorMessage = (error, message) => {
654
+ if (isError(error)) return error.message;
655
+ if (message !== void 0) return message;
656
+ let msg;
657
+ if (isString(error) || isNumber(error) || isBigInt(error) || isBoolean(error) || isSymbol(error)) msg = error.toString();
658
+ else if (error === void 0) msg = "undefined";
659
+ else if (error === null) msg = "null";
660
+ else msg = stringify(error);
661
+ return msg;
728
662
  };
729
- const getErrorMessage = (error, message = "Unknown error") => error instanceof Error ? error.message : message;
730
663
 
731
664
  //#endregion
732
665
  //#region src/common/math.ts
733
- /**
734
- * @example
735
- * ```
736
- * const value = linear(0.5, [0, 2]) // value: 1
737
- * ```
738
- */
739
666
  const linear = (value, range) => {
740
667
  const [min, max] = range;
741
- const interpolation = t(value, {
668
+ const interpolation = clamp(value, {
742
669
  min: 0,
743
670
  max: 1
744
671
  });
745
672
  return min + (max - min) * interpolation;
746
673
  };
747
- /**
748
- * @example
749
- * ```
750
- * const value = scale(0.5, [0, 1], [200, 400]) // value: 300
751
- * ```
752
- */
753
674
  const scale = (value, inRange, outRange) => {
754
675
  const [inMin, inMax] = inRange;
755
676
  const [outMin, outMax] = outRange;
@@ -764,10 +685,10 @@ const parseKey = (input, raw = input) => {
764
685
  end: 0
765
686
  };
766
687
  else if (/^\s/.test(input)) {
767
- const { value: value$1, end: end$1 } = parseKey(input.slice(1), raw);
688
+ const { value, end } = parseKey(input.slice(1), raw);
768
689
  return {
769
- value: value$1,
770
- end: end$1 + 1
690
+ value,
691
+ end: end + 1
771
692
  };
772
693
  }
773
694
  let value = "";
@@ -858,19 +779,6 @@ const createSingleton = (fn) => {
858
779
  };
859
780
  return wrapper;
860
781
  };
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
782
  const createLock = () => {
875
783
  const locks = [];
876
784
  return {
@@ -951,41 +859,20 @@ const toForwardSlash = (str) => str.replace(/\\/g, "/");
951
859
  const joinWithSlash = (...paths) => join("/", ...paths);
952
860
  const splitWithSlash = (path) => split("/", path);
953
861
  const splitByLineBreak = (str) => str.split(/\r?\n/);
954
- const concatTemplateStrings = (template$1, values) => template$1.reduce((acc, part, index) => acc + part + (values[index] ?? ""), "");
955
- /**
956
- * @example
957
- * ```ts
958
- * // Default behavior: trim both start and end
959
- * const str1 = unindent`
960
- * if (a) {
961
- * b()
962
- * }
963
- * `;
964
- *
965
- * // Factory function: custom trim behavior
966
- * const str2 = unindent(false, false)`
967
- * if (a) {
968
- * b()
969
- * }
970
- * `;
971
- *
972
- * // Only trim start, keep end
973
- * const str3 = unindent(true, false)(" hello\n world\n");
974
- * ```
975
- */
976
- const unindent = (...params) => {
862
+ const concatTemplateStrings = (template, values) => template.reduce((acc, part, index) => acc + part + (values[index] ?? ""), "");
863
+ function unindent(...params) {
977
864
  let trimStart = true;
978
865
  let trimEnd = true;
979
- const unindentImpl = (...params$1) => {
980
- const lines = splitByLineBreak(e$1(params$1[0]) ? params$1[0] : concatTemplateStrings(params$1[0], params$1.slice(1)));
866
+ const unindentImpl = (...params) => {
867
+ const lines = splitByLineBreak(isString(params[0]) ? params[0] : concatTemplateStrings(params[0], params.slice(1)));
981
868
  let commonIndent = Number.POSITIVE_INFINITY;
982
869
  let firstContentLine = -1;
983
870
  for (let i = 0; i < lines.length; i++) {
984
871
  const line = lines[i];
985
872
  if (REGEXP_WHITESPACE_ONLY.test(line)) continue;
986
873
  if (firstContentLine === -1) firstContentLine = i;
987
- const indent$1 = line.match(REGEXP_WHITESPACE_PREFIX)?.[0].length ?? 0;
988
- commonIndent = Math.min(commonIndent, indent$1);
874
+ const indent = line.match(REGEXP_WHITESPACE_PREFIX)?.[0].length ?? 0;
875
+ commonIndent = Math.min(commonIndent, indent);
989
876
  }
990
877
  if (firstContentLine === -1) commonIndent = 0;
991
878
  if (!Number.isFinite(commonIndent)) commonIndent = 0;
@@ -995,41 +882,20 @@ const unindent = (...params) => {
995
882
  if (trimEnd) while (endIndex > startIndex && REGEXP_WHITESPACE_ONLY.test(lines[endIndex - 1])) endIndex--;
996
883
  return lines.slice(startIndex, endIndex).map((line) => line.slice(commonIndent)).join("\n");
997
884
  };
998
- if ((e$4(params[0]) || params[0] === void 0) && (e$4(params[1]) || params[1] === void 0)) {
885
+ if ((isBoolean(params[0]) || params[0] === void 0) && (isBoolean(params[1]) || params[1] === void 0)) {
999
886
  trimStart = params[0] !== false;
1000
887
  trimEnd = params[1] !== false;
1001
888
  return unindentImpl;
1002
889
  }
1003
- if (e$1(params[0]) || e$6(params[0])) return unindentImpl(...params);
890
+ if (isString(params[0]) || isArray(params[0])) return unindentImpl(...params);
1004
891
  throw new TypeError(`First parameter has an invalid type: "${typeof params[0]}"`);
1005
- };
1006
- /**
1007
- * @example
1008
- * ```ts
1009
- * // Using indent count with default space character
1010
- * const str1 = indent(2)`
1011
- * if (a) {
1012
- * b()
1013
- * }
1014
- * `;
1015
- *
1016
- * // Using custom indent string directly
1017
- * const str2 = indent(">>")`
1018
- * if (a) {
1019
- * b()
1020
- * }
1021
- * `;
1022
- *
1023
- * // Only trim start, keep end
1024
- * const str3 = indent(2, true, false)("hello\nworld\n");
1025
- * ```
1026
- */
1027
- const indent = (...params) => {
892
+ }
893
+ function indent(...params) {
1028
894
  let indentString;
1029
895
  let trimStart = true;
1030
896
  let trimEnd = true;
1031
- const indentImpl = (...params$1) => {
1032
- const lines = splitByLineBreak(e$1(params$1[0]) ? params$1[0] : concatTemplateStrings(params$1[0], params$1.slice(1)));
897
+ const indentImpl = (...params) => {
898
+ const lines = splitByLineBreak(isString(params[0]) ? params[0] : concatTemplateStrings(params[0], params.slice(1)));
1033
899
  const whitespaceLines = lines.map((line) => REGEXP_WHITESPACE_ONLY.test(line));
1034
900
  let startIndex = 0;
1035
901
  let endIndex = lines.length;
@@ -1039,23 +905,23 @@ const indent = (...params) => {
1039
905
  return whitespaceLines[index + startIndex] ? line : indentString + line;
1040
906
  }).join("\n");
1041
907
  };
1042
- if ((e$4(params[1]) || params[1] === void 0) && (e$4(params[2]) || params[2] === void 0)) {
908
+ if ((isBoolean(params[1]) || params[1] === void 0) && (isBoolean(params[2]) || params[2] === void 0)) {
1043
909
  trimStart = params[1] !== false;
1044
910
  trimEnd = params[2] !== false;
1045
911
  }
1046
- if (e$2(params[0])) {
912
+ if (isNumber(params[0])) {
1047
913
  indentString = " ".repeat(params[0]);
1048
914
  return indentImpl;
1049
915
  }
1050
- if (e$1(params[0])) {
916
+ if (isString(params[0])) {
1051
917
  indentString = params[0];
1052
918
  return indentImpl;
1053
919
  }
1054
920
  throw new TypeError(`First parameter has an invalid type: "${typeof params[0]}"`);
1055
- };
921
+ }
1056
922
  function template(str, ...args) {
1057
923
  const [firstArg, fallback] = args;
1058
- if (e$7(firstArg)) {
924
+ if (isPlainObject(firstArg)) {
1059
925
  const mapping = firstArg;
1060
926
  return str.replace(/\{(\w+)\}/g, (_, key) => mapping[key] || ((isFunction(fallback) ? fallback(key) : fallback) ?? key));
1061
927
  } else return str.replace(/\{(\d+)\}/g, (_, key) => {
@@ -1071,7 +937,7 @@ const wrap = (fn, wait, options) => {
1071
937
  const { leading, trailing } = options;
1072
938
  let timerId;
1073
939
  const wrapped = (...args) => {
1074
- if (e$8(timerId)) return;
940
+ if (isNonNullish(timerId)) return;
1075
941
  timerId = globalThis.setTimeout(() => {
1076
942
  timerId = void 0;
1077
943
  trailing && fn(...args);
@@ -1079,7 +945,7 @@ const wrap = (fn, wait, options) => {
1079
945
  leading && fn(...args);
1080
946
  };
1081
947
  wrapped.cancel = () => {
1082
- if (e$8(timerId)) globalThis.clearTimeout(timerId);
948
+ if (isNonNullish(timerId)) globalThis.clearTimeout(timerId);
1083
949
  timerId = void 0;
1084
950
  };
1085
951
  return wrapped;
@@ -1100,4 +966,4 @@ const throttle = (fn, wait = 0, options = {}) => {
1100
966
  };
1101
967
 
1102
968
  //#endregion
1103
- 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 _, concatTemplateStrings as a, sleep as b, joinWithSlash as c, split as d, splitByLineBreak as f, unindent as g, toForwardSlash as h, addSuffix as i, err as j, unsafeParse as k, removePrefix as l, template as m, throttle as n, indent as o, splitWithSlash as p, addPrefix as r, join as s, debounce as t, removeSuffix as u, createPromiseWithResolvers as v, scale as w, parseKeyValuePairs as x, createSingleton as y };
969
+ export { Result as A, linear as C, safeParse as D, normalizeError as E, ok as M, ResultError as N, stringify as O, parseValueToBoolean as S, getErrorMessage as T, createLock as _, concatTemplateStrings as a, sleep as b, joinWithSlash as c, split as d, splitByLineBreak as f, unindent as g, toForwardSlash as h, addSuffix as i, err as j, unsafeParse as k, removePrefix as l, template as m, throttle as n, indent as o, splitWithSlash as p, addPrefix as r, join as s, debounce as t, removeSuffix as u, createPromiseWithResolvers as v, scale as w, parseKeyValuePairs as x, createSingleton as y };