@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.
- package/README.md +718 -95
- package/dist/errors.cjs +20 -0
- package/dist/errors.cjs.map +1 -0
- package/dist/errors.d.cts +10 -0
- package/dist/errors.d.cts.map +1 -0
- package/dist/errors.d.mts +10 -0
- package/dist/errors.d.mts.map +1 -0
- package/dist/errors.mjs +17 -0
- package/dist/errors.mjs.map +1 -0
- package/dist/flow-experimental.cjs +286 -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 +284 -0
- package/dist/flow-experimental.mjs.map +1 -0
- package/dist/flow.cjs +296 -0
- package/dist/flow.cjs.map +1 -0
- package/dist/flow.d.cts +79 -0
- package/dist/flow.d.cts.map +1 -0
- package/dist/flow.d.mts +79 -0
- package/dist/flow.d.mts.map +1 -0
- package/dist/flow.mjs +294 -0
- package/dist/flow.mjs.map +1 -0
- package/dist/index.cjs +28 -7
- package/dist/index.d.cts +11 -5
- package/dist/index.d.mts +11 -0
- package/dist/index.mjs +12 -0
- package/dist/match.cjs +294 -3
- package/dist/match.cjs.map +1 -0
- package/dist/match.d.cts +481 -5
- package/dist/match.d.cts.map +1 -0
- package/dist/match.d.mts +481 -0
- package/dist/match.d.mts.map +1 -0
- package/dist/match.mjs +287 -0
- package/dist/match.mjs.map +1 -0
- package/dist/option-experimental.cjs +1503 -0
- package/dist/option-experimental.cjs.map +1 -0
- package/dist/option-experimental.d.cts +1383 -0
- package/dist/option-experimental.d.cts.map +1 -0
- package/dist/option-experimental.d.mts +1383 -0
- package/dist/option-experimental.d.mts.map +1 -0
- package/dist/option-experimental.mjs +1501 -0
- package/dist/option-experimental.mjs.map +1 -0
- package/dist/option.cjs +806 -4
- package/dist/option.cjs.map +1 -0
- package/dist/option.d.cts +580 -3
- package/dist/option.d.cts.map +1 -0
- package/dist/option.d.mts +580 -0
- package/dist/option.d.mts.map +1 -0
- package/dist/option.mjs +805 -0
- package/dist/option.mjs.map +1 -0
- package/dist/result-experimental.cjs +1266 -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 +1265 -0
- package/dist/result-experimental.mjs.map +1 -0
- package/dist/result.cjs +1077 -5
- package/dist/result.cjs.map +1 -0
- package/dist/result.d.cts +833 -3
- package/dist/result.d.cts.map +1 -0
- package/dist/result.d.mts +833 -0
- package/dist/result.d.mts.map +1 -0
- package/dist/result.mjs +1077 -0
- package/dist/result.mjs.map +1 -0
- package/dist/tuple.cjs +3 -0
- package/dist/tuple.cjs.map +1 -1
- package/dist/tuple.d.cts +5 -2
- package/dist/tuple.d.cts.map +1 -1
- package/dist/tuple.d.mts +15 -0
- package/dist/tuple.d.mts.map +1 -0
- package/dist/{tuple.js → tuple.mjs} +3 -1
- package/dist/tuple.mjs.map +1 -0
- package/dist/unit.cjs +8 -2
- package/dist/unit.cjs.map +1 -0
- package/dist/unit.d.cts +8 -2
- package/dist/unit.d.cts.map +1 -0
- package/dist/unit.d.mts +8 -0
- package/dist/unit.d.mts.map +1 -0
- package/dist/unit.mjs +7 -0
- package/dist/unit.mjs.map +1 -0
- package/dist/utils.cjs +24 -0
- package/dist/utils.cjs.map +1 -0
- package/dist/utils.d.cts +14 -0
- package/dist/utils.d.cts.map +1 -0
- package/dist/utils.d.mts +14 -0
- package/dist/utils.d.mts.map +1 -0
- package/dist/utils.mjs +20 -0
- package/dist/utils.mjs.map +1 -0
- package/examples/README.md +46 -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 +237 -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 +241 -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 +147 -0
- package/examples/match/index.ts +19 -0
- package/examples/match-experimental/01-experimental-match.ts +150 -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 +120 -48
- package/dist/chunk-CUT6urMc.cjs +0 -30
- package/dist/index.d.ts +0 -5
- package/dist/index.js +0 -6
- package/dist/match-BQP0RNSk.js +0 -13
- package/dist/match-BQP0RNSk.js.map +0 -1
- package/dist/match-COIWq-e8.d.cts +0 -18
- package/dist/match-COIWq-e8.d.cts.map +0 -1
- package/dist/match-DXKW7ym5.d.ts +0 -18
- package/dist/match-DXKW7ym5.d.ts.map +0 -1
- package/dist/match-DyAuOeqx.cjs +0 -25
- package/dist/match-DyAuOeqx.cjs.map +0 -1
- package/dist/match.d.ts +0 -5
- package/dist/match.js +0 -3
- package/dist/option-8_eiz02z.d.cts +0 -45
- package/dist/option-8_eiz02z.d.cts.map +0 -1
- package/dist/option-Be_DXVE6.js +0 -181
- package/dist/option-Be_DXVE6.js.map +0 -1
- package/dist/option-CoelyMEg.d.ts +0 -45
- package/dist/option-CoelyMEg.d.ts.map +0 -1
- package/dist/option-DHCdfOco.cjs +0 -193
- package/dist/option-DHCdfOco.cjs.map +0 -1
- package/dist/option.d.ts +0 -3
- package/dist/option.js +0 -4
- package/dist/result-CdGWA5IL.js +0 -318
- package/dist/result-CdGWA5IL.js.map +0 -1
- package/dist/result-DsVjSFnO.d.ts +0 -132
- package/dist/result-DsVjSFnO.d.ts.map +0 -1
- package/dist/result-Dy_C5dC6.d.cts +0 -132
- package/dist/result-Dy_C5dC6.d.cts.map +0 -1
- package/dist/result-nuhyCRyu.cjs +0 -336
- package/dist/result-nuhyCRyu.cjs.map +0 -1
- package/dist/result.d.ts +0 -3
- package/dist/result.js +0 -4
- package/dist/tuple.d.ts +0 -12
- package/dist/tuple.d.ts.map +0 -1
- package/dist/tuple.js.map +0 -1
- package/dist/unit-CnjFzJN1.cjs +0 -12
- package/dist/unit-CnjFzJN1.cjs.map +0 -1
- package/dist/unit-CoBLIJFc.d.ts +0 -9
- package/dist/unit-CoBLIJFc.d.ts.map +0 -1
- package/dist/unit-D0y_qAUW.d.cts +0 -9
- package/dist/unit-D0y_qAUW.d.cts.map +0 -1
- package/dist/unit-udy5j53P.js +0 -6
- package/dist/unit-udy5j53P.js.map +0 -1
- package/dist/unit.d.ts +0 -2
- package/dist/unit.js +0 -3
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Async Flow - Unified Async Generator
|
|
3
|
+
*
|
|
4
|
+
* Handles Promise<Option>, Promise<Result>, and async operations.
|
|
5
|
+
* Uses ExperimentalOption and ExperimentalResult.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import {
|
|
9
|
+
ExperimentalFlow as Flow,
|
|
10
|
+
ExperimentalOption as Option,
|
|
11
|
+
ExperimentalResult as Result,
|
|
12
|
+
} from "../../dist/index.mjs"
|
|
13
|
+
|
|
14
|
+
type User = { id: number; name: string }
|
|
15
|
+
|
|
16
|
+
// Mock async functions
|
|
17
|
+
const fetchUser = async (id: number): Promise<Result<User, string>> => {
|
|
18
|
+
await new Promise((r) => setTimeout(r, 10))
|
|
19
|
+
return id === 1
|
|
20
|
+
? Result.Ok({ id, name: "Alice" })
|
|
21
|
+
: Result.Err("User not found")
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const fetchSettings = async (_userId: number) => {
|
|
25
|
+
await new Promise((r) => setTimeout(r, 10))
|
|
26
|
+
return Option.Some({ theme: "dark" })
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// ============================================================================
|
|
30
|
+
// Flow.asyncGen - Direct usage (requires explicit awaits)
|
|
31
|
+
// ============================================================================
|
|
32
|
+
|
|
33
|
+
const asyncDirect = await Flow.asyncGen(async function* () {
|
|
34
|
+
// 1. Await async Result function, then yield*
|
|
35
|
+
const user = yield* await fetchUser(1)
|
|
36
|
+
|
|
37
|
+
// 2. Await async Option function, then yield*
|
|
38
|
+
const settings = yield* await fetchSettings(user.id)
|
|
39
|
+
|
|
40
|
+
// 3. Sync yield works too
|
|
41
|
+
const bonus = yield* Option.Some(50)
|
|
42
|
+
|
|
43
|
+
return `${user.name} prefers ${settings.theme} theme (Bonus: ${bonus})`
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
console.log("Async Direct:", asyncDirect.unwrap())
|
|
47
|
+
|
|
48
|
+
// ============================================================================
|
|
49
|
+
// Flow.asyncGenAdapter - Adapter usage (cleaner syntax)
|
|
50
|
+
// ============================================================================
|
|
51
|
+
|
|
52
|
+
const asyncAdapter = await Flow.asyncGenAdapter(async function* ($) {
|
|
53
|
+
// 1. Wrap promise - adapter handles await automatically!
|
|
54
|
+
const user = yield* $(fetchUser(1))
|
|
55
|
+
|
|
56
|
+
// 2. Wrap another promise
|
|
57
|
+
const settings = yield* $(fetchSettings(user.id))
|
|
58
|
+
|
|
59
|
+
// 3. Wrap sync values
|
|
60
|
+
const multiplier = yield* $(Result.Ok<number, Error>(2))
|
|
61
|
+
|
|
62
|
+
return {
|
|
63
|
+
user,
|
|
64
|
+
settings,
|
|
65
|
+
score: 100 * multiplier,
|
|
66
|
+
}
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
console.log("Async Adapter:", asyncAdapter.safeUnwrap())
|
|
70
|
+
|
|
71
|
+
// Error propagation in Async
|
|
72
|
+
const asyncError = await Flow.asyncGenAdapter(async function* ($) {
|
|
73
|
+
const user = yield* $(fetchUser(999)) // Returns Err
|
|
74
|
+
return user // Not reached
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
console.log("Async Error:", asyncError.unwrapErr()) // "User not found"
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Flow - Error Recovery Patterns
|
|
3
|
+
*
|
|
4
|
+
* Examples of how to handle errors and perform recovery (orElse) within Flow generators.
|
|
5
|
+
* Uses ExperimentalResult.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import {
|
|
9
|
+
ExperimentalFlow as Flow,
|
|
10
|
+
ExperimentalResult as Result,
|
|
11
|
+
} from "../../dist/index.mjs"
|
|
12
|
+
|
|
13
|
+
// Mock operations
|
|
14
|
+
const mayFail = (id: number): Result<number, string> =>
|
|
15
|
+
id > 0 ? Result.Ok(id) : Result.Err("Invalid ID")
|
|
16
|
+
|
|
17
|
+
const recover = (_err: string): Result<number, string> => Result.Ok(0) // Default to 0
|
|
18
|
+
|
|
19
|
+
const complexRecovery = async (
|
|
20
|
+
_err: string,
|
|
21
|
+
): Promise<Result<number, string>> => {
|
|
22
|
+
await new Promise((r) => setTimeout(r, 10))
|
|
23
|
+
return Result.Ok(100)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// ============================================================================
|
|
27
|
+
// Pattern 1: Simple recovery using .orElse()
|
|
28
|
+
// Best when the recovery logic is simple and synchronous/atomic.
|
|
29
|
+
// ============================================================================
|
|
30
|
+
|
|
31
|
+
const simpleRecovery = Flow.gen(function* () {
|
|
32
|
+
// Try to clean 5, if fail, recover is not called
|
|
33
|
+
const a = yield* mayFail(5).orElse(recover)
|
|
34
|
+
|
|
35
|
+
// Try to clean -1, fails -> recovers (returns Ok(0))
|
|
36
|
+
// The 'yield*' sees the *recovered* Ok value.
|
|
37
|
+
const b = yield* mayFail(-1).orElse(recover)
|
|
38
|
+
|
|
39
|
+
return a + b // 5 + 0 = 5
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
console.log("Simple Recovery:", simpleRecovery.unwrap())
|
|
43
|
+
|
|
44
|
+
// ============================================================================
|
|
45
|
+
// Pattern 2: Manual branching for complex flows
|
|
46
|
+
// Necessary when recovery involves multiple yield steps or generators.
|
|
47
|
+
// ============================================================================
|
|
48
|
+
|
|
49
|
+
const manualRecovery = Flow.gen(function* () {
|
|
50
|
+
// const result = mayFail(-1); // Don't yield yet!
|
|
51
|
+
//
|
|
52
|
+
// let val: number;
|
|
53
|
+
// if (result.isOk()) {
|
|
54
|
+
// val = result.unwrap();
|
|
55
|
+
// } else {
|
|
56
|
+
// // Perform complex recovery logic here
|
|
57
|
+
// const fallback = yield* Option.Some(99);
|
|
58
|
+
// val = fallback + 1; // 100
|
|
59
|
+
// }
|
|
60
|
+
|
|
61
|
+
const val = yield* mayFail(-1).orElse(() => {
|
|
62
|
+
console.log("Failed, recovering...")
|
|
63
|
+
|
|
64
|
+
return Result.Ok(100)
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
return val
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
console.log("Manual Recovery:", manualRecovery.unwrap())
|
|
71
|
+
|
|
72
|
+
// ============================================================================
|
|
73
|
+
// Pattern 3: Async recovery using .orElseAsync() (if available on Result)
|
|
74
|
+
// or manual branching for async logic.
|
|
75
|
+
// ============================================================================
|
|
76
|
+
|
|
77
|
+
const asyncRecovery = await Flow.asyncGen(async function* () {
|
|
78
|
+
// const res = mayFail(-5);
|
|
79
|
+
//
|
|
80
|
+
// let val: number;
|
|
81
|
+
// if (res.isOk()) {
|
|
82
|
+
// val = res.unwrap();
|
|
83
|
+
// } else {
|
|
84
|
+
// // You can yield async recovery operations here
|
|
85
|
+
// val = yield* await complexRecovery(res.unwrapErr());
|
|
86
|
+
// }
|
|
87
|
+
|
|
88
|
+
const val = yield* await mayFail(-5).orElseAsync(complexRecovery)
|
|
89
|
+
|
|
90
|
+
return val
|
|
91
|
+
})
|
|
92
|
+
|
|
93
|
+
console.log("Async Recovery:", asyncRecovery.unwrap()) // 100
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Complex Backend Example - User Enrichment Service
|
|
3
|
+
*
|
|
4
|
+
* Demonstrates:
|
|
5
|
+
* - Orchestrating multiple async services (Database, External APIs)
|
|
6
|
+
* - Error handling with custom typed errors
|
|
7
|
+
* - Mixing Result (fallible) and Option (nullable) types
|
|
8
|
+
* - Using Flow.asyncGenAdapter for clean, declarative control flow
|
|
9
|
+
* - Uses ExperimentalOption and ExperimentalResult
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import {
|
|
13
|
+
ExperimentalFlow as Flow,
|
|
14
|
+
ExperimentalOption as Option,
|
|
15
|
+
ExperimentalResult as Result,
|
|
16
|
+
} from "../../dist/index.mjs"
|
|
17
|
+
|
|
18
|
+
// ============================================================================
|
|
19
|
+
// 1. Domain Types & Errors
|
|
20
|
+
// ============================================================================
|
|
21
|
+
|
|
22
|
+
type UserID = number
|
|
23
|
+
|
|
24
|
+
interface User {
|
|
25
|
+
id: UserID
|
|
26
|
+
username: string
|
|
27
|
+
email: string
|
|
28
|
+
isActive: boolean
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
interface UserPreferences {
|
|
32
|
+
theme: "light" | "dark" | "system"
|
|
33
|
+
notificationsEnabled: boolean
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
interface Order {
|
|
37
|
+
id: string
|
|
38
|
+
total: number
|
|
39
|
+
status: "pending" | "completed"
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
interface EnrichedUser {
|
|
43
|
+
user: User
|
|
44
|
+
preferences: UserPreferences
|
|
45
|
+
recentOrders: Order[]
|
|
46
|
+
lifetimeValue: number
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// Custom Errors
|
|
50
|
+
class NotFoundError extends Error {
|
|
51
|
+
readonly _tag = "NotFoundError"
|
|
52
|
+
constructor(message: string) {
|
|
53
|
+
super(message)
|
|
54
|
+
this.name = "NotFoundError"
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
class ValidationError extends Error {
|
|
59
|
+
readonly _tag = "ValidationError"
|
|
60
|
+
constructor(message: string) {
|
|
61
|
+
super(message)
|
|
62
|
+
this.name = "ValidationError"
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
class ServiceUnavailableError extends Error {
|
|
67
|
+
readonly _tag = "ServiceUnavailableError"
|
|
68
|
+
constructor(service: string) {
|
|
69
|
+
super(`${service} unavailable`)
|
|
70
|
+
this.name = "ServiceUnavailableError"
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// ============================================================================
|
|
75
|
+
// 2. Mock Services
|
|
76
|
+
// ============================================================================
|
|
77
|
+
|
|
78
|
+
const DB = {
|
|
79
|
+
users: new Map<UserID, User>([
|
|
80
|
+
[
|
|
81
|
+
1,
|
|
82
|
+
{
|
|
83
|
+
id: 1,
|
|
84
|
+
username: "alice_w",
|
|
85
|
+
email: "alice@example.com",
|
|
86
|
+
isActive: true,
|
|
87
|
+
},
|
|
88
|
+
],
|
|
89
|
+
[
|
|
90
|
+
2,
|
|
91
|
+
{
|
|
92
|
+
id: 2,
|
|
93
|
+
username: "bob_builder",
|
|
94
|
+
email: "bob@example.com",
|
|
95
|
+
isActive: false,
|
|
96
|
+
},
|
|
97
|
+
],
|
|
98
|
+
]),
|
|
99
|
+
prefs: new Map<UserID, UserPreferences>([
|
|
100
|
+
[1, { theme: "dark", notificationsEnabled: true }],
|
|
101
|
+
]),
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const UserRepository = {
|
|
105
|
+
findById: async (id: UserID): Promise<Result<User, NotFoundError>> => {
|
|
106
|
+
// Simulate DB latency
|
|
107
|
+
await new Promise((r) => setTimeout(r, 10))
|
|
108
|
+
|
|
109
|
+
const user = DB.users.get(id)
|
|
110
|
+
return user
|
|
111
|
+
? Result.Ok(user)
|
|
112
|
+
: Result.Err(new NotFoundError(`User ${id} not found`))
|
|
113
|
+
},
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const PreferencesService = {
|
|
117
|
+
getPreferences: async (id: UserID): Promise<Option<UserPreferences>> => {
|
|
118
|
+
await new Promise((r) => setTimeout(r, 10))
|
|
119
|
+
return Option.fromNullable(DB.prefs.get(id))
|
|
120
|
+
},
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const OrderService = {
|
|
124
|
+
getRecentOrders: async (
|
|
125
|
+
id: UserID,
|
|
126
|
+
): Promise<Result<Order[], ServiceUnavailableError>> => {
|
|
127
|
+
await new Promise((r) => setTimeout(r, 20))
|
|
128
|
+
|
|
129
|
+
// Simulate random service failure for demo
|
|
130
|
+
if (Math.random() < 0.1) {
|
|
131
|
+
return Result.Err(new ServiceUnavailableError("OrderService"))
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
if (id === 1) {
|
|
135
|
+
return Result.Ok([
|
|
136
|
+
{ id: "ord_123", total: 100, status: "completed" },
|
|
137
|
+
{ id: "ord_456", total: 49.99, status: "pending" },
|
|
138
|
+
])
|
|
139
|
+
}
|
|
140
|
+
return Result.Ok([])
|
|
141
|
+
},
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// ============================================================================
|
|
145
|
+
// 3. Main Logic: Enriched User Fow
|
|
146
|
+
// ============================================================================
|
|
147
|
+
|
|
148
|
+
// Default preferences if none found
|
|
149
|
+
const DEFAULT_PREFS: UserPreferences = {
|
|
150
|
+
theme: "system",
|
|
151
|
+
notificationsEnabled: false,
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const enrichUser = (userId: number) =>
|
|
155
|
+
Flow.asyncGenAdapter(async function* ($) {
|
|
156
|
+
// 1. Validation Logic (Synchronous Result)
|
|
157
|
+
if (userId <= 0) {
|
|
158
|
+
yield* $(Result.Err(new ValidationError("User ID must be positive")))
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// 2. Fetch User (Async Result)
|
|
162
|
+
// The adapter automatically awaits the Promise and unwraps the Result
|
|
163
|
+
console.log(`[Flow] Fetching user ${userId}...`)
|
|
164
|
+
const user = yield* $(UserRepository.findById(userId))
|
|
165
|
+
|
|
166
|
+
// 3. Early exit if inactive
|
|
167
|
+
if (!user.isActive) {
|
|
168
|
+
yield* $(Result.Err(new ValidationError("User is inactive")))
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// 4. Fetch Preferences (Async Option) & Orders (Async Result) in parallel
|
|
172
|
+
// We can use Promise.all to fetch them concurrently, then yield* to unwrap
|
|
173
|
+
console.log(`[Flow] Fetching details for ${user.username}...`)
|
|
174
|
+
|
|
175
|
+
const [prefsOpt, ordersRes] = await Promise.all([
|
|
176
|
+
PreferencesService.getPreferences(user.id),
|
|
177
|
+
OrderService.getRecentOrders(user.id),
|
|
178
|
+
])
|
|
179
|
+
|
|
180
|
+
// Unwrap Orders (Result) - will bubble up ServiceUnavailableError if failed
|
|
181
|
+
const orders = yield* $(ordersRes)
|
|
182
|
+
|
|
183
|
+
// Unwrap Preferences (Option) - we want to provide a default if None,
|
|
184
|
+
// rather than halting the flow (which yielding a None would do).
|
|
185
|
+
// So we DON'T use yield* on the Option directly here.
|
|
186
|
+
const preferences = prefsOpt.unwrapOr(DEFAULT_PREFS)
|
|
187
|
+
|
|
188
|
+
// 5. Aggregate Data
|
|
189
|
+
const lifetimeValue = orders.reduce(
|
|
190
|
+
(sum, ord) => (ord.status === "completed" ? sum + ord.total : sum),
|
|
191
|
+
0,
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
const enriched: EnrichedUser = {
|
|
195
|
+
user,
|
|
196
|
+
preferences,
|
|
197
|
+
recentOrders: orders,
|
|
198
|
+
lifetimeValue,
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
return enriched
|
|
202
|
+
})
|
|
203
|
+
|
|
204
|
+
// ============================================================================
|
|
205
|
+
// 4. Execution Examples
|
|
206
|
+
// ============================================================================
|
|
207
|
+
|
|
208
|
+
async function runDemo() {
|
|
209
|
+
console.log("--- Scenario 1: Happy Path (Alice) ---")
|
|
210
|
+
const res1 = await enrichUser(1)
|
|
211
|
+
/*
|
|
212
|
+
* We can match on the final result to handle success/failure
|
|
213
|
+
*/
|
|
214
|
+
res1.match({
|
|
215
|
+
Ok: (data) => console.log("SUCCESS:", JSON.stringify(data, null, 2)),
|
|
216
|
+
Err: (err) => console.error("FAILURE:", err.message),
|
|
217
|
+
})
|
|
218
|
+
|
|
219
|
+
console.log("\n--- Scenario 2: User Not Found (ID 99) ---")
|
|
220
|
+
const res2 = await enrichUser(99)
|
|
221
|
+
console.log(
|
|
222
|
+
"Result:",
|
|
223
|
+
res2.isErr() ? `Left(${res2.unwrapErr().message})` : "Ok",
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
console.log("\n--- Scenario 3: Validation Error (ID -5) ---")
|
|
227
|
+
const res3 = await enrichUser(-5)
|
|
228
|
+
console.log(
|
|
229
|
+
"Result:",
|
|
230
|
+
res3.isErr() ? `Left(${res3.unwrapErr().message})` : "Ok",
|
|
231
|
+
)
|
|
232
|
+
|
|
233
|
+
console.log("\n--- Scenario 4: Logical Validation (Bob - Inactive) ---")
|
|
234
|
+
const res4 = await enrichUser(2)
|
|
235
|
+
console.log(
|
|
236
|
+
"Result:",
|
|
237
|
+
res4.isErr() ? `Left(${res4.unwrapErr().message})` : "Ok",
|
|
238
|
+
)
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
runDemo().catch(console.error)
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Complex Backend Example - User Enrichment Service
|
|
3
|
+
*
|
|
4
|
+
* Demonstrates:
|
|
5
|
+
* - Orchestrating multiple async services (Database, External APIs)
|
|
6
|
+
* - Error handling with custom typed errors using FlowError
|
|
7
|
+
* - Mixing Result (fallible) and Option (nullable) types
|
|
8
|
+
* - Using Flow.asyncGen with direct error yielding via FlowError
|
|
9
|
+
* - Uses ExperimentalOption and ExperimentalResult
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import {
|
|
13
|
+
ExperimentalFlow as Flow,
|
|
14
|
+
ExperimentalFlowError as FlowError,
|
|
15
|
+
ExperimentalOption as Option,
|
|
16
|
+
ExperimentalResult as Result,
|
|
17
|
+
} from "../../src/index.js"
|
|
18
|
+
|
|
19
|
+
// ============================================================================
|
|
20
|
+
// 1. Domain Types & Errors
|
|
21
|
+
// ============================================================================
|
|
22
|
+
|
|
23
|
+
type UserID = number
|
|
24
|
+
|
|
25
|
+
interface User {
|
|
26
|
+
id: UserID
|
|
27
|
+
username: string
|
|
28
|
+
email: string
|
|
29
|
+
isActive: boolean
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
interface UserPreferences {
|
|
33
|
+
theme: "light" | "dark" | "system"
|
|
34
|
+
notificationsEnabled: boolean
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
interface Order {
|
|
38
|
+
id: string
|
|
39
|
+
total: number
|
|
40
|
+
status: "pending" | "completed"
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
interface EnrichedUser {
|
|
44
|
+
user: User
|
|
45
|
+
preferences: UserPreferences
|
|
46
|
+
recentOrders: Order[]
|
|
47
|
+
lifetimeValue: number
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Custom Errors - extend FlowError for direct yielding in Flow generators
|
|
51
|
+
class NotFoundError extends FlowError {
|
|
52
|
+
readonly _tag = "NotFoundError"
|
|
53
|
+
constructor(message: string) {
|
|
54
|
+
super(message)
|
|
55
|
+
Object.defineProperty(this, "name", { value: "NotFoundError" })
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
class ValidationError extends FlowError {
|
|
60
|
+
readonly _tag = "ValidationError"
|
|
61
|
+
constructor(message: string) {
|
|
62
|
+
super(message)
|
|
63
|
+
Object.defineProperty(this, "name", { value: "ValidationError" })
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
class ServiceUnavailableError extends FlowError {
|
|
68
|
+
readonly _tag = "ServiceUnavailableError"
|
|
69
|
+
constructor(service: string) {
|
|
70
|
+
super(`${service} unavailable`)
|
|
71
|
+
Object.defineProperty(this, "name", { value: "ServiceUnavailableError" })
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// ============================================================================
|
|
76
|
+
// 2. Mock Services
|
|
77
|
+
// ============================================================================
|
|
78
|
+
|
|
79
|
+
const DB = {
|
|
80
|
+
users: new Map<UserID, User>([
|
|
81
|
+
[
|
|
82
|
+
1,
|
|
83
|
+
{
|
|
84
|
+
id: 1,
|
|
85
|
+
username: "alice_w",
|
|
86
|
+
email: "alice@example.com",
|
|
87
|
+
isActive: true,
|
|
88
|
+
},
|
|
89
|
+
],
|
|
90
|
+
[
|
|
91
|
+
2,
|
|
92
|
+
{
|
|
93
|
+
id: 2,
|
|
94
|
+
username: "bob_builder",
|
|
95
|
+
email: "bob@example.com",
|
|
96
|
+
isActive: false,
|
|
97
|
+
},
|
|
98
|
+
],
|
|
99
|
+
]),
|
|
100
|
+
prefs: new Map<UserID, UserPreferences>([
|
|
101
|
+
[1, { theme: "dark", notificationsEnabled: true }],
|
|
102
|
+
]),
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const UserRepository = {
|
|
106
|
+
findById: async (id: UserID): Promise<Result<User, NotFoundError>> => {
|
|
107
|
+
// Simulate DB latency
|
|
108
|
+
await new Promise((r) => setTimeout(r, 10))
|
|
109
|
+
|
|
110
|
+
const user = DB.users.get(id)
|
|
111
|
+
return user
|
|
112
|
+
? Result.Ok(user)
|
|
113
|
+
: Result.Err(new NotFoundError(`User ${id} not found`))
|
|
114
|
+
},
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const PreferencesService = {
|
|
118
|
+
getPreferences: async (id: UserID): Promise<Option<UserPreferences>> => {
|
|
119
|
+
await new Promise((r) => setTimeout(r, 10))
|
|
120
|
+
return Option.fromNullable(DB.prefs.get(id))
|
|
121
|
+
},
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const OrderService = {
|
|
125
|
+
getRecentOrders: async (
|
|
126
|
+
id: UserID,
|
|
127
|
+
): Promise<Result<Order[], ServiceUnavailableError>> => {
|
|
128
|
+
await new Promise((r) => setTimeout(r, 20))
|
|
129
|
+
|
|
130
|
+
// Simulate random service failure for demo
|
|
131
|
+
if (Math.random() < 0.1) {
|
|
132
|
+
return Result.Err(new ServiceUnavailableError("OrderService"))
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
if (id === 1) {
|
|
136
|
+
return Result.Ok([
|
|
137
|
+
{ id: "ord_123", total: 100, status: "completed" },
|
|
138
|
+
{ id: "ord_456", total: 49.99, status: "pending" },
|
|
139
|
+
])
|
|
140
|
+
}
|
|
141
|
+
return Result.Ok([])
|
|
142
|
+
},
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// ============================================================================
|
|
146
|
+
// 3. Main Logic: Enriched User Fow
|
|
147
|
+
// ============================================================================
|
|
148
|
+
|
|
149
|
+
// Default preferences if none found
|
|
150
|
+
const DEFAULT_PREFS: UserPreferences = {
|
|
151
|
+
theme: "system",
|
|
152
|
+
notificationsEnabled: false,
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const enrichUser = async (userId: number) => {
|
|
156
|
+
return await Flow.asyncGen(async function* () {
|
|
157
|
+
// Direct error yielding with FlowError - no Result.Err wrapper needed!
|
|
158
|
+
if (userId <= 0) {
|
|
159
|
+
yield* new ValidationError("UserID must be positive")
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
console.log(`[Flow] Fetching user ${userId}...`)
|
|
163
|
+
const user = yield* await UserRepository.findById(userId)
|
|
164
|
+
|
|
165
|
+
if (!user.isActive) {
|
|
166
|
+
yield* new ValidationError("User account is inactive")
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
console.log(`[Flow] Fetching details for ${user.username}...`)
|
|
170
|
+
|
|
171
|
+
const orders = yield* await OrderService.getRecentOrders(user.id)
|
|
172
|
+
|
|
173
|
+
const prefsOpt = await PreferencesService.getPreferences(user.id)
|
|
174
|
+
const preferences = prefsOpt.unwrapOr(DEFAULT_PREFS)
|
|
175
|
+
|
|
176
|
+
const lifetimeValue = orders.reduce(
|
|
177
|
+
(sum, order) => (order.status === "completed" ? sum + order.total : sum),
|
|
178
|
+
0,
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
const enrichedUser: EnrichedUser = {
|
|
182
|
+
user,
|
|
183
|
+
preferences,
|
|
184
|
+
recentOrders: orders,
|
|
185
|
+
lifetimeValue,
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
return enrichedUser
|
|
189
|
+
})
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// ============================================================================
|
|
193
|
+
// 4. Execution Examples
|
|
194
|
+
// ============================================================================
|
|
195
|
+
|
|
196
|
+
async function runDemo() {
|
|
197
|
+
console.log("--- Scenario 1: Happy Path (Alice) ---")
|
|
198
|
+
const res1 = await enrichUser(1)
|
|
199
|
+
/*
|
|
200
|
+
* We can match on the final result to handle success/failure
|
|
201
|
+
*/
|
|
202
|
+
res1.match({
|
|
203
|
+
Ok: (data) => console.log("SUCCESS:", JSON.stringify(data, null, 2)),
|
|
204
|
+
Err: (err) => console.error("FAILURE:", (err as Error).message),
|
|
205
|
+
})
|
|
206
|
+
|
|
207
|
+
console.log("\n--- Scenario 2: User Not Found (ID 99) ---")
|
|
208
|
+
const res2 = await enrichUser(99)
|
|
209
|
+
console.log(
|
|
210
|
+
"Result:",
|
|
211
|
+
res2.isErr() ? `Left(${(res2.unwrapErr() as Error).message})` : "Ok",
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
console.log("\n--- Scenario 3: Validation Error (ID -5) ---")
|
|
215
|
+
const res3 = await enrichUser(-5)
|
|
216
|
+
console.log(
|
|
217
|
+
"Result:",
|
|
218
|
+
res3.isErr() ? `Left(${(res3.unwrapErr() as Error).message})` : "Ok",
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
console.log("\n--- Scenario 4: Logical Validation (Bob - Inactive) ---")
|
|
222
|
+
const res4 = await enrichUser(2)
|
|
223
|
+
console.log(
|
|
224
|
+
"Result:",
|
|
225
|
+
res4.isErr() ? `Left(${(res4.unwrapErr() as Error).message})` : "Ok",
|
|
226
|
+
)
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
runDemo().catch(console.error)
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ExperimentalFlow Examples Index
|
|
3
|
+
*
|
|
4
|
+
* These examples use the experimental Flow API with
|
|
5
|
+
* ExperimentalOption and ExperimentalResult.
|
|
6
|
+
* Run examples with:
|
|
7
|
+
* bun run examples/flow-experimental/01-basics.ts
|
|
8
|
+
* bun run examples/flow-experimental/02-async.ts
|
|
9
|
+
* bun run examples/flow-experimental/03-recovery.ts
|
|
10
|
+
* bun run examples/flow-experimental/04-complex-backend.ts
|
|
11
|
+
* bun run examples/flow-experimental/05-complex-backend-asyncGen.ts
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
export {}
|