@carbonteq/fp 0.9.1 → 0.10.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.
Files changed (146) hide show
  1. package/README.md +310 -96
  2. package/dist/errors.cjs +1 -0
  3. package/dist/errors.cjs.map +1 -1
  4. package/dist/errors.d.cts.map +1 -1
  5. package/dist/errors.d.mts.map +1 -1
  6. package/dist/errors.mjs.map +1 -1
  7. package/dist/flow-experimental.cjs +286 -0
  8. package/dist/flow-experimental.cjs.map +1 -0
  9. package/dist/flow-experimental.d.cts +69 -0
  10. package/dist/flow-experimental.d.cts.map +1 -0
  11. package/dist/flow-experimental.d.mts +69 -0
  12. package/dist/flow-experimental.d.mts.map +1 -0
  13. package/dist/flow-experimental.mjs +284 -0
  14. package/dist/flow-experimental.mjs.map +1 -0
  15. package/dist/flow.cjs +296 -0
  16. package/dist/flow.cjs.map +1 -0
  17. package/dist/flow.d.cts +79 -0
  18. package/dist/flow.d.cts.map +1 -0
  19. package/dist/flow.d.mts +79 -0
  20. package/dist/flow.d.mts.map +1 -0
  21. package/dist/flow.mjs +294 -0
  22. package/dist/flow.mjs.map +1 -0
  23. package/dist/index.cjs +26 -11
  24. package/dist/index.d.cts +8 -3
  25. package/dist/index.d.mts +8 -3
  26. package/dist/index.mjs +8 -3
  27. package/dist/match.cjs +282 -0
  28. package/dist/match.cjs.map +1 -1
  29. package/dist/match.d.cts +471 -5
  30. package/dist/match.d.cts.map +1 -1
  31. package/dist/match.d.mts +471 -5
  32. package/dist/match.d.mts.map +1 -1
  33. package/dist/match.mjs +277 -1
  34. package/dist/match.mjs.map +1 -1
  35. package/dist/option-experimental.cjs +1503 -0
  36. package/dist/option-experimental.cjs.map +1 -0
  37. package/dist/option-experimental.d.cts +1383 -0
  38. package/dist/option-experimental.d.cts.map +1 -0
  39. package/dist/option-experimental.d.mts +1383 -0
  40. package/dist/option-experimental.d.mts.map +1 -0
  41. package/dist/option-experimental.mjs +1501 -0
  42. package/dist/option-experimental.mjs.map +1 -0
  43. package/dist/option.cjs +556 -29
  44. package/dist/option.cjs.map +1 -1
  45. package/dist/option.d.cts +505 -24
  46. package/dist/option.d.cts.map +1 -1
  47. package/dist/option.d.mts +505 -24
  48. package/dist/option.d.mts.map +1 -1
  49. package/dist/option.mjs +556 -30
  50. package/dist/option.mjs.map +1 -1
  51. package/dist/result-experimental.cjs +1266 -0
  52. package/dist/result-experimental.cjs.map +1 -0
  53. package/dist/result-experimental.d.cts +1127 -0
  54. package/dist/result-experimental.d.cts.map +1 -0
  55. package/dist/result-experimental.d.mts +1127 -0
  56. package/dist/result-experimental.d.mts.map +1 -0
  57. package/dist/result-experimental.mjs +1265 -0
  58. package/dist/result-experimental.mjs.map +1 -0
  59. package/dist/result.cjs +715 -122
  60. package/dist/result.cjs.map +1 -1
  61. package/dist/result.d.cts +785 -94
  62. package/dist/result.d.cts.map +1 -1
  63. package/dist/result.d.mts +785 -94
  64. package/dist/result.d.mts.map +1 -1
  65. package/dist/result.mjs +714 -117
  66. package/dist/result.mjs.map +1 -1
  67. package/dist/tuple.cjs +3 -0
  68. package/dist/tuple.cjs.map +1 -1
  69. package/dist/tuple.d.cts +5 -1
  70. package/dist/tuple.d.cts.map +1 -1
  71. package/dist/tuple.d.mts +5 -1
  72. package/dist/tuple.d.mts.map +1 -1
  73. package/dist/tuple.mjs +2 -0
  74. package/dist/tuple.mjs.map +1 -1
  75. package/dist/unit.cjs +2 -0
  76. package/dist/unit.cjs.map +1 -1
  77. package/dist/unit.d.cts +2 -0
  78. package/dist/unit.d.cts.map +1 -1
  79. package/dist/unit.d.mts +2 -0
  80. package/dist/unit.d.mts.map +1 -1
  81. package/dist/unit.mjs +1 -0
  82. package/dist/unit.mjs.map +1 -1
  83. package/dist/utils.cjs +15 -0
  84. package/dist/utils.cjs.map +1 -1
  85. package/dist/utils.d.cts +10 -1
  86. package/dist/utils.d.cts.map +1 -1
  87. package/dist/utils.d.mts +10 -1
  88. package/dist/utils.d.mts.map +1 -1
  89. package/dist/utils.mjs +13 -1
  90. package/dist/utils.mjs.map +1 -1
  91. package/examples/README.md +46 -0
  92. package/examples/flow/01-basics.ts +74 -0
  93. package/examples/flow/02-async.ts +73 -0
  94. package/examples/flow/03-recovery.ts +60 -0
  95. package/examples/flow/04-complex-backend.ts +237 -0
  96. package/examples/flow/05-complex-backend-asyncGen.ts +224 -0
  97. package/examples/flow/index.ts +13 -0
  98. package/examples/flow-experimental/01-basics.ts +78 -0
  99. package/examples/flow-experimental/02-async.ts +77 -0
  100. package/examples/flow-experimental/03-recovery.ts +93 -0
  101. package/examples/flow-experimental/04-complex-backend.ts +241 -0
  102. package/examples/flow-experimental/05-complex-backend-asyncGen.ts +229 -0
  103. package/examples/flow-experimental/index.ts +14 -0
  104. package/examples/match/01-stable-match.ts +147 -0
  105. package/examples/match/index.ts +19 -0
  106. package/examples/match-experimental/01-experimental-match.ts +150 -0
  107. package/examples/match-experimental/index.ts +18 -0
  108. package/examples/option/01-basics.ts +16 -0
  109. package/examples/option/02-map-flatMap.ts +36 -0
  110. package/examples/option/03-zip-flatZip.ts +23 -0
  111. package/examples/option/04-constructors.ts +21 -0
  112. package/examples/option/05-transform.ts +15 -0
  113. package/examples/option/06-aggregation.ts +14 -0
  114. package/examples/option/index.ts +49 -0
  115. package/examples/option-experimental/01-map.ts +109 -0
  116. package/examples/option-experimental/02-flatMap.ts +234 -0
  117. package/examples/option-experimental/03-zip.ts +197 -0
  118. package/examples/option-experimental/04-flatZip.ts +251 -0
  119. package/examples/option-experimental/05-gen.ts +360 -0
  120. package/examples/option-experimental/06-genAdapter.ts +463 -0
  121. package/examples/option-experimental/07-asyncGen.ts +353 -0
  122. package/examples/option-experimental/08-asyncGenAdapter.ts +514 -0
  123. package/examples/option-experimental/09-workflow-simple-sync.ts +321 -0
  124. package/examples/option-experimental/10-workflow-async.ts +378 -0
  125. package/examples/option-experimental/index.ts +341 -0
  126. package/examples/option-experimental/shared-domain.ts +325 -0
  127. package/examples/result/01-basics.ts +16 -0
  128. package/examples/result/02-map-flatMap.ts +34 -0
  129. package/examples/result/03-zip-flatZip.ts +23 -0
  130. package/examples/result/04-validation.ts +44 -0
  131. package/examples/result/05-constructors.ts +30 -0
  132. package/examples/result/06-utilities.ts +36 -0
  133. package/examples/result/index.ts +53 -0
  134. package/examples/result-experimental/01-map.ts +60 -0
  135. package/examples/result-experimental/02-flatMap.ts +169 -0
  136. package/examples/result-experimental/03-zip.ts +145 -0
  137. package/examples/result-experimental/04-flatZip.ts +252 -0
  138. package/examples/result-experimental/05-gen.ts +293 -0
  139. package/examples/result-experimental/06-genAdapter.ts +396 -0
  140. package/examples/result-experimental/07-asyncGen.ts +379 -0
  141. package/examples/result-experimental/08-asyncGenAdapter.ts +553 -0
  142. package/examples/result-experimental/09-workflow-simple-sync.ts +304 -0
  143. package/examples/result-experimental/10-workflow-async.ts +356 -0
  144. package/examples/result-experimental/index.ts +312 -0
  145. package/examples/result-experimental/shared-domain.ts +263 -0
  146. package/package.json +50 -18
