diff --git "a/.opencode/node_modules/effect/dist/Layer.d.ts" "b/.opencode/node_modules/effect/dist/Layer.d.ts" --- "a/.opencode/node_modules/effect/dist/Layer.d.ts" +++ "b/.opencode/node_modules/effect/dist/Layer.d.ts" @@ -1,19 +1,11 @@ /** - * A `Layer` describes how to build one or more services in your - * application. Services can be injected into effects via - * `Effect.provideService`. Effects can require services via `Effect.service`. + * Builds and wires services for Effect applications. * - * Layer can be thought of as recipes for producing bundles of services, given - * their dependencies (other services). - * - * Construction of services can be effectful and utilize resources that must be - * acquired and safely released when the services are done being utilized. - * - * By default layers are shared, meaning that if the same layer is used twice - * the layer will only be allocated a single time. - * - * Because of their excellent composition properties, layers are the idiomatic - * way in Effect-TS to create services that depend on other services. + * A `Layer` describes how to acquire one or more services, which + * services are required to build them, and which errors can occur during + * acquisition. Layers can manage scoped resources, memoize shared services, + * combine with other layers, provide services to effects or streams, and attach + * error handling, tracing, or lifecycle hooks. * * @since 2.0.0 */ @@ -32,15 +24,22 @@ import type * as Types from "./Types.ts"; import type * as Unify from "./Unify.ts"; declare const TypeId = "~effect/Layer"; /** - * A Layer describes how to build one or more services for dependency injection. + * A `Layer` describes how to build one or more services for dependency injection. * - * A Layer represents: - * - ROut: The services this layer provides - * - E: The possible errors during layer construction - * - RIn: The services this layer requires as dependencies + * **When to use** + * + * Use to model construction of application services for dependency injection, + * especially when services have dependencies, can fail during construction, or + * need scoped setup and release. + * + * **Details** + * + * A `Layer` represents `ROut` as the services this layer + * provides, `E` as the possible errors during layer construction, and `RIn` as + * the services this layer requires as dependencies. * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface Layer extends Variance, Pipeable { [Unify.typeSymbol]?: unknown; @@ -48,8 +47,16 @@ export interface Layer extends Variance [Unify.ignoreSymbol]?: LayerUnifyIgnore; } /** - * @since 4.0.0 + * Type-level hook that allows `Layer` values to participate in `Unify` + * inference. + * + * **Details** + * + * This is used by Effect's pipe and unification machinery to preserve the + * provided services, error, and requirements of a `Layer`. + * * @category models + * @since 4.0.0 */ export interface LayerUnify A[Unify.typeSymbol] extends Layer | infer _ ? Layer>, Error>, Services>> : never; } /** - * @since 4.0.0 + * Type-level marker used by `Unify` for `Layer` types that should be ignored + * during unification. + * * @category models + * @since 4.0.0 */ export interface LayerUnifyIgnore { } /** * The variance interface for Layer type parameters. * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface Variance { readonly [TypeId]: { @@ -76,13 +86,26 @@ export interface Variance { }; } /** - * A constraint interface for working with any Layer type. + * A type-level constraint for working with any `Layer` type. + * + * **When to use** * - * This interface is used to constrain generic types to Layer types - * without specifying exact type parameters. + * Use to constrain generic parameters or layer collections to any `Layer` + * value while preserving its provided, error, and required service types for + * inference. + * + * **Details** * + * This interface is used to constrain generic types to `Layer` values without + * specifying exact type parameters. + * + * @see {@link Layer} for the concrete layer interface + * @see {@link Services} for extracting required services from a layer type + * @see {@link Error} for extracting construction errors from a layer type + * @see {@link Success} for extracting provided services from a layer type + * + * @category utility types * @since 3.9.0 - * @category type-level */ export interface Any { readonly [TypeId]: { @@ -92,36 +115,64 @@ export interface Any { }; } /** - * Extracts the service dependencies (RIn) from a Layer type. + * Extracts the service requirements (`RIn`) from a `Layer` type. * - * @since 2.0.0 - * @category type-level + * **When to use** + * + * Use to derive the dependency requirements of a generic or inferred `Layer` + * without restating its `RIn` type parameter. + * + * @see {@link Success} for extracting the services provided by the same `Layer` + * @see {@link Error} for extracting the construction failure type from the same `Layer` + * + * @category utility types + * @since 4.0.0 */ export type Services = T extends infer L ? L extends Layer ? _RIn : never : never; /** - * Extracts the error type (E) from a Layer type. + * Extracts the error type (`E`) from a `Layer` type. * + * **When to use** + * + * Use to derive a layer construction error type for helper types, wrappers, or + * APIs that preserve a layer failure channel. + * + * @see {@link Success} for extracting the services provided by the same `Layer` + * @see {@link Services} for extracting the dependency requirements of the same `Layer` + * + * @category utility types * @since 2.0.0 - * @category type-level */ export type Error = T extends Layer ? _E : never; /** - * Extracts the service output type (ROut) from a Layer type. + * Extracts the service output type (`ROut`) from a `Layer` type. + * + * **When to use** * + * Use to derive the services provided by an existing or generic `Layer` without + * restating its `ROut` type parameter. + * + * @see {@link Error} for extracting the layer construction error type instead + * @see {@link Services} for extracting the layer input service requirements instead + * + * @category utility types * @since 2.0.0 - * @category type-level */ export type Success = T extends Layer ? _ROut : never; declare const MemoMapTypeId = "~effect/Layer/MemoMap"; /** - * A MemoMap is used to memoize layer construction and ensure sharing of layers. + * A `MemoMap` is used to memoize layer construction and ensure sharing of + * layers. + * + * **Details** * - * The MemoMap prevents duplicate construction of the same layer instance, + * The `MemoMap` prevents duplicate construction of the same layer instance, * enabling efficient resource sharing across layer dependencies. * - * @example + * **Example** (Sharing layer construction with a memo map) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -132,7 +183,7 @@ declare const MemoMapTypeId = "~effect/Layer/MemoMap"; * const memoMap = yield* Layer.makeMemoMap * const scope = yield* Effect.scope * - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) * const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) @@ -141,25 +192,27 @@ declare const MemoMapTypeId = "~effect/Layer/MemoMap"; * }) * ``` * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface MemoMap { readonly [MemoMapTypeId]: typeof MemoMapTypeId; + readonly get: (layer: Layer, scope: Scope.Scope) => Effect, E, RIn> | undefined; readonly getOrElseMemoize: (layer: Layer, scope: Scope.Scope, build: (memoMap: MemoMap, scope: Scope.Scope) => Effect, E, RIn>) => Effect, E, RIn>; } /** * Returns `true` if the specified value is a `Layer`, `false` otherwise. * - * @example + * **Example** (Checking whether a value is a layer) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) * const notALayer = { someProperty: "value" } @@ -168,19 +221,23 @@ export interface MemoMap { * console.log(Layer.isLayer(notALayer)) // false * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ export declare const isLayer: (u: unknown) => u is Layer; /** - * Constructs a Layer from a function that uses a `MemoMap` and `Scope` to build the layer. + * Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to + * build the layer. + * + * **Details** * * The function receives a `MemoMap` for memoization and a `Scope` for resource management. * A child scope is created, and if the build fails, the child scope is closed. * - * @example + * **Example** (Constructing a layer from a build function) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -195,20 +252,23 @@ export declare const isLayer: (u: unknown) => u is Layer(build: (memoMap: MemoMap, scope: Scope.Scope) => Effect, E, RIn>) => Layer; /** - * Constructs a Layer from a function that uses a `MemoMap` and `Scope` to build the layer, - * with automatic memoization. + * Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to + * build the layer, with automatic memoization. + * + * **Details** * * This is similar to `fromBuild` but provides automatic memoization of the layer construction. * The layer will be memoized based on the provided `MemoMap`. * - * @example + * **Example** (Memoizing layer construction) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -223,16 +283,17 @@ export declare const fromBuild: (build: (memoMap: MemoMap, scope: * ) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export declare const fromBuildMemo: (build: (memoMap: MemoMap, scope: Scope.Scope) => Effect, E, RIn>) => Layer; /** - * Constructs a `MemoMap` that can be used to build additional layers. + * Constructs a `MemoMap` synchronously so it can be used to build additional layers. + * + * **Example** (Creating a memo map unsafely) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -243,7 +304,7 @@ export declare const fromBuildMemo: (build: (memoMap: MemoMap, sco * const memoMap = Layer.makeMemoMapUnsafe() * const scope = yield* Effect.scope * - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) * const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) @@ -252,16 +313,35 @@ export declare const fromBuildMemo: (build: (memoMap: MemoMap, sco * }) * ``` * - * @since 4.0.0 * @category memo map + * @since 4.0.0 */ export declare const makeMemoMapUnsafe: () => MemoMap; /** - * Constructs a `MemoMap` that can be used to build additional layers. + * Constructs a child `MemoMap` synchronously, allowing it to reuse layers + * already memoized in the parent while isolating any new layer allocations to + * the child map. + * + * **When to use** + * + * Use to synchronously fork a memo map for manual layer building when child + * builds should see parent memoized layers without writing newly built layers + * back to the parent. + * + * @see {@link forkMemoMap} for allocating the child memo map inside `Effect` + * @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent + * + * @category memo map + * @since 4.0.0 + */ +export declare const forkMemoMapUnsafe: (parent: MemoMap) => MemoMap; +/** + * Constructs a `MemoMap` effectfully so it can be used to build additional layers. + * + * **Example** (Creating a memo map in an effect) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -272,7 +352,7 @@ export declare const makeMemoMapUnsafe: () => MemoMap; * const memoMap = yield* Layer.makeMemoMap * const scope = yield* Effect.scope * - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) * const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) @@ -281,19 +361,46 @@ export declare const makeMemoMapUnsafe: () => MemoMap; * }) * ``` * - * @since 2.0.0 * @category memo map + * @since 2.0.0 */ export declare const makeMemoMap: Effect; +/** + * Constructs a child `MemoMap` effectfully, allowing it to reuse layers already + * memoized in the parent while isolating any new layer allocations to the child + * map. + * + * **When to use** + * + * Use when a layer build should inherit already memoized layers from an + * existing `MemoMap` while keeping newly memoized layers out of the parent map. + * + * @see {@link makeMemoMap} for creating a root memo map in an `Effect` + * @see {@link forkMemoMapUnsafe} for the synchronous constructor variant + * @see {@link buildWithMemoMap} for building layers with an explicit memo map + * + * @category memo map + * @since 4.0.0 + */ +export declare const forkMemoMap: (parent: MemoMap) => Effect; declare const CurrentMemoMap_base: Context.ServiceClass; /** - * A service reference for the current `MemoMap` used in layer construction. + * Context service for the current `MemoMap` used in layer construction. * - * This service provides access to the current memoization map during layer building, - * allowing layers to share memoized results. + * **When to use** + * + * Use when building custom layer operations that need to access the current + * memoization map from the fiber context. + * + * **Details** + * + * This service wraps a `MemoMap` as a `Context.Service`, making it available + * for dependency injection during layer construction. + * + * @see {@link MemoMap} the memoization map type wrapped by this service * - * @since 3.13.0 * @category models + * @since 3.13.0 */ export declare class CurrentMemoMap extends CurrentMemoMap_base { static getOrCreate: (self: Context.Context) => MemoMap; @@ -302,9 +409,10 @@ export declare class CurrentMemoMap extends CurrentMemoMap_base { * Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize * the layer construction. * - * @example + * **Example** (Building layers with an explicit memo map) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -320,13 +428,13 @@ export declare class CurrentMemoMap extends CurrentMemoMap_base { * const scope = yield* Effect.scope * * // Build database layer with memoization - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) * const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) * * // Build logger layer with same memoization (reuses memo if same layer) - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(msg))) * }) * const loggerContext = yield* Layer.buildWithMemoMap( @@ -342,17 +450,18 @@ export declare class CurrentMemoMap extends CurrentMemoMap_base { * }) * ``` * - * @since 2.0.0 * @category memo map + * @since 2.0.0 */ export declare const buildWithMemoMap: { /** * Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize * the layer construction. * - * @example + * **Example** (Building layers with an explicit memo map) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -368,13 +477,13 @@ export declare const buildWithMemoMap: { * const scope = yield* Effect.scope * * // Build database layer with memoization - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) * const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) * * // Build logger layer with same memoization (reuses memo if same layer) - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(msg))) * }) * const loggerContext = yield* Layer.buildWithMemoMap( @@ -390,17 +499,18 @@ export declare const buildWithMemoMap: { * }) * ``` * - * @since 2.0.0 * @category memo map + * @since 2.0.0 */ (memoMap: MemoMap, scope: Scope.Scope): (self: Layer) => Effect, E, RIn>; /** * Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize * the layer construction. * - * @example + * **Example** (Building layers with an explicit memo map) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -416,13 +526,13 @@ export declare const buildWithMemoMap: { * const scope = yield* Effect.scope * * // Build database layer with memoization - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) * const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) * * // Build logger layer with same memoization (reuses memo if same layer) - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(msg))) * }) * const loggerContext = yield* Layer.buildWithMemoMap( @@ -438,17 +548,18 @@ export declare const buildWithMemoMap: { * }) * ``` * - * @since 2.0.0 * @category memo map + * @since 2.0.0 */ (self: Layer, memoMap: MemoMap, scope: Scope.Scope): Effect, E, RIn>; }; /** * Builds a layer into a scoped value. * - * @example + * **Example** (Building a layer into a context) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -456,7 +567,7 @@ export declare const buildWithMemoMap: { * * // Build a layer to get its services * const program = Effect.gen(function*() { - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) * @@ -470,20 +581,27 @@ export declare const buildWithMemoMap: { * }) * ``` * - * @since 2.0.0 * @category destructors + * @since 2.0.0 */ export declare const build: (self: Layer) => Effect, E, RIn | Scope.Scope>; /** - * Builds a layer into an `Effect` value. Any resources associated with this - * layer will be released when the specified scope is closed unless their scope - * has been extended. This allows building layers where the lifetime of some of - * the services output by the layer exceed the lifetime of the effect the - * layer is provided to. + * Builds a layer using an explicit scope. + * + * **When to use** + * + * Use to control the lifetime of layer resources with a scope supplied by the + * caller. + * + * **Details** + * + * Resources created by the layer are released when the supplied scope is + * closed, unless a resource extends its own scope. + * + * **Example** (Building a layer with an explicit scope) * - * @example * ```ts - * import { Effect, Layer, Scope, Context } from "effect" + * import { Context, Effect, Layer, Scope } from "effect" * * class Database extends Context.Service Effect.Effect @@ -493,7 +611,7 @@ export declare const build: (self: Layer) => Effect< * const program = Effect.gen(function*() { * const scope = yield* Effect.scope * - * const dbLayer = Layer.effect(Database)(Effect.gen(function*() { + * const dbLayer = Layer.effect(Database, Effect.gen(function*() { * console.log("Initializing database...") * yield* Scope.addFinalizer( * scope, @@ -511,20 +629,27 @@ export declare const build: (self: Layer) => Effect< * }) * ``` * - * @since 2.0.0 * @category destructors + * @since 2.0.0 */ export declare const buildWithScope: { /** - * Builds a layer into an `Effect` value. Any resources associated with this - * layer will be released when the specified scope is closed unless their scope - * has been extended. This allows building layers where the lifetime of some of - * the services output by the layer exceed the lifetime of the effect the - * layer is provided to. + * Builds a layer using an explicit scope. + * + * **When to use** + * + * Use to control the lifetime of layer resources with a scope supplied by the + * caller. + * + * **Details** + * + * Resources created by the layer are released when the supplied scope is + * closed, unless a resource extends its own scope. + * + * **Example** (Building a layer with an explicit scope) * - * @example * ```ts - * import { Effect, Layer, Scope, Context } from "effect" + * import { Context, Effect, Layer, Scope } from "effect" * * class Database extends Context.Service Effect.Effect @@ -534,7 +659,7 @@ export declare const buildWithScope: { * const program = Effect.gen(function*() { * const scope = yield* Effect.scope * - * const dbLayer = Layer.effect(Database)(Effect.gen(function*() { + * const dbLayer = Layer.effect(Database, Effect.gen(function*() { * console.log("Initializing database...") * yield* Scope.addFinalizer( * scope, @@ -552,20 +677,27 @@ export declare const buildWithScope: { * }) * ``` * - * @since 2.0.0 * @category destructors + * @since 2.0.0 */ (scope: Scope.Scope): (self: Layer) => Effect, E, RIn>; /** - * Builds a layer into an `Effect` value. Any resources associated with this - * layer will be released when the specified scope is closed unless their scope - * has been extended. This allows building layers where the lifetime of some of - * the services output by the layer exceed the lifetime of the effect the - * layer is provided to. + * Builds a layer using an explicit scope. + * + * **When to use** + * + * Use to control the lifetime of layer resources with a scope supplied by the + * caller. + * + * **Details** + * + * Resources created by the layer are released when the supplied scope is + * closed, unless a resource extends its own scope. + * + * **Example** (Building a layer with an explicit scope) * - * @example * ```ts - * import { Effect, Layer, Scope, Context } from "effect" + * import { Context, Effect, Layer, Scope } from "effect" * * class Database extends Context.Service Effect.Effect @@ -575,7 +707,7 @@ export declare const buildWithScope: { * const program = Effect.gen(function*() { * const scope = yield* Effect.scope * - * const dbLayer = Layer.effect(Database)(Effect.gen(function*() { + * const dbLayer = Layer.effect(Database, Effect.gen(function*() { * console.log("Initializing database...") * yield* Scope.addFinalizer( * scope, @@ -593,151 +725,117 @@ export declare const buildWithScope: { * }) * ``` * - * @since 2.0.0 * @category destructors + * @since 2.0.0 */ (self: Layer, scope: Scope.Scope): Effect, E, RIn>; }; /** - * Constructs a layer from the specified value. + * Constructs a layer that provides a single service from an already available + * value. + * + * **When to use** + * + * Use when you need a `Layer` that provides a service from an already + * constructed implementation without effectful acquisition. + * + * **Example** (Creating a layer from a service implementation) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * - * class Logger extends Context.Service Effect.Effect - * }>()("Logger") {} - * - * // Create layers from concrete service implementations - * const databaseLayer = Layer.succeed(Database)({ + * const DatabaseLive = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Query result: ${sql}`)) * }) - * - * const loggerLayer = Layer.succeed(Logger)({ - * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(`[LOG] ${msg}`))) - * }) - * - * // Use the layers in a program - * const program = Effect.gen(function*() { - * const database = yield* Database - * const logger = yield* Logger - * - * yield* logger.log("Starting database query") - * const result = yield* database.query("SELECT * FROM users") - * yield* logger.log(`Query completed: ${result}`) - * - * return result - * }).pipe( - * Effect.provide(Layer.mergeAll(databaseLayer, loggerLayer)) - * ) * ``` * - * @since 2.0.0 + * @see {@link sync} for constructing layers from lazy values + * * @category constructors + * @since 2.0.0 */ export declare const succeed: { /** - * Constructs a layer from the specified value. + * Constructs a layer that provides a single service from an already available + * value. + * + * **When to use** + * + * Use when you need a `Layer` that provides a service from an already + * constructed implementation without effectful acquisition. + * + * **Example** (Creating a layer from a service implementation) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * - * class Logger extends Context.Service Effect.Effect - * }>()("Logger") {} - * - * // Create layers from concrete service implementations - * const databaseLayer = Layer.succeed(Database)({ + * const DatabaseLive = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Query result: ${sql}`)) * }) - * - * const loggerLayer = Layer.succeed(Logger)({ - * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(`[LOG] ${msg}`))) - * }) - * - * // Use the layers in a program - * const program = Effect.gen(function*() { - * const database = yield* Database - * const logger = yield* Logger - * - * yield* logger.log("Starting database query") - * const result = yield* database.query("SELECT * FROM users") - * yield* logger.log(`Query completed: ${result}`) - * - * return result - * }).pipe( - * Effect.provide(Layer.mergeAll(databaseLayer, loggerLayer)) - * ) * ``` * - * @since 2.0.0 + * @see {@link sync} for constructing layers from lazy values + * * @category constructors + * @since 2.0.0 */ (service: Context.Key): (resource: S) => Layer; /** - * Constructs a layer from the specified value. + * Constructs a layer that provides a single service from an already available + * value. + * + * **When to use** + * + * Use when you need a `Layer` that provides a service from an already + * constructed implementation without effectful acquisition. + * + * **Example** (Creating a layer from a service implementation) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * - * class Logger extends Context.Service Effect.Effect - * }>()("Logger") {} - * - * // Create layers from concrete service implementations - * const databaseLayer = Layer.succeed(Database)({ + * const DatabaseLive = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Query result: ${sql}`)) * }) - * - * const loggerLayer = Layer.succeed(Logger)({ - * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(`[LOG] ${msg}`))) - * }) - * - * // Use the layers in a program - * const program = Effect.gen(function*() { - * const database = yield* Database - * const logger = yield* Logger - * - * yield* logger.log("Starting database query") - * const result = yield* database.query("SELECT * FROM users") - * yield* logger.log(`Query completed: ${result}`) - * - * return result - * }).pipe( - * Effect.provide(Layer.mergeAll(databaseLayer, loggerLayer)) - * ) * ``` * - * @since 2.0.0 + * @see {@link sync} for constructing layers from lazy values + * * @category constructors + * @since 2.0.0 */ (service: Context.Key, resource: Types.NoInfer): Layer; }; /** - * Constructs a layer from the specified value, which must return one or more - * services. + * Constructs a layer that provides all services in an already available + * `Context`. + * + * **When to use** + * + * Use when you need a `Layer` built from an existing `Context`, including when + * you need to provide multiple services at once. * - * This is a more general version of `succeed` that allows you to provide multiple - * services at once through a `Context`. + * **Details** + * + * This is a more general version of `succeed` that allows you to provide + * multiple services at once through a `Context`. + * + * **Example** (Providing multiple services from a context) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -758,107 +856,155 @@ export declare const succeed: { * const layer = Layer.succeedContext(context) * ``` * - * @since 2.0.0 + * @see {@link succeed} for providing a single service from a value + * * @category constructors + * @since 2.0.0 */ export declare const succeedContext: (context: Context.Context) => Layer; /** - * A Layer that constructs an empty Context. + * An empty layer that provides no services, cannot fail, has no requirements, + * and performs no construction or finalization work. + * + * **When to use** + * + * Use as the no-op branch when conditionally composing layers. * - * This layer provides no services and can be used as a neutral element - * in layer composition or as a starting point for building layers. + * **Example** (Disabling optional lifecycle work) * - * @example * ```ts - * import { Layer } from "effect" + * import { Console, Layer } from "effect" + * + * declare const flag: boolean * - * const emptyLayer = Layer.empty + * const StartupLogLive = flag + * ? Layer.effectDiscard(Console.log("application starting")) + * : Layer.empty * ``` * - * @since 2.0.0 + * @see {@link effectDiscard} for running an effect while providing no services + * * @category constructors + * @since 2.0.0 */ export declare const empty: Layer; /** - * Lazily constructs a layer from the specified value. + * Constructs a layer lazily that provides a single service. + * + * **When to use** + * + * Use when you need a `Layer` that provides one service whose value is created + * synchronously, but creation should be deferred until the layer is built. + * + * **Details** * * This is a lazy version of `succeed` where the service value is computed * synchronously only when the layer is built. * - * @example + * **Example** (Lazily providing a service) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * - * const layer = Layer.sync(Database)(() => ({ + * const layer = Layer.sync(Database, () => ({ * query: (sql: string) => Effect.succeed(`Query: ${sql}`) * })) * ``` * - * @since 2.0.0 + * @see {@link succeed} for constructing layers from static values + * * @category constructors + * @since 2.0.0 */ export declare const sync: { /** - * Lazily constructs a layer from the specified value. + * Constructs a layer lazily that provides a single service. + * + * **When to use** + * + * Use when you need a `Layer` that provides one service whose value is created + * synchronously, but creation should be deferred until the layer is built. + * + * **Details** * * This is a lazy version of `succeed` where the service value is computed * synchronously only when the layer is built. * - * @example + * **Example** (Lazily providing a service) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * - * const layer = Layer.sync(Database)(() => ({ + * const layer = Layer.sync(Database, () => ({ * query: (sql: string) => Effect.succeed(`Query: ${sql}`) * })) * ``` * - * @since 2.0.0 + * @see {@link succeed} for constructing layers from static values + * * @category constructors + * @since 2.0.0 */ (service: Context.Key): (evaluate: LazyArg) => Layer; /** - * Lazily constructs a layer from the specified value. + * Constructs a layer lazily that provides a single service. + * + * **When to use** + * + * Use when you need a `Layer` that provides one service whose value is created + * synchronously, but creation should be deferred until the layer is built. + * + * **Details** * * This is a lazy version of `succeed` where the service value is computed * synchronously only when the layer is built. * - * @example + * **Example** (Lazily providing a service) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * - * const layer = Layer.sync(Database)(() => ({ + * const layer = Layer.sync(Database, () => ({ * query: (sql: string) => Effect.succeed(`Query: ${sql}`) * })) * ``` * - * @since 2.0.0 + * @see {@link succeed} for constructing layers from static values + * * @category constructors + * @since 2.0.0 */ (service: Context.Key, evaluate: LazyArg>): Layer; }; /** - * Lazily constructs a layer from the specified value, which must return one or more - * services. + * Constructs a layer lazily that provides all services in a `Context`. + * + * **When to use** * - * This is a lazy version of `succeedContext` where the Context is computed + * Use when you need a `Layer` that creates multiple services synchronously but + * defers that work until the layer is built. + * + * **Details** + * + * This is a lazy version of `succeedContext` where the `Context` is computed * synchronously only when the layer is built. * - * @example + * **Example** (Lazily providing a context) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -871,117 +1017,143 @@ export declare const sync: { * ) * ``` * - * @since 2.0.0 + * @see {@link sync} for lazily providing a single service + * @see {@link succeedContext} for providing an already available context + * * @category constructors + * @since 2.0.0 */ export declare const syncContext: (evaluate: LazyArg>) => Layer; /** - * Constructs a layer from the specified scoped effect. + * Constructs a layer from an effect that produces a single service. * - * This allows you to create a Layer from an Effect that produces a service. - * The Effect is executed in the scope of the layer, allowing for proper - * resource management. + * **When to use** + * + * Use when you need to construct a `Layer`-provided service with an `Effect`, + * dependencies, or scoped resource acquisition. * - * **Previously Known As** + * **Details** * - * This API replaces the following from Effect 3.x: + * This allows you to create a `Layer` from an `Effect` that produces a service. + * The `Effect` is executed in the scope of the layer, allowing for proper + * resource management. * - * - `Layer.scoped` + * **Example** (Creating a layer from an effect) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * - * const layer = Layer.effect(Database)( + * const layer = Layer.effect(Database, * Effect.sync(() => ({ * query: (sql: string) => Effect.succeed(`Query: ${sql}`) * })) * ) * ``` * - * @since 2.0.0 + * @see {@link effectContext} for effectfully providing multiple services + * @see {@link effectDiscard} for running construction work without providing services + * * @category constructors + * @since 2.0.0 */ export declare const effect: { /** - * Constructs a layer from the specified scoped effect. + * Constructs a layer from an effect that produces a single service. * - * This allows you to create a Layer from an Effect that produces a service. - * The Effect is executed in the scope of the layer, allowing for proper - * resource management. + * **When to use** * - * **Previously Known As** + * Use when you need to construct a `Layer`-provided service with an `Effect`, + * dependencies, or scoped resource acquisition. * - * This API replaces the following from Effect 3.x: + * **Details** * - * - `Layer.scoped` + * This allows you to create a `Layer` from an `Effect` that produces a service. + * The `Effect` is executed in the scope of the layer, allowing for proper + * resource management. + * + * **Example** (Creating a layer from an effect) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * - * const layer = Layer.effect(Database)( + * const layer = Layer.effect(Database, * Effect.sync(() => ({ * query: (sql: string) => Effect.succeed(`Query: ${sql}`) * })) * ) * ``` * - * @since 2.0.0 + * @see {@link effectContext} for effectfully providing multiple services + * @see {@link effectDiscard} for running construction work without providing services + * * @category constructors + * @since 2.0.0 */ (service: Context.Key): (effect: Effect) => Layer>; /** - * Constructs a layer from the specified scoped effect. + * Constructs a layer from an effect that produces a single service. * - * This allows you to create a Layer from an Effect that produces a service. - * The Effect is executed in the scope of the layer, allowing for proper - * resource management. + * **When to use** * - * **Previously Known As** + * Use when you need to construct a `Layer`-provided service with an `Effect`, + * dependencies, or scoped resource acquisition. + * + * **Details** * - * This API replaces the following from Effect 3.x: + * This allows you to create a `Layer` from an `Effect` that produces a service. + * The `Effect` is executed in the scope of the layer, allowing for proper + * resource management. * - * - `Layer.scoped` + * **Example** (Creating a layer from an effect) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * - * const layer = Layer.effect(Database)( + * const layer = Layer.effect(Database, * Effect.sync(() => ({ * query: (sql: string) => Effect.succeed(`Query: ${sql}`) * })) * ) * ``` * - * @since 2.0.0 + * @see {@link effectContext} for effectfully providing multiple services + * @see {@link effectDiscard} for running construction work without providing services + * * @category constructors + * @since 2.0.0 */ (service: Context.Key, effect: Effect, E, R>): Layer>; }; /** - * Constructs a layer from the specified scoped effect, which must return one - * or more services. + * Constructs a layer from an effect that produces all services in a `Context`. * - * This allows you to create a Layer from an effectful computation that returns - * multiple services. The Effect is executed in the scope of the layer. + * **When to use** + * + * Use when you need a `Layer` that effectfully constructs a `Context` with + * multiple services. + * + * **Details** + * + * This allows you to create a `Layer` from an effectful computation that + * returns multiple services. The `Effect` is executed in the scope of the + * layer. + * + * **Example** (Creating a layer from an effectful context) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service< * Database, @@ -995,23 +1167,23 @@ export declare const effect: { * ) * ``` * - * @since 2.0.0 + * @see {@link effect} for effectfully providing a single service + * * @category constructors + * @since 2.0.0 */ export declare const effectContext: (effect: Effect, E, R>) => Layer>; /** - * Constructs a layer from the specified scoped effect. - * - * This is useful when you want to run an Effect for its side effects during - * layer construction, but don't need to provide any services. + * Constructs a layer from an effect, discarding its value and providing no + * services. * - * **Previously Known As** + * **When to use** * - * This API replaces the following from Effect 3.x: + * Use when layer construction should run an Effect for its side effects while providing no + * services. * - * - `Layer.scopedDiscard` + * **Example** (Running an effect during layer construction) * - * @example * ```ts * import { Effect, Layer } from "effect" * @@ -1022,19 +1194,24 @@ export declare const effectContext: (effect: Effect, * ) * ``` * - * @since 2.0.0 + * @see {@link empty} for a no-op layer that performs no construction work + * * @category constructors + * @since 2.0.0 */ export declare const effectDiscard: (effect: Effect) => Layer>; /** - * Lazily constructs a layer using the specified factory. + * Constructs a layer lazily using the specified factory. + * + * **Details** * * The factory is evaluated only when the suspended layer is first built, and * the result is memoized with normal layer sharing semantics. * - * @example + * **Example** (Choosing a layer lazily) + * * ```ts - * import { Layer, Context } from "effect" + * import { Context, Layer } from "effect" * * class Config extends Context.Service()("Config") {} * @@ -1042,50 +1219,68 @@ export declare const effectDiscard: (effect: Effect) => Layer< * * const layer = Layer.suspend(() => * useProd - * ? Layer.succeed(Config)("https://api.example.com") - * : Layer.succeed(Config)("http://localhost:3000") + * ? Layer.succeed(Config, "https://api.example.com") + * : Layer.succeed(Config, "http://localhost:3000") * ) * ``` * - * @since 4.0.0 * @category constructors + * @since 2.0.0 */ export declare const suspend: (evaluate: LazyArg>) => Layer; /** - * Unwraps a Layer from an Effect, flattening the nested structure. + * Unwraps a `Layer` from an `Effect`, flattening the nested structure. + * + * **When to use** + * + * Use when you have an `Effect` that produces a `Layer` and you want to + * use that layer directly. + * + * **Details** + * + * The resulting Layer will have the combined error and dependency types from + * both the outer Effect and the inner Layer. * - * This is useful when you have an Effect that produces a Layer, and you want to - * use that Layer directly. The resulting Layer will have the combined error and - * dependency types from both the outer Effect and the inner Layer. + * **Example** (Unwrapping an effectful layer) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * * const layerEffect = Effect.succeed( - * Layer.succeed(Database)({ query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) }) + * Layer.succeed(Database, { query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) }) * ) * * const unwrappedLayer = Layer.unwrap(layerEffect) * ``` * + * @category converting * @since 4.0.0 - * @category utils */ export declare const unwrap: (self: Effect, E, R>) => Layer>; /** - * Combines all the provided layers concurrently, creating a new layer with merged input, error, and output types. + * Combines all the provided layers concurrently, creating a new layer with + * merged input, error, and output types. + * + * **When to use** + * + * Use when you need to combine multiple independent layers. + * + * **Details** * * All layers are built concurrently, and their outputs are merged into a single layer. - * This is useful when you need to combine multiple independent layers. * - * @example + * If multiple merged layers depend on the same layer value, that dependency is + * shared by default. Reuse a named layer value when you want services to share + * the same resource, such as one database pool. + * + * **Example** (Merging independent layers) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1095,29 +1290,41 @@ export declare const unwrap: (self: Effect, E, * readonly log: (msg: string) => Effect.Effect * }>()("Logger") {} * - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(msg))) * }) * * const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) * ``` * - * @since 2.0.0 + * @see {@link merge} for merging one layer with another layer or array + * * @category zipping + * @since 2.0.0 */ export declare const mergeAll: , ...Array>]>(...layers: Layers) => Layer, Error, Services>; /** - * Merges this layer with the specified layer concurrently, producing a new layer with combined input and output types. + * Merges this layer with another layer concurrently, producing a new layer with + * combined input, error, and output types. * - * This is a binary version of `mergeAll` that merges exactly two layers or one layer with an array of layers. - * The layers are built concurrently and their outputs are combined. + * **When to use** + * + * Use to combine an existing `Layer` with another `Layer` or an array of + * layers while preserving pipeline style. + * + * **Details** + * + * This is a binary version of `mergeAll` that merges exactly two layers or one + * layer with an array of layers. The layers are built concurrently and their + * outputs are combined. + * + * **Example** (Merging two layers) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1127,29 +1334,41 @@ export declare const mergeAll: , ...Array * readonly log: (msg: string) => Effect.Effect * }>()("Logger") {} * - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(msg))) * }) * * const mergedLayer = Layer.merge(dbLayer, loggerLayer) * ``` * - * @since 2.0.0 + * @see {@link mergeAll} for merging several layers at once + * * @category zipping + * @since 2.0.0 */ export declare const merge: { /** - * Merges this layer with the specified layer concurrently, producing a new layer with combined input and output types. + * Merges this layer with another layer concurrently, producing a new layer with + * combined input, error, and output types. * - * This is a binary version of `mergeAll` that merges exactly two layers or one layer with an array of layers. - * The layers are built concurrently and their outputs are combined. + * **When to use** + * + * Use to combine an existing `Layer` with another `Layer` or an array of + * layers while preserving pipeline style. + * + * **Details** + * + * This is a binary version of `mergeAll` that merges exactly two layers or one + * layer with an array of layers. The layers are built concurrently and their + * outputs are combined. + * + * **Example** (Merging two layers) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1159,29 +1378,41 @@ export declare const merge: { * readonly log: (msg: string) => Effect.Effect * }>()("Logger") {} * - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(msg))) * }) * * const mergedLayer = Layer.merge(dbLayer, loggerLayer) * ``` * - * @since 2.0.0 + * @see {@link mergeAll} for merging several layers at once + * * @category zipping + * @since 2.0.0 */ (that: Layer): (self: Layer) => Layer; /** - * Merges this layer with the specified layer concurrently, producing a new layer with combined input and output types. + * Merges this layer with another layer concurrently, producing a new layer with + * combined input, error, and output types. * - * This is a binary version of `mergeAll` that merges exactly two layers or one layer with an array of layers. - * The layers are built concurrently and their outputs are combined. + * **When to use** + * + * Use to combine an existing `Layer` with another `Layer` or an array of + * layers while preserving pipeline style. + * + * **Details** + * + * This is a binary version of `mergeAll` that merges exactly two layers or one + * layer with an array of layers. The layers are built concurrently and their + * outputs are combined. + * + * **Example** (Merging two layers) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1191,29 +1422,41 @@ export declare const merge: { * readonly log: (msg: string) => Effect.Effect * }>()("Logger") {} * - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(msg))) * }) * * const mergedLayer = Layer.merge(dbLayer, loggerLayer) * ``` * - * @since 2.0.0 + * @see {@link mergeAll} for merging several layers at once + * * @category zipping + * @since 2.0.0 */ ]>(that: Layers): (self: Layer) => Layer, E | Error, Services | R>; /** - * Merges this layer with the specified layer concurrently, producing a new layer with combined input and output types. + * Merges this layer with another layer concurrently, producing a new layer with + * combined input, error, and output types. + * + * **When to use** * - * This is a binary version of `mergeAll` that merges exactly two layers or one layer with an array of layers. - * The layers are built concurrently and their outputs are combined. + * Use to combine an existing `Layer` with another `Layer` or an array of + * layers while preserving pipeline style. + * + * **Details** + * + * This is a binary version of `mergeAll` that merges exactly two layers or one + * layer with an array of layers. The layers are built concurrently and their + * outputs are combined. + * + * **Example** (Merging two layers) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1223,29 +1466,41 @@ export declare const merge: { * readonly log: (msg: string) => Effect.Effect * }>()("Logger") {} * - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(msg))) * }) * * const mergedLayer = Layer.merge(dbLayer, loggerLayer) * ``` * - * @since 2.0.0 + * @see {@link mergeAll} for merging several layers at once + * * @category zipping + * @since 2.0.0 */ (self: Layer, that: Layer): Layer; /** - * Merges this layer with the specified layer concurrently, producing a new layer with combined input and output types. + * Merges this layer with another layer concurrently, producing a new layer with + * combined input, error, and output types. + * + * **When to use** + * + * Use to combine an existing `Layer` with another `Layer` or an array of + * layers while preserving pipeline style. + * + * **Details** + * + * This is a binary version of `mergeAll` that merges exactly two layers or one + * layer with an array of layers. The layers are built concurrently and their + * outputs are combined. * - * This is a binary version of `mergeAll` that merges exactly two layers or one layer with an array of layers. - * The layers are built concurrently and their outputs are combined. + * **Example** (Merging two layers) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1255,29 +1510,40 @@ export declare const merge: { * readonly log: (msg: string) => Effect.Effect * }>()("Logger") {} * - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(msg))) * }) * * const mergedLayer = Layer.merge(dbLayer, loggerLayer) * ``` * - * @since 2.0.0 + * @see {@link mergeAll} for merging several layers at once + * * @category zipping + * @since 2.0.0 */ ]>(self: Layer, that: Layers): Layer, E | Error, Services | R>; }; /** - * Feeds the output services of this builder into the input of the specified - * builder, resulting in a new builder with the inputs of this builder as - * well as any leftover inputs, and the outputs of the specified builder. + * Feeds the output services of the dependency layer into the requirements of + * this layer, returning a layer that only provides the services from this layer. + * + * **When to use** + * + * Use when you need to hide an implementation dependency layer from callers. + * + * **Details** + * + * In `serviceLayer.pipe(Layer.provide(dependencyLayer))`, the dependency layer is + * built first and is used to satisfy the requirements of `serviceLayer`. + * + * **Example** (Providing layer dependencies) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1295,16 +1561,16 @@ export declare const merge: { * }>()("Logger") {} * * // Create dependency layers - * const databaseLayer = Layer.succeed(Database)({ + * const databaseLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`DB: ${sql}`)) * }) * - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(`[LOG] ${msg}`))) * }) * * // UserService depends on Database and Logger - * const userServiceLayer = Layer.effect(UserService)(Effect.gen(function*() { + * const userServiceLayer = Layer.effect(UserService, Effect.gen(function*() { * const database = yield* Database * const logger = yield* Logger * @@ -1333,18 +1599,29 @@ export declare const merge: { * ) * ``` * + * @see {@link provideMerge} for retaining the dependency services + * + * @category providing services * @since 2.0.0 - * @category utils */ export declare const provide: { /** - * Feeds the output services of this builder into the input of the specified - * builder, resulting in a new builder with the inputs of this builder as - * well as any leftover inputs, and the outputs of the specified builder. + * Feeds the output services of the dependency layer into the requirements of + * this layer, returning a layer that only provides the services from this layer. + * + * **When to use** + * + * Use when you need to hide an implementation dependency layer from callers. + * + * **Details** + * + * In `serviceLayer.pipe(Layer.provide(dependencyLayer))`, the dependency layer is + * built first and is used to satisfy the requirements of `serviceLayer`. + * + * **Example** (Providing layer dependencies) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1362,16 +1639,16 @@ export declare const provide: { * }>()("Logger") {} * * // Create dependency layers - * const databaseLayer = Layer.succeed(Database)({ + * const databaseLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`DB: ${sql}`)) * }) * - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(`[LOG] ${msg}`))) * }) * * // UserService depends on Database and Logger - * const userServiceLayer = Layer.effect(UserService)(Effect.gen(function*() { + * const userServiceLayer = Layer.effect(UserService, Effect.gen(function*() { * const database = yield* Database * const logger = yield* Logger * @@ -1400,18 +1677,29 @@ export declare const provide: { * ) * ``` * + * @see {@link provideMerge} for retaining the dependency services + * + * @category providing services * @since 2.0.0 - * @category utils */ (that: Layer): (self: Layer) => Layer>; /** - * Feeds the output services of this builder into the input of the specified - * builder, resulting in a new builder with the inputs of this builder as - * well as any leftover inputs, and the outputs of the specified builder. + * Feeds the output services of the dependency layer into the requirements of + * this layer, returning a layer that only provides the services from this layer. + * + * **When to use** + * + * Use when you need to hide an implementation dependency layer from callers. + * + * **Details** + * + * In `serviceLayer.pipe(Layer.provide(dependencyLayer))`, the dependency layer is + * built first and is used to satisfy the requirements of `serviceLayer`. + * + * **Example** (Providing layer dependencies) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1429,16 +1717,16 @@ export declare const provide: { * }>()("Logger") {} * * // Create dependency layers - * const databaseLayer = Layer.succeed(Database)({ + * const databaseLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`DB: ${sql}`)) * }) * - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(`[LOG] ${msg}`))) * }) * * // UserService depends on Database and Logger - * const userServiceLayer = Layer.effect(UserService)(Effect.gen(function*() { + * const userServiceLayer = Layer.effect(UserService, Effect.gen(function*() { * const database = yield* Database * const logger = yield* Logger * @@ -1467,18 +1755,29 @@ export declare const provide: { * ) * ``` * + * @see {@link provideMerge} for retaining the dependency services + * + * @category providing services * @since 2.0.0 - * @category utils */ ]>(that: Layers): (self: Layer) => Layer, Services | Exclude>>; /** - * Feeds the output services of this builder into the input of the specified - * builder, resulting in a new builder with the inputs of this builder as - * well as any leftover inputs, and the outputs of the specified builder. + * Feeds the output services of the dependency layer into the requirements of + * this layer, returning a layer that only provides the services from this layer. + * + * **When to use** + * + * Use when you need to hide an implementation dependency layer from callers. + * + * **Details** + * + * In `serviceLayer.pipe(Layer.provide(dependencyLayer))`, the dependency layer is + * built first and is used to satisfy the requirements of `serviceLayer`. + * + * **Example** (Providing layer dependencies) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1496,16 +1795,16 @@ export declare const provide: { * }>()("Logger") {} * * // Create dependency layers - * const databaseLayer = Layer.succeed(Database)({ + * const databaseLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`DB: ${sql}`)) * }) * - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(`[LOG] ${msg}`))) * }) * * // UserService depends on Database and Logger - * const userServiceLayer = Layer.effect(UserService)(Effect.gen(function*() { + * const userServiceLayer = Layer.effect(UserService, Effect.gen(function*() { * const database = yield* Database * const logger = yield* Logger * @@ -1534,18 +1833,29 @@ export declare const provide: { * ) * ``` * + * @see {@link provideMerge} for retaining the dependency services + * + * @category providing services * @since 2.0.0 - * @category utils */ (self: Layer, that: Layer): Layer>; /** - * Feeds the output services of this builder into the input of the specified - * builder, resulting in a new builder with the inputs of this builder as - * well as any leftover inputs, and the outputs of the specified builder. + * Feeds the output services of the dependency layer into the requirements of + * this layer, returning a layer that only provides the services from this layer. + * + * **When to use** + * + * Use when you need to hide an implementation dependency layer from callers. + * + * **Details** + * + * In `serviceLayer.pipe(Layer.provide(dependencyLayer))`, the dependency layer is + * built first and is used to satisfy the requirements of `serviceLayer`. + * + * **Example** (Providing layer dependencies) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1563,16 +1873,16 @@ export declare const provide: { * }>()("Logger") {} * * // Create dependency layers - * const databaseLayer = Layer.succeed(Database)({ + * const databaseLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`DB: ${sql}`)) * }) * - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(`[LOG] ${msg}`))) * }) * * // UserService depends on Database and Logger - * const userServiceLayer = Layer.effect(UserService)(Effect.gen(function*() { + * const userServiceLayer = Layer.effect(UserService, Effect.gen(function*() { * const database = yield* Database * const logger = yield* Logger * @@ -1601,19 +1911,30 @@ export declare const provide: { * ) * ``` * + * @see {@link provideMerge} for retaining the dependency services + * + * @category providing services * @since 2.0.0 - * @category utils */ ]>(self: Layer, that: Layers): Layer, Services | Exclude>>; }; /** - * Feeds the output services of this layer into the input of the specified - * layer, resulting in a new layer with the inputs of this layer, and the - * outputs of both layers. + * Feeds the output services of the dependency layer into the requirements of + * this layer, returning a layer that provides both sets of services. + * + * **When to use** + * + * Use when you need to compose `Layer`s while keeping both the constructed + * service and the dependency used to build it available. + * + * **Details** + * + * Prefer {@link provide} when the dependency should stay private. + * + * **Example** (Providing dependencies while retaining services) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1631,16 +1952,16 @@ export declare const provide: { * }>()("UserService") {} * * // Create dependency layers - * const databaseLayer = Layer.succeed(Database)({ + * const databaseLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`DB: ${sql}`)) * }) * - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(`[LOG] ${msg}`))) * }) * * // UserService depends on Database and Logger - * const userServiceLayer = Layer.effect(UserService)(Effect.gen(function*() { + * const userServiceLayer = Layer.effect(UserService, Effect.gen(function*() { * const database = yield* Database * const logger = yield* Logger * @@ -1675,18 +1996,29 @@ export declare const provide: { * ) * ``` * + * @see {@link provide} for keeping dependency services private + * + * @category providing services * @since 2.0.0 - * @category utils */ export declare const provideMerge: { /** - * Feeds the output services of this layer into the input of the specified - * layer, resulting in a new layer with the inputs of this layer, and the - * outputs of both layers. + * Feeds the output services of the dependency layer into the requirements of + * this layer, returning a layer that provides both sets of services. + * + * **When to use** + * + * Use when you need to compose `Layer`s while keeping both the constructed + * service and the dependency used to build it available. + * + * **Details** + * + * Prefer {@link provide} when the dependency should stay private. + * + * **Example** (Providing dependencies while retaining services) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1704,16 +2036,16 @@ export declare const provideMerge: { * }>()("UserService") {} * * // Create dependency layers - * const databaseLayer = Layer.succeed(Database)({ + * const databaseLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`DB: ${sql}`)) * }) * - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(`[LOG] ${msg}`))) * }) * * // UserService depends on Database and Logger - * const userServiceLayer = Layer.effect(UserService)(Effect.gen(function*() { + * const userServiceLayer = Layer.effect(UserService, Effect.gen(function*() { * const database = yield* Database * const logger = yield* Logger * @@ -1748,18 +2080,29 @@ export declare const provideMerge: { * ) * ``` * + * @see {@link provide} for keeping dependency services private + * + * @category providing services * @since 2.0.0 - * @category utils */ (that: Layer): (self: Layer) => Layer>; /** - * Feeds the output services of this layer into the input of the specified - * layer, resulting in a new layer with the inputs of this layer, and the - * outputs of both layers. + * Feeds the output services of the dependency layer into the requirements of + * this layer, returning a layer that provides both sets of services. + * + * **When to use** + * + * Use when you need to compose `Layer`s while keeping both the constructed + * service and the dependency used to build it available. + * + * **Details** + * + * Prefer {@link provide} when the dependency should stay private. + * + * **Example** (Providing dependencies while retaining services) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1777,16 +2120,16 @@ export declare const provideMerge: { * }>()("UserService") {} * * // Create dependency layers - * const databaseLayer = Layer.succeed(Database)({ + * const databaseLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`DB: ${sql}`)) * }) * - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(`[LOG] ${msg}`))) * }) * * // UserService depends on Database and Logger - * const userServiceLayer = Layer.effect(UserService)(Effect.gen(function*() { + * const userServiceLayer = Layer.effect(UserService, Effect.gen(function*() { * const database = yield* Database * const logger = yield* Logger * @@ -1821,18 +2164,29 @@ export declare const provideMerge: { * ) * ``` * + * @see {@link provide} for keeping dependency services private + * + * @category providing services * @since 2.0.0 - * @category utils */ ]>(that: Layers): (self: Layer) => Layer, E | Error, Services | Exclude>>; /** - * Feeds the output services of this layer into the input of the specified - * layer, resulting in a new layer with the inputs of this layer, and the - * outputs of both layers. + * Feeds the output services of the dependency layer into the requirements of + * this layer, returning a layer that provides both sets of services. + * + * **When to use** + * + * Use when you need to compose `Layer`s while keeping both the constructed + * service and the dependency used to build it available. + * + * **Details** + * + * Prefer {@link provide} when the dependency should stay private. + * + * **Example** (Providing dependencies while retaining services) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1850,16 +2204,16 @@ export declare const provideMerge: { * }>()("UserService") {} * * // Create dependency layers - * const databaseLayer = Layer.succeed(Database)({ + * const databaseLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`DB: ${sql}`)) * }) * - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(`[LOG] ${msg}`))) * }) * * // UserService depends on Database and Logger - * const userServiceLayer = Layer.effect(UserService)(Effect.gen(function*() { + * const userServiceLayer = Layer.effect(UserService, Effect.gen(function*() { * const database = yield* Database * const logger = yield* Logger * @@ -1894,18 +2248,29 @@ export declare const provideMerge: { * ) * ``` * + * @see {@link provide} for keeping dependency services private + * + * @category providing services * @since 2.0.0 - * @category utils */ (self: Layer, that: Layer): Layer>; /** - * Feeds the output services of this layer into the input of the specified - * layer, resulting in a new layer with the inputs of this layer, and the - * outputs of both layers. + * Feeds the output services of the dependency layer into the requirements of + * this layer, returning a layer that provides both sets of services. + * + * **When to use** + * + * Use when you need to compose `Layer`s while keeping both the constructed + * service and the dependency used to build it available. + * + * **Details** + * + * Prefer {@link provide} when the dependency should stay private. + * + * **Example** (Providing dependencies while retaining services) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1923,16 +2288,16 @@ export declare const provideMerge: { * }>()("UserService") {} * * // Create dependency layers - * const databaseLayer = Layer.succeed(Database)({ + * const databaseLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`DB: ${sql}`)) * }) * - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(`[LOG] ${msg}`))) * }) * * // UserService depends on Database and Logger - * const userServiceLayer = Layer.effect(UserService)(Effect.gen(function*() { + * const userServiceLayer = Layer.effect(UserService, Effect.gen(function*() { * const database = yield* Database * const logger = yield* Logger * @@ -1967,17 +2332,20 @@ export declare const provideMerge: { * ) * ``` * + * @see {@link provide} for keeping dependency services private + * + * @category providing services * @since 2.0.0 - * @category utils */ ]>(self: Layer, that: Layers): Layer, E | Error, Services | Exclude>>; }; /** * Constructs a layer dynamically based on the output of this layer. * - * @example + * **Example** (Creating services from layer output) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Config extends Context.Service()("Logger") {} * * // Base config layer - * const configLayer = Layer.succeed(Config)({ + * const configLayer = Layer.succeed(Config, { * dbUrl: "postgres://localhost:5432/mydb", * logLevel: "debug" * }) @@ -2004,7 +2372,7 @@ export declare const provideMerge: { * const config = Context.get(context, Config) * * // Create database layer based on config - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => * Effect.succeed( * `Querying ${config.dbUrl}: ${sql}` @@ -2012,7 +2380,7 @@ export declare const provideMerge: { * }) * * // Create logger layer based on config - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => * config.logLevel === "debug" * ? Effect.sync(() => console.log(`[DEBUG] ${msg}`)) @@ -2039,16 +2407,17 @@ export declare const provideMerge: { * ) * ``` * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ export declare const flatMap: { /** * Constructs a layer dynamically based on the output of this layer. * - * @example + * **Example** (Creating services from layer output) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Config extends Context.Service()("Logger") {} * * // Base config layer - * const configLayer = Layer.succeed(Config)({ + * const configLayer = Layer.succeed(Config, { * dbUrl: "postgres://localhost:5432/mydb", * logLevel: "debug" * }) @@ -2075,7 +2444,7 @@ export declare const flatMap: { * const config = Context.get(context, Config) * * // Create database layer based on config - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => * Effect.succeed( * `Querying ${config.dbUrl}: ${sql}` @@ -2083,7 +2452,7 @@ export declare const flatMap: { * }) * * // Create logger layer based on config - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => * config.logLevel === "debug" * ? Effect.sync(() => console.log(`[DEBUG] ${msg}`)) @@ -2110,16 +2479,17 @@ export declare const flatMap: { * ) * ``` * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ (f: (context: Context.Context) => Layer): (self: Layer) => Layer; /** * Constructs a layer dynamically based on the output of this layer. * - * @example + * **Example** (Creating services from layer output) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Config extends Context.Service()("Logger") {} * * // Base config layer - * const configLayer = Layer.succeed(Config)({ + * const configLayer = Layer.succeed(Config, { * dbUrl: "postgres://localhost:5432/mydb", * logLevel: "debug" * }) @@ -2146,7 +2516,7 @@ export declare const flatMap: { * const config = Context.get(context, Config) * * // Create database layer based on config - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => * Effect.succeed( * `Querying ${config.dbUrl}: ${sql}` @@ -2154,7 +2524,7 @@ export declare const flatMap: { * }) * * // Create logger layer based on config - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => * config.logLevel === "debug" * ? Effect.sync(() => console.log(`[DEBUG] ${msg}`)) @@ -2181,102 +2551,219 @@ export declare const flatMap: { * ) * ``` * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ (self: Layer, f: (context: Context.Context) => Layer): Layer; }; /** * Performs the specified effect if this layer succeeds. * - * @since 4.0.0 + * **When to use** + * + * Use to run an effectful observation after a layer has been built + * successfully, such as logging or metrics, without changing the services the + * layer provides. + * + * **Details** + * + * The callback receives the services produced by this layer. Its result is + * discarded, and the original layer output is preserved. + * + * @see {@link tapError} for running an effect when layer construction fails with a typed error + * @see {@link tapCause} for running an effect when layer construction fails with any cause + * * @category sequencing + * @since 2.0.0 */ export declare const tap: { /** * Performs the specified effect if this layer succeeds. * - * @since 4.0.0 + * **When to use** + * + * Use to run an effectful observation after a layer has been built + * successfully, such as logging or metrics, without changing the services the + * layer provides. + * + * **Details** + * + * The callback receives the services produced by this layer. Its result is + * discarded, and the original layer output is preserved. + * + * @see {@link tapError} for running an effect when layer construction fails with a typed error + * @see {@link tapCause} for running an effect when layer construction fails with any cause + * * @category sequencing + * @since 2.0.0 */ (f: (context: Context.Context) => Effect): (self: Layer) => Layer>; /** * Performs the specified effect if this layer succeeds. * - * @since 4.0.0 + * **When to use** + * + * Use to run an effectful observation after a layer has been built + * successfully, such as logging or metrics, without changing the services the + * layer provides. + * + * **Details** + * + * The callback receives the services produced by this layer. Its result is + * discarded, and the original layer output is preserved. + * + * @see {@link tapError} for running an effect when layer construction fails with a typed error + * @see {@link tapCause} for running an effect when layer construction fails with any cause + * * @category sequencing + * @since 2.0.0 */ (self: Layer, f: (context: Context.Context) => Effect): Layer>; }; /** * Performs the specified effect if this layer fails. * - * @since 4.0.0 + * **When to use** + * + * Use to run logging, metrics, or other effects when layer construction fails + * while preserving the original typed error. + * + * **Details** + * + * The callback receives the typed error. If the callback succeeds, the layer + * still fails with the original error; if the callback fails, that failure is + * added to the layer's error type. + * + * @see {@link tap} for running an effect when layer construction succeeds + * @see {@link tapCause} for inspecting the full failure cause, including defects and interruption + * * @category sequencing + * @since 2.0.0 */ export declare const tapError: { /** * Performs the specified effect if this layer fails. * - * @since 4.0.0 + * **When to use** + * + * Use to run logging, metrics, or other effects when layer construction fails + * while preserving the original typed error. + * + * **Details** + * + * The callback receives the typed error. If the callback succeeds, the layer + * still fails with the original error; if the callback fails, that failure is + * added to the layer's error type. + * + * @see {@link tap} for running an effect when layer construction succeeds + * @see {@link tapCause} for inspecting the full failure cause, including defects and interruption + * * @category sequencing + * @since 2.0.0 */ (f: (e: XE) => Effect): (self: Layer) => Layer>; /** * Performs the specified effect if this layer fails. * - * @since 4.0.0 + * **When to use** + * + * Use to run logging, metrics, or other effects when layer construction fails + * while preserving the original typed error. + * + * **Details** + * + * The callback receives the typed error. If the callback succeeds, the layer + * still fails with the original error; if the callback fails, that failure is + * added to the layer's error type. + * + * @see {@link tap} for running an effect when layer construction succeeds + * @see {@link tapCause} for inspecting the full failure cause, including defects and interruption + * * @category sequencing + * @since 2.0.0 */ (self: Layer, f: (e: XE) => Effect): Layer>; }; /** - * Performs the specified effect if this layer fails. + * Performs the specified effect when this layer fails with any cause. + * + * **When to use** * - * **Previously Known As** + * Use to run diagnostics or reporting when layer construction fails and the + * full `Cause` is needed. * - * This API replaces the following from Effect 3.x: + * **Details** * - * - `Layer.tapErrorCause` + * The callback receives the layer's `Cause`, so it can inspect typed errors, + * defects, and interruption information. If the callback succeeds, the layer + * fails again with the original cause; if the callback fails, that failure is + * added to the layer's error type. + * + * @see {@link tapError} for observing only typed layer construction errors + * @see {@link catchCause} for recovering from a layer construction failure by switching to another layer * - * @since 4.0.0 * @category sequencing + * @since 4.0.0 */ export declare const tapCause: { /** - * Performs the specified effect if this layer fails. + * Performs the specified effect when this layer fails with any cause. + * + * **When to use** * - * **Previously Known As** + * Use to run diagnostics or reporting when layer construction fails and the + * full `Cause` is needed. * - * This API replaces the following from Effect 3.x: + * **Details** * - * - `Layer.tapErrorCause` + * The callback receives the layer's `Cause`, so it can inspect typed errors, + * defects, and interruption information. If the callback succeeds, the layer + * fails again with the original cause; if the callback fails, that failure is + * added to the layer's error type. + * + * @see {@link tapError} for observing only typed layer construction errors + * @see {@link catchCause} for recovering from a layer construction failure by switching to another layer * - * @since 4.0.0 * @category sequencing + * @since 4.0.0 */ (f: (cause: Cause.Cause) => Effect): (self: Layer) => Layer>; /** - * Performs the specified effect if this layer fails. + * Performs the specified effect when this layer fails with any cause. + * + * **When to use** * - * **Previously Known As** + * Use to run diagnostics or reporting when layer construction fails and the + * full `Cause` is needed. * - * This API replaces the following from Effect 3.x: + * **Details** * - * - `Layer.tapErrorCause` + * The callback receives the layer's `Cause`, so it can inspect typed errors, + * defects, and interruption information. If the callback succeeds, the layer + * fails again with the original cause; if the callback fails, that failure is + * added to the layer's error type. + * + * @see {@link tapError} for observing only typed layer construction errors + * @see {@link catchCause} for recovering from a layer construction failure by switching to another layer * - * @since 4.0.0 * @category sequencing + * @since 4.0.0 */ (self: Layer, f: (cause: Cause.Cause) => Effect): Layer>; }; /** - * Translates effect failure into death of the fiber, making all failures - * unchecked and not a part of the type of the layer. + * Converts layer construction failures into defects, removing them from the + * layer's error type. + * + * **Details** + * + * Use this only when failures should be treated as unrecoverable defects rather + * than typed errors that callers can handle. + * + * **Example** (Converting layer failures to defects) * - * @example * ```ts - * import { Data, Effect, Layer, Context } from "effect" + * import { Context, Data, Effect, Layer } from "effect" * * class DatabaseError extends Data.TaggedError("DatabaseError")<{ * message: string @@ -2287,14 +2774,9 @@ export declare const tapCause: { * }>()("Database") {} * * // Layer that can fail during construction - * const flakyDatabaseLayer = Layer.effect(Database)(Effect.gen(function*() { - * // Simulate a database connection that might fail - * const shouldFail = Math.random() > 0.5 - * if (shouldFail) { - * return yield* new DatabaseError({ message: "Connection failed" }) - * } - * - * return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } + * const flakyDatabaseLayer = Layer.effect(Database, Effect.gen(function*() { + * console.log("connecting") + * return yield* new DatabaseError({ message: "Connection failed" }) * })) * * // Convert failures to fiber death - removes error from type @@ -2308,12 +2790,12 @@ export declare const tapCause: { * Effect.provide(reliableDatabaseLayer) * ) * - * // If the database layer fails, the entire fiber will die - * // instead of the effect failing with DatabaseError + * // Running the program prints "connecting", then the DatabaseError is + * // converted into a fiber defect instead of remaining a typed error. * ``` * - * @since 2.0.0 * @category error handling + * @since 2.0.0 */ export declare const orDie: (self: Layer) => Layer; declare const catch_: { @@ -2322,18 +2804,31 @@ declare const catch_: { }; export { /** - * Recovers from all errors. + * Recovers from all typed errors by switching to another layer. + * + * **When to use** + * + * Use when every typed `Layer` construction error should use the same + * recovery path. + * + * @see {@link catchTag} for recovering from specific tagged errors + * @see {@link catchCause} for recovering with access to the full cause * - * @since 4.0.0 * @category error handling + * @since 4.0.0 */ catch_ as catch }; /** * Recovers from specific tagged errors. * - * @example + * **When to use** + * + * Use when only some tagged `Layer` construction errors should be recovered. + * + * **Example** (Recovering from tagged layer errors) + * * ```ts - * import { Data, Effect, Layer, Context } from "effect" + * import { Context, Data, Effect, Layer } from "effect" * * class ConfigError extends Data.TaggedError("ConfigError") {} * @@ -2341,25 +2836,32 @@ catch_ as catch }; * readonly apiUrl: string * }>()("Config") {} * - * const configLayer = Layer.effect(Config)(Effect.fail(new ConfigError())) + * const configLayer = Layer.effect(Config, Effect.fail(new ConfigError())) * - * const fallbackLayer = Layer.succeed(Config)({ apiUrl: "http://localhost" }) + * const fallbackLayer = Layer.succeed(Config, { apiUrl: "http://localhost" }) * * const recovered = configLayer.pipe( * Layer.catchTag("ConfigError", () => fallbackLayer) * ) * ``` * - * @since 4.0.0 + * @see {@link catchCause} for recovering with access to the full cause + * * @category error handling + * @since 4.0.0 */ export declare const catchTag: { /** * Recovers from specific tagged errors. * - * @example + * **When to use** + * + * Use when only some tagged `Layer` construction errors should be recovered. + * + * **Example** (Recovering from tagged layer errors) + * * ```ts - * import { Data, Effect, Layer, Context } from "effect" + * import { Context, Data, Effect, Layer } from "effect" * * class ConfigError extends Data.TaggedError("ConfigError") {} * @@ -2367,25 +2869,32 @@ export declare const catchTag: { * readonly apiUrl: string * }>()("Config") {} * - * const configLayer = Layer.effect(Config)(Effect.fail(new ConfigError())) + * const configLayer = Layer.effect(Config, Effect.fail(new ConfigError())) * - * const fallbackLayer = Layer.succeed(Config)({ apiUrl: "http://localhost" }) + * const fallbackLayer = Layer.succeed(Config, { apiUrl: "http://localhost" }) * * const recovered = configLayer.pipe( * Layer.catchTag("ConfigError", () => fallbackLayer) * ) * ``` * - * @since 4.0.0 + * @see {@link catchCause} for recovering with access to the full cause + * * @category error handling + * @since 4.0.0 */ | NonEmptyReadonlyArray>, E, RIn2, E2, ROut2>(k: K, f: (e: Types.ExtractTag, K extends NonEmptyReadonlyArray ? K[number] : K>) => Layer): (self: Layer) => Layer ? K[number] : K>, RIn2 | RIn>; /** * Recovers from specific tagged errors. * - * @example + * **When to use** + * + * Use when only some tagged `Layer` construction errors should be recovered. + * + * **Example** (Recovering from tagged layer errors) + * * ```ts - * import { Data, Effect, Layer, Context } from "effect" + * import { Context, Data, Effect, Layer } from "effect" * * class ConfigError extends Data.TaggedError("ConfigError") {} * @@ -2393,198 +2902,205 @@ export declare const catchTag: { * readonly apiUrl: string * }>()("Config") {} * - * const configLayer = Layer.effect(Config)(Effect.fail(new ConfigError())) + * const configLayer = Layer.effect(Config, Effect.fail(new ConfigError())) * - * const fallbackLayer = Layer.succeed(Config)({ apiUrl: "http://localhost" }) + * const fallbackLayer = Layer.succeed(Config, { apiUrl: "http://localhost" }) * * const recovered = configLayer.pipe( * Layer.catchTag("ConfigError", () => fallbackLayer) * ) * ``` * - * @since 4.0.0 + * @see {@link catchCause} for recovering with access to the full cause + * * @category error handling + * @since 4.0.0 */ | NonEmptyReadonlyArray>, RIn2, E2, ROut2>(self: Layer, k: K, f: (e: Types.ExtractTag ? K[number] : K>) => Layer): Layer ? K[number] : K>, RIn | RIn2>; }; /** - * Recovers from all errors. + * Recovers from any failure cause by switching to another layer. + * + * **When to use** + * + * Use when you need `Layer` recovery to inspect more than the typed error, + * such as defects or interruption information. + * + * **Details** + * + * The handler receives the full `Cause` of the failed layer, including typed + * errors, unexpected defects, and interruption information, and returns the + * fallback layer to build instead. Finalizers for resources acquired by the + * failed layer are still run before the fallback layer is acquired. + * + * **Example** (Recovering from layer failures by cause) * - * @example * ```ts - * import { Data, Effect, Layer, Context } from "effect" + * import { Context, Data, Effect, Layer } from "effect" * * class DatabaseError extends Data.TaggedError("DatabaseError")<{ * message: string * }> {} * - * class NetworkError extends Data.TaggedError("NetworkError")<{ - * reason: string - * }> {} - * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * - * class Logger extends Context.Service Effect.Effect - * }>()("Logger") {} - * - * // Primary database layer that might fail - * const primaryDatabaseLayer = Layer.effect(Database)(Effect.gen(function*() { - * return yield* new DatabaseError({ message: "Primary DB unreachable" }) - * return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Primary: ${sql}`)) } - * })) + * const primaryDatabaseLayer = Layer.effect(Database, + * Effect.fail(new DatabaseError({ message: "Primary DB unreachable" })) + * ) * - * // Fallback layers for different error causes * const databaseWithFallback = primaryDatabaseLayer.pipe( * Layer.catchCause(() => { - * // For any cause/error, fallback to in-memory database - * return Layer.mergeAll( - * Layer.succeed(Database)({ - * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Memory: ${sql}`)) - * }), - * Layer.succeed(Logger)({ - * log: Effect.fn("Logger.log")((msg: string) => - * Effect.sync(() => console.log(`[FALLBACK] ${msg}`)) - * ) - * }) - * ) + * return Layer.succeed(Database, { + * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Memory: ${sql}`)) + * }) * }) * ) * * const program = Effect.gen(function*() { * const database = yield* Database - * return yield* database.query("SELECT * FROM users") + * const result = yield* database.query("SELECT * FROM users") + * console.log(result) * }).pipe( * Effect.provide(databaseWithFallback) * ) + * + * Effect.runPromise(program) + * // Memory: SELECT * FROM users * ``` * - * @since 2.0.0 + * @see {@link catchTag} for recovering from specific tagged errors + * * @category error handling + * @since 4.0.0 */ export declare const catchCause: { /** - * Recovers from all errors. + * Recovers from any failure cause by switching to another layer. + * + * **When to use** + * + * Use when you need `Layer` recovery to inspect more than the typed error, + * such as defects or interruption information. + * + * **Details** + * + * The handler receives the full `Cause` of the failed layer, including typed + * errors, unexpected defects, and interruption information, and returns the + * fallback layer to build instead. Finalizers for resources acquired by the + * failed layer are still run before the fallback layer is acquired. + * + * **Example** (Recovering from layer failures by cause) * - * @example * ```ts - * import { Data, Effect, Layer, Context } from "effect" + * import { Context, Data, Effect, Layer } from "effect" * * class DatabaseError extends Data.TaggedError("DatabaseError")<{ * message: string * }> {} * - * class NetworkError extends Data.TaggedError("NetworkError")<{ - * reason: string - * }> {} - * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * - * class Logger extends Context.Service Effect.Effect - * }>()("Logger") {} - * - * // Primary database layer that might fail - * const primaryDatabaseLayer = Layer.effect(Database)(Effect.gen(function*() { - * return yield* new DatabaseError({ message: "Primary DB unreachable" }) - * return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Primary: ${sql}`)) } - * })) + * const primaryDatabaseLayer = Layer.effect(Database, + * Effect.fail(new DatabaseError({ message: "Primary DB unreachable" })) + * ) * - * // Fallback layers for different error causes * const databaseWithFallback = primaryDatabaseLayer.pipe( * Layer.catchCause(() => { - * // For any cause/error, fallback to in-memory database - * return Layer.mergeAll( - * Layer.succeed(Database)({ - * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Memory: ${sql}`)) - * }), - * Layer.succeed(Logger)({ - * log: Effect.fn("Logger.log")((msg: string) => - * Effect.sync(() => console.log(`[FALLBACK] ${msg}`)) - * ) - * }) - * ) + * return Layer.succeed(Database, { + * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Memory: ${sql}`)) + * }) * }) * ) * * const program = Effect.gen(function*() { * const database = yield* Database - * return yield* database.query("SELECT * FROM users") + * const result = yield* database.query("SELECT * FROM users") + * console.log(result) * }).pipe( * Effect.provide(databaseWithFallback) * ) + * + * Effect.runPromise(program) + * // Memory: SELECT * FROM users * ``` * - * @since 2.0.0 + * @see {@link catchTag} for recovering from specific tagged errors + * * @category error handling + * @since 4.0.0 */ (onError: (cause: Cause.Cause) => Layer): (self: Layer) => Layer; /** - * Recovers from all errors. + * Recovers from any failure cause by switching to another layer. + * + * **When to use** + * + * Use when you need `Layer` recovery to inspect more than the typed error, + * such as defects or interruption information. + * + * **Details** + * + * The handler receives the full `Cause` of the failed layer, including typed + * errors, unexpected defects, and interruption information, and returns the + * fallback layer to build instead. Finalizers for resources acquired by the + * failed layer are still run before the fallback layer is acquired. + * + * **Example** (Recovering from layer failures by cause) * - * @example * ```ts - * import { Data, Effect, Layer, Context } from "effect" + * import { Context, Data, Effect, Layer } from "effect" * * class DatabaseError extends Data.TaggedError("DatabaseError")<{ * message: string * }> {} * - * class NetworkError extends Data.TaggedError("NetworkError")<{ - * reason: string - * }> {} - * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * - * class Logger extends Context.Service Effect.Effect - * }>()("Logger") {} - * - * // Primary database layer that might fail - * const primaryDatabaseLayer = Layer.effect(Database)(Effect.gen(function*() { - * return yield* new DatabaseError({ message: "Primary DB unreachable" }) - * return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Primary: ${sql}`)) } - * })) + * const primaryDatabaseLayer = Layer.effect(Database, + * Effect.fail(new DatabaseError({ message: "Primary DB unreachable" })) + * ) * - * // Fallback layers for different error causes * const databaseWithFallback = primaryDatabaseLayer.pipe( * Layer.catchCause(() => { - * // For any cause/error, fallback to in-memory database - * return Layer.mergeAll( - * Layer.succeed(Database)({ - * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Memory: ${sql}`)) - * }), - * Layer.succeed(Logger)({ - * log: Effect.fn("Logger.log")((msg: string) => - * Effect.sync(() => console.log(`[FALLBACK] ${msg}`)) - * ) - * }) - * ) + * return Layer.succeed(Database, { + * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Memory: ${sql}`)) + * }) * }) * ) * * const program = Effect.gen(function*() { * const database = yield* Database - * return yield* database.query("SELECT * FROM users") + * const result = yield* database.query("SELECT * FROM users") + * console.log(result) * }).pipe( * Effect.provide(databaseWithFallback) * ) + * + * Effect.runPromise(program) + * // Memory: SELECT * FROM users * ``` * - * @since 2.0.0 + * @see {@link catchTag} for recovering from specific tagged errors + * * @category error handling + * @since 4.0.0 */ (self: Layer, onError: (cause: Cause.Cause) => Layer): Layer; }; /** * Updates a service in the context with a new implementation. * + * **When to use** + * + * Use to adapt or extend a service's behavior during the creation of a + * layer. + * * **Details** * * This function modifies the existing implementation of a service in the @@ -2592,18 +3108,18 @@ export declare const catchCause: { * transformation function `f`, and replaces the old service with the * transformed one. * - * **When to Use** - * - * This is useful for adapting or extending a service's behavior during the - * creation of a layer. - * + * @category providing services * @since 3.13.0 - * @category utils */ export declare const updateService: { /** * Updates a service in the context with a new implementation. * + * **When to use** + * + * Use to adapt or extend a service's behavior during the creation of a + * layer. + * * **Details** * * This function modifies the existing implementation of a service in the @@ -2611,18 +3127,18 @@ export declare const updateService: { * transformation function `f`, and replaces the old service with the * transformed one. * - * **When to Use** - * - * This is useful for adapting or extending a service's behavior during the - * creation of a layer. - * + * @category providing services * @since 3.13.0 - * @category utils */ (service: Context.Key, f: (a: Types.NoInfer) => A): (layer: Layer) => Layer; /** * Updates a service in the context with a new implementation. * + * **When to use** + * + * Use to adapt or extend a service's behavior during the creation of a + * layer. + * * **Details** * * This function modifies the existing implementation of a service in the @@ -2630,75 +3146,111 @@ export declare const updateService: { * transformation function `f`, and replaces the old service with the * transformed one. * - * **When to Use** - * - * This is useful for adapting or extending a service's behavior during the - * creation of a layer. - * + * @category providing services * @since 3.13.0 - * @category utils */ (layer: Layer, service: Context.Key, f: (a: Types.NoInfer) => A): Layer; }; /** * Creates a fresh version of this layer that will not be shared. * - * @example + * **When to use** + * + * Use when you need two parts of an application to receive separate instances + * of a resource, such as two independent client sessions. + * + * **Gotchas** + * + * Do not use it just to work around confusing composition. By default, sharing + * the same layer value is usually the desired behavior. + * + * **Example** (Creating non-shared layer instances) + * * ```ts - * import { Effect, Layer, Ref, Context } from "effect" + * import { Context, Effect, Layer, Ref } from "effect" * * class Counter extends Context.Service Effect.Effect + * readonly id: number * }>()("Counter") {} * - * // Layer that creates a counter with shared state - * const counterLayer = Layer.effect(Counter)(Effect.gen(function*() { - * const ref = yield* Ref.make(0) - * return { - * count: 0, - * increment: Effect.fn("Counter.increment")(() => - * Ref.update(ref, (n) => n + 1).pipe( - * Effect.flatMap(() => Ref.get(ref)) - * ) - * ) - * } + * class Left extends Context.Service()("Left") {} + * + * class Right extends Context.Service()("Right") {} + * + * const leftLayer = Layer.effect(Left, Effect.gen(function*() { + * const counter = yield* Counter + * return { counterId: counter.id } + * })) + * + * const rightLayer = Layer.effect(Right, Effect.gen(function*() { + * const counter = yield* Counter + * return { counterId: counter.id } * })) * - * // By default, layers are shared - same instance used everywhere - * const sharedProgram = Effect.gen(function*() { - * const counter1 = yield* Counter - * const counter2 = yield* Counter + * const showIds = Effect.gen(function*() { + * const left = yield* Left + * const right = yield* Right + * console.log(`same Counter: ${left.counterId === right.counterId}`) + * }) * - * // Both counter1 and counter2 refer to the same instance - * console.log("Shared layer - same instance") - * }).pipe( - * Effect.provide(counterLayer) - * ) + * const program = Effect.gen(function*() { + * const nextId = yield* Ref.make(0) * - * // Fresh layer creates a new instance each time - * const freshProgram = Effect.gen(function*() { - * const counter1 = yield* Counter - * const counter2 = yield* Counter + * const counterLayer = Layer.effect(Counter, Effect.gen(function*() { + * const id = yield* Ref.updateAndGet(nextId, (n) => n + 1) + * console.log("constructed Counter") + * return { id } + * })) * - * // counter1 and counter2 are different instances - * console.log("Fresh layer - different instances") - * }).pipe( - * Effect.provide(Layer.fresh(counterLayer)) - * ) + * const shared = Layer.merge( + * Layer.provide(leftLayer, counterLayer), + * Layer.provide(rightLayer, counterLayer) + * ) + * + * yield* Effect.provide(showIds, shared) + * + * const freshCounterLayer = Layer.fresh(counterLayer) + * const fresh = Layer.merge( + * Layer.provide(leftLayer, freshCounterLayer), + * Layer.provide(rightLayer, freshCounterLayer) + * ) + * + * yield* Effect.provide(showIds, fresh) + * }) + * + * Effect.runPromise(program) + * // constructed Counter + * // same Counter: true + * // constructed Counter + * // constructed Counter + * // same Counter: false * ``` * + * @category layers * @since 2.0.0 - * @category utils */ export declare const fresh: (self: Layer) => Layer; /** - * Builds this layer and uses it until it is interrupted. This is useful when - * your entire application is a layer, such as an HTTP server. + * Builds this layer and keeps it alive until the returned effect is interrupted. + * + * **When to use** + * + * Use when you model your entire application as a layer, such as an HTTP + * server. + * + * **Details** + * + * When the returned effect is interrupted, the layer scope is closed and all + * finalizers registered during layer acquisition are run. + * + * **Example** (Launching an application layer) * - * @example * ```ts - * import { Console, Effect, Layer, Context } from "effect" + * import { Console, Context, Effect, Layer } from "effect" * * class HttpServer extends Context.Service Effect.Effect @@ -2710,7 +3262,7 @@ export declare const fresh: (self: Layer) => Layer; * }>()("Logger") {} * * // Server layer that starts an HTTP server - * const serverLayer = Layer.effect(HttpServer)(Effect.gen(function*() { + * const serverLayer = Layer.effect(HttpServer, Effect.gen(function*() { * yield* Console.log("Starting HTTP server...") * * return { @@ -2725,7 +3277,7 @@ export declare const fresh: (self: Layer) => Layer; * } * })) * - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Console.log(`[LOG] ${msg}`)) * }) * @@ -2743,19 +3295,29 @@ export declare const fresh: (self: Layer) => Layer; * // Effect.runFork(application) * ``` * + * @category converting * @since 2.0.0 - * @category conversions */ export declare const launch: (self: Layer) => Effect; /** * A utility type for creating partial mocks of services in testing. * - * This type makes Effect methods and Effect-returning functions optional, - * while keeping non-Effect properties required. This allows you to provide - * only the methods you need to test while leaving others unimplemented. + * **When to use** * - * @since 4.0.0 - * @category Testing + * Use to type partial test service implementations where only exercised + * effectful members are stubbed. + * + * **Details** + * + * This type makes `Effect`, `Stream`, and `Channel` values and functions + * returning them optional, while keeping non-effectful properties required. + * This allows you to provide only the methods you need to test while leaving + * others unimplemented. + * + * @see {@link mock} for creating a mock layer from a partial service implementation + * + * @category testing + * @since 3.17.0 */ export type PartialEffectful = Types.Simplify<{ [K in keyof A as A[K] extends AnyEffectOrStream ? K : never]?: A[K]; @@ -2765,12 +3327,21 @@ export type PartialEffectful = Types.Simplify<{ type AnyEffectOrStream = Effect | Stream.Stream | Channel.Channel | ((...args: any) => Effect) | ((...args: any) => Stream.Stream) | ((...args: any) => Channel.Channel); /** * Creates a mock layer for testing purposes. You can provide a partial - * implementation of the service, and any methods not provided will - * throw an unimplemented defect when called. + * implementation of the service. Any missing members that are `Effect`s, + * `Stream`s, `Channel`s, or functions returning them will fail with an + * unimplemented defect when used. + * + * **Details** + * + * Missing members are represented by a value that can be used as an `Effect`, + * `Stream`, `Channel`, or as a function returning an `Effect`. This lets the + * mock preserve the shape of common service methods while still failing loudly + * when an unimplemented member is exercised. + * + * **Example** (Mocking services for tests) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class UserService extends Context.Service | Stream.Stream | * ) * ``` * - * @since 4.0.0 - * @category Testing + * @category testing + * @since 3.17.0 */ export declare const mock: { /** * Creates a mock layer for testing purposes. You can provide a partial - * implementation of the service, and any methods not provided will - * throw an unimplemented defect when called. + * implementation of the service. Any missing members that are `Effect`s, + * `Stream`s, `Channel`s, or functions returning them will fail with an + * unimplemented defect when used. + * + * **Details** + * + * Missing members are represented by a value that can be used as an `Effect`, + * `Stream`, `Channel`, or as a function returning an `Effect`. This lets the + * mock preserve the shape of common service methods while still failing loudly + * when an unimplemented member is exercised. + * + * **Example** (Mocking services for tests) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class UserService extends Context.Service(service: Context.Key): (implementation: PartialEffectful) => Layer; /** * Creates a mock layer for testing purposes. You can provide a partial - * implementation of the service, and any methods not provided will - * throw an unimplemented defect when called. + * implementation of the service. Any missing members that are `Effect`s, + * `Stream`s, `Channel`s, or functions returning them will fail with an + * unimplemented defect when used. + * + * **Details** + * + * Missing members are represented by a value that can be used as an `Effect`, + * `Stream`, `Channel`, or as a function returning an `Effect`. This lets the + * mock preserve the shape of common service methods while still failing loudly + * when an unimplemented member is exercised. + * + * **Example** (Mocking services for tests) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class UserService extends Context.Service(service: Context.Key, implementation: Types.NoInfer>): Layer; }; /** - * Ensures that an layer's success type extends a given type `ROut`. + * Ensures that a layer's success type extends a given type `ROut`. + * + * **Details** * * This function provides compile-time type checking to ensure that the success - * value of an layer conforms to a specific type constraint. + * value of a layer conforms to a specific type constraint. + * + * **Example** (Constraining layer success types) * - * @example * ```ts * import { Layer } from "effect" * @@ -2927,20 +3519,23 @@ export declare const mock: { * // This would cause a TypeScript compilation error: * // const invalidLayer = satisfiesNumber(StringLayer) * // ^^^^^^^^^^^ - * // Type 'number' is not assignable to type 'string' + * // Type 'string' is not assignable to type 'number' * ``` * + * @category utility types * @since 4.0.0 - * @category Type constraints */ export declare const satisfiesSuccessType: () => (layer: Layer) => Layer; /** - * Ensures that an layer's error type extends a given type `E`. + * Ensures that a layer's error type extends a given type `E`. + * + * **Details** * * This function provides compile-time type checking to ensure that the error - * type of an layer conforms to a specific type constraint. + * type of a layer conforms to a specific type constraint. + * + * **Example** (Constraining layer error types) * - * @example * ```ts * import { Layer } from "effect" * @@ -2960,24 +3555,27 @@ export declare const satisfiesSuccessType: () => () => (layer: Layer) => Layer; /** - * Ensures that an layer's requirements type extends a given type `R`. + * Ensures that a layer's requirements type extends a given type `R`. + * + * **Details** * * This function provides compile-time type checking to ensure that the - * requirements (context) type of an layer conforms to a specific type constraint. + * requirements type of a layer conforms to a specific type constraint. + * + * **Example** (Constraining layer service requirements) * - * @example * ```ts * import { Layer } from "effect" * * declare const FortyTwoLayer: Layer.Layer * declare const StringLayer: Layer.Layer * - * // Define a constraint that the success type must be a number + * // Define a constraint that the service requirements must be numbers * const satisfiesNumber = Layer.satisfiesServicesType() * * // This works - Layer extends Layer @@ -2989,21 +3587,35 @@ export declare const satisfiesErrorType: () => (laye * // Type 'string' is not assignable to type 'number' * ``` * + * @category utility types * @since 4.0.0 - * @category Type constraints */ export declare const satisfiesServicesType: () => (layer: Layer) => Layer; /** * Represents options that can be used to control the behavior of spans created * for layers. * + * **When to use** + * + * Use to configure tracing metadata, stack trace capture, and `onEnd` + * finalization for spans created by `Layer.span` and `Layer.withSpan` during + * layer construction. + * + * **Details** + * + * Extends `Tracer.SpanOptions` with `onEnd`, which runs when the layer span + * ends as the layer scope closes. + * + * @see {@link span} for creating a layer span + * @see {@link withSpan} for wrapping layer construction in a span + * + * @category options * @since 4.0.0 - * @category Models */ export interface SpanOptions extends Tracer.SpanOptions { /** - * A function that will be called when the span associated with the layer is - * ending (i.e. when the `Scope` that the span is associated with is closed). + * Runs when the span associated with the layer ends, which happens when the + * layer scope is closed. */ readonly onEnd?: ((span: Tracer.Span, exit: Exit.Exit) => Effect) | undefined; } @@ -3011,13 +3623,19 @@ export interface SpanOptions extends Tracer.SpanOptions { * Constructs a new `Layer` which creates a span and registers it as the current * parent span. * + * **Details** + * * This allows you to create a traced scope for layer construction, making all * operations within the layer constructor part of the same trace span. The span - * is automatically closed when the layer's scope is closed. + * is automatically ended when the layer's scope is closed. If `onEnd` is + * provided, it receives the span and the layer scope's exit value when the span + * ends. + * + * **Example** (Tracing layer construction with a span) * - * @example * ```ts - * import { Console, Effect, Layer, Context, type Tracer } from "effect" + * import { Console, Context, Effect, Layer } from "effect" + * import type { Tracer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -3049,21 +3667,23 @@ export interface SpanOptions extends Tracer.SpanOptions { * }) * ``` * - * @since 4.0.0 * @category tracing + * @since 2.0.0 */ export declare const span: (name: string, options?: SpanOptions) => Layer; /** - * Constructs a new `Layer` which takes an existing span and registers it as the - * current parent span. + * Constructs a layer that provides an existing span as the current parent span. * - * This allows you to create a traced scope for layer construction, making all - * operations within the layer constructor part of the same trace span. The span - * is automatically closed when the layer's scope is closed. + * **Details** + * + * The supplied span is made available through `Tracer.ParentSpan` for layers + * that are built with this layer. This API does not create, end, or close the + * span; the caller remains responsible for the span's lifetime. + * + * **Example** (Using an existing parent span) * - * @example * ```ts - * import { Console, Effect, Layer, Context, Tracer } from "effect" + * import { Console, Context, Effect, Layer, Tracer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -3088,21 +3708,24 @@ export declare const span: (name: string, options?: SpanOptions) => Layer Layer; /** - * Wraps a Layer with a new tracing span, making all operations in the layer + * Wraps a `Layer` with a new tracing span, making all operations in the layer * constructor part of the named trace span. * + * **Details** + * * This creates a new span for the layer's construction and execution. The span * is automatically ended when the layer's scope is closed. This is useful for * tracking the lifecycle and performance of layer initialization. * - * @example + * **Example** (Wrapping a layer with a span) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -3143,25 +3766,27 @@ export declare const parentSpan: (span: Tracer.AnySpan) => Layer Effect.Effect @@ -3202,25 +3827,27 @@ export declare const withSpan: { * * yield* logger.log("Application ready") * return yield* database.query("SELECT * FROM users") - * }).pipe(Effect.provide(appLayer) - * ) + * }).pipe(Effect.provide(appLayer)) * ``` * - * @since 4.0.0 * @category tracing + * @since 2.0.0 */ (name: string, options?: SpanOptions): (self: Layer) => Layer>; /** - * Wraps a Layer with a new tracing span, making all operations in the layer + * Wraps a `Layer` with a new tracing span, making all operations in the layer * constructor part of the named trace span. * + * **Details** + * * This creates a new span for the layer's construction and execution. The span * is automatically ended when the layer's scope is closed. This is useful for * tracking the lifecycle and performance of layer initialization. * - * @example + * **Example** (Wrapping a layer with a span) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -3261,25 +3888,32 @@ export declare const withSpan: { * * yield* logger.log("Application ready") * return yield* database.query("SELECT * FROM users") - * }).pipe(Effect.provide(appLayer) - * ) + * }).pipe(Effect.provide(appLayer)) * ``` * - * @since 4.0.0 * @category tracing + * @since 2.0.0 */ (self: Layer, name: string, options?: SpanOptions): Layer>; }; /** - * Wraps a `Layer` with a new tracing span and sets the span as the parent span. + * Wraps a layer so spans created during its construction use the supplied span + * as their parent. + * + * **Details** * - * This attaches a layer to an existing trace span, making all operations within - * the layer children of the provided parent span. This is useful for integrating - * layer construction into an existing trace hierarchy. + * Use this to attach layer construction to an existing trace hierarchy. This API + * does not create or end the supplied parent span. + * + * When the supplied span is a native `Span`, layer construction also receives + * diagnostic information that helps associate failures with the layer call site. + * External spans are only installed as the parent span and do not add this + * diagnostic call-site information. + * + * **Example** (Attaching layers to an existing parent span) * - * @example * ```ts - * import { Effect, Layer, Context, Tracer } from "effect" + * import { Context, Effect, Layer, Tracer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -3326,20 +3960,28 @@ export declare const withSpan: { * ) * ``` * - * @since 4.0.0 * @category tracing + * @since 2.0.0 */ export declare const withParentSpan: { /** - * Wraps a `Layer` with a new tracing span and sets the span as the parent span. + * Wraps a layer so spans created during its construction use the supplied span + * as their parent. + * + * **Details** + * + * Use this to attach layer construction to an existing trace hierarchy. This API + * does not create or end the supplied parent span. + * + * When the supplied span is a native `Span`, layer construction also receives + * diagnostic information that helps associate failures with the layer call site. + * External spans are only installed as the parent span and do not add this + * diagnostic call-site information. * - * This attaches a layer to an existing trace span, making all operations within - * the layer children of the provided parent span. This is useful for integrating - * layer construction into an existing trace hierarchy. + * **Example** (Attaching layers to an existing parent span) * - * @example * ```ts - * import { Effect, Layer, Context, Tracer } from "effect" + * import { Context, Effect, Layer, Tracer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -3386,20 +4028,28 @@ export declare const withParentSpan: { * ) * ``` * - * @since 4.0.0 * @category tracing + * @since 2.0.0 */ (span: Tracer.AnySpan, options?: Tracer.TraceOptions): (self: Layer) => Layer>; /** - * Wraps a `Layer` with a new tracing span and sets the span as the parent span. + * Wraps a layer so spans created during its construction use the supplied span + * as their parent. + * + * **Details** * - * This attaches a layer to an existing trace span, making all operations within - * the layer children of the provided parent span. This is useful for integrating - * layer construction into an existing trace hierarchy. + * Use this to attach layer construction to an existing trace hierarchy. This API + * does not create or end the supplied parent span. + * + * When the supplied span is a native `Span`, layer construction also receives + * diagnostic information that helps associate failures with the layer call site. + * External spans are only installed as the parent span and do not add this + * diagnostic call-site information. + * + * **Example** (Attaching layers to an existing parent span) * - * @example * ```ts - * import { Effect, Layer, Context, Tracer } from "effect" + * import { Context, Effect, Layer, Tracer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -3446,8 +4096,8 @@ export declare const withParentSpan: { * ) * ``` * - * @since 4.0.0 * @category tracing + * @since 2.0.0 */ (self: Layer, span: Tracer.AnySpan, options?: Tracer.TraceOptions): Layer>; };