@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,1503 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_unit = require('./unit.cjs');
3
+ const require_utils = require('./utils.cjs');
4
+ const require_result_experimental = require('./result-experimental.cjs');
5
+
6
+ //#region src/option-experimental.ts
7
+ /**
8
+ * Error thrown when attempting to unwrap a `None` value.
9
+ *
10
+ * This exception is thrown by {@link ExperimentalOption.unwrap} when called on a `None`.
11
+ * It represents a programmer error - you should only call `unwrap()` when
12
+ * you are certain the ExperimentalOption contains a value, or use safe alternatives
13
+ * like {@link ExperimentalOption.unwrapOr} or {@link ExperimentalOption.safeUnwrap}.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * try {
18
+ * ExperimentalOption.None.unwrap();
19
+ * } catch (e) {
20
+ * e instanceof UnwrappedNone // true
21
+ * e.name // "UnwrapError"
22
+ * }
23
+ * ```
24
+ */
25
+ var UnwrappedNone = class extends Error {
26
+ name = "UnwrapError";
27
+ constructor() {
28
+ super("Attempted to unwrap ExperimentalOption::None");
29
+ }
30
+ };
31
+ const UNWRAPPED_NONE_ERR = new UnwrappedNone();
32
+ const NONE_VAL = Symbol("ExperimentalOption::None");
33
+ /**
34
+ * Wrapper that makes ExperimentalOption yieldable with proper type tracking.
35
+ *
36
+ * @internal
37
+ */
38
+ var OptionYieldWrap = class {
39
+ constructor(option) {
40
+ this.option = option;
41
+ }
42
+ *[Symbol.iterator]() {
43
+ return yield this;
44
+ }
45
+ };
46
+ /**
47
+ * Wrapper that makes ExperimentalOption yieldable in async generators with proper type tracking.
48
+ *
49
+ * @internal
50
+ */
51
+ var AsyncOptionYieldWrap = class {
52
+ option;
53
+ constructor(option) {
54
+ this.option = require_utils.isPromiseLike(option) ? option : Promise.resolve(option);
55
+ }
56
+ async *[Symbol.asyncIterator]() {
57
+ return yield this;
58
+ }
59
+ };
60
+ /**
61
+ * A type-safe container for optional values.
62
+ *
63
+ * `ExperimentalOption<T>` represents a value that may or may not be present. It eliminates the
64
+ * need for `null` and `undefined` checks by making absence explicit through the
65
+ * type system.
66
+ *
67
+ * ## States
68
+ *
69
+ * - **Some\<T\>**: Contains a value of type `T`
70
+ * - **None**: Represents absence of a value (singleton)
71
+ *
72
+ * ## Basic Usage
73
+ *
74
+ * ```ts
75
+ * import { ExperimentalOption } from "@carbonteq/fp";
76
+ *
77
+ * // Creating ExperimentalOptions
78
+ * const some: ExperimentalOption<number> = ExperimentalOption.Some(42);
79
+ * const none: ExperimentalOption<number> = ExperimentalOption.None;
80
+ *
81
+ * // From nullable values
82
+ * const fromNull = ExperimentalOption.fromNullable(null); // None
83
+ * const fromValue = ExperimentalOption.fromNullable("hello"); // Some("hello")
84
+ *
85
+ * // Checking and extracting
86
+ * if (some.isSome()) {
87
+ * console.log(some.unwrap()); // 42
88
+ * }
89
+ *
90
+ * // Chaining operations
91
+ * const result = ExperimentalOption.Some(5)
92
+ * .map(x => x * 2)
93
+ * .flatMap(x => ExperimentalOption.Some(x + 1));
94
+ * // Some(11)
95
+ * ```
96
+ *
97
+ * ## Async Variants
98
+ *
99
+ * For operations that return Promises, use `*Async` methods:
100
+ *
101
+ * ```ts
102
+ * // Sync
103
+ * ExperimentalOption.Some(5).map(x => x * 2); // ExperimentalOption<number>
104
+ *
105
+ * // Async
106
+ * ExperimentalOption.Some(5).mapAsync(async x => x * 2); // Promise<ExperimentalOption<number>>
107
+ * ```
108
+ *
109
+ * @template T - The type of the contained value
110
+ *
111
+ * @see {@link https://carbonteq.github.io/ct-fp/option | ExperimentalOption Documentation}
112
+ */
113
+ var ExperimentalOption = class ExperimentalOption {
114
+ /** Discriminant tag for type-level identification */
115
+ _tag;
116
+ #val;
117
+ constructor(val, tag) {
118
+ this.#val = val;
119
+ this._tag = tag;
120
+ }
121
+ /**
122
+ * Singleton `None` instance representing absence of a value.
123
+ *
124
+ * This is a shared instance - all `None` values reference the same object.
125
+ *
126
+ * @example
127
+ * ```ts
128
+ * const none1 = ExperimentalOption.None;
129
+ * const none2 = ExperimentalOption.None;
130
+ * none1 === none2 // true
131
+ * ```
132
+ */
133
+ static None = new ExperimentalOption(NONE_VAL, "None");
134
+ /**
135
+ * Creates a `Some` variant containing the provided value.
136
+ *
137
+ * @template Inner - The type of value to wrap
138
+ * @param val - The value to wrap in a Some
139
+ * @returns An `ExperimentalOption<Inner>` in the Some state
140
+ *
141
+ * @example
142
+ * ```ts
143
+ * const opt = ExperimentalOption.Some(42); // ExperimentalOption<number>
144
+ * const str = ExperimentalOption.Some("hello"); // ExperimentalOption<string>
145
+ * const obj = ExperimentalOption.Some({ id: 1 }); // ExperimentalOption<{ id: number }>
146
+ * ```
147
+ */
148
+ static Some(val) {
149
+ return new ExperimentalOption(val, "Some");
150
+ }
151
+ /**
152
+ * Creates an `ExperimentalOption` from a nullable value, returning `None` for `null` or `undefined`.
153
+ *
154
+ * Unlike {@link fromFalsy}, this only treats `null` and `undefined` as absence.
155
+ * Values like `0`, `""`, and `false` are considered valid and wrapped in `Some`.
156
+ *
157
+ * @template T - The input type which may include null/undefined
158
+ * @param val - The value to convert to an ExperimentalOption
159
+ * @returns `Some<NonNullable<T>>` if value is non-nullish, else `None`
160
+ *
161
+ * @example
162
+ * ```ts
163
+ * ExperimentalOption.fromNullable("hello") // Some("hello")
164
+ * ExperimentalOption.fromNullable(null) // None
165
+ * ExperimentalOption.fromNullable(undefined) // None
166
+ * ExperimentalOption.fromNullable(0) // Some(0) - 0 is not nullish
167
+ * ExperimentalOption.fromNullable("") // Some("") - empty string is not nullish
168
+ * ExperimentalOption.fromNullable(false) // Some(false) - false is not nullish
169
+ *
170
+ * // With user input
171
+ * function findUser(id: string): User | null {
172
+ * return database.getUser(id) ?? null;
173
+ * }
174
+ * const user = ExperimentalOption.fromNullable(findUser("123"));
175
+ * // ExperimentalOption<User>
176
+ * ```
177
+ */
178
+ static fromNullable(val) {
179
+ return val === null || val === void 0 ? ExperimentalOption.None : ExperimentalOption.Some(val);
180
+ }
181
+ /**
182
+ * Creates an `ExperimentalOption` from a value that may be falsy, returning `None` for falsy values.
183
+ *
184
+ * Treats `false`, `0`, `""`, `null`, and `undefined` as absence.
185
+ * Use {@link fromNullable} if you only want to exclude `null`/`undefined`.
186
+ *
187
+ * @template T - The type of value to wrap
188
+ * @param val - The value to convert to an ExperimentalOption
189
+ * @returns `Some<T>` if value is truthy, else `None`
190
+ *
191
+ * @example
192
+ * ```ts
193
+ * ExperimentalOption.fromFalsy("hello") // Some("hello")
194
+ * ExperimentalOption.fromFalsy("") // None
195
+ * ExperimentalOption.fromFalsy(0) // None
196
+ * ExperimentalOption.fromFalsy(false) // None
197
+ * ExperimentalOption.fromFalsy(null) // None
198
+ * ExperimentalOption.fromFalsy(undefined) // None
199
+ *
200
+ * // Useful for validation
201
+ * const isValid = ExperimentalOption.fromFalsy(getConfigValue("API_KEY"));
202
+ * ```
203
+ */
204
+ static fromFalsy(val) {
205
+ return val ? ExperimentalOption.Some(val) : ExperimentalOption.None;
206
+ }
207
+ /**
208
+ * Creates an `ExperimentalOption` based on a predicate function result.
209
+ *
210
+ * Returns `Some` if the predicate returns `true`, otherwise `None`.
211
+ *
212
+ * @template T - The type of value to test
213
+ * @param val - The value to test
214
+ * @param pred - A predicate function that returns true if value should be wrapped
215
+ * @returns `Some<T>` if predicate returns true, else `None`
216
+ *
217
+ * @example
218
+ * ```ts
219
+ * const age = 25;
220
+ * ExperimentalOption.fromPredicate(age, a => a >= 18) // Some(25)
221
+ * ExperimentalOption.fromPredicate(15, a => a >= 18) // None
222
+ *
223
+ * // Can be used for validation
224
+ * const isValidEmail = (email: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
225
+ * ExperimentalOption.fromPredicate(user.email, isValidEmail)
226
+ *
227
+ * // With complex predicates
228
+ * const isValidPassword = (pw: string) =>
229
+ * pw.length >= 8 && /[A-Z]/.test(pw) && /[0-9]/.test(pw);
230
+ * ExperimentalOption.fromPredicate(password, isValidPassword)
231
+ * ```
232
+ */
233
+ static fromPredicate(val, pred) {
234
+ return pred(val) ? ExperimentalOption.Some(val) : ExperimentalOption.None;
235
+ }
236
+ /**
237
+ * Combines multiple ExperimentalOptions into a single ExperimentalOption of an array.
238
+ *
239
+ * Returns `Some` containing an array of all unwrapped values if ALL inputs are `Some`.
240
+ * Returns `None` if ANY input is `None`.
241
+ *
242
+ * @template T - Variadic tuple of ExperimentalOption types
243
+ * @param options - Variable number of ExperimentalOptions to combine
244
+ * @returns `ExperimentalOption<[T1, T2, ...]>` with array of values, or `None`
245
+ *
246
+ * @example
247
+ * ```ts
248
+ * // All Some -> array of values
249
+ * const all = ExperimentalOption.all(
250
+ * ExperimentalOption.Some(1),
251
+ * ExperimentalOption.Some(2),
252
+ * ExperimentalOption.Some(3)
253
+ * );
254
+ * // Some([1, 2, 3])
255
+ *
256
+ * // Any None -> None
257
+ * const withNone = ExperimentalOption.all(
258
+ * ExperimentalOption.Some(1),
259
+ * ExperimentalOption.None,
260
+ * ExperimentalOption.Some(3)
261
+ * );
262
+ * // None
263
+ *
264
+ * // Empty -> Some([])
265
+ * const empty = ExperimentalOption.all();
266
+ * // Some([])
267
+ *
268
+ * // Practical example: combine multiple validations
269
+ * const name = ExperimentalOption.fromNullable(user.name);
270
+ * const email = ExperimentalOption.fromNullable(user.email);
271
+ * const age = ExperimentalOption.fromNullable(user.age);
272
+ *
273
+ * const complete = ExperimentalOption.all(name, email, age);
274
+ * // ExperimentalOption<[string, string, number]>
275
+ * ```
276
+ */
277
+ static all(...options) {
278
+ const vals = [];
279
+ for (const opt of options) {
280
+ if (opt.isNone()) return ExperimentalOption.None;
281
+ vals.push(opt.#val);
282
+ }
283
+ return ExperimentalOption.Some(vals);
284
+ }
285
+ /**
286
+ * Returns the first `Some` from a list of ExperimentalOptions, or `None` if all are `None`.
287
+ *
288
+ * Short-circuits on the first `Some` found, evaluating subsequent options lazily.
289
+ *
290
+ * @template T - The type of values in the ExperimentalOptions
291
+ * @param options - Variable number of ExperimentalOptions to check
292
+ * @returns The first `Some<T>` found, or `None`
293
+ *
294
+ * @example
295
+ * ```ts
296
+ * // Returns first Some
297
+ * const first = ExperimentalOption.any(
298
+ * ExperimentalOption.None,
299
+ * ExperimentalOption.Some("First value"),
300
+ * ExperimentalOption.Some("Second value")
301
+ * );
302
+ * // Some("First value")
303
+ *
304
+ * // All None -> None
305
+ * const allNone = ExperimentalOption.any(
306
+ * ExperimentalOption.None,
307
+ * ExperimentalOption.None,
308
+ * ExperimentalOption.None
309
+ * );
310
+ * // None
311
+ *
312
+ * // Practical: Try multiple fallback sources
313
+ * const config = ExperimentalOption.any(
314
+ * ExperimentalOption.fromNullable(process.env.API_KEY),
315
+ * ExperimentalOption.fromNullable(getEnvVar("API_KEY")),
316
+ * ExperimentalOption.fromNullable(readConfigFile("API_KEY"))
317
+ * );
318
+ *
319
+ * // Empty -> None
320
+ * const empty = ExperimentalOption.any();
321
+ * // None
322
+ * ```
323
+ */
324
+ static any(...options) {
325
+ for (const opt of options) if (opt.isSome()) return opt;
326
+ return ExperimentalOption.None;
327
+ }
328
+ /**
329
+ * Type guard that narrows the type to `Some`.
330
+ *
331
+ * Returns `true` if this ExperimentalOption is in the `Some` state, containing a value.
332
+ *
333
+ * @returns `true` if this is a `Some`, `false` if `None`
334
+ *
335
+ * @example
336
+ * ```ts
337
+ * const opt: ExperimentalOption<number> = ExperimentalOption.Some(42);
338
+ *
339
+ * if (opt.isSome()) {
340
+ * // TypeScript knows opt is ExperimentalOption<number> & { _tag: "Some" }
341
+ * console.log(opt.unwrap()); // 42
342
+ * }
343
+ * ```
344
+ */
345
+ isSome() {
346
+ return this._tag === "Some" && this.#val !== NONE_VAL;
347
+ }
348
+ /**
349
+ * Type guard that narrows the type to `None`.
350
+ *
351
+ * Returns `true` if this ExperimentalOption is in the `None` state (absence of value).
352
+ *
353
+ * @returns `true` if this is `None`, `false` if `Some`
354
+ *
355
+ * @example
356
+ * ```ts
357
+ * const opt: ExperimentalOption<number> = ExperimentalOption.None;
358
+ *
359
+ * if (opt.isNone()) {
360
+ * // TypeScript knows opt is ExperimentalOption<never> & { _tag: "None" }
361
+ * console.log("No value present");
362
+ * }
363
+ * ```
364
+ */
365
+ isNone() {
366
+ return this._tag === "None" || this.#val === NONE_VAL;
367
+ }
368
+ /**
369
+ * Type guard that checks if the contained value is the `Unit` type.
370
+ *
371
+ * Returns `true` if this ExperimentalOption contains the special `UNIT` value,
372
+ * used to represent operations that produce no meaningful output.
373
+ *
374
+ * @returns `true` if this contains `UNIT`, `false` otherwise
375
+ *
376
+ * @example
377
+ * ```ts
378
+ * const unitOpt: ExperimentalOption<UNIT> = ExperimentalOption.Some(UNIT);
379
+ * unitOpt.isUnit(); // true
380
+ *
381
+ * const normalOpt: ExperimentalOption<number> = ExperimentalOption.Some(42);
382
+ * normalOpt.isUnit(); // false
383
+ * ```
384
+ */
385
+ isUnit() {
386
+ return this.#val === require_unit.UNIT;
387
+ }
388
+ /**
389
+ * Returns the contained value or throws {@link UnwrappedNone} if `None`.
390
+ *
391
+ * This is an unsafe operation that throws on `None`. Use only when you are
392
+ * certain the ExperimentalOption contains a value, or use safe alternatives like
393
+ * {@link unwrapOr} or {@link safeUnwrap}.
394
+ *
395
+ * @throws {@link UnwrappedNone} if this is `None`
396
+ * @returns The contained value
397
+ *
398
+ * @example
399
+ * ```ts
400
+ * ExperimentalOption.Some(42).unwrap(); // 42
401
+ * ExperimentalOption.None.unwrap(); // throws UnwrappedNone
402
+ *
403
+ * // Safe usage pattern
404
+ * const opt = ExperimentalOption.Some(42);
405
+ * if (opt.isSome()) {
406
+ * const value = opt.unwrap(); // Safe: we checked isSome()
407
+ * }
408
+ * ```
409
+ *
410
+ * @see {@link unwrapOr} for safe unwrapping with a default value
411
+ * @see {@link unwrapOrElse} for lazy default computation
412
+ * @see {@link safeUnwrap} for null-returning safe unwrap
413
+ */
414
+ unwrap() {
415
+ if (this.isNone()) throw UNWRAPPED_NONE_ERR;
416
+ return this.#val;
417
+ }
418
+ /**
419
+ * Returns the contained value, or the provided default value if `None`.
420
+ *
421
+ * A safe alternative to {@link unwrap} that doesn't throw.
422
+ *
423
+ * @param defaultValue - The value to return if this is `None`
424
+ * @returns The contained value, or the default
425
+ *
426
+ * @example
427
+ * ```ts
428
+ * ExperimentalOption.Some(42).unwrapOr(0); // 42
429
+ * ExperimentalOption.None.unwrapOr(0); // 0
430
+ *
431
+ * // With user input
432
+ * const age = ExperimentalOption.fromNullable(user.age).unwrapOr(18);
433
+ *
434
+ * // With complex defaults
435
+ * const config = ExperimentalOption.fromNullable(getConfig())
436
+ * .unwrapOr({ port: 3000, host: "localhost" });
437
+ * ```
438
+ *
439
+ * @see {@link unwrapOrElse} for lazy default computation
440
+ * @see {@link safeUnwrap} for null-returning safe unwrap
441
+ */
442
+ unwrapOr(defaultValue) {
443
+ if (this.isNone()) return defaultValue;
444
+ return this.#val;
445
+ }
446
+ /**
447
+ * Returns the contained value, or computes a default via a function if `None`.
448
+ *
449
+ * Unlike {@link unwrapOr}, the default is computed lazily - only if this is `None`.
450
+ * Use this when the default value is expensive to compute.
451
+ *
452
+ * @param fn - A factory function that produces the default value
453
+ * @returns The contained value, or the computed default
454
+ *
455
+ * @example
456
+ * ```ts
457
+ * // Lazy default - only computed if needed
458
+ * const value = ExperimentalOption.None.unwrapOrElse(() => {
459
+ * console.log("Computing expensive default...");
460
+ * return expensivelyComputeDefault();
461
+ * });
462
+ * // Prints "Computing expensive default..."
463
+ *
464
+ * // Not computed when Some
465
+ * const some = ExperimentalOption.Some(42).unwrapOrElse(() => {
466
+ * console.log("This won't print");
467
+ * return expensivelyComputeDefault();
468
+ * });
469
+ * // Returns 42 without printing
470
+ *
471
+ * // Practical: cache lookup with fallback
472
+ * const cached = ExperimentalOption.fromNullable(cache.get(key))
473
+ * .unwrapOrElse(() => {
474
+ * const value = fetchFromDatabase(key);
475
+ * cache.set(key, value);
476
+ * return value;
477
+ * });
478
+ * ```
479
+ *
480
+ * @see {@link unwrapOr} for simple default values
481
+ * @see {@link unwrap} for unsafe unwrapping
482
+ */
483
+ unwrapOrElse(fn) {
484
+ if (this.isNone()) return fn();
485
+ return this.#val;
486
+ }
487
+ /**
488
+ * Returns the contained value, or `null` if `None`.
489
+ *
490
+ * Provides a safe way to extract values that integrates with TypeScript's
491
+ * null checking while maintaining the ExperimentalOption semantics.
492
+ *
493
+ * @returns The contained value, or `null`
494
+ *
495
+ * @example
496
+ * ```ts
497
+ * ExperimentalOption.Some(42).safeUnwrap(); // 42
498
+ * ExperimentalOption.None.safeUnwrap(); // null
499
+ *
500
+ * // Integration with existing null-handling code
501
+ * const value = ExperimentalOption.fromNullable(user.name).safeUnwrap();
502
+ * if (value !== null) {
503
+ * console.log(value.toUpperCase());
504
+ * }
505
+ *
506
+ * // With nullish coalescing
507
+ * const displayName = ExperimentalOption.fromNullable(user.displayName)
508
+ * .safeUnwrap() ?? user.email;
509
+ * ```
510
+ *
511
+ * @see {@link unwrapOr} for typed defaults
512
+ * @see {@link unwrapOrElse} for lazy defaults
513
+ */
514
+ safeUnwrap() {
515
+ if (this.isNone()) return null;
516
+ return this.#val;
517
+ }
518
+ /**
519
+ * Pattern matches on both states of the ExperimentalOption, providing exhaustive handling.
520
+ *
521
+ * This is the most explicit way to handle ExperimentalOptions, ensuring both `Some` and `None`
522
+ * cases are handled at compile time.
523
+ *
524
+ * @template U - The result type of both branches
525
+ * @param cases - Object containing handlers for both states
526
+ * @returns The result of calling the appropriate handler
527
+ *
528
+ * @example
529
+ * ```ts
530
+ * const result = ExperimentalOption.Some(42).match({
531
+ * Some: (value) => `Got: ${value}`,
532
+ * None: () => "Got nothing"
533
+ * });
534
+ * // "Got: 42"
535
+ *
536
+ * const noneResult = ExperimentalOption.None.match({
537
+ * Some: (value) => `Got: ${value}`,
538
+ * None: () => "Got nothing"
539
+ * });
540
+ * // "Got nothing"
541
+ *
542
+ * // Practical: user lookup
543
+ * const message = findUser(userId).match({
544
+ * Some: (user) => `Welcome, ${user.name}!`,
545
+ * None: () => "User not found"
546
+ * });
547
+ * ```
548
+ *
549
+ * @see {@link isSome} and {@link isNone} for conditional handling
550
+ */
551
+ match(cases) {
552
+ if (this.isNone()) return cases.None();
553
+ return cases.Some(this.#val);
554
+ }
555
+ /**
556
+ * Pattern matches using positional arguments (FP convention alias for `match`).
557
+ *
558
+ * This is a more concise alternative to `match` using positional arguments
559
+ * instead of an object. Familiar to developers from Scala, Haskell, and other FP languages.
560
+ *
561
+ * @template U - The result type of both branches
562
+ * @param onSome - Handler called with the value if `Some`
563
+ * @param onNone - Handler called if `None`
564
+ * @returns The result of calling the appropriate handler
565
+ *
566
+ * @example
567
+ * ```ts
568
+ * const result = ExperimentalOption.Some(42).fold(
569
+ * (value) => `Got: ${value}`,
570
+ * () => "Got nothing"
571
+ * );
572
+ * // "Got: 42"
573
+ *
574
+ * const noneResult = ExperimentalOption.None.fold(
575
+ * (value) => `Got: ${value}`,
576
+ * () => "Got nothing"
577
+ * );
578
+ * // "Got nothing"
579
+ *
580
+ * // Equivalent to match:
581
+ * experimentalOption.fold(onSome, onNone);
582
+ * experimentalOption.match({ Some: onSome, None: onNone });
583
+ * ```
584
+ *
585
+ * @see {@link match} for object-based pattern matching
586
+ * @see {@link foldAsync} for async handlers
587
+ */
588
+ fold(onSome, onNone) {
589
+ if (this.isNone()) return onNone();
590
+ return onSome(this.#val);
591
+ }
592
+ /**
593
+ * Async pattern matching using positional arguments.
594
+ *
595
+ * Async variant of `fold` for when handlers return Promises.
596
+ * Rejections from `onSome` are propagated (not converted to `None`).
597
+ *
598
+ * @template U - The result type of both branches
599
+ * @param onSome - Async handler called with the value if `Some`
600
+ * @param onNone - Async handler called if `None`
601
+ * @returns Promise resolving to the result of the appropriate handler
602
+ *
603
+ * @example
604
+ * ```ts
605
+ * const result = await ExperimentalOption.Some(userId).foldAsync(
606
+ * async (id) => await fetchUser(id),
607
+ * async () => await getDefaultUser()
608
+ * );
609
+ *
610
+ * // With database lookup
611
+ * const user = await ExperimentalOption.fromNullable(sessionUserId).foldAsync(
612
+ * async (id) => await db.users.findById(id),
613
+ * async () => ({ id: 0, name: "Guest" })
614
+ * );
615
+ * ```
616
+ *
617
+ * @see {@link fold} for synchronous handlers
618
+ * @see {@link matchAsync} for object-based async pattern matching
619
+ */
620
+ async foldAsync(onSome, onNone) {
621
+ if (this.isNone()) return onNone();
622
+ return onSome(this.#val);
623
+ }
624
+ /**
625
+ * Async pattern matching on both states of the ExperimentalOption.
626
+ *
627
+ * Async variant of `match` for when handlers return Promises.
628
+ * Rejections from `Some` handler are propagated (not converted to `None`).
629
+ *
630
+ * @template U - The result type of both branches
631
+ * @param cases - Object containing async handlers for both states
632
+ * @returns Promise resolving to the result of the appropriate handler
633
+ *
634
+ * @example
635
+ * ```ts
636
+ * const result = await ExperimentalOption.Some(userId).matchAsync({
637
+ * Some: async (id) => await fetchUser(id),
638
+ * None: async () => await getDefaultUser()
639
+ * });
640
+ *
641
+ * // With API calls
642
+ * const data = await maybeConfig.matchAsync({
643
+ * Some: async (config) => await loadWithConfig(config),
644
+ * None: async () => await loadDefaults()
645
+ * });
646
+ * ```
647
+ *
648
+ * @see {@link match} for synchronous pattern matching
649
+ * @see {@link foldAsync} for positional-argument async matching
650
+ */
651
+ async matchAsync(cases) {
652
+ if (this.isNone()) return cases.None();
653
+ return cases.Some(this.#val);
654
+ }
655
+ /**
656
+ * Pattern matches with a subset of cases, using a default for unhandled cases.
657
+ *
658
+ * Unlike `match` which requires all cases, `matchPartial` allows handling
659
+ * only specific cases with a fallback default function.
660
+ *
661
+ * @template U - The result type
662
+ * @param cases - Partial object with optional `Some` and `None` handlers
663
+ * @param getDefault - Lazy default function for unhandled cases
664
+ * @returns The result of the matching handler or the default
665
+ *
666
+ * @example
667
+ * ```ts
668
+ * // Only handle Some, default for None
669
+ * ExperimentalOption.Some(42).matchPartial({ Some: (v) => v * 2 }, () => 0); // 84
670
+ * ExperimentalOption.None.matchPartial({ Some: (v) => v * 2 }, () => 0); // 0
671
+ *
672
+ * // Only handle None
673
+ * ExperimentalOption.Some(42).matchPartial({ None: () => -1 }, () => 100); // 100
674
+ * ExperimentalOption.None.matchPartial({ None: () => -1 }, () => 100); // -1
675
+ *
676
+ * // Lazy default with function
677
+ * experimentalOption.matchPartial(
678
+ * { Some: (v) => process(v) },
679
+ * () => computeExpensiveDefault()
680
+ * );
681
+ * ```
682
+ *
683
+ * @see {@link match} for exhaustive pattern matching
684
+ */
685
+ matchPartial(cases, getDefault) {
686
+ if (this.isNone()) return cases.None ? cases.None() : getDefault();
687
+ return cases.Some ? cases.Some(this.#val) : getDefault();
688
+ }
689
+ map(fn) {
690
+ if (this.isNone()) return ExperimentalOption.None;
691
+ return ExperimentalOption.Some(fn(this.#val));
692
+ }
693
+ /**
694
+ * Transforms the contained value using an async function.
695
+ *
696
+ * If `Some`, awaits the async function and wraps the result in a new `Some`.
697
+ * If `None`, returns a resolved `None` Promise without calling the function.
698
+ *
699
+ * @template U - The type of the transformed value
700
+ * @param fn - An async function that transforms the contained value
701
+ * @returns `Promise<Some<U>>` with the transformed value, or `Promise<None>`
702
+ *
703
+ * @example
704
+ * ```ts
705
+ * // Simple async transform
706
+ * const result = await ExperimentalOption.Some(5).mapAsync(async x => {
707
+ * return x * 2;
708
+ * });
709
+ * // Some(10)
710
+ *
711
+ * // Chaining with .then()
712
+ * ExperimentalOption.Some(5)
713
+ * .map(x => x * 2) // Some(10)
714
+ * .mapAsync(async x => {
715
+ * return await fetchData(x); // Some<Data>
716
+ * })
717
+ * .then(o => o.map(d => d.name)); // Promise<Some<string>>
718
+ *
719
+ * // Practical: API call after validation
720
+ * const userData = await ExperimentalOption.Some(userId)
721
+ * .mapAsync(async id => await fetchUser(id))
722
+ * .then(o => o.mapAsync(async user => await fetchProfile(user.id)));
723
+ * // Promise<ExperimentalOption<Profile>>
724
+ * ```
725
+ *
726
+ * @see {@link map} for synchronous transformations
727
+ */
728
+ async mapAsync(fn) {
729
+ if (this.isNone()) return Promise.resolve(ExperimentalOption.None);
730
+ return fn(this.#val).then((u) => ExperimentalOption.Some(u));
731
+ }
732
+ /**
733
+ * Maps the value or returns a default value (unwrapped).
734
+ *
735
+ * Unlike {@link map}, this returns the value directly (not wrapped in ExperimentalOption).
736
+ * If `Some`, applies the function and returns the result.
737
+ * If `None`, returns the default value without calling the function.
738
+ *
739
+ * @template U - The type of the result
740
+ * @param defaultValue - The value to return if `None`
741
+ * @param fn - A function to apply if `Some`
742
+ * @returns The mapped value or the default
743
+ *
744
+ * @example
745
+ * ```ts
746
+ * ExperimentalOption.Some(5).mapOr(0, x => x * 2); // 10
747
+ * ExperimentalOption.None.mapOr(0, x => x * 2); // 0
748
+ *
749
+ * // Practical: formatting with fallback
750
+ * const displayName = ExperimentalOption.fromNullable(user.name)
751
+ * .mapOr("Anonymous", name => name.toUpperCase());
752
+ * // "JOHN" or "Anonymous"
753
+ *
754
+ * // With complex defaults
755
+ * const balance = ExperimentalOption.fromNullable(account?.balance)
756
+ * .mapOr(0, b => b.toFixed(2));
757
+ * ```
758
+ *
759
+ * @see {@link map} for wrapped results
760
+ * @see {@link mapOrAsync} for async transformations
761
+ */
762
+ mapOr(defaultValue, fn) {
763
+ if (this.isNone()) return defaultValue;
764
+ return fn(this.#val);
765
+ }
766
+ /**
767
+ * Maps the value using an async function or returns a default value.
768
+ *
769
+ * @template U - The type of the result
770
+ * @param defaultValue - The value to return if `None`
771
+ * @param fn - An async function to apply if `Some`
772
+ * @returns `Promise<U>` with the mapped value or the default
773
+ *
774
+ * @example
775
+ * ```ts
776
+ * const result = await ExperimentalOption.Some(5).mapOrAsync(0, async x => {
777
+ * return x * 2;
778
+ * });
779
+ * // 10
780
+ *
781
+ * const noneResult = await ExperimentalOption.None.mapOrAsync(0, async x => {
782
+ * return x * 2;
783
+ * });
784
+ * // 0
785
+ *
786
+ * // Practical: async fetch with fallback
787
+ * const balance = await ExperimentalOption.fromNullable(userId)
788
+ * .mapOrAsync(0, async id => await getAccountBalance(id));
789
+ * ```
790
+ *
791
+ * @see {@link mapOr} for synchronous transformations
792
+ */
793
+ async mapOrAsync(defaultValue, fn) {
794
+ if (this.isNone()) return defaultValue;
795
+ return fn(this.#val);
796
+ }
797
+ /**
798
+ * Chains operations that return ExperimentalOptions, flattening nested ExperimentalOptions.
799
+ *
800
+ * Also known as `bind` or `chain`. Use this to sequence operations where
801
+ * each step depends on the previous value and may fail.
802
+ *
803
+ * If `Some`, applies the function and returns its result directly.
804
+ * If `None`, returns `None` without calling the function.
805
+ *
806
+ * @template U - The type of the value in the returned ExperimentalOption
807
+ * @param fn - A function that returns an ExperimentalOption
808
+ * @returns The result of the function, or `None`
809
+ *
810
+ * @example
811
+ * ```ts
812
+ * // Basic chaining
813
+ * ExperimentalOption.Some(5).flatMap(x => ExperimentalOption.Some(x + 1)); // Some(6)
814
+ * ExperimentalOption.Some(5).flatMap(x => ExperimentalOption.None); // None
815
+ * ExperimentalOption.None.flatMap(x => ExperimentalOption.Some(x + 1)); // None
816
+ *
817
+ * // Chaining optional operations
818
+ * const email = findUser(userId)
819
+ * .flatMap(user => ExperimentalOption.fromNullable(user.profile))
820
+ * .flatMap(profile => ExperimentalOption.fromNullable(profile.avatar))
821
+ * .flatMap(avatar => ExperimentalOption.fromNullable(avatar.url));
822
+ *
823
+ * // Practical: multi-step validation
824
+ * const valid = ExperimentalOption.Some(input)
825
+ * .flatMap(s => parseEmail(s))
826
+ * .flatMap(email => checkDomain(email))
827
+ * .flatMap(domain => resolveDomain(domain));
828
+ * ```
829
+ *
830
+ * @see {@link flatMapAsync} for async operations
831
+ * @see {@link map} for simple transformations
832
+ * @see {@link gen} for imperative-style chaining
833
+ */
834
+ flatMap(fn) {
835
+ if (this.isNone()) return ExperimentalOption.None;
836
+ return fn(this.#val);
837
+ }
838
+ /**
839
+ * Chains async operations that return ExperimentalOptions.
840
+ *
841
+ * @template U - The type of the value in the returned ExperimentalOption
842
+ * @param fn - An async function that returns an ExperimentalOption
843
+ * @returns `Promise<ExperimentalOption<U>>` with the result, or `Promise<None>`
844
+ *
845
+ * @example
846
+ * ```ts
847
+ * // Async database lookup chain
848
+ * const profile = await ExperimentalOption.Some(userId)
849
+ * .flatMapAsync(async id => await findUser(id))
850
+ * .flatMapAsync(async user => await getProfile(user.id))
851
+ * .flatMapAsync(async p => await getAvatar(p.avatarId));
852
+ * // Promise<ExperimentalOption<Avatar>>
853
+ *
854
+ * // Practical: multi-step async pipeline
855
+ * const result = await ExperimentalOption.Some(email)
856
+ * .flatMapAsync(validateEmail)
857
+ * .flatMapAsync(e => fetchUserByEmail(e))
858
+ * .flatMapAsync(u => getUserPermissions(u.id));
859
+ * ```
860
+ *
861
+ * @see {@link flatMap} for synchronous operations
862
+ * @see {@link asyncGen} for imperative-style async chaining
863
+ */
864
+ async flatMapAsync(fn) {
865
+ if (this.isNone()) return ExperimentalOption.None;
866
+ return fn(this.#val);
867
+ }
868
+ /**
869
+ * Converts `Some` to `None` if the predicate returns `false`.
870
+ *
871
+ * If `Some`, tests the predicate and returns `Some` if true, `None` if false.
872
+ * If `None`, returns `None` without calling the predicate.
873
+ *
874
+ * @param pred - A predicate function to test the contained value
875
+ * @returns `Some<T>` if predicate passes, else `None`
876
+ *
877
+ * @example
878
+ * ```ts
879
+ * ExperimentalOption.Some(5).filter(x => x > 3); // Some(5)
880
+ * ExperimentalOption.Some(5).filter(x => x > 10); // None
881
+ * ExperimentalOption.None.filter(x => x > 3); // None
882
+ *
883
+ * // Age validation
884
+ * const adult = ExperimentalOption.Some(age)
885
+ * .filter(a => a >= 18);
886
+ *
887
+ * // Multiple filters
888
+ * const valid = ExperimentalOption.Some(password)
889
+ * .filter(pw => pw.length >= 8)
890
+ * .filter(pw => /[A-Z]/.test(pw))
891
+ * .filter(pw => /[0-9]/.test(pw));
892
+ * ```
893
+ *
894
+ * @see {@link filterAsync} for async predicates
895
+ * @see {@link fromPredicate} for creating ExperimentalOptions from predicates
896
+ */
897
+ filter(pred) {
898
+ if (this.isNone()) return ExperimentalOption.None;
899
+ return pred(this.#val) ? this : ExperimentalOption.None;
900
+ }
901
+ /**
902
+ * Converts `Some` to `None` if the async predicate returns `false`.
903
+ *
904
+ * @param pred - An async predicate function to test the contained value
905
+ * @returns `Promise<Some<T>>` if predicate passes, else `Promise<None>`
906
+ *
907
+ * @example
908
+ * ```ts
909
+ * // Async validation
910
+ * const valid = await ExperimentalOption.Some(email)
911
+ * .filterAsync(async e => await checkEmailDomain(e));
912
+ *
913
+ * // Practical: database validation
914
+ * const unique = await ExperimentalOption.Some(username)
915
+ * .filterAsync(async u => await isUsernameAvailable(u));
916
+ * ```
917
+ *
918
+ * @see {@link filter} for synchronous predicates
919
+ */
920
+ async filterAsync(pred) {
921
+ if (this.isNone()) return Promise.resolve(ExperimentalOption.None);
922
+ return pred(this.#val).then((passed) => passed ? this : ExperimentalOption.None);
923
+ }
924
+ zip(fn) {
925
+ if (this.isNone()) return ExperimentalOption.None;
926
+ return ExperimentalOption.Some([this.#val, fn(this.#val)]);
927
+ }
928
+ /**
929
+ * Pairs the original value with an async derived value.
930
+ *
931
+ * @template U - The type of the derived value
932
+ * @param fn - An async function that derives a value from the contained value
933
+ * @returns `Promise<Some<[T, U]>>` with the tuple, or `Promise<None>`
934
+ *
935
+ * @example
936
+ * ```ts
937
+ * const result = await ExperimentalOption.Some(user)
938
+ * .zipAsync(async u => await fetchCount(u));
939
+ * // Some([user, number])
940
+ *
941
+ * // Practical: user with additional data
942
+ * const enriched = await ExperimentalOption.Some(userId)
943
+ * .zipAsync(async id => await fetchUser(id))
944
+ * .then(o => o.zipAsync(async ([id, user]) => await getStats(user.id)));
945
+ * // Promise<ExperimentalOption<[userId, User, Stats]>>
946
+ * ```
947
+ *
948
+ * @see {@link zip} for synchronous derivation
949
+ */
950
+ async zipAsync(fn) {
951
+ if (this.isNone()) return Promise.resolve(ExperimentalOption.None);
952
+ return fn(this.#val).then((u) => ExperimentalOption.Some([this.#val, u]));
953
+ }
954
+ /**
955
+ * Pairs the original value with a value from another ExperimentalOption.
956
+ *
957
+ * Combines two independent ExperimentalOptions into a tuple. Both must be `Some` to succeed.
958
+ *
959
+ * @template U - The type of the value in the other ExperimentalOption
960
+ * @param fn - A function that returns an ExperimentalOption to combine with
961
+ * @returns `Some<[T, U]>` with both values, or `None`
962
+ *
963
+ * @example
964
+ * ```ts
965
+ * // Basic usage
966
+ * ExperimentalOption.Some(5).flatZip(x => ExperimentalOption.Some(10)); // Some([5, 10])
967
+ * ExperimentalOption.Some(5).flatZip(x => ExperimentalOption.None); // None
968
+ * ExperimentalOption.None.flatZip(x => ExperimentalOption.Some(10)); // None
969
+ *
970
+ * // Practical: combine independent lookups
971
+ * const productData = ExperimentalOption.Some(productId)
972
+ * .flatZip(id => fetchProductPrice(id));
973
+ * // ExperimentalOption<[productId, price]>
974
+ *
975
+ * // Multiple dependencies
976
+ * const complete = ExperimentalOption.Some(userId)
977
+ * .flatZip(id => fetchUser(id))
978
+ * .flatMap(([id, user]) => ExperimentalOption.Some([id, user.profileId]))
979
+ * .flatZip(([id, profileId]) => fetchProfile(profileId));
980
+ * // ExperimentalOption<[userId, profileId, profile]>
981
+ * ```
982
+ *
983
+ * @see {@link flatZipAsync} for async ExperimentalOptions
984
+ * @see {@link zip} for derived values
985
+ * @see {@link all} for combining multiple ExperimentalOptions at once
986
+ */
987
+ flatZip(fn) {
988
+ if (this.isNone()) return ExperimentalOption.None;
989
+ const other = fn(this.#val);
990
+ if (other.isNone()) return ExperimentalOption.None;
991
+ return ExperimentalOption.Some([this.#val, other.unwrap()]);
992
+ }
993
+ /**
994
+ * Pairs the original value with a value from an async ExperimentalOption.
995
+ *
996
+ * @template U - The type of the value in the other ExperimentalOption
997
+ * @param fn - An async function that returns an ExperimentalOption
998
+ * @returns `Promise<Some<[T, U]>>` with both values, or `Promise<None>`
999
+ *
1000
+ * @example
1001
+ * ```ts
1002
+ * const result = await ExperimentalOption.Some(userId)
1003
+ * .flatZipAsync(async id => await fetchUser(id));
1004
+ * // ExperimentalOption<[userId, User]>
1005
+ *
1006
+ * // Practical: async pipeline
1007
+ * const enriched = await ExperimentalOption.Some(userId)
1008
+ * .flatZipAsync(async id => await fetchUser(id))
1009
+ * .then(o => o.flatMapAsync(async ([id, user]) =>
1010
+ * ExperimentalOption.Some([id, user, await fetchProfile(user.profileId)])
1011
+ * ));
1012
+ * ```
1013
+ *
1014
+ * @see {@link flatZip} for synchronous ExperimentalOptions
1015
+ */
1016
+ async flatZipAsync(fn) {
1017
+ if (this.isNone()) return Promise.resolve(ExperimentalOption.None);
1018
+ return fn(this.#val).then((other) => {
1019
+ if (other.isNone()) return ExperimentalOption.None;
1020
+ return ExperimentalOption.Some([this.#val, other.unwrap()]);
1021
+ });
1022
+ }
1023
+ /**
1024
+ * Executes a side effect function if `Some`, returning `this` unchanged.
1025
+ *
1026
+ * Useful for logging, debugging, or executing effects without breaking the chain.
1027
+ *
1028
+ * @param fn - A side effect function to execute with the contained value
1029
+ * @returns `this` (unchanged, for chaining)
1030
+ *
1031
+ * @example
1032
+ * ```ts
1033
+ * // Logging without breaking chain
1034
+ * ExperimentalOption.Some(user)
1035
+ * .tap(u => console.log(`Processing ${u.name}`))
1036
+ * .map(u => u.email);
1037
+ *
1038
+ * // Debugging
1039
+ * ExperimentalOption.Some(input)
1040
+ * .tap(val => console.log("Before:", val))
1041
+ * .map(transform)
1042
+ * .tap(val => console.log("After:", val));
1043
+ *
1044
+ * // Practical: audit trail
1045
+ * const result = ExperimentalOption.Some(transaction)
1046
+ * .tap((t) => auditLog("start", t.id))
1047
+ * .flatMap((t) => process(t))
1048
+ * .tap((r) => auditLog("success", r.id));
1049
+ * ```
1050
+ *
1051
+ * @see {@link tapAsync} for async side effects
1052
+ */
1053
+ tap(fn) {
1054
+ if (this.isSome()) fn(this.#val);
1055
+ return this;
1056
+ }
1057
+ /**
1058
+ * Executes an async side effect function if `Some`, returning `this` unchanged.
1059
+ *
1060
+ * @param fn - An async side effect function to execute
1061
+ * @returns `Promise<ExperimentalOption<T>>` that resolves to `this`
1062
+ *
1063
+ * @example
1064
+ * ```ts
1065
+ * // Async logging
1066
+ * await ExperimentalOption.Some(user)
1067
+ * .tapAsync(async u => await logAnalytics(u.id))
1068
+ * .map(u => u.email);
1069
+ *
1070
+ * // Practical: metrics collection
1071
+ * const result = await ExperimentalOption.Some(request)
1072
+ * .tapAsync(async req => await trackMetric("request_start", req.id))
1073
+ * .flatMapAsync(async req => await processRequest(req))
1074
+ * .tapAsync(async res => await trackMetric("request_success", res.id));
1075
+ * ```
1076
+ *
1077
+ * @see {@link tap} for synchronous side effects
1078
+ */
1079
+ async tapAsync(fn) {
1080
+ if (this.isSome()) return fn(this.#val).then(() => this);
1081
+ return Promise.resolve(this);
1082
+ }
1083
+ /**
1084
+ * Converts this ExperimentalOption to a Result.
1085
+ *
1086
+ * `Some` becomes `Ok`, `None` becomes `Err` with the provided error.
1087
+ *
1088
+ * @template E - The type of the error for the `Err` variant
1089
+ * @param error - The error value to use if this is `None`
1090
+ * @returns `Result<T, E>` with the value or error
1091
+ *
1092
+ * @example
1093
+ * ```ts
1094
+ * ExperimentalOption.Some(42).toResult("was none"); // Ok(42)
1095
+ * ExperimentalOption.None.toResult("was none"); // Err("was none")
1096
+ *
1097
+ * // Practical: convert to Result for error handling
1098
+ * const user = ExperimentalOption.fromNullable(getUser())
1099
+ * .toResult(new Error("User not found"));
1100
+ *
1101
+ * // With custom error types
1102
+ * const config = ExperimentalOption.fromNullable(loadConfig())
1103
+ * .toResult({ code: "CONFIG_MISSING", message: "Config file not found" });
1104
+ * ```
1105
+ *
1106
+ * @see {@link ExperimentalResult} for the Result type
1107
+ */
1108
+ toResult(error) {
1109
+ if (this.isNone()) return require_result_experimental.ExperimentalResult.Err(error);
1110
+ return require_result_experimental.ExperimentalResult.Ok(this.#val);
1111
+ }
1112
+ /**
1113
+ * Maps over array elements inside an `ExperimentalOption<Array<T>>`.
1114
+ *
1115
+ * Only callable when `T` is an array type. Applies the mapper to each
1116
+ * element if `Some`, or returns `None`.
1117
+ *
1118
+ * @template Inner - The element type of the array
1119
+ * @template Out - The output element type
1120
+ * @param mapper - A function to transform each array element
1121
+ * @returns `Some<Out[]>` with mapped array, or `None`
1122
+ * @throws {TypeError} if called on a non-array ExperimentalOption
1123
+ *
1124
+ * @example
1125
+ * ```ts
1126
+ * ExperimentalOption.Some([1, 2, 3]).innerMap(n => n * 2);
1127
+ * // Some([2, 4, 6])
1128
+ *
1129
+ * ExperimentalOption.None.innerMap(n => n * 2);
1130
+ * // None
1131
+ *
1132
+ * // Practical: transform list results
1133
+ * const users = await fetchUsers() // ExperimentalOption<User[]>
1134
+ * .innerMap(u => u.name)
1135
+ * .innerMap(names => names.sort());
1136
+ * // Some<string[]>
1137
+ *
1138
+ * // Error case
1139
+ * ExperimentalOption.Some(42).innerMap(x => x * 2);
1140
+ * // throws TypeError: innerMap can only be called on ExperimentalOption<Array<T>>
1141
+ * ```
1142
+ *
1143
+ * @see {@link map} for transforming the contained value directly
1144
+ */
1145
+ innerMap(mapper) {
1146
+ if (this.isNone()) return ExperimentalOption.None;
1147
+ if (!Array.isArray(this.#val)) throw new TypeError("innerMap can only be called on ExperimentalOption<Array<T>>");
1148
+ return ExperimentalOption.Some(this.#val.map(mapper));
1149
+ }
1150
+ /**
1151
+ * Returns a string representation of the ExperimentalOption.
1152
+ *
1153
+ * @returns A string describing the ExperimentalOption state and value
1154
+ *
1155
+ * @example
1156
+ * ```ts
1157
+ * ExperimentalOption.Some(42).toString(); // "ExperimentalOption::Some(42)"
1158
+ * ExperimentalOption.None.toString(); // "ExperimentalOption::None"
1159
+ * ExperimentalOption.Some("hello").toString(); // "ExperimentalOption::Some(hello)"
1160
+ * ```
1161
+ */
1162
+ toString() {
1163
+ if (this.isNone()) return "ExperimentalOption::None";
1164
+ return `ExperimentalOption::Some(${String(this.#val)})`;
1165
+ }
1166
+ /**
1167
+ * Makes ExperimentalOption iterable for use with generator-based syntax.
1168
+ *
1169
+ * Yields self and returns the unwrapped value when resumed.
1170
+ * Used internally by {@link ExperimentalOption.gen} for `yield*` syntax.
1171
+ *
1172
+ * @example
1173
+ * ```ts
1174
+ * const result = ExperimentalOption.gen(function* () {
1175
+ * const value = yield* ExperimentalOption.Some(42);
1176
+ * return value * 2;
1177
+ * });
1178
+ * // Some(84)
1179
+ * ```
1180
+ *
1181
+ * @internal
1182
+ */
1183
+ *[Symbol.iterator]() {
1184
+ const trace = (/* @__PURE__ */ new Error()).stack;
1185
+ return yield new require_utils.CapturedTrace(this, trace);
1186
+ }
1187
+ /**
1188
+ * Makes ExperimentalOption iterable for use with async generator-based syntax.
1189
+ *
1190
+ * Yields self and returns the unwrapped value when resumed.
1191
+ * Used internally by {@link ExperimentalOption.asyncGen} for `yield*` syntax.
1192
+ *
1193
+ * @example
1194
+ * ```ts
1195
+ * const result = await ExperimentalOption.asyncGen(async function* () {
1196
+ * const value = yield* await Promise.resolve(ExperimentalOption.Some(42));
1197
+ * return value * 2;
1198
+ * });
1199
+ * // Some(84)
1200
+ * ```
1201
+ *
1202
+ * @internal
1203
+ */
1204
+ async *[Symbol.asyncIterator]() {
1205
+ const trace = (/* @__PURE__ */ new Error()).stack;
1206
+ return yield new require_utils.CapturedTrace(this, trace);
1207
+ }
1208
+ /**
1209
+ * Generator-based syntax for chaining ExperimentalOption operations (simplified, no adapter).
1210
+ *
1211
+ * Provides imperative-style code while maintaining functional ExperimentalOption handling.
1212
+ * Use `yield*` to unwrap ExperimentalOptions or short-circuit on `None`.
1213
+ *
1214
+ * Short-circuits on first `None`, returning singleton `None`. Uses iteration
1215
+ * instead of recursion to avoid stack overflow on deep chains.
1216
+ *
1217
+ * @template T - The return type of the generator
1218
+ * @param genFn - A generator function that yields ExperimentalOptions
1219
+ * @returns `Some<T>` with the generator's return value, or `None`
1220
+ *
1221
+ * @example
1222
+ * ```ts
1223
+ * // Simple sync chain
1224
+ * const result = ExperimentalOption.gen(function* () {
1225
+ * const a = yield* ExperimentalOption.Some(1);
1226
+ * const b = yield* ExperimentalOption.Some(2);
1227
+ * return a + b;
1228
+ * });
1229
+ * // Some(3)
1230
+ *
1231
+ * // None short-circuit
1232
+ * const shortCircuit = ExperimentalOption.gen(function* () {
1233
+ * const a = yield* ExperimentalOption.Some(1);
1234
+ * const b = yield* ExperimentalOption.None; // Short-circuits here
1235
+ * const c = yield* ExperimentalOption.Some(3); // Never executes
1236
+ * return a + b + c;
1237
+ * });
1238
+ * // None
1239
+ *
1240
+ * // Chaining optional operations
1241
+ * const email = ExperimentalOption.gen(function* () {
1242
+ * const user = yield* findUser(userId);
1243
+ * const profile = yield* ExperimentalOption.fromNullable(user.profile);
1244
+ * const settings = yield* ExperimentalOption.fromNullable(profile.settings);
1245
+ * return settings.email;
1246
+ * });
1247
+ *
1248
+ * // Nested optional access
1249
+ * const city = ExperimentalOption.gen(function* () {
1250
+ * const user = yield* ExperimentalOption.fromNullable(getUser());
1251
+ * const address = yield* ExperimentalOption.fromNullable(user?.address);
1252
+ * const city = yield* ExperimentalOption.fromNullable(address?.city);
1253
+ * return city;
1254
+ * });
1255
+ * ```
1256
+ *
1257
+ * @see {@link genAdapter} for better type inference in complex chains
1258
+ * @see {@link asyncGen} for async operations
1259
+ */
1260
+ static gen(genFn) {
1261
+ const iterator = genFn();
1262
+ let nextArg;
1263
+ let currentResult;
1264
+ while (true) {
1265
+ const next = iterator.next(nextArg);
1266
+ if (next.done) {
1267
+ currentResult = ExperimentalOption.Some(next.value);
1268
+ break;
1269
+ }
1270
+ let yielded = next.value;
1271
+ if (require_utils.isCapturedTrace(yielded)) yielded = yielded.value;
1272
+ if (yielded.isNone()) {
1273
+ iterator.return?.(void 0);
1274
+ currentResult = ExperimentalOption.None;
1275
+ break;
1276
+ }
1277
+ nextArg = yielded.unwrap();
1278
+ }
1279
+ return currentResult;
1280
+ }
1281
+ /**
1282
+ * Generator-based syntax for chaining ExperimentalOption operations with an adapter function.
1283
+ *
1284
+ * Provides better type inference and IDE support compared to {@link gen}.
1285
+ * The `$` adapter wraps ExperimentalOptions and enables clearer type tracking.
1286
+ *
1287
+ * Short-circuits on first `None`, returning singleton `None`. Uses iteration
1288
+ * instead of recursion to avoid stack overflow on deep chains.
1289
+ *
1290
+ * @template Eff - The effect type (inferred from usage)
1291
+ * @template T - The return type of the generator
1292
+ * @param genFn - A generator function receiving an adapter `$`
1293
+ * @returns `Some<T>` with the generator's return value, or `None`
1294
+ *
1295
+ * @example
1296
+ * ```ts
1297
+ * // Better type inference
1298
+ * const result = ExperimentalOption.genAdapter(function* ($) {
1299
+ * const a = yield* $(ExperimentalOption.Some(1));
1300
+ * const b = yield* $(ExperimentalOption.Some(2));
1301
+ * return a + b;
1302
+ * });
1303
+ * // Some(3)
1304
+ *
1305
+ * // Deep nested access with better type safety
1306
+ * const email = ExperimentalOption.genAdapter(function* ($) {
1307
+ * const user = yield* $(ExperimentalOption.fromNullable(apiResponse?.user));
1308
+ * const profile = yield* $(ExperimentalOption.fromNullable(user?.profile));
1309
+ * const contact = yield* $(ExperimentalOption.fromNullable(profile?.contact));
1310
+ * return contact?.email;
1311
+ * });
1312
+ *
1313
+ * // Complex validation chain
1314
+ * const validConfig = ExperimentalOption.genAdapter(function* ($) {
1315
+ * const raw = yield* $(loadConfig());
1316
+ * const parsed = yield* $(parseConfig(raw));
1317
+ * const validated = yield* $(validateConfig(parsed));
1318
+ * return validated;
1319
+ * });
1320
+ * ```
1321
+ *
1322
+ * @see {@link gen} for simpler chains without adapter
1323
+ * @see {@link asyncGenAdapter} for async operations
1324
+ */
1325
+ static genAdapter(genFn) {
1326
+ const adapter = (option) => new OptionYieldWrap(option);
1327
+ const iterator = genFn(adapter);
1328
+ let nextArg;
1329
+ let currentResult;
1330
+ while (true) {
1331
+ const next = iterator.next(nextArg);
1332
+ if (next.done) {
1333
+ currentResult = ExperimentalOption.Some(next.value);
1334
+ break;
1335
+ }
1336
+ let option = next.value.option;
1337
+ if (require_utils.isCapturedTrace(option)) option = option.value;
1338
+ if (option.isNone()) {
1339
+ iterator.return?.(void 0);
1340
+ currentResult = ExperimentalOption.None;
1341
+ break;
1342
+ }
1343
+ nextArg = option.unwrap();
1344
+ }
1345
+ return currentResult;
1346
+ }
1347
+ /**
1348
+ * Async generator-based syntax for chaining ExperimentalOption operations (simplified, no adapter).
1349
+ *
1350
+ * Use `yield*` with `ExperimentalOption<T>` values directly. For `Promise<ExperimentalOption<T>>`,
1351
+ * await first then `yield*`.
1352
+ *
1353
+ * Short-circuits on first `None`, returning singleton `None`. Uses async iteration
1354
+ * instead of recursion to avoid stack overflow on deep chains.
1355
+ *
1356
+ * @template T - The return type of the generator
1357
+ * @param genFn - An async generator function that yields ExperimentalOptions
1358
+ * @returns `Promise<Some<T>>` with the generator's return value, or `Promise<None>`
1359
+ *
1360
+ * @example
1361
+ * ```ts
1362
+ * // Simple async chain
1363
+ * const result = await ExperimentalOption.asyncGen(async function* () {
1364
+ * const a = yield* ExperimentalOption.Some(1);
1365
+ * const b = yield* await asyncOperation(a); // await Promise<ExperimentalOption> first
1366
+ * const c = yield* ExperimentalOption.Some(3);
1367
+ * return a + b + c;
1368
+ * });
1369
+ * // Some(result)
1370
+ *
1371
+ * // None short-circuit in async
1372
+ * const shortCircuit = await ExperimentalOption.asyncGen(async function* () {
1373
+ * const data = yield* await fetchOptionalData();
1374
+ * const parsed = yield* parse(data); // Short-circuits on None
1375
+ * const validated = yield* validate(parsed); // Never executes
1376
+ * return validated;
1377
+ * });
1378
+ * // None
1379
+ *
1380
+ * // Mixed sync/async workflow
1381
+ * const result = await ExperimentalOption.asyncGen(async function* () {
1382
+ * const id = yield* ExperimentalOption.Some(parseInt(input)); // sync
1383
+ * const user = yield* await fetchUser(id); // async
1384
+ * const profile = yield* ExperimentalOption.fromNullable(user?.profile); // sync
1385
+ * const enriched = yield* await enrichProfile(profile); // async
1386
+ * return enriched;
1387
+ * });
1388
+ *
1389
+ * // Complex pipeline with multiple optional steps
1390
+ * async function processLead(email: string): Promise<ExperimentalOption<Lead>> {
1391
+ * return await ExperimentalOption.asyncGen(async function* () {
1392
+ * const normalized = yield* ExperimentalOption.Some(normalizeEmail(email));
1393
+ * const existing = yield* await findExistingLead(normalized);
1394
+ * const enriched = yield* await enrichLeadData(existing);
1395
+ * const validated = yield* validateLead(enriched);
1396
+ * return validated;
1397
+ * });
1398
+ * }
1399
+ * ```
1400
+ *
1401
+ * @see {@link asyncGenAdapter} for better type inference and cleaner syntax
1402
+ * @see {@link gen} for synchronous operations
1403
+ */
1404
+ static async asyncGen(genFn) {
1405
+ const iterator = genFn();
1406
+ let nextArg;
1407
+ let currentResult;
1408
+ while (true) {
1409
+ const next = await iterator.next(nextArg);
1410
+ if (next.done) {
1411
+ currentResult = ExperimentalOption.Some(next.value);
1412
+ break;
1413
+ }
1414
+ let option = next.value;
1415
+ if (require_utils.isCapturedTrace(option)) option = option.value;
1416
+ if (option.isNone()) {
1417
+ await iterator.return?.(void 0);
1418
+ currentResult = ExperimentalOption.None;
1419
+ break;
1420
+ }
1421
+ nextArg = await option.unwrap();
1422
+ }
1423
+ return currentResult;
1424
+ }
1425
+ /**
1426
+ * Async generator-based syntax for chaining ExperimentalOption operations with an adapter function.
1427
+ *
1428
+ * The `$` adapter handles both sync `ExperimentalOption<T>` and async `Promise<ExperimentalOption<T>>`,
1429
+ * automatically awaiting promises. This provides cleaner syntax for mixed sync/async workflows.
1430
+ *
1431
+ * Short-circuits on first `None`, returning singleton `None`. Uses async iteration
1432
+ * instead of recursion to avoid stack overflow on deep chains.
1433
+ *
1434
+ * @template Eff - The effect type (inferred from usage)
1435
+ * @template T - The return type of the generator
1436
+ * @param genFn - An async generator function receiving an adapter `$`
1437
+ * @returns `Promise<Some<T>>` with the generator's return value, or `Promise<None>`
1438
+ *
1439
+ * @example
1440
+ * ```ts
1441
+ * // No need to manually await - adapter handles it
1442
+ * const result = await ExperimentalOption.asyncGenAdapter(async function* ($) {
1443
+ * const a = yield* $(ExperimentalOption.Some(1)); // sync ExperimentalOption
1444
+ * const b = yield* $(asyncOperation(a)); // Promise<ExperimentalOption> - auto-awaited
1445
+ * const c = yield* $(ExperimentalOption.Some(3));
1446
+ * return a + b + c;
1447
+ * });
1448
+ *
1449
+ * // Complex workflow with database and API calls
1450
+ * const userData = await ExperimentalOption.asyncGenAdapter(async function* ($) {
1451
+ * const session = yield* $(getSession()); // Promise<ExperimentalOption<Session>>
1452
+ * const userId = yield* $(ExperimentalOption.fromNullable(session?.userId));
1453
+ * const profile = yield* $(await fetchProfile(userId)); // Promise<ExperimentalOption<Profile>>
1454
+ * const preferences = yield* $(ExperimentalOption.fromNullable(profile?.preferences));
1455
+ * const enriched = yield* $(await enrichPreferences(preferences));
1456
+ * return enriched;
1457
+ * });
1458
+ *
1459
+ * // Real-world: Optional data enrichment
1460
+ * async function getProductDetails(productId: string): Promise<ExperimentalOption<ProductDetails>> {
1461
+ * return await ExperimentalOption.asyncGenAdapter(async function* ($) {
1462
+ * const product = yield* $(await fetchProduct(productId));
1463
+ * const pricing = yield* $(await fetchPricing(product.sku));
1464
+ * const inventory = yield* $(await checkInventory(product.id));
1465
+ * const reviews = yield* $(await fetchReviews(product.id));
1466
+ * const related = yield* $(await fetchRelatedProducts(product.category));
1467
+ *
1468
+ * return { product, pricing, inventory, reviews, related };
1469
+ * });
1470
+ * }
1471
+ * ```
1472
+ *
1473
+ * @see {@link asyncGen} when you want explicit `await` for async operations
1474
+ * @see {@link genAdapter} for synchronous operations
1475
+ */
1476
+ static async asyncGenAdapter(genFn) {
1477
+ const adapter = (option) => new AsyncOptionYieldWrap(option);
1478
+ const iterator = genFn(adapter);
1479
+ let nextArg;
1480
+ let currentResult;
1481
+ while (true) {
1482
+ const next = await iterator.next(nextArg);
1483
+ if (next.done) {
1484
+ currentResult = ExperimentalOption.Some(next.value);
1485
+ break;
1486
+ }
1487
+ let option = await next.value.option;
1488
+ if (require_utils.isCapturedTrace(option)) option = option.value;
1489
+ if (option.isNone()) {
1490
+ await iterator.return?.(void 0);
1491
+ currentResult = ExperimentalOption.None;
1492
+ break;
1493
+ }
1494
+ nextArg = await option.unwrap();
1495
+ }
1496
+ return currentResult;
1497
+ }
1498
+ };
1499
+
1500
+ //#endregion
1501
+ exports.ExperimentalOption = ExperimentalOption;
1502
+ exports.UnwrappedNone = UnwrappedNone;
1503
+ //# sourceMappingURL=option-experimental.cjs.map