@carbonteq/fp 0.8.2 → 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 (195) hide show
  1. package/README.md +718 -95
  2. package/dist/errors.cjs +20 -0
  3. package/dist/errors.cjs.map +1 -0
  4. package/dist/errors.d.cts +10 -0
  5. package/dist/errors.d.cts.map +1 -0
  6. package/dist/errors.d.mts +10 -0
  7. package/dist/errors.d.mts.map +1 -0
  8. package/dist/errors.mjs +17 -0
  9. package/dist/errors.mjs.map +1 -0
  10. package/dist/flow-experimental.cjs +286 -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 +284 -0
  17. package/dist/flow-experimental.mjs.map +1 -0
  18. package/dist/flow.cjs +296 -0
  19. package/dist/flow.cjs.map +1 -0
  20. package/dist/flow.d.cts +79 -0
  21. package/dist/flow.d.cts.map +1 -0
  22. package/dist/flow.d.mts +79 -0
  23. package/dist/flow.d.mts.map +1 -0
  24. package/dist/flow.mjs +294 -0
  25. package/dist/flow.mjs.map +1 -0
  26. package/dist/index.cjs +28 -7
  27. package/dist/index.d.cts +11 -5
  28. package/dist/index.d.mts +11 -0
  29. package/dist/index.mjs +12 -0
  30. package/dist/match.cjs +294 -3
  31. package/dist/match.cjs.map +1 -0
  32. package/dist/match.d.cts +481 -5
  33. package/dist/match.d.cts.map +1 -0
  34. package/dist/match.d.mts +481 -0
  35. package/dist/match.d.mts.map +1 -0
  36. package/dist/match.mjs +287 -0
  37. package/dist/match.mjs.map +1 -0
  38. package/dist/option-experimental.cjs +1503 -0
  39. package/dist/option-experimental.cjs.map +1 -0
  40. package/dist/option-experimental.d.cts +1383 -0
  41. package/dist/option-experimental.d.cts.map +1 -0
  42. package/dist/option-experimental.d.mts +1383 -0
  43. package/dist/option-experimental.d.mts.map +1 -0
  44. package/dist/option-experimental.mjs +1501 -0
  45. package/dist/option-experimental.mjs.map +1 -0
  46. package/dist/option.cjs +806 -4
  47. package/dist/option.cjs.map +1 -0
  48. package/dist/option.d.cts +580 -3
  49. package/dist/option.d.cts.map +1 -0
  50. package/dist/option.d.mts +580 -0
  51. package/dist/option.d.mts.map +1 -0
  52. package/dist/option.mjs +805 -0
  53. package/dist/option.mjs.map +1 -0
  54. package/dist/result-experimental.cjs +1266 -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 +1265 -0
  61. package/dist/result-experimental.mjs.map +1 -0
  62. package/dist/result.cjs +1077 -5
  63. package/dist/result.cjs.map +1 -0
  64. package/dist/result.d.cts +833 -3
  65. package/dist/result.d.cts.map +1 -0
  66. package/dist/result.d.mts +833 -0
  67. package/dist/result.d.mts.map +1 -0
  68. package/dist/result.mjs +1077 -0
  69. package/dist/result.mjs.map +1 -0
  70. package/dist/tuple.cjs +3 -0
  71. package/dist/tuple.cjs.map +1 -1
  72. package/dist/tuple.d.cts +5 -2
  73. package/dist/tuple.d.cts.map +1 -1
  74. package/dist/tuple.d.mts +15 -0
  75. package/dist/tuple.d.mts.map +1 -0
  76. package/dist/{tuple.js → tuple.mjs} +3 -1
  77. package/dist/tuple.mjs.map +1 -0
  78. package/dist/unit.cjs +8 -2
  79. package/dist/unit.cjs.map +1 -0
  80. package/dist/unit.d.cts +8 -2
  81. package/dist/unit.d.cts.map +1 -0
  82. package/dist/unit.d.mts +8 -0
  83. package/dist/unit.d.mts.map +1 -0
  84. package/dist/unit.mjs +7 -0
  85. package/dist/unit.mjs.map +1 -0
  86. package/dist/utils.cjs +24 -0
  87. package/dist/utils.cjs.map +1 -0
  88. package/dist/utils.d.cts +14 -0
  89. package/dist/utils.d.cts.map +1 -0
  90. package/dist/utils.d.mts +14 -0
  91. package/dist/utils.d.mts.map +1 -0
  92. package/dist/utils.mjs +20 -0
  93. package/dist/utils.mjs.map +1 -0
  94. package/examples/README.md +46 -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 +237 -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 +241 -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 +147 -0
  108. package/examples/match/index.ts +19 -0
  109. package/examples/match-experimental/01-experimental-match.ts +150 -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 +120 -48
  150. package/dist/chunk-CUT6urMc.cjs +0 -30
  151. package/dist/index.d.ts +0 -5
  152. package/dist/index.js +0 -6
  153. package/dist/match-BQP0RNSk.js +0 -13
  154. package/dist/match-BQP0RNSk.js.map +0 -1
  155. package/dist/match-COIWq-e8.d.cts +0 -18
  156. package/dist/match-COIWq-e8.d.cts.map +0 -1
  157. package/dist/match-DXKW7ym5.d.ts +0 -18
  158. package/dist/match-DXKW7ym5.d.ts.map +0 -1
  159. package/dist/match-DyAuOeqx.cjs +0 -25
  160. package/dist/match-DyAuOeqx.cjs.map +0 -1
  161. package/dist/match.d.ts +0 -5
  162. package/dist/match.js +0 -3
  163. package/dist/option-8_eiz02z.d.cts +0 -45
  164. package/dist/option-8_eiz02z.d.cts.map +0 -1
  165. package/dist/option-Be_DXVE6.js +0 -181
  166. package/dist/option-Be_DXVE6.js.map +0 -1
  167. package/dist/option-CoelyMEg.d.ts +0 -45
  168. package/dist/option-CoelyMEg.d.ts.map +0 -1
  169. package/dist/option-DHCdfOco.cjs +0 -193
  170. package/dist/option-DHCdfOco.cjs.map +0 -1
  171. package/dist/option.d.ts +0 -3
  172. package/dist/option.js +0 -4
  173. package/dist/result-CdGWA5IL.js +0 -318
  174. package/dist/result-CdGWA5IL.js.map +0 -1
  175. package/dist/result-DsVjSFnO.d.ts +0 -132
  176. package/dist/result-DsVjSFnO.d.ts.map +0 -1
  177. package/dist/result-Dy_C5dC6.d.cts +0 -132
  178. package/dist/result-Dy_C5dC6.d.cts.map +0 -1
  179. package/dist/result-nuhyCRyu.cjs +0 -336
  180. package/dist/result-nuhyCRyu.cjs.map +0 -1
  181. package/dist/result.d.ts +0 -3
  182. package/dist/result.js +0 -4
  183. package/dist/tuple.d.ts +0 -12
  184. package/dist/tuple.d.ts.map +0 -1
  185. package/dist/tuple.js.map +0 -1
  186. package/dist/unit-CnjFzJN1.cjs +0 -12
  187. package/dist/unit-CnjFzJN1.cjs.map +0 -1
  188. package/dist/unit-CoBLIJFc.d.ts +0 -9
  189. package/dist/unit-CoBLIJFc.d.ts.map +0 -1
  190. package/dist/unit-D0y_qAUW.d.cts +0 -9
  191. package/dist/unit-D0y_qAUW.d.cts.map +0 -1
  192. package/dist/unit-udy5j53P.js +0 -6
  193. package/dist/unit-udy5j53P.js.map +0 -1
  194. package/dist/unit.d.ts +0 -2
  195. package/dist/unit.js +0 -3
