functype 1.27.1 → 2.0.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 +63 -88
- package/dist/_virtual/_rolldown/runtime.js +1 -0
- package/dist/branded/ValidatedBrand.d.ts +122 -0
- package/dist/branded/ValidatedBrand.js +1 -0
- package/dist/branded/index.d.ts +52 -2
- package/dist/cli/data.d.ts +37 -0
- package/dist/cli/data.js +1 -0
- package/dist/cli/exports.d.ts +5 -46
- package/dist/cli/exports.js +1 -1
- package/dist/cli/formatters.js +4 -0
- package/dist/cli/full-interfaces.d.ts +6 -0
- package/dist/cli/full-interfaces.js +1139 -0
- package/dist/cli/index.js +3 -6
- package/dist/cli/interfaces.generated.js +1 -0
- package/dist/collections/index.d.ts +13 -0
- package/dist/companion/Companion.d.ts +23 -0
- package/dist/companion/Companion.js +1 -0
- package/dist/companion/CompanionTypes.d.ts +30 -0
- package/dist/{CompanionTypes-BVqO7Kc2.js → companion/CompanionTypes.js} +1 -1
- package/dist/companion/index.d.ts +2 -1
- package/dist/companion/index.js +1 -1
- package/dist/conditional/Cond.d.ts +147 -0
- package/dist/conditional/Cond.js +1 -0
- package/dist/conditional/Match.d.ts +295 -0
- package/dist/conditional/Match.js +1 -0
- package/dist/conditional/index.d.ts +3 -2
- package/dist/conditional/index.js +1 -1
- package/dist/core/base/Base.d.ts +12 -0
- package/dist/core/base/Base.js +1 -0
- package/dist/core/throwable/Throwable.d.ts +38 -0
- package/dist/core/throwable/Throwable.js +1 -0
- package/dist/decoder/Decoder.d.ts +15 -0
- package/dist/decoder/DecoderCompanion.js +1 -0
- package/dist/decoder/DecoderError.d.ts +56 -0
- package/dist/decoder/DecoderError.js +2 -0
- package/dist/decoder/Encoder.d.ts +15 -0
- package/dist/decoder/index.d.ts +71 -2
- package/dist/decoder/index.js +1 -1
- package/dist/decoder/tagged.js +1 -0
- package/dist/do/index.d.ts +246 -2
- package/dist/do/index.js +1 -1
- package/dist/do/protocol.d.ts +29 -0
- package/dist/either/index.d.ts +279 -2
- package/dist/either/index.js +1 -1
- package/dist/error/ErrorChain.d.ts +60 -0
- package/dist/error/ErrorChain.js +4 -0
- package/dist/error/ErrorFormatter.d.ts +67 -0
- package/dist/error/ErrorFormatter.js +6 -0
- package/dist/error/ParseError.d.ts +6 -0
- package/dist/error/ParseError.js +1 -0
- package/dist/error/typed/TypedError.d.ts +146 -0
- package/dist/error/typed/TypedError.js +1 -0
- package/dist/error/typed/Validation.d.ts +76 -0
- package/dist/error/typed/Validation.js +1 -0
- package/dist/extractable/Extractable.d.ts +62 -0
- package/dist/extractable/Extractable.js +1 -0
- package/dist/fetch/Http.d.ts +32 -0
- package/dist/fetch/Http.js +1 -0
- package/dist/fetch/HttpClient.d.ts +80 -0
- package/dist/fetch/HttpClient.js +1 -0
- package/dist/fetch/HttpError.d.ts +57 -0
- package/dist/fetch/HttpError.js +1 -0
- package/dist/fetch/HttpRequest.d.ts +103 -0
- package/dist/fetch/index.d.ts +5 -2
- package/dist/fetch/index.js +1 -1
- package/dist/foldable/Foldable.d.ts +27 -0
- package/dist/foldable/index.d.ts +55 -0
- package/dist/foldable/index.js +1 -0
- package/dist/functype/Functype.d.ts +76 -0
- package/dist/functype/FunctypeSum.d.ts +39 -0
- package/dist/functype/index.d.ts +4 -2
- package/dist/hkt/index.d.ts +68 -0
- package/dist/hkt/index.js +1 -0
- package/dist/identity/Identity.d.ts +34 -0
- package/dist/identity/Identity.js +1 -0
- package/dist/index.d.ts +74 -8
- package/dist/index.js +1 -1
- package/dist/internal/base64.js +1 -0
- package/dist/internal/call-alone.js +1 -0
- package/dist/internal/concurrency.d.ts +11 -0
- package/dist/internal/concurrency.js +1 -0
- package/dist/internal/define.js +1 -0
- package/dist/internal/mutation-utils.js +1 -0
- package/dist/internal/signal.js +1 -0
- package/dist/internal/stringify.js +1 -0
- package/dist/invariant/index.d.ts +32 -2
- package/dist/io/Context.d.ts +112 -0
- package/dist/io/Context.js +1 -0
- package/dist/io/Exit.d.ts +249 -0
- package/dist/io/Exit.js +1 -0
- package/dist/io/IO.d.ts +1243 -0
- package/dist/io/IO.js +1 -0
- package/dist/io/Layer.d.ts +139 -0
- package/dist/io/Layer.js +1 -0
- package/dist/io/SpanTracer.d.ts +78 -0
- package/dist/io/SpanTracer.js +1 -0
- package/dist/io/Tag.d.ts +75 -0
- package/dist/io/Tag.js +1 -0
- package/dist/io/TestClock.d.ts +133 -0
- package/dist/io/TestClock.js +1 -0
- package/dist/io/index.d.ts +41 -2
- package/dist/io/index.js +1 -1
- package/dist/lazy/Lazy.d.ts +312 -0
- package/dist/lazy/Lazy.js +1 -0
- package/dist/lazy/index.d.ts +2 -2
- package/dist/lazy/index.js +1 -1
- package/dist/list/LazyList.d.ts +182 -0
- package/dist/list/LazyList.js +1 -0
- package/dist/list/index.d.ts +137 -2
- package/dist/list/index.js +1 -1
- package/dist/logger/index.d.ts +24 -2
- package/dist/map/index.d.ts +95 -2
- package/dist/map/index.js +1 -1
- package/dist/map/shim.d.ts +13 -0
- package/dist/map/shim.js +1 -0
- package/dist/matchable/Matchable.d.ts +38 -0
- package/dist/matchable/Matchable.js +1 -0
- package/dist/obj/Obj.d.ts +212 -0
- package/dist/obj/Obj.js +1 -0
- package/dist/obj/index.d.ts +2 -2
- package/dist/obj/index.js +1 -1
- package/dist/option/index.d.ts +304 -2
- package/dist/option/index.js +1 -1
- package/dist/package.json.js +1 -0
- package/dist/pipe/index.d.ts +14 -0
- package/dist/ref/Ref.d.ts +77 -0
- package/dist/ref/Ref.js +1 -0
- package/dist/reshapeable/Reshapeable.d.ts +90 -0
- package/dist/serializable/Serializable.d.ts +39 -0
- package/dist/serialization/Serialization.d.ts +147 -0
- package/dist/serialization/Serialization.js +1 -0
- package/dist/serialization/SerializationCompanion.d.ts +125 -0
- package/dist/serialization/SerializationCompanion.js +1 -0
- package/dist/serialization/error-envelope.d.ts +44 -0
- package/dist/serialization/error-envelope.js +1 -0
- package/dist/serialization/index.d.ts +4 -2
- package/dist/serialization/index.js +1 -1
- package/dist/set/index.d.ts +106 -2
- package/dist/set/index.js +1 -1
- package/dist/stack/Stack.d.ts +120 -0
- package/dist/stack/Stack.js +1 -0
- package/dist/traced/TraceEvent.d.ts +27 -0
- package/dist/traced/TracedOption.d.ts +46 -0
- package/dist/traced/TracedOption.js +1 -0
- package/dist/traced/Tracer.d.ts +26 -0
- package/dist/traversable/KVTraversable.d.ts +14 -0
- package/dist/traversable/Traversable.d.ts +30 -0
- package/dist/try/index.d.ts +238 -2
- package/dist/try/index.js +1 -1
- package/dist/tuple/index.d.ts +92 -2
- package/dist/tuple/index.js +1 -1
- package/dist/typeable/Typeable.d.ts +40 -0
- package/dist/typeable/Typeable.js +1 -0
- package/dist/typeclass/ContainerOps.d.ts +131 -0
- package/dist/typeclass/Functor.d.ts +41 -0
- package/dist/typeclass/Promisable.d.ts +33 -0
- package/dist/typeclass/index.d.ts +4 -1
- package/dist/typeclass/index.js +1 -1
- package/dist/typeclass/variance.d.ts +54 -0
- package/dist/typeclass/variance.js +1 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/util/index.d.ts +1 -3
- package/dist/valuable/Valuable.d.ts +28 -0
- package/dist/valuable/Valuable.js +1 -0
- package/dist/wire/index.d.ts +40 -2
- package/package.json +7 -12
- package/dist/Brand-bfnGXuum.d.ts +0 -54
- package/dist/Companion-DiOMBHDG.js +0 -1
- package/dist/CompanionTypes-Cc90cQ4P.d.ts +0 -58
- package/dist/Invariant-DEan-SxV.d.ts +0 -35
- package/dist/Logger-BmprRS8v.d.ts +0 -27
- package/dist/Tuple-B8KM-H8Y.d.ts +0 -213
- package/dist/Wire-3hvw0Ogg.d.ts +0 -42
- package/dist/core/task/index.d.ts +0 -2
- package/dist/core/task/index.js +0 -1
- package/dist/full-interfaces-0XJEOHi_.js +0 -1202
- package/dist/index-CLYh2qZu.d.ts +0 -6649
- package/dist/rolldown-runtime-DK3Fl9T5.js +0 -1
- package/dist/serialization-9_SyrfdG.js +0 -3
- package/dist/src-BTLBc-KK.js +0 -10
- package/dist/typeclass-C61yDVYd.js +0 -1
package/dist/io/IO.d.ts
ADDED
|
@@ -0,0 +1,1243 @@
|
|
|
1
|
+
import { Either } from "../either/index.js";
|
|
2
|
+
import { Concurrency, ConcurrencyOptions } from "../internal/concurrency.js";
|
|
3
|
+
import { Option } from "../option/index.js";
|
|
4
|
+
import { Try } from "../try/index.js";
|
|
5
|
+
import { Type } from "../types/index.js";
|
|
6
|
+
import { Context } from "./Context.js";
|
|
7
|
+
import { Exit } from "./Exit.js";
|
|
8
|
+
import { Layer } from "./Layer.js";
|
|
9
|
+
import { SpanAttributes } from "./SpanTracer.js";
|
|
10
|
+
import { Tag, TagService } from "./Tag.js";
|
|
11
|
+
/**
|
|
12
|
+
* Error thrown when an effect times out.
|
|
13
|
+
*/
|
|
14
|
+
export declare class TimeoutError extends Error {
|
|
15
|
+
readonly duration: number;
|
|
16
|
+
readonly _tag: "TimeoutError";
|
|
17
|
+
constructor(duration: number, message?: string);
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Error thrown when an effect is interrupted.
|
|
21
|
+
*/
|
|
22
|
+
export declare class InterruptedError extends Error {
|
|
23
|
+
readonly _tag: "InterruptedError";
|
|
24
|
+
constructor(message?: string);
|
|
25
|
+
/**
|
|
26
|
+
* Runtime type guard. Use it to recognise a cancellation when the `E` channel has
|
|
27
|
+
* collapsed to `unknown` (effects built with `IO.async` or `IO(...)`), where
|
|
28
|
+
* `catchTag("InterruptedError", …)` can't typecheck.
|
|
29
|
+
*/
|
|
30
|
+
static is(e: unknown): e is InterruptedError;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Error thrown when a combinator that cannot run on the synchronous interpreter is
|
|
34
|
+
* reached by `runSync`. `timeout`, `race` and `sleep` (with `IO.never` and `.delay`, which
|
|
35
|
+
* are built on it) are inherently asynchronous — there is no sync semantics for "wait `ms`",
|
|
36
|
+
* "wait `ms` then give up", or for racing concurrent effects.
|
|
37
|
+
*
|
|
38
|
+
* This is a **programmer error, not a domain failure**: it says the effect was built
|
|
39
|
+
* wrong for the terminal it was run with, so recovery combinators deliberately do not
|
|
40
|
+
* catch it (see {@link syncErrorChannel}). Before it had its own type it was a
|
|
41
|
+
* plain `Error`, indistinguishable from a failed effect, so any downstream `.recover()`
|
|
42
|
+
* absorbed it and silently produced the fallback — `IO.succeed(1).timeoutTo(50, 99)`
|
|
43
|
+
* returned `Right(99)` under `runSync()`. See #246. It is a defect, so `runSync()` throws it.
|
|
44
|
+
*/
|
|
45
|
+
export declare class UnsupportedSyncOperationError extends Error {
|
|
46
|
+
readonly operation: "timeout" | "race" | "sleep";
|
|
47
|
+
readonly _tag: "UnsupportedSyncOperationError";
|
|
48
|
+
constructor(operation: "timeout" | "race" | "sleep");
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Error surfaced by value-driven repeat combinators when the iteration bound is
|
|
52
|
+
* reached without the predicate being satisfied. Carries the last observed
|
|
53
|
+
* value so callers can report what the loop settled on.
|
|
54
|
+
*
|
|
55
|
+
* Type parameter `A` is the value type the loop was producing (or the state
|
|
56
|
+
* type for `IO.iterate`).
|
|
57
|
+
*
|
|
58
|
+
* ## Narrowing when `E` is `unknown`
|
|
59
|
+
*
|
|
60
|
+
* If the step effect has `E = unknown` (common when lifting a Promise via
|
|
61
|
+
* `IO(() => ...)` or `IO.async(...)` — see the JSDoc on those constructors),
|
|
62
|
+
* TypeScript's union algebra collapses `unknown | RepeatExhausted<A>` back to
|
|
63
|
+
* `unknown`, and `RepeatExhausted<A>` is lost from the surface type. The
|
|
64
|
+
* runtime behavior is still correct (the `RepeatExhausted` instance is in the
|
|
65
|
+
* `Left` at runtime — see reporter's JSON in issue #221) — but consumers need
|
|
66
|
+
* a narrowing step to recover it. Use `RepeatExhausted.is`:
|
|
67
|
+
*
|
|
68
|
+
* @example
|
|
69
|
+
* ```ts
|
|
70
|
+
* const res = await IO.iterate(seed, step, done, { max: 20 }).run()
|
|
71
|
+
* res.fold(
|
|
72
|
+
* (e) => {
|
|
73
|
+
* if (RepeatExhausted.is<StepState>(e)) {
|
|
74
|
+
* // e is now RepeatExhausted<StepState>; e.lastValue is StepState
|
|
75
|
+
* return e.lastValue
|
|
76
|
+
* }
|
|
77
|
+
* // e is still the collapsed E channel — handle as the caller sees fit
|
|
78
|
+
* throw e as Error
|
|
79
|
+
* },
|
|
80
|
+
* (settled) => settled,
|
|
81
|
+
* )
|
|
82
|
+
* ```
|
|
83
|
+
*
|
|
84
|
+
* The alternative — annotating `step`'s error channel so `E` is a concrete
|
|
85
|
+
* tagged type — also works and preserves `RepeatExhausted<A>` in the union:
|
|
86
|
+
*
|
|
87
|
+
* @example
|
|
88
|
+
* ```ts
|
|
89
|
+
* const step = (s: S): IO<never, never, S> =>
|
|
90
|
+
* IO(() => runOnce(s)).mapError((_e) => _e as never)
|
|
91
|
+
* // iterate result E channel: never | RepeatExhausted<S> === RepeatExhausted<S>
|
|
92
|
+
* ```
|
|
93
|
+
*/
|
|
94
|
+
export declare class RepeatExhausted<A = unknown> extends Error {
|
|
95
|
+
readonly max: number;
|
|
96
|
+
readonly lastValue?: A | undefined;
|
|
97
|
+
readonly _tag: "RepeatExhausted";
|
|
98
|
+
constructor(max: number, lastValue?: A | undefined, message?: string);
|
|
99
|
+
/**
|
|
100
|
+
* Runtime type guard. Narrows an `unknown` (or wider) value to
|
|
101
|
+
* `RepeatExhausted<A>` when the tag matches. Use this to recover typed
|
|
102
|
+
* exhaustion when the `E` channel has collapsed to `unknown` — a common
|
|
103
|
+
* situation when the step effect is lifted from a Promise via `IO(...)` or
|
|
104
|
+
* `IO.async(...)`. See the class-level JSDoc for a full example.
|
|
105
|
+
*
|
|
106
|
+
* The type parameter `A` is an unchecked assertion — the guard confirms the
|
|
107
|
+
* shape is a `RepeatExhausted`, but cannot verify `lastValue` matches `A` at
|
|
108
|
+
* runtime. Callers pass the state/value type they expect the loop to have
|
|
109
|
+
* been producing.
|
|
110
|
+
*/
|
|
111
|
+
static is<A = unknown>(e: unknown): e is RepeatExhausted<A>;
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* IO Effect type module - a lazy, composable effect type with typed errors.
|
|
115
|
+
* @module IO
|
|
116
|
+
* @category IO
|
|
117
|
+
*
|
|
118
|
+
* IO<R, E, A> represents an effectful computation that:
|
|
119
|
+
* - Requires environment R to run
|
|
120
|
+
* - May fail with error E
|
|
121
|
+
* - Produces value A on success
|
|
122
|
+
*
|
|
123
|
+
* Key features:
|
|
124
|
+
* - Lazy execution (nothing runs until explicitly executed)
|
|
125
|
+
* - Unified sync/async API
|
|
126
|
+
* - Typed errors at compile time
|
|
127
|
+
* - Composable via map/flatMap
|
|
128
|
+
*/
|
|
129
|
+
/**
|
|
130
|
+
* The key an IO keeps its effect under: an IO's one own field, its data.
|
|
131
|
+
*
|
|
132
|
+
* It is a plain string key so test matchers compare it. With a symbol key, vitest's `toEqual`
|
|
133
|
+
* walked the IO's iterator, met the IO itself, and saw no string keys, so it called any two IOs
|
|
134
|
+
* equal. It used to be a symbol so IO.gen's yields would assign without deep variance failures;
|
|
135
|
+
* test/io/io-variance.spec.ts guards that, and passes with this key too.
|
|
136
|
+
* @internal
|
|
137
|
+
*/
|
|
138
|
+
export declare const IOEffectKey: "effect";
|
|
139
|
+
export type IOEffectKey = typeof IOEffectKey;
|
|
140
|
+
/**
|
|
141
|
+
* Internal effect representation types
|
|
142
|
+
*/
|
|
143
|
+
type IOEffect<R, E, A> = {
|
|
144
|
+
readonly _tag: "Sync";
|
|
145
|
+
readonly thunk: () => A;
|
|
146
|
+
} | {
|
|
147
|
+
readonly _tag: "Async";
|
|
148
|
+
readonly thunk: (signal?: AbortSignal) => Promise<A>;
|
|
149
|
+
} | {
|
|
150
|
+
readonly _tag: "Auto";
|
|
151
|
+
readonly thunk: () => A | Promise<A>;
|
|
152
|
+
} | {
|
|
153
|
+
readonly _tag: "Succeed";
|
|
154
|
+
readonly value: A;
|
|
155
|
+
} | {
|
|
156
|
+
readonly _tag: "Fail";
|
|
157
|
+
readonly error: E;
|
|
158
|
+
} | {
|
|
159
|
+
readonly _tag: "Die";
|
|
160
|
+
readonly defect: unknown;
|
|
161
|
+
} | {
|
|
162
|
+
readonly _tag: "Interrupt";
|
|
163
|
+
} | {
|
|
164
|
+
readonly _tag: "Sleep";
|
|
165
|
+
readonly duration: number;
|
|
166
|
+
} | {
|
|
167
|
+
readonly _tag: "FlatMap";
|
|
168
|
+
readonly effect: IO<R, E, unknown>;
|
|
169
|
+
readonly f: (a: unknown) => IO<R, E, A>;
|
|
170
|
+
} | {
|
|
171
|
+
readonly _tag: "Map";
|
|
172
|
+
readonly effect: IO<R, E, unknown>;
|
|
173
|
+
readonly f: (a: unknown) => A;
|
|
174
|
+
} | {
|
|
175
|
+
readonly _tag: "MapError";
|
|
176
|
+
readonly effect: IO<R, unknown, A>;
|
|
177
|
+
readonly f: (e: unknown) => E;
|
|
178
|
+
} | {
|
|
179
|
+
readonly _tag: "Recover";
|
|
180
|
+
readonly effect: IO<R, E, A>;
|
|
181
|
+
readonly fallback: A;
|
|
182
|
+
} | {
|
|
183
|
+
readonly _tag: "RecoverWith";
|
|
184
|
+
readonly effect: IO<R, unknown, unknown>;
|
|
185
|
+
readonly f: (e: unknown) => IO<R, E, A>;
|
|
186
|
+
} | {
|
|
187
|
+
readonly _tag: "Fold";
|
|
188
|
+
readonly effect: IO<R, unknown, unknown>;
|
|
189
|
+
readonly onFailure: (e: unknown) => A;
|
|
190
|
+
readonly onSuccess: (a: unknown) => A;
|
|
191
|
+
} | {
|
|
192
|
+
readonly _tag: "Bracket";
|
|
193
|
+
readonly acquire: IO<R, E, unknown>;
|
|
194
|
+
readonly use: (a: unknown) => IO<R, E, A>;
|
|
195
|
+
readonly release: (a: unknown) => IO<R, never, void>;
|
|
196
|
+
} | {
|
|
197
|
+
readonly _tag: "BracketExit";
|
|
198
|
+
readonly acquire: IO<R, E, unknown>;
|
|
199
|
+
readonly use: (a: unknown) => IO<R, E, A>;
|
|
200
|
+
readonly release: (a: unknown, exit: Exit<unknown, unknown>) => IO<R, never, void>;
|
|
201
|
+
} | {
|
|
202
|
+
readonly _tag: "Race";
|
|
203
|
+
readonly effects: readonly IO<R, E, A>[];
|
|
204
|
+
} | {
|
|
205
|
+
readonly _tag: "Timeout";
|
|
206
|
+
readonly effect: IO<R, E, A>;
|
|
207
|
+
readonly duration: number;
|
|
208
|
+
} | {
|
|
209
|
+
readonly _tag: "InterruptWhen";
|
|
210
|
+
readonly effect: IO<R, E, A>;
|
|
211
|
+
readonly signal: AbortSignal;
|
|
212
|
+
} | {
|
|
213
|
+
readonly _tag: "All";
|
|
214
|
+
readonly effects: readonly IO<R, E, unknown>[];
|
|
215
|
+
readonly concurrency: Concurrency;
|
|
216
|
+
} | {
|
|
217
|
+
readonly _tag: "Service";
|
|
218
|
+
readonly tag: Tag<A>;
|
|
219
|
+
} | {
|
|
220
|
+
readonly _tag: "ProvideContext";
|
|
221
|
+
readonly effect: IO<R, E, A>;
|
|
222
|
+
readonly context: Context<R>;
|
|
223
|
+
} | {
|
|
224
|
+
readonly _tag: "WithSpan";
|
|
225
|
+
readonly effect: IO<R, E, A>;
|
|
226
|
+
readonly name: string;
|
|
227
|
+
readonly attributes: SpanAttributes;
|
|
228
|
+
} | {
|
|
229
|
+
readonly _tag: "Gen";
|
|
230
|
+
readonly start: () => Iterator<unknown, A, unknown>;
|
|
231
|
+
};
|
|
232
|
+
/**
|
|
233
|
+
* The `this` an IO's run methods accept. An IO whose services are all provided (`R = never`) runs
|
|
234
|
+
* as itself. Any other IO gets a type whose one key says what to do, so calling `run()` on it fails
|
|
235
|
+
* with that sentence and the services it still needs, rather than with `IO<never, E, A>`.
|
|
236
|
+
* @internal
|
|
237
|
+
*/
|
|
238
|
+
export type Runnable<R, E extends Type, A extends Type> = [R] extends [never] ? IO<never, E, A> : {
|
|
239
|
+
readonly "Provide these services first, with provideLayer or provideService": R;
|
|
240
|
+
};
|
|
241
|
+
/**
|
|
242
|
+
* The tags `catchTag` accepts: the `_tag` of each error in `E` that has one. When there is none to
|
|
243
|
+
* catch, it is a sentence saying why, which is what a call then fails with: `E` is `never`, so the
|
|
244
|
+
* IO can't fail, or no error in `E` has a `_tag`, such as a plain `Error` or `unknown`.
|
|
245
|
+
* @internal
|
|
246
|
+
*/
|
|
247
|
+
export type CatchableTag<E> = [E] extends [never] ? "This IO can't fail (its error type is never), so there is nothing to catch" : [TagOf<E>] extends [never] ? "catchTag needs errors with a _tag field: use catchAll or recoverWith for this error type" : TagOf<E>;
|
|
248
|
+
type TagOf<E> = E extends {
|
|
249
|
+
readonly _tag: string;
|
|
250
|
+
} ? E["_tag"] : never;
|
|
251
|
+
/**
|
|
252
|
+
* What `IO.gen` accepts from a `yield`: an IO. It names an IO's own data key and its
|
|
253
|
+
* `Symbol.toStringTag`, not `IO<any, any, any>`, which failed deep structural variance checks on
|
|
254
|
+
* yields such as `IO<never, never, void>`. Anything else, such as an Option, a Promise or a plain
|
|
255
|
+
* `{ effect }` object, fails to compile: the error is reported on the generator passed to `IO.gen`,
|
|
256
|
+
* and names the yielded type. Before, any value with a `Symbol.toStringTag` passed, and died at
|
|
257
|
+
* run time.
|
|
258
|
+
* @internal
|
|
259
|
+
*/
|
|
260
|
+
export interface IOYieldable {
|
|
261
|
+
readonly [IOEffectKey]: unknown;
|
|
262
|
+
readonly [Symbol.toStringTag]: string;
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* The services an `IO.gen` body needs: the union of every yielded IO's `R`.
|
|
266
|
+
* It distributes over the union of yielded IOs, and is `never` when the body yields none. A yielded
|
|
267
|
+
* `any` (`0 extends 1 & Y`) names no services, so the IO can still run.
|
|
268
|
+
* @internal
|
|
269
|
+
*/
|
|
270
|
+
export type IOGenRequirements<Y> = 0 extends 1 & Y ? never : Y extends IO<infer R, infer _E, infer _A> ? R : never;
|
|
271
|
+
/**
|
|
272
|
+
* The errors an `IO.gen` body can fail with: the union of every yielded IO's `E`, or `unknown` for a
|
|
273
|
+
* yielded `any`.
|
|
274
|
+
* @internal
|
|
275
|
+
*/
|
|
276
|
+
export type IOGenErrors<Y> = 0 extends 1 & Y ? unknown : Y extends IO<infer _R, infer E, infer _A> ? E : never;
|
|
277
|
+
/**
|
|
278
|
+
* IO<R, E, A> represents a lazy, composable effect.
|
|
279
|
+
*
|
|
280
|
+
* @typeParam R - Requirements (environment/dependencies needed to run)
|
|
281
|
+
* @typeParam E - Error type (typed failures)
|
|
282
|
+
* @typeParam A - Success type (value produced on success)
|
|
283
|
+
*/
|
|
284
|
+
export interface IO<in out R extends Type, out E extends Type, out A extends Type> {
|
|
285
|
+
readonly [Symbol.toStringTag]: string;
|
|
286
|
+
/**
|
|
287
|
+
* Internal effect representation (symbol-keyed for opacity)
|
|
288
|
+
* @internal
|
|
289
|
+
*/
|
|
290
|
+
readonly [IOEffectKey]: IOEffect<R, E, A>;
|
|
291
|
+
/**
|
|
292
|
+
* Transforms the success value.
|
|
293
|
+
* @param f - Function to apply to the success value
|
|
294
|
+
* @returns New IO with transformed value
|
|
295
|
+
*/
|
|
296
|
+
map<B extends Type>(f: (a: A) => B): IO<R, E, B>;
|
|
297
|
+
/**
|
|
298
|
+
* Chains another IO effect based on the success value.
|
|
299
|
+
* @param f - Function returning next IO effect
|
|
300
|
+
* @returns New IO with combined effects
|
|
301
|
+
*/
|
|
302
|
+
flatMap<R2 extends Type, E2 extends Type, B extends Type>(f: (a: A) => IO<R2, E2, B>): IO<R | R2, E | E2, B>;
|
|
303
|
+
/**
|
|
304
|
+
* Applies a side effect without changing the value.
|
|
305
|
+
* @param f - Side effect function
|
|
306
|
+
* @returns Same IO for chaining
|
|
307
|
+
*/
|
|
308
|
+
tap(f: (a: A) => void): IO<R, E, A>;
|
|
309
|
+
/**
|
|
310
|
+
* Applies an effectful side effect without changing the value.
|
|
311
|
+
* @param f - Function returning IO for side effect
|
|
312
|
+
* @returns Same value after running side effect
|
|
313
|
+
*/
|
|
314
|
+
tapEffect<R2 extends Type, E2 extends Type, B extends Type>(f: (a: A) => IO<R2, E2, B>): IO<R | R2, E | E2, A>;
|
|
315
|
+
/**
|
|
316
|
+
* Transforms the error value.
|
|
317
|
+
* @param f - Function to apply to the error
|
|
318
|
+
* @returns New IO with transformed error
|
|
319
|
+
*/
|
|
320
|
+
mapError<E2 extends Type>(f: (e: E) => E2): IO<R, E2, A>;
|
|
321
|
+
/**
|
|
322
|
+
* Executes a side effect on the error without changing it.
|
|
323
|
+
* Useful for logging errors while preserving the error chain.
|
|
324
|
+
*
|
|
325
|
+
* @param f - Side effect function to run on error
|
|
326
|
+
* @returns Same IO with the side effect attached
|
|
327
|
+
*
|
|
328
|
+
* @example
|
|
329
|
+
* ```typescript
|
|
330
|
+
* const io = IO.asyncResult(() => query(), toError)
|
|
331
|
+
* .tapError(err => console.error('Query failed:', err))
|
|
332
|
+
* .map(data => transform(data))
|
|
333
|
+
* ```
|
|
334
|
+
*/
|
|
335
|
+
tapError(f: (e: E) => void): IO<R, E, A>;
|
|
336
|
+
/**
|
|
337
|
+
* Recovers from any error with a fallback value.
|
|
338
|
+
* @param fallback - Value to use on error
|
|
339
|
+
* @returns New IO that never fails
|
|
340
|
+
*/
|
|
341
|
+
recover<B extends Type>(fallback: B): IO<R, never, A | B>;
|
|
342
|
+
/**
|
|
343
|
+
* Recovers from error by running another effect.
|
|
344
|
+
* @param f - Function returning recovery effect
|
|
345
|
+
* @returns New IO with error handling
|
|
346
|
+
*/
|
|
347
|
+
recoverWith<R2 extends Type, E2 extends Type, B extends Type>(f: (e: E) => IO<R2, E2, B>): IO<R | R2, E2, A | B>;
|
|
348
|
+
/**
|
|
349
|
+
* Pattern matches on success and failure.
|
|
350
|
+
* @param onFailure - Handler for failures
|
|
351
|
+
* @param onSuccess - Handler for successes
|
|
352
|
+
* @returns New IO with handled result
|
|
353
|
+
*/
|
|
354
|
+
fold<B extends Type>(onFailure: (e: E) => B, onSuccess: (a: A) => B): IO<R, never, B>;
|
|
355
|
+
/**
|
|
356
|
+
* Pattern matches with object pattern syntax.
|
|
357
|
+
*/
|
|
358
|
+
match<B extends Type>(patterns: {
|
|
359
|
+
failure: (e: E) => B;
|
|
360
|
+
success: (a: A) => B;
|
|
361
|
+
}): IO<R, never, B>;
|
|
362
|
+
/**
|
|
363
|
+
* Catches errors with a specific tag and handles them.
|
|
364
|
+
* @param tag - The error tag to catch
|
|
365
|
+
* @param handler - Handler for the caught error
|
|
366
|
+
*/
|
|
367
|
+
catchTag<K extends CatchableTag<E>, R2 extends Type, E2 extends Type, B extends Type>(tag: K, handler: (e: Extract<E, {
|
|
368
|
+
_tag: K;
|
|
369
|
+
}>) => IO<R2, E2, B>): IO<R | R2, Exclude<E, {
|
|
370
|
+
_tag: K;
|
|
371
|
+
}> | E2, A | B>;
|
|
372
|
+
/**
|
|
373
|
+
* Catches all errors (alias for recoverWith).
|
|
374
|
+
*/
|
|
375
|
+
catchAll<R2 extends Type, E2 extends Type, B extends Type>(handler: (e: E) => IO<R2, E2, B>): IO<R | R2, E2, A | B>;
|
|
376
|
+
/**
|
|
377
|
+
* Retries the effect up to n times on failure.
|
|
378
|
+
* @param n - Maximum number of retries
|
|
379
|
+
*/
|
|
380
|
+
retry(n: number): IO<R, E, A>;
|
|
381
|
+
/**
|
|
382
|
+
* Retries the effect with a delay between attempts.
|
|
383
|
+
* @param n - Maximum number of retries
|
|
384
|
+
* @param delayMs - Delay between retries in milliseconds
|
|
385
|
+
*/
|
|
386
|
+
retryWithDelay(n: number, delayMs: number): IO<R, E, A>;
|
|
387
|
+
/**
|
|
388
|
+
* Retries the effect only while a predicate over the error holds.
|
|
389
|
+
*
|
|
390
|
+
* Useful for selective retry policies — e.g. retry HTTP 5xx but not 4xx,
|
|
391
|
+
* retry network errors but not validation errors. The predicate is evaluated
|
|
392
|
+
* BEFORE each retry; returning `false` short-circuits and re-fails with the
|
|
393
|
+
* original error.
|
|
394
|
+
*
|
|
395
|
+
* @param opts.n - Maximum number of retry attempts.
|
|
396
|
+
* @param opts.while - Predicate `(error, attempt) => boolean` (attempt is 1-indexed
|
|
397
|
+
* for the first retry; if the predicate returns false, the retry is skipped).
|
|
398
|
+
* @param opts.delayMs - Optional fixed delay between attempts.
|
|
399
|
+
*
|
|
400
|
+
* @example
|
|
401
|
+
* ```ts
|
|
402
|
+
* Http.get("/api/users", { decode })
|
|
403
|
+
* .retryWhile({
|
|
404
|
+
* n: 3,
|
|
405
|
+
* while: (e) => e._tag === "HttpStatusError" && e.status >= 500,
|
|
406
|
+
* delayMs: 250,
|
|
407
|
+
* })
|
|
408
|
+
* ```
|
|
409
|
+
*/
|
|
410
|
+
retryWhile(opts: {
|
|
411
|
+
readonly n: number;
|
|
412
|
+
readonly while: (error: E, attempt: number) => boolean;
|
|
413
|
+
readonly delayMs?: number;
|
|
414
|
+
}): IO<R, E, A>;
|
|
415
|
+
/**
|
|
416
|
+
* Retries the effect with exponential backoff and optional full jitter.
|
|
417
|
+
*
|
|
418
|
+
* Delay schedule: `min(maxMs, baseMs * factor^(attempt-1))`. With jitter
|
|
419
|
+
* enabled, the actual delay is `computed * (0.5 + Math.random() * 0.5)`
|
|
420
|
+
* (full jitter, 50–100% of the computed value) — prevents thundering herd.
|
|
421
|
+
*
|
|
422
|
+
* @param opts.n - Maximum number of retry attempts.
|
|
423
|
+
* @param opts.baseMs - Initial delay before the first retry.
|
|
424
|
+
* @param opts.maxMs - Cap on per-attempt delay. Defaults to 30_000.
|
|
425
|
+
* @param opts.factor - Backoff multiplier per attempt. Defaults to 2.
|
|
426
|
+
* @param opts.jitter - Apply full jitter (50–100% of computed delay). Defaults to true.
|
|
427
|
+
* @param opts.while - Optional predicate `(error, attempt) => boolean` gating each retry.
|
|
428
|
+
*
|
|
429
|
+
* @example
|
|
430
|
+
* ```ts
|
|
431
|
+
* const isRetryable = (e: HttpError): boolean =>
|
|
432
|
+
* e._tag === "NetworkError" ||
|
|
433
|
+
* (e._tag === "HttpStatusError" && (e.status >= 500 || e.status === 429))
|
|
434
|
+
*
|
|
435
|
+
* Http.get("/api/users", { decode })
|
|
436
|
+
* .retryWithBackoff({ n: 3, baseMs: 250, while: isRetryable })
|
|
437
|
+
* .timeout(10_000)
|
|
438
|
+
* ```
|
|
439
|
+
*/
|
|
440
|
+
retryWithBackoff(opts: {
|
|
441
|
+
readonly n: number;
|
|
442
|
+
readonly baseMs: number;
|
|
443
|
+
readonly maxMs?: number;
|
|
444
|
+
readonly factor?: number;
|
|
445
|
+
readonly jitter?: boolean;
|
|
446
|
+
readonly while?: (error: E, attempt: number) => boolean;
|
|
447
|
+
}): IO<R, E, A>;
|
|
448
|
+
/**
|
|
449
|
+
* Re-runs the effect until its output satisfies `done`, or the `max` bound is hit.
|
|
450
|
+
*
|
|
451
|
+
* Value-channel dual of `retryWhile`: this repeats on success values that
|
|
452
|
+
* haven't yet met the predicate, whereas the retry* family repeats on failure.
|
|
453
|
+
* The first failure short-circuits and propagates unchanged. Compose the two
|
|
454
|
+
* axes when both matter:
|
|
455
|
+
*
|
|
456
|
+
* @example
|
|
457
|
+
* ```ts
|
|
458
|
+
* pollJob
|
|
459
|
+
* .retry(3) // error axis
|
|
460
|
+
* .repeatUntil((job) => job.done, { max: 20, delayMs: 500 }) // value axis
|
|
461
|
+
* ```
|
|
462
|
+
*
|
|
463
|
+
* @param done - Pure sync predicate. Loop stops (successfully) when this returns true.
|
|
464
|
+
* @param opts.max - Maximum iterations before exhaustion is signaled.
|
|
465
|
+
* @param opts.delayMs - Optional fixed delay between iterations.
|
|
466
|
+
* @returns The satisfying value, or `RepeatExhausted<A>` in the error channel
|
|
467
|
+
* (carrying the last observed value) if the bound is reached first.
|
|
468
|
+
*/
|
|
469
|
+
repeatUntil(done: (a: A) => boolean, opts: {
|
|
470
|
+
readonly max: number;
|
|
471
|
+
readonly delayMs?: number;
|
|
472
|
+
}): IO<R, E | RepeatExhausted<A>, A>;
|
|
473
|
+
/**
|
|
474
|
+
* Re-runs the effect while `cont` holds, or until the `max` bound is hit.
|
|
475
|
+
*
|
|
476
|
+
* Symmetric sibling of `repeatUntil` — mirrors the naming of `retryWhile`.
|
|
477
|
+
* `repeatWhile(cont)` is equivalent to `repeatUntil((a) => !cont(a))`; the
|
|
478
|
+
* loop stops successfully as soon as `cont` returns false.
|
|
479
|
+
*
|
|
480
|
+
* @param cont - Pure sync predicate. Loop continues while this returns true.
|
|
481
|
+
* @param opts.max - Maximum iterations before exhaustion is signaled.
|
|
482
|
+
* @param opts.delayMs - Optional fixed delay between iterations.
|
|
483
|
+
*/
|
|
484
|
+
repeatWhile(cont: (a: A) => boolean, opts: {
|
|
485
|
+
readonly max: number;
|
|
486
|
+
readonly delayMs?: number;
|
|
487
|
+
}): IO<R, E | RepeatExhausted<A>, A>;
|
|
488
|
+
/**
|
|
489
|
+
* Sequences two IOs, keeping the second value.
|
|
490
|
+
*/
|
|
491
|
+
zipRight<R2 extends Type, E2 extends Type, B extends Type>(that: IO<R2, E2, B>): IO<R | R2, E | E2, B>;
|
|
492
|
+
/**
|
|
493
|
+
* Sequences two IOs, keeping the first value.
|
|
494
|
+
*/
|
|
495
|
+
zipLeft<R2 extends Type, E2 extends Type, B extends Type>(that: IO<R2, E2, B>): IO<R | R2, E | E2, A>;
|
|
496
|
+
/**
|
|
497
|
+
* Zips two IOs into a tuple.
|
|
498
|
+
*/
|
|
499
|
+
zip<R2 extends Type, E2 extends Type, B extends Type>(that: IO<R2, E2, B>): IO<R | R2, E | E2, readonly [A, B]>;
|
|
500
|
+
/**
|
|
501
|
+
* Flattens a nested IO.
|
|
502
|
+
*/
|
|
503
|
+
flatten<R2 extends Type, E2 extends Type, B extends Type>(this: IO<R, E, IO<R2, E2, B>>): IO<R | R2, E | E2, B>;
|
|
504
|
+
/**
|
|
505
|
+
* Provides a context to satisfy the requirements of this effect.
|
|
506
|
+
* @param context - The context containing required services
|
|
507
|
+
*/
|
|
508
|
+
provideContext<R2 extends Type>(context: Context<R2>): IO<Exclude<R, R2>, E, A>;
|
|
509
|
+
/**
|
|
510
|
+
* Provides a single service to satisfy part of the requirements.
|
|
511
|
+
* @param tag - The service tag
|
|
512
|
+
* @param service - The service implementation
|
|
513
|
+
*/
|
|
514
|
+
provideService<S extends Type>(tag: Tag<S>, service: S): IO<Exclude<R, S>, E, A>;
|
|
515
|
+
/**
|
|
516
|
+
* Provides services using a layer.
|
|
517
|
+
*
|
|
518
|
+
* The layer may provide services the effect's `R` doesn't name, such as a `SpanTracer` for
|
|
519
|
+
* the `withSpan` calls inside it, which read the tracer without requiring it.
|
|
520
|
+
* @param layer - The layer that provides services
|
|
521
|
+
*/
|
|
522
|
+
provideLayer<RIn extends Type, E2 extends Type, ROut extends Type>(layer: Layer<RIn, E2, ROut>): IO<RIn | Exclude<R, ROut>, E | E2, A>;
|
|
523
|
+
/**
|
|
524
|
+
* Runs the effect and returns an Either of its typed error or its value.
|
|
525
|
+
*
|
|
526
|
+
* The `Left` holds only a typed failure, an `E`. A defect (a bug: a throw from `IO.sync`, a
|
|
527
|
+
* `map` callback, `IO.die`) rejects the promise with the thrown value, and an interruption
|
|
528
|
+
* rejects it with an `InterruptedError`. Use {@link runExit} to get all four outcomes without
|
|
529
|
+
* a rejection. An `interruptOn` region turns its cancellation into a typed `InterruptedError`,
|
|
530
|
+
* so that one resolves as a `Left`.
|
|
531
|
+
* Requires R = never.
|
|
532
|
+
*/
|
|
533
|
+
run(this: Runnable<R, E, A>): Promise<Either<E, A>>;
|
|
534
|
+
/**
|
|
535
|
+
* Runs the effect and returns a Promise of the value.
|
|
536
|
+
* Throws on any error (typed E, defect, or interrupt).
|
|
537
|
+
* Requires R = never.
|
|
538
|
+
*/
|
|
539
|
+
runOrThrow(this: Runnable<R, E, A>): Promise<A>;
|
|
540
|
+
/**
|
|
541
|
+
* Runs a sync effect and returns an Either of its typed error or its value.
|
|
542
|
+
*
|
|
543
|
+
* Like {@link run}, the `Left` holds only a typed failure. A defect is thrown as is, and an
|
|
544
|
+
* interruption as an `InterruptedError`. An effect it can't run synchronously is a defect too:
|
|
545
|
+
* an `IO.async` throws an `Error`, and `timeout`, `race` and `sleep` throw
|
|
546
|
+
* {@link UnsupportedSyncOperationError}.
|
|
547
|
+
* Requires R = never.
|
|
548
|
+
*/
|
|
549
|
+
runSync(this: Runnable<R, E, A>): Either<E, A>;
|
|
550
|
+
/**
|
|
551
|
+
* Runs a sync effect and returns the value.
|
|
552
|
+
* Throws on any error or if the effect is async.
|
|
553
|
+
* Requires R = never.
|
|
554
|
+
*/
|
|
555
|
+
runSyncOrThrow(this: Runnable<R, E, A>): A;
|
|
556
|
+
/**
|
|
557
|
+
* Runs the effect and returns an Exit.
|
|
558
|
+
*
|
|
559
|
+
* With `options.signal`, the run stops at the next step once the signal aborts and
|
|
560
|
+
* returns an `Interrupted` Exit, with the same rules as {@link IO.interruptOn}: no further
|
|
561
|
+
* step or callback runs, recovery can't swallow it, and cleanup completes. Unlike
|
|
562
|
+
* `interruptOn`, `E` is not widened: the cancellation is reported as `Interrupted`, not as
|
|
563
|
+
* a typed `InterruptedError`. This suits runners (React hooks, query adapters) that
|
|
564
|
+
* discard a cancelled result rather than handle it.
|
|
565
|
+
*/
|
|
566
|
+
runExit(this: Runnable<R, E, A>, options?: {
|
|
567
|
+
readonly signal?: AbortSignal;
|
|
568
|
+
}): Promise<Exit<E, A>>;
|
|
569
|
+
/**
|
|
570
|
+
* Runs the effect and returns an Option.
|
|
571
|
+
* Some(value) on success, None on failure.
|
|
572
|
+
*/
|
|
573
|
+
runOption(this: Runnable<R, E, A>): Promise<Option<A>>;
|
|
574
|
+
/**
|
|
575
|
+
* Runs the effect and returns a Try.
|
|
576
|
+
* Success(value) on success, Failure(error) on failure.
|
|
577
|
+
*/
|
|
578
|
+
runTry(this: Runnable<R, E, A>): Promise<ReturnType<typeof Try<A>>>;
|
|
579
|
+
/**
|
|
580
|
+
* Starts the effect and returns a handle that cancels it, with {@link IO.interruptOn}
|
|
581
|
+
* semantics: after `cancel()`, no further step runs and `result` resolves to
|
|
582
|
+
* `Left(InterruptedError)`. Calling `cancel()` after the effect finished does nothing.
|
|
583
|
+
* As with {@link run}, a defect rejects `result`.
|
|
584
|
+
* Requires R = never.
|
|
585
|
+
*
|
|
586
|
+
* @example
|
|
587
|
+
* ```typescript
|
|
588
|
+
* const { result, cancel } = loadReport.runCancellable()
|
|
589
|
+
* onUnmount(cancel)
|
|
590
|
+
* const report = await result
|
|
591
|
+
* ```
|
|
592
|
+
*/
|
|
593
|
+
runCancellable(this: Runnable<R, E, A>): {
|
|
594
|
+
readonly result: Promise<Either<E | InterruptedError, A>>;
|
|
595
|
+
readonly cancel: () => void;
|
|
596
|
+
};
|
|
597
|
+
/**
|
|
598
|
+
* Pipes the IO through a function.
|
|
599
|
+
*/
|
|
600
|
+
pipe<B>(f: (self: IO<R, E, A>) => B): B;
|
|
601
|
+
/**
|
|
602
|
+
* Delays execution by the specified milliseconds. The wait is an {@link IO.sleep}, so an
|
|
603
|
+
* interruption ends it at once.
|
|
604
|
+
*/
|
|
605
|
+
delay(ms: number): IO<R, E, A>;
|
|
606
|
+
/**
|
|
607
|
+
* Fails with TimeoutError if the effect doesn't complete within the specified duration.
|
|
608
|
+
*
|
|
609
|
+
* At the deadline the effect is interrupted: it starts no new step, a sleep in it wakes, and
|
|
610
|
+
* an `IO.async` thunk sees its signal abort. The `TimeoutError` comes back at once. An effect
|
|
611
|
+
* that ignores cancellation may still be running then; its `bracket` release runs when it
|
|
612
|
+
* settles. When the effect finishes first, the timer is cleared.
|
|
613
|
+
* @param ms - Maximum time in milliseconds
|
|
614
|
+
*/
|
|
615
|
+
timeout(ms: number): IO<R, E | TimeoutError, A>;
|
|
616
|
+
/**
|
|
617
|
+
* Returns a fallback value if the effect doesn't complete within the specified duration.
|
|
618
|
+
* @param ms - Maximum time in milliseconds
|
|
619
|
+
* @param fallback - Value to return on timeout
|
|
620
|
+
*/
|
|
621
|
+
timeoutTo<B extends Type>(ms: number, fallback: B): IO<R, E, A | B>;
|
|
622
|
+
/**
|
|
623
|
+
* Makes this effect cancellable by an `AbortSignal`, such as the one React Query or a
|
|
624
|
+
* request handler provides.
|
|
625
|
+
*
|
|
626
|
+
* Once the signal aborts, no further step starts. The effect stops at the next step
|
|
627
|
+
* boundary (between `flatMap`s, retries, repeat iterations and `IO.gen` yields), and no
|
|
628
|
+
* `map`, `recover` or other callback inside it runs after that. The result is a failure
|
|
629
|
+
* with `InterruptedError`, which `catchTag("InterruptedError", …)` can handle outside this
|
|
630
|
+
* call. Inside it, `retry`, `recover` and `catchAll` cannot swallow the cancellation.
|
|
631
|
+
*
|
|
632
|
+
* - `bracket` / `acquireRelease` cleanup still runs, to completion: acquire and release
|
|
633
|
+
* are not interruptible.
|
|
634
|
+
* - `IO.sleep`, `IO.never` and `.delay` wake at once: the wait ends as the cancellation and
|
|
635
|
+
* its timer is cleared. The waits inside `retryWithDelay`, `retryWhile`,
|
|
636
|
+
* `retryWithBackoff`, `repeatUntil` and `repeatWhile` are sleeps too.
|
|
637
|
+
* - A promise already in flight can't be stopped (JavaScript has no way to). The
|
|
638
|
+
* cancellation is seen at the next step after it settles, so if that promise was the
|
|
639
|
+
* effect's last step, the effect succeeds with its result. `IO.async` and `IO.tryPromise`
|
|
640
|
+
* thunks receive the region's signal as their argument, so `IO.async((signal) =>
|
|
641
|
+
* fetch(url, { signal }))` aborts the request itself; its rejection is reported as the
|
|
642
|
+
* cancellation. `IO(() => …)` thunks get no signal.
|
|
643
|
+
* - A defect (a bug) that happens after the abort is still reported as a defect.
|
|
644
|
+
* - `runSync` only sees a signal that was already aborted when this effect starts.
|
|
645
|
+
* - When `E` is `unknown` (effects from `IO.async` or `IO(...)`), the union collapses to
|
|
646
|
+
* `unknown`; use `InterruptedError.is(e)` to recognise the cancellation.
|
|
647
|
+
*
|
|
648
|
+
* @example
|
|
649
|
+
* ```typescript
|
|
650
|
+
* const poll = checkStatus.repeatUntil((s) => s.done, { max: 60, delayMs: 500 })
|
|
651
|
+
* const result = await poll.interruptOn(signal).run()
|
|
652
|
+
* // Left(InterruptedError) if the signal aborts first, and polling has stopped
|
|
653
|
+
* ```
|
|
654
|
+
*/
|
|
655
|
+
interruptOn(signal: AbortSignal): IO<R, E | InterruptedError, A>;
|
|
656
|
+
/**
|
|
657
|
+
* Runs this effect in a span named `name`, through the {@link SpanTracer} provided to the run.
|
|
658
|
+
* A `withSpan` inside it opens its span under this one, without being passed a parent.
|
|
659
|
+
*
|
|
660
|
+
* - The span is active for the whole body, through the tracer's `run`: a log sink inside can
|
|
661
|
+
* read the trace IDs, including after an `await` in an `IO.async` thunk.
|
|
662
|
+
* - Every outcome closes it exactly once: success, typed failure, defect and interruption.
|
|
663
|
+
* A failure after the run was cancelled, such as a `race` loser's aborted `fetch`, closes it
|
|
664
|
+
* as interrupted. A loser that ignores the signal closes when it finishes, with its own
|
|
665
|
+
* outcome, such as `Success`; one that never settles never closes its span.
|
|
666
|
+
* - With no tracer provided, it does nothing: same result, nothing recorded.
|
|
667
|
+
* - Provide the tracer outside the spans: `io.withSpan("a").provideService(SpanTracer, t)`,
|
|
668
|
+
* or with a layer, `provideLayer(Layer.succeed(SpanTracer, t))`. A span outside the
|
|
669
|
+
* provide sees no tracer.
|
|
670
|
+
* - It works under `runSync` too, because a tracer's `run` is synchronous.
|
|
671
|
+
* - Parallel children of `IO.all`, `race` and `timeout` each nest under the enclosing span and
|
|
672
|
+
* don't see each other's.
|
|
673
|
+
*
|
|
674
|
+
* @param name - The span's name
|
|
675
|
+
* @param attributes - Attributes recorded on the span
|
|
676
|
+
*
|
|
677
|
+
* @example
|
|
678
|
+
* ```typescript
|
|
679
|
+
* const program = fetchUser(id).withSpan("fetchUser", { "user.id": id })
|
|
680
|
+
* await program.provideService(SpanTracer, tracer).run()
|
|
681
|
+
* ```
|
|
682
|
+
*/
|
|
683
|
+
withSpan(name: string, attributes?: SpanAttributes): IO<R, E, A>;
|
|
684
|
+
/**
|
|
685
|
+
* Converts to string representation.
|
|
686
|
+
*/
|
|
687
|
+
toString(): string;
|
|
688
|
+
/**
|
|
689
|
+
* Converts to JSON representation.
|
|
690
|
+
*/
|
|
691
|
+
toJSON(): {
|
|
692
|
+
_tag: string;
|
|
693
|
+
effect: unknown;
|
|
694
|
+
};
|
|
695
|
+
/**
|
|
696
|
+
* Makes IO iterable for generator do-notation (yield* syntax).
|
|
697
|
+
* Yields the IO itself, allowing IO.gen to extract the value.
|
|
698
|
+
*/
|
|
699
|
+
[Symbol.iterator](): Iterator<IO<R, E, A>, A, unknown>;
|
|
700
|
+
}
|
|
701
|
+
/**
|
|
702
|
+
* Do-builder interface for chaining binds and maps
|
|
703
|
+
*/
|
|
704
|
+
interface DoBuilder<R extends Type, E extends Type, Ctx extends Record<string, Type>> {
|
|
705
|
+
/**
|
|
706
|
+
* The underlying IO effect
|
|
707
|
+
*/
|
|
708
|
+
readonly effect: IO<R, E, Ctx>;
|
|
709
|
+
/**
|
|
710
|
+
* Binds the result of an effect to a named property in the context.
|
|
711
|
+
* @param name - The property name to bind to
|
|
712
|
+
* @param f - Function that returns an IO effect (receives current context)
|
|
713
|
+
*/
|
|
714
|
+
bind<N extends string, R2 extends Type, E2 extends Type, A extends Type>(name: Exclude<N, keyof Ctx>, f: (ctx: Ctx) => IO<R2, E2, A>): DoBuilder<R | R2, E | E2, Ctx & Record<N, A>>;
|
|
715
|
+
/**
|
|
716
|
+
* Binds a pure value to a named property in the context.
|
|
717
|
+
* @param name - The property name to bind to
|
|
718
|
+
* @param f - Function that returns a value (receives current context)
|
|
719
|
+
*/
|
|
720
|
+
let<N extends string, A extends Type>(name: Exclude<N, keyof Ctx>, f: (ctx: Ctx) => A): DoBuilder<R, E, Ctx & Record<N, A>>;
|
|
721
|
+
/**
|
|
722
|
+
* Transforms the final context value.
|
|
723
|
+
* @param f - Function to transform the context
|
|
724
|
+
*/
|
|
725
|
+
map<B extends Type>(f: (ctx: Ctx) => B): IO<R, E, B>;
|
|
726
|
+
/**
|
|
727
|
+
* Chains to another IO based on the context.
|
|
728
|
+
* @param f - Function that returns an IO effect
|
|
729
|
+
*/
|
|
730
|
+
flatMap<R2 extends Type, E2 extends Type, B extends Type>(f: (ctx: Ctx) => IO<R2, E2, B>): IO<R | R2, E | E2, B>;
|
|
731
|
+
/**
|
|
732
|
+
* Executes a side effect without changing the context.
|
|
733
|
+
* @param f - Side effect function
|
|
734
|
+
*/
|
|
735
|
+
tap(f: (ctx: Ctx) => void): DoBuilder<R, E, Ctx>;
|
|
736
|
+
/**
|
|
737
|
+
* Executes an effectful side effect without changing the context.
|
|
738
|
+
* @param f - Function returning an IO for the side effect
|
|
739
|
+
*/
|
|
740
|
+
tapEffect<R2 extends Type, E2 extends Type, B extends Type>(f: (ctx: Ctx) => IO<R2, E2, B>): DoBuilder<R | R2, E | E2, Ctx>;
|
|
741
|
+
/**
|
|
742
|
+
* Returns the final context as is.
|
|
743
|
+
*/
|
|
744
|
+
done(): IO<R, E, Ctx>;
|
|
745
|
+
}
|
|
746
|
+
/**
|
|
747
|
+
* IO constructor - creates an IO from a function.
|
|
748
|
+
* Automatically detects if the function returns a Promise and handles it appropriately.
|
|
749
|
+
*
|
|
750
|
+
* @example
|
|
751
|
+
* ```typescript
|
|
752
|
+
* // Sync usage
|
|
753
|
+
* const syncIO = IO(() => 42)
|
|
754
|
+
*
|
|
755
|
+
* // Async usage - auto-detected
|
|
756
|
+
* const asyncIO = IO(() => fetch('/api/data'))
|
|
757
|
+
* ```
|
|
758
|
+
*/
|
|
759
|
+
declare const IOConstructor: <A extends Type>(f: () => A | Promise<A>) => IO<never, unknown, A>;
|
|
760
|
+
declare const IOStatics: {
|
|
761
|
+
/**
|
|
762
|
+
* Creates an IO from a synchronous thunk.
|
|
763
|
+
* The function is not executed until the IO is run.
|
|
764
|
+
*/
|
|
765
|
+
sync: <A extends Type>(f: () => A) => IO<never, never, A>;
|
|
766
|
+
/**
|
|
767
|
+
* Creates an IO that succeeds with the given value.
|
|
768
|
+
*/
|
|
769
|
+
succeed: <A extends Type>(value: A) => IO<never, never, A>;
|
|
770
|
+
/**
|
|
771
|
+
* Creates an IO that fails with the given error.
|
|
772
|
+
*/
|
|
773
|
+
fail: <E extends Type>(error: E) => IO<never, E, never>;
|
|
774
|
+
/**
|
|
775
|
+
* Creates an IO that dies with an unrecoverable defect.
|
|
776
|
+
*/
|
|
777
|
+
die: (defect: unknown) => IO<never, never, never>;
|
|
778
|
+
/**
|
|
779
|
+
* Creates an IO from an async thunk.
|
|
780
|
+
* The Promise is not created until the IO is run.
|
|
781
|
+
*
|
|
782
|
+
* Inside an `interruptOn` region (or `runCancellable`, or `runExit({ signal })`), the thunk
|
|
783
|
+
* receives the region's abort signal; pass it to `fetch` and the request stops when the run is
|
|
784
|
+
* cancelled. Inside `race`, `timeout` or an `IO.all` with more than one effect in flight, it
|
|
785
|
+
* always receives a signal, which aborts when the combinator stops it. Elsewhere it receives
|
|
786
|
+
* `undefined`. A function whose first parameter is
|
|
787
|
+
* something else (`(page = 1) => load(page)`) would receive the signal in that slot, so wrap
|
|
788
|
+
* it: `IO.async(() => load())`.
|
|
789
|
+
*/
|
|
790
|
+
async: <A extends Type>(f: (signal?: AbortSignal) => Promise<A>) => IO<never, unknown, A>;
|
|
791
|
+
/**
|
|
792
|
+
* Creates an IO from a Promise with error handling.
|
|
793
|
+
* `try` receives the region's abort signal, as `IO.async`'s thunk does.
|
|
794
|
+
*/
|
|
795
|
+
tryPromise: <A extends Type, E extends Type>(opts: {
|
|
796
|
+
readonly try: (signal?: AbortSignal) => Promise<A>;
|
|
797
|
+
readonly catch: (error: unknown) => E;
|
|
798
|
+
}) => IO<never, E, A>;
|
|
799
|
+
/**
|
|
800
|
+
* Creates an IO from a function that might throw.
|
|
801
|
+
*/
|
|
802
|
+
tryCatch: <A extends Type, E extends Type>(f: () => A, onError: (error: unknown) => E) => IO<never, E, A>;
|
|
803
|
+
/**
|
|
804
|
+
* Lifts a synchronous function into an IO-returning function.
|
|
805
|
+
*/
|
|
806
|
+
liftSync: <Args extends unknown[], A extends Type>(f: (...args: Args) => A) => (...args: Args) => IO<never, never, A>;
|
|
807
|
+
/**
|
|
808
|
+
* Lifts a Promise-returning function into an IO-returning function.
|
|
809
|
+
*/
|
|
810
|
+
liftPromise: <Args extends unknown[], A extends Type>(f: (...args: Args) => Promise<A>) => (...args: Args) => IO<never, unknown, A>;
|
|
811
|
+
/**
|
|
812
|
+
* Creates an IO from an Either.
|
|
813
|
+
*/
|
|
814
|
+
fromEither: <E extends Type, A extends Type>(either: Either<E, A>) => IO<never, E, A>;
|
|
815
|
+
/**
|
|
816
|
+
* Lifts an async function that returns `Either<E, A>` into `IO<never, E, A>`, keeping `E` typed.
|
|
817
|
+
* The promise is not created until the IO is run.
|
|
818
|
+
*
|
|
819
|
+
* A Left becomes a failure in the E channel. A rejected promise is a defect by default (the function
|
|
820
|
+
* is not expected to throw); pass `onReject` to map rejections into the error channel instead.
|
|
821
|
+
*
|
|
822
|
+
* @example
|
|
823
|
+
* ```typescript
|
|
824
|
+
* const save = (row: Row): Promise<Either<SaveError, Saved>> => ...
|
|
825
|
+
*
|
|
826
|
+
* IO.forEach(rows, (row) => IO.fromPromiseEither(() => save(row))).run()
|
|
827
|
+
* // Promise<Either<SaveError, readonly Saved[]>>, in order, stopping at the first Left
|
|
828
|
+
* ```
|
|
829
|
+
*/
|
|
830
|
+
fromPromiseEither: <E extends Type, A extends Type, E2 extends Type = never>(f: () => PromiseLike<Either<E, A>>, onReject?: (error: unknown) => E2) => IO<never, E | E2, A>;
|
|
831
|
+
/**
|
|
832
|
+
* Creates an IO from an Option.
|
|
833
|
+
*/
|
|
834
|
+
fromOption: <A extends Type>(option: Option<A>) => IO<never, void, A>;
|
|
835
|
+
/**
|
|
836
|
+
* Creates an IO from an Option with custom error.
|
|
837
|
+
*/
|
|
838
|
+
fromOptionOrFail: <E extends Type, A extends Type>(option: Option<A>, onNone: () => E) => IO<never, E, A>;
|
|
839
|
+
/**
|
|
840
|
+
* Creates an IO from a Try.
|
|
841
|
+
*/
|
|
842
|
+
fromTry: <A extends Type>(t: ReturnType<typeof Try<A>>) => IO<never, Error, A>;
|
|
843
|
+
/**
|
|
844
|
+
* Creates an IO from a result object with data/error pattern.
|
|
845
|
+
* If error is present (truthy), fails with the error.
|
|
846
|
+
* Otherwise succeeds with Option-wrapped data (None if data is null/undefined).
|
|
847
|
+
*
|
|
848
|
+
* This handles the common `{ data, error }` response pattern used by
|
|
849
|
+
* Supabase, many REST APIs, and similar libraries.
|
|
850
|
+
*
|
|
851
|
+
* @example
|
|
852
|
+
* ```typescript
|
|
853
|
+
* const response = { data: user, error: null }
|
|
854
|
+
* const io = IO.fromResult(response) // IO<never, null, Option<User>> -> Some(user)
|
|
855
|
+
*
|
|
856
|
+
* const emptyResponse = { data: null, error: null }
|
|
857
|
+
* const emptyIo = IO.fromResult(emptyResponse) // IO<never, null, Option<User>> -> None
|
|
858
|
+
*
|
|
859
|
+
* const errorResponse = { data: null, error: new Error("Not found") }
|
|
860
|
+
* const failedIo = IO.fromResult(errorResponse) // IO<never, Error, Option<null>> -> fails
|
|
861
|
+
* ```
|
|
862
|
+
*/
|
|
863
|
+
fromResult: <D extends Type, E extends Type>(result: {
|
|
864
|
+
data: D | null;
|
|
865
|
+
error: E | null;
|
|
866
|
+
}) => IO<never, E, Option<D>>;
|
|
867
|
+
/**
|
|
868
|
+
* Creates an IO from an async thunk with typed error handling.
|
|
869
|
+
* Catches any thrown errors and maps them using the provided function.
|
|
870
|
+
* Supports cancellation via AbortSignal.
|
|
871
|
+
*
|
|
872
|
+
* This is a simpler alternative to `tryPromise` that takes a direct
|
|
873
|
+
* error mapper function instead of an options object.
|
|
874
|
+
*
|
|
875
|
+
* @param f - Async function to execute (receives optional AbortSignal)
|
|
876
|
+
* @param onError - Function to map caught errors to typed error E
|
|
877
|
+
* @param signal - Optional AbortSignal for cancellation support
|
|
878
|
+
*
|
|
879
|
+
* @example
|
|
880
|
+
* ```typescript
|
|
881
|
+
* const io = IO.tryAsync(
|
|
882
|
+
* () => fetch('/api/users').then(r => r.json()),
|
|
883
|
+
* (e) => new ApiError(e)
|
|
884
|
+
* )
|
|
885
|
+
*
|
|
886
|
+
* // With cancellation:
|
|
887
|
+
* const controller = new AbortController()
|
|
888
|
+
* const io = IO.tryAsync(
|
|
889
|
+
* (signal) => fetch('/api/users', { signal }).then(r => r.json()),
|
|
890
|
+
* (e) => new ApiError(e),
|
|
891
|
+
* controller.signal
|
|
892
|
+
* )
|
|
893
|
+
* controller.abort() // Cancels the request
|
|
894
|
+
* ```
|
|
895
|
+
*/
|
|
896
|
+
tryAsync: <A extends Type, E extends Type>(f: (signal?: AbortSignal) => Promise<A>, onError: (error: unknown) => E, signal?: AbortSignal) => IO<never, E, A>;
|
|
897
|
+
/**
|
|
898
|
+
* Creates an IO from an async function that returns { data, error }.
|
|
899
|
+
* Handles both:
|
|
900
|
+
* - Thrown errors (mapped via onThrow)
|
|
901
|
+
* - Returned errors in the result object
|
|
902
|
+
* Supports cancellation via AbortSignal.
|
|
903
|
+
*
|
|
904
|
+
* This is the most ergonomic way to wrap Supabase and similar API calls.
|
|
905
|
+
*
|
|
906
|
+
* @param f - Async function returning { data, error } object (receives optional AbortSignal)
|
|
907
|
+
* @param onThrow - Function to map thrown errors to typed error E
|
|
908
|
+
* @param config - Optional configuration for custom field names and cancellation
|
|
909
|
+
*
|
|
910
|
+
* @example
|
|
911
|
+
* ```typescript
|
|
912
|
+
* // Supabase query in one line:
|
|
913
|
+
* const getUser = (id: string): IO<never, Error, Option<User>> =>
|
|
914
|
+
* IO.asyncResult(
|
|
915
|
+
* () => supabase.from('users').select('*').eq('id', id).single(),
|
|
916
|
+
* toError
|
|
917
|
+
* )
|
|
918
|
+
*
|
|
919
|
+
* // With custom field names:
|
|
920
|
+
* const result = IO.asyncResult(
|
|
921
|
+
* () => customApi.fetch(),
|
|
922
|
+
* toError,
|
|
923
|
+
* { dataKey: 'result', errorKey: 'err' }
|
|
924
|
+
* )
|
|
925
|
+
*
|
|
926
|
+
* // With cancellation:
|
|
927
|
+
* const controller = new AbortController()
|
|
928
|
+
* const getUser = IO.asyncResult(
|
|
929
|
+
* (signal) => supabase.from('users').abortSignal(signal).select('*').single(),
|
|
930
|
+
* toError,
|
|
931
|
+
* { signal: controller.signal }
|
|
932
|
+
* )
|
|
933
|
+
* controller.abort() // Cancels the request
|
|
934
|
+
* ```
|
|
935
|
+
*/
|
|
936
|
+
asyncResult: <D extends Type, E extends Type>(f: (signal?: AbortSignal) => Promise<Record<string, unknown>>, onThrow: (error: unknown) => E, config?: {
|
|
937
|
+
dataKey?: string;
|
|
938
|
+
errorKey?: string;
|
|
939
|
+
signal?: AbortSignal;
|
|
940
|
+
}) => IO<never, E, Option<D>>;
|
|
941
|
+
/**
|
|
942
|
+
* Creates an IO that requires a service identified by the tag.
|
|
943
|
+
* The service must be provided before the effect can be run. If it reaches the interpreter
|
|
944
|
+
* unprovided (through a cast), the run dies with a "Service not found" defect.
|
|
945
|
+
*
|
|
946
|
+
* @example
|
|
947
|
+
* ```typescript
|
|
948
|
+
* interface Logger {
|
|
949
|
+
* log(message: string): void
|
|
950
|
+
* }
|
|
951
|
+
* const Logger = Tag<Logger>("Logger")
|
|
952
|
+
*
|
|
953
|
+
* const program = IO.service(Logger).flatMap(logger =>
|
|
954
|
+
* IO.sync(() => logger.log("Hello!"))
|
|
955
|
+
* )
|
|
956
|
+
*
|
|
957
|
+
* // Provide the service to run
|
|
958
|
+
* program.provideService(Logger, consoleLogger).run()
|
|
959
|
+
* ```
|
|
960
|
+
*/
|
|
961
|
+
service: <S extends Type>(tag: Tag<S>) => IO<S, never, S>;
|
|
962
|
+
/**
|
|
963
|
+
* Accesses a service and applies a function to it.
|
|
964
|
+
*/
|
|
965
|
+
serviceWith: <S extends Type, A extends Type>(tag: Tag<S>, f: (service: S) => A) => IO<S, never, A>;
|
|
966
|
+
/**
|
|
967
|
+
* Accesses a service and applies an effectful function to it.
|
|
968
|
+
*/
|
|
969
|
+
serviceWithIO: <S extends Type, R extends Type, E extends Type, A extends Type>(tag: Tag<S>, f: (service: S) => IO<R, E, A>) => IO<S | R, E, A>;
|
|
970
|
+
/**
|
|
971
|
+
* Accesses multiple services and applies a function to them.
|
|
972
|
+
* Provides a convenient way to work with multiple dependencies.
|
|
973
|
+
*
|
|
974
|
+
* @example
|
|
975
|
+
* ```typescript
|
|
976
|
+
* const program = IO.withServices(
|
|
977
|
+
* { logger: Logger, db: Database },
|
|
978
|
+
* ({ logger, db }) => {
|
|
979
|
+
* logger.log("Querying...")
|
|
980
|
+
* return db.query("SELECT * FROM users")
|
|
981
|
+
* }
|
|
982
|
+
* )
|
|
983
|
+
* ```
|
|
984
|
+
*/
|
|
985
|
+
withServices: <Services extends Record<string, Tag<Type>>, A extends Type>(services: Services, f: (ctx: { [K in keyof Services]: TagService<Services[K]>; }) => A | Promise<A>) => IO<TagService<Services[keyof Services]>, unknown, A>;
|
|
986
|
+
/**
|
|
987
|
+
* Runs all IOs and collects the results in input order. Stops at the first failure.
|
|
988
|
+
*
|
|
989
|
+
* By default they all start at once. Pass `{ concurrency: n }` to run at most `n` at once, or
|
|
990
|
+
* `{ concurrency: 1 }` to run them one after another. With more than one in flight, the first
|
|
991
|
+
* failure is the result at once and the others are interrupted: they start no new step, a sleep
|
|
992
|
+
* in them wakes, and an `IO.async` thunk sees its signal abort. A promise that ignores its signal
|
|
993
|
+
* keeps running, but the result doesn't wait; its `bracket` release runs when it settles. An
|
|
994
|
+
* interruption of the run interrupts every effect.
|
|
995
|
+
*
|
|
996
|
+
* @example
|
|
997
|
+
* ```typescript
|
|
998
|
+
* const users = IO.all(ids.map(fetchUser), { concurrency: 4 })
|
|
999
|
+
* ```
|
|
1000
|
+
*/
|
|
1001
|
+
all: <R extends Type, E extends Type, A extends Type>(effects: readonly IO<R, E, A>[], options?: ConcurrencyOptions) => IO<R, E, readonly A[]>;
|
|
1002
|
+
/**
|
|
1003
|
+
* Runs IOs in sequence, returning the first success or last failure.
|
|
1004
|
+
* An empty array is a defect (`Die`), since no effect can succeed.
|
|
1005
|
+
* To run them at once and take the first to finish, use `IO.race`.
|
|
1006
|
+
*
|
|
1007
|
+
* @example
|
|
1008
|
+
* ```typescript
|
|
1009
|
+
* const result = await IO.firstSuccessOf([
|
|
1010
|
+
* IO.fail("error1"),
|
|
1011
|
+
* IO.succeed("success"),
|
|
1012
|
+
* IO.fail("error2")
|
|
1013
|
+
* ]).run() // Right("success")
|
|
1014
|
+
* ```
|
|
1015
|
+
*/
|
|
1016
|
+
firstSuccessOf: <R extends Type, E extends Type, A extends Type>(effects: readonly IO<R, E, A>[]) => IO<R, E, A>;
|
|
1017
|
+
/**
|
|
1018
|
+
* Creates an IO that waits for the given number of milliseconds, then succeeds.
|
|
1019
|
+
*
|
|
1020
|
+
* An interruption (`interruptOn`, `runCancellable`, `runExit({ signal })`, or a `race`,
|
|
1021
|
+
* `timeout` or parallel `IO.all` stopping it) ends the wait at once and clears its timer.
|
|
1022
|
+
* `runSync` can't sleep: it throws {@link UnsupportedSyncOperationError}.
|
|
1023
|
+
*/
|
|
1024
|
+
sleep: (ms: number) => IO<never, never, void>;
|
|
1025
|
+
/**
|
|
1026
|
+
* Effectful stateful loop — the value-driven dual of the retry family.
|
|
1027
|
+
*
|
|
1028
|
+
* Threads state `S` through an effectful `step` until `done(state)` holds, or
|
|
1029
|
+
* the `max` bound is reached. Semantics:
|
|
1030
|
+
*
|
|
1031
|
+
* - `done(seed)` is evaluated **before** the first `step` — an already-satisfied
|
|
1032
|
+
* seed returns immediately without executing the effect.
|
|
1033
|
+
* - The first `E` failure short-circuits the loop and propagates.
|
|
1034
|
+
* - `max` defaults to `10_000` and caps total step invocations to keep every
|
|
1035
|
+
* loop bounded by construction. Callers running larger iterations must set
|
|
1036
|
+
* `max` explicitly.
|
|
1037
|
+
* - Stack-safe: recursion happens via IO's `flatMap` trampoline, not the JS
|
|
1038
|
+
* call stack.
|
|
1039
|
+
*
|
|
1040
|
+
* @example
|
|
1041
|
+
* ```ts
|
|
1042
|
+
* // Poll for a completed job, threading the response through state.
|
|
1043
|
+
* const settled = await IO.iterate(
|
|
1044
|
+
* { status: "pending" as JobStatus },
|
|
1045
|
+
* (state) => fetchJob(state.id),
|
|
1046
|
+
* (state) => state.status === "done" || state.status === "failed",
|
|
1047
|
+
* { max: 30 },
|
|
1048
|
+
* ).run()
|
|
1049
|
+
* ```
|
|
1050
|
+
*
|
|
1051
|
+
* @param seed - Initial state.
|
|
1052
|
+
* @param step - Effect producing the next state from the current state.
|
|
1053
|
+
* @param done - Pure sync predicate over the state.
|
|
1054
|
+
* @param opts.max - Maximum step invocations (default `10_000`).
|
|
1055
|
+
* @returns The satisfying state, or `RepeatExhausted<S>` (carrying the last
|
|
1056
|
+
* observed state) if the bound is reached first.
|
|
1057
|
+
*/
|
|
1058
|
+
iterate: <R extends Type, E extends Type, S extends Type>(seed: S, step: (state: S) => IO<R, E, S>, done: (state: S) => boolean, opts?: {
|
|
1059
|
+
readonly max?: number;
|
|
1060
|
+
}) => IO<R, E | RepeatExhausted<S>, S>;
|
|
1061
|
+
/**
|
|
1062
|
+
* Creates an IO that never completes on its own. An interruption ends it, as it ends
|
|
1063
|
+
* {@link IO.sleep}; it sets no timer.
|
|
1064
|
+
*/
|
|
1065
|
+
never: <A extends Type = never>() => IO<never, never, A>;
|
|
1066
|
+
/**
|
|
1067
|
+
* Creates a unit IO.
|
|
1068
|
+
*/
|
|
1069
|
+
readonly unit: IO<never, never, void>;
|
|
1070
|
+
/**
|
|
1071
|
+
* Converts a nullable value to an IO.
|
|
1072
|
+
*/
|
|
1073
|
+
fromNullable: <A extends Type>(value: A | null | undefined) => IO<never, void, A>;
|
|
1074
|
+
/**
|
|
1075
|
+
* Creates an IO that is immediately interrupted.
|
|
1076
|
+
*/
|
|
1077
|
+
interrupt: () => IO<never, never, never>;
|
|
1078
|
+
/**
|
|
1079
|
+
* Ensures a resource is properly released after use.
|
|
1080
|
+
* The release function always runs, even if use fails.
|
|
1081
|
+
*
|
|
1082
|
+
* @example
|
|
1083
|
+
* ```typescript
|
|
1084
|
+
* const withFile = IO.bracket(
|
|
1085
|
+
* IO.sync(() => openFile("data.txt")), // acquire
|
|
1086
|
+
* file => IO.async(() => file.read()), // use
|
|
1087
|
+
* file => IO.sync(() => file.close()) // release
|
|
1088
|
+
* )
|
|
1089
|
+
* ```
|
|
1090
|
+
*/
|
|
1091
|
+
bracket: <R extends Type, E extends Type, A extends Type, B extends Type>(acquire: IO<R, E, A>, use: (a: A) => IO<R, E, B>, release: (a: A) => IO<R, never, void>) => IO<R, E, B>;
|
|
1092
|
+
/**
|
|
1093
|
+
* Alias for bracket with a more descriptive name.
|
|
1094
|
+
*/
|
|
1095
|
+
acquireRelease: <R extends Type, E extends Type, A extends Type, B extends Type>(acquire: IO<R, E, A>, use: (a: A) => IO<R, E, B>, release: (a: A) => IO<R, never, void>) => IO<R, E, B>;
|
|
1096
|
+
/**
|
|
1097
|
+
* Like `bracket`, but the release callback receives the Exit of the use-step.
|
|
1098
|
+
* Use this when cleanup needs to branch on whether `use` succeeded or failed —
|
|
1099
|
+
* e.g., emit a different audit event on `Success` vs `Failure`.
|
|
1100
|
+
*
|
|
1101
|
+
* The release effect always runs (whether use succeeded, failed, or was
|
|
1102
|
+
* interrupted). If `acquire` itself fails, release is not called.
|
|
1103
|
+
*
|
|
1104
|
+
* @example
|
|
1105
|
+
* ```typescript
|
|
1106
|
+
* IO.bracketExit(
|
|
1107
|
+
* appendEvent({ event: "job_start" }),
|
|
1108
|
+
* () => body,
|
|
1109
|
+
* (_a, exit) =>
|
|
1110
|
+
* exit.isSuccess()
|
|
1111
|
+
* ? appendEvent({ event: "job_complete" })
|
|
1112
|
+
* : appendEvent({ event: "job_failed", error: String(exit.toValue().value) })
|
|
1113
|
+
* )
|
|
1114
|
+
* ```
|
|
1115
|
+
*/
|
|
1116
|
+
bracketExit: <R extends Type, E extends Type, A extends Type, B extends Type>(acquire: IO<R, E, A>, use: (a: A) => IO<R, E, B>, release: (a: A, exit: Exit<E, B>) => IO<R, never, void>) => IO<R, E, B>;
|
|
1117
|
+
/**
|
|
1118
|
+
* Runs the effects at once and returns the first to settle, whether it succeeded or failed.
|
|
1119
|
+
*
|
|
1120
|
+
* The others are interrupted: they start no new step, a sleep in them wakes, and an
|
|
1121
|
+
* `IO.async` thunk sees its signal abort. `race` returns at once and doesn't wait for them, so
|
|
1122
|
+
* an effect that ignores cancellation may still be running; its `bracket` release runs when it
|
|
1123
|
+
* settles.
|
|
1124
|
+
*
|
|
1125
|
+
* First to *settle* wins, so a failure that comes first is the result. This differs from ZIO
|
|
1126
|
+
* and Effect, where `race` returns the first to *succeed*. An empty array is a defect (`Die`).
|
|
1127
|
+
*
|
|
1128
|
+
* @example
|
|
1129
|
+
* ```typescript
|
|
1130
|
+
* const result = await IO.race([
|
|
1131
|
+
* IO.sleep(1000).map(() => "slow"),
|
|
1132
|
+
* IO.sleep(100).map(() => "fast")
|
|
1133
|
+
* ]).run() // "fast"
|
|
1134
|
+
* ```
|
|
1135
|
+
*/
|
|
1136
|
+
race: <R extends Type, E extends Type, A extends Type>(effects: readonly IO<R, E, A>[]) => IO<R, E, A>;
|
|
1137
|
+
/**
|
|
1138
|
+
* Executes an effect for each element in the array, collecting results in input order.
|
|
1139
|
+
*
|
|
1140
|
+
* Runs them one after another by default, unlike `IO.all`. `{ concurrency }` works as it does
|
|
1141
|
+
* for `IO.all`.
|
|
1142
|
+
*
|
|
1143
|
+
* @example
|
|
1144
|
+
* ```typescript
|
|
1145
|
+
* const results = await IO.forEach([1, 2, 3], n =>
|
|
1146
|
+
* IO.sync(() => n * 2)
|
|
1147
|
+
* ).run() // [2, 4, 6]
|
|
1148
|
+
* const pages = IO.forEach(urls, fetchPage, { concurrency: 4 })
|
|
1149
|
+
* ```
|
|
1150
|
+
*/
|
|
1151
|
+
forEach: <R extends Type, E extends Type, A extends Type, B extends Type>(items: readonly A[], f: (a: A) => IO<R, E, B>, options?: ConcurrencyOptions) => IO<R, E, readonly B[]>;
|
|
1152
|
+
/**
|
|
1153
|
+
* Creates a timeout effect that fails with TimeoutError.
|
|
1154
|
+
*/
|
|
1155
|
+
timeout: <R extends Type, E extends Type, A extends Type>(effect: IO<R, E, A>, ms: number) => IO<R, E | TimeoutError, A>;
|
|
1156
|
+
/**
|
|
1157
|
+
* Creates an IO from a generator function.
|
|
1158
|
+
* This enables do-notation style programming.
|
|
1159
|
+
*
|
|
1160
|
+
* @example
|
|
1161
|
+
* ```typescript
|
|
1162
|
+
* const program = IO.gen(function* () {
|
|
1163
|
+
* const a = yield* IO.succeed(1)
|
|
1164
|
+
* const b = yield* IO.succeed(2)
|
|
1165
|
+
* return a + b
|
|
1166
|
+
* })
|
|
1167
|
+
* ```
|
|
1168
|
+
*
|
|
1169
|
+
* The result records what the body reads. Its `R` is the union of the services every
|
|
1170
|
+
* yielded IO needs, and its `E` is the union of their errors:
|
|
1171
|
+
*
|
|
1172
|
+
* ```typescript
|
|
1173
|
+
* const getUser = (id: string) =>
|
|
1174
|
+
* IO.gen(function* () {
|
|
1175
|
+
* const db = yield* IO.service(Database)
|
|
1176
|
+
* return yield* IO.tryPromise({ try: () => db.find(id), catch: (e) => new DbError(e) })
|
|
1177
|
+
* })
|
|
1178
|
+
* // IO<Database, DbError, User>
|
|
1179
|
+
* getUser("1").provideLayer(DatabaseLive)
|
|
1180
|
+
* ```
|
|
1181
|
+
*/
|
|
1182
|
+
gen: <Y extends IOYieldable, A extends Type>(f: () => Generator<Y, A, unknown>) => IO<IOGenRequirements<Y>, IOGenErrors<Y>, A>;
|
|
1183
|
+
/**
|
|
1184
|
+
* Starts a Do-builder context for binding values.
|
|
1185
|
+
* This enables do-notation style programming without generators.
|
|
1186
|
+
*
|
|
1187
|
+
* @example
|
|
1188
|
+
* ```typescript
|
|
1189
|
+
* const program = IO.Do
|
|
1190
|
+
* .bind("user", () => getUser("123"))
|
|
1191
|
+
* .bind("posts", ({ user }) => getPosts(user.id))
|
|
1192
|
+
* .let("count", ({ posts }) => posts.length)
|
|
1193
|
+
* .map(({ user, posts, count }) => ({ user, posts, count }))
|
|
1194
|
+
* ```
|
|
1195
|
+
*/
|
|
1196
|
+
readonly Do: DoBuilder<never, never, Record<never, never>>;
|
|
1197
|
+
};
|
|
1198
|
+
/**
|
|
1199
|
+
* IO effect type for lazy, composable effects with typed errors.
|
|
1200
|
+
*
|
|
1201
|
+
* @example
|
|
1202
|
+
* ```typescript
|
|
1203
|
+
* // Basic usage
|
|
1204
|
+
* const program = IO.sync(() => 42)
|
|
1205
|
+
* .map(x => x * 2)
|
|
1206
|
+
* .flatMap(x => IO.succeed(x + 1))
|
|
1207
|
+
*
|
|
1208
|
+
* const result = await program.run() // 85
|
|
1209
|
+
*
|
|
1210
|
+
* // Error handling
|
|
1211
|
+
* const safe = IO.tryPromise({
|
|
1212
|
+
* try: () => fetch('/api/data'),
|
|
1213
|
+
* catch: (e) => new NetworkError(e)
|
|
1214
|
+
* })
|
|
1215
|
+
* .map(res => res.json())
|
|
1216
|
+
* .recover({ fallback: 'default' })
|
|
1217
|
+
*
|
|
1218
|
+
* // Composition
|
|
1219
|
+
* const composed = IO.all([
|
|
1220
|
+
* IO.succeed(1),
|
|
1221
|
+
* IO.succeed(2),
|
|
1222
|
+
* IO.succeed(3)
|
|
1223
|
+
* ]) // IO<never, never, [1, 2, 3]>
|
|
1224
|
+
* ```
|
|
1225
|
+
*/
|
|
1226
|
+
export declare const IO: IOCompanion;
|
|
1227
|
+
/** The type of `IO`: its constructor and its statics, named so that errors and hovers print `IOCompanion`. */
|
|
1228
|
+
export interface IOCompanion extends IOConstructorType, IOStaticsType {}
|
|
1229
|
+
type IOConstructorType = typeof IOConstructor;
|
|
1230
|
+
type IOStaticsType = typeof IOStatics;
|
|
1231
|
+
/**
|
|
1232
|
+
* An IO with no requirements and no error
|
|
1233
|
+
*/
|
|
1234
|
+
export type UIO<A extends Type> = IO<never, never, A>;
|
|
1235
|
+
/**
|
|
1236
|
+
* An IO with no requirements
|
|
1237
|
+
*/
|
|
1238
|
+
export type Task<E extends Type, A extends Type> = IO<never, E, A>;
|
|
1239
|
+
/**
|
|
1240
|
+
* An IO with no error
|
|
1241
|
+
*/
|
|
1242
|
+
export type RIO<R extends Type, A extends Type> = IO<R, never, A>;
|
|
1243
|
+
export {};
|