functype 1.27.2 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +63 -88
- package/dist/_virtual/_rolldown/runtime.js +1 -0
- package/dist/branded/ValidatedBrand.d.ts +122 -0
- package/dist/branded/ValidatedBrand.js +1 -0
- package/dist/branded/index.d.ts +52 -2
- package/dist/cli/data.d.ts +37 -0
- package/dist/cli/data.js +1 -0
- package/dist/cli/exports.d.ts +5 -46
- package/dist/cli/exports.js +1 -1
- package/dist/cli/formatters.js +4 -0
- package/dist/cli/full-interfaces.d.ts +6 -0
- package/dist/cli/full-interfaces.js +1139 -0
- package/dist/cli/index.js +3 -6
- package/dist/cli/interfaces.generated.js +1 -0
- package/dist/collections/index.d.ts +13 -0
- package/dist/companion/Companion.d.ts +23 -0
- package/dist/companion/Companion.js +1 -0
- package/dist/companion/CompanionTypes.d.ts +30 -0
- package/dist/{CompanionTypes-BVqO7Kc2.js → companion/CompanionTypes.js} +1 -1
- package/dist/companion/index.d.ts +2 -1
- package/dist/companion/index.js +1 -1
- package/dist/conditional/Cond.d.ts +147 -0
- package/dist/conditional/Cond.js +1 -0
- package/dist/conditional/Match.d.ts +295 -0
- package/dist/conditional/Match.js +1 -0
- package/dist/conditional/index.d.ts +3 -2
- package/dist/conditional/index.js +1 -1
- package/dist/core/base/Base.d.ts +12 -0
- package/dist/core/base/Base.js +1 -0
- package/dist/core/throwable/Throwable.d.ts +38 -0
- package/dist/core/throwable/Throwable.js +1 -0
- package/dist/decoder/Decoder.d.ts +15 -0
- package/dist/decoder/DecoderCompanion.js +1 -0
- package/dist/decoder/DecoderError.d.ts +56 -0
- package/dist/decoder/DecoderError.js +2 -0
- package/dist/decoder/Encoder.d.ts +15 -0
- package/dist/decoder/index.d.ts +71 -2
- package/dist/decoder/index.js +1 -1
- package/dist/decoder/tagged.js +1 -0
- package/dist/do/index.d.ts +246 -2
- package/dist/do/index.js +1 -1
- package/dist/do/protocol.d.ts +29 -0
- package/dist/either/index.d.ts +279 -2
- package/dist/either/index.js +1 -1
- package/dist/error/ErrorChain.d.ts +60 -0
- package/dist/error/ErrorChain.js +4 -0
- package/dist/error/ErrorFormatter.d.ts +67 -0
- package/dist/error/ErrorFormatter.js +6 -0
- package/dist/error/ParseError.d.ts +6 -0
- package/dist/error/ParseError.js +1 -0
- package/dist/error/typed/TypedError.d.ts +146 -0
- package/dist/error/typed/TypedError.js +1 -0
- package/dist/error/typed/Validation.d.ts +76 -0
- package/dist/error/typed/Validation.js +1 -0
- package/dist/extractable/Extractable.d.ts +62 -0
- package/dist/extractable/Extractable.js +1 -0
- package/dist/fetch/Http.d.ts +32 -0
- package/dist/fetch/Http.js +1 -0
- package/dist/fetch/HttpClient.d.ts +80 -0
- package/dist/fetch/HttpClient.js +1 -0
- package/dist/fetch/HttpError.d.ts +57 -0
- package/dist/fetch/HttpError.js +1 -0
- package/dist/fetch/HttpRequest.d.ts +103 -0
- package/dist/fetch/index.d.ts +5 -2
- package/dist/fetch/index.js +1 -1
- package/dist/foldable/Foldable.d.ts +27 -0
- package/dist/foldable/index.d.ts +55 -0
- package/dist/foldable/index.js +1 -0
- package/dist/functype/Functype.d.ts +76 -0
- package/dist/functype/FunctypeSum.d.ts +39 -0
- package/dist/functype/index.d.ts +4 -2
- package/dist/hkt/index.d.ts +68 -0
- package/dist/hkt/index.js +1 -0
- package/dist/identity/Identity.d.ts +34 -0
- package/dist/identity/Identity.js +1 -0
- package/dist/index.d.ts +74 -8
- package/dist/index.js +1 -1
- package/dist/internal/base64.js +1 -0
- package/dist/internal/call-alone.js +1 -0
- package/dist/internal/concurrency.d.ts +11 -0
- package/dist/internal/concurrency.js +1 -0
- package/dist/internal/define.js +1 -0
- package/dist/internal/mutation-utils.js +1 -0
- package/dist/internal/signal.js +1 -0
- package/dist/internal/stringify.js +1 -0
- package/dist/invariant/index.d.ts +32 -2
- package/dist/io/Context.d.ts +112 -0
- package/dist/io/Context.js +1 -0
- package/dist/io/Exit.d.ts +249 -0
- package/dist/io/Exit.js +1 -0
- package/dist/io/IO.d.ts +1243 -0
- package/dist/io/IO.js +1 -0
- package/dist/io/Layer.d.ts +139 -0
- package/dist/io/Layer.js +1 -0
- package/dist/io/SpanTracer.d.ts +78 -0
- package/dist/io/SpanTracer.js +1 -0
- package/dist/io/Tag.d.ts +75 -0
- package/dist/io/Tag.js +1 -0
- package/dist/io/TestClock.d.ts +133 -0
- package/dist/io/TestClock.js +1 -0
- package/dist/io/index.d.ts +41 -2
- package/dist/io/index.js +1 -1
- package/dist/lazy/Lazy.d.ts +312 -0
- package/dist/lazy/Lazy.js +1 -0
- package/dist/lazy/index.d.ts +2 -2
- package/dist/lazy/index.js +1 -1
- package/dist/list/LazyList.d.ts +182 -0
- package/dist/list/LazyList.js +1 -0
- package/dist/list/index.d.ts +137 -2
- package/dist/list/index.js +1 -1
- package/dist/logger/index.d.ts +24 -2
- package/dist/map/index.d.ts +95 -2
- package/dist/map/index.js +1 -1
- package/dist/map/shim.d.ts +13 -0
- package/dist/map/shim.js +1 -0
- package/dist/matchable/Matchable.d.ts +38 -0
- package/dist/matchable/Matchable.js +1 -0
- package/dist/obj/Obj.d.ts +212 -0
- package/dist/obj/Obj.js +1 -0
- package/dist/obj/index.d.ts +2 -2
- package/dist/obj/index.js +1 -1
- package/dist/option/index.d.ts +304 -2
- package/dist/option/index.js +1 -1
- package/dist/package.json.js +1 -0
- package/dist/pipe/index.d.ts +14 -0
- package/dist/ref/Ref.d.ts +77 -0
- package/dist/ref/Ref.js +1 -0
- package/dist/reshapeable/Reshapeable.d.ts +90 -0
- package/dist/serializable/Serializable.d.ts +39 -0
- package/dist/serialization/Serialization.d.ts +147 -0
- package/dist/serialization/Serialization.js +1 -0
- package/dist/serialization/SerializationCompanion.d.ts +125 -0
- package/dist/serialization/SerializationCompanion.js +1 -0
- package/dist/serialization/error-envelope.d.ts +44 -0
- package/dist/serialization/error-envelope.js +1 -0
- package/dist/serialization/index.d.ts +4 -2
- package/dist/serialization/index.js +1 -1
- package/dist/set/index.d.ts +106 -2
- package/dist/set/index.js +1 -1
- package/dist/stack/Stack.d.ts +120 -0
- package/dist/stack/Stack.js +1 -0
- package/dist/traced/TraceEvent.d.ts +27 -0
- package/dist/traced/TracedOption.d.ts +46 -0
- package/dist/traced/TracedOption.js +1 -0
- package/dist/traced/Tracer.d.ts +26 -0
- package/dist/traversable/KVTraversable.d.ts +14 -0
- package/dist/traversable/Traversable.d.ts +30 -0
- package/dist/try/index.d.ts +238 -2
- package/dist/try/index.js +1 -1
- package/dist/tuple/index.d.ts +92 -2
- package/dist/tuple/index.js +1 -1
- package/dist/typeable/Typeable.d.ts +40 -0
- package/dist/typeable/Typeable.js +1 -0
- package/dist/typeclass/ContainerOps.d.ts +131 -0
- package/dist/typeclass/Functor.d.ts +41 -0
- package/dist/typeclass/Promisable.d.ts +33 -0
- package/dist/typeclass/index.d.ts +4 -1
- package/dist/typeclass/index.js +1 -1
- package/dist/typeclass/variance.d.ts +54 -0
- package/dist/typeclass/variance.js +1 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/util/index.d.ts +1 -3
- package/dist/valuable/Valuable.d.ts +28 -0
- package/dist/valuable/Valuable.js +1 -0
- package/dist/wire/index.d.ts +40 -2
- package/package.json +7 -12
- package/dist/Brand-bfnGXuum.d.ts +0 -54
- package/dist/Companion-DiOMBHDG.js +0 -1
- package/dist/CompanionTypes-Cc90cQ4P.d.ts +0 -58
- package/dist/Invariant-DEan-SxV.d.ts +0 -35
- package/dist/Logger-BmprRS8v.d.ts +0 -27
- package/dist/Tuple-B8KM-H8Y.d.ts +0 -213
- package/dist/Wire-3hvw0Ogg.d.ts +0 -42
- package/dist/core/task/index.d.ts +0 -2
- package/dist/core/task/index.js +0 -1
- package/dist/full-interfaces-BadxJrCt.js +0 -1202
- package/dist/index-CLYh2qZu.d.ts +0 -6649
- package/dist/rolldown-runtime-DK3Fl9T5.js +0 -1
- package/dist/serialization-9_SyrfdG.js +0 -3
- package/dist/src-BQPeS6p2.js +0 -10
- package/dist/typeclass-C61yDVYd.js +0 -1
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { Option } from "../option/index.js";
|
|
2
|
+
import { Tracer } from "./Tracer.js";
|
|
3
|
+
/**
|
|
4
|
+
* A wrapper around `Option<A>` that emits a `TraceEvent` to the
|
|
5
|
+
* injected `Tracer` on every combinator call.
|
|
6
|
+
*
|
|
7
|
+
* Structure-preserving ops return `TracedOption<B>`, carrying the same spanId
|
|
8
|
+
* and incrementing seq. Terminal ops (`fold`, `getOrElse`) emit and return the
|
|
9
|
+
* raw value, exiting the wrapper. `unwrap()` emits a terminal event too, so a
|
|
10
|
+
* span never ends without one.
|
|
11
|
+
*
|
|
12
|
+
* Its methods are shared, so call them on the value: `const { map } = traced` loses `this`.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* ```ts
|
|
16
|
+
* declare const user: Option<{ name: string }>
|
|
17
|
+
* const events: TraceEvent[] = []
|
|
18
|
+
* const tracer = { emit: (e: TraceEvent) => void events.push(e) }
|
|
19
|
+
*
|
|
20
|
+
* TracedOption(user, tracer, "span-1")
|
|
21
|
+
* .map(u => u.name.trim(), "trim")
|
|
22
|
+
* .filter(n => n.length > 0, "non-empty")
|
|
23
|
+
* .getOrElse(() => "anonymous", "fallback")
|
|
24
|
+
* ```
|
|
25
|
+
*/
|
|
26
|
+
export type TracedOption<A> = {
|
|
27
|
+
readonly _tag: "TracedOption";
|
|
28
|
+
map<B>(f: (a: A) => B, label?: string): TracedOption<B>;
|
|
29
|
+
flatMap<B>(f: (a: A) => Option<B>, label?: string): TracedOption<B>;
|
|
30
|
+
filter(predicate: (a: A) => boolean, label?: string): TracedOption<A>;
|
|
31
|
+
fold<B>(onNone: () => B, onSome: (a: A) => B, label?: string): B;
|
|
32
|
+
getOrElse<B = never>(defaultValue: () => A | B, label?: string): A | B;
|
|
33
|
+
unwrap(): Option<A>;
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* Wraps `inner` with tracing. Each combinator emits one `TraceEvent` to `tracer`,
|
|
37
|
+
* then delegates to the real Option implementation.
|
|
38
|
+
*
|
|
39
|
+
* @param inner - The Option to wrap.
|
|
40
|
+
* @param tracer - Receives events. Typically obtained via IO.service(Tracer).
|
|
41
|
+
* @param spanId - Groups all events from one chain. Required: core does not
|
|
42
|
+
* generate ids, so tracing stays deterministic and free of a
|
|
43
|
+
* global `crypto` dependency.
|
|
44
|
+
* @param seq - Starting sequence number. Defaults to 0. Increments on each op.
|
|
45
|
+
*/
|
|
46
|
+
export declare function TracedOption<A>(inner: Option<A>, tracer: Tracer, spanId: string, seq?: number): TracedOption<A>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{define as e}from"../internal/define.js";function t(e){return e._tag}function n(e){return String(e[Symbol.toStringTag])}function r(e,r,i,a,o){let{inner:s,tracer:c,spanId:l,seq:u}=e;return c.emit({spanId:l,seq:u,op:r,tag:n(s),inTag:t(s),...i!==void 0&&{outTag:i},...a!==void 0&&{label:a},...o!==void 0&&{meta:o}}),u+1}const i=e()(`TracedOption`,{map(e,n){let i=this.inner.map(e);return a(i,this.tracer,this.spanId,r(this,`map`,t(i),n))},flatMap(e,n){let i=this.inner.flatMap(e);return a(i,this.tracer,this.spanId,r(this,`flatMap`,t(i),n))},filter(e,n){let i=this.inner.filter(e),o=t(i)!==`None`;return a(i,this.tracer,this.spanId,r(this,`filter`,t(i),n,{kept:o}))},fold(e,t,n){return r(this,`fold`,void 0,n),this.inner.fold(e,t)},getOrElse(e,n){let i=t(this.inner)===`None`;return r(this,`getOrElse`,void 0,n,{usedDefault:i}),this.inner.getOrElse(e)},unwrap(){return r(this,`unwrap`,void 0,void 0),this.inner}});function a(e,t,n,r=0){let a=Object.create(i);return a._tag=`TracedOption`,a.inner=e,a.tracer=t,a.spanId=n,a.seq=r,a}export{a as TracedOption};
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { TraceEvent } from "./TraceEvent.js";
|
|
2
|
+
/**
|
|
3
|
+
* A sink for structured trace events emitted by `TracedOption` chains.
|
|
4
|
+
*
|
|
5
|
+
* Type-only — no runtime, no opinion on output format, no `console`-global
|
|
6
|
+
* dependency. Same rationale as `Logger`: core names the contract, consumers
|
|
7
|
+
* own the implementation. The whole surface is one method, so the common
|
|
8
|
+
* implementations are literals at the call site:
|
|
9
|
+
*
|
|
10
|
+
* ```ts
|
|
11
|
+
* const noop: Tracer = { emit: () => undefined }
|
|
12
|
+
* const collecting = (target: TraceEvent[]): Tracer => ({ emit: (e) => void target.push(e) })
|
|
13
|
+
* const viaLogger = (logger: Logger): Tracer => ({ emit: (e) => logger.debug("trace", e) })
|
|
14
|
+
* ```
|
|
15
|
+
*
|
|
16
|
+
* For dependency injection, declare your own Tag — `Tag` and `Layer` are
|
|
17
|
+
* public from `functype/io`, and core deliberately does not reserve an id:
|
|
18
|
+
*
|
|
19
|
+
* ```ts
|
|
20
|
+
* const Tracer = Tag<Tracer>("app/Tracer")
|
|
21
|
+
* program.provideLayer(Layer.succeed(Tracer, { emit }))
|
|
22
|
+
* ```
|
|
23
|
+
*/
|
|
24
|
+
export interface Tracer {
|
|
25
|
+
emit(event: TraceEvent): void;
|
|
26
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { Type } from "../types/index.js";
|
|
2
|
+
import { Reducible } from "./Traversable.js";
|
|
3
|
+
/**
|
|
4
|
+
* A traversable interface for key-value containers: Traversable without map, flatMap,
|
|
5
|
+
* flatMapAsync and ap, which is `Reducible`.
|
|
6
|
+
*
|
|
7
|
+
* Key-value containers (Map, Obj) cannot satisfy Functor's unconstrained
|
|
8
|
+
* `map<B extends Type>` because their type parameter is constrained
|
|
9
|
+
* (e.g., to Record or Tuple pairs). These containers redefine map/flatMap
|
|
10
|
+
* with their own tighter constraints.
|
|
11
|
+
*
|
|
12
|
+
* @typeParam A - The element type of the traversable
|
|
13
|
+
*/
|
|
14
|
+
export type KVTraversable<A extends Type> = Reducible<A>;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { AsyncMonad } from "../typeclass/Functor.js";
|
|
2
|
+
import { Widen } from "../typeclass/variance.js";
|
|
3
|
+
import { Type } from "../types/index.js";
|
|
4
|
+
/**
|
|
5
|
+
* Traversable typeclass for data structures that can be traversed through.
|
|
6
|
+
*
|
|
7
|
+
* Covariance: A is declared `<out A>`. Query (`contains`) accepts `unknown` —
|
|
8
|
+
* mirroring Scala's `contains(elem: Any)` — so an unrelated-type arg is a
|
|
9
|
+
* sound `false` rather than a type error. Aggregations (`reduce`, `reduceRight`)
|
|
10
|
+
* widen the accumulator via `<B = A>`, matching Scala's `reduce[B >: A]`; when
|
|
11
|
+
* called without an explicit type arg the behavior is identical to the pre-0.59
|
|
12
|
+
* signature, so existing call sites compile unchanged.
|
|
13
|
+
*
|
|
14
|
+
* Implementers that previously overrode these methods with the widened shape
|
|
15
|
+
* (List, Set) can inherit from this base without a per-type override.
|
|
16
|
+
*/
|
|
17
|
+
export interface Traversable<out A extends Type> extends AsyncMonad<A>, Reducible<A> {}
|
|
18
|
+
/**
|
|
19
|
+
* Traversable's members without the monad's: size, membership and reduction. Key-value containers
|
|
20
|
+
* and collections, whose `map` and `flatMap` take tighter shapes, extend this rather than
|
|
21
|
+
* `Omit<Traversable<A>, …>`: a member reached through a mapped type has no declaration, so
|
|
22
|
+
* `@typescript-eslint/unbound-method` can't see it.
|
|
23
|
+
*/
|
|
24
|
+
export interface Reducible<out A extends Type> {
|
|
25
|
+
get size(): number;
|
|
26
|
+
get isEmpty(): boolean;
|
|
27
|
+
contains(value: unknown): boolean;
|
|
28
|
+
reduce<B = A>(op: (b: Widen<A, B>, a: Widen<A, B>) => Widen<A, B>): Widen<A, B>;
|
|
29
|
+
reduceRight<B = A>(op: (b: Widen<A, B>, a: Widen<A, B>) => Widen<A, B>): Widen<A, B>;
|
|
30
|
+
}
|
package/dist/try/index.d.ts
CHANGED
|
@@ -1,2 +1,238 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
1
|
+
import { Doable } from "../do/protocol.js";
|
|
2
|
+
import { Either } from "../either/index.js";
|
|
3
|
+
import { Extractable } from "../extractable/Extractable.js";
|
|
4
|
+
import { FunctypeSum } from "../functype/FunctypeSum.js";
|
|
5
|
+
import { Option } from "../option/index.js";
|
|
6
|
+
import { Pipe } from "../pipe/index.js";
|
|
7
|
+
import { Reshapeable } from "../reshapeable/Reshapeable.js";
|
|
8
|
+
import { SerializedError } from "../serialization/error-envelope.js";
|
|
9
|
+
import { Promisable } from "../typeclass/Promisable.js";
|
|
10
|
+
import { Type } from "../types/index.js";
|
|
11
|
+
/**
|
|
12
|
+
* Possible types of Try instances
|
|
13
|
+
*/
|
|
14
|
+
export type TypeNames = "Success" | "Failure";
|
|
15
|
+
/**
|
|
16
|
+
* What every Try has, Success or Failure. `Try<T>` is the union of `SuccessOf<T>` and `FailureOf<T>`,
|
|
17
|
+
* so TypeScript narrows it on `isSuccess()`, `isFailure()` and `_tag`, as it does Either.
|
|
18
|
+
*/
|
|
19
|
+
export interface TryBase<out T> extends FunctypeSum<T, TypeNames>, Extractable<T>, Pipe<T>, Promisable<T>, Doable<T>, Reshapeable<T> {
|
|
20
|
+
readonly _tag: TypeNames;
|
|
21
|
+
/** The value of a Success; undefined on a Failure */
|
|
22
|
+
readonly value: T | undefined;
|
|
23
|
+
/** The error of a Failure; undefined on a Success */
|
|
24
|
+
readonly error: Error | undefined;
|
|
25
|
+
isSuccess(): this is SuccessOf<T>;
|
|
26
|
+
isFailure(): this is FailureOf<T>;
|
|
27
|
+
/**
|
|
28
|
+
* Returns the value, or calls `defaultValue` on a Failure. The default is lazy: it runs only on
|
|
29
|
+
* a Failure. A default that fits `T` keeps `T`, so a literal union is not widened; a default of
|
|
30
|
+
* another type widens the result to `T | T2`.
|
|
31
|
+
*/
|
|
32
|
+
getOrElse<T2 extends Type = never>(defaultValue: () => T | T2): T | T2;
|
|
33
|
+
/**
|
|
34
|
+
* Returns the value, or throws on a Failure. Pass an `Error` to throw it, or a builder to make one from
|
|
35
|
+
* the failure's error. With no argument, rethrows the original error.
|
|
36
|
+
*/
|
|
37
|
+
orThrow(error?: Error | ((error: Error) => Error)): T;
|
|
38
|
+
/**
|
|
39
|
+
* Returns the success value, or calls the never-returning handler with the Failure's error.
|
|
40
|
+
* Use this when you have a helper like `(msg) => fail(msg, 2)` that terminates the program —
|
|
41
|
+
* the result type is unconditionally `T`, so you avoid the TypeScript narrowing trap where
|
|
42
|
+
* `if (t.isFailure()) fail(...)` fails to narrow `t.value` when `fail` is an arrow function
|
|
43
|
+
* typed as `(...): never`.
|
|
44
|
+
*/
|
|
45
|
+
expect(handler: (error: Error) => never): T;
|
|
46
|
+
/**
|
|
47
|
+
* Returns this Try if it is a Success, otherwise calls `alternative` for another Try.
|
|
48
|
+
* The alternative is lazy: it runs only on a Failure.
|
|
49
|
+
*/
|
|
50
|
+
orElse<T2 extends Type>(alternative: () => Try<T2>): Try<T | T2>;
|
|
51
|
+
orNull(): T | null;
|
|
52
|
+
orUndefined(): T | undefined;
|
|
53
|
+
toOption(): Option<T>;
|
|
54
|
+
/**
|
|
55
|
+
* Converts to a plain readonly array: `[value]` for Success, `[]` for Failure.
|
|
56
|
+
* Symmetric with `Try.toList()` but skips the List wrapper for code that
|
|
57
|
+
* just wants to feed Array.prototype methods or spread into another array.
|
|
58
|
+
*/
|
|
59
|
+
toArray(): readonly T[];
|
|
60
|
+
/**
|
|
61
|
+
* Converts to Either<E, T>. Failure becomes Left(builder(error)) when given a function,
|
|
62
|
+
* or Left(leftValue) when given a value. Success becomes Right(value).
|
|
63
|
+
*
|
|
64
|
+
* Prefer the function form to thread the underlying Error's context into the Left:
|
|
65
|
+
*
|
|
66
|
+
* Try(() => JSON.parse(text)).toEither((e) => `parse failed: ${e.message}`)
|
|
67
|
+
*/
|
|
68
|
+
toEither<E extends Type>(leftOrBuilder: E | ((err: Error) => E)): Either<E, T>;
|
|
69
|
+
toTry(): Try<T>;
|
|
70
|
+
map<U>(f: (value: T) => U): Try<U>;
|
|
71
|
+
ap<U>(ff: Try<(value: T) => U>): Try<U>;
|
|
72
|
+
flatMap<U>(f: (value: T) => Try<U>): Try<U>;
|
|
73
|
+
flatMapAsync<U>(f: (value: T) => Promise<Try<U>>): Promise<Try<U>>;
|
|
74
|
+
/**
|
|
75
|
+
* Pattern matches over the Try, applying onFailure if Failure and onSuccess if Success
|
|
76
|
+
* @param onFailure - Function to apply if the Try is Failure
|
|
77
|
+
* @param onSuccess - Function to apply if the Try is Success
|
|
78
|
+
* @returns The result of applying the appropriate function
|
|
79
|
+
*/
|
|
80
|
+
fold<U extends Type>(onFailure: (error: Error) => U, onSuccess: (value: T) => U): U;
|
|
81
|
+
/**
|
|
82
|
+
* Async variant of fold. Accepts sync or async handlers on either branch and
|
|
83
|
+
* always returns a Promise.
|
|
84
|
+
*/
|
|
85
|
+
foldAsync<U extends Type>(onFailure: (error: Error) => U | Promise<U>, onSuccess: (value: T) => U | Promise<U>): Promise<U>;
|
|
86
|
+
toString(): string;
|
|
87
|
+
/**
|
|
88
|
+
* Pattern matches over the Try, applying a handler function based on the variant
|
|
89
|
+
* @param patterns - Object with handler functions for Success and Failure variants
|
|
90
|
+
* @returns The result of applying the matching handler function
|
|
91
|
+
*/
|
|
92
|
+
match<R>(patterns: {
|
|
93
|
+
Success: (value: T) => R;
|
|
94
|
+
Failure: (error: Error) => R;
|
|
95
|
+
}): R;
|
|
96
|
+
/**
|
|
97
|
+
* Recovers from a Failure by applying a function to the error, returning a new Try.
|
|
98
|
+
* The recovery value may be a wider type; the result is `Try<T | U>`, matching
|
|
99
|
+
* Scala's `recover[U >: T]` shape so Try stays covariant in T.
|
|
100
|
+
*/
|
|
101
|
+
recover<U extends Type>(f: (error: Error) => U): Try<T | U>;
|
|
102
|
+
/**
|
|
103
|
+
* Recovers from a Failure by applying a function that returns a new Try.
|
|
104
|
+
* As with `recover`, the recovery Try may carry a wider type; the result widens accordingly.
|
|
105
|
+
*/
|
|
106
|
+
recoverWith<U extends Type>(f: (error: Error) => Try<U>): Try<T | U>;
|
|
107
|
+
/**
|
|
108
|
+
* Applies a predicate to the success value. If the predicate fails, short-circuits
|
|
109
|
+
* to a Failure with the error produced by `onUnsatisfied`. Failure passes through
|
|
110
|
+
* unchanged (predicate not evaluated). Lets you turn a value-level guard into the
|
|
111
|
+
* error channel without writing a manual `throw` inside a `Try(() => ...)` body.
|
|
112
|
+
* @param predicate - The predicate to test the success value
|
|
113
|
+
* @param onUnsatisfied - Builds the Error for the new Failure when the predicate fails
|
|
114
|
+
* @returns A Success if the predicate holds, a Failure carrying `onUnsatisfied(value)` otherwise
|
|
115
|
+
*/
|
|
116
|
+
filterOrElse(predicate: (value: T) => boolean, onUnsatisfied: (value: T) => Error): Try<T>;
|
|
117
|
+
toValue(): {
|
|
118
|
+
_tag: TypeNames;
|
|
119
|
+
value: T | Error;
|
|
120
|
+
};
|
|
121
|
+
/**
|
|
122
|
+
* Custom JSON serialization. Success emits `{"@functype":"Try","_tag":"Success","value":T}`.
|
|
123
|
+
* Failure emits `{"@functype":"Try","_tag":"Failure","error":SerializedError}` where
|
|
124
|
+
* SerializedError captures `name`, `message`, `stack`, and the full `cause` chain —
|
|
125
|
+
* `e.name` survives round-trip but `instanceof SomeError` does not.
|
|
126
|
+
*/
|
|
127
|
+
toJSON(): {
|
|
128
|
+
"@functype": "Try";
|
|
129
|
+
_tag: "Success";
|
|
130
|
+
value: T;
|
|
131
|
+
} | {
|
|
132
|
+
"@functype": "Try";
|
|
133
|
+
_tag: "Failure";
|
|
134
|
+
error: SerializedError;
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
/** A Try that succeeded. Discriminated by `_tag: "Success"`. */
|
|
138
|
+
export interface SuccessOf<out T> extends TryBase<T> {
|
|
139
|
+
readonly _tag: "Success";
|
|
140
|
+
readonly value: T;
|
|
141
|
+
readonly error: undefined;
|
|
142
|
+
}
|
|
143
|
+
/** A Try that failed. Discriminated by `_tag: "Failure"`. */
|
|
144
|
+
export interface FailureOf<out T> extends TryBase<T> {
|
|
145
|
+
readonly _tag: "Failure";
|
|
146
|
+
readonly value: undefined;
|
|
147
|
+
readonly error: Error;
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* The result of a computation that may throw: a Success or a Failure. TypeScript narrows it across
|
|
151
|
+
* both branches of `isSuccess()` / `isFailure()` and `_tag` checks.
|
|
152
|
+
*/
|
|
153
|
+
export type Try<T> = SuccessOf<T> | FailureOf<T>;
|
|
154
|
+
declare const TryConstructor: <T>(f: () => T) => Try<T>;
|
|
155
|
+
declare const TryStatics: {
|
|
156
|
+
/**
|
|
157
|
+
* Creates a Success directly without needing a callback
|
|
158
|
+
* @param value - The success value
|
|
159
|
+
* @returns Try containing the value as Success
|
|
160
|
+
*/
|
|
161
|
+
success: <T>(value: T) => Try<T>;
|
|
162
|
+
/**
|
|
163
|
+
* Creates a Failure directly without needing to throw
|
|
164
|
+
* @param error - The error (string or Error instance)
|
|
165
|
+
* @returns Try containing the error as Failure
|
|
166
|
+
*/
|
|
167
|
+
failure: <T>(error: Error | string) => Try<T>;
|
|
168
|
+
/**
|
|
169
|
+
* Creates a Try from a Promise, resolving to Success or Failure
|
|
170
|
+
* @param promise - The promise to convert
|
|
171
|
+
* @returns Promise resolving to a Try
|
|
172
|
+
*/
|
|
173
|
+
fromPromise: <T>(promise: Promise<T>) => Promise<Try<T>>;
|
|
174
|
+
/**
|
|
175
|
+
* Creates a Try from a thunk that returns a Promise. The thunk is invoked
|
|
176
|
+
* when async() is called, so the Promise starts executing under the Try
|
|
177
|
+
* wrapper — synchronous throws from the thunk are caught the same way
|
|
178
|
+
* `Try(() => sync)` catches them, and rejections are caught the same way
|
|
179
|
+
* `Try.fromPromise(promise)` catches them.
|
|
180
|
+
*
|
|
181
|
+
* Prefer this over `Try.fromPromise(thunk())` when you want the work to be
|
|
182
|
+
* deferred until wrapping (e.g. composing a chain of Try-returning thunks
|
|
183
|
+
* before any of them runs).
|
|
184
|
+
*
|
|
185
|
+
* @example
|
|
186
|
+
* const result = await Try.async(() => fs.readFile(path, "utf8"))
|
|
187
|
+
* result.fold(err => log(err.message), data => process(data))
|
|
188
|
+
*
|
|
189
|
+
* @param thunk - Function returning a Promise to be wrapped
|
|
190
|
+
* @returns Promise resolving to a Try
|
|
191
|
+
*/
|
|
192
|
+
async: <T>(thunk: () => Promise<T>) => Promise<Try<T>>;
|
|
193
|
+
/**
|
|
194
|
+
* Type guard to check if a Try is Success
|
|
195
|
+
* @param tryValue - The Try to check
|
|
196
|
+
* @returns True if Try is Success
|
|
197
|
+
*/
|
|
198
|
+
isSuccess: <T>(tryValue: Try<T>) => tryValue is SuccessOf<T>;
|
|
199
|
+
/**
|
|
200
|
+
* Type guard to check if a Try is Failure
|
|
201
|
+
* @param tryValue - The Try to check
|
|
202
|
+
* @returns True if Try is Failure
|
|
203
|
+
*/
|
|
204
|
+
isFailure: <T>(tryValue: Try<T>) => tryValue is FailureOf<T>;
|
|
205
|
+
/**
|
|
206
|
+
* Creates a Try from JSON string
|
|
207
|
+
* @param json - The JSON string
|
|
208
|
+
* @returns Try instance
|
|
209
|
+
*/
|
|
210
|
+
fromJSON: <T>(json: string) => Try<T>;
|
|
211
|
+
/**
|
|
212
|
+
* Creates a Try from binary string
|
|
213
|
+
* @param binary - The binary string
|
|
214
|
+
* @returns Try instance
|
|
215
|
+
*/
|
|
216
|
+
fromBinary: <T>(binary: string) => Try<T>;
|
|
217
|
+
/**
|
|
218
|
+
* Combines an array of Trys into a single Try containing an array.
|
|
219
|
+
* Short-circuits on the first Failure, preserving its error.
|
|
220
|
+
* @param tries - Array of Try values
|
|
221
|
+
* @returns Success with array of values, or first Failure
|
|
222
|
+
*/
|
|
223
|
+
sequence: <T>(tries: ReadonlyArray<Try<T>>) => Try<T[]>;
|
|
224
|
+
/**
|
|
225
|
+
* Maps an array through a function returning Try, then sequences the results.
|
|
226
|
+
* Short-circuits on the first Failure.
|
|
227
|
+
* @param arr - Array of values
|
|
228
|
+
* @param f - Function returning Try
|
|
229
|
+
* @returns Success with array of mapped values, or first Failure
|
|
230
|
+
*/
|
|
231
|
+
traverse: <T, U>(arr: ReadonlyArray<T>, f: (value: T, index: number) => Try<U>) => Try<U[]>;
|
|
232
|
+
};
|
|
233
|
+
export declare const Try: TryCompanion;
|
|
234
|
+
/** The type of `Try`: its constructor and its statics, named so that errors and hovers print `TryCompanion`. */
|
|
235
|
+
export interface TryCompanion extends TryConstructorType, TryStaticsType {}
|
|
236
|
+
type TryConstructorType = typeof TryConstructor;
|
|
237
|
+
type TryStaticsType = typeof TryStatics;
|
|
238
|
+
export {};
|
package/dist/try/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Companion as e}from"../companion/Companion.js";import{Left as t,Right as n}from"../either/index.js";import{base64ToUtf8 as r}from"../internal/base64.js";import{define as i}from"../internal/define.js";import{showValue as a}from"../internal/stringify.js";import{List as o}from"../list/index.js";import{Option as s,Some as c}from"../option/index.js";import{createSerializer as l,createTaggedSerializer as u,expectMarker as d}from"../serialization/SerializationCompanion.js";import{deserializeError as f,serializeError as p}from"../serialization/error-envelope.js";const m=e=>e instanceof Error?e:Error(String(e)),h=i()(`Success`,{[Symbol.toStringTag]:`Try`,isSuccess(){return!0},isFailure(){return!1},getOrElse(){return this.value},orThrow(){return this.value},expect(){return this.value},orElse(){return this},orNull(){return this.value},orUndefined(){return this.value},toEither(){return n(this.value)},map(e){return S(()=>e(this.value))},ap(e){return e.map(e=>e(this.value))},flatMap(e){return e(this.value)},async flatMapAsync(e){return e(this.value)},fold(e,t){return t(this.value)},async foldAsync(e,t){return t(this.value)},match(e){return e.Success(this.value)},recover(){return this},recoverWith(){return this},filterOrElse(e,t){try{return e(this.value)?this:v(t(this.value))}catch(e){return v(m(e))}},foldLeft(e){return t=>t(e,this.value)},foldRight(e){return t=>t(this.value,e)},toString(){return`Success(${a(this.value)})`},toPromise(){return Promise.resolve(this.value)},toValue(){return{_tag:`Success`,value:this.value}},toJSON(){return{"@functype":`Try`,_tag:`Success`,value:this.value}},toOption(){return c(this.value)},toList(){return o([this.value])},toArray(){return[this.value]},toTry(){return this},pipe(e){return e(this.value)},serialize(){return l(`Try`,`Success`,this.value)},contains(e){return this.value===e},exists(e){return e(this.value)},every(e){return e(this.value)},forEach(e){e(this.value)},doUnwrap(){return{ok:!0,value:this.value}}}),g=i()(`Failure`,{[Symbol.toStringTag]:`Try`,isSuccess(){return!1},isFailure(){return!0},getOrElse(e){return e()},orThrow(e){throw e===void 0?this.error:typeof e==`function`?e(this.error):e},expect(e){return e(this.error)},orElse(e){return e()},orNull(){return null},orUndefined(){},toEither(e){return t(typeof e==`function`?e(this.error):e)},map(){return v(this.error)},ap(){return v(this.error)},flatMap(){return v(this.error)},flatMapAsync(){return Promise.resolve(v(this.error))},fold(e){return e(this.error)},async foldAsync(e){return e(this.error)},match(e){return e.Failure(this.error)},recover(e){return S(()=>e(this.error))},recoverWith(e){try{return e(this.error)}catch(e){return v(m(e))}},filterOrElse(){return this},foldLeft(e){return()=>e},foldRight(e){return()=>e},toString(){return`Failure(${a(this.error)})`},toPromise(){return Promise.reject(this.error)},toValue(){return{_tag:`Failure`,value:this.error}},toJSON(){return{"@functype":`Try`,_tag:`Failure`,error:p(this.error)}},toOption(){return s(null)},toList(){return o([])},toArray(){return[]},toTry(){return this},pipe(){throw this.error},serialize(){return u(`Try`,`Failure`,{error:p(this.error)})},contains(){return!1},exists(){return!1},every(){return!0},forEach(){},doUnwrap(){return{ok:!1,empty:!1,error:this.error}}}),_=e=>{let t=Object.create(h);return t._tag=`Success`,t.value=e,t.error=void 0,t},v=e=>{let t=Object.create(g);return t._tag=`Failure`,t.value=void 0,t.error=e,t},y=e=>{try{return _(e())}catch(e){return v(e instanceof Error?e:Error(String(e)))}},b=(e,t)=>{if(d(e,`Try`,t),e._tag===`Success`)return _(e.value);if(e.error!==void 0&&e.error!==null&&typeof e.error==`object`)return v(f(e.error));let n=Error(typeof e.error==`string`?e.error:``);return typeof e.stack==`string`&&e.stack&&(n.stack=e.stack),v(n)},x={success:e=>_(e),failure:e=>v(typeof e==`string`?Error(e):e),fromPromise:e=>e.then(e=>_(e)).catch(e=>v(e instanceof Error?e:Error(String(e)))),async:e=>{try{return e().then(e=>_(e)).catch(e=>v(e instanceof Error?e:Error(String(e))))}catch(e){return Promise.resolve(v(e instanceof Error?e:Error(String(e))))}},isSuccess:e=>e.isSuccess(),isFailure:e=>e.isFailure(),fromJSON:e=>b(JSON.parse(e),`fromJSON`),fromBinary:e=>{let t=r(e);return x.fromJSON(t)},sequence:e=>S(()=>e.map(e=>e.orThrow())),traverse:(e,t)=>S(()=>e.map((e,n)=>t(e,n).orThrow()))},S=e(y,x);export{S as Try};
|
package/dist/tuple/index.d.ts
CHANGED
|
@@ -1,2 +1,92 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
1
|
+
import { Foldable } from "../foldable/Foldable.js";
|
|
2
|
+
import { Pipe } from "../pipe/index.js";
|
|
3
|
+
import { Serializable } from "../serializable/Serializable.js";
|
|
4
|
+
import { Typeable } from "../typeable/Typeable.js";
|
|
5
|
+
import { Type } from "../types/index.js";
|
|
6
|
+
export interface Tuple<out T extends Type[]> extends Foldable<T[number]>, Pipe<Tuple<T>>, Serializable<Tuple<T>>, Typeable<"Tuple"> {
|
|
7
|
+
readonly [Symbol.toStringTag]: string;
|
|
8
|
+
get<K extends number>(index: K): T[K];
|
|
9
|
+
fold<B>(initial: B, fn: (acc: B, a: T[number]) => B): B;
|
|
10
|
+
map<U extends Type[]>(f: (value: T) => U): Tuple<U>;
|
|
11
|
+
flatMap<U extends Type[]>(f: (value: T) => Tuple<U>): Tuple<U>;
|
|
12
|
+
toArray(): T;
|
|
13
|
+
readonly length: number;
|
|
14
|
+
[Symbol.iterator](): Iterator<T[number]>;
|
|
15
|
+
toString(): string;
|
|
16
|
+
toValue(): {
|
|
17
|
+
_tag: "Tuple";
|
|
18
|
+
value: T;
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
declare const TupleConstructor: <T extends Type[]>(values: T) => Tuple<T>;
|
|
22
|
+
declare const TupleStatics: {
|
|
23
|
+
/**
|
|
24
|
+
* Create a Tuple from multiple arguments
|
|
25
|
+
* @example
|
|
26
|
+
* const t = Tuple.of(1, "hello", true)
|
|
27
|
+
* // TypeScript infers: Tuple<[number, string, boolean]>
|
|
28
|
+
*/
|
|
29
|
+
of: <T extends Type[]>(...values: T) => Tuple<T>;
|
|
30
|
+
/**
|
|
31
|
+
* Create a Tuple of size 2 (pair)
|
|
32
|
+
* @example
|
|
33
|
+
* const pair = Tuple.pair("key", 42)
|
|
34
|
+
* // TypeScript infers: Tuple<[string, number]>
|
|
35
|
+
*/
|
|
36
|
+
pair: <A extends Type, B extends Type>(first: A, second: B) => Tuple<[A, B]>;
|
|
37
|
+
/**
|
|
38
|
+
* Create a Tuple of size 3 (triple)
|
|
39
|
+
* @example
|
|
40
|
+
* const triple = Tuple.triple("x", 10, true)
|
|
41
|
+
* // TypeScript infers: Tuple<[string, number, boolean]>
|
|
42
|
+
*/
|
|
43
|
+
triple: <A extends Type, B extends Type, C extends Type>(first: A, second: B, third: C) => Tuple<[A, B, C]>;
|
|
44
|
+
/**
|
|
45
|
+
* Create an empty Tuple
|
|
46
|
+
* @example
|
|
47
|
+
* const empty = Tuple.empty()
|
|
48
|
+
* // TypeScript infers: Tuple<[]>
|
|
49
|
+
*/
|
|
50
|
+
empty: () => Tuple<[]>;
|
|
51
|
+
/**
|
|
52
|
+
* Create a Tuple from an array (alias for constructor)
|
|
53
|
+
* @example
|
|
54
|
+
* const t = Tuple.from([1, 2, 3])
|
|
55
|
+
*/
|
|
56
|
+
from: <T extends Type[]>(values: T) => Tuple<T>;
|
|
57
|
+
/**
|
|
58
|
+
* Reconstruct a Tuple from a JSON envelope emitted by `serialize().toJSON()`
|
|
59
|
+
* or instance `toJSON()`. Verifies `@functype === "Tuple"` if the marker is
|
|
60
|
+
* present (the marker became canonical in 1.2.0; older envelopes are
|
|
61
|
+
* accepted by leniently treating missing-marker as opt-in legacy).
|
|
62
|
+
*/
|
|
63
|
+
fromJSON: <T extends Type[]>(json: string) => Tuple<T>;
|
|
64
|
+
};
|
|
65
|
+
/**
|
|
66
|
+
* Tuple provides a type-safe, fixed-length array with functional operations.
|
|
67
|
+
*
|
|
68
|
+
* @example
|
|
69
|
+
* // Creating tuples
|
|
70
|
+
* const t1 = Tuple([1, "hello", true])
|
|
71
|
+
* const t2 = Tuple.of(1, "hello", true)
|
|
72
|
+
* const pair = Tuple.pair("key", 42)
|
|
73
|
+
*
|
|
74
|
+
* @example
|
|
75
|
+
* // Type-safe access
|
|
76
|
+
* const triple = Tuple.triple("x", 10, true)
|
|
77
|
+
* const first = triple.get(0) // string
|
|
78
|
+
* const second = triple.get(1) // number
|
|
79
|
+
* const third = triple.get(2) // boolean
|
|
80
|
+
*
|
|
81
|
+
* @example
|
|
82
|
+
* // Functional operations
|
|
83
|
+
* const doubled = Tuple([1, 2, 3])
|
|
84
|
+
* .map(arr => arr.map(x => x * 2))
|
|
85
|
+
* .toArray() // [2, 4, 6]
|
|
86
|
+
*/
|
|
87
|
+
export declare const Tuple: TupleCompanion;
|
|
88
|
+
/** The type of `Tuple`: its constructor and its statics, named so that errors and hovers print `TupleCompanion`. */
|
|
89
|
+
export interface TupleCompanion extends TupleConstructorType, TupleStaticsType {}
|
|
90
|
+
type TupleConstructorType = typeof TupleConstructor;
|
|
91
|
+
type TupleStaticsType = typeof TupleStatics;
|
|
92
|
+
export {};
|
package/dist/tuple/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Companion as e}from"../companion/Companion.js";import{define as t}from"../internal/define.js";import{createSerializer as n}from"../serialization/SerializationCompanion.js";const r=t()(`Tuple`,{[Symbol.toStringTag]:`Tuple`,get length(){return this.value.length},get(e){return this.value[e]},map(e){return i(e(this.value))},flatMap(e){return e(this.value)},toArray(){return this.value},[Symbol.iterator](){return this.value[Symbol.iterator]()},fold(e,t){return this.value.reduce(t,e)},foldLeft(e){return t=>this.value.reduce(t,e)},foldRight(e){return t=>this.value.reduceRight((e,n)=>t(n,e),e)},pipe(e){return e(this)},serialize(){return n(`Tuple`,this.value)},toJSON(){return{"@functype":`Tuple`,_tag:`Tuple`,value:[...this.value]}},toValue(){return{_tag:`Tuple`,value:this.value}},toString(){return`Tuple(${this.value.map(e=>String(e)).join(`, `)})`}}),i=e=>{let t=Object.create(r);return t._tag=`Tuple`,t.value=e,t},a=e(e=>i(e),{of:(...e)=>i(e),pair:(e,t)=>i([e,t]),triple:(e,t,n)=>i([e,t,n]),empty:()=>i([]),from:e=>i(e),fromJSON:e=>{let t=JSON.parse(e);if(t[`@functype`]!==void 0&&t[`@functype`]!==`Tuple`)throw Error(`Tuple.fromJSON: expected @functype="Tuple", got ${JSON.stringify(t[`@functype`])}`);return i(t.value)}});export{a as Tuple};
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Base interface for objects with a type tag
|
|
3
|
+
* @internal
|
|
4
|
+
*/
|
|
5
|
+
interface TypeableBase<Tag extends string> {
|
|
6
|
+
readonly _tag: Tag;
|
|
7
|
+
}
|
|
8
|
+
export type Typeable<Tag extends string, T = object> = T & TypeableBase<Tag>;
|
|
9
|
+
/**
|
|
10
|
+
* Parameters for creating a Typeable instance
|
|
11
|
+
* @internal
|
|
12
|
+
*/
|
|
13
|
+
export type TypeableParams<Tag extends string, T> = {
|
|
14
|
+
_tag: Tag;
|
|
15
|
+
impl: T;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* Utility type to extract the Tag from a Typeable type
|
|
19
|
+
* @typeParam T - The Typeable type to extract the tag from
|
|
20
|
+
* @internal
|
|
21
|
+
*/
|
|
22
|
+
export type ExtractTag<T> = T extends Typeable<infer Tag, unknown> ? Tag : never;
|
|
23
|
+
/**
|
|
24
|
+
* Core utility for creating nominal typing in TypeScript by adding a type tag to any object.
|
|
25
|
+
* This allows for creating distinct types that are structurally identical but considered different by TypeScript's type system.
|
|
26
|
+
*
|
|
27
|
+
* @param params - The parameters containing the tag and implementation
|
|
28
|
+
* @returns A Typeable object with the specified tag
|
|
29
|
+
* @typeParam Tag - The string literal type used as the discriminator
|
|
30
|
+
* @typeParam T - The base type to extend with the tag
|
|
31
|
+
*/
|
|
32
|
+
export declare function Typeable<Tag extends string, T>({ _tag, impl }: TypeableParams<Tag, T>): Typeable<Tag, T>;
|
|
33
|
+
/**
|
|
34
|
+
* Type guard with automatic type inference using the full type
|
|
35
|
+
* @param value - The value to check
|
|
36
|
+
* @param tag - The tag to check for
|
|
37
|
+
* @returns Whether the value is a Typeable with the specified tag
|
|
38
|
+
*/
|
|
39
|
+
export declare function isTypeable<T>(value: unknown, tag: string): value is T;
|
|
40
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function e({_tag:e,impl:t}){return{...t,_tag:e}}function t(e,t){return!e||typeof e!=`object`||!(`_tag`in e)?!1:!t||e._tag===t}export{e as Typeable,t as isTypeable};
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { Option } from "../option/index.js";
|
|
2
|
+
import { Type } from "../types/index.js";
|
|
3
|
+
/**
|
|
4
|
+
* Universal operations that work on any container (single-value or collection).
|
|
5
|
+
* These operations make sense for Option, Either, Try, List, Set, etc.
|
|
6
|
+
*
|
|
7
|
+
* @typeParam A - The type of value(s) in the container
|
|
8
|
+
*/
|
|
9
|
+
export interface ContainerOps<out A extends Type> {
|
|
10
|
+
/**
|
|
11
|
+
* Counts elements that satisfy the predicate.
|
|
12
|
+
* For single-value containers: returns 0 or 1
|
|
13
|
+
* For collections: returns the count of matching elements
|
|
14
|
+
*/
|
|
15
|
+
count(p: (x: A) => boolean): number;
|
|
16
|
+
/**
|
|
17
|
+
* Finds the first element that satisfies the predicate.
|
|
18
|
+
* For single-value containers: returns Some(value) if predicate matches, None otherwise
|
|
19
|
+
* For collections: returns the first matching element wrapped in Option
|
|
20
|
+
*/
|
|
21
|
+
find(p: (a: A) => boolean): Option<A>;
|
|
22
|
+
/**
|
|
23
|
+
* Tests whether any element satisfies the predicate.
|
|
24
|
+
* For single-value containers: tests the single value
|
|
25
|
+
* For collections: returns true if any element matches
|
|
26
|
+
*/
|
|
27
|
+
exists(p: (a: A) => boolean): boolean;
|
|
28
|
+
/**
|
|
29
|
+
* Applies an effect function to each element.
|
|
30
|
+
* For single-value containers: applies to the value if present
|
|
31
|
+
* For collections: applies to each element
|
|
32
|
+
*/
|
|
33
|
+
forEach(f: (a: A) => void): void;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Operations specific to collections (List, Set, etc.).
|
|
37
|
+
* These operations don't make sense for single-value containers.
|
|
38
|
+
*
|
|
39
|
+
* @typeParam A - The element type
|
|
40
|
+
* @typeParam Self - The collection type itself for proper return types
|
|
41
|
+
*/
|
|
42
|
+
export interface CollectionOps<out A extends Type, Self> {
|
|
43
|
+
/**
|
|
44
|
+
* Tests whether every element satisfies the predicate. True for an empty collection.
|
|
45
|
+
* Stops at the first element that fails. The counterpart of `exists`.
|
|
46
|
+
*
|
|
47
|
+
* @example
|
|
48
|
+
* ```typescript
|
|
49
|
+
* List([1, 2, 3]).every((x) => x > 0) // true
|
|
50
|
+
* List<number>([]).every((x) => x > 0) // true
|
|
51
|
+
* ```
|
|
52
|
+
*/
|
|
53
|
+
every(p: (a: A) => boolean): boolean;
|
|
54
|
+
/**
|
|
55
|
+
* Left-associative fold over all elements using an initial value and combining function.
|
|
56
|
+
* Unlike foldLeft (which is curried), this provides a convenient uncurried signature.
|
|
57
|
+
*
|
|
58
|
+
* @example
|
|
59
|
+
* ```typescript
|
|
60
|
+
* List([1, 2, 3]).fold(0, (acc, x) => acc + x) // 6
|
|
61
|
+
* ```
|
|
62
|
+
*
|
|
63
|
+
* @param initial - The initial accumulator value
|
|
64
|
+
* @param fn - A function that combines the accumulator with each element
|
|
65
|
+
* @returns The final accumulated value
|
|
66
|
+
*/
|
|
67
|
+
fold<B>(initial: B, fn: (acc: B, a: A) => B): B;
|
|
68
|
+
/**
|
|
69
|
+
* Drops the first n elements from the collection.
|
|
70
|
+
*/
|
|
71
|
+
drop(n: number): Self;
|
|
72
|
+
/**
|
|
73
|
+
* Drops the last n elements from the collection.
|
|
74
|
+
*/
|
|
75
|
+
dropRight(n: number): Self;
|
|
76
|
+
/**
|
|
77
|
+
* Drops elements from the start while the predicate is true.
|
|
78
|
+
*/
|
|
79
|
+
dropWhile(p: (a: A) => boolean): Self;
|
|
80
|
+
/**
|
|
81
|
+
* Flattens a collection of collections into a single collection.
|
|
82
|
+
*/
|
|
83
|
+
flatten<B>(): Self;
|
|
84
|
+
/**
|
|
85
|
+
* Gets the first element of the collection.
|
|
86
|
+
*/
|
|
87
|
+
head(): A | undefined;
|
|
88
|
+
/**
|
|
89
|
+
* Gets the first element wrapped in Option.
|
|
90
|
+
*/
|
|
91
|
+
headOption(): Option<A>;
|
|
92
|
+
/**
|
|
93
|
+
* Takes the first n elements from the collection.
|
|
94
|
+
*/
|
|
95
|
+
take(n: number): Self;
|
|
96
|
+
/**
|
|
97
|
+
* Takes elements from the start while the predicate is true.
|
|
98
|
+
*/
|
|
99
|
+
takeWhile(p: (a: A) => boolean): Self;
|
|
100
|
+
/**
|
|
101
|
+
* Takes the last n elements from the collection.
|
|
102
|
+
*/
|
|
103
|
+
takeRight(n: number): Self;
|
|
104
|
+
/**
|
|
105
|
+
* Gets the last element of the collection.
|
|
106
|
+
*/
|
|
107
|
+
last(): A | undefined;
|
|
108
|
+
/**
|
|
109
|
+
* Gets the last element wrapped in Option.
|
|
110
|
+
*/
|
|
111
|
+
lastOption(): Option<A>;
|
|
112
|
+
/**
|
|
113
|
+
* Gets all elements except the first. A method, not a property (2.0): on a List or Set it copies
|
|
114
|
+
* the rest of the collection, so a loop that calls it on every step does quadratic work.
|
|
115
|
+
*/
|
|
116
|
+
tail(): Self;
|
|
117
|
+
/**
|
|
118
|
+
* Gets all elements except the last. Like `tail()`, it copies the rest of a List or Set.
|
|
119
|
+
*/
|
|
120
|
+
init(): Self;
|
|
121
|
+
/**
|
|
122
|
+
* Converts the collection to an array.
|
|
123
|
+
*/
|
|
124
|
+
toArray<B = A>(): B[];
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* What `flatten` yields for one element: an iterable's items, and anything else, including a string, as
|
|
128
|
+
* itself. That matches the runtime, which spreads arrays and other non-string iterables. Languages
|
|
129
|
+
* disagree on strings: Scala and Python split them into characters, JavaScript's `flat` keeps them whole.
|
|
130
|
+
*/
|
|
131
|
+
export type Flattened<A> = A extends string ? A : A extends Iterable<infer B> ? B : A;
|