@@ -0,0 +1,1266 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_errors = require('./errors.cjs');
3
+ const require_unit = require('./unit.cjs');
4
+ const require_utils = require('./utils.cjs');
5
+ const require_option_experimental = require('./option-experimental.cjs');
6
+
7
+ //#region src/result-experimental.ts
8
+ /** Sentinel value stored in #val when Result is Err */
9
+ const ERR_VAL = Symbol("Result::Err");
10
+ /**
11
+ * Wrapper that makes Result yieldable with proper type tracking.
12
+ * The Generator signature ensures TypeScript tracks the inner type T.
13
+ *
14
+ * @internal
15
+ */
16
+ var ResultYieldWrap = class {
17
+ constructor(result) {
18
+ this.result = result;
19
+ }
20
+ *[Symbol.iterator]() {
21
+ const trace = (/* @__PURE__ */ new Error()).stack;
22
+ return yield new require_utils.CapturedTrace(this, trace);
23
+ }
24
+ };
25
+ /**
26
+ * Wrapper that makes Result yieldable in async generators with proper type tracking.
27
+ * Supports Promise<Result<T, E>> for async result chaining.
28
+ *
29
+ * @internal
30
+ */
31
+ var AsyncResultYieldWrap = class {
32
+ constructor(result) {
33
+ this.result = result;
34
+ }
35
+ async *[Symbol.asyncIterator]() {
36
+ const trace = (/* @__PURE__ */ new Error()).stack;
37
+ return yield new require_utils.CapturedTrace(this, trace);
38
+ }
39
+ };
40
+ /**
41
+ * Experimental Result variant with explicit async companion methods.
42
+ */
43
+ var ExperimentalResult = class ExperimentalResult {
44
+ /** Discriminant tag for type-level identification */
45
+ _tag;
46
+ /** Value when Ok; ERR_VAL sentinel when Err */
47
+ #val;
48
+ /** Error when Err (sync); undefined when Ok */
49
+ #err;
50
+ constructor(val, err, tag) {
51
+ this.#val = val;
52
+ this.#err = err;
53
+ this._tag = tag;
54
+ }
55
+ /** Singleton UNIT_RESULT for void-success operations */
56
+ static UNIT_RESULT = new ExperimentalResult(require_unit.UNIT, void 0, "Ok");
57
+ /** Create an Ok containing the given value */
58
+ static Ok(val) {
59
+ return new ExperimentalResult(val, void 0, "Ok");
60
+ }
61
+ /** Create an Err containing the given error */
62
+ static Err(err) {
63
+ return new ExperimentalResult(ERR_VAL, err, "Err");
64
+ }
65
+ /**
66
+ * Type guard for Ok state.
67
+ *
68
+ * Narrows the type, making `T` accessible and `E` equivalent to `never` in
69
+ * the true branch.
70
+ *
71
+ * @returns `true` if this Result is Ok
72
+ *
73
+ * @example
74
+ * ```ts
75
+ * const result = ExperimentalResult.Ok(42);
76
+ * if (result.isOk()) {
77
+ * // TypeScript knows value is accessible: 42
78
+ * console.log(result.unwrap()); // 42
79
+ * }
80
+ * ```
81
+ *
82
+ * @see isErr
83
+ */
84
+ isOk() {
85
+ return this._tag === "Ok" && this.#val !== ERR_VAL;
86
+ }
87
+ /**
88
+ * Type guard for Err state.
89
+ *
90
+ * Narrows the type, making `E` accessible and `T` equivalent to `never` in
91
+ * the true branch.
92
+ *
93
+ * @returns `true` if this Result is Err
94
+ *
95
+ * @example
96
+ * ```ts
97
+ * const result = ExperimentalResult.Err("failed");
98
+ * if (result.isErr()) {
99
+ * // TypeScript knows error is accessible: "failed"
100
+ * console.log(result.unwrapErr()); // "failed"
101
+ * }
102
+ * ```
103
+ *
104
+ * @see isOk
105
+ */
106
+ isErr() {
107
+ return this._tag === "Err" || this.#val === ERR_VAL;
108
+ }
109
+ /**
110
+ * Type guard for Unit value.
111
+ *
112
+ * Returns `true` when the Ok value is the `UNIT` singleton, used for void-success
113
+ * operations (e.g., side-effecting functions that return nothing on success).
114
+ *
115
+ * @returns `true` if this Result is Ok containing UNIT
116
+ *
117
+ * @example
118
+ * ```ts
119
+ * function saveToDb(): ExperimentalResult<UNIT, DbError> {
120
+ * // ... save logic
121
+ * return ExperimentalResult.UNIT_RESULT;
122
+ * }
123
+ *
124
+ * const result = saveToDb();
125
+ * if (result.isUnit()) {
126
+ * console.log("Saved successfully");
127
+ * }
128
+ * ```
129
+ */
130
+ isUnit() {
131
+ return this.#val === require_unit.UNIT;
132
+ }
133
+ /**
134
+ * Returns a string representation of the Result.
135
+ *
136
+ * Useful for debugging and logging. Shows "Result::Ok" or "Result::Err" with
137
+ * the contained value or error.
138
+ *
139
+ * @returns String representation in format "Result::Ok<value>" or "Result::Err<error>"
140
+ *
141
+ * @example
142
+ * ```ts
143
+ * ExperimentalResult.Ok(42).toString(); // "Result::Ok<42>"
144
+ * ExperimentalResult.Err("fail").toString(); // "Result::Err<fail>"
145
+ * ```
146
+ */
147
+ toString() {
148
+ if (this.isOk()) return `Result::Ok<${String(this.#val)}>`;
149
+ return `Result::Err<${String(this.#err)}>`;
150
+ }
151
+ /**
152
+ * Returns the contained value or throws.
153
+ *
154
+ * If the Result is Err and the error extends Error, the original error is re-thrown
155
+ * (preserving stack trace). Otherwise, throws `UnwrappedOkWithErr`.
156
+ *
157
+ * **Use with caution**: Prefer `unwrapOr`, `unwrapOrElse`, or `match` for safer
158
+ * error handling.
159
+ *
160
+ * @throws The original error if E extends Error, otherwise `UnwrappedOkWithErr`
161
+ * @returns The contained value if Ok
162
+ *
163
+ * @example
164
+ * ```ts
165
+ * ExperimentalResult.Ok(42).unwrap(); // 42
166
+ * ExperimentalResult.Err(new Error("fail")).unwrap(); // throws Error("fail")
167
+ * ExperimentalResult.Err("fail").unwrap(); // throws UnwrappedOkWithErr
168
+ * ```
169
+ *
170
+ * @see unwrapOr
171
+ * @see unwrapOrElse
172
+ * @see safeUnwrap
173
+ */
174
+ unwrap() {
175
+ if (this.isErr()) {
176
+ const err = this.#err;
177
+ if (err instanceof Error) throw err;
178
+ throw new require_errors.UnwrappedOkWithErr(this.toString());
179
+ }
180
+ return this.#val;
181
+ }
182
+ /**
183
+ * Returns the contained error or throws.
184
+ *
185
+ * **Use with caution**: Prefer `match` or `isErr` check for safer error access.
186
+ *
187
+ * @throws `UnwrappedErrWithOk` if the Result is Ok
188
+ * @returns The contained error if Err
189
+ *
190
+ * @example
191
+ * ```ts
192
+ * ExperimentalResult.Err("fail").unwrapErr(); // "fail"
193
+ * ExperimentalResult.Ok(42).unwrapErr(); // throws UnwrappedErrWithOk
194
+ * ```
195
+ */
196
+ unwrapErr() {
197
+ if (this._tag === "Err") return this.#err;
198
+ throw new require_errors.UnwrappedErrWithOk(this.toString());
199
+ }
200
+ /**
201
+ * Returns the contained value or the provided default.
202
+ *
203
+ * A safe alternative to `unwrap` for providing fallback values.
204
+ *
205
+ * @param defaultValue - The value to return if Err
206
+ * @returns The contained value if Ok, otherwise defaultValue
207
+ *
208
+ * @example
209
+ * ```ts
210
+ * ExperimentalResult.Ok(42).unwrapOr(0); // 42
211
+ * ExperimentalResult.Err("fail").unwrapOr(0); // 0
212
+ * ```
213
+ *
214
+ * @see unwrapOrElse
215
+ * @see safeUnwrap
216
+ */
217
+ unwrapOr(defaultValue) {
218
+ if (this.isErr()) return defaultValue;
219
+ return this.#val;
220
+ }
221
+ /**
222
+ * Returns the contained value or computes a default from the error.
223
+ *
224
+ * Use when the fallback value depends on the error content.
225
+ *
226
+ * @param fn - Function that receives the error and returns a fallback value
227
+ * @returns The contained value if Ok, otherwise the result of fn(error)
228
+ *
229
+ * @example
230
+ * ```ts
231
+ * const result = ExperimentalResult.Err("Not found");
232
+ * result.unwrapOrElse((err) => `Default: ${err}`); // "Default: Not found"
233
+ *
234
+ * ExperimentalResult.Ok(42).unwrapOrElse((err) => 0); // 42
235
+ * ```
236
+ *
237
+ * @see unwrapOr
238
+ * @see unwrap
239
+ */
240
+ unwrapOrElse(fn) {
241
+ if (this.isErr()) return fn(this.#err);
242
+ return this.#val;
243
+ }
244
+ /**
245
+ * Safely unwraps the value, returning null for Err.
246
+ *
247
+ * A convenience method for JavaScript-friendly null handling.
248
+ *
249
+ * @returns The contained value if Ok, otherwise null
250
+ *
251
+ * @example
252
+ * ```ts
253
+ * ExperimentalResult.Ok(42).safeUnwrap(); // 42
254
+ * ExperimentalResult.Err("fail").safeUnwrap(); // null
255
+ *
256
+ * // Useful for null coalescing
257
+ * const value = result.safeUnwrap() ?? "default";
258
+ * ```
259
+ *
260
+ * @see unwrapOr
261
+ */
262
+ safeUnwrap() {
263
+ if (this.isErr()) return null;
264
+ return this.#val === ERR_VAL ? null : this.#val;
265
+ }
266
+ /**
267
+ * Exhaustive pattern matching on Result state.
268
+ *
269
+ * Handles both Ok and Err branches with provided functions, ensuring all cases
270
+ * are covered. TypeScript enforces that both branches are specified.
271
+ *
272
+ * @param cases - Object containing Ok and Err handler functions
273
+ * @returns The result of calling the appropriate handler
274
+ *
275
+ * @example
276
+ * ```ts
277
+ * const message = ExperimentalResult.Ok(42).match({
278
+ * Ok: (val) => `Success: ${val}`,
279
+ * Err: (err) => `Failed: ${err}`,
280
+ * });
281
+ * // "Success: 42"
282
+ *
283
+ * // For side effects
284
+ * result.match({
285
+ * Ok: (data) => console.log("Got:", data),
286
+ * Err: (error) => console.error("Error:", error),
287
+ * });
288
+ * ```
289
+ */
290
+ match(cases) {
291
+ if (this.isErr()) return cases.Err(this.#err);
292
+ return cases.Ok(this.#val);
293
+ }
294
+ /**
295
+ * Pattern matches using positional arguments (FP convention alias for `match`).
296
+ *
297
+ * This is a more concise alternative to `match` using positional arguments
298
+ * instead of an object. Familiar to developers from Scala, Haskell, and other FP languages.
299
+ *
300
+ * @template U - The result type of both branches
301
+ * @param onOk - Handler called with the value if `Ok`
302
+ * @param onErr - Handler called with the error if `Err`
303
+ * @returns The result of calling the appropriate handler
304
+ *
305
+ * @example
306
+ * ```ts
307
+ * const result = ExperimentalResult.Ok(42).fold(
308
+ * (value) => `Success: ${value}`,
309
+ * (error) => `Failed: ${error}`
310
+ * );
311
+ * // "Success: 42"
312
+ *
313
+ * const errResult = ExperimentalResult.Err("network error").fold(
314
+ * (value) => `Success: ${value}`,
315
+ * (error) => `Failed: ${error}`
316
+ * );
317
+ * // "Failed: network error"
318
+ *
319
+ * // Equivalent to match:
320
+ * result.fold(onOk, onErr);
321
+ * result.match({ Ok: onOk, Err: onErr });
322
+ * ```
323
+ *
324
+ * @see {@link match} for object-based pattern matching
325
+ * @see {@link foldAsync} for async handlers
326
+ */
327
+ fold(onOk, onErr) {
328
+ if (this.isErr()) return onErr(this.#err);
329
+ return onOk(this.#val);
330
+ }
331
+ /**
332
+ * Async pattern matching using positional arguments.
333
+ *
334
+ * Async variant of `fold` for when handlers return Promises.
335
+ *
336
+ * @template U - The result type of both branches
337
+ * @param onOk - Async handler called with the value if `Ok`
338
+ * @param onErr - Async handler called with the error if `Err`
339
+ * @returns Promise resolving to the result of the appropriate handler
340
+ *
341
+ * @example
342
+ * ```ts
343
+ * const result = await ExperimentalResult.Ok(userId).foldAsync(
344
+ * async (id) => await fetchUserData(id),
345
+ * async (error) => await logAndGetFallback(error)
346
+ * );
347
+ *
348
+ * // Error recovery with logging
349
+ * const data = await apiResult.foldAsync(
350
+ * async (response) => await processResponse(response),
351
+ * async (error) => {
352
+ * await reportError(error);
353
+ * return getDefaultData();
354
+ * }
355
+ * );
356
+ * ```
357
+ *
358
+ * @see {@link fold} for synchronous handlers
359
+ * @see {@link matchAsync} for object-based async pattern matching
360
+ */
361
+ async foldAsync(onOk, onErr) {
362
+ if (this.isErr()) return onErr(this.#err);
363
+ return onOk(this.#val);
364
+ }
365
+ /**
366
+ * Async pattern matching on both states of the Result.
367
+ *
368
+ * Async variant of `match` for when handlers return Promises.
369
+ *
370
+ * @template U - The result type of both branches
371
+ * @param cases - Object containing async handlers for both states
372
+ * @returns Promise resolving to the result of the appropriate handler
373
+ *
374
+ * @example
375
+ * ```ts
376
+ * const result = await apiResult.matchAsync({
377
+ * Ok: async (data) => await processData(data),
378
+ * Err: async (error) => await handleError(error)
379
+ * });
380
+ *
381
+ * // With database operations
382
+ * const user = await findUserResult.matchAsync({
383
+ * Ok: async (user) => await enrichUserData(user),
384
+ * Err: async (error) => {
385
+ * await logError(error);
386
+ * return createGuestUser();
387
+ * }
388
+ * });
389
+ * ```
390
+ *
391
+ * @see {@link match} for synchronous pattern matching
392
+ * @see {@link foldAsync} for positional-argument async matching
393
+ */
394
+ async matchAsync(cases) {
395
+ if (this.isErr()) return cases.Err(this.#err);
396
+ return cases.Ok(this.#val);
397
+ }
398
+ /**
399
+ * Pattern matches with a subset of cases, using a default for unhandled cases.
400
+ *
401
+ * Unlike `match` which requires all cases, `matchPartial` allows handling
402
+ * only specific cases with a fallback default value or function.
403
+ *
404
+ * @template U - The result type
405
+ * @param cases - Partial object with optional `Ok` and `Err` handlers
406
+ * @param getDefault - Lazy default function for unhandled cases
407
+ * @returns The result of the matching handler or the default
408
+ *
409
+ * @example
410
+ * ```ts
411
+ * // Only handle Ok, default for Err
412
+ * ExperimentalResult.Ok(42).matchPartial({ Ok: (v) => v * 2 }, () => 0); // 84
413
+ * ExperimentalResult.Err("fail").matchPartial({ Ok: (v) => v * 2 }, () => 0); // 0
414
+ *
415
+ * // Only handle Err for logging
416
+ * result.matchPartial({ Err: (e) => { logError(e); return null; } }, () => null);
417
+ *
418
+ * // Lazy default with function
419
+ * result.matchPartial(
420
+ * { Ok: (v) => process(v) },
421
+ * () => computeExpensiveDefault()
422
+ * );
423
+ * ```
424
+ *
425
+ * @see {@link match} for exhaustive pattern matching
426
+ */
427
+ matchPartial(cases, getDefault) {
428
+ if (this.isErr()) return cases.Err ? cases.Err(this.#err) : getDefault();
429
+ return cases.Ok ? cases.Ok(this.#val) : getDefault();
430
+ }
431
+ map(fn) {
432
+ if (this.isErr()) return ExperimentalResult.Err(this.#err);
433
+ const curr = this.#val;
434
+ return ExperimentalResult.Ok(fn(curr));
435
+ }
436
+ /**
437
+ * Transforms the success value using an async function.
438
+ *
439
+ * Same as `map` but for async mappers. Returns `Promise<Result<U, E>>`.
440
+ *
441
+ * @param fn - Async function to transform the success value
442
+ * @returns Promise resolving to Result<U, E> with transformed value or propagated error
443
+ *
444
+ * @example
445
+ * ```ts
446
+ * await ExperimentalResult.Ok(42).mapAsync(async (x) => x * 2); // Promise<Ok(84)>
447
+ * await ExperimentalResult.Err("fail").mapAsync(async (x) => x * 2); // Promise<Err("fail")>
448
+ * ```
449
+ *
450
+ * @see map
451
+ */
452
+ async mapAsync(fn) {
453
+ if (this.isErr()) return Promise.resolve(ExperimentalResult.Err(this.#err));
454
+ const curr = this.#val;
455
+ return fn(curr).then((u) => ExperimentalResult.Ok(u)).catch((e) => ExperimentalResult.Err(e));
456
+ }
457
+ /**
458
+ * Chains operations that return Results, flattening nested Results.
459
+ *
460
+ * If the Result is Ok, applies the function (which returns a new Result) and
461
+ * returns that Result directly. If Err, propagates the error unchanged.
462
+ *
463
+ * Error types are unified: `Result<U, E | E2>`.
464
+ *
465
+ * For async operations, use `flatMapAsync` instead.
466
+ *
467
+ * @param fn - Function that returns a Result
468
+ * @returns Result<U, E | E2> from the function or propagated error
469
+ *
470
+ * @example
471
+ * ```ts
472
+ * // Success chain
473
+ * ExperimentalResult.Ok(42)
474
+ * .flatMap((x) => ExperimentalResult.Ok(x + 1)) // Ok(43)
475
+ * .flatMap((x) => ExperimentalResult.Err("too big")); // Err("too big")
476
+ *
477
+ * // Error propagation
478
+ * ExperimentalResult.Err("initial").flatMap((x) => ExperimentalResult.Ok(x + 1)); // Err("initial")
479
+ * ```
480
+ *
481
+ * @see flatMapAsync
482
+ * @see map
483
+ * @see flatZip
484
+ */
485
+ flatMap(fn) {
486
+ if (this.isErr()) return ExperimentalResult.Err(this.#err);
487
+ return fn(this.#val);
488
+ }
489
+ /**
490
+ * Chains async operations that return Results.
491
+ *
492
+ * Same as `flatMap` but for async Result-returning functions.
493
+ * Returns `Promise<Result<U, E | E2>>`.
494
+ *
495
+ * @param fn - Async function that returns a Promise resolving to Result
496
+ * @returns Promise resolving to Result<U, E | E2>
497
+ *
498
+ * @example
499
+ * ```ts
500
+ * const fetchUser = (id: number): Promise<Result<User, string>> =>
501
+ * Promise.resolve(ExperimentalResult.Ok({ id, name: "Alice" }));
502
+ *
503
+ * await ExperimentalResult.Ok(42)
504
+ * .flatMapAsync(fetchUser)
505
+ * .then((r) => r.map((user) => user.name));
506
+ * // Promise<Ok("Alice")>
507
+ * ```
508
+ *
509
+ * @see flatMap
510
+ */
511
+ async flatMapAsync(fn) {
512
+ if (this.isErr()) return ExperimentalResult.Err(this.#err);
513
+ return fn(this.#val).then((r) => r.isErr() ? ExperimentalResult.Err(r.#err) : r).catch((e) => ExperimentalResult.Err(e));
514
+ }
515
+ zip(fn) {
516
+ if (this.isErr()) return ExperimentalResult.Err(this.#err);
517
+ const curr = this.#val;
518
+ return ExperimentalResult.Ok([curr, fn(curr)]);
519
+ }
520
+ /**
521
+ * Pairs the original value with a derived async value.
522
+ *
523
+ * Same as `zip` but for async derivation functions.
524
+ * Returns `Promise<Result<[T, U], E>>`.
525
+ *
526
+ * @param fn - Async function to derive a value from the original
527
+ * @returns Promise resolving to Result<[T, U], E>
528
+ *
529
+ * @example
530
+ * ```ts
531
+ * await ExperimentalResult.Ok(42).zipAsync(async (x) => x * 10); // Promise<Ok([42, 420])>
532
+ * ```
533
+ *
534
+ * @see zip
535
+ */
536
+ async zipAsync(fn) {
537
+ if (this.isErr()) return ExperimentalResult.Err(this.#err);
538
+ const curr = this.#val;
539
+ return fn(curr).then((u) => ExperimentalResult.Ok([curr, u]));
540
+ }
541
+ /**
542
+ * Combines the current Result with another independent Result in a tuple.
543
+ *
544
+ * Unlike `zip` which derives a value from the original, `flatZip` works with
545
+ * two independent Results. If either is Err, propagates the first error.
546
+ *
547
+ * For async Results, use `flatZipAsync` instead.
548
+ *
549
+ * @param fn - Function that receives the value and returns another Result
550
+ * @returns Result<[T, U], E | E2> containing tuple of both values, or error
551
+ *
552
+ * @example
553
+ * ```ts
554
+ * ExperimentalResult.Ok(42)
555
+ * .flatZip((x) => ExperimentalResult.Ok(x + 5)) // Ok([42, 47])
556
+ * .flatZip(([a, b]) => ExperimentalResult.Err("x")); // Err("x")
557
+ *
558
+ * ExperimentalResult.Ok(42).flatZip((x) => ExperimentalResult.Err("fail")); // Err("fail")
559
+ * ExperimentalResult.Err("init").flatZip((x) => ExperimentalResult.Ok(5)); // Err("init")
560
+ * ```
561
+ *
562
+ * @see flatZipAsync
563
+ * @see zip
564
+ * @see flatMap
565
+ */
566
+ flatZip(fn) {
567
+ if (this.isErr()) return ExperimentalResult.Err(this.#err);
568
+ const curr = this.#val;
569
+ const r = fn(curr);
570
+ if (r.isErr()) return ExperimentalResult.Err(r.unwrapErr());
571
+ return ExperimentalResult.Ok([curr, r.unwrap()]);
572
+ }
573
+ /**
574
+ * Combines the current Result with another independent async Result in a tuple.
575
+ *
576
+ * Same as `flatZip` but for async Result-returning functions.
577
+ * Returns `Promise<Result<[T, U], E | E2>>`.
578
+ *
579
+ * @param fn - Async function that receives the value and returns a Promise resolving to Result
580
+ * @returns Promise resolving to Result<[T, U], E | E2>
581
+ *
582
+ * @example
583
+ * ```ts
584
+ * const fetchData = (id: number): Promise<Result<Data, string>> =>
585
+ * Promise.resolve(ExperimentalResult.Ok({ id, value: 100 }));
586
+ *
587
+ * await ExperimentalResult.Ok(42).flatZipAsync(fetchData); // Promise<Ok([42, {id: 42, value: 100}])>
588
+ * ```
589
+ *
590
+ * @see flatZip
591
+ */
592
+ async flatZipAsync(fn) {
593
+ if (this.isErr()) return ExperimentalResult.Err(this.#err);
594
+ const curr = this.#val;
595
+ return fn(curr).then((r) => {
596
+ if (r.isErr()) return ExperimentalResult.Err(r.unwrapErr());
597
+ return ExperimentalResult.Ok([curr, r.unwrap()]);
598
+ });
599
+ }
600
+ mapErr(fn) {
601
+ if (this.isErr()) return ExperimentalResult.Err(fn(this.#err));
602
+ return ExperimentalResult.Ok(this.#val);
603
+ }
604
+ /**
605
+ * Transforms the error value using an async function.
606
+ *
607
+ * Same as `mapErr` but for async error transformations.
608
+ * Returns `Promise<Result<T, E2>>`.
609
+ *
610
+ * @param fn - Async function to transform the error
611
+ * @returns Promise resolving to Result<T, E2> with transformed error or original Ok
612
+ *
613
+ * @example
614
+ * ```ts
615
+ * await ExperimentalResult.Err("timeout").mapErrAsync(async (e) => await formatError(e));
616
+ * // Promise<Err("Timeout occurred: timeout")>
617
+ * ```
618
+ *
619
+ * @see mapErr
620
+ */
621
+ async mapErrAsync(fn) {
622
+ if (this.isErr()) return fn(this.#err).then((e) => ExperimentalResult.Err(e));
623
+ return ExperimentalResult.Ok(this.#val);
624
+ }
625
+ mapBoth(fnOk, fnErr) {
626
+ if (this.isErr()) return ExperimentalResult.Err(fnErr(this.#err));
627
+ return ExperimentalResult.Ok(fnOk(this.#val));
628
+ }
629
+ /**
630
+ * Transforms both the success value and error value using async functions.
631
+ *
632
+ * Same as `mapBoth` but for async transformations.
633
+ * Returns `Promise<Result<T2, E2>>`.
634
+ *
635
+ * @param fnOk - Async function to transform the success value
636
+ * @param fnErr - Async function to transform the error
637
+ * @returns Promise resolving to Result<T2, E2> with transformed value or error
638
+ *
639
+ * @example
640
+ * ```ts
641
+ * await ExperimentalResult.Ok(42).mapBothAsync(
642
+ * async (val) => await formatSuccess(val),
643
+ * async (err) => await formatError(err)
644
+ * );
645
+ * // Promise<Ok("Success: 42")>
646
+ * ```
647
+ *
648
+ * @see mapBoth
649
+ */
650
+ async mapBothAsync(fnOk, fnErr) {
651
+ if (this.isErr()) return fnErr(this.#err).then((e) => ExperimentalResult.Err(e));
652
+ return fnOk(this.#val).then((v) => ExperimentalResult.Ok(v));
653
+ }
654
+ /**
655
+ * Recovers from an error by providing a fallback Result.
656
+ *
657
+ * If the Result is Ok, returns it unchanged. If Err, calls the function
658
+ * with the error to produce a new Result.
659
+ *
660
+ * For async recovery, use `orElseAsync` instead.
661
+ *
662
+ * @param fn - Function that receives the error and returns a fallback Result
663
+ * @returns Result<T, E2> - original Ok or fallback Result from fn
664
+ *
665
+ * @example
666
+ * ```ts
667
+ * // Recovery with fallback
668
+ * fetchFromPrimary()
669
+ * .orElse((e) => fetchFromBackup())
670
+ * .orElse((e) => ExperimentalResult.Ok(defaultValue));
671
+ *
672
+ * // Ok passes through unchanged
673
+ * ExperimentalResult.Ok(42).orElse((e) => ExperimentalResult.Ok(0)); // Ok(42)
674
+ *
675
+ * // Err triggers recovery
676
+ * ExperimentalResult.Err("not found").orElse((e) => ExperimentalResult.Ok(0)); // Ok(0)
677
+ * ExperimentalResult.Err("fail").orElse((e) => ExperimentalResult.Err("critical")); // Err("critical")
678
+ * ```
679
+ *
680
+ * @see orElseAsync
681
+ */
682
+ orElse(fn) {
683
+ if (this.isOk()) return this;
684
+ return fn(this.#err);
685
+ }
686
+ /**
687
+ * Recovers from an error by providing a fallback async Result.
688
+ *
689
+ * Same as `orElse` but for async Result-returning functions.
690
+ * Returns `Promise<Result<T, E2>>`.
691
+ *
692
+ * @param fn - Async function that receives the error and returns a Promise resolving to fallback Result
693
+ * @returns Promise resolving to Result<T, E2> - original Ok or fallback Result from fn
694
+ *
695
+ * @example
696
+ * ```ts
697
+ * await fetchData().orElseAsync(async (e) => {
698
+ * return await fetchBackupData();
699
+ * });
700
+ * ```
701
+ *
702
+ * @see orElse
703
+ */
704
+ async orElseAsync(fn) {
705
+ if (this.isOk()) return this;
706
+ return fn(this.#err);
707
+ }
708
+ validate(validators) {
709
+ if (this.isErr()) return this;
710
+ const baseVal = this.#val;
711
+ const results = validators.map((v) => v(baseVal));
712
+ if (results.some((r) => require_utils.isPromiseLike(r))) return Promise.all(results).then((resolved) => {
713
+ const errs = [];
714
+ for (const r of resolved) if (r.isErr()) errs.push(r.unwrapErr());
715
+ if (errs.length > 0) return ExperimentalResult.Err(errs);
716
+ return this;
717
+ });
718
+ const syncResults = results;
719
+ const errs = [];
720
+ for (const r of syncResults) if (r.isErr()) errs.push(r.#err);
721
+ if (errs.length > 0) return ExperimentalResult.Err(errs);
722
+ return this;
723
+ }
724
+ /**
725
+ * Runs async validators on the Ok value, collecting ALL errors.
726
+ *
727
+ * Explicit async variant of `validate` for when all validators are async.
728
+ * Always returns `Promise<Result<T, E | VE[]>>`.
729
+ *
730
+ * @param validators - Array of async validator functions
731
+ * @returns Promise resolving to Result<T, E | VE[]> with original value or array of all errors
732
+ *
733
+ * @example
734
+ * ```ts
735
+ * // Form validation with async checks
736
+ * const validated = await ExperimentalResult.Ok(formData).validateAsync([
737
+ * async (d) => await checkEmailUnique(d.email),
738
+ * async (d) => await checkUsernameAvailable(d.username),
739
+ * ]);
740
+ *
741
+ * // Password validation against database
742
+ * await ExperimentalResult.Ok("password123!").validateAsync([
743
+ * async (pw) => await checkNotPreviousPassword(pw),
744
+ * async (pw) => await checkNotCommonPassword(pw),
745
+ * ]);
746
+ * ```
747
+ *
748
+ * @see validate
749
+ */
750
+ async validateAsync(validators) {
751
+ if (this.isErr()) return this;
752
+ const baseVal = this.#val;
753
+ return Promise.all(validators.map((v) => v(baseVal))).then((resolved) => {
754
+ const errs = [];
755
+ for (const r of resolved) if (r.isErr()) errs.push(r.#err);
756
+ if (errs.length > 0) return ExperimentalResult.Err(errs);
757
+ return this;
758
+ });
759
+ }
760
+ /**
761
+ * Combines multiple Results, collecting all values or all errors.
762
+ *
763
+ * Unlike typical Result behavior which short-circuits on first error,
764
+ * `all` collects ALL errors from all Results. This is useful when you
765
+ * want to show complete validation feedback.
766
+ *
767
+ * - All Ok → `Ok([...values])` with preserved tuple types
768
+ * - Any Err → `Err([...errors])` collecting ALL errors
769
+ *
770
+ * @param results - Variable number of Results to combine
771
+ * @returns Result with tuple of all values, or array of all errors
772
+ *
773
+ * @example
774
+ * ```ts
775
+ * ExperimentalResult.all(ExperimentalResult.Ok(1), ExperimentalResult.Ok(2), ExperimentalResult.Ok(3)); // Ok([1, 2, 3])
776
+ * ExperimentalResult.all(ExperimentalResult.Ok(1), ExperimentalResult.Err("a"), ExperimentalResult.Err("b")); // Err(["a", "b"])
777
+ * ExperimentalResult.all(); // Ok([])
778
+ *
779
+ * // Real-world: Parallel validation
780
+ * const [user, posts, likes] = await Promise.all([
781
+ * fetchUser(id),
782
+ * fetchPosts(id),
783
+ * fetchLikes(id),
784
+ * ]);
785
+ *
786
+ * const combined = ExperimentalResult.all(user, posts, likes);
787
+ * // Ok([User, Post[], Like[]]) or Err([...errors])
788
+ * ```
789
+ *
790
+ * @see any
791
+ * @see validate
792
+ */
793
+ static all(...results) {
794
+ const vals = [];
795
+ const errs = [];
796
+ for (const r of results) if (r.isErr()) errs.push(r.unwrapErr());
797
+ else vals.push(r.unwrap());
798
+ if (errs.length > 0) return ExperimentalResult.Err(errs);
799
+ return ExperimentalResult.Ok(vals);
800
+ }
801
+ /**
802
+ * Returns the first Ok, or collects all errors if all are Err.
803
+ *
804
+ * Useful for fallback chains where you want the first success, but want
805
+ * to collect all errors if everything fails.
806
+ *
807
+ * - First Ok → Returns that Ok immediately
808
+ * - All Err → `Err([...all errors])`
809
+ *
810
+ * @param results - Variable number of Results to check
811
+ * @returns First Ok found, or Err with array of all errors
812
+ *
813
+ * @example
814
+ * ```ts
815
+ * ExperimentalResult.any(
816
+ * ExperimentalResult.Err("Error 1"),
817
+ * ExperimentalResult.Ok("First success"),
818
+ * ExperimentalResult.Ok("Second success"),
819
+ * ); // Ok("First success")
820
+ *
821
+ * ExperimentalResult.any(
822
+ * ExperimentalResult.Err("Error 1"),
823
+ * ExperimentalResult.Err("Error 2"),
824
+ * ExperimentalResult.Err("Error 3"),
825
+ * ); // Err(["Error 1", "Error 2", "Error 3"])
826
+ *
827
+ * // Fallback chain
828
+ * ExperimentalResult.any(
829
+ * fetchFromCache(key),
830
+ * fetchFromDb(key),
831
+ * fetchFromRemote(key),
832
+ * );
833
+ * ```
834
+ *
835
+ * @see all
836
+ */
837
+ static any(...results) {
838
+ for (const r of results) if (r.isOk()) return r;
839
+ return ExperimentalResult.Err(results.map((r) => r.unwrapErr()));
840
+ }
841
+ tap(fn) {
842
+ if (this.isOk()) fn(this.#val);
843
+ return this;
844
+ }
845
+ /**
846
+ * Executes an async side effect function for Ok values, then returns self.
847
+ *
848
+ * Same as `tap` but for async side effect functions.
849
+ * Returns `Promise<Result<T, E>>`.
850
+ *
851
+ * @param fn - Async function to execute with the Ok value
852
+ * @returns Promise resolving to the same Result (chainable)
853
+ *
854
+ * @example
855
+ * ```ts
856
+ * await ExperimentalResult.Ok(user)
857
+ * .tapAsync(async (u) => await logAuditTrail(u))
858
+ * .map((u) => u.id);
859
+ * ```
860
+ *
861
+ * @see tap
862
+ */
863
+ async tapAsync(fn) {
864
+ if (this.isOk()) await fn(this.#val);
865
+ return this;
866
+ }
867
+ /**
868
+ * Executes a side effect function for Err values, then returns self.
869
+ *
870
+ * Useful for logging errors or executing cleanup without breaking the chain.
871
+ * The function is only called if the Result is Err.
872
+ *
873
+ * For async side effects, use `tapErrAsync` instead.
874
+ *
875
+ * @param fn - Function to execute with the error
876
+ * @returns The same Result (chainable)
877
+ *
878
+ * @example
879
+ * ```ts
880
+ * ExperimentalResult.Err("Connection failed")
881
+ * .tapErr((err) => console.error(`[Error Log] ${new Date().toISOString()}: ${err}`))
882
+ * .orElse((e) => ExperimentalResult.Ok(defaultValue));
883
+ * // Logs error timestamp
884
+ * // Returns: Ok(defaultValue)
885
+ *
886
+ * // Ok - tapErr does nothing
887
+ * ExperimentalResult.Ok(42).tapErr((e) => console.log(e)); // Ok(42)
888
+ * ```
889
+ *
890
+ * @see tapErrAsync
891
+ * @see tap
892
+ */
893
+ tapErr(fn) {
894
+ if (this.isErr()) fn(this.#err);
895
+ return this;
896
+ }
897
+ /**
898
+ * Executes an async side effect function for Err values, then returns self.
899
+ *
900
+ * Same as `tapErr` but for async side effect functions.
901
+ * Returns `Promise<Result<T, E>>`.
902
+ *
903
+ * @param fn - Async function to execute with the error
904
+ * @returns Promise resolving to the same Result (chainable)
905
+ *
906
+ * @example
907
+ * ```ts
908
+ * await ExperimentalResult.Err("API error")
909
+ * .tapErrAsync(async (e) => await reportToSentry(e))
910
+ * .orElse((e) => ExperimentalResult.Ok(backupData));
911
+ * ```
912
+ *
913
+ * @see tapErr
914
+ */
915
+ async tapErrAsync(fn) {
916
+ if (this.isErr()) await fn(this.#err);
917
+ return this;
918
+ }
919
+ /**
920
+ * Swaps the Ok and Err states, turning success into failure and vice versa.
921
+ *
922
+ * Useful for inverting the meaning of a Result, such as converting
923
+ * validation errors to successes and valid values to errors.
924
+ *
925
+ * @returns Result<E, T> with swapped states
926
+ *
927
+ * @example
928
+ * ```ts
929
+ * ExperimentalResult.Ok("Success value").flip(); // Err("Success value")
930
+ * ExperimentalResult.Err("Error value").flip(); // Ok("Error value")
931
+ *
932
+ * // Invert validation (fail if value is in blacklist)
933
+ * const blacklist = ["admin", "root"];
934
+ * const isBlacklisted = (name: string) =>
935
+ * ExperimentalResult.fromPredicate(name, (n) => !blacklist.includes(n), "blacklisted")
936
+ * .flip(); // Ok if blacklisted, Err if not
937
+ * ```
938
+ */
939
+ flip() {
940
+ if (this.isErr()) return ExperimentalResult.Ok(this.#err);
941
+ return ExperimentalResult.Err(this.#val);
942
+ }
943
+ /**
944
+ * Converts Result to Option, discarding error information.
945
+ *
946
+ * - Ok(value) → Some(value)
947
+ * - Err(error) → None
948
+ *
949
+ * Use when you only care about presence/absence of a value, not the error.
950
+ *
951
+ * @returns Option<T> - Some if Ok, None if Err
952
+ *
953
+ * @example
954
+ * ```ts
955
+ * ExperimentalResult.Ok(42).toOption(); // Some(42)
956
+ * ExperimentalResult.Err("fail").toOption(); // None
957
+ *
958
+ * // Safe user lookup
959
+ * const userOpt = fetchUser(id).toOption();
960
+ * // User or None, regardless of why fetch failed
961
+ * ```
962
+ *
963
+ * @see Option.toResult
964
+ */
965
+ toOption() {
966
+ if (this.isErr()) return require_option_experimental.ExperimentalOption.None;
967
+ return require_option_experimental.ExperimentalOption.Some(this.#val);
968
+ }
969
+ /**
970
+ * Maps over array elements inside a Result<Array<T>, E>.
971
+ *
972
+ * Applies the mapper function to each element if the Result is Ok and
973
+ * contains an array. Propagates Err unchanged.
974
+ *
975
+ * @param mapper - Function to map over each array element
976
+ * @returns Result<Array<Out>, E> with mapped array or propagated error
977
+ * @throws Error if the Result is Ok but value is not an array
978
+ *
979
+ * @example
980
+ * ```ts
981
+ * ExperimentalResult.Ok([1, 2, 3]).innerMap((x) => x * 2); // Ok([2, 4, 6])
982
+ * ExperimentalResult.Err("fail").innerMap((x) => x * 2); // Err("fail")
983
+ * ```
984
+ */
985
+ innerMap(mapper) {
986
+ if (this.isErr()) return this;
987
+ if (Array.isArray(this.#val)) return new ExperimentalResult(this.#val.map(mapper), this.#err, "Ok");
988
+ throw new Error("Can only be called for Result<Array<T>, E>");
989
+ }
990
+ /**
991
+ * Makes Result iterable for use with generator-based syntax.
992
+ * Yields self and returns the unwrapped value when resumed.
993
+ *
994
+ * @example
995
+ * ```ts
996
+ * const result = ExperimentalResult.gen(function* () {
997
+ * const value = yield* ExperimentalResult.Ok(42);
998
+ * return value * 2;
999
+ * });
1000
+ * ```
1001
+ */
1002
+ *[Symbol.iterator]() {
1003
+ const trace = (/* @__PURE__ */ new Error()).stack;
1004
+ return yield new require_utils.CapturedTrace(this, trace);
1005
+ }
1006
+ /**
1007
+ * Makes Result iterable for use with async generator-based syntax.
1008
+ * Yields self and returns the unwrapped value when resumed.
1009
+ *
1010
+ * @example
1011
+ * ```ts
1012
+ * const result = await ExperimentalResult.asyncGen(async function* () {
1013
+ * const value = yield* ExperimentalResult.Ok(42);
1014
+ * return value * 2;
1015
+ * });
1016
+ * ```
1017
+ */
1018
+ async *[Symbol.asyncIterator]() {
1019
+ const trace = (/* @__PURE__ */ new Error()).stack;
1020
+ return yield new require_utils.CapturedTrace(this, trace);
1021
+ }
1022
+ /**
1023
+ * Creates an ExperimentalResult from a nullable value.
1024
+ * Returns Err(error) for null/undefined, otherwise Ok(non-null value).
1025
+ */
1026
+ static fromNullable(val, error) {
1027
+ return val === null || val === void 0 ? ExperimentalResult.Err(error) : ExperimentalResult.Ok(val);
1028
+ }
1029
+ /** Create Result based on predicate result */
1030
+ static fromPredicate(val, pred, error) {
1031
+ return pred(val) ? ExperimentalResult.Ok(val) : ExperimentalResult.Err(error);
1032
+ }
1033
+ /** Catches sync exceptions */
1034
+ static tryCatch(fn, errorMapper) {
1035
+ try {
1036
+ return ExperimentalResult.Ok(fn());
1037
+ } catch (e) {
1038
+ return ExperimentalResult.Err(errorMapper ? errorMapper(e) : e);
1039
+ }
1040
+ }
1041
+ /** Catches async exceptions - returns Promise<Result<T, E>> */
1042
+ static async tryAsyncCatch(fn, errorMapper) {
1043
+ try {
1044
+ return ExperimentalResult.Ok(await fn());
1045
+ } catch (e) {
1046
+ return ExperimentalResult.Err(errorMapper ? errorMapper(e) : e);
1047
+ }
1048
+ }
1049
+ /**
1050
+ * Generator-based syntax for chaining Result operations (simplified, no adapter).
1051
+ * Provides imperative-style code while maintaining functional error handling.
1052
+ *
1053
+ * Short-circuits on first Err, returning that error. Uses iteration instead of
1054
+ * recursion to avoid stack overflow on deep chains.
1055
+ *
1056
+ * @example
1057
+ * ```ts
1058
+ * const result = ExperimentalResult.gen(function* () {
1059
+ * const a = yield* ExperimentalResult.Ok(1);
1060
+ * const b = yield* ExperimentalResult.Ok(2);
1061
+ * return a + b;
1062
+ * });
1063
+ * // Result<number, never>
1064
+ * ```
1065
+ */
1066
+ static gen(genFn) {
1067
+ const iterator = genFn();
1068
+ let nextArg;
1069
+ let currentResult;
1070
+ while (true) {
1071
+ const next = iterator.next(nextArg);
1072
+ if (next.done) {
1073
+ currentResult = ExperimentalResult.Ok(next.value);
1074
+ break;
1075
+ }
1076
+ let yielded = next.value;
1077
+ let stack;
1078
+ if (require_utils.isCapturedTrace(yielded)) {
1079
+ stack = yielded.stack;
1080
+ yielded = yielded.value;
1081
+ }
1082
+ if (yielded.isErr()) {
1083
+ const err = yielded.unwrapErr();
1084
+ if (stack && err instanceof Error) {
1085
+ const stackLines = stack.split("\n");
1086
+ if (stackLines.length > 2) {
1087
+ const userStack = stackLines.slice(2).join("\n");
1088
+ err.stack = `${err.name}: ${err.message}\n${userStack}`;
1089
+ }
1090
+ }
1091
+ iterator.return?.(void 0);
1092
+ currentResult = yielded;
1093
+ break;
1094
+ }
1095
+ nextArg = yielded.unwrap();
1096
+ }
1097
+ return currentResult;
1098
+ }
1099
+ /**
1100
+ * Generator-based syntax for chaining Result operations (with adapter).
1101
+ * Uses an adapter function ($) for improved type inference.
1102
+ *
1103
+ * Short-circuits on first Err, returning that error. Uses iteration instead of
1104
+ * recursion to avoid stack overflow on deep chains.
1105
+ *
1106
+ * @example
1107
+ * ```ts
1108
+ * const result = ExperimentalResult.genAdapter(function* ($) {
1109
+ * const a = yield* $(ExperimentalResult.Ok(1));
1110
+ * const b = yield* $(ExperimentalResult.Ok(2));
1111
+ * return a + b;
1112
+ * });
1113
+ * // Result<number, never>
1114
+ * ```
1115
+ */
1116
+ static genAdapter(genFn) {
1117
+ const adapter = (result) => new ResultYieldWrap(result);
1118
+ const iterator = genFn(adapter);
1119
+ let nextArg;
1120
+ let currentResult;
1121
+ while (true) {
1122
+ const next = iterator.next(nextArg);
1123
+ if (next.done) {
1124
+ currentResult = ExperimentalResult.Ok(next.value);
1125
+ break;
1126
+ }
1127
+ const wrapped = next.value;
1128
+ let result = wrapped.result;
1129
+ let stack;
1130
+ if (require_utils.isCapturedTrace(wrapped)) {
1131
+ stack = wrapped.stack;
1132
+ result = wrapped.value.result;
1133
+ }
1134
+ if (result.isErr()) {
1135
+ const err = result.unwrapErr();
1136
+ if (stack && err instanceof Error) {
1137
+ const stackLines = stack.split("\n");
1138
+ if (stackLines.length > 2) {
1139
+ const userStack = stackLines.slice(2).join("\n");
1140
+ err.stack = `${err.name}: ${err.message}\n${userStack}`;
1141
+ }
1142
+ }
1143
+ iterator.return?.(void 0);
1144
+ currentResult = result;
1145
+ break;
1146
+ }
1147
+ nextArg = result.unwrap();
1148
+ }
1149
+ return currentResult;
1150
+ }
1151
+ /**
1152
+ * Async generator-based syntax for chaining Result operations (simplified, no adapter).
1153
+ * Use yield* with Result values directly. For Promise<Result<T, E>>, await first then yield*.
1154
+ *
1155
+ * Short-circuits on first Err, returning that error. Uses async iteration instead of
1156
+ * recursion to avoid stack overflow on deep chains.
1157
+ *
1158
+ * @example
1159
+ * ```ts
1160
+ * const fetchData = async (
1161
+ * id: number,
1162
+ * ): Promise<ExperimentalResult<{ id: number }, string>> =>
1163
+ * ExperimentalResult.Ok({ id });
1164
+ * const result = await ExperimentalResult.asyncGen(async function* () {
1165
+ * const a = yield* ExperimentalResult.Ok(1);
1166
+ * const dataResult = yield* (await fetchData(a));
1167
+ * return a + dataResult.id;
1168
+ * });
1169
+ * // ExperimentalResult<number, string>
1170
+ * ```
1171
+ */
1172
+ static async asyncGen(genFn) {
1173
+ const iterator = genFn();
1174
+ let nextArg;
1175
+ let currentResult;
1176
+ while (true) {
1177
+ const next = await iterator.next(nextArg);
1178
+ if (next.done) {
1179
+ currentResult = ExperimentalResult.Ok(next.value);
1180
+ break;
1181
+ }
1182
+ let result = next.value;
1183
+ let stack;
1184
+ if (require_utils.isCapturedTrace(result)) {
1185
+ stack = result.stack;
1186
+ result = result.value;
1187
+ }
1188
+ if (result.isErr()) {
1189
+ const err = result.unwrapErr();
1190
+ if (stack && err instanceof Error) {
1191
+ const stackLines = stack.split("\n");
1192
+ if (stackLines.length > 2) {
1193
+ const userStack = stackLines.slice(2).join("\n");
1194
+ err.stack = `${err.name}: ${err.message}\n${userStack}`;
1195
+ }
1196
+ }
1197
+ await iterator.return?.(void 0);
1198
+ currentResult = result;
1199
+ break;
1200
+ }
1201
+ nextArg = result.unwrap();
1202
+ }
1203
+ return currentResult;
1204
+ }
1205
+ /**
1206
+ * Async generator-based syntax for chaining Result operations (with adapter).
1207
+ * Uses an adapter function ($) for improved type inference.
1208
+ * Supports both Result<T, E> and Promise<Result<T, E>> for flexibility.
1209
+ *
1210
+ * Short-circuits on first Err, returning that error. Uses async iteration instead of
1211
+ * recursion to avoid stack overflow on deep chains.
1212
+ *
1213
+ * @example
1214
+ * ```ts
1215
+ * const fetchData = async (
1216
+ * id: number,
1217
+ * ): Promise<ExperimentalResult<{ id: number }, string>> =>
1218
+ * ExperimentalResult.Ok({ id });
1219
+ * const result = await ExperimentalResult.asyncGenAdapter(async function* ($) {
1220
+ * const a = yield* $(ExperimentalResult.Ok(1));
1221
+ * const data = yield* $(fetchData(a));
1222
+ * return a + data.id;
1223
+ * });
1224
+ * // ExperimentalResult<number, string>
1225
+ * ```
1226
+ */
1227
+ static async asyncGenAdapter(genFn) {
1228
+ const adapter = (result) => new AsyncResultYieldWrap(Promise.resolve(result));
1229
+ const iterator = genFn(adapter);
1230
+ let nextArg;
1231
+ let currentResult;
1232
+ while (true) {
1233
+ const next = await iterator.next(nextArg);
1234
+ if (next.done) {
1235
+ currentResult = ExperimentalResult.Ok(next.value);
1236
+ break;
1237
+ }
1238
+ const wrapped = next.value;
1239
+ let result;
1240
+ let stack;
1241
+ if (require_utils.isCapturedTrace(wrapped)) {
1242
+ stack = wrapped.stack;
1243
+ result = await wrapped.value.result;
1244
+ } else result = await wrapped.result;
1245
+ if (result.isErr()) {
1246
+ const err = result.unwrapErr();
1247
+ if (stack && err instanceof Error) {
1248
+ const stackLines = stack.split("\n");
1249
+ if (stackLines.length > 2) {
1250
+ const userStack = stackLines.slice(2).join("\n");
1251
+ err.stack = `${err.name}: ${err.message}\n${userStack}`;
1252
+ }
1253
+ }
1254
+ await iterator.return?.(void 0);
1255
+ currentResult = result;
1256
+ break;
1257
+ }
1258
+ nextArg = result.unwrap();
1259
+ }
1260
+ return currentResult;
1261
+ }
1262
+ };
1263
+
1264
+ //#endregion
1265
+ exports.ExperimentalResult = ExperimentalResult;
1266
+ //# sourceMappingURL=result-experimental.cjs.map