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