resultar 1.4.5 → 2.0.0-beta.2

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,745 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/result-async.ts
21
- var result_async_exports = {};
22
- __export(result_async_exports, {
23
- DisposableResultAsync: () => DisposableResultAsync,
24
- ResultAsync: () => ResultAsync,
25
- errAsync: () => errAsync,
26
- fromPromise: () => fromPromise,
27
- fromSafePromise: () => fromSafePromise,
28
- fromThrowableAsync: () => fromThrowableAsync,
29
- okAsync: () => okAsync,
30
- safeTryAsync: () => safeTryAsync,
31
- tryCatchAsync: () => tryCatchAsync,
32
- unitAsync: () => unitAsync
33
- });
34
- module.exports = __toCommonJS(result_async_exports);
35
-
36
- // src/error.ts
37
- var defaultErrorConfig = {
38
- withStackTrace: false
39
- };
40
- var createResultarError = (message, result, config = defaultErrorConfig) => {
41
- const data = result.isOk() ? { type: "Ok", value: result.value } : { type: "Err", value: result.error };
42
- const maybeStack = config.withStackTrace ? new Error().stack : void 0;
43
- return {
44
- name: "ResultarError",
45
- data,
46
- message,
47
- stack: maybeStack
48
- };
49
- };
50
-
51
- // src/utils.ts
52
- var combineResultList = (resultList) => {
53
- let acc = ok([]);
54
- for (const result of resultList) {
55
- if (result.isErr()) {
56
- acc = err(result.error);
57
- break;
58
- } else {
59
- acc.map((list) => list.push(result.value));
60
- }
61
- }
62
- return acc;
63
- };
64
- var combineResultAsyncList = (asyncResultList) => ResultAsync.fromSafePromise(Promise.all(asyncResultList)).andThen(
65
- combineResultList
66
- );
67
- var combineResultListWithAllErrors = (resultList) => {
68
- let acc = ok([]);
69
- for (const result of resultList) {
70
- if (result.isErr() && acc.isErr()) {
71
- acc.error.push(result.error);
72
- } else if (result.isErr() && acc.isOk()) {
73
- acc = err([result.error]);
74
- } else if (result.isOk() && acc.isOk()) {
75
- acc.value.push(result.value);
76
- }
77
- }
78
- return acc;
79
- };
80
- var combineResultAsyncListWithAllErrors = (asyncResultList) => ResultAsync.fromSafePromise(Promise.all(asyncResultList)).andThen(
81
- combineResultListWithAllErrors
82
- );
83
-
84
- // src/result.ts
85
- var Ok = class {
86
- constructor(value) {
87
- this.value = value;
88
- }
89
- ok = true;
90
- };
91
- var Err = class {
92
- constructor(error) {
93
- this.error = error;
94
- }
95
- ok = false;
96
- };
97
- var Result = class _Result {
98
- constructor(state) {
99
- this.state = state;
100
- if (state.ok) {
101
- this.value = state.value;
102
- this.error = void 0;
103
- } else {
104
- this.error = state.error;
105
- this.value = void 0;
106
- }
107
- }
108
- /**
109
- * Creates a `Result` by running a function that might throw.
110
- * If the function throws, the error will be caught and returned as an `Err`.
111
- * If the function succeeds, the value will be wrapped in an `Ok`.
112
- *
113
- * @param fn - The function to execute, which might throw an error
114
- * @param errorFn - Optional function to transform the thrown error before wrapping in `Err`
115
- * @returns A `Result` containing either the function's return value or the caught error
116
- */
117
- static tryCatch(fn, errorFn) {
118
- try {
119
- return ok(fn());
120
- } catch (error) {
121
- if (errorFn) {
122
- return err(errorFn(error));
123
- }
124
- return err(error);
125
- }
126
- }
127
- /**
128
- * Wraps a function with a try catch, creating a new function with the same
129
- * arguments but returning `Ok` if successful, `Err` if the function throws
130
- *
131
- * @param fn function to wrap with ok on success or err on failure
132
- * @param errorFn when an error is thrown, this will wrap the error result if provided
133
- */
134
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
135
- static fromThrowable(fn, errorFn) {
136
- return (...args) => {
137
- try {
138
- const result = fn(...args);
139
- return ok(result);
140
- } catch (error) {
141
- if (errorFn) {
142
- return err(errorFn(error));
143
- }
144
- return err(error);
145
- }
146
- };
147
- }
148
- static ok(value) {
149
- return new _Result(new Ok(value));
150
- }
151
- /**
152
- * Creates a new `Result` instance representing a successful operation with an undefined value.
153
- *
154
- * @return {Result<undefined, E>} A new `Result` instance with an undefined value.
155
- */
156
- static unit() {
157
- return new _Result(new Ok(void 0));
158
- }
159
- static err(error) {
160
- return new _Result(new Err(error));
161
- }
162
- static combine(resultList) {
163
- return combineResultList(resultList);
164
- }
165
- static combineWithAllErrors(resultList) {
166
- return combineResultListWithAllErrors(
167
- resultList
168
- );
169
- }
170
- value;
171
- error;
172
- /**
173
- * Used to check if a `Result` is an `OK`
174
- *
175
- * @returns `true` if the result is an `OK` variant of Result
176
- */
177
- isOk() {
178
- return this.state.ok;
179
- }
180
- /**
181
- * Used to check if a `Result` is an `Err`
182
- *
183
- * @returns `true` if the result is an `Err` variant of Result
184
- */
185
- isErr() {
186
- return !this.state.ok;
187
- }
188
- /**
189
- * Maps a `Result<T, E>` to `Result<U, E>`
190
- * by applying a function to a contained `Ok` value, leaving an `Err` value
191
- * untouched.
192
- *
193
- * @param f The function to apply an `OK` value
194
- * @returns the result of applying `f` or an `Err` untouched
195
- */
196
- map(f) {
197
- if (this.state.ok) {
198
- const value = f(this.value);
199
- return ok(value);
200
- }
201
- return err(this.error);
202
- }
203
- /**
204
- * Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a
205
- * contained `Err` value, leaving an `Ok` value untouched.
206
- *
207
- * This function can be used to pass through a successful result while
208
- * handling an error.
209
- *
210
- * @param f a function to apply to the error `Err` value
211
- */
212
- mapErr(fn) {
213
- if (this.state.ok) {
214
- return ok(this.value);
215
- }
216
- return err(fn(this.error));
217
- }
218
- /**
219
- * Similar to `map` Except you must return a new `Result`.
220
- *
221
- * This is useful for when you need to do a subsequent computation using the
222
- * inner `T` value, but that computation might fail.
223
- * Additionally, `andThen` is really useful as a tool to flatten a
224
- * `Result<Result<A, E2>, E1>` into a `Result<A, E2>` (see example below).
225
- *
226
- * @param f The function to apply to the current value
227
- */
228
- andThen(f) {
229
- if (this.state.ok) {
230
- return f(this.value);
231
- }
232
- return err(this.error);
233
- }
234
- if(fCondition) {
235
- return {
236
- true: (fTrue) => ({
237
- false: (fFalse) => {
238
- if (this.state.ok) {
239
- const condition = fCondition(this.value);
240
- return condition ? fTrue(this.value) : fFalse(this.value);
241
- }
242
- return err(this.error);
243
- }
244
- })
245
- };
246
- }
247
- orElse(f) {
248
- if (this.state.ok) {
249
- return ok(this.value);
250
- }
251
- return f(this.error);
252
- }
253
- asyncAndThen(f) {
254
- if (this.state.ok) {
255
- return f(this.value);
256
- }
257
- return errAsync(this.error);
258
- }
259
- /**
260
- * Maps a `Result<T, E>` to `ResultAsync<U, E>`
261
- * by applying an async function to a contained `Ok` value, leaving an `Err`
262
- * value untouched.
263
- *
264
- * @param f An async function to apply an `OK` value
265
- */
266
- asyncMap(f) {
267
- if (this.state.ok) {
268
- return ResultAsync.fromSafePromise(f(this.value));
269
- }
270
- return errAsync(this.error);
271
- }
272
- /**
273
- * Unwrap the `Ok` value, or return the default if there is an `Err`
274
- *
275
- * @param v the default value to return if there is an `Err`
276
- */
277
- unwrapOr(defaultValue) {
278
- if (this.state.ok) {
279
- return this.value;
280
- }
281
- return defaultValue;
282
- }
283
- /**
284
- * Given 2 functions (one for the `Ok` variant and one for the `Err` variant)
285
- * execute the function that matches the `Result` variant.
286
- *
287
- * Match callbacks do not necessitate to return a `Result`, however you can
288
- * return a `Result` if you want to.
289
- *
290
- * `match` is like chaining `map` and `mapErr`, with the distinction that
291
- * with `match` both functions must have the same return type.
292
- *
293
- * @param ok
294
- * @param err
295
- */
296
- match(fnOk, fnErr) {
297
- if (this.state.ok) {
298
- return fnOk(this.value);
299
- }
300
- return fnErr(this.error);
301
- }
302
- /**
303
- * Performs a side effect for the `Ok` or `Err` variant of `Result`.
304
- *
305
- * @param fn The function to apply an `OK` value
306
- * @returns the result of applying `f` or an `Err` untouched
307
- */
308
- log(fn) {
309
- try {
310
- fn(this.value, this.error);
311
- } catch {
312
- }
313
- return this;
314
- }
315
- /**
316
- * Performs a side effect for the `Ok` variant of `Result`.
317
- *
318
- * @param fn The function to apply an `OK` value
319
- * @returns the result of applying `f` or an `Err` untouched
320
- */
321
- tap(fn) {
322
- if (this.state.ok) {
323
- try {
324
- fn(this.value);
325
- } catch {
326
- }
327
- }
328
- return this;
329
- }
330
- /**
331
- * Performs a side effect for the `Err` variant of `Result`.
332
- *
333
- * @param fn The function to apply an `Err` value
334
- * @returns the result of applying `f` or an `Ok` untouched
335
- */
336
- tapError(fn) {
337
- if (!this.state.ok) {
338
- try {
339
- fn(this.error);
340
- } catch {
341
- }
342
- }
343
- return this;
344
- }
345
- finally(f) {
346
- const resultDisposable = new DisposableResult(this, f);
347
- try {
348
- return resultDisposable;
349
- } finally {
350
- resultDisposable[Symbol.dispose]();
351
- }
352
- }
353
- unwrapOrThrow() {
354
- if (this.state.ok) {
355
- return this.value;
356
- }
357
- throw this.error;
358
- }
359
- /**
360
- * **This method is unsafe, and should only be used in a test environments**
361
- *
362
- * Takes a `Result<T, E>` and returns a `T` when the result is an `Ok`, otherwise it throws a custom object.
363
- *
364
- * @param config
365
- */
366
- _unsafeUnwrap(config) {
367
- if (this.state.ok) {
368
- return this.value;
369
- }
370
- throw createResultarError("Called `_unsafeUnwrap` on an Err", this, config);
371
- }
372
- /**
373
- * **This method is unsafe, and should only be used in a test environments**
374
- *
375
- * takes a `Result<T, E>` and returns a `E` when the result is an `Err`,
376
- * otherwise it throws a custom object.
377
- *
378
- * @param config
379
- */
380
- _unsafeUnwrapErr(config) {
381
- if (this.state.ok) {
382
- throw createResultarError(
383
- "Called `_unsafeUnwrapErr` on an Ok",
384
- this,
385
- config
386
- );
387
- }
388
- return this.error;
389
- }
390
- *[Symbol.iterator]() {
391
- if (this.state.ok) {
392
- return this.value;
393
- }
394
- const self = this;
395
- yield self;
396
- return self;
397
- }
398
- safeUnwrap() {
399
- if (this.state.ok) {
400
- const { value } = this;
401
- return function* () {
402
- return value;
403
- }();
404
- }
405
- const { error } = this;
406
- return function* () {
407
- yield err(error);
408
- throw new Error("Do not use this generator out of `safeTry`");
409
- }();
410
- }
411
- };
412
- var DisposableResult = class {
413
- constructor(result, finalizer) {
414
- this.result = result;
415
- this.finalizer = finalizer;
416
- }
417
- get value() {
418
- return this.result.value;
419
- }
420
- get error() {
421
- return this.result.error;
422
- }
423
- _unsafeUnwrap(config) {
424
- return this.result._unsafeUnwrap(config);
425
- }
426
- _unsafeUnwrapErr(config) {
427
- return this.result._unsafeUnwrapErr(config);
428
- }
429
- isOk() {
430
- return this.result.isOk();
431
- }
432
- isErr() {
433
- return this.result.isErr();
434
- }
435
- unwrapOr(defaultValue) {
436
- return this.result.unwrapOr(defaultValue);
437
- }
438
- [Symbol.dispose]() {
439
- this.finalizer(this.result.value, this.result.error);
440
- }
441
- };
442
- var ok = Result.ok;
443
- var err = Result.err;
444
- var fromThrowable = Result.fromThrowable;
445
- var unit = Result.unit;
446
- var tryCatch = Result.tryCatch;
447
-
448
- // src/result-async.ts
449
- var DisposableResultAsync = class {
450
- innerPromise;
451
- constructor(res) {
452
- this.innerPromise = res;
453
- }
454
- then(successCallback, failureCallback) {
455
- return this.innerPromise.then(successCallback, failureCallback);
456
- }
457
- };
458
- var ResultAsync = class _ResultAsync {
459
- static okAsync(value) {
460
- return new _ResultAsync(Promise.resolve(Result.ok(value)));
461
- }
462
- /**
463
- * Returns a ResultAsync that is immediately resolved with a Result.ok(undefined) value.
464
- *
465
- * @return {ResultAsync<undefined, E>} A ResultAsync instance with undefined as the value type and E as the error type.
466
- */
467
- static unitAsync() {
468
- return new _ResultAsync(Promise.resolve(Result.unit()));
469
- }
470
- static errAsync(error) {
471
- return new _ResultAsync(Promise.resolve(Result.err(error)));
472
- }
473
- /**
474
- * Creates a ResultAsync from a Promise, catching any errors that occur during its execution.
475
- *
476
- * @param fn - The Promise or a function returning a Promise to be wrapped in a ResultAsync.
477
- * @param errorFn - Optional function to transform the caught error into a specific error type.
478
- * If not provided, the original error will be used.
479
- * @returns A ResultAsync that will resolve to Ok with the promise's value if successful,
480
- * or Err with either the transformed error (if errorFn is provided) or the original error.
481
- *
482
- * @example
483
- * ```typescript
484
- * // Without error transformer
485
- * const result = ResultAsync.tryCatch(Promise.resolve(42));
486
- *
487
- * // With error transformer
488
- * const result = ResultAsync.tryCatch(
489
- * fetch('https://api.example.com'),
490
- * (error) => new CustomError('API request failed')
491
- * );
492
- * ```
493
- */
494
- static tryCatch(fn, errorFn) {
495
- const promiseToProcess = typeof fn === "function" ? fn() : fn;
496
- const newPromise = promiseToProcess.then((value) => Result.ok(value)).catch((error) => {
497
- if (errorFn) {
498
- return Result.err(errorFn(error));
499
- }
500
- return Result.err(error);
501
- });
502
- return new _ResultAsync(newPromise);
503
- }
504
- static fromSafePromise(promise) {
505
- const newPromise = promise.then((value) => Result.ok(value));
506
- return new _ResultAsync(newPromise);
507
- }
508
- static fromPromise(promise, errorFn) {
509
- const newPromise = promise.then((value) => Result.ok(value)).catch((error) => Result.err(errorFn(error)));
510
- return new _ResultAsync(newPromise);
511
- }
512
- static combine(asyncResultList) {
513
- return combineResultAsyncList(asyncResultList);
514
- }
515
- static combineWithAllErrors(asyncResultList) {
516
- return combineResultAsyncListWithAllErrors(
517
- asyncResultList
518
- );
519
- }
520
- /**
521
- * Wraps a async function with a try catch, creating a new function with the same
522
- * arguments but returning `Ok` if successful, `Err` if the function throws
523
- *
524
- * @param fn function to wrap with ok on success or err on failure
525
- * @param errorFn when an error is thrown, this will wrap the error result if provided
526
- * @returns a new function that returns a `ResultAsync`
527
- */
528
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
529
- static fromThrowable(fn, errorFn) {
530
- return (...args) => new _ResultAsync(
531
- (async () => {
532
- try {
533
- const v = await fn(...args);
534
- return Result.ok(v);
535
- } catch (error) {
536
- const e = errorFn ? errorFn(error) : error;
537
- return Result.err(e);
538
- }
539
- })()
540
- );
541
- }
542
- innerPromise;
543
- constructor(res) {
544
- this.innerPromise = res;
545
- }
546
- then(successCallback, failureCallback) {
547
- return this.innerPromise.then(successCallback, failureCallback);
548
- }
549
- mapErr(f) {
550
- return new _ResultAsync(this.innerPromise.then(async (res) => {
551
- if (res.isOk()) {
552
- return okAsync(res.value);
553
- }
554
- return errAsync(await f(res.error));
555
- }));
556
- }
557
- map(f) {
558
- const x = new _ResultAsync(
559
- this.innerPromise.then(async (res) => {
560
- if (res.isErr()) {
561
- return errAsync(res.error);
562
- }
563
- return okAsync(await f(res.value));
564
- })
565
- );
566
- return x;
567
- }
568
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
569
- andThen(f) {
570
- return new _ResultAsync(
571
- // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
572
- this.innerPromise.then(async (res) => {
573
- if (res.isErr()) {
574
- return errAsync(res.error);
575
- }
576
- const newValue = f(res.value);
577
- return newValue instanceof _ResultAsync ? newValue.innerPromise : newValue;
578
- })
579
- );
580
- }
581
- if(fCondition) {
582
- return {
583
- true: (fTrue) => ({
584
- false: (fFalse) => new _ResultAsync(this.innerPromise.then(async (res) => {
585
- if (res.isOk()) {
586
- const condition = fCondition(res.value);
587
- return condition ? fTrue(res.value) : fFalse(res.value);
588
- }
589
- return errAsync(res.error);
590
- }))
591
- })
592
- };
593
- }
594
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
595
- orElse(f) {
596
- return new _ResultAsync(
597
- this.innerPromise.then(async (res) => {
598
- if (res.isErr()) {
599
- return f(res.error);
600
- }
601
- return okAsync(res.value);
602
- })
603
- );
604
- }
605
- async match(ok2, fnErr) {
606
- return this.innerPromise.then((res) => res.match(ok2, fnErr));
607
- }
608
- async unwrapOr(t) {
609
- return this.innerPromise.then((res) => res.unwrapOr(t));
610
- }
611
- async unwrapOrThrow() {
612
- return this.innerPromise.then((res) => res.unwrapOrThrow());
613
- }
614
- /**
615
- * Performs a side effect for the `Ok` variant of `ResultAsync`.
616
- * This function can be used for control flow based on result values.
617
- * @param f The function to call if the result is `Ok`
618
- * @returns `self` if the result is `Err`, otherwise the result of `f`
619
- */
620
- log(f) {
621
- return new _ResultAsync(
622
- this.innerPromise.then(async (res) => {
623
- if (res.isOk()) {
624
- try {
625
- await f(res.value);
626
- } catch {
627
- }
628
- return okAsync(res.value);
629
- }
630
- try {
631
- await f(void 0, res.error);
632
- } catch {
633
- }
634
- return errAsync(res.error);
635
- })
636
- );
637
- }
638
- /**
639
- * Performs a side effect for the `Ok` variant of `ResultAsync`.
640
- * This function can be used for control flow based on result values.
641
- * @param f The function to call if the result is `Ok`
642
- * @returns `self` if the result is `Err`, otherwise the result of `f`
643
- */
644
- tap(f) {
645
- return new _ResultAsync(
646
- this.innerPromise.then(async (res) => {
647
- if (res.isErr()) {
648
- return errAsync(res.error);
649
- }
650
- try {
651
- await f(res.value);
652
- } catch {
653
- }
654
- return okAsync(res.value);
655
- })
656
- );
657
- }
658
- /**
659
- * Performs a side effect for the `Err` variant of `ResultAsync`.
660
- * This function can be used for control flow based on result values.
661
- * @param f The function to call if the result is `Err`
662
- * @returns `self` if the result is `Ok`, otherwise the result of `f`
663
- * @example
664
- */
665
- tapError(f) {
666
- return new _ResultAsync(
667
- this.innerPromise.then(async (res) => {
668
- if (res.isErr()) {
669
- try {
670
- await f(res.error);
671
- } catch {
672
- }
673
- return errAsync(res.error);
674
- }
675
- return okAsync(res.value);
676
- })
677
- );
678
- }
679
- finally(f) {
680
- return new DisposableResultAsync(
681
- // eslint-disable-next-line @typescript-eslint/require-await
682
- this.innerPromise.then(async (res) => {
683
- try {
684
- res.finally(f);
685
- } catch {
686
- }
687
- return res;
688
- })
689
- );
690
- }
691
- async *[Symbol.asyncIterator]() {
692
- const result = await this.innerPromise;
693
- if (result.isErr()) {
694
- yield errAsync(result.error);
695
- }
696
- return result.value;
697
- }
698
- /**
699
- * @deprecated will be removed in 2.0.0.
700
- *
701
- * You can use `safeTry` without this method.
702
- * @example
703
- * ```typescript
704
- * safeTry(async function* () {
705
- * const okValue = yield* yourResult
706
- * })
707
- * ```
708
- * Emulates Rust's `?` operator in `safeTry`'s body. See also `safeTry`.
709
- */
710
- async *safeUnwrap() {
711
- return yield* await this.innerPromise.then((res) => res.safeUnwrap());
712
- }
713
- };
714
- function safeTryAsync(body) {
715
- return new ResultAsync(
716
- (async () => {
717
- const n = await body().next();
718
- if (n.value.isOk()) {
719
- return okAsync(n.value.value);
720
- }
721
- return errAsync(n.value.error);
722
- })()
723
- );
724
- }
725
- var okAsync = ResultAsync.okAsync;
726
- var errAsync = ResultAsync.errAsync;
727
- var fromPromise = ResultAsync.fromPromise;
728
- var fromSafePromise = ResultAsync.fromSafePromise;
729
- var unitAsync = ResultAsync.unitAsync;
730
- var fromThrowableAsync = ResultAsync.fromThrowable;
731
- var tryCatchAsync = ResultAsync.tryCatch;
732
- // Annotate the CommonJS export names for ESM import in node:
733
- 0 && (module.exports = {
734
- DisposableResultAsync,
735
- ResultAsync,
736
- errAsync,
737
- fromPromise,
738
- fromSafePromise,
739
- fromThrowableAsync,
740
- okAsync,
741
- safeTryAsync,
742
- tryCatchAsync,
743
- unitAsync
744
- });
745
- //# sourceMappingURL=result-async.cjs.map