@carbonteq/fp 0.9.1 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +310 -96
- package/dist/errors.cjs +1 -0
- package/dist/errors.cjs.map +1 -1
- package/dist/errors.d.cts.map +1 -1
- package/dist/errors.d.mts.map +1 -1
- package/dist/errors.mjs.map +1 -1
- 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 +26 -11
- package/dist/index.d.cts +8 -3
- package/dist/index.d.mts +8 -3
- package/dist/index.mjs +8 -3
- package/dist/match.cjs +282 -0
- package/dist/match.cjs.map +1 -1
- package/dist/match.d.cts +471 -5
- package/dist/match.d.cts.map +1 -1
- package/dist/match.d.mts +471 -5
- package/dist/match.d.mts.map +1 -1
- package/dist/match.mjs +277 -1
- package/dist/match.mjs.map +1 -1
- 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 +556 -29
- package/dist/option.cjs.map +1 -1
- package/dist/option.d.cts +505 -24
- package/dist/option.d.cts.map +1 -1
- package/dist/option.d.mts +505 -24
- package/dist/option.d.mts.map +1 -1
- package/dist/option.mjs +556 -30
- package/dist/option.mjs.map +1 -1
- 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 +715 -122
- package/dist/result.cjs.map +1 -1
- package/dist/result.d.cts +785 -94
- package/dist/result.d.cts.map +1 -1
- package/dist/result.d.mts +785 -94
- package/dist/result.d.mts.map +1 -1
- package/dist/result.mjs +714 -117
- package/dist/result.mjs.map +1 -1
- package/dist/tuple.cjs +3 -0
- package/dist/tuple.cjs.map +1 -1
- package/dist/tuple.d.cts +5 -1
- package/dist/tuple.d.cts.map +1 -1
- package/dist/tuple.d.mts +5 -1
- package/dist/tuple.d.mts.map +1 -1
- package/dist/tuple.mjs +2 -0
- package/dist/tuple.mjs.map +1 -1
- package/dist/unit.cjs +2 -0
- package/dist/unit.cjs.map +1 -1
- package/dist/unit.d.cts +2 -0
- package/dist/unit.d.cts.map +1 -1
- package/dist/unit.d.mts +2 -0
- package/dist/unit.d.mts.map +1 -1
- package/dist/unit.mjs +1 -0
- package/dist/unit.mjs.map +1 -1
- package/dist/utils.cjs +15 -0
- package/dist/utils.cjs.map +1 -1
- package/dist/utils.d.cts +10 -1
- package/dist/utils.d.cts.map +1 -1
- package/dist/utils.d.mts +10 -1
- package/dist/utils.d.mts.map +1 -1
- package/dist/utils.mjs +13 -1
- package/dist/utils.mjs.map +1 -1
- 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 +50 -18
package/dist/utils.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.mjs","names":[],"sources":["../src/utils.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"utils.mjs","names":[],"sources":["../src/utils.ts"],"sourcesContent":["/** Type guard that checks whether a value is Promise-like (`thenable`). */\nexport function isPromiseLike<T>(value: unknown): value is Promise<T> {\n return (\n !!value &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n // @ts-expect-error: we are checking for .then property existence\n typeof value.then === \"function\"\n )\n}\n\n/** Wrapper used to preserve callsite stack traces across yielded values. */\nexport class CapturedTrace<T> {\n constructor(\n readonly value: T,\n readonly stack: string | undefined,\n ) {}\n}\n\n/** Type guard for `CapturedTrace` wrappers. */\nexport function isCapturedTrace(\n value: unknown,\n): value is CapturedTrace<unknown> {\n return value instanceof CapturedTrace\n}\n"],"mappings":";;AACA,SAAgB,cAAiB,OAAqC;AACpE,QACE,CAAC,CAAC,UACD,OAAO,UAAU,YAAY,OAAO,UAAU,eAE/C,OAAO,MAAM,SAAS;;;AAK1B,IAAa,gBAAb,MAA8B;CAC5B,YACE,AAAS,OACT,AAAS,OACT;EAFS;EACA;;;;AAKb,SAAgB,gBACd,OACiC;AACjC,QAAO,iBAAiB"}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# Examples
|
|
2
|
+
|
|
3
|
+
This directory contains runnable examples split between stable and experimental APIs.
|
|
4
|
+
|
|
5
|
+
`examples/flow/` is stable, while `examples/flow-experimental/` is experimental.
|
|
6
|
+
|
|
7
|
+
## Stable APIs (Result / Option / Flow)
|
|
8
|
+
|
|
9
|
+
Runnable stable examples live here:
|
|
10
|
+
|
|
11
|
+
- `examples/result/` uses `Result`.
|
|
12
|
+
- `examples/option/` uses `Option`.
|
|
13
|
+
- `examples/flow/` uses stable `Flow` with stable `Result` and `Option`.
|
|
14
|
+
- `examples/match/` uses `match()` with stable `Option`/`Result`.
|
|
15
|
+
|
|
16
|
+
## Experimental APIs (ExperimentalResult / ExperimentalOption / Flow)
|
|
17
|
+
|
|
18
|
+
These examples use experimental types and may change between releases.
|
|
19
|
+
|
|
20
|
+
- `examples/result-experimental/` uses `ExperimentalResult`.
|
|
21
|
+
- `examples/option-experimental/` uses `ExperimentalOption`.
|
|
22
|
+
- `examples/flow-experimental/` uses `ExperimentalFlow` with `ExperimentalResult` and `ExperimentalOption`.
|
|
23
|
+
- `examples/match-experimental/` uses `match()` with experimental variants.
|
|
24
|
+
|
|
25
|
+
Run individual examples with Bun, for example:
|
|
26
|
+
|
|
27
|
+
```sh
|
|
28
|
+
bun run examples/result-experimental/01-map.ts
|
|
29
|
+
bun run examples/option-experimental/01-map.ts
|
|
30
|
+
bun run examples/flow-experimental/01-basics.ts
|
|
31
|
+
bun run examples/flow/01-basics.ts
|
|
32
|
+
bun run examples/result/01-basics.ts
|
|
33
|
+
bun run examples/option/01-basics.ts
|
|
34
|
+
bun run examples/match/01-stable-match.ts
|
|
35
|
+
bun run examples/match-experimental/01-experimental-match.ts
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
For a full list of Result/Option examples, see:
|
|
39
|
+
|
|
40
|
+
- `examples/result/index.ts`
|
|
41
|
+
- `examples/option/index.ts`
|
|
42
|
+
- `examples/match/index.ts`
|
|
43
|
+
|
|
44
|
+
- `examples/result-experimental/index.ts`
|
|
45
|
+
- `examples/option-experimental/index.ts`
|
|
46
|
+
- `examples/match-experimental/index.ts`
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Flow - Unified Generator for Option and Result
|
|
3
|
+
*
|
|
4
|
+
* Flow allows you to yield both Option and Result types in the same generator.
|
|
5
|
+
* It automatically handles short-circuiting:
|
|
6
|
+
* - If Option.None is yielded -> returns Result.Err(UnwrappedNone)
|
|
7
|
+
* - If Result.Err(e) is yielded -> returns Result.Err(e)
|
|
8
|
+
*
|
|
9
|
+
* Uses stable Option and Result.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { Flow, Option, Result } from "../../dist/index.mjs"
|
|
13
|
+
|
|
14
|
+
// ============================================================================
|
|
15
|
+
// Flow.gen - Direct usage (simpler, good for simple chains)
|
|
16
|
+
// ============================================================================
|
|
17
|
+
|
|
18
|
+
const basicGen = Flow.gen(function* () {
|
|
19
|
+
console.log("Start Flow.gen")
|
|
20
|
+
|
|
21
|
+
// 1. Yield Option -> Unwraps value or error
|
|
22
|
+
const a = yield* Option.Some(10)
|
|
23
|
+
|
|
24
|
+
// 2. Yield Result -> Unwraps value or error
|
|
25
|
+
const b = yield* Result.Ok(20)
|
|
26
|
+
|
|
27
|
+
// 3. Helper to convert nullable to Option -> Then yield
|
|
28
|
+
const c = yield* Option.fromNullable(30)
|
|
29
|
+
|
|
30
|
+
return a + b + c
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
console.log("Basic Gen:", basicGen.safeUnwrap()) // 60
|
|
34
|
+
|
|
35
|
+
// Error Handling: Option.None
|
|
36
|
+
const noneError = Flow.gen(function* () {
|
|
37
|
+
const a = yield* Option.Some(1)
|
|
38
|
+
yield* Option.None // Stops here
|
|
39
|
+
|
|
40
|
+
return a + 10
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
console.log("None Error:", noneError.isErr()) // true
|
|
44
|
+
console.log("Error Type:", noneError.unwrapErr()) // UnwrappedNone
|
|
45
|
+
|
|
46
|
+
// Error Handling: Result.Err
|
|
47
|
+
const resultError = Flow.gen(function* () {
|
|
48
|
+
const a = yield* Result.Ok(1)
|
|
49
|
+
yield* Result.Err("Something went wrong") // Stops here
|
|
50
|
+
return a + 10
|
|
51
|
+
})
|
|
52
|
+
|
|
53
|
+
console.log("Result Error:", resultError.unwrapErr()) // "Something went wrong"
|
|
54
|
+
|
|
55
|
+
// ============================================================================
|
|
56
|
+
// Flow.genAdapter - Adapter usage (better type inference)
|
|
57
|
+
// ============================================================================
|
|
58
|
+
|
|
59
|
+
// The `$` adapter function helps TypeScript infer types correctly,
|
|
60
|
+
// especially in more complex expressions or chains.
|
|
61
|
+
|
|
62
|
+
const adapterGen = Flow.genAdapter(function* ($) {
|
|
63
|
+
const val1 = yield* $(Option.Some(100))
|
|
64
|
+
const val2 = yield* $(Result.Ok(200))
|
|
65
|
+
|
|
66
|
+
// You can wrap complex expressions
|
|
67
|
+
const val3 = yield* $(
|
|
68
|
+
Option.fromPredicate(val1 + val2, (v) => v > 100).map((v) => v / 10),
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
return val3
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
console.log("Adapter Gen:", adapterGen.unwrap()) // 30
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Async Flow - Unified Async Generator
|
|
3
|
+
*
|
|
4
|
+
* Handles Promise<Option>, Promise<Result>, and async operations.
|
|
5
|
+
* Uses stable Option and Result.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { Flow, Option, Result } from "../../dist/index.mjs"
|
|
9
|
+
|
|
10
|
+
type User = { id: number; name: string }
|
|
11
|
+
|
|
12
|
+
// Mock async functions
|
|
13
|
+
const fetchUser = async (id: number): Promise<Result<User, string>> => {
|
|
14
|
+
await new Promise((r) => setTimeout(r, 10))
|
|
15
|
+
return id === 1
|
|
16
|
+
? Result.Ok({ id, name: "Alice" })
|
|
17
|
+
: Result.Err("User not found")
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const fetchSettings = async (_userId: number) => {
|
|
21
|
+
await new Promise((r) => setTimeout(r, 10))
|
|
22
|
+
return Option.Some({ theme: "dark" })
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// ============================================================================
|
|
26
|
+
// Flow.asyncGen - Direct usage (requires explicit awaits)
|
|
27
|
+
// ============================================================================
|
|
28
|
+
|
|
29
|
+
const asyncDirect = await Flow.asyncGen(async function* () {
|
|
30
|
+
// 1. Await async Result function, then yield*
|
|
31
|
+
const user = yield* await fetchUser(1)
|
|
32
|
+
|
|
33
|
+
// 2. Await async Option function, then yield*
|
|
34
|
+
const settings = yield* await fetchSettings(user.id)
|
|
35
|
+
|
|
36
|
+
// 3. Sync yield works too
|
|
37
|
+
const bonus = yield* Option.Some(50)
|
|
38
|
+
|
|
39
|
+
return `${user.name} prefers ${settings.theme} theme (Bonus: ${bonus})`
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
console.log("Async Direct:", asyncDirect.unwrap())
|
|
43
|
+
|
|
44
|
+
// ============================================================================
|
|
45
|
+
// Flow.asyncGenAdapter - Adapter usage (cleaner syntax)
|
|
46
|
+
// ============================================================================
|
|
47
|
+
|
|
48
|
+
const asyncAdapter = await Flow.asyncGenAdapter(async function* ($) {
|
|
49
|
+
// 1. Wrap promise - adapter handles await automatically!
|
|
50
|
+
const user = yield* $(fetchUser(1))
|
|
51
|
+
|
|
52
|
+
// 2. Wrap another promise
|
|
53
|
+
const settings = yield* $(fetchSettings(user.id))
|
|
54
|
+
|
|
55
|
+
// 3. Wrap sync values
|
|
56
|
+
const multiplier = yield* $(Result.Ok<number, Error>(2))
|
|
57
|
+
|
|
58
|
+
return {
|
|
59
|
+
user,
|
|
60
|
+
settings,
|
|
61
|
+
score: 100 * multiplier,
|
|
62
|
+
}
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
console.log("Async Adapter:", asyncAdapter.safeUnwrap())
|
|
66
|
+
|
|
67
|
+
// Error propagation in Async
|
|
68
|
+
const asyncError = await Flow.asyncGenAdapter(async function* ($) {
|
|
69
|
+
const user = yield* $(fetchUser(999)) // Returns Err
|
|
70
|
+
return user // Not reached
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
console.log("Async Error:", asyncError.unwrapErr()) // "User not found"
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Flow - Error Recovery Patterns
|
|
3
|
+
*
|
|
4
|
+
* Examples of how to handle errors and perform recovery (orElse) within Flow generators.
|
|
5
|
+
* Uses stable Result.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { Flow, Result } from "../../dist/index.mjs"
|
|
9
|
+
|
|
10
|
+
// Mock operations
|
|
11
|
+
const mayFail = (id: number): Result<number, string> =>
|
|
12
|
+
id > 0 ? Result.Ok(id) : Result.Err("Invalid ID")
|
|
13
|
+
|
|
14
|
+
const recover = (_err: string): Result<number, string> => Result.Ok(0) // Default to 0
|
|
15
|
+
|
|
16
|
+
// ============================================================================
|
|
17
|
+
// Pattern 1: Simple recovery using .orElse()
|
|
18
|
+
// Best when the recovery logic is simple and synchronous/atomic.
|
|
19
|
+
// ============================================================================
|
|
20
|
+
|
|
21
|
+
const simpleRecovery = Flow.gen(function* () {
|
|
22
|
+
// Try to clean 5, if fail, recover is not called
|
|
23
|
+
const a = yield* mayFail(5).orElse(recover)
|
|
24
|
+
|
|
25
|
+
// Try to clean -1, fails -> recovers (returns Ok(0))
|
|
26
|
+
// The 'yield*' sees the *recovered* Ok value.
|
|
27
|
+
const b = yield* mayFail(-1).orElse(recover)
|
|
28
|
+
|
|
29
|
+
return a + b // 5 + 0 = 5
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
console.log("Simple Recovery:", simpleRecovery.unwrap())
|
|
33
|
+
|
|
34
|
+
// ============================================================================
|
|
35
|
+
// Pattern 2: Manual branching for complex flows
|
|
36
|
+
// Necessary when recovery involves multiple yield steps or generators.
|
|
37
|
+
// ============================================================================
|
|
38
|
+
|
|
39
|
+
const manualRecovery = Flow.gen(function* () {
|
|
40
|
+
// const result = mayFail(-1); // Don't yield yet!
|
|
41
|
+
//
|
|
42
|
+
// let val: number;
|
|
43
|
+
// if (result.isOk()) {
|
|
44
|
+
// val = result.unwrap();
|
|
45
|
+
// } else {
|
|
46
|
+
// // Perform complex recovery logic here
|
|
47
|
+
// const fallback = yield* Option.Some(99);
|
|
48
|
+
// val = fallback + 1; // 100
|
|
49
|
+
// }
|
|
50
|
+
|
|
51
|
+
const val = yield* mayFail(-1).orElse(() => {
|
|
52
|
+
console.log("Failed, recovering...")
|
|
53
|
+
|
|
54
|
+
return Result.Ok(100)
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
return val
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
console.log("Manual Recovery:", manualRecovery.unwrap())
|
|
@@ -0,0 +1,237 @@
|
|
|
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 stable Option and Result
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { Flow, Option, Result } from "../../dist/index.mjs"
|
|
13
|
+
|
|
14
|
+
// ============================================================================
|
|
15
|
+
// 1. Domain Types & Errors
|
|
16
|
+
// ============================================================================
|
|
17
|
+
|
|
18
|
+
type UserID = number
|
|
19
|
+
|
|
20
|
+
interface User {
|
|
21
|
+
id: UserID
|
|
22
|
+
username: string
|
|
23
|
+
email: string
|
|
24
|
+
isActive: boolean
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
interface UserPreferences {
|
|
28
|
+
theme: "light" | "dark" | "system"
|
|
29
|
+
notificationsEnabled: boolean
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
interface Order {
|
|
33
|
+
id: string
|
|
34
|
+
total: number
|
|
35
|
+
status: "pending" | "completed"
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
interface EnrichedUser {
|
|
39
|
+
user: User
|
|
40
|
+
preferences: UserPreferences
|
|
41
|
+
recentOrders: Order[]
|
|
42
|
+
lifetimeValue: number
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Custom Errors
|
|
46
|
+
class NotFoundError extends Error {
|
|
47
|
+
readonly _tag = "NotFoundError"
|
|
48
|
+
constructor(message: string) {
|
|
49
|
+
super(message)
|
|
50
|
+
this.name = "NotFoundError"
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
class ValidationError extends Error {
|
|
55
|
+
readonly _tag = "ValidationError"
|
|
56
|
+
constructor(message: string) {
|
|
57
|
+
super(message)
|
|
58
|
+
this.name = "ValidationError"
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
class ServiceUnavailableError extends Error {
|
|
63
|
+
readonly _tag = "ServiceUnavailableError"
|
|
64
|
+
constructor(service: string) {
|
|
65
|
+
super(`${service} unavailable`)
|
|
66
|
+
this.name = "ServiceUnavailableError"
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// ============================================================================
|
|
71
|
+
// 2. Mock Services
|
|
72
|
+
// ============================================================================
|
|
73
|
+
|
|
74
|
+
const DB = {
|
|
75
|
+
users: new Map<UserID, User>([
|
|
76
|
+
[
|
|
77
|
+
1,
|
|
78
|
+
{
|
|
79
|
+
id: 1,
|
|
80
|
+
username: "alice_w",
|
|
81
|
+
email: "alice@example.com",
|
|
82
|
+
isActive: true,
|
|
83
|
+
},
|
|
84
|
+
],
|
|
85
|
+
[
|
|
86
|
+
2,
|
|
87
|
+
{
|
|
88
|
+
id: 2,
|
|
89
|
+
username: "bob_builder",
|
|
90
|
+
email: "bob@example.com",
|
|
91
|
+
isActive: false,
|
|
92
|
+
},
|
|
93
|
+
],
|
|
94
|
+
]),
|
|
95
|
+
prefs: new Map<UserID, UserPreferences>([
|
|
96
|
+
[1, { theme: "dark", notificationsEnabled: true }],
|
|
97
|
+
]),
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const UserRepository = {
|
|
101
|
+
findById: async (id: UserID): Promise<Result<User, NotFoundError>> => {
|
|
102
|
+
// Simulate DB latency
|
|
103
|
+
await new Promise((r) => setTimeout(r, 10))
|
|
104
|
+
|
|
105
|
+
const user = DB.users.get(id)
|
|
106
|
+
return user
|
|
107
|
+
? Result.Ok(user)
|
|
108
|
+
: Result.Err(new NotFoundError(`User ${id} not found`))
|
|
109
|
+
},
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const PreferencesService = {
|
|
113
|
+
getPreferences: async (id: UserID): Promise<Option<UserPreferences>> => {
|
|
114
|
+
await new Promise((r) => setTimeout(r, 10))
|
|
115
|
+
return Option.fromNullable(DB.prefs.get(id))
|
|
116
|
+
},
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const OrderService = {
|
|
120
|
+
getRecentOrders: async (
|
|
121
|
+
id: UserID,
|
|
122
|
+
): Promise<Result<Order[], ServiceUnavailableError>> => {
|
|
123
|
+
await new Promise((r) => setTimeout(r, 20))
|
|
124
|
+
|
|
125
|
+
// Simulate random service failure for demo
|
|
126
|
+
if (Math.random() < 0.1) {
|
|
127
|
+
return Result.Err(new ServiceUnavailableError("OrderService"))
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
if (id === 1) {
|
|
131
|
+
return Result.Ok([
|
|
132
|
+
{ id: "ord_123", total: 100, status: "completed" },
|
|
133
|
+
{ id: "ord_456", total: 49.99, status: "pending" },
|
|
134
|
+
])
|
|
135
|
+
}
|
|
136
|
+
return Result.Ok([])
|
|
137
|
+
},
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// ============================================================================
|
|
141
|
+
// 3. Main Logic: Enriched User Fow
|
|
142
|
+
// ============================================================================
|
|
143
|
+
|
|
144
|
+
// Default preferences if none found
|
|
145
|
+
const DEFAULT_PREFS: UserPreferences = {
|
|
146
|
+
theme: "system",
|
|
147
|
+
notificationsEnabled: false,
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const enrichUser = (userId: number) =>
|
|
151
|
+
Flow.asyncGenAdapter(async function* ($) {
|
|
152
|
+
// 1. Validation Logic (Synchronous Result)
|
|
153
|
+
if (userId <= 0) {
|
|
154
|
+
yield* $(Result.Err(new ValidationError("User ID must be positive")))
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// 2. Fetch User (Async Result)
|
|
158
|
+
// The adapter automatically awaits the Promise and unwraps the Result
|
|
159
|
+
console.log(`[Flow] Fetching user ${userId}...`)
|
|
160
|
+
const user = yield* $(UserRepository.findById(userId))
|
|
161
|
+
|
|
162
|
+
// 3. Early exit if inactive
|
|
163
|
+
if (!user.isActive) {
|
|
164
|
+
yield* $(Result.Err(new ValidationError("User is inactive")))
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// 4. Fetch Preferences (Async Option) & Orders (Async Result) in parallel
|
|
168
|
+
// We can use Promise.all to fetch them concurrently, then yield* to unwrap
|
|
169
|
+
console.log(`[Flow] Fetching details for ${user.username}...`)
|
|
170
|
+
|
|
171
|
+
const [prefsOpt, ordersRes] = await Promise.all([
|
|
172
|
+
PreferencesService.getPreferences(user.id),
|
|
173
|
+
OrderService.getRecentOrders(user.id),
|
|
174
|
+
])
|
|
175
|
+
|
|
176
|
+
// Unwrap Orders (Result) - will bubble up ServiceUnavailableError if failed
|
|
177
|
+
const orders = yield* $(ordersRes)
|
|
178
|
+
|
|
179
|
+
// Unwrap Preferences (Option) - we want to provide a default if None,
|
|
180
|
+
// rather than halting the flow (which yielding a None would do).
|
|
181
|
+
// So we DON'T use yield* on the Option directly here.
|
|
182
|
+
const preferences = prefsOpt.unwrapOr(DEFAULT_PREFS)
|
|
183
|
+
|
|
184
|
+
// 5. Aggregate Data
|
|
185
|
+
const lifetimeValue = orders.reduce(
|
|
186
|
+
(sum, ord) => (ord.status === "completed" ? sum + ord.total : sum),
|
|
187
|
+
0,
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
const enriched: EnrichedUser = {
|
|
191
|
+
user,
|
|
192
|
+
preferences,
|
|
193
|
+
recentOrders: orders,
|
|
194
|
+
lifetimeValue,
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
return enriched
|
|
198
|
+
})
|
|
199
|
+
|
|
200
|
+
// ============================================================================
|
|
201
|
+
// 4. Execution Examples
|
|
202
|
+
// ============================================================================
|
|
203
|
+
|
|
204
|
+
async function runDemo() {
|
|
205
|
+
console.log("--- Scenario 1: Happy Path (Alice) ---")
|
|
206
|
+
const res1 = await enrichUser(1)
|
|
207
|
+
/*
|
|
208
|
+
* We can match on the final result to handle success/failure
|
|
209
|
+
*/
|
|
210
|
+
res1.match({
|
|
211
|
+
Ok: (data) => console.log("SUCCESS:", JSON.stringify(data, null, 2)),
|
|
212
|
+
Err: (err) => console.error("FAILURE:", err.message),
|
|
213
|
+
})
|
|
214
|
+
|
|
215
|
+
console.log("\n--- Scenario 2: User Not Found (ID 99) ---")
|
|
216
|
+
const res2 = await enrichUser(99)
|
|
217
|
+
console.log(
|
|
218
|
+
"Result:",
|
|
219
|
+
res2.isErr() ? `Left(${res2.unwrapErr().message})` : "Ok",
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
console.log("\n--- Scenario 3: Validation Error (ID -5) ---")
|
|
223
|
+
const res3 = await enrichUser(-5)
|
|
224
|
+
console.log(
|
|
225
|
+
"Result:",
|
|
226
|
+
res3.isErr() ? `Left(${res3.unwrapErr().message})` : "Ok",
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
console.log("\n--- Scenario 4: Logical Validation (Bob - Inactive) ---")
|
|
230
|
+
const res4 = await enrichUser(2)
|
|
231
|
+
console.log(
|
|
232
|
+
"Result:",
|
|
233
|
+
res4.isErr() ? `Left(${res4.unwrapErr().message})` : "Ok",
|
|
234
|
+
)
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
runDemo().catch(console.error)
|