diff --git a/packages/effect/SCHEMA.md b/packages/effect/SCHEMA.md index 9fc1459328..ab93e0883e 100644 --- a/packages/effect/SCHEMA.md +++ b/packages/effect/SCHEMA.md @@ -48,8 +48,8 @@ export interface Bottom< readonly Type: T readonly Encoded: E - readonly DecodingContext: RD - readonly EncodingContext: RE + readonly DecodingServices: RD + readonly EncodingServices: RE readonly "~type.make.in": TypeMakeIn readonly "~type.make": TypeMake @@ -153,11 +153,11 @@ This makes it easier to work with schemas in contexts where one direction has no ```ts import type { Effect } from "effect" -import { Context } from "effect" +import { ServiceMap } from "effect" import { Schema } from "effect/schema" // A service that retrieves full user info from an ID -class UserDatabase extends Context.Tag< +class UserDatabase extends ServiceMap.Key< UserDatabase, { getUserById: ( @@ -581,11 +581,11 @@ SchemaResult.asEffect(ToParser.makeSchemaResult(schema)({})) **Example** (Providing a default from an optional service) ```ts -import { Context, Effect, Option } from "effect" +import { ServiceMap, Effect, Option } from "effect" import { Schema, SchemaResult, ToParser } from "effect/schema" // Define a service that may provide a default value -class ConstructorService extends Context.Tag< +class ConstructorService extends ServiceMap.Key< ConstructorService, { defaultValue: Effect.Effect } >()("ConstructorService") {} @@ -3552,7 +3552,7 @@ declare const minLength: ( minLength: number, annotations?: Annotations.Filter> ) => ( - self: S & Schema, Schema.Context> + self: S & Schema, Schema.Services> ) => filter ``` @@ -3597,10 +3597,10 @@ b ### Providing a Service ```ts -import { Context, Effect, Option } from "effect" +import { ServiceMap, Effect, Option } from "effect" import { Formatter, Schema } from "effect/schema" -class Service extends Context.Tag< +class Service extends ServiceMap.Key< Service, { fallback: Effect.Effect } >()("Service") {} diff --git a/packages/effect/dtslint/schema/Schema.tst.ts b/packages/effect/dtslint/schema/Schema.tst.ts index 0939a05028..edff24647f 100644 --- a/packages/effect/dtslint/schema/Schema.tst.ts +++ b/packages/effect/dtslint/schema/Schema.tst.ts @@ -1,4 +1,4 @@ -import type { Brand, Context } from "effect" +import type { Brand, ServiceMap } from "effect" import { Effect, flow, @@ -1751,7 +1751,7 @@ describe("Schema", () => { describe("withConstructorDefault", () => { it("effectful", () => { - const service = hole>() + const service = hole>() const schema = Schema.String.pipe(Schema.withConstructorDefault(() => Effect.gen(function*() { diff --git a/packages/effect/src/Cause.ts b/packages/effect/src/Cause.ts index 3ec8414f4d..1a9771b746 100644 --- a/packages/effect/src/Cause.ts +++ b/packages/effect/src/Cause.ts @@ -1,7 +1,7 @@ /** * @since 2.0.0 */ -import type * as Context from "./Context.js" +import type * as ServiceMap from "./ServiceMap.js" import type * as Effect from "./Effect.js" import type { Equal } from "./Equal.js" import type * as Filter from "./Filter.js" @@ -80,7 +80,7 @@ export declare namespace Cause { export interface FailureProto extends Inspectable { readonly _tag: Tag readonly annotations: ReadonlyMap - annotate(tag: Context.Tag, value: S): this + annotate(tag: ServiceMap.Key, value: S): this } } diff --git a/packages/effect/src/Channel.ts b/packages/effect/src/Channel.ts index d96cd0984f..1f3c858972 100644 --- a/packages/effect/src/Channel.ts +++ b/packages/effect/src/Channel.ts @@ -4,7 +4,7 @@ import type * as Arr from "./Array.js" import * as Cause from "./Cause.js" import * as Chunk from "./Chunk.js" -import * as Context from "./Context.js" +import * as ServiceMap from "./ServiceMap.js" import * as Effect from "./Effect.js" import * as Exit from "./Exit.js" import * as Fiber from "./Fiber.js" @@ -2166,11 +2166,11 @@ export const toPull: ( self: Channel ) { const semaphore = Effect.unsafeMakeSemaphore(1) - const context = yield* Effect.context() - const scope = Context.get(context, Scope.Scope) + const context = yield* Effect.services() + const scope = ServiceMap.get(context, Scope.Scope) const pull = yield* toTransform(self)(Pull.haltVoid, scope) return pull.pipe( - Effect.provideContext(context), + Effect.provideServices(context), semaphore.withPermits(1) ) }, diff --git a/packages/effect/src/Clock.ts b/packages/effect/src/Clock.ts index e51bd88478..714e324641 100644 --- a/packages/effect/src/Clock.ts +++ b/packages/effect/src/Clock.ts @@ -1,7 +1,7 @@ /** * @since 2.0.0 */ -import type * as Context from "./Context.js" +import type * as ServiceMap from "./ServiceMap.js" import type * as Duration from "./Duration.js" import type { Effect } from "./Effect.js" import * as effect from "./internal/effect.js" @@ -40,7 +40,7 @@ export interface Clock { * @since 4.0.0 * @category references */ -export const CurrentClock: Context.Reference = effect.CurrentClock +export const CurrentClock: ServiceMap.Reference = effect.CurrentClock /** * @since 2.0.0 diff --git a/packages/effect/src/Console.ts b/packages/effect/src/Console.ts index 2d9998a7d3..e24795faa2 100644 --- a/packages/effect/src/Console.ts +++ b/packages/effect/src/Console.ts @@ -1,12 +1,12 @@ /** * @since 2.0.0 */ -import type * as Context from "./Context.js" import type * as Effect from "./Effect.js" import { dual } from "./Function.js" import * as core from "./internal/core.js" import * as effect from "./internal/effect.js" import type { Scope } from "./Scope.js" +import type * as ServiceMap from "./ServiceMap.js" /** * @since 2.0.0 @@ -38,7 +38,7 @@ export interface Console { * @since 4.0.0 * @category references */ -export const CurrentConsole: Context.Reference = effect.CurrentConsole +export const CurrentConsole: ServiceMap.Reference = effect.CurrentConsole /** * @since 2.0.0 diff --git a/packages/effect/src/Context.ts b/packages/effect/src/Context.ts deleted file mode 100644 index 7d13350ce0..0000000000 --- a/packages/effect/src/Context.ts +++ /dev/null @@ -1,505 +0,0 @@ -/** - * This module provides a data structure called `Context` that can be used for dependency injection in effectful - * programs. It is essentially a table mapping `Tag`s to their implementations (called `Service`s), and can be used to - * manage dependencies in a type-safe way. The `Context` data structure is essentially a way of providing access to a set - * of related services that can be passed around as a single unit. This module provides functions to create, modify, and - * query the contents of a `Context`, as well as a number of utility types for working with tags and services. - * - * @since 2.0.0 - */ -import type { EffectIterator, Yieldable } from "./Effect.js" -import type { Equal } from "./Equal.js" -import type { LazyArg } from "./Function.js" -import type { Inspectable } from "./Inspectable.js" -import * as internal from "./internal/context.js" -import type { Option } from "./Option.js" -import type { Pipeable } from "./Pipeable.js" -import type * as Types from "./Types.js" -import type * as Unify from "./Unify.js" - -const TagTypeId: unique symbol = internal.TagTypeId - -/** - * @since 2.0.0 - * @category symbol - */ -export type TagTypeId = typeof TagTypeId - -/** - * @since 3.5.9 - * @category models - */ -export interface Tag extends Pipeable, Inspectable, Yieldable { - readonly _op: "Tag" - readonly Service: Value - readonly Identifier: Id - readonly [TagTypeId]: { - readonly _Service: Types.Invariant - readonly _Identifier: Types.Invariant - } - [Symbol.iterator](): EffectIterator> - of(self: Value): Value - context(self: Value): Context - readonly stack?: string | undefined - readonly key: string - [Unify.typeSymbol]?: unknown - [Unify.unifySymbol]?: TagUnify - [Unify.ignoreSymbol]?: TagUnifyIgnore -} - -const ReferenceTypeId: unique symbol = internal.ReferenceTypeId - -/** - * @since 3.11.0 - * @category symbol - */ -export type ReferenceTypeId = typeof ReferenceTypeId - -/** - * @since 3.11.0 - * @category models - */ -export interface Reference extends Pipeable, Inspectable, Yieldable, Tag { - readonly [ReferenceTypeId]: ReferenceTypeId - readonly defaultValue: () => Value - [Symbol.iterator](): EffectIterator> -} - -/** - * @since 2.0.0 - * @category models - */ -export interface TagClassShape { - readonly [TagTypeId]: TagTypeId - readonly Type: Shape - readonly Id: Id -} - -/** - * @since 2.0.0 - * @category models - */ -export interface TagClass extends Tag { - new(_: never): TagClassShape -} - -/** - * @since 3.11.0 - * @category models - */ -export interface ReferenceClass extends Reference { - new(_: never): TagClassShape -} - -/** - * @category models - * @since 2.0.0 - */ -export interface TagUnify { - Tag?: () => A[Unify.typeSymbol] extends Tag | infer _ ? Tag : never -} - -/** - * @category models - * @since 2.0.0 - */ -export interface TagUnifyIgnore {} - -/** - * @since 2.0.0 - */ -export declare namespace Tag { - /** - * @since 2.0.0 - */ - export type Any = Tag | Tag - /** - * @since 2.0.0 - */ - export type Service> = T extends Tag ? S - : T extends TagClassShape ? S - : never - /** - * @since 2.0.0 - */ - export type Identifier> = T extends Tag ? I - : T extends TagClassShape ? T - : never -} - -/** - * Creates a new `Tag` instance with an optional key parameter. - * - * @param key - A key that will be used to compare tags. - * - * @example - * ```ts - * import * as assert from "node:assert" - * import { Context } from "effect" - * - * assert.strictEqual(Context.GenericTag("PORT").key === Context.GenericTag("PORT").key, true) - * ``` - * - * @since 2.0.0 - * @category constructors - */ -export const GenericTag: (key: string) => Tag = - internal.makeGenericTag - -const TypeId: unique symbol = internal.TypeId as TypeId - -/** - * @since 2.0.0 - * @category symbol - */ -export type TypeId = typeof TypeId - -/** - * @since 2.0.0 - * @category models - */ -export interface Context extends Equal, Pipeable, Inspectable { - readonly [TypeId]: { - readonly _Services: Types.Contravariant - } - readonly unsafeMap: Map -} - -/** - * @since 2.0.0 - * @category constructors - */ -export const unsafeMake: (unsafeMap: Map) => Context = internal.makeContext - -/** - * Checks if the provided argument is a `Context`. - * - * @param input - The value to be checked if it is a `Context`. - * - * @example - * ```ts - * import * as assert from "node:assert" - * import { Context } from "effect" - * - * assert.strictEqual(Context.isContext(Context.empty()), true) - * ``` - * - * @since 2.0.0 - * @category guards - */ -export const isContext: (input: unknown) => input is Context = internal.isContext - -/** - * Checks if the provided argument is a `Tag`. - * - * @param input - The value to be checked if it is a `Tag`. - * - * @example - * ```ts - * import * as assert from "node:assert" - * import { Context } from "effect" - * - * assert.strictEqual(Context.isTag(Context.GenericTag("Tag")), true) - * ``` - * - * @since 2.0.0 - * @category guards - */ -export const isTag: (input: unknown) => input is Tag = internal.isTag - -/** - * Checks if the provided argument is a `Reference`. - * - * @param input - The value to be checked if it is a `Reference`. - * @since 3.11.0 - * @category guards - * @experimental - */ -export const isReference: (u: unknown) => u is Reference = internal.isReference - -/** - * Returns an empty `Context`. - * - * @example - * ```ts - * import * as assert from "node:assert" - * import { Context } from "effect" - * - * assert.strictEqual(Context.isContext(Context.empty()), true) - * ``` - * - * @since 2.0.0 - * @category constructors - */ -export const empty: () => Context = internal.empty - -/** - * Creates a new `Context` with a single service associated to the tag. - * - * @example - * ```ts - * import * as assert from "node:assert" - * import { Context } from "effect" - * - * const Port = Context.GenericTag<{ PORT: number }>("Port") - * - * const Services = Context.make(Port, { PORT: 8080 }) - * - * assert.deepStrictEqual(Context.get(Services, Port), { PORT: 8080 }) - * ``` - * - * @since 2.0.0 - * @category constructors - */ -export const make: ( - tag: T, - service: Tag.Service -) => Context> = internal.make - -/** - * Adds a service to a given `Context`. - * - * @example - * ```ts - * import * as assert from "node:assert" - * import { Context, pipe } from "effect" - * - * const Port = Context.GenericTag<{ PORT: number }>("Port") - * const Timeout = Context.GenericTag<{ TIMEOUT: number }>("Timeout") - * - * const someContext = Context.make(Port, { PORT: 8080 }) - * - * const Services = pipe( - * someContext, - * Context.add(Timeout, { TIMEOUT: 5000 }) - * ) - * - * assert.deepStrictEqual(Context.get(Services, Port), { PORT: 8080 }) - * assert.deepStrictEqual(Context.get(Services, Timeout), { TIMEOUT: 5000 }) - * ``` - * - * @since 2.0.0 - */ -export const add: { - ( - tag: T, - service: Tag.Service - ): (self: Context) => Context> - ( - self: Context, - tag: T, - service: Tag.Service - ): Context> -} = internal.add - -/** - * Get a service from the context that corresponds to the given tag. - * - * @param self - The `Context` to search for the service. - * @param tag - The `Tag` of the service to retrieve. - * - * @example - * ```ts - * import * as assert from "node:assert" - * import { pipe, Context } from "effect" - * - * const Port = Context.GenericTag<{ PORT: number }>("Port") - * const Timeout = Context.GenericTag<{ TIMEOUT: number }>("Timeout") - * - * const Services = pipe( - * Context.make(Port, { PORT: 8080 }), - * Context.add(Timeout, { TIMEOUT: 5000 }) - * ) - * - * assert.deepStrictEqual(Context.get(Services, Timeout), { TIMEOUT: 5000 }) - * ``` - * - * @since 2.0.0 - * @category getters - */ -export const get: { - (tag: Tag): (self: Context) => S - (self: Context, tag: Tag): S -} = internal.get - -/** - * Get a service from the context that corresponds to the given tag, or - * use the fallback value. - * - * @since 3.7.0 - * @category getters - */ -export const getOrElse: { - (tag: Tag, orElse: LazyArg): (self: Context) => S | B - (self: Context, tag: Tag, orElse: LazyArg): S | B -} = internal.getOrElse - -/** - * Get a service from the context that corresponds to the given tag. - * This function is unsafe because if the tag is not present in the context, a runtime error will be thrown. - * - * For a safer version see {@link getOption}. - * - * @param self - The `Context` to search for the service. - * @param tag - The `Tag` of the service to retrieve. - * - * @example - * ```ts - * import * as assert from "node:assert" - * import { Context } from "effect" - * - * const Port = Context.GenericTag<{ PORT: number }>("Port") - * const Timeout = Context.GenericTag<{ TIMEOUT: number }>("Timeout") - * - * const Services = Context.make(Port, { PORT: 8080 }) - * - * assert.deepStrictEqual(Context.unsafeGet(Services, Port), { PORT: 8080 }) - * assert.throws(() => Context.unsafeGet(Services, Timeout)) - * ``` - * - * @since 2.0.0 - * @category unsafe - */ -export const unsafeGet: { - (tag: Tag): (self: Context) => S - (self: Context, tag: Tag): S -} = internal.unsafeGet - -/** - * Get the value associated with the specified tag from the context wrapped in an `Option` object. If the tag is not - * found, the `Option` object will be `None`. - * - * @param self - The `Context` to search for the service. - * @param tag - The `Tag` of the service to retrieve. - * - * @example - * ```ts - * import * as assert from "node:assert" - * import { Context, Option } from "effect" - * - * const Port = Context.GenericTag<{ PORT: number }>("Port") - * const Timeout = Context.GenericTag<{ TIMEOUT: number }>("Timeout") - * - * const Services = Context.make(Port, { PORT: 8080 }) - * - * assert.deepStrictEqual(Context.getOption(Services, Port), Option.some({ PORT: 8080 })) - * assert.deepStrictEqual(Context.getOption(Services, Timeout), Option.none()) - * ``` - * - * @since 2.0.0 - * @category getters - */ -export const getOption: { - (tag: Tag): (self: Context) => Option - (self: Context, tag: Tag): Option -} = internal.getOption - -/** - * Merges two `Context`s, returning a new `Context` containing the services of both. - * - * @param self - The first `Context` to merge. - * @param that - The second `Context` to merge. - * - * @example - * ```ts - * import * as assert from "node:assert" - * import { Context } from "effect" - * - * const Port = Context.GenericTag<{ PORT: number }>("Port") - * const Timeout = Context.GenericTag<{ TIMEOUT: number }>("Timeout") - * - * const firstContext = Context.make(Port, { PORT: 8080 }) - * const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) - * - * const Services = Context.merge(firstContext, secondContext) - * - * assert.deepStrictEqual(Context.get(Services, Port), { PORT: 8080 }) - * assert.deepStrictEqual(Context.get(Services, Timeout), { TIMEOUT: 5000 }) - * ``` - * - * @since 2.0.0 - */ -export const merge: { - (that: Context): (self: Context) => Context - (self: Context, that: Context): Context -} = internal.merge - -/** - * Returns a new `Context` that contains only the specified services. - * - * @param self - The `Context` to prune services from. - * @param tags - The list of `Tag`s to be included in the new `Context`. - * - * @example - * ```ts - * import * as assert from "node:assert" - * import { pipe, Context, Option } from "effect" - * - * const Port = Context.GenericTag<{ PORT: number }>("Port") - * const Timeout = Context.GenericTag<{ TIMEOUT: number }>("Timeout") - * - * const someContext = pipe( - * Context.make(Port, { PORT: 8080 }), - * Context.add(Timeout, { TIMEOUT: 5000 }) - * ) - * - * const Services = pipe(someContext, Context.pick(Port)) - * - * assert.deepStrictEqual(Context.getOption(Services, Port), Option.some({ PORT: 8080 })) - * assert.deepStrictEqual(Context.getOption(Services, Timeout), Option.none()) - * ``` - * - * @since 2.0.0 - */ -export const pick: >>( - ...tags: Tags -) => (self: Context) => Context> = internal.pick - -/** - * @since 2.0.0 - */ -export const omit: >>( - ...tags: Tags -) => (self: Context) => Context>> = internal.omit - -/** - * @example - * ```ts - * import { Context, Layer } from "effect" - * - * class MyTag extends Context.Tag()("MyTag") { - * static Live = Layer.succeed(this, { myNum: 108 }) - * } - * ``` - * - * @since 2.0.0 - * @category constructors - */ -export const Tag: () => (id: Id) => TagClass = internal.Tag - -/** - * Creates a context tag with a default value. - * - * **Details** - * - * `Context.Reference` allows you to create a tag that can hold a value. You can - * provide a default value for the service, which will automatically be used - * when the context is accessed, or override it with a custom implementation - * when needed. - * - * @since 3.11.0 - * @category constructors - */ -export const Reference: ( - id: Id, - options: { readonly defaultValue: () => Service } -) => ReferenceClass = internal.Reference - -/** - * @since 4.0.0 - * @category constructors - */ -export const GenericReference: ( - key: string, - options: { readonly defaultValue: () => Service } -) => Reference = internal.GenericReference diff --git a/packages/effect/src/DateTime.ts b/packages/effect/src/DateTime.ts index 2000f956c3..694f1122b8 100644 --- a/packages/effect/src/DateTime.ts +++ b/packages/effect/src/DateTime.ts @@ -2,7 +2,6 @@ * @since 3.6.0 */ import type { IllegalArgumentError } from "./Cause.js" -import * as Context from "./Context.js" import type * as Duration from "./Duration.js" import * as Effect from "./Effect.js" import type * as equivalence from "./Equivalence.js" @@ -15,6 +14,7 @@ import type * as Option from "./Option.js" import type * as order from "./Order.js" import type { Pipeable } from "./Pipeable.js" import type * as Result from "./Result.js" +import * as ServiceMap from "./ServiceMap.js" /** * @since 3.6.0 @@ -956,7 +956,7 @@ export const setPartsUtc: { * @since 3.11.0 * @category current time zone */ -export class CurrentTimeZone extends Context.Tag()("effect/DateTime/CurrentTimeZone") {} +export class CurrentTimeZone extends ServiceMap.Key()("effect/DateTime/CurrentTimeZone") {} /** * Set the time zone of a `DateTime` to the current time zone, which is diff --git a/packages/effect/src/Effect.ts b/packages/effect/src/Effect.ts index 96c159c0a8..0d67be84f3 100644 --- a/packages/effect/src/Effect.ts +++ b/packages/effect/src/Effect.ts @@ -4,7 +4,6 @@ import type * as Arr from "./Array.js" import type * as Cause from "./Cause.js" import type { Clock } from "./Clock.js" -import * as Context from "./Context.js" import * as Duration from "./Duration.js" import * as Exit from "./Exit.js" import type { Fiber } from "./Fiber.js" @@ -29,6 +28,7 @@ import type * as Result from "./Result.js" import type { Schedule } from "./Schedule.js" import type { Scheduler } from "./Scheduler.js" import type { Scope } from "./Scope.js" +import * as ServiceMap from "./ServiceMap.js" import type { AnySpan, ParentSpan, Span, SpanLink, SpanOptions, Tracer } from "./Tracer.js" import type { TxRef } from "./TxRef.js" import type { Concurrency, Covariant, ExcludeTag, ExtractTag, NoInfer, NotFunction, Tags } from "./Types.js" @@ -146,7 +146,7 @@ export declare namespace Effect { /** * @since 2.0.0 */ - export type Context = T extends Effect ? _R + export type Services = T extends Effect ? _R : never } @@ -2677,7 +2677,7 @@ export const raceAll: >( readonly parentFiber: Fiber }) => void } -) => Effect, Effect.Error, Effect.Context> = internal.raceAll +) => Effect, Effect.Error, Effect.Services> = internal.raceAll /** * @since 4.0.0 @@ -2692,7 +2692,7 @@ export const raceAllFirst: >( readonly parentFiber: Fiber }) => void } -) => Effect, Effect.Error, Effect.Context> = internal.raceAllFirst +) => Effect, Effect.Error, Effect.Services> = internal.raceAllFirst // ----------------------------------------------------------------------------- // Filtering @@ -3010,7 +3010,7 @@ export const matchEffect: { * @since 2.0.0 * @category Environment */ -export const context: () => Effect, never, R> = internal.context +export const services: () => Effect, never, R> = internal.services /** * @since 2.0.0 @@ -3024,7 +3024,7 @@ export const provide: { ) => Effect< A, E | Layer.Error, - Layer.Context | Exclude> + Layer.Services | Exclude> > ( layer: Layer @@ -3032,7 +3032,7 @@ export const provide: { self: Effect ) => Effect> ( - context: Context.Context + context: ServiceMap.ServiceMap ): (self: Effect) => Effect> ]>( self: Effect, @@ -3040,7 +3040,7 @@ export const provide: { ): Effect< A, E | Layer.Error, - Layer.Context | Exclude> + Layer.Services | Exclude> > ( self: Effect, @@ -3048,7 +3048,7 @@ export const provide: { ): Effect> ( self: Effect, - context: Context.Context + context: ServiceMap.ServiceMap ): Effect> } = internalLayer.provide @@ -3056,29 +3056,27 @@ export const provide: { * @since 2.0.0 * @category Environment */ -export const provideContext: { +export const provideServices: { ( - context: Context.Context + context: ServiceMap.ServiceMap ): (self: Effect) => Effect> ( self: Effect, - context: Context.Context + context: ServiceMap.ServiceMap ): Effect> -} = internal.provideContext +} = internal.provideServices /** * @since 4.0.0 - * @category Context + * @category ServiceMap */ -export const service: (tag: Context.Tag) => Effect = internal.service +export const service: (key: ServiceMap.Key) => Effect = internal.service /** * @since 2.0.0 - * @category Context + * @category ServiceMap */ -export const serviceOption: ( - tag: Context.Tag -) => Effect> = internal.serviceOption +export const serviceOption: (key: ServiceMap.Key) => Effect> = internal.serviceOption /** * Provides part of the required context while leaving the rest unchanged. @@ -3089,34 +3087,27 @@ export const serviceOption: ( * providing part of the context and leaving the rest to be fulfilled later. * * @since 4.0.0 - * @category Context + * @category ServiceMap */ -export const updateContext: { +export const updateServices: { ( - f: (context: Context.Context) => Context.Context> + f: (services: ServiceMap.ServiceMap) => ServiceMap.ServiceMap> ): (self: Effect) => Effect ( self: Effect, - f: (context: Context.Context) => Context.Context> + f: (services: ServiceMap.ServiceMap) => ServiceMap.ServiceMap> ): Effect -} = internal.updateContext +} = internal.updateServices /** * Updates the service with the required service entry. * * @since 2.0.0 - * @category Context + * @category ServiceMap */ export const updateService: { - ( - tag: Context.Tag, - f: (value: A) => A - ): (self: Effect) => Effect - ( - self: Effect, - tag: Context.Tag, - f: (value: A) => A - ): Effect + (key: ServiceMap.Key, f: (value: A) => A): (self: Effect) => Effect + (self: Effect, key: ServiceMap.Key, f: (value: A) => A): Effect } = internal.updateService /** @@ -3132,17 +3123,17 @@ export const updateService: { * @see {@link provide} for providing multiple layers to an effect. * * @since 2.0.0 - * @category Context + * @category ServiceMap */ export const provideService: { ( - tag: Context.Tag + key: ServiceMap.Key ): { (service: S): (self: Effect) => Effect> (self: Effect, service: S): Effect> } - (tag: Context.Tag, service: S): (self: Effect) => Effect> - (self: Effect, tag: Context.Tag, service: S): Effect> + (key: ServiceMap.Key, service: S): (self: Effect) => Effect> + (self: Effect, key: ServiceMap.Key, service: S): Effect> } = internal.provideService /** @@ -3150,16 +3141,16 @@ export const provideService: { * requires more than one service use `provide` instead. * * @since 2.0.0 - * @category Context + * @category ServiceMap */ export const provideServiceEffect: { ( - tag: Context.Tag, + key: ServiceMap.Key, acquire: Effect ): (self: Effect) => Effect | R2> ( self: Effect, - tag: Context.Tag, + key: ServiceMap.Key, acquire: Effect ): Effect | R2> } = internal.provideServiceEffect @@ -4184,12 +4175,12 @@ export const request: { ) => Effect< Request.Success, Request.Error | EX, - Request.Context | RX + Request.Services | RX > , EX = never, RX = never>( self: A, resolver: RequestResolver | Effect, EX, RX> - ): Effect, Request.Error | EX, Request.Context | RX> + ): Effect, Request.Error | EX, Request.Services | RX> } = internalRequest.request // ----------------------------------------------------------------------------- @@ -5542,7 +5533,7 @@ export const trackDuration: { * @since 4.0.0 * @category Transactions */ -export class Transaction extends Context.Tag< +export class Transaction extends ServiceMap.Key< Transaction, { retry: boolean @@ -5583,17 +5574,17 @@ export const transaction = ( * @category Transactions */ export const transactionWith = ( - f: (state: Transaction["Type"]) => Effect + f: (state: Transaction["Service"]) => Effect ): Effect> => withFiber((fiber) => { - if (fiber.context.unsafeMap.has(Transaction.key)) { - return f(Context.unsafeGet(fiber.context, Transaction)) as Effect< + if (fiber.services.unsafeMap.has(Transaction.key)) { + return f(ServiceMap.unsafeGet(fiber.services, Transaction)) as Effect< A, E, Exclude > } - const state: Transaction["Type"] = { journal: new Map(), retry: false } + const state: Transaction["Service"] = { journal: new Map(), retry: false } const scheduler = fiber.currentScheduler let result: Exit.Exit | undefined return uninterruptibleMask((restore) => @@ -5627,7 +5618,7 @@ export const transactionWith = ( ) }) -const isTransactionConsistent = (state: Transaction["Type"]) => { +const isTransactionConsistent = (state: Transaction["Service"]) => { for (const [ref, { version }] of state.journal) { if (ref.version !== version) { return false @@ -5636,7 +5627,7 @@ const isTransactionConsistent = (state: Transaction["Type"]) => { return true } -const awaitPendingTransaction = (state: Transaction["Type"]) => +const awaitPendingTransaction = (state: Transaction["Service"]) => suspend(() => { const key = {} const refs = Array.from(state.journal.keys()) @@ -5657,7 +5648,7 @@ const awaitPendingTransaction = (state: Transaction["Type"]) => }) }) -function commitTransaction(scheduler: Scheduler, state: Transaction["Type"]) { +function commitTransaction(scheduler: Scheduler, state: Transaction["Service"]) { for (const [ref, { value }] of state.journal) { if (value !== ref.value) { ref.version = ref.version + 1 @@ -5670,7 +5661,7 @@ function commitTransaction(scheduler: Scheduler, state: Transaction["Type"]) { } } -function clearTransaction(state: Transaction["Type"]) { +function clearTransaction(state: Transaction["Service"]) { state.retry = false state.journal.clear() } diff --git a/packages/effect/src/Fiber.ts b/packages/effect/src/Fiber.ts index 4dd38755bf..449d5b2fb9 100644 --- a/packages/effect/src/Fiber.ts +++ b/packages/effect/src/Fiber.ts @@ -1,7 +1,6 @@ /** * @since 2.0.0 */ -import type * as Context from "./Context.js" import type { Effect } from "./Effect.js" import type { Exit } from "./Exit.js" import * as effect from "./internal/effect.js" @@ -9,6 +8,7 @@ import type { Option } from "./Option.js" import type { Pipeable } from "./Pipeable.js" import { hasProperty } from "./Predicate.js" import type { Scheduler } from "./Scheduler.js" +import type * as ServiceMap from "./ServiceMap.js" import type { AnySpan } from "./Tracer.js" import type { Covariant } from "./Types.js" @@ -33,9 +33,9 @@ export interface Fiber extends Pipeable { readonly id: number readonly currentOpCount: number - readonly getRef: (ref: Context.Reference) => A - readonly context: Context.Context - setContext(context: Context.Context): void + readonly getRef: (ref: ServiceMap.Reference) => A + readonly services: ServiceMap.ServiceMap + setServices(services: ServiceMap.ServiceMap): void readonly currentScheduler: Scheduler readonly currentSpan?: AnySpan | undefined readonly maxOpsBeforeYield: number diff --git a/packages/effect/src/FileSystem.ts b/packages/effect/src/FileSystem.ts index 9e8a06d3e9..38c0ccd822 100644 --- a/packages/effect/src/FileSystem.ts +++ b/packages/effect/src/FileSystem.ts @@ -3,8 +3,6 @@ */ import * as Arr from "./Array.js" import * as Brand from "./Brand.js" -import type { Tag } from "./Context.js" -import * as Context from "./Context.js" import * as Data from "./Data.js" import * as Effect from "./Effect.js" import { pipe } from "./Function.js" @@ -14,6 +12,7 @@ import type { PlatformError } from "./PlatformError.js" import { BadArgument, SystemError } from "./PlatformError.js" import * as Pull from "./Pull.js" import type { Scope } from "./Scope.js" +import * as ServiceMap from "./ServiceMap.js" import * as Sink from "./Sink.js" import * as Stream from "./Stream.js" @@ -441,7 +440,7 @@ export interface WriteFileStringOptions { * @since 4.0.0 * @category tag */ -export const FileSystem: Tag = Context.GenericTag("effect/FileSystem") +export const FileSystem: ServiceMap.Key = ServiceMap.Key("effect/FileSystem") /** * @since 4.0.0 @@ -799,6 +798,6 @@ export const WatchEventRemove: Data.Case.Constructor * @since 4.0.0 * @category file watcher */ -export class WatchBackend extends Context.Tag Option.Option> }>()("effect/FileSystem/WatchBackend") {} diff --git a/packages/effect/src/Inspectable.ts b/packages/effect/src/Inspectable.ts index 9d84fedb2a..5fb4b3e710 100644 --- a/packages/effect/src/Inspectable.ts +++ b/packages/effect/src/Inspectable.ts @@ -1,7 +1,7 @@ /** * @since 2.0.0 */ -import type * as Context from "./Context.js" +import type * as ServiceMap from "./ServiceMap.js" import { hasProperty, isFunction } from "./Predicate.js" /** @@ -132,7 +132,7 @@ export const stringifyCircular = ( * @category redactable */ export interface Redactable { - readonly [symbolRedactable]: (context: Context.Context) => unknown + readonly [symbolRedactable]: (context: ServiceMap.ServiceMap) => unknown } /** diff --git a/packages/effect/src/Layer.ts b/packages/effect/src/Layer.ts index d1d08d1494..11053aa7c2 100644 --- a/packages/effect/src/Layer.ts +++ b/packages/effect/src/Layer.ts @@ -19,7 +19,6 @@ */ import type { NonEmptyArray } from "./Array.js" import type * as Cause from "./Cause.js" -import * as Context from "./Context.js" import * as Deferred from "./Deferred.js" import type { Effect } from "./Effect.js" import type * as Exit from "./Exit.js" @@ -29,6 +28,7 @@ import * as internalEffect from "./internal/effect.js" import { type Pipeable, pipeArguments } from "./Pipeable.js" import { hasProperty } from "./Predicate.js" import * as Scope from "./Scope.js" +import * as ServiceMap from "./ServiceMap.js" import type * as Types from "./Types.js" /** @@ -49,7 +49,7 @@ export type LayerTypeId = typeof LayerTypeId */ export interface Layer extends Layer.Variance, Pipeable { /** @internal */ - build(memoMap: MemoMap, scope: Scope.Scope): Effect, E, RIn> + build(memoMap: MemoMap, scope: Scope.Scope): Effect, E, RIn> } /** @@ -82,7 +82,7 @@ export declare namespace Layer { * @since 2.0.0 * @category type-level */ - export type Context = T extends Layer ? _RIn : never + export type Services = T extends Layer ? _RIn : never /** * @since 2.0.0 * @category type-level @@ -116,8 +116,8 @@ export interface MemoMap { readonly getOrElseMemoize: ( layer: Layer, scope: Scope.Scope, - build: (memoMap: MemoMap, scope: Scope.Scope) => Effect, E, RIn> - ) => Effect, E, RIn> + build: (memoMap: MemoMap, scope: Scope.Scope) => Effect, E, RIn> + ) => Effect, E, RIn> } /** @@ -143,7 +143,7 @@ const fromBuildUnsafe = ( build: ( memoMap: MemoMap, scope: Scope.Scope - ) => Effect, E, RIn> + ) => Effect, E, RIn> ): Layer => { const self = Object.create(LayerProto) self.build = build @@ -158,7 +158,7 @@ export const fromBuild = ( build: ( memoMap: MemoMap, scope: Scope.Scope - ) => Effect, E, RIn> + ) => Effect, E, RIn> ): Layer => fromBuildUnsafe((memoMap: MemoMap, scope: Scope.Scope) => internalEffect.flatMap(Scope.fork(scope), (scope) => @@ -176,7 +176,7 @@ export const fromBuildMemo = ( build: ( memoMap: MemoMap, scope: Scope.Scope - ) => Effect, E, RIn> + ) => Effect, E, RIn> ): Layer => { const self: Layer = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)) return self @@ -189,15 +189,15 @@ class MemoMapImpl implements MemoMap { readonly map = new Map, { observers: number - effect: Effect, any> + effect: Effect, any> readonly finalizer: (exit: Exit.Exit) => Effect }>() getOrElseMemoize( layer: Layer, scope: Scope.Scope, - build: (memoMap: MemoMap, scope: Scope.Scope) => Effect, E, RIn> - ): Effect, E, RIn> { + build: (memoMap: MemoMap, scope: Scope.Scope) => Effect, E, RIn> + ): Effect, E, RIn> { if (this.map.has(layer)) { const entry = this.map.get(layer)! entry.observers++ @@ -207,7 +207,7 @@ class MemoMapImpl implements MemoMap { ) } const layerScope = Scope.unsafeMake() - const deferred = Deferred.unsafeMake, E>() + const deferred = Deferred.unsafeMake, E>() const entry = { observers: 1, effect: Deferred.await(deferred), @@ -252,7 +252,7 @@ export const makeMemoMap: Effect = internalEffect.sync(unsafeMakeMemoMa * @since 3.13.0 * @category models */ -export class CurrentMemoMap extends Context.Reference("effect/Layer/CurrentMemoMap", { +export class CurrentMemoMap extends ServiceMap.Reference("effect/Layer/CurrentMemoMap", { defaultValue: unsafeMakeMemoMap }) {} @@ -267,17 +267,17 @@ export const buildWithMemoMap: { ( memoMap: MemoMap, scope: Scope.Scope - ): (self: Layer) => Effect, E, RIn> + ): (self: Layer) => Effect, E, RIn> ( self: Layer, memoMap: MemoMap, scope: Scope.Scope - ): Effect, E, RIn> + ): Effect, E, RIn> } = dual(3, ( self: Layer, memoMap: MemoMap, scope: Scope.Scope -): Effect, E, RIn> => +): Effect, E, RIn> => internalEffect.provideService( self.build(memoMap, scope), CurrentMemoMap, @@ -292,7 +292,7 @@ export const buildWithMemoMap: { */ export const build = ( self: Layer -): Effect, E, RIn | Scope.Scope> => +): Effect, E, RIn | Scope.Scope> => internalEffect.flatMap(internalEffect.scope, (scope) => self.build(unsafeMakeMemoMap(), scope)) /** @@ -306,12 +306,12 @@ export const build = ( * @category destructors */ export const buildWithScope: { - (scope: Scope.Scope): (self: Layer) => Effect, E, RIn> - (self: Layer, scope: Scope.Scope): Effect, E, RIn> + (scope: Scope.Scope): (self: Layer) => Effect, E, RIn> + (self: Layer, scope: Scope.Scope): Effect, E, RIn> } = dual(2, ( self: Layer, scope: Scope.Scope -): Effect, E, RIn> => internalEffect.suspend(() => self.build(unsafeMakeMemoMap(), scope))) +): Effect, E, RIn> => internalEffect.suspend(() => self.build(unsafeMakeMemoMap(), scope))) /** * Constructs a layer from the specified value. @@ -320,12 +320,12 @@ export const buildWithScope: { * @category constructors */ export const succeed: { - (tag: Context.Tag): (resource: NoInfer) => Layer> - (tag: Context.Tag, resource: NoInfer): Layer> + (key: ServiceMap.Key): (resource: NoInfer) => Layer> + (key: ServiceMap.Key, resource: NoInfer): Layer> } = dual(2, ( - tag: Context.Tag, + key: ServiceMap.Key, resource: NoInfer -): Layer> => succeedContext(Context.make(tag, resource))) +): Layer> => succeedServices(ServiceMap.make(key, resource))) /** * Constructs a layer from the specified value, which must return one or more @@ -334,16 +334,16 @@ export const succeed: { * @since 2.0.0 * @category constructors */ -export const succeedContext = (context: Context.Context): Layer => - fromBuildUnsafe(constant(internalEffect.succeed(context))) +export const succeedServices = (services: ServiceMap.ServiceMap): Layer => + fromBuildUnsafe(constant(internalEffect.succeed(services))) /** - * A Layer that constructs an empty Context. + * A Layer that constructs an empty ServiceMap. * * @since 2.0.0 * @category constructors */ -export const empty: Layer = succeedContext(Context.empty()) +export const empty: Layer = succeedServices(ServiceMap.empty()) /** * Lazily constructs a layer from the specified value. @@ -352,12 +352,12 @@ export const empty: Layer = succeedContext(Context.empty()) * @category constructors */ export const sync: { - (tag: Context.Tag): (evaluate: LazyArg>) => Layer> - (tag: Context.Tag, evaluate: LazyArg>): Layer> + (key: ServiceMap.Key): (evaluate: LazyArg>) => Layer> + (key: ServiceMap.Key, evaluate: LazyArg>): Layer> } = dual(2, ( - tag: Context.Tag, + key: ServiceMap.Key, evaluate: LazyArg> -): Layer> => syncContext(() => Context.make(tag, evaluate()))) +): Layer> => syncServices(() => ServiceMap.make(key, evaluate()))) /** * Lazily constructs a layer from the specified value, which must return one or more @@ -366,7 +366,7 @@ export const sync: { * @since 2.0.0 * @category constructors */ -export const syncContext = (evaluate: LazyArg>): Layer => +export const syncServices = (evaluate: LazyArg>): Layer => fromBuildUnsafe(constant(internalEffect.sync(evaluate))) /** @@ -376,12 +376,12 @@ export const syncContext = (evaluate: LazyArg>): Layer * @category constructors */ export const effect: { - (tag: Context.Tag): (effect: Effect, E, R>) => Layer> - (tag: Context.Tag, effect: Effect, E, R>): Layer> + (key: ServiceMap.Key): (effect: Effect, E, R>) => Layer> + (key: ServiceMap.Key, effect: Effect, E, R>): Layer> } = dual( 2, - (tag: Context.Tag, effect: Effect): Layer => - effectContext(internalEffect.map(effect, (value) => Context.make(tag, value))) + (key: ServiceMap.Key, effect: Effect): Layer => + effectServices(internalEffect.map(effect, (value) => ServiceMap.make(key, value))) ) /** @@ -391,8 +391,8 @@ export const effect: { * @since 2.0.0 * @category constructors */ -export const effectContext = ( - effect: Effect, E, R> +export const effectServices = ( + effect: Effect, E, R> ): Layer> => fromBuildMemo((_, scope) => Scope.provide(effect, scope)) /** @@ -402,7 +402,7 @@ export const effectContext = ( * @category constructors */ export const effectDiscard = (effect: Effect): Layer> => - effectContext(internalEffect.as(effect, Context.empty())) + effectServices(internalEffect.as(effect, ServiceMap.empty())) /** * @since 4.0.0 @@ -411,8 +411,8 @@ export const effectDiscard = (effect: Effect): Layer( self: Effect, E, R> ): Layer> => { - const tag = Context.GenericTag>("effect/Layer/unwrap") - return flatMap(effect(tag, self), Context.get(tag)) + const key = ServiceMap.Key>("effect/Layer/unwrap") + return flatMap(effect(key, self), ServiceMap.get(key)) } const mergeAllEffect = , ...Array>]>( @@ -420,9 +420,9 @@ const mergeAllEffect = , ...Array }[number]>, + ServiceMap.ServiceMap<{ [k in keyof Layers]: Layer.Success }[number]>, { [k in keyof Layers]: Layer.Error }[number], - { [k in keyof Layers]: Layer.Context }[number] + { [k in keyof Layers]: Layer.Services }[number] > => internalEffect.forEach(layers, (layer) => layer.build(memoMap, scope), { concurrency: layers.length }).pipe( internalEffect.map((contexts) => { @@ -432,7 +432,7 @@ const mergeAllEffect = , ...Array, ...Array, Layer.Error, - Layer.Context + Layer.Services > => fromBuild((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)) /** @@ -467,7 +467,7 @@ export const merge: { ) => Layer< A | Layer.Success, E | Layer.Error, - | Layer.Context + | Layer.Services | R > ( @@ -480,7 +480,7 @@ export const merge: { ): Layer< A | Layer.Success, E | Layer.Error, - | Layer.Context + | Layer.Services | R > } = dual(2, ( @@ -492,9 +492,9 @@ const provideWith = ( self: Layer, that: Layer | ReadonlyArray>, f: ( - selfContext: Context.Context, - thatContext: Context.Context - ) => Context.Context + selfServices: ServiceMap.ServiceMap, + thatServices: ServiceMap.ServiceMap + ) => ServiceMap.ServiceMap ) => fromBuild((memoMap, scope) => internalEffect.flatMap( @@ -503,7 +503,7 @@ const provideWith = ( : (that as Layer).build(memoMap, scope), (context) => self.build(memoMap, scope).pipe( - internalEffect.provideContext(context), + internalEffect.provideServices(context), internalEffect.map((merged) => f(merged, context)) ) ) @@ -528,7 +528,7 @@ export const provide: { ) => Layer< A, E | Layer.Error, - | Layer.Context + | Layer.Services | Exclude> > ( @@ -541,7 +541,7 @@ export const provide: { ): Layer< A, E | Layer.Error, - | Layer.Context + | Layer.Services | Exclude> > } = dual(2, ( @@ -568,7 +568,7 @@ export const provideMerge: { ) => Layer< A | Layer.Success, E | Layer.Error, - | Layer.Context + | Layer.Services | Exclude> > ( @@ -581,7 +581,7 @@ export const provideMerge: { ): Layer< A | Layer.Success, E | Layer.Error, - | Layer.Context + | Layer.Services | Exclude> > } = dual(2, ( @@ -591,7 +591,7 @@ export const provideMerge: { provideWith( self, that, - (selfContext, thatContext) => Context.merge(thatContext, selfContext) + (self, that) => ServiceMap.merge(that, self) )) /** @@ -602,15 +602,15 @@ export const provideMerge: { */ export const flatMap: { ( - f: (context: Context.Context) => Layer + f: (context: ServiceMap.ServiceMap) => Layer ): (self: Layer) => Layer ( self: Layer, - f: (context: Context.Context) => Layer + f: (context: ServiceMap.ServiceMap) => Layer ): Layer } = dual(2, ( self: Layer, - f: (context: Context.Context) => Layer + f: (context: ServiceMap.ServiceMap) => Layer ): Layer => fromBuild((memoMap, scope) => internalEffect.flatMap( diff --git a/packages/effect/src/LayerMap.ts b/packages/effect/src/LayerMap.ts index b02af76d97..3595bb2dd2 100644 --- a/packages/effect/src/LayerMap.ts +++ b/packages/effect/src/LayerMap.ts @@ -2,7 +2,7 @@ * @since 3.14.0 * @experimental */ -import * as Context from "./Context.js" +import * as ServiceMap from "./ServiceMap.js" import type * as Duration from "./Duration.js" import * as Effect from "./Effect.js" import { identity } from "./Function.js" @@ -34,7 +34,7 @@ export interface LayerMap { /** * The internal RcMap that stores the resources. */ - readonly rcMap: RcMap.RcMap, S], E> + readonly rcMap: RcMap.RcMap, S], E> /** * Retrieves an instance of the resource associated with the key. @@ -107,9 +107,9 @@ export interface LayerMap { * ``` */ export const make: < - Accessor extends Context.Tag | Effect.Effect, + Accessor extends ServiceMap.Key | Effect.Effect, K, - L extends Layer.Layer, Scope.Scope>, any, any> + L extends Layer.Layer, Scope.Scope>, any, any> >( tagOrAccessor: Accessor, lookup: (key: K) => L, @@ -119,32 +119,32 @@ export const make: < ) => Effect.Effect< LayerMap< K, - Exclude, Scope.Scope>, + Exclude, Scope.Scope>, Effect.Effect.Success, Effect.Effect.Error | (L extends Layer.Layer ? _E : never) >, never, Scope.Scope | (L extends Layer.Layer ? _R : never) > = Effect.fnUntraced(function*( - tagOrAccessor: Effect.Effect | Context.Tag, + tagOrAccessor: Effect.Effect | ServiceMap.Key, lookup: (key: K) => Layer.Layer, EL, RL>, options?: { readonly idleTimeToLive?: Duration.DurationInput | undefined } | undefined ) { - const context = yield* Effect.context() + const context = yield* Effect.services() // If we are inside another layer build, use the current memo map, // otherwise create a new one. const memoMap = context.unsafeMap.has(Layer.CurrentMemoMap.key) - ? Context.get(context, Layer.CurrentMemoMap) + ? ServiceMap.get(context, Layer.CurrentMemoMap) : yield* Layer.makeMemoMap const rcMap = yield* RcMap.make({ lookup: Effect.fnUntraced(function*(key: K) { const scope = yield* Effect.scope const context = yield* (Layer.buildWithMemoMap(lookup(key), memoMap, scope) as Effect.Effect< - Context.Context> + ServiceMap.ServiceMap> >) const service = yield* (Effect.provide(tagOrAccessor.asEffect(), context) as Effect.Effect) return [context, service] as const @@ -173,8 +173,8 @@ export const make: < * @experimental */ export const fromRecord = < - Accessor extends Context.Tag | Effect.Effect, - const Layers extends Record, Scope.Scope>, any, any>> + Accessor extends ServiceMap.Key | Effect.Effect, + const Layers extends Record, Scope.Scope>, any, any>> >( tagOrAccessor: Accessor, layers: Layers, @@ -184,7 +184,7 @@ export const fromRecord = < ): Effect.Effect< LayerMap< keyof Layers, - Exclude, Scope.Scope>, + Exclude, Scope.Scope>, Effect.Effect.Success, | Effect.Effect.Error | (Layers[keyof Layers] extends Layer.Layer ? _E : never) @@ -206,7 +206,7 @@ export interface TagClass< in out E, in out R, in out Deps extends Layer.Layer -> extends Context.TagClass> { +> extends ServiceMap.KeyClass> { /** * A default layer for the `LayerMap` service. */ @@ -297,11 +297,11 @@ export interface TagClass< export const Service = () => < const Id extends string, - Accessor extends Context.Tag | Effect.Effect, + Accessor extends ServiceMap.Key | Effect.Effect, Lookup extends { - readonly lookup: (key: any) => Layer.Layer, Scope.Scope>, any, any> + readonly lookup: (key: any) => Layer.Layer, Scope.Scope>, any, any> } | { - readonly layers: Record, Scope.Scope>, any, any>> + readonly layers: Record, Scope.Scope>, any, any>> }, const Deps extends ReadonlyArray> = [] >( @@ -317,10 +317,10 @@ export const Service = () => Lookup extends { readonly lookup: (key: infer K) => any } ? K : Lookup extends { readonly layers: infer Layers } ? keyof Layers : never, - Exclude, Scope.Scope>, + Exclude, Scope.Scope>, Effect.Effect.Success, Effect.Effect.Error | Service.Error, - Service.Context, + Service.ServiceMap, Deps[number] > => { const Err = globalThis.Error as any @@ -331,7 +331,7 @@ export const Service = () => function TagClass() {} const TagClass_ = TagClass as any as Mutable> - Object.setPrototypeOf(TagClass, Object.getPrototypeOf(Context.GenericTag(id))) + Object.setPrototypeOf(TagClass, Object.getPrototypeOf(ServiceMap.Key(id))) TagClass.key = id Object.defineProperty(TagClass, "stack", { get() { @@ -392,5 +392,5 @@ export declare namespace Service { * @category Service * @experimental */ - export type Context = Layers extends Layer.Layer ? _R : never + export type ServiceMap = Layers extends Layer.Layer ? _R : never } diff --git a/packages/effect/src/Logger.ts b/packages/effect/src/Logger.ts index 950dafc407..83d5f27036 100644 --- a/packages/effect/src/Logger.ts +++ b/packages/effect/src/Logger.ts @@ -3,7 +3,6 @@ */ import * as Array from "./Array.js" import type * as Cause from "./Cause.js" -import * as Context from "./Context.js" import type * as Duration from "./Duration.js" import type * as Effect from "./Effect.js" import type * as Fiber from "./Fiber.js" @@ -19,6 +18,7 @@ import type { PlatformError } from "./PlatformError.js" import * as Predicate from "./Predicate.js" import { CurrentLogAnnotations, CurrentLogSpans } from "./References.js" import type * as Scope from "./Scope.js" +import * as ServiceMap from "./ServiceMap.js" import type * as Types from "./Types.js" /** @@ -87,7 +87,7 @@ export const isLogger = (u: unknown): u is Logger => Predicate * @since 4.0.0 * @category references */ -export const CurrentLoggers: Context.Reference>> = effect.CurrentLoggers +export const CurrentLoggers: ServiceMap.Reference>> = effect.CurrentLoggers /** * @since 2.0.0 @@ -493,13 +493,13 @@ export const layer = < Scope.Scope > > => - Layer.effectContext( + Layer.effectServices( withFiber(effect.fnUntraced(function*(fiber) { const currentLoggers = new Set(options?.mergeWithExisting === true ? fiber.getRef(effect.CurrentLoggers) : []) for (const logger of loggers) { currentLoggers.add(isEffect(logger) ? yield* logger : logger) } - return Context.make(effect.CurrentLoggers, currentLoggers) + return ServiceMap.make(effect.CurrentLoggers, currentLoggers) })) ) diff --git a/packages/effect/src/Metric.ts b/packages/effect/src/Metric.ts index 84fccebbf4..b69bd1d680 100644 --- a/packages/effect/src/Metric.ts +++ b/packages/effect/src/Metric.ts @@ -3,7 +3,6 @@ */ import * as Arr from "./Array.js" -import * as Context from "./Context.js" import * as Duration from "./Duration.js" import type { Effect } from "./Effect.js" import type { Exit } from "./Exit.js" @@ -16,6 +15,7 @@ import * as Order from "./Order.js" import type { Pipeable } from "./Pipeable.js" import { pipeArguments } from "./Pipeable.js" import * as Predicate from "./Predicate.js" +import * as ServiceMap from "./ServiceMap.js" import * as _String from "./String.js" import type { Contravariant, Covariant } from "./Types.js" @@ -47,9 +47,9 @@ export interface Metric extends Pipeable { readonly type: Metric.Type readonly description: string | undefined readonly attributes: Metric.AttributeSet | undefined - readonly unsafeValue: (context: Context.Context) => State - readonly unsafeUpdate: (input: Input, context: Context.Context) => void - readonly unsafeModify: (input: Input, context: Context.Context) => void + readonly unsafeValue: (context: ServiceMap.ServiceMap) => State + readonly unsafeUpdate: (input: Input, context: ServiceMap.ServiceMap) => void + readonly unsafeModify: (input: Input, context: ServiceMap.ServiceMap) => void } /** @@ -165,9 +165,9 @@ export declare namespace Metric { * @since 2.0.0 */ export interface Hooks { - readonly get: (context: Context.Context) => State - readonly update: (input: Input, context: Context.Context) => void - readonly modify: (input: Input, context: Context.Context) => void + readonly get: (context: ServiceMap.ServiceMap) => State + readonly update: (input: Input, context: ServiceMap.ServiceMap) => void + readonly modify: (input: Input, context: ServiceMap.ServiceMap) => void } /** @@ -208,7 +208,7 @@ export const CurrentMetricAttributesKey = "effect/Metric/CurrentMetricAttributes * @since 4.0.0 * @category References */ -export class CurrentMetricAttributes extends Context.Reference(CurrentMetricAttributesKey, { +export class CurrentMetricAttributes extends ServiceMap.Reference(CurrentMetricAttributesKey, { defaultValue: () => ({}) as Metric.AttributeSet }) {} @@ -222,7 +222,7 @@ export const CurrentMetricRegistryKey = "effect/Metric/CurrentMetricRegistry" as * @since 4.0.0 * @category References */ -export class CurrentMetricRegistry extends Context.Reference(CurrentMetricRegistryKey, { +export class CurrentMetricRegistry extends ServiceMap.Reference(CurrentMetricRegistryKey, { defaultValue: () => new Map>() }) {} @@ -243,22 +243,22 @@ abstract class Metric$ implements Metric { readonly attributes: Metric.AttributeSet | undefined ) {} - unsafeValue(context: Context.Context): State { + unsafeValue(context: ServiceMap.ServiceMap): State { return this.hook(context).get(context) } - unsafeModify(input: Input, context: Context.Context): void { + unsafeModify(input: Input, context: ServiceMap.ServiceMap): void { return this.hook(context).modify(input, context) } - unsafeUpdate(input: Input, context: Context.Context): void { + unsafeUpdate(input: Input, context: ServiceMap.ServiceMap): void { return this.hook(context).update(input, context) } abstract createHooks(): Metric.Hooks - hook(context: Context.Context): Metric.Hooks { - const extraAttributes = Context.get(context, CurrentMetricAttributes) + hook(context: ServiceMap.ServiceMap): Metric.Hooks { + const extraAttributes = ServiceMap.get(context, CurrentMetricAttributes) if (Object.keys(extraAttributes).length === 0) { if (Predicate.isNotUndefined(this.#metadata)) { return this.#metadata.hooks @@ -277,11 +277,11 @@ abstract class Metric$ implements Metric { } getOrCreate( - context: Context.Context, + context: ServiceMap.ServiceMap, attributes: Metric.Attributes | undefined ): Metric.Metadata { const key = makeKey(this, attributes) - const registry = Context.get(context, CurrentMetricRegistry) + const registry = ServiceMap.get(context, CurrentMetricRegistry) if (registry.has(key)) { return registry.get(key)! } @@ -545,8 +545,8 @@ class SummaryMetric extends Metric$) => { - const clock = Context.get(context, InternalEffect.CurrentClock) + const get = (context: ServiceMap.ServiceMap) => { + const clock = ServiceMap.get(context, InternalEffect.CurrentClock) const quantiles = snapshot(clock.unsafeCurrentTimeMillis()) return { quantiles, count, min, max, sum } } @@ -561,9 +561,9 @@ class MetricTransform extends Metric$, - readonly unsafeValue: (context: Context.Context) => State, - readonly unsafeUpdate: (input: Input2, context: Context.Context) => void, - readonly unsafeModify: (input: Input2, context: Context.Context) => void + readonly unsafeValue: (context: ServiceMap.ServiceMap) => State, + readonly unsafeUpdate: (input: Input2, context: ServiceMap.ServiceMap) => void, + readonly unsafeModify: (input: Input2, context: ServiceMap.ServiceMap) => void ) { super(metric.id, metric.description, metric.attributes) this.type = metric.type @@ -777,7 +777,7 @@ export const summary = (name: string, options: { mapInput(summaryWithTimestamp(name, options), (input, context) => [ input, - Context.get(context, InternalEffect.CurrentClock).unsafeCurrentTimeMillis() + ServiceMap.get(context, InternalEffect.CurrentClock).unsafeCurrentTimeMillis() ] as [number, number]) /** @@ -854,7 +854,7 @@ export const value = ( self: Metric ): Effect => InternalEffect.flatMap( - InternalEffect.context(), + InternalEffect.services(), (context) => InternalEffect.sync(() => self.unsafeValue(context)) ) @@ -875,7 +875,7 @@ export const modify: { (self: Metric, input: Input) => Effect >(2, (self, input) => InternalEffect.flatMap( - InternalEffect.context(), + InternalEffect.services(), (context) => InternalEffect.sync(() => self.unsafeModify(input, context)) )) @@ -896,7 +896,7 @@ export const update: { (self: Metric, input: Input) => Effect >(2, (self, input) => InternalEffect.flatMap( - InternalEffect.context(), + InternalEffect.services(), (context) => InternalEffect.sync(() => self.unsafeUpdate(input, context)) )) @@ -910,23 +910,23 @@ export const update: { */ export const mapInput: { ( - f: (input: Input2, context: Context.Context) => Input + f: (input: Input2, context: ServiceMap.ServiceMap) => Input ): (self: Metric) => Metric ( self: Metric, - f: (input: Input2, context: Context.Context) => Input + f: (input: Input2, context: ServiceMap.ServiceMap) => Input ): Metric } = dual< ( - f: (input: Input2, context: Context.Context) => Input + f: (input: Input2, context: ServiceMap.ServiceMap) => Input ) => (self: Metric) => Metric, ( self: Metric, - f: (input: Input2, context: Context.Context) => Input + f: (input: Input2, context: ServiceMap.ServiceMap) => Input ) => Metric >(2, ( self: Metric, - f: (input: Input2, context: Context.Context) => Input + f: (input: Input2, context: ServiceMap.ServiceMap) => Input ): Metric => new MetricTransform( self, @@ -967,9 +967,9 @@ export const withAttributes: { ): Metric => new MetricTransform( self, - (context) => self.unsafeValue(addAttributesToContext(context, attributes)), - (input, context) => self.unsafeUpdate(input, addAttributesToContext(context, attributes)), - (input, context) => self.unsafeModify(input, addAttributesToContext(context, attributes)) + (context) => self.unsafeValue(addAttributesToServiceMap(context, attributes)), + (input, context) => self.unsafeUpdate(input, addAttributesToServiceMap(context, attributes)), + (input, context) => self.unsafeModify(input, addAttributesToServiceMap(context, attributes)) )) // Metric Snapshots @@ -979,7 +979,7 @@ export const withAttributes: { * @category Snapshotting */ export const snapshot: Effect> = InternalEffect.map( - InternalEffect.context(), + InternalEffect.services(), (context) => makeSnapshot(context) ) @@ -987,7 +987,7 @@ export const snapshot: Effect> = InternalEffect.m * @since 2.0.0 * @category Debugging */ -export const dump: Effect = InternalEffect.flatMap(InternalEffect.context(), (context) => { +export const dump: Effect = InternalEffect.flatMap(InternalEffect.services(), (context) => { const metrics = makeSnapshot(context) if (metrics.length > 0) { const maxNameLength = metrics.reduce((max, metric) => { @@ -1022,8 +1022,8 @@ export const dump: Effect = InternalEffect.flatMap(InternalEffect.contex return InternalEffect.succeed("") }) -const makeSnapshot = (context: Context.Context): ReadonlyArray => { - const registry = Context.get(context, CurrentMetricRegistry) +const makeSnapshot = (context: ServiceMap.ServiceMap): ReadonlyArray => { + const registry = ServiceMap.get(context, CurrentMetricRegistry) return Array.from(registry.values()).map(({ hooks, ...meta }) => ({ ...meta, state: hooks.get(context) @@ -1161,15 +1161,15 @@ export const FiberRuntimeMetricsKey: typeof InternalMetric.FiberRuntimeMetricsKe * @category Runtime Metrics */ export interface FiberRuntimeMetricsService { - readonly recordFiberStart: (context: Context.Context) => void - readonly recordFiberEnd: (context: Context.Context, exit: Exit) => void + readonly recordFiberStart: (context: ServiceMap.ServiceMap) => void + readonly recordFiberEnd: (context: ServiceMap.ServiceMap, exit: Exit) => void } /** * @since 4.0.0 * @category Runtime Metrics */ -export class FiberRuntimeMetrics extends Context.Reference(InternalMetric.FiberRuntimeMetricsKey, { +export class FiberRuntimeMetrics extends ServiceMap.Reference(InternalMetric.FiberRuntimeMetricsKey, { defaultValue: (): FiberRuntimeMetricsService | undefined => undefined }) {} @@ -1178,11 +1178,11 @@ export class FiberRuntimeMetrics extends Context.Reference(InternalMetric.FiberR * @category Runtime Metrics */ export const FiberRuntimeMetricsImpl: FiberRuntimeMetricsService = { - recordFiberStart(context: Context.Context) { + recordFiberStart(context: ServiceMap.ServiceMap) { fibersStarted.unsafeUpdate(1, context) fibersActive.unsafeModify(1, context) }, - recordFiberEnd(context: Context.Context, exit: Exit) { + recordFiberEnd(context: ServiceMap.ServiceMap, exit: Exit) { fibersActive.unsafeModify(-1, context) if (InternalEffect.exitIsSuccess(exit)) { fiberSuccesses.unsafeUpdate(1, context) @@ -1239,9 +1239,9 @@ function makeKey( } function makeHooks( - get: (context: Context.Context) => State, - update: (input: Input, context: Context.Context) => void, - modify?: (input: Input, context: Context.Context) => void + get: (context: ServiceMap.ServiceMap) => State, + update: (input: Input, context: ServiceMap.ServiceMap) => void, + modify?: (input: Input, context: ServiceMap.ServiceMap) => void ): Metric.Hooks { return { get, update, modify: modify ?? update } } @@ -1271,11 +1271,11 @@ function attributesToRecord(attributes?: Metric.Attributes): Metric.AttributeSet return attributes as Metric.AttributeSet | undefined } -function addAttributesToContext( - context: Context.Context, +function addAttributesToServiceMap( + context: ServiceMap.ServiceMap, attributes: Metric.Attributes -): Context.Context { - const current = Context.get(context, CurrentMetricAttributes) +): ServiceMap.ServiceMap { + const current = ServiceMap.get(context, CurrentMetricAttributes) const updated = mergeAttributes(current, attributes) - return Context.add(context, CurrentMetricAttributes, updated) + return ServiceMap.add(context, CurrentMetricAttributes, updated) } diff --git a/packages/effect/src/Path.ts b/packages/effect/src/Path.ts index 426a2eb13e..a0ea764caf 100644 --- a/packages/effect/src/Path.ts +++ b/packages/effect/src/Path.ts @@ -1,7 +1,7 @@ /** * @since 4.0.0 */ -import * as Context from "./Context.js" +import * as ServiceMap from "./ServiceMap.js" import type { Effect } from "./Effect.js" import type { BadArgument } from "./PlatformError.js" @@ -60,4 +60,4 @@ export declare namespace Path { * @since 4.0.0 * @category tag */ -export const Path: Context.Tag = Context.GenericTag("effect/Path") +export const Path: ServiceMap.Key = ServiceMap.Key("effect/Path") diff --git a/packages/effect/src/Pull.ts b/packages/effect/src/Pull.ts index d6307369f1..8b308579a8 100644 --- a/packages/effect/src/Pull.ts +++ b/packages/effect/src/Pull.ts @@ -42,7 +42,7 @@ export type Leftover

