/** * @since 1.0.0 */ import type * as Chunk from "@effect/data/Chunk" import * as Context from "@effect/data/Context" import type * as Duration from "@effect/data/Duration" import type * as Either from "@effect/data/Either" import type * as Equal from "@effect/data/Equal" import type { Equivalence } from "@effect/data/Equivalence" import type { LazyArg } from "@effect/data/Function" import { identity } from "@effect/data/Function" import type * as HashMap from "@effect/data/HashMap" import type * as HashSet from "@effect/data/HashSet" import type { TypeLambda } from "@effect/data/HKT" import type { Inspectable } from "@effect/data/Inspectable" import type * as Option from "@effect/data/Option" import type { Pipeable } from "@effect/data/Pipeable" import type { Predicate, Refinement } from "@effect/data/Predicate" import type * as Unify from "@effect/data/Unify" import type * as Cause from "@effect/io/Cause" import type * as Clock from "@effect/io/Clock" import type { Concurrency } from "@effect/io/Concurrency" import type { Config } from "@effect/io/Config" import type { ConfigError } from "@effect/io/ConfigError" import type { ConfigProvider } from "@effect/io/ConfigProvider" import type * as Deferred from "@effect/io/Deferred" import type { ExecutionStrategy } from "@effect/io/ExecutionStrategy" import type * as Exit from "@effect/io/Exit" import type * as Fiber from "@effect/io/Fiber" import type * as FiberId from "@effect/io/FiberId" import type * as FiberRef from "@effect/io/FiberRef" import type * as FiberRefs from "@effect/io/FiberRefs" import type * as FiberRefsPatch from "@effect/io/FiberRefsPatch" import { clockTag } from "@effect/io/internal/clock" import * as core from "@effect/io/internal/core" import * as defaultServices from "@effect/io/internal/defaultServices" import * as effect from "@effect/io/internal/effect" import * as circular from "@effect/io/internal/effect/circular" import * as fiberRuntime from "@effect/io/internal/fiberRuntime" import * as layer from "@effect/io/internal/layer" import * as circularLayer from "@effect/io/internal/layer/circular" import * as query from "@effect/io/internal/query" import * as _runtime from "@effect/io/internal/runtime" import * as _schedule from "@effect/io/internal/schedule" import type * as Layer from "@effect/io/Layer" import type * as Logger from "@effect/io/Logger" import type { LogLevel } from "@effect/io/LogLevel" import type * as Metric from "@effect/io/Metric" import type * as MetricLabel from "@effect/io/MetricLabel" import type * as Random from "@effect/io/Random" import type * as Ref from "@effect/io/Ref" import type * as Request from "@effect/io/Request" import type { RequestBlock } from "@effect/io/RequestBlock" import type { RequestResolver } from "@effect/io/RequestResolver" import type * as Runtime from "@effect/io/Runtime" import type * as RuntimeFlags from "@effect/io/RuntimeFlags" import type * as RuntimeFlagsPatch from "@effect/io/RuntimeFlagsPatch" import type * as Schedule from "@effect/io/Schedule" import * as Scheduler from "@effect/io/Scheduler" import type * as Scope from "@effect/io/Scope" import type * as Supervisor from "@effect/io/Supervisor" import type * as Tracer from "@effect/io/Tracer" // ------------------------------------------------------------------------------------- // models // ------------------------------------------------------------------------------------- /** * @since 1.0.0 */ export type MergeRecord = { [k in keyof K | keyof H]: k extends keyof K ? K[k] : k extends keyof H ? H[k] : never } extends infer X ? X : never /** * @since 1.0.0 * @category symbols */ export const EffectTypeId: unique symbol = core.EffectTypeId /** * @since 1.0.0 * @category symbols */ export type EffectTypeId = typeof EffectTypeId /** * The `Effect` interface defines a value that lazily describes a workflow or job. * The workflow requires some context `R`, and may fail with an error of type `E`, * or succeed with a value of type `A`. * * `Effect` values model resourceful interaction with the outside world, including * synchronous, asynchronous, concurrent, and parallel interaction. They use a * fiber-based concurrency model, with built-in support for scheduling, fine-grained * interruption, structured concurrency, and high scalability. * * To run an `Effect` value, you need a `Runtime`, which is a type that is capable * of executing `Effect` values. * * @since 1.0.0 * @category models */ export interface Effect extends Effect.Variance, Equal.Equal, Pipeable, Inspectable { readonly [Unify.typeSymbol]?: unknown readonly [Unify.unifySymbol]?: EffectUnify readonly [Unify.blacklistSymbol]?: EffectUnifyBlacklist } /** * @since 1.0.0 * @category models */ export interface EffectUnify extends Either.EitherUnify, Option.OptionUnify, Context.TagUnify { Effect?: () => A[Unify.typeSymbol] extends Effect | infer _ ? Effect : never } /** * @category models * @since 1.0.0 */ export interface EffectUnifyBlacklist { Tag?: true Option?: true Either?: true } /** * @category type lambdas * @since 1.0.0 */ export interface EffectTypeLambda extends TypeLambda { readonly type: Effect } /** * @since 1.0.0 * @category models */ export interface Blocked extends Effect { readonly _tag: "Blocked" readonly i0: RequestBlock readonly i1: Effect } /** * @since 1.0.0 * @category models */ declare module "@effect/data/Context" { interface Tag extends Effect {} interface TagUnifyBlacklist { Effect?: true Either?: true Option?: true } } /** * @since 1.0.0 * @category models */ declare module "@effect/data/Either" { interface Left extends Effect { readonly _tag: "Left" } interface Right extends Effect { readonly _tag: "Right" } interface EitherUnifyBlacklist { Effect?: true Tag?: true Option?: true } } /** * @since 1.0.0 * @category models */ declare module "@effect/data/Option" { interface None extends Effect { readonly _tag: "None" } interface Some extends Effect { readonly _tag: "Some" } interface OptionUnifyBlacklist { Effect?: true Tag?: true Either?: true } } /** * @since 1.0.0 */ export declare namespace Effect { /** * @since 1.0.0 * @category models */ export interface Variance { readonly [EffectTypeId]: { readonly _R: (_: never) => R readonly _E: (_: never) => E readonly _A: (_: never) => A } } /** * @since 1.0.0 * @category models */ export type Unify> = Effect< Context, Error, Success > /** * @since 1.0.0 * @category type-level */ export type Context> = [T] extends [Effect] ? _R : never /** * @since 1.0.0 * @category type-level */ export type Error> = [T] extends [Effect] ? _E : never /** * @since 1.0.0 * @category type-level */ export type Success> = [T] extends [Effect] ? _A : never } // ------------------------------------------------------------------------------------- // refinements // ------------------------------------------------------------------------------------- /** * This function returns `true` if the specified value is an `Effect` value, * `false` otherwise. * * This function can be useful for checking the type of a value before * attempting to operate on it as an `Effect` value. For example, you could * use `isEffect` to check the type of a value before using it as an * argument to a function that expects an `Effect` value. * * @param u - The value to check for being an `Effect` value. * * @returns `true` if the specified value is an `Effect` value, `false` * otherwise. * * @since 1.0.0 * @category refinements */ export const isEffect: (u: unknown) => u is Effect = core.isEffect // ------------------------------------------------------------------------------------- // caching // ------------------------------------------------------------------------------------- /** * Returns an effect that, if evaluated, will return the cached result of this * effect. Cached results will expire after `timeToLive` duration. * * @since 1.0.0 * @category caching */ export const cachedWithTTL: { (timeToLive: Duration.DurationInput): (self: Effect) => Effect> (self: Effect, timeToLive: Duration.DurationInput): Effect> } = circular.cached /** * Returns an effect that, if evaluated, will return the cached result of this * effect. Cached results will expire after `timeToLive` duration. In * addition, returns an effect that can be used to invalidate the current * cached value before the `timeToLive` duration expires. * * @since 1.0.0 * @category caching */ export const cachedInvalidateWithTTL: { (timeToLive: Duration.DurationInput): ( self: Effect ) => Effect, Effect]> ( self: Effect, timeToLive: Duration.DurationInput ): Effect, Effect]> } = circular.cachedInvalidate /** * Returns an effect that, if evaluated, will return the lazily computed * result of this effect. * * @since 1.0.0 * @category caching */ export const cached: (self: Effect) => Effect> = effect.memoize /** * Returns a memoized version of the specified effectual function. * * @since 1.0.0 * @category caching */ export const cachedFunction: ( f: (a: A) => Effect, eq?: Equivalence ) => Effect Effect> = circular.memoizeFunction /** * Returns an effect that will be executed at most once, even if it is * evaluated multiple times. * * @since 1.0.0 * @category caching */ export const once: (self: Effect) => Effect> = effect.once // ------------------------------------------------------------------------------------- // collecting & elements // ------------------------------------------------------------------------------------- /** * Runs all the provided effects in sequence respecting the structure provided in input. * * Supports multiple arguments, a single argument tuple / array or record / struct. * * @since 1.0.0 * @category collecting & elements */ export const all: < const Arg extends Iterable> | Record>, O extends { readonly concurrency?: Concurrency readonly batching?: boolean | "inherit" readonly discard?: boolean readonly mode?: "default" | "validate" | "either" } >(arg: Arg, options?: O) => All.Return = fiberRuntime.all /** * Data-last variant of `Effect.all`. * * Runs all the provided effects in sequence respecting the structure provided in input. * * Supports multiple arguments, a single argument tuple / array or record / struct. * * @since 1.0.0 * @category collecting & elements */ export const allWith: < O extends { readonly concurrency?: Concurrency readonly batching?: boolean | "inherit" readonly discard?: boolean readonly mode?: "default" | "validate" | "either" } >( options?: O ) => > | Record>>( arg: Arg ) => All.Return = fiberRuntime.allWith /** * @since 1.0.0 */ export declare namespace All { /** * @since 1.0.0 */ export type EffectAny = Effect /** * @since 1.0.0 */ export type ReturnIterable, Discard extends boolean, Mode> = [T] extends [Iterable>] ? Effect< R, Mode extends "either" ? never : Mode extends "validate" ? Array> : E, Discard extends true ? void : Mode extends "either" ? Array> : Array > : never /** * @since 1.0.0 */ export type ReturnTuple, Discard extends boolean, Mode> = Effect< T[number] extends never ? never : [T[number]] extends [{ [EffectTypeId]: { _R: (_: never) => infer R } }] ? R : never, Mode extends "either" ? never : T[number] extends never ? never : Mode extends "validate" ? { -readonly [K in keyof T]: [T[K]] extends [Effect.Variance] ? Option.Option<_E> : never } : [T[number]] extends [{ [EffectTypeId]: { _E: (_: never) => infer E } }] ? E : never, Discard extends true ? void : T[number] extends never ? [] : Mode extends "either" ? { -readonly [K in keyof T]: [T[K]] extends [Effect.Variance] ? Either.Either<_E, _A> : never } : { -readonly [K in keyof T]: [T[K]] extends [Effect.Variance] ? _A : never } > extends infer X ? X : never /** * @since 1.0.0 */ export type ReturnObject = [T] extends [{ [K: string]: EffectAny }] ? Effect< keyof T extends never ? never : [T[keyof T]] extends [{ [EffectTypeId]: { _R: (_: never) => infer R } }] ? R : never, Mode extends "either" ? never : keyof T extends never ? never : Mode extends "validate" ? { -readonly [K in keyof T]: [T[K]] extends [Effect.Variance] ? Option.Option<_E> : never } : [T[keyof T]] extends [{ [EffectTypeId]: { _E: (_: never) => infer E } }] ? E : never, Discard extends true ? void : Mode extends "either" ? { -readonly [K in keyof T]: [T[K]] extends [Effect.Variance] ? Either.Either<_E, _A> : never } : { -readonly [K in keyof T]: [T[K]] extends [Effect.Variance] ? _A : never } > : never /** * @since 1.0.0 */ export type IsDiscard = [Extract] extends [never] ? false : true /** * @since 1.0.0 */ export type ExtractMode = [A] extends [{ mode: infer M }] ? M : "default" /** * @since 1.0.0 */ export type Return< Arg extends Iterable | Record, O extends { readonly concurrency?: Concurrency readonly batching?: boolean | "inherit" readonly discard?: boolean readonly mode?: "default" | "validate" | "either" } > = [Arg] extends [ReadonlyArray] ? ReturnTuple, ExtractMode> : [Arg] extends [Iterable] ? ReturnIterable, ExtractMode> : [Arg] extends [Record] ? ReturnObject, ExtractMode> : never } /** * Evaluate and run each effect in the structure and collect the results, * discarding results from failed effects. * * @since 1.0.0 * @category collecting & elements */ export const allSuccesses: ( elements: Iterable>, options?: { readonly concurrency?: Concurrency readonly batching?: boolean | "inherit" } ) => Effect> = fiberRuntime.allSuccesses /** * Drops all elements until the effectful predicate returns true. * * @since 1.0.0 * @category collecting & elements */ export const dropUntil: { (predicate: (a: A, i: number) => Effect): (elements: Iterable) => Effect> (elements: Iterable, predicate: (a: A, i: number) => Effect): Effect> } = effect.dropUntil /** * Drops all elements so long as the predicate returns true. * * @since 1.0.0 * @category collecting & elements */ export const dropWhile: { (f: (a: A, i: number) => Effect): (elements: Iterable) => Effect> (elements: Iterable, f: (a: A, i: number) => Effect): Effect> } = effect.dropWhile /** * Determines whether all elements of the `Collection` satisfies the effectual * predicate `f`. * * @since 1.0.0 * @category collecting & elements */ export const every: { (f: (a: A, i: number) => Effect): (elements: Iterable) => Effect (elements: Iterable, f: (a: A, i: number) => Effect): Effect } = effect.every /** * Determines whether any element of the `Iterable` satisfies the effectual * predicate `f`. * * @since 1.0.0 * @category collecting & elements */ export const exists: { ( f: (a: A, i: number) => Effect, options?: { readonly concurrency?: Concurrency readonly batching?: boolean | "inherit" } ): (elements: Iterable) => Effect ( elements: Iterable, f: (a: A, i: number) => Effect, options?: { readonly concurrency: Concurrency readonly batching?: boolean | "inherit" } ): Effect } = fiberRuntime.exists /** * Filters the collection using the specified effectful predicate. * * @since 1.0.0 * @category collecting & elements */ export const filter: { ( f: (a: A, i: number) => Effect, options?: { readonly concurrency?: Concurrency readonly batching?: boolean | "inherit" readonly negate?: boolean } ): (elements: Iterable) => Effect> ( elements: Iterable, f: (a: A, i: number) => Effect, options?: { readonly concurrency?: Concurrency readonly batching?: boolean | "inherit" readonly negate?: boolean } ): Effect> } = fiberRuntime.filter /** * Returns the first element that satisfies the effectful predicate. * * @since 1.0.0 * @category collecting & elements */ export const findFirst: { (f: (a: A, i: number) => Effect): (elements: Iterable) => Effect> (elements: Iterable, f: (a: A, i: number) => Effect): Effect> } = effect.findFirst /** * This function takes an iterable of `Effect` values and returns a new * `Effect` value that represents the first `Effect` value in the iterable * that succeeds. If all of the `Effect` values in the iterable fail, then * the resulting `Effect` value will fail as well. * * This function is sequential, meaning that the `Effect` values in the * iterable will be executed in sequence, and the first one that succeeds * will determine the outcome of the resulting `Effect` value. * * @param effects - The iterable of `Effect` values to evaluate. * * @returns A new `Effect` value that represents the first successful * `Effect` value in the iterable, or a failed `Effect` value if all of the * `Effect` values in the iterable fail. * * @since 1.0.0 * @category collecting & elements */ export const firstSuccessOf: (effects: Iterable>) => Effect = effect.firstSuccessOf /** * @since 1.0.0 * @category collecting & elements */ export const forEach: { ( f: (a: A, i: number) => Effect, options?: { readonly concurrency?: Concurrency readonly batching?: boolean | "inherit" readonly discard?: false } ): (self: Iterable) => Effect> ( f: (a: A, i: number) => Effect, options: { readonly concurrency?: Concurrency readonly batching?: boolean | "inherit" readonly discard: true } ): (self: Iterable) => Effect ( self: Iterable, f: (a: A, i: number) => Effect, options?: { readonly concurrency?: Concurrency readonly batching?: boolean | "inherit" readonly discard?: false } ): Effect> ( self: Iterable, f: (a: A, i: number) => Effect, options: { readonly concurrency?: Concurrency readonly batching?: boolean | "inherit" readonly discard: true } ): Effect } = fiberRuntime.forEachOptions /** * Returns a successful effect with the head of the collection if the collection * is non-empty, or fails with the error `None` if the collection is empty. * * @since 1.0.0 * @category collecting & elements */ export const head: (self: Effect>) => Effect, A> = effect.head /** * Merges an `Iterable>` to a single effect, working * sequentially. * * @since 1.0.0 * @category collecting & elements */ export const mergeAll: { ( zero: Z, f: (z: Z, a: A, i: number) => Z, options?: { readonly concurrency?: Concurrency readonly batching?: boolean | "inherit" } ): (elements: Iterable>) => Effect ( elements: Iterable>, zero: Z, f: (z: Z, a: A, i: number) => Z, options?: { readonly concurrency?: Concurrency readonly batching?: boolean | "inherit" } ): Effect } = fiberRuntime.mergeAll /** * Feeds elements of type `A` to a function `f` that returns an effect. * Collects all successes and failures in a tupled fashion. * * @since 1.0.0 * @category collecting & elements */ export const partition: { ( f: (a: A) => Effect, options?: { readonly concurrency?: Concurrency readonly batching?: boolean | "inherit" } ): (elements: Iterable) => Effect, Array]> (elements: Iterable, f: (a: A) => Effect, options?: { readonly concurrency?: Concurrency readonly batching?: boolean | "inherit" }): Effect, Array]> } = fiberRuntime.partition /** * Folds an `Iterable` using an effectual function f, working sequentially * from left to right. * * @since 1.0.0 * @category collecting & elements */ export const reduce: { (zero: Z, f: (z: Z, a: A, i: number) => Effect): (elements: Iterable) => Effect (elements: Iterable, zero: Z, f: (z: Z, a: A, i: number) => Effect): Effect } = effect.reduce /** * Reduces an `Iterable>` to a single effect. * * @since 1.0.0 * @category collecting & elements */ export const reduceEffect: { ( zero: Effect, f: (acc: A, a: A, i: number) => A, options?: { readonly concurrency?: Concurrency readonly batching?: boolean | "inherit" } ): (elements: Iterable>) => Effect ( elements: Iterable>, zero: Effect, f: (acc: A, a: A, i: number) => A, options?: { readonly concurrency?: Concurrency readonly batching?: boolean | "inherit" } ): Effect } = fiberRuntime.reduceEffect /** * Folds an `Iterable` using an effectual function f, working sequentially from left to right. * * @since 1.0.0 * @category collecting & elements */ export const reduceRight: { (zero: Z, f: (a: A, z: Z, i: number) => Effect): (elements: Iterable) => Effect (elements: Iterable, zero: Z, f: (a: A, z: Z, i: number) => Effect): Effect } = effect.reduceRight /** * Folds over the elements in this chunk from the left, stopping the fold early * when the predicate is not satisfied. * * @since 1.0.0 * @category collecting & elements */ export const reduceWhile: { ( zero: Z, options: { readonly while: Predicate readonly body: (s: Z, a: A, i: number) => Effect } ): (elements: Iterable) => Effect ( elements: Iterable, zero: Z, options: { readonly while: Predicate readonly body: (s: Z, a: A, i: number) => Effect } ): Effect } = effect.reduceWhile /** * Replicates the given effect `n` times. * * @since 1.0.0 * @category collecting & elements */ export const replicate: { (n: number): (self: Effect) => Array> (self: Effect, n: number): Array> } = fiberRuntime.replicate /** * Performs this effect the specified number of times and collects the * results. * * @since 1.0.0 * @category collecting & elements */ export const replicateEffect: { ( n: number, options?: { readonly concurrency?: Concurrency readonly batching?: boolean | "inherit" readonly discard?: false } ): (self: Effect) => Effect> ( n: number, options: { readonly concurrency?: Concurrency readonly batching?: boolean | "inherit" readonly discard: true } ): (self: Effect) => Effect ( self: Effect, n: number, options?: { readonly concurrency?: Concurrency readonly batching?: boolean | "inherit" readonly discard?: false } ): Effect> ( self: Effect, n: number, options: { readonly concurrency?: Concurrency readonly batching?: boolean | "inherit" readonly discard: true } ): Effect } = fiberRuntime.replicateEffect /** * Takes elements until the effectual predicate returns true. * * @since 1.0.0 * @category collecting & elements */ export const takeUntil: { (predicate: (a: A, i: number) => Effect): (elements: Iterable) => Effect> (elements: Iterable, predicate: (a: A, i: number) => Effect): Effect> } = effect.takeUntil /** * Takes all elements so long as the effectual predicate returns true. * * @since 1.0.0 * @category collecting & elements */ export const takeWhile: { (predicate: (a: A, i: number) => Effect): (elements: Iterable) => Effect> (elements: Iterable, predicate: (a: A, i: number) => Effect): Effect> } = effect.takeWhile /** * Feeds elements of type `A` to `f` and accumulates all errors in error * channel or successes in success channel. * * This combinator is lossy meaning that if there are errors all successes * will be lost. To retain all information please use `partition`. * * @since 1.0.0 * @category collecting & elements */ export const validateAll: { ( f: (a: A, i: number) => Effect, options?: { readonly concurrency?: Concurrency readonly batching?: boolean | "inherit" readonly discard?: false } ): (elements: Iterable) => Effect, Array> ( f: (a: A, i: number) => Effect, options: { readonly concurrency?: Concurrency readonly batching?: boolean | "inherit" readonly discard: true } ): (elements: Iterable) => Effect, void> ( elements: Iterable, f: (a: A, i: number) => Effect, options?: { readonly concurrency?: Concurrency readonly batching?: boolean | "inherit" readonly discard?: false } ): Effect, Array> ( elements: Iterable, f: (a: A, i: number) => Effect, options: { readonly concurrency?: Concurrency readonly batching?: boolean | "inherit" readonly discard: true } ): Effect, void> } = fiberRuntime.validateAll /** * Feeds elements of type `A` to `f` until it succeeds. Returns first success * or the accumulation of all errors. * * If `elements` is empty then `Effect.fail([])` is returned. * * @example * import * as Effect from "@effect/io/Effect" * import * as Exit from "@effect/io/Exit" * * const f = (n: number) => (n > 0 ? Effect.succeed(n) : Effect.fail(`${n} is negative`)) * * assert.deepStrictEqual(Effect.runSyncExit(Effect.validateFirst([], f)), Exit.fail([])) * assert.deepStrictEqual(Effect.runSyncExit(Effect.validateFirst([1, 2], f)), Exit.succeed(1)) * assert.deepStrictEqual(Effect.runSyncExit(Effect.validateFirst([1, -1], f)), Exit.succeed(1)) * assert.deepStrictEqual(Effect.runSyncExit(Effect.validateFirst([-1, 2], f)), Exit.succeed(2)) * assert.deepStrictEqual(Effect.runSyncExit(Effect.validateFirst([-1, -2], f)), Exit.fail(['-1 is negative', '-2 is negative'])) * * @since 1.0.0 * @category collecting & elements */ export const validateFirst: { ( f: (a: A, i: number) => Effect, options?: { readonly concurrency?: Concurrency readonly batching?: boolean | "inherit" } ): (elements: Iterable) => Effect, B> ( elements: Iterable, f: (a: A, i: number) => Effect, options?: { readonly concurrency?: Concurrency readonly batching?: boolean | "inherit" } ): Effect, B> } = fiberRuntime.validateFirst // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- /** * Imports an asynchronous side-effect into a pure `Effect` value. * The callback function `Effect => void` must be called at most once. * * If an Effect is returned by the registration function, it will be executed * if the fiber executing the effect is interrupted. * * The registration function can also receive an `AbortSignal` if required for * interruption. * * The `FiberId` of the fiber that may complete the async callback may be * provided to allow for better diagnostics. * * @since 1.0.0 * @category constructors */ export const async: ( register: (callback: (_: Effect) => void, signal: AbortSignal) => void | Effect, blockingOn?: FiberId.FiberId ) => Effect = core.async /** * Converts an asynchronous, callback-style API into an `Effect`, which will * be executed asynchronously. * * With this variant, the registration function may return a an `Effect`. * * @since 1.0.0 * @category constructors */ export const asyncEffect: ( register: (callback: (_: Effect) => void) => Effect ) => Effect = _runtime.asyncEffect /** * Imports an asynchronous effect into a pure `Effect` value, possibly returning * the value synchronously. * * If the register function returns a value synchronously, then the callback * function `Effect => void` must not be called. Otherwise the callback * function must be called at most once. * * The `FiberId` of the fiber that may complete the async callback may be * provided to allow for better diagnostics. * * @since 1.0.0 * @category constructors */ export const asyncOption: ( register: (callback: (_: Effect) => void) => Option.Option>, blockingOn?: FiberId.FiberId ) => Effect = effect.asyncOption /** * Imports an asynchronous side-effect into an effect. It has the option of * returning the value synchronously, which is useful in cases where it cannot * be determined if the effect is synchronous or asynchronous until the register * is actually executed. It also has the option of returning a canceler, * which will be used by the runtime to cancel the asynchronous effect if the fiber * executing the effect is interrupted. * * If the register function returns a value synchronously, then the callback * function `Effect => void` must not be called. Otherwise the callback * function must be called at most once. * * The `FiberId` of the fiber that may complete the async callback may be * provided to allow for better diagnostics. * * @since 1.0.0 * @category constructors */ export const asyncEither: ( register: (callback: (effect: Effect) => void) => Either.Either, Effect>, blockingOn?: FiberId.FiberId ) => Effect = core.asyncEither /** * @since 1.0.0 * @category constructors */ export const fail: (error: E) => Effect = core.fail /** * @since 1.0.0 * @category constructors */ export const failSync: (evaluate: LazyArg) => Effect = core.failSync /** * @since 1.0.0 * @category constructors */ export const failCause: (cause: Cause.Cause) => Effect = core.failCause /** * @since 1.0.0 * @category constructors */ export const failCauseSync: (evaluate: LazyArg>) => Effect = core.failCauseSync /** * @since 1.0.0 * @category constructors */ export const die: (defect: unknown) => Effect = core.die /** * Returns an effect that dies with a `RuntimeException` having the specified * text message. This method can be used for terminating a fiber because a * defect has been detected in the code. * * @since 1.0.0 * @category constructors */ export const dieMessage: (message: string) => Effect = core.dieMessage /** * @since 1.0.0 * @category constructors */ export const dieSync: (evaluate: LazyArg) => Effect = core.dieSync /** * @since 1.0.0 * @category constructors */ export const gen: , AEff>( f: (resume: Adapter) => Generator ) => Effect< [Eff] extends [never] ? never : [Eff] extends [EffectGen] ? R : never, [Eff] extends [never] ? never : [Eff] extends [EffectGen] ? E : never, AEff > = effect.gen /** * @category models * @since 1.0.0 */ export interface EffectGen { readonly _R: () => R readonly _E: () => E readonly _A: () => A readonly value: Effect [Symbol.iterator](): Generator, A> } /** * @since 1.0.0 * @category models */ export interface Adapter { (self: Effect): EffectGen (a: A, ab: (a: A) => Effect<_R, _E, _A>): EffectGen<_R, _E, _A> (a: A, ab: (a: A) => B, bc: (b: B) => Effect<_R, _E, _A>): EffectGen<_R, _E, _A> (a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => Effect<_R, _E, _A>): EffectGen<_R, _E, _A> ( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => Effect<_R, _E, _A> ): EffectGen<_R, _E, _A> ( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => Effect<_R, _E, _A> ): EffectGen<_R, _E, _A> ( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => Effect<_R, _E, _A> ): EffectGen<_R, _E, _A> ( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => Effect<_R, _E, _A> ): EffectGen<_R, _E, _A> ( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (g: H) => Effect<_R, _E, _A> ): EffectGen<_R, _E, _A> ( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => Effect<_R, _E, _A> ): EffectGen<_R, _E, _A> ( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => Effect<_R, _E, _A> ): EffectGen<_R, _E, _A> ( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => Effect<_R, _E, _A> ): EffectGen<_R, _E, _A> ( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => L, lm: (l: L) => Effect<_R, _E, _A> ): EffectGen<_R, _E, _A> ( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => L, lm: (l: L) => M, mn: (m: M) => Effect<_R, _E, _A> ): EffectGen<_R, _E, _A> ( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => L, lm: (l: L) => M, mn: (m: M) => N, no: (n: N) => Effect<_R, _E, _A> ): EffectGen<_R, _E, _A> ( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => L, lm: (l: L) => M, mn: (m: M) => N, no: (n: N) => O, op: (o: O) => Effect<_R, _E, _A> ): EffectGen<_R, _E, _A> ( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => L, lm: (l: L) => M, mn: (m: M) => N, no: (n: N) => O, op: (o: O) => P, pq: (p: P) => Effect<_R, _E, _A> ): EffectGen<_R, _E, _A> ( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => L, lm: (l: L) => M, mn: (m: M) => N, no: (n: N) => O, op: (o: O) => P, pq: (p: P) => Q, qr: (q: Q) => Effect<_R, _E, _A> ): EffectGen<_R, _E, _A> ( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => L, lm: (l: L) => M, mn: (m: M) => N, no: (n: N) => O, op: (o: O) => P, pq: (p: P) => Q, qr: (q: Q) => R, rs: (r: R) => Effect<_R, _E, _A> ): EffectGen<_R, _E, _A> ( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => L, lm: (l: L) => M, mn: (m: M) => N, no: (n: N) => O, op: (o: O) => P, pq: (p: P) => Q, qr: (q: Q) => R, rs: (r: R) => S, st: (s: S) => Effect<_R, _E, _A> ): EffectGen<_R, _E, _A> ( a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => L, lm: (l: L) => M, mn: (m: M) => N, no: (n: N) => O, op: (o: O) => P, pq: (p: P) => Q, qr: (q: Q) => R, rs: (r: R) => S, st: (s: S) => T, tu: (s: T) => Effect<_R, _E, _A> ): EffectGen<_R, _E, _A> } /** * Returns a effect that will never produce anything. The moral equivalent of * `while(true) {}`, only without the wasted CPU cycles. * * @since 1.0.0 * @category constructors */ export const never: Effect = core.never /** * Requires the option produced by this value to be `None`. * * @since 1.0.0 * @category constructors */ export const none: (self: Effect>) => Effect, void> = effect.none /** * Like `tryPromise` but produces a defect in case of errors. * * An optional `AbortSignal` can be provided to allow for interruption of the * wrapped Promise api. * * @since 1.0.0 * @category constructors */ export const promise: ( evaluate: (signal: AbortSignal) => Promise ) => Effect = effect.promise /** * @since 1.0.0 * @category constructors */ export const succeed: (value: A) => Effect = core.succeed /** * Returns an effect which succeeds with `None`. * * @since 1.0.0 * @category constructors */ export const succeedNone: Effect> = effect.succeedNone /** * Returns an effect which succeeds with the value wrapped in a `Some`. * * @since 1.0.0 * @category constructors */ export const succeedSome: (value: A) => Effect> = effect.succeedSome /** * @since 1.0.0 * @category constructors */ export const suspend: (effect: LazyArg>) => Effect = core.suspend /** * @since 1.0.0 * @category constructors */ export const sync: (evaluate: LazyArg) => Effect = core.sync /** * @since 1.0.0 * @category constructors */ export const unit: Effect = core.unit /** * @since 1.0.0 * @category constructors */ export const yieldNow: (options?: { readonly priority?: number }) => Effect = core.yieldNow // ------------------------------------------------------------------------------------- // error handling // ------------------------------------------------------------------------------------- const _catch: { (discriminator: N, options: { readonly failure: K readonly onFailure: (error: Extract) => Effect }): (self: Effect) => Effect, A1 | A> ( self: Effect, discriminator: N, options: { readonly failure: K readonly onFailure: (error: Extract) => Effect } ): Effect, A | A1> } = effect._catch export { /** * Recovers from specified error. * * @since 1.0.0 * @category error handling */ _catch as catch } /** * Recovers from all recoverable errors. * * **Note**: that `Effect.catchAll` will not recover from unrecoverable defects. To * recover from both recoverable and unrecoverable errors use * `Effect.catchAllCause`. * * @since 1.0.0 * @category error handling */ export const catchAll: { (f: (e: E) => Effect): (self: Effect) => Effect (self: Effect, f: (e: E) => Effect): Effect } = core.catchAll /** * Recovers from both recoverable and unrecoverable errors. * * See `absorb`, `sandbox`, `mapErrorCause` for other functions that can * recover from defects. * * @since 1.0.0 * @category error handling */ export const catchAllCause: { ( f: (cause: Cause.Cause) => Effect ): (self: Effect) => Effect ( self: Effect, f: (cause: Cause.Cause) => Effect ): Effect } = core.catchAllCause /** * Recovers from all defects with provided function. * * **WARNING**: There is no sensible way to recover from defects. This * method should be used only at the boundary between Effect and an external * system, to transmit information on a defect for diagnostic or explanatory * purposes. * * @since 1.0.0 * @category error handling */ export const catchAllDefect: { ( f: (defect: unknown) => Effect ): (self: Effect) => Effect ( self: Effect, f: (defect: unknown) => Effect ): Effect } = effect.catchAllDefect /** * Recovers from errors that match the given predicate. * * @since 1.0.0 * @category error handling */ export const catchIf: { ( refinement: Refinement, f: (e: EB) => Effect ): (self: Effect) => Effect, A2 | A> ( predicate: Predicate, f: (e: EX) => Effect ): (self: Effect) => Effect ( self: Effect, refinement: Refinement, f: (e: EB) => Effect ): Effect, A | A2> ( self: Effect, predicate: Predicate, f: (e: EX) => Effect ): Effect } = core.catchIf /** * Recovers from some or all of the error cases. * * @since 1.0.0 * @category error handling */ export const catchSome: { ( pf: (e: E) => Option.Option> ): (self: Effect) => Effect ( self: Effect, pf: (e: E) => Option.Option> ): Effect } = core.catchSome /** * Recovers from some or all of the error cases with provided cause. * * @since 1.0.0 * @category error handling */ export const catchSomeCause: { ( f: (cause: Cause.Cause) => Option.Option> ): (self: Effect) => Effect ( self: Effect, f: (cause: Cause.Cause) => Option.Option> ): Effect } = effect.catchSomeCause /** * Recovers from some or all of the defects with provided partial function. * * **WARNING**: There is no sensible way to recover from defects. This * method should be used only at the boundary between Effect and an external * system, to transmit information on a defect for diagnostic or explanatory * purposes. * * @since 1.0.0 * @category error handling */ export const catchSomeDefect: { ( pf: (defect: unknown) => Option.Option> ): (self: Effect) => Effect ( self: Effect, pf: (defect: unknown) => Option.Option> ): Effect } = effect.catchSomeDefect /** * Recovers from the specified tagged error. * * @since 1.0.0 * @category error handling */ export const catchTag: { ( k: K, f: (e: Extract) => Effect ): (self: Effect) => Effect, A1 | A> ( self: Effect, k: K, f: (e: Extract) => Effect ): Effect, A | A1> } = effect.catchTag /** * Recovers from the specified tagged errors. * * @since 1.0.0 * @category error handling */ export const catchTags: { < E, Cases extends (E extends { _tag: string } ? { [K in E["_tag"]]+?: ((error: Extract) => Effect) } : {}) >( cases: Cases ): ( self: Effect ) => Effect< | R | { [K in keyof Cases]: Cases[K] extends (...args: Array) => Effect ? R : never }[keyof Cases], | Exclude | { [K in keyof Cases]: Cases[K] extends (...args: Array) => Effect ? E : never }[keyof Cases], | A | { [K in keyof Cases]: Cases[K] extends (...args: Array) => Effect ? A : never }[keyof Cases] > < R, E, A, Cases extends (E extends { _tag: string } ? { [K in E["_tag"]]+?: ((error: Extract) => Effect) } : {}) >( self: Effect, cases: Cases ): Effect< | R | { [K in keyof Cases]: Cases[K] extends (...args: Array) => Effect ? R : never }[keyof Cases], | Exclude | { [K in keyof Cases]: Cases[K] extends (...args: Array) => Effect ? E : never }[keyof Cases], | A | { [K in keyof Cases]: Cases[K] extends (...args: Array) => Effect ? A : never }[keyof Cases] > } = effect.catchTags /** * Returns an effect that succeeds with the cause of failure of this effect, * or `Cause.empty` if the effect did succeed. * * @since 1.0.0 * @category error handling */ export const cause: (self: Effect) => Effect> = effect.cause /** * Returns an effect that ignores errors and runs repeatedly until it * eventually succeeds. * * @since 1.0.0 * @category error handling */ export const eventually: (self: Effect) => Effect = effect.eventually /** * Returns a new effect that ignores the success or failure of this effect. * * @since 1.0.0 * @category error handling */ export const ignore: (self: Effect) => Effect = effect.ignore /** * Returns a new effect that ignores the success or failure of this effect, * but which also logs failures at the Debug level, just in case the failure * turns out to be important. * * @since 1.0.0 * @category error handling */ export const ignoreLogged: (self: Effect) => Effect = effect.ignoreLogged /** * Exposes all parallel errors in a single call. * * @since 1.0.0 * @category error handling */ export const parallelErrors: (self: Effect) => Effect, A> = effect.parallelErrors /** * Exposes the full `Cause` of failure for the specified effect. * * @since 1.0.0 * @category error handling */ export const sandbox: (self: Effect) => Effect, A> = effect.sandbox /** * Retries with the specified retry policy. Retries are done following the * failure of the original `io` (up to a fixed maximum with `once` or `recurs` * for example), so that that `io.retry(Schedule.once)` means "execute `io` * and in case of failure, try again once". * * @since 1.0.0 * @category error handling */ export const retry: { (policy: Schedule.Schedule): (self: Effect) => Effect (self: Effect, policy: Schedule.Schedule): Effect } = _schedule.retry_Effect /** * Retries this effect the specified number of times. * * @since 1.0.0 * @category error handling */ export const retryN: { (n: number): (self: Effect) => Effect (self: Effect, n: number): Effect } = _schedule.retryN_Effect /** * Retries with the specified schedule, until it fails, and then both the * value produced by the schedule together with the last error are passed to * the recovery function. * * @since 1.0.0 * @category error handling */ export const retryOrElse: { ( policy: Schedule.Schedule, orElse: (e: E, out: A1) => Effect ): (self: Effect) => Effect ( self: Effect, policy: Schedule.Schedule, orElse: (e: E, out: A1) => Effect ): Effect } = _schedule.retryOrElse_Effect /** * Retries this effect until its error satisfies the specified predicate. * * @since 1.0.0 * @category error handling */ export const retryUntil: { (f: Refinement): (self: Effect) => Effect (f: Predicate): (self: Effect) => Effect (self: Effect, f: Refinement): Effect (self: Effect, f: Predicate): Effect } = _schedule.retryUntil_Effect /** * Retries this effect until its error satisfies the specified effectful * predicate. * * @since 1.0.0 * @category error handling */ export const retryUntilEffect: { (f: (e: E) => Effect): (self: Effect) => Effect (self: Effect, f: (e: E) => Effect): Effect } = _schedule.retryUntilEffect_Effect /** * Retries this effect while its error satisfies the specified predicate. * * @since 1.0.0 * @category error handling */ export const retryWhile: { (f: Predicate): (self: Effect) => Effect (self: Effect, f: Predicate): Effect } = _schedule.retryWhile_Effect /** * Retries this effect while its error satisfies the specified effectful * predicate. * * @since 1.0.0 * @category error handling */ export const retryWhileEffect: { (f: (e: E) => Effect): (self: Effect) => Effect (self: Effect, f: (e: E) => Effect): Effect } = _schedule.retryWhileEffect_Effect const try_: { (options: { readonly try: LazyArg; readonly catch: (error: unknown) => E }): Effect (evaluate: LazyArg): Effect } = effect.try_ export { /** * Imports a synchronous side-effect into a pure `Effect` value, translating any * thrown exceptions into typed failed effects creating with `Effect.fail`. * * @since 1.0.0 * @category error handling */ try_ as try } /** * Returns an effect whose success is mapped by the specified side effecting * `try` function, translating any promise rejections into typed failed effects * via the `catch` function. * * @since 1.0.0 * @category error handling */ export const tryMap: { ( options: { readonly try: (a: A) => B; readonly catch: (error: unknown) => E1 } ): (self: Effect) => Effect ( self: Effect, options: { readonly try: (a: A) => B; readonly catch: (error: unknown) => E1 } ): Effect } = effect.tryMap /** * Returns an effect whose success is mapped by the specified side effecting * `try` function, translating any promise rejections into typed failed effects * via the `catch` function. * * An optional `AbortSignal` can be provided to allow for interruption of the * wrapped Promise api. * * @since 1.0.0 * @category error handling */ export const tryMapPromise: { ( options: { readonly try: (a: A, signal: AbortSignal) => Promise readonly catch: (error: unknown) => E1 } ): (self: Effect) => Effect ( self: Effect, options: { readonly try: (a: A, signal: AbortSignal) => Promise readonly catch: (error: unknown) => E1 } ): Effect } = effect.tryMapPromise /** * Create an `Effect` that when executed will construct `promise` and wait for * its result, errors will produce failure as `unknown`. * * An optional `AbortSignal` can be provided to allow for interruption of the * wrapped Promise api. * * @since 1.0.0 * @category error handling */ export const tryPromise: { ( options: { readonly try: (signal: AbortSignal) => Promise readonly catch: (error: unknown) => E } ): Effect (try_: (signal: AbortSignal) => Promise): Effect } = effect.tryPromise /** * The inverse operation `sandbox(effect)` * * Terminates with exceptions on the `Left` side of the `Either` error, if it * exists. Otherwise extracts the contained `Effect` * * @since 1.0.0 * @category error handling */ export const unsandbox: (self: Effect, A>) => Effect = effect.unsandbox // ------------------------------------------------------------------------------------- // interuption // ------------------------------------------------------------------------------------- /** * This function checks if any fibers are attempting to interrupt the current * fiber, and if so, performs self-interruption. * * Note that this allows for interruption to occur in uninterruptible regions. * * @returns A new `Effect` value that represents the check for interruption * and the potential self-interruption of the current fiber. * * @since 1.0.0 * @category interruption */ export const allowInterrupt: Effect = effect.allowInterrupt /** * Checks the interrupt status, and produces the effect returned by the * specified callback. * * @since 1.0.0 * @category interruption */ export const checkInterruptible: (f: (isInterruptible: boolean) => Effect) => Effect = core.checkInterruptible /** * Returns an effect whose interruption will be disconnected from the * fiber's own interruption, being performed in the background without * slowing down the fiber's interruption. * * This method is useful to create "fast interrupting" effects. For * example, if you call this on a bracketed effect, then even if the * effect is "stuck" in acquire or release, its interruption will return * immediately, while the acquire / release are performed in the * background. * * See timeout and race for other applications. * * @since 1.0.0 * @category interruption */ export const disconnect: (self: Effect) => Effect = fiberRuntime.disconnect /** * @since 1.0.0 * @category interruption */ export const interrupt: Effect = core.interrupt /** * @since 1.0.0 * @category interruption */ export const interruptWith: (fiberId: FiberId.FiberId) => Effect = core.interruptWith /** * @since 1.0.0 * @category interruption */ export const interruptible: (self: Effect) => Effect = core.interruptible /** * @since 1.0.0 * @category interruption */ export const interruptibleMask: ( f: (restore: (effect: Effect) => Effect) => Effect ) => Effect = core.interruptibleMask /** * @since 1.0.0 * @category interruption */ export const onInterrupt: { ( cleanup: (interruptors: HashSet.HashSet) => Effect ): (self: Effect) => Effect ( self: Effect, cleanup: (interruptors: HashSet.HashSet) => Effect ): Effect } = core.onInterrupt /** * @since 1.0.0 * @category interruption */ export const uninterruptible: (self: Effect) => Effect = core.uninterruptible /** * @since 1.0.0 * @category interruption */ export const uninterruptibleMask: ( f: (restore: (effect: Effect) => Effect) => Effect ) => Effect = core.uninterruptibleMask // ------------------------------------------------------------------------------------- // mapping // ------------------------------------------------------------------------------------- /** * This function maps the success value of an `Effect` value to a specified * constant value. * * @param value - The constant value that the success value of the `Effect` * value will be mapped to. * @param self - The `Effect` value whose success value will be mapped to the * specified constant value. * * @returns A new `Effect` value that represents the mapping of the success * value of the original `Effect` value to the specified constant value. * * @since 1.0.0 * @category mapping */ export const as: { (value: B): (self: Effect) => Effect (self: Effect, value: B): Effect } = core.as /** * This function maps the success value of an `Effect` value to a `Some` value * in an `Option` value. If the original `Effect` value fails, the returned * `Effect` value will also fail. * * @param self - The `Effect` value whose success value will be mapped to a * `Some` value in an `Option` value. * * @returns A new `Effect` value that represents the mapping of the success * value of the original `Effect` value to a `Some` value in an `Option` * value. The returned `Effect` value may fail if the original `Effect` value * fails. * * @category mapping * @since 1.0.0 */ export const asSome: (self: Effect) => Effect> = effect.asSome /** * This function maps the error value of an `Effect` value to a `Some` value * in an `Option` value. If the original `Effect` value succeeds, the returned * `Effect` value will also succeed. * * @param self - The `Effect` value whose error value will be mapped to a * `Some` value in an `Option` value. * * @returns A new `Effect` value that represents the mapping of the error * value of the original `Effect` value to a `Some` value in an `Option` * value. The returned `Effect` value may succeed if the original `Effect` * value succeeds. * * @category mapping * @since 1.0.0 */ export const asSomeError: (self: Effect) => Effect, A> = effect.asSomeError /** * This function maps the success value of an `Effect` value to `void`. If the * original `Effect` value succeeds, the returned `Effect` value will also * succeed. If the original `Effect` value fails, the returned `Effect` value * will fail with the same error. * * @param self - The `Effect` value whose success value will be mapped to `void`. * * @returns A new `Effect` value that represents the mapping of the success * value of the original `Effect` value to `void`. * * @since 1.0.0 * @category mapping */ export const asUnit: (self: Effect) => Effect = core.asUnit /** * Returns an effect that swaps the error/success cases. This allows you to * use all methods on the error channel, possibly before flipping back. * * @since 1.0.0 * @category mapping */ export const flip: (self: Effect) => Effect = core.flip /** * Swaps the error/value parameters, applies the function `f` and flips the * parameters back * * @since 1.0.0 * @category mapping */ export const flipWith: { ( f: (effect: Effect) => Effect ): (self: Effect) => Effect ( self: Effect, f: (effect: Effect) => Effect ): Effect } = effect.flipWith /** * @since 1.0.0 * @category mapping */ export const map: { (f: (a: A) => B): (self: Effect) => Effect (self: Effect, f: (a: A) => B): Effect } = core.map /** * Statefully and effectfully maps over the elements of this chunk to produce * new elements. * * @since 1.0.0 * @category mapping */ export const mapAccum: { ( zero: Z, f: (z: Z, a: A, i: number) => Effect ): (elements: Iterable) => Effect]> ( elements: Iterable, zero: Z, f: (z: Z, a: A, i: number) => Effect ): Effect]> } = effect.mapAccum /** * Returns an effect whose failure and success channels have been mapped by * the specified `onFailure` and `onSuccess` functions. * * @since 1.0.0 * @category mapping */ export const mapBoth: { ( options: { readonly onFailure: (e: E) => E2; readonly onSuccess: (a: A) => A2 } ): (self: Effect) => Effect ( self: Effect, options: { readonly onFailure: (e: E) => E2; readonly onSuccess: (a: A) => A2 } ): Effect } = core.mapBoth /** * Returns an effect with its error channel mapped using the specified function. * * @since 1.0.0 * @category mapping */ export const mapError: { (f: (e: E) => E2): (self: Effect) => Effect (self: Effect, f: (e: E) => E2): Effect } = core.mapError /** * Returns an effect with its full cause of failure mapped using the specified * function. This can be used to transform errors while preserving the * original structure of `Cause`. * * See `absorb`, `sandbox`, `catchAllCause` for other functions for dealing * with defects. * * @since 1.0.0 * @category mapping */ export const mapErrorCause: { (f: (cause: Cause.Cause) => Cause.Cause): (self: Effect) => Effect (self: Effect, f: (cause: Cause.Cause) => Cause.Cause): Effect } = effect.mapErrorCause /** * Returns a new effect where the error channel has been merged into the * success channel to their common combined type. * * @since 1.0.0 * @category mapping */ export const merge: (self: Effect) => Effect = effect.merge /** * Returns a new effect where boolean value of this effect is negated. * * @since 1.0.0 * @category mapping */ export const negate: (self: Effect) => Effect = effect.negate // ------------------------------------------------------------------------------------- // scoping, resources & finalization // ------------------------------------------------------------------------------------- /** * This function constructs a scoped resource from an `acquire` and `release` * `Effect` value. * * If the `acquire` `Effect` value successfully completes execution, then the * `release` `Effect` value will be added to the finalizers associated with the * scope of this `Effect` value, and it is guaranteed to be run when the scope * is closed. * * The `acquire` and `release` `Effect` values will be run uninterruptibly. * Additionally, the `release` `Effect` value may depend on the `Exit` value * specified when the scope is closed. * * @param acquire - The `Effect` value that acquires the resource. * @param release - The `Effect` value that releases the resource. * * @returns A new `Effect` value that represents the scoped resource. * * @since 1.0.0 * @category scoping, resources & finalization */ export const acquireRelease: { ( release: (a: A, exit: Exit.Exit) => Effect ): (acquire: Effect) => Effect ( acquire: Effect, release: (a: A, exit: Exit.Exit) => Effect ): Effect } = fiberRuntime.acquireRelease /** * This function constructs a scoped resource from an `acquire` and `release` * `Effect` value. * * If the `acquire` `Effect` value successfully completes execution, then the * `release` `Effect` value will be added to the finalizers associated with the * scope of this `Effect` value, and it is guaranteed to be run when the scope * is closed. * * The `acquire` `Effect` values will be run interruptibly. * The `release` `Effect` values will be run uninterruptibly. * * Additionally, the `release` `Effect` value may depend on the `Exit` value * specified when the scope is closed. * * @param acquire - The `Effect` value that acquires the resource. * @param release - The `Effect` value that releases the resource. * * @returns A new `Effect` value that represents the scoped resource. * * @since 1.0.0 * @category scoping, resources & finalization */ export const acquireReleaseInterruptible: { ( release: (exit: Exit.Exit) => Effect ): (acquire: Effect) => Effect ( acquire: Effect, release: (exit: Exit.Exit) => Effect ): Effect } = fiberRuntime.acquireReleaseInterruptible /** * This function is used to ensure that an `Effect` value that represents the * acquisition of a resource (for example, opening a file, launching a thread, * etc.) will not be interrupted, and that the resource will always be released * when the `Effect` value completes execution. * * `acquireUseRelease` does the following: * * 1. Ensures that the `Effect` value that acquires the resource will not be * interrupted. Note that acquisition may still fail due to internal * reasons (such as an uncaught exception). * 2. Ensures that the `release` `Effect` value will not be interrupted, * and will be executed as long as the acquisition `Effect` value * successfully acquires the resource. * * During the time period between the acquisition and release of the resource, * the `use` `Effect` value will be executed. * * If the `release` `Effect` value fails, then the entire `Effect` value will * fail, even if the `use` `Effect` value succeeds. If this fail-fast behavior * is not desired, errors produced by the `release` `Effect` value can be caught * and ignored. * * @param acquire - The `Effect` value that acquires the resource. * @param use - The `Effect` value that is executed between the acquisition * and release of the resource. * @param release - The `Effect` value that releases the resource. * * @returns A new `Effect` value that represents the acquisition, use, and * release of the resource. * * @since 1.0.0 * @category scoping, resources & finalization */ export const acquireUseRelease: { ( use: (a: A) => Effect, release: (a: A, exit: Exit.Exit) => Effect ): (acquire: Effect) => Effect ( acquire: Effect, use: (a: A) => Effect, release: (a: A, exit: Exit.Exit) => Effect ): Effect } = core.acquireUseRelease /** * This function adds a finalizer to the scope of the calling `Effect` value. * The finalizer is guaranteed to be run when the scope is closed, and it may * depend on the `Exit` value that the scope is closed with. * * @param finalizer - The finalizer to add to the scope of the calling * `Effect` value. This function must take an `Exit` value as its parameter, * and return a new `Effect` value. * * @returns A new `Effect` value that represents the addition of the finalizer * to the scope of the calling `Effect` value. * * @since 1.0.0 * @category scoping, resources & finalization */ export const addFinalizer: ( finalizer: (exit: Exit.Exit) => Effect ) => Effect = fiberRuntime.addFinalizer /** * Returns an effect that, if this effect _starts_ execution, then the * specified `finalizer` is guaranteed to be executed, whether this effect * succeeds, fails, or is interrupted. * * For use cases that need access to the effect's result, see `onExit`. * * Finalizers offer very powerful guarantees, but they are low-level, and * should generally not be used for releasing resources. For higher-level * logic built on `ensuring`, see the `acquireRelease` family of methods. * * @since 1.0.0 * @category scoping, resources & finalization */ export const ensuring: { (finalizer: Effect): (self: Effect) => Effect (self: Effect, finalizer: Effect): Effect } = fiberRuntime.ensuring /** * Runs the specified effect if this effect fails, providing the error to the * effect if it exists. The provided effect will not be interrupted. * * @since 1.0.0 * @category scoping, resources & finalization */ export const onError: { ( cleanup: (cause: Cause.Cause) => Effect ): (self: Effect) => Effect ( self: Effect, cleanup: (cause: Cause.Cause) => Effect ): Effect } = core.onError /** * Ensures that a cleanup functions runs, whether this effect succeeds, fails, * or is interrupted. * * @since 1.0.0 * @category scoping, resources & finalization */ export const onExit: { ( cleanup: (exit: Exit.Exit) => Effect ): (self: Effect) => Effect ( self: Effect, cleanup: (exit: Exit.Exit) => Effect ): Effect } = core.onExit /** * @since 1.0.0 * @category scoping, resources & finalization */ export const parallelFinalizers: (self: Effect) => Effect = fiberRuntime.parallelFinalizers /** * @since 1.0.0 * @category scoping, resources & finalization */ export const finalizersMask: (strategy: ExecutionStrategy) => ( self: (restore: (self: Effect) => Effect) => Effect ) => Effect = fiberRuntime.finalizersMask /** * Returns a new scoped workflow that runs finalizers added to the scope of * this workflow sequentially in the reverse of the order in which they were * added. Note that finalizers are run sequentially by default so this only * has meaning if used within a scope where finalizers are being run in * parallel. * * @since 1.0.0 * @category scoping, resources & finalization */ export const sequentialFinalizers: (self: Effect) => Effect = fiberRuntime.sequentialFinalizers /** * @since 1.0.0 * @category scoping, resources & finalization */ export const scope: Effect = fiberRuntime.scope /** * Accesses the current scope and uses it to perform the specified effect. * * @since 1.0.0 * @category scoping, resources & finalization */ export const scopeWith: (f: (scope: Scope.Scope) => Effect) => Effect = fiberRuntime.scopeWith /** * Scopes all resources uses in this workflow to the lifetime of the workflow, * ensuring that their finalizers are run as soon as this workflow completes * execution, whether by success, failure, or interruption. * * @since 1.0.0 * @category scoping, resources & finalization */ export const scoped: (effect: Effect) => Effect, E, A> = fiberRuntime.scopedEffect /** * Scopes all resources acquired by `resource` to the lifetime of `use` * without effecting the scope of any resources acquired by `use`. * * @since 1.0.0 * @category scoping, resources & finalization */ export const using: { ( use: (a: A) => Effect ): (self: Effect) => Effect, E2 | E, A2> ( self: Effect, use: (a: A) => Effect ): Effect, E | E2, A2> } = fiberRuntime.using /** * Returns a new scoped workflow that returns the result of this workflow as * well as a finalizer that can be run to close the scope of this workflow. * * @since 1.0.0 * @category scoping, resources & finalization */ export const withEarlyRelease: ( self: Effect ) => Effect, A]> = fiberRuntime.withEarlyRelease // ------------------------------------------------------------------------------------- // supervision & fibers // ------------------------------------------------------------------------------------- /** * Returns a new effect that will not succeed with its value before first * waiting for the end of all child fibers forked by the effect. * * @since 1.0.0 * @category supervision & fibers */ export const awaitAllChildren: (self: Effect) => Effect = circular.awaitAllChildren /** * Returns a new workflow that will not supervise any fibers forked by this * workflow. * * @since 1.0.0 * @category supervision & fibers */ export const daemonChildren: (self: Effect) => Effect = fiberRuntime.daemonChildren /** * Constructs an effect with information about the current `Fiber`. * * @since 1.0.0 * @category supervision & fibers */ export const descriptor: Effect = effect.descriptor /** * Constructs an effect based on information about the current `Fiber`. * * @since 1.0.0 * @category supervision & fibers */ export const descriptorWith: (f: (descriptor: Fiber.Fiber.Descriptor) => Effect) => Effect = effect.descriptorWith /** * Returns a new workflow that executes this one and captures the changes in * `FiberRef` values. * * @since 1.0.0 * @category supervision & fibers */ export const diffFiberRefs: ( self: Effect ) => Effect = effect.diffFiberRefs /** * Acts on the children of this fiber (collected into a single fiber), * guaranteeing the specified callback will be invoked, whether or not this * effect succeeds. * * @since 1.0.0 * @category supervision & fibers */ export const ensuringChild: { ( f: (fiber: Fiber.Fiber>) => Effect ): (self: Effect) => Effect ( self: Effect, f: (fiber: Fiber.Fiber>) => Effect ): Effect } = circular.ensuringChild /** * Acts on the children of this fiber, guaranteeing the specified callback * will be invoked, whether or not this effect succeeds. * * @since 1.0.0 * @category supervision & fibers */ export const ensuringChildren: { ( children: (fibers: ReadonlyArray>) => Effect ): (self: Effect) => Effect ( self: Effect, children: (fibers: ReadonlyArray>) => Effect ): Effect } = circular.ensuringChildren /** * @since 1.0.0 * @category supervision & fibers */ export const fiberId: Effect = core.fiberId /** * @since 1.0.0 * @category supervision & fibers */ export const fiberIdWith: (f: (descriptor: FiberId.Runtime) => Effect) => Effect = core.fiberIdWith /** * Returns an effect that forks this effect into its own separate fiber, * returning the fiber immediately, without waiting for it to begin executing * the effect. * * You can use the `fork` method whenever you want to execute an effect in a * new fiber, concurrently and without "blocking" the fiber executing other * effects. Using fibers can be tricky, so instead of using this method * directly, consider other higher-level methods, such as `raceWith`, * `zipPar`, and so forth. * * The fiber returned by this method has methods to interrupt the fiber and to * wait for it to finish executing the effect. See `Fiber` for more * information. * * Whenever you use this method to launch a new fiber, the new fiber is * attached to the parent fiber's scope. This means when the parent fiber * terminates, the child fiber will be terminated as well, ensuring that no * fibers leak. This behavior is called "auto supervision", and if this * behavior is not desired, you may use the `forkDaemon` or `forkIn` methods. * * @since 1.0.0 * @category supervision & fibers */ export const fork: (self: Effect) => Effect> = fiberRuntime.fork /** * Forks the effect into a new fiber attached to the global scope. Because the * new fiber is attached to the global scope, when the fiber executing the * returned effect terminates, the forked fiber will continue running. * * @since 1.0.0 * @category supervision & fibers */ export const forkDaemon: (self: Effect) => Effect> = fiberRuntime.forkDaemon /** * Returns an effect that forks all of the specified values, and returns a * composite fiber that produces a list of their results, in order. * * @since 1.0.0 * @category supervision & fibers */ export const forkAll: { ( options?: { readonly discard?: false } ): (effects: Iterable>) => Effect>> (options: { readonly discard: true }): (effects: Iterable>) => Effect ( effects: Iterable>, options?: { readonly discard?: false } ): Effect>> (effects: Iterable>, options: { readonly discard: true }): Effect } = circular.forkAll /** * Forks the effect in the specified scope. The fiber will be interrupted * when the scope is closed. * * @since 1.0.0 * @category supervision & fibers */ export const forkIn: { (scope: Scope.Scope): (self: Effect) => Effect> (self: Effect, scope: Scope.Scope): Effect> } = circular.forkIn /** * Forks the fiber in a `Scope`, interrupting it when the scope is closed. * * @since 1.0.0 * @category supervision & fibers */ export const forkScoped: (self: Effect) => Effect> = circular.forkScoped /** * Like fork but handles an error with the provided handler. * * @since 1.0.0 * @category supervision & fibers */ export const forkWithErrorHandler: { ( handler: (e: E) => Effect ): (self: Effect) => Effect> ( self: Effect, handler: (e: E) => Effect ): Effect> } = fiberRuntime.forkWithErrorHandler /** * Creates an `Effect` value that represents the exit value of the specified * fiber. * * @since 1.0.0 * @category supervision & fibers */ export const fromFiber: (fiber: Fiber.Fiber) => Effect = circular.fromFiber /** * Creates an `Effect` value that represents the exit value of the specified * fiber. * * @since 1.0.0 * @category supervision & fibers */ export const fromFiberEffect: (fiber: Effect>) => Effect = circular.fromFiberEffect /** * Returns an effect with the behavior of this one, but where all child fibers * forked in the effect are reported to the specified supervisor. * * @since 1.0.0 * @category supervision & fibers */ export const supervised: { (supervisor: Supervisor.Supervisor): (self: Effect) => Effect (self: Effect, supervisor: Supervisor.Supervisor): Effect } = circular.supervised /** * Transplants specified effects so that when those effects fork other * effects, the forked effects will be governed by the scope of the fiber that * executes this effect. * * This can be used to "graft" deep grandchildren onto a higher-level scope, * effectively extending their lifespans into the parent scope. * * @since 1.0.0 * @category supervision & fibers */ export const transplant: ( f: (grafter: (effect: Effect) => Effect) => Effect ) => Effect = core.transplant /** * @since 1.0.0 * @category supervision & fibers */ export const withConcurrency: { (concurrency: number | "unbounded"): (self: Effect) => Effect (self: Effect, concurrency: number | "unbounded"): Effect } = core.withConcurrency // --------------------------------------------------------------------------------------- // scheduler // --------------------------------------------------------------------------------------- /** * @since 1.0.0 * @category scheduler */ export const setScheduler = (scheduler: Scheduler.Scheduler): Layer.Layer => layer.scopedDiscard( fiberRuntime.fiberRefLocallyScoped(Scheduler.currentScheduler, scheduler) ) /** * Sets the provided scheduler for usage in the wrapped effect * * @since 1.0.0 * @category scheduler */ export const withScheduler: { (scheduler: Scheduler.Scheduler): (self: Effect) => Effect (self: Effect, scheduler: Scheduler.Scheduler): Effect } = Scheduler.withScheduler /** * Sets the scheduling priority used when yielding * * @since 1.0.0 * @category utils */ export const withSchedulingPriority: { (priority: number): (self: Effect) => Effect (self: Effect, priority: number): Effect } = core.withSchedulingPriority /** * Sets the maximum number of operations before yield by the default schedulers * * @since 1.0.0 * @category utils */ export const withMaxOpsBeforeYield: { (priority: number): (self: Effect) => Effect (self: Effect, priority: number): Effect } = core.withMaxOpsBeforeYield // --------------------------------------------------------------------------------------- // clock // --------------------------------------------------------------------------------------- /** * Retreives the `Clock` service from the context * * @since 1.0.0 * @category clock */ export const clock: Effect = effect.clock /** * Retreives the `Clock` service from the context and provides it to the * specified effectful function. * * @since 1.0.0 * @category clock */ export const clockWith: (f: (clock: Clock.Clock) => Effect) => Effect = effect.clockWith /** * @since 1.0.0 * @category clock */ export const setClock = (clock: A): Layer.Layer => layer.scopedDiscard( fiberRuntime.fiberRefLocallyScopedWith(defaultServices.currentServices, Context.add(clockTag, clock)) ) /** * Sets the implementation of the clock service to the specified value and * restores it to its original value when the scope is closed. * * @since 1.0.0 * @category constructors */ export const withClockScoped: (value: A) => Effect = fiberRuntime.withClockScoped /** * Executes the specified workflow with the specified implementation of the * clock service. * * @since 1.0.0 * @category clock */ export const withClock: { (value: A): (effect: Effect) => Effect (effect: Effect, value: A): Effect } = defaultServices.withClock // --------------------------------------------------------------------------------------- // delays & timeouts // --------------------------------------------------------------------------------------- /** * Returns an effect that is delayed from this effect by the specified * `Duration`. * * @since 1.0.0 * @category delays & timeouts */ export const delay: { (duration: Duration.DurationInput): (self: Effect) => Effect (self: Effect, duration: Duration.DurationInput): Effect } = effect.delay /** * Returns an effect that suspends for the specified duration. This method is * asynchronous, and does not actually block the fiber executing the effect. * * @since 1.0.0 * @category delays & timeouts */ export const sleep: (duration: Duration.DurationInput) => Effect = effect.sleep /** * Returns a new effect that executes this one and times the execution. * * @since 1.0.0 * @category delays & timeouts */ export const timed: (self: Effect) => Effect = effect.timed /** * A more powerful variation of `timed` that allows specifying the clock. * * @since 1.0.0 * @category delays & timeouts */ export const timedWith: { ( nanoseconds: Effect ): (self: Effect) => Effect ( self: Effect, nanoseconds: Effect ): Effect } = effect.timedWith /** * Returns an effect that will timeout this effect, returning `None` if the * timeout elapses before the effect has produced a value; and returning * `Some` of the produced value otherwise. * * If the timeout elapses without producing a value, the running effect will * be safely interrupted. * * WARNING: The effect returned by this method will not itself return until * the underlying effect is actually interrupted. This leads to more * predictable resource utilization. If early return is desired, then instead * of using `effect.timeout(d)`, use `effect.disconnect.timeout(d)`, which * first disconnects the effect's interruption signal before performing the * timeout, resulting in earliest possible return, before an underlying effect * has been successfully interrupted. * * @since 1.0.0 * @category delays & timeouts */ export const timeout: { (duration: Duration.DurationInput): (self: Effect) => Effect> (self: Effect, duration: Duration.DurationInput): Effect> } = circular.timeout /** * The same as `timeout`, but instead of producing a `None` in the event of * timeout, it will produce the specified error. * * @since 1.0.0 * @category delays & timeouts */ export const timeoutFail: { (options: { readonly onTimeout: LazyArg readonly duration: Duration.DurationInput }): (self: Effect) => Effect (self: Effect, options: { readonly onTimeout: LazyArg readonly duration: Duration.DurationInput }): Effect } = circular.timeoutFail /** * The same as `timeout`, but instead of producing a `None` in the event of * timeout, it will produce the specified failure. * * @since 1.0.0 * @category delays & timeouts */ export const timeoutFailCause: { ( options: { readonly onTimeout: LazyArg> readonly duration: Duration.DurationInput } ): (self: Effect) => Effect ( self: Effect, options: { readonly onTimeout: LazyArg> readonly duration: Duration.DurationInput } ): Effect } = circular.timeoutFailCause /** * Returns an effect that will timeout this effect, returning either the * default value if the timeout elapses before the effect has produced a * value or returning the result of applying the function `onSuccess` to the * success value of the effect. * * If the timeout elapses without producing a value, the running effect will * be safely interrupted. * * @since 1.0.0 * @category delays & timeouts */ export const timeoutTo: { ( options: { readonly onTimeout: LazyArg readonly onSuccess: (a: A) => B readonly duration: Duration.DurationInput } ): (self: Effect) => Effect ( self: Effect, options: { readonly onTimeout: LazyArg readonly onSuccess: (a: A) => B readonly duration: Duration.DurationInput } ): Effect } = circular.timeoutTo // ------------------------------------------------------------------------------------- // config // ------------------------------------------------------------------------------------- /** * Uses the default config provider to load the specified config, or fail with * an error of type Config.Error. * * @since 1.0.0 * @category config */ export const config: (config: Config) => Effect = defaultServices.config /** * Retrieves the default config provider, and passes it to the specified * function, which may return an effect that uses the provider to perform some * work or compute some value. * * @since 1.0.0 * @category config */ export const configProviderWith: (f: (configProvider: ConfigProvider) => Effect) => Effect = defaultServices.configProviderWith /** * Sets the current `ConfigProvider`. * * @since 1.0.0 * @category config */ export const setConfigProvider: (configProvider: ConfigProvider) => Layer.Layer = circularLayer.setConfigProvider /** * Executes the specified workflow with the specified configuration provider. * * @since 1.0.0 * @category config */ export const withConfigProvider: { (value: ConfigProvider): (effect: Effect) => Effect (effect: Effect, value: ConfigProvider): Effect } = defaultServices.withConfigProvider /** * Sets the configuration provider to the specified value and restores it to its original value * when the scope is closed. * * @since 1.0.0 * @category config */ export const withConfigProviderScoped: (value: ConfigProvider) => Effect = fiberRuntime.withConfigProviderScoped // ------------------------------------------------------------------------------------- // context // ------------------------------------------------------------------------------------- /** * @since 1.0.0 * @category context */ export const context: () => Effect> = core.context /** * Accesses the context of the effect. * * @since 1.0.0 * @category context */ export const contextWith: (f: (context: Context.Context) => A) => Effect = effect.contextWith /** * Effectually accesses the context of the effect. * * @since 1.0.0 * @category context */ export const contextWithEffect: ( f: (context: Context.Context) => Effect ) => Effect = core.contextWithEffect /** * Provides some of the context required to run this effect, * leaving the remainder `R0`. * * @since 1.0.0 * @category context */ export const mapInputContext: { (f: (context: Context.Context) => Context.Context): (self: Effect) => Effect (self: Effect, f: (context: Context.Context) => Context.Context): Effect } = core.mapInputContext /** * Splits the context into two parts, providing one part using the * specified layer/context/runtime and leaving the remainder `R0`. * * @since 1.0.0 * @category context */ export const provide: { ( layer: Layer.Layer ): (self: Effect) => Effect, E2 | E, A> (context: Context.Context): (self: Effect) => Effect, E, A> (runtime: Runtime.Runtime): (self: Effect) => Effect, E, A> (self: Effect, layer: Layer.Layer): Effect, E | E2, A> (self: Effect, context: Context.Context): Effect, E, A> (self: Effect, runtime: Runtime.Runtime): Effect, E, A> } = layer.effect_provide /** * Provides the effect with the single service it requires. If the effect * requires more than one service use `provideContext` instead. * * @since 1.0.0 * @category context */ export const provideService: { >( tag: T, service: Context.Tag.Service ): (self: Effect) => Effect>, E, A> >( self: Effect, tag: T, service: Context.Tag.Service ): Effect>, E, A> } = effect.provideService /** * Provides the effect with the single service it requires. If the effect * requires more than one service use `provideContext` instead. * * @since 1.0.0 * @category context */ export const provideServiceEffect: { , R1, E1>( tag: T, effect: Effect> ): (self: Effect) => Effect>, E1 | E, A> , R1, E1>( self: Effect, tag: T, effect: Effect> ): Effect>, E | E1, A> } = effect.provideServiceEffect /** * @since 1.0.0 * @category context */ export const serviceFunction: , Args extends Array, A>( service: T, f: (_: Context.Tag.Service) => (...args: Args) => A ) => (...args: Args) => Effect, never, A> = effect.serviceFunction /** * @since 1.0.0 * @category context */ export const serviceFunctionEffect: , Args extends Array, R, E, A>( service: T, f: (_: Context.Tag.Service) => (...args: Args) => Effect ) => (...args: Args) => Effect, E, A> = effect.serviceFunctionEffect /** * @since 1.0.0 * @category context */ export const serviceFunctions: ( tag: Context.Tag ) => { [k in { [k in keyof S]: S[k] extends (...args: Array) => Effect ? k : never }[keyof S]]: S[k] extends (...args: infer Args) => Effect ? (...args: Args) => Effect : never } = effect.serviceFunctions /** * @since 1.0.0 * @category context */ export const serviceConstants: ( tag: Context.Tag ) => { [k in { [k in keyof S]: S[k] extends Effect ? k : never }[keyof S]]: S[k] extends Effect ? Effect : never } = effect.serviceConstants /** * @since 1.0.0 * @category context */ export const serviceMembers: (tag: Context.Tag) => { functions: { [k in { [k in keyof S]: S[k] extends (...args: Array) => Effect ? k : never }[keyof S]]: S[k] extends (...args: infer Args) => Effect ? (...args: Args) => Effect : never } constants: { [k in { [k in keyof S]: S[k] extends Effect ? k : never }[keyof S]]: S[k] extends Effect ? Effect : never } } = effect.serviceMembers /** * @since 1.0.0 * @category context */ export const serviceOption: (tag: Context.Tag) => Effect> = (tag) => contextWith((_: Context.Context) => Context.getOption(_, tag)) /** * Updates the service with the required service entry. * * @since 1.0.0 * @category context */ export const updateService: { >( tag: T, f: (service: Context.Tag.Service) => Context.Tag.Service ): (self: Effect) => Effect, E, A> >( self: Effect, tag: T, f: (service: Context.Tag.Service) => Context.Tag.Service ): Effect, E, A> } = effect.updateService // ------------------------------------------------------------------------------------- // do notation // ------------------------------------------------------------------------------------- /** * @since 1.0.0 * @category do notation */ export const Do: Effect = effect.Do /** * Binds an effectful value in a `do` scope * * @since 1.0.0 * @category do notation */ export const bind: { ( tag: Exclude, f: (_: K) => Effect ): (self: Effect) => Effect> ( self: Effect, tag: Exclude, f: (_: K) => Effect ): Effect> } = effect.bind /** * @category do notation * @since 1.0.0 */ export const bindTo: { (tag: N): (self: Effect) => Effect> (self: Effect, tag: N): Effect> } = effect.bindTo const let_: { ( tag: Exclude, f: (_: K) => A ): (self: Effect) => Effect> ( self: Effect, tag: Exclude, f: (_: K) => A ): Effect> } = effect.bindValue export { /** * Like bind for values * * @since 1.0.0 * @category do notation */ let_ as let } // ------------------------------------------------------------------------------------- // conversions // ------------------------------------------------------------------------------------- /** * Returns an effect whose failure and success have been lifted into an * `Either`. The resulting effect cannot fail, because the failure case has * been exposed as part of the `Either` success case. * * This method is useful for recovering from effects that may fail. * * The error parameter of the returned `Effect` is `never`, since it is * guaranteed the effect does not model failure. * * @since 1.0.0 * @category conversions */ export const either: (self: Effect) => Effect> = core.either /** * @since 1.0.0 * @category conversions */ export const exit: (self: Effect) => Effect> = core.exit /** * @since 1.0.0 * @category conversions */ export const intoDeferred: { (deferred: Deferred.Deferred): (self: Effect) => Effect (self: Effect, deferred: Deferred.Deferred): Effect } = core.intoDeferred /** * Executes this effect, skipping the error but returning optionally the * success. * * @since 1.0.0 * @category conversions */ export const option: (self: Effect) => Effect> = effect.option // ------------------------------------------------------------------------------------- // filtering & conditionals // ------------------------------------------------------------------------------------- const if_: { ( options: { readonly onTrue: Effect; readonly onFalse: Effect } ): (self: boolean | Effect) => Effect ( self: boolean, options: { readonly onTrue: Effect; readonly onFalse: Effect } ): Effect ( self: Effect, options: { readonly onTrue: Effect; readonly onFalse: Effect } ): Effect } = core.if_ export { /** * Runs `onTrue` if the result of `self` is `true` and `onFalse` otherwise. * * @since 1.0.0 * @category filtering & conditionals */ if_ as if } /** * Filter the specified effect with the provided function, dying with specified * defect if the predicate fails. * * @since 1.0.0 * @category filtering & conditionals */ export const filterOrDie: { ( filter: Refinement, orDieWith: (a: X) => unknown ): (self: Effect) => Effect ( filter: Predicate, orDieWith: (a: Y) => unknown ): (self: Effect) => Effect ( self: Effect, filter: Refinement, orDieWith: (a: X) => unknown ): Effect ( self: Effect, filter: Predicate, orDieWith: (a: Y) => unknown ): Effect } = effect.filterOrDie /** * Filter the specified effect with the provided function, dying with specified * message if the predicate fails. * * @since 1.0.0 * @category filtering & conditionals */ export const filterOrDieMessage: { (filter: Refinement, message: string): (self: Effect) => Effect (filter: Predicate, message: string): (self: Effect) => Effect (self: Effect, filter: Refinement, message: string): Effect (self: Effect, filter: Predicate, message: string): Effect } = effect.filterOrDieMessage /** * Filters the specified effect with the provided function returning the value * of the effect if it is successful, otherwise returns the value of `orElse`. * * @since 1.0.0 * @category filtering & conditionals */ export const filterOrElse: { ( filter: Refinement, orElse: (a: X) => Effect ): (self: Effect) => Effect ( filter: Predicate, orElse: (a: Y) => Effect ): (self: Effect) => Effect ( self: Effect, filter: Refinement, orElse: (a: X) => Effect ): Effect ( self: Effect, filter: Predicate, orElse: (a: Y) => Effect ): Effect } = effect.filterOrElse /** * Filter the specified effect with the provided function, failing with specified * error if the predicate fails. * * @since 1.0.0 * @category filtering & conditionals */ export const filterOrFail: { ( filter: Refinement, orFailWith: (a: X) => E2 ): (self: Effect) => Effect ( filter: Predicate, orFailWith: (a: Y) => E2 ): (self: Effect) => Effect ( self: Effect, filter: Refinement, orFailWith: (a: X) => E2 ): Effect ( self: Effect, filter: Predicate, orFailWith: (a: Y) => E2 ): Effect } = effect.filterOrFail /** * The moral equivalent of `if (!p) exp`. * * @since 1.0.0 * @category filtering & conditionals */ export const unless: { (predicate: LazyArg): (self: Effect) => Effect> (self: Effect, predicate: LazyArg): Effect> } = effect.unless /** * The moral equivalent of `if (!p) exp` when `p` has side-effects. * * @since 1.0.0 * @category filtering & conditionals */ export const unlessEffect: { ( predicate: Effect ): ( self: Effect ) => Effect> ( self: Effect, predicate: Effect ): Effect> } = effect.unlessEffect /** * The moral equivalent of `if (p) exp`. * * @since 1.0.0 * @category filtering & conditionals */ export const when: { (predicate: LazyArg): (self: Effect) => Effect> (self: Effect, predicate: LazyArg): Effect> } = effect.when /** * @since 1.0.0 * @category filtering & conditionals */ export const whenEffect: { ( predicate: Effect ): ( effect: Effect ) => Effect> ( self: Effect, predicate: Effect ): Effect> } = core.whenEffect /** * Executes this workflow when value of the specified `FiberRef` satisfies the * predicate. * * @since 1.0.0 * @category filtering & conditionals */ export const whenFiberRef: { ( fiberRef: FiberRef.FiberRef, predicate: Predicate ): ( self: Effect ) => Effect]> ( self: Effect, fiberRef: FiberRef.FiberRef, predicate: Predicate ): Effect]> } = effect.whenFiberRef /** * Executes this workflow when the value of the `Ref` satisfies the predicate. * * @since 1.0.0 * @category filtering & conditionals */ export const whenRef: { ( ref: Ref.Ref, predicate: Predicate ): ( self: Effect ) => Effect]> ( self: Effect, ref: Ref.Ref, predicate: Predicate ): Effect]> } = effect.whenRef // ------------------------------------------------------------------------------------- // sequencing // ------------------------------------------------------------------------------------- /** * This function is a pipeable operator that maps over an `Effect` value, * flattening the result of the mapping function into a new `Effect` value. * * @param f - The mapping function to apply to the `Effect` value. * This function must return another `Effect` value. * * @returns A new `Effect` value that is the result of flattening the * mapped `Effect` value. * * @since 1.0.0 * @category sequencing */ export const flatMap: { (f: (a: A) => Effect): (self: Effect) => Effect (self: Effect, f: (a: A) => Effect): Effect } = core.flatMap /** * @since 1.0.0 * @category sequencing */ export const flatten: (self: Effect>) => Effect = core.flatten /** * Returns an effect that races this effect with all the specified effects, * yielding the value of the first effect to succeed with a value. Losers of * the race will be interrupted immediately * * @since 1.0.0 * @category sequencing */ export const raceAll: (effects: Iterable>) => Effect = fiberRuntime.raceAll /** * Returns an effect that races this effect with the specified effect, * returning the first successful `A` from the faster side. If one effect * succeeds, the other will be interrupted. If neither succeeds, then the * effect will fail with some error. * * @since 1.0.0 * @category sequencing */ export const race: { (that: Effect): (self: Effect) => Effect (self: Effect, that: Effect): Effect } = fiberRuntime.race /** * Returns an effect that races this effect with the specified effect, * yielding the first result to complete, whether by success or failure. If * neither effect completes, then the composed effect will not complete. * * WARNING: The raced effect will safely interrupt the "loser", but will not * resume until the loser has been cleanly terminated. If early return is * desired, then instead of performing `l raceFirst r`, perform * `l.disconnect raceFirst r.disconnect`, which disconnects left and right * interrupt signal, allowing a fast return, with interruption performed * in the background. * * @since 1.0.0 * @category sequencing */ export const raceFirst: { (that: Effect): (self: Effect) => Effect (self: Effect, that: Effect): Effect } = circular.raceFirst /** * Returns an effect that races this effect with the specified effect, calling * the specified finisher as soon as one result or the other has been computed. * * @since 1.0.0 * @category sequencing */ export const raceWith: { ( other: Effect, options: { readonly onSelfDone: (exit: Exit.Exit, fiber: Fiber.Fiber) => Effect readonly onOtherDone: (exit: Exit.Exit, fiber: Fiber.Fiber) => Effect } ): (self: Effect) => Effect ( self: Effect, other: Effect, options: { readonly onSelfDone: (exit: Exit.Exit, fiber: Fiber.Fiber) => Effect readonly onOtherDone: (exit: Exit.Exit, fiber: Fiber.Fiber) => Effect } ): Effect } = fiberRuntime.raceWith /** * Summarizes a effect by computing some value before and after execution, and * then combining the values to produce a summary, together with the result of * execution. * * @since 1.0.0 * @category sequencing */ export const summarized: { ( summary: Effect, f: (start: B, end: B) => C ): (self: Effect) => Effect ( self: Effect, summary: Effect, f: (start: B, end: B) => C ): Effect } = effect.summarized /** * @since 1.0.0 * @category sequencing */ export const tap: { ( f: (a: X) => Effect ): (self: Effect) => Effect (self: Effect, f: (a: X) => Effect): Effect } = core.tap /** * Returns an effect that effectfully "peeks" at the failure or success of * this effect. * * @since 1.0.0 * @category sequencing */ export const tapBoth: { ( options: { readonly onFailure: (e: XE) => Effect; readonly onSuccess: (a: XA) => Effect } ): (self: Effect) => Effect ( self: Effect, options: { readonly onFailure: (e: XE) => Effect; readonly onSuccess: (a: XA) => Effect } ): Effect } = effect.tapBoth /** * Returns an effect that effectually "peeks" at the defect of this effect. * * @since 1.0.0 * @category sequencing */ export const tapDefect: { ( f: (cause: Cause.Cause) => Effect ): (self: Effect) => Effect ( self: Effect, f: (cause: Cause.Cause) => Effect ): Effect } = effect.tapDefect /** * Returns an effect that effectfully "peeks" at the failure of this effect. * * @since 1.0.0 * @category sequencing */ export const tapError: { ( f: (e: XE) => Effect ): (self: Effect) => Effect (self: Effect, f: (e: XE) => Effect): Effect } = effect.tapError /** * Returns an effect that effectfully "peeks" at the specific tagged failure of this effect. * * @since 1.0.0 * @category sequencing */ export const tapErrorTag: { ( k: K, f: (e: Extract) => Effect ): (self: Effect) => Effect ( self: Effect, k: K, f: (e: Extract) => Effect ): Effect } = effect.tapErrorTag /** * Returns an effect that effectually "peeks" at the cause of the failure of * this effect. * * @since 1.0.0 * @category sequencing */ export const tapErrorCause: { ( f: (cause: Cause.Cause) => Effect ): (self: Effect) => Effect ( self: Effect, f: (cause: Cause.Cause) => Effect ): Effect } = effect.tapErrorCause // ------------------------------------------------------------------------------------- // repetition / recursion // ------------------------------------------------------------------------------------- /** * Repeats this effect forever (until the first error). * * @since 1.0.0 * @category repetition / recursion */ export const forever: (self: Effect) => Effect = effect.forever /** * Iterates with the specified effectual function. The moral equivalent of: * * ```ts * let s = initial * * while (cont(s)) { * s = body(s) * } * * return s * ``` * * @since 1.0.0 * @category repetition / recursion */ export const iterate: ( initial: Z, options: { readonly while: (z: Z) => boolean readonly body: (z: Z) => Effect } ) => Effect = effect.iterate /** * Loops with the specified effectual function, collecting the results into a * list. The moral equivalent of: * * ```ts * let s = initial * let as = [] as readonly A[] * * while (cont(s)) { * as = [body(s), ...as] * s = inc(s) * } * * A.reverse(as) * ``` * * @since 1.0.0 * @category repetition / recursion */ export const loop: { ( initial: Z, options: { readonly while: (z: Z) => boolean readonly step: (z: Z) => Z readonly body: (z: Z) => Effect readonly discard?: false } ): Effect> ( initial: Z, options: { readonly while: (z: Z) => boolean readonly step: (z: Z) => Z readonly body: (z: Z) => Effect readonly discard: true } ): Effect } = effect.loop /** * Returns a new effect that repeats this effect according to the specified * schedule or until the first failure. Scheduled recurrences are in addition * to the first execution, so that `io.repeat(Schedule.once)` yields an effect * that executes `io`, and then if that succeeds, executes `io` an additional * time. * * @since 1.0.0 * @category repetition / recursion */ export const repeat: { ( schedule: Schedule.Schedule ): (self: Effect) => Effect (self: Effect, schedule: Schedule.Schedule): Effect } = _schedule.repeat_Effect /** * Returns a new effect that repeats this effect the specified number of times * or until the first failure. Repeats are in addition to the first execution, * so that `io.repeatN(1)` yields an effect that executes `io`, and then if * that succeeds, executes `io` an additional time. * * @since 1.0.0 * @category repetition / recursion */ export const repeatN: { (n: number): (self: Effect) => Effect (self: Effect, n: number): Effect } = effect.repeatN /** * Returns a new effect that repeats this effect according to the specified * schedule or until the first failure, at which point, the failure value and * schedule output are passed to the specified handler. * * Scheduled recurrences are in addition to the first execution, so that * `pipe(effect, Effect.repeat(Schedule.once()))` yields an effect that executes * `effect`, and then if that succeeds, executes `effect` an additional time. * * @since 1.0.0 * @category repetition / recursion */ export const repeatOrElse: { ( schedule: Schedule.Schedule, orElse: (error: E, option: Option.Option) => Effect ): (self: Effect) => Effect ( self: Effect, schedule: Schedule.Schedule, orElse: (error: E, option: Option.Option) => Effect ): Effect } = _schedule.repeatOrElse_Effect /** * Repeats this effect until its value satisfies the specified predicate or * until the first failure. * * @since 1.0.0 * @category repetition / recursion */ export const repeatUntil: { (f: Refinement): (self: Effect) => Effect (f: Predicate): (self: Effect) => Effect (self: Effect, f: Predicate): Effect (self: Effect, f: Predicate): Effect } = _schedule.repeatUntil_Effect /** * Repeats this effect until its value satisfies the specified effectful * predicate or until the first failure. * * @since 1.0.0 * @category repetition / recursion */ export const repeatUntilEffect: { (f: (a: A) => Effect): (self: Effect) => Effect (self: Effect, f: (a: A) => Effect): Effect } = _schedule.repeatUntilEffect_Effect /** * Repeats this effect while its value satisfies the specified effectful * predicate or until the first failure. * * @since 1.0.0 * @category repetition / recursion */ export const repeatWhile: { (f: Predicate): (self: Effect) => Effect (self: Effect, f: Predicate): Effect } = _schedule.repeatWhile_Effect /** * Repeats this effect while its value satisfies the specified effectful * predicate or until the first failure. * * @since 1.0.0 * @category repetition / recursion */ export const repeatWhileEffect: { (f: (a: A) => Effect): (self: Effect) => Effect (self: Effect, f: (a: A) => Effect): Effect } = _schedule.repeatWhileEffect_Effect /** * Runs this effect according to the specified schedule. * * See `scheduleFrom` for a variant that allows the schedule's decision to * depend on the result of this effect. * * @since 1.0.0 * @category repetition / recursion */ export const schedule: { (schedule: Schedule.Schedule): (self: Effect) => Effect (self: Effect, schedule: Schedule.Schedule): Effect } = _schedule.schedule_Effect /** * Runs this effect according to the specified schedule in a new fiber * attached to the current scope. * * @since 1.0.0 * @category repetition / recursion */ export const scheduleForked: { ( schedule: Schedule.Schedule ): (self: Effect) => Effect> ( self: Effect, schedule: Schedule.Schedule ): Effect> } = circular.scheduleForked /** * Runs this effect according to the specified schedule starting from the * specified input value. * * @since 1.0.0 * @category repetition / recursion */ export const scheduleFrom: { ( initial: In, schedule: Schedule.Schedule ): (self: Effect) => Effect ( self: Effect, initial: In, schedule: Schedule.Schedule ): Effect } = _schedule.scheduleFrom_Effect /** * @since 1.0.0 * @category repetition / recursion */ export const whileLoop: ( options: { readonly while: LazyArg readonly body: LazyArg> readonly step: (a: A) => void } ) => Effect = core.whileLoop // ------------------------------------------------------------------------------------- // fiber refs // ------------------------------------------------------------------------------------- /** * Returns a collection of all `FiberRef` values for the fiber running this * effect. * * @since 1.0.0 * @category fiber refs */ export const getFiberRefs: Effect = effect.fiberRefs /** * Inherits values from all `FiberRef` instances into current fiber. * * @since 1.0.0 * @category fiber refs */ export const inheritFiberRefs: (childFiberRefs: FiberRefs.FiberRefs) => Effect = effect.inheritFiberRefs /** * @since 1.0.0 * @category fiber refs */ export const locally: { (self: FiberRef.FiberRef, value: A): (use: Effect) => Effect (use: Effect, self: FiberRef.FiberRef, value: A): Effect } = core.fiberRefLocally /** * @since 1.0.0 * @category fiber refs */ export const locallyWith: { (self: FiberRef.FiberRef, f: (a: A) => A): (use: Effect) => Effect (use: Effect, self: FiberRef.FiberRef, f: (a: A) => A): Effect } = core.fiberRefLocallyWith /** * @since 1.0.0 * @category fiber refs */ export const locallyScoped: { (value: A): (self: FiberRef.FiberRef) => Effect (self: FiberRef.FiberRef, value: A): Effect } = fiberRuntime.fiberRefLocallyScoped /** * @since 1.0.0 * @category fiber refs */ export const locallyScopedWith: { (f: (a: A) => A): (self: FiberRef.FiberRef) => Effect (self: FiberRef.FiberRef, f: (a: A) => A): Effect } = fiberRuntime.fiberRefLocallyScopedWith /** * Applies the specified changes to the `FiberRef` values for the fiber * running this workflow. * * @since 1.0.0 * @category fiber refs */ export const patchFiberRefs: (patch: FiberRefsPatch.FiberRefsPatch) => Effect = effect.patchFiberRefs /** * Sets the `FiberRef` values for the fiber running this effect to the values * in the specified collection of `FiberRef` values. * * @since 1.0.0 * @category fiber refs */ export const setFiberRefs: (fiberRefs: FiberRefs.FiberRefs) => Effect = effect.setFiberRefs /** * Updates the `FiberRef` values for the fiber running this effect using the * specified function. * * @since 1.0.0 * @category fiber refs */ export const updateFiberRefs: ( f: (fiberId: FiberId.Runtime, fiberRefs: FiberRefs.FiberRefs) => FiberRefs.FiberRefs ) => Effect = effect.updateFiberRefs // ------------------------------------------------------------------------------------- // getters & folding // ------------------------------------------------------------------------------------- /** * Returns `true` if this effect is a failure, `false` otherwise. * * @since 1.0.0 * @category getters & folding */ export const isFailure: (self: Effect) => Effect = effect.isFailure /** * Returns `true` if this effect is a success, `false` otherwise. * * @since 1.0.0 * @category getters & folding */ export const isSuccess: (self: Effect) => Effect = effect.isSuccess /** * Folds over the failure value or the success value to yield an effect that * does not fail, but succeeds with the value returned by the left or right * function passed to `match`. * * @since 1.0.0 * @category getters & folding */ export const match: { ( options: { readonly onFailure: (error: E) => A2 readonly onSuccess: (value: A) => A3 } ): (self: Effect) => Effect ( self: Effect, options: { readonly onFailure: (error: E) => A2 readonly onSuccess: (value: A) => A3 } ): Effect } = effect.match /** * @since 1.0.0 * @category getters & folding */ export const matchCause: { ( options: { readonly onFailure: (cause: Cause.Cause) => A2 readonly onSuccess: (a: A) => A3 } ): (self: Effect) => Effect ( self: Effect, options: { readonly onFailure: (cause: Cause.Cause) => A2 readonly onSuccess: (a: A) => A3 } ): Effect } = core.matchCause /** * @since 1.0.0 * @category getters & folding */ export const matchCauseEffect: { ( options: { readonly onFailure: (cause: Cause.Cause) => Effect readonly onSuccess: (a: A) => Effect } ): (self: Effect) => Effect ( self: Effect, options: { readonly onFailure: (cause: Cause.Cause) => Effect readonly onSuccess: (a: A) => Effect } ): Effect } = core.matchCauseEffect /** * @since 1.0.0 * @category getters & folding */ export const matchEffect: { ( options: { readonly onFailure: (e: E) => Effect readonly onSuccess: (a: A) => Effect } ): (self: Effect) => Effect ( self: Effect, options: { readonly onFailure: (e: E) => Effect readonly onSuccess: (a: A) => Effect } ): Effect } = core.matchEffect // ------------------------------------------------------------------------------------- // logging // ------------------------------------------------------------------------------------- /** * Logs the specified message or cause at the current log level. * * You can set the current log level using `FiberRef.currentLogLevel`. * * @since 1.0.0 * @category logging */ export const log: ( messageOrCause: A, supplementary?: A extends Cause.Cause ? unknown : Cause.Cause ) => Effect = effect.log /** * Logs the specified message or cause at the Trace log level. * * @since 1.0.0 * @category logging */ export const logTrace: ( messageOrCause: A, supplementary?: A extends Cause.Cause ? unknown : Cause.Cause ) => Effect = effect.logTrace /** * Logs the specified message or cause at the Debug log level. * * @since 1.0.0 * @category logging */ export const logDebug: ( messageOrCause: A, supplementary?: A extends Cause.Cause ? unknown : Cause.Cause ) => Effect = effect.logDebug /** * Logs the specified message or cause at the Info log level. * * @since 1.0.0 * @category logging */ export const logInfo: ( messageOrCause: A, supplementary?: A extends Cause.Cause ? unknown : Cause.Cause ) => Effect = effect.logInfo /** * Logs the specified message or cause at the Warning log level. * * @since 1.0.0 * @category logging */ export const logWarning: ( messageOrCause: A, supplementary?: A extends Cause.Cause ? unknown : Cause.Cause ) => Effect = effect.logWarning /** * Logs the specified message or cause at the Error log level. * * @since 1.0.0 * @category logging */ export const logError: ( messageOrCause: A, supplementary?: A extends Cause.Cause ? unknown : Cause.Cause ) => Effect = effect.logError /** * Logs the specified message or cause at the Fatal log level. * * @since 1.0.0 * @category logging */ export const logFatal: ( messageOrCause: A, supplementary?: A extends Cause.Cause ? unknown : Cause.Cause ) => Effect = effect.logFatal /** * Adjusts the label for the current logging span. * * @since 1.0.0 * @category logging */ export const withLogSpan: { (label: string): (effect: Effect) => Effect (effect: Effect, label: string): Effect } = effect.withLogSpan /** * Annotates each log in this effect with the specified log annotation. * * @since 1.0.0 * @category logging */ export const annotateLogs: { (key: string, value: Logger.AnnotationValue): (effect: Effect) => Effect (values: Record): (effect: Effect) => Effect (effect: Effect, key: string, value: Logger.AnnotationValue): Effect (effect: Effect, values: Record): Effect } = effect.annotateLogs /** * Retrieves the log annotations associated with the current scope. * * @since 1.0.0 * @category logging */ export const logAnnotations: Effect> = effect.logAnnotations /** * Decides wether child fibers will report or not unhandled errors via the logger * * @since 1.0.0 * @category logging */ export const withUnhandledErrorLogLevel: { (level: Option.Option): (self: Effect) => Effect (self: Effect, level: Option.Option): Effect } = core.withUnhandledErrorLogLevel /** * @since 1.0.0 * @category logging */ export const setUnhandledErrorLogLevel = (level: Option.Option): Layer.Layer => layer.scopedDiscard( fiberRuntime.fiberRefLocallyScoped(core.currentUnhandledErrorLogLevel, level) ) // ------------------------------------------------------------------------------------- // alternatives // ------------------------------------------------------------------------------------- /** * Translates effect failure into death of the fiber, making all failures * unchecked and not a part of the type of the effect. * * @since 1.0.0 * @category alternatives */ export const orDie: (self: Effect) => Effect = core.orDie /** * Keeps none of the errors, and terminates the fiber with them, using the * specified function to convert the `E` into a `Throwable`. * * @since 1.0.0 * @category alternatives */ export const orDieWith: { (f: (error: E) => unknown): (self: Effect) => Effect (self: Effect, f: (error: E) => unknown): Effect } = core.orDieWith /** * Executes this effect and returns its value, if it succeeds, but otherwise * executes the specified effect. * * @since 1.0.0 * @category alternatives */ export const orElse: { (that: LazyArg>): (self: Effect) => Effect (self: Effect, that: LazyArg>): Effect } = core.orElse /** * Executes this effect and returns its value, if it succeeds, but otherwise * fails with the specified error. * * @since 1.0.0 * @category alternatives */ export const orElseFail: { (evaluate: LazyArg): (self: Effect) => Effect (self: Effect, evaluate: LazyArg): Effect } = effect.orElseFail /** * Executes this effect and returns its value, if it succeeds, but * otherwise succeeds with the specified value. * * @since 1.0.0 * @category alternatives */ export const orElseSucceed: { (evaluate: LazyArg): (self: Effect) => Effect (self: Effect, evaluate: LazyArg): Effect } = effect.orElseSucceed // ------------------------------------------------------------------------------------- // random // ------------------------------------------------------------------------------------- /** * Retreives the `Random` service from the context. * * @since 1.0.0 * @category random */ export const random: Effect = effect.random /** * Retreives the `Random` service from the context and uses it to run the * specified workflow. * * @since 1.0.0 * @category random */ export const randomWith: (f: (random: Random.Random) => Effect) => Effect = defaultServices.randomWith // ------------------------------------------------------------------------------------- // runtime // ------------------------------------------------------------------------------------- /** * Returns an effect that accesses the runtime, which can be used to * (unsafely) execute tasks. This is useful for integration with legacy code * that must call back into Effect code. * * @since 1.0.0 * @category runtime */ export const runtime: () => Effect> = _runtime.runtime /** * Retrieves an effect that succeeds with the current runtime flags, which * govern behavior and features of the runtime system. * * @since 1.0.0 * @category runtime */ export const getRuntimeFlags: Effect = core.runtimeFlags /** * @since 1.0.0 * @category runtime */ export const patchRuntimeFlags: (patch: RuntimeFlagsPatch.RuntimeFlagsPatch) => Effect = core.updateRuntimeFlags /** * @since 1.0.0 * @category runtime */ export const withRuntimeFlagsPatch: { (update: RuntimeFlagsPatch.RuntimeFlagsPatch): (self: Effect) => Effect (self: Effect, update: RuntimeFlagsPatch.RuntimeFlagsPatch): Effect } = core.withRuntimeFlags /** * @since 1.0.0 * @category runtime */ export const withRuntimeFlagsPatchScoped: ( update: RuntimeFlagsPatch.RuntimeFlagsPatch ) => Effect = fiberRuntime.withRuntimeFlagsScoped // ------------------------------------------------------------------------------------- // metrics // ------------------------------------------------------------------------------------- /** * Tags each metric in this effect with the specific tag. * * @since 1.0.0 * @category metrics */ export const tagMetrics: { (key: string, value: string): (self: Effect) => Effect (self: Effect, key: string, value: string): Effect } = effect.tagMetrics /** * Tags each metric in this effect with the specific tag. * * @since 1.0.0 * @category metrics */ export const labelMetrics: { (labels: Iterable): (self: Effect) => Effect (self: Effect, labels: Iterable): Effect } = effect.labelMetrics /** * Tags each metric in this effect with the specific tag. * * @since 1.0.0 * @category metrics */ export const labelMetricsSet: { (labels: HashSet.HashSet): (self: Effect) => Effect (self: Effect, labels: HashSet.HashSet): Effect } = effect.labelMetricsSet /** * Tags each metric in a scope with a the specific tag. * * @since 1.0.0 * @category metrics */ export const tagMetricsScoped: (key: string, value: string) => Effect = fiberRuntime.tagMetricsScoped /** * Tags each metric in a scope with a the specific tag. * * @since 1.0.0 * @category metrics */ export const labelMetricsScoped: ( labels: ReadonlyArray ) => Effect = fiberRuntime.labelMetricsScoped /** * Tags each metric in a scope with a the specific tag. * * @since 1.0.0 * @category metrics */ export const labelMetricsScopedSet: ( labels: HashSet.HashSet ) => Effect = fiberRuntime.labelMetricsScopedSet /** * Retrieves the metric labels associated with the current scope. * * @since 1.0.0 * @category metrics */ export const metricLabels: Effect> = core.metricLabels /** * @since 1.0.0 * @category metrics */ export const withMetric: { (metric: Metric.Metric): (self: Effect) => Effect (self: Effect, metric: Metric.Metric): Effect } = effect.withMetric // ------------------------------------------------------------------------------------- // unify // ------------------------------------------------------------------------------------- /** * Used to unify functions that would otherwise return `Effect | Effect` * * @category unify * @since 1.0.0 */ export const unifiedFn: , Ret extends Effect>( f: (...args: Args) => Ret ) => (...args: Args) => Effect.Unify = core.unified /** * Used to unify effects that would otherwise be `Effect | Effect` * * @category unify * @since 1.0.0 */ export const unified: >(f: Ret) => Effect.Unify = identity // ------------------------------------------------------------------------------------- // semaphore // ------------------------------------------------------------------------------------- /** * @category semaphore * @since 1.0.0 */ export interface Permit { readonly index: number } /** * @category semaphore * @since 1.0.0 */ export interface Semaphore { readonly withPermits: (permits: number) => (self: Effect) => Effect readonly take: (permits: number) => Effect readonly release: (permits: number) => Effect } /** * Unsafely creates a new Semaphore * * @since 1.0.0 * @category semaphore */ export const unsafeMakeSemaphore: (permits: number) => Semaphore = circular.unsafeMakeSemaphore /** * Creates a new Semaphore * * @since 1.0.0 * @category semaphore */ export const makeSemaphore: (permits: number) => Effect = circular.makeSemaphore // ------------------------------------------------------------------------------------- // execution // ------------------------------------------------------------------------------------- /** * @since 1.0.0 * @category execution */ export const runFork: (effect: Effect) => Fiber.RuntimeFiber = _runtime.unsafeForkEffect /** * @since 1.0.0 * @category execution */ export const runCallback: ( effect: Effect, onExit?: (exit: Exit.Exit) => void ) => Runtime.Cancel = _runtime.unsafeRunEffect /** * Runs an `Effect` workflow, returning a `Promise` which resolves with the * result of the workflow or rejects with an error. * * @since 1.0.0 * @category execution */ export const runPromise: (effect: Effect) => Promise = _runtime.unsafeRunPromiseEffect /** * Runs an `Effect` workflow, returning a `Promise` which resolves with the * `Exit` value of the workflow. * * @since 1.0.0 * @category execution */ export const runPromiseExit: (effect: Effect) => Promise> = _runtime.unsafeRunPromiseExitEffect /** * @since 1.0.0 * @category execution */ export const runSync: (effect: Effect) => A = _runtime.unsafeRunSyncEffect /** * @since 1.0.0 * @category execution */ export const runSyncExit: (effect: Effect) => Exit.Exit = _runtime.unsafeRunSyncExitEffect // ------------------------------------------------------------------------------------- // zipping // ------------------------------------------------------------------------------------- /** * Sequentially zips the this result with the specified result. Combines both * `Cause`s when both effects fail. * * @since 1.0.0 * @category zipping */ export const validate: { ( that: Effect, options?: { readonly concurrent?: boolean; readonly batching?: boolean | "inherit" } ): (self: Effect) => Effect ( self: Effect, that: Effect, options?: { readonly concurrent?: boolean; readonly batching?: boolean | "inherit" } ): Effect } = fiberRuntime.validate /** * Sequentially zips this effect with the specified effect using the specified * combiner function. Combines the causes in case both effect fail. * * @since 1.0.0 * @category zipping */ export const validateWith: { ( that: Effect, f: (a: A, b: B) => C, options?: { readonly concurrent?: boolean; readonly batching?: boolean | "inherit" } ): (self: Effect) => Effect ( self: Effect, that: Effect, f: (a: A, b: B) => C, options?: { readonly concurrent?: boolean; readonly batching?: boolean | "inherit" } ): Effect } = fiberRuntime.validateWith /** * @since 1.0.0 * @category zipping */ export const zip: { ( that: Effect, options?: { readonly concurrent?: boolean readonly batching?: boolean | "inherit" } ): (self: Effect) => Effect ( self: Effect, that: Effect, options?: { readonly concurrent?: boolean readonly batching?: boolean | "inherit" } ): Effect } = fiberRuntime.zipOptions /** * @since 1.0.0 * @category zipping */ export const zipLeft: { ( that: Effect, options?: { readonly concurrent?: boolean; readonly batching?: boolean | "inherit" } ): (self: Effect) => Effect ( self: Effect, that: Effect, options?: { readonly concurrent?: boolean; readonly batching?: boolean | "inherit" } ): Effect } = fiberRuntime.zipLeftOptions /** * @since 1.0.0 * @category zipping */ export const zipRight: { ( that: Effect, options?: { readonly concurrent?: boolean; readonly batching?: boolean | "inherit" } ): (self: Effect) => Effect ( self: Effect, that: Effect, options?: { readonly concurrent?: boolean readonly batching?: boolean | "inherit" } ): Effect } = fiberRuntime.zipRightOptions /** * @since 1.0.0 * @category zipping */ export const zipWith: { ( that: Effect, f: (a: A, b: A2) => B, options?: { readonly concurrent?: boolean; readonly batching?: boolean | "inherit" } ): (self: Effect) => Effect ( self: Effect, that: Effect, f: (a: A, b: A2) => B, options?: { readonly concurrent?: boolean; readonly batching?: boolean | "inherit" } ): Effect } = fiberRuntime.zipWithOptions // ------------------------------------------------------------------------------------- // requests & batching // ------------------------------------------------------------------------------------- /** * @category requests & batching * @since 1.0.0 */ export const blocked: (blockedRequests: RequestBlock, _continue: Effect) => Blocked = core.blocked /** * @category requests & batching * @since 1.0.0 */ export const runRequestBlock: (blockedRequests: RequestBlock) => Blocked = core.runRequestBlock /** * @category requests & batching * @since 1.0.0 */ export const step: (self: Effect) => Effect | Blocked> = core.step /** * @category requests & batching * @since 1.0.0 */ export const flatMapStep: ( self: Effect, f: (step: Exit.Exit | Blocked) => Effect ) => Effect = core.flatMapStep /** * @since 1.0.0 * @category requests & batching */ export const request: { < A extends Request.Request, Ds extends RequestResolver | Effect> >( request: A, dataSource: Ds ): Effect< [Ds] extends [Effect] ? Effect.Context : never, Request.Request.Error, Request.Request.Success > } = query.fromRequest as any /** * @since 1.0.0 * @category requests & batching */ export const cacheRequestResult: >( request: A, result: Request.Request.Result ) => Effect = query.cacheRequest /** * @since 1.0.0 * @category requests & batching */ export const withRequestBatching: { (requestBatching: boolean): (self: Effect) => Effect (self: Effect, requestBatching: boolean): Effect } = core.withRequestBatching /** * @since 1.0.0 * @category requests & batching */ export const setRequestBatching = (requestBatching: boolean) => layer.scopedDiscard( fiberRuntime.fiberRefLocallyScoped(core.currentRequestBatching, requestBatching) ) /** * @since 1.0.0 * @category requests & batching */ export const setRequestCaching = (requestCaching: boolean) => layer.scopedDiscard( fiberRuntime.fiberRefLocallyScoped(query.currentCacheEnabled, requestCaching) ) /** * @since 1.0.0 * @category requests & batching */ export const setRequestCache: { ( cache: Effect ): Layer.Layer, E, never> ( cache: Request.Cache ): Layer.Layer } = ((cache: Request.Cache | Effect) => layer.scopedDiscard( core.isEffect(cache) ? core.flatMap(cache, (x) => fiberRuntime.fiberRefLocallyScoped(query.currentCache as any, x)) : fiberRuntime.fiberRefLocallyScoped(query.currentCache as any, cache) )) as any /** * @since 1.0.0 * @category requests & batching */ export const withRequestCaching: { (strategy: boolean): (self: Effect) => Effect (self: Effect, strategy: boolean): Effect } = query.withRequestCaching /** * @since 1.0.0 * @category requests & batching */ export const withRequestCache: { (cache: Request.Cache): (self: Effect) => Effect (self: Effect, cache: Request.Cache): Effect } = query.withRequestCache // ------------------------------------------------------------------------------------- // tracing // ------------------------------------------------------------------------------------- /** * Create a Layer that sets the current Tracer * * @since 1.0.0 * @category tracing */ export const setTracer: (tracer: Tracer.Tracer) => Layer.Layer = circularLayer.setTracer /** * @since 1.0.0 * @category tracing */ export const tracer: Effect = effect.tracer /** * @since 1.0.0 * @category tracing */ export const tracerWith: (f: (tracer: Tracer.Tracer) => Effect) => Effect = defaultServices.tracerWith /** * @since 1.0.0 * @category tracing */ export const withTracer: { (value: Tracer.Tracer): (effect: Effect) => Effect (effect: Effect, value: Tracer.Tracer): Effect } = defaultServices.withTracer /** * @since 1.0.0 * @category tracing */ export const withTracerScoped: (value: Tracer.Tracer) => Effect = fiberRuntime.withTracerScoped /** * @since 1.0.0 * @category tracing */ export const withTracerTiming: { (enabled: boolean): (effect: Effect) => Effect (effect: Effect, enabled: boolean): Effect } = core.withTracerTiming /** * @since 1.0.0 * @category tracing */ export const setTracerTiming: (enabled: boolean) => Layer.Layer = (enabled: boolean) => layer.scopedDiscard( fiberRuntime.fiberRefLocallyScoped(core.currentTracerTimingEnabled, enabled) ) /** * Adds an annotation to each span in this effect. * * @since 1.0.0 * @category tracing */ export const annotateSpans: { (key: string, value: Tracer.AttributeValue): (effect: Effect) => Effect (values: Record): (effect: Effect) => Effect (effect: Effect, key: string, value: Tracer.AttributeValue): Effect (effect: Effect, values: Record): Effect } = effect.annotateSpans /** * Adds an annotation to the current span if available * * @since 1.0.0 * @category tracing */ export const annotateCurrentSpan: { (key: string, value: Tracer.AttributeValue): Effect (values: Record): Effect } = effect.annotateCurrentSpan /** * @since 1.0.0 * @category tracing */ export const currentSpan: Effect> = effect.currentSpan /** * @since 1.0.0 * @category tracing */ export const currentParentSpan: Effect> = effect.currentParentSpan /** * @since 1.0.0 * @category tracing */ export const spanAnnotations: Effect> = effect.spanAnnotations /** * @since 1.0.0 * @category tracing */ export const spanLinks: Effect> = effect.spanLinks /** * For all spans in this effect, add a link with the provided span. * * @since 1.0.0 * @category tracing */ export const linkSpans: { ( span: Tracer.ParentSpan, attributes?: Record ): (self: Effect) => Effect ( self: Effect, span: Tracer.ParentSpan, attributes?: Record ): Effect } = effect.linkSpans /** * Create a new span for tracing. * * @since 1.0.0 * @category tracing */ export const makeSpan: ( name: string, options?: { readonly attributes?: Record readonly links?: ReadonlyArray readonly parent?: Tracer.ParentSpan readonly root?: boolean readonly context?: Context.Context } ) => Effect = effect.makeSpan /** * Adds the provided span to the span stack. * * @since 1.0.0 * @category tracing */ export const setParentSpan: (span: Tracer.ParentSpan) => Layer.Layer = circularLayer.setParentSpan /** * Create and add a span to the current span stack. * * The span is ended when the Layer is released. * * @since 1.0.0 * @category tracing */ export const setSpan: ( name: string, options?: { readonly attributes?: Record readonly links?: ReadonlyArray readonly parent?: Tracer.ParentSpan readonly root?: boolean readonly context?: Context.Context } ) => Layer.Layer = circularLayer.setSpan /** * Create a new span for tracing, and automatically close it when the effect * completes. * * The span is not added to the current span stack, so no child spans will be * created for it. * * @since 1.0.0 * @category tracing */ export const useSpan: { (name: string, evaluate: (span: Tracer.Span) => Effect): Effect ( name: string, options: { readonly attributes?: Record readonly links?: ReadonlyArray readonly parent?: Tracer.ParentSpan readonly root?: boolean readonly context?: Context.Context }, evaluate: (span: Tracer.Span) => Effect ): Effect } = effect.useSpan /** * Create a new span for tracing, and automatically close it when the Scope * finalizes. * * The span is not added to the current span stack, so no child spans will be * created for it. * * @since 1.0.0 * @category tracing */ export const useSpanScoped: ( name: string, options?: { readonly attributes?: Record readonly links?: ReadonlyArray readonly parent?: Tracer.ParentSpan readonly root?: boolean readonly context?: Context.Context } ) => Effect = fiberRuntime.useSpanScoped /** * Wraps the effect with a new span for tracing. * * @since 1.0.0 * @category tracing */ export const withSpan: { ( name: string, options?: { readonly attributes?: Record readonly links?: ReadonlyArray readonly parent?: Tracer.ParentSpan readonly root?: boolean readonly context?: Context.Context } ): (self: Effect) => Effect ( self: Effect, name: string, options?: { readonly attributes?: Record readonly links?: ReadonlyArray readonly parent?: Tracer.ParentSpan readonly root?: boolean readonly context?: Context.Context } ): Effect } = effect.withSpan /** * Create and add a span to the current span stack. * * The span is ended when the Scope is finalized. * * @since 1.0.0 * @category tracing */ export const withSpanScoped: ( name: string, options?: { readonly attributes?: Record readonly links?: ReadonlyArray readonly parent?: Tracer.ParentSpan readonly root?: boolean readonly context?: Context.Context } ) => Effect = fiberRuntime.withSpanScoped /** * Adds the provided span to the current span stack. * * @since 1.0.0 * @category tracing */ export const withParentSpan: { (span: Tracer.ParentSpan): (self: Effect) => Effect (self: Effect, span: Tracer.ParentSpan): Effect } = effect.withParentSpan /** * Adds the provided span to the current span stack. * * @since 1.0.0 * @category tracing */ export const withParentSpanScoped: (span: Tracer.ParentSpan) => Effect = fiberRuntime.withParentSpanScoped // ------------------------------------------------------------------------------------- // optionality // ------------------------------------------------------------------------------------- /** * Returns an effect that errors with `NoSuchElementException` if the value is * null or undefined, otherwise succeeds with the value. * * @since 1.0.0 * @category optionality */ export const fromNullable: (value: A) => Effect> = effect.fromNullable /** * Wraps the success value of this effect with `Option.some`, and maps * `Cause.NoSuchElementException` to `Option.none`. * * @since 1.0.0 * @category optionality */ export const optionFromOptional: ( self: Effect ) => Effect, Option.Option> = effect.optionFromOptional