better-effect 0.12.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +327 -7
- package/dist/adapters/iti.d.mts +3 -3
- package/dist/bun.d.mts +43 -0
- package/dist/bun.d.mts.map +1 -0
- package/dist/bun.mjs +40 -0
- package/dist/bun.mjs.map +1 -0
- package/dist/{context-BUEf1qjL.mjs → context-BphfFUMO.mjs} +4 -2
- package/dist/context-BphfFUMO.mjs.map +1 -0
- package/dist/current-request-CIU7AHhF.d.mts +22 -0
- package/dist/current-request-CIU7AHhF.d.mts.map +1 -0
- package/dist/current-request-DDKNyymv.mjs +20 -0
- package/dist/current-request-DDKNyymv.mjs.map +1 -0
- package/dist/{signal-D2UTcaaG.mjs → disposable-CP-Q2H3l.mjs} +4 -52
- package/dist/disposable-CP-Q2H3l.mjs.map +1 -0
- package/dist/{effect-CK4YZaX0.mjs → effect-CPdV7Yv8.mjs} +2 -2
- package/dist/{effect-CK4YZaX0.mjs.map → effect-CPdV7Yv8.mjs.map} +1 -1
- package/dist/hono.d.mts +7 -5
- package/dist/hono.d.mts.map +1 -1
- package/dist/hono.mjs +88 -30
- package/dist/hono.mjs.map +1 -1
- package/dist/{index-heuaRmXR.d.mts → index-AiKM71-u.d.mts} +3 -1
- package/dist/{index-heuaRmXR.d.mts.map → index-AiKM71-u.d.mts.map} +1 -1
- package/dist/{index-GYJ4qm9K.d.mts → index-BodMy6rO.d.mts} +6 -5
- package/dist/index-BodMy6rO.d.mts.map +1 -0
- package/dist/{index-CX6iAoCB.d.mts → index-CCi07kUw.d.mts} +2 -2
- package/dist/{index-CX6iAoCB.d.mts.map → index-CCi07kUw.d.mts.map} +1 -1
- package/dist/{index-BMdU_Z72.d.mts → index-DAKn0qHk.d.mts} +4 -3
- package/dist/index-DAKn0qHk.d.mts.map +1 -0
- package/dist/{index-B1nH4luq.d.mts → index-cXgyMa0v.d.mts} +6 -20
- package/dist/index-cXgyMa0v.d.mts.map +1 -0
- package/dist/index.d.mts +6 -5
- package/dist/index.mjs +7 -6
- package/dist/index.mjs.map +1 -1
- package/dist/{layer-D56fRdLt.mjs → layer-D16GKxuX.mjs} +4 -4
- package/dist/layer-D16GKxuX.mjs.map +1 -0
- package/dist/next.d.mts +116 -0
- package/dist/next.d.mts.map +1 -0
- package/dist/next.mjs +68 -0
- package/dist/next.mjs.map +1 -0
- package/dist/{node-context-lggRF4bR.mjs → node-context-Ca18oNSg.mjs} +2 -2
- package/dist/{node-context-lggRF4bR.mjs.map → node-context-Ca18oNSg.mjs.map} +1 -1
- package/dist/{node-context-DWsCUBRa.d.mts → node-context-DczjAcrX.d.mts} +2 -2
- package/dist/{node-context-DWsCUBRa.d.mts.map → node-context-DczjAcrX.d.mts.map} +1 -1
- package/dist/node.d.mts +4 -4
- package/dist/node.mjs +4 -4
- package/dist/observer-9nhbL7Pr.d.mts +68 -0
- package/dist/observer-9nhbL7Pr.d.mts.map +1 -0
- package/dist/opentelemetry.d.mts +94 -0
- package/dist/opentelemetry.d.mts.map +1 -0
- package/dist/opentelemetry.mjs +453 -0
- package/dist/opentelemetry.mjs.map +1 -0
- package/dist/{outcome-CB43bnFW.d.mts → outcome-DI8LPIQ4.d.mts} +14 -69
- package/dist/outcome-DI8LPIQ4.d.mts.map +1 -0
- package/dist/{program-metadata-DhQCCirO.mjs → program-metadata-BxjGkT17.mjs} +3 -3
- package/dist/{program-metadata-DhQCCirO.mjs.map → program-metadata-BxjGkT17.mjs.map} +1 -1
- package/dist/runtime/explicit.d.mts +1 -1
- package/dist/runtime/explicit.mjs +1 -1
- package/dist/runtime/node.d.mts +2 -2
- package/dist/runtime/node.mjs +2 -2
- package/dist/{runtime-CBMrX8Wl.mjs → runtime-C_55ofnL.mjs} +42 -27
- package/dist/runtime-C_55ofnL.mjs.map +1 -0
- package/dist/signal-nfgFyNCk.mjs +52 -0
- package/dist/signal-nfgFyNCk.mjs.map +1 -0
- package/dist/{standard-services-GBZ32tll.mjs → standard-services-vnGIafkS.mjs} +3 -17
- package/dist/standard-services-vnGIafkS.mjs.map +1 -0
- package/dist/standard-services.d.mts +3 -2
- package/dist/standard-services.mjs +3 -2
- package/dist/testing.d.mts +6 -5
- package/dist/testing.d.mts.map +1 -1
- package/dist/testing.mjs +6 -6
- package/dist/types-oihI-ESv.d.mts +54 -0
- package/dist/types-oihI-ESv.d.mts.map +1 -0
- package/dist/web-Bq3MfMrj.mjs +147 -0
- package/dist/web-Bq3MfMrj.mjs.map +1 -0
- package/dist/web.d.mts +47 -0
- package/dist/web.d.mts.map +1 -0
- package/dist/web.mjs +2 -0
- package/package.json +33 -2
- package/dist/context-BUEf1qjL.mjs.map +0 -1
- package/dist/index-B1nH4luq.d.mts.map +0 -1
- package/dist/index-BMdU_Z72.d.mts.map +0 -1
- package/dist/index-GYJ4qm9K.d.mts.map +0 -1
- package/dist/layer-D56fRdLt.mjs.map +0 -1
- package/dist/outcome-CB43bnFW.d.mts.map +0 -1
- package/dist/runtime-CBMrX8Wl.mjs.map +0 -1
- package/dist/signal-D2UTcaaG.mjs.map +0 -1
- package/dist/standard-services-GBZ32tll.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runtime-C_55ofnL.mjs","names":[],"sources":["../src/layer/map-layer-backend.ts","../src/runtime/outcome.ts","../src/runtime/observer.ts","../src/layer/resolution.ts","../src/runtime/execution.ts","../src/layer/runtime.ts","../src/runtime/runtime.ts"],"sourcesContent":["import { assertServiceCompatibility } from './internal-identity'\nimport { captureLayerRegistrationTag, normalizeLayerRegistration } from './registration'\n\nimport { DuplicateServiceError, ServiceTagCollisionError } from './errors'\n\nimport type { LayerBackend, LayerBackendDisposeOptions } from './backend'\nimport type { LayerRegistration } from './types'\n\nimport { ServiceNotFoundError, type AnyServiceToken } from '../service'\nimport { captureServiceTag } from '../service/tag'\n\ntype LayerAcquiredValue = Awaited<ReturnType<LayerRegistration['acquire']>>\n\n/** Native map-backed Layer backend used by Runtime when no adapter is supplied. */\nexport class MapLayerBackend implements LayerBackend {\n private readonly providers = new Map<string, LayerRegistration>()\n\n private readonly instances = new Map<string, LayerAcquiredValue>()\n\n private readonly pending = new Map<string, Promise<LayerAcquiredValue>>()\n\n /** Register a provider, rejecting duplicate or colliding Service tags. */\n register(registration: LayerRegistration): void {\n const normalized = normalizeLayerRegistration(registration)\n const tag = captureLayerRegistrationTag(normalized)\n const existing = this.providers.get(tag)\n\n if (existing) {\n if (existing.service !== normalized.service) {\n throw new ServiceTagCollisionError(existing.service, normalized.service)\n }\n\n throw new DuplicateServiceError(normalized.service)\n }\n\n this.providers.set(tag, normalized)\n }\n\n /** Resolve and cache a provider instance by Service tag. */\n async resolve<T extends AnyServiceToken>(token: T): Promise<InstanceType<T>> {\n const tag = captureServiceTag(token)\n const provider = this.providers.get(tag)\n\n if (!provider) {\n throw new ServiceNotFoundError(token)\n }\n\n const validate = (instance: LayerAcquiredValue): InstanceType<T> => {\n assertServiceCompatibility(token, provider.service, instance)\n\n // SAFETY: The provider and requested token share a tag, and compatibility checks verify the registered members before restoring the token-specific instance type.\n return instance as InstanceType<T>\n }\n\n const cached = this.instances.get(tag)\n\n if (cached !== undefined) {\n return validate(cached)\n }\n\n const pending = this.pending.get(tag)\n\n if (pending) {\n return validate(await pending)\n }\n\n const acquisition = Promise.resolve()\n .then(() => provider.acquire())\n .then((instance) => {\n validate(instance)\n this.instances.set(tag, instance)\n\n return instance\n })\n .finally(() => {\n this.pending.delete(tag)\n })\n\n this.pending.set(tag, acquisition)\n\n return validate(await acquisition)\n }\n\n /** Clear pending acquisitions, cached instances, and provider registrations. */\n async disposeAll(options?: LayerBackendDisposeOptions): Promise<void> {\n const acquisitions = [...this.pending.values()]\n\n if (acquisitions.length > 0) {\n const observePending = options?.onPendingAcquisitions\n\n if (observePending) {\n await observePending(acquisitions)\n }\n\n await Promise.allSettled(acquisitions)\n }\n\n this.instances.clear()\n this.pending.clear()\n this.providers.clear()\n }\n}\n","import { Err } from 'better-result'\n\nimport type { CleanupFailureDiagnostic, MaybePromise, ScopeOutcome } from '../scope'\n\nimport type { LayerDisposeError } from '../layer/errors'\n\nimport type { LayerBackend } from '../layer/backend'\n\nimport type { RuntimeContextStorage } from './context'\n\nimport type { RuntimeExecutionAttributes, 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 and diagnostic attributes supplied to one Runtime execution. */\nexport type RuntimeRunOptions = {\n readonly signal?: AbortSignal\n /** Copied once and exposed as a readonly event view. */\n readonly attributes?: RuntimeExecutionAttributes\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\n/** Classify only a nominal better-result Err as a failed Runtime outcome. */\nexport const classifyRuntimeOutcome = <A>(value: A): ScopeOutcome => {\n if (value instanceof Err) {\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 { ScopeCloseError, 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 /** Runtime execution owner, omitted for warmup and other root activity. */\n readonly executionId?: string\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 /** Runtime execution owner, omitted for warmup and other root activity. */\n readonly executionId?: string\n}\n\n/** Values supplied to one Runtime execution for diagnostic correlation. */\n// oxlint-disable-next-line anti-slop/no-unsafe-dictionary-type -- attributes intentionally accept caller-defined values.\nexport type RuntimeExecutionAttributes = Readonly<Record<string, unknown>>\n\n/** Metadata shared by the start and end events for one execution. */\nexport type RuntimeExecutionMetadata = {\n readonly executionId: string\n readonly name?: string\n // oxlint-disable-next-line anti-slop/no-unsafe-dictionary-type -- preserve the caller-defined attribute contract.\n readonly attributes?: RuntimeExecutionAttributes\n /** Monotonic host timestamp captured immediately before the Program starts. */\n readonly startedAt: number\n}\n\n/** Event emitted immediately before a program starts in an execution Scope. */\nexport type RuntimeExecutionStartEvent = RuntimeExecutionMetadata & {\n readonly scope: Scope\n}\n\n/** Event emitted after a program and its execution Scope settle. */\nexport type RuntimeExecutionEndEvent = RuntimeExecutionMetadata & {\n readonly scope: Scope\n /** The program outcome used to run execution-scope cleanup. */\n readonly outcome: ScopeOutcome\n /** Execution-scope cleanup failure, without changing the primary program outcome. */\n readonly cleanupFailure?: ScopeCloseError\n /** Monotonic elapsed time for the Program and its execution cleanup. */\n readonly durationMs: number\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 /** Runtime execution owner, omitted for Runtime-root cleanup. */\n readonly executionId?: string\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\n/** Compose best-effort Runtime observers into one observer. */\nexport const RuntimeObserver = {\n compose: (...observers: readonly RuntimeObserver[]): RuntimeObserver => ({\n onServiceResolve: (event) => {\n notifyRuntimeObservers(observers, (observer) => observer.onServiceResolve, event)\n },\n onServiceAcquire: (event) => {\n notifyRuntimeObservers(observers, (observer) => observer.onServiceAcquire, event)\n },\n onExecutionStart: (event) => {\n notifyRuntimeObservers(observers, (observer) => observer.onExecutionStart, event)\n },\n onExecutionEnd: (event) => {\n notifyRuntimeObservers(observers, (observer) => observer.onExecutionEnd, event)\n },\n onResourceRelease: (event) => {\n notifyRuntimeObservers(observers, (observer) => observer.onResourceRelease, event)\n }\n })\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 { captureServiceTag } from '../service/tag'\n\nimport {\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 {\n notifyRuntimeObservers,\n type RuntimeObserver,\n type RuntimeServiceResolveEvent\n} from '../runtime/observer'\n\nimport type { ScopeOutcome } from '../scope'\n\nimport { ServiceTagCollisionError } from './errors'\n\nconst findCycleStart = (path: readonly AnyServiceToken[], tag: string): number =>\n path.findIndex((current) => captureServiceTag(current) === tag)\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 tag = captureServiceTag(token)\n const context = getRuntimeContext(storage)\n const path = context?.resolutionPath ?? []\n const cycleStart = findCycleStart(path, tag)\n const resolutionPath = [...path, token]\n\n const notifyResolve = (outcome: ScopeOutcome): void => {\n const event: RuntimeServiceResolveEvent = {\n service: token,\n resolutionPath,\n outcome\n }\n\n if (context?.executionId !== undefined) {\n Object.assign(event, { executionId: context.executionId })\n }\n\n notifyRuntimeObservers(observers, (observer) => observer.onServiceResolve, event)\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 context\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","export type RuntimeExecutionIdGenerator = () => string\n\nexport type RuntimeMonotonicClock = () => number\n\n/** Per-Runtime host capabilities used to correlate and time executions. */\nexport type RuntimeExecutionDependencies = {\n readonly createExecutionId: RuntimeExecutionIdGenerator\n readonly now: RuntimeMonotonicClock\n}\n\nexport type RuntimeExecutionDependencyOverrides = {\n readonly createExecutionId?: RuntimeExecutionIdGenerator\n readonly now?: RuntimeMonotonicClock\n}\n\nconst hostMonotonicNow = (): number => {\n // oxlint-disable-next-line anti-slop/no-runtime-typeof -- feature-detect the optional host clock.\n if (typeof globalThis.performance?.now === 'function') {\n const value = globalThis.performance.now()\n\n if (Number.isFinite(value)) {\n return value\n }\n }\n\n const wallClock = Date.now()\n return Number.isFinite(wallClock) ? wallClock : 0\n}\n\nconst makeMonotonicClock = (): RuntimeMonotonicClock => {\n let previous = 0\n\n return () => {\n previous = Math.max(previous, hostMonotonicNow())\n return previous\n }\n}\n\nlet fallbackExecutionSequence = 0\n\nconst makeExecutionIdGenerator = (): RuntimeExecutionIdGenerator => () => {\n // oxlint-disable-next-line anti-slop/no-runtime-typeof -- feature-detect the optional host ID source.\n if (typeof globalThis.crypto?.randomUUID === 'function') {\n return globalThis.crypto.randomUUID()\n }\n\n fallbackExecutionSequence += 1\n\n return `execution-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${fallbackExecutionSequence.toString(36)}`\n}\n\n/** Create isolated execution capabilities for one Runtime handle. */\nexport const makeRuntimeExecutionDependencies = (\n overrides: RuntimeExecutionDependencyOverrides = {}\n): RuntimeExecutionDependencies => ({\n createExecutionId: overrides.createExecutionId ?? makeExecutionIdGenerator(),\n now: overrides.now ?? makeMonotonicClock()\n})\n","import { captureServiceTag } from '../service/tag'\nimport 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'\nimport { captureLayerRegistrationTag } from './registration'\n\nimport { createResolutionResolver } from './resolution'\n\nimport { getProgramName } from '../effect/program-metadata'\nimport type { ProgramIdentity } from '../effect/program-metadata'\n\nimport {\n makeRuntimeExecutionDependencies,\n type RuntimeExecutionDependencies,\n type RuntimeExecutionDependencyOverrides\n} from '../runtime/execution'\n\nimport { notifyRuntimeObservers } from '../runtime/observer'\n\nimport type {\n RuntimeExecutionAttributes,\n RuntimeExecutionEndEvent,\n RuntimeExecutionMetadata,\n RuntimeObserver,\n RuntimeResourceReleaseEvent,\n RuntimeServiceAcquireEvent\n} from '../runtime/observer'\n\nimport type { RuntimeInspection } from '../runtime/types'\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 {\n CleanupFailureDiagnostic,\n ScopeCloseError,\n ScopeFinalizer,\n ScopeOutcome\n} 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 /** Return a detached diagnostic snapshot without changing Runtime state. */\n inspect(): RuntimeInspection\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 readonly metadata: RuntimeExecutionMetadata\n}\n\ntype MutableRuntimeExecutionInspection = {\n executionId: string\n startedAt: number\n name?: string\n}\n\nconst copyExecutionAttributes = (\n attributes: RuntimeExecutionAttributes | undefined\n): RuntimeExecutionAttributes | undefined => {\n if (attributes === undefined) {\n return undefined\n }\n\n // oxlint-disable-next-line anti-slop/no-runtime-typeof -- validate JavaScript callers at the Runtime boundary.\n if (typeof attributes !== 'object' || attributes === null) {\n throw new TypeError('Runtime execution attributes must be an object')\n }\n\n return Object.freeze({ ...attributes })\n}\n\ntype MutableRuntimeExecutionMetadata = {\n executionId: string\n startedAt: number\n name?: string\n attributes?: RuntimeExecutionAttributes\n}\n\ntype PreparedExecution = {\n readonly metadata: RuntimeExecutionMetadata\n readonly signalLink: AbortSignalLink\n}\n\nconst prepareExecution = <ProgramValue>(\n program: () => ProgramValue | PromiseLike<ProgramValue>,\n options: RuntimeRunOptions | undefined,\n dependencies: RuntimeExecutionDependencies,\n runtimeSignal: AbortSignal | undefined,\n shutdownSignal: AbortSignal\n): PreparedExecution => ({\n metadata: makeExecutionMetadata(program, options?.attributes, dependencies),\n signalLink: linkAbortSignals(runtimeSignal, options?.signal, shutdownSignal)\n})\n\nconst makeExecutionMetadata = (\n program: ProgramIdentity,\n attributes: RuntimeExecutionAttributes | undefined,\n dependencies: RuntimeExecutionDependencies\n): RuntimeExecutionMetadata => {\n const name = getProgramName(program)\n const copiedAttributes = copyExecutionAttributes(attributes)\n\n const metadata: MutableRuntimeExecutionMetadata = {\n executionId: dependencies.createExecutionId(),\n startedAt: dependencies.now()\n }\n\n if (name !== undefined) {\n metadata.name = name\n }\n\n if (copiedAttributes !== undefined) {\n metadata.attributes = copiedAttributes\n }\n\n return Object.freeze(metadata)\n}\n\nconst executionDuration = (\n metadata: RuntimeExecutionMetadata,\n dependencies: RuntimeExecutionDependencies\n): number => {\n try {\n const elapsed = dependencies.now() - metadata.startedAt\n\n return Number.isFinite(elapsed) ? Math.max(0, elapsed) : 0\n } catch {\n return 0\n }\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 releaseLayerResource = async (\n service: LayerProvider['service'],\n release: ScopeFinalizer,\n outcome: ScopeOutcome,\n observers: readonly RuntimeObserver[],\n executionId: string | undefined\n): Promise<void> => {\n try {\n await release(outcome)\n const event: RuntimeResourceReleaseEvent = { service, outcome }\n\n if (executionId !== undefined) {\n Object.assign(event, { executionId })\n }\n\n notifyRuntimeObservers(observers, (observer) => observer.onResourceRelease, event)\n } catch (cause) {\n const event: RuntimeResourceReleaseEvent = { service, outcome, error: cause }\n\n if (executionId !== undefined) {\n Object.assign(event, { executionId })\n }\n\n notifyRuntimeObservers(observers, (observer) => observer.onResourceRelease, event)\n throw cause\n }\n}\n\nconst bindProviderToScope = (\n provider: LayerProvider,\n scope: CloseableScope,\n contextStorage: RuntimeContextStorage,\n resolver: ServiceResolver,\n observers: readonly RuntimeObserver[],\n ownerExecutionId?: string\n): LayerRegistration => ({\n service: provider.service,\n serviceTag: provider.serviceTag,\n\n acquire: () => {\n const current = getRuntimeContext(contextStorage)\n const executionId = current?.executionId ?? ownerExecutionId\n const context = makeRuntimeContext(\n resolver,\n scope,\n current?.resolutionPath ?? [],\n current?.signal,\n current\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.acquireWithRelease\n ? (\n await scope.acquire(provider.acquireWithRelease, (acquired, outcome) =>\n releaseLayerResource(\n provider.service,\n acquired.release,\n outcome,\n observers,\n ownerExecutionId\n )\n )\n ).instance\n : provider.release\n ? await scope.acquire(\n () => provider.acquire(),\n (resource, outcome) =>\n releaseLayerResource(\n provider.service,\n (releaseOutcome) => provider.release!(resource, releaseOutcome),\n outcome,\n observers,\n ownerExecutionId\n )\n )\n : await provider.acquire()\n\n const event: RuntimeServiceAcquireEvent = {\n service: provider.service,\n resolutionPath,\n outcome: SCOPE_SUCCESS\n }\n\n if (executionId !== undefined) {\n Object.assign(event, { executionId })\n }\n\n notifyRuntimeObservers(observers, (observer) => observer.onServiceAcquire, event)\n\n return instance\n } catch (cause) {\n const event: RuntimeServiceAcquireEvent = {\n service: provider.service,\n resolutionPath,\n outcome: {\n status: 'failure',\n cause\n }\n }\n\n if (executionId !== undefined) {\n Object.assign(event, { executionId })\n }\n\n notifyRuntimeObservers(observers, (observer) => observer.onServiceAcquire, event)\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(captureLayerRegistrationTag(registration))\n this.local.register(registration)\n }\n\n async resolve<T extends AnyServiceToken>(token: T): Promise<InstanceType<T>> {\n const tag = captureServiceTag(token)\n\n if (this.localTags.has(tag)) {\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 serviceTags: readonly string[]\n\n private readonly shutdownController = new AbortController()\n\n private state: 'active' | 'disposing' | 'disposed' = 'active'\n\n private warmupState: RuntimeInspection['warmup'] = 'idle'\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 serviceTags: readonly string[],\n private readonly executionDependencies: RuntimeExecutionDependencies\n ) {\n this.serviceTags = Object.freeze([...serviceTags])\n }\n\n inspect(): RuntimeInspection {\n const executions = Object.freeze(\n [...this.executions].map(({ metadata }) => {\n const inspection: MutableRuntimeExecutionInspection = {\n executionId: metadata.executionId,\n startedAt: metadata.startedAt\n }\n\n if (metadata.name !== undefined) {\n inspection.name = metadata.name\n }\n\n return Object.freeze(inspection)\n })\n )\n\n return Object.freeze({\n state: this.state,\n warmup: this.warmupState,\n activeExecutions: executions.length,\n executions,\n services: Object.freeze([...this.serviceTags]),\n shutdownSignalAborted: this.shutdownController.signal.aborted\n })\n }\n\n run<A>(\n program: CompleteExecution<Provided, A>,\n options?: RuntimeRunOptions\n ): Promise<Awaited<A>> {\n this.assertActive()\n\n let prepared: PreparedExecution\n\n try {\n prepared = prepareExecution(\n program,\n options,\n this.executionDependencies,\n this.signal,\n this.shutdownController.signal\n )\n } catch (cause) {\n return Promise.reject(cause)\n }\n\n try {\n this.assertActive()\n } catch (cause) {\n prepared.signalLink.dispose()\n throw cause\n }\n\n let executionScope: CloseableScope\n\n try {\n executionScope = this.rootScope.fork()\n } catch (cause) {\n prepared.signalLink.dispose()\n throw cause\n }\n\n return this.startExecution<Awaited<A>>(prepared.signalLink, prepared.metadata, () =>\n this.runExecution(\n executionScope,\n program,\n this.resolver,\n prepared.signalLink.signal,\n prepared.metadata\n )\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 let prepared: PreparedExecution\n\n try {\n prepared = prepareExecution(\n program,\n options,\n this.executionDependencies,\n this.signal,\n this.shutdownController.signal\n )\n } catch (cause) {\n return Promise.reject(cause)\n }\n\n try {\n this.assertActive()\n } catch (cause) {\n prepared.signalLink.dispose()\n throw cause\n }\n\n const localBackend = new MapLayerBackend()\n const backend = new ExecutionLayerBackend(localBackend, this.backend)\n const resolver = createResolutionResolver(backend, this.contextStorage, this.observers)\n let executionScope: CloseableScope\n\n try {\n executionScope = this.rootScope.fork()\n } catch (cause) {\n prepared.signalLink.dispose()\n throw cause\n }\n\n return this.startExecution<Awaited<A>>(\n prepared.signalLink,\n prepared.metadata,\n 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 prepared.metadata.executionId\n )\n )\n }\n\n return await program()\n },\n resolver,\n prepared.signalLink.signal,\n prepared.metadata\n )\n } finally {\n await localBackend.disposeAll()\n }\n }\n )\n }\n\n warmup(): Promise<void> {\n this.assertActive()\n\n if (this.warmupPromise) {\n return this.warmupPromise\n }\n\n this.warmupState = 'running'\n\n let warmup: Promise<void>\n\n try {\n 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 } catch (cause) {\n this.warmupState = 'failed'\n return Promise.reject(cause)\n }\n\n this.warmupPromise = warmup\n\n void warmup.then(\n () => {\n if (this.warmupPromise === warmup) {\n this.warmupState = 'completed'\n this.warmupPromise = undefined\n }\n },\n () => {\n if (this.warmupPromise === warmup) {\n this.warmupState = 'failed'\n this.warmupPromise = undefined\n }\n }\n )\n\n return warmup\n }\n\n private startExecution<A>(\n signalLink: AbortSignalLink,\n metadata: RuntimeExecutionMetadata,\n run: (metadata: RuntimeExecutionMetadata) => PromiseLike<A>\n ): 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, metadata }\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(metadata)\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 metadata: RuntimeExecutionMetadata\n ): Promise<Awaited<A>> {\n let outcome: ScopeOutcome | undefined\n let cleanupFailure: ScopeCloseError | undefined\n const onOutcome = (determinedOutcome: ScopeOutcome): void => {\n outcome = determinedOutcome\n }\n const onExecutionCleanupFailure = async (\n diagnostic: CleanupFailureDiagnostic\n ): Promise<void> => {\n cleanupFailure = diagnostic.error\n\n if (this.onCleanupFailure !== undefined) {\n await this.onCleanupFailure(diagnostic)\n }\n }\n const runOptions = {\n classify: classifyRuntimeOutcome,\n onOutcome,\n onCleanupFailure: onExecutionCleanupFailure\n }\n\n const startEvent = Object.freeze({\n ...metadata,\n scope: executionScope\n })\n notifyRuntimeObservers(this.observers, (observer) => observer.onExecutionStart, startEvent)\n\n let ended = false\n const notifyEnd = (finalOutcome: ScopeOutcome): void => {\n if (ended) {\n return\n }\n\n ended = true\n const endEvent: RuntimeExecutionEndEvent = {\n ...metadata,\n scope: executionScope,\n outcome: finalOutcome,\n durationMs: executionDuration(metadata, this.executionDependencies)\n }\n\n if (cleanupFailure !== undefined) {\n Object.assign(endEvent, { cleanupFailure })\n }\n\n notifyRuntimeObservers(\n this.observers,\n (observer) => observer.onExecutionEnd,\n Object.freeze(endEvent)\n )\n }\n\n let execution: Promise<Awaited<A>>\n\n try {\n execution = runScoped(executionScope, program, {\n ...runOptions,\n contextStorage: this.contextStorage,\n context: makeRuntimeContext(\n resolver,\n executionScope,\n [],\n signal,\n undefined,\n metadata.executionId\n )\n })\n } catch (cause) {\n const failure: ScopeOutcome = {\n status: 'failure',\n cause\n }\n notifyEnd(failure)\n return Promise.reject(cause)\n }\n\n return execution.then(\n (value) => {\n notifyEnd(\n outcome ?? {\n status: 'success'\n }\n )\n return value\n },\n (cause) => {\n notifyEnd(\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 executionOverrides: RuntimeExecutionDependencyOverrides = {}\n): Promise<RuntimeHandle<ProvidedEnvironment<L>>> => {\n const services = layer.providers.map((provider) => provider.service)\n const serviceTags = layer.providers.map((provider) => captureLayerRegistrationTag(provider))\n const rootScope = Scope.make()\n const contextStorage = options.contextStorage ?? defaultRuntimeContextStorage\n const observers = options.observers ?? []\n const resolver = createResolutionResolver(backend, contextStorage, observers)\n const executionDependencies = makeRuntimeExecutionDependencies(executionOverrides)\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 services,\n serviceTags,\n executionDependencies\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 { RuntimeExecutionInspection, RuntimeFor, RuntimeInspection } from './types'\n\nimport type { RuntimeObserver } from './observer'\n\ntype RuntimeOptionsInput = RuntimeOptions & RuntimeRunOptions\n\ntype RuntimeBackendInput = LayerBackend | RuntimeOptionsInput | undefined\n\ntype RuntimeConfig = {\n readonly backend: LayerBackend\n readonly options: RuntimeOptionsInput\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?: RuntimeOptionsInput\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?: RuntimeOptionsInput\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?: RuntimeOptionsInput\n ): Promise<Awaited<A>>\n\n static run<A, L extends LayerInput>(\n layer: L & CompleteInput<L>,\n options: RuntimeOptionsInput,\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 | RuntimeOptionsInput\n | CompleteExecution<ProvidedEnvironment<L>, A>,\n programOrOptions?: CompleteExecution<ProvidedEnvironment<L>, A> | RuntimeOptionsInput,\n legacyOptions?: RuntimeOptionsInput\n ): Promise<Awaited<A>> {\n let program: CompleteExecution<ProvidedEnvironment<L>, A>\n let backendOrOptions: RuntimeBackendInput\n let options: RuntimeOptionsInput | 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 RuntimeOptionsInput | 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 let programOutcome: ScopeOutcome | undefined\n const outcomeObserver: RuntimeObserver = {\n onExecutionEnd: ({ outcome }) => {\n programOutcome = outcome\n }\n }\n const runtimeOptions: RuntimeOptions = {\n ...config.options,\n observers: [outcomeObserver, ...(config.options.observers ?? [])]\n }\n const runtime = await Runtime.make(layer, config.backend, runtimeOptions)\n\n let value!: Awaited<A>\n let executionFailed = false\n let executionFailure: unknown\n\n try {\n value = await runtime.runUnchecked(program, config.options)\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 /** Return a detached diagnostic snapshot without changing Runtime state. */\n inspect(): RuntimeInspection {\n return this.handle.inspect()\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>(\n program: () => A | PromiseLike<A>,\n options?: RuntimeRunOptions\n ): 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>, options)\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 /** Detached diagnostic snapshot returned by `Runtime.inspect()`. */\n export type Inspection = RuntimeInspection\n\n /** Detached diagnostic view of one active execution. */\n export type ExecutionInspection = RuntimeExecutionInspection\n}\n"],"mappings":";;;;;;;;;AAcA,IAAa,kBAAb,MAAqD;CACnD,4BAA6B,IAAI,IAA+B;CAEhE,4BAA6B,IAAI,IAAgC;CAEjE,0BAA2B,IAAI,IAAyC;;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AAQ;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,UAA6B;EAC3B,OAAO,KAAK,OAAO,QAAQ;CAC7B;;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,aACE,SACA,SACqB;EAErB,OAAO,KAAK,OAAO,IAAI,SAA2C,OAAO;CAC3E;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,52 @@
|
|
|
1
|
+
import { n as currentRuntimeContext } from "./context-BphfFUMO.mjs";
|
|
2
|
+
//#region src/runtime/signal.ts
|
|
3
|
+
const neverAbortedSignal = new AbortController().signal;
|
|
4
|
+
/** Link caller, Runtime and shutdown signals without owning the caller's controller. */
|
|
5
|
+
const linkAbortSignals = (...signals) => {
|
|
6
|
+
const active = signals.filter((signal) => signal !== void 0);
|
|
7
|
+
if (active.length === 0) return {
|
|
8
|
+
signal: neverAbortedSignal,
|
|
9
|
+
dispose: () => {}
|
|
10
|
+
};
|
|
11
|
+
if (active.length === 1) return {
|
|
12
|
+
signal: active[0],
|
|
13
|
+
dispose: () => {}
|
|
14
|
+
};
|
|
15
|
+
const controller = new AbortController();
|
|
16
|
+
const listeners = [];
|
|
17
|
+
let disposed = false;
|
|
18
|
+
const dispose = () => {
|
|
19
|
+
if (disposed) return;
|
|
20
|
+
disposed = true;
|
|
21
|
+
for (const [source, listener] of listeners) source.removeEventListener("abort", listener);
|
|
22
|
+
listeners.length = 0;
|
|
23
|
+
};
|
|
24
|
+
const abortFrom = (source) => {
|
|
25
|
+
if (controller.signal.aborted) return;
|
|
26
|
+
controller.abort(source.reason);
|
|
27
|
+
dispose();
|
|
28
|
+
};
|
|
29
|
+
for (const source of active) {
|
|
30
|
+
if (source.aborted) {
|
|
31
|
+
abortFrom(source);
|
|
32
|
+
break;
|
|
33
|
+
}
|
|
34
|
+
const listener = () => abortFrom(source);
|
|
35
|
+
listeners.push([source, listener]);
|
|
36
|
+
source.addEventListener("abort", listener, { once: true });
|
|
37
|
+
}
|
|
38
|
+
return {
|
|
39
|
+
signal: controller.signal,
|
|
40
|
+
dispose
|
|
41
|
+
};
|
|
42
|
+
};
|
|
43
|
+
/** Return the current cooperative-cancellation signal. */
|
|
44
|
+
const currentAbortSignal = () => currentRuntimeContext().signal ?? neverAbortedSignal;
|
|
45
|
+
/** Yieldable access to the signal of the current Runtime execution. */
|
|
46
|
+
const CurrentAbortSignal = { *[Symbol.iterator]() {
|
|
47
|
+
return currentAbortSignal();
|
|
48
|
+
} };
|
|
49
|
+
//#endregion
|
|
50
|
+
export { linkAbortSignals as n, CurrentAbortSignal as t };
|
|
51
|
+
|
|
52
|
+
//# sourceMappingURL=signal-nfgFyNCk.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"signal-nfgFyNCk.mjs","names":[],"sources":["../src/runtime/signal.ts"],"sourcesContent":["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"],"mappings":";;AAEA,MAAM,qBAAqB,IAAI,gBAAgB,CAAC,CAAC;;AAUjD,MAAa,oBACX,GAAG,YACiB;CACpB,MAAM,SAAS,QAAQ,QAAQ,WAAkC,WAAW,KAAA,CAAS;CAErF,IAAI,OAAO,WAAW,GACpB,OAAO;EAAE,QAAQ;EAAoB,eAAe,CAAC;CAAE;CAGzD,IAAI,OAAO,WAAW,GACpB,OAAO;EAAE,QAAQ,OAAO;EAAK,eAAe,CAAC;CAAE;CAGjD,MAAM,aAAa,IAAI,gBAAgB;CACvC,MAAM,YAA8B,CAAC;CACrC,IAAI,WAAW;CAEf,MAAM,gBAAsB;EAC1B,IAAI,UACF;EAGF,WAAW;EAEX,KAAK,MAAM,CAAC,QAAQ,aAAa,WAC/B,OAAO,oBAAoB,SAAS,QAAQ;EAG9C,UAAU,SAAS;CACrB;CAEA,MAAM,aAAa,WAA8B;EAC/C,IAAI,WAAW,OAAO,SACpB;EAGF,WAAW,MAAM,OAAO,MAAM;EAC9B,QAAQ;CACV;CAEA,KAAK,MAAM,UAAU,QAAQ;EAC3B,IAAI,OAAO,SAAS;GAClB,UAAU,MAAM;GAChB;EACF;EAEA,MAAM,iBAAuB,UAAU,MAAM;EAC7C,UAAU,KAAK,CAAC,QAAQ,QAAQ,CAAC;EACjC,OAAO,iBAAiB,SAAS,UAAU,EAAE,MAAM,KAAK,CAAC;CAC3D;CAEA,OAAO;EAAE,QAAQ,WAAW;EAAQ;CAAQ;AAC9C;;AAGA,MAAa,2BACX,sBAAsB,CAAC,CAAC,UAAU;;AAGpC,MAAa,qBAAqB,EAEhC,EAAE,OAAO,YAAoD;CAC3D,OAAO,mBAAmB;AAC5B,EACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as Service, t as Layer } from "./layer-
|
|
1
|
+
import { n as Service, t as Layer } from "./layer-D16GKxuX.mjs";
|
|
2
2
|
import { Result, TaggedError } from "better-result";
|
|
3
3
|
//#region src/standard-services/config.ts
|
|
4
4
|
/** A schema validation failure. Raw source values are intentionally omitted. */
|
|
@@ -504,21 +504,7 @@ var LoggerTest = class LoggerTest {
|
|
|
504
504
|
}
|
|
505
505
|
};
|
|
506
506
|
const LoggerTestLayer = () => LoggerTest.layer();
|
|
507
|
-
/** Execution-local request value carried by a normal Service provider. */
|
|
508
|
-
var CurrentRequest = class CurrentRequest extends Service()("CurrentRequest") {
|
|
509
|
-
value;
|
|
510
|
-
request;
|
|
511
|
-
constructor(value) {
|
|
512
|
-
super();
|
|
513
|
-
this.value = value;
|
|
514
|
-
this.request = value;
|
|
515
|
-
}
|
|
516
|
-
static layer(value) {
|
|
517
|
-
return Layer.succeed(CurrentRequest, new CurrentRequest(value));
|
|
518
|
-
}
|
|
519
|
-
};
|
|
520
|
-
const CurrentRequestLayer = (value) => CurrentRequest.layer(value);
|
|
521
507
|
//#endregion
|
|
522
|
-
export {
|
|
508
|
+
export { ConfigValidationError as S, IdGeneratorTestLayer as _, Logger as a, ConfigLive as b, LoggerTestLayer as c, RandomSeeded as d, RandomSeededLayer as f, IdGeneratorTest as g, IdGeneratorLive as h, ClockTestLayer as i, Random as l, IdGeneratorExhaustedError as m, ClockLive as n, LoggerLive as o, IdGenerator as p, ClockTest as r, LoggerTest as s, Clock as t, RandomLive as u, IdGeneratorUnavailableError as v, ConfigSourceError as x, Config as y };
|
|
523
509
|
|
|
524
|
-
//# sourceMappingURL=standard-services-
|
|
510
|
+
//# sourceMappingURL=standard-services-vnGIafkS.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"standard-services-vnGIafkS.mjs","names":[],"sources":["../src/standard-services/config.ts","../src/standard-services/id-generator.ts","../src/standard-services/index.ts"],"sourcesContent":["import {\n Result,\n TaggedError,\n type Err,\n type Result as ResultType,\n type StandardSchemaV1,\n type UnhandledException\n} from 'better-result'\n\nimport type { ServiceRequirement } from '../effect/types'\nimport { Layer } from '../layer'\nimport { Service } from '../service'\n\n/** Raw string values supplied to a configuration schema. */\nexport type ConfigSource = Readonly<Record<string, string | undefined>>\n\n/** Optional sources used by environment-backed configuration values. */\nexport type ConfigSourceOptions = {\n readonly dotEnvPath?: string\n readonly envSource?: ConfigSource\n}\n\n/** Options for the one-call schema-bound configuration API. */\nexport type ConfigFromEnvOptions<Schema extends StandardSchemaV1> = ConfigSourceOptions & {\n readonly schema: Schema\n}\n\n/** The decoded value produced by a Standard Schema. */\nexport type ConfigOutput<Schema extends StandardSchemaV1> = StandardSchemaV1.InferOutput<Schema>\n\n/** The raw input type described by a Standard Schema. */\nexport type ConfigInput<Schema extends StandardSchemaV1> = StandardSchemaV1.InferInput<Schema>\n\n/** A safe validation issue exposed by a configuration failure. */\nexport type ConfigIssue = StandardSchemaV1.Issue\n\n/** A schema validation failure. Raw source values are intentionally omitted. */\nexport class ConfigValidationError extends TaggedError('ConfigValidationError')<{\n readonly issues: ReadonlyArray<ConfigIssue>\n readonly message: string\n}> {}\n\n/** A dotenv or host-source loading failure. Raw source values are intentionally omitted. */\nexport class ConfigSourceError extends TaggedError('ConfigSourceError')<{\n readonly cause: unknown\n readonly message: string\n readonly path?: string\n}> {}\n\n/** Errors that may be returned while loading or validating configuration. */\nexport type ConfigError = ConfigValidationError | ConfigSourceError | UnhandledException\n\ntype ConfigYield<Requirements extends Service.Any, Error> =\n | Err<never, Error>\n | ServiceRequirement<Requirements>\n\n/** A reusable, async-yieldable Standard Schema configuration descriptor. */\nexport type ConfigValue<\n Schema extends StandardSchemaV1,\n Requirements extends Service.Any = never,\n Error = ConfigError\n> = {\n [Symbol.asyncIterator](): AsyncGenerator<\n ConfigYield<Requirements, Error>,\n ConfigOutput<Schema>,\n unknown\n >\n}\n\ntype RuntimeConfigYield = Err<never, ConfigError> | ServiceRequirement<Service.Any>\n\ntype ConfigValueSpec<Schema extends StandardSchemaV1> = {\n readonly schema: Schema\n readonly source: 'bound' | 'provider'\n readonly sourceOptions?: ConfigSourceOptions\n}\n\ntype MutableConfigSourceOptions = {\n dotEnvPath?: string\n envSource?: ConfigSource\n}\n\ntype RuntimeGlobal = typeof globalThis & {\n readonly process?: { readonly env?: ConfigSource }\n readonly Bun?: {\n readonly env?: ConfigSource\n readonly file?: (path: string) => { text(): Promise<string> }\n }\n}\n\n// SAFETY: Hosts may expose process/Bun globals at runtime without declaring them on globalThis.\nconst runtimeGlobal = globalThis as RuntimeGlobal\n\nconst hostEnvironment = (): ConfigSource => {\n const processEnvironment = runtimeGlobal.process?.env\n\n if (processEnvironment !== undefined) {\n return processEnvironment\n }\n\n return runtimeGlobal.Bun?.env ?? {}\n}\n\nconst readText = async (path: string): Promise<string> => {\n const file = runtimeGlobal.Bun?.file\n\n if (file !== undefined) {\n return await file(path).text()\n }\n\n const { readFile } = await import('node:fs/promises')\n\n return await readFile(path, 'utf8')\n}\n\nconst parseDotEnv = (text: string) => {\n const values = new Map<string, string>()\n\n for (const [lineIndex, rawLine] of text\n .replace(/^\\uFEFF/, '')\n .split(/\\r?\\n/u)\n .entries()) {\n let line = rawLine.trim()\n\n if (line === '' || line.startsWith('#')) {\n continue\n }\n\n if (/^export\\s/u.test(line)) {\n line = line.replace(/^export\\s+/u, '')\n }\n\n const separator = line.indexOf('=')\n\n if (separator <= 0) {\n throw new Error(`Invalid dotenv entry at line ${lineIndex + 1}`)\n }\n\n const key = line.slice(0, separator).trim()\n\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(key)) {\n throw new Error(`Invalid dotenv key at line ${lineIndex + 1}`)\n }\n\n let value = line.slice(separator + 1).trim()\n const quote = value[0]\n\n if (quote === '\"' || quote === \"'\") {\n const closingQuote = value.indexOf(quote, 1)\n const trailing = closingQuote < 0 ? '' : value.slice(closingQuote + 1).trim()\n\n if (closingQuote < 0 || (trailing !== '' && !trailing.startsWith('#'))) {\n throw new Error(`Unterminated dotenv value at line ${lineIndex + 1}`)\n }\n\n value = value.slice(1, closingQuote)\n } else {\n const comment = value.search(/\\s+#/u)\n\n if (comment >= 0) {\n value = value.slice(0, comment).trimEnd()\n }\n }\n\n values.set(key, value)\n }\n\n return Object.fromEntries(values)\n}\n\nconst loadSource = async (options: ConfigSourceOptions = {}): Promise<ConfigSource> => {\n const dotenv =\n options.dotEnvPath === undefined ? {} : parseDotEnv(await readText(options.dotEnvPath))\n const explicit = options.envSource ?? hostEnvironment()\n\n return {\n ...dotenv,\n ...explicit\n }\n}\n\nconst sourceError = (path: string | undefined, cause: unknown): ConfigSourceError => {\n const message =\n path === undefined\n ? 'Failed to load configuration source'\n : `Failed to load configuration source at ${path}`\n\n if (path === undefined) {\n return new ConfigSourceError({ cause, message })\n }\n\n return new ConfigSourceError({ cause, message, path })\n}\n\nconst validate = async <Schema extends StandardSchemaV1>(\n schema: Schema,\n source: ConfigSource\n): Promise<ResultType<ConfigOutput<Schema>, ConfigValidationError | UnhandledException>> => {\n const checked = await Result.tryPromise(() =>\n Promise.resolve(schema['~standard'].validate(source))\n )\n\n if (checked.status === 'error') {\n return checked\n }\n\n if (checked.value.issues !== undefined) {\n return Result.err(\n new ConfigValidationError({\n issues: Object.freeze([...checked.value.issues]),\n message: 'Configuration validation failed'\n })\n )\n }\n\n // SAFETY: A successful Standard Schema result carries its declared output type.\n return Result.ok(checked.value.value as ConfigOutput<Schema>)\n}\n\nconst evaluate = async <Schema extends StandardSchemaV1>(\n spec: ConfigValueSpec<Schema>,\n provider?: Config\n): Promise<ResultType<ConfigOutput<Schema>, ConfigError>> => {\n const loaded = await Result.tryPromise({\n try: async () => {\n if (spec.source === 'provider') {\n const base = provider?.source\n\n if (base === undefined) {\n throw new Error('Config provider did not expose a source')\n }\n\n if (spec.sourceOptions === undefined) {\n return base\n }\n\n return {\n ...base,\n ...(await loadSource(spec.sourceOptions))\n }\n }\n\n return await loadSource(spec.sourceOptions)\n },\n catch: (cause) => sourceError(spec.sourceOptions?.dotEnvPath, cause)\n })\n\n if (loaded.status === 'error') {\n return loaded\n }\n\n return await validate(spec.schema, loaded.value)\n}\n\nconst makeConfigValue = <Schema extends StandardSchemaV1, Requirements extends Service.Any>(\n spec: ConfigValueSpec<Schema>\n): ConfigValue<Schema, Requirements> => {\n const value = {\n ...spec,\n async *[Symbol.asyncIterator](): AsyncGenerator<\n RuntimeConfigYield,\n ConfigOutput<Schema>,\n unknown\n > {\n let provider: Config | undefined\n\n if (spec.source === 'provider') {\n provider = yield* Config\n }\n\n return yield* Result.await(evaluate(spec, provider))\n }\n }\n\n // SAFETY: The runtime iterator only yields Result errors and Service values; the public cast restores the phantom requirement.\n return value as ConfigValue<Schema, Requirements>\n}\n\n/** Host-backed raw configuration source and provider token. */\nexport class Config extends Service<Config>()('Config') {\n constructor(readonly source: ConfigSource) {\n super()\n }\n\n /** Read one raw value from the configured source. */\n get(key: string): string | undefined {\n return this.source[key]\n }\n\n /** Create a provider from an already-loaded source. */\n static layer(source: ConfigSource) {\n return Layer.succeed(Config, new Config(source))\n }\n\n /** Create a provider whose source is loaded from dotenv and the host environment. */\n static layerFromEnv(options: ConfigSourceOptions = {}) {\n return Layer.make(Config, async () => {\n try {\n return new Config(await loadSource(options))\n } catch (cause) {\n throw sourceError(options.dotEnvPath, cause)\n }\n })\n }\n\n /** Describe a configuration read from the contextual Config provider. */\n static schema<Schema extends StandardSchemaV1>(schema: Schema): ConfigValue<Schema, Config> {\n return makeConfigValue({ schema, source: 'provider' })\n }\n\n /** Describe a reusable configuration loaded from dotenv and the host environment. */\n static fromEnv<Schema extends StandardSchemaV1>(\n options: ConfigFromEnvOptions<Schema>\n ): ConfigValue<Schema> {\n const sourceOptions: MutableConfigSourceOptions = {}\n\n if (options.dotEnvPath !== undefined) {\n sourceOptions.dotEnvPath = options.dotEnvPath\n }\n\n if (options.envSource !== undefined) {\n sourceOptions.envSource = options.envSource\n }\n\n return makeConfigValue({\n schema: options.schema,\n source: 'bound',\n sourceOptions\n })\n }\n\n /** Add an environment source to a provider-backed descriptor for functional `pipe` composition. */\n static withEnv(options: ConfigSourceOptions) {\n return <Schema extends StandardSchemaV1, Requirements extends Service.Any, Error = ConfigError>(\n value: ConfigValue<Schema, Requirements, Error>\n ): ConfigValue<Schema, Requirements, Error> => {\n // SAFETY: Values produced by this module retain their schema/source descriptor fields; custom iterables pass through unchanged.\n const internal = value as ConfigValue<Schema, Requirements> & ConfigValueSpec<Schema>\n\n if (!('schema' in internal)) {\n return value\n }\n\n // SAFETY: The internal descriptor preserves the original schema and requirement phantom.\n return makeConfigValue({\n schema: internal.schema,\n source: internal.source,\n sourceOptions: options\n }) as ConfigValue<Schema, Requirements, Error>\n }\n }\n}\n\n/** The default lazy host-environment Config provider. */\nexport const ConfigLive = Config.layerFromEnv()\n\nexport type { StandardSchemaV1 }\n","import { Layer } from '../layer'\nimport { Service } from '../service'\n\ntype HostCrypto = {\n readonly randomUUID?: () => string\n}\n\nconst hostCrypto = (): HostCrypto | undefined => {\n // SAFETY: Supported hosts expose crypto on globalThis, but the optional property models older or restricted hosts.\n return (globalThis as { readonly crypto?: HostCrypto }).crypto\n}\n\n/** Thrown when the host does not expose the supported Web Crypto UUID API. */\nexport class IdGeneratorUnavailableError extends Error {\n constructor() {\n super('IdGenerator requires a host crypto.randomUUID implementation')\n\n this.name = 'IdGeneratorUnavailableError'\n }\n}\n\n/** Thrown when an {@link IdGeneratorTest} queue has no IDs left. */\nexport class IdGeneratorExhaustedError extends Error {\n constructor(readonly generated: number) {\n super(\n `IdGeneratorTest queue exhausted after ${generated} generated ID${generated === 1 ? '' : 's'}`\n )\n\n this.name = 'IdGeneratorExhaustedError'\n }\n}\n\n/** Host-backed UUID string ID service. */\nexport class IdGenerator extends Service<IdGenerator>()('IdGenerator') {\n /** Generate a cryptographically strong UUID string using the host Web Crypto API. */\n next(): string {\n const crypto = hostCrypto()\n\n // oxlint-disable-next-line anti-slop/no-runtime-typeof -- host feature detection must verify the callable Web Crypto method.\n if (crypto === undefined || typeof crypto.randomUUID !== 'function') {\n throw new IdGeneratorUnavailableError()\n }\n\n return crypto.randomUUID()\n }\n}\n\n/** The default host IdGenerator provider. */\nexport const IdGeneratorLive = Layer.make(IdGenerator)\n\ntype IdFactory = (index: number) => string\n\n// oxlint-disable-next-line anti-slop/no-unknown-parameters -- runtime validation protects the public string-ID boundary.\nconst validateId = (value: unknown, source: string): string => {\n // oxlint-disable-next-line anti-slop/no-runtime-typeof -- runtime validation rejects unsafe test doubles.\n if (typeof value !== 'string') {\n throw new TypeError(`${source} must return a string ID`)\n }\n\n return value\n}\n\n/** Deterministic queue- or factory-backed IdGenerator implementation for tests. */\nexport class IdGeneratorTest implements Service.Contract<IdGenerator> {\n private readonly queue: string[]\n\n private factory: IdFactory | undefined\n\n private generatedCount = 0\n\n constructor(ids: readonly string[] = []) {\n this.queue = ids.map((id) => validateId(id, 'IdGeneratorTest queue values'))\n }\n\n /** Number of IDs successfully returned by this test generator. */\n get generated(): number {\n return this.generatedCount\n }\n\n /** Number of queued IDs still available, or Infinity for a factory. */\n get remaining(): number {\n return this.factory === undefined ? this.queue.length : Infinity\n }\n\n /** Return the next queued or factory-generated string ID. */\n next(): string {\n if (this.factory === undefined) {\n const value = this.queue.shift()\n\n if (value === undefined) {\n throw new IdGeneratorExhaustedError(this.generatedCount)\n }\n\n this.generatedCount += 1\n return value\n }\n\n const value = validateId(this.factory(this.generatedCount), 'IdGeneratorTest factory')\n this.generatedCount += 1\n return value\n }\n\n /**\n * Create a factory-backed generator. The factory receives a monotonic\n * zero-based index: the first call receives 0, then 1, and so on.\n */\n static from(factory: IdFactory): IdGeneratorTest {\n // oxlint-disable-next-line anti-slop/no-runtime-typeof -- runtime validation rejects an invalid factory at the API boundary.\n if (typeof factory !== 'function') {\n throw new TypeError('IdGeneratorTest.from requires a factory function')\n }\n\n const generator = new IdGeneratorTest()\n generator.factory = factory\n return generator\n }\n\n /** Create a Layer for this generator, allocating a fresh empty queue by default. */\n static layer(generator: IdGeneratorTest = new IdGeneratorTest()) {\n return Layer.succeed(IdGenerator, generator)\n }\n}\n\n/** Compatible functional shorthand for {@link IdGeneratorTest.layer}. */\nexport const IdGeneratorTestLayer = (generator?: IdGeneratorTest) =>\n IdGeneratorTest.layer(generator)\n","import { CurrentAbortSignal } from '../runtime'\nimport { Layer } from '../layer'\nimport { Service } from '../service'\n\nexport { CurrentAbortSignal }\nexport { CurrentRequest, CurrentRequestLayer } from './current-request'\n\nexport { Config, ConfigLive, ConfigSourceError, ConfigValidationError } from './config'\n\nexport type {\n ConfigError,\n ConfigFromEnvOptions,\n ConfigInput,\n ConfigIssue,\n ConfigOutput,\n ConfigSource,\n ConfigSourceOptions,\n ConfigValue,\n StandardSchemaV1\n} from './config'\n\nexport {\n IdGenerator,\n IdGeneratorExhaustedError,\n IdGeneratorLive,\n IdGeneratorTest,\n IdGeneratorTestLayer,\n IdGeneratorUnavailableError\n} from './id-generator'\n\nconst assertDelay = (milliseconds: number): void => {\n if (!Number.isFinite(milliseconds) || milliseconds < 0) {\n throw new RangeError('Delay must be a finite non-negative number')\n }\n}\n\nconst abortError = (): DOMException => new DOMException('The operation was aborted', 'AbortError')\n\nconst abortReason = (signal: AbortSignal): AbortSignal['reason'] =>\n signal.reason === undefined ? abortError() : signal.reason\n\n/** Optional cooperative cancellation for a host or test Clock sleep. */\nexport type ClockSleepOptions = {\n readonly signal?: AbortSignal\n}\n\n/** Host-backed time and waiting service. */\nexport class Clock extends Service<Clock>()('Clock') {\n now(): Date {\n return new Date()\n }\n\n /** Rejects with the signal reason, or an AbortError-compatible fallback. */\n sleep(milliseconds: number, options?: ClockSleepOptions): Promise<void> {\n assertDelay(milliseconds)\n const signal = options?.signal\n\n if (signal?.aborted) {\n return Promise.reject(abortReason(signal))\n }\n\n return new Promise<void>((resolve, reject) => {\n let timer: ReturnType<typeof setTimeout> | undefined\n let settled = false\n\n function cleanup(): void {\n if (timer !== undefined) {\n clearTimeout(timer)\n timer = undefined\n }\n\n signal?.removeEventListener('abort', onAbort)\n }\n\n function settle(callback: () => void): void {\n if (settled) {\n return\n }\n\n settled = true\n cleanup()\n callback()\n }\n\n function onAbort(): void {\n if (signal !== undefined) {\n settle(() => reject(abortReason(signal)))\n }\n }\n\n try {\n signal?.addEventListener('abort', onAbort, { once: true })\n\n if (signal?.aborted) {\n onAbort()\n return\n }\n\n const handle = setTimeout(() => settle(resolve), milliseconds)\n\n if (settled) {\n clearTimeout(handle)\n } else {\n timer = handle\n }\n } catch (cause) {\n settle(() => reject(cause))\n }\n })\n }\n}\n\n/** The default host Clock provider. */\nexport const ClockLive = Layer.make(Clock)\n\ntype ClockWaiter = {\n readonly at: number\n readonly resolve: () => void\n readonly reject: (cause?: unknown) => void\n readonly signal: AbortSignal | undefined\n readonly onAbort: () => void\n settled: boolean\n}\n\n/** Limits deadline advances performed by `ClockTest.runAll`. */\nexport type ClockTestRunAllOptions = {\n readonly maxSteps?: number\n}\n\nconst defaultClockTestMaxSteps = 1_000\n\n/** Deterministic Clock implementation for tests. */\nexport class ClockTest implements Service.Contract<Clock> {\n private currentTime: number\n\n private readonly waiters: ClockWaiter[] = []\n\n constructor(initial: Date | number = 0) {\n this.currentTime = initial instanceof Date ? initial.getTime() : initial\n\n if (!Number.isFinite(this.currentTime)) {\n throw new RangeError('ClockTest time must be finite')\n }\n }\n\n /** Number of sleeps that have not been settled or cancelled. */\n get pendingSleeps(): number {\n return this.waiters.length\n }\n\n now(): Date {\n return new Date(this.currentTime)\n }\n\n /** Set an absolute time; moving backward leaves existing absolute deadlines unchanged. */\n setTime(value: Date | number): void {\n const next = value instanceof Date ? value.getTime() : value\n\n if (!Number.isFinite(next)) {\n throw new RangeError('ClockTest time must be finite')\n }\n\n this.currentTime = next\n this.flushWaiters()\n }\n\n advance(milliseconds: number): void {\n assertDelay(milliseconds)\n this.currentTime += milliseconds\n this.flushWaiters()\n }\n\n sleep(milliseconds: number, options?: ClockSleepOptions): Promise<void> {\n assertDelay(milliseconds)\n const signal = options?.signal\n\n if (signal?.aborted) {\n return Promise.reject(abortReason(signal))\n }\n\n return new Promise<void>((resolve, reject) => {\n let waiter!: ClockWaiter\n const onAbort = (): void => {\n if (signal !== undefined) {\n this.cancelWaiter(waiter, abortReason(signal))\n }\n }\n\n waiter = {\n at: this.currentTime + milliseconds,\n resolve,\n reject,\n signal,\n onAbort,\n settled: false\n }\n this.enqueueWaiter(waiter)\n\n try {\n signal?.addEventListener('abort', onAbort, { once: true })\n\n if (signal?.aborted) {\n this.cancelWaiter(waiter, abortReason(signal))\n return\n }\n } catch (cause) {\n this.cancelWaiter(waiter, cause)\n return\n }\n\n this.flushWaiters()\n })\n }\n\n /** Advance synchronously; due Promise continuations run after this method returns. */\n advanceToNext(): boolean {\n const next = this.waiters[0]\n\n if (next === undefined) {\n return false\n }\n\n this.currentTime = next.at\n this.flushWaiters()\n return true\n }\n\n /** Advance all pending deadlines, guarding at 1,000 steps by default. */\n async runAll(options?: ClockTestRunAllOptions): Promise<number> {\n const maxSteps = getMaxSteps(options)\n let steps = 0\n\n while (this.pendingSleeps > 0) {\n if (steps >= maxSteps) {\n throw new RangeError(`ClockTest.runAll exceeded maxSteps (${maxSteps})`)\n }\n\n this.advanceToNext()\n steps += 1\n await Promise.resolve()\n }\n\n return steps\n }\n\n static layer(initial: Date | number = 0) {\n return Layer.succeed(Clock, new ClockTest(initial))\n }\n\n private enqueueWaiter(waiter: ClockWaiter): void {\n const index = this.waiters.findIndex((pending) => pending.at > waiter.at)\n\n if (index === -1) {\n this.waiters.push(waiter)\n } else {\n this.waiters.splice(index, 0, waiter)\n }\n }\n\n private cancelWaiter(waiter: ClockWaiter, cause: unknown): void {\n const index = this.waiters.indexOf(waiter)\n\n if (index !== -1) {\n this.waiters.splice(index, 1)\n }\n\n this.finishWaiter(waiter, () => waiter.reject(cause))\n }\n\n private flushWaiters(): void {\n while (true) {\n const waiter = this.waiters[0]\n\n if (waiter === undefined || waiter.at > this.currentTime) {\n return\n }\n\n this.waiters.shift()\n this.finishWaiter(waiter, waiter.resolve)\n }\n }\n\n private finishWaiter(waiter: ClockWaiter, finish: () => void): void {\n if (waiter.settled) {\n return\n }\n\n waiter.settled = true\n waiter.signal?.removeEventListener('abort', waiter.onAbort)\n finish()\n }\n}\n\nconst getMaxSteps = (options?: ClockTestRunAllOptions): number => {\n const maxSteps = options?.maxSteps ?? defaultClockTestMaxSteps\n\n if (!Number.isInteger(maxSteps) || maxSteps < 0) {\n throw new RangeError('ClockTest.runAll maxSteps must be a finite non-negative integer')\n }\n\n return maxSteps\n}\n\nexport const ClockTestLayer = (initial: Date | number = 0) => ClockTest.layer(initial)\n\n/** Host-backed pseudo-random number service. */\nexport class Random extends Service<Random>()('Random') {\n next(): number {\n return Math.random()\n }\n\n nextInt(maxExclusive: number): number {\n if (!Number.isInteger(maxExclusive) || maxExclusive <= 0) {\n throw new RangeError('Random.nextInt maxExclusive must be a positive integer')\n }\n\n return Math.floor(this.next() * maxExclusive)\n }\n}\n\n/** The default host Random provider. */\nexport const RandomLive = Layer.make(Random)\n\n/** Reproducible pseudo-random implementation with isolated mutable state. */\nexport class RandomSeeded implements Service.Contract<Random> {\n private state: number\n\n constructor(seed: number) {\n if (!Number.isFinite(seed)) {\n throw new RangeError('RandomSeeded seed must be finite')\n }\n\n this.state = seed >>> 0\n }\n\n next(): number {\n this.state = (1664525 * this.state + 1013904223) >>> 0\n return this.state / 0x1_0000_0000\n }\n\n nextInt(maxExclusive: number): number {\n if (!Number.isInteger(maxExclusive) || maxExclusive <= 0) {\n throw new RangeError('RandomSeeded.nextInt maxExclusive must be a positive integer')\n }\n\n return Math.floor(this.next() * maxExclusive)\n }\n\n static layer(seed: number) {\n return Layer.succeed(Random, new RandomSeeded(seed))\n }\n}\n\nexport const RandomSeededLayer = (seed: number) => RandomSeeded.layer(seed)\n\nexport type LoggerLevel = 'debug' | 'info' | 'warn' | 'error'\n\nexport type LoggerEvent = {\n level: LoggerLevel\n message: string\n data?: LoggerData\n}\n\nexport type LoggerData =\n | string\n | number\n | boolean\n | bigint\n | null\n | readonly LoggerData[]\n | { readonly [key: string]: LoggerData }\ntype LoggerInput = LoggerEvent | LoggerLevel\n\nconst isLoggerLevel = (value: LoggerInput): value is LoggerLevel =>\n value === 'debug' || value === 'info' || value === 'warn' || value === 'error'\n\nconst toLoggerEvent = (input: LoggerInput, message?: string, data?: LoggerData): LoggerEvent => {\n if (!isLoggerLevel(input)) {\n return input\n }\n\n const event: LoggerEvent = { level: input, message: message ?? '' }\n\n if (data !== undefined) {\n event.data = data\n }\n\n return event\n}\n\n/** Structured host logger bridge. */\nexport class Logger extends Service<Logger>()('Logger') {\n log(event: LoggerEvent): void\n log(level: LoggerLevel, message: string, data?: LoggerData): void\n log(first: LoggerInput, message?: string, data?: LoggerData): void {\n const event = toLoggerEvent(first, message, data)\n\n const write = console[event.level]\n\n if (event.data === undefined) {\n write.call(console, event.message)\n } else {\n write.call(console, event.message, event.data)\n }\n }\n\n debug(message: string, data?: LoggerData): void {\n this.log('debug', message, data)\n }\n\n info(message: string, data?: LoggerData): void {\n this.log('info', message, data)\n }\n\n warn(message: string, data?: LoggerData): void {\n this.log('warn', message, data)\n }\n\n error(message: string, data?: LoggerData): void {\n this.log('error', message, data)\n }\n}\n\n/** The default host Logger provider. */\nexport const LoggerLive = Layer.make(Logger)\n\n/** Ordered in-memory Logger implementation for tests. */\nexport class LoggerTest implements Service.Contract<Logger> {\n readonly events: LoggerEvent[] = []\n\n log(event: LoggerEvent): void\n log(level: LoggerLevel, message: string, data?: LoggerData): void\n log(first: LoggerInput, message?: string, data?: LoggerData): void {\n const event = toLoggerEvent(first, message, data)\n\n this.events.push(event)\n }\n\n debug(message: string, data?: LoggerData): void {\n this.log('debug', message, data)\n }\n\n info(message: string, data?: LoggerData): void {\n this.log('info', message, data)\n }\n\n warn(message: string, data?: LoggerData): void {\n this.log('warn', message, data)\n }\n\n error(message: string, data?: LoggerData): void {\n this.log('error', message, data)\n }\n\n clear(): void {\n this.events.length = 0\n }\n\n static make() {\n const logger = new LoggerTest()\n return { logger, layer: Layer.succeed(Logger, logger) }\n }\n\n static layer(logger: LoggerTest = new LoggerTest()) {\n return Layer.succeed(Logger, logger)\n }\n}\n\nexport const LoggerTestLayer = () => LoggerTest.layer()\n"],"mappings":";;;;AAqCA,IAAa,wBAAb,cAA2C,YAAY,uBAAuB,CAAC,CAG5E,CAAC;;AAGJ,IAAa,oBAAb,cAAuC,YAAY,mBAAmB,CAAC,CAIpE,CAAC;AA4CJ,MAAM,gBAAgB;AAEtB,MAAM,wBAAsC;CAC1C,MAAM,qBAAqB,cAAc,SAAS;CAElD,IAAI,uBAAuB,KAAA,GACzB,OAAO;CAGT,OAAO,cAAc,KAAK,OAAO,CAAC;AACpC;AAEA,MAAM,W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AAb,MAAa,WAA+C;CAC1D,SAAiC,CAAC;CAIlC,IAAI,OAAoB,SAAkB,MAAyB;EACjE,MAAM,QAAQ,cAAc,OAAO,SAAS,IAAI;EAEhD,KAAK,OAAO,KAAK,KAAK;CACxB;CAEA,MAAM,SAAiB,MAAyB;EAC9C,KAAK,IAAI,SAAS,SAAS,IAAI;CACjC;CAEA,KAAK,SAAiB,MAAyB;EAC7C,KAAK,IAAI,QAAQ,SAAS,IAAI;CAChC;CAEA,KAAK,SAAiB,MAAyB;EAC7C,KAAK,IAAI,QAAQ,SAAS,IAAI;CAChC;CAEA,MAAM,SAAiB,MAAyB;EAC9C,KAAK,IAAI,SAAS,SAAS,IAAI;CACjC;CAEA,QAAc;EACZ,KAAK,OAAO,SAAS;CACvB;CAEA,OAAO,OAAO;EACZ,MAAM,SAAS,IAAI,WAAW;EAC9B,OAAO;GAAE;GAAQ,OAAO,MAAM,QAAQ,QAAQ,MAAM;EAAE;CACxD;CAEA,OAAO,MAAM,SAAqB,IAAI,WAAW,GAAG;EAClD,OAAO,MAAM,QAAQ,QAAQ,MAAM;CACrC;AACF;AAEA,MAAa,wBAAwB,WAAW,MAAM"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
-
import { c as CurrentAbortSignal } from "./index-
|
|
2
|
-
import {
|
|
1
|
+
import { c as CurrentAbortSignal } from "./index-BodMy6rO.mjs";
|
|
2
|
+
import { n as CurrentRequestLayer, t as CurrentRequest } from "./current-request-CIU7AHhF.mjs";
|
|
3
|
+
import { A as ConfigOutput, C as IdGeneratorUnavailableError, D as ConfigInput, E as ConfigFromEnvOptions, F as ConfigValue, I as StandardSchemaV1, M as ConfigSourceError, N as ConfigSourceOptions, O as ConfigIssue, P as ConfigValidationError, S as IdGeneratorTestLayer, T as ConfigError, _ as RandomSeededLayer, a as ClockTestLayer, b as IdGeneratorLive, c as LoggerData, d as LoggerLive, f as LoggerTest, g as RandomSeeded, h as RandomLive, i as ClockTest, j as ConfigSource, k as ConfigLive, l as LoggerEvent, m as Random, n as ClockLive, o as ClockTestRunAllOptions, p as LoggerTestLayer, r as ClockSleepOptions, s as Logger, t as Clock, u as LoggerLevel, v as IdGenerator, w as Config, x as IdGeneratorTest, y as IdGeneratorExhaustedError } from "./index-cXgyMa0v.mjs";
|
|
3
4
|
export { Clock, ClockLive, ClockSleepOptions, ClockTest, ClockTestLayer, ClockTestRunAllOptions, Config, type ConfigError, type ConfigFromEnvOptions, type ConfigInput, type ConfigIssue, ConfigLive, type ConfigOutput, type ConfigSource, ConfigSourceError, type ConfigSourceOptions, ConfigValidationError, type ConfigValue, CurrentAbortSignal, CurrentRequest, CurrentRequestLayer, IdGenerator, IdGeneratorExhaustedError, IdGeneratorLive, IdGeneratorTest, IdGeneratorTestLayer, IdGeneratorUnavailableError, Logger, LoggerData, LoggerEvent, LoggerLevel, LoggerLive, LoggerTest, LoggerTestLayer, Random, RandomLive, RandomSeeded, RandomSeededLayer, type StandardSchemaV1 };
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
-
import { t as CurrentAbortSignal } from "./signal-
|
|
2
|
-
import {
|
|
1
|
+
import { t as CurrentAbortSignal } from "./signal-nfgFyNCk.mjs";
|
|
2
|
+
import { n as CurrentRequestLayer, t as CurrentRequest } from "./current-request-DDKNyymv.mjs";
|
|
3
|
+
import { S as ConfigValidationError, _ as IdGeneratorTestLayer, a as Logger, b as ConfigLive, c as LoggerTestLayer, d as RandomSeeded, f as RandomSeededLayer, g as IdGeneratorTest, h as IdGeneratorLive, i as ClockTestLayer, l as Random, m as IdGeneratorExhaustedError, n as ClockLive, o as LoggerLive, p as IdGenerator, r as ClockTest, s as LoggerTest, t as Clock, u as RandomLive, v as IdGeneratorUnavailableError, x as ConfigSourceError, y as Config } from "./standard-services-vnGIafkS.mjs";
|
|
3
4
|
export { Clock, ClockLive, ClockTest, ClockTestLayer, Config, ConfigLive, ConfigSourceError, ConfigValidationError, CurrentAbortSignal, CurrentRequest, CurrentRequestLayer, IdGenerator, IdGeneratorExhaustedError, IdGeneratorLive, IdGeneratorTest, IdGeneratorTestLayer, IdGeneratorUnavailableError, Logger, LoggerLive, LoggerTest, LoggerTestLayer, Random, RandomLive, RandomSeeded, RandomSeededLayer };
|
package/dist/testing.d.mts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { M as AnyService, c as RuntimeContextStorage } from "./index-
|
|
2
|
-
import { C as
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
1
|
+
import { M as AnyService, c as RuntimeContextStorage } from "./index-AiKM71-u.mjs";
|
|
2
|
+
import { C as OverrideLayerResult, E as ValidateLayerInput, O as ValidateOverrides, T as RequiredEnvironment, b as LayerInputState, d as LayerBackend, g as CompleteExecutionLayer, h as CompleteExecution, i as RuntimeRunOptions, j as MissingDependencies, k as ValidateOverridesWitness, n as RuntimeDisposeOptions, r as RuntimeOptions, w as ProvidedEnvironment, y as LayerInput } from "./outcome-DI8LPIQ4.mjs";
|
|
3
|
+
import { a as RuntimeObserver, c as RuntimeServiceResolveEvent, i as RuntimeExecutionStartEvent, n as RuntimeExecutionEndEvent, o as RuntimeResourceReleaseEvent, s as RuntimeServiceAcquireEvent } from "./observer-9nhbL7Pr.mjs";
|
|
4
|
+
import { t as MapLayerBackend } from "./index-DAKn0qHk.mjs";
|
|
5
|
+
import { l as Runtime } from "./index-BodMy6rO.mjs";
|
|
6
|
+
import { f as LoggerTest, g as RandomSeeded, i as ClockTest, x as IdGeneratorTest } from "./index-cXgyMa0v.mjs";
|
|
6
7
|
//#region src/testing/contracts.d.ts
|
|
7
8
|
/** One runner-neutral conformance scenario. */
|
|
8
9
|
interface ContractScenario {
|
package/dist/testing.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"testing.d.mts","names":[],"sources":["../src/testing/contracts.ts","../src/testing/recorded-runtime-observer.ts","../src/testing/runtime-graph-observer.ts","../src/testing/test-runtime.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"testing.d.mts","names":[],"sources":["../src/testing/contracts.ts","../src/testing/recorded-runtime-observer.ts","../src/testing/runtime-graph-observer.ts","../src/testing/test-runtime.ts"],"mappings":";;;;;;;;UAyBiB;;WAEN;;WAGA,WAAW;;;cAIT,yBAAyB;WAEzB;EAAA,YAAA,kBACT,gBACA;;;KASQ;;UAGK;;WAEN,mBAAmB,eAAe,YAAY;;WAG9C,oBAAoB;;WAGpB,WAAW,SAAS,wBAAwB;;;KAI3C;;UAGK;;WAEN,mBAAmB;;WAGnB,aAAa;;WAGb,yBAAyB;;WAGzB,kBAAkB;;WAGlB,6BAA6B;;WAG7B,WAAW,SAAS,iCAAiC;;;;;;;;cAmKnD,uBACX,SAAS,yCACC;;;;;;;cAohBC,gCACX,SAAS,kDACC;;;;KCnwBA,uBACR,6BACA,6BACA,6BACA,2BACA;;KAGQ;WACD,6BAA6B;WAC7B,8BAA8B;WAC9B,0BAA0B;WAC1B,wBAAwB;WACxB,2BAA2B;WAC3B,mBAAmB;;;cAOjB,mCAAmC;mBAC7B;mBACA;mBACA;mBACA;mBACA;mBACA;SAEV,QAAQ;WAIN,mBAAoB,OAAO;WAI3B,mBAAoB,OAAO;WAI3B,mBAAoB,OAAO;WAI3B,iBAAkB,OAAO;WAIzB,oBAAqB,OAAO;MAIjC,+BAA+B;MAI/B,gCAAgC;MAIhC,4BAA4B;MAI5B,0BAA0B;MAI1B,6BAA6B;MAI7B,qBAAqB;EAIzB;EASA,YAAY;UAWJ;;;;;KCnGE;WACD;WACA;WACA;WACA;;;KAIC;WACD;WACA;WACA;;;KAIC;WACD,gBAAgB;WAChB,gBAAgB;;;KAIf;;WAED;;WAEA;;;;;;;;cAmHE,gCAAgC;mBAMxB;mBACA;mBANF;mBACA;mBACA;UAEV;;SAMA,KAAK,UAAS,8BAAmC;WAmB/C,mBAAoB,OAAO;WAmC3B,mBAAoB,OAAO;;EAcpC,UAAU;;EAwBV;;EAiDA;UAMQ;UAYA;;;;cCrRI;KAET,2BACH,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UAAU,wBAAwB;;GAKzC,OAAO,iBAAiB;UAIjB;UAIA;UA4BA;UAQA;;SAcD,IAAI,GAAG,UAAU,YACtB,OAAO,IAAI,mBAAmB,IAC9B,KAAK,aAAa,oBAAoB,IAAI,KACzC,QAAQ,QAAQ;SAEZ,IAAI,GAAG,UAAU,kBAAkB,gBAAgB,yBACxD,OAAO,IAAI,mBAAmB,KAAK,mBAAmB,iBAAiB,GAAG,QAAQ,YAClF,SAAS,UAAU,6BAA6B,GAAG,UACnD,KAAK,aAAa,oBAAoB,iBAAiB,GAAG,WAAW,GAAG,WACvE,QAAQ,QAAQ;;;kBA8II;;OAEX,QACV,aAAa,aAAa,YAC1B,2BAA2B,8BACzB,mBAAmB,MAAM;;OAGjB,aAAa;;OAGb,iBAAiB"}
|
package/dist/testing.mjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { i as LayerDisposeError, r as DuplicateServiceError, s as ServiceTagCollisionError, u as ServiceNotFoundError } from "./registration-drnZk0SY.mjs";
|
|
2
|
-
import { g as RuntimeContextOverlapError, h as RuntimeContextNotConfiguredError } from "./context-
|
|
2
|
+
import { g as RuntimeContextOverlapError, h as RuntimeContextNotConfiguredError } from "./context-BphfFUMO.mjs";
|
|
3
3
|
import { t as isPromiseLike } from "./runtime-CDcCF5cb.mjs";
|
|
4
|
-
import {
|
|
5
|
-
import { n as Service, r as ServiceRuntime, t as Layer } from "./layer-
|
|
6
|
-
import { i as Scope, o as ScopeRuntime } from "./program-metadata-
|
|
7
|
-
import { i as MapLayerBackend, n as RuntimeObserver, r as classifyRuntimeOutcome, t as Runtime } from "./runtime-
|
|
8
|
-
import { d as
|
|
4
|
+
import { a as ScopeClosedError, i as ScopeCloseError } from "./disposable-CP-Q2H3l.mjs";
|
|
5
|
+
import { n as Service, r as ServiceRuntime, t as Layer } from "./layer-D16GKxuX.mjs";
|
|
6
|
+
import { i as Scope, o as ScopeRuntime } from "./program-metadata-BxjGkT17.mjs";
|
|
7
|
+
import { i as MapLayerBackend, n as RuntimeObserver, r as classifyRuntimeOutcome, t as Runtime } from "./runtime-C_55ofnL.mjs";
|
|
8
|
+
import { a as Logger, d as RandomSeeded, g as IdGeneratorTest, l as Random, p as IdGenerator, r as ClockTest, s as LoggerTest, t as Clock } from "./standard-services-vnGIafkS.mjs";
|
|
9
9
|
//#region src/testing/contracts.ts
|
|
10
10
|
/** Thrown by a conformance scenario when an adapter violates its contract. */
|
|
11
11
|
var ConformanceError = class extends Error {
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { C as EffectError, M as AnyService, V as ServiceTagOf, k as Program } from "./index-AiKM71-u.mjs";
|
|
2
|
+
import { D as ValidateOneOverride, E as ValidateLayerInput, S as MissingServices, T as RequiredEnvironment, j as MissingDependencies, p as Layer, v as ExecutionMissing, w as ProvidedEnvironment, y as LayerInput } from "./outcome-DI8LPIQ4.mjs";
|
|
3
|
+
import { t as CurrentRequest } from "./current-request-CIU7AHhF.mjs";
|
|
4
|
+
//#region src/web/types.d.ts
|
|
5
|
+
/** A Web Response returned synchronously or asynchronously by a boundary policy. */
|
|
6
|
+
type ResponseLike = Response | PromiseLike<Response>;
|
|
7
|
+
/** JSON-compatible values accepted by the default Web success policy. */
|
|
8
|
+
type WebJsonValue = null | boolean | number | string | readonly WebJsonValue[] | {
|
|
9
|
+
readonly [key: string]: WebJsonValue;
|
|
10
|
+
};
|
|
11
|
+
/** The value passed to a WebEffect success policy. */
|
|
12
|
+
type WebEffectSuccess<A = unknown> = {
|
|
13
|
+
readonly value: A;
|
|
14
|
+
};
|
|
15
|
+
/** A lazy Program type accepted by the WebEffect boundary. */
|
|
16
|
+
type WebEffectProgram<A = unknown, E = unknown, R extends AnyService = never> = Program<A, E, R>;
|
|
17
|
+
/** @internal */
|
|
18
|
+
type AnyProgram = WebEffectProgram<any, any, AnyService>;
|
|
19
|
+
type IsAny<Type> = 0 extends 1 & Type ? true : false;
|
|
20
|
+
type IsWidenedEnvironment<Provided extends AnyService> = IsAny<Provided> extends true ? true : string extends ServiceTagOf<Provided> ? true : false;
|
|
21
|
+
/** @internal The request Layer installed by WebEffect when no custom Layer is supplied. */
|
|
22
|
+
type DefaultRequestLayer = ReturnType<typeof CurrentRequest.layer>;
|
|
23
|
+
/** @internal Services provided by a request Layer. */
|
|
24
|
+
type RequestProvided<RequestLayer extends LayerInput> = ProvidedEnvironment<RequestLayer>;
|
|
25
|
+
/** @internal Services available to a WebEffect Program. */
|
|
26
|
+
type AvailableServices<Provided extends AnyService, RequestLayer extends LayerInput> = Provided | InstanceType<typeof CurrentRequest> | RequestProvided<RequestLayer>;
|
|
27
|
+
type InvalidFailure<Actual, Expected> = {
|
|
28
|
+
readonly __betterEffectInvalidWebFailure: {
|
|
29
|
+
readonly actual: Actual;
|
|
30
|
+
readonly expected: Expected;
|
|
31
|
+
};
|
|
32
|
+
};
|
|
33
|
+
type FailureCheck<Failure, Actual> = [Actual] extends [Failure] ? unknown : InvalidFailure<Actual, Failure>;
|
|
34
|
+
type RequestLayerMissing<Provided extends AnyService, RequestLayer extends LayerInput> = MissingServices<Extract<RequiredEnvironment<RequestLayer>, AnyService>, Extract<Provided | InstanceType<typeof CurrentRequest>, AnyService>>;
|
|
35
|
+
/** @internal Validate a custom request Layer against the Runtime and CurrentRequest. */
|
|
36
|
+
type WebRequestLayerChecks<Provided extends AnyService, RequestLayer extends LayerInput> = ValidateLayerInput<RequestLayer> & (IsWidenedEnvironment<Provided> extends true ? unknown : ValidateOneOverride<Layer<Provided, never>, RequestLayer>) & ValidateOneOverride<DefaultRequestLayer, RequestLayer> & ([RequestLayerMissing<Provided, RequestLayer>] extends [never] ? unknown : MissingDependencies<RequestLayerMissing<Provided, RequestLayer>>);
|
|
37
|
+
/** @internal Services missing from a WebEffect Program. */
|
|
38
|
+
type WebProgramMissing<Provided extends AnyService, RequestLayer extends LayerInput, Program extends AnyProgram> = ExecutionMissing<AvailableServices<Provided, RequestLayer>, Program>;
|
|
39
|
+
/** @internal Validate a WebEffect Program's Services and typed failure channel. */
|
|
40
|
+
type CompleteWebProgram<Provided extends AnyService, RequestLayer extends LayerInput, Program extends AnyProgram, Failure = unknown> = Program & WebProgramChecks<Provided, RequestLayer, Program, Failure>;
|
|
41
|
+
/** @internal Checks applied to a Program after the request Layer has been inferred. */
|
|
42
|
+
type WebProgramChecks<Provided extends AnyService, RequestLayer extends LayerInput, Program extends AnyProgram, Failure = unknown> = (WebProgramMissing<Provided, RequestLayer, Program> extends never ? unknown : MissingDependencies<WebProgramMissing<Provided, RequestLayer, Program>>) & FailureCheck<NoInfer<Failure>, EffectError<Program>>;
|
|
43
|
+
/** Options for converting a WebEffect Result into a standard Response. */
|
|
44
|
+
type WebEffectOptions<Failure = unknown, RequestLayer extends LayerInput = DefaultRequestLayer, Success = unknown> = {
|
|
45
|
+
/** Build a request-local Layer. It is evaluated once for each Request. */
|
|
46
|
+
readonly requestLayer?: (request: Request) => RequestLayer;
|
|
47
|
+
/** Convert a successful Program value into a Response. */
|
|
48
|
+
readonly onSuccess?: (result: WebEffectSuccess<Success>) => ResponseLike;
|
|
49
|
+
/** Convert a typed Program failure into a Response. */
|
|
50
|
+
readonly onFailure?: (error: Failure) => ResponseLike;
|
|
51
|
+
};
|
|
52
|
+
//#endregion
|
|
53
|
+
export { WebEffectOptions as a, WebJsonValue as c, ResponseLike as i, WebProgramChecks as l, CompleteWebProgram as n, WebEffectProgram as o, DefaultRequestLayer as r, WebEffectSuccess as s, AnyProgram as t, WebRequestLayerChecks as u };
|
|
54
|
+
//# sourceMappingURL=types-oihI-ESv.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types-oihI-ESv.d.mts","names":[],"sources":["../src/web/types.ts"],"mappings":";;;;;KAiBY,eAAe,WAAW,YAAY;;KAGtC,2DAKC;YACG,cAAc;;;KAGlB,iBAAiB;WAClB,OAAO;;;KAIN,iBAAiB,aAAa,aAAa,UAAU,sBAAsB,QACrF,GACA,GACA;;KAIU,aAAa,2BAA2B;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