= P extends Effect ? _E ex * @since 4.0.0 * @category type extractors */ -export type Context

= P extends Effect ? _R : never +export type ServiceMap

= P extends Effect ? _R : never /** * @since 4.0.0 diff --git a/packages/effect/src/RcMap.ts b/packages/effect/src/RcMap.ts index eef3867100..978a60d0ec 100644 --- a/packages/effect/src/RcMap.ts +++ b/packages/effect/src/RcMap.ts @@ -2,7 +2,6 @@ * @since 3.5.0 */ import * as Cause from "./Cause.js" -import * as Context from "./Context.js" import * as Deferred from "./Deferred.js" import * as Duration from "./Duration.js" import * as Effect from "./Effect.js" @@ -13,6 +12,7 @@ import * as MutableHashMap from "./MutableHashMap.js" import type { Pipeable } from "./Pipeable.js" import { pipeArguments } from "./Pipeable.js" import * as Scope from "./Scope.js" +import * as ServiceMap from "./ServiceMap.js" /** * @since 3.5.0 @@ -33,7 +33,7 @@ export type TypeId = typeof TypeId export interface RcMap extends Pipeable { readonly [TypeId]: TypeId readonly lookup: (key: K) => Effect.Effect - readonly context: Context.Context + readonly services: ServiceMap.ServiceMap readonly scope: Scope.Scope readonly idleTimeToLive: Duration.Duration | undefined readonly capacity: number @@ -85,14 +85,14 @@ export declare namespace State { const unsafeMake = (options: { readonly lookup: (key: K) => Effect.Effect - readonly context: Context.Context + readonly services: ServiceMap.ServiceMap readonly scope: Scope.Scope readonly idleTimeToLive: Duration.Duration | undefined readonly capacity: number }): RcMap => ({ [TypeId]: TypeId, lookup: options.lookup, - context: options.context, + services: options.services, scope: options.scope, idleTimeToLive: options.idleTimeToLive, capacity: options.capacity, @@ -159,11 +159,11 @@ export const make: { readonly capacity?: number | undefined }) => Effect.withFiber, never, R | Scope.Scope>((fiber) => { - const context = fiber.context as Context.Context - const scope = Context.get(context, Scope.Scope) + const services = fiber.services as ServiceMap.ServiceMap + const scope = ServiceMap.get(services, Scope.Scope) const self = unsafeMake({ lookup: options.lookup as any, - context, + services, scope, idleTimeToLive: options.idleTimeToLive ? Duration.decode(options.idleTimeToLive) : undefined, capacity: Math.max(options.capacity ?? Number.POSITIVE_INFINITY, 0) @@ -227,15 +227,15 @@ const acquire = Effect.fnUntraced(function*(self: RcMap, key: const scope = Scope.unsafeMake() const deferred = Deferred.unsafeMake() const acquire = self.lookup(key) - const contextMap = new Map(self.context.unsafeMap) - yield* restore(Effect.updateContext( + const servicesMap = new Map(self.services.unsafeMap) + yield* restore(Effect.updateServices( acquire as Effect.Effect, - (inputContext: Context.Context) => { - inputContext.unsafeMap.forEach((value, key) => { - contextMap.set(key, value) + (inputServices: ServiceMap.ServiceMap) => { + inputServices.unsafeMap.forEach((value, key) => { + servicesMap.set(key, value) }) - contextMap.set(Scope.Scope.key, scope) - return Context.unsafeMake(contextMap) + servicesMap.set(Scope.Scope.key, scope) + return ServiceMap.unsafeMake(servicesMap) } )).pipe( Effect.exit, diff --git a/packages/effect/src/References.ts b/packages/effect/src/References.ts index 4d19cbcbd4..5ebd5a8496 100644 --- a/packages/effect/src/References.ts +++ b/packages/effect/src/References.ts @@ -1,12 +1,12 @@ /** * @since 4.0.0 */ -import * as Context from "./Context.js" import { constTrue } from "./Function.js" import type { LogLevel } from "./LogLevel.js" import type { ReadonlyRecord } from "./Record.js" import type { Scheduler } from "./Scheduler.js" import { MaxOpsBeforeYield, MixedScheduler } from "./Scheduler.js" +import * as ServiceMap from "./ServiceMap.js" import { CurrentTracer, DisablePropagation, type SpanLink } from "./Tracer.js" export { @@ -31,7 +31,7 @@ export { * @since 4.0.0 * @category references */ -export class CurrentConcurrency extends Context.Reference< +export class CurrentConcurrency extends ServiceMap.Reference< "effect/References/CurrentConcurrency", "unbounded" | number >("effect/References/CurrentConcurrency", { defaultValue: () => "unbounded" }) {} @@ -40,7 +40,7 @@ export class CurrentConcurrency extends Context.Reference< * @since 4.0.0 * @category references */ -export class CurrentScheduler extends Context.Reference< +export class CurrentScheduler extends ServiceMap.Reference< "effect/References/CurrentScheduler", Scheduler >("effect/References/CurrentScheduler", { @@ -51,7 +51,7 @@ export class CurrentScheduler extends Context.Reference< * @since 4.0.0 * @category references */ -export class TracerEnabled extends Context.Reference< +export class TracerEnabled extends ServiceMap.Reference< "effect/References/TracerEnabled", boolean >("effect/References/TracerEnabled", { @@ -62,7 +62,7 @@ export class TracerEnabled extends Context.Reference< * @since 4.0.0 * @category references */ -export class TracerSpanAnnotations extends Context.Reference< +export class TracerSpanAnnotations extends ServiceMap.Reference< "effect/References/TracerSpanAnnotations", ReadonlyRecord >("effect/References/TracerSpanAnnotations", { @@ -73,7 +73,7 @@ export class TracerSpanAnnotations extends Context.Reference< * @since 4.0.0 * @category references */ -export class TracerSpanLinks extends Context.Reference< +export class TracerSpanLinks extends ServiceMap.Reference< "effect/References/TracerSpanLinks", ReadonlyArray >("effect/References/TracerSpanLinks", { @@ -84,7 +84,7 @@ export class TracerSpanLinks extends Context.Reference< * @since 4.0.0 * @category references */ -export class CurrentLogAnnotations extends Context.Reference< +export class CurrentLogAnnotations extends ServiceMap.Reference< "effect/References/CurrentLogAnnotations", ReadonlyRecord >("effect/References/CurrentLogAnnotations", { @@ -95,7 +95,7 @@ export class CurrentLogAnnotations extends Context.Reference< * @since 4.0.0 * @category references */ -export class CurrentLogLevel extends Context.Reference< +export class CurrentLogLevel extends ServiceMap.Reference< "effect/References/CurrentLogLevel", LogLevel >("effect/References/CurrentLogLevel", { @@ -106,7 +106,7 @@ export class CurrentLogLevel extends Context.Reference< * @since 4.0.0 * @category references */ -export class CurrentLogSpans extends Context.Reference< +export class CurrentLogSpans extends ServiceMap.Reference< "effect/References/CurrentLogSpans", ReadonlyArray<[label: string, timestamp: number]> >("effect/References/CurrentLogSpans", { @@ -117,7 +117,7 @@ export class CurrentLogSpans extends Context.Reference< * @since 4.0.0 * @category references */ -export class MinimumLogLevel extends Context.Reference< +export class MinimumLogLevel extends ServiceMap.Reference< "effect/References/MinimumLogLevel", LogLevel >("effect/References/MinimumLogLevel", { diff --git a/packages/effect/src/Request.ts b/packages/effect/src/Request.ts index 8400a82c5a..133e53fa5f 100644 --- a/packages/effect/src/Request.ts +++ b/packages/effect/src/Request.ts @@ -2,7 +2,7 @@ * @since 2.0.0 */ import type * as Cause from "./Cause.js" -import type * as Context from "./Context.js" +import type * as ServiceMap from "./ServiceMap.js" import type * as Effect from "./Effect.js" import type * as Exit from "./Exit.js" import { dual } from "./Function.js" @@ -81,7 +81,7 @@ export declare namespace Request { * @since 4.0.0 * @category type-level */ - export type Context> = [T] extends [Request] ? _R + export type Services> = [T] extends [Request] ? _R : never /** @@ -148,10 +148,10 @@ export const tagged = & { _tag: string }>( * @since 2.0.0 * @category constructors */ -export const Class: new, Success, Error = never, Context = never>( +export const Class: new, Success, Error = never, ServiceMap = never>( args: Types.Equals>, {}> extends true ? void : { readonly [P in keyof A as P extends keyof Request ? never : P]: A[P] } -) => Request & Readonly = (function() { +) => Request & Readonly = (function() { function Class(this: any, args: any) { if (args) { Object.assign(this, args) @@ -167,10 +167,10 @@ export const Class: new, Success, Error = never, C */ export const TaggedClass = ( tag: Tag -): new, Success, Error = never, Context = never>( +): new, Success, Error = never, ServiceMap = never>( args: Types.Equals>, {}> extends true ? void : { readonly [P in keyof A as P extends "_tag" | keyof Request ? never : P]: A[P] } -) => Request & Readonly & { readonly _tag: Tag } => { +) => Request & Readonly & { readonly _tag: Tag } => { return class TaggedClass extends Class { readonly _tag = tag } as any @@ -256,7 +256,7 @@ export const succeed = dual< */ export interface Entry { readonly request: R - readonly context: Context.Context< + readonly services: ServiceMap.ServiceMap< [R] extends [Request] ? _R : never > readonly unsafeComplete: ( @@ -273,7 +273,7 @@ export interface Entry { */ export const makeEntry = (options: { readonly request: R - readonly context: Context.Context< + readonly services: ServiceMap.ServiceMap< [R] extends [Request] ? _R : never > readonly unsafeComplete: ( diff --git a/packages/effect/src/RequestResolver.ts b/packages/effect/src/RequestResolver.ts index 4ea866cde0..c78589a7c1 100644 --- a/packages/effect/src/RequestResolver.ts +++ b/packages/effect/src/RequestResolver.ts @@ -2,7 +2,6 @@ * @since 2.0.0 */ import type { NonEmptyArray } from "./Array.js" -import * as Context from "./Context.js" import * as Duration from "./Duration.js" import type { Effect } from "./Effect.js" import { constTrue, dual, identity } from "./Function.js" @@ -12,6 +11,7 @@ import * as MutableHashMap from "./MutableHashMap.js" import { type Pipeable, pipeArguments } from "./Pipeable.js" import { hasProperty } from "./Predicate.js" import * as Request from "./Request.js" +import * as ServiceMap from "./ServiceMap.js" import * as Tracer from "./Tracer.js" import type * as Types from "./Types.js" @@ -436,7 +436,7 @@ export const withSpan: { const links = options?.links ? options.links.slice() : [] const seen = new Set() for (const entry of entries) { - const span = Context.getOption(entry.context, Tracer.ParentSpan) + const span = ServiceMap.getOption(entry.services, Tracer.ParentSpan) if (span._tag === "None" || seen.has(span.value)) continue seen.add(span.value) links.push({ span: span.value, attributes: {} }) diff --git a/packages/effect/src/Schedule.ts b/packages/effect/src/Schedule.ts index c657ed0bbe..73aeab37a8 100644 --- a/packages/effect/src/Schedule.ts +++ b/packages/effect/src/Schedule.ts @@ -1048,9 +1048,9 @@ export const forever: Schedule = spaced(Duration.zero) * @category ensuring types */ export const ensureInput = () => -( - self: Schedule -): Schedule => self +( + self: Schedule +): Schedule => self /** * Ensures that the provided schedule respects a specified output type @@ -1059,9 +1059,9 @@ export const ensureInput = () => * @category ensuring types */ export const ensureOutput = () => -( - self: Schedule -): Schedule => self +( + self: Schedule +): Schedule => self /** * Ensures that the provided schedule respects a specified error type @@ -1070,9 +1070,9 @@ export const ensureOutput = () => * @category ensuring types */ export const ensureError = () => -( - self: Schedule -): Schedule => self +( + self: Schedule +): Schedule => self /** * Ensures that the provided schedule respects a specified context type @@ -1080,7 +1080,7 @@ export const ensureError = () => * @since 2.0.0 * @category ensuring types */ -export const ensureContext = () => -( - self: Schedule -): Schedule => self +export const ensureServices = () => +( + self: Schedule +): Schedule => self diff --git a/packages/effect/src/Scheduler.ts b/packages/effect/src/Scheduler.ts index 7b92f4a197..ab5f7a534a 100644 --- a/packages/effect/src/Scheduler.ts +++ b/packages/effect/src/Scheduler.ts @@ -1,7 +1,7 @@ /** * @since 2.0.0 */ -import * as Context from "./Context.js" +import * as ServiceMap from "./ServiceMap.js" import type * as Fiber from "./Fiber.js" /** @@ -90,7 +90,7 @@ export class MixedScheduler implements Scheduler { * @since 4.0.0 * @category references */ -export class MaxOpsBeforeYield extends Context.Reference< +export class MaxOpsBeforeYield extends ServiceMap.Reference< "effect/Scheduler/MaxOpsBeforeYield", number >("effect/Scheduler/MaxOpsBeforeYield", { defaultValue: () => 2048 }) {} diff --git a/packages/effect/src/Scope.ts b/packages/effect/src/Scope.ts index e41d2b9246..31b5105af3 100644 --- a/packages/effect/src/Scope.ts +++ b/packages/effect/src/Scope.ts @@ -2,7 +2,7 @@ * @since 2.0.0 */ -import type * as Context from "./Context.js" +import type * as ServiceMap from "./ServiceMap.js" import type { Effect } from "./Effect.js" import type { Exit } from "./Exit.js" import * as effect from "./internal/effect.js" @@ -82,7 +82,7 @@ export declare namespace Scope { * @since 2.0.0 * @category tags */ -export const Scope: Context.Tag = effect.scopeTag +export const Scope: ServiceMap.Key = effect.scopeTag /** * @since 2.0.0 diff --git a/packages/effect/src/ServiceMap.ts b/packages/effect/src/ServiceMap.ts new file mode 100644 index 0000000000..1c0ff0eef8 --- /dev/null +++ b/packages/effect/src/ServiceMap.ts @@ -0,0 +1,659 @@ +/** + * This module provides a data structure called `ServiceMap` that can be used for dependency injection in effectful + * programs. It is essentially a table mapping `Keys`s to their implementations (called `Service`s), and can be used to + * manage dependencies in a type-safe way. The `ServiceMap` data structure is essentially a way of providing access to a set + * of related services that can be passed around as a single unit. This module provides functions to create, modify, and + * query the contents of a `ServiceMap`, as well as a number of utility types for working with keys and services. + * + * @since 4.0.0 + */ +import { type EffectIterator, type Yieldable } from "./Effect.js" +import * as Equal from "./Equal.js" +import { dual, type LazyArg } from "./Function.js" +import * as Hash from "./Hash.js" +import type { Inspectable } from "./Inspectable.js" +import { exitSucceed, PipeInspectableProto, withFiber, YieldableProto } from "./internal/core.js" +import * as Option from "./Option.js" +import type { Pipeable } from "./Pipeable.js" +import { hasProperty } from "./Predicate.js" +import type * as Types from "./Types.js" + +/** + * @since 4.0.0 + * @category Symbols + */ +export const KeyTypeId: unique symbol = Symbol.for("effect/ServiceMap/Key") + +/** + * @since 4.0.0 + * @category Symbols + */ +export type KeyTypeId = typeof KeyTypeId + +/** + * @since 4.0.0 + * @category Models + */ +export interface Key extends Pipeable, Inspectable, Yieldable { + readonly [KeyTypeId]: { + readonly _Service: Types.Invariant + readonly _Identifier: Types.Invariant + } + readonly Service: Service + readonly Identifier: Id + [Symbol.iterator](): EffectIterator> + of(self: Service): Service + serviceMap(self: Service): ServiceMap + + readonly stack?: string | undefined + readonly key: string +} + +/** + * @since 4.0.0 + * @category Models + */ +export interface KeyClass extends Key { + new(_: never): { + readonly [KeyTypeId]: KeyTypeId + readonly key: Id + readonly Service: Service + } + readonly key: Id +} + +/** + * @since 4.0.0 + * @category Constructors + */ +export const Key: { + (key: string): Key + (): (id: Id) => KeyClass +} = function() { + const prevLimit = Error.stackTraceLimit + Error.stackTraceLimit = 2 + const err = new Error() + Error.stackTraceLimit = prevLimit + function KeyClass() {} + const self = KeyClass as any as Types.Mutable> + Object.setPrototypeOf(self, KeyProto) + Object.defineProperty(self, "stack", { + get() { + return err.stack + } + }) + if (arguments.length > 0) { + self.key = arguments[0] + if (arguments[1]?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId + self.defaultValue = arguments[1].defaultValue + } + return self + } + return function(key: string) { + self.key = key + return self + } +} as any + +const KeyProto: any = { + [KeyTypeId]: { + _Service: (_: unknown) => _, + _Identifier: (_: unknown) => _ + }, + ...PipeInspectableProto, + ...YieldableProto, + toJSON(this: Key) { + return { + _id: "Key", + key: this.key, + stack: this.stack + } + }, + asEffect() { + return withFiber((fiber) => exitSucceed(unsafeGet(fiber.services, this))) + }, + of(self: Service): Service { + return self + }, + serviceMap( + this: Key, + self: Service + ): ServiceMap { + return make(this, self) + } +} + +/** + * @since 4.0.0 + * @category Symbols + */ +export const ReferenceTypeId: unique symbol = Symbol.for("effect/ServiceMap/Reference") + +/** + * @since 4.0.0 + * @category Symbols + */ +export type ReferenceTypeId = typeof ReferenceTypeId + +/** + * @since 4.0.0 + * @category Models + */ +export interface Reference extends Key { + readonly [ReferenceTypeId]: ReferenceTypeId + readonly defaultValue: () => Service + [Symbol.iterator](): EffectIterator> +} + +/** + * @since 4.0.0 + * @category Models + */ +export interface ReferenceClass extends Reference { + new(_: never): { + readonly [KeyTypeId]: KeyTypeId + readonly [ReferenceTypeId]: ReferenceTypeId + readonly key: Id + readonly Service: Service + } + readonly key: Id +} + +/** + * @since 4.0.0 + */ +export declare namespace Key { + /** + * @since 4.0.0 + */ + export interface Variance { + readonly [KeyTypeId]: { + readonly _Service: Types.Invariant + readonly _Identifier: Types.Invariant + } + } + /** + * @since 4.0.0 + */ + export type Any = Key | Key + /** + * @since 4.0.0 + */ + export type Service = T extends Variance ? S : never + /** + * @since 4.0.0 + */ + export type Identifier = T extends Variance ? I : never +} + +/** + * @since 4.0.0 + * @category Symbols + */ +export const TypeId: unique symbol = Symbol.for("effect/ServiceMap") + +/** + * @since 4.0.0 + * @category Symbols + */ +export type TypeId = typeof TypeId + +/** + * @since 4.0.0 + * @category Models + */ +export interface ServiceMap extends Equal.Equal, Pipeable, Inspectable { + readonly [TypeId]: { + readonly _Services: Types.Contravariant + } + readonly unsafeMap: Map +} + +/** + * @since 4.0.0 + * @category Constructors + */ +export const unsafeMake = (unsafeMap: Map): ServiceMap => { + const self = Object.create(Proto) + self.unsafeMap = unsafeMap + return self +} + +const Proto: Omit, "unsafeMap"> = { + ...PipeInspectableProto, + [TypeId]: { + _Services: (_: never) => _ + }, + toJSON(this: ServiceMap) { + return { + _id: "ServiceMap", + services: Array.from(this.unsafeMap).map(([key, value]) => ({ key, value })) + } + }, + [Equal.symbol](this: ServiceMap, that: unknown): boolean { + if ( + !isServiceMap(that) + || this.unsafeMap.size !== that.unsafeMap.size + ) return false + for (const k of this.unsafeMap.keys()) { + if ( + !that.unsafeMap.has(k) || + !Equal.equals(this.unsafeMap.get(k), that.unsafeMap.get(k)) + ) { + return false + } + } + return true + }, + [Hash.symbol](this: ServiceMap): number { + return Hash.cached(this, () => Hash.number(this.unsafeMap.size)) + } +} + +/** + * Checks if the provided argument is a `ServiceMap`. + * + * @param u - The value to be checked if it is a `ServiceMap`. + * + * @example + * ```ts + * import * as assert from "node:assert" + * import { ServiceMap } from "effect" + * + * assert.strictEqual(ServiceMap.isServiceMap(ServiceMap.empty()), true) + * ``` + * + * @since 4.0.0 + * @category Guards + */ +export const isServiceMap = (u: unknown): u is ServiceMap => hasProperty(u, TypeId) + +/** + * Checks if the provided argument is a `Key`. + * + * @param u - The value to be checked if it is a `Key`. + * + * @example + * ```ts + * import * as assert from "node:assert" + * import { ServiceMap } from "effect" + * + * assert.strictEqual(ServiceMap.isKey(ServiceMap.Key("Key")), true) + * ``` + * + * @since 4.0.0 + * @category Guards + */ +export const isKey = (u: unknown): u is Key => hasProperty(u, KeyTypeId) + +/** + * Checks if the provided argument is a `Reference`. + * + * @since 4.0.0 + * @category Guards + */ +export const isReference = (u: unknown): u is Reference => hasProperty(u, ReferenceTypeId) + +/** + * Returns an empty `ServiceMap`. + * + * @example + * ```ts + * import * as assert from "node:assert" + * import { ServiceMap } from "effect" + * + * assert.strictEqual(ServiceMap.isServiceMap(ServiceMap.empty()), true) + * ``` + * + * @since 4.0.0 + * @category Constructors + */ +export const empty = (): ServiceMap => emptyServiceMap +const emptyServiceMap = unsafeMake(new Map()) + +/** + * Creates a new `ServiceMap` with a single service associated to the key. + * + * @example + * ```ts + * import * as assert from "node:assert" + * import { ServiceMap } from "effect" + * + * const Port = ServiceMap.Key<{ PORT: number }>("Port") + * + * const Services = ServiceMap.make(Port, { PORT: 8080 }) + * + * assert.deepStrictEqual(ServiceMap.get(Services, Port), { PORT: 8080 }) + * ``` + * + * @since 4.0.0 + * @category Constructors + */ +export const make = ( + key: Key, + service: Types.NoInfer +): ServiceMap => unsafeMake(new Map([[key.key, service]])) + +/** + * Adds a service to a given `ServiceMap`. + * + * @example + * ```ts + * import * as assert from "node:assert" + * import { ServiceMap, pipe } from "effect" + * + * const Port = ServiceMap.Key<{ PORT: number }>("Port") + * const Timeout = ServiceMap.Key<{ TIMEOUT: number }>("Timeout") + * + * const someServiceMap = ServiceMap.make(Port, { PORT: 8080 }) + * + * const Services = pipe( + * someServiceMap, + * ServiceMap.add(Timeout, { TIMEOUT: 5000 }) + * ) + * + * assert.deepStrictEqual(ServiceMap.get(Services, Port), { PORT: 8080 }) + * assert.deepStrictEqual(ServiceMap.get(Services, Timeout), { TIMEOUT: 5000 }) + * ``` + * + * @since 4.0.0 + * @category Adders + */ +export const add: { + ( + key: Key, + service: Types.NoInfer + ): (self: ServiceMap) => ServiceMap + ( + self: ServiceMap, + key: Key, + service: Types.NoInfer + ): ServiceMap +} = dual(3, ( + self: ServiceMap, + key: Key, + service: Types.NoInfer +): ServiceMap => { + const map = new Map(self.unsafeMap) + map.set(key.key, service) + return unsafeMake(map) +}) + +/** + * Get a service from the context that corresponds to the given key, or + * use the fallback value. + * + * @since 4.0.0 + * @category Getters + */ +export const getOrElse: { + (key: Key, orElse: LazyArg): (self: ServiceMap) => S | B + (self: ServiceMap, key: Key, orElse: LazyArg): S | B +} = dual(3, (self: ServiceMap, key: Key, orElse: LazyArg): S | B => { + if (self.unsafeMap.has(key.key)) { + return self.unsafeMap.get(key.key)! as any + } + return isReference(key) ? getDefaultValue(key) : orElse() +}) + +/** + * Get a service from the context that corresponds to the given key. + * This function is unsafe because if the key is not present in the context, a runtime error will be thrown. + * + * For a safer version see {@link getOption}. + * + * @param self - The `ServiceMap` to search for the service. + * @param key - The `Key` of the service to retrieve. + * + * @example + * ```ts + * import * as assert from "node:assert" + * import { ServiceMap } from "effect" + * + * const Port = ServiceMap.Key<{ PORT: number }>("Port") + * const Timeout = ServiceMap.Key<{ TIMEOUT: number }>("Timeout") + * + * const Services = ServiceMap.make(Port, { PORT: 8080 }) + * + * assert.deepStrictEqual(ServiceMap.unsafeGet(Services, Port), { PORT: 8080 }) + * assert.throws(() => ServiceMap.unsafeGet(Services, Timeout)) + * ``` + * + * @since 4.0.0 + * @category unsafe + */ +export const unsafeGet: { + (key: Key): (self: ServiceMap) => S + (self: ServiceMap, key: Key): S +} = dual( + 2, + (self: ServiceMap, key: Key): S => { + if (!self.unsafeMap.has(key.key)) { + if (ReferenceTypeId in key) return getDefaultValue(key as any) + throw serviceNotFoundError(key) + } + return self.unsafeMap.get(key.key)! as any + } +) + +/** + * @since 4.0.0 + * @category unsafe + */ +export const unsafeGetReference = (self: ServiceMap, key: Reference): S => { + if (!self.unsafeMap.has(key.key)) { + return getDefaultValue(key as any) + } + return self.unsafeMap.get(key.key)! as any +} + +const defaultValueCacheKey = "~effect/ServiceMap/defaultValue" +const getDefaultValue = (ref: Reference) => { + if (defaultValueCacheKey in ref) { + return ref[defaultValueCacheKey] as any + } + return (ref as any)[defaultValueCacheKey] = ref.defaultValue() +} + +const serviceNotFoundError = (key: Key) => { + const error = new Error( + `Service not found${key.key ? `: ${String(key.key)}` : ""}` + ) + if (key.stack) { + const lines = key.stack.split("\n") + if (lines.length > 2) { + const afterAt = lines[2].match(/at (.*)/) + if (afterAt) { + error.message = error.message + ` (defined at ${afterAt[1]})` + } + } + } + if (error.stack) { + const lines = error.stack.split("\n") + lines.splice(1, 3) + error.stack = lines.join("\n") + } + return error +} + +/** + * Get a service from the context that corresponds to the given key. + * + * @param self - The `ServiceMap` to search for the service. + * @param key - The `Key` of the service to retrieve. + * + * @example + * ```ts + * import * as assert from "node:assert" + * import { pipe, ServiceMap } from "effect" + * + * const Port = ServiceMap.Key<{ PORT: number }>("Port") + * const Timeout = ServiceMap.Key<{ TIMEOUT: number }>("Timeout") + * + * const Services = pipe( + * ServiceMap.make(Port, { PORT: 8080 }), + * ServiceMap.add(Timeout, { TIMEOUT: 5000 }) + * ) + * + * assert.deepStrictEqual(ServiceMap.get(Services, Timeout), { TIMEOUT: 5000 }) + * ``` + * + * @since 4.0.0 + * @category Getters + */ +export const get: { + (key: Key): (self: ServiceMap) => S + (self: ServiceMap, key: Key): S +} = unsafeGet + +/** + * Get the value associated with the specified key from the context wrapped in an `Option` object. If the key is not + * found, the `Option` object will be `None`. + * + * @param self - The `ServiceMap` to search for the service. + * @param key - The `Key` of the service to retrieve. + * + * @example + * ```ts + * import * as assert from "node:assert" + * import { ServiceMap, Option } from "effect" + * + * const Port = ServiceMap.Key<{ PORT: number }>("Port") + * const Timeout = ServiceMap.Key<{ TIMEOUT: number }>("Timeout") + * + * const Services = ServiceMap.make(Port, { PORT: 8080 }) + * + * assert.deepStrictEqual(ServiceMap.getOption(Services, Port), Option.some({ PORT: 8080 })) + * assert.deepStrictEqual(ServiceMap.getOption(Services, Timeout), Option.none()) + * ``` + * + * @since 4.0.0 + * @category Getters + */ +export const getOption: { + (key: Key): (self: ServiceMap) => Option.Option + (self: ServiceMap, key: Key): Option.Option +} = dual(2, (self: ServiceMap, key: Key): Option.Option => { + if (self.unsafeMap.has(key.key)) { + return Option.some(self.unsafeMap.get(key.key)! as any) + } + return isReference(key) ? Option.some(getDefaultValue(key as any)) : Option.none() +}) + +/** + * Merges two `ServiceMap`s, returning a new `ServiceMap` containing the services of both. + * + * @param self - The first `ServiceMap` to merge. + * @param that - The second `ServiceMap` to merge. + * + * @example + * ```ts + * import * as assert from "node:assert" + * import { ServiceMap } from "effect" + * + * const Port = ServiceMap.Key<{ PORT: number }>("Port") + * const Timeout = ServiceMap.Key<{ TIMEOUT: number }>("Timeout") + * + * const firstServiceMap = ServiceMap.make(Port, { PORT: 8080 }) + * const secondServiceMap = ServiceMap.make(Timeout, { TIMEOUT: 5000 }) + * + * const Services = ServiceMap.merge(firstServiceMap, secondServiceMap) + * + * assert.deepStrictEqual(ServiceMap.get(Services, Port), { PORT: 8080 }) + * assert.deepStrictEqual(ServiceMap.get(Services, Timeout), { TIMEOUT: 5000 }) + * ``` + * + * @since 4.0.0 + */ +export const merge: { + (that: ServiceMap): (self: ServiceMap) => ServiceMap + (self: ServiceMap, that: ServiceMap): ServiceMap +} = dual(2, (self: ServiceMap, that: ServiceMap): ServiceMap => { + if (self.unsafeMap.size === 0) return that as any + if (that.unsafeMap.size === 0) return self as any + const map = new Map(self.unsafeMap) + for (const [key, value] of that.unsafeMap) { + map.set(key, value) + } + return unsafeMake(map) +}) + +/** + * Returns a new `ServiceMap` that contains only the specified services. + * + * @param self - The `ServiceMap` to prune services from. + * @param keys - The list of `Key`s to be included in the new `ServiceMap`. + * + * @example + * ```ts + * import * as assert from "node:assert" + * import { pipe, ServiceMap, Option } from "effect" + * + * const Port = ServiceMap.Key<{ PORT: number }>("Port") + * const Timeout = ServiceMap.Key<{ TIMEOUT: number }>("Timeout") + * + * const someServiceMap = pipe( + * ServiceMap.make(Port, { PORT: 8080 }), + * ServiceMap.add(Timeout, { TIMEOUT: 5000 }) + * ) + * + * const Services = pipe(someServiceMap, ServiceMap.pick(Port)) + * + * assert.deepStrictEqual(ServiceMap.getOption(Services, Port), Option.some({ PORT: 8080 })) + * assert.deepStrictEqual(ServiceMap.getOption(Services, Timeout), Option.none()) + * ``` + * + * @since 4.0.0 + */ +export const pick = >>( + ...keys: Keys +) => +(self: ServiceMap): ServiceMap> => { + const map = new Map() + const keySet = new Set(keys.map((key) => key.key)) + for (const [key, value] of self.unsafeMap) { + if (keySet.has(key)) { + map.set(key, value) + } + } + return unsafeMake(map) +} + +/** + * @since 4.0.0 + */ +export const omit = >>( + ...keys: Keys +) => +(self: ServiceMap): ServiceMap>> => { + const map = new Map(self.unsafeMap) + for (const key of keys) { + map.delete(key.key) + } + return unsafeMake(map) +} + +/** + * Creates a service map key with a default value. + * + * **Details** + * + * `ServiceMap.Reference` allows you to create a key that can hold a value. You can + * provide a default value for the service, which will automatically be used + * when the context is accessed, or override it with a custom implementation + * when needed. + * + * @since 4.0.0 + * @category References + */ +export const Reference: { + ( + id: Id, + options: { readonly defaultValue: () => Service } + ): ReferenceClass + ( + key: string, + options: { readonly defaultValue: () => Service } + ): Reference +} = Key as any diff --git a/packages/effect/src/Stream.ts b/packages/effect/src/Stream.ts index 43788b672b..cc262c9475 100644 --- a/packages/effect/src/Stream.ts +++ b/packages/effect/src/Stream.ts @@ -4,7 +4,6 @@ import * as Arr from "./Array.js" import * as Cause from "./Cause.js" import * as Channel from "./Channel.js" -import * as Context from "./Context.js" import * as Effect from "./Effect.js" import type * as Exit from "./Exit.js" import * as Fiber from "./Fiber.js" @@ -19,6 +18,7 @@ import type * as PubSub from "./PubSub.js" import * as Pull from "./Pull.js" import * as Queue from "./Queue.js" import * as Scope from "./Scope.js" +import * as ServiceMap from "./ServiceMap.js" import type * as Sink from "./Sink.js" import type { Covariant } from "./Types.js" import type * as Unify from "./Unify.js" @@ -124,7 +124,8 @@ export declare namespace Stream { * @since 3.4.0 * @category type-level */ - export type Context> = [T] extends [Stream] ? _R : never + export type ServiceMap> = [T] extends [Stream] ? _R + : never } const streamVariance = { @@ -1277,21 +1278,21 @@ export const mkString = (self: Stream): Effect.Effect( - context: Context.Context, + services: ServiceMap.ServiceMap, options?: { readonly strategy?: QueuingStrategy | undefined } ) => (self: Stream) => ReadableStream, ( self: Stream, - context: Context.Context, + services: ServiceMap.ServiceMap, options?: { readonly strategy?: QueuingStrategy | undefined } ) => ReadableStream >( (args) => isStream(args[0]), ( self: Stream, - context: Context.Context, + services: ServiceMap.ServiceMap, options?: { readonly strategy?: QueuingStrategy | undefined } ): ReadableStream => { let currentResolve: (() => void) | undefined = undefined @@ -1300,7 +1301,7 @@ export const toReadableStreamContext = dual< return new ReadableStream({ start(controller) { - fiber = Effect.runFork(Effect.provideContext( + fiber = Effect.runFork(Effect.provideServices( runForEachChunk(self, (chunk) => latch.whenOpen(Effect.sync(() => { latch.unsafeClose() @@ -1310,7 +1311,7 @@ export const toReadableStreamContext = dual< currentResolve!() currentResolve = undefined }))), - context + services )) fiber.addObserver((exit) => { if (exit._tag === "Failure") { @@ -1323,7 +1324,7 @@ export const toReadableStreamContext = dual< pull() { return new Promise((resolve) => { currentResolve = resolve - Effect.runSync(latch.open) + latch.unsafeOpen() }) }, cancel() { @@ -1357,7 +1358,7 @@ export const toReadableStream: { ( self: Stream, options?: { readonly strategy?: QueuingStrategy | undefined } - ): ReadableStream => toReadableStreamContext(self, Context.empty(), options) + ): ReadableStream => toReadableStreamWith(self, ServiceMap.empty(), options) ) /** @@ -1385,7 +1386,7 @@ export const toReadableStreamEffect: { options?: { readonly strategy?: QueuingStrategy | undefined } ): Effect.Effect, never, R> => Effect.map( - Effect.context(), - (context) => toReadableStreamContext(self, context, options) + Effect.services(), + (context) => toReadableStreamWith(self, context, options) ) ) diff --git a/packages/effect/src/Tracer.ts b/packages/effect/src/Tracer.ts index fceb7cfa4c..6d36f0f3d4 100644 --- a/packages/effect/src/Tracer.ts +++ b/packages/effect/src/Tracer.ts @@ -1,11 +1,11 @@ /** * @since 2.0.0 */ -import * as Context from "./Context.js" import type * as Exit from "./Exit.js" import type { Fiber } from "./Fiber.js" import { constFalse, type LazyArg } from "./Function.js" import type * as Option from "./Option.js" +import * as ServiceMap from "./ServiceMap.js" /** * @since 2.0.0 @@ -14,7 +14,7 @@ export interface Tracer { readonly span: ( name: string, parent: Option.Option, - context: Context.Context, + context: ServiceMap.ServiceMap, links: ReadonlyArray, startTime: bigint, kind: SpanKind @@ -55,7 +55,7 @@ export const ParentSpanKey = "effect/Tracer/ParentSpan" * @since 2.0.0 * @category tags */ -export class ParentSpan extends Context.Tag()(ParentSpanKey) {} +export class ParentSpan extends ServiceMap.Key()(ParentSpanKey) {} /** * @since 2.0.0 @@ -66,7 +66,7 @@ export interface ExternalSpan { readonly spanId: string readonly traceId: string readonly sampled: boolean - readonly context: Context.Context + readonly context: ServiceMap.ServiceMap } /** @@ -78,7 +78,7 @@ export interface SpanOptions { readonly links?: ReadonlyArray | undefined readonly parent?: AnySpan | undefined readonly root?: boolean | undefined - readonly context?: Context.Context | undefined + readonly context?: ServiceMap.ServiceMap | undefined readonly kind?: SpanKind | undefined readonly captureStackTrace?: boolean | LazyArg | undefined } @@ -99,7 +99,7 @@ export interface Span { readonly spanId: string readonly traceId: string readonly parent: Option.Option - readonly context: Context.Context + readonly context: ServiceMap.ServiceMap readonly status: SpanStatus readonly attributes: ReadonlyMap readonly links: ReadonlyArray @@ -134,21 +134,21 @@ export const externalSpan = ( readonly spanId: string readonly traceId: string readonly sampled?: boolean | undefined - readonly context?: Context.Context | undefined + readonly context?: ServiceMap.ServiceMap | undefined } ): ExternalSpan => ({ _tag: "ExternalSpan", spanId: options.spanId, traceId: options.traceId, sampled: options.sampled ?? true, - context: options.context ?? Context.empty() + context: options.context ?? ServiceMap.empty() }) /** * @since 3.12.0 * @category references */ -export class DisablePropagation extends Context.Reference<"effect/Tracer/DisablePropagation", boolean>( +export class DisablePropagation extends ServiceMap.Reference<"effect/Tracer/DisablePropagation", boolean>( "effect/Tracer/DisablePropagation", { defaultValue: constFalse } ) {} @@ -163,7 +163,7 @@ export const CurrentTracerKey = "effect/Tracer/CurrentTracer" * @since 4.0.0 * @category references */ -export class CurrentTracer extends Context.Reference(CurrentTracerKey, { +export class CurrentTracer extends ServiceMap.Reference(CurrentTracerKey, { defaultValue: () => make({ span: (name, parent, context, links, startTime, kind) => @@ -195,7 +195,7 @@ export class NativeSpan implements Span { constructor( readonly name: string, readonly parent: Option.Option, - readonly context: Context.Context, + readonly context: ServiceMap.ServiceMap, readonly links: ReadonlyArray, readonly startTime: bigint, readonly kind: SpanKind diff --git a/packages/effect/src/index.ts b/packages/effect/src/index.ts index 7d5369c6ab..8ef5b8eccb 100644 --- a/packages/effect/src/index.ts +++ b/packages/effect/src/index.ts @@ -116,17 +116,6 @@ export * as Clock from "./Clock.js" */ export * as Console from "./Console.js" -/** - * This module provides a data structure called `Context` that can be used for dependency injection in effectful - * programs. It is essentially a table mapping `Tag`s to their implementations (called `Service`s), and can be used to - * manage dependencies in a type-safe way. The `Context` data structure is essentially a way of providing access to a set - * of related services that can be passed around as a single unit. This module provides functions to create, modify, and - * query the contents of a `Context`, as well as a number of utility types for working with tags and services. - * - * @since 2.0.0 - */ -export * as Context from "./Context.js" - /** * @since 2.0.0 */ @@ -489,6 +478,17 @@ export * as Scheduler from "./Scheduler.js" */ export * as Scope from "./Scope.js" +/** + * This module provides a data structure called `ServiceMap` that can be used for dependency injection in effectful + * programs. It is essentially a table mapping `Keys`s to their implementations (called `Service`s), and can be used to + * manage dependencies in a type-safe way. The `ServiceMap` data structure is essentially a way of providing access to a set + * of related services that can be passed around as a single unit. This module provides functions to create, modify, and + * query the contents of a `ServiceMap`, as well as a number of utility types for working with keys and services. + * + * @since 4.0.0 + */ +export * as ServiceMap from "./ServiceMap.js" + /** * @since 2.0.0 */ diff --git a/packages/effect/src/internal/context.ts b/packages/effect/src/internal/context.ts deleted file mode 100644 index 69270a52b0..0000000000 --- a/packages/effect/src/internal/context.ts +++ /dev/null @@ -1,337 +0,0 @@ -import type * as C from "../Context.js" -import * as Equal from "../Equal.js" -import type { LazyArg } from "../Function.js" -import { dual } from "../Function.js" -import * as Hash from "../Hash.js" -import { toJSON } from "../Inspectable.js" -import type * as O from "../Option.js" -import { hasProperty } from "../Predicate.js" -import { exitSucceed, PipeInspectableProto, withFiber, YieldableProto } from "./core.js" -import * as option from "./option.js" - -/** @internal */ -export const TagTypeId: C.TagTypeId = Symbol.for( - "effect/Context/Tag" -) as C.TagTypeId - -/** @internal */ -export const ReferenceTypeId: C.ReferenceTypeId = Symbol.for( - "effect/Context/Reference" -) as C.ReferenceTypeId - -/** @internal */ -export const TagProto: any = { - _op: "Tag", - [TagTypeId]: { - _Service: (_: unknown) => _, - _Identifier: (_: unknown) => _ - }, - ...PipeInspectableProto, - ...YieldableProto, - toJSON(this: C.Tag) { - return { - _id: "Tag", - key: this.key, - stack: this.stack - } - }, - asEffect() { - return withFiber((fiber) => exitSucceed(unsafeGet(fiber.context, this))) - }, - of(self: Service): Service { - return self - }, - context( - this: C.Tag, - self: Service - ): C.Context { - return make(this, self) - } -} - -export const ReferenceProto: any = { - ...TagProto, - [ReferenceTypeId]: ReferenceTypeId, - asEffect() { - return withFiber((fiber) => exitSucceed(unsafeGetReference(fiber.context, this))) - } -} - -/** @internal */ -export const makeGenericTag = ( - key: string -): C.Tag => { - const limit = Error.stackTraceLimit - Error.stackTraceLimit = 2 - const creationError = new Error() - Error.stackTraceLimit = limit - function TagClass() {} - Object.setPrototypeOf(TagClass, TagProto) - TagClass.key = key - Object.defineProperty(TagClass, "stack", { - get() { - return creationError.stack - } - }) - return TagClass as any -} - -/** @internal */ -export const Tag = (): (id: Id) => C.TagClass => - makeGenericTag as any - -/** @internal */ -export const GenericReference = ( - key: string, - options: { - readonly defaultValue: () => Service - } -): C.Reference => { - const limit = Error.stackTraceLimit - Error.stackTraceLimit = 2 - const creationError = new Error() - Error.stackTraceLimit = limit - - function ReferenceClass() {} - Object.setPrototypeOf(ReferenceClass, ReferenceProto) - ReferenceClass.key = key - ReferenceClass.defaultValue = options.defaultValue - Object.defineProperty(ReferenceClass, "stack", { - get() { - return creationError.stack - } - }) - return ReferenceClass as any -} - -/** @internal */ -export const Reference: ( - id: Id, - options: { - readonly defaultValue: () => Service - } -) => C.ReferenceClass = GenericReference as any - -/** @internal */ -export const TypeId: C.TypeId = Symbol.for("effect/Context") as C.TypeId - -/** @internal */ -export const ContextProto: Omit, "unsafeMap"> = { - [TypeId]: { - _Services: (_: unknown) => _ - }, - [Equal.symbol](this: C.Context, that: unknown): boolean { - if (isContext(that)) { - if (this.unsafeMap.size === that.unsafeMap.size) { - for (const k of this.unsafeMap.keys()) { - if ( - !that.unsafeMap.has(k) || - !Equal.equals(this.unsafeMap.get(k), that.unsafeMap.get(k)) - ) { - return false - } - } - return true - } - } - return false - }, - [Hash.symbol](this: C.Context): number { - return Hash.cached(this, () => Hash.number(this.unsafeMap.size)) - }, - ...PipeInspectableProto, - toJSON(this: C.Context) { - return { - _id: "Context", - services: Array.from(this.unsafeMap).map(toJSON) - } - } -} - -/** @internal */ -export const makeContext = ( - unsafeMap: Map -): C.Context => { - const context = Object.create(ContextProto) - context.unsafeMap = unsafeMap - return context -} - -const serviceNotFoundError = (tag: C.Tag) => { - const error = new Error( - `Service not found${tag.key ? `: ${String(tag.key)}` : ""}` - ) - if (tag.stack) { - const lines = tag.stack.split("\n") - if (lines.length > 2) { - const afterAt = lines[2].match(/at (.*)/) - if (afterAt) { - error.message = error.message + ` (defined at ${afterAt[1]})` - } - } - } - if (error.stack) { - const lines = error.stack.split("\n") - lines.splice(1, 3) - error.stack = lines.join("\n") - } - return error -} - -/** @internal */ -export const isContext = (u: unknown): u is C.Context => hasProperty(u, TypeId) - -/** @internal */ -export const isTag = (u: unknown): u is C.Tag => hasProperty(u, TagTypeId) - -/** @internal */ -export const isReference = (u: unknown): u is C.Reference => hasProperty(u, ReferenceTypeId) - -const _empty = makeContext(new Map()) - -/** @internal */ -export const empty = (): C.Context => _empty - -/** @internal */ -export const make = ( - tag: T, - service: C.Tag.Service -): C.Context> => makeContext(new Map([[tag.key, service]])) - -/** @internal */ -export const add = dual< - ( - tag: T, - service: C.Tag.Service - ) => ( - self: C.Context - ) => C.Context>, - ( - self: C.Context, - tag: T, - service: C.Tag.Service - ) => C.Context> ->(3, (self, tag, service) => { - const map = new Map(self.unsafeMap) - map.set(tag.key, service) - return makeContext(map) -}) - -const defaultValueCache = new Map() - -const getDefaultValue = (tag: C.Reference) => { - if (defaultValueCache.has(tag.key)) { - return defaultValueCache.get(tag.key) - } - const value = tag.defaultValue() - defaultValueCache.set(tag.key, value) - return value -} - -/** @internal */ -export const unsafeGetReference = ( - self: C.Context, - tag: C.Reference -): S => { - return self.unsafeMap.has(tag.key) - ? self.unsafeMap.get(tag.key) - : getDefaultValue(tag) -} - -/** @internal */ -export const unsafeGet = dual< - (tag: C.Tag) => (self: C.Context) => S, - (self: C.Context, tag: C.Tag) => S ->(2, (self, tag) => { - if (!self.unsafeMap.has(tag.key)) { - if (ReferenceTypeId in tag) return getDefaultValue(tag as any) - throw serviceNotFoundError(tag) - } - return self.unsafeMap.get(tag.key)! as any -}) - -/** @internal */ -export const get: { - ( - tag: C.Tag - ): (self: C.Context) => S - ( - self: C.Context, - tag: C.Tag - ): S -} = unsafeGet as any - -/** @internal */ -export const getOrElse = dual< - ( - tag: C.Tag, - orElse: LazyArg - ) => (self: C.Context) => S | B, - ( - self: C.Context, - tag: C.Tag, - orElse: LazyArg - ) => S | B ->(3, (self, tag, orElse) => { - if (!self.unsafeMap.has(tag.key)) { - return isReference(tag) ? getDefaultValue(tag) : orElse() - } - return self.unsafeMap.get(tag.key)! as any -}) - -/** @internal */ -export const getOption = dual< - ( - tag: C.Tag - ) => (self: C.Context) => O.Option, - (self: C.Context, tag: C.Tag) => O.Option ->(2, (self, tag) => { - if (!self.unsafeMap.has(tag.key)) { - return isReference(tag) ? option.some(getDefaultValue(tag)) : option.none - } - return option.some(self.unsafeMap.get(tag.key)! as any) -}) - -/** @internal */ -export const merge = dual< - ( - that: C.Context - ) => (self: C.Context) => C.Context, - ( - self: C.Context, - that: C.Context - ) => C.Context ->(2, (self, that) => { - const map = new Map(self.unsafeMap) - for (const [tag, s] of that.unsafeMap) { - map.set(tag, s) - } - return makeContext(map) -}) - -/** @internal */ -export const pick = >>(...tags: Tags) => -( - self: C.Context -): C.Context> => { - const tagSet = new Set(tags.map((_) => _.key)) - const newEnv = new Map() - for (const [tag, s] of self.unsafeMap.entries()) { - if (tagSet.has(tag)) { - newEnv.set(tag, s) - } - } - return makeContext(newEnv) -} - -/** @internal */ -export const omit = >>(...tags: Tags) => -( - self: C.Context -): C.Context>> => { - const newEnv = new Map(self.unsafeMap) - for (const tag of tags) { - newEnv.delete(tag.key) - } - return makeContext(newEnv) -} diff --git a/packages/effect/src/internal/core.ts b/packages/effect/src/internal/core.ts index 5338e28daa..f11abfa851 100644 --- a/packages/effect/src/internal/core.ts +++ b/packages/effect/src/internal/core.ts @@ -1,5 +1,4 @@ import type * as Cause from "../Cause.js" -import type * as Context from "../Context.js" import type * as Effect from "../Effect.js" import * as Equal from "../Equal.js" import type * as Exit from "../Exit.js" @@ -8,6 +7,7 @@ import * as Hash from "../Hash.js" import { format, NodeInspectSymbol } from "../Inspectable.js" import { pipeArguments } from "../Pipeable.js" import { hasProperty, isObject } from "../Predicate.js" +import type * as ServiceMap from "../ServiceMap.js" import type { Equals } from "../Types.js" import { SingleShotGen, YieldWrap } from "../Utils.js" import type { FiberImpl } from "./effect.js" @@ -205,7 +205,7 @@ export abstract class FailureBase implements Cause.Cause.Fai this.annotations = annotations } - abstract annotate(this: any, tag: Context.Tag, value: S): this + abstract annotate(this: any, tag: ServiceMap.Key, value: S): this pipe() { return pipeArguments(this, arguments) @@ -237,7 +237,7 @@ class Fail extends FailureBase<"Fail"> implements Cause.Fail { error: this.error } } - annotate(tag: Context.Tag, value: S): this { + annotate(tag: ServiceMap.Key, value: S): this { return new Fail( this.error, new Map([...this.annotations, [tag.key, value]]) @@ -279,7 +279,7 @@ class Die extends FailureBase<"Die"> implements Cause.Die { defect: this.defect } } - annotate(tag: Context.Tag, value: S): this { + annotate(tag: ServiceMap.Key, value: S): this { return new Die( this.defect, new Map([...this.annotations, [tag.key, value]]) diff --git a/packages/effect/src/internal/effect.ts b/packages/effect/src/internal/effect.ts index 26250deabf..3d27391d9d 100644 --- a/packages/effect/src/internal/effect.ts +++ b/packages/effect/src/internal/effect.ts @@ -2,7 +2,6 @@ import * as Arr from "../Array.js" import type * as Cause from "../Cause.js" import type * as Clock from "../Clock.js" import type * as Console from "../Console.js" -import * as Context from "../Context.js" import * as Duration from "../Duration.js" import type * as Effect from "../Effect.js" import * as Equal from "../Equal.js" @@ -34,11 +33,11 @@ import { import * as Result from "../Result.js" import * as Scheduler from "../Scheduler.js" import type * as Scope from "../Scope.js" +import * as ServiceMap from "../ServiceMap.js" import * as Tracer from "../Tracer.js" import type { Concurrency, ExcludeTag, ExtractTag, NoInfer, NotFunction, Simplify, Tags } from "../Types.js" import type { YieldWrap } from "../Utils.js" import { yieldWrapGet } from "../Utils.js" -import * as InternalContext from "./context.js" import type { Primitive } from "./core.js" import { args, @@ -86,10 +85,10 @@ class Interrupt extends FailureBase<"Interrupt"> implements Cause.Interrupt { fiberId: this.fiberId } } - annotate(tag: Context.Tag, value: S): this { + annotate(key: ServiceMap.Key, value: S): this { return new Interrupt( this.fiberId, - new Map([...this.annotations, [tag.key, value]]) + new Map([...this.annotations, [key.key, value]]) ) as this } [Equal.symbol](that: any): boolean { @@ -202,21 +201,21 @@ export const causeSquash = (self: Cause.Cause): unknown => { /** @internal */ export const causeAnnotate: { ( - tag: Context.Tag, + key: ServiceMap.Key, value: S ): (self: Cause.Cause) => Cause.Cause ( self: Cause.Cause, - tag: Context.Tag, + key: ServiceMap.Key, value: S ): Cause.Cause } = dual( 3, ( self: Cause.Cause, - tag: Context.Tag, + key: ServiceMap.Key, value: S - ): Cause.Cause => new CauseImpl(self.failures.map((f) => f.annotate(tag, value))) + ): Cause.Cause => new CauseImpl(self.failures.map((f) => f.annotate(key, value))) ) // ---------------------------------------------------------------------------- @@ -266,11 +265,11 @@ const keepAlive = (() => { export interface FiberImpl extends Fiber.Fiber { id: number currentOpCount: number - readonly context: Context.Context + readonly services: ServiceMap.ServiceMap readonly currentScheduler: Scheduler.Scheduler readonly currentTracerContext?: Tracer.Tracer["context"] readonly currentSpan?: Tracer.AnySpan | undefined - readonly runtimeMetrics?: Context.Tag.Service | undefined + readonly runtimeMetrics?: Metric.FiberRuntimeMetrics["Service"] | undefined readonly maxOpsBeforeYield: number interruptible: boolean readonly _stack: Array @@ -281,7 +280,7 @@ export interface FiberImpl extends Fiber.Fiber | (() => void) | undefined evaluate(effect: Primitive): void runLoop(this: FiberImpl, effect: Primitive): Exit.Exit | Yield - getRef(this: Fiber.Fiber, ref: Context.Reference): X + getRef(this: Fiber.Fiber, ref: ServiceMap.Reference): X addObserver(this: FiberImpl, cb: (exit: Exit.Exit) => void): () => void unsafeInterrupt(this: FiberImpl, fiberId?: number | undefined): void unsafePoll(this: FiberImpl): Exit.Exit | undefined @@ -290,13 +289,13 @@ export interface FiberImpl extends Fiber.Fiber(this: FiberImpl, value: Exit.Exit | (() => void)): Yield children(this: FiberImpl): Set> - setContext(this: FiberImpl, context: Context.Context): void + setServices(this: FiberImpl, services: ServiceMap.ServiceMap): void } const FiberProto = { [FiberTypeId]: fiberVariance, - getRef(this: Fiber.Fiber, ref: Context.Reference): X { - return InternalContext.unsafeGetReference(this.context, ref) + getRef(this: Fiber.Fiber, ref: ServiceMap.Reference): X { + return ServiceMap.unsafeGetReference(this.services, ref) }, addObserver(this: FiberImpl, cb: (exit: Exit.Exit) => void): () => void { if (this._exit) { @@ -327,7 +326,7 @@ const FiberProto = { return this._exit }, evaluate(this: FiberImpl, effect: Primitive): void { - this.runtimeMetrics?.recordFiberStart(this.context) + this.runtimeMetrics?.recordFiberStart(this.services) if (this._exit) { return } else if (this._yielded !== undefined) { @@ -348,7 +347,7 @@ const FiberProto = { } this._exit = exit - this.runtimeMetrics?.recordFiberEnd(this.context, this._exit) + this.runtimeMetrics?.recordFiberEnd(this.services, this._exit) keepAlive.decrement() for (let i = 0; i < this._observers.length; i++) { this._observers[i](exit) @@ -415,20 +414,23 @@ const FiberProto = { pipe(this: FiberImpl) { return pipeArguments(this, arguments) }, - setContext(this: any, context: Context.Context): void { - this.context = context + setServices(this: any, services: ServiceMap.ServiceMap): void { + this.services = services this.currentScheduler = this.getRef(CurrentScheduler) - this.currentSpan = context.unsafeMap.get(Tracer.ParentSpanKey) + this.currentSpan = services.unsafeMap.get(Tracer.ParentSpanKey) this.maxOpsBeforeYield = this.getRef(Scheduler.MaxOpsBeforeYield) - this.runtimeMetrics = context.unsafeMap.get(InternalMetric.FiberRuntimeMetricsKey) - const currentTracer = context.unsafeMap.get(Tracer.CurrentTracerKey) + this.runtimeMetrics = services.unsafeMap.get(InternalMetric.FiberRuntimeMetricsKey) + const currentTracer = services.unsafeMap.get(Tracer.CurrentTracerKey) this.currentTracerContext = currentTracer ? currentTracer["context"] : undefined } } -export const makeFiber = (context: Context.Context, interruptible: boolean = true): FiberImpl => { +export const makeFiber = ( + services: ServiceMap.ServiceMap, + interruptible: boolean = true +): FiberImpl => { const fiber = Object.create(FiberProto) - fiber.setContext(context) + fiber.setServices(services) fiber.id = ++fiberIdStore.id fiber.currentOpCount = 0 fiber.interruptible = interruptible @@ -925,7 +927,7 @@ export const raceAll = >( ): Effect.Effect< Effect.Effect.Success, Effect.Effect.Error, - Effect.Effect.Context + Effect.Effect.Services > => withFiber((parent) => callback((resume) => { @@ -984,7 +986,7 @@ export const raceAllFirst = >( ): Effect.Effect< Effect.Effect.Success, Effect.Effect.Error, - Effect.Effect.Context + Effect.Effect.Services > => withFiber((parent) => callback((resume) => { @@ -1278,44 +1280,44 @@ export const exitAsVoidAll = >>( /** @internal */ export const service: { - (tag: Context.Tag): Effect.Effect + (key: ServiceMap.Key): Effect.Effect } = fromYieldable as any /** @internal */ export const serviceOption = ( - tag: Context.Tag -): Effect.Effect> => withFiber((fiber) => succeed(InternalContext.getOption(fiber.context, tag))) + key: ServiceMap.Key +): Effect.Effect> => withFiber((fiber) => succeed(ServiceMap.getOption(fiber.services, key))) /** @internal */ export const serviceOptional = ( - tag: Context.Tag + key: ServiceMap.Key ): Effect.Effect => withFiber((fiber) => - fiber.context.unsafeMap.has(tag.key) - ? succeed(InternalContext.unsafeGet(fiber.context, tag)) + fiber.services.unsafeMap.has(key.key) + ? succeed(ServiceMap.unsafeGet(fiber.services, key)) : fail(new NoSuchElementError()) ) /** @internal */ -export const updateContext: { +export const updateServices: { ( - f: (context: Context.Context) => Context.Context> + f: (services: ServiceMap.ServiceMap) => ServiceMap.ServiceMap> ): (self: Effect.Effect) => Effect.Effect ( self: Effect.Effect, - f: (context: Context.Context) => Context.Context> + f: (services: ServiceMap.ServiceMap) => ServiceMap.ServiceMap> ): Effect.Effect } = dual( 2, ( self: Effect.Effect, - f: (context: Context.Context) => Context.Context> + f: (services: ServiceMap.ServiceMap) => ServiceMap.ServiceMap> ): Effect.Effect => withFiber((fiber) => { - const prev = fiber.context as Context.Context - fiber.setContext(f(prev)) + const prev = fiber.services as ServiceMap.ServiceMap + fiber.setServices(f(prev)) return onExit(self as any, () => { - fiber.setContext(prev) + fiber.setServices(prev) return void_ }) }) @@ -1324,106 +1326,106 @@ export const updateContext: { /** @internal */ export const updateService: { ( - tag: Context.Tag, + key: ServiceMap.Key, f: (value: A) => A ): (self: Effect.Effect) => Effect.Effect ( self: Effect.Effect, - tag: Context.Tag, + key: ServiceMap.Key, f: (value: A) => A ): Effect.Effect } = dual( 3, ( self: Effect.Effect, - tag: Context.Tag, + key: ServiceMap.Key, f: (value: A) => A ): Effect.Effect => withFiber((fiber) => { - const prev = InternalContext.unsafeGet(fiber.context, tag) - fiber.setContext(InternalContext.add(fiber.context, tag, f(prev))) + const prev = ServiceMap.unsafeGet(fiber.services, key) + fiber.setServices(ServiceMap.add(fiber.services, key, f(prev))) return onExit(self, () => { - fiber.setContext(InternalContext.add(fiber.context, tag, prev)) + fiber.setServices(ServiceMap.add(fiber.services, key, prev)) return void_ }) }) ) /** @internal */ -export const context = (): Effect.Effect> => getContext as any -const getContext = withFiber((fiber) => succeed(fiber.context)) +export const services = (): Effect.Effect> => getServiceMap as any +const getServiceMap = withFiber((fiber) => succeed(fiber.services)) /** @internal */ -export const contextWith = ( - f: (context: Context.Context) => Effect.Effect -): Effect.Effect => withFiber((fiber) => f(fiber.context as Context.Context)) +export const servicesWith = ( + f: (services: ServiceMap.ServiceMap) => Effect.Effect +): Effect.Effect => withFiber((fiber) => f(fiber.services as ServiceMap.ServiceMap)) /** @internal */ -export const provideContext: { +export const provideServices: { ( - context: Context.Context + services: ServiceMap.ServiceMap ): ( self: Effect.Effect ) => Effect.Effect> ( self: Effect.Effect, - context: Context.Context + services: ServiceMap.ServiceMap ): Effect.Effect> } = dual( 2, ( self: Effect.Effect, - provided: Context.Context - ): Effect.Effect> => updateContext(self, InternalContext.merge(provided)) as any + services: ServiceMap.ServiceMap + ): Effect.Effect> => updateServices(self, ServiceMap.merge(services)) as any ) /** @internal */ export const provideService: { ( - tag: Context.Tag + key: ServiceMap.Key ): { (service: S): (self: Effect.Effect) => Effect.Effect> (self: Effect.Effect, service: S): Effect.Effect> } ( - tag: Context.Tag, + key: ServiceMap.Key, service: S ): ( self: Effect.Effect ) => Effect.Effect> ( self: Effect.Effect, - tag: Context.Tag, + key: ServiceMap.Key, service: S ): Effect.Effect> } = function(this: any) { if (arguments.length === 1) { - return dual(2, (self, service) => updateContext(self, InternalContext.add(arguments[0], service))) as any + return dual(2, (self, service) => updateServices(self, ServiceMap.add(arguments[0], service))) as any } - return dual(3, (self, tag, service) => updateContext(self, InternalContext.add(tag, service))) + return dual(3, (self, tag, service) => updateServices(self, ServiceMap.add(tag, service))) .apply(this, arguments as any) as any } /** @internal */ export const provideServiceEffect: { ( - tag: Context.Tag, + key: ServiceMap.Key, acquire: Effect.Effect ): ( self: Effect.Effect ) => Effect.Effect | R2> ( self: Effect.Effect, - tag: Context.Tag, + key: ServiceMap.Key, acquire: Effect.Effect ): Effect.Effect | R2> } = dual( 3, ( self: Effect.Effect, - tag: Context.Tag, + key: ServiceMap.Key, acquire: Effect.Effect - ): Effect.Effect | R2> => flatMap(acquire, (service) => provideService(self, tag, service)) + ): Effect.Effect | R2> => flatMap(acquire, (service) => provideService(self, key, service)) ) /** @internal */ @@ -2242,7 +2244,7 @@ export const timeoutOrElse: { { onWinner: ({ fiber, index, parentFiber }) => { if (index !== 0) return - ;(parentFiber as FiberImpl).setContext(fiber.context) + ;(parentFiber as FiberImpl).setServices(fiber.services) } } ) @@ -2305,9 +2307,7 @@ export const CloseableScopeTypeId: Scope.CloseableScopeTypeId = Symbol.for( ) as Scope.CloseableScopeTypeId /** @internal */ -export const scopeTag: Context.Tag = InternalContext.Tag()( - "effect/Scope" -) +export const scopeTag: ServiceMap.Key = ServiceMap.Key("effect/Scope") const ScopeProto = { [ScopeTypeId]: ScopeTypeId, @@ -2440,8 +2440,8 @@ export const addFinalizer = ( flatMap( scope, (scope) => - contextWith((context: Context.Context) => - scopeAddFinalizer(scope, (exit) => provideContext(finalizer(exit), context)) + servicesWith((services: ServiceMap.ServiceMap) => + scopeAddFinalizer(scope, (exit) => provideServices(finalizer(exit), services)) ) ) @@ -2571,7 +2571,7 @@ export const cachedInvalidateWithTTL: { ttl: Duration.DurationInput ): Effect.Effect<[Effect.Effect, Effect.Effect], never, R> => withFiber((fiber) => { - const context = fiber.context as Context.Context + const services = fiber.services as ServiceMap.ServiceMap const ttlMillis = Duration.toMillis(ttl) const latch = unsafeMakeLatch(false) let expiresAt = 0 @@ -2585,7 +2585,7 @@ export const cachedInvalidateWithTTL: { running = true latch.unsafeClose() exit = undefined - return onExit(provideContext(self, context), (exit_) => { + return onExit(provideServices(self, services), (exit_) => { running = false expiresAt = now + ttlMillis exit = exit_ @@ -3047,7 +3047,7 @@ const unsafeFork = ( immediate = false, daemon = false ): Fiber.Fiber => { - const child = makeFiber(parent.context, parent.interruptible) + const child = makeFiber(parent.services, parent.interruptible) if (immediate) { child.evaluate(effect as any) } else { @@ -3166,7 +3166,7 @@ export const runFork = ( } | undefined ): FiberImpl => { - const fiber = makeFiber(CurrentScheduler.context(options?.scheduler ?? new Scheduler.MixedScheduler())) + const fiber = makeFiber(CurrentScheduler.serviceMap(options?.scheduler ?? new Scheduler.MixedScheduler())) fiber.evaluate(effect as any) if (options?.signal) { if (options.signal.aborted) { @@ -3382,9 +3382,11 @@ export const tracer: Effect.Effect = withFiber((fiber) => succeed export const withTracer: { (tracer: Tracer.Tracer): (effect: Effect.Effect) => Effect.Effect (effect: Effect.Effect, tracer: Tracer.Tracer): Effect.Effect -} = dual(2, (effect: Effect.Effect, tracer: Tracer.Tracer): Effect.Effect => { - return provideService(effect, Tracer.CurrentTracer, tracer) -}) +} = dual( + 2, + (effect: Effect.Effect, tracer: Tracer.Tracer): Effect.Effect => + provideService(effect, Tracer.CurrentTracer, tracer) +) /** @internal */ export const withTracerEnabled: { @@ -3417,12 +3419,12 @@ const NoopSpanProto: Omit = { export const noopSpan = (options: { readonly name: string readonly parent: Option.Option - readonly context: Context.Context + readonly context: ServiceMap.ServiceMap }): Tracer.Span => Object.assign(Object.create(NoopSpanProto), options) const filterDisablePropagation: (self: Option.Option) => Option.Option = Option.flatMap( (span) => - InternalContext.get(span.context, Tracer.DisablePropagation) + ServiceMap.get(span.context, Tracer.DisablePropagation) ? span._tag === "Span" ? filterDisablePropagation(span.parent) : Option.none() : Option.some(span) ) @@ -3437,7 +3439,7 @@ export const unsafeMakeSpan = ( options: Tracer.SpanOptions ) => { const disablePropagation = !fiber.getRef(TracerEnabled) || - (options.context && InternalContext.get(options.context, Tracer.DisablePropagation)) + (options.context && ServiceMap.get(options.context, Tracer.DisablePropagation)) const parent = options.parent ? Option.some(options.parent) : options.root @@ -3450,8 +3452,8 @@ export const unsafeMakeSpan = ( span = noopSpan({ name, parent, - context: InternalContext.add( - options.context ?? InternalContext.empty(), + context: ServiceMap.add( + options.context ?? ServiceMap.empty(), Tracer.DisablePropagation, true ) @@ -3469,7 +3471,7 @@ export const unsafeMakeSpan = ( span = tracer.span( name, parent, - options.context ?? InternalContext.empty(), + options.context ?? ServiceMap.empty(), links, clock.unsafeCurrentTimeNanos(), options.kind ?? "internal" @@ -3509,7 +3511,7 @@ export const makeSpanScoped = ( options = addSpanStackTrace(options) return uninterruptible( withFiber((fiber) => { - const scope = InternalContext.unsafeGet(fiber.context, scopeTag) + const scope = ServiceMap.unsafeGet(fiber.services, scopeTag) const span = unsafeMakeSpan(fiber, name, options) const clock = fiber.getRef(CurrentClock) return as( @@ -3693,7 +3695,7 @@ export const currentParentSpan: Effect.Effect("effect/Clock/CurrentClock", { +export const CurrentClock = ServiceMap.Reference("effect/Clock/CurrentClock", { defaultValue: (): Clock.Clock => new ClockImpl() }) @@ -3833,7 +3835,7 @@ export class UnknownError extends TaggedError("UnknownError") { // ---------------------------------------------------------------------------- /** @internal */ -export const CurrentConsole = InternalContext.GenericReference( +export const CurrentConsole = ServiceMap.Reference( "effect/Console/CurrentConsole", { defaultValue: (): Console.Console => globalThis.console } ) @@ -3874,10 +3876,10 @@ export const logLevelGreaterThan = Order.greaterThan(LogLevelOrder) // ---------------------------------------------------------------------------- /** @internal */ -export const CurrentLoggers = Context.GenericReference< +export const CurrentLoggers = ServiceMap.Reference< ReadonlySet> >("effect/Loggers/CurrentLoggers", { - defaultValue: (): ReadonlySet> => new Set([defaultLogger]) + defaultValue: () => new Set([defaultLogger]) }) /** @internal */ @@ -3934,7 +3936,7 @@ export const structuredMessage = (u: unknown): unknown => { } } -const getSpan = Context.getOrElse(Tracer.ParentSpan, constUndefined) +const getSpan = ServiceMap.getOrElse(Tracer.ParentSpan, constUndefined) /** @internal */ export const logWithLevel = (level?: LogLevel.LogLevel) => @@ -3977,7 +3979,7 @@ export const logWithLevel = (level?: LogLevel.LogLevel) => }) } } - const span = getSpan(fiber.context) + const span = getSpan(fiber.services) if (span && span._tag === "Span") { span.event( toStringUnknown(Array.isArray(message) ? message[0] : message), diff --git a/packages/effect/src/internal/layer.ts b/packages/effect/src/internal/layer.ts index 0236f5a43b..cad57bfe5e 100644 --- a/packages/effect/src/internal/layer.ts +++ b/packages/effect/src/internal/layer.ts @@ -1,7 +1,7 @@ -import * as Context from "../Context.js" import type { Effect } from "../Effect.js" import { dual } from "../Function.js" import * as Layer from "../Layer.js" +import * as ServiceMap from "../ServiceMap.js" import * as effect from "./effect.js" const provideLayer = ( @@ -11,7 +11,7 @@ const provideLayer = ( effect.scopedWith((scope) => effect.flatMap( Layer.buildWithScope(layer, scope), - (context) => effect.provideContext(self, context) + (context) => effect.provideServices(self, context) ) ) @@ -25,13 +25,13 @@ export const provide = dual< ) => Effect< A, E | Layer.Layer.Error, - | Layer.Layer.Context + | Layer.Layer.Services | Exclude> > ( layer: Layer.Layer ): (self: Effect) => Effect> - (context: Context.Context): (self: Effect) => Effect> + (services: ServiceMap.ServiceMap): (self: Effect) => Effect> }, { ]>( @@ -40,7 +40,7 @@ export const provide = dual< ): Effect< A, E | Layer.Layer.Error, - | Layer.Layer.Context + | Layer.Layer.Services | Exclude> > ( @@ -49,7 +49,7 @@ export const provide = dual< ): Effect> ( self: Effect, - context: Context.Context + services: ServiceMap.ServiceMap ): Effect> } >( @@ -58,10 +58,10 @@ export const provide = dual< self: Effect, source: | Layer.Layer - | Context.Context + | ServiceMap.ServiceMap | Array ): Effect> => - Context.isContext(source) - ? effect.provideContext(self, source) + ServiceMap.isServiceMap(source) + ? effect.provideServices(self, source) : provideLayer(self, Array.isArray(source) ? Layer.mergeAll(...source as any) : source) ) diff --git a/packages/effect/src/internal/rcRef.ts b/packages/effect/src/internal/rcRef.ts index 440dc37e34..ddf7554056 100644 --- a/packages/effect/src/internal/rcRef.ts +++ b/packages/effect/src/internal/rcRef.ts @@ -1,4 +1,3 @@ -import * as Context from "../Context.js" import * as Duration from "../Duration.js" import * as Effect from "../Effect.js" import * as Exit from "../Exit.js" @@ -6,6 +5,7 @@ import * as Fiber from "../Fiber.js" import { identity } from "../Function.js" import type * as RcRef from "../RcRef.js" import * as Scope from "../Scope.js" +import * as ServiceMap from "../ServiceMap.js" /** @internal */ export const TypeId: RcRef.TypeId = Symbol.for("effect/RcRef") as RcRef.TypeId @@ -46,7 +46,7 @@ class RcRefImpl implements RcRef.RcRef { constructor( readonly acquire: Effect.Effect, - readonly context: Context.Context, + readonly services: ServiceMap.ServiceMap, readonly scope: Scope.Scope, readonly idleTimeToLive: Duration.Duration | undefined ) {} @@ -58,11 +58,11 @@ export const make = (options: { readonly idleTimeToLive?: Duration.DurationInput | undefined }) => Effect.withFiber, never, R | Scope.Scope>((fiber) => { - const context = fiber.context as Context.Context - const scope = Context.get(context, Scope.Scope) + const services = fiber.services as ServiceMap.ServiceMap + const scope = ServiceMap.get(services, Scope.Scope) const ref = new RcRefImpl( options.acquire as Effect.Effect, - context, + services, scope, options.idleTimeToLive ? Duration.decode(options.idleTimeToLive) : undefined ) @@ -94,9 +94,9 @@ const getState = (self: RcRefImpl) => } case "Empty": { const scope = Scope.unsafeMake() - return restore(Effect.provideContext( + return restore(Effect.provideServices( self.acquire as Effect.Effect, - Context.add(self.context, Scope.Scope, scope) + ServiceMap.add(self.services, Scope.Scope, scope) )).pipe(Effect.map((value) => { const state: State.Acquired = { _tag: "Acquired", diff --git a/packages/effect/src/internal/request.ts b/packages/effect/src/internal/request.ts index 3f638e8d2d..30100acf82 100644 --- a/packages/effect/src/internal/request.ts +++ b/packages/effect/src/internal/request.ts @@ -15,7 +15,7 @@ export const request: { ): (self: A) => Effect< Request.Success, Request.Error | EX, - Request.Context | RX + Request.Services | RX > , EX = never, RX = never>( self: A, @@ -23,7 +23,7 @@ export const request: { ): Effect< Request.Success, Request.Error | EX, - Request.Context | RX + Request.Services | RX > } = dual( 2, @@ -33,13 +33,13 @@ export const request: { ): Effect< Request.Success, Request.Error | EX, - Request.Context | RX + Request.Services | RX > => { const withResolver = (resolver: RequestResolver) => effect.callback< Request.Success, Request.Error, - Request.Context + Request.Services >((resume) => { const entry = addEntry(resolver, self, resume, effect.getCurrentFiberOrUndefined()!) return maybeRemoveEntry(resolver, entry) @@ -87,7 +87,7 @@ const addEntry = >( const entry = makeEntry({ request, - context: fiber.context as any, + services: fiber.services as any, unsafeComplete(effect) { resume(effect) batch.entrySet.delete(entry) diff --git a/packages/effect/src/schema/Schema.ts b/packages/effect/src/schema/Schema.ts index 0d8e7e1297..9ce3fd38f0 100644 --- a/packages/effect/src/schema/Schema.ts +++ b/packages/effect/src/schema/Schema.ts @@ -89,8 +89,8 @@ export interface Bottom< readonly "Type": T readonly "Encoded": E - readonly "DecodingContext": RD - readonly "EncodingContext": RE + readonly "DecodingServices": RD + readonly "EncodingServices": RE readonly "~type.make.in": TypeMakeIn readonly "~type.make": TypeMake @@ -123,8 +123,8 @@ export function revealBottom( ): Bottom< S["Type"], S["Encoded"], - S["DecodingContext"], - S["EncodingContext"], + S["DecodingServices"], + S["EncodingServices"], S["ast"], S["~rebuild.out"], S["~annotate.in"], @@ -197,8 +197,8 @@ export abstract class Bottom$< declare readonly "Type": T declare readonly "Encoded": E - declare readonly "DecodingContext": RD - declare readonly "EncodingContext": RE + declare readonly "DecodingServices": RD + declare readonly "EncodingServices": RE declare readonly "~rebuild.out": RebuildOut declare readonly "~annotate.in": AnnotateIn @@ -287,15 +287,15 @@ export declare namespace Codec { /** * @since 4.0.0 */ - export type DecodingContext = S["DecodingContext"] + export type DecodingServices = S["DecodingServices"] /** * @since 4.0.0 */ - export type EncodingContext = S["EncodingContext"] + export type EncodingServices = S["EncodingServices"] /** * @since 4.0.0 */ - export type ToAsserts = ( + export type ToAsserts = ( input: I ) => asserts input is I & S["Type"] } @@ -306,8 +306,8 @@ export declare namespace Codec { */ export interface Codec extends Schema { readonly "Encoded": E - readonly "DecodingContext": RD - readonly "EncodingContext": RE + readonly "DecodingServices": RD + readonly "EncodingServices": RE readonly "~rebuild.out": Codec } @@ -555,8 +555,8 @@ export const encodeSync = ToParser.encodeSync class make$ extends Bottom$< S["Type"], S["Encoded"], - S["DecodingContext"], - S["EncodingContext"], + S["DecodingServices"], + S["EncodingServices"], S["ast"], S["~rebuild.out"], S["~annotate.in"], @@ -589,8 +589,8 @@ class makeWithSchema$ extends make$ { export function make(ast: S["ast"]): Bottom< S["Type"], S["Encoded"], - S["DecodingContext"], - S["EncodingContext"], + S["DecodingServices"], + S["EncodingServices"], S["ast"], S["~rebuild.out"], S["~annotate.in"], @@ -624,8 +624,8 @@ export interface optionalKey extends Bottom< S["Type"], S["Encoded"], - S["DecodingContext"], - S["EncodingContext"], + S["DecodingServices"], + S["EncodingServices"], S["ast"], optionalKey, S["~annotate.in"], @@ -682,8 +682,8 @@ export interface mutableKey extends Bottom< S["Type"], S["Encoded"], - S["DecodingContext"], - S["EncodingContext"], + S["DecodingServices"], + S["EncodingServices"], S["ast"], mutableKey, S["~annotate.in"], @@ -789,8 +789,8 @@ export interface flip extends Bottom< S["Encoded"], S["Type"], - S["EncodingContext"], - S["DecodingContext"], + S["EncodingServices"], + S["DecodingServices"], AST.AST, flip, Annotations.Bottom, @@ -835,8 +835,8 @@ export interface declare> extend Bottom< T, E, - TypeParameters[number]["DecodingContext"], - TypeParameters[number]["EncodingContext"], + TypeParameters[number]["DecodingServices"], + TypeParameters[number]["EncodingServices"], AST.Declaration, declare, Annotations.Declaration @@ -1264,12 +1264,12 @@ export declare namespace Struct { /** * @since 4.0.0 */ - export type DecodingContext = { readonly [K in keyof F]: F[K]["DecodingContext"] }[keyof F] + export type DecodingServices = { readonly [K in keyof F]: F[K]["DecodingServices"] }[keyof F] /** * @since 4.0.0 */ - export type EncodingContext = { readonly [K in keyof F]: F[K]["EncodingContext"] }[keyof F] + export type EncodingServices = { readonly [K in keyof F]: F[K]["EncodingServices"] }[keyof F] type TypeConstructorDefaultedKeys = { [K in keyof Fields]: Fields[K] extends { readonly "~type.constructor.default": "with-default" } ? K @@ -1297,8 +1297,8 @@ export interface Struct extends Bottom< Simplify>, Simplify>, - Struct.DecodingContext, - Struct.EncodingContext, + Struct.DecodingServices, + Struct.EncodingServices, AST.TypeLiteral, Struct, Annotations.Struct>>, @@ -1479,16 +1479,16 @@ export declare namespace Record { /** * @since 4.0.0 */ - export type DecodingContext = - | Key["DecodingContext"] - | Value["DecodingContext"] + export type DecodingServices = + | Key["DecodingServices"] + | Value["DecodingServices"] /** * @since 4.0.0 */ - export type EncodingContext = - | Key["EncodingContext"] - | Value["EncodingContext"] + export type EncodingServices = + | Key["EncodingServices"] + | Value["EncodingServices"] /** * @since 4.0.0 @@ -1509,8 +1509,8 @@ export interface Record$ extends Bottom< Record.Type, Record.Encoded, - Record.DecodingContext, - Record.EncodingContext, + Record.DecodingServices, + Record.EncodingServices, AST.TypeLiteral, Record$, Annotations.Bottom>, @@ -1589,16 +1589,16 @@ export declare namespace StructWithRest { /** * @since 4.0.0 */ - export type DecodingContext = - | S["DecodingContext"] - | { [K in keyof Records]: Records[K]["DecodingContext"] }[number] + export type DecodingServices = + | S["DecodingServices"] + | { [K in keyof Records]: Records[K]["DecodingServices"] }[number] /** * @since 4.0.0 */ - export type EncodingContext = - | S["EncodingContext"] - | { [K in keyof Records]: Records[K]["EncodingContext"] }[number] + export type EncodingServices = + | S["EncodingServices"] + | { [K in keyof Records]: Records[K]["EncodingServices"] }[number] /** * @since 4.0.0 @@ -1619,8 +1619,8 @@ export interface StructWithRest< Bottom< Simplify>, Simplify>, - StructWithRest.DecodingContext, - StructWithRest.EncodingContext, + StructWithRest.DecodingServices, + StructWithRest.EncodingServices, AST.TypeLiteral, StructWithRest, Annotations.Bottom>>, @@ -1703,12 +1703,12 @@ export declare namespace Tuple { /** * @since 4.0.0 */ - export type DecodingContext = E[number]["DecodingContext"] + export type DecodingServices = E[number]["DecodingServices"] /** * @since 4.0.0 */ - export type EncodingContext = E[number]["EncodingContext"] + export type EncodingServices = E[number]["EncodingServices"] type MakeIn_< E, @@ -1736,8 +1736,8 @@ export interface Tuple extends Bottom< Tuple.Type, Tuple.Encoded, - Tuple.DecodingContext, - Tuple.EncodingContext, + Tuple.DecodingServices, + Tuple.EncodingServices, AST.TupleType, Tuple, Annotations.Bottom>, @@ -1851,8 +1851,8 @@ export interface TupleWithRest< Bottom< TupleWithRest.Type, TupleWithRest.Encoded, - S["DecodingContext"] | Rest[number]["DecodingContext"], - S["EncodingContext"] | Rest[number]["EncodingContext"], + S["DecodingServices"] | Rest[number]["DecodingServices"], + S["EncodingServices"] | Rest[number]["EncodingServices"], AST.TupleType, TupleWithRest, Annotations.Bottom>, @@ -1895,8 +1895,8 @@ export interface Array$ extends Bottom< ReadonlyArray, ReadonlyArray, - S["DecodingContext"], - S["EncodingContext"], + S["DecodingServices"], + S["EncodingServices"], AST.TupleType, Array$, Annotations.Bottom>, @@ -1929,8 +1929,8 @@ export interface NonEmptyArray extends Bottom< readonly [S["Type"], ...Array], readonly [S["Type"], ...Array], - S["DecodingContext"], - S["EncodingContext"], + S["DecodingServices"], + S["EncodingServices"], AST.TupleType, NonEmptyArray, Annotations.Bottom]>, @@ -1964,8 +1964,8 @@ export interface mutable extends Bottom< Mutable, Mutable, - S["DecodingContext"], - S["EncodingContext"], + S["DecodingServices"], + S["EncodingServices"], S["ast"], mutable, // we keep "~annotate.in", "~type.make" and "~type.make.in" as they are because they are contravariant @@ -2001,8 +2001,8 @@ export interface readonly$ extends Bottom< Readonly, Readonly, - S["DecodingContext"], - S["EncodingContext"], + S["DecodingServices"], + S["EncodingServices"], S["ast"], readonly$, // we keep "~annotate.in", "~type.make" and "~type.make.in" as they are because they are contravariant @@ -2038,8 +2038,8 @@ export interface Union> extends Bottom< Members[number]["Type"], Members[number]["Encoded"], - Members[number]["DecodingContext"], - Members[number]["EncodingContext"], + Members[number]["DecodingServices"], + Members[number]["EncodingServices"], AST.UnionType, Union, Annotations.Bottom, @@ -2218,8 +2218,8 @@ export interface suspend extends Bottom< S["Type"], S["Encoded"], - S["DecodingContext"], - S["EncodingContext"], + S["DecodingServices"], + S["EncodingServices"], AST.Suspend, suspend, S["~annotate.in"], @@ -2273,8 +2273,8 @@ export interface refine extends Bottom< T, S["Encoded"], - S["DecodingContext"], - S["EncodingContext"], + S["DecodingServices"], + S["EncodingServices"], S["ast"], refine, S["~annotate.in"], @@ -2331,7 +2331,7 @@ export interface decodingMiddleware extends S["Type"], S["Encoded"], RD, - S["EncodingContext"], + S["EncodingServices"], S["ast"], decodingMiddleware, S["~annotate.in"], @@ -2352,7 +2352,7 @@ export interface decodingMiddleware extends */ export function decodingMiddleware( decode: ( - sr: Effect.Effect, Issue.Issue, S["DecodingContext"]>, + sr: Effect.Effect, Issue.Issue, S["DecodingServices"]>, options: AST.ParseOptions ) => Effect.Effect, Issue.Issue, RD> ) { @@ -2372,7 +2372,7 @@ export interface encodingMiddleware extends Bottom< S["Type"], S["Encoded"], - S["DecodingContext"], + S["DecodingServices"], RE, S["ast"], encodingMiddleware, @@ -2394,7 +2394,7 @@ export interface encodingMiddleware extends */ export function encodingMiddleware( encode: ( - sr: Effect.Effect, Issue.Issue, S["EncodingContext"]>, + sr: Effect.Effect, Issue.Issue, S["EncodingServices"]>, options: AST.ParseOptions ) => Effect.Effect, Issue.Issue, RE> ) { @@ -2423,7 +2423,7 @@ export function catchDecoding( export function catchDecodingWithContext( f: (issue: Issue.Issue) => Effect.Effect, Issue.Issue, R> ) { - return (self: S): decodingMiddleware => { + return (self: S): decodingMiddleware => { return self.pipe(decodingMiddleware(Effect.catchEager(f))) } } @@ -2445,7 +2445,7 @@ export function catchEncoding( export function catchEncodingWithContext( f: (issue: Issue.Issue) => Effect.Effect, Issue.Issue, R> ) { - return (self: S): encodingMiddleware => { + return (self: S): encodingMiddleware => { return self.pipe(encodingMiddleware(Effect.catchEager(f))) } } @@ -2458,8 +2458,8 @@ export interface decodeTo extends Bottom< To["Type"], From["Encoded"], - To["DecodingContext"] | From["DecodingContext"] | RD, - To["EncodingContext"] | From["EncodingContext"] | RE, + To["DecodingServices"] | From["DecodingServices"] | RD, + To["EncodingServices"] | From["EncodingServices"] | RE, To["ast"], decodeTo, To["~annotate.in"], @@ -2588,8 +2588,8 @@ export interface withConstructorDefault extends Bottom< S["Type"], S["Encoded"], - S["DecodingContext"], - S["EncodingContext"], + S["DecodingServices"], + S["EncodingServices"], S["ast"], withConstructorDefault, S["~annotate.in"], @@ -2786,8 +2786,8 @@ export interface Opaque extends Bottom< Self, S["Encoded"], - S["DecodingContext"], - S["EncodingContext"], + S["DecodingServices"], + S["EncodingServices"], S["ast"], S["~rebuild.out"], S["~annotate.in"], @@ -3005,8 +3005,8 @@ export interface Class, Annotations.Declaration, @@ -3074,8 +3074,8 @@ function makeClass< declare static readonly "Type": Self declare static readonly "Encoded": S["Encoded"] - declare static readonly "DecodingContext": S["DecodingContext"] - declare static readonly "EncodingContext": S["EncodingContext"] + declare static readonly "DecodingServices": S["DecodingServices"] + declare static readonly "EncodingServices": S["EncodingServices"] declare static readonly "~rebuild.out": Class declare static readonly "~annotate.in": Annotations.Declaration @@ -3307,7 +3307,7 @@ export const RequestClass = Request.Request< Success["Type"], Error["Type"], - Success["DecodingContext"] | Success["EncodingContext"] | Error["DecodingContext"] | Error["EncodingContext"] + Success["DecodingServices"] | Success["EncodingServices"] | Error["DecodingServices"] | Error["EncodingServices"] > & Brand > => { return class RequestClass extends makeClass( diff --git a/packages/effect/src/unstable/http/FetchHttpClient.ts b/packages/effect/src/unstable/http/FetchHttpClient.ts index a13ecf1af4..f7f4161046 100644 --- a/packages/effect/src/unstable/http/FetchHttpClient.ts +++ b/packages/effect/src/unstable/http/FetchHttpClient.ts @@ -1,9 +1,9 @@ /** * @since 1.0.0 */ -import * as Context from "../../Context.js" import * as Effect from "../../Effect.js" import type * as Layer from "../../Layer.js" +import * as ServiceMap from "../../ServiceMap.js" import * as Stream from "../../Stream.js" import * as Headers from "./Headers.js" import * as HttpClient from "./HttpClient.js" @@ -14,19 +14,21 @@ import * as HttpClientResponse from "./HttpClientResponse.js" * @since 1.0.0 * @category tags */ -export class Fetch extends Context.Tag()("effect/http/FetchHttpClient/Fetch") {} +export class Fetch extends ServiceMap.Reference("effect/http/FetchHttpClient/Fetch", { + defaultValue: (): typeof globalThis.fetch => globalThis.fetch +}) {} /** * @since 1.0.0 * @category tags */ export class RequestInit - extends Context.Tag()("effect/http/FetchHttpClient/RequestInit") + extends ServiceMap.Key()("effect/http/FetchHttpClient/RequestInit") {} const fetch: HttpClient.HttpClient = HttpClient.make((request, url, signal, fiber) => { - const fetch: typeof globalThis.fetch = fiber.context.unsafeMap.get(Fetch.key) ?? globalThis.fetch - const options: globalThis.RequestInit = fiber.context.unsafeMap.get(RequestInit.key) ?? {} + const fetch = fiber.getRef(Fetch) + const options: globalThis.RequestInit = fiber.services.unsafeMap.get(RequestInit.key) ?? {} const headers = options.headers ? Headers.merge(Headers.fromInput(options.headers), request.headers) : request.headers const send = (body: BodyInit | undefined) => Effect.map( @@ -65,4 +67,4 @@ const fetch: HttpClient.HttpClient = HttpClient.make((request, url, signal, fibe * @since 1.0.0 * @category layers */ -export const layer: Layer.Layer = HttpClient.layerMergedContext(Effect.succeed(fetch)) +export const layer: Layer.Layer = HttpClient.layerMergedServices(Effect.succeed(fetch)) diff --git a/packages/effect/src/unstable/http/Headers.ts b/packages/effect/src/unstable/http/Headers.ts index 7ed3c39dd7..80cf50bcc6 100644 --- a/packages/effect/src/unstable/http/Headers.ts +++ b/packages/effect/src/unstable/http/Headers.ts @@ -1,7 +1,7 @@ /** * @since 4.0.0 */ -import * as Context from "../../Context.js" +import * as ServiceMap from "../../ServiceMap.js" import * as Equal from "../../Equal.js" import type { Equivalence as Equivalence_ } from "../../Equivalence.js" import { dual } from "../../Function.js" @@ -47,9 +47,9 @@ const Proto = Object.assign(Object.create(null), { [TypeId]: TypeId, [symbolRedactable]( this: Headers, - context: Context.Context + context: ServiceMap.ServiceMap ): Record> { - return redact(this, Context.get(context, CurrentRedactedNames)) + return redact(this, ServiceMap.get(context, CurrentRedactedNames)) }, [Equal.symbol](this: Headers, that: Headers): boolean { return Equivalence(this, that) @@ -279,7 +279,7 @@ export const redact: { * @since 4.0.0 * @category fiber refs */ -export class CurrentRedactedNames extends Context.Reference< +export class CurrentRedactedNames extends ServiceMap.Reference< "effect/Headers/CurrentRedactedNames", ReadonlyArray >("effect/Headers/CurrentRedactedNames", { diff --git a/packages/effect/src/unstable/http/HttpBody.ts b/packages/effect/src/unstable/http/HttpBody.ts index c819d840b2..8b4c099784 100644 --- a/packages/effect/src/unstable/http/HttpBody.ts +++ b/packages/effect/src/unstable/http/HttpBody.ts @@ -240,7 +240,7 @@ export const jsonSchema = >( options?: ParseOptions | undefined ) => { const encode = Schema.encodeUnknownEffect(Serializer.json(schema)) - return (body: S["Type"]): Effect.Effect => + return (body: S["Type"]): Effect.Effect => encode(body, options).pipe( Effect.mapError(({ issue }) => new HttpBodyError({ reason: { _tag: "SchemaError", issue }, cause: issue })), Effect.flatMap((body) => json(body)) diff --git a/packages/effect/src/unstable/http/HttpClient.ts b/packages/effect/src/unstable/http/HttpClient.ts index 94aed740f1..c1e48e880d 100644 --- a/packages/effect/src/unstable/http/HttpClient.ts +++ b/packages/effect/src/unstable/http/HttpClient.ts @@ -3,7 +3,6 @@ */ import type { NonEmptyReadonlyArray } from "../../Array.js" import * as Cause from "../../Cause.js" -import * as Context from "../../Context.js" import * as Effect from "../../Effect.js" import * as Exit from "../../Exit.js" import type { Fiber } from "../../Fiber.js" @@ -17,6 +16,7 @@ import * as Ref from "../../Ref.js" import * as Result from "../../Result.js" import * as Schedule from "../../Schedule.js" import type * as Scope from "../../Scope.js" +import * as ServiceMap from "../../ServiceMap.js" import * as Stream from "../../Stream.js" import * as Tracer from "../../Tracer.js" import type { ExcludeTag, ExtractTag, NoExcessProperties, NoInfer, Tags } from "../../Types.js" @@ -121,7 +121,7 @@ export declare namespace HttpClient { * @since 4.0.0 * @category tags */ -export const HttpClient: Context.Tag = Context.GenericTag( +export const HttpClient: ServiceMap.Key = ServiceMap.Key( "effect/HttpClient" ) @@ -954,7 +954,7 @@ export const followRedirects: { * @since 4.0.0 * @category References */ -export class TracerDisabledWhen extends Context.Reference< +export class TracerDisabledWhen extends ServiceMap.Reference< "effect/HttpClient/TracerDisabledWhen", Predicate.Predicate >("effect/HttpClient/TracerDisabledWhen", { @@ -965,7 +965,7 @@ export class TracerDisabledWhen extends Context.Reference< * @since 4.0.0 * @category References */ -export class TracerPropagationEnabled extends Context.Reference("effect/HttpClient/TracerPropagationEnabled", { +export class TracerPropagationEnabled extends ServiceMap.Reference("effect/HttpClient/TracerPropagationEnabled", { defaultValue: () => constTrue }) {} @@ -973,7 +973,7 @@ export class TracerPropagationEnabled extends Context.Reference("effect/HttpClie * @since 4.0.0 * @category References */ -export class SpanNameGenerator extends Context.Reference< +export class SpanNameGenerator extends ServiceMap.Reference< "effect/HttpClient/SpanNameGenerator", (request: HttpClientRequest.HttpClientRequest) => string >("effect/HttpClient/SpanNameGenerator", { @@ -983,16 +983,16 @@ export class SpanNameGenerator extends Context.Reference< /** * @since 4.0.0 */ -export const layerMergedContext = ( +export const layerMergedServices = ( effect: Effect.Effect ): Layer.Layer => Layer.effect( HttpClient, - Effect.flatMap(Effect.context(), (context) => + Effect.flatMap(Effect.services(), (context) => Effect.map(effect, (client) => transformResponse( client, - Effect.updateContext((input: Context.Context) => Context.merge(context, input)) + Effect.updateServices((input: ServiceMap.ServiceMap) => ServiceMap.merge(context, input)) ))) ) diff --git a/packages/effect/src/unstable/http/HttpClientRequest.ts b/packages/effect/src/unstable/http/HttpClientRequest.ts index 3036df36a9..547f5e3612 100644 --- a/packages/effect/src/unstable/http/HttpClientRequest.ts +++ b/packages/effect/src/unstable/http/HttpClientRequest.ts @@ -605,11 +605,11 @@ export const schemaBodyJson = >( body: S["Type"] ): ( self: HttpClientRequest - ) => Effect.Effect + ) => Effect.Effect ( self: HttpClientRequest, body: S["Type"] - ): Effect.Effect + ): Effect.Effect } => { const encode = HttpBody.jsonSchema(schema, options) return dual( @@ -617,7 +617,7 @@ export const schemaBodyJson = >( ( self: HttpClientRequest, body: unknown - ): Effect.Effect => + ): Effect.Effect => Effect.map(encode(body), (body) => setBody(self, body)) ) } diff --git a/packages/effect/src/unstable/http/HttpIncomingMessage.ts b/packages/effect/src/unstable/http/HttpIncomingMessage.ts index c6dff30fd0..c8384903ad 100644 --- a/packages/effect/src/unstable/http/HttpIncomingMessage.ts +++ b/packages/effect/src/unstable/http/HttpIncomingMessage.ts @@ -1,7 +1,6 @@ /** * @since 4.0.0 */ -import * as Context from "../../Context.js" import * as Effect from "../../Effect.js" import * as FileSystem from "../../FileSystem.js" import { dual } from "../../Function.js" @@ -11,6 +10,7 @@ import { hasProperty } from "../../Predicate.js" import type { ParseOptions } from "../../schema/AST.js" import * as Schema from "../../schema/Schema.js" import * as Serializer from "../../schema/Serializer.js" +import * as ServiceMap from "../../ServiceMap.js" import type * as Stream from "../../Stream.js" import type * as Headers from "./Headers.js" import * as UrlParams from "./UrlParams.js" @@ -56,7 +56,7 @@ export const schemaBodyJson = >(schema: S, options? const decode = Schema.decodeEffect(Serializer.json(schema).annotate({ options })) return ( self: HttpIncomingMessage - ): Effect.Effect => Effect.flatMap(self.json, decode) + ): Effect.Effect => Effect.flatMap(self.json, decode) } /** @@ -97,7 +97,7 @@ export const schemaHeaders = Option.none() }) {} diff --git a/packages/effect/test/Effect.test.ts b/packages/effect/test/Effect.test.ts index 36ab5b7926..afd550747c 100644 --- a/packages/effect/test/Effect.test.ts +++ b/packages/effect/test/Effect.test.ts @@ -1,6 +1,5 @@ import { assert, describe, it } from "@effect/vitest" import * as Cause from "effect/Cause" -import * as Context from "effect/Context" import * as Data from "effect/Data" import * as Effect from "effect/Effect" import * as Exit from "effect/Exit" @@ -11,9 +10,10 @@ import * as Option from "effect/Option" import * as Result from "effect/Result" import * as Schedule from "effect/Schedule" import * as Scope from "effect/Scope" +import * as ServiceMap from "effect/ServiceMap" import * as TestClock from "effect/TestClock" -class ATag extends Context.Tag()("ATag") {} +class ATag extends ServiceMap.Key()("ATag") {} describe("Effect", () => { it("callback can branch over sync/async", async () => { @@ -91,7 +91,7 @@ describe("Effect", () => { assert.isTrue(release) }) - it("Context.Tag", () => + it("ServiceMap.Key", () => ATag.asEffect().pipe( Effect.tap((_) => Effect.sync(() => assert.strictEqual(_, "A"))), Effect.provideService(ATag, "A"), diff --git a/packages/effect/test/HttpClient.test.ts b/packages/effect/test/HttpClient.test.ts index a800a1d9bd..c01e9beff1 100644 --- a/packages/effect/test/HttpClient.test.ts +++ b/packages/effect/test/HttpClient.test.ts @@ -1,5 +1,5 @@ import { expect, it } from "@effect/vitest" -import { Context, Effect, Layer, Stream, Struct, TestClock } from "effect" +import { ServiceMap, Effect, Layer, Stream, Struct, TestClock } from "effect" import { Schema } from "effect/schema" import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http" @@ -30,7 +30,7 @@ const makeJsonPlaceholder = Effect.gen(function*() { } as const }) interface JsonPlaceholder extends Effect.Effect.Success {} -const JsonPlaceholder = Context.GenericTag("test/JsonPlaceholder") +const JsonPlaceholder = ServiceMap.Key("test/JsonPlaceholder") const JsonPlaceholderLive = Layer.effect(JsonPlaceholder, makeJsonPlaceholder) ;[ { diff --git a/packages/effect/test/Layer.test.ts b/packages/effect/test/Layer.test.ts index 63f2e507f0..a8aaa5111f 100644 --- a/packages/effect/test/Layer.test.ts +++ b/packages/effect/test/Layer.test.ts @@ -1,21 +1,21 @@ import { assert, describe, it } from "@effect/vitest" -import * as Context from "effect/Context" import * as Effect from "effect/Effect" import * as Exit from "effect/Exit" import * as Fiber from "effect/Fiber" import * as Layer from "effect/Layer" import * as Scope from "effect/Scope" +import * as ServiceMap from "effect/ServiceMap" describe("Layer", () => { it.effect("layers can be acquired in parallel", () => Effect.gen(function*() { - const BoolTag = Context.GenericTag("boolean") + const BoolTag = ServiceMap.Key("boolean") const latch = Effect.unsafeMakeLatch() - const layer1 = Layer.effectContext(Effect.never) - const layer2 = Layer.effectContext( + const layer1 = Layer.effectServices(Effect.never) + const layer2 = Layer.effectServices( Effect.acquireRelease( latch.open.pipe( - Effect.map((bool) => Context.make(BoolTag, bool)) + Effect.map((bool) => ServiceMap.make(BoolTag, bool)) ), () => Effect.void ) @@ -42,7 +42,7 @@ describe("Layer", () => { const layer = Layer.succeed(Service1Tag, service1) const env = layer.pipe(Layer.merge(layer), Layer.merge(layer), Layer.build) const result = yield* env.pipe( - Effect.map((context) => Context.get(context, Service1Tag)) + Effect.map((context) => ServiceMap.get(context, Service1Tag)) ) assert.strictEqual(result, service1) })) @@ -286,7 +286,7 @@ export class Service1 { return Effect.succeed(1) } } -const Service1Tag = Context.GenericTag("Service1") +const Service1Tag = ServiceMap.Key("Service1") const makeLayer1 = (array: Array): Layer.Layer => { return Layer.effect( Service1Tag, @@ -304,7 +304,7 @@ class Service2 { return Effect.succeed(2) } } -const Service2Tag = Context.GenericTag("Service2") +const Service2Tag = ServiceMap.Key("Service2") const makeLayer2 = (array: Array): Layer.Layer => { return Layer.effect( Service2Tag, @@ -322,7 +322,7 @@ class Service3 { return Effect.succeed(3) } } -const Service3Tag = Context.GenericTag("Service3") +const Service3Tag = ServiceMap.Key("Service3") const makeLayer3 = (array: Array): Layer.Layer => { return Layer.effect( Service3Tag, diff --git a/packages/effect/test/Logger.test.ts b/packages/effect/test/Logger.test.ts index 6572612b4f..2d59588edc 100644 --- a/packages/effect/test/Logger.test.ts +++ b/packages/effect/test/Logger.test.ts @@ -32,7 +32,7 @@ describe("Logger", () => { result.push(inp) }) )])) - yield* Effect.logInfo("info", "message").pipe(Effect.provideContext(context)) + yield* Effect.logInfo("info", "message").pipe(Effect.provideServices(context)) assert.strictEqual(result.length, 1) }) ) diff --git a/packages/effect/test/Request.test.ts b/packages/effect/test/Request.test.ts index e3e591ab89..c002b82091 100644 --- a/packages/effect/test/Request.test.ts +++ b/packages/effect/test/Request.test.ts @@ -1,7 +1,7 @@ import { assert, describe, expect, it } from "@effect/vitest" import * as Array from "effect/Array" import * as Cause from "effect/Cause" -import * as Context from "effect/Context" +import * as ServiceMap from "effect/ServiceMap" import * as Effect from "effect/Effect" import * as Exit from "effect/Exit" import * as Fiber from "effect/Fiber" @@ -9,9 +9,9 @@ import { flow, pipe } from "effect/Function" import * as Request from "effect/Request" import * as Resolver from "effect/RequestResolver" -class Counter extends Context.Tag()("Counter") {} -class Requests extends Context.Tag()("Requests") {} -class Interrupts extends Context.Reference("Interrupts", { +class Counter extends ServiceMap.Key()("Counter") {} +class Requests extends ServiceMap.Key()("Requests") {} +class Interrupts extends ServiceMap.Reference("Interrupts", { defaultValue: () => ({ interrupts: 0 }) }) {} const delay = (self: Effect.Effect) => diff --git a/packages/effect/test/schema/Schema.test.ts b/packages/effect/test/schema/Schema.test.ts index dbe0a48034..3e5207b250 100644 --- a/packages/effect/test/schema/Schema.test.ts +++ b/packages/effect/test/schema/Schema.test.ts @@ -1,4 +1,4 @@ -import { BigInt, Context, Effect, Equal, flow, Option, Order, Predicate, String as Str, Struct, Tuple } from "effect" +import { BigInt, ServiceMap, Effect, Equal, flow, Option, Order, Predicate, String as Str, Struct, Tuple } from "effect" import { AST, Check, Getter, Issue, Schema, ToParser, Transformation } from "effect/schema" import { produce } from "immer" import { describe, it } from "vitest" @@ -2301,7 +2301,7 @@ describe("Schema", () => { }) it("Struct & Effect async & service", async () => { - class Service extends Context.Tag }>()("Service") {} + class Service extends ServiceMap.Key }>()("Service") {} const schema = Schema.Struct({ a: Schema.FiniteFromString.pipe(Schema.withConstructorDefault(() => @@ -4262,7 +4262,7 @@ describe("Schema", () => { }) it("catchDecodingWithContext", async () => { - class Service extends Context.Tag }>()("Service") {} + class Service extends ServiceMap.Key }>()("Service") {} const schema = Schema.String.pipe(Schema.catchDecodingWithContext(() => Effect.gen(function*() { @@ -4282,7 +4282,7 @@ describe("Schema", () => { describe("decodingMiddleware", () => { it("providing a service", async () => { - class Service extends Context.Tag }>()("Service") {} + class Service extends ServiceMap.Key }>()("Service") {} const schema = Schema.String.pipe( Schema.catchDecodingWithContext(() => @@ -4319,7 +4319,7 @@ describe("Schema", () => { describe("encodingMiddleware", () => { it("providing a service", async () => { - class Service extends Context.Tag }>()("Service") {} + class Service extends ServiceMap.Key }>()("Service") {} const schema = Schema.String.pipe( Schema.catchEncodingWithContext(() => @@ -4622,7 +4622,7 @@ describe("SchemaGetter", () => { }) it("with context", async () => { - class Service extends Context.Tag }>()("Service") {} + class Service extends ServiceMap.Key }>()("Service") {} const schema = Schema.String.pipe( Schema.decode({ @@ -4708,7 +4708,7 @@ describe("SchemaGetter", () => { }) it("should throw on missing dependency", () => { - class MagicNumber extends Context.Tag()("MagicNumber") {} + class MagicNumber extends ServiceMap.Key()("MagicNumber") {} const DepString = Schema.Number.pipe(Schema.decode({ decode: Getter.onSome((n) => Effect.gen(function*() { diff --git a/packages/effect/test/schema/standardSchemaV1.test.ts b/packages/effect/test/schema/standardSchemaV1.test.ts index 897ea6c10b..2340f18f5d 100644 --- a/packages/effect/test/schema/standardSchemaV1.test.ts +++ b/packages/effect/test/schema/standardSchemaV1.test.ts @@ -1,5 +1,5 @@ import { assertTrue, deepStrictEqual, strictEqual } from "@effect/vitest/utils" -import { Context, Effect, Option, Predicate } from "effect" +import { ServiceMap, Effect, Option, Predicate } from "effect" import type { Formatter } from "effect/schema" import { Check, Getter, Schema } from "effect/schema" import { describe, it } from "vitest" @@ -88,7 +88,7 @@ describe("standardSchemaV1", () => { }) describe("missing dependencies", () => { - class MagicNumber extends Context.Tag()("MagicNumber") {} + class MagicNumber extends ServiceMap.Key()("MagicNumber") {} it("sync decoding should throw", () => { const DepString = Schema.Number.pipe(Schema.decode({ diff --git a/packages/effect/test/utils/schema.ts b/packages/effect/test/utils/schema.ts index dab5b3da42..060114282d 100644 --- a/packages/effect/test/utils/schema.ts +++ b/packages/effect/test/utils/schema.ts @@ -1,5 +1,5 @@ import type { StandardSchemaV1 } from "@standard-schema/spec" -import type { Context } from "effect" +import type { ServiceMap } from "effect" import { Effect, FastCheck, Predicate, Record, Result } from "effect" import { AST, Formatter, Issue, Schema, Serializer, ToArbitrary, ToParser } from "effect/schema" import { deepStrictEqual, fail, strictEqual, throws } from "./assert.js" @@ -250,7 +250,7 @@ function make(asserts: { options?: { readonly expected?: A readonly parseOptions?: AST.ParseOptions | undefined - readonly provide?: ReadonlyArray, any]> | undefined + readonly provide?: ReadonlyArray, any]> | undefined } | undefined ) { const decoded = ToParser.decodeUnknownEffect(schema)(input, options?.parseOptions) @@ -278,7 +278,7 @@ function make(asserts: { message: string, options?: { readonly parseOptions?: AST.ParseOptions | undefined - readonly provide?: ReadonlyArray, any]> | undefined + readonly provide?: ReadonlyArray, any]> | undefined } | undefined ) { const decoded = ToParser.decodeUnknownEffect(schema)(input, options?.parseOptions) diff --git a/packages/platform-node-shared/src/NodeFileSystem.ts b/packages/platform-node-shared/src/NodeFileSystem.ts index c8cbd8ccdb..463107a65d 100644 --- a/packages/platform-node-shared/src/NodeFileSystem.ts +++ b/packages/platform-node-shared/src/NodeFileSystem.ts @@ -1,7 +1,6 @@ /** * @since 1.0.0 */ -import type * as Context from "effect/Context" import * as Effect from "effect/Effect" import { effectify } from "effect/Effect" import * as Exit from "effect/Exit" @@ -570,7 +569,7 @@ const watchNode = (path: string) => ) ) -const watch = (backend: Option.Option>, path: string) => +const watch = (backend: Option.Option, path: string) => stat(path).pipe( Effect.map((stat) => backend.pipe( diff --git a/packages/platform-node-shared/src/NodeStream.ts b/packages/platform-node-shared/src/NodeStream.ts index 88b91e1836..7d154c396a 100644 --- a/packages/platform-node-shared/src/NodeStream.ts +++ b/packages/platform-node-shared/src/NodeStream.ts @@ -5,7 +5,7 @@ import type { NonEmptyReadonlyArray } from "effect/Array" import * as Arr from "effect/Array" import * as Cause from "effect/Cause" import * as Channel from "effect/Channel" -import * as Context from "effect/Context" +import * as ServiceMap from "effect/ServiceMap" import * as Effect from "effect/Effect" import * as Exit from "effect/Exit" import * as Fiber from "effect/Fiber" @@ -158,7 +158,7 @@ export const pipeThroughSimple: { */ export const toReadable = (stream: Stream.Stream): Effect.Effect => Effect.map( - Effect.context(), + Effect.services(), (context) => new StreamAdapter(context, stream) ) @@ -168,7 +168,7 @@ export const toReadable = (stream: Stream.Stream(stream: Stream.Stream): Readable => new StreamAdapter( - Context.empty(), + ServiceMap.empty(), stream ) @@ -316,7 +316,7 @@ class StreamAdapter extends Readable { private fiber: Fiber.Fiber | undefined = undefined constructor( - context: Context.Context, + context: ServiceMap.ServiceMap, stream: Stream.Stream ) { super({}) @@ -334,7 +334,7 @@ class StreamAdapter extends Readable { } }))).pipe( this.readLatch.whenOpen, - Effect.provideContext(context), + Effect.provideServices(context), Effect.runFork ) this.fiber.addObserver((exit) => { diff --git a/packages/vitest/src/index.ts b/packages/vitest/src/index.ts index edd626c61a..8357fb0376 100644 --- a/packages/vitest/src/index.ts +++ b/packages/vitest/src/index.ts @@ -170,13 +170,13 @@ export const live: Vitest.Tester = internal.live * * ```ts * import { expect, layer } from "@effect/vitest" - * import { Context, Effect, Layer } from "effect" + * import { ServiceMap, Effect, Layer } from "effect" * - * class Foo extends Context.Tag("Foo")() { + * class Foo extends ServiceMap.Key("Foo")() { * static Live = Layer.succeed(Foo, "foo") * } * - * class Bar extends Context.Tag("Bar")() { + * class Bar extends ServiceMap.Key("Bar")() { * static Live = Layer.effect( * Bar, * Effect.map(Foo, () => "bar" as const) diff --git a/packages/vitest/test/index.test.ts b/packages/vitest/test/index.test.ts index 37fb0aefb6..8ce3cccced 100644 --- a/packages/vitest/test/index.test.ts +++ b/packages/vitest/test/index.test.ts @@ -1,5 +1,5 @@ import { afterAll, describe, expect, it, layer } from "@effect/vitest" -import { Clock, Context, Duration, Effect, FastCheck, Fiber, Layer, TestClock } from "effect" +import { Clock, ServiceMap, Duration, Effect, FastCheck, Fiber, Layer, TestClock } from "effect" it.effect( "effect", @@ -62,15 +62,15 @@ it.live.fails("interrupts on timeout", (ctx) => yield* Effect.sleep(1000) }), 1) -class Foo extends Context.Tag()("Foo") { +class Foo extends ServiceMap.Key()("Foo") { static Live = Layer.succeed(Foo, "foo") } -class Bar extends Context.Tag()("Bar") { +class Bar extends ServiceMap.Key()("Bar") { static Live = Layer.effect(Bar, Effect.map(Foo.asEffect(), () => "bar" as const)) } -class Sleeper extends Context.Tag Effect.Effect }>()("Sleeper") { static layer = Layer.effect( @@ -119,7 +119,7 @@ describe("layer", () => { expect(released).toEqual(true) }) - class Scoped extends Context.Tag()("Scoped") { + class Scoped extends ServiceMap.Key()("Scoped") { static Live = Layer.effect( Scoped, Effect.acquireRelease( diff --git a/scratchpad/examples/01-refs.ts b/scratchpad/examples/01-refs.ts index 785aadacb1..674148eb8b 100644 --- a/scratchpad/examples/01-refs.ts +++ b/scratchpad/examples/01-refs.ts @@ -1,6 +1,6 @@ -import { Context, Effect } from "effect" +import { ServiceMap, Effect } from "effect" -class FeatureFlag extends Context.Reference("FeatureFlag", { +class FeatureFlag extends ServiceMap.Reference("FeatureFlag", { defaultValue: () => false }) {} diff --git a/scratchpad/examples/08-implicit-scope.ts b/scratchpad/examples/08-implicit-scope.ts index 4346809d4d..d2e399a666 100644 --- a/scratchpad/examples/08-implicit-scope.ts +++ b/scratchpad/examples/08-implicit-scope.ts @@ -1,6 +1,6 @@ -import { Context, Effect, Layer } from "effect" +import { ServiceMap, Effect, Layer } from "effect" -class BackgroundCounter extends Context.Tag }>()("BackgroundCounter") { static layer = Layer.effect( diff --git a/scratchpad/layer.ts b/scratchpad/layer.ts index b52a2d5fc1..4fd80f8635 100644 --- a/scratchpad/layer.ts +++ b/scratchpad/layer.ts @@ -1,10 +1,10 @@ -import * as Context from "effect/Context" +import * as ServiceMap from "effect/ServiceMap" import * as Effect from "effect/Effect" import * as Layer from "effect/Layer" import * as References from "effect/References" import { bench } from "./bench.js" -class Users extends Context.Tag()("Users") {} +class Users extends ServiceMap.Key()("Users") {} const UsersLive = Layer.succeed(Users, {})