package/dist/option.cjs CHANGED
@@ -1,5 +1,807 @@
1
- require('./unit-CnjFzJN1.cjs');
2
- const require_option = require('./option-DHCdfOco.cjs');
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 = require('./result.cjs');
3
5
 
4
- exports.Option = require_option.Option;
5
- exports.UnwrappedNone = require_option.UnwrappedNone;
6
+ //#region src/option.ts
7
+ var UnwrappedNone = class extends Error {
8
+ name = "UnwrapError";
9
+ constructor() {
10
+ super("Attempted to unwrap Option::None");
11
+ }
12
+ };
13
+ const UNWRAPPED_NONE_ERR = new UnwrappedNone();
14
+ const NONE_VAL = Symbol("Option::None");
15
+ /**
16
+ * Wrapper that makes Option yieldable with proper type tracking.
17
+ *
18
+ * @internal
19
+ */
20
+ var OptionYieldWrap = class {
21
+ constructor(option) {
22
+ this.option = option;
23
+ }
24
+ *[Symbol.iterator]() {
25
+ return yield this;
26
+ }
27
+ };
28
+ /**
29
+ * Wrapper that makes Option yieldable in async generators with proper type tracking.
30
+ *
31
+ * @internal
32
+ */
33
+ var AsyncOptionYieldWrap = class {
34
+ option;
35
+ constructor(option) {
36
+ this.option = require_utils.isPromiseLike(option) ? option : Promise.resolve(option);
37
+ }
38
+ async *[Symbol.asyncIterator]() {
39
+ return yield this;
40
+ }
41
+ };
42
+ /**
43
+ * Represents an optional value: `Some<T>` or `None`.
44
+ * Provides composable, null-safe transformation and chaining methods.
45
+ */
46
+ var Option = class Option {
47
+ /** Discriminant tag for type-level identification */
48
+ _tag;
49
+ #ctx;
50
+ #val;
51
+ /**
52
+ * Creates a new Option instance with internal context.
53
+ *
54
+ * @param val - Stored value or sentinel
55
+ * @param ctx - Internal async tracking context
56
+ * @param tag - Discriminant tag for Some/None
57
+ *
58
+ * @internal
59
+ */
60
+ constructor(val, ctx, tag) {
61
+ this.#val = val;
62
+ this.#ctx = ctx;
63
+ this._tag = tag;
64
+ }
65
+ /** Singleton None instance */
66
+ static None = new Option(NONE_VAL, { promiseNoneSlot: true }, "None");
67
+ /**
68
+ * Creates a Some variant containing the provided value.
69
+ *
70
+ * @template Inner - Type of the wrapped value
71
+ * @param val - Value to wrap in Some
72
+ * @returns Option in the Some state
73
+ */
74
+ static Some(val) {
75
+ return new Option(val, { promiseNoneSlot: false }, "Some");
76
+ }
77
+ /**
78
+ * Creates an Option from a nullable value, returning None for null/undefined.
79
+ *
80
+ * @template T - Input type that may include null/undefined
81
+ * @param val - Value to convert
82
+ * @returns Some for non-nullish values, otherwise None
83
+ */
84
+ static fromNullable(val) {
85
+ return val === null || val === void 0 ? Option.None : Option.Some(val);
86
+ }
87
+ /**
88
+ * Creates an Option from a potentially falsy value, returning None for falsy.
89
+ *
90
+ * Treats false, 0, "", null, and undefined as absence.
91
+ *
92
+ * @template T - Input type
93
+ * @param val - Value to convert
94
+ * @returns Some for truthy values, otherwise None
95
+ */
96
+ static fromFalsy(val) {
97
+ return val ? Option.Some(val) : Option.None;
98
+ }
99
+ /**
100
+ * Creates an Option based on a predicate.
101
+ *
102
+ * @template T - Input type
103
+ * @param val - Value to test
104
+ * @param pred - Predicate to decide Some vs None
105
+ * @returns Some when predicate passes, otherwise None
106
+ */
107
+ static fromPredicate(val, pred) {
108
+ return pred(val) ? Option.Some(val) : Option.None;
109
+ }
110
+ /**
111
+ * Wraps a Promise<Option<T>> as Option<Promise<T>>.
112
+ *
113
+ * NOTE: the returned value starts as `Some(Promise<T>)`; final `None` is known
114
+ * only after settlement. Use `toPromise()` (or await `unwrap`/`safeUnwrap`) to
115
+ * observe settled absence.
116
+ *
117
+ * @template U - Inner value type
118
+ * @param o - Promise resolving to an Option
119
+ * @returns Option containing a Promise of the inner value
120
+ */
121
+ static fromPromise(o) {
122
+ const ctx = { promiseNoneSlot: false };
123
+ return new Option(new Promise((resolve, reject) => o.then((innerOpt) => {
124
+ if (innerOpt.isNone()) ctx.promiseNoneSlot = true;
125
+ resolve(innerOpt.#val);
126
+ }, reject)), ctx, "Some");
127
+ }
128
+ /**
129
+ * Combines multiple Options into a single Option of an array.
130
+ *
131
+ * Returns Some of all values if all inputs are Some; otherwise None.
132
+ *
133
+ * @template T - Variadic tuple of Option types
134
+ * @param options - Options to combine
135
+ * @returns Some of tuple values, or None if any input is None
136
+ */
137
+ static all(...options) {
138
+ const vals = [];
139
+ for (const opt of options) {
140
+ if (opt.isNone()) return Option.None;
141
+ vals.push(opt.#val);
142
+ }
143
+ return Option.Some(vals);
144
+ }
145
+ /**
146
+ * Returns the first Some in the list, or None if all are None.
147
+ *
148
+ * For async Some values, settlement is awaited and selection follows input order.
149
+ *
150
+ * @template T - Value type
151
+ * @param options - Options to search
152
+ * @returns The first Some found, otherwise None
153
+ */
154
+ static any(...options) {
155
+ const pending = [];
156
+ for (const opt of options) if (opt.isSome()) {
157
+ if (require_utils.isPromiseLike(opt.#val)) {
158
+ pending.push(opt);
159
+ continue;
160
+ }
161
+ return opt;
162
+ }
163
+ if (pending.length === 0) return Option.None;
164
+ const ctx = { promiseNoneSlot: false };
165
+ return new Option(Promise.all(pending.map(async (opt) => {
166
+ const val = await opt.#val;
167
+ return {
168
+ isNone: opt.#ctx.promiseNoneSlot || val === NONE_VAL,
169
+ val
170
+ };
171
+ })).then((settled) => {
172
+ for (const item of settled) if (!item.isNone) return item.val;
173
+ ctx.promiseNoneSlot = true;
174
+ return NONE_VAL;
175
+ }), ctx, "Some");
176
+ }
177
+ /**
178
+ * Type guard that narrows to Some.
179
+ *
180
+ * @returns true if this Option is Some
181
+ */
182
+ isSome() {
183
+ return this._tag === "Some" && !this.isNone();
184
+ }
185
+ /**
186
+ * Type guard that narrows to None.
187
+ *
188
+ * Includes async None tracking for Option<Promise<T>>.
189
+ *
190
+ * @returns true if this Option is None
191
+ */
192
+ isNone() {
193
+ return this._tag === "None" || this.#val === NONE_VAL || require_utils.isPromiseLike(this.#val) && this.#ctx.promiseNoneSlot;
194
+ }
195
+ /**
196
+ * Type guard for the UNIT sentinel value.
197
+ *
198
+ * @returns true if the contained value is UNIT
199
+ */
200
+ isUnit() {
201
+ return this.#val === require_unit.UNIT;
202
+ }
203
+ unwrap() {
204
+ if (this.isNone()) throw UNWRAPPED_NONE_ERR;
205
+ const curr = this.#val;
206
+ if (require_utils.isPromiseLike(curr)) {
207
+ const ctx = this.#ctx;
208
+ return curr.then((value) => {
209
+ if (value === NONE_VAL || ctx.promiseNoneSlot) throw UNWRAPPED_NONE_ERR;
210
+ return value;
211
+ });
212
+ }
213
+ return curr;
214
+ }
215
+ /**
216
+ * Returns the contained value or the provided default.
217
+ *
218
+ * @param defaultValue - Value to use when None
219
+ * @returns The contained value or default
220
+ */
221
+ unwrapOr(defaultValue) {
222
+ if (this.isNone()) return defaultValue;
223
+ return this.#val;
224
+ }
225
+ /**
226
+ * Returns the contained value or computes a default lazily.
227
+ *
228
+ * @param fn - Default factory invoked only when None
229
+ * @returns The contained value or computed default
230
+ */
231
+ unwrapOrElse(fn) {
232
+ if (this.isNone()) return fn();
233
+ return this.#val;
234
+ }
235
+ safeUnwrap() {
236
+ if (this.isNone()) return null;
237
+ const curr = this.#val;
238
+ if (require_utils.isPromiseLike(curr)) {
239
+ const ctx = this.#ctx;
240
+ return curr.then((value) => value === NONE_VAL || ctx.promiseNoneSlot ? null : value);
241
+ }
242
+ return curr;
243
+ }
244
+ /**
245
+ * Exhaustive pattern match on Option state.
246
+ *
247
+ * @template U - Result type
248
+ * @param cases - Handlers for Some and None
249
+ * @returns Result of the matching handler
250
+ */
251
+ match(cases) {
252
+ if (this.isNone()) return cases.None();
253
+ return cases.Some(this.#val);
254
+ }
255
+ map(mapper) {
256
+ if (this.isNone()) return Option.None;
257
+ const curr = this.#val;
258
+ if (require_utils.isPromiseLike(curr)) {
259
+ const p = curr;
260
+ const newCtx = { promiseNoneSlot: false };
261
+ return new Option(Option.safeMap(p, mapper, newCtx), newCtx, "Some");
262
+ }
263
+ const transformed = mapper(curr);
264
+ if (require_utils.isPromiseLike(transformed)) return new Option(transformed, { promiseNoneSlot: false }, "Some");
265
+ return new Option(transformed, { promiseNoneSlot: false }, "Some");
266
+ }
267
+ /**
268
+ * Safely maps a promised value while tracking None in async context.
269
+ *
270
+ * @template Curr - Input value type
271
+ * @template U - Output value type
272
+ * @param p - Promise to map over
273
+ * @param mapper - Transform function
274
+ * @param ctx - Async context for None tracking
275
+ * @returns Promise of the transformed value or sentinel
276
+ */
277
+ static safeMap(p, mapper, ctx) {
278
+ return p.then((v) => {
279
+ if (v === NONE_VAL) {
280
+ ctx.promiseNoneSlot = true;
281
+ return NONE_VAL;
282
+ }
283
+ return mapper(v);
284
+ });
285
+ }
286
+ mapOr(defaultVal, fn) {
287
+ if (this.isNone()) return require_utils.isPromiseLike(this.#val) ? Promise.resolve(defaultVal) : defaultVal;
288
+ const curr = this.#val;
289
+ if (require_utils.isPromiseLike(curr)) {
290
+ const p = curr;
291
+ const ctx = this.#ctx;
292
+ return p.then(async (v) => {
293
+ if (v === NONE_VAL || ctx.promiseNoneSlot) return defaultVal;
294
+ return fn(v);
295
+ });
296
+ }
297
+ return fn(curr);
298
+ }
299
+ flatMap(mapper) {
300
+ if (this.isNone()) return Option.None;
301
+ const curr = this.#val;
302
+ if (require_utils.isPromiseLike(curr)) {
303
+ const p = curr;
304
+ const newCtx = { promiseNoneSlot: false };
305
+ const castedNone = NONE_VAL;
306
+ return new Option(new Promise((resolve, reject) => {
307
+ p.then((innerVal) => {
308
+ if (innerVal === NONE_VAL) {
309
+ newCtx.promiseNoneSlot = true;
310
+ resolve(castedNone);
311
+ } else {
312
+ const r = mapper(innerVal);
313
+ if (require_utils.isPromiseLike(r)) r.then((innerOpt) => {
314
+ if (innerOpt.isNone()) newCtx.promiseNoneSlot = true;
315
+ resolve(innerOpt.#val);
316
+ }, reject);
317
+ else if (r.isNone()) {
318
+ newCtx.promiseNoneSlot = true;
319
+ resolve(NONE_VAL);
320
+ } else resolve(r.#val);
321
+ }
322
+ }, reject);
323
+ }), newCtx, "Some");
324
+ }
325
+ const mapped = mapper(curr);
326
+ if (require_utils.isPromiseLike(mapped)) return Option.fromPromise(mapped);
327
+ return mapped;
328
+ }
329
+ filter(pred) {
330
+ if (this.isNone()) return Option.None;
331
+ const curr = this.#val;
332
+ if (require_utils.isPromiseLike(curr)) {
333
+ const p = curr;
334
+ const newCtx = { promiseNoneSlot: false };
335
+ return new Option(p.then(async (v) => {
336
+ if (v === NONE_VAL) {
337
+ newCtx.promiseNoneSlot = true;
338
+ return NONE_VAL;
339
+ }
340
+ if (!await pred(v)) {
341
+ newCtx.promiseNoneSlot = true;
342
+ return NONE_VAL;
343
+ }
344
+ return v;
345
+ }), newCtx, "Some");
346
+ }
347
+ const result = pred(curr);
348
+ if (require_utils.isPromiseLike(result)) {
349
+ const newCtx = { promiseNoneSlot: false };
350
+ return new Option(result.then((passed) => {
351
+ if (passed) return curr;
352
+ newCtx.promiseNoneSlot = true;
353
+ return NONE_VAL;
354
+ }), newCtx, "Some");
355
+ }
356
+ return result ? this : Option.None;
357
+ }
358
+ zip(fn) {
359
+ if (this.isNone()) return Option.None;
360
+ const curr = this.#val;
361
+ if (require_utils.isPromiseLike(curr)) {
362
+ const val = curr;
363
+ const newCtx = { promiseNoneSlot: false };
364
+ return new Option(val.then(async (v) => {
365
+ if (v === NONE_VAL) {
366
+ newCtx.promiseNoneSlot = true;
367
+ return NONE_VAL;
368
+ }
369
+ return [v, await fn(v)];
370
+ }), newCtx, "Some");
371
+ }
372
+ const value = curr;
373
+ const u = fn(value);
374
+ if (require_utils.isPromiseLike(u)) return new Option(u.then((uu) => [value, uu]), { promiseNoneSlot: false }, "Some");
375
+ return new Option([value, u], { promiseNoneSlot: false }, "Some");
376
+ }
377
+ flatZip(fn) {
378
+ if (this.isNone()) return Option.None;
379
+ const curr = this.#val;
380
+ if (require_utils.isPromiseLike(curr)) {
381
+ const val = curr;
382
+ const newCtx = { promiseNoneSlot: false };
383
+ return new Option(val.then(async (v) => {
384
+ if (v === NONE_VAL) {
385
+ newCtx.promiseNoneSlot = true;
386
+ return NONE_VAL;
387
+ }
388
+ const next = await fn(v);
389
+ if (next.isNone()) {
390
+ newCtx.promiseNoneSlot = true;
391
+ return NONE_VAL;
392
+ }
393
+ return [v, next.#val];
394
+ }), newCtx, "Some");
395
+ }
396
+ const c = curr;
397
+ const u = fn(c);
398
+ if (require_utils.isPromiseLike(u)) {
399
+ const newCtx = { promiseNoneSlot: false };
400
+ return new Option(u.then((uu) => {
401
+ if (uu.isNone()) {
402
+ newCtx.promiseNoneSlot = true;
403
+ return NONE_VAL;
404
+ }
405
+ return [c, uu.#val];
406
+ }), newCtx, "Some");
407
+ }
408
+ return u.map((inner) => [c, inner]);
409
+ }
410
+ /**
411
+ * Executes a side effect for Some values and returns self.
412
+ *
413
+ * For `Option<Promise<T>>`, `tap` receives the wrapped promise object,
414
+ * not the settled inner value.
415
+ *
416
+ * @param fn - Side effect function
417
+ * @returns The same Option (chainable)
418
+ */
419
+ tap(fn) {
420
+ if (this.isSome()) fn(this.#val);
421
+ return this;
422
+ }
423
+ /**
424
+ * Converts this Option to a Result, using the provided error for None.
425
+ *
426
+ * @template E - Error type
427
+ * @param error - Error value for None
428
+ * @returns Ok with value when Some, otherwise Err with error
429
+ */
430
+ toResult(error) {
431
+ if (this.isNone()) return require_result.Result.Err(error);
432
+ return require_result.Result.Ok(this.#val);
433
+ }
434
+ /**
435
+ * Resolves the inner promise (if any) while preserving Option structure.
436
+ *
437
+ * @template Curr - Awaited value type
438
+ * @returns Promise of Option with awaited value, or None
439
+ */
440
+ async toPromise() {
441
+ if (this.isNone()) return Option.None;
442
+ const curr = this.#val;
443
+ let inner;
444
+ if (require_utils.isPromiseLike(curr)) {
445
+ const awaited = await curr;
446
+ if (awaited === NONE_VAL || this.#ctx.promiseNoneSlot) return Option.None;
447
+ inner = awaited;
448
+ } else inner = curr;
449
+ return new Option(inner, this.#ctx, "Some");
450
+ }
451
+ /**
452
+ * Maps over array elements inside an Option<Array<T>>.
453
+ *
454
+ * @template Inner - Array element type
455
+ * @template Out - Mapped element type
456
+ * @param mapper - Function to map each element
457
+ * @returns Option containing the mapped array
458
+ * @throws TypeError if called on a non-array value
459
+ */
460
+ innerMap(mapper) {
461
+ if (this.isNone()) return Option.None;
462
+ if (!Array.isArray(this.#val)) throw new TypeError("innerMap can only be called on Option<Array<T>>");
463
+ return new Option(this.#val.map(mapper), this.#ctx, "Some");
464
+ }
465
+ /**
466
+ * Returns a string representation of the Option.
467
+ *
468
+ * @returns "Option::None" or "Option::Some(value)"
469
+ */
470
+ toString() {
471
+ if (this.isNone()) return "Option::None";
472
+ return `Option::Some(${String(this.#val)})`;
473
+ }
474
+ /**
475
+ * Makes Option iterable for use with generator-based syntax.
476
+ *
477
+ * Yields self and returns the unwrapped value when resumed.
478
+ * Used internally by {@link Option.gen} for `yield*` syntax.
479
+ *
480
+ * @example
481
+ * ```ts
482
+ * const result = Option.gen(function* () {
483
+ * const value = yield* Option.Some(42);
484
+ * return value * 2;
485
+ * });
486
+ * // Some(84)
487
+ * ```
488
+ *
489
+ * @internal
490
+ */
491
+ *[Symbol.iterator]() {
492
+ const trace = (/* @__PURE__ */ new Error()).stack;
493
+ return yield new require_utils.CapturedTrace(this, trace);
494
+ }
495
+ /**
496
+ * Makes Option iterable for use with async generator-based syntax.
497
+ *
498
+ * Yields self and returns the unwrapped value when resumed.
499
+ * Used internally by {@link Option.asyncGen} for `yield*` syntax.
500
+ *
501
+ * @example
502
+ * ```ts
503
+ * const result = await Option.asyncGen(async function* () {
504
+ * const value = yield* await Promise.resolve(Option.Some(42));
505
+ * return value * 2;
506
+ * });
507
+ * // Some(84)
508
+ * ```
509
+ *
510
+ * @internal
511
+ */
512
+ async *[Symbol.asyncIterator]() {
513
+ const trace = (/* @__PURE__ */ new Error()).stack;
514
+ return yield new require_utils.CapturedTrace(this, trace);
515
+ }
516
+ /**
517
+ * Generator-based syntax for chaining Option operations (simplified, no adapter).
518
+ *
519
+ * Provides imperative-style code while maintaining functional Option handling.
520
+ * Use `yield*` to unwrap Options or short-circuit on `None`.
521
+ *
522
+ * Short-circuits on first `None`, returning singleton `None`. Uses iteration
523
+ * instead of recursion to avoid stack overflow on deep chains.
524
+ *
525
+ * @template T - The return type of the generator
526
+ * @param genFn - A generator function that yields Options
527
+ * @returns `Some<T>` with the generator's return value, or `None`
528
+ *
529
+ * @example
530
+ * ```ts
531
+ * // Simple sync chain
532
+ * const result = Option.gen(function* () {
533
+ * const a = yield* Option.Some(1);
534
+ * const b = yield* Option.Some(2);
535
+ * return a + b;
536
+ * });
537
+ * // Some(3)
538
+ *
539
+ * // None short-circuit
540
+ * const shortCircuit = Option.gen(function* () {
541
+ * const a = yield* Option.Some(1);
542
+ * const b = yield* Option.None; // Short-circuits here
543
+ * const c = yield* Option.Some(3); // Never executes
544
+ * return a + b + c;
545
+ * });
546
+ * // None
547
+ *
548
+ * // Chaining optional operations
549
+ * const email = Option.gen(function* () {
550
+ * const user = yield* findUser(userId);
551
+ * const profile = yield* Option.fromNullable(user.profile);
552
+ * const settings = yield* Option.fromNullable(profile.settings);
553
+ * return settings.email;
554
+ * });
555
+ *
556
+ * // Nested optional access
557
+ * const city = Option.gen(function* () {
558
+ * const user = yield* Option.fromNullable(getUser());
559
+ * const address = yield* Option.fromNullable(user?.address);
560
+ * const city = yield* Option.fromNullable(address?.city);
561
+ * return city;
562
+ * });
563
+ * ```
564
+ *
565
+ * @see {@link genAdapter} for better type inference in complex chains
566
+ * @see {@link asyncGen} for async operations
567
+ */
568
+ static gen(genFn) {
569
+ const iterator = genFn();
570
+ let nextArg;
571
+ let currentResult;
572
+ while (true) {
573
+ const next = iterator.next(nextArg);
574
+ if (next.done) {
575
+ currentResult = Option.Some(next.value);
576
+ break;
577
+ }
578
+ let yielded = next.value;
579
+ if (require_utils.isCapturedTrace(yielded)) yielded = yielded.value;
580
+ if (yielded.isNone()) {
581
+ currentResult = Option.None;
582
+ break;
583
+ }
584
+ nextArg = yielded.unwrap();
585
+ }
586
+ return currentResult;
587
+ }
588
+ /**
589
+ * Generator-based syntax for chaining Option operations with an adapter function.
590
+ *
591
+ * Provides better type inference and IDE support compared to {@link gen}.
592
+ * The `$` adapter wraps Options and enables clearer type tracking.
593
+ *
594
+ * Short-circuits on first `None`, returning singleton `None`. Uses iteration
595
+ * instead of recursion to avoid stack overflow on deep chains.
596
+ *
597
+ * @template Eff - The effect type (inferred from usage)
598
+ * @template T - The return type of the generator
599
+ * @param genFn - A generator function receiving an adapter `$`
600
+ * @returns `Some<T>` with the generator's return value, or `None`
601
+ *
602
+ * @example
603
+ * ```ts
604
+ * // Better type inference
605
+ * const result = Option.genAdapter(function* ($) {
606
+ * const a = yield* $(Option.Some(1));
607
+ * const b = yield* $(Option.Some(2));
608
+ * return a + b;
609
+ * });
610
+ * // Some(3)
611
+ *
612
+ * // Deep nested access with better type safety
613
+ * const email = Option.genAdapter(function* ($) {
614
+ * const user = yield* $(Option.fromNullable(apiResponse?.user));
615
+ * const profile = yield* $(Option.fromNullable(user?.profile));
616
+ * const contact = yield* $(Option.fromNullable(profile?.contact));
617
+ * return contact?.email;
618
+ * });
619
+ *
620
+ * // Complex validation chain
621
+ * const validConfig = Option.genAdapter(function* ($) {
622
+ * const raw = yield* $(loadConfig());
623
+ * const parsed = yield* $(parseConfig(raw));
624
+ * const validated = yield* $(validateConfig(parsed));
625
+ * return validated;
626
+ * });
627
+ * ```
628
+ *
629
+ * @see {@link gen} for simpler chains without adapter
630
+ * @see {@link asyncGenAdapter} for async operations
631
+ */
632
+ static genAdapter(genFn) {
633
+ const adapter = (option) => new OptionYieldWrap(option);
634
+ const iterator = genFn(adapter);
635
+ let nextArg;
636
+ let currentResult;
637
+ while (true) {
638
+ const next = iterator.next(nextArg);
639
+ if (next.done) {
640
+ currentResult = Option.Some(next.value);
641
+ break;
642
+ }
643
+ let option = next.value.option;
644
+ if (require_utils.isCapturedTrace(option)) option = option.value;
645
+ if (option.isNone()) {
646
+ currentResult = Option.None;
647
+ break;
648
+ }
649
+ nextArg = option.unwrap();
650
+ }
651
+ return currentResult;
652
+ }
653
+ /**
654
+ * Async generator-based syntax for chaining Option operations (simplified, no adapter).
655
+ *
656
+ * Use `yield*` with `Option<T>` values directly. For `Promise<Option<T>>`,
657
+ * await first then `yield*`.
658
+ *
659
+ * Short-circuits on first `None`, returning singleton `None`. Uses async iteration
660
+ * instead of recursion to avoid stack overflow on deep chains.
661
+ *
662
+ * @template T - The return type of the generator
663
+ * @param genFn - An async generator function that yields Options
664
+ * @returns `Promise<Some<T>>` with the generator's return value, or `Promise<None>`
665
+ *
666
+ * @example
667
+ * ```ts
668
+ * // Simple async chain
669
+ * const result = await Option.asyncGen(async function* () {
670
+ * const a = yield* Option.Some(1);
671
+ * const b = yield* await asyncOperation(a); // await Promise<Option> first
672
+ * const c = yield* Option.Some(3);
673
+ * return a + b + c;
674
+ * });
675
+ * // Some(result)
676
+ *
677
+ * // None short-circuit in async
678
+ * const shortCircuit = await Option.asyncGen(async function* () {
679
+ * const data = yield* await fetchOptionalData();
680
+ * const parsed = yield* parse(data); // Short-circuits on None
681
+ * const validated = yield* validate(parsed); // Never executes
682
+ * return validated;
683
+ * });
684
+ * // None
685
+ *
686
+ * // Mixed sync/async workflow
687
+ * const result = await Option.asyncGen(async function* () {
688
+ * const id = yield* Option.Some(parseInt(input)); // sync
689
+ * const user = yield* await fetchUser(id); // async
690
+ * const profile = yield* Option.fromNullable(user?.profile); // sync
691
+ * const enriched = yield* await enrichProfile(profile); // async
692
+ * return enriched;
693
+ * });
694
+ *
695
+ * // Complex pipeline with multiple optional steps
696
+ * async function processLead(email: string): Promise<Option<Lead>> {
697
+ * return await Option.asyncGen(async function* () {
698
+ * const normalized = yield* Option.Some(normalizeEmail(email));
699
+ * const existing = yield* await findExistingLead(normalized);
700
+ * const enriched = yield* await enrichLeadData(existing);
701
+ * const validated = yield* validateLead(enriched);
702
+ * return validated;
703
+ * });
704
+ * }
705
+ * ```
706
+ *
707
+ * @see {@link asyncGenAdapter} for better type inference and cleaner syntax
708
+ * @see {@link gen} for synchronous operations
709
+ */
710
+ static async asyncGen(genFn) {
711
+ const iterator = genFn();
712
+ let nextArg;
713
+ let currentResult;
714
+ while (true) {
715
+ const next = await iterator.next(nextArg);
716
+ if (next.done) {
717
+ currentResult = Option.Some(next.value);
718
+ break;
719
+ }
720
+ let option = next.value;
721
+ if (require_utils.isCapturedTrace(option)) option = option.value;
722
+ if (option.isNone()) {
723
+ currentResult = Option.None;
724
+ break;
725
+ }
726
+ nextArg = await option.unwrap();
727
+ }
728
+ return currentResult;
729
+ }
730
+ /**
731
+ * Async generator-based syntax for chaining Option operations with an adapter function.
732
+ *
733
+ * The `$` adapter handles both sync `Option<T>` and async `Promise<Option<T>>`,
734
+ * automatically awaiting promises. This provides cleaner syntax for mixed sync/async workflows.
735
+ *
736
+ * Short-circuits on first `None`, returning singleton `None`. Uses async iteration
737
+ * instead of recursion to avoid stack overflow on deep chains.
738
+ *
739
+ * @template Eff - The effect type (inferred from usage)
740
+ * @template T - The return type of the generator
741
+ * @param genFn - An async generator function receiving an adapter `$`
742
+ * @returns `Promise<Some<T>>` with the generator's return value, or `Promise<None>`
743
+ *
744
+ * @example
745
+ * ```ts
746
+ * // No need to manually await - adapter handles it
747
+ * const result = await Option.asyncGenAdapter(async function* ($) {
748
+ * const a = yield* $(Option.Some(1)); // sync Option
749
+ * const b = yield* $(asyncOperation(a)); // Promise<Option> - auto-awaited
750
+ * const c = yield* $(Option.Some(3));
751
+ * return a + b + c;
752
+ * });
753
+ *
754
+ * // Complex workflow with database and API calls
755
+ * const userData = await Option.asyncGenAdapter(async function* ($) {
756
+ * const session = yield* $(getSession()); // Promise<Option<Session>>
757
+ * const userId = yield* $(Option.fromNullable(session?.userId));
758
+ * const profile = yield* $(await fetchProfile(userId)); // Promise<Option<Profile>>
759
+ * const preferences = yield* $(Option.fromNullable(profile?.preferences));
760
+ * const enriched = yield* $(await enrichPreferences(preferences));
761
+ * return enriched;
762
+ * });
763
+ *
764
+ * // Real-world: Optional data enrichment
765
+ * async function getProductDetails(productId: string): Promise<Option<ProductDetails>> {
766
+ * return await Option.asyncGenAdapter(async function* ($) {
767
+ * const product = yield* $(await fetchProduct(productId));
768
+ * const pricing = yield* $(await fetchPricing(product.sku));
769
+ * const inventory = yield* $(await checkInventory(product.id));
770
+ * const reviews = yield* $(await fetchReviews(product.id));
771
+ * const related = yield* $(await fetchRelatedProducts(product.category));
772
+ *
773
+ * return { product, pricing, inventory, reviews, related };
774
+ * });
775
+ * }
776
+ * ```
777
+ *
778
+ * @see {@link asyncGen} when you want explicit `await` for async operations
779
+ * @see {@link genAdapter} for synchronous operations
780
+ */
781
+ static async asyncGenAdapter(genFn) {
782
+ const adapter = (option) => new AsyncOptionYieldWrap(option);
783
+ const iterator = genFn(adapter);
784
+ let nextArg;
785
+ let currentResult;
786
+ while (true) {
787
+ const next = await iterator.next(nextArg);
788
+ if (next.done) {
789
+ currentResult = Option.Some(next.value);
790
+ break;
791
+ }
792
+ let option = await next.value.option;
793
+ if (require_utils.isCapturedTrace(option)) option = option.value;
794
+ if (option.isNone()) {
795
+ currentResult = Option.None;
796
+ break;
797
+ }
798
+ nextArg = await option.unwrap();
799
+ }
800
+ return currentResult;
801
+ }
802
+ };
803
+
804
+ //#endregion
805
+ exports.Option = Option;
806
+ exports.UnwrappedNone = UnwrappedNone;
807
+ //# sourceMappingURL=option.cjs.map