@carbonteq/fp 0.9.1 → 0.11.1

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