better-effect 0.8.0 → 0.9.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +47 -0
- package/dist/adapters/iti.d.mts +3 -3
- package/dist/adapters/iti.mjs +2 -1
- package/dist/adapters/iti.mjs.map +1 -1
- package/dist/{internal-identity-Cm4-KIUj.mjs → errors-Dnjhzbt0.mjs} +2 -25
- package/dist/errors-Dnjhzbt0.mjs.map +1 -0
- package/dist/{index-BFgG9zZC.d.mts → index-1NLNdkJy.d.mts} +2 -2
- package/dist/{index-BFgG9zZC.d.mts.map → index-1NLNdkJy.d.mts.map} +1 -1
- package/dist/index-BJFBEsm5.d.mts +406 -0
- package/dist/index-BJFBEsm5.d.mts.map +1 -0
- package/dist/{index-fUyY0eNJ.d.mts → index-CYAgpM_5.d.mts} +28 -14
- package/dist/index-CYAgpM_5.d.mts.map +1 -0
- package/dist/index.d.mts +5 -320
- package/dist/index.mjs +142 -277
- package/dist/index.mjs.map +1 -1
- package/dist/internal-identity-DmUpBeeL.mjs +27 -0
- package/dist/internal-identity-DmUpBeeL.mjs.map +1 -0
- package/dist/{map-layer-backend-CGibcwkc.d.mts → map-layer-backend-DMJauecV.d.mts} +2 -2
- package/dist/{map-layer-backend-CGibcwkc.d.mts.map → map-layer-backend-DMJauecV.d.mts.map} +1 -1
- package/dist/{map-layer-backend-BodcEeNA.mjs → map-layer-backend-gal-mcRv.mjs} +3 -2
- package/dist/{map-layer-backend-BodcEeNA.mjs.map → map-layer-backend-gal-mcRv.mjs.map} +1 -1
- package/dist/runtime/explicit.d.mts +1 -1
- package/dist/runtime/node.d.mts +1 -1
- package/dist/signal-Cl9tqGyX.mjs +270 -0
- package/dist/signal-Cl9tqGyX.mjs.map +1 -0
- package/dist/standard-services.d.mts +116 -0
- package/dist/standard-services.d.mts.map +1 -0
- package/dist/standard-services.mjs +180 -0
- package/dist/standard-services.mjs.map +1 -0
- package/dist/testing.d.mts +1 -1
- package/dist/testing.mjs +1 -1
- package/package.json +6 -2
- package/dist/index-fUyY0eNJ.d.mts.map +0 -1
- package/dist/index.d.mts.map +0 -1
- package/dist/internal-identity-Cm4-KIUj.mjs.map +0 -1
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["Constructor","SCOPE_SUCCESS","SCOPE_SUCCESS","next"],"sources":["../src/runtime/default.ts","../src/service/runtime.ts","../src/service/service.ts","../src/layer/internal.ts","../src/layer/layer.ts","../src/scope/errors.ts","../src/scope/disposable.ts","../src/scope/runtime.ts","../src/scope/internal.ts","../src/scope/scope.ts","../src/effect/combinators.ts","../src/effect/effect.ts","../src/function/pipe.ts","../src/resource/errors.ts","../src/resource/internal.ts","../src/resource/resource.ts","../src/runtime/outcome.ts","../src/runtime/signal.ts","../src/runtime/observer.ts","../src/layer/resolution.ts","../src/layer/runtime.ts","../src/runtime/runtime.ts"],"sourcesContent":["import { nodeRuntimeContextStorage } from './node'\n\nimport { setDefaultRuntimeContextStorage } from './context'\n\n/** The Node/Bun storage used by the main Runtime entrypoint. */\nexport const defaultRuntimeContextStorage = nodeRuntimeContextStorage\n\nsetDefaultRuntimeContextStorage(defaultRuntimeContextStorage)\n","import { ServiceRuntimeNotConfiguredError } from './errors'\n\nimport {\n currentRuntimeContext,\n getRuntimeContext,\n makeRuntimeContext,\n runRuntimeContext\n} from '../runtime/context'\n\nimport { defaultRuntimeContextStorage } from '../runtime/default'\n\nimport type { AnyServiceToken } from './types'\n\nimport type { RuntimeContextStorage } from '../runtime/context'\n\n/** Resolves class-backed Service tokens for a runtime execution. */\nexport interface ServiceResolver {\n /** Resolve a token to its corresponding Service instance. */\n resolve<T extends AnyServiceToken>(token: T): InstanceType<T> | PromiseLike<InstanceType<T>>\n}\n\n/** Provides the resolver context used by Service tokens during execution. */\nexport class ServiceRuntime {\n /**\n * Run a callback with a resolver available to `yield* Service` expressions.\n *\n * The context is scoped to the callback and is restored afterward.\n *\n * @example\n * ```ts\n * const value = ServiceRuntime.run(resolver, () => {\n * return ServiceRuntime.resolve(Database)\n * })\n * ```\n */\n static run<A>(\n resolver: ServiceResolver,\n program: () => A,\n storage: RuntimeContextStorage = defaultRuntimeContextStorage\n ): A {\n const current = getRuntimeContext(storage)\n const context = makeRuntimeContext(\n resolver,\n current?.scope,\n current?.resolver === resolver ? current.resolutionPath : [],\n current?.signal\n )\n\n return runRuntimeContext(storage, context, program)\n }\n\n /** Return the resolver active in the current execution context. */\n static current(): ServiceResolver {\n let context\n\n try {\n context = currentRuntimeContext()\n } catch {\n throw new ServiceRuntimeNotConfiguredError()\n }\n\n if (!context.resolver) {\n throw new ServiceRuntimeNotConfiguredError()\n }\n\n return context.resolver\n }\n\n /** Resolve a Service token using the active resolver. */\n static async resolve<T extends AnyServiceToken>(token: T): Promise<InstanceType<T>> {\n const resolver = ServiceRuntime.current()\n\n return await resolver.resolve(token)\n }\n}\n","import { ServiceRuntime } from './runtime'\n\nimport type { ServiceRequirement } from '../effect/types'\n\nimport type {\n AnyService,\n AnyServiceToken,\n ServiceClass,\n ServiceContract,\n ServiceIdentity,\n ServiceIdentityTypeId,\n ServiceInstance,\n ServiceRequirements,\n ServiceTag,\n ServiceToken,\n ServiceTokenOf\n} from './types'\n\ntype ServiceTagLiteral<Tag extends string> = string extends Tag\n ? never\n : Tag extends ''\n ? never\n : Tag\n\ninterface ServiceFactory<Self> {\n <const Tag extends string>(\n tag: ServiceTagLiteral<Tag>\n ): (abstract new () => ServiceIdentity<Tag>) & {\n readonly name: string\n readonly serviceTag: Tag\n } & {\n readonly of: Service.FactoryOf<Self, Tag>\n readonly [Symbol.asyncIterator]: (\n this: ServiceToken<Tag, Self & ServiceIdentity<Tag>>\n ) => AsyncGenerator<ServiceRequirement<Self>, Self, unknown>\n }\n}\n\n/**\n * Declare a class-backed Service with a stable string-literal identity.\n *\n * The returned class is simultaneously the implementation type, the runtime\n * dependency token, and the value yielded by `yield*` in an Effect generator.\n * The explicit self type preserves exact instance inference, while the second\n * call captures the tag as a literal for Layer composition and diagnostics.\n *\n * @example\n * ```ts\n * class Database extends Service<Database>()('Database') {\n * query(): string {\n * return 'ok'\n * }\n * }\n *\n * const database = yield* Database\n * database.query()\n * ```\n *\n * @typeParam Self The instance type implemented by the declared Service.\n */\nexport function Service<Self>(): ServiceFactory<Self> {\n return function <const Tag extends string>(tag: ServiceTagLiteral<Tag>) {\n if (tag.length === 0) {\n throw new TypeError('Service tags must not be empty')\n }\n\n abstract class BaseService implements ServiceIdentity<Tag> {\n /** The stable logical identity used by Layers and resolver backends. */\n static readonly serviceTag: Tag = tag\n declare readonly [ServiceIdentityTypeId]: Tag\n\n /**\n * Type-check a structural implementation of this Service.\n *\n * This is an identity helper. It returns the supplied value unchanged\n * and does not invoke a constructor or modify its prototype.\n *\n * @example\n * ```ts\n * class Database extends Service<Database>()('Database') {\n * query(sql: string): string {\n * return sql\n * }\n * }\n *\n * const database = Database.of({\n * query: (sql) => `Result: ${sql}`\n * })\n *\n * database.query('SELECT 1')\n * // 'Result: SELECT 1'\n * // database is the original object, not an instance of Database\n * ```\n */\n static of(this: void, implementation: ServiceContract<Self & ServiceIdentity<Tag>>): Self {\n // SAFETY: ServiceContract removes only the phantom marker; this boundary restores Self.\n return implementation as Self\n }\n\n /** Resolve this Service from the resolver active in the current runtime. */\n // oxlint-disable-next-line require-yield\n static async *[Symbol.asyncIterator](\n this: ServiceToken<Tag, Self & ServiceIdentity<Tag>>\n ): AsyncGenerator<ServiceRequirement<Self>, Self, unknown> {\n return await ServiceRuntime.resolve(this)\n }\n }\n\n return BaseService\n }\n}\n\n/** Type-level aliases for Service tokens and their instance contracts. */\nexport declare namespace Service {\n /** The widened Service instance constraint. */\n export type Any = AnyService\n\n /** A class-backed Service token with a stable tag and instance contract. */\n export type Token<Tag extends string = string, Instance extends AnyService = any> = ServiceToken<\n Tag,\n Instance\n >\n\n /** A constructible Service class with a stable tag and instance contract. */\n export type Class<\n Tag extends string = string,\n Instance extends AnyService = AnyService\n > = ServiceClass<Tag, Instance>\n\n /** Extract the instance represented by a Service token. */\n export type Instance<T extends AnyServiceToken> = ServiceInstance<T>\n\n /** Extract the stable tag represented by a Service instance. */\n export type Tag<S extends AnyService> = ServiceTag<S>\n\n /** A branded Service instance identity with a stable tag. */\n export type Identity<Tag extends string = string> = ServiceIdentity<Tag>\n\n /** Remove the internal identity marker from a Service implementation contract. */\n export type Contract<S extends AnyService> = ServiceContract<S>\n\n /** Extract the Service token represented by a branded Service instance. */\n export type TokenOf<S extends AnyService> = ServiceTokenOf<S>\n\n /** Declaration bridge for the recursive structural `Service.of` signature. */\n export type FactoryOf<Self, Tag extends string> = (\n this: void,\n implementation: ServiceContract<Self & ServiceIdentity<Tag>>\n ) => Self\n\n /** Extract Effect Service requirements from a Service instance. */\n export type Requirements<S extends AnyService> = ServiceRequirements<S>\n}\n","import { LayerGeneratorYieldError } from './errors'\n\nimport type { ServiceRequirement } from '../effect/types'\nimport type { ServiceClass } from '../service'\n\nimport type { LayerGenerator } from './types'\n\nexport const runLayerGenerator = async <\n S extends ServiceClass<any, any>,\n Yield extends ServiceRequirement<unknown>\n>(\n service: S,\n factory: LayerGenerator<S, Yield>\n): Promise<InstanceType<S>> => {\n const iterator = factory()\n\n const state = await iterator.next()\n\n if (!state.done) {\n try {\n // SAFETY: The iterator is closed only to discard an invalid yield; its return value is ignored.\n await iterator.return(undefined as never)\n } finally {\n // oxlint-disable-next-line no-unsafe-finally\n throw new LayerGeneratorYieldError(service)\n }\n }\n\n // SAFETY: The public generator boundary accepts only the requested Service contract.\n return state.value as InstanceType<S>\n}\n","import type { ServiceRequirement } from '../effect/types'\nimport type { AnyService, ServiceClass, ServiceContract, ServiceRequirements } from '../service'\nimport type { ScopeOutcome } from '../scope'\nimport type { Covariant, Invariant } from '../internal/variance'\nimport type { MaybePromise } from '../utils/types'\n\nimport { DuplicateServiceError, ServiceTagCollisionError } from './errors'\nimport { runLayerGenerator } from './internal'\n\nimport type {\n LayerInput,\n CompleteInput,\n LayerResult,\n MergeResult,\n OverrideLayerResult,\n ValidateLayerInput,\n ValidateLayerTuple,\n ValidateOverrides,\n ProvidedEnvironment,\n RequiredEnvironment\n} from './inference'\nimport type { ProviderEntry } from './metadata'\nimport type { LayerGenerator, LayerGeneratorRequirements, LayerRegistration } from './types'\n\ndeclare const LayerTypeId: unique symbol\n\ninterface LayerVariance<in out Provided, out Required> {\n readonly _Provided: Invariant<Provided>\n readonly _Required: Covariant<Required>\n}\n\ninterface LayerProvider extends LayerRegistration {\n /** Provider storage deliberately erases the concrete instance type. */\n // oxlint-disable-next-line anti-slop/no-unknown-parameters\n readonly release?: (instance: unknown, outcome: ScopeOutcome) => MaybePromise<void>\n}\n\n/** A Service class whose constructor can be called without arguments. */\ntype DefaultConstructibleServiceClass<\n Tag extends string = string,\n Instance extends AnyService = AnyService\n> = ServiceClass<Tag, Instance> & (new () => Instance)\n\n/**\n * Declarative collection of Service providers.\n *\n * A Layer describes how to acquire implementations; it does not execute\n * providers until a `Runtime` is created. Use `merge` to compose distinct\n * providers and `override` when replacing an existing provider intentionally.\n *\n * @example\n * ```ts\n * const AppLive = Layer.merge(\n * Layer.succeed(Database, database),\n * Layer.make(UserRepository)\n * )\n *\n * const runtime = await Runtime.make(AppLive, backend)\n * ```\n */\nexport class Layer<\n in out Provided extends AnyService = AnyService,\n out Required extends AnyService = AnyService\n> {\n declare readonly [LayerTypeId]: LayerVariance<Provided, Required>\n\n /** The provider registrations retained by this Layer. */\n readonly providers: readonly LayerProvider[]\n\n private constructor(providers: readonly LayerProvider[]) {\n this.providers = Object.freeze([...providers])\n }\n\n /** Create a Layer that lazily acquires a Service instance. */\n static make<S extends DefaultConstructibleServiceClass<any, any>>(\n service: S\n ): LayerResult<ProviderEntry<InstanceType<S>, ServiceRequirements<InstanceType<S>>>>\n\n static make<S extends ServiceClass<any, any>>(\n service: S,\n acquire: () => MaybePromise<ServiceContract<InstanceType<S>>>\n ): LayerResult<ProviderEntry<InstanceType<S>, ServiceRequirements<InstanceType<S>>>>\n\n static make<S extends ServiceClass<any, any>>(\n service: S,\n acquire?: () => MaybePromise<ServiceContract<InstanceType<S>>>\n ): LayerResult<ProviderEntry<InstanceType<S>, ServiceRequirements<InstanceType<S>>>> {\n const defaultAcquire = (): InstanceType<S> => {\n // SAFETY: The no-argument overload constrains `service` to a default constructible class.\n const Constructor = service as new () => InstanceType<S>\n\n return new Constructor()\n }\n\n const normalizedAcquire = normalizeAcquire<S>(acquire ?? defaultAcquire)\n\n // SAFETY: Runtime storage erases only the concrete provider metadata; the public constructor result restores its typed provenance.\n return new Layer([\n {\n service,\n acquire: normalizedAcquire\n }\n ]) as LayerResult<ProviderEntry<InstanceType<S>, ServiceRequirements<InstanceType<S>>>>\n }\n\n /** Create a Layer from an already-constructed Service instance. */\n static succeed<S extends ServiceClass<any, any>>(\n service: S,\n instance: ServiceContract<InstanceType<S>>\n ): LayerResult<ProviderEntry<InstanceType<S>, ServiceRequirements<InstanceType<S>>>> {\n const normalizedAcquire = normalizeAcquire<S>(() => instance)\n\n // SAFETY: The structural instance has been checked against the requested Service contract.\n return new Layer([\n {\n service,\n acquire: normalizedAcquire\n }\n ]) as LayerResult<ProviderEntry<InstanceType<S>, ServiceRequirements<InstanceType<S>>>>\n }\n\n /** Define a provider with Runtime-root cleanup. */\n static scoped<S extends ServiceClass<any, any>>(\n service: S,\n acquire: () => MaybePromise<ServiceContract<InstanceType<S>>>,\n release: (instance: InstanceType<S>, outcome: ScopeOutcome) => MaybePromise<void>\n ): LayerResult<ProviderEntry<InstanceType<S>, ServiceRequirements<InstanceType<S>>>> {\n // SAFETY: The public callbacks constrain acquisition and release to the requested Service.\n return new Layer([\n {\n service,\n acquire: normalizeAcquire<S>(acquire),\n release: (instance, outcome) => {\n // SAFETY: The backend invokes release with the instance acquired for this token.\n return release(instance as InstanceType<S>, outcome)\n }\n }\n ]) as LayerResult<ProviderEntry<InstanceType<S>, ServiceRequirements<InstanceType<S>>>>\n }\n\n /** Define a provider whose acquisition can yield contextual Services. */\n static scopedGen<S extends ServiceClass<any, any>, Yield extends ServiceRequirement<unknown>>(\n service: S,\n factory: LayerGenerator<S, Yield>,\n release: (instance: InstanceType<S>, outcome: ScopeOutcome) => MaybePromise<void>\n ): LayerResult<ProviderEntry<InstanceType<S>, LayerGeneratorRequirements<S, Yield>>> {\n // SAFETY: The generator and release callback are checked against the requested Service.\n return new Layer([\n {\n service,\n acquire: () => runLayerGenerator(service, factory),\n release: (instance, outcome) => {\n // SAFETY: The backend invokes release with the instance acquired for this token.\n return release(instance as InstanceType<S>, outcome)\n }\n }\n ]) as LayerResult<ProviderEntry<InstanceType<S>, LayerGeneratorRequirements<S, Yield>>>\n }\n\n /** Define a provider whose acquisition can yield contextual Services. */\n static gen<S extends ServiceClass<any, any>, Yield extends ServiceRequirement<unknown>>(\n service: S,\n factory: LayerGenerator<S, Yield>\n ): LayerResult<ProviderEntry<InstanceType<S>, LayerGeneratorRequirements<S, Yield>>> {\n // SAFETY: The generator result is normalized to the requested Service at the runtime boundary.\n return new Layer([\n {\n service,\n acquire: () => runLayerGenerator(service, factory)\n }\n ]) as LayerResult<ProviderEntry<InstanceType<S>, LayerGeneratorRequirements<S, Yield>>>\n }\n\n /** Compose Layers without replacing providers. */\n static merge<const Layers extends readonly LayerInput[]>(\n ...layers: Layers & ValidateLayerTuple<Layers>\n ): MergeResult<Layers> {\n const providers = new Map<string, LayerProvider>()\n\n for (const layer of layers) {\n for (const provider of layer.providers) {\n const service = provider.service\n const existing = providers.get(service.serviceTag)\n\n if (existing) {\n if (existing.service !== service) {\n throw new ServiceTagCollisionError(existing.service, service)\n }\n\n throw new DuplicateServiceError(service)\n }\n\n providers.set(service.serviceTag, provider)\n }\n }\n\n // SAFETY: The heterogeneous provider list is erased only at this internal storage boundary.\n return new Layer([...providers.values()]) as MergeResult<Layers>\n }\n\n /** Mark a Layer composition root as complete without changing its runtime value. */\n static complete<L extends LayerInput>(layer: L & CompleteInput<L>): L {\n return layer\n }\n\n /** Replace providers in a base Layer, using tag identity and compatible contracts. */\n static override<Base extends LayerInput, const Overrides extends readonly LayerInput[]>(\n base: Base & ValidateLayerInput<Base>,\n ...overrides: Overrides & ValidateOverrides<Base, Overrides>\n ): OverrideLayerResult<Base, Overrides> {\n const providers = new Map<string, LayerProvider>()\n\n for (const provider of base.providers) {\n providers.set(provider.service.serviceTag, provider)\n }\n\n for (const layer of overrides) {\n for (const provider of layer.providers) {\n providers.set(provider.service.serviceTag, provider)\n }\n }\n\n // SAFETY: Runtime provider replacement preserves the computed override metadata.\n return new Layer([...providers.values()]) as OverrideLayerResult<Base, Overrides>\n }\n}\n\nconst normalizeAcquire =\n <S extends ServiceClass<any, any>>(\n acquire: () => MaybePromise<ServiceContract<InstanceType<S>>>\n ): (() => MaybePromise<InstanceType<S>>) =>\n () => {\n // SAFETY: ServiceContract removes only the declaration-only identity; runtime values are unchanged.\n return acquire() as MaybePromise<InstanceType<S>>\n }\n\n/** Type-level aliases for inspecting Layer environments and completeness. */\nexport declare namespace Layer {\n /** The widened Layer shape accepted by generic Layer infrastructure. */\n export type Any = LayerInput\n\n /** Extract the branded Service instances provided by a Layer. */\n export type Provided<L extends LayerInput> = ProvidedEnvironment<L>\n\n /** Extract the external Service requirements of a Layer. */\n export type Required<L extends LayerInput> = RequiredEnvironment<L>\n\n /** Extract the Services still missing from a Layer composition. */\n export type Missing<L extends LayerInput> = RequiredEnvironment<L>\n\n /** Validate a Layer's requirements and input shape. */\n export type Complete<L extends LayerInput> = CompleteInput<L>\n}\n","/** Thrown when Scope context is accessed outside an active Scope execution. */\nexport class ScopeRuntimeNotConfiguredError extends Error {\n constructor() {\n super('No Scope is available in the current execution context')\n\n this.name = 'ScopeRuntimeNotConfiguredError'\n }\n}\n\n/** Thrown when a resource or finalizer is added after Scope closure begins. */\nexport class ScopeClosedError extends Error {\n constructor() {\n super('Cannot add resources or finalizers to a closed Scope')\n\n this.name = 'ScopeClosedError'\n }\n}\n\n/** Aggregates finalizer failures encountered while closing a Scope. */\nexport class ScopeCloseError extends Error {\n constructor(readonly causes: readonly unknown[]) {\n super(\n `Failed to close Scope (${causes.length} finalizer${causes.length === 1 ? '' : 's'} failed)`\n )\n\n this.name = 'ScopeCloseError'\n }\n}\n\n/** Thrown when a value has neither Symbol.dispose nor Symbol.asyncDispose. */\nexport class ResourceNotDisposableError extends Error {\n constructor() {\n super('Resource does not implement Symbol.dispose or Symbol.asyncDispose')\n\n this.name = 'ResourceNotDisposableError'\n }\n}\n","import type { ScopeFinalizer } from './types'\n\nconst SCOPE_SUCCESS = { status: 'success' } as const\n\ntype Disposer = (...args: never[]) => void | PromiseLike<void>\n\ntype DisposableCandidate = {\n [Symbol.dispose]?: Disposer\n\n [Symbol.asyncDispose]?: Disposer\n}\n\n/** Return a Scope finalizer for a value's async or sync disposal protocol. */\nexport const getDisposeFinalizer = <Resource>(resource: Resource): ScopeFinalizer | undefined => {\n // SAFETY: Object() provides a property-bearing view for protocol lookup; each method is checked for callability before invocation.\n const candidate = Object(resource) as DisposableCandidate\n const asyncDispose = candidate[Symbol.asyncDispose]\n\n if (asyncDispose instanceof Function) {\n return () => asyncDispose.call(resource)\n }\n\n const dispose = candidate[Symbol.dispose]\n\n if (dispose instanceof Function) {\n return () => dispose.call(resource)\n }\n\n return undefined\n}\n\n/** Dispose a value immediately when it implements a disposal protocol. */\nexport const disposeResource = <Resource>(resource: Resource): void | PromiseLike<void> => {\n const finalizer = getDisposeFinalizer(resource)\n\n return finalizer?.(SCOPE_SUCCESS)\n}\n","import { ScopeRuntimeNotConfiguredError } from './errors'\n\nimport type { Scope } from './scope'\n\nimport {\n activeRuntimeContextStorage,\n currentRuntimeContext,\n getRuntimeContext,\n makeRuntimeContext,\n runRuntimeContext\n} from '../runtime/context'\n\nimport type { RuntimeContextStorage } from '../runtime/context'\n\nconst scopeStorages = new WeakMap<object, RuntimeContextStorage>()\n\n/** Bridges the current Scope through async execution context. */\nexport class ScopeRuntime {\n /** Supply a Scope while invoking a callback. */\n static run<A>(\n scope: Scope,\n program: () => A,\n storage: RuntimeContextStorage = scopeStorages.get(scope) ?? activeRuntimeContextStorage()\n ): A {\n scopeStorages.set(scope, storage)\n\n const current = getRuntimeContext(storage)\n const context = makeRuntimeContext(\n current?.resolver,\n scope,\n current?.resolutionPath ?? [],\n current?.signal\n )\n\n return runRuntimeContext(storage, context, program)\n }\n\n /** Return the Scope active in the current execution context. */\n static current(): Scope {\n let context\n\n try {\n context = currentRuntimeContext()\n } catch {\n throw new ScopeRuntimeNotConfiguredError()\n }\n\n if (!context.scope) {\n throw new ScopeRuntimeNotConfiguredError()\n }\n\n return context.scope\n }\n\n /** Associate a Runtime-owned Scope with its context storage. */\n static bind(scope: Scope, storage: RuntimeContextStorage): void {\n scopeStorages.set(scope, storage)\n }\n}\n","import { ScopeCloseError } from './errors'\n\nimport { ScopeRuntime } from './runtime'\n\nimport type { CloseableScope } from './scope'\n\nimport {\n runRuntimeContext,\n type RuntimeContext,\n type RuntimeContextStorage\n} from '../runtime/context'\n\nimport type { CleanupFailureDiagnostic, MaybePromise, ScopeOutcome } from './types'\n\nexport type OutcomeClassifier<A> = (value: A) => ScopeOutcome\n\nexport type RunScopedOptions<A> = {\n readonly classify: OutcomeClassifier<A>\n readonly onCleanupFailure?: (diagnostic: CleanupFailureDiagnostic) => MaybePromise<void>\n readonly contextStorage?: RuntimeContextStorage\n readonly context?: RuntimeContext\n}\n\nconst notifyCleanupFailure = async (\n observer: ((diagnostic: CleanupFailureDiagnostic) => MaybePromise<void>) | undefined,\n diagnostic: CleanupFailureDiagnostic\n): Promise<void> => {\n if (!observer) {\n return\n }\n\n try {\n await observer(diagnostic)\n } catch {\n // Cleanup diagnostics are best effort and never affect the primary result.\n }\n}\n\nexport const runScoped = async <A>(\n scope: CloseableScope,\n program: () => A | PromiseLike<A>,\n options: RunScopedOptions<Awaited<A>>\n): Promise<Awaited<A>> => {\n let value!: Awaited<A>\n\n let programFailed = false\n let programFailure: unknown\n\n try {\n const run = () => ScopeRuntime.run(scope, program, options.contextStorage)\n\n value = await (options.context && options.contextStorage\n ? runRuntimeContext(options.contextStorage, options.context, run)\n : run())\n } catch (cause) {\n programFailed = true\n programFailure = cause\n }\n\n const outcome: ScopeOutcome = programFailed\n ? {\n status: 'failure',\n cause: programFailure\n }\n : options.classify(value)\n\n let cleanupFailed = false\n let cleanupFailure: unknown\n\n try {\n await scope.close(outcome)\n } catch (cause) {\n cleanupFailed = true\n cleanupFailure = cause\n }\n\n if (cleanupFailed) {\n const error =\n cleanupFailure instanceof ScopeCloseError\n ? cleanupFailure\n : new ScopeCloseError([cleanupFailure])\n\n await notifyCleanupFailure(options.onCleanupFailure, {\n outcome,\n error\n })\n\n cleanupFailure = error\n }\n\n if (programFailed) {\n throw programFailure\n }\n\n if (outcome.status === 'failure') {\n return value\n }\n\n if (cleanupFailed) {\n throw cleanupFailure\n }\n\n return value\n}\n","import { ResourceNotDisposableError, ScopeCloseError, ScopeClosedError } from './errors'\n\nimport { getDisposeFinalizer } from './disposable'\n\nimport { runScoped } from './internal'\n\nimport { ScopeRuntime } from './runtime'\n\nimport type { DisposableResource, MaybePromise, ScopeFinalizer, ScopeOutcome } from './types'\n\n/**\n * Non-owning lifecycle context for finalizers and child Scopes.\n *\n * A Scope can register cleanup and create children, but it cannot close\n * itself. Use `Scope.make()` or `Scope.run()` when your code owns the Scope.\n */\nexport interface Scope {\n /** Register a finalizer that runs when the owning Scope closes. */\n addFinalizer(finalizer: ScopeFinalizer): void\n\n /** Acquire a resource and register its outcome-aware release callback. */\n acquire<R>(\n acquire: () => MaybePromise<R>,\n release: (resource: R, outcome: ScopeOutcome) => MaybePromise<void>\n ): Promise<R>\n\n /** Register an already-acquired disposable resource. */\n add<R extends DisposableResource>(resource: R): Promise<R>\n\n /** Create a child Scope owned by this Scope. */\n fork(): CloseableScope\n}\n\n/** A Scope whose owner is responsible for calling `close()`. */\nexport interface CloseableScope extends Scope {\n /** Close the Scope and run children and finalizers in child-first LIFO order. */\n close(outcome?: ScopeOutcome): Promise<void>\n}\n\nconst SCOPE_SUCCESS: ScopeOutcome = Object.freeze({ status: 'success' })\n\nclass ScopeImpl implements CloseableScope {\n private readonly children = new Set<ScopeImpl>()\n\n private readonly finalizers: ScopeFinalizer[] = []\n\n private closePromise: Promise<void> | undefined\n\n private closeOutcome: ScopeOutcome | undefined\n\n constructor(private parent?: ScopeImpl) {}\n\n fork(): CloseableScope {\n this.assertOpen()\n\n const child = new ScopeImpl(this)\n\n this.children.add(child)\n\n return child\n }\n\n addFinalizer(finalizer: ScopeFinalizer): void {\n this.assertOpen()\n\n this.finalizers.push(finalizer)\n }\n\n async acquire<R>(\n acquire: () => MaybePromise<R>,\n release: (resource: R, outcome: ScopeOutcome) => MaybePromise<void>\n ): Promise<R> {\n this.assertOpen()\n\n const resource = await acquire()\n\n try {\n this.addFinalizer((outcome) => release(resource, outcome))\n\n return resource\n } catch (scopeFailure) {\n try {\n await release(resource, this.closeOutcome ?? SCOPE_SUCCESS)\n } catch (releaseFailure) {\n throw new AggregateError(\n [scopeFailure, releaseFailure],\n 'Scope closed while acquiring a resource and immediate cleanup also failed'\n )\n }\n\n throw scopeFailure\n }\n }\n\n async add<R extends DisposableResource>(resource: R): Promise<R> {\n const finalizer = getDisposeFinalizer(resource)\n\n if (!finalizer) {\n throw new ResourceNotDisposableError()\n }\n\n try {\n this.addFinalizer(finalizer)\n\n return resource\n } catch (scopeFailure) {\n try {\n await finalizer(this.closeOutcome ?? SCOPE_SUCCESS)\n } catch (releaseFailure) {\n throw new AggregateError(\n [scopeFailure, releaseFailure],\n 'Scope closed while adding a disposable resource and cleanup also failed'\n )\n }\n\n throw scopeFailure\n }\n }\n\n close(outcome: ScopeOutcome = SCOPE_SUCCESS): Promise<void> {\n if (this.closePromise) {\n return this.closePromise\n }\n\n this.closeOutcome = outcome\n this.closePromise = ScopeRuntime.run(this, () => this.closeInternal(outcome))\n\n return this.closePromise\n }\n\n private async closeInternal(outcome: ScopeOutcome): Promise<void> {\n const failures: unknown[] = []\n\n const children = [...this.children]\n\n this.children.clear()\n\n for (let index = children.length - 1; index >= 0; index--) {\n const child = children[index]\n\n if (!child) {\n continue\n }\n\n try {\n await child.close(outcome)\n } catch (cause) {\n if (cause instanceof ScopeCloseError) {\n failures.push(...cause.causes)\n } else {\n failures.push(cause)\n }\n }\n }\n\n for (let index = this.finalizers.length - 1; index >= 0; index--) {\n const finalizer = this.finalizers[index]\n\n if (!finalizer) {\n continue\n }\n\n try {\n await finalizer(outcome)\n } catch (cause) {\n failures.push(cause)\n }\n }\n\n this.finalizers.length = 0\n\n this.detach()\n\n if (failures.length > 0) {\n throw new ScopeCloseError(failures)\n }\n }\n\n private detach(): void {\n const parent = this.parent\n\n if (!parent) {\n return\n }\n\n parent.children.delete(this)\n this.parent = undefined\n }\n\n private assertOpen(): void {\n if (this.closePromise) {\n throw new ScopeClosedError()\n }\n }\n}\n\nexport const Scope = {\n /** Create an owned, initially open Scope. */\n make(): CloseableScope {\n return new ScopeImpl()\n },\n\n /** Return the non-owning Scope available in the current execution context. */\n current(): Scope {\n return ScopeRuntime.current()\n },\n\n /** Run a callback with an existing Scope supplied as the current context. */\n provide<A>(scope: Scope, program: () => A): A {\n return ScopeRuntime.run(scope, program)\n },\n\n /** Resolve the current Scope through `yield* Scope` inside an Effect. */\n // oxlint-disable-next-line require-yield\n *[Symbol.iterator](): Generator<never, Scope, unknown> {\n return ScopeRuntime.current()\n },\n\n /**\n * Run a program in a newly owned Scope.\n *\n * Scope is independent from `better-result`, so returned values—including\n * `Result.err`—close this Scope with a successful outcome. Result-aware\n * outcome classification belongs to `Runtime.run`.\n *\n * @example\n * ```ts\n * await Scope.run(async (scope) => {\n * const connection = await scope.acquire(connect, (connection) => connection.close())\n * return connection.query()\n * })\n * ```\n */\n run<A>(program: (scope: Scope) => A | PromiseLike<A>): Promise<Awaited<A>> {\n const scope = new ScopeImpl()\n\n return runScoped(scope, () => program(scope), {\n classify: () => SCOPE_SUCCESS\n })\n }\n} as const\n\n/** Type-level aliases for Scope ownership, outcomes, and cleanup contracts. */\nexport declare namespace Scope {\n /** A Scope whose owner is responsible for calling `close()`. */\n export type Closeable = CloseableScope\n\n /** The outcome supplied to Scope finalizers and resource releases. */\n export type Outcome = ScopeOutcome\n\n /** A cleanup callback registered with a Scope. */\n export type Finalizer = ScopeFinalizer\n\n /** A value implementing a JavaScript disposal protocol. */\n export type Disposable = DisposableResource\n}\n","import { Result } from 'better-result'\n\nimport type { Result as ResultType } from 'better-result'\n\nimport type { AnyService } from '../service'\nimport { isPromiseLike } from '../utils/runtime'\nimport type { Effect, EffectError, EffectRequirements, EffectSuccess } from './types'\n\ntype EffectInput<A, E> = ResultType<A, E> | PromiseLike<ResultType<A, E>>\n\ntype AnyEffectInput = EffectInput<any, any>\ntype AnyEffectValue = ResultType<any, any>\ntype AnyAsyncEffectInput = PromiseLike<ResultType<any, any>>\ntype CombinatorCallback = (value: any) => any\ntype CombinatorInput = AnyEffectInput | CombinatorCallback\n\ntype PreserveAsync<Input, Output> = Input extends PromiseLike<unknown> ? Promise<Output> : Output\n\ntype MappedResult<Input, B> = Effect<B, EffectError<Input>, EffectRequirements<Input>>\n\ntype ErrorMappedResult<Input, E2> = Effect<EffectSuccess<Input>, E2, EffectRequirements<Input>>\n\ntype ChainedResult<First, Next> = Effect<\n EffectSuccess<Next>,\n EffectError<First> | EffectError<Next>,\n EffectRequirements<First> | EffectRequirements<Next>\n>\n\ntype ChainedOutput<First, Next> = ChainedResult<First, Next>\n\ntype AsyncChainedOutput<First, Next> = Promise<ChainedResult<First, Next>>\n\ntype MapOperation<A, B> = {\n <Input>(effect: Input & EffectInput<A, any>): PreserveAsync<Input, MappedResult<Input, B>>\n}\n\ntype MapErrorOperation<E1, E2> = {\n <Input>(effect: Input & EffectInput<any, E1>): PreserveAsync<Input, ErrorMappedResult<Input, E2>>\n}\n\ntype AndThenOperation<Next> = {\n <Input>(effect: Input & AnyEffectValue): ChainedOutput<Input, Next>\n}\n\ntype AndThenAsyncOperation<A, Next> = {\n <Input>(effect: Input & EffectInput<A, any>): AsyncChainedOutput<Input, Next>\n}\n\nconst mapResult = <A, B, E, Requirements extends AnyService>(\n result: ResultType<A, E>,\n fn: (value: A) => B\n): Effect<B, E, Requirements> => {\n // SAFETY: Result.map changes only the success channel; the declaration-only Effect marker is restored by this adapter.\n return Result.map(result, fn) as Effect<B, E, Requirements>\n}\n\nconst mapErrorResult = <A, E1, E2, Requirements extends AnyService>(\n result: ResultType<A, E1>,\n fn: (error: E1) => E2\n): Effect<A, E2, Requirements> => {\n // SAFETY: Result.mapError changes only the error channel; the declaration-only Effect marker is restored by this adapter.\n return Result.mapError(result, fn) as Effect<A, E2, Requirements>\n}\n\nconst andThenResult = <\n A,\n B,\n E1,\n E2,\n Requirements1 extends AnyService,\n Requirements2 extends AnyService\n>(\n result: ResultType<A, E1>,\n next: (value: A) => ResultType<B, E2>\n): Effect<B, E1 | E2, Requirements1 | Requirements2> => {\n // SAFETY: The public callback returns an Effect, whose only runtime contract is the underlying Result.\n const resultNext = next as (value: A) => ResultType<B, E2>\n\n // SAFETY: Result.andThen unions Result errors; the declaration-only Effect marker is restored by this adapter.\n return Result.andThen(result, resultNext) as Effect<B, E1 | E2, Requirements1 | Requirements2>\n}\n\nconst andThenAsyncResult = <\n A,\n B,\n E1,\n E2,\n Requirements1 extends AnyService,\n Requirements2 extends AnyService\n>(\n result: ResultType<A, E1>,\n next: (value: A) => PromiseLike<ResultType<B, E2>>\n): Promise<Effect<B, E1 | E2, Requirements1 | Requirements2>> => {\n // SAFETY: The public callback returns an Effect, whose only runtime contract is the underlying Result.\n const resultNext = (value: A) => {\n // SAFETY: Promise resolution preserves the callback's Result value; only declaration-only Effect metadata is erased.\n return Promise.resolve(next(value)) as Promise<ResultType<B, E2>>\n }\n\n // SAFETY: Result.andThenAsync unions Result errors; the declaration-only Effect marker is restored by this adapter.\n return Result.andThenAsync(result, resultNext) as Promise<\n Effect<B, E1 | E2, Requirements1 | Requirements2>\n >\n}\n\n/**\n * Map the successful value of a Result or Effect result.\n *\n * Supports both data-first and data-last forms and preserves asynchronous\n * results and declaration-only Service requirements.\n *\n * @example\n * ```ts\n * const doubled = Effect.map(Result.ok(2), (value) => value * 2)\n * const toLabel = Effect.map((value: number) => `#${value}`)\n * ```\n */\nexport function map<A, B>(fn: (value: A) => B): MapOperation<A, B>\nexport function map<Input, B>(\n effect: Input & AnyEffectInput,\n fn: (value: EffectSuccess<Input>) => B\n): PreserveAsync<Input, MappedResult<Input, B>>\nexport function map(first: CombinatorInput, second?: CombinatorCallback): any {\n if (first instanceof Function && second === undefined) {\n // SAFETY: The curried overload accepts a unary mapping callback in this branch.\n const callback = first as CombinatorCallback\n\n return (effect: AnyEffectInput) => {\n // SAFETY: The overload implementation has already established the callback and Effect input positions.\n return map(effect as never, callback as never)\n }\n }\n\n // SAFETY: The data-first overload requires the second argument to be a unary mapping callback.\n const fn = second as CombinatorCallback\n\n if (isPromiseLike(first)) {\n return Promise.resolve(first).then((result) => {\n // SAFETY: Result is the runtime representation shared by Effect and better-result.\n return mapResult(result as ResultType<any, any>, fn)\n })\n }\n\n // SAFETY: The data-first overload supplies a Result-compatible Effect value.\n return mapResult(first as ResultType<any, any>, fn)\n}\n\n/**\n * Map the error value of a Result or Effect result while preserving its\n * successful value, asynchronous shape, and declaration-only Service requirements.\n *\n * @example\n * ```ts\n * const labelled = Effect.mapError(Result.err('missing'), (error) => ({ error }))\n * ```\n */\nexport function mapError<E1, E2>(fn: (error: E1) => E2): MapErrorOperation<E1, E2>\nexport function mapError<Input, E2>(\n effect: Input & AnyEffectInput,\n fn: (error: EffectError<Input>) => E2\n): PreserveAsync<Input, ErrorMappedResult<Input, E2>>\nexport function mapError(first: CombinatorInput, second?: CombinatorCallback): any {\n if (first instanceof Function && second === undefined) {\n // SAFETY: The curried overload accepts a unary error-mapping callback in this branch.\n const callback = first as CombinatorCallback\n\n return (effect: AnyEffectInput) => {\n // SAFETY: The overload implementation has already established the callback and Effect input positions.\n return mapError(effect as never, callback as never)\n }\n }\n\n // SAFETY: The data-first overload requires the second argument to be a unary error-mapping callback.\n const fn = second as CombinatorCallback\n\n if (isPromiseLike(first)) {\n return Promise.resolve(first).then((result) => {\n // SAFETY: Result is the runtime representation shared by Effect and better-result.\n return mapErrorResult(result as ResultType<any, any>, fn)\n })\n }\n\n // SAFETY: The data-first overload supplies a Result-compatible Effect value.\n return mapErrorResult(first as ResultType<any, any>, fn)\n}\n\n/**\n * Chain a synchronous Result-producing operation after a successful result.\n *\n * The next operation is skipped when the input is an error. Both error types\n * and both sets of Service requirements are preserved in the output.\n *\n * @example\n * ```ts\n * const user = Effect.andThen(Result.ok('u1'), (id) => repository.find(id))\n * ```\n */\nexport function andThen<A, Next extends AnyEffectValue>(\n next: (value: A) => Next\n): AndThenOperation<Next>\nexport function andThen<Input, Next extends AnyEffectValue>(\n effect: Input & AnyEffectValue,\n next: (value: EffectSuccess<Input>) => Next\n): ChainedOutput<Input, Next>\nexport function andThen(first: CombinatorInput, second?: CombinatorCallback): any {\n if (first instanceof Function && second === undefined) {\n // SAFETY: The curried overload accepts a unary continuation in this branch.\n const callback = first as CombinatorCallback\n\n return (effect: AnyEffectInput) => {\n // SAFETY: The overload implementation has already established the callback and Effect input positions.\n return andThen(effect as never, callback as never)\n }\n }\n\n // SAFETY: The data-first overload requires the second argument to return a Result.\n const next = second as CombinatorCallback\n\n // SAFETY: The data-first overload supplies a Result-compatible Effect value.\n return andThenResult(first as ResultType<any, any>, next)\n}\n\n/**\n * Chain an asynchronous Result-producing operation after a successful result.\n *\n * The returned value is always a Promise and retains both operations' error\n * and Service-requirement metadata.\n *\n * @example\n * ```ts\n * const user = Effect.andThenAsync(loadUser(), (user) => fetchProfile(user.id))\n * ```\n */\nexport function andThenAsync<A, Next extends AnyAsyncEffectInput>(\n next: (value: A) => Next\n): AndThenAsyncOperation<A, Next>\nexport function andThenAsync<Input, Next extends AnyAsyncEffectInput>(\n effect: Input & AnyEffectInput,\n next: (value: EffectSuccess<Input>) => Next\n): AsyncChainedOutput<Input, Next>\nexport function andThenAsync(first: CombinatorInput, second?: CombinatorCallback): any {\n if (first instanceof Function && second === undefined) {\n // SAFETY: The curried overload accepts a unary asynchronous continuation in this branch.\n const callback = first as CombinatorCallback\n\n return (effect: AnyEffectInput) => {\n // SAFETY: The overload implementation has already established the callback and Effect input positions.\n return andThenAsync(effect as never, callback as never)\n }\n }\n\n // SAFETY: The data-first overload requires the second argument to return a PromiseLike Effect.\n const next = second as CombinatorCallback\n\n if (isPromiseLike(first)) {\n return Promise.resolve(first).then((result) => {\n // SAFETY: Result is the runtime representation shared by Effect and better-result.\n return andThenAsyncResult(result as ResultType<any, any>, next)\n })\n }\n\n // SAFETY: The data-first overload supplies a Result-compatible Effect value.\n return andThenAsyncResult(first as ResultType<any, any>, next)\n}\n","import { Result } from 'better-result'\n\nimport type { Err, Result as ResultType, UnhandledException } from 'better-result'\n\nimport { Scope } from '../scope'\n\nimport type { DisposableResource, MaybePromise, ScopeOutcome } from '../scope'\nimport type { AnyService } from '../service'\n\nimport type {\n AnyEffect,\n Effect as EffectType,\n EffectError,\n EffectFromGenerator,\n EffectRequirements,\n EffectSuccess,\n EffectYield,\n Program as ProgramType,\n ProgramFromGenerator\n} from './types'\n\nimport { andThen, andThenAsync, map, mapError } from './combinators'\n\nexport type Effect<A, E, R extends AnyService = never> = EffectType<A, E, R>\n\ntype LazyProgram<A, E, R extends AnyService = never> = ProgramType<A, E, R>\n\n/** A nominal lazy computation that produces an Effect when invoked. */\nexport type Program<A, E, R extends AnyService = never> = LazyProgram<A, E, R>\n\ntype AnyResult = ResultType<any, any>\n\ntype EffectGenerator =\n | (() => Generator<EffectYield, AnyResult, unknown>)\n | (() => AsyncGenerator<EffectYield, AnyResult, unknown>)\n\ntype RuntimeResultGenerator = (body: EffectGenerator) => AnyResult | Promise<AnyResult>\n\n// SAFETY: Service iterators yield no runtime markers, so Result.gen receives only the Err values that exist at runtime.\nconst runResultGenerator = Result.gen as RuntimeResultGenerator\n\n/**\n * Compose `better-result` operations while preserving Service requirements in\n * a declaration-only type channel.\n *\n * A generator may yield Service tokens and Result operations. It must return a\n * `Result` as its final value; Service yields are resolved by the active\n * Runtime and do not add runtime values to the Result stream.\n * Use `fn` when generator execution should wait for a Runtime boundary.\n *\n * @example\n * ```ts\n * const loadUser = Effect.gen(async function* () {\n * const database = yield* Database\n * const user = yield* Result.await(database.findUser('u1'))\n *\n * return Result.ok(user)\n * })\n * ```\n */\nexport function gen<Yield extends EffectYield, Returned extends AnyResult>(\n body: () => Generator<Yield, Returned, unknown>\n): EffectFromGenerator<Yield, Returned>\n\nexport function gen<Yield extends EffectYield, Returned extends AnyResult>(\n body: () => AsyncGenerator<Yield, Returned, unknown>\n): Promise<EffectFromGenerator<Yield, Returned>>\n\nexport function gen(body: EffectGenerator): AnyResult | Promise<AnyResult> {\n return runResultGenerator(body)\n}\n\n/** Build a lazy Program without running its generator. */\nexport function fn<Yield extends EffectYield, Returned extends AnyResult>(\n body: () => Generator<Yield, Returned, unknown>\n): ProgramFromGenerator<Yield, Returned>\n\nexport function fn<Yield extends EffectYield, Returned extends AnyResult>(\n body: () => AsyncGenerator<Yield, Returned, unknown>\n): ProgramFromGenerator<Yield, Returned>\n\nexport function fn(body: EffectGenerator): Program<any, any, AnyService> {\n const program = () => runResultGenerator(body)\n\n // SAFETY: The generator overloads derive the Program channels; this cast only adds the declaration-only nominal marker.\n return program as Program<any, any, AnyService>\n}\n\n/**\n * Acquire a resource in the current Scope and register its release callback.\n *\n * Acquisition failures are represented in the Effect Result error channel;\n * release failures remain owned by Scope cleanup. The release callback\n * receives the final outcome chosen by the enclosing execution boundary.\n *\n * @example\n * ```ts\n * const connection = yield* Effect.acquireRelease(\n * () => pool.connect(),\n * (connection, outcome) => connection.close(outcome)\n * )\n * ```\n */\nexport function acquireRelease<R>(\n acquire: () => MaybePromise<R>,\n release: (resource: R, outcome: ScopeOutcome) => MaybePromise<void>\n): AsyncGenerator<Err<never, UnhandledException>, R, unknown> {\n const scope = Scope.current()\n\n return Result.await(Result.tryPromise(() => scope.acquire(acquire, release)))\n}\n\n/**\n * Register an already-acquired disposable resource in the current Scope.\n *\n * The resource is not acquired by this helper. Registration failures are\n * represented in the Effect Result error channel; disposal failures remain\n * owned by Scope cleanup.\n *\n * @example\n * ```ts\n * const file = yield* Effect.add(await openFile('notes.txt'))\n * ```\n */\nexport function add<R extends DisposableResource>(\n resource: R\n): AsyncGenerator<Err<never, UnhandledException>, R, unknown> {\n const scope = Scope.current()\n\n return Result.await(Result.tryPromise(() => scope.add(resource)))\n}\n\n/**\n * Effect namespace containing generator, resource, and Result combinators.\n *\n * Prefer these helpers when a program needs typed Service requirements or\n * Scope-aware acquisition and cleanup.\n */\nexport const Effect = {\n /** Compose a generator-based Effect program. */\n gen,\n /** Build a lazy Program from a generator. */\n fn,\n /** Acquire and register a resource in the current Scope. */\n acquireRelease,\n /** Register an already-acquired disposable in the current Scope. */\n add,\n /** Map a successful Effect result. */\n map,\n /** Map an Effect error. */\n mapError,\n /** Chain a synchronous Effect result. */\n andThen,\n /** Chain an asynchronous Effect result. */\n andThenAsync\n} as const\n\n/** Type-level aliases for inspecting Effect result channels and requirements. */\nexport declare namespace Effect {\n /** A nominal lazy computation that produces an Effect when invoked. */\n export type Program<A, E, R extends AnyService = never> = LazyProgram<A, E, R>\n\n /** Extract the success channel from an Effect result or Promise. */\n export type Success<T> = EffectSuccess<T>\n\n /** Extract the error channel from an Effect result or Promise. */\n export type Error<T> = EffectError<T>\n\n /** Extract the Service requirements from an Effect result or Promise. */\n export type Requirements<T> = EffectRequirements<T>\n\n /** An Effect with erased success, error, and requirements. */\n export type Any = AnyEffect\n}\n","type Unary<A, B> = (value: A) => B\n\n/**\n * Compose a value through a sequence of unary functions.\n *\n * `pipe` is deliberately independent of Effect, Result, Promise, Scope, and\n * Service metadata.\n *\n * @example\n * ```ts\n * const label = pipe(\n * 'alice',\n * (name) => name.trim(),\n * (name) => name.toUpperCase()\n * )\n * ```\n */\ntype PipeRuntimeValue = Parameters<Unary<any, any>>[0]\n\ntype PipeRuntimeOperation = Unary<PipeRuntimeValue, PipeRuntimeValue>\n\nexport function pipe<A>(value: A): A\nexport function pipe<A, B>(value: A, ab: Unary<A, B>): B\nexport function pipe<A, B, C>(value: A, ab: Unary<A, B>, bc: Unary<B, C>): C\nexport function pipe<A, B, C, D>(value: A, ab: Unary<A, B>, bc: Unary<B, C>, cd: Unary<C, D>): D\nexport function pipe<A, B, C, D, E>(\n value: A,\n ab: Unary<A, B>,\n bc: Unary<B, C>,\n cd: Unary<C, D>,\n de: Unary<D, E>\n): E\nexport function pipe<A, B, C, D, E, F>(\n value: A,\n ab: Unary<A, B>,\n bc: Unary<B, C>,\n cd: Unary<C, D>,\n de: Unary<D, E>,\n ef: Unary<E, F>\n): F\nexport function pipe<A, B, C, D, E, F, G>(\n value: A,\n ab: Unary<A, B>,\n bc: Unary<B, C>,\n cd: Unary<C, D>,\n de: Unary<D, E>,\n ef: Unary<E, F>,\n fg: Unary<F, G>\n): G\nexport function pipe<A, B, C, D, E, F, G, H>(\n value: A,\n ab: Unary<A, B>,\n bc: Unary<B, C>,\n cd: Unary<C, D>,\n de: Unary<D, E>,\n ef: Unary<E, F>,\n fg: Unary<F, G>,\n gh: Unary<G, H>\n): H\nexport function pipe<A, B, C, D, E, F, G, H, I>(\n value: A,\n ab: Unary<A, B>,\n bc: Unary<B, C>,\n cd: Unary<C, D>,\n de: Unary<D, E>,\n ef: Unary<E, F>,\n fg: Unary<F, G>,\n gh: Unary<G, H>,\n hi: Unary<H, I>\n): I\nexport function pipe<A, B, C, D, E, F, G, H, I, J>(\n value: A,\n ab: Unary<A, B>,\n bc: Unary<B, C>,\n cd: Unary<C, D>,\n de: Unary<D, E>,\n ef: Unary<E, F>,\n fg: Unary<F, G>,\n gh: Unary<G, H>,\n hi: Unary<H, I>,\n ij: Unary<I, J>\n): J\nexport function pipe<A, B, C, D, E, F, G, H, I, J, K>(\n value: A,\n ab: Unary<A, B>,\n bc: Unary<B, C>,\n cd: Unary<C, D>,\n de: Unary<D, E>,\n ef: Unary<E, F>,\n fg: Unary<F, G>,\n gh: Unary<G, H>,\n hi: Unary<H, I>,\n ij: Unary<I, J>,\n jk: Unary<J, K>\n): K\nexport function pipe(\n value: PipeRuntimeValue,\n ...operations: ReadonlyArray<PipeRuntimeOperation>\n): PipeRuntimeValue {\n return operations.reduce((current, operation) => operation(current), value)\n}\n","import { TaggedError } from 'better-result'\n\n/** Describes a failure encountered while releasing a Resource. */\nexport class ResourceReleaseFailure extends TaggedError('ResourceReleaseFailure')<{\n readonly resource: string\n readonly cause: unknown\n readonly message: string\n}> {}\n","import { Result, type Result as ResultType, type UnhandledException } from 'better-result'\n\nimport { ResourceReleaseFailure } from './errors'\n\nimport { disposeResource } from '../scope/disposable'\n\nexport { disposeResource }\n\nimport type { AsyncResult, MaybePromise, ReleaseFailureObserver, ReleaseOutcome } from './types'\n\nconst toReleaseFailure = (resource: string, cause: unknown): ResourceReleaseFailure =>\n new ResourceReleaseFailure({\n resource,\n cause,\n message: `Failed to release resource: ${resource}`\n })\n\nexport const runResult = async <T, E>(\n operation: () => AsyncResult<T, E>\n): Promise<ResultType<T, E | UnhandledException>> => {\n const execution = await Result.tryPromise(() => Promise.resolve(operation()))\n\n return execution.andThen((result) => result)\n}\n\nconst normalizeReleaseOutcome = (\n name: string,\n outcome: ReleaseOutcome\n): ResultType<void, ResourceReleaseFailure> => {\n if (outcome === undefined) {\n return Result.ok()\n }\n\n return outcome.mapError((cause) => toReleaseFailure(name, cause))\n}\n\nexport const runRelease = async <R>(\n name: string,\n resource: R,\n release: (resource: R) => MaybePromise<ReleaseOutcome>\n): Promise<ResultType<void, ResourceReleaseFailure>> => {\n const execution = await Result.tryPromise({\n try: () => Promise.resolve(release(resource)),\n catch: (cause) => toReleaseFailure(name, cause)\n })\n\n return execution.andThen((outcome) => normalizeReleaseOutcome(name, outcome))\n}\n\nconst notifyReleaseFailure = async (\n observer: ReleaseFailureObserver | undefined,\n\n failure: ResourceReleaseFailure\n): Promise<void> => {\n if (!observer) {\n return\n }\n\n try {\n await observer(failure)\n } catch {\n /*\n * Diagnostics must never replace\n * the actual operation error.\n */\n }\n}\n\nexport const combineUseAndRelease = async <A, E>(\n used: ResultType<A, E>,\n\n released: ResultType<void, ResourceReleaseFailure>,\n\n onReleaseFailure?: ReleaseFailureObserver\n): Promise<ResultType<A, E | ResourceReleaseFailure>> => {\n if (Result.isError(used)) {\n if (Result.isError(released)) {\n await notifyReleaseFailure(onReleaseFailure, released.error)\n }\n\n return Result.err<A, E | ResourceReleaseFailure>(used.error)\n }\n\n if (Result.isError(released)) {\n await notifyReleaseFailure(onReleaseFailure, released.error)\n\n return Result.err<A, E | ResourceReleaseFailure>(released.error)\n }\n\n return Result.ok<A, E | ResourceReleaseFailure>(used.value)\n}\n","import { Result, type Result as ResultType, type UnhandledException } from 'better-result'\n\nimport { Scope } from '../scope'\n\nimport { ResourceReleaseFailure } from './errors'\n\nimport { combineUseAndRelease, disposeResource, runRelease, runResult } from './internal'\n\nimport type { AcquireUseReleaseOptions } from './types'\n\n/**\n * Acquire a resource, use it, and always attempt release afterward.\n *\n * Acquisition, use, and release may be synchronous or asynchronous Result\n * operations. If both use and release fail, the use error remains primary and\n * `onReleaseFailure` receives the cleanup failure as a diagnostic.\n *\n * When `release` is omitted, `Symbol.asyncDispose` is preferred over\n * `Symbol.dispose`.\n *\n * @example\n * ```ts\n * const result = await Resource.acquireUseRelease({\n * name: 'database connection',\n * acquire: () => connect(),\n * use: (connection) => query(connection),\n * release: (connection) => connection.close()\n * })\n * ```\n */\nconst acquireUseRelease = <R, A, AcquireError, UseError>({\n name,\n acquire,\n use,\n release = disposeResource,\n onReleaseFailure\n}: AcquireUseReleaseOptions<R, A, AcquireError, UseError>): Promise<\n ResultType<A, AcquireError | UseError | UnhandledException | ResourceReleaseFailure>\n> =>\n Result.gen(async function* () {\n const resource = yield* Result.await(runResult(acquire))\n\n const scope = Scope.make()\n\n let released: ResultType<void, ResourceReleaseFailure> = Result.ok()\n\n scope.addFinalizer(async () => {\n released = await runRelease(name, resource, release)\n })\n\n const used = await runResult(() => use(resource))\n\n await scope.close()\n\n return await combineUseAndRelease(used, released, onReleaseFailure)\n })\n\nexport const Resource = {\n /** Acquire, use, and release a resource with deterministic error precedence. */\n acquireUseRelease\n} as const\n","import { Result } from 'better-result'\n\nimport type { Result as ResultType } from 'better-result'\n\nimport type { LayerDisposeError } from '../layer/errors'\n\nimport type { LayerBackend } from '../layer/backend'\n\nimport type { CleanupFailureDiagnostic, MaybePromise, ScopeOutcome } from '../scope'\n\nimport type { RuntimeContextStorage } from './context'\n\nimport type { RuntimeObserver } from './observer'\n\n/** Aggregated cleanup information reported during Runtime shutdown. */\nexport type RuntimeShutdownDiagnostic = {\n /** Final outcome supplied to the Runtime root Scope. */\n readonly outcome: ScopeOutcome\n /** Aggregated root-Scope and backend cleanup failure. */\n readonly error: LayerDisposeError\n}\n\n/** Observer notified about cleanup failures without changing primary results. */\nexport type CleanupFailureObserver = (\n diagnostic: CleanupFailureDiagnostic | RuntimeShutdownDiagnostic\n) => MaybePromise<void>\n\n/** Optional Runtime configuration for cleanup diagnostics. */\nexport type RuntimeOptions = {\n /** Backend used to register and resolve the Layer. Defaults to MapLayerBackend. */\n readonly backend?: LayerBackend\n /** Resolve every Layer provider before Runtime.make resolves. */\n readonly warmup?: boolean\n /** Best-effort lifecycle and Service resolution observers. */\n readonly observers?: readonly RuntimeObserver[]\n /** Optional observer for best-effort cleanup diagnostics. */\n readonly onCleanupFailure?: CleanupFailureObserver\n /** Context storage used by Service, Scope and Layer resolution. */\n readonly contextStorage?: RuntimeContextStorage\n /** Optional signal exposed through the RuntimeContext. */\n readonly signal?: AbortSignal\n}\n\n/** Optional signal supplied to one managed Runtime execution. */\nexport type RuntimeRunOptions = {\n readonly signal?: AbortSignal\n}\n\n/** Cooperative shutdown policy for a managed Runtime. */\nexport type RuntimeDisposeOptions = {\n /** Time to let active executions settle before requesting cancellation. */\n readonly gracePeriod?: number\n /** Abort active execution signals after the grace period expires. */\n readonly abortAfterGracePeriod?: boolean\n}\n\ntype ResultLike = ResultType<any, any>\n\nconst isResultLike = <A>(value: A): value is A & ResultLike => {\n const candidate = Object(value)\n const tag = Object.prototype.toString.call(value)\n\n return (\n tag !== '[object Function]' &&\n 'status' in candidate &&\n (candidate.status === 'ok' || candidate.status === 'error')\n )\n}\n\nexport const classifyRuntimeOutcome = <A>(value: A): ScopeOutcome => {\n if (isResultLike(value) && Result.isError(value)) {\n return {\n status: 'failure',\n cause: value.error\n }\n }\n\n return {\n status: 'success'\n }\n}\n","import { currentRuntimeContext } from './context'\n\nconst neverAbortedSignal = new AbortController().signal\n\ntype SignalListener = readonly [AbortSignal, () => void]\n\nexport type AbortSignalLink = {\n readonly signal: AbortSignal\n readonly dispose: () => void\n}\n\n/** Link caller, Runtime and shutdown signals without owning the caller's controller. */\nexport const linkAbortSignals = (\n ...signals: readonly (AbortSignal | undefined)[]\n): AbortSignalLink => {\n const active = signals.filter((signal): signal is AbortSignal => signal !== undefined)\n\n if (active.length === 0) {\n return { signal: neverAbortedSignal, dispose: () => {} }\n }\n\n if (active.length === 1) {\n return { signal: active[0]!, dispose: () => {} }\n }\n\n const controller = new AbortController()\n const listeners: SignalListener[] = []\n let disposed = false\n\n const dispose = (): void => {\n if (disposed) {\n return\n }\n\n disposed = true\n\n for (const [source, listener] of listeners) {\n source.removeEventListener('abort', listener)\n }\n\n listeners.length = 0\n }\n\n const abortFrom = (source: AbortSignal): void => {\n if (controller.signal.aborted) {\n return\n }\n\n controller.abort(source.reason)\n dispose()\n }\n\n for (const source of active) {\n if (source.aborted) {\n abortFrom(source)\n break\n }\n\n const listener = (): void => abortFrom(source)\n listeners.push([source, listener])\n source.addEventListener('abort', listener, { once: true })\n }\n\n return { signal: controller.signal, dispose }\n}\n\n/** Return the current cooperative-cancellation signal. */\nexport const currentAbortSignal = (): AbortSignal =>\n currentRuntimeContext().signal ?? neverAbortedSignal\n\n/** Yieldable access to the signal of the current Runtime execution. */\nexport const CurrentAbortSignal = {\n // oxlint-disable-next-line require-yield\n *[Symbol.iterator](): Generator<never, AbortSignal, unknown> {\n return currentAbortSignal()\n }\n} as const\n","import type { AnyServiceToken } from '../service'\nimport type { Scope } from '../scope'\nimport type { ScopeOutcome } from '../scope'\nimport type { MaybePromise } from '../utils/types'\n\n/** Event emitted after a Service resolution attempt settles. */\nexport type RuntimeServiceResolveEvent = {\n readonly service: AnyServiceToken\n readonly resolutionPath: readonly AnyServiceToken[]\n readonly outcome: ScopeOutcome\n}\n\n/** Event emitted after a provider acquisition attempt settles. */\nexport type RuntimeServiceAcquireEvent = {\n readonly service: AnyServiceToken\n readonly resolutionPath: readonly AnyServiceToken[]\n readonly outcome: ScopeOutcome\n}\n\n/** Event emitted immediately before a program starts in an execution Scope. */\nexport type RuntimeExecutionStartEvent = {\n readonly scope: Scope\n}\n\n/** Event emitted after a program and its execution Scope settle. */\nexport type RuntimeExecutionEndEvent = {\n readonly scope: Scope\n readonly outcome: ScopeOutcome\n}\n\n/** Event emitted after a Layer provider release callback settles. */\nexport type RuntimeResourceReleaseEvent = {\n readonly service: AnyServiceToken\n readonly outcome: ScopeOutcome\n readonly error?: unknown\n}\n\n/** Optional best-effort hooks for Runtime lifecycle and resolution events. */\nexport type RuntimeObserver = {\n readonly onServiceResolve?: (event: RuntimeServiceResolveEvent) => MaybePromise<void>\n readonly onServiceAcquire?: (event: RuntimeServiceAcquireEvent) => MaybePromise<void>\n readonly onExecutionStart?: (event: RuntimeExecutionStartEvent) => MaybePromise<void>\n readonly onExecutionEnd?: (event: RuntimeExecutionEndEvent) => MaybePromise<void>\n readonly onResourceRelease?: (event: RuntimeResourceReleaseEvent) => MaybePromise<void>\n}\n\nexport const notifyRuntimeObservers = <Event>(\n observers: readonly RuntimeObserver[],\n select: (observer: RuntimeObserver) => ((event: Event) => MaybePromise<void>) | undefined,\n event: Event\n): void => {\n for (const observer of observers) {\n const callback = select(observer)\n\n if (!callback) {\n continue\n }\n\n try {\n void Promise.resolve(callback(event)).catch(() => {})\n } catch {\n // Observability must never change the Runtime result.\n }\n }\n}\n","import {\n CircularDependencyError,\n ServiceAcquisitionError,\n ServiceNotFoundError,\n type AnyServiceToken,\n type ServiceResolver\n} from '../service'\n\nimport { getRuntimeContext, makeRuntimeContext, runRuntimeContext } from '../runtime/context'\n\nimport { defaultRuntimeContextStorage } from '../runtime/default'\n\nimport type { RuntimeContextStorage } from '../runtime/context'\n\nimport { notifyRuntimeObservers, type RuntimeObserver } from '../runtime/observer'\n\nimport type { ScopeOutcome } from '../scope'\n\nimport { ServiceTagCollisionError } from './errors'\n\nconst findCycleStart = (path: readonly AnyServiceToken[], token: AnyServiceToken): number =>\n path.findIndex((current) => current.serviceTag === token.serviceTag)\n\nconst shouldPreserve = (cause: unknown): boolean =>\n cause instanceof CircularDependencyError ||\n cause instanceof ServiceAcquisitionError ||\n cause instanceof ServiceNotFoundError ||\n cause instanceof ServiceTagCollisionError\n\n/** Wrap a backend with Runtime-local resolution paths and acquisition errors. */\nexport const createResolutionResolver = (\n resolver: ServiceResolver,\n storage: RuntimeContextStorage = defaultRuntimeContextStorage,\n observers: readonly RuntimeObserver[] = []\n): ServiceResolver => {\n const wrapped: ServiceResolver = {\n async resolve<T extends AnyServiceToken>(token: T): Promise<InstanceType<T>> {\n const context = getRuntimeContext(storage)\n const path = context?.resolutionPath ?? []\n const cycleStart = findCycleStart(path, token)\n const resolutionPath = [...path, token]\n\n const notifyResolve = (outcome: ScopeOutcome): void => {\n notifyRuntimeObservers(observers, (observer) => observer.onServiceResolve, {\n service: token,\n resolutionPath,\n outcome\n })\n }\n\n if (cycleStart >= 0) {\n const error = new CircularDependencyError([...path.slice(cycleStart), token])\n notifyResolve({ status: 'failure', cause: error })\n throw error\n }\n\n const nextContext = makeRuntimeContext(\n wrapped,\n context?.scope,\n resolutionPath,\n context?.signal\n )\n\n return await runRuntimeContext(storage, nextContext, async () => {\n try {\n const instance = await resolver.resolve(token)\n notifyResolve({ status: 'success' })\n return instance\n } catch (cause) {\n if (shouldPreserve(cause)) {\n notifyResolve({ status: 'failure', cause })\n throw cause\n }\n\n const error = new ServiceAcquisitionError(token, resolutionPath, cause)\n notifyResolve({ status: 'failure', cause: error })\n throw error\n }\n })\n }\n }\n\n return wrapped\n}\n","import type { AnyService, AnyServiceToken, ServiceResolver } from '../service'\n\nimport { Scope, type CloseableScope } from '../scope'\nimport { runScoped } from '../scope/internal'\nimport { ScopeRuntime } from '../scope/runtime'\n\nimport {\n getRuntimeContext,\n makeRuntimeContext,\n runRuntimeContext,\n type RuntimeContextStorage\n} from '../runtime/context'\n\nimport { defaultRuntimeContextStorage } from '../runtime/default'\n\nimport {\n classifyRuntimeOutcome,\n type CleanupFailureObserver,\n type RuntimeDisposeOptions,\n type RuntimeOptions,\n type RuntimeRunOptions,\n type RuntimeShutdownDiagnostic\n} from '../runtime/outcome'\n\nimport { linkAbortSignals, type AbortSignalLink } from '../runtime/signal'\n\nimport { LayerDisposeError, LayerRegistrationError } from './errors'\n\nimport { createResolutionResolver } from './resolution'\n\nimport { notifyRuntimeObservers, type RuntimeObserver } from '../runtime/observer'\n\nimport type { LayerBackend } from './backend'\n\nimport { MapLayerBackend } from './map-layer-backend'\n\nimport type {\n CompleteExecution,\n CompleteExecutionLayer,\n CompleteInput,\n LayerInput,\n ProvidedEnvironment\n} from './inference'\n\nimport type { LayerRegistration } from './types'\n\nimport type { ScopeOutcome } from '../scope'\n\ntype LayerProvider = LayerInput['providers'][number]\n\ninterface RuntimeHandleCore<Provided extends AnyService> {\n /** The backend used to resolve this Layer's providers. */\n readonly backend: LayerBackend\n\n /** Run a program in a child Scope of the Layer's root Scope. */\n run<A>(program: CompleteExecution<Provided, A>, options?: RuntimeRunOptions): Promise<Awaited<A>>\n\n /** Run a program with providers owned by that execution's child Scope. */\n runWith<Request extends LayerInput, A>(\n layer: Request & CompleteExecutionLayer<Provided, Request>,\n program: CompleteExecution<Provided | ProvidedEnvironment<Request>, A>,\n options?: RuntimeRunOptions\n ): Promise<Awaited<A>>\n\n /** Resolve every registered provider before accepting normal executions. */\n warmup(): Promise<void>\n\n /** Stop new executions and release Layer-owned resources. */\n dispose(input?: RuntimeDisposeOptions | ScopeOutcome): Promise<void>\n}\n\n/** Runtime-facing handle that owns a Layer's resources and execution scopes. */\nexport type RuntimeHandle<Provided extends AnyService = any> = RuntimeHandleCore<Provided>\n\nconst SCOPE_SUCCESS: ScopeOutcome = Object.freeze({ status: 'success' })\n\nclass RuntimeHandleDisposedError extends Error {\n constructor() {\n super('Cannot run a program using a disposed Layer')\n\n this.name = 'RuntimeHandleDisposedError'\n }\n}\n\nconst normalizeDisposeCauses = (cause: unknown): readonly unknown[] => {\n if (cause instanceof AggregateError) {\n return [...cause.errors]\n }\n\n return [cause]\n}\n\nconst isScopeOutcome = (\n input: RuntimeDisposeOptions | ScopeOutcome | undefined\n): input is ScopeOutcome => input !== undefined && 'status' in input\n\nconst validateDisposeOptions = (options: RuntimeDisposeOptions): void => {\n const { gracePeriod } = options\n\n if (gracePeriod !== undefined && (!Number.isFinite(gracePeriod) || gracePeriod < 0)) {\n throw new RangeError('Runtime dispose gracePeriod must be a finite non-negative number')\n }\n}\n\ntype ActiveExecution = {\n readonly promise: Promise<unknown>\n}\n\nconst notifyShutdownFailure = async (\n observer: CleanupFailureObserver | undefined,\n diagnostic: RuntimeShutdownDiagnostic\n): Promise<void> => {\n if (!observer) {\n return\n }\n\n try {\n await observer(diagnostic)\n } catch {\n // Shutdown diagnostics are best effort and never affect the primary result.\n }\n}\n\nconst bindProviderToScope = (\n provider: LayerProvider,\n scope: CloseableScope,\n contextStorage: RuntimeContextStorage,\n resolver: ServiceResolver,\n observers: readonly RuntimeObserver[]\n): LayerRegistration => ({\n service: provider.service,\n\n acquire: () => {\n const current = getRuntimeContext(contextStorage)\n const context = makeRuntimeContext(\n resolver,\n scope,\n current?.resolutionPath ?? [],\n current?.signal\n )\n\n return runRuntimeContext(contextStorage, context, () =>\n ScopeRuntime.run(\n scope,\n async () => {\n const resolutionPath = current?.resolutionPath ?? [provider.service]\n\n try {\n const instance = provider.release\n ? await scope.acquire(\n () => provider.acquire(),\n async (resource, outcome) => {\n try {\n await provider.release!(resource, outcome)\n notifyRuntimeObservers(observers, (observer) => observer.onResourceRelease, {\n service: provider.service,\n outcome\n })\n } catch (cause) {\n notifyRuntimeObservers(observers, (observer) => observer.onResourceRelease, {\n service: provider.service,\n outcome,\n error: cause\n })\n throw cause\n }\n }\n )\n : await provider.acquire()\n\n notifyRuntimeObservers(observers, (observer) => observer.onServiceAcquire, {\n service: provider.service,\n resolutionPath,\n outcome: SCOPE_SUCCESS\n })\n\n return instance\n } catch (cause) {\n notifyRuntimeObservers(observers, (observer) => observer.onServiceAcquire, {\n service: provider.service,\n resolutionPath,\n outcome: {\n status: 'failure',\n cause\n }\n })\n throw cause\n }\n },\n contextStorage\n )\n )\n }\n})\n\n/** Resolve request-local providers first, then fall back to the Runtime root. */\nclass ExecutionLayerBackend implements LayerBackend {\n private readonly localTags = new Set<string>()\n\n constructor(\n private readonly local: MapLayerBackend,\n private readonly root: LayerBackend\n ) {}\n\n register(registration: LayerRegistration): void {\n this.localTags.add(registration.service.serviceTag)\n this.local.register(registration)\n }\n\n async resolve<T extends AnyServiceToken>(token: T): Promise<InstanceType<T>> {\n if (this.localTags.has(token.serviceTag)) {\n return await this.local.resolve(token)\n }\n\n return await this.root.resolve(token)\n }\n\n async disposeAll(): Promise<void> {\n await this.local.disposeAll()\n this.localTags.clear()\n }\n}\n\nclass RuntimeHandleImpl<Provided extends AnyService> implements RuntimeHandleCore<Provided> {\n private disposePromise: Promise<void> | undefined\n\n private warmupPromise: Promise<void> | undefined\n\n private readonly executions = new Set<ActiveExecution>()\n\n private readonly shutdownController = new AbortController()\n\n private state: 'active' | 'disposing' | 'disposed' = 'active'\n\n constructor(\n readonly backend: LayerBackend,\n private readonly resolver: ServiceResolver,\n private readonly rootScope: CloseableScope,\n private readonly onCleanupFailure: CleanupFailureObserver | undefined,\n private readonly contextStorage: RuntimeContextStorage,\n private readonly signal: AbortSignal | undefined,\n private readonly observers: readonly RuntimeObserver[],\n private readonly services: readonly AnyServiceToken[]\n ) {}\n\n run<A>(\n program: CompleteExecution<Provided, A>,\n options?: RuntimeRunOptions\n ): Promise<Awaited<A>> {\n this.assertActive()\n\n const executionScope = this.rootScope.fork()\n const signalLink = linkAbortSignals(\n this.signal,\n options?.signal,\n this.shutdownController.signal\n )\n\n return this.startExecution<Awaited<A>>(signalLink, () =>\n this.runExecution(executionScope, program, this.resolver, signalLink.signal)\n )\n }\n\n runWith<Request extends LayerInput, A>(\n layer: Request & CompleteExecutionLayer<Provided, Request>,\n program: CompleteExecution<Provided | ProvidedEnvironment<Request>, A>,\n options?: RuntimeRunOptions\n ): Promise<Awaited<A>> {\n this.assertActive()\n\n const executionScope = this.rootScope.fork()\n const localBackend = new MapLayerBackend()\n const backend = new ExecutionLayerBackend(localBackend, this.backend)\n const resolver = createResolutionResolver(backend, this.contextStorage, this.observers)\n const signalLink = linkAbortSignals(\n this.signal,\n options?.signal,\n this.shutdownController.signal\n )\n\n return this.startExecution<Awaited<A>>(signalLink, async (): Promise<Awaited<A>> => {\n try {\n return await this.runExecution<Awaited<A>>(\n executionScope,\n async (): Promise<Awaited<A>> => {\n for (const provider of layer.providers) {\n backend.register(\n bindProviderToScope(\n provider,\n executionScope,\n this.contextStorage,\n resolver,\n this.observers\n )\n )\n }\n\n return await program()\n },\n resolver,\n signalLink.signal\n )\n } finally {\n await localBackend.disposeAll()\n }\n })\n }\n\n warmup(): Promise<void> {\n this.assertActive()\n\n if (this.warmupPromise) {\n return this.warmupPromise\n }\n\n const warmup = runRuntimeContext(\n this.contextStorage,\n makeRuntimeContext(this.resolver, this.rootScope, [], this.signal),\n async () => {\n for (const service of this.services) {\n await this.resolver.resolve(service)\n }\n }\n )\n\n this.warmupPromise = warmup\n\n void warmup.then(\n () => {\n if (this.warmupPromise === warmup) {\n this.warmupPromise = undefined\n }\n },\n () => {\n if (this.warmupPromise === warmup) {\n this.warmupPromise = undefined\n }\n }\n )\n\n return warmup\n }\n\n private startExecution<A>(signalLink: AbortSignalLink, run: () => PromiseLike<A>): Promise<A> {\n let resolveExecution!: (value: A | PromiseLike<A>) => void\n let rejectExecution!: (cause?: unknown) => void\n\n const execution = new Promise<A>((resolve, reject) => {\n resolveExecution = resolve\n rejectExecution = reject\n })\n\n const activeExecution: ActiveExecution = { promise: execution }\n\n this.executions.add(activeExecution)\n\n void execution.then(\n () => {\n this.executions.delete(activeExecution)\n signalLink.dispose()\n },\n () => {\n this.executions.delete(activeExecution)\n signalLink.dispose()\n }\n )\n\n try {\n const running = run()\n\n void running.then(\n (value) => {\n resolveExecution(value)\n },\n (cause) => {\n rejectExecution(cause)\n }\n )\n } catch (cause) {\n rejectExecution(cause)\n }\n\n return execution\n }\n\n private runExecution<A>(\n executionScope: CloseableScope,\n program: () => A | PromiseLike<A>,\n resolver: ServiceResolver = this.resolver,\n signal: AbortSignal = this.shutdownController.signal\n ): Promise<Awaited<A>> {\n const options = this.onCleanupFailure\n ? {\n classify: classifyRuntimeOutcome,\n onCleanupFailure: this.onCleanupFailure\n }\n : {\n classify: classifyRuntimeOutcome\n }\n\n notifyRuntimeObservers(this.observers, (observer) => observer.onExecutionStart, {\n scope: executionScope\n })\n\n const execution = runScoped(executionScope, program, {\n ...options,\n contextStorage: this.contextStorage,\n context: makeRuntimeContext(resolver, executionScope, [], signal)\n })\n\n return execution.then(\n (value) => {\n notifyRuntimeObservers(this.observers, (observer) => observer.onExecutionEnd, {\n scope: executionScope,\n outcome: classifyRuntimeOutcome(value)\n })\n return value\n },\n (cause) => {\n notifyRuntimeObservers(this.observers, (observer) => observer.onExecutionEnd, {\n scope: executionScope,\n outcome: {\n status: 'failure',\n cause\n }\n })\n throw cause\n }\n )\n }\n\n dispose(input?: RuntimeDisposeOptions | ScopeOutcome): Promise<void> {\n if (this.disposePromise) {\n return this.disposePromise\n }\n\n const outcome =\n isScopeOutcome(input) || input === undefined ? (input ?? SCOPE_SUCCESS) : SCOPE_SUCCESS\n const options = isScopeOutcome(input) || input === undefined ? {} : input\n\n validateDisposeOptions(options)\n this.state = 'disposing'\n\n const executions = [...this.executions]\n\n this.disposePromise = this.performDispose(executions, outcome, options)\n\n return this.disposePromise\n }\n\n private async performDispose(\n executions: readonly ActiveExecution[],\n outcome: ScopeOutcome,\n options: RuntimeDisposeOptions\n ): Promise<void> {\n const failures: unknown[] = []\n\n await Promise.allSettled(this.warmupPromise ? [this.warmupPromise] : [])\n await this.waitForExecutions(executions, options)\n\n try {\n const signalLink = linkAbortSignals(this.signal, this.shutdownController.signal)\n\n try {\n await runRuntimeContext(\n this.contextStorage,\n makeRuntimeContext(this.resolver, this.rootScope, [], signalLink.signal),\n () => this.rootScope.close(outcome)\n )\n } finally {\n signalLink.dispose()\n }\n } catch (cause) {\n failures.push(cause)\n }\n\n try {\n await this.backend.disposeAll()\n } catch (cause) {\n failures.push(cause)\n }\n\n this.state = 'disposed'\n\n if (failures.length > 0) {\n const error = new LayerDisposeError(failures.flatMap(normalizeDisposeCauses))\n\n await notifyShutdownFailure(this.onCleanupFailure, {\n outcome,\n error\n })\n\n throw error\n }\n }\n\n private async waitForExecutions(\n executions: readonly ActiveExecution[],\n options: RuntimeDisposeOptions\n ): Promise<void> {\n const settled = Promise.allSettled(executions.map((execution) => execution.promise))\n\n if (options.abortAfterGracePeriod !== true || executions.length === 0) {\n await settled\n return\n }\n\n const gracePeriod = options.gracePeriod ?? 0\n let timer: ReturnType<typeof setTimeout> | undefined\n\n const timedOut = await Promise.race([\n settled.then(() => false),\n new Promise<boolean>((resolve) => {\n timer = setTimeout(() => resolve(true), gracePeriod)\n })\n ])\n\n if (timer !== undefined) {\n clearTimeout(timer)\n }\n\n if (timedOut && !this.shutdownController.signal.aborted) {\n this.shutdownController.abort(new Error('Runtime shutdown grace period exceeded'))\n }\n\n await settled\n }\n\n private assertActive(): void {\n if (this.state !== 'active') {\n throw new RuntimeHandleDisposedError()\n }\n }\n}\n\n/** Build a Runtime handle for a complete Layer and register its providers. */\nexport const createRuntimeHandle = async <L extends LayerInput>(\n layer: L & CompleteInput<L>,\n backend: LayerBackend,\n options: RuntimeOptions = {}\n): Promise<RuntimeHandle<ProvidedEnvironment<L>>> => {\n const rootScope = Scope.make()\n const contextStorage = options.contextStorage ?? defaultRuntimeContextStorage\n const observers = options.observers ?? []\n const resolver = createResolutionResolver(backend, contextStorage, observers)\n ScopeRuntime.bind(rootScope, contextStorage)\n let current: LayerProvider | undefined\n\n try {\n for (const provider of layer.providers) {\n current = provider\n\n await backend.register(\n bindProviderToScope(provider, rootScope, contextStorage, resolver, observers)\n )\n }\n } catch (registrationCause) {\n const outcome: ScopeOutcome = {\n status: 'failure',\n cause: registrationCause\n }\n const cleanupCauses: unknown[] = []\n\n try {\n await runRuntimeContext(\n contextStorage,\n makeRuntimeContext(resolver, rootScope, [], options.signal),\n () => rootScope.close(outcome)\n )\n } catch (cause) {\n cleanupCauses.push(cause)\n }\n\n try {\n await backend.disposeAll()\n } catch (cause) {\n cleanupCauses.push(cause)\n }\n\n if (cleanupCauses.length > 0) {\n const shutdownError = new LayerDisposeError(cleanupCauses.flatMap(normalizeDisposeCauses))\n\n await notifyShutdownFailure(options.onCleanupFailure, {\n outcome,\n error: shutdownError\n })\n }\n\n const cleanupCause =\n cleanupCauses.length === 1\n ? cleanupCauses[0]\n : cleanupCauses.length > 1\n ? new LayerDisposeError(cleanupCauses.flatMap(normalizeDisposeCauses))\n : undefined\n\n throw new LayerRegistrationError(current?.service, registrationCause, cleanupCause)\n }\n\n return new RuntimeHandleImpl<ProvidedEnvironment<L>>(\n backend,\n resolver,\n rootScope,\n options.onCleanupFailure,\n contextStorage,\n options.signal,\n observers,\n layer.providers.map((provider) => provider.service)\n )\n}\n","import type { LayerBackend } from '../layer'\n\nimport { MapLayerBackend } from '../layer/map-layer-backend'\n\nimport { createRuntimeHandle, type RuntimeHandle } from '../layer/runtime'\n\nimport type {\n CompleteExecutionLayer,\n LayerInput,\n CompleteInput,\n ProvidedEnvironment\n} from '../layer/inference'\n\nimport type { CompleteExecution } from '../layer/inference'\n\nimport type { AnyService } from '../service'\n\nimport {\n classifyRuntimeOutcome,\n type RuntimeDisposeOptions,\n type RuntimeOptions,\n type RuntimeRunOptions,\n type RuntimeShutdownDiagnostic\n} from './outcome'\n\nimport type { ScopeOutcome } from '../scope'\n\nimport type { RuntimeFor } from './types'\n\ntype RuntimeBackendInput = LayerBackend | RuntimeOptions | undefined\n\ntype RuntimeConfig = {\n readonly backend: LayerBackend\n readonly options: RuntimeOptions\n}\n\nconst isLayerBackend = (value: RuntimeBackendInput): value is LayerBackend =>\n value !== undefined && 'register' in value && 'resolve' in value && 'disposeAll' in value\n\nconst resolveRuntimeConfig = (\n backendOrOptions: RuntimeBackendInput,\n legacyOptions?: RuntimeOptions\n): RuntimeConfig => {\n if (isLayerBackend(backendOrOptions)) {\n return {\n backend: backendOrOptions,\n options: legacyOptions ?? {}\n }\n }\n\n const options = backendOrOptions ?? {}\n\n return {\n backend: options.backend ?? new MapLayerBackend(),\n options\n }\n}\n\n/**\n * Long-lived execution environment backed by a complete Layer.\n *\n * A Runtime owns Layer resources until `dispose()` is called. Each `run()` is\n * isolated in a child Scope, while Layer-scoped resources remain shared.\n *\n * @example\n * ```ts\n * const runtime = await Runtime.make(AppLive)\n * const result = await runtime.run(loadUser('u1'))\n * await runtime.dispose()\n * ```\n *\n * @typeParam Provided The branded Service instances supplied by the Layer.\n */\nexport class Runtime<Provided extends AnyService = any> {\n private constructor(private readonly handle: RuntimeHandle<Provided>) {}\n\n /**\n * Create a long-lived Runtime that owns its Layer resources.\n *\n * @example\n * ```ts\n * const runtime = await Runtime.make(AppLive)\n * const result = await runtime.run(program)\n * await runtime.dispose()\n * ```\n */\n static make<L extends LayerInput>(\n layer: L & CompleteInput<L>,\n backend: LayerBackend,\n options?: RuntimeOptions\n ): Promise<Runtime<ProvidedEnvironment<L>>>\n\n static make<L extends LayerInput>(\n layer: L & CompleteInput<L>,\n options?: RuntimeOptions\n ): Promise<Runtime<ProvidedEnvironment<L>>>\n\n static async make<L extends LayerInput>(\n layer: L & CompleteInput<L>,\n backendOrOptions?: LayerBackend | RuntimeOptions,\n legacyOptions?: RuntimeOptions\n ): Promise<Runtime<ProvidedEnvironment<L>>> {\n const { backend, options } = resolveRuntimeConfig(backendOrOptions, legacyOptions)\n const handle = await createRuntimeHandle(layer, backend, options)\n const runtime = new Runtime<ProvidedEnvironment<L>>(handle)\n\n if (options.warmup) {\n await runtime.warmup()\n }\n\n return runtime\n }\n\n /**\n * Run one program and dispose its Layer resources before resolving.\n *\n * This is convenient for request-style or command-style execution where a\n * Runtime should not outlive the operation.\n */\n static run<A, L extends LayerInput>(\n layer: L & CompleteInput<L>,\n backend: LayerBackend,\n program: CompleteExecution<ProvidedEnvironment<L>, A>,\n options?: RuntimeOptions\n ): Promise<Awaited<A>>\n\n static run<A, L extends LayerInput>(\n layer: L & CompleteInput<L>,\n program: CompleteExecution<ProvidedEnvironment<L>, A>,\n options?: RuntimeOptions\n ): Promise<Awaited<A>>\n\n static run<A, L extends LayerInput>(\n layer: L & CompleteInput<L>,\n options: RuntimeOptions,\n program: CompleteExecution<ProvidedEnvironment<L>, A>\n ): Promise<Awaited<A>>\n\n static async run<A, L extends LayerInput>(\n layer: L & CompleteInput<L>,\n backendOrProgramOrOptions:\n | LayerBackend\n | RuntimeOptions\n | CompleteExecution<ProvidedEnvironment<L>, A>,\n programOrOptions?: CompleteExecution<ProvidedEnvironment<L>, A> | RuntimeOptions,\n legacyOptions?: RuntimeOptions\n ): Promise<Awaited<A>> {\n let program: CompleteExecution<ProvidedEnvironment<L>, A>\n let backendOrOptions: RuntimeBackendInput\n let options: RuntimeOptions | undefined\n\n // oxlint-disable-next-line anti-slop/no-runtime-typeof -- overload dispatch needs to distinguish a Program callback from configuration.\n if (typeof backendOrProgramOrOptions === 'function') {\n program = backendOrProgramOrOptions\n // SAFETY: The function overload branch establishes that this argument is the optional RuntimeOptions value.\n backendOrOptions = programOrOptions as RuntimeOptions | undefined\n options = undefined\n } else {\n backendOrOptions = backendOrProgramOrOptions\n // SAFETY: The non-function overload branch establishes that this argument is the complete execution callback.\n program = programOrOptions as CompleteExecution<ProvidedEnvironment<L>, A>\n options = legacyOptions\n }\n\n const config = resolveRuntimeConfig(backendOrOptions, options)\n const runtime = await Runtime.make(layer, config.backend, config.options)\n\n let value!: Awaited<A>\n let executionFailed = false\n let executionFailure: unknown\n let programOutcome: ScopeOutcome | undefined\n\n try {\n value = await runtime.runUnchecked(async () => {\n try {\n const programValue = await program()\n\n programOutcome = classifyRuntimeOutcome(programValue)\n\n return programValue\n } catch (cause) {\n programOutcome = {\n status: 'failure',\n cause\n }\n\n throw cause\n }\n })\n } catch (cause) {\n executionFailed = true\n executionFailure = cause\n }\n\n const outcome: ScopeOutcome =\n programOutcome ??\n ({\n status: 'failure',\n cause: executionFailure\n } as const)\n\n try {\n await runtime.disposeWithOutcome(outcome)\n } catch (shutdownFailure) {\n if (!executionFailed && outcome.status === 'success') {\n throw shutdownFailure\n }\n }\n\n if (executionFailed) {\n throw executionFailure\n }\n\n return value\n }\n\n /** Run a callback with a managed Runtime and always dispose it afterward. */\n static use<A, L extends LayerInput>(\n layer: L & CompleteInput<L>,\n use: (runtime: Runtime<ProvidedEnvironment<L>>) => A | PromiseLike<A>,\n options?: RuntimeOptions\n ): Promise<Awaited<A>>\n\n static async use<A, L extends LayerInput>(\n layer: L & CompleteInput<L>,\n use: (runtime: Runtime<ProvidedEnvironment<L>>) => A | PromiseLike<A>,\n options?: RuntimeOptions\n ): Promise<Awaited<A>> {\n const runtime = await Runtime.make(layer, options)\n\n let value!: Awaited<A>\n let executionFailed = false\n let executionFailure: unknown\n let programOutcome: ScopeOutcome | undefined\n\n try {\n value = await use(runtime)\n programOutcome = classifyRuntimeOutcome(value)\n } catch (cause) {\n executionFailed = true\n executionFailure = cause\n programOutcome = {\n status: 'failure',\n cause\n }\n }\n\n const outcome: ScopeOutcome =\n programOutcome ??\n ({\n status: 'failure',\n cause: executionFailure\n } as const)\n\n try {\n await runtime.disposeWithOutcome(outcome)\n } catch (shutdownFailure) {\n if (!executionFailed && outcome.status === 'success') {\n throw shutdownFailure\n }\n }\n\n if (executionFailed) {\n throw executionFailure\n }\n\n return value\n }\n\n /** Resolve every Layer provider and dispose the Runtime if warmup fails. */\n async warmup(): Promise<void> {\n try {\n await this.handle.warmup()\n } catch (cause) {\n try {\n await this.handle.dispose({ status: 'failure', cause })\n } catch {\n // Warmup failure remains the primary error; cleanup is best effort.\n }\n\n throw cause\n }\n }\n\n /** Run one execution in this Runtime's child Scope. */\n run<A>(\n program: CompleteExecution<Provided, A>,\n options?: RuntimeRunOptions\n ): Promise<Awaited<A>> {\n return this.handle.run(program, options)\n }\n\n /** Run one execution with a Layer owned by that execution's child Scope. */\n runWith<Request extends LayerInput, A>(\n layer: Request & CompleteExecutionLayer<Provided, Request>,\n program: CompleteExecution<Provided | ProvidedEnvironment<Request>, A>,\n options?: RuntimeRunOptions\n ): Promise<Awaited<A>> {\n return this.handle.runWith(layer, program, options)\n }\n\n private runUnchecked<A>(program: () => A | PromiseLike<A>): Promise<Awaited<A>> {\n // SAFETY: One-shot Runtime.run performs the same complete-program validation at its public boundary before using this internal escape hatch.\n return this.handle.run(program as CompleteExecution<Provided, A>)\n }\n\n /** Stop new executions and release the Runtime's Layer resources. */\n dispose(options?: RuntimeDisposeOptions): Promise<void>\n\n /** @deprecated Scope outcomes are kept for internal compatibility. */\n dispose(outcome: ScopeOutcome): Promise<void>\n\n dispose(optionsOrOutcome?: RuntimeDisposeOptions | ScopeOutcome): Promise<void> {\n return this.handle.dispose(optionsOrOutcome)\n }\n\n /** Release Runtime-owned resources through JavaScript's async disposal protocol. */\n async [Symbol.asyncDispose](): Promise<void> {\n await this.dispose()\n }\n\n private disposeWithOutcome(outcome: ScopeOutcome): Promise<void> {\n return this.handle.dispose(outcome)\n }\n}\n\n/** Type-level aliases for naming Runtime handles and shutdown options. */\nexport declare namespace Runtime {\n /** Name a Runtime type from a concrete Layer. */\n export type For<L extends LayerInput> = RuntimeFor<L>\n\n /** Optional Runtime shutdown configuration. */\n export type Options = RuntimeOptions\n\n /** Optional signal supplied to one managed Runtime execution. */\n export type RunOptions = RuntimeRunOptions\n\n /** Cooperative shutdown policy for a managed Runtime. */\n export type DisposeOptions = RuntimeDisposeOptions\n\n /** Diagnostic reported for aggregated Runtime shutdown cleanup failures. */\n export type ShutdownDiagnostic = RuntimeShutdownDiagnostic\n}\n"],"mappings":";;;;;;;;AAKA,MAAa,+BAA+B;AAE5C,gCAAgC,4BAA4B;;;;ACe5D,IAAa,iBAAb,MAAa,eAAe;;;;;;;;;;;;;CAa1B,OAAO,IACL,UACA,SACA,UAAiC,8BAC9B;EACH,MAAM,UAAU,kBAAkB,OAAO;EACzC,MAAM,UAAU,mBACd,UACA,SAAS,OACT,SAAS,aAAa,WAAW,QAAQ,iBAAiB,CAAC,GAC3D,SAAS,MACX;EAEA,OAAO,kBAAkB,SAAS,SAAS,OAAO;CACpD;;CAGA,OAAO,UAA2B;EAChC,IAAI;EAEJ,IAAI;GACF,UAAU,sBAAsB;EAClC,QAAQ;GACN,MAAM,IAAI,iCAAiC;EAC7C;EAEA,IAAI,CAAC,QAAQ,UACX,MAAM,IAAI,iCAAiC;EAG7C,OAAO,QAAQ;CACjB;;CAGA,aAAa,QAAmC,OAAoC;EAGlF,OAAO,MAFU,eAAe,QAEZ,CAAC,CAAC,QAAQ,KAAK;CACrC;AACF;;;;;;;;;;;;;;;;;;;;;;;;;ACdA,SAAgB,UAAsC;CACpD,OAAO,SAAoC,KAA6B;EACtE,IAAI,IAAI,WAAW,GACjB,MAAM,IAAI,UAAU,gCAAgC;EAGtD,MAAe,YAA4C;;GAEzD,OAAgB,aAAkB;;;;;;;;;;;;;;;;;;;;;;;;GA0BlC,OAAO,GAAe,gBAAoE;IAExF,OAAO;GACT;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GR,OAAO;CACT;;CAGA,MAAM,SAAwB;EAC5B,IAAI;GACF,MAAM,KAAK,OAAO,OAAO;EAC3B,SAAS,OAAO;GACd,IAAI;IACF,MAAM,KAAK,OAAO,QAAQ;KAAE,QAAQ;KAAW;IAAM,CAAC;GACxD,QAAQ,CAER;GAEA,MAAM;EACR;CACF;;CAGA,IACE,SACA,SACqB;EACrB,OAAO,KAAK,OAAO,IAAI,SAAS,OAAO;CACzC;;CAGA,QACE,OACA,SACA,SACqB;EACrB,OAAO,KAAK,OAAO,QAAQ,OAAO,SAAS,OAAO;CACpD;CAEA,aAAwB,SAAwD;EAE9E,OAAO,KAAK,OAAO,IAAI,OAAyC;CAClE;CAQA,QAAQ,kBAAwE;EAC9E,OAAO,KAAK,OAAO,QAAQ,gBAAgB;CAC7C;;CAGA,OAAO,OAAO,gBAA+B;EAC3C,MAAM,KAAK,QAAQ;CACrB;CAEA,mBAA2B,SAAsC;EAC/D,OAAO,KAAK,OAAO,QAAQ,OAAO;CACpC;AACF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["SCOPE_SUCCESS","SCOPE_SUCCESS","next"],"sources":["../src/scope/errors.ts","../src/scope/disposable.ts","../src/scope/runtime.ts","../src/scope/internal.ts","../src/scope/scope.ts","../src/effect/combinators.ts","../src/effect/effect.ts","../src/function/pipe.ts","../src/resource/errors.ts","../src/resource/internal.ts","../src/resource/resource.ts","../src/runtime/outcome.ts","../src/runtime/observer.ts","../src/layer/resolution.ts","../src/layer/runtime.ts","../src/runtime/runtime.ts"],"sourcesContent":["/** Thrown when Scope context is accessed outside an active Scope execution. */\nexport class ScopeRuntimeNotConfiguredError extends Error {\n constructor() {\n super('No Scope is available in the current execution context')\n\n this.name = 'ScopeRuntimeNotConfiguredError'\n }\n}\n\n/** Thrown when a resource or finalizer is added after Scope closure begins. */\nexport class ScopeClosedError extends Error {\n constructor() {\n super('Cannot add resources or finalizers to a closed Scope')\n\n this.name = 'ScopeClosedError'\n }\n}\n\n/** Aggregates finalizer failures encountered while closing a Scope. */\nexport class ScopeCloseError extends Error {\n constructor(readonly causes: readonly unknown[]) {\n super(\n `Failed to close Scope (${causes.length} finalizer${causes.length === 1 ? '' : 's'} failed)`\n )\n\n this.name = 'ScopeCloseError'\n }\n}\n\n/** Thrown when a value has neither Symbol.dispose nor Symbol.asyncDispose. */\nexport class ResourceNotDisposableError extends Error {\n constructor() {\n super('Resource does not implement Symbol.dispose or Symbol.asyncDispose')\n\n this.name = 'ResourceNotDisposableError'\n }\n}\n","import type { ScopeFinalizer } from './types'\n\nconst SCOPE_SUCCESS = { status: 'success' } as const\n\ntype Disposer = (...args: never[]) => void | PromiseLike<void>\n\ntype DisposableCandidate = {\n [Symbol.dispose]?: Disposer\n\n [Symbol.asyncDispose]?: Disposer\n}\n\n/** Return a Scope finalizer for a value's async or sync disposal protocol. */\nexport const getDisposeFinalizer = <Resource>(resource: Resource): ScopeFinalizer | undefined => {\n // SAFETY: Object() provides a property-bearing view for protocol lookup; each method is checked for callability before invocation.\n const candidate = Object(resource) as DisposableCandidate\n const asyncDispose = candidate[Symbol.asyncDispose]\n\n if (asyncDispose instanceof Function) {\n return () => asyncDispose.call(resource)\n }\n\n const dispose = candidate[Symbol.dispose]\n\n if (dispose instanceof Function) {\n return () => dispose.call(resource)\n }\n\n return undefined\n}\n\n/** Dispose a value immediately when it implements a disposal protocol. */\nexport const disposeResource = <Resource>(resource: Resource): void | PromiseLike<void> => {\n const finalizer = getDisposeFinalizer(resource)\n\n return finalizer?.(SCOPE_SUCCESS)\n}\n","import { ScopeRuntimeNotConfiguredError } from './errors'\n\nimport type { Scope } from './scope'\n\nimport {\n activeRuntimeContextStorage,\n currentRuntimeContext,\n getRuntimeContext,\n makeRuntimeContext,\n runRuntimeContext\n} from '../runtime/context'\n\nimport type { RuntimeContextStorage } from '../runtime/context'\n\nconst scopeStorages = new WeakMap<object, RuntimeContextStorage>()\n\n/** Bridges the current Scope through async execution context. */\nexport class ScopeRuntime {\n /** Supply a Scope while invoking a callback. */\n static run<A>(\n scope: Scope,\n program: () => A,\n storage: RuntimeContextStorage = scopeStorages.get(scope) ?? activeRuntimeContextStorage()\n ): A {\n scopeStorages.set(scope, storage)\n\n const current = getRuntimeContext(storage)\n const context = makeRuntimeContext(\n current?.resolver,\n scope,\n current?.resolutionPath ?? [],\n current?.signal\n )\n\n return runRuntimeContext(storage, context, program)\n }\n\n /** Return the Scope active in the current execution context. */\n static current(): Scope {\n let context\n\n try {\n context = currentRuntimeContext()\n } catch {\n throw new ScopeRuntimeNotConfiguredError()\n }\n\n if (!context.scope) {\n throw new ScopeRuntimeNotConfiguredError()\n }\n\n return context.scope\n }\n\n /** Associate a Runtime-owned Scope with its context storage. */\n static bind(scope: Scope, storage: RuntimeContextStorage): void {\n scopeStorages.set(scope, storage)\n }\n}\n","import { ScopeCloseError } from './errors'\n\nimport { ScopeRuntime } from './runtime'\n\nimport type { CloseableScope } from './scope'\n\nimport {\n runRuntimeContext,\n type RuntimeContext,\n type RuntimeContextStorage\n} from '../runtime/context'\n\nimport type { CleanupFailureDiagnostic, MaybePromise, ScopeOutcome } from './types'\n\nexport type OutcomeClassifier<A> = (value: A) => ScopeOutcome\n\nexport type RunScopedOptions<A> = {\n readonly classify: OutcomeClassifier<A>\n readonly onCleanupFailure?: (diagnostic: CleanupFailureDiagnostic) => MaybePromise<void>\n readonly contextStorage?: RuntimeContextStorage\n readonly context?: RuntimeContext\n}\n\nconst notifyCleanupFailure = async (\n observer: ((diagnostic: CleanupFailureDiagnostic) => MaybePromise<void>) | undefined,\n diagnostic: CleanupFailureDiagnostic\n): Promise<void> => {\n if (!observer) {\n return\n }\n\n try {\n await observer(diagnostic)\n } catch {\n // Cleanup diagnostics are best effort and never affect the primary result.\n }\n}\n\nexport const runScoped = async <A>(\n scope: CloseableScope,\n program: () => A | PromiseLike<A>,\n options: RunScopedOptions<Awaited<A>>\n): Promise<Awaited<A>> => {\n let value!: Awaited<A>\n\n let programFailed = false\n let programFailure: unknown\n\n try {\n const run = () => ScopeRuntime.run(scope, program, options.contextStorage)\n\n value = await (options.context && options.contextStorage\n ? runRuntimeContext(options.contextStorage, options.context, run)\n : run())\n } catch (cause) {\n programFailed = true\n programFailure = cause\n }\n\n const outcome: ScopeOutcome = programFailed\n ? {\n status: 'failure',\n cause: programFailure\n }\n : options.classify(value)\n\n let cleanupFailed = false\n let cleanupFailure: unknown\n\n try {\n await scope.close(outcome)\n } catch (cause) {\n cleanupFailed = true\n cleanupFailure = cause\n }\n\n if (cleanupFailed) {\n const error =\n cleanupFailure instanceof ScopeCloseError\n ? cleanupFailure\n : new ScopeCloseError([cleanupFailure])\n\n await notifyCleanupFailure(options.onCleanupFailure, {\n outcome,\n error\n })\n\n cleanupFailure = error\n }\n\n if (programFailed) {\n throw programFailure\n }\n\n if (outcome.status === 'failure') {\n return value\n }\n\n if (cleanupFailed) {\n throw cleanupFailure\n }\n\n return value\n}\n","import { ResourceNotDisposableError, ScopeCloseError, ScopeClosedError } from './errors'\n\nimport { getDisposeFinalizer } from './disposable'\n\nimport { runScoped } from './internal'\n\nimport { ScopeRuntime } from './runtime'\n\nimport type { DisposableResource, MaybePromise, ScopeFinalizer, ScopeOutcome } from './types'\n\n/**\n * Non-owning lifecycle context for finalizers and child Scopes.\n *\n * A Scope can register cleanup and create children, but it cannot close\n * itself. Use `Scope.make()` or `Scope.run()` when your code owns the Scope.\n */\nexport interface Scope {\n /** Register a finalizer that runs when the owning Scope closes. */\n addFinalizer(finalizer: ScopeFinalizer): void\n\n /** Acquire a resource and register its outcome-aware release callback. */\n acquire<R>(\n acquire: () => MaybePromise<R>,\n release: (resource: R, outcome: ScopeOutcome) => MaybePromise<void>\n ): Promise<R>\n\n /** Register an already-acquired disposable resource. */\n add<R extends DisposableResource>(resource: R): Promise<R>\n\n /** Create a child Scope owned by this Scope. */\n fork(): CloseableScope\n}\n\n/** A Scope whose owner is responsible for calling `close()`. */\nexport interface CloseableScope extends Scope {\n /** Close the Scope and run children and finalizers in child-first LIFO order. */\n close(outcome?: ScopeOutcome): Promise<void>\n}\n\nconst SCOPE_SUCCESS: ScopeOutcome = Object.freeze({ status: 'success' })\n\nclass ScopeImpl implements CloseableScope {\n private readonly children = new Set<ScopeImpl>()\n\n private readonly finalizers: ScopeFinalizer[] = []\n\n private closePromise: Promise<void> | undefined\n\n private closeOutcome: ScopeOutcome | undefined\n\n constructor(private parent?: ScopeImpl) {}\n\n fork(): CloseableScope {\n this.assertOpen()\n\n const child = new ScopeImpl(this)\n\n this.children.add(child)\n\n return child\n }\n\n addFinalizer(finalizer: ScopeFinalizer): void {\n this.assertOpen()\n\n this.finalizers.push(finalizer)\n }\n\n async acquire<R>(\n acquire: () => MaybePromise<R>,\n release: (resource: R, outcome: ScopeOutcome) => MaybePromise<void>\n ): Promise<R> {\n this.assertOpen()\n\n const resource = await acquire()\n\n try {\n this.addFinalizer((outcome) => release(resource, outcome))\n\n return resource\n } catch (scopeFailure) {\n try {\n await release(resource, this.closeOutcome ?? SCOPE_SUCCESS)\n } catch (releaseFailure) {\n throw new AggregateError(\n [scopeFailure, releaseFailure],\n 'Scope closed while acquiring a resource and immediate cleanup also failed'\n )\n }\n\n throw scopeFailure\n }\n }\n\n async add<R extends DisposableResource>(resource: R): Promise<R> {\n const finalizer = getDisposeFinalizer(resource)\n\n if (!finalizer) {\n throw new ResourceNotDisposableError()\n }\n\n try {\n this.addFinalizer(finalizer)\n\n return resource\n } catch (scopeFailure) {\n try {\n await finalizer(this.closeOutcome ?? SCOPE_SUCCESS)\n } catch (releaseFailure) {\n throw new AggregateError(\n [scopeFailure, releaseFailure],\n 'Scope closed while adding a disposable resource and cleanup also failed'\n )\n }\n\n throw scopeFailure\n }\n }\n\n close(outcome: ScopeOutcome = SCOPE_SUCCESS): Promise<void> {\n if (this.closePromise) {\n return this.closePromise\n }\n\n this.closeOutcome = outcome\n this.closePromise = ScopeRuntime.run(this, () => this.closeInternal(outcome))\n\n return this.closePromise\n }\n\n private async closeInternal(outcome: ScopeOutcome): Promise<void> {\n const failures: unknown[] = []\n\n const children = [...this.children]\n\n this.children.clear()\n\n for (let index = children.length - 1; index >= 0; index--) {\n const child = children[index]\n\n if (!child) {\n continue\n }\n\n try {\n await child.close(outcome)\n } catch (cause) {\n if (cause instanceof ScopeCloseError) {\n failures.push(...cause.causes)\n } else {\n failures.push(cause)\n }\n }\n }\n\n for (let index = this.finalizers.length - 1; index >= 0; index--) {\n const finalizer = this.finalizers[index]\n\n if (!finalizer) {\n continue\n }\n\n try {\n await finalizer(outcome)\n } catch (cause) {\n failures.push(cause)\n }\n }\n\n this.finalizers.length = 0\n\n this.detach()\n\n if (failures.length > 0) {\n throw new ScopeCloseError(failures)\n }\n }\n\n private detach(): void {\n const parent = this.parent\n\n if (!parent) {\n return\n }\n\n parent.children.delete(this)\n this.parent = undefined\n }\n\n private assertOpen(): void {\n if (this.closePromise) {\n throw new ScopeClosedError()\n }\n }\n}\n\nexport const Scope = {\n /** Create an owned, initially open Scope. */\n make(): CloseableScope {\n return new ScopeImpl()\n },\n\n /** Return the non-owning Scope available in the current execution context. */\n current(): Scope {\n return ScopeRuntime.current()\n },\n\n /** Run a callback with an existing Scope supplied as the current context. */\n provide<A>(scope: Scope, program: () => A): A {\n return ScopeRuntime.run(scope, program)\n },\n\n /** Resolve the current Scope through `yield* Scope` inside an Effect. */\n // oxlint-disable-next-line require-yield\n *[Symbol.iterator](): Generator<never, Scope, unknown> {\n return ScopeRuntime.current()\n },\n\n /**\n * Run a program in a newly owned Scope.\n *\n * Scope is independent from `better-result`, so returned values—including\n * `Result.err`—close this Scope with a successful outcome. Result-aware\n * outcome classification belongs to `Runtime.run`.\n *\n * @example\n * ```ts\n * await Scope.run(async (scope) => {\n * const connection = await scope.acquire(connect, (connection) => connection.close())\n * return connection.query()\n * })\n * ```\n */\n run<A>(program: (scope: Scope) => A | PromiseLike<A>): Promise<Awaited<A>> {\n const scope = new ScopeImpl()\n\n return runScoped(scope, () => program(scope), {\n classify: () => SCOPE_SUCCESS\n })\n }\n} as const\n\n/** Type-level aliases for Scope ownership, outcomes, and cleanup contracts. */\nexport declare namespace Scope {\n /** A Scope whose owner is responsible for calling `close()`. */\n export type Closeable = CloseableScope\n\n /** The outcome supplied to Scope finalizers and resource releases. */\n export type Outcome = ScopeOutcome\n\n /** A cleanup callback registered with a Scope. */\n export type Finalizer = ScopeFinalizer\n\n /** A value implementing a JavaScript disposal protocol. */\n export type Disposable = DisposableResource\n}\n","import { Result } from 'better-result'\n\nimport type { Result as ResultType } from 'better-result'\n\nimport type { AnyService } from '../service'\nimport { isPromiseLike } from '../utils/runtime'\nimport type { Effect, EffectError, EffectRequirements, EffectSuccess } from './types'\n\ntype EffectInput<A, E> = ResultType<A, E> | PromiseLike<ResultType<A, E>>\n\ntype AnyEffectInput = EffectInput<any, any>\ntype AnyEffectValue = ResultType<any, any>\ntype AnyAsyncEffectInput = PromiseLike<ResultType<any, any>>\ntype CombinatorCallback = (value: any) => any\ntype CombinatorInput = AnyEffectInput | CombinatorCallback\n\ntype PreserveAsync<Input, Output> = Input extends PromiseLike<unknown> ? Promise<Output> : Output\n\ntype MappedResult<Input, B> = Effect<B, EffectError<Input>, EffectRequirements<Input>>\n\ntype ErrorMappedResult<Input, E2> = Effect<EffectSuccess<Input>, E2, EffectRequirements<Input>>\n\ntype ChainedResult<First, Next> = Effect<\n EffectSuccess<Next>,\n EffectError<First> | EffectError<Next>,\n EffectRequirements<First> | EffectRequirements<Next>\n>\n\ntype ChainedOutput<First, Next> = ChainedResult<First, Next>\n\ntype AsyncChainedOutput<First, Next> = Promise<ChainedResult<First, Next>>\n\ntype MapOperation<A, B> = {\n <Input>(effect: Input & EffectInput<A, any>): PreserveAsync<Input, MappedResult<Input, B>>\n}\n\ntype MapErrorOperation<E1, E2> = {\n <Input>(effect: Input & EffectInput<any, E1>): PreserveAsync<Input, ErrorMappedResult<Input, E2>>\n}\n\ntype AndThenOperation<Next> = {\n <Input>(effect: Input & AnyEffectValue): ChainedOutput<Input, Next>\n}\n\ntype AndThenAsyncOperation<A, Next> = {\n <Input>(effect: Input & EffectInput<A, any>): AsyncChainedOutput<Input, Next>\n}\n\ntype TappedResult<Input> = Effect<\n EffectSuccess<Input>,\n EffectError<Input>,\n EffectRequirements<Input>\n>\n\ntype RecoveredResult<Input, Next> = Effect<\n EffectSuccess<Input> | EffectSuccess<Next>,\n EffectError<Next>,\n EffectRequirements<Input> | EffectRequirements<Next>\n>\n\ntype FlattenedResult<Input> = Effect<\n EffectSuccess<EffectSuccess<Input>>,\n EffectError<Input> | EffectError<EffectSuccess<Input>>,\n EffectRequirements<Input> | EffectRequirements<EffectSuccess<Input>>\n>\n\ntype AsResult<Input, Value> = Effect<Value, EffectError<Input>, EffectRequirements<Input>>\n\ntype MatchedResult<Input, OkResult, ErrResult> = Effect<\n EffectSuccess<OkResult> | EffectSuccess<ErrResult>,\n EffectError<OkResult> | EffectError<ErrResult>,\n EffectRequirements<Input> | EffectRequirements<OkResult> | EffectRequirements<ErrResult>\n>\n\ntype AllResult<Results extends readonly AnyEffectValue[]> = Effect<\n { -readonly [Index in keyof Results]: EffectSuccess<Results[Index]> },\n EffectError<Results[number]>,\n EffectRequirements<Results[number]>\n>\n\ntype ZipResult<Left, Right> = Effect<\n [EffectSuccess<Left>, EffectSuccess<Right>],\n EffectError<Left> | EffectError<Right>,\n EffectRequirements<Left> | EffectRequirements<Right>\n>\n\ntype TapOperation = {\n <Input>(\n effect: Input & AnyEffectInput,\n fn: (value: EffectSuccess<Input>) => void\n ): PreserveAsync<Input, TappedResult<Input>>\n}\n\ntype TapErrorOperation = {\n <Input>(\n effect: Input & AnyEffectInput,\n fn: (error: EffectError<Input>) => void\n ): PreserveAsync<Input, TappedResult<Input>>\n}\n\ntype TapBothOperation = {\n <Input>(\n effect: Input & AnyEffectInput,\n handlers: {\n ok: (value: EffectSuccess<Input>) => void\n err: (error: EffectError<Input>) => void\n }\n ): PreserveAsync<Input, TappedResult<Input>>\n}\n\ntype RecoverOperation<Next> = {\n <Input>(\n effect: Input & AnyEffectInput,\n fn: (error: EffectError<Input>) => Next\n ): PreserveAsync<Input, RecoveredResult<Input, Next>>\n}\n\ntype RecoverAsyncOperation<Next> = {\n <Input>(\n effect: Input & AnyEffectInput,\n fn: (error: EffectError<Input>) => Next\n ): Promise<RecoveredResult<Input, Next>>\n}\n\nconst asResult = <Value>(value: Value): ResultType<any, any> => {\n // SAFETY: Effect is the declaration-only Result facade, so every runtime value is a Result.\n return value as ResultType<any, any>\n}\n\nconst mapResult = <A, B, E, Requirements extends AnyService>(\n result: ResultType<A, E>,\n fn: (value: A) => B\n): Effect<B, E, Requirements> => {\n // SAFETY: Result.map changes only the success channel; the declaration-only Effect marker is restored by this adapter.\n return Result.map(result, fn) as Effect<B, E, Requirements>\n}\n\nconst mapErrorResult = <A, E1, E2, Requirements extends AnyService>(\n result: ResultType<A, E1>,\n fn: (error: E1) => E2\n): Effect<A, E2, Requirements> => {\n // SAFETY: Result.mapError changes only the error channel; the declaration-only Effect marker is restored by this adapter.\n return Result.mapError(result, fn) as Effect<A, E2, Requirements>\n}\n\nconst andThenResult = <\n A,\n B,\n E1,\n E2,\n Requirements1 extends AnyService,\n Requirements2 extends AnyService\n>(\n result: ResultType<A, E1>,\n next: (value: A) => ResultType<B, E2>\n): Effect<B, E1 | E2, Requirements1 | Requirements2> => {\n // SAFETY: The public callback returns an Effect, whose only runtime contract is the underlying Result.\n const resultNext = next as (value: A) => ResultType<B, E2>\n\n // SAFETY: Result.andThen unions Result errors; the declaration-only Effect marker is restored by this adapter.\n return Result.andThen(result, resultNext) as Effect<B, E1 | E2, Requirements1 | Requirements2>\n}\n\nconst andThenAsyncResult = <\n A,\n B,\n E1,\n E2,\n Requirements1 extends AnyService,\n Requirements2 extends AnyService\n>(\n result: ResultType<A, E1>,\n next: (value: A) => PromiseLike<ResultType<B, E2>>\n): Promise<Effect<B, E1 | E2, Requirements1 | Requirements2>> => {\n // SAFETY: The public callback returns an Effect, whose only runtime contract is the underlying Result.\n const resultNext = (value: A) => {\n // SAFETY: Promise resolution preserves the callback's Result value; only declaration-only Effect metadata is erased.\n return Promise.resolve(next(value)) as Promise<ResultType<B, E2>>\n }\n\n // SAFETY: Result.andThenAsync unions Result errors; the declaration-only Effect marker is restored by this adapter.\n return Result.andThenAsync(result, resultNext) as Promise<\n Effect<B, E1 | E2, Requirements1 | Requirements2>\n >\n}\n\n/**\n * Map the successful value of a Result or Effect result.\n *\n * Supports both data-first and data-last forms and preserves asynchronous\n * results and declaration-only Service requirements.\n *\n * @example\n * ```ts\n * const doubled = Effect.map(Result.ok(2), (value) => value * 2)\n * const toLabel = Effect.map((value: number) => `#${value}`)\n * ```\n */\nexport function map<A, B>(fn: (value: A) => B): MapOperation<A, B>\nexport function map<Input, B>(\n effect: Input & AnyEffectInput,\n fn: (value: EffectSuccess<Input>) => B\n): PreserveAsync<Input, MappedResult<Input, B>>\nexport function map(first: CombinatorInput, second?: CombinatorCallback): any {\n if (first instanceof Function && second === undefined) {\n // SAFETY: The curried overload accepts a unary mapping callback in this branch.\n const callback = first as CombinatorCallback\n\n return (effect: AnyEffectInput) => {\n // SAFETY: The overload implementation has already established the callback and Effect input positions.\n return map(effect as never, callback as never)\n }\n }\n\n // SAFETY: The data-first overload requires the second argument to be a unary mapping callback.\n const fn = second as CombinatorCallback\n\n if (isPromiseLike(first)) {\n return Promise.resolve(first).then((result) => {\n // SAFETY: Result is the runtime representation shared by Effect and better-result.\n return mapResult(result as ResultType<any, any>, fn)\n })\n }\n\n // SAFETY: The data-first overload supplies a Result-compatible Effect value.\n return mapResult(first as ResultType<any, any>, fn)\n}\n\n/**\n * Map the error value of a Result or Effect result while preserving its\n * successful value, asynchronous shape, and declaration-only Service requirements.\n *\n * @example\n * ```ts\n * const labelled = Effect.mapError(Result.err('missing'), (error) => ({ error }))\n * ```\n */\nexport function mapError<E1, E2>(fn: (error: E1) => E2): MapErrorOperation<E1, E2>\nexport function mapError<Input, E2>(\n effect: Input & AnyEffectInput,\n fn: (error: EffectError<Input>) => E2\n): PreserveAsync<Input, ErrorMappedResult<Input, E2>>\nexport function mapError(first: CombinatorInput, second?: CombinatorCallback): any {\n if (first instanceof Function && second === undefined) {\n // SAFETY: The curried overload accepts a unary error-mapping callback in this branch.\n const callback = first as CombinatorCallback\n\n return (effect: AnyEffectInput) => {\n // SAFETY: The overload implementation has already established the callback and Effect input positions.\n return mapError(effect as never, callback as never)\n }\n }\n\n // SAFETY: The data-first overload requires the second argument to be a unary error-mapping callback.\n const fn = second as CombinatorCallback\n\n if (isPromiseLike(first)) {\n return Promise.resolve(first).then((result) => {\n // SAFETY: Result is the runtime representation shared by Effect and better-result.\n return mapErrorResult(result as ResultType<any, any>, fn)\n })\n }\n\n // SAFETY: The data-first overload supplies a Result-compatible Effect value.\n return mapErrorResult(first as ResultType<any, any>, fn)\n}\n\n/**\n * Chain a synchronous Result-producing operation after a successful result.\n *\n * The next operation is skipped when the input is an error. Both error types\n * and both sets of Service requirements are preserved in the output.\n *\n * @example\n * ```ts\n * const user = Effect.andThen(Result.ok('u1'), (id) => repository.find(id))\n * ```\n */\nexport function andThen<A, Next extends AnyEffectValue>(\n next: (value: A) => Next\n): AndThenOperation<Next>\nexport function andThen<Input, Next extends AnyEffectValue>(\n effect: Input & AnyEffectValue,\n next: (value: EffectSuccess<Input>) => Next\n): ChainedOutput<Input, Next>\nexport function andThen(first: CombinatorInput, second?: CombinatorCallback): any {\n if (first instanceof Function && second === undefined) {\n // SAFETY: The curried overload accepts a unary continuation in this branch.\n const callback = first as CombinatorCallback\n\n return (effect: AnyEffectInput) => {\n // SAFETY: The overload implementation has already established the callback and Effect input positions.\n return andThen(effect as never, callback as never)\n }\n }\n\n // SAFETY: The data-first overload requires the second argument to return a Result.\n const next = second as CombinatorCallback\n\n // SAFETY: The data-first overload supplies a Result-compatible Effect value.\n return andThenResult(first as ResultType<any, any>, next)\n}\n\n/**\n * Chain an asynchronous Result-producing operation after a successful result.\n *\n * The returned value is always a Promise and retains both operations' error\n * and Service-requirement metadata.\n *\n * @example\n * ```ts\n * const user = Effect.andThenAsync(loadUser(), (user) => fetchProfile(user.id))\n * ```\n */\nexport function andThenAsync<A, Next extends AnyAsyncEffectInput>(\n next: (value: A) => Next\n): AndThenAsyncOperation<A, Next>\nexport function andThenAsync<Input, Next extends AnyAsyncEffectInput>(\n effect: Input & AnyEffectInput,\n next: (value: EffectSuccess<Input>) => Next\n): AsyncChainedOutput<Input, Next>\nexport function andThenAsync(first: CombinatorInput, second?: CombinatorCallback): any {\n if (first instanceof Function && second === undefined) {\n // SAFETY: The curried overload accepts a unary asynchronous continuation in this branch.\n const callback = first as CombinatorCallback\n\n return (effect: AnyEffectInput) => {\n // SAFETY: The overload implementation has already established the callback and Effect input positions.\n return andThenAsync(effect as never, callback as never)\n }\n }\n\n // SAFETY: The data-first overload requires the second argument to return a PromiseLike Effect.\n const next = second as CombinatorCallback\n\n if (isPromiseLike(first)) {\n return Promise.resolve(first).then((result) => {\n // SAFETY: Result is the runtime representation shared by Effect and better-result.\n return andThenAsyncResult(result as ResultType<any, any>, next)\n })\n }\n\n // SAFETY: The data-first overload supplies a Result-compatible Effect value.\n return andThenAsyncResult(first as ResultType<any, any>, next)\n}\n\nconst tapResult = <A, E, Requirements extends AnyService>(\n result: ResultType<A, E>,\n fn: (value: A) => void\n): Effect<A, E, Requirements> =>\n // SAFETY: Result.tap preserves the Result value; the declaration-only Effect marker is restored here.\n Result.tap(result, fn) as Effect<A, E, Requirements>\n\nconst tapErrorResult = <A, E, Requirements extends AnyService>(\n result: ResultType<A, E>,\n fn: (error: E) => void\n): Effect<A, E, Requirements> =>\n // SAFETY: Result.tapError preserves the Result value; the declaration-only Effect marker is restored here.\n Result.tapError(result, fn) as Effect<A, E, Requirements>\n\nconst tapBothResult = <A, E, Requirements extends AnyService>(\n result: ResultType<A, E>,\n handlers: { ok: (value: A) => void; err: (error: E) => void }\n): Effect<A, E, Requirements> =>\n // SAFETY: Result.tapBoth preserves the Result value; the declaration-only Effect marker is restored here.\n Result.tapBoth(result, handlers) as Effect<A, E, Requirements>\n\nconst recoverResult = <\n A,\n E,\n B,\n E2,\n Requirements1 extends AnyService,\n Requirements2 extends AnyService\n>(\n result: ResultType<A, E>,\n fn: (error: E) => ResultType<B, E2>\n): Effect<A | B, E2, Requirements1 | Requirements2> =>\n // SAFETY: Result.tryRecover owns recovery and short-circuiting; only Effect metadata is restored here.\n Result.tryRecover(result, fn) as Effect<A | B, E2, Requirements1 | Requirements2>\n\nconst recoverAsyncResult = <\n A,\n E,\n B,\n E2,\n Requirements1 extends AnyService,\n Requirements2 extends AnyService\n>(\n result: ResultType<A, E>,\n fn: (error: E) => PromiseLike<ResultType<B, E2>>\n): Promise<Effect<A | B, E2, Requirements1 | Requirements2>> =>\n // SAFETY: Result.tryRecoverAsync owns asynchronous recovery; only Effect metadata is restored here.\n Result.tryRecoverAsync(result, (error) => Promise.resolve(fn(error))) as Promise<\n Effect<A | B, E2, Requirements1 | Requirements2>\n >\n\nconst flattenResult = <\n A,\n E1,\n E2,\n Requirements1 extends AnyService,\n Requirements2 extends AnyService\n>(\n result: ResultType<ResultType<A, E2>, E1>\n): Effect<A, E1 | E2, Requirements1 | Requirements2> =>\n // SAFETY: Result.flatten removes one Result layer; the outer and inner Effect markers are restored here.\n Result.flatten(result) as Effect<A, E1 | E2, Requirements1 | Requirements2>\n\nconst matchResult = <A, E, OkResult, ErrResult>(\n result: ResultType<A, E>,\n handlers: { ok: (value: A) => OkResult; err: (error: E) => ErrResult }\n): OkResult | ErrResult =>\n // SAFETY: Result.match invokes only the selected branch; handler Results remain ordinary runtime values.\n Result.match(result, handlers as never) as OkResult | ErrResult\n\nconst allResult = <const Results extends readonly AnyEffectValue[]>(\n results: Results\n): AllResult<Results> =>\n // SAFETY: Result.all preserves tuple order and short-circuiting; the declaration-only channels are restored here.\n Result.all(results as readonly ResultType<any, any>[]) as AllResult<Results>\n\n/** Observe a successful value without changing the Result. */\nexport function tap(fn: (value: any) => void): TapOperation\nexport function tap<Input>(\n effect: Input & AnyEffectInput,\n fn: (value: EffectSuccess<Input>) => void\n): PreserveAsync<Input, TappedResult<Input>>\nexport function tap(first: CombinatorInput, second?: CombinatorCallback): any {\n if (first instanceof Function && second === undefined) {\n const callback = first\n return (effect: AnyEffectInput) => tap(effect, callback)\n }\n\n if (second === undefined) {\n throw new TypeError('Effect.tap requires a callback')\n }\n\n const fn = second\n if (isPromiseLike(first)) {\n return Promise.resolve(first).then((result) => tapResult(asResult(result), fn))\n }\n\n return tapResult(asResult(first), fn)\n}\n\n/** Observe an error value without changing the Result. */\nexport function tapError(fn: (error: any) => void): TapErrorOperation\nexport function tapError<Input>(\n effect: Input & AnyEffectInput,\n fn: (error: EffectError<Input>) => void\n): PreserveAsync<Input, TappedResult<Input>>\nexport function tapError(first: CombinatorInput, second?: CombinatorCallback): any {\n if (first instanceof Function && second === undefined) {\n const callback = first\n return (effect: AnyEffectInput) => tapError(effect, callback)\n }\n\n if (second === undefined) {\n throw new TypeError('Effect.tapError requires a callback')\n }\n\n const fn = second\n if (isPromiseLike(first)) {\n return Promise.resolve(first).then((result) => tapErrorResult(asResult(result), fn))\n }\n\n return tapErrorResult(asResult(first), fn)\n}\n\n/** Observe whichever Result branch is active without changing the Result. */\nexport function tapBoth(handlers: {\n ok: (value: any) => void\n err: (error: any) => void\n}): TapBothOperation\nexport function tapBoth<Input>(\n effect: Input & AnyEffectInput,\n handlers: {\n ok: (value: EffectSuccess<Input>) => void\n err: (error: EffectError<Input>) => void\n }\n): PreserveAsync<Input, TappedResult<Input>>\nexport function tapBoth(first: any, second?: any): any {\n if (second === undefined) {\n return (effect: AnyEffectInput) => tapBoth(effect, first)\n }\n\n if (isPromiseLike(first)) {\n return Promise.resolve(first).then((result) => tapBothResult(result, second))\n }\n\n return tapBothResult(asResult(first), second)\n}\n\n/** Recover an Err with a synchronous Result-producing callback. */\nexport function recover<Next extends AnyEffectValue>(\n fn: (error: any) => Next\n): RecoverOperation<Next>\nexport function recover<Input, Next extends AnyEffectValue>(\n effect: Input & AnyEffectInput,\n fn: (error: EffectError<Input>) => Next\n): PreserveAsync<Input, RecoveredResult<Input, Next>>\nexport function recover(first: CombinatorInput, second?: CombinatorCallback): any {\n if (first instanceof Function && second === undefined) {\n const callback = first\n return (effect: AnyEffectInput) => recover(effect, callback)\n }\n\n if (second === undefined) {\n throw new TypeError('Effect.recover requires a callback')\n }\n\n const fn = second\n if (isPromiseLike(first)) {\n return Promise.resolve(first).then((result) => recoverResult(asResult(result), fn))\n }\n\n return recoverResult(asResult(first), fn)\n}\n\n/** Recover an Err with an asynchronous Result-producing callback. */\nexport function recoverAsync<Next extends AnyAsyncEffectInput>(\n fn: (error: any) => Next\n): RecoverAsyncOperation<Next>\nexport function recoverAsync<Input, Next extends AnyAsyncEffectInput>(\n effect: Input & AnyEffectInput,\n fn: (error: EffectError<Input>) => Next\n): Promise<RecoveredResult<Input, Next>>\nexport function recoverAsync(first: CombinatorInput, second?: CombinatorCallback): any {\n if (first instanceof Function && second === undefined) {\n const callback = first\n return (effect: AnyEffectInput) => recoverAsync(effect, callback)\n }\n\n if (second === undefined) {\n throw new TypeError('Effect.recoverAsync requires a callback')\n }\n\n const fn = second\n if (isPromiseLike(first)) {\n return Promise.resolve(first).then((result) => recoverAsyncResult(asResult(result), fn))\n }\n\n return recoverAsyncResult(asResult(first), fn)\n}\n\n/** Remove one nested Result/Effect layer. */\nexport function flatten<Input>(effect: Input & AnyEffectValue): FlattenedResult<Input> {\n // SAFETY: flattenResult restores the nested Effect channels after Result.flatten removes one runtime layer.\n return flattenResult(asResult(effect)) as FlattenedResult<Input>\n}\n\n/** Replace a successful value while preserving errors and requirements. */\nexport function as<Value>(\n value: Value\n): <Input>(effect: Input & AnyEffectValue) => AsResult<Input, Value>\nexport function as<Input, Value>(\n effect: Input & AnyEffectValue,\n value: Value\n): AsResult<Input, Value>\nexport function as(first: any, second?: any): any {\n if (arguments.length < 2) {\n return (effect: AnyEffectValue) => as(effect, first)\n }\n\n return mapResult(asResult(first), () => second)\n}\n\n/** Replace a successful value with void. */\nexport function asVoid<Input>(effect: Input & AnyEffectValue): AsResult<Input, void> {\n return mapResult(asResult(effect), () => undefined)\n}\n\n/** Match an Effect and return branch Effects with their channels unioned. */\nexport function match<Input, OkResult extends AnyEffectValue, ErrResult extends AnyEffectValue>(\n effect: Input & AnyEffectValue,\n handlers: {\n ok: (value: EffectSuccess<Input>) => OkResult\n err: (error: EffectError<Input>) => ErrResult\n }\n): PreserveAsync<Input, MatchedResult<Input, OkResult, ErrResult>>\nexport function match<Input, OkValue, ErrValue>(\n effect: Input & AnyEffectValue,\n handlers: {\n ok: (value: EffectSuccess<Input>) => OkValue\n err: (error: EffectError<Input>) => ErrValue\n }\n): PreserveAsync<Input, OkValue | ErrValue>\nexport function match(first: AnyEffectInput, second?: any): any {\n if (isPromiseLike(first)) {\n return Promise.resolve(first).then((result) => match(asResult(result), second))\n }\n\n return matchResult(asResult(first), second)\n}\n\n/** Collect already-created Effects in input order. */\nexport function all<const Results extends readonly AnyEffectValue[]>(\n results: Results\n): AllResult<Results> {\n return allResult(results)\n}\n\n/** Combine two already-created Effects in input order. */\nexport function zip<Left, Right>(\n left: Left & AnyEffectValue,\n right: Right & AnyEffectValue\n): ZipResult<Left, Right> {\n // SAFETY: Result.all returns the ordered pair; ZipResult restores only the declaration-only Effect channels.\n return Result.all([left, right]) as ZipResult<Left, Right>\n}\n","import { Result } from 'better-result'\n\nimport type { Err, Result as ResultType, UnhandledException } from 'better-result'\n\nimport { Scope } from '../scope'\n\nimport type { DisposableResource, MaybePromise, ScopeOutcome } from '../scope'\nimport type { AnyService } from '../service'\n\nimport type {\n AnyEffect,\n Effect as EffectType,\n EffectError,\n EffectFromGenerator,\n EffectRequirements,\n EffectSuccess,\n EffectYield,\n Program as ProgramType,\n ProgramFromGenerator\n} from './types'\n\nimport {\n all,\n andThen,\n andThenAsync,\n as,\n asVoid,\n flatten,\n map,\n mapError,\n match,\n recover,\n recoverAsync,\n tap,\n tapBoth,\n tapError,\n zip\n} from './combinators'\n\nexport type Effect<A, E, R extends AnyService = never> = EffectType<A, E, R>\n\ntype LazyProgram<A, E, R extends AnyService = never> = ProgramType<A, E, R>\n\n/** A nominal lazy computation that produces an Effect when invoked. */\nexport type Program<A, E, R extends AnyService = never> = LazyProgram<A, E, R>\n\ntype AnyResult = ResultType<any, any>\n\ntype AnyProgram = ProgramType<any, any, AnyService>\n\ntype ProgramAllSuccess<Programs extends readonly AnyProgram[]> = {\n -readonly [Index in keyof Programs]: EffectSuccess<Programs[Index]>\n}\n\ntype ProgramAllError<Programs extends readonly AnyProgram[]> = EffectError<Programs[number]>\n\ntype ProgramAllRequirements<Programs extends readonly AnyProgram[]> = EffectRequirements<\n Programs[number]\n>\n\ntype ProgramAllResult<Programs extends readonly AnyProgram[]> = ProgramType<\n ProgramAllSuccess<Programs>,\n ProgramAllError<Programs>,\n ProgramAllRequirements<Programs>\n>\n\nexport type ProgramAllOptions = {\n readonly concurrency?: number\n}\n\ntype EffectGenerator =\n | (() => Generator<EffectYield, AnyResult, unknown>)\n | (() => AsyncGenerator<EffectYield, AnyResult, unknown>)\n\ntype RuntimeResultGenerator = (body: EffectGenerator) => AnyResult | Promise<AnyResult>\n\n// SAFETY: Service iterators yield no runtime markers, so Result.gen receives only the Err values that exist at runtime.\nconst runResultGenerator = Result.gen as RuntimeResultGenerator\n\n/**\n * Compose `better-result` operations while preserving Service requirements in\n * a declaration-only type channel.\n *\n * A generator may yield Service tokens and Result operations. It must return a\n * `Result` as its final value; Service yields are resolved by the active\n * Runtime and do not add runtime values to the Result stream.\n * Use `fn` when generator execution should wait for a Runtime boundary.\n *\n * @example\n * ```ts\n * const loadUser = Effect.gen(async function* () {\n * const database = yield* Database\n * const user = yield* Result.await(database.findUser('u1'))\n *\n * return Result.ok(user)\n * })\n * ```\n */\nexport function gen<Yield extends EffectYield, Returned extends AnyResult>(\n body: () => Generator<Yield, Returned, unknown>\n): EffectFromGenerator<Yield, Returned>\n\nexport function gen<Yield extends EffectYield, Returned extends AnyResult>(\n body: () => AsyncGenerator<Yield, Returned, unknown>\n): Promise<EffectFromGenerator<Yield, Returned>>\n\nexport function gen(body: EffectGenerator): AnyResult | Promise<AnyResult> {\n return runResultGenerator(body)\n}\n\n/** Build a lazy Program without running its generator. */\nexport function fn<Yield extends EffectYield, Returned extends AnyResult>(\n body: () => Generator<Yield, Returned, unknown>\n): ProgramFromGenerator<Yield, Returned>\n\nexport function fn<Yield extends EffectYield, Returned extends AnyResult>(\n body: () => AsyncGenerator<Yield, Returned, unknown>\n): ProgramFromGenerator<Yield, Returned>\n\nexport function fn(body: EffectGenerator): Program<any, any, AnyService> {\n const program = () => runResultGenerator(body)\n\n // SAFETY: The generator overloads derive the Program channels; this cast only adds the declaration-only nominal marker.\n return program as Program<any, any, AnyService>\n}\n\nconst validateProgramConcurrency = (concurrency: number | undefined): void => {\n if (\n concurrency !== undefined &&\n (!Number.isFinite(concurrency) || !Number.isInteger(concurrency) || concurrency <= 0)\n ) {\n throw new RangeError('Program.all concurrency must be a positive integer')\n }\n}\n\n/** Build a lazy Program collection with optional bounded concurrency. */\nexport function programAll<const Programs extends readonly AnyProgram[]>(\n programs: Programs,\n options: ProgramAllOptions = {}\n): ProgramAllResult<Programs> {\n validateProgramConcurrency(options.concurrency)\n\n const concurrency = options.concurrency\n const program = async (): Promise<AnyResult> => {\n const results: Array<AnyResult | undefined> = Array.from({ length: programs.length })\n const failures: boolean[] = Array.from({ length: programs.length }, () => false)\n const causes: unknown[] = Array.from({ length: programs.length })\n let nextIndex = 0\n\n const worker = async (): Promise<void> => {\n while (true) {\n const index = nextIndex++\n\n if (index >= programs.length) {\n return\n }\n\n try {\n results[index] = await programs[index]!()\n } catch (cause) {\n failures[index] = true\n causes[index] = cause\n }\n }\n }\n\n const workers = Math.min(concurrency ?? programs.length, programs.length)\n await Promise.all(Array.from({ length: workers }, () => worker()))\n\n const failureIndex = failures.findIndex(Boolean)\n\n if (failureIndex >= 0) {\n throw causes[failureIndex]\n }\n\n // SAFETY: Program's callable contract produces Result values; the array is erased only at this collection boundary.\n return Result.all(results as AnyResult[])\n }\n\n // SAFETY: Program channels are declaration-only and are restored from the input tuple here.\n return program as ProgramAllResult<Programs>\n}\n\n/** Value-level namespace for lazy Program combinators. */\nexport const Program = {\n all: programAll\n} as const\n\n/**\n * Acquire a resource in the current Scope and register its release callback.\n *\n * Acquisition failures are represented in the Effect Result error channel;\n * release failures remain owned by Scope cleanup. The release callback\n * receives the final outcome chosen by the enclosing execution boundary.\n *\n * @example\n * ```ts\n * const connection = yield* Effect.acquireRelease(\n * () => pool.connect(),\n * (connection, outcome) => connection.close(outcome)\n * )\n * ```\n */\nexport function acquireRelease<R>(\n acquire: () => MaybePromise<R>,\n release: (resource: R, outcome: ScopeOutcome) => MaybePromise<void>\n): AsyncGenerator<Err<never, UnhandledException>, R, unknown> {\n const scope = Scope.current()\n\n return Result.await(Result.tryPromise(() => scope.acquire(acquire, release)))\n}\n\n/**\n * Register an already-acquired disposable resource in the current Scope.\n *\n * The resource is not acquired by this helper. Registration failures are\n * represented in the Effect Result error channel; disposal failures remain\n * owned by Scope cleanup.\n *\n * @example\n * ```ts\n * const file = yield* Effect.add(await openFile('notes.txt'))\n * ```\n */\nexport function add<R extends DisposableResource>(\n resource: R\n): AsyncGenerator<Err<never, UnhandledException>, R, unknown> {\n const scope = Scope.current()\n\n return Result.await(Result.tryPromise(() => scope.add(resource)))\n}\n\n/**\n * Effect namespace containing generator, resource, and Result combinators.\n *\n * Prefer these helpers when a program needs typed Service requirements or\n * Scope-aware acquisition and cleanup.\n */\ntype EffectNamespace = {\n readonly gen: typeof gen\n readonly fn: typeof fn\n readonly acquireRelease: typeof acquireRelease\n readonly add: typeof add\n readonly map: typeof map\n readonly mapError: typeof mapError\n readonly andThen: typeof andThen\n readonly andThenAsync: typeof andThenAsync\n readonly tap: typeof tap\n readonly tapError: typeof tapError\n readonly tapBoth: typeof tapBoth\n readonly recover: typeof recover\n readonly recoverAsync: typeof recoverAsync\n readonly flatten: typeof flatten\n readonly as: typeof as\n readonly asVoid: typeof asVoid\n readonly match: typeof match\n readonly all: typeof all\n readonly zip: typeof zip\n}\n\nexport const Effect: EffectNamespace = {\n /** Compose a generator-based Effect program. */\n gen,\n /** Build a lazy Program from a generator. */\n fn,\n /** Acquire and register a resource in the current Scope. */\n acquireRelease,\n /** Register an already-acquired disposable in the current Scope. */\n add,\n /** Map a successful Effect result. */\n map,\n /** Map an Effect error. */\n mapError,\n /** Chain a synchronous Effect result. */\n andThen,\n /** Chain an asynchronous Effect result. */\n andThenAsync,\n /** Observe successful values without changing the Result. */\n tap,\n /** Observe error values without changing the Result. */\n tapError,\n /** Observe the active Result branch without changing the Result. */\n tapBoth,\n /** Recover an error with another Effect. */\n recover,\n /** Recover an error asynchronously with another Effect. */\n recoverAsync,\n /** Remove one nested Effect layer. */\n flatten,\n /** Replace a successful value. */\n as,\n /** Replace a successful value with void. */\n asVoid,\n /** Match either Result branch. */\n match,\n /** Collect Effects in input order. */\n all,\n /** Zip two Effects in input order. */\n zip\n} as const\n\n/** Type-level aliases for inspecting Effect result channels and requirements. */\nexport declare namespace Effect {\n /** A nominal lazy computation that produces an Effect when invoked. */\n export type Program<A, E, R extends AnyService = never> = LazyProgram<A, E, R>\n\n /** Extract the success channel from an Effect result or Promise. */\n export type Success<T> = EffectSuccess<T>\n\n /** Extract the error channel from an Effect result or Promise. */\n export type Error<T> = EffectError<T>\n\n /** Extract the Service requirements from an Effect result or Promise. */\n export type Requirements<T> = EffectRequirements<T>\n\n /** An Effect with erased success, error, and requirements. */\n export type Any = AnyEffect\n}\n","type Unary<A, B> = (value: A) => B\n\n/**\n * Compose a value through a sequence of unary functions.\n *\n * `pipe` is deliberately independent of Effect, Result, Promise, Scope, and\n * Service metadata.\n *\n * @example\n * ```ts\n * const label = pipe(\n * 'alice',\n * (name) => name.trim(),\n * (name) => name.toUpperCase()\n * )\n * ```\n */\ntype PipeRuntimeValue = Parameters<Unary<any, any>>[0]\n\ntype PipeRuntimeOperation = Unary<PipeRuntimeValue, PipeRuntimeValue>\n\nexport function pipe<A>(value: A): A\nexport function pipe<A, B>(value: A, ab: Unary<A, B>): B\nexport function pipe<A, B, C>(value: A, ab: Unary<A, B>, bc: Unary<B, C>): C\nexport function pipe<A, B, C, D>(value: A, ab: Unary<A, B>, bc: Unary<B, C>, cd: Unary<C, D>): D\nexport function pipe<A, B, C, D, E>(\n value: A,\n ab: Unary<A, B>,\n bc: Unary<B, C>,\n cd: Unary<C, D>,\n de: Unary<D, E>\n): E\nexport function pipe<A, B, C, D, E, F>(\n value: A,\n ab: Unary<A, B>,\n bc: Unary<B, C>,\n cd: Unary<C, D>,\n de: Unary<D, E>,\n ef: Unary<E, F>\n): F\nexport function pipe<A, B, C, D, E, F, G>(\n value: A,\n ab: Unary<A, B>,\n bc: Unary<B, C>,\n cd: Unary<C, D>,\n de: Unary<D, E>,\n ef: Unary<E, F>,\n fg: Unary<F, G>\n): G\nexport function pipe<A, B, C, D, E, F, G, H>(\n value: A,\n ab: Unary<A, B>,\n bc: Unary<B, C>,\n cd: Unary<C, D>,\n de: Unary<D, E>,\n ef: Unary<E, F>,\n fg: Unary<F, G>,\n gh: Unary<G, H>\n): H\nexport function pipe<A, B, C, D, E, F, G, H, I>(\n value: A,\n ab: Unary<A, B>,\n bc: Unary<B, C>,\n cd: Unary<C, D>,\n de: Unary<D, E>,\n ef: Unary<E, F>,\n fg: Unary<F, G>,\n gh: Unary<G, H>,\n hi: Unary<H, I>\n): I\nexport function pipe<A, B, C, D, E, F, G, H, I, J>(\n value: A,\n ab: Unary<A, B>,\n bc: Unary<B, C>,\n cd: Unary<C, D>,\n de: Unary<D, E>,\n ef: Unary<E, F>,\n fg: Unary<F, G>,\n gh: Unary<G, H>,\n hi: Unary<H, I>,\n ij: Unary<I, J>\n): J\nexport function pipe<A, B, C, D, E, F, G, H, I, J, K>(\n value: A,\n ab: Unary<A, B>,\n bc: Unary<B, C>,\n cd: Unary<C, D>,\n de: Unary<D, E>,\n ef: Unary<E, F>,\n fg: Unary<F, G>,\n gh: Unary<G, H>,\n hi: Unary<H, I>,\n ij: Unary<I, J>,\n jk: Unary<J, K>\n): K\nexport function pipe(\n value: PipeRuntimeValue,\n ...operations: ReadonlyArray<PipeRuntimeOperation>\n): PipeRuntimeValue {\n return operations.reduce((current, operation) => operation(current), value)\n}\n","import { TaggedError } from 'better-result'\n\n/** Describes a failure encountered while releasing a Resource. */\nexport class ResourceReleaseFailure extends TaggedError('ResourceReleaseFailure')<{\n readonly resource: string\n readonly cause: unknown\n readonly message: string\n}> {}\n","import { Result, type Result as ResultType, type UnhandledException } from 'better-result'\n\nimport { ResourceReleaseFailure } from './errors'\n\nimport { disposeResource } from '../scope/disposable'\n\nexport { disposeResource }\n\nimport type { AsyncResult, MaybePromise, ReleaseFailureObserver, ReleaseOutcome } from './types'\n\nconst toReleaseFailure = (resource: string, cause: unknown): ResourceReleaseFailure =>\n new ResourceReleaseFailure({\n resource,\n cause,\n message: `Failed to release resource: ${resource}`\n })\n\nexport const runResult = async <T, E>(\n operation: () => AsyncResult<T, E>\n): Promise<ResultType<T, E | UnhandledException>> => {\n const execution = await Result.tryPromise(() => Promise.resolve(operation()))\n\n return execution.andThen((result) => result)\n}\n\nconst normalizeReleaseOutcome = (\n name: string,\n outcome: ReleaseOutcome\n): ResultType<void, ResourceReleaseFailure> => {\n if (outcome === undefined) {\n return Result.ok()\n }\n\n return outcome.mapError((cause) => toReleaseFailure(name, cause))\n}\n\nexport const runRelease = async <R>(\n name: string,\n resource: R,\n release: (resource: R) => MaybePromise<ReleaseOutcome>\n): Promise<ResultType<void, ResourceReleaseFailure>> => {\n const execution = await Result.tryPromise({\n try: () => Promise.resolve(release(resource)),\n catch: (cause) => toReleaseFailure(name, cause)\n })\n\n return execution.andThen((outcome) => normalizeReleaseOutcome(name, outcome))\n}\n\nconst notifyReleaseFailure = async (\n observer: ReleaseFailureObserver | undefined,\n\n failure: ResourceReleaseFailure\n): Promise<void> => {\n if (!observer) {\n return\n }\n\n try {\n await observer(failure)\n } catch {\n /*\n * Diagnostics must never replace\n * the actual operation error.\n */\n }\n}\n\nexport const combineUseAndRelease = async <A, E>(\n used: ResultType<A, E>,\n\n released: ResultType<void, ResourceReleaseFailure>,\n\n onReleaseFailure?: ReleaseFailureObserver\n): Promise<ResultType<A, E | ResourceReleaseFailure>> => {\n if (Result.isError(used)) {\n if (Result.isError(released)) {\n await notifyReleaseFailure(onReleaseFailure, released.error)\n }\n\n return Result.err<A, E | ResourceReleaseFailure>(used.error)\n }\n\n if (Result.isError(released)) {\n await notifyReleaseFailure(onReleaseFailure, released.error)\n\n return Result.err<A, E | ResourceReleaseFailure>(released.error)\n }\n\n return Result.ok<A, E | ResourceReleaseFailure>(used.value)\n}\n","import { Result, type Result as ResultType, type UnhandledException } from 'better-result'\n\nimport { Scope } from '../scope'\n\nimport { ResourceReleaseFailure } from './errors'\n\nimport { combineUseAndRelease, disposeResource, runRelease, runResult } from './internal'\n\nimport type { AcquireUseReleaseOptions } from './types'\n\n/**\n * Acquire a resource, use it, and always attempt release afterward.\n *\n * Acquisition, use, and release may be synchronous or asynchronous Result\n * operations. If both use and release fail, the use error remains primary and\n * `onReleaseFailure` receives the cleanup failure as a diagnostic.\n *\n * When `release` is omitted, `Symbol.asyncDispose` is preferred over\n * `Symbol.dispose`.\n *\n * @example\n * ```ts\n * const result = await Resource.acquireUseRelease({\n * name: 'database connection',\n * acquire: () => connect(),\n * use: (connection) => query(connection),\n * release: (connection) => connection.close()\n * })\n * ```\n */\nconst acquireUseRelease = <R, A, AcquireError, UseError>({\n name,\n acquire,\n use,\n release = disposeResource,\n onReleaseFailure\n}: AcquireUseReleaseOptions<R, A, AcquireError, UseError>): Promise<\n ResultType<A, AcquireError | UseError | UnhandledException | ResourceReleaseFailure>\n> =>\n Result.gen(async function* () {\n const resource = yield* Result.await(runResult(acquire))\n\n const scope = Scope.make()\n\n let released: ResultType<void, ResourceReleaseFailure> = Result.ok()\n\n scope.addFinalizer(async () => {\n released = await runRelease(name, resource, release)\n })\n\n const used = await runResult(() => use(resource))\n\n await scope.close()\n\n return await combineUseAndRelease(used, released, onReleaseFailure)\n })\n\nexport const Resource = {\n /** Acquire, use, and release a resource with deterministic error precedence. */\n acquireUseRelease\n} as const\n","import { Result } from 'better-result'\n\nimport type { Result as ResultType } from 'better-result'\n\nimport type { LayerDisposeError } from '../layer/errors'\n\nimport type { LayerBackend } from '../layer/backend'\n\nimport type { CleanupFailureDiagnostic, MaybePromise, ScopeOutcome } from '../scope'\n\nimport type { RuntimeContextStorage } from './context'\n\nimport type { RuntimeObserver } from './observer'\n\n/** Aggregated cleanup information reported during Runtime shutdown. */\nexport type RuntimeShutdownDiagnostic = {\n /** Final outcome supplied to the Runtime root Scope. */\n readonly outcome: ScopeOutcome\n /** Aggregated root-Scope and backend cleanup failure. */\n readonly error: LayerDisposeError\n}\n\n/** Observer notified about cleanup failures without changing primary results. */\nexport type CleanupFailureObserver = (\n diagnostic: CleanupFailureDiagnostic | RuntimeShutdownDiagnostic\n) => MaybePromise<void>\n\n/** Optional Runtime configuration for cleanup diagnostics. */\nexport type RuntimeOptions = {\n /** Backend used to register and resolve the Layer. Defaults to MapLayerBackend. */\n readonly backend?: LayerBackend\n /** Resolve every Layer provider before Runtime.make resolves. */\n readonly warmup?: boolean\n /** Best-effort lifecycle and Service resolution observers. */\n readonly observers?: readonly RuntimeObserver[]\n /** Optional observer for best-effort cleanup diagnostics. */\n readonly onCleanupFailure?: CleanupFailureObserver\n /** Context storage used by Service, Scope and Layer resolution. */\n readonly contextStorage?: RuntimeContextStorage\n /** Optional signal exposed through the RuntimeContext. */\n readonly signal?: AbortSignal\n}\n\n/** Optional signal supplied to one managed Runtime execution. */\nexport type RuntimeRunOptions = {\n readonly signal?: AbortSignal\n}\n\n/** Cooperative shutdown policy for a managed Runtime. */\nexport type RuntimeDisposeOptions = {\n /** Time to let active executions settle before requesting cancellation. */\n readonly gracePeriod?: number\n /** Abort active execution signals after the grace period expires. */\n readonly abortAfterGracePeriod?: boolean\n}\n\ntype ResultLike = ResultType<any, any>\n\nconst isResultLike = <A>(value: A): value is A & ResultLike => {\n const candidate = Object(value)\n const tag = Object.prototype.toString.call(value)\n\n return (\n tag !== '[object Function]' &&\n 'status' in candidate &&\n (candidate.status === 'ok' || candidate.status === 'error')\n )\n}\n\nexport const classifyRuntimeOutcome = <A>(value: A): ScopeOutcome => {\n if (isResultLike(value) && Result.isError(value)) {\n return {\n status: 'failure',\n cause: value.error\n }\n }\n\n return {\n status: 'success'\n }\n}\n","import type { AnyServiceToken } from '../service'\nimport type { Scope } from '../scope'\nimport type { ScopeOutcome } from '../scope'\nimport type { MaybePromise } from '../utils/types'\n\n/** Event emitted after a Service resolution attempt settles. */\nexport type RuntimeServiceResolveEvent = {\n readonly service: AnyServiceToken\n readonly resolutionPath: readonly AnyServiceToken[]\n readonly outcome: ScopeOutcome\n}\n\n/** Event emitted after a provider acquisition attempt settles. */\nexport type RuntimeServiceAcquireEvent = {\n readonly service: AnyServiceToken\n readonly resolutionPath: readonly AnyServiceToken[]\n readonly outcome: ScopeOutcome\n}\n\n/** Event emitted immediately before a program starts in an execution Scope. */\nexport type RuntimeExecutionStartEvent = {\n readonly scope: Scope\n}\n\n/** Event emitted after a program and its execution Scope settle. */\nexport type RuntimeExecutionEndEvent = {\n readonly scope: Scope\n readonly outcome: ScopeOutcome\n}\n\n/** Event emitted after a Layer provider release callback settles. */\nexport type RuntimeResourceReleaseEvent = {\n readonly service: AnyServiceToken\n readonly outcome: ScopeOutcome\n readonly error?: unknown\n}\n\n/** Optional best-effort hooks for Runtime lifecycle and resolution events. */\nexport type RuntimeObserver = {\n readonly onServiceResolve?: (event: RuntimeServiceResolveEvent) => MaybePromise<void>\n readonly onServiceAcquire?: (event: RuntimeServiceAcquireEvent) => MaybePromise<void>\n readonly onExecutionStart?: (event: RuntimeExecutionStartEvent) => MaybePromise<void>\n readonly onExecutionEnd?: (event: RuntimeExecutionEndEvent) => MaybePromise<void>\n readonly onResourceRelease?: (event: RuntimeResourceReleaseEvent) => MaybePromise<void>\n}\n\nexport const notifyRuntimeObservers = <Event>(\n observers: readonly RuntimeObserver[],\n select: (observer: RuntimeObserver) => ((event: Event) => MaybePromise<void>) | undefined,\n event: Event\n): void => {\n for (const observer of observers) {\n const callback = select(observer)\n\n if (!callback) {\n continue\n }\n\n try {\n void Promise.resolve(callback(event)).catch(() => {})\n } catch {\n // Observability must never change the Runtime result.\n }\n }\n}\n","import {\n CircularDependencyError,\n ServiceAcquisitionError,\n ServiceNotFoundError,\n type AnyServiceToken,\n type ServiceResolver\n} from '../service'\n\nimport { getRuntimeContext, makeRuntimeContext, runRuntimeContext } from '../runtime/context'\n\nimport { defaultRuntimeContextStorage } from '../runtime/default'\n\nimport type { RuntimeContextStorage } from '../runtime/context'\n\nimport { notifyRuntimeObservers, type RuntimeObserver } from '../runtime/observer'\n\nimport type { ScopeOutcome } from '../scope'\n\nimport { ServiceTagCollisionError } from './errors'\n\nconst findCycleStart = (path: readonly AnyServiceToken[], token: AnyServiceToken): number =>\n path.findIndex((current) => current.serviceTag === token.serviceTag)\n\nconst shouldPreserve = (cause: unknown): boolean =>\n cause instanceof CircularDependencyError ||\n cause instanceof ServiceAcquisitionError ||\n cause instanceof ServiceNotFoundError ||\n cause instanceof ServiceTagCollisionError\n\n/** Wrap a backend with Runtime-local resolution paths and acquisition errors. */\nexport const createResolutionResolver = (\n resolver: ServiceResolver,\n storage: RuntimeContextStorage = defaultRuntimeContextStorage,\n observers: readonly RuntimeObserver[] = []\n): ServiceResolver => {\n const wrapped: ServiceResolver = {\n async resolve<T extends AnyServiceToken>(token: T): Promise<InstanceType<T>> {\n const context = getRuntimeContext(storage)\n const path = context?.resolutionPath ?? []\n const cycleStart = findCycleStart(path, token)\n const resolutionPath = [...path, token]\n\n const notifyResolve = (outcome: ScopeOutcome): void => {\n notifyRuntimeObservers(observers, (observer) => observer.onServiceResolve, {\n service: token,\n resolutionPath,\n outcome\n })\n }\n\n if (cycleStart >= 0) {\n const error = new CircularDependencyError([...path.slice(cycleStart), token])\n notifyResolve({ status: 'failure', cause: error })\n throw error\n }\n\n const nextContext = makeRuntimeContext(\n wrapped,\n context?.scope,\n resolutionPath,\n context?.signal\n )\n\n return await runRuntimeContext(storage, nextContext, async () => {\n try {\n const instance = await resolver.resolve(token)\n notifyResolve({ status: 'success' })\n return instance\n } catch (cause) {\n if (shouldPreserve(cause)) {\n notifyResolve({ status: 'failure', cause })\n throw cause\n }\n\n const error = new ServiceAcquisitionError(token, resolutionPath, cause)\n notifyResolve({ status: 'failure', cause: error })\n throw error\n }\n })\n }\n }\n\n return wrapped\n}\n","import type { AnyService, AnyServiceToken, ServiceResolver } from '../service'\n\nimport { Scope, type CloseableScope } from '../scope'\nimport { runScoped } from '../scope/internal'\nimport { ScopeRuntime } from '../scope/runtime'\n\nimport {\n getRuntimeContext,\n makeRuntimeContext,\n runRuntimeContext,\n type RuntimeContextStorage\n} from '../runtime/context'\n\nimport { defaultRuntimeContextStorage } from '../runtime/default'\n\nimport {\n classifyRuntimeOutcome,\n type CleanupFailureObserver,\n type RuntimeDisposeOptions,\n type RuntimeOptions,\n type RuntimeRunOptions,\n type RuntimeShutdownDiagnostic\n} from '../runtime/outcome'\n\nimport { linkAbortSignals, type AbortSignalLink } from '../runtime/signal'\n\nimport { LayerDisposeError, LayerRegistrationError } from './errors'\n\nimport { createResolutionResolver } from './resolution'\n\nimport { notifyRuntimeObservers, type RuntimeObserver } from '../runtime/observer'\n\nimport type { LayerBackend } from './backend'\n\nimport { MapLayerBackend } from './map-layer-backend'\n\nimport type {\n CompleteExecution,\n CompleteExecutionLayer,\n CompleteInput,\n LayerInput,\n ProvidedEnvironment\n} from './inference'\n\nimport type { LayerRegistration } from './types'\n\nimport type { ScopeOutcome } from '../scope'\n\ntype LayerProvider = LayerInput['providers'][number]\n\ninterface RuntimeHandleCore<Provided extends AnyService> {\n /** The backend used to resolve this Layer's providers. */\n readonly backend: LayerBackend\n\n /** Run a program in a child Scope of the Layer's root Scope. */\n run<A>(program: CompleteExecution<Provided, A>, options?: RuntimeRunOptions): Promise<Awaited<A>>\n\n /** Run a program with providers owned by that execution's child Scope. */\n runWith<Request extends LayerInput, A>(\n layer: Request & CompleteExecutionLayer<Provided, Request>,\n program: CompleteExecution<Provided | ProvidedEnvironment<Request>, A>,\n options?: RuntimeRunOptions\n ): Promise<Awaited<A>>\n\n /** Resolve every registered provider before accepting normal executions. */\n warmup(): Promise<void>\n\n /** Stop new executions and release Layer-owned resources. */\n dispose(input?: RuntimeDisposeOptions | ScopeOutcome): Promise<void>\n}\n\n/** Runtime-facing handle that owns a Layer's resources and execution scopes. */\nexport type RuntimeHandle<Provided extends AnyService = any> = RuntimeHandleCore<Provided>\n\nconst SCOPE_SUCCESS: ScopeOutcome = Object.freeze({ status: 'success' })\n\nclass RuntimeHandleDisposedError extends Error {\n constructor() {\n super('Cannot run a program using a disposed Layer')\n\n this.name = 'RuntimeHandleDisposedError'\n }\n}\n\nconst normalizeDisposeCauses = (cause: unknown): readonly unknown[] => {\n if (cause instanceof AggregateError) {\n return [...cause.errors]\n }\n\n return [cause]\n}\n\nconst isScopeOutcome = (\n input: RuntimeDisposeOptions | ScopeOutcome | undefined\n): input is ScopeOutcome => input !== undefined && 'status' in input\n\nconst validateDisposeOptions = (options: RuntimeDisposeOptions): void => {\n const { gracePeriod } = options\n\n if (gracePeriod !== undefined && (!Number.isFinite(gracePeriod) || gracePeriod < 0)) {\n throw new RangeError('Runtime dispose gracePeriod must be a finite non-negative number')\n }\n}\n\ntype ActiveExecution = {\n readonly promise: Promise<unknown>\n}\n\nconst notifyShutdownFailure = async (\n observer: CleanupFailureObserver | undefined,\n diagnostic: RuntimeShutdownDiagnostic\n): Promise<void> => {\n if (!observer) {\n return\n }\n\n try {\n await observer(diagnostic)\n } catch {\n // Shutdown diagnostics are best effort and never affect the primary result.\n }\n}\n\nconst bindProviderToScope = (\n provider: LayerProvider,\n scope: CloseableScope,\n contextStorage: RuntimeContextStorage,\n resolver: ServiceResolver,\n observers: readonly RuntimeObserver[]\n): LayerRegistration => ({\n service: provider.service,\n\n acquire: () => {\n const current = getRuntimeContext(contextStorage)\n const context = makeRuntimeContext(\n resolver,\n scope,\n current?.resolutionPath ?? [],\n current?.signal\n )\n\n return runRuntimeContext(contextStorage, context, () =>\n ScopeRuntime.run(\n scope,\n async () => {\n const resolutionPath = current?.resolutionPath ?? [provider.service]\n\n try {\n const instance = provider.release\n ? await scope.acquire(\n () => provider.acquire(),\n async (resource, outcome) => {\n try {\n await provider.release!(resource, outcome)\n notifyRuntimeObservers(observers, (observer) => observer.onResourceRelease, {\n service: provider.service,\n outcome\n })\n } catch (cause) {\n notifyRuntimeObservers(observers, (observer) => observer.onResourceRelease, {\n service: provider.service,\n outcome,\n error: cause\n })\n throw cause\n }\n }\n )\n : await provider.acquire()\n\n notifyRuntimeObservers(observers, (observer) => observer.onServiceAcquire, {\n service: provider.service,\n resolutionPath,\n outcome: SCOPE_SUCCESS\n })\n\n return instance\n } catch (cause) {\n notifyRuntimeObservers(observers, (observer) => observer.onServiceAcquire, {\n service: provider.service,\n resolutionPath,\n outcome: {\n status: 'failure',\n cause\n }\n })\n throw cause\n }\n },\n contextStorage\n )\n )\n }\n})\n\n/** Resolve request-local providers first, then fall back to the Runtime root. */\nclass ExecutionLayerBackend implements LayerBackend {\n private readonly localTags = new Set<string>()\n\n constructor(\n private readonly local: MapLayerBackend,\n private readonly root: LayerBackend\n ) {}\n\n register(registration: LayerRegistration): void {\n this.localTags.add(registration.service.serviceTag)\n this.local.register(registration)\n }\n\n async resolve<T extends AnyServiceToken>(token: T): Promise<InstanceType<T>> {\n if (this.localTags.has(token.serviceTag)) {\n return await this.local.resolve(token)\n }\n\n return await this.root.resolve(token)\n }\n\n async disposeAll(): Promise<void> {\n await this.local.disposeAll()\n this.localTags.clear()\n }\n}\n\nclass RuntimeHandleImpl<Provided extends AnyService> implements RuntimeHandleCore<Provided> {\n private disposePromise: Promise<void> | undefined\n\n private warmupPromise: Promise<void> | undefined\n\n private readonly executions = new Set<ActiveExecution>()\n\n private readonly shutdownController = new AbortController()\n\n private state: 'active' | 'disposing' | 'disposed' = 'active'\n\n constructor(\n readonly backend: LayerBackend,\n private readonly resolver: ServiceResolver,\n private readonly rootScope: CloseableScope,\n private readonly onCleanupFailure: CleanupFailureObserver | undefined,\n private readonly contextStorage: RuntimeContextStorage,\n private readonly signal: AbortSignal | undefined,\n private readonly observers: readonly RuntimeObserver[],\n private readonly services: readonly AnyServiceToken[]\n ) {}\n\n run<A>(\n program: CompleteExecution<Provided, A>,\n options?: RuntimeRunOptions\n ): Promise<Awaited<A>> {\n this.assertActive()\n\n const executionScope = this.rootScope.fork()\n const signalLink = linkAbortSignals(\n this.signal,\n options?.signal,\n this.shutdownController.signal\n )\n\n return this.startExecution<Awaited<A>>(signalLink, () =>\n this.runExecution(executionScope, program, this.resolver, signalLink.signal)\n )\n }\n\n runWith<Request extends LayerInput, A>(\n layer: Request & CompleteExecutionLayer<Provided, Request>,\n program: CompleteExecution<Provided | ProvidedEnvironment<Request>, A>,\n options?: RuntimeRunOptions\n ): Promise<Awaited<A>> {\n this.assertActive()\n\n const executionScope = this.rootScope.fork()\n const localBackend = new MapLayerBackend()\n const backend = new ExecutionLayerBackend(localBackend, this.backend)\n const resolver = createResolutionResolver(backend, this.contextStorage, this.observers)\n const signalLink = linkAbortSignals(\n this.signal,\n options?.signal,\n this.shutdownController.signal\n )\n\n return this.startExecution<Awaited<A>>(signalLink, async (): Promise<Awaited<A>> => {\n try {\n return await this.runExecution<Awaited<A>>(\n executionScope,\n async (): Promise<Awaited<A>> => {\n for (const provider of layer.providers) {\n backend.register(\n bindProviderToScope(\n provider,\n executionScope,\n this.contextStorage,\n resolver,\n this.observers\n )\n )\n }\n\n return await program()\n },\n resolver,\n signalLink.signal\n )\n } finally {\n await localBackend.disposeAll()\n }\n })\n }\n\n warmup(): Promise<void> {\n this.assertActive()\n\n if (this.warmupPromise) {\n return this.warmupPromise\n }\n\n const warmup = runRuntimeContext(\n this.contextStorage,\n makeRuntimeContext(this.resolver, this.rootScope, [], this.signal),\n async () => {\n for (const service of this.services) {\n await this.resolver.resolve(service)\n }\n }\n )\n\n this.warmupPromise = warmup\n\n void warmup.then(\n () => {\n if (this.warmupPromise === warmup) {\n this.warmupPromise = undefined\n }\n },\n () => {\n if (this.warmupPromise === warmup) {\n this.warmupPromise = undefined\n }\n }\n )\n\n return warmup\n }\n\n private startExecution<A>(signalLink: AbortSignalLink, run: () => PromiseLike<A>): Promise<A> {\n let resolveExecution!: (value: A | PromiseLike<A>) => void\n let rejectExecution!: (cause?: unknown) => void\n\n const execution = new Promise<A>((resolve, reject) => {\n resolveExecution = resolve\n rejectExecution = reject\n })\n\n const activeExecution: ActiveExecution = { promise: execution }\n\n this.executions.add(activeExecution)\n\n void execution.then(\n () => {\n this.executions.delete(activeExecution)\n signalLink.dispose()\n },\n () => {\n this.executions.delete(activeExecution)\n signalLink.dispose()\n }\n )\n\n try {\n const running = run()\n\n void running.then(\n (value) => {\n resolveExecution(value)\n },\n (cause) => {\n rejectExecution(cause)\n }\n )\n } catch (cause) {\n rejectExecution(cause)\n }\n\n return execution\n }\n\n private runExecution<A>(\n executionScope: CloseableScope,\n program: () => A | PromiseLike<A>,\n resolver: ServiceResolver = this.resolver,\n signal: AbortSignal = this.shutdownController.signal\n ): Promise<Awaited<A>> {\n const options = this.onCleanupFailure\n ? {\n classify: classifyRuntimeOutcome,\n onCleanupFailure: this.onCleanupFailure\n }\n : {\n classify: classifyRuntimeOutcome\n }\n\n notifyRuntimeObservers(this.observers, (observer) => observer.onExecutionStart, {\n scope: executionScope\n })\n\n const execution = runScoped(executionScope, program, {\n ...options,\n contextStorage: this.contextStorage,\n context: makeRuntimeContext(resolver, executionScope, [], signal)\n })\n\n return execution.then(\n (value) => {\n notifyRuntimeObservers(this.observers, (observer) => observer.onExecutionEnd, {\n scope: executionScope,\n outcome: classifyRuntimeOutcome(value)\n })\n return value\n },\n (cause) => {\n notifyRuntimeObservers(this.observers, (observer) => observer.onExecutionEnd, {\n scope: executionScope,\n outcome: {\n status: 'failure',\n cause\n }\n })\n throw cause\n }\n )\n }\n\n dispose(input?: RuntimeDisposeOptions | ScopeOutcome): Promise<void> {\n if (this.disposePromise) {\n return this.disposePromise\n }\n\n const outcome =\n isScopeOutcome(input) || input === undefined ? (input ?? SCOPE_SUCCESS) : SCOPE_SUCCESS\n const options = isScopeOutcome(input) || input === undefined ? {} : input\n\n validateDisposeOptions(options)\n this.state = 'disposing'\n\n const executions = [...this.executions]\n\n this.disposePromise = this.performDispose(executions, outcome, options)\n\n return this.disposePromise\n }\n\n private async performDispose(\n executions: readonly ActiveExecution[],\n outcome: ScopeOutcome,\n options: RuntimeDisposeOptions\n ): Promise<void> {\n const failures: unknown[] = []\n\n await Promise.allSettled(this.warmupPromise ? [this.warmupPromise] : [])\n await this.waitForExecutions(executions, options)\n\n try {\n const signalLink = linkAbortSignals(this.signal, this.shutdownController.signal)\n\n try {\n await runRuntimeContext(\n this.contextStorage,\n makeRuntimeContext(this.resolver, this.rootScope, [], signalLink.signal),\n () => this.rootScope.close(outcome)\n )\n } finally {\n signalLink.dispose()\n }\n } catch (cause) {\n failures.push(cause)\n }\n\n try {\n await this.backend.disposeAll()\n } catch (cause) {\n failures.push(cause)\n }\n\n this.state = 'disposed'\n\n if (failures.length > 0) {\n const error = new LayerDisposeError(failures.flatMap(normalizeDisposeCauses))\n\n await notifyShutdownFailure(this.onCleanupFailure, {\n outcome,\n error\n })\n\n throw error\n }\n }\n\n private async waitForExecutions(\n executions: readonly ActiveExecution[],\n options: RuntimeDisposeOptions\n ): Promise<void> {\n const settled = Promise.allSettled(executions.map((execution) => execution.promise))\n\n if (options.abortAfterGracePeriod !== true || executions.length === 0) {\n await settled\n return\n }\n\n const gracePeriod = options.gracePeriod ?? 0\n let timer: ReturnType<typeof setTimeout> | undefined\n\n const timedOut = await Promise.race([\n settled.then(() => false),\n new Promise<boolean>((resolve) => {\n timer = setTimeout(() => resolve(true), gracePeriod)\n })\n ])\n\n if (timer !== undefined) {\n clearTimeout(timer)\n }\n\n if (timedOut && !this.shutdownController.signal.aborted) {\n this.shutdownController.abort(new Error('Runtime shutdown grace period exceeded'))\n }\n\n await settled\n }\n\n private assertActive(): void {\n if (this.state !== 'active') {\n throw new RuntimeHandleDisposedError()\n }\n }\n}\n\n/** Build a Runtime handle for a complete Layer and register its providers. */\nexport const createRuntimeHandle = async <L extends LayerInput>(\n layer: L & CompleteInput<L>,\n backend: LayerBackend,\n options: RuntimeOptions = {}\n): Promise<RuntimeHandle<ProvidedEnvironment<L>>> => {\n const rootScope = Scope.make()\n const contextStorage = options.contextStorage ?? defaultRuntimeContextStorage\n const observers = options.observers ?? []\n const resolver = createResolutionResolver(backend, contextStorage, observers)\n ScopeRuntime.bind(rootScope, contextStorage)\n let current: LayerProvider | undefined\n\n try {\n for (const provider of layer.providers) {\n current = provider\n\n await backend.register(\n bindProviderToScope(provider, rootScope, contextStorage, resolver, observers)\n )\n }\n } catch (registrationCause) {\n const outcome: ScopeOutcome = {\n status: 'failure',\n cause: registrationCause\n }\n const cleanupCauses: unknown[] = []\n\n try {\n await runRuntimeContext(\n contextStorage,\n makeRuntimeContext(resolver, rootScope, [], options.signal),\n () => rootScope.close(outcome)\n )\n } catch (cause) {\n cleanupCauses.push(cause)\n }\n\n try {\n await backend.disposeAll()\n } catch (cause) {\n cleanupCauses.push(cause)\n }\n\n if (cleanupCauses.length > 0) {\n const shutdownError = new LayerDisposeError(cleanupCauses.flatMap(normalizeDisposeCauses))\n\n await notifyShutdownFailure(options.onCleanupFailure, {\n outcome,\n error: shutdownError\n })\n }\n\n const cleanupCause =\n cleanupCauses.length === 1\n ? cleanupCauses[0]\n : cleanupCauses.length > 1\n ? new LayerDisposeError(cleanupCauses.flatMap(normalizeDisposeCauses))\n : undefined\n\n throw new LayerRegistrationError(current?.service, registrationCause, cleanupCause)\n }\n\n return new RuntimeHandleImpl<ProvidedEnvironment<L>>(\n backend,\n resolver,\n rootScope,\n options.onCleanupFailure,\n contextStorage,\n options.signal,\n observers,\n layer.providers.map((provider) => provider.service)\n )\n}\n","import type { LayerBackend } from '../layer'\n\nimport { MapLayerBackend } from '../layer/map-layer-backend'\n\nimport { createRuntimeHandle, type RuntimeHandle } from '../layer/runtime'\n\nimport type {\n CompleteExecutionLayer,\n LayerInput,\n CompleteInput,\n ProvidedEnvironment\n} from '../layer/inference'\n\nimport type { CompleteExecution } from '../layer/inference'\n\nimport type { AnyService } from '../service'\n\nimport {\n classifyRuntimeOutcome,\n type RuntimeDisposeOptions,\n type RuntimeOptions,\n type RuntimeRunOptions,\n type RuntimeShutdownDiagnostic\n} from './outcome'\n\nimport type { ScopeOutcome } from '../scope'\n\nimport type { RuntimeFor } from './types'\n\ntype RuntimeBackendInput = LayerBackend | RuntimeOptions | undefined\n\ntype RuntimeConfig = {\n readonly backend: LayerBackend\n readonly options: RuntimeOptions\n}\n\nconst isLayerBackend = (value: RuntimeBackendInput): value is LayerBackend =>\n value !== undefined && 'register' in value && 'resolve' in value && 'disposeAll' in value\n\nconst resolveRuntimeConfig = (\n backendOrOptions: RuntimeBackendInput,\n legacyOptions?: RuntimeOptions\n): RuntimeConfig => {\n if (isLayerBackend(backendOrOptions)) {\n return {\n backend: backendOrOptions,\n options: legacyOptions ?? {}\n }\n }\n\n const options = backendOrOptions ?? {}\n\n return {\n backend: options.backend ?? new MapLayerBackend(),\n options\n }\n}\n\n/**\n * Long-lived execution environment backed by a complete Layer.\n *\n * A Runtime owns Layer resources until `dispose()` is called. Each `run()` is\n * isolated in a child Scope, while Layer-scoped resources remain shared.\n *\n * @example\n * ```ts\n * const runtime = await Runtime.make(AppLive)\n * const result = await runtime.run(loadUser('u1'))\n * await runtime.dispose()\n * ```\n *\n * @typeParam Provided The branded Service instances supplied by the Layer.\n */\nexport class Runtime<Provided extends AnyService = any> {\n private constructor(private readonly handle: RuntimeHandle<Provided>) {}\n\n /**\n * Create a long-lived Runtime that owns its Layer resources.\n *\n * @example\n * ```ts\n * const runtime = await Runtime.make(AppLive)\n * const result = await runtime.run(program)\n * await runtime.dispose()\n * ```\n */\n static make<L extends LayerInput>(\n layer: L & CompleteInput<L>,\n backend: LayerBackend,\n options?: RuntimeOptions\n ): Promise<Runtime<ProvidedEnvironment<L>>>\n\n static make<L extends LayerInput>(\n layer: L & CompleteInput<L>,\n options?: RuntimeOptions\n ): Promise<Runtime<ProvidedEnvironment<L>>>\n\n static async make<L extends LayerInput>(\n layer: L & CompleteInput<L>,\n backendOrOptions?: LayerBackend | RuntimeOptions,\n legacyOptions?: RuntimeOptions\n ): Promise<Runtime<ProvidedEnvironment<L>>> {\n const { backend, options } = resolveRuntimeConfig(backendOrOptions, legacyOptions)\n const handle = await createRuntimeHandle(layer, backend, options)\n const runtime = new Runtime<ProvidedEnvironment<L>>(handle)\n\n if (options.warmup) {\n await runtime.warmup()\n }\n\n return runtime\n }\n\n /**\n * Run one program and dispose its Layer resources before resolving.\n *\n * This is convenient for request-style or command-style execution where a\n * Runtime should not outlive the operation.\n */\n static run<A, L extends LayerInput>(\n layer: L & CompleteInput<L>,\n backend: LayerBackend,\n program: CompleteExecution<ProvidedEnvironment<L>, A>,\n options?: RuntimeOptions\n ): Promise<Awaited<A>>\n\n static run<A, L extends LayerInput>(\n layer: L & CompleteInput<L>,\n program: CompleteExecution<ProvidedEnvironment<L>, A>,\n options?: RuntimeOptions\n ): Promise<Awaited<A>>\n\n static run<A, L extends LayerInput>(\n layer: L & CompleteInput<L>,\n options: RuntimeOptions,\n program: CompleteExecution<ProvidedEnvironment<L>, A>\n ): Promise<Awaited<A>>\n\n static async run<A, L extends LayerInput>(\n layer: L & CompleteInput<L>,\n backendOrProgramOrOptions:\n | LayerBackend\n | RuntimeOptions\n | CompleteExecution<ProvidedEnvironment<L>, A>,\n programOrOptions?: CompleteExecution<ProvidedEnvironment<L>, A> | RuntimeOptions,\n legacyOptions?: RuntimeOptions\n ): Promise<Awaited<A>> {\n let program: CompleteExecution<ProvidedEnvironment<L>, A>\n let backendOrOptions: RuntimeBackendInput\n let options: RuntimeOptions | undefined\n\n // oxlint-disable-next-line anti-slop/no-runtime-typeof -- overload dispatch needs to distinguish a Program callback from configuration.\n if (typeof backendOrProgramOrOptions === 'function') {\n program = backendOrProgramOrOptions\n // SAFETY: The function overload branch establishes that this argument is the optional RuntimeOptions value.\n backendOrOptions = programOrOptions as RuntimeOptions | undefined\n options = undefined\n } else {\n backendOrOptions = backendOrProgramOrOptions\n // SAFETY: The non-function overload branch establishes that this argument is the complete execution callback.\n program = programOrOptions as CompleteExecution<ProvidedEnvironment<L>, A>\n options = legacyOptions\n }\n\n const config = resolveRuntimeConfig(backendOrOptions, options)\n const runtime = await Runtime.make(layer, config.backend, config.options)\n\n let value!: Awaited<A>\n let executionFailed = false\n let executionFailure: unknown\n let programOutcome: ScopeOutcome | undefined\n\n try {\n value = await runtime.runUnchecked(async () => {\n try {\n const programValue = await program()\n\n programOutcome = classifyRuntimeOutcome(programValue)\n\n return programValue\n } catch (cause) {\n programOutcome = {\n status: 'failure',\n cause\n }\n\n throw cause\n }\n })\n } catch (cause) {\n executionFailed = true\n executionFailure = cause\n }\n\n const outcome: ScopeOutcome =\n programOutcome ??\n ({\n status: 'failure',\n cause: executionFailure\n } as const)\n\n try {\n await runtime.disposeWithOutcome(outcome)\n } catch (shutdownFailure) {\n if (!executionFailed && outcome.status === 'success') {\n throw shutdownFailure\n }\n }\n\n if (executionFailed) {\n throw executionFailure\n }\n\n return value\n }\n\n /** Run a callback with a managed Runtime and always dispose it afterward. */\n static use<A, L extends LayerInput>(\n layer: L & CompleteInput<L>,\n use: (runtime: Runtime<ProvidedEnvironment<L>>) => A | PromiseLike<A>,\n options?: RuntimeOptions\n ): Promise<Awaited<A>>\n\n static async use<A, L extends LayerInput>(\n layer: L & CompleteInput<L>,\n use: (runtime: Runtime<ProvidedEnvironment<L>>) => A | PromiseLike<A>,\n options?: RuntimeOptions\n ): Promise<Awaited<A>> {\n const runtime = await Runtime.make(layer, options)\n\n let value!: Awaited<A>\n let executionFailed = false\n let executionFailure: unknown\n let programOutcome: ScopeOutcome | undefined\n\n try {\n value = await use(runtime)\n programOutcome = classifyRuntimeOutcome(value)\n } catch (cause) {\n executionFailed = true\n executionFailure = cause\n programOutcome = {\n status: 'failure',\n cause\n }\n }\n\n const outcome: ScopeOutcome =\n programOutcome ??\n ({\n status: 'failure',\n cause: executionFailure\n } as const)\n\n try {\n await runtime.disposeWithOutcome(outcome)\n } catch (shutdownFailure) {\n if (!executionFailed && outcome.status === 'success') {\n throw shutdownFailure\n }\n }\n\n if (executionFailed) {\n throw executionFailure\n }\n\n return value\n }\n\n /** Resolve every Layer provider and dispose the Runtime if warmup fails. */\n async warmup(): Promise<void> {\n try {\n await this.handle.warmup()\n } catch (cause) {\n try {\n await this.handle.dispose({ status: 'failure', cause })\n } catch {\n // Warmup failure remains the primary error; cleanup is best effort.\n }\n\n throw cause\n }\n }\n\n /** Run one execution in this Runtime's child Scope. */\n run<A>(\n program: CompleteExecution<Provided, A>,\n options?: RuntimeRunOptions\n ): Promise<Awaited<A>> {\n return this.handle.run(program, options)\n }\n\n /** Run one execution with a Layer owned by that execution's child Scope. */\n runWith<Request extends LayerInput, A>(\n layer: Request & CompleteExecutionLayer<Provided, Request>,\n program: CompleteExecution<Provided | ProvidedEnvironment<Request>, A>,\n options?: RuntimeRunOptions\n ): Promise<Awaited<A>> {\n return this.handle.runWith(layer, program, options)\n }\n\n private runUnchecked<A>(program: () => A | PromiseLike<A>): Promise<Awaited<A>> {\n // SAFETY: One-shot Runtime.run performs the same complete-program validation at its public boundary before using this internal escape hatch.\n return this.handle.run(program as CompleteExecution<Provided, A>)\n }\n\n /** Stop new executions and release the Runtime's Layer resources. */\n dispose(options?: RuntimeDisposeOptions): Promise<void>\n\n /** @deprecated Scope outcomes are kept for internal compatibility. */\n dispose(outcome: ScopeOutcome): Promise<void>\n\n dispose(optionsOrOutcome?: RuntimeDisposeOptions | ScopeOutcome): Promise<void> {\n return this.handle.dispose(optionsOrOutcome)\n }\n\n /** Release Runtime-owned resources through JavaScript's async disposal protocol. */\n async [Symbol.asyncDispose](): Promise<void> {\n await this.dispose()\n }\n\n private disposeWithOutcome(outcome: ScopeOutcome): Promise<void> {\n return this.handle.dispose(outcome)\n }\n}\n\n/** Type-level aliases for naming Runtime handles and shutdown options. */\nexport declare namespace Runtime {\n /** Name a Runtime type from a concrete Layer. */\n export type For<L extends LayerInput> = RuntimeFor<L>\n\n /** Optional Runtime shutdown configuration. */\n export type Options = RuntimeOptions\n\n /** Optional signal supplied to one managed Runtime execution. */\n export type RunOptions = RuntimeRunOptions\n\n /** Cooperative shutdown policy for a managed Runtime. */\n export type DisposeOptions = RuntimeDisposeOptions\n\n /** Diagnostic reported for aggregated Runtime shutdown cleanup failures. */\n export type ShutdownDiagnostic = RuntimeShutdownDiagnostic\n}\n"],"mappings":";;;;;;;;AACA,IAAa,iCAAb,cAAoD,MAAM;CACxD,cAAc;EACZ,MAAM,wDAAwD;EAE9D,KAAK,OAAO;CACd;AACF;;AAGA,IAAa,mBAAb,cAAsC,MAAM;CAC1C,cAAc;EACZ,MAAM,sDAAsD;EAE5D,KAAK,OAAO;CACd;AACF;;AAGA,IAAa,kBAAb,cAAqC,MAAM;CACpB;CAArB,YAAY,QAAqC;EAC/C,MACE,0BAA0B,OAAO,OAAO,YAAY,OAAO,WAAW,IAAI,KAAK,IAAI,SACrF;EAHmB,KAAA,SAAA;EAKnB,KAAK,OAAO;CACd;AACF;;AAGA,IAAa,6BAAb,cAAgD,MAAM;CACpD,cAAc;EACZ,MAAM,mEAAmE;EAEzE,KAAK,OAAO;CACd;AACF;;;AClCA,MAAMA,kBAAgB,EAAE,QAAQ,UAAU;;AAW1C,MAAa,uBAAiC,aAAmD;CAE/F,MAAM,YAAY,OAAO,QAAQ;CACjC,MAAM,eAAe,UAAU,OAAO;CAEtC,IAAI,wBAAwB,UAC1B,aAAa,aAAa,KAAK,QA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B;IACf,QAAQ;IACR;GACF;EACF;EAEA,MAAM,UACJ,kBACC;GACC,QAAQ;GACR,OAAO;EACT;EAEF,IAAI;GACF,MAAM,QAAQ,mBAAmB,OAAO;EAC1C,SAAS,iBAAiB;GACxB,IAAI,CAAC,mBAAmB,QAAQ,WAAW,WACzC,MAAM;EAEV;EAEA,IAAI,iBACF,MAAM;EAGR,OAAO;CACT;;CAGA,MAAM,SAAwB;EAC5B,IAAI;GACF,MAAM,KAAK,OAAO,OAAO;EAC3B,SAAS,OAAO;GACd,IAAI;IACF,MAAM,KAAK,OAAO,QAAQ;KAAE,QAAQ;KAAW;IAAM,CAAC;GACxD,QAAQ,CAER;GAEA,MAAM;EACR;CACF;;CAGA,IACE,SACA,SACqB;EACrB,OAAO,KAAK,OAAO,IAAI,SAAS,OAAO;CACzC;;CAGA,QACE,OACA,SACA,SACqB;EACrB,OAAO,KAAK,OAAO,QAAQ,OAAO,SAAS,OAAO;CACpD;CAEA,aAAwB,SAAwD;EAE9E,OAAO,KAAK,OAAO,IAAI,OAAyC;CAClE;CAQA,QAAQ,kBAAwE;EAC9E,OAAO,KAAK,OAAO,QAAQ,gBAAgB;CAC7C;;CAGA,OAAO,OAAO,gBAA+B;EAC3C,MAAM,KAAK,QAAQ;CACrB;CAEA,mBAA2B,SAAsC;EAC/D,OAAO,KAAK,OAAO,QAAQ,OAAO;CACpC;AACF"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { a as ServiceTagCollisionError } from "./errors-Dnjhzbt0.mjs";
|
|
2
|
+
//#region src/layer/internal-identity.ts
|
|
3
|
+
const serviceMemberNames = (token) => {
|
|
4
|
+
const names = /* @__PURE__ */ new Set();
|
|
5
|
+
let prototype = token.prototype;
|
|
6
|
+
while (prototype && prototype !== Object.prototype) {
|
|
7
|
+
for (const name of Object.getOwnPropertyNames(prototype)) if (name !== "constructor") names.add(name);
|
|
8
|
+
for (const symbol of Object.getOwnPropertySymbols(prototype)) names.add(symbol);
|
|
9
|
+
prototype = Object.getPrototypeOf(prototype);
|
|
10
|
+
}
|
|
11
|
+
return [...names];
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Check the runtime portion of a same-tag association before returning it.
|
|
15
|
+
* TypeScript remains authoritative for full structural compatibility; this
|
|
16
|
+
* check catches the common incompatible-method collision after erasure.
|
|
17
|
+
*/
|
|
18
|
+
const assertServiceCompatibility = (requested, registered, instance) => {
|
|
19
|
+
if (requested === registered || requested.serviceTag !== registered.serviceTag) return;
|
|
20
|
+
const candidate = Object(instance);
|
|
21
|
+
if (candidate !== instance) throw new ServiceTagCollisionError(registered, requested);
|
|
22
|
+
for (const name of serviceMemberNames(requested)) if (!(name in candidate)) throw new ServiceTagCollisionError(registered, requested);
|
|
23
|
+
};
|
|
24
|
+
//#endregion
|
|
25
|
+
export { assertServiceCompatibility as t };
|
|
26
|
+
|
|
27
|
+
//# sourceMappingURL=internal-identity-DmUpBeeL.mjs.map
|