functype 2.3.0 → 2.4.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 +1 -1
- package/dist/cli/data.js +1 -1
- package/dist/cli/full-interfaces.js +30 -21
- package/dist/conditional/Match.d.ts +22 -16
- package/dist/conditional/index.d.ts +2 -2
- package/dist/either/index.d.ts +5 -5
- package/dist/index.d.ts +2 -2
- package/dist/io/Exit.d.ts +7 -7
- package/dist/io/IO.d.ts +30 -21
- package/dist/io/IO.js +1 -1
- package/dist/list/index.d.ts +4 -4
- package/dist/map/index.d.ts +4 -4
- package/dist/obj/Obj.d.ts +1 -1
- package/dist/option/index.d.ts +5 -5
- package/dist/package.json.js +1 -1
- package/dist/stack/Stack.d.ts +4 -4
- package/dist/traced/TracedOption.d.ts +1 -1
- package/dist/try/index.d.ts +5 -5
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -851,7 +851,7 @@ Work that shipped but wasn't captured in the planned roadmap above:
|
|
|
851
851
|
- ✓ `Widen<A, B>` conditional-type helper enforcing Scala's `[B >: A]` lower-bound semantics in `reduce` / `reduceRight`
|
|
852
852
|
- ✓ Method-level widening patterns (`orElse`, `getOrElse`, `recover`, `add`, `concat`, etc.)
|
|
853
853
|
- ✓ Contributor guide at [`docs/variance-guide.md`](docs/variance-guide.md)
|
|
854
|
-
-
|
|
854
|
+
- ✓ `IO<out R, out E, out A>`: covariant in all three, as in Effect
|
|
855
855
|
- [x] **Do-notation with generator comprehensions** (`src/do/`)
|
|
856
856
|
- [x] **HTTP module** — typed fetch wrapper with validator support (`src/fetch/` — Http, HttpClient, HttpError, HttpRequest)
|
|
857
857
|
- [x] **Throwable** — enhanced error wrapper preserving stack traces and context (`src/core/throwable/`)
|
package/dist/cli/data.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{version as e}from"../package.json.js";import{GENERATED_INTERFACES as t}from"./interfaces.generated.js";const n=e,r=(e,...n)=>Array.from(/* @__PURE__ */ new Set([...t[e],...n])).sort(),i={Option:{description:`Safe nullable handling - Some<T> or None`,interfaces:r(`Option`),methods:{create:[`Option(v)`,`Option.none()`,`Some(v)`,`None()`],transform:[`.map(f)`,`.flatMap(f)`,`.filter(p)`,`.ap(ff)`,`.orElse(() => alt)`],extract:[`.fold(n, s)`,`.foldAsync(n, s)`,`.getOrElse(() => d)`,`.orThrow(err | () => Error)`,`.expect(() => never)`,`.orNull()`,`.match({Some, None})`,`.toEither(left | () => left)`,`.toList()`,`.toArray()`],check:[`.isSome()`,`.isNone()`,`.isEmpty`,`.exists(p)`,`.every(p)`],other:[`Option.sequence(arr)`,`Option.traverse(arr, f)`]}},Either:{description:`Error handling with Left (error) or Right (success)`,interfaces:r(`Either`,`Traversable`),methods:{create:[`Right(v)`,`Left(e)`,`Either.right(v)`,`Either.left(e)`,`Either.void()`],transform:[`.map(f)`,`.mapTry(f, onError)`,`.flatMap(f)`,`.mapLeft(f)`,`.swap()`,`.orElse(() => alt)`],extract:[`.fold(l, r)`,`.foldAsync(l, r)`,`.getOrElse(() => d)`,`.orThrow(err | (left) => Error)`,`.expect((l) => never)`,`.match({Left, Right})`],check:[`.isRight()`,`.isLeft()`,`.exists(p)`,`.every(p)`],other:[`Either.sequence(arr)`,`Either.traverse(arr, f)`,`Either.traverseAsync(items, f, {concurrency?}) // in order by default, stops at first Left`,`Either.fromNullable(v, e)`]}},Try:{description:`Wrap operations that may throw - Success<T> or Failure`,interfaces:r(`Try`,`Matchable`,`Traversable`),methods:{create:[`Try(() => expr)`,`Try.success(v)`,`Try.failure(e)`,`Try.fromPromise(p)`,`Try.async(() => Promise<T>)`],transform:[`.map(f)`,`.flatMap(f)`,`.recover(f)`,`.recoverWith(f)`,`.orElse(() => alt)`],extract:[`.fold(f, s)`,`.foldAsync(f, s)`,`.getOrElse(() => d)`,`.orThrow(err | (error) => Error)`,`.expect((e) => never)`,`.toOption()`,`.toEither(left | (err) => left)`,`.toList()`,`.toArray()`],check:[`.isSuccess()`,`.isFailure()`,`.exists(p)`,`.every(p)`],other:[`Try.sequence(arr)`,`Try.traverse(arr, f)`]}},List:{description:`Immutable array with functional operations`,interfaces:r(`List`,`Functor`,`Monad`,`Foldable`,`Serializable`,`Traversable`),methods:{create:[`List([...])`,`List.of(...)`,`List.empty()`],transform:[`.map(f)`,`.flatMap(f)`,`.filter(p)`,`.take(n)`,`.takeWhile(p)`,`.takeRight(n)`,`.drop(n)`,`.dropRight(n)`,`.dropWhile(p)`,`.flatten()`,`.concat(list)`,`.reverse()`,`.distinct()`,`.sorted()`,`.sortBy(f)`,`.zip(list)`,`.zipWithIndex()`,`.prepend(v)`,`.slice(s, e)`],extract:[`.fold(z, f)`,`.reduce(f)`,`.head()`,`.headOption()`,`.tail()`,`.last()`,`.lastOption()`,`.init()`,`.indexOf(v)`,`.toArray()`],check:[`.isEmpty`,`.size`,`.contains(v)`,`.exists(p)`,`.every(p)`],other:[`.groupBy(f)`,`.partition(p)`,`.span(p)`,`.mapAsync(f, {concurrency?}) // in order by default`,`.flatMapAsync(f, {concurrency?})`]}},Set:{description:`Immutable set of unique values`,interfaces:r(`Set`,`Functor`,`Foldable`,`Serializable`,`Traversable`),methods:{create:[`Set([...])`,`Set.of(...)`,`Set.empty()`],transform:[`.map(f)`,`.flatMap(f)`,`.filter(p)`,`.filterNot(p)`,`.add(v)`,`.remove(v)`,`.union(other)`,`.intersection(other)`,`.difference(other)`,`.symmetricDifference(other)`,`.mapAsync(f, {concurrency?}) // in order by default`],extract:[`.fold(z, f)`,`.toArray()`],check:[`.has(v)`,`.isEmpty`,`.size`,`.exists(p)`,`.every(p)`,`.isSubsetOf(other)`,`.isSupersetOf(other)`,`.isDisjointFrom(other)`],other:[`import { Set } from "functype" // its own name; the built-in is globalThis.Set`]}},Obj:{description:`Immutable object wrapper with fluent operations`,interfaces:r(`Obj`,`KVTraversable`,`Foldable`,`Matchable`,`Extractable`,`Serializable`),methods:{create:[`Obj({...})`,`Obj.of({...})`,`Obj.empty()`],transform:[`.set(k, v)`,`.assign(partial)`,`.merge(obj)`,`.when(cond, partial)`,`.omit(...keys)`,`.pick(...keys)`,`.map(f)`,`.flatMap(f)`],extract:[`.get(k)`,`.value()`,`.keys()`,`.values()`,`.entries()`,`.fold(n, s)`,`.match({Obj})`],check:[`.has(k)`,`.isEmpty`,`.size`]}},Map:{description:`Immutable key-value store`,interfaces:r(`Map`),methods:{create:[`Map([[k, v], ...])`,`Map.of([k, v], ...)`,`Map.empty()`,`Map.fromJSON(json)`,`Map.fromBinary(b)`],transform:[`.add(Tuple([k, v]))`,`.remove(k)`,`.map(f)`,`.flatMap(f)`,`.ap(ff)`,`.flatMapAsync(f)`],extract:[`.get(k) // Option<V>`,`.keys() // List<K>`,`.values() // List<V>`,`.getOrElse(k, () => d)`,`.orElse(k, () => Option<V>)`,`.fold(z, f)`,`.foldLeft(z)(f)`,`.foldRight(z)(f)`,`.match({Empty, NonEmpty})`,`.toList()`,`.toSet()`,`[...map] // iterate [k, v] pairs`],check:[`.has(k) // key only`,`.contains(Tuple([k, v])) // === on the value`,`.isEmpty`,`.size`],other:[`import { Map } from "functype" // its own name; the built-in is globalThis.Map`]}},Lazy:{description:"Deferred computation with memoization. Note: `serialize()` and `toValue()` FORCE the thunk (visible side effect) since a closure cannot be JSON-serialized — there is no representable 'unevaluated post-serialize' state. Thunk failures are captured via SerializedError and rethrown on access after fromJSON.",interfaces:r(`Lazy`),methods:{create:[`Lazy(() => expr)`,`Lazy.fromValue(value) — wrap a non-deferred value`,`Lazy.evaluated(value) — reads as 'already-forced'; used by fromJSON`,`Lazy.fail(error) — Lazy that throws on access`],transform:[`.map(f)`,`.flatMap(f)`],extract:[`.fold(f)`,`.foldWith(onFailure, onSuccess)`,`.getOrElse(() => d)`,`.orNull()`,`.orThrow()`,`.toJSON()`,`Lazy.fromJSON(json)`],check:[`.isEvaluated`]}},LazyList:{description:`Lazy sequences for large/infinite data`,interfaces:r(`LazyList`,`Functor`,`Monad`,`Iterable`),methods:{create:[`LazyList(iterable)`,`LazyList.from(a, b, ...)`,`LazyList.of(a, b, ...)`,`LazyList.range(start, end)`,`LazyList.iterate(seed, f)`,`LazyList.generate(f)`,`LazyList.fromJSON(json)`],transform:[`.map(f)`,`.filter(p)`,`.take(n)`,`.takeRight(n)`,`.drop(n)`,`.takeWhile(p)`,`.dropWhile(p)`,`.concat(ll)`,`.reverse()`,`.distinct()`,`.zip(ll)`,`.zipWithIndex()`],extract:[`.head()`,`.headOption()`,`.tail()`,`.last()`,`.lastOption()`,`.init()`,`.find(p)`,`.toArray()`,`.toJSON()`],check:[`.some(p)`,`.every(p)`,`.count()`]}},Exit:{description:`Outcome of running an IO effect — Success | Failure | Die | Interrupted, returned by .runExit(). Die carries a defect: a value that is not an E. Either has no branch for one, so .run() rejects on it.`,interfaces:[],methods:{create:[`Exit.succeed(v)`,`Exit.fail(e)`,`Exit.die(defect)`,`Exit.interrupt(fiberId)`,`Exit.interrupted()`],transform:[`.map(f)`,`.mapError(f)`,`.mapBoth(onErr, onOk)`,`.flatMap(f)`],extract:[`.fold(onFailure, onSuccess, onInterrupted?, onDie?)`,`.match({Success, Failure, Interrupted, Die?})`,`.orThrow()`,`.getOrElse(() => v)`,`.toOption()`,`.toEither()`,`.toValue()`],check:[`.isSuccess()`,`.isFailure()`,`.isDie()`,`.isInterrupted()`],other:[`Exit.zip(a, b)`,`Exit.all(exits)`,`Exit.fromEither(e)`,`Exit.fromOption(o, onNone)`,`// after a guard: .value / .error / .defect / .fiberId`,`// onDie / Die are optional and fall back to the failure handler`,`// defects stay recoverable: .recover/.recoverWith/.fold/.mapError treat Die as Failure`]}},IO:{description:`Lazy effect type with typed errors and dependency injection`,interfaces:[`Functor`,`Monad`,`Foldable`,`Matchable`],methods:{create:[`IO(() => v)`,`IO.succeed(v)`,`IO.fail(e)`,`IO.sync(f)`,`IO.async(f)`,`IO.tryPromise({try, catch})`,`IO.fromEither(e)`,`IO.fromPromiseEither(f, onReject?)`,`IO.fromOption(o)`,`IO.fromTry(t)`,`IO.die(defect)`],transform:[`.map(f)`,`.mapTry(f, onError) // a throw in f becomes a typed error, not a defect`,`.flatMap(f)`,`.tap(f)`,`.mapError(f)`,`.recover(v)`,`.recoverWith(f)`],extract:[`.run() // Either<E,A> — Left holds only E; a defect or interruption rejects`,`.runOrThrow()`,`.runSync() // Either<E,A>; throws a defect or interruption`,`.runSyncOrThrow()`,`.runExit() // Exit<E,A> — the only terminal that distinguishes Failure/Die/Interrupted`,`.runCancellable() // { result, cancel }`,`.runExit({ signal }) // Interrupted on abort, E unchanged`,`.runOption()`,`.runTry()`,`.fold(onErr, onOk)`,`.match({failure, success})`],check:[],other:[`.catchTag(tag, f)`,`.catchAll(f)`,`.retry(n)`,`.retryWithDelay(n, ms)`,`.retryWhile({ n, while, delayMs? })`,`.retryWithBackoff({ n, baseMs, maxMs?, factor?, jitter?, while? })`,`.repeatUntil(done, { max, delayMs? })`,`.repeatWhile(cont, { max, delayMs? })`,`.timeout(ms) // interrupts the effect at the deadline`,`.interruptOn(signal) // stops at the next step once the AbortSignal fires; E gains InterruptedError`,`.withSpan(name, attributes?) // runs in a span via the provided SpanTracer; an inner withSpan nests under it`,`IO.async((signal?) => fetch(url, { signal })) // thunk gets the run's AbortSignal inside a region`,`.delay(ms)`,`.zip(io)`,`.pipe(f)`,`IO.all([...], { concurrency? }) // all at once by default; first failure interrupts the rest`,`IO.forEach(items, f, { concurrency? })`,`IO.race([...]) // first to settle wins; the rest are interrupted`,`IO.firstSuccessOf([...]) // tries each in order; the first success wins`,`IO.iterate(seed, step, done, { max? })`,`IO.bracket(acquire, use, release)`,`IO.gen(function*() {...})`,`IO.Do.bind().map()`,`IO.service(Tag)`,`.provideService(Tag, impl)`,`.provideLayer(layer)`]}},Cond:{description:`Conditional expression builder - replace if-else chains`,interfaces:[],methods:{create:[`Cond<T>()`],other:[`.case(pred, result)`,`.otherwise(result)`,`.eval()`]}},Match:{description:`Pattern matching - replace switch statements`,interfaces:[],methods:{create:[`Match(value)`],other:[`.case(pattern, result)`,`.when(pred, result)`,`.default(result)`,`.done()`]}},Brand:{description:`Nominal typing without runtime overhead`,interfaces:[],methods:{create:[`Brand<K, T>(value)`],extract:[`.unwrap()`,`.toString()`]}},Wire:{description:`Serialization-boundary marker for a row, collection or nullable field at DB / HTTP / JSONB boundaries. Zero runtime, assignable both ways with T. prefer-list and prefer-option skip everything inside it. A collection is Wire<ReadonlyArray<Row>>.`,interfaces:[],methods:{create:[`type UserRow = Wire<{ email: string | null }>`,`type Rows = Wire<ReadonlyArray<Row>>`,`email: Wire<string | null>`],other:[`List(rows).filter(...) // convert to List for transformation`,`Option(row.email) // convert to Option`]}},ValidatedBrand:{description:`Branded types with runtime validation`,interfaces:[],methods:{create:[`ValidatedBrand(validator)`,`.of(v)`,`.from(v)`,`.unsafeOf(v)`],check:[`.is(v)`],other:[`.refine(validator)`]}},Tuple:{description:`Fixed-size typed array`,interfaces:r(`Tuple`,`Typeable`,`Valuable`,`Iterable`),methods:{create:[`Tuple([a, b, ...])`,`Tuple.of(a, b, ...)`,`Tuple.fromJSON(json)`],extract:[`.get(i)`,`.length`,`.toArray()`,`.toJSON()`],transform:[`.map(f)`]}},Identity:{description:`The identity monad: wraps a value with no extra effect. Useful as a neutral container in generic code.`,interfaces:[],methods:{create:[`Identity(value)`,`Identity.of(value)`,`Identity.pure(value)`],extract:[`.id`],other:[`.isSame(other)`]}},Ref:{description:`Mutable reference cell for controlled, local mutability. Invariant in A by design (a mutable cell can't be widened).`,interfaces:[],methods:{create:[`Ref(initial)`,`Ref.of(initial)`],extract:[`.get()`],transform:[`.set(a)`,`.update(f)`,`.modify(f) // returns B, stores A`],other:[`.getAndSet(a)`,`.updateAndGet(f)`,`.getAndUpdate(f)`,`.compareAndSet(expected, next)`]}},Do:{description:`Generator do-notation across Option, Either, List and Try (DoAsync for promises). Short-circuits on None/Left/Failure/empty List.`,interfaces:[],methods:{create:[`Do(function* () { const a = yield* $(opt); return a })`,`DoAsync(async function* () { … })`],other:[`$(monad) // unwrap inside Do`,`isDoCapable(value)`,`unwrap(monad)`]}},invariant:{description:`One-line bug check: invariant(cond, msg) throws a tagged InvariantViolation when cond is falsy and narrows cond after it. For programmer errors only; expected failures return Either.`,interfaces:[],methods:{create:[`invariant(row, "upsert returned no row")`,"invariant(n >= 0, () => `bad step ${n}`) // lazy message"],other:[`InvariantViolation(msg) // throw directly for an unreachable branch`]}},TracedOption:{description:`Opt-in Option wrapper that emits one TraceEvent per combinator to an injected Tracer, then delegates. For code-path introspection.`,interfaces:[],methods:{create:[`TracedOption(option, tracer, spanId, seq?)`],transform:[`.map(f, label?)`,`.flatMap(f, label?)`,`.filter(p, label?)`],extract:[`.fold(onNone, onSome, label?)`,`.getOrElse(() => default, label?)`,`.unwrap() // back to Option`]}},Tracer:{description:`One-method trace sink consumed by TracedOption. Type-only, like Logger; declare your own Tag for injection.`,interfaces:[],methods:{create:[`const tracer: Tracer = { emit: (e: TraceEvent) => … }`],other:[`TraceEvent: { spanId, seq, op, tag, inTag, outTag?, label?, meta? }`]}},SpanTracer:{description:`Span contract and Tag for IO.withSpan: start, run (body with the span active), end. None provided: withSpan is a no-op.`,interfaces:[],methods:{create:[`const tracer: SpanTracer<MySpan> = { start, run, end }`,`io.withSpan("name", { key: "value" }).provideService(SpanTracer, tracer) // provide outside the spans`],other:[`OpenTelemetry: run = (span, fn) => context.with(trace.setSpan(context.active(), span), fn)`,`parent is the enclosing span in this run, or undefined; fall back to the ambient context then`]}},Stack:{description:`Immutable LIFO stack`,interfaces:[`Foldable`,`Collection`,`Serializable`,`Traversable`],methods:{create:[`Stack()`,`Stack.of(...)`],transform:[`.push(v)`,`.pop()`],extract:[`.peek()`,`.toArray()`],check:[`.isEmpty`,`.size`]}},Http:{description:"HTTP fetch wrapper returning IO<never, HttpError, HttpResponse<T>>. Pass `decode: Decoder<T>` (Either-returning) for typed responses; wrap a throwing parser such as Zod's .parse in `Decoder.fromThrowing(parse)`. 2.0 removed the `validate` field. Request bodies auto-flatten functype ADTs to primitives; `flatten: false` preserves tagged emission for functype-to-functype services. Per-call `params` (HttpQueryParams) appends query strings with proper encoding. Http.client accepts `beforeRequest` and `afterResponse` (both effectful IO transformers). `afterResponse` runs on the success path only — error handling belongs in .catchTag. Composes via .tap/.map/.flatMap/.catchTag/.retry/.retryWhile/.retryWithBackoff/.timeout.",interfaces:[],methods:{create:[`Http.get(url, { decode, params }?)`,`Http.post(url, { body, decode, params }?)`,`Http.put(url, { body, decode, params }?)`,`Http.patch(url, { body, decode, params }?)`,`Http.delete(url, { decode, params }?)`,`Http.request({ url, decode, params })`,`Http.client({ baseUrl, defaultHeaders, fetch, beforeRequest, afterResponse }): HttpMethods`],transform:[`.tap(f)`,`.map(f)`,`.flatMap(f)`,`.mapError(f)`,`.retry(n)`,`.retryWithDelay(n, ms)`,`.retryWhile({ n, while, delayMs? })`,`.retryWithBackoff({ n, baseMs, maxMs?, factor?, jitter?, while? })`,`.timeout(ms)`],extract:[`.run()`,`.runOrThrow()`,`.runOption()`,`.runTry()`,`.runExit()`,`.runCancellable()`],check:[],other:[`.catchTag(tag, handler)`,`.catchAll(handler)`,`.recover(fallback)`,`decode: Decoder<T> (Either-returning, structural failures preserved)`,`decode: Decoder.fromThrowing(parse) (a throwing parser such as Zod .parse; a throw becomes a DecoderError leaf)`,`flatten: boolean (default true; false preserves tagged emission)`,`encode: Encoder<TReq> = (value) => JSONValue (custom wire shape; overrides flatten)`,`params: HttpQueryParams (scalar | array; undefined/null dropped; percent-encoded)`,`beforeRequest: (req) => IO<never, HttpError, HttpRequestView>`,`afterResponse: (HttpResponse<unknown>) => IO<never, HttpError, HttpResponse<unknown>> — success path only; refresh-on-401 uses .catchTag`]}},HttpError:{description:`Three-variant ADT for HTTP failures: NetworkError | HttpStatusError | DecodeError (also exported as ResponseDecodeError alias)`,interfaces:[],methods:{create:[`HttpError.networkError(url, method, cause)`,`HttpError.httpStatusError(url, method, status, statusText, body)`,`HttpError.decodeError(url, method, body, cause)`],check:[`HttpError.isNetworkError(e)`,`HttpError.isHttpStatusError(e)`,`HttpError.isDecodeError(e)`],other:[`HttpError.match(error, { NetworkError, HttpStatusError, DecodeError })`]}},Decoder:{description:"Either-returning decoder contract: `Decoder<A> = (raw: unknown) => Either<DecoderError, A>`. Bundled combinators for primitives + functype ADTs (Option/Either/List/Map, null-bias). `Decoder.tagged.*` round-trips the `{_tag, value}` shape for functype-to-functype services.",interfaces:[],methods:{create:[`Decoder.string / .number / .boolean / .unknown / .nullable(inner)`,`Decoder.fromThrowing(parse) // adapt a throwing parser such as Zod's schema.parse`,`Decoder.option(inner)`,`Decoder.either.envelope({ok, err})`,`Decoder.either.discriminated({tag, leftTag, rightTag}, l, r)`,`Decoder.list(inner) / .array(inner) / .map(inner)`,`Decoder.object({k: Decoder<V>, ...}) — accumulates field failures into Composite`,`Decoder.tagged.option/either/try/list/map/obj(inner?) — round-trips {_tag, value}`],other:[`Pluggable by construction: any (raw) => Either<DecoderError, T> IS a Decoder<T>`,`Composes across sources: Decoder.object({a: Decoder.fromZod(s), b: Decoder.option(myAjv)})`]}},DecoderError:{description:"Recursive ADT for decoder failures: Leaf | Composite. Children mirror the input tree so multi-field failures preserve structural paths. Distinct from `HttpError.DecodeError` — this is the inner structural cause that the HTTP wrapper carries.",interfaces:[],methods:{create:[`DecoderError.leaf(path, message, cause?)`,`DecoderError.composite(path, children: List<DecoderError>)`],check:[`DecoderError.isLeaf(e)`,`DecoderError.isComposite(e)`],other:[`DecoderError.match(e, { Leaf, Composite })`,`DecoderError.prepend(segment, e) — used by combinators to attribute child failures`,`DecoderError.flatten(e): List<{path, message}> — collect leaves`,`DecoderError.format(e): string — render tree as multi-line`,`DecoderError.formatPath(path): string — one path as format renders it (endpoints[1].name; (root) when empty)`]}},Serialization:{description:"Universal `@functype`-marked JSON serialization. `deserialize` walks parsed JSON and reconstructs any functype value found — no type argument needed. Lenient: plain JSON passes through. Strict on unknown markers (defends against Effect/fp-ts `_tag` collision). 1.2.1 adds `toEnvelope`/`fromEnvelope` for nesting inside structured serializers (SuperJSON, DBOS), and `deserializeStrict` for boundaries that require functype on the wire.",interfaces:[],methods:{create:[],transform:[`Serialization.serialize(value: unknown): string — lenient JSON codec`,`Serialization.deserialize(json: string): Try<unknown> — lenient; pass-through for unmarked JSON`,`Serialization.deserializeStrict(json: string): Try<unknown> — Failure if no @functype marker at top level`,`Serialization.toEnvelope(value: unknown): JSONValue — parsed JSON shape (1.2.2 tightened from unknown)`,`Serialization.fromEnvelope(envelope: unknown): Try<unknown> — inverse of toEnvelope; input stays permissive (Postel's law)`,`Serialization.JSONValue — exported recursive type for the envelope shape`],check:[`Serialization.isFunctypeValue(v): v is Serializable<unknown>`],other:[`Plain JSON passthrough: non-functype data walks through unchanged (use deserializeStrict to reject)`,`Strict policy on unknown markers: unknown @functype marker → Try.Failure`,`Dispatch table covers all 11 Serializable types (Option, Either, Try, List, Set, Map, Obj, Stack, Tuple, LazyList, Lazy)`,`Algebraic square: serialize ≡ JSON.stringify ∘ toEnvelope; deserialize ≡ fromEnvelope ∘ JSON.parse`,`No DBOS / SuperJSON facade — consumers wire host serializer in ~8 lines via toEnvelope/fromEnvelope`]}},SerializedError:{description:"Canonical Error projection used by Try.Failure and Lazy-with-thrown-thunk. Round-trips name + message + stack + cause chain. `e.name === 'TypeError'` survives; `instanceof TypeError` does NOT.",interfaces:[],methods:{create:[`serializeError(err: unknown): SerializedError`,`deserializeError(s: SerializedError | string): Error`],other:[`Shape: { name: string; message: string; stack?: string; cause?: SerializedError | string }`,`Non-Error throwables (strings, plain objects) projected under name: 'NonErrorThrowable'`,`Cause chain is recursive — arbitrary nesting depth survives`]}},Logger:{description:`Minimal 4-method logging interface every functype-* package targets. Type-only, no runtime. Impls live in consumers: consoleBootLogger (functype-os/config), DirectLogger (functype-log/direct). Tracer is type-only on the same terms; Clock/Random are not added.`,interfaces:[],methods:{create:[`interface Logger { debug, info, warn, error: (msg, meta?) => void }`,`import type { Logger } from "functype"`],check:[],other:[`All 4 methods MANDATORY (no defensive logger.debug?.() at call sites)`,`Signature: (message: string, metadata?: Record<string, unknown>) => void`,`DirectLogger from functype-log/direct structurally satisfies Logger (superset shape)`,`IO-shaped Logger from functype-log does NOT satisfy core Logger (methods return IO<>, not void) — bridge via toDirectLogger(ioLogger)`,`Used by: bootDiagnostics({ logger? }) in functype-os/config`]}},TypedError:{description:`Code-tagged structured error ADT (extends Throwable); TypedError.validation(...) feeds accumulating validation.`,interfaces:[],methods:{create:[`TypedError.validation(field, value, rule) → TypedError<"VALIDATION_FAILED">`,`TypedError.badRequest(reason, expected?)`,`TypedError.notFound(resource, id)`,`TypedError.auth(resource, requiredRole?)`,`TypedError.permission(action, resource, userId?)`,`TypedError.conflict(resource, value) / .rateLimit(limit, window, retryAfter?)`,`TypedError.timeout(ms, operation) / .network(url, method, status?) / .internal(errorId)`],check:[`TypedError.isTypedError(v)`,`TypedError.hasCode(e, code)`],other:[`Fields: .code, .message, .status (HTTP), .context, .timestamp, .traceId?`,`VALIDATION_FAILED context shape: { field, value, rule }`,`getErrorChain(error) → Error[] and formatErrorChain(error, { includeTasks? }) walk any error's cause chain`]}},Validation:{description:`Error-accumulating validation (functype's Validated role) — FormValidation<T> collects all field errors, not fail-fast.`,interfaces:[],methods:{create:[`Validation.rule<T>('min:18' | 'email' | 'required' | 'in:a,b' | ...)`,`Validation.combine(...validators) / Validation.custom(predicate, message)`,`Validation.validators.email / .url / .uuid / .required / .numeric / .positiveNumber / .nonEmptyString`],transform:[`Validation.form(schema, data) → FormValidation<T> (accumulates all field errors)`,`Validator<T> = (value: unknown) => Either<TypedError<'VALIDATION_FAILED'>, T>`],other:[`FormValidation<T> = Either<List<TypedError<"VALIDATION_FAILED">>, T> — functype's "Validated" accumulating result type`,`form() is flat/per-field: for cross-field (lo < hi) or dynamic-key (weights.*) checks, hand-accumulate into a List<TypedError> and return the FormValidation shape`]}}},a={Functor:{description:`Transform contained values`,methods:[`.map<B>(f: A => B): Functor<B>`]},Applicative:{extends:`Functor`,description:`Apply wrapped functions`,methods:[`.ap<B>(ff: Applicative<A => B>): Applicative<B>`]},Monad:{extends:`Applicative`,description:`Chain operations returning wrapped values`,methods:[`.flatMap<B>(f: A => Monad<B>): Monad<B>`]},Foldable:{description:`Extract via pattern matching`,methods:[`.fold<B>(empty: () => B, f: A => B): B`,`.foldLeft<B>(z: B, op: (B, A) => B): B`,`.foldRight<B>(z: B, op: (A, B) => B): B`]},Extractable:{description:`Get contained value with fallback`,methods:[`.getOrElse(d: () => T): T`,`.orThrow(e?: Error): T`,`.expect(handler: (e?) => never): T`,`.orNull(): T | null`,`.orUndefined(): T | undefined`]},Matchable:{description:`Pattern match on type variants`,methods:[`.match<R>(patterns: Record<Tag, Handler>): R`]},Traversable:{description:`Iterate and check contents`,methods:[`.size: number`,`.isEmpty: boolean`,`.contains(v: A): boolean`,`.reduce<B>(f, init): B`]},Collection:{description:`Collection operations`,methods:[`.toArray(): A[]`,`.forEach(f: A => void): void`]},Serializable:{description:`Convert to string formats`,methods:[`.serialize().toJSON(): string`,`.serialize().toBinary(): string`]}},o={Core:[`Option`,`Either`,`Try`,`Obj`,`Identity`],Collection:[`List`,`Set`,`Map`,`LazyList`,`Tuple`,`Stack`],Effect:[`IO`,`Exit`,`Http`,`HttpError`,`Decoder`,`DecoderError`],Utility:[`Lazy`,`Cond`,`Match`,`Do`,`Ref`,`Brand`,`ValidatedBrand`,`Wire`,`invariant`,`TracedOption`],Validation:[`TypedError`,`Validation`],Serialization:[`Serialization`,`SerializedError`],Service:[`Logger`,`Tracer`,`SpanTracer`]};export{o as CATEGORIES,a as INTERFACES,i as TYPES,n as VERSION};
|
|
1
|
+
import{version as e}from"../package.json.js";import{GENERATED_INTERFACES as t}from"./interfaces.generated.js";const n=e,r=(e,...n)=>Array.from(/* @__PURE__ */ new Set([...t[e],...n])).sort(),i={Option:{description:`Safe nullable handling - Some<T> or None`,interfaces:r(`Option`),methods:{create:[`Option(v)`,`Option.none()`,`Some(v)`,`None()`],transform:[`.map(f)`,`.flatMap(f)`,`.filter(p)`,`.ap(ff)`,`.orElse(() => alt)`],extract:[`.fold(n, s)`,`.foldAsync(n, s)`,`.getOrElse(() => d)`,`.orThrow(err | () => Error)`,`.expect(() => never)`,`.orNull()`,`.match({Some, None})`,`.toEither(left | () => left)`,`.toList()`,`.toArray()`],check:[`.isSome()`,`.isNone()`,`.isEmpty`,`.exists(p)`,`.every(p)`],other:[`Option.sequence(arr)`,`Option.traverse(arr, f)`]}},Either:{description:`Error handling with Left (error) or Right (success)`,interfaces:r(`Either`,`Traversable`),methods:{create:[`Right(v)`,`Left(e)`,`Either.right(v)`,`Either.left(e)`,`Either.void()`],transform:[`.map(f)`,`.mapTry(f, onError)`,`.flatMap(f)`,`.mapLeft(f)`,`.swap()`,`.orElse(() => alt)`],extract:[`.fold(l, r)`,`.foldAsync(l, r)`,`.getOrElse(() => d)`,`.orThrow(err | (left) => Error)`,`.expect((l) => never)`,`.match({Left, Right})`],check:[`.isRight()`,`.isLeft()`,`.exists(p)`,`.every(p)`],other:[`Either.sequence(arr)`,`Either.traverse(arr, f)`,`Either.traverseAsync(items, f, {concurrency?}) // in order by default, stops at first Left`,`Either.fromNullable(v, e)`]}},Try:{description:`Wrap operations that may throw - Success<T> or Failure`,interfaces:r(`Try`,`Matchable`,`Traversable`),methods:{create:[`Try(() => expr)`,`Try.success(v)`,`Try.failure(e)`,`Try.fromPromise(p)`,`Try.async(() => Promise<T>)`],transform:[`.map(f)`,`.flatMap(f)`,`.recover(f)`,`.recoverWith(f)`,`.orElse(() => alt)`],extract:[`.fold(f, s)`,`.foldAsync(f, s)`,`.getOrElse(() => d)`,`.orThrow(err | (error) => Error)`,`.expect((e) => never)`,`.toOption()`,`.toEither(left | (err) => left)`,`.toList()`,`.toArray()`],check:[`.isSuccess()`,`.isFailure()`,`.exists(p)`,`.every(p)`],other:[`Try.sequence(arr)`,`Try.traverse(arr, f)`]}},List:{description:`Immutable array with functional operations`,interfaces:r(`List`,`Functor`,`Monad`,`Foldable`,`Serializable`,`Traversable`),methods:{create:[`List([...])`,`List.of(...)`,`List.empty()`],transform:[`.map(f)`,`.flatMap(f)`,`.filter(p)`,`.take(n)`,`.takeWhile(p)`,`.takeRight(n)`,`.drop(n)`,`.dropRight(n)`,`.dropWhile(p)`,`.flatten()`,`.concat(list)`,`.reverse()`,`.distinct()`,`.sorted()`,`.sortBy(f)`,`.zip(list)`,`.zipWithIndex()`,`.prepend(v)`,`.slice(s, e)`],extract:[`.fold(z, f)`,`.reduce(f)`,`.head()`,`.headOption()`,`.tail()`,`.last()`,`.lastOption()`,`.init()`,`.indexOf(v)`,`.toArray()`],check:[`.isEmpty`,`.size`,`.contains(v)`,`.exists(p)`,`.every(p)`],other:[`.groupBy(f)`,`.partition(p)`,`.span(p)`,`.mapAsync(f, {concurrency?}) // in order by default`,`.flatMapAsync(f, {concurrency?})`]}},Set:{description:`Immutable set of unique values`,interfaces:r(`Set`,`Functor`,`Foldable`,`Serializable`,`Traversable`),methods:{create:[`Set([...])`,`Set.of(...)`,`Set.empty()`],transform:[`.map(f)`,`.flatMap(f)`,`.filter(p)`,`.filterNot(p)`,`.add(v)`,`.remove(v)`,`.union(other)`,`.intersection(other)`,`.difference(other)`,`.symmetricDifference(other)`,`.mapAsync(f, {concurrency?}) // in order by default`],extract:[`.fold(z, f)`,`.toArray()`],check:[`.has(v)`,`.isEmpty`,`.size`,`.exists(p)`,`.every(p)`,`.isSubsetOf(other)`,`.isSupersetOf(other)`,`.isDisjointFrom(other)`],other:[`import { Set } from "functype" // its own name; the built-in is globalThis.Set`]}},Obj:{description:`Immutable object wrapper with fluent operations`,interfaces:r(`Obj`,`KVTraversable`,`Foldable`,`Matchable`,`Extractable`,`Serializable`),methods:{create:[`Obj({...})`,`Obj.of({...})`,`Obj.empty()`],transform:[`.set(k, v)`,`.assign(partial)`,`.merge(obj)`,`.when(cond, partial)`,`.omit(...keys)`,`.pick(...keys)`,`.map(f)`,`.flatMap(f)`],extract:[`.get(k)`,`.value()`,`.keys()`,`.values()`,`.entries()`,`.fold(n, s)`,`.match({Obj})`],check:[`.has(k)`,`.isEmpty`,`.size`]}},Map:{description:`Immutable key-value store`,interfaces:r(`Map`),methods:{create:[`Map([[k, v], ...])`,`Map.of([k, v], ...)`,`Map.empty()`,`Map.fromJSON(json)`,`Map.fromBinary(b)`],transform:[`.add(Tuple([k, v]))`,`.remove(k)`,`.map(f)`,`.flatMap(f)`,`.ap(ff)`,`.flatMapAsync(f)`],extract:[`.get(k) // Option<V>`,`.keys() // List<K>`,`.values() // List<V>`,`.getOrElse(k, () => d)`,`.orElse(k, () => Option<V>)`,`.fold(z, f)`,`.foldLeft(z)(f)`,`.foldRight(z)(f)`,`.match({Empty, NonEmpty})`,`.toList()`,`.toSet()`,`[...map] // iterate [k, v] pairs`],check:[`.has(k) // key only`,`.contains(Tuple([k, v])) // === on the value`,`.isEmpty`,`.size`],other:[`import { Map } from "functype" // its own name; the built-in is globalThis.Map`]}},Lazy:{description:"Deferred computation with memoization. Note: `serialize()` and `toValue()` FORCE the thunk (visible side effect) since a closure cannot be JSON-serialized — there is no representable 'unevaluated post-serialize' state. Thunk failures are captured via SerializedError and rethrown on access after fromJSON.",interfaces:r(`Lazy`),methods:{create:[`Lazy(() => expr)`,`Lazy.fromValue(value) — wrap a non-deferred value`,`Lazy.evaluated(value) — reads as 'already-forced'; used by fromJSON`,`Lazy.fail(error) — Lazy that throws on access`],transform:[`.map(f)`,`.flatMap(f)`],extract:[`.fold(f)`,`.foldWith(onFailure, onSuccess)`,`.getOrElse(() => d)`,`.orNull()`,`.orThrow()`,`.toJSON()`,`Lazy.fromJSON(json)`],check:[`.isEvaluated`]}},LazyList:{description:`Lazy sequences for large/infinite data`,interfaces:r(`LazyList`,`Functor`,`Monad`,`Iterable`),methods:{create:[`LazyList(iterable)`,`LazyList.from(a, b, ...)`,`LazyList.of(a, b, ...)`,`LazyList.range(start, end)`,`LazyList.iterate(seed, f)`,`LazyList.generate(f)`,`LazyList.fromJSON(json)`],transform:[`.map(f)`,`.filter(p)`,`.take(n)`,`.takeRight(n)`,`.drop(n)`,`.takeWhile(p)`,`.dropWhile(p)`,`.concat(ll)`,`.reverse()`,`.distinct()`,`.zip(ll)`,`.zipWithIndex()`],extract:[`.head()`,`.headOption()`,`.tail()`,`.last()`,`.lastOption()`,`.init()`,`.find(p)`,`.toArray()`,`.toJSON()`],check:[`.some(p)`,`.every(p)`,`.count()`]}},Exit:{description:`Outcome of running an IO effect — Success | Failure | Die | Interrupted, returned by .runExit(). Die carries a defect: a value that is not an E. Either has no branch for one, so .run() rejects on it.`,interfaces:[],methods:{create:[`Exit.succeed(v)`,`Exit.fail(e)`,`Exit.die(defect)`,`Exit.interrupt(fiberId)`,`Exit.interrupted()`],transform:[`.map(f)`,`.mapError(f)`,`.mapBoth(onErr, onOk)`,`.flatMap(f)`],extract:[`.fold(onFailure, onSuccess, onInterrupted?, onDie?)`,`.match({Success, Failure, Interrupted, Die?})`,`.orThrow()`,`.getOrElse(() => v)`,`.toOption()`,`.toEither()`,`.toValue()`],check:[`.isSuccess()`,`.isFailure()`,`.isDie()`,`.isInterrupted()`],other:[`Exit.zip(a, b)`,`Exit.all(exits)`,`Exit.fromEither(e)`,`Exit.fromOption(o, onNone)`,`// after a guard: .value / .error / .defect / .fiberId`,`// onDie / Die are optional and fall back to the failure handler`,`// defects stay recoverable: .recover/.recoverWith/.fold/.mapError treat Die as Failure`]}},IO:{description:`Lazy effect type with typed errors and dependency injection`,interfaces:[`Functor`,`Monad`,`Foldable`,`Matchable`],methods:{create:[`IO(() => v)`,`IO.succeed(v)`,`IO.fail(e)`,`IO.sync(f)`,`IO.async(f)`,`IO.tryPromise({try, catch})`,`IO.fromEither(e)`,`IO.fromPromiseEither(f, onReject?)`,`IO.fromOption(o)`,`IO.fromTry(t)`,`IO.die(defect)`],transform:[`.map(f)`,`.mapTry(f, onError) // a throw in f becomes a typed error, not a defect`,`.flatMap(f)`,`.tap(f)`,`.mapError(f)`,`.recover(v)`,`.recoverWith(f)`],extract:[`.run() // Either<E,A> — Left holds only E; a defect or interruption rejects`,`.runOrThrow()`,`.runSync() // Either<E,A>; throws a defect or interruption`,`.runSyncOrThrow()`,`.runExit() // Exit<E,A> — the only terminal that distinguishes Failure/Die/Interrupted`,`.runCancellable() // { result, cancel }`,`.runExit({ signal }) // Interrupted on abort, E unchanged`,`.runOption()`,`.runTry()`,`.fold(onErr, onOk)`,`.match({failure, success})`],check:[],other:[`.catchTag(tag, f)`,`.catchAll(f)`,`.retry(n)`,`.retryWithDelay(n, ms)`,`.retryWhile({ n, while, delayMs? })`,`.retryWithBackoff({ n, baseMs, maxMs?, factor?, jitter?, while? })`,`.repeatUntil(done, { max, delayMs? })`,`.repeatWhile(cont, { max, delayMs? })`,`.timeout(ms) // interrupts the effect at the deadline`,`.interruptOn(signal) // stops at the next step once the AbortSignal fires; E gains InterruptedError`,`.withSpan(name, attributes?) // runs in a span via the provided SpanTracer; an inner withSpan nests under it`,`IO.async((signal?) => fetch(url, { signal })) // thunk gets the run's AbortSignal inside a region`,`.delay(ms)`,`.zip(io)`,`.pipe(f)`,`IO.all([...], { concurrency? }) // all at once by default; first failure interrupts the rest`,`IO.forEach(items, f, { concurrency? })`,`IO.race([...]) // first to settle wins; the rest are interrupted`,`IO.firstSuccessOf([...]) // tries each in order; the first success wins`,`IO.iterate(seed, step, done, { max? })`,`IO.bracket(acquire, use, release)`,`IO.gen(function*() {...})`,`IO.Do.bind().map()`,`IO.service(Tag)`,`.provideService(Tag, impl)`,`.provideLayer(layer)`]}},Cond:{description:`Conditional expression builder - replace if-else chains`,interfaces:[],methods:{create:[`Cond<T>()`],other:[`.case(pred, result)`,`.otherwise(result)`,`.eval()`]}},Match:{description:`Pattern matching - replace switch statements`,interfaces:[],methods:{create:[`Match(value)`],other:[`.case(pattern, result)`,`.when(pred, result)`,`.default(result)`,`.done()`]}},Brand:{description:`Nominal typing without runtime overhead`,interfaces:[],methods:{create:[`Brand<K, T>(value)`],extract:[`.unwrap()`,`.toString()`]}},Wire:{description:`Serialization-boundary marker for a row, collection or nullable field at DB / HTTP / JSONB boundaries. Zero runtime, assignable both ways with T. prefer-list and prefer-option skip everything inside it. A collection is Wire<ReadonlyArray<Row>>.`,interfaces:[],methods:{create:[`type UserRow = Wire<{ email: string | null }>`,`type Rows = Wire<ReadonlyArray<Row>>`,`email: Wire<string | null>`],other:[`List(rows).filter(...) // convert to List for transformation`,`Option(row.email) // convert to Option`]}},ValidatedBrand:{description:`Branded types with runtime validation`,interfaces:[],methods:{create:[`ValidatedBrand(validator)`,`.of(v)`,`.from(v)`,`.unsafeOf(v)`],check:[`.is(v)`],other:[`.refine(validator)`]}},Tuple:{description:`Fixed-size typed array`,interfaces:r(`Tuple`,`Typeable`,`Valuable`,`Iterable`),methods:{create:[`Tuple([a, b, ...])`,`Tuple.of(a, b, ...)`,`Tuple.fromJSON(json)`],extract:[`.get(i)`,`.length`,`.toArray()`,`.toJSON()`],transform:[`.map(f)`]}},Identity:{description:`The identity monad: wraps a value with no extra effect. Useful as a neutral container in generic code.`,interfaces:[],methods:{create:[`Identity(value)`,`Identity.of(value)`,`Identity.pure(value)`],extract:[`.id`],other:[`.isSame(other)`]}},Ref:{description:`Mutable reference cell for controlled, local mutability. Invariant in A by design (a mutable cell can't be widened).`,interfaces:[],methods:{create:[`Ref(initial)`,`Ref.of(initial)`],extract:[`.get()`],transform:[`.set(a)`,`.update(f)`,`.modify(f) // returns B, stores A`],other:[`.getAndSet(a)`,`.updateAndGet(f)`,`.getAndUpdate(f)`,`.compareAndSet(expected, next)`]}},Do:{description:`Generator do-notation across Option, Either, List and Try (DoAsync for promises). Short-circuits on None/Left/Failure/empty List.`,interfaces:[],methods:{create:[`Do(function* () { const a = yield* $(opt); return a })`,`DoAsync(async function* () { … })`],other:[`$(monad) // unwrap inside Do`,`isDoCapable(value)`,`unwrap(monad)`]}},invariant:{description:`One-line bug check: invariant(cond, msg) throws a tagged InvariantViolation when cond is falsy and narrows cond after it. For programmer errors only; expected failures return Either.`,interfaces:[],methods:{create:[`invariant(row, "upsert returned no row")`,"invariant(n >= 0, () => `bad step ${n}`) // lazy message"],other:[`InvariantViolation(msg) // throw directly for an unreachable branch`]}},TracedOption:{description:`Opt-in Option wrapper that emits one TraceEvent per combinator to an injected Tracer, then delegates. For code-path introspection.`,interfaces:[],methods:{create:[`TracedOption(option, tracer, spanId, seq?)`],transform:[`.map(f, label?)`,`.flatMap(f, label?)`,`.filter(p, label?)`],extract:[`.fold(onNone, onSome, label?)`,`.getOrElse(() => default, label?)`,`.unwrap() // back to Option`]}},Tracer:{description:`One-method trace sink consumed by TracedOption. Type-only, like Logger; declare your own Tag for injection.`,interfaces:[],methods:{create:[`const tracer: Tracer = { emit: (e: TraceEvent) => … }`],other:[`TraceEvent: { spanId, seq, op, tag, inTag, outTag?, label?, meta? }`]}},SpanTracer:{description:`Span contract and Tag for IO.withSpan: start, run (body with the span active), end. None provided: withSpan is a no-op.`,interfaces:[],methods:{create:[`const tracer: SpanTracer<MySpan> = { start, run, end }`,`io.withSpan("name", { key: "value" }).provideService(SpanTracer, tracer) // provide outside the spans`],other:[`OpenTelemetry: run = (span, fn) => context.with(trace.setSpan(context.active(), span), fn)`,`parent is the enclosing span in this run, or undefined; fall back to the ambient context then`]}},Stack:{description:`Immutable LIFO stack`,interfaces:[`Foldable`,`Collection`,`Serializable`,`Traversable`],methods:{create:[`Stack()`,`Stack.of(...)`],transform:[`.push(v)`,`.pop()`],extract:[`.peek()`,`.toArray()`],check:[`.isEmpty`,`.size`]}},Http:{description:"HTTP fetch wrapper returning IO<never, HttpError, HttpResponse<T>>. Pass `decode: Decoder<T>` (Either-returning) for typed responses; wrap a throwing parser such as Zod's .parse in `Decoder.fromThrowing(parse)`. 2.0 removed the `validate` field. Request bodies auto-flatten functype ADTs to primitives; `flatten: false` preserves tagged emission for functype-to-functype services. Per-call `params` (HttpQueryParams) appends query strings with proper encoding. Http.client accepts `beforeRequest` and `afterResponse` (both effectful IO transformers). `afterResponse` runs on the success path only — error handling belongs in .catchTag. Composes via .tap/.map/.flatMap/.catchTag/.retry/.retryWhile/.retryWithBackoff/.timeout.",interfaces:[],methods:{create:[`Http.get(url, { decode, params }?)`,`Http.post(url, { body, decode, params }?)`,`Http.put(url, { body, decode, params }?)`,`Http.patch(url, { body, decode, params }?)`,`Http.delete(url, { decode, params }?)`,`Http.request({ url, decode, params })`,`Http.client({ baseUrl, defaultHeaders, fetch, beforeRequest, afterResponse }): HttpMethods`],transform:[`.tap(f)`,`.map(f)`,`.flatMap(f)`,`.mapError(f)`,`.retry(n)`,`.retryWithDelay(n, ms)`,`.retryWhile({ n, while, delayMs? })`,`.retryWithBackoff({ n, baseMs, maxMs?, factor?, jitter?, while? })`,`.timeout(ms)`],extract:[`.run()`,`.runOrThrow()`,`.runOption()`,`.runTry()`,`.runExit()`,`.runCancellable()`],check:[],other:[`.catchTag(tag, handler)`,`.catchAll(handler)`,`.recover(fallback)`,`decode: Decoder<T> (Either-returning, structural failures preserved)`,`decode: Decoder.fromThrowing(parse) (a throwing parser such as Zod .parse; a throw becomes a DecoderError leaf)`,`flatten: boolean (default true; false preserves tagged emission)`,`encode: Encoder<TReq> = (value) => JSONValue (custom wire shape; overrides flatten)`,`params: HttpQueryParams (scalar | array; undefined/null dropped; percent-encoded)`,`beforeRequest: (req) => IO<never, HttpError, HttpRequestView>`,`afterResponse: (HttpResponse<unknown>) => IO<never, HttpError, HttpResponse<unknown>> — success path only; refresh-on-401 uses .catchTag`]}},HttpError:{description:`Three-variant ADT for HTTP failures: NetworkError | HttpStatusError | DecodeError (also exported as ResponseDecodeError alias)`,interfaces:[],methods:{create:[`HttpError.networkError(url, method, cause)`,`HttpError.httpStatusError(url, method, status, statusText, body)`,`HttpError.decodeError(url, method, body, cause)`],check:[`HttpError.isNetworkError(e)`,`HttpError.isHttpStatusError(e)`,`HttpError.isDecodeError(e)`],other:[`HttpError.match(error, { NetworkError, HttpStatusError, DecodeError })`]}},Decoder:{description:"Either-returning decoder contract: `Decoder<A> = (raw: unknown) => Either<DecoderError, A>`. Bundled combinators for primitives + functype ADTs (Option/Either/List/Map, null-bias). `Decoder.tagged.*` round-trips the `{_tag, value}` shape for functype-to-functype services.",interfaces:[],methods:{create:[`Decoder.string / .number / .boolean / .unknown / .nullable(inner)`,`Decoder.fromThrowing(parse) // adapt a throwing parser such as Zod's schema.parse`,`Decoder.option(inner)`,`Decoder.either.envelope({ok, err})`,`Decoder.either.discriminated({tag, leftTag, rightTag}, l, r)`,`Decoder.list(inner) / .array(inner) / .map(inner)`,`Decoder.object({k: Decoder<V>, ...}) — accumulates field failures into Composite`,`Decoder.tagged.option/either/try/list/map/obj(inner?) — round-trips {_tag, value}`],other:[`Pluggable by construction: any (raw) => Either<DecoderError, T> IS a Decoder<T>`,`Composes across sources: Decoder.object({a: Decoder.fromZod(s), b: Decoder.option(myAjv)})`]}},DecoderError:{description:"Recursive ADT for decoder failures: Leaf | Composite. Children mirror the input tree so multi-field failures preserve structural paths. Distinct from `HttpError.DecodeError` — this is the inner structural cause that the HTTP wrapper carries.",interfaces:[],methods:{create:[`DecoderError.leaf(path, message, cause?)`,`DecoderError.composite(path, children: List<DecoderError>)`],check:[`DecoderError.isLeaf(e)`,`DecoderError.isComposite(e)`],other:[`DecoderError.match(e, { Leaf, Composite })`,`DecoderError.prepend(segment, e) — used by combinators to attribute child failures`,`DecoderError.flatten(e): List<{path, message}> — collect leaves`,`DecoderError.format(e): string — render tree as multi-line`,`DecoderError.formatPath(path): string — one path as format renders it (endpoints[1].name; (root) when empty)`]}},Serialization:{description:"Universal `@functype`-marked JSON serialization. `deserialize` walks parsed JSON and reconstructs any functype value found — no type argument needed. Lenient: plain JSON passes through. Strict on unknown markers (defends against Effect/fp-ts `_tag` collision). 1.2.1 adds `toEnvelope`/`fromEnvelope` for nesting inside structured serializers (SuperJSON, DBOS), and `deserializeStrict` for boundaries that require functype on the wire.",interfaces:[],methods:{create:[],transform:[`Serialization.serialize(value: unknown): string — lenient JSON codec`,`Serialization.deserialize(json: string): Try<unknown> — lenient; pass-through for unmarked JSON`,`Serialization.deserializeStrict(json: string): Try<unknown> — Failure if no @functype marker at top level`,`Serialization.toEnvelope(value: unknown): JSONValue — parsed JSON shape (1.2.2 tightened from unknown)`,`Serialization.fromEnvelope(envelope: unknown): Try<unknown> — inverse of toEnvelope; input stays permissive (Postel's law)`,`Serialization.JSONValue — exported recursive type for the envelope shape`],check:[`Serialization.isFunctypeValue(v): v is Serializable<unknown>`],other:[`Plain JSON passthrough: non-functype data walks through unchanged (use deserializeStrict to reject)`,`Strict policy on unknown markers: unknown @functype marker → Try.Failure`,`Dispatch table covers all 11 Serializable types (Option, Either, Try, List, Set, Map, Obj, Stack, Tuple, LazyList, Lazy)`,`Algebraic square: serialize ≡ JSON.stringify ∘ toEnvelope; deserialize ≡ fromEnvelope ∘ JSON.parse`,`No DBOS / SuperJSON facade — consumers wire host serializer in ~8 lines via toEnvelope/fromEnvelope`]}},SerializedError:{description:"Canonical Error projection used by Try.Failure and Lazy-with-thrown-thunk. Round-trips name + message + stack + cause chain. `e.name === 'TypeError'` survives; `instanceof TypeError` does NOT.",interfaces:[],methods:{create:[`serializeError(err: unknown): SerializedError`,`deserializeError(s: SerializedError | string): Error`],other:[`Shape: { name: string; message: string; stack?: string; cause?: SerializedError | string }`,`Non-Error throwables (strings, plain objects) projected under name: 'NonErrorThrowable'`,`Cause chain is recursive — arbitrary nesting depth survives`]}},Logger:{description:`Minimal 4-method logging interface every functype-* package targets. Type-only, no runtime. Impls live in consumers: consoleBootLogger (functype-os/config), DirectLogger (functype-log/direct). Tracer is type-only on the same terms; Clock/Random are not added.`,interfaces:[],methods:{create:[`interface Logger { debug, info, warn, error: (msg, meta?) => void }`,`import type { Logger } from "functype"`],check:[],other:[`All 4 methods MANDATORY (no defensive logger.debug?.() at call sites)`,`Signature: (message: string, metadata?: Record<string, unknown>) => void`,`DirectLogger from functype-log/direct structurally satisfies Logger (superset shape)`,`IO-shaped Logger from functype-log does NOT satisfy core Logger (methods return IO<>, not void) — bridge via toDirectLogger(ioLogger)`,`Used by: bootDiagnostics({ logger? }) in functype-os/config`]}},TypedError:{description:`Code-tagged structured error ADT (extends Throwable); TypedError.validation(...) feeds accumulating validation.`,interfaces:[],methods:{create:[`TypedError.validation(field, value, rule) → TypedError<"VALIDATION_FAILED">`,`TypedError.badRequest(reason, expected?)`,`TypedError.notFound(resource, id)`,`TypedError.auth(resource, requiredRole?)`,`TypedError.permission(action, resource, userId?)`,`TypedError.conflict(resource, value) / .rateLimit(limit, window, retryAfter?)`,`TypedError.timeout(ms, operation) / .network(url, method, status?) / .internal(errorId)`],check:[`TypedError.isTypedError(v)`,`TypedError.hasCode(e, code)`],other:[`Fields: .code, .message, .status (HTTP), .context, .timestamp, .traceId?`,`VALIDATION_FAILED context shape: { field, value, rule }`,`getErrorChain(error) → Error[] and formatErrorChain(error, { includeTasks? }) walk any error's cause chain`]}},Validation:{description:`Error-accumulating validation (functype's Validated role) — FormValidation<T> collects all field errors, not fail-fast.`,interfaces:[],methods:{create:[`Validation.rule<T>('min:18' | 'email' | 'required' | 'in:a,b' | ...)`,`Validation.combine(...validators) / Validation.custom(predicate, message)`,`Validation.validators.email / .url / .uuid / .required / .numeric / .positiveNumber / .nonEmptyString`],transform:[`Validation.form(schema, data) → FormValidation<T> (accumulates all field errors)`,`Validator<T> = (value: unknown) => Either<TypedError<'VALIDATION_FAILED'>, T>`],other:[`FormValidation<T> = Either<List<TypedError<"VALIDATION_FAILED">>, T> — functype's "Validated" accumulating result type`,`form() is flat/per-field: for cross-field (lo < hi) or dynamic-key (weights.*) checks, hand-accumulate into a List<TypedError> and return the FormValidation shape`]}}},a={Functor:{description:`Transform contained values`,methods:[`.map<B>(f: A => B): Functor<B>`]},Applicative:{extends:`Functor`,description:`Apply wrapped functions`,methods:[`.ap<B>(ff: Applicative<A => B>): Applicative<B>`]},Monad:{extends:`Applicative`,description:`Chain operations returning wrapped values`,methods:[`.flatMap<B>(f: A => Monad<B>): Monad<B>`]},Foldable:{description:`Extract via pattern matching`,methods:[`.fold<B, C = B>(empty: () => B, f: A => C): B | C`,`.foldLeft<B>(z: B, op: (B, A) => B): B`,`.foldRight<B>(z: B, op: (A, B) => B): B`]},Extractable:{description:`Get contained value with fallback`,methods:[`.getOrElse(d: () => T): T`,`.orThrow(e?: Error): T`,`.expect(handler: (e?) => never): T`,`.orNull(): T | null`,`.orUndefined(): T | undefined`]},Matchable:{description:`Pattern match on type variants`,methods:[`.match(patterns: Record<Tag, Handler>): union of the handlers' results`]},Traversable:{description:`Iterate and check contents`,methods:[`.size: number`,`.isEmpty: boolean`,`.contains(v: A): boolean`,`.reduce<B>(f, init): B`]},Collection:{description:`Collection operations`,methods:[`.toArray(): A[]`,`.forEach(f: A => void): void`]},Serializable:{description:`Convert to string formats`,methods:[`.serialize().toJSON(): string`,`.serialize().toBinary(): string`]}},o={Core:[`Option`,`Either`,`Try`,`Obj`,`Identity`],Collection:[`List`,`Set`,`Map`,`LazyList`,`Tuple`,`Stack`],Effect:[`IO`,`Exit`,`Http`,`HttpError`,`Decoder`,`DecoderError`],Utility:[`Lazy`,`Cond`,`Match`,`Do`,`Ref`,`Brand`,`ValidatedBrand`,`Wire`,`invariant`,`TracedOption`],Validation:[`TypedError`,`Validation`],Serialization:[`Serialization`,`SerializedError`],Service:[`Logger`,`Tracer`,`SpanTracer`]};export{o as CATEGORIES,a as INTERFACES,i as TYPES,n as VERSION};
|
|
@@ -95,7 +95,7 @@ export interface OptionBase<out T extends Type>
|
|
|
95
95
|
* @param onSome - Function to apply if the Option has a value
|
|
96
96
|
* @returns The result of applying the appropriate function
|
|
97
97
|
*/
|
|
98
|
-
fold<U>(onNone: () => U
|
|
98
|
+
fold<U, V = U>(onNone: () => U | NoInfer<V>, onSome: (value: T) => V | NoInfer<U>): U | V
|
|
99
99
|
/**
|
|
100
100
|
* Async variant of fold. Accepts sync or async handlers on either branch and
|
|
101
101
|
* always returns a Promise.
|
|
@@ -175,7 +175,7 @@ export interface OptionBase<out T extends Type>
|
|
|
175
175
|
* @param patterns - Object with handler functions for Some and None variants
|
|
176
176
|
* @returns The result of applying the matching handler function
|
|
177
177
|
*/
|
|
178
|
-
match<R>(patterns: { Some: (value: T) => R
|
|
178
|
+
match<R, S = R>(patterns: { Some: (value: T) => R | NoInfer<S>; None: () => S | NoInfer<R> }): R | S
|
|
179
179
|
}
|
|
180
180
|
|
|
181
181
|
export interface SomeOf<out T extends Type> extends OptionBase<T> {
|
|
@@ -267,7 +267,10 @@ export interface EitherBase<out L extends Type, out R extends Type>
|
|
|
267
267
|
*/
|
|
268
268
|
filterOrElse<L2 extends Type>(predicate: (value: R) => boolean, onUnsatisfied: (value: R) => L2): Either<L | L2, R>
|
|
269
269
|
bimap<L2 extends Type, R2 extends Type>(fl: (value: L) => L2, fr: (value: R) => R2): Either<L2, R2>
|
|
270
|
-
fold<T extends Type
|
|
270
|
+
fold<T extends Type, U extends Type = T>(
|
|
271
|
+
onLeft: (value: L) => T | NoInfer<U>,
|
|
272
|
+
onRight: (value: R) => U | NoInfer<T>,
|
|
273
|
+
): T | U
|
|
271
274
|
/**
|
|
272
275
|
* Async variant of fold. Accepts sync or async handlers on either branch and
|
|
273
276
|
* always returns a Promise, keeping chains fluent when at least one branch is async.
|
|
@@ -286,7 +289,7 @@ export interface EitherBase<out L extends Type, out R extends Type>
|
|
|
286
289
|
/**
|
|
287
290
|
* Pattern matches over the Either, applying a handler function based on the variant
|
|
288
291
|
*/
|
|
289
|
-
match<T>(patterns: { Left: (value: L) => T
|
|
292
|
+
match<T, U = T>(patterns: { Left: (value: L) => T | NoInfer<U>; Right: (value: R) => U | NoInfer<T> }): T | U
|
|
290
293
|
/**
|
|
291
294
|
* Returns the value and tag for inspection
|
|
292
295
|
*/
|
|
@@ -373,7 +376,10 @@ export interface TryBase<out T>
|
|
|
373
376
|
* @param onSuccess - Function to apply if the Try is Success
|
|
374
377
|
* @returns The result of applying the appropriate function
|
|
375
378
|
*/
|
|
376
|
-
fold<U extends Type
|
|
379
|
+
fold<U extends Type, V extends Type = U>(
|
|
380
|
+
onFailure: (error: Error) => U | NoInfer<V>,
|
|
381
|
+
onSuccess: (value: T) => V | NoInfer<U>,
|
|
382
|
+
): U | V
|
|
377
383
|
/**
|
|
378
384
|
* Async variant of fold. Accepts sync or async handlers on either branch and
|
|
379
385
|
* always returns a Promise.
|
|
@@ -388,7 +394,7 @@ export interface TryBase<out T>
|
|
|
388
394
|
* @param patterns - Object with handler functions for Success and Failure variants
|
|
389
395
|
* @returns The result of applying the matching handler function
|
|
390
396
|
*/
|
|
391
|
-
match<R>(patterns: { Success: (value: T) => R
|
|
397
|
+
match<R, S = R>(patterns: { Success: (value: T) => R | NoInfer<S>; Failure: (error: Error) => S | NoInfer<R> }): R | S
|
|
392
398
|
/**
|
|
393
399
|
* Recovers from a Failure by applying a function to the error, returning a new Try.
|
|
394
400
|
* The recovery value may be a wider type; the result is \`Try<T | U>\`, matching
|
|
@@ -512,7 +518,7 @@ export interface FailureOf<out T> extends TryBase<T> {
|
|
|
512
518
|
* @param patterns - Object with handler functions for Empty and NonEmpty variants
|
|
513
519
|
* @returns The result of applying the matching handler function
|
|
514
520
|
*/
|
|
515
|
-
match<R>(patterns: { Empty: () => R
|
|
521
|
+
match<R, S = R>(patterns: { Empty: () => R | NoInfer<S>; NonEmpty: (values: A[]) => S | NoInfer<R> }): R | S
|
|
516
522
|
}`,Set:`export interface Set<out A> extends FunctypeCollection<A, "Set">, Collection<A> {
|
|
517
523
|
add<B>(value: B): Set<A | B>
|
|
518
524
|
remove(value: unknown): Set<A>
|
|
@@ -624,7 +630,10 @@ export interface FailureOf<out T> extends TryBase<T> {
|
|
|
624
630
|
* @param patterns - Object with handler functions for Empty and NonEmpty variants
|
|
625
631
|
* @returns The result of applying the matching handler function
|
|
626
632
|
*/
|
|
627
|
-
match<R
|
|
633
|
+
match<R, S = R>(patterns: {
|
|
634
|
+
Empty: () => R | NoInfer<S>
|
|
635
|
+
NonEmpty: (entries: Array<Tuple<[K, V]>>) => S | NoInfer<R>
|
|
636
|
+
}): R | S
|
|
628
637
|
toValue(): { _tag: "Map"; value: [K, V][] }
|
|
629
638
|
}`,Lazy:`export interface Lazy<out T extends Type> extends FunctypeBase<T, "Lazy">, Extractable<T>, Pipe<T> {
|
|
630
639
|
/** Tag identifying this as a Lazy type */
|
|
@@ -894,12 +903,12 @@ export interface ExitBase<E extends Type, A extends Type> {
|
|
|
894
903
|
* behaviour, where defects were indistinguishable from typed failures. Supply it
|
|
895
904
|
* when the distinction matters; note the value it receives is \`unknown\`, not \`E\`.
|
|
896
905
|
*/
|
|
897
|
-
fold<T>(
|
|
898
|
-
onFailure: (e: E) => T
|
|
899
|
-
onSuccess: (a: A) => T
|
|
900
|
-
onInterrupted?: (fiberId: string) => T
|
|
901
|
-
onDie?: (defect: unknown) => T
|
|
902
|
-
): T
|
|
906
|
+
fold<T, U = T, V = T, W = T>(
|
|
907
|
+
onFailure: (e: E) => T | NoInfer<U | V | W>,
|
|
908
|
+
onSuccess: (a: A) => U | NoInfer<T | V | W>,
|
|
909
|
+
onInterrupted?: (fiberId: string) => V | NoInfer<T | U | W>,
|
|
910
|
+
onDie?: (defect: unknown) => W | NoInfer<T | U | V>,
|
|
911
|
+
): T | U | V | W
|
|
903
912
|
|
|
904
913
|
/**
|
|
905
914
|
* Pattern matches over the Exit with object patterns.
|
|
@@ -907,12 +916,12 @@ export interface ExitBase<E extends Type, A extends Type> {
|
|
|
907
916
|
* \`Die\` is optional for the same back-compat reason as {@link fold}'s \`onDie\`, and
|
|
908
917
|
* falls back to \`Failure\` when absent.
|
|
909
918
|
*/
|
|
910
|
-
match<T>(patterns: {
|
|
911
|
-
Success: (value: A) => T
|
|
912
|
-
Failure: (error: E) => T
|
|
913
|
-
Interrupted: (fiberId: string) => T
|
|
914
|
-
Die?: (defect: unknown) => T
|
|
915
|
-
}): T
|
|
919
|
+
match<T, U = T, V = T, W = T>(patterns: {
|
|
920
|
+
Success: (value: A) => T | NoInfer<U | V | W>
|
|
921
|
+
Failure: (error: E) => U | NoInfer<T | V | W>
|
|
922
|
+
Interrupted: (fiberId: string) => V | NoInfer<T | U | W>
|
|
923
|
+
Die?: (defect: unknown) => W | NoInfer<T | U | V>
|
|
924
|
+
}): T | U | V | W
|
|
916
925
|
|
|
917
926
|
/**
|
|
918
927
|
* Returns the success value or throws
|
|
@@ -1071,7 +1080,7 @@ export interface InterruptedExitOf<E extends Type, A extends Type> extends ExitB
|
|
|
1071
1080
|
* @param patterns - Object with handler functions for Empty and NonEmpty variants
|
|
1072
1081
|
* @returns The result of applying the matching handler function
|
|
1073
1082
|
*/
|
|
1074
|
-
match<R>(patterns: { Empty: () => R
|
|
1083
|
+
match<R, S = R>(patterns: { Empty: () => R | NoInfer<S>; NonEmpty: (values: A[]) => S | NoInfer<R> }): R | S
|
|
1075
1084
|
} & Traversable<A> &`,HttpError:`export type HttpError = NetworkError | HttpStatusError | DecodeError`,Http:`export interface HttpClientConfig {
|
|
1076
1085
|
readonly baseUrl?: string
|
|
1077
1086
|
readonly defaultHeaders?: Record<string, string>
|
|
@@ -21,6 +21,13 @@ type Pattern<T> = T | { [K in keyof T]?: Pattern<T[K]>; } | ((value: T) => boole
|
|
|
21
21
|
* @internal
|
|
22
22
|
*/
|
|
23
23
|
type PatternResult<T, R> = R | ((matched: T) => R);
|
|
24
|
+
/**
|
|
25
|
+
* The bound on a case's result type. It accepts every value, as `unknown` does, an `unknown` or
|
|
26
|
+
* generic result included, but because it names the primitive types TypeScript keeps a literal
|
|
27
|
+
* result as a literal: `caseValue("ok", "healthy")` gives `"healthy"`, not `string`. Arrays and
|
|
28
|
+
* objects are inferred as usual, so `[1, 2]` stays `number[]`.
|
|
29
|
+
*/
|
|
30
|
+
export type MatchResult = string | number | bigint | boolean | symbol | NonNullable<unknown> | null | undefined | void;
|
|
24
31
|
/**
|
|
25
32
|
* Untyped Match (before first case is added).
|
|
26
33
|
* The result type R is inferred when the first case method is called.
|
|
@@ -32,23 +39,23 @@ export type UntypedMatch<T extends Type> = {
|
|
|
32
39
|
/**
|
|
33
40
|
* Match against a pattern - infers result type R from the result parameter
|
|
34
41
|
*/
|
|
35
|
-
case: <R extends
|
|
42
|
+
case: <R extends MatchResult>(pattern: Pattern<T>, result: PatternResult<T, R>) => Match<T, R>;
|
|
36
43
|
/**
|
|
37
44
|
* Match a specific value - infers result type R from the result parameter
|
|
38
45
|
*/
|
|
39
|
-
caseValue: <R extends
|
|
46
|
+
caseValue: <R extends MatchResult>(match: T, result: R | (() => R)) => Match<T, R>;
|
|
40
47
|
/**
|
|
41
48
|
* Match multiple values - infers result type R from the result parameter
|
|
42
49
|
*/
|
|
43
|
-
caseValues: <R extends
|
|
50
|
+
caseValues: <R extends MatchResult>(matches: T[], result: R | (() => R)) => Match<T, R>;
|
|
44
51
|
/**
|
|
45
52
|
* Match with a guard function - infers result type R from the result parameter
|
|
46
53
|
*/
|
|
47
|
-
when: <R extends
|
|
54
|
+
when: <R extends MatchResult>(guard: (value: T) => boolean, result: PatternResult<T, R>) => Match<T, R>;
|
|
48
55
|
/**
|
|
49
56
|
* Match multiple patterns (OR operation) - infers result type R from the result parameter
|
|
50
57
|
*/
|
|
51
|
-
caseAny: <R extends
|
|
58
|
+
caseAny: <R extends MatchResult>(patterns: Pattern<T>[], result: PatternResult<T, R>) => Match<T, R>;
|
|
52
59
|
};
|
|
53
60
|
/**
|
|
54
61
|
* Pattern matching construct similar to Scala's match expressions.
|
|
@@ -82,32 +89,32 @@ export type Match<T extends Type, R extends Type> = {
|
|
|
82
89
|
* Match against a pattern (value, nested object, or predicate).
|
|
83
90
|
* The result type R2 is added to the union of possible results.
|
|
84
91
|
*/
|
|
85
|
-
case: <R2 extends
|
|
92
|
+
case: <R2 extends MatchResult>(pattern: Pattern<T>, result: PatternResult<T, R2>) => Match<T, R | R2>;
|
|
86
93
|
/**
|
|
87
94
|
* Add a case that matches a specific value.
|
|
88
95
|
* The result type R2 is added to the union of possible results.
|
|
89
96
|
*/
|
|
90
|
-
caseValue: <R2 extends
|
|
97
|
+
caseValue: <R2 extends MatchResult>(match: T, result: R2 | (() => R2)) => Match<T, R | R2>;
|
|
91
98
|
/**
|
|
92
99
|
* Add a case that matches multiple values.
|
|
93
100
|
* The result type R2 is added to the union of possible results.
|
|
94
101
|
*/
|
|
95
|
-
caseValues: <R2 extends
|
|
102
|
+
caseValues: <R2 extends MatchResult>(matches: T[], result: R2 | (() => R2)) => Match<T, R | R2>;
|
|
96
103
|
/**
|
|
97
104
|
* Match with a guard function (alias for readability).
|
|
98
105
|
* The result type R2 is added to the union of possible results.
|
|
99
106
|
*/
|
|
100
|
-
when: <R2 extends
|
|
107
|
+
when: <R2 extends MatchResult>(guard: (value: T) => boolean, result: PatternResult<T, R2>) => Match<T, R | R2>;
|
|
101
108
|
/**
|
|
102
109
|
* Match multiple patterns (OR operation).
|
|
103
110
|
* The result type R2 is added to the union of possible results.
|
|
104
111
|
*/
|
|
105
|
-
caseAny: <R2 extends
|
|
112
|
+
caseAny: <R2 extends MatchResult>(patterns: Pattern<T>[], result: PatternResult<T, R2>) => Match<T, R | R2>;
|
|
106
113
|
/**
|
|
107
114
|
* Default case - makes match non-exhaustive.
|
|
108
115
|
* The result type R2 is added to the union of possible results.
|
|
109
116
|
*/
|
|
110
|
-
default: <R2 extends
|
|
117
|
+
default: <R2 extends MatchResult>(result: PatternResult<T, R2>) => R | R2;
|
|
111
118
|
/**
|
|
112
119
|
* Force exhaustive matching (compile-time check for union types)
|
|
113
120
|
*/
|
|
@@ -278,13 +285,12 @@ declare const MatchStatics: {
|
|
|
278
285
|
* .default("Unknown")
|
|
279
286
|
*
|
|
280
287
|
* @example
|
|
281
|
-
* // A
|
|
282
|
-
* // to match into a literal union
|
|
288
|
+
* // A literal result keeps its literal type, so a match fits a literal union
|
|
283
289
|
* type Grade = "healthy" | "degraded" | "unknown"
|
|
284
290
|
* const grade: Grade = Match(status)
|
|
285
|
-
* .caseValue("ok", "healthy"
|
|
286
|
-
* .caseValue("degraded", () => "degraded"
|
|
287
|
-
* .default("unknown"
|
|
291
|
+
* .caseValue("ok", "healthy")
|
|
292
|
+
* .caseValue("degraded", () => "degraded")
|
|
293
|
+
* .default("unknown")
|
|
288
294
|
*
|
|
289
295
|
* @example
|
|
290
296
|
* // Using exhaustive() method
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { Cond, CondCompanion } from "./Cond.js";
|
|
2
|
-
import { Match, MatchCompanion, UntypedMatch } from "./Match.js";
|
|
3
|
-
export { Cond, CondCompanion, Match, MatchCompanion, UntypedMatch };
|
|
2
|
+
import { Match, MatchCompanion, MatchResult, UntypedMatch } from "./Match.js";
|
|
3
|
+
export { Cond, CondCompanion, Match, MatchCompanion, MatchResult, UntypedMatch };
|
package/dist/either/index.d.ts
CHANGED
|
@@ -95,7 +95,7 @@ export interface EitherBase<out L extends Type, out R extends Type> extends Func
|
|
|
95
95
|
*/
|
|
96
96
|
filterOrElse<L2 extends Type>(predicate: (value: R) => boolean, onUnsatisfied: (value: R) => L2): Either<L | L2, R>;
|
|
97
97
|
bimap<L2 extends Type, R2 extends Type>(fl: (value: L) => L2, fr: (value: R) => R2): Either<L2, R2>;
|
|
98
|
-
fold<T extends Type>(onLeft: (value: L) => T
|
|
98
|
+
fold<T extends Type, U extends Type = T>(onLeft: (value: L) => T | NoInfer<U>, onRight: (value: R) => U | NoInfer<T>): T | U;
|
|
99
99
|
/**
|
|
100
100
|
* Async variant of fold. Accepts sync or async handlers on either branch and
|
|
101
101
|
* always returns a Promise, keeping chains fluent when at least one branch is async.
|
|
@@ -113,10 +113,10 @@ export interface EitherBase<out L extends Type, out R extends Type> extends Func
|
|
|
113
113
|
/**
|
|
114
114
|
* Pattern matches over the Either, applying a handler function based on the variant
|
|
115
115
|
*/
|
|
116
|
-
match<T>(patterns: {
|
|
117
|
-
Left: (value: L) => T
|
|
118
|
-
Right: (value: R) => T
|
|
119
|
-
}): T;
|
|
116
|
+
match<T, U = T>(patterns: {
|
|
117
|
+
Left: (value: L) => T | NoInfer<U>;
|
|
118
|
+
Right: (value: R) => U | NoInfer<T>;
|
|
119
|
+
}): T | U;
|
|
120
120
|
/**
|
|
121
121
|
* Returns the value and tag for inspection
|
|
122
122
|
*/
|
package/dist/index.d.ts
CHANGED
|
@@ -70,5 +70,5 @@ import { Tracer } from "./traced/Tracer.js";
|
|
|
70
70
|
import { TracedOption } from "./traced/TracedOption.js";
|
|
71
71
|
import { Valuable, ValuableParams } from "./valuable/Valuable.js";
|
|
72
72
|
import { Wire, WireMark } from "./wire/index.js";
|
|
73
|
-
import { Match, MatchCompanion, UntypedMatch } from "./conditional/Match.js";
|
|
74
|
-
export { $, type Applicative, type AsyncMonad, Base, BoundedNumber, BoundedString, Brand, BrandedBoolean, type BrandedBoolean as BrandedBooleanType, BrandedNumber, type BrandedNumber as BrandedNumberType, BrandedString, type BrandedString as BrandedStringType, Collection, type CollectionOps, Companion, CompanionMethods, type Concurrency, type ConcurrencyOptions, Cond, CondCompanion, type ContainerOps, Context, type ContextServices, type Context as ContextType, type DecodeError, Decoder, DecoderCompanion, DecoderError, type DecoderErrorCompanion, type DecoderErrorComposite, type DecoderErrorLeaf, type DieExitOf, Do, DoAsync, DoGenerator, type DoResult, type Doable, ESMap, ESMapType, Either, EitherBase, EitherCompanion, EitherKind, EmailAddress, EmptyListError, type Encoder, ErrorChainElement, ErrorChainFormatOptions, ErrorCode, ErrorFormatterOptions, ErrorMessage, ErrorStatus, ErrorWithTaskInfo, Exit, type ExitBase, type ExitCompanion, type ExitTag, type Exit as ExitType, type ExtractBrand, ExtractTag, type Extractable, FUNCTYPE_MARKER, FailureError, FailureErrorType, type FailureExitOf, FailureOf, FieldValidation, type Flattened, Foldable, FoldableUtils, FormValidation, type Functor, Functype, FunctypeBase, FunctypeCollection, FunctypeCore, FunctypeEnvelope, FunctypeSum, FunctypeValue, HKT, type HasService, Http, HttpClient, type HttpClientConfig, type HttpCompanion, HttpError, type HttpErrorCompanion, HttpError as HttpErrors, type HttpMethod, type HttpMethodOptions, type HttpMethods, type HttpQueryParams, type HttpRequestOptions, type HttpRequestView, type HttpResponse, type HttpStatusError, IO, type IOCompanion, type Task as IOTask, type IO as IOType, ISO8601Date, Identity, IdentityCompanion, InstanceType, IntegerNumber, InterruptedError, type InterruptedExitOf, InvariantViolation, type JSONValue, KVTraversable, Kind, Layer, type LayerError, type LayerInput, type LayerOutput, type Layer as LayerType, Lazy, type LazyCompanion, LazyList, LazyListCompanion, type Lazy as LazyType, Left, LeftError, LeftErrorType, LeftOf, List, ListCompanion, ListKind, type Logger, Map, MapCompanion, Match, MatchCompanion, type Matchable, MatchableUtils, type Monad, NAME, type NetworkError, NonEmptyString, NonNegativeNumber, None, NoneError, NoneOf, Obj, ObjCompanion, Option, OptionBase, OptionCompanion, OptionConstructor, OptionKind, ParseError, type ParseMode, ParsedEnvelope, PatternString, Pipe, PositiveInteger, PositiveNumber, type Promisable, type RIO, Reducible, Ref, type RefCompanion, type Ref as RefType, RepeatExhausted, type Reshapeable, type ResponseDecodeError, Right, RightOf, Serializable, SerializableEnvelope, Serialization_d_exports as Serialization, SerializationMethods, SerializationResult, SerializedError, Set, SetCompanion, Some, SomeOf, type SpanAttributes, SpanTracer, Stack, StackCompanion, type SuccessExitOf, SuccessOf, Tag, type TagService, type Tag as TagType, TaggedThrowable, TaskErrorInfo, TestClock, TestClockTag, type TestClock as TestClockType, TestContext, type TestContext as TestContextType, TestEither, Throwable, ThrowableType, TimeoutError, type TraceEvent, type TraceOp, TracedOption, type Tracer, Traversable, Try, TryBase, TryCompanion, TryKind, Tuple, TupleCompanion, Type, TypeCheckLeft, TypeCheckRight, TypeNames, Typeable, TypeableParams, TypedError, TypedErrorContext, type UIO, UUID, UniversalContainer, UnsupportedSyncOperationError, UntypedMatch, type Unwrap, UrlString, ValidatedBrand, type ValidatedBrandCompanion, type ValidatedBrand as ValidatedBrandType, Validation, ValidationRule, Validator, Valuable, ValuableParams, type Widen, type Wire, type WireMark, createBrander, createErrorSerializer, createSerializationCompanion, createSerializer, createTaggedSerializer, deserializeError, envelope, expectMarker, formatError, formatErrorChain, formatStackTrace, fromBinary, fromJSON, getErrorChain, hasBrand, invariant, isCompanion, isDoCapable, isExtractable, isLeft, isRight, isTaggedThrowable, isTypeable, reduceRightWiden, reduceWiden, safeStringify, serializeError, taggedEnvelope, tryCatch, tryCatchAsync, unwrap, unwrapBrand };
|
|
73
|
+
import { Match, MatchCompanion, MatchResult, UntypedMatch } from "./conditional/Match.js";
|
|
74
|
+
export { $, type Applicative, type AsyncMonad, Base, BoundedNumber, BoundedString, Brand, BrandedBoolean, type BrandedBoolean as BrandedBooleanType, BrandedNumber, type BrandedNumber as BrandedNumberType, BrandedString, type BrandedString as BrandedStringType, Collection, type CollectionOps, Companion, CompanionMethods, type Concurrency, type ConcurrencyOptions, Cond, CondCompanion, type ContainerOps, Context, type ContextServices, type Context as ContextType, type DecodeError, Decoder, DecoderCompanion, DecoderError, type DecoderErrorCompanion, type DecoderErrorComposite, type DecoderErrorLeaf, type DieExitOf, Do, DoAsync, DoGenerator, type DoResult, type Doable, ESMap, ESMapType, Either, EitherBase, EitherCompanion, EitherKind, EmailAddress, EmptyListError, type Encoder, ErrorChainElement, ErrorChainFormatOptions, ErrorCode, ErrorFormatterOptions, ErrorMessage, ErrorStatus, ErrorWithTaskInfo, Exit, type ExitBase, type ExitCompanion, type ExitTag, type Exit as ExitType, type ExtractBrand, ExtractTag, type Extractable, FUNCTYPE_MARKER, FailureError, FailureErrorType, type FailureExitOf, FailureOf, FieldValidation, type Flattened, Foldable, FoldableUtils, FormValidation, type Functor, Functype, FunctypeBase, FunctypeCollection, FunctypeCore, FunctypeEnvelope, FunctypeSum, FunctypeValue, HKT, type HasService, Http, HttpClient, type HttpClientConfig, type HttpCompanion, HttpError, type HttpErrorCompanion, HttpError as HttpErrors, type HttpMethod, type HttpMethodOptions, type HttpMethods, type HttpQueryParams, type HttpRequestOptions, type HttpRequestView, type HttpResponse, type HttpStatusError, IO, type IOCompanion, type Task as IOTask, type IO as IOType, ISO8601Date, Identity, IdentityCompanion, InstanceType, IntegerNumber, InterruptedError, type InterruptedExitOf, InvariantViolation, type JSONValue, KVTraversable, Kind, Layer, type LayerError, type LayerInput, type LayerOutput, type Layer as LayerType, Lazy, type LazyCompanion, LazyList, LazyListCompanion, type Lazy as LazyType, Left, LeftError, LeftErrorType, LeftOf, List, ListCompanion, ListKind, type Logger, Map, MapCompanion, Match, MatchCompanion, MatchResult, type Matchable, MatchableUtils, type Monad, NAME, type NetworkError, NonEmptyString, NonNegativeNumber, None, NoneError, NoneOf, Obj, ObjCompanion, Option, OptionBase, OptionCompanion, OptionConstructor, OptionKind, ParseError, type ParseMode, ParsedEnvelope, PatternString, Pipe, PositiveInteger, PositiveNumber, type Promisable, type RIO, Reducible, Ref, type RefCompanion, type Ref as RefType, RepeatExhausted, type Reshapeable, type ResponseDecodeError, Right, RightOf, Serializable, SerializableEnvelope, Serialization_d_exports as Serialization, SerializationMethods, SerializationResult, SerializedError, Set, SetCompanion, Some, SomeOf, type SpanAttributes, SpanTracer, Stack, StackCompanion, type SuccessExitOf, SuccessOf, Tag, type TagService, type Tag as TagType, TaggedThrowable, TaskErrorInfo, TestClock, TestClockTag, type TestClock as TestClockType, TestContext, type TestContext as TestContextType, TestEither, Throwable, ThrowableType, TimeoutError, type TraceEvent, type TraceOp, TracedOption, type Tracer, Traversable, Try, TryBase, TryCompanion, TryKind, Tuple, TupleCompanion, Type, TypeCheckLeft, TypeCheckRight, TypeNames, Typeable, TypeableParams, TypedError, TypedErrorContext, type UIO, UUID, UniversalContainer, UnsupportedSyncOperationError, UntypedMatch, type Unwrap, UrlString, ValidatedBrand, type ValidatedBrandCompanion, type ValidatedBrand as ValidatedBrandType, Validation, ValidationRule, Validator, Valuable, ValuableParams, type Widen, type Wire, type WireMark, createBrander, createErrorSerializer, createSerializationCompanion, createSerializer, createTaggedSerializer, deserializeError, envelope, expectMarker, formatError, formatErrorChain, formatStackTrace, fromBinary, fromJSON, getErrorChain, hasBrand, invariant, isCompanion, isDoCapable, isExtractable, isLeft, isRight, isTaggedThrowable, isTypeable, reduceRightWiden, reduceWiden, safeStringify, serializeError, taggedEnvelope, tryCatch, tryCatchAsync, unwrap, unwrapBrand };
|
package/dist/io/Exit.d.ts
CHANGED
|
@@ -56,19 +56,19 @@ export interface ExitBase<E extends Type, A extends Type> {
|
|
|
56
56
|
* behaviour, where defects were indistinguishable from typed failures. Supply it
|
|
57
57
|
* when the distinction matters; note the value it receives is `unknown`, not `E`.
|
|
58
58
|
*/
|
|
59
|
-
fold<T>(onFailure: (e: E) => T
|
|
59
|
+
fold<T, U = T, V = T, W = T>(onFailure: (e: E) => T | NoInfer<U | V | W>, onSuccess: (a: A) => U | NoInfer<T | V | W>, onInterrupted?: (fiberId: string) => V | NoInfer<T | U | W>, onDie?: (defect: unknown) => W | NoInfer<T | U | V>): T | U | V | W;
|
|
60
60
|
/**
|
|
61
61
|
* Pattern matches over the Exit with object patterns.
|
|
62
62
|
*
|
|
63
63
|
* `Die` is optional for the same back-compat reason as {@link fold}'s `onDie`, and
|
|
64
64
|
* falls back to `Failure` when absent.
|
|
65
65
|
*/
|
|
66
|
-
match<T>(patterns: {
|
|
67
|
-
Success: (value: A) => T
|
|
68
|
-
Failure: (error: E) => T
|
|
69
|
-
Interrupted: (fiberId: string) => T
|
|
70
|
-
Die?: (defect: unknown) => T
|
|
71
|
-
}): T;
|
|
66
|
+
match<T, U = T, V = T, W = T>(patterns: {
|
|
67
|
+
Success: (value: A) => T | NoInfer<U | V | W>;
|
|
68
|
+
Failure: (error: E) => U | NoInfer<T | V | W>;
|
|
69
|
+
Interrupted: (fiberId: string) => V | NoInfer<T | U | W>;
|
|
70
|
+
Die?: (defect: unknown) => W | NoInfer<T | U | V>;
|
|
71
|
+
}): T | U | V | W;
|
|
72
72
|
/**
|
|
73
73
|
* Returns the success value or throws
|
|
74
74
|
*/
|
package/dist/io/IO.d.ts
CHANGED
|
@@ -234,13 +234,22 @@ type IOEffect<R, E, A> = {
|
|
|
234
234
|
readonly start: () => Iterator<unknown, A, unknown>;
|
|
235
235
|
};
|
|
236
236
|
/**
|
|
237
|
-
* The
|
|
238
|
-
*
|
|
239
|
-
* with that sentence and the services it still needs, rather than with `IO<never, E, A>`.
|
|
237
|
+
* The services, errors and values of an IO, or of each IO in a union of them, so a runner called
|
|
238
|
+
* on `IO<never, E1, A1> | IO<never, E2, A2>` gives `E1 | E2` and `A1 | A2`.
|
|
240
239
|
* @internal
|
|
241
240
|
*/
|
|
242
|
-
export type
|
|
243
|
-
|
|
241
|
+
export type RequirementsOf<Self> = Self extends IO<infer R, infer _E, infer _A> ? R : never;
|
|
242
|
+
/** @internal */
|
|
243
|
+
export type ErrorOf<Self> = Self extends IO<infer _R, infer E, infer _A> ? E : never;
|
|
244
|
+
/** @internal */
|
|
245
|
+
export type ValueOf<Self> = Self extends IO<infer _R, infer _E, infer A> ? A : never;
|
|
246
|
+
/**
|
|
247
|
+
* What a runner's `this` must also be: nothing more when the IO, or every IO in a union, needs no
|
|
248
|
+
* services, else the "provide these services" sentence, which is what the call then fails with.
|
|
249
|
+
* @internal
|
|
250
|
+
*/
|
|
251
|
+
export type RunnableSelf<Self> = [RequirementsOf<Self>] extends [never] ? unknown : {
|
|
252
|
+
readonly "Provide these services first, with provideLayer or provideService": RequirementsOf<Self>;
|
|
244
253
|
};
|
|
245
254
|
/**
|
|
246
255
|
* The tags `catchTag` accepts: the `_tag` of each error in `E` that has one. When there is none to
|
|
@@ -285,7 +294,7 @@ export type IOGenErrors<Y> = 0 extends 1 & Y ? unknown : Y extends IO<infer _R,
|
|
|
285
294
|
* @typeParam E - Error type (typed failures)
|
|
286
295
|
* @typeParam A - Success type (value produced on success)
|
|
287
296
|
*/
|
|
288
|
-
export interface IO<
|
|
297
|
+
export interface IO<out R extends Type, out E extends Type, out A extends Type> {
|
|
289
298
|
readonly [Symbol.toStringTag]: string;
|
|
290
299
|
/**
|
|
291
300
|
* Internal effect representation (symbol-keyed for opacity)
|
|
@@ -375,14 +384,14 @@ export interface IO<in out R extends Type, out E extends Type, out A extends Typ
|
|
|
375
384
|
* @param onSuccess - Handler for successes
|
|
376
385
|
* @returns New IO with handled result
|
|
377
386
|
*/
|
|
378
|
-
fold<B extends Type>(onFailure: (e: E) => B
|
|
387
|
+
fold<B extends Type, C extends Type = B>(onFailure: (e: E) => B | NoInfer<C>, onSuccess: (a: A) => C | NoInfer<B>): IO<R, never, B | C>;
|
|
379
388
|
/**
|
|
380
389
|
* Pattern matches with object pattern syntax.
|
|
381
390
|
*/
|
|
382
|
-
match<B extends Type>(patterns: {
|
|
383
|
-
failure: (e: E) => B
|
|
384
|
-
success: (a: A) => B
|
|
385
|
-
}): IO<R, never, B>;
|
|
391
|
+
match<B extends Type, C extends Type = B>(patterns: {
|
|
392
|
+
failure: (e: E) => B | NoInfer<C>;
|
|
393
|
+
success: (a: A) => C | NoInfer<B>;
|
|
394
|
+
}): IO<R, never, B | C>;
|
|
386
395
|
/**
|
|
387
396
|
* Catches errors with a specific tag and handles them.
|
|
388
397
|
* @param tag - The error tag to catch
|
|
@@ -554,13 +563,13 @@ export interface IO<in out R extends Type, out E extends Type, out A extends Typ
|
|
|
554
563
|
* so that one resolves as a `Left`.
|
|
555
564
|
* Requires R = never.
|
|
556
565
|
*/
|
|
557
|
-
run
|
|
566
|
+
run<Self extends IO<Type, Type, Type>>(this: Self & RunnableSelf<Self>): Promise<Either<ErrorOf<Self>, ValueOf<Self>>>;
|
|
558
567
|
/**
|
|
559
568
|
* Runs the effect and returns a Promise of the value.
|
|
560
569
|
* Throws on any error (typed E, defect, or interrupt).
|
|
561
570
|
* Requires R = never.
|
|
562
571
|
*/
|
|
563
|
-
runOrThrow
|
|
572
|
+
runOrThrow<Self extends IO<Type, Type, Type>>(this: Self & RunnableSelf<Self>): Promise<ValueOf<Self>>;
|
|
564
573
|
/**
|
|
565
574
|
* Runs a sync effect and returns an Either of its typed error or its value.
|
|
566
575
|
*
|
|
@@ -570,13 +579,13 @@ export interface IO<in out R extends Type, out E extends Type, out A extends Typ
|
|
|
570
579
|
* {@link UnsupportedSyncOperationError}.
|
|
571
580
|
* Requires R = never.
|
|
572
581
|
*/
|
|
573
|
-
runSync
|
|
582
|
+
runSync<Self extends IO<Type, Type, Type>>(this: Self & RunnableSelf<Self>): Either<ErrorOf<Self>, ValueOf<Self>>;
|
|
574
583
|
/**
|
|
575
584
|
* Runs a sync effect and returns the value.
|
|
576
585
|
* Throws on any error or if the effect is async.
|
|
577
586
|
* Requires R = never.
|
|
578
587
|
*/
|
|
579
|
-
runSyncOrThrow
|
|
588
|
+
runSyncOrThrow<Self extends IO<Type, Type, Type>>(this: Self & RunnableSelf<Self>): ValueOf<Self>;
|
|
580
589
|
/**
|
|
581
590
|
* Runs the effect and returns an Exit.
|
|
582
591
|
*
|
|
@@ -587,19 +596,19 @@ export interface IO<in out R extends Type, out E extends Type, out A extends Typ
|
|
|
587
596
|
* a typed `InterruptedError`. This suits runners (React hooks, query adapters) that
|
|
588
597
|
* discard a cancelled result rather than handle it.
|
|
589
598
|
*/
|
|
590
|
-
runExit
|
|
599
|
+
runExit<Self extends IO<Type, Type, Type>>(this: Self & RunnableSelf<Self>, options?: {
|
|
591
600
|
readonly signal?: AbortSignal;
|
|
592
|
-
}): Promise<Exit<
|
|
601
|
+
}): Promise<Exit<ErrorOf<Self>, ValueOf<Self>>>;
|
|
593
602
|
/**
|
|
594
603
|
* Runs the effect and returns an Option.
|
|
595
604
|
* Some(value) on success, None on failure.
|
|
596
605
|
*/
|
|
597
|
-
runOption
|
|
606
|
+
runOption<Self extends IO<Type, Type, Type>>(this: Self & RunnableSelf<Self>): Promise<Option<ValueOf<Self>>>;
|
|
598
607
|
/**
|
|
599
608
|
* Runs the effect and returns a Try.
|
|
600
609
|
* Success(value) on success, Failure(error) on failure.
|
|
601
610
|
*/
|
|
602
|
-
runTry
|
|
611
|
+
runTry<Self extends IO<Type, Type, Type>>(this: Self & RunnableSelf<Self>): Promise<ReturnType<typeof Try<ValueOf<Self>>>>;
|
|
603
612
|
/**
|
|
604
613
|
* Starts the effect and returns a handle that cancels it, with {@link IO.interruptOn}
|
|
605
614
|
* semantics: after `cancel()`, no further step runs and `result` resolves to
|
|
@@ -614,8 +623,8 @@ export interface IO<in out R extends Type, out E extends Type, out A extends Typ
|
|
|
614
623
|
* const report = await result
|
|
615
624
|
* ```
|
|
616
625
|
*/
|
|
617
|
-
runCancellable
|
|
618
|
-
readonly result: Promise<Either<
|
|
626
|
+
runCancellable<Self extends IO<Type, Type, Type>>(this: Self & RunnableSelf<Self>): {
|
|
627
|
+
readonly result: Promise<Either<ErrorOf<Self> | InterruptedError, ValueOf<Self>>>;
|
|
619
628
|
readonly cancel: () => void;
|
|
620
629
|
};
|
|
621
630
|
/**
|
package/dist/io/IO.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Companion as e}from"../companion/Companion.js";import{Left as t,Right as n}from"../either/index.js";import{workerCount as r}from"../internal/concurrency.js";import{define as i}from"../internal/define.js";import{anySignal as a}from"../internal/signal.js";import{safeStringify as o}from"../internal/stringify.js";import{None as s,Option as c,Some as l}from"../option/index.js";import{Try as u}from"../try/index.js";import{Context as d}from"./Context.js";import{Exit as f}from"./Exit.js";import{SpanTracer as p}from"./SpanTracer.js";const m=e=>e,h=e=>e(),g=(e,t)=>e(t),_=(e,t,n)=>e(t,n);var v=class extends Error{constructor(e,t){super(t??`Effect timed out after ${e}ms`),this.duration=e,this._tag=`TimeoutError`,this.name=`TimeoutError`}},y=class extends Error{constructor(e){super(e??`Effect was interrupted`),this._tag=`InterruptedError`,this.name=`InterruptedError`}static is(e){return typeof e==`object`&&!!e&&`_tag`in e&&e._tag===`InterruptedError`}},b=class extends Error{constructor(e){super(`Cannot run ${e} effect synchronously — use run()/runExit() instead`),this.operation=e,this._tag=`UnsupportedSyncOperationError`,this.name=`UnsupportedSyncOperationError`}},x=class extends Error{constructor(e,t,n){super(n??`Repeat exhausted after ${e} iterations`),this.max=e,this.lastValue=t,this._tag=`RepeatExhausted`,this.name=`RepeatExhausted`}static is(e){return typeof e==`object`&&!!e&&`_tag`in e&&e._tag===`RepeatExhausted`}};const S=`effect`,C=e=>e[S],w=e=>{let t=!1;return{next:n=>t?{done:!0,value:n}:(t=!0,{done:!1,value:e})}},T=e=>m(e),E=i()(`IO`,{[Symbol.toStringTag]:`IO`,map(e){return D(m({_tag:`Map`,effect:this,f:e}))},flatMap(e){return D(m({_tag:`FlatMap`,effect:this,f:e}))},mapTry(e,t){return this.flatMap(n=>Q.tryCatch(()=>e(n),t))},tap(e){return this.map(t=>(e(t),t))},tapEffect(e){return this.flatMap(t=>e(t).map(()=>t))},mapError(e){return D(m({_tag:`MapError`,effect:this,f:e}))},tapError(e){return this.mapError(t=>(e(t),t))},recover(e){return D(m({_tag:`Recover`,effect:this,fallback:e}))},recoverWith(e){return D(m({_tag:`RecoverWith`,effect:this,f:e}))},fold(e,t){return D(m({_tag:`Fold`,effect:this,onFailure:e,onSuccess:t}))},match(e){return this.fold(e.failure,e.success)},catchTag(e,t){return D(m({_tag:`RecoverWith`,effect:this,f:n=>typeof n==`object`&&n&&`_tag`in n&&n._tag===e?m(t(m(n))):m(Q.fail(n))}))},catchAll(e){return this.recoverWith(e)},retry(e){return e<=0?this:this.recoverWith(()=>this.retry(e-1))},retryWithDelay(e,t){return e<=0?this:this.recoverWith(()=>Q.sleep(t).flatMap(()=>this.retryWithDelay(e-1,t)))},retryWhile(e){let t=(n,r)=>this.recoverWith(i=>{if(n<=0||!e.while(i,r))return m(Q.fail(i));let a=t(n-1,r+1);return e.delayMs===void 0?a:m(Q.sleep(e.delayMs).flatMap(()=>a))});return t(e.n,1)},retryWithBackoff(e){let t=e.factor??2,n=e.maxMs??3e4,r=e.jitter??!0,i=e.while??(()=>!0),a=(o,s)=>this.recoverWith(c=>{if(o<=0||!i(c,s))return m(Q.fail(c));let l=Math.min(n,e.baseMs*t**(s-1)),u=r?l*(.5+Math.random()*.5):l,d=a(o-1,s+1);return m(Q.sleep(u).flatMap(()=>d))});return a(e.n,1)},repeatUntil(e,t){if(t.max<=0)return m(Q.fail(new x(t.max)));let n=r=>this.flatMap(i=>{if(e(i))return m(Q.succeed(i));if(r<=1)return m(Q.fail(new x(t.max,i)));let a=n(r-1);return t.delayMs===void 0?a:m(Q.sleep(t.delayMs).flatMap(()=>a))});return n(t.max)},repeatWhile(e,t){return this.repeatUntil(t=>!e(t),t)},zipRight(e){return this.flatMap(()=>e)},zipLeft(e){return this.flatMap(t=>e.map(()=>t))},zip(e){return this.flatMap(t=>e.map(e=>[t,e]))},flatten(){return this.flatMap(e=>e)},provideContext(e){return D(m({_tag:`ProvideContext`,effect:this,context:e}))},provideService(e,t){let n=d.make(e,t);return D(m({_tag:`ProvideContext`,effect:this,context:n}))},provideLayer(e){let t=m(Q.async(async()=>{let t=d.empty();return await e.build(m(t))}));return m(t.flatMap(e=>D(m({_tag:`ProvideContext`,effect:this,context:e}))))},async run(){return F(await q(C(T(this)),A,void 0,void 0))},async runOrThrow(){return I(await q(C(T(this)),A,void 0,void 0))},runSync(){return F(B(C(T(this)),A,void 0))},runSyncOrThrow(){return I(B(C(T(this)),A,void 0))},async runExit(e){let t=e?.signal;if(!t)return q(C(T(this)),A,void 0,void 0);let n=await q(C(T(this)),A,t,void 0);return t.aborted&&n.isFailure()?f.interrupted():n},async runOption(){let e=await q(C(T(this)),A,void 0,void 0);return e.isSuccess()?l(e.value):s()},async runTry(){let e=await q(C(T(this)),A,void 0,void 0);if(e.isSuccess())return m(u(()=>e.value));let t=O(e),n=t?t.value:/* @__PURE__ */ Error(`Effect was interrupted`);return m(u(()=>{throw n}))},runCancellable(){let e=new AbortController;return{result:T(this).interruptOn(e.signal).run(),cancel:()=>e.abort()}},pipe(e){return e(this)},delay(e){return Q.sleep(e).flatMap(()=>this)},timeout(e){return D(m({_tag:`Timeout`,effect:this,duration:e}))},timeoutTo(e,t){return D(m({_tag:`Timeout`,effect:this,duration:e,fallback:{value:t}}))},interruptOn(e){return D(m({_tag:`InterruptWhen`,effect:this,signal:e}))},withSpan(e,t=j){return D(m({_tag:`WithSpan`,effect:this,name:e,attributes:t}))},toString(){return`IO(${o(this[S]._tag)})`},toJSON(){return{_tag:`IO`,effect:this[S]._tag}},[Symbol.iterator](){return w(this)}}),D=e=>{let t=Object.create(E);return t[S]=e,t},O=e=>{if(e._tag===`Failure`)return{value:e.error};if(e._tag===`Die`)return{value:e.defect}},k=e=>e._tag===`Die`&&e.defect instanceof b?void 0:O(e),A=d.empty(),j=Object.freeze({}),M=e=>{let t=e.get(p);return t.isNone()?void 0:t.orThrow()},N=()=>/* @__PURE__ */ Error(`Cannot run async effect synchronously`),P=e=>/* @__PURE__ */ Error(`Service not found: ${e.id}`),F=e=>{if(e._tag===`Success`)return n(e.value);if(e._tag===`Failure`)return t(e.error);throw e._tag===`Die`?e.defect:new y},I=e=>{if(e._tag===`Success`)return e.value;throw e._tag===`Failure`?e.error:e._tag===`Die`?e.defect:new y},L=e=>{try{return e()}catch(e){return f.die(e)}},R=e=>{let t=typeof e==`object`&&e?e[S]:void 0;if(typeof t==`object`&&t&&typeof t._tag==`string`)return m(t);throw TypeError("IO.gen was yielded a value that isn't an IO. Use `yield*` on an IO; convert an Option, Either or Try first with IO.fromOption, IO.fromEither or IO.fromTry, and wrap a plain value with IO.succeed.")},z=()=>f.die(/* @__PURE__ */ TypeError(`A step produced no outcome: a SpanTracer's run must return what its fn returns`)),B=(e,t,n)=>{let r=[],i=m(e),a=m(t),o;for(;;){if(o===void 0)try{switch(i._tag){case`Map`:case`FlatMap`:case`MapError`:case`Recover`:case`RecoverWith`:case`Fold`:r.push(i,a),i=C(i.effect);continue;case`ProvideContext`:a=a.merge(i.context),i=C(i.effect);continue;case`Gen`:{let e=h(i.start),t=e.next(void 0);if(t.done===!0){o=f.succeed(t.value);continue}r.push({_tag:`GenNext`,iterator:e},a),i=R(t.value);continue}default:o=V(i,a,n)??z();continue}}catch(e){o=f.die(e);continue}if(r.length===0)return m(o);let e=r.pop(),t=r.pop();try{switch(t._tag){case`Map`:o._tag===`Success`&&(o=f.succeed(g(t.f,o.value)));break;case`FlatMap`:o._tag===`Success`&&(i=C(g(t.f,o.value)),a=e,o=void 0);break;case`MapError`:{let e=k(o);e&&(o=f.fail(g(t.f,e.value)));break}case`Recover`:k(o)&&(o=f.succeed(t.fallback));break;case`RecoverWith`:{let n=k(o);n&&(i=C(g(t.f,n.value)),a=e,o=void 0);break}case`Fold`:{let e=k(o);e?o=f.succeed(g(t.onFailure,e.value)):o._tag===`Success`&&(o=f.succeed(g(t.onSuccess,o.value)));break}case`GenNext`:if(o._tag===`Success`){let n=t.iterator.next(o.value);n.done===!0?o=f.succeed(n.value):(r.push(t,e),i=R(n.value),a=e,o=void 0)}}}catch(e){o=f.die(e)}}},V=(e,t,n)=>{try{switch(e._tag){case`Succeed`:return f.succeed(e.value);case`Fail`:return f.fail(e.error);case`Die`:return f.die(e.defect);case`Sync`:return f.succeed(h(e.thunk));case`Async`:return f.die(N());case`Auto`:return H(e.thunk);case`Service`:{let n=t.get(e.tag);return n.isNone()?f.die(P(e.tag)):f.succeed(n.orThrow())}case`Interrupt`:return f.interrupted();case`Bracket`:{let r=B(C(e.acquire),t,n);if(!r.isSuccess())return r;let i=r.value,a=L(()=>B(C(g(e.use,i)),t,n)),o=B(C(g(e.release,i)),t,n);return o.isSuccess()?a:o}case`BracketExit`:{let r=B(C(e.acquire),t,n);if(!r.isSuccess())return r;let i=r.value,a=L(()=>B(C(g(e.use,i)),t,n)),o=B(C(_(e.release,i,a)),t,n);return o.isSuccess()?a:o}case`All`:return W(e.effects,t,n);case`Race`:return f.die(new b(`race`));case`Timeout`:return f.die(new b(`timeout`));case`Sleep`:return f.die(new b(`sleep`));case`WithSpan`:return U(e,t,n);case`InterruptWhen`:{if(e.signal.aborted)return f.fail(new y);let r=B(C(e.effect),t,n);return r.isInterrupted()?f.fail(new y):r}default:return f.die(/* @__PURE__ */ Error(`Unexpected step: ${e._tag}`))}}catch(e){return f.die(e)}},H=e=>{try{let t=e();return t instanceof Promise?f.die(N()):f.succeed(t)}catch(e){return f.fail(e)}},U=(e,t,n)=>{let r=M(t);if(!r)return B(C(e.effect),t,n);let i=r.start(e.name,e.attributes,n),a=L(()=>r.run(i,()=>B(C(e.effect),t,i)));return r.end(i,a),a},W=(e,t,n)=>{let r=[];for(let i of e){let e=B(C(i),t,n);if(!e.isSuccess())return m(e);r.push(e.value)}return f.succeed(r)},G=(e,t)=>{if(t)return e.isDie()?m(e):f.interrupted()},K=(e,t,n)=>e.isSuccess()||e.isDie()?e:n?f.interrupted():e.isInterrupted()||t.aborted?f.fail(new y):e,q=async(e,t,n,r)=>{let i=[],a=m(e),o=m(t),s,c=()=>n?.aborted??!1;for(;;){if(s===void 0){if(c()){s=f.interrupted();continue}try{switch(a._tag){case`Map`:case`FlatMap`:case`MapError`:case`Recover`:case`RecoverWith`:case`Fold`:i.push(a,o),a=C(a.effect);continue;case`ProvideContext`:o=o.merge(a.context),a=C(a.effect);continue;case`Gen`:{let e=h(a.start),t=e.next(void 0);if(t.done===!0){s=c()?f.interrupted():f.succeed(t.value);continue}i.push({_tag:`GenNext`,iterator:e},o),a=R(t.value);continue}default:{let e=X(a,o,n,r);s=(e instanceof Promise?await e:e)??z();continue}}}catch(e){s=f.die(e);continue}}if(i.length===0)return m(s);let e=i.pop(),t=i.pop();try{switch(t._tag){case`Map`:s._tag===`Success`&&(s=c()?f.interrupted():f.succeed(g(t.f,s.value)));break;case`FlatMap`:s._tag===`Success`&&(c()?s=f.interrupted():(a=C(g(t.f,s.value)),o=e,s=void 0));break;case`MapError`:{let e=O(s);e&&(s=G(s,c())??f.fail(g(t.f,e.value)));break}case`Recover`:O(s)&&(s=G(s,c())??f.succeed(t.fallback));break;case`RecoverWith`:{let n=O(s);if(n){let r=G(s,c());r?s=r:(a=C(g(t.f,n.value)),o=e,s=void 0)}break}case`Fold`:{let e=O(s);e?s=G(s,c())??f.succeed(g(t.onFailure,e.value)):s._tag===`Success`&&(s=c()?f.interrupted():f.succeed(g(t.onSuccess,s.value)));break}case`GenNext`:if(s._tag===`Success`){if(c())s=f.interrupted();else{let n=t.iterator.next(s.value);n.done===!0?s=c()?f.interrupted():f.succeed(n.value):(i.push(t,e),a=R(n.value),o=e,s=void 0)}}}}catch(e){s=f.die(e)}}},J=e=>e.catch(e=>f.die(e)),Y=(e,t)=>J(Promise.resolve().then(()=>t?.aborted?f.interrupted():e())),X=(e,t,n,r)=>{try{switch(e._tag){case`Succeed`:return f.succeed(e.value);case`Fail`:return f.fail(e.error);case`Die`:return f.die(e.defect);case`Sync`:return f.succeed(h(e.thunk));case`Async`:return ee(e.thunk,n);case`Auto`:try{let t=h(e.thunk);return t instanceof Promise?t.then(e=>f.succeed(e),e=>f.fail(e)):f.succeed(t)}catch(e){return f.fail(e)}case`Service`:{let n=t.get(e.tag);return n.isNone()?f.die(P(e.tag)):f.succeed(n.orThrow())}case`Interrupt`:return f.interrupted();case`Sleep`:return se(e.duration,n);case`Bracket`:return Y(()=>te(e,t,n,r),n);case`BracketExit`:return Y(()=>ne(e,t,n,r),n);case`Race`:return e.effects.length===0?f.die(/* @__PURE__ */ Error(`No effects to race`)):Y(()=>ce(e.effects,t,n,r),n);case`Timeout`:return Y(()=>le(e.effect,e.duration,e.fallback,t,n,r),n);case`InterruptWhen`:return Y(()=>re(e,t,n,r),n);case`WithSpan`:return Y(()=>ie(e,t,n,r),n);case`All`:return Y(()=>ue(e.effects,e.concurrency,t,n,r),n);default:return f.die(/* @__PURE__ */ Error(`Unexpected step: ${e._tag}`))}}catch(e){return f.die(e)}},ee=async(e,t)=>{try{return f.succeed(await e(t))}catch(e){return f.fail(e)}},Z=async(e,t,n,r)=>{if(n?.aborted)return f.interrupted();try{return await q(C(e()),t,n,r)}catch(e){return f.die(e)}},te=async(e,t,n,r)=>{try{let i=await q(C(e.acquire),t,void 0,r);if(!i.isSuccess())return i;let a=i.value,o=await Z(()=>g(e.use,a),t,n,r),s=await q(C(g(e.release,a)),t,void 0,r);return s.isSuccess()?o:s}catch(e){return f.die(e)}},ne=async(e,t,n,r)=>{try{let i=await q(C(e.acquire),t,void 0,r);if(!i.isSuccess())return i;let a=i.value,o=await Z(()=>g(e.use,a),t,n,r),s=await q(C(_(e.release,a,o)),t,void 0,r);return s.isSuccess()?o:s}catch(e){return f.die(e)}},re=async(e,t,n,r)=>{let{signal:i}=e,o=a([n,i]);try{let a=await q(C(e.effect),t,o.signal,r);return K(a,i,n?.aborted??!1)}catch(e){return f.die(e)}finally{o.dispose()}},ie=async(e,t,n,r)=>{let i=M(t);if(!i)return q(C(e.effect),t,n,r);let a=i.start(e.name,e.attributes,r),o=await ae(()=>i.run(a,()=>q(C(e.effect),t,n,a)));return i.end(a,oe(o,n)),o},ae=async e=>{try{return await e()}catch(e){return f.die(e)}},oe=(e,t)=>e.isFailure()&&t?.aborted===!0?f.interrupted():e,se=(e,t)=>new Promise(n=>{let r=e===1/0?void 0:setTimeout(()=>{t?.removeEventListener(`abort`,i),n(f.succeed(void 0))},e);function i(){clearTimeout(r),n(f.interrupted())}t?.addEventListener(`abort`,i,{once:!0})}),ce=(e,t,n,r)=>{let i=e.map(()=>{let e=new AbortController;return{own:e,scope:a([n,e.signal])}}),o={settled:!1};return new Promise(n=>{e.forEach((e,a)=>{q(C(e),t,i[a].scope.signal,r).then(e=>{o.settled||(o.settled=!0,i.forEach(({own:e,scope:t},n)=>{n!==a&&e.abort(),t.dispose()}),n(e))})})})},le=(e,t,n,r,i,o)=>{let s=new AbortController,c=a([i,s.signal]);return new Promise(a=>{let l=setTimeout(()=>{s.abort(),c.dispose(),a(n===void 0?f.fail(new v(t)):i?.aborted===!0?f.interrupted():f.succeed(n.value))},t);q(C(e),r,c.signal,o).then(e=>{clearTimeout(l),c.dispose(),a(e)})})},ue=(e,t,n,i,o)=>{if(e.length===0)return Promise.resolve(f.succeed([]));let s=new AbortController,c=a([i,s.signal]),l=Array(e.length),u={next:0,succeeded:0,settled:!1};return new Promise(i=>{let a=e=>{u.settled=!0,e.isSuccess()||s.abort(),c.dispose(),i(e)},d=()=>{if(u.settled||u.next>=e.length)return;let t=u.next;u.next=t+1,q(C(e[t]),n,c.signal,o).then(n=>{u.settled||(n.isSuccess()?(l[t]=n.value,u.succeeded+=1,u.succeeded===e.length?a(f.succeed(l)):d()):a(m(n)))})};Array.from({length:r(t,e.length)}).forEach(d)})},Q={sync:e=>D({_tag:`Sync`,thunk:e}),succeed:e=>D({_tag:`Succeed`,value:e}),fail:e=>D({_tag:`Fail`,error:e}),die:e=>D({_tag:`Die`,defect:e}),async:e=>D(m({_tag:`Async`,thunk:e})),tryPromise:e=>D({_tag:`Async`,thunk:e.try}).mapError(e.catch),tryCatch:(e,r)=>Q.sync(()=>{try{return n(e())}catch(e){return t(r(e))}}).flatMap(e=>Q.fromEither(e)),liftSync:e=>(...t)=>Q.sync(()=>e(...t)),liftPromise:e=>(...t)=>Q.async(()=>e(...t)),fromEither:e=>m(e.isRight()?Q.succeed(e.value):Q.fail(e.value)),fromPromiseEither:(e,t)=>{let n=Q.async(async()=>e());return(t?n.mapError(t):n.recoverWith(e=>Q.die(e))).flatMap(e=>Q.fromEither(e))},fromOption:e=>m(e.isSome()?Q.succeed(e.value):Q.fail(void 0)),fromOptionOrFail:(e,t)=>m(e.isSome()?Q.succeed(e.value):Q.fail(t())),fromTry:e=>m(e.isSuccess()?Q.succeed(e.orThrow()):Q.fail(e.error)),fromResult:e=>m(e.error?Q.fail(e.error):Q.succeed(c(e.data))),tryAsync:(e,t,n)=>n?.aborted?m(Q.fail(t(n.reason??new DOMException(`Aborted`,`AbortError`)))):Q.async(t=>{if(!n)return e(t);if(!t)return e(n);let r=a([n,t]);try{return e(r.signal).finally(r.dispose)}catch(e){throw r.dispose(),e}}).mapError(t),asyncResult:(e,t,n)=>{let r=n?.dataKey??`data`,i=n?.errorKey??`error`;return Q.tryAsync(t=>e(t),t,n?.signal).flatMap(e=>Q.fromResult({data:e[r],error:e[i]}))},service:e=>D({_tag:`Service`,tag:e}),serviceWith:(e,t)=>Q.service(e).map(t),serviceWithIO:(e,t)=>Q.service(e).flatMap(t),withServices:(e,t)=>{let n=Object.entries(e);if(n.length===0)return m(D({_tag:`Auto`,thunk:()=>t({})}));let r=m(Q.succeed({})),i=n.reduce((e,[t,n])=>m(e.flatMap(e=>Q.service(n).map(n=>({...e,[t]:n})))),r);return m(i.flatMap(e=>D({_tag:`Auto`,thunk:()=>t(e)})))},all:(e,t)=>{let n=t?.concurrency??`unbounded`;if(r(n,1),n!==1&&e.length>1)return D(m({_tag:`All`,effects:e,concurrency:n}));if(e.length===0)return m(Q.succeed([]));let i=m(Q.succeed([]));return m(e.reduce((e,t)=>e.flatMap(e=>t.map(t=>[...e,t])),i))},firstSuccessOf:e=>e.length===0?m(Q.die(/* @__PURE__ */ Error(`No effects provided`))):e.reduce((e,t)=>e.recoverWith(()=>t)),sleep:e=>D(m({_tag:`Sleep`,duration:e})),iterate:(e,t,n,r)=>{let i=r?.max??1e4,a=(e,r)=>n(e)?m(Q.succeed(e)):r<=0?m(Q.fail(new x(i,e))):t(e).flatMap(e=>a(e,r-1));return a(e,i)},never:()=>D(m({_tag:`Sleep`,duration:1/0})),get unit(){return m(D({_tag:`Succeed`,value:void 0}))},fromNullable:e=>m(e==null?Q.fail(void 0):Q.succeed(e)),interrupt:()=>D({_tag:`Interrupt`}),bracket:(e,t,n)=>D({_tag:`Bracket`,acquire:e,use:t,release:n}),acquireRelease:(e,t,n)=>Q.bracket(e,t,n),bracketExit:(e,t,n)=>D({_tag:`BracketExit`,acquire:e,use:t,release:n}),race:e=>D({_tag:`Race`,effects:e}),forEach:(e,t,n)=>{let i=n?.concurrency??1;if(r(i,1),i!==1)return Q.unit.flatMap(()=>Q.all(e.map(t),{concurrency:i}));if(e.length===0)return m(Q.succeed([]));let a=m(Q.succeed([]));return m(e.reduce((e,n)=>e.flatMap(e=>t(n).map(t=>[...e,t])),a))},timeout:(e,t)=>D(m({_tag:`Timeout`,effect:e,duration:t})),gen:e=>D(m({_tag:`Gen`,start:e})),get Do(){return $(Q.succeed({}))}},$=e=>({effect:e,bind(t,n){let r=e.flatMap(e=>n(e).map(n=>({...e,[t]:n})));return $(r)},let(t,n){let r=e.map(e=>({...e,[t]:n(e)}));return $(r)},map(t){return e.map(t)},flatMap(t){return e.flatMap(t)},tap(t){return $(e.tap(t))},tapEffect(t){return $(e.tapEffect(t))},done(){return e}}),de=e(e=>D(m({_tag:`Auto`,thunk:e})),Q);export{de as IO,S as IOEffectKey,y as InterruptedError,x as RepeatExhausted,v as TimeoutError,b as UnsupportedSyncOperationError};
|
|
1
|
+
import{Companion as e}from"../companion/Companion.js";import{Left as t,Right as n}from"../either/index.js";import{workerCount as r}from"../internal/concurrency.js";import{define as i}from"../internal/define.js";import{anySignal as a}from"../internal/signal.js";import{safeStringify as o}from"../internal/stringify.js";import{None as s,Option as c,Some as l}from"../option/index.js";import{Try as u}from"../try/index.js";import{Context as d}from"./Context.js";import{Exit as f}from"./Exit.js";import{SpanTracer as p}from"./SpanTracer.js";const m=e=>e,h=e=>e(),g=(e,t)=>e(t),_=(e,t,n)=>e(t,n);var v=class extends Error{constructor(e,t){super(t??`Effect timed out after ${e}ms`),this.duration=e,this._tag=`TimeoutError`,this.name=`TimeoutError`}},y=class extends Error{constructor(e){super(e??`Effect was interrupted`),this._tag=`InterruptedError`,this.name=`InterruptedError`}static is(e){return typeof e==`object`&&!!e&&`_tag`in e&&e._tag===`InterruptedError`}},b=class extends Error{constructor(e){super(`Cannot run ${e} effect synchronously — use run()/runExit() instead`),this.operation=e,this._tag=`UnsupportedSyncOperationError`,this.name=`UnsupportedSyncOperationError`}},x=class extends Error{constructor(e,t,n){super(n??`Repeat exhausted after ${e} iterations`),this.max=e,this.lastValue=t,this._tag=`RepeatExhausted`,this.name=`RepeatExhausted`}static is(e){return typeof e==`object`&&!!e&&`_tag`in e&&e._tag===`RepeatExhausted`}};const S=`effect`,C=e=>e[S],w=e=>{let t=!1;return{next:n=>t?{done:!0,value:n}:(t=!0,{done:!1,value:e})}},T=e=>m(e),E=i()(`IO`,{[Symbol.toStringTag]:`IO`,map(e){return D(m({_tag:`Map`,effect:this,f:e}))},flatMap(e){return D(m({_tag:`FlatMap`,effect:this,f:e}))},mapTry(e,t){return this.flatMap(n=>Q.tryCatch(()=>e(n),t))},tap(e){return this.map(t=>(e(t),t))},tapEffect(e){return this.flatMap(t=>e(t).map(()=>t))},mapError(e){return D(m({_tag:`MapError`,effect:this,f:e}))},tapError(e){return this.mapError(t=>(e(t),t))},recover(e){return D(m({_tag:`Recover`,effect:this,fallback:e}))},recoverWith(e){return D(m({_tag:`RecoverWith`,effect:this,f:e}))},fold(e,t){return D(m({_tag:`Fold`,effect:this,onFailure:e,onSuccess:t}))},match(e){return this.fold(e.failure,e.success)},catchTag(e,t){return D(m({_tag:`RecoverWith`,effect:this,f:n=>typeof n==`object`&&n&&`_tag`in n&&n._tag===e?m(t(m(n))):m(Q.fail(n))}))},catchAll(e){return this.recoverWith(e)},retry(e){return e<=0?this:this.recoverWith(()=>this.retry(e-1))},retryWithDelay(e,t){return e<=0?this:this.recoverWith(()=>Q.sleep(t).flatMap(()=>this.retryWithDelay(e-1,t)))},retryWhile(e){let t=(n,r)=>this.recoverWith(i=>{if(n<=0||!e.while(i,r))return m(Q.fail(i));let a=t(n-1,r+1);return e.delayMs===void 0?a:m(Q.sleep(e.delayMs).flatMap(()=>a))});return t(e.n,1)},retryWithBackoff(e){let t=e.factor??2,n=e.maxMs??3e4,r=e.jitter??!0,i=e.while??(()=>!0),a=(o,s)=>this.recoverWith(c=>{if(o<=0||!i(c,s))return m(Q.fail(c));let l=Math.min(n,e.baseMs*t**(s-1)),u=r?l*(.5+Math.random()*.5):l,d=a(o-1,s+1);return m(Q.sleep(u).flatMap(()=>d))});return a(e.n,1)},repeatUntil(e,t){if(t.max<=0)return m(Q.fail(new x(t.max)));let n=r=>this.flatMap(i=>{if(e(i))return m(Q.succeed(i));if(r<=1)return m(Q.fail(new x(t.max,i)));let a=n(r-1);return t.delayMs===void 0?a:m(Q.sleep(t.delayMs).flatMap(()=>a))});return n(t.max)},repeatWhile(e,t){return this.repeatUntil(t=>!e(t),t)},zipRight(e){return this.flatMap(()=>e)},zipLeft(e){return this.flatMap(t=>e.map(()=>t))},zip(e){return this.flatMap(t=>e.map(e=>[t,e]))},flatten(){return this.flatMap(e=>e)},provideContext(e){return D(m({_tag:`ProvideContext`,effect:this,context:e}))},provideService(e,t){let n=d.make(e,t);return D(m({_tag:`ProvideContext`,effect:this,context:n}))},provideLayer(e){let t=m(Q.async(async()=>{let t=d.empty();return await e.build(m(t))}));return m(t.flatMap(e=>D(m({_tag:`ProvideContext`,effect:this,context:e}))))},async run(){return m(F(await q(C(T(this)),A,void 0,void 0)))},async runOrThrow(){return m(I(await q(C(T(this)),A,void 0,void 0)))},runSync(){return m(F(B(C(T(this)),A,void 0)))},runSyncOrThrow(){return m(I(B(C(T(this)),A,void 0)))},async runExit(e){let t=e?.signal;if(!t)return m(await q(C(T(this)),A,void 0,void 0));let n=await q(C(T(this)),A,t,void 0);return m(t.aborted&&n.isFailure()?f.interrupted():n)},async runOption(){let e=await q(C(T(this)),A,void 0,void 0);return m(e.isSuccess()?l(e.value):s())},async runTry(){let e=await q(C(T(this)),A,void 0,void 0);if(e.isSuccess())return m(u(()=>e.value));let t=O(e),n=t?t.value:/* @__PURE__ */ Error(`Effect was interrupted`);return m(u(()=>{throw n}))},runCancellable(){let e=new AbortController;return m({result:T(this).interruptOn(e.signal).run(),cancel:()=>e.abort()})},pipe(e){return e(this)},delay(e){return Q.sleep(e).flatMap(()=>this)},timeout(e){return D(m({_tag:`Timeout`,effect:this,duration:e}))},timeoutTo(e,t){return D(m({_tag:`Timeout`,effect:this,duration:e,fallback:{value:t}}))},interruptOn(e){return D(m({_tag:`InterruptWhen`,effect:this,signal:e}))},withSpan(e,t=j){return D(m({_tag:`WithSpan`,effect:this,name:e,attributes:t}))},toString(){return`IO(${o(this[S]._tag)})`},toJSON(){return{_tag:`IO`,effect:this[S]._tag}},[Symbol.iterator](){return w(this)}}),D=e=>{let t=Object.create(E);return t[S]=e,t},O=e=>{if(e._tag===`Failure`)return{value:e.error};if(e._tag===`Die`)return{value:e.defect}},k=e=>e._tag===`Die`&&e.defect instanceof b?void 0:O(e),A=d.empty(),j=Object.freeze({}),M=e=>{let t=e.get(p);return t.isNone()?void 0:t.orThrow()},N=()=>/* @__PURE__ */ Error(`Cannot run async effect synchronously`),P=e=>/* @__PURE__ */ Error(`Service not found: ${e.id}`),F=e=>{if(e._tag===`Success`)return n(e.value);if(e._tag===`Failure`)return t(e.error);throw e._tag===`Die`?e.defect:new y},I=e=>{if(e._tag===`Success`)return e.value;throw e._tag===`Failure`?e.error:e._tag===`Die`?e.defect:new y},L=e=>{try{return e()}catch(e){return f.die(e)}},R=e=>{let t=typeof e==`object`&&e?e[S]:void 0;if(typeof t==`object`&&t&&typeof t._tag==`string`)return m(t);throw TypeError("IO.gen was yielded a value that isn't an IO. Use `yield*` on an IO; convert an Option, Either or Try first with IO.fromOption, IO.fromEither or IO.fromTry, and wrap a plain value with IO.succeed.")},z=()=>f.die(/* @__PURE__ */ TypeError(`A step produced no outcome: a SpanTracer's run must return what its fn returns`)),B=(e,t,n)=>{let r=[],i=m(e),a=m(t),o;for(;;){if(o===void 0)try{switch(i._tag){case`Map`:case`FlatMap`:case`MapError`:case`Recover`:case`RecoverWith`:case`Fold`:r.push(i,a),i=C(i.effect);continue;case`ProvideContext`:a=a.merge(i.context),i=C(i.effect);continue;case`Gen`:{let e=h(i.start),t=e.next(void 0);if(t.done===!0){o=f.succeed(t.value);continue}r.push({_tag:`GenNext`,iterator:e},a),i=R(t.value);continue}default:o=V(i,a,n)??z();continue}}catch(e){o=f.die(e);continue}if(r.length===0)return m(o);let e=r.pop(),t=r.pop();try{switch(t._tag){case`Map`:o._tag===`Success`&&(o=f.succeed(g(t.f,o.value)));break;case`FlatMap`:o._tag===`Success`&&(i=C(g(t.f,o.value)),a=e,o=void 0);break;case`MapError`:{let e=k(o);e&&(o=f.fail(g(t.f,e.value)));break}case`Recover`:k(o)&&(o=f.succeed(t.fallback));break;case`RecoverWith`:{let n=k(o);n&&(i=C(g(t.f,n.value)),a=e,o=void 0);break}case`Fold`:{let e=k(o);e?o=f.succeed(g(t.onFailure,e.value)):o._tag===`Success`&&(o=f.succeed(g(t.onSuccess,o.value)));break}case`GenNext`:if(o._tag===`Success`){let n=t.iterator.next(o.value);n.done===!0?o=f.succeed(n.value):(r.push(t,e),i=R(n.value),a=e,o=void 0)}}}catch(e){o=f.die(e)}}},V=(e,t,n)=>{try{switch(e._tag){case`Succeed`:return f.succeed(e.value);case`Fail`:return f.fail(e.error);case`Die`:return f.die(e.defect);case`Sync`:return f.succeed(h(e.thunk));case`Async`:return f.die(N());case`Auto`:return H(e.thunk);case`Service`:{let n=t.get(e.tag);return n.isNone()?f.die(P(e.tag)):f.succeed(n.orThrow())}case`Interrupt`:return f.interrupted();case`Bracket`:{let r=B(C(e.acquire),t,n);if(!r.isSuccess())return r;let i=r.value,a=L(()=>B(C(g(e.use,i)),t,n)),o=B(C(g(e.release,i)),t,n);return o.isSuccess()?a:o}case`BracketExit`:{let r=B(C(e.acquire),t,n);if(!r.isSuccess())return r;let i=r.value,a=L(()=>B(C(g(e.use,i)),t,n)),o=B(C(_(e.release,i,a)),t,n);return o.isSuccess()?a:o}case`All`:return W(e.effects,t,n);case`Race`:return f.die(new b(`race`));case`Timeout`:return f.die(new b(`timeout`));case`Sleep`:return f.die(new b(`sleep`));case`WithSpan`:return U(e,t,n);case`InterruptWhen`:{if(e.signal.aborted)return f.fail(new y);let r=B(C(e.effect),t,n);return r.isInterrupted()?f.fail(new y):r}default:return f.die(/* @__PURE__ */ Error(`Unexpected step: ${e._tag}`))}}catch(e){return f.die(e)}},H=e=>{try{let t=e();return t instanceof Promise?f.die(N()):f.succeed(t)}catch(e){return f.fail(e)}},U=(e,t,n)=>{let r=M(t);if(!r)return B(C(e.effect),t,n);let i=r.start(e.name,e.attributes,n),a=L(()=>r.run(i,()=>B(C(e.effect),t,i)));return r.end(i,a),a},W=(e,t,n)=>{let r=[];for(let i of e){let e=B(C(i),t,n);if(!e.isSuccess())return m(e);r.push(e.value)}return f.succeed(r)},G=(e,t)=>{if(t)return e.isDie()?m(e):f.interrupted()},K=(e,t,n)=>e.isSuccess()||e.isDie()?e:n?f.interrupted():e.isInterrupted()||t.aborted?f.fail(new y):e,q=async(e,t,n,r)=>{let i=[],a=m(e),o=m(t),s,c=()=>n?.aborted??!1;for(;;){if(s===void 0){if(c()){s=f.interrupted();continue}try{switch(a._tag){case`Map`:case`FlatMap`:case`MapError`:case`Recover`:case`RecoverWith`:case`Fold`:i.push(a,o),a=C(a.effect);continue;case`ProvideContext`:o=o.merge(a.context),a=C(a.effect);continue;case`Gen`:{let e=h(a.start),t=e.next(void 0);if(t.done===!0){s=c()?f.interrupted():f.succeed(t.value);continue}i.push({_tag:`GenNext`,iterator:e},o),a=R(t.value);continue}default:{let e=X(a,o,n,r);s=(e instanceof Promise?await e:e)??z();continue}}}catch(e){s=f.die(e);continue}}if(i.length===0)return m(s);let e=i.pop(),t=i.pop();try{switch(t._tag){case`Map`:s._tag===`Success`&&(s=c()?f.interrupted():f.succeed(g(t.f,s.value)));break;case`FlatMap`:s._tag===`Success`&&(c()?s=f.interrupted():(a=C(g(t.f,s.value)),o=e,s=void 0));break;case`MapError`:{let e=O(s);e&&(s=G(s,c())??f.fail(g(t.f,e.value)));break}case`Recover`:O(s)&&(s=G(s,c())??f.succeed(t.fallback));break;case`RecoverWith`:{let n=O(s);if(n){let r=G(s,c());r?s=r:(a=C(g(t.f,n.value)),o=e,s=void 0)}break}case`Fold`:{let e=O(s);e?s=G(s,c())??f.succeed(g(t.onFailure,e.value)):s._tag===`Success`&&(s=c()?f.interrupted():f.succeed(g(t.onSuccess,s.value)));break}case`GenNext`:if(s._tag===`Success`){if(c())s=f.interrupted();else{let n=t.iterator.next(s.value);n.done===!0?s=c()?f.interrupted():f.succeed(n.value):(i.push(t,e),a=R(n.value),o=e,s=void 0)}}}}catch(e){s=f.die(e)}}},J=e=>e.catch(e=>f.die(e)),Y=(e,t)=>J(Promise.resolve().then(()=>t?.aborted?f.interrupted():e())),X=(e,t,n,r)=>{try{switch(e._tag){case`Succeed`:return f.succeed(e.value);case`Fail`:return f.fail(e.error);case`Die`:return f.die(e.defect);case`Sync`:return f.succeed(h(e.thunk));case`Async`:return ee(e.thunk,n);case`Auto`:try{let t=h(e.thunk);return t instanceof Promise?t.then(e=>f.succeed(e),e=>f.fail(e)):f.succeed(t)}catch(e){return f.fail(e)}case`Service`:{let n=t.get(e.tag);return n.isNone()?f.die(P(e.tag)):f.succeed(n.orThrow())}case`Interrupt`:return f.interrupted();case`Sleep`:return se(e.duration,n);case`Bracket`:return Y(()=>te(e,t,n,r),n);case`BracketExit`:return Y(()=>ne(e,t,n,r),n);case`Race`:return e.effects.length===0?f.die(/* @__PURE__ */ Error(`No effects to race`)):Y(()=>ce(e.effects,t,n,r),n);case`Timeout`:return Y(()=>le(e.effect,e.duration,e.fallback,t,n,r),n);case`InterruptWhen`:return Y(()=>re(e,t,n,r),n);case`WithSpan`:return Y(()=>ie(e,t,n,r),n);case`All`:return Y(()=>ue(e.effects,e.concurrency,t,n,r),n);default:return f.die(/* @__PURE__ */ Error(`Unexpected step: ${e._tag}`))}}catch(e){return f.die(e)}},ee=async(e,t)=>{try{return f.succeed(await e(t))}catch(e){return f.fail(e)}},Z=async(e,t,n,r)=>{if(n?.aborted)return f.interrupted();try{return await q(C(e()),t,n,r)}catch(e){return f.die(e)}},te=async(e,t,n,r)=>{try{let i=await q(C(e.acquire),t,void 0,r);if(!i.isSuccess())return i;let a=i.value,o=await Z(()=>g(e.use,a),t,n,r),s=await q(C(g(e.release,a)),t,void 0,r);return s.isSuccess()?o:s}catch(e){return f.die(e)}},ne=async(e,t,n,r)=>{try{let i=await q(C(e.acquire),t,void 0,r);if(!i.isSuccess())return i;let a=i.value,o=await Z(()=>g(e.use,a),t,n,r),s=await q(C(_(e.release,a,o)),t,void 0,r);return s.isSuccess()?o:s}catch(e){return f.die(e)}},re=async(e,t,n,r)=>{let{signal:i}=e,o=a([n,i]);try{let a=await q(C(e.effect),t,o.signal,r);return K(a,i,n?.aborted??!1)}catch(e){return f.die(e)}finally{o.dispose()}},ie=async(e,t,n,r)=>{let i=M(t);if(!i)return q(C(e.effect),t,n,r);let a=i.start(e.name,e.attributes,r),o=await ae(()=>i.run(a,()=>q(C(e.effect),t,n,a)));return i.end(a,oe(o,n)),o},ae=async e=>{try{return await e()}catch(e){return f.die(e)}},oe=(e,t)=>e.isFailure()&&t?.aborted===!0?f.interrupted():e,se=(e,t)=>new Promise(n=>{let r=e===1/0?void 0:setTimeout(()=>{t?.removeEventListener(`abort`,i),n(f.succeed(void 0))},e);function i(){clearTimeout(r),n(f.interrupted())}t?.addEventListener(`abort`,i,{once:!0})}),ce=(e,t,n,r)=>{let i=e.map(()=>{let e=new AbortController;return{own:e,scope:a([n,e.signal])}}),o={settled:!1};return new Promise(n=>{e.forEach((e,a)=>{q(C(e),t,i[a].scope.signal,r).then(e=>{o.settled||(o.settled=!0,i.forEach(({own:e,scope:t},n)=>{n!==a&&e.abort(),t.dispose()}),n(e))})})})},le=(e,t,n,r,i,o)=>{let s=new AbortController,c=a([i,s.signal]);return new Promise(a=>{let l=setTimeout(()=>{s.abort(),c.dispose(),a(n===void 0?f.fail(new v(t)):i?.aborted===!0?f.interrupted():f.succeed(n.value))},t);q(C(e),r,c.signal,o).then(e=>{clearTimeout(l),c.dispose(),a(e)})})},ue=(e,t,n,i,o)=>{if(e.length===0)return Promise.resolve(f.succeed([]));let s=new AbortController,c=a([i,s.signal]),l=Array(e.length),u={next:0,succeeded:0,settled:!1};return new Promise(i=>{let a=e=>{u.settled=!0,e.isSuccess()||s.abort(),c.dispose(),i(e)},d=()=>{if(u.settled||u.next>=e.length)return;let t=u.next;u.next=t+1,q(C(e[t]),n,c.signal,o).then(n=>{u.settled||(n.isSuccess()?(l[t]=n.value,u.succeeded+=1,u.succeeded===e.length?a(f.succeed(l)):d()):a(m(n)))})};Array.from({length:r(t,e.length)}).forEach(d)})},Q={sync:e=>D({_tag:`Sync`,thunk:e}),succeed:e=>D({_tag:`Succeed`,value:e}),fail:e=>D({_tag:`Fail`,error:e}),die:e=>D({_tag:`Die`,defect:e}),async:e=>D(m({_tag:`Async`,thunk:e})),tryPromise:e=>D({_tag:`Async`,thunk:e.try}).mapError(e.catch),tryCatch:(e,r)=>Q.sync(()=>{try{return n(e())}catch(e){return t(r(e))}}).flatMap(e=>Q.fromEither(e)),liftSync:e=>(...t)=>Q.sync(()=>e(...t)),liftPromise:e=>(...t)=>Q.async(()=>e(...t)),fromEither:e=>m(e.isRight()?Q.succeed(e.value):Q.fail(e.value)),fromPromiseEither:(e,t)=>{let n=Q.async(async()=>e());return(t?n.mapError(t):n.recoverWith(e=>Q.die(e))).flatMap(e=>Q.fromEither(e))},fromOption:e=>m(e.isSome()?Q.succeed(e.value):Q.fail(void 0)),fromOptionOrFail:(e,t)=>m(e.isSome()?Q.succeed(e.value):Q.fail(t())),fromTry:e=>m(e.isSuccess()?Q.succeed(e.orThrow()):Q.fail(e.error)),fromResult:e=>m(e.error?Q.fail(e.error):Q.succeed(c(e.data))),tryAsync:(e,t,n)=>n?.aborted?m(Q.fail(t(n.reason??new DOMException(`Aborted`,`AbortError`)))):Q.async(t=>{if(!n)return e(t);if(!t)return e(n);let r=a([n,t]);try{return e(r.signal).finally(r.dispose)}catch(e){throw r.dispose(),e}}).mapError(t),asyncResult:(e,t,n)=>{let r=n?.dataKey??`data`,i=n?.errorKey??`error`;return Q.tryAsync(t=>e(t),t,n?.signal).flatMap(e=>Q.fromResult({data:e[r],error:e[i]}))},service:e=>D({_tag:`Service`,tag:e}),serviceWith:(e,t)=>Q.service(e).map(t),serviceWithIO:(e,t)=>Q.service(e).flatMap(t),withServices:(e,t)=>{let n=Object.entries(e);if(n.length===0)return m(D({_tag:`Auto`,thunk:()=>t({})}));let r=m(Q.succeed({})),i=n.reduce((e,[t,n])=>m(e.flatMap(e=>Q.service(n).map(n=>({...e,[t]:n})))),r);return m(i.flatMap(e=>D({_tag:`Auto`,thunk:()=>t(e)})))},all:(e,t)=>{let n=t?.concurrency??`unbounded`;if(r(n,1),n!==1&&e.length>1)return D(m({_tag:`All`,effects:e,concurrency:n}));if(e.length===0)return m(Q.succeed([]));let i=m(Q.succeed([]));return m(e.reduce((e,t)=>e.flatMap(e=>t.map(t=>[...e,t])),i))},firstSuccessOf:e=>e.length===0?m(Q.die(/* @__PURE__ */ Error(`No effects provided`))):e.reduce((e,t)=>e.recoverWith(()=>t)),sleep:e=>D(m({_tag:`Sleep`,duration:e})),iterate:(e,t,n,r)=>{let i=r?.max??1e4,a=(e,r)=>n(e)?m(Q.succeed(e)):r<=0?m(Q.fail(new x(i,e))):t(e).flatMap(e=>a(e,r-1));return a(e,i)},never:()=>D(m({_tag:`Sleep`,duration:1/0})),get unit(){return m(D({_tag:`Succeed`,value:void 0}))},fromNullable:e=>m(e==null?Q.fail(void 0):Q.succeed(e)),interrupt:()=>D({_tag:`Interrupt`}),bracket:(e,t,n)=>D({_tag:`Bracket`,acquire:e,use:t,release:n}),acquireRelease:(e,t,n)=>Q.bracket(e,t,n),bracketExit:(e,t,n)=>D({_tag:`BracketExit`,acquire:e,use:t,release:n}),race:e=>D({_tag:`Race`,effects:e}),forEach:(e,t,n)=>{let i=n?.concurrency??1;if(r(i,1),i!==1)return Q.unit.flatMap(()=>Q.all(e.map(t),{concurrency:i}));if(e.length===0)return m(Q.succeed([]));let a=m(Q.succeed([]));return m(e.reduce((e,n)=>e.flatMap(e=>t(n).map(t=>[...e,t])),a))},timeout:(e,t)=>D(m({_tag:`Timeout`,effect:e,duration:t})),gen:e=>D(m({_tag:`Gen`,start:e})),get Do(){return $(Q.succeed({}))}},$=e=>({effect:e,bind(t,n){let r=e.flatMap(e=>n(e).map(n=>({...e,[t]:n})));return $(r)},let(t,n){let r=e.map(e=>({...e,[t]:n(e)}));return $(r)},map(t){return e.map(t)},flatMap(t){return e.flatMap(t)},tap(t){return $(e.tap(t))},tapEffect(t){return $(e.tapEffect(t))},done(){return e}}),de=e(e=>D(m({_tag:`Auto`,thunk:e})),Q);export{de as IO,S as IOEffectKey,y as InterruptedError,x as RepeatExhausted,v as TimeoutError,b as UnsupportedSyncOperationError};
|
package/dist/list/index.d.ts
CHANGED
|
@@ -97,10 +97,10 @@ export interface List<out A> extends FunctypeCollection<A, "List">, Doable<A>, R
|
|
|
97
97
|
* @param patterns - Object with handler functions for Empty and NonEmpty variants
|
|
98
98
|
* @returns The result of applying the matching handler function
|
|
99
99
|
*/
|
|
100
|
-
match<R>(patterns: {
|
|
101
|
-
Empty: () => R
|
|
102
|
-
NonEmpty: (values: A[]) => R
|
|
103
|
-
}): R;
|
|
100
|
+
match<R, S = R>(patterns: {
|
|
101
|
+
Empty: () => R | NoInfer<S>;
|
|
102
|
+
NonEmpty: (values: A[]) => S | NoInfer<R>;
|
|
103
|
+
}): R | S;
|
|
104
104
|
}
|
|
105
105
|
declare const ListConstructor: <A>(values?: Iterable<A>) => List<A>;
|
|
106
106
|
declare const ListStatics: {
|
package/dist/map/index.d.ts
CHANGED
|
@@ -50,10 +50,10 @@ export interface Map<K, out V> extends KVTraversable<Tuple<[K, V]>>, Collection<
|
|
|
50
50
|
* @param patterns - Object with handler functions for Empty and NonEmpty variants
|
|
51
51
|
* @returns The result of applying the matching handler function
|
|
52
52
|
*/
|
|
53
|
-
match<R>(patterns: {
|
|
54
|
-
Empty: () => R
|
|
55
|
-
NonEmpty: (entries: Array<Tuple<[K, V]>>) => R
|
|
56
|
-
}): R;
|
|
53
|
+
match<R, S = R>(patterns: {
|
|
54
|
+
Empty: () => R | NoInfer<S>;
|
|
55
|
+
NonEmpty: (entries: Array<Tuple<[K, V]>>) => S | NoInfer<R>;
|
|
56
|
+
}): R | S;
|
|
57
57
|
toValue(): {
|
|
58
58
|
_tag: "Map";
|
|
59
59
|
value: [K, V][];
|
package/dist/obj/Obj.d.ts
CHANGED
|
@@ -135,7 +135,7 @@ export interface Obj<T extends Record<string, Type>> extends FunctypeValue<T, "O
|
|
|
135
135
|
* @param onValue - Handler for non-empty Obj
|
|
136
136
|
* @returns The result of the matching handler
|
|
137
137
|
*/
|
|
138
|
-
fold<U extends Type>(onEmpty: () => U
|
|
138
|
+
fold<U extends Type, V extends Type = U>(onEmpty: () => U | NoInfer<V>, onValue: (value: T) => V | NoInfer<U>): U | V;
|
|
139
139
|
/**
|
|
140
140
|
* Returns a string representation of this Obj
|
|
141
141
|
* @returns A string representation
|
package/dist/option/index.d.ts
CHANGED
|
@@ -109,7 +109,7 @@ export interface OptionBase<out T extends Type> extends Functype<T, "Some" | "No
|
|
|
109
109
|
* @param onSome - Function to apply if the Option has a value
|
|
110
110
|
* @returns The result of applying the appropriate function
|
|
111
111
|
*/
|
|
112
|
-
fold<U>(onNone: () => U
|
|
112
|
+
fold<U, V = U>(onNone: () => U | NoInfer<V>, onSome: (value: T) => V | NoInfer<U>): U | V;
|
|
113
113
|
/**
|
|
114
114
|
* Async variant of fold. Accepts sync or async handlers on either branch and
|
|
115
115
|
* always returns a Promise.
|
|
@@ -196,10 +196,10 @@ export interface OptionBase<out T extends Type> extends Functype<T, "Some" | "No
|
|
|
196
196
|
* @param patterns - Object with handler functions for Some and None variants
|
|
197
197
|
* @returns The result of applying the matching handler function
|
|
198
198
|
*/
|
|
199
|
-
match<R>(patterns: {
|
|
200
|
-
Some: (value: T) => R
|
|
201
|
-
None: () => R
|
|
202
|
-
}): R;
|
|
199
|
+
match<R, S = R>(patterns: {
|
|
200
|
+
Some: (value: T) => R | NoInfer<S>;
|
|
201
|
+
None: () => S | NoInfer<R>;
|
|
202
|
+
}): R | S;
|
|
203
203
|
}
|
|
204
204
|
/** An Option holding a value. Discriminated by `_tag: "Some"`. */
|
|
205
205
|
export interface SomeOf<out T extends Type> extends OptionBase<T> {
|
package/dist/package.json.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=`2.
|
|
1
|
+
var e=`2.4.0`;export{e as version};
|
package/dist/stack/Stack.d.ts
CHANGED
|
@@ -78,10 +78,10 @@ export type Stack<A extends Type> = {
|
|
|
78
78
|
* @param patterns - Object with handler functions for Empty and NonEmpty variants
|
|
79
79
|
* @returns The result of applying the matching handler function
|
|
80
80
|
*/
|
|
81
|
-
match<R>(patterns: {
|
|
82
|
-
Empty: () => R
|
|
83
|
-
NonEmpty: (values: A[]) => R
|
|
84
|
-
}): R;
|
|
81
|
+
match<R, S = R>(patterns: {
|
|
82
|
+
Empty: () => R | NoInfer<S>;
|
|
83
|
+
NonEmpty: (values: A[]) => S | NoInfer<R>;
|
|
84
|
+
}): R | S;
|
|
85
85
|
} & Traversable<A> & Valuable<"Stack", A[]> & Serializable<A> & Pipe<A[]> & Foldable<A> & Matchable<A[], "Empty" | "NonEmpty">;
|
|
86
86
|
/** Copies `values`, so a later change to the caller's array can't reach the Stack. */
|
|
87
87
|
declare const StackConstructor: <A extends Type>(values?: readonly A[]) => Stack<A>;
|
|
@@ -28,7 +28,7 @@ export type TracedOption<A> = {
|
|
|
28
28
|
map<B>(f: (a: A) => B, label?: string): TracedOption<B>;
|
|
29
29
|
flatMap<B>(f: (a: A) => Option<B>, label?: string): TracedOption<B>;
|
|
30
30
|
filter(predicate: (a: A) => boolean, label?: string): TracedOption<A>;
|
|
31
|
-
fold<B>(onNone: () => B
|
|
31
|
+
fold<B, C = B>(onNone: () => B | NoInfer<C>, onSome: (a: A) => C | NoInfer<B>, label?: string): B | C;
|
|
32
32
|
getOrElse<B = never>(defaultValue: () => A | B, label?: string): A | B;
|
|
33
33
|
unwrap(): Option<A>;
|
|
34
34
|
};
|
package/dist/try/index.d.ts
CHANGED
|
@@ -77,7 +77,7 @@ export interface TryBase<out T> extends FunctypeSum<T, TypeNames>, Extractable<T
|
|
|
77
77
|
* @param onSuccess - Function to apply if the Try is Success
|
|
78
78
|
* @returns The result of applying the appropriate function
|
|
79
79
|
*/
|
|
80
|
-
fold<U extends Type>(onFailure: (error: Error) => U
|
|
80
|
+
fold<U extends Type, V extends Type = U>(onFailure: (error: Error) => U | NoInfer<V>, onSuccess: (value: T) => V | NoInfer<U>): U | V;
|
|
81
81
|
/**
|
|
82
82
|
* Async variant of fold. Accepts sync or async handlers on either branch and
|
|
83
83
|
* always returns a Promise.
|
|
@@ -89,10 +89,10 @@ export interface TryBase<out T> extends FunctypeSum<T, TypeNames>, Extractable<T
|
|
|
89
89
|
* @param patterns - Object with handler functions for Success and Failure variants
|
|
90
90
|
* @returns The result of applying the matching handler function
|
|
91
91
|
*/
|
|
92
|
-
match<R>(patterns: {
|
|
93
|
-
Success: (value: T) => R
|
|
94
|
-
Failure: (error: Error) => R
|
|
95
|
-
}): R;
|
|
92
|
+
match<R, S = R>(patterns: {
|
|
93
|
+
Success: (value: T) => R | NoInfer<S>;
|
|
94
|
+
Failure: (error: Error) => S | NoInfer<R>;
|
|
95
|
+
}): R | S;
|
|
96
96
|
/**
|
|
97
97
|
* Recovers from a Failure by applying a function to the error, returning a new Try.
|
|
98
98
|
* The recovery value may be a wider type; the result is `Try<T | U>`, matching
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "functype",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.4.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "A functional programming library for TypeScript, using immutable data structures and type classes",
|
|
6
6
|
"keywords": [
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
"@eslint/compat": "^2.1.1",
|
|
35
35
|
"@eslint/eslintrc": "^3.3.7",
|
|
36
36
|
"@types/node": "~24.19.2",
|
|
37
|
-
"eslint-config-functype": "2.
|
|
37
|
+
"eslint-config-functype": "2.204.0",
|
|
38
38
|
"esbuild": "^0.28.2",
|
|
39
39
|
"eslint-plugin-functional": "^10.0.1",
|
|
40
40
|
"fast-check": "^4.10.3",
|