better-effect 0.13.0 → 0.14.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.
Files changed (109) hide show
  1. package/README.md +337 -88
  2. package/dist/adapters/iti.d.mts +2 -3
  3. package/dist/adapters/iti.d.mts.map +1 -1
  4. package/dist/adapters/iti.mjs +2 -2
  5. package/dist/bun.d.mts +75 -23
  6. package/dist/bun.d.mts.map +1 -1
  7. package/dist/bun.mjs +170 -33
  8. package/dist/bun.mjs.map +1 -1
  9. package/dist/{context-BphfFUMO.mjs → context-DSGSqcJj.mjs} +12 -3
  10. package/dist/context-DSGSqcJj.mjs.map +1 -0
  11. package/dist/{current-request-DDKNyymv.mjs → current-request-Bc1YHL0w.mjs} +3 -2
  12. package/dist/{current-request-DDKNyymv.mjs.map → current-request-Bc1YHL0w.mjs.map} +1 -1
  13. package/dist/{current-request-CIU7AHhF.d.mts → current-request-Dm-QQ3Xr.d.mts} +4 -4
  14. package/dist/current-request-Dm-QQ3Xr.d.mts.map +1 -0
  15. package/dist/{effect-CPdV7Yv8.mjs → effect-W0IQXY8P.mjs} +21 -2
  16. package/dist/effect-W0IQXY8P.mjs.map +1 -0
  17. package/dist/{errors-BKcsQ0ip.d.mts → errors-CpHMzPiP.d.mts} +6 -2
  18. package/dist/errors-CpHMzPiP.d.mts.map +1 -0
  19. package/dist/hono.d.mts +63 -27
  20. package/dist/hono.d.mts.map +1 -1
  21. package/dist/hono.mjs +111 -45
  22. package/dist/hono.mjs.map +1 -1
  23. package/dist/{index-CCi07kUw.d.mts → index-3Bkl-sxS.d.mts} +7 -2
  24. package/dist/{index-CCi07kUw.d.mts.map → index-3Bkl-sxS.d.mts.map} +1 -1
  25. package/dist/{index-cXgyMa0v.d.mts → index-C2ed9Ilq.d.mts} +32 -7
  26. package/dist/index-C2ed9Ilq.d.mts.map +1 -0
  27. package/dist/{index-BodMy6rO.d.mts → index-ClNndn2-.d.mts} +93 -63
  28. package/dist/index-ClNndn2-.d.mts.map +1 -0
  29. package/dist/{index-DAKn0qHk.d.mts → index-Cy1VsU-u.d.mts} +2 -4
  30. package/dist/index-Cy1VsU-u.d.mts.map +1 -0
  31. package/dist/index.d.mts +6 -8
  32. package/dist/index.mjs +8 -9
  33. package/dist/index.mjs.map +1 -1
  34. package/dist/{internal-identity-CbXoZIfw.mjs → internal-identity-BuHBtP0k.mjs} +2 -2
  35. package/dist/{internal-identity-CbXoZIfw.mjs.map → internal-identity-BuHBtP0k.mjs.map} +1 -1
  36. package/dist/layer-2kjHVv4N.mjs +343 -0
  37. package/dist/layer-2kjHVv4N.mjs.map +1 -0
  38. package/dist/layer-C2OaqTmB.d.mts +987 -0
  39. package/dist/layer-C2OaqTmB.d.mts.map +1 -0
  40. package/dist/next.d.mts +102 -26
  41. package/dist/next.d.mts.map +1 -1
  42. package/dist/next.mjs +157 -40
  43. package/dist/next.mjs.map +1 -1
  44. package/dist/{node-context-DczjAcrX.d.mts → node-context-1YEjrU9g.d.mts} +2 -2
  45. package/dist/{node-context-DczjAcrX.d.mts.map → node-context-1YEjrU9g.d.mts.map} +1 -1
  46. package/dist/{node-context-Ca18oNSg.mjs → node-context-g3bCcY9t.mjs} +2 -2
  47. package/dist/{node-context-Ca18oNSg.mjs.map → node-context-g3bCcY9t.mjs.map} +1 -1
  48. package/dist/node.d.mts +11 -6
  49. package/dist/node.d.mts.map +1 -1
  50. package/dist/node.mjs +156 -10
  51. package/dist/node.mjs.map +1 -1
  52. package/dist/opentelemetry.d.mts +20 -2
  53. package/dist/opentelemetry.d.mts.map +1 -1
  54. package/dist/opentelemetry.mjs +423 -5
  55. package/dist/opentelemetry.mjs.map +1 -1
  56. package/dist/{registration-drnZk0SY.mjs → registration-Bwe2GbVu.mjs} +8 -2
  57. package/dist/registration-Bwe2GbVu.mjs.map +1 -0
  58. package/dist/runtime/explicit.d.mts +2 -2
  59. package/dist/runtime/explicit.mjs +1 -1
  60. package/dist/runtime/node.d.mts +3 -3
  61. package/dist/runtime/node.mjs +2 -2
  62. package/dist/runtime-qpcVwaz_.mjs +1680 -0
  63. package/dist/runtime-qpcVwaz_.mjs.map +1 -0
  64. package/dist/service-CO9VJQYa.mjs +74 -0
  65. package/dist/service-CO9VJQYa.mjs.map +1 -0
  66. package/dist/{signal-nfgFyNCk.mjs → signal-5Rg9bUUe.mjs} +2 -2
  67. package/dist/{signal-nfgFyNCk.mjs.map → signal-5Rg9bUUe.mjs.map} +1 -1
  68. package/dist/{standard-services-vnGIafkS.mjs → standard-services-B-iMM_W7.mjs} +38 -4
  69. package/dist/standard-services-B-iMM_W7.mjs.map +1 -0
  70. package/dist/standard-services.d.mts +4 -4
  71. package/dist/standard-services.mjs +3 -3
  72. package/dist/testing.d.mts +25 -7
  73. package/dist/testing.d.mts.map +1 -1
  74. package/dist/testing.mjs +51 -7
  75. package/dist/testing.mjs.map +1 -1
  76. package/dist/{types-oihI-ESv.d.mts → types-BFTqCCcw.d.mts} +32 -5
  77. package/dist/types-BFTqCCcw.d.mts.map +1 -0
  78. package/dist/web-effect-B9hp9jIe.mjs +380 -0
  79. package/dist/web-effect-B9hp9jIe.mjs.map +1 -0
  80. package/dist/web.d.mts +22 -13
  81. package/dist/web.d.mts.map +1 -1
  82. package/dist/web.mjs +1 -1
  83. package/package.json +10 -16
  84. package/dist/context-BphfFUMO.mjs.map +0 -1
  85. package/dist/current-request-CIU7AHhF.d.mts.map +0 -1
  86. package/dist/disposable-CP-Q2H3l.mjs +0 -57
  87. package/dist/disposable-CP-Q2H3l.mjs.map +0 -1
  88. package/dist/effect-CPdV7Yv8.mjs.map +0 -1
  89. package/dist/errors-BKcsQ0ip.d.mts.map +0 -1
  90. package/dist/index-AiKM71-u.d.mts +0 -376
  91. package/dist/index-AiKM71-u.d.mts.map +0 -1
  92. package/dist/index-BodMy6rO.d.mts.map +0 -1
  93. package/dist/index-DAKn0qHk.d.mts.map +0 -1
  94. package/dist/index-cXgyMa0v.d.mts.map +0 -1
  95. package/dist/layer-D16GKxuX.mjs +0 -269
  96. package/dist/layer-D16GKxuX.mjs.map +0 -1
  97. package/dist/observer-9nhbL7Pr.d.mts +0 -68
  98. package/dist/observer-9nhbL7Pr.d.mts.map +0 -1
  99. package/dist/outcome-DI8LPIQ4.d.mts +0 -387
  100. package/dist/outcome-DI8LPIQ4.d.mts.map +0 -1
  101. package/dist/program-metadata-BxjGkT17.mjs +0 -260
  102. package/dist/program-metadata-BxjGkT17.mjs.map +0 -1
  103. package/dist/registration-drnZk0SY.mjs.map +0 -1
  104. package/dist/runtime-C_55ofnL.mjs +0 -791
  105. package/dist/runtime-C_55ofnL.mjs.map +0 -1
  106. package/dist/standard-services-vnGIafkS.mjs.map +0 -1
  107. package/dist/types-oihI-ESv.d.mts.map +0 -1
  108. package/dist/web-Bq3MfMrj.mjs +0 -147
  109. package/dist/web-Bq3MfMrj.mjs.map +0 -1
@@ -1 +0,0 @@
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;;CAGxE,SAAS,cAAuC;EAC9C,MAAM,aAAa,2BAA2B,YAAY;EAC1D,MAAM,MAAM,4BAA4B,UAAU;EAClD,MAAM,WAAW,KAAK,UAAU,IAAI,GAAG;EAEvC,IAAI,UAAU;GACZ,IAAI,SAAS,YAAY,WAAW,SAClC,MAAM,IAA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AAM,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"}
@@ -1 +0,0 @@
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,O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AoB,kBACpB,gBAAgB;KAEf,eAAe,QAAQ;WACjB;aACE,QAAQ;aACR,UAAU;;;KAIlB,aAAa,SAAS,WAAW,iBAAiB,qBAEnD,eAAe,QAAQ;KAEtB,oBACH,iBAAiB,YACjB,qBAAqB,cACnB,gBACF,QAAQ,oBAAoB,eAAe,aAC3C,QAAQ,WAAW,oBAAoB,iBAAiB;;KAI9C,sBACV,iBAAiB,YACjB,qBAAqB,cACnB,mBAAmB,iBACpB,qBAAqB,mCAElB,oBAAoB,MAAM,kBAAkB,iBAChD,oBAAoB,qBAAqB,kBACvC,oBAAoB,UAAU,2CAE5B,oBAAoB,oBAAoB,UAAU;;KAG5C,kBACV,iBAAiB,YACjB,qBAAqB,YACrB,gBAAgB,cACd,iBAAiB,kBAAkB,UAAU,eAAe;;KAGpD,mBACV,iBAAiB,YACjB,qBAAqB,YACrB,gBAAgB,YAChB,qBACE,UAAU,iBAAiB,UAAU,cAAc,SAAS;;KAGpD,iBACV,iBAAiB,YACjB,qBAAqB,YACrB,gBAAgB,YAChB,sBACG,kBAAkB,UAAU,cAAc,mCAE3C,oBAAoB,kBAAkB,UAAU,cAAc,aAChE,aAAa,QAAQ,UAAU,YAAY;;KAGjC,iBACV,mBACA,qBAAqB,aAAa,qBAClC;;WAGS,gBAAgB,SAAS,YAAY;;WAErC,aAAa,QAAQ,iBAAiB,aAAa;;WAEnD,aAAa,OAAO,YAAY"}
@@ -1,147 +0,0 @@
1
- import { t as Layer } from "./layer-D16GKxuX.mjs";
2
- import { t as CurrentRequest } from "./current-request-DDKNyymv.mjs";
3
- import { Result } from "better-result";
4
- //#region src/web/responses.ts
5
- const DEFAULT_FAILURE_MESSAGE = "Internal Server Error";
6
- /** An unsupported value encountered by the default Web JSON policy. */
7
- var WebEffectSerializationError = class extends TypeError {
8
- constructor(detail) {
9
- super(`WebEffect default success serialization ${detail}`);
10
- this.name = "WebEffectSerializationError";
11
- }
12
- };
13
- const isObject = (value) => typeof value === "object" && value !== null;
14
- const isCallable = (value) => typeof value === "function";
15
- const isHeaders = (value) => {
16
- if (!isObject(value)) return false;
17
- const candidate = value;
18
- return isCallable(candidate.append) && isCallable(candidate.delete) && isCallable(candidate.get) && isCallable(candidate.getSetCookie) && isCallable(candidate.has) && isCallable(candidate.set) && isCallable(candidate.forEach);
19
- };
20
- const isBody = (value) => {
21
- if (value === null) return true;
22
- if (!isObject(value)) return false;
23
- const candidate = value;
24
- return typeof candidate.locked === "boolean" && isCallable(candidate.cancel) && isCallable(candidate.getReader) && isCallable(candidate.pipeThrough) && isCallable(candidate.pipeTo) && isCallable(candidate.tee);
25
- };
26
- const isResponseStatus = (value) => typeof value === "number" && Number.isInteger(value) && (value === 0 || value >= 200 && value <= 599);
27
- const isResponseType = (value) => value === "basic" || value === "cors" || value === "default" || value === "error" || value === "opaque" || value === "opaqueredirect";
28
- /** Accept native, cross-realm, and standards-compatible Web Response values. */
29
- const isWebResponse = (value) => {
30
- if (!isObject(value)) return false;
31
- try {
32
- const candidate = value;
33
- const status = candidate.status;
34
- if (!isResponseStatus(status)) return false;
35
- return isBody(candidate.body) && typeof candidate.bodyUsed === "boolean" && isHeaders(candidate.headers) && typeof candidate.ok === "boolean" && candidate.ok === (status >= 200 && status <= 299) && typeof candidate.redirected === "boolean" && typeof candidate.statusText === "string" && isResponseType(candidate.type) && typeof candidate.url === "string" && isCallable(candidate.arrayBuffer) && isCallable(candidate.blob) && isCallable(candidate.bytes) && isCallable(candidate.clone) && isCallable(candidate.formData) && isCallable(candidate.json) && isCallable(candidate.text);
36
- } catch {
37
- return false;
38
- }
39
- };
40
- const propertyPath = (path, property) => `${path}.${property}`;
41
- const unsupported = (path, kind) => {
42
- throw new WebEffectSerializationError(`cannot encode ${kind} at ${path}`);
43
- };
44
- const ownDataProperties = (value, path) => {
45
- if (Object.getOwnPropertySymbols(value).length > 0) unsupported(path, "symbol-keyed properties");
46
- return Object.getOwnPropertyNames(value).map((property) => {
47
- const descriptor = Object.getOwnPropertyDescriptor(value, property);
48
- if (descriptor === void 0 || !("value" in descriptor) || descriptor.enumerable !== true) unsupported(propertyPath(path, property), "non-enumerable or accessor properties");
49
- return [property, descriptor.value];
50
- });
51
- };
52
- const arrayIndex = (property) => {
53
- const index = Number(property);
54
- return Number.isInteger(index) && index >= 0 && index < 2 ** 32 - 1 && String(index) === property ? index : void 0;
55
- };
56
- const sanitizeArray = (value, path, ancestors) => {
57
- if (Object.getOwnPropertySymbols(value).length > 0) unsupported(path, "symbol-keyed properties");
58
- const properties = Object.getOwnPropertyNames(value);
59
- if (properties.length !== value.length + 1 || !properties.includes("length")) unsupported(path, "sparse or augmented arrays");
60
- const output = [];
61
- for (let index = 0; index < value.length; index += 1) {
62
- const property = String(index);
63
- const descriptor = Object.getOwnPropertyDescriptor(value, property);
64
- if (descriptor === void 0 || !("value" in descriptor) || descriptor.enumerable !== true || arrayIndex(property) === void 0) unsupported(propertyPath(path, property), "sparse or accessor array elements");
65
- const dataDescriptor = descriptor;
66
- output.push(sanitizeJsonValue(dataDescriptor.value, propertyPath(path, property), ancestors));
67
- }
68
- return output;
69
- };
70
- const sanitizeObject = (value, path, ancestors) => {
71
- const prototype = Object.getPrototypeOf(value);
72
- if (prototype !== Object.prototype && prototype !== null) unsupported(path, "non-plain objects");
73
- const output = Object.create(null);
74
- for (const [property, child] of ownDataProperties(value, path)) output[property] = sanitizeJsonValue(child, propertyPath(path, property), ancestors);
75
- return output;
76
- };
77
- const sanitizeJsonValue = (value, path, ancestors = /* @__PURE__ */ new Set()) => {
78
- if (value === null || typeof value === "boolean" || typeof value === "string") return value;
79
- if (typeof value === "number") return Number.isFinite(value) ? value : unsupported(path, "non-finite numbers");
80
- if (typeof value === "undefined") return unsupported(path, "undefined values");
81
- if (typeof value === "bigint" || typeof value === "function" || typeof value === "symbol") return unsupported(path, `${typeof value} values`);
82
- if (!isObject(value)) return unsupported(path, "unsupported values");
83
- if (ancestors.has(value)) return unsupported(path, "circular values");
84
- ancestors.add(value);
85
- try {
86
- return Array.isArray(value) ? sanitizeArray(value, path, ancestors) : sanitizeObject(value, path, ancestors);
87
- } finally {
88
- ancestors.delete(value);
89
- }
90
- };
91
- /** Convert a successful value using the boundary's constrained JSON policy. */
92
- const defaultSuccess = ({ value }) => {
93
- if (isWebResponse(value)) return value;
94
- if (value === void 0) return new Response(null, { status: 204 });
95
- return Response.json({ data: sanitizeJsonValue(value, "$") });
96
- };
97
- /** Redact typed failures unless the failure is an intentional Response. */
98
- const defaultFailure = (error) => {
99
- if (isWebResponse(error)) return error;
100
- return Response.json({ error: DEFAULT_FAILURE_MESSAGE }, { status: 500 });
101
- };
102
- /** Validate policy output at the JavaScript boundary before returning it. */
103
- const assertResponse = (response) => {
104
- if (!isWebResponse(response)) throw new TypeError("WebEffect response policies must return a Response");
105
- return response;
106
- };
107
- //#endregion
108
- //#region src/web/web-effect.ts
109
- const combineRequestLayer = (request, customLayer) => {
110
- const currentRequestLayer = CurrentRequest.layer(request);
111
- if (customLayer === void 0) return currentRequestLayer;
112
- return Layer.override(currentRequestLayer, customLayer);
113
- };
114
- /** Execute one Result-valued Program inside a framework-neutral Web request boundary. */
115
- var WebEffect = class {
116
- constructor() {}
117
- static async handle(runtime, request, program, options) {
118
- const boundaryOptions = options;
119
- const onSuccess = boundaryOptions?.onSuccess ?? defaultSuccess;
120
- const onFailure = boundaryOptions?.onFailure ?? defaultFailure;
121
- const requestLayer = combineRequestLayer(request, boundaryOptions?.requestLayer?.(request));
122
- let response;
123
- let failurePolicyFailed = false;
124
- let failurePolicyCause;
125
- await runtime.runWith(requestLayer, async () => {
126
- const result = await program();
127
- if (Result.isError(result)) {
128
- try {
129
- response = assertResponse(await onFailure(result.error));
130
- } catch (cause) {
131
- failurePolicyFailed = true;
132
- failurePolicyCause = cause;
133
- }
134
- return Result.err(result.error);
135
- }
136
- response = assertResponse(await onSuccess({ value: result.value }));
137
- return Result.ok(response);
138
- }, { signal: request.signal });
139
- if (failurePolicyFailed) throw failurePolicyCause;
140
- if (response === void 0) throw new Error("WebEffect response policy did not produce a Response");
141
- return response;
142
- }
143
- };
144
- //#endregion
145
- export { WebEffectSerializationError as n, assertResponse as r, WebEffect as t };
146
-
147
- //# sourceMappingURL=web-Bq3MfMrj.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"web-Bq3MfMrj.mjs","names":["dataDescriptor"],"sources":["../src/web/responses.ts","../src/web/web-effect.ts"],"sourcesContent":["import type { WebEffectSuccess, WebJsonValue } from './types'\n\n/* oxlint-disable anti-slop/no-object-parameters -- Web Response values are validated structurally at this boundary. */\n/* oxlint-disable anti-slop/no-runtime-typeof -- Web Response and JSON values require runtime protocol validation. */\n/* oxlint-disable anti-slop/no-unknown-parameters -- Web Response and JSON policies accept opaque JavaScript values. */\n/* oxlint-disable anti-slop/no-unknown-returns -- Web Response and JSON policies narrow opaque JavaScript values locally. */\n\nconst DEFAULT_FAILURE_MESSAGE = 'Internal Server Error'\n\ntype BodyCandidate = {\n readonly cancel: unknown\n readonly getReader: unknown\n readonly locked: unknown\n readonly pipeThrough: unknown\n readonly pipeTo: unknown\n readonly tee: unknown\n}\n\ntype ResponseCandidate = {\n readonly body: unknown\n readonly bodyUsed: unknown\n readonly headers: unknown\n readonly ok: unknown\n readonly redirected: unknown\n readonly status: unknown\n readonly statusText: unknown\n readonly type: unknown\n readonly url: unknown\n readonly arrayBuffer: unknown\n readonly blob: unknown\n readonly bytes: unknown\n readonly clone: unknown\n readonly formData: unknown\n readonly json: unknown\n readonly text: unknown\n}\n\n/** An unsupported value encountered by the default Web JSON policy. */\nexport class WebEffectSerializationError extends TypeError {\n constructor(detail: string) {\n super(`WebEffect default success serialization ${detail}`)\n this.name = 'WebEffectSerializationError'\n }\n}\n\nconst isObject = (value: unknown): value is object => typeof value === 'object' && value !== null\n\nconst isCallable = (value: unknown): value is (...arguments_: never[]) => unknown =>\n typeof value === 'function'\n\ntype HeadersCandidate = {\n readonly append: unknown\n readonly delete: unknown\n readonly get: unknown\n readonly getSetCookie: unknown\n readonly has: unknown\n readonly set: unknown\n readonly forEach: unknown\n}\n\nconst isHeaders = (value: unknown): boolean => {\n if (!isObject(value)) {\n return false\n }\n\n // SAFETY: isObject above establishes the runtime object shape before structural field inspection.\n const candidate = value as HeadersCandidate\n\n return (\n isCallable(candidate.append) &&\n isCallable(candidate.delete) &&\n isCallable(candidate.get) &&\n isCallable(candidate.getSetCookie) &&\n isCallable(candidate.has) &&\n isCallable(candidate.set) &&\n isCallable(candidate.forEach)\n )\n}\n\nconst isBody = (value: unknown): boolean => {\n if (value === null) {\n return true\n }\n\n if (!isObject(value)) {\n return false\n }\n\n // SAFETY: isObject above establishes the runtime object shape before structural field inspection.\n const candidate = value as BodyCandidate\n\n return (\n typeof candidate.locked === 'boolean' &&\n isCallable(candidate.cancel) &&\n isCallable(candidate.getReader) &&\n isCallable(candidate.pipeThrough) &&\n isCallable(candidate.pipeTo) &&\n isCallable(candidate.tee)\n )\n}\n\nconst isResponseStatus = (value: unknown): value is number =>\n typeof value === 'number' &&\n Number.isInteger(value) &&\n (value === 0 || (value >= 200 && value <= 599))\n\nconst isResponseType = (value: unknown): value is Response['type'] =>\n value === 'basic' ||\n value === 'cors' ||\n value === 'default' ||\n value === 'error' ||\n value === 'opaque' ||\n value === 'opaqueredirect'\n\n/** Accept native, cross-realm, and standards-compatible Web Response values. */\nconst isWebResponse = (value: unknown): value is Response => {\n if (!isObject(value)) {\n return false\n }\n\n try {\n // SAFETY: isObject above establishes the runtime object shape before structural field inspection.\n const candidate = value as ResponseCandidate\n\n const status = candidate.status\n\n if (!isResponseStatus(status)) {\n return false\n }\n\n return (\n isBody(candidate.body) &&\n typeof candidate.bodyUsed === 'boolean' &&\n isHeaders(candidate.headers) &&\n typeof candidate.ok === 'boolean' &&\n candidate.ok === (status >= 200 && status <= 299) &&\n typeof candidate.redirected === 'boolean' &&\n typeof candidate.statusText === 'string' &&\n isResponseType(candidate.type) &&\n typeof candidate.url === 'string' &&\n isCallable(candidate.arrayBuffer) &&\n isCallable(candidate.blob) &&\n isCallable(candidate.bytes) &&\n isCallable(candidate.clone) &&\n isCallable(candidate.formData) &&\n isCallable(candidate.json) &&\n isCallable(candidate.text)\n )\n } catch {\n return false\n }\n}\n\nconst propertyPath = (path: string, property: string): string => `${path}.${property}`\n\nconst unsupported = (path: string, kind: string): never => {\n throw new WebEffectSerializationError(`cannot encode ${kind} at ${path}`)\n}\n\nconst ownDataProperties = (\n value: object,\n path: string\n): readonly (readonly [string, unknown])[] => {\n const symbols = Object.getOwnPropertySymbols(value)\n\n if (symbols.length > 0) {\n unsupported(path, 'symbol-keyed properties')\n }\n\n return Object.getOwnPropertyNames(value).map((property) => {\n const descriptor = Object.getOwnPropertyDescriptor(value, property)\n\n if (descriptor === undefined || !('value' in descriptor) || descriptor.enumerable !== true) {\n unsupported(propertyPath(path, property), 'non-enumerable or accessor properties')\n }\n\n // SAFETY: the preceding descriptor guard establishes a data descriptor with an enumerable value.\n const dataDescriptor = descriptor as PropertyDescriptor & { readonly value: unknown }\n\n return [property, dataDescriptor.value] as const\n })\n}\n\nconst arrayIndex = (property: string): number | undefined => {\n const index = Number(property)\n\n return Number.isInteger(index) && index >= 0 && index < 2 ** 32 - 1 && String(index) === property\n ? index\n : undefined\n}\n\nconst sanitizeArray = (\n value: readonly unknown[],\n path: string,\n ancestors: Set<object>\n): readonly WebJsonValue[] => {\n const symbols = Object.getOwnPropertySymbols(value)\n\n if (symbols.length > 0) {\n unsupported(path, 'symbol-keyed properties')\n }\n\n const properties = Object.getOwnPropertyNames(value)\n\n if (properties.length !== value.length + 1 || !properties.includes('length')) {\n unsupported(path, 'sparse or augmented arrays')\n }\n\n const output: WebJsonValue[] = []\n\n for (let index = 0; index < value.length; index += 1) {\n const property = String(index)\n const descriptor = Object.getOwnPropertyDescriptor(value, property)\n\n if (\n descriptor === undefined ||\n !('value' in descriptor) ||\n descriptor.enumerable !== true ||\n arrayIndex(property) === undefined\n ) {\n unsupported(propertyPath(path, property), 'sparse or accessor array elements')\n }\n\n // SAFETY: the preceding descriptor guard establishes a data descriptor with an enumerable value.\n const dataDescriptor = descriptor as PropertyDescriptor & { readonly value: unknown }\n\n output.push(sanitizeJsonValue(dataDescriptor.value, propertyPath(path, property), ancestors))\n }\n\n return output\n}\n\nconst sanitizeObject = (\n value: object,\n path: string,\n ancestors: Set<object>\n): { readonly [key: string]: WebJsonValue } => {\n const prototype = Object.getPrototypeOf(value)\n\n if (prototype !== Object.prototype && prototype !== null) {\n unsupported(path, 'non-plain objects')\n }\n\n // SAFETY: Object.create(null) is an empty dictionary that is populated only with sanitized values.\n const output: { [key: string]: WebJsonValue } = Object.create(null) as {\n [key: string]: WebJsonValue\n }\n\n for (const [property, child] of ownDataProperties(value, path)) {\n output[property] = sanitizeJsonValue(child, propertyPath(path, property), ancestors)\n }\n\n return output\n}\n\nconst sanitizeJsonValue = (\n value: unknown,\n path: string,\n ancestors: Set<object> = new Set()\n): WebJsonValue => {\n if (value === null || typeof value === 'boolean' || typeof value === 'string') {\n return value\n }\n\n if (typeof value === 'number') {\n return Number.isFinite(value) ? value : unsupported(path, 'non-finite numbers')\n }\n\n if (typeof value === 'undefined') {\n return unsupported(path, 'undefined values')\n }\n\n if (typeof value === 'bigint' || typeof value === 'function' || typeof value === 'symbol') {\n return unsupported(path, `${typeof value} values`)\n }\n\n if (!isObject(value)) {\n return unsupported(path, 'unsupported values')\n }\n\n if (ancestors.has(value)) {\n return unsupported(path, 'circular values')\n }\n\n ancestors.add(value)\n\n try {\n return Array.isArray(value)\n ? sanitizeArray(value, path, ancestors)\n : sanitizeObject(value, path, ancestors)\n } finally {\n ancestors.delete(value)\n }\n}\n\n/** Convert a successful value using the boundary's constrained JSON policy. */\nexport const defaultSuccess = ({ value }: WebEffectSuccess): Response => {\n if (isWebResponse(value)) {\n return value\n }\n\n if (value === undefined) {\n return new Response(null, { status: 204 })\n }\n\n return Response.json({ data: sanitizeJsonValue(value, '$') })\n}\n\n/** Redact typed failures unless the failure is an intentional Response. */\n// oxlint-disable-next-line anti-slop/no-unknown-parameters -- Typed Result errors are intentionally opaque at this HTTP boundary.\nexport const defaultFailure = (error: unknown): Response => {\n if (isWebResponse(error)) {\n return error\n }\n\n return Response.json({ error: DEFAULT_FAILURE_MESSAGE }, { status: 500 })\n}\n\n/** Validate policy output at the JavaScript boundary before returning it. */\n// oxlint-disable-next-line anti-slop/no-unknown-parameters -- Policy callbacks are opaque JavaScript inputs at this boundary.\nexport const assertResponse = (response: unknown): Response => {\n if (!isWebResponse(response)) {\n throw new TypeError('WebEffect response policies must return a Response')\n }\n\n return response\n}\n","import { Result } from 'better-result'\n\nimport { Layer } from '../layer'\nimport type { LayerInput } from '../layer/inference'\nimport { CurrentRequest } from '../standard-services/current-request'\nimport type { Runtime } from '../runtime'\nimport type { AnyService } from '../service'\nimport type { EffectError, EffectSuccess } from '../effect/types'\nimport { assertResponse, defaultFailure, defaultSuccess } from './responses'\nimport type {\n AnyProgram,\n CompleteWebProgram,\n DefaultRequestLayer,\n WebEffectOptions,\n WebEffectProgram,\n WebProgramChecks,\n WebRequestLayerChecks\n} from './types'\n\nconst combineRequestLayer = <RequestLayer extends LayerInput>(\n request: Request,\n customLayer: RequestLayer | undefined\n): LayerInput => {\n const currentRequestLayer = CurrentRequest.layer(request)\n\n if (customLayer === undefined) {\n return currentRequestLayer\n }\n\n // SAFETY: WebEffect.handle validates the custom Layer's shape and override contract at its public boundary.\n return Layer.override(currentRequestLayer, customLayer as never)\n}\n\n/** Execute one Result-valued Program inside a framework-neutral Web request boundary. */\nexport class WebEffect {\n private constructor() {}\n\n /**\n * Run one lazy Program and map its Result to a standard Web Response.\n *\n * The request Layer and execution Scope are owned by the supplied Runtime;\n * request resources close before this Promise resolves, while Runtime-root\n * resources remain owned by the Runtime.\n */\n static handle<\n Provided extends AnyService,\n const Program extends AnyProgram,\n RequestLayer extends LayerInput,\n Failure = EffectError<Program>\n >(\n runtime: Runtime<Provided>,\n request: Request,\n program: Program,\n options: WebEffectOptions<NoInfer<Failure>, RequestLayer, EffectSuccess<Program>> & {\n readonly requestLayer: (request: Request) => RequestLayer\n } & WebRequestLayerChecks<Provided, RequestLayer> &\n WebProgramChecks<Provided, RequestLayer, Program, NoInfer<Failure>>\n ): Promise<Response>\n\n static handle<\n Provided extends AnyService,\n const Program extends AnyProgram,\n Failure = EffectError<Program>\n >(\n runtime: Runtime<Provided>,\n request: Request,\n program: Program & CompleteWebProgram<Provided, DefaultRequestLayer, Program, NoInfer<Failure>>,\n options: WebEffectOptions<NoInfer<Failure>, DefaultRequestLayer, EffectSuccess<Program>>\n ): Promise<Response>\n\n static handle<Provided extends AnyService, const Program extends AnyProgram>(\n runtime: Runtime<Provided>,\n request: Request,\n program: Program & CompleteWebProgram<Provided, DefaultRequestLayer, Program>,\n options?: undefined\n ): Promise<Response>\n\n static async handle(\n runtime: Runtime<AnyService>,\n request: Request,\n program: AnyProgram,\n options?: WebEffectOptions<unknown, LayerInput, unknown>\n ): Promise<Response> {\n const boundaryOptions = options\n const onSuccess = boundaryOptions?.onSuccess ?? defaultSuccess\n const onFailure = boundaryOptions?.onFailure ?? defaultFailure\n const requestLayer = combineRequestLayer(request, boundaryOptions?.requestLayer?.(request))\n let response: Response | undefined\n let failurePolicyFailed = false\n let failurePolicyCause: unknown\n\n // Return a Result from the execution even after mapping it so Runtime can\n // classify typed failures and give request finalizers the original cause.\n // A policy defect is rethrown after this Result settles so it cannot replace\n // the typed failure supplied to the request Scope.\n // SAFETY: Public overloads validate the request Layer before this erased Runtime boundary.\n await runtime.runWith(\n requestLayer as Layer.Any,\n async () => {\n const result = await program()\n\n if (Result.isError(result)) {\n try {\n response = assertResponse(await onFailure(result.error))\n } catch (cause) {\n failurePolicyFailed = true\n failurePolicyCause = cause\n }\n\n return Result.err(result.error)\n }\n\n response = assertResponse(\n await onSuccess({\n value: result.value\n })\n )\n return Result.ok(response)\n },\n { signal: request.signal }\n )\n\n if (failurePolicyFailed) {\n throw failurePolicyCause\n }\n\n if (response === undefined) {\n throw new Error('WebEffect response policy did not produce a Response')\n }\n\n return response\n }\n}\n\n/** Type-level aliases for the framework-neutral Web boundary. */\nexport declare namespace WebEffect {\n /** Options used by `WebEffect.handle`. */\n export type Options<\n Failure = unknown,\n RequestLayer extends LayerInput = DefaultRequestLayer,\n Success = unknown\n > = WebEffectOptions<Failure, RequestLayer, Success>\n\n /** The success value passed to `onSuccess`. */\n export type Success<A = unknown> = {\n readonly value: A\n }\n\n /** A standard Web response or an asynchronous response. */\n export type ResponseLike = Response | PromiseLike<Response>\n\n /** A lazy Result-valued Program accepted by `handle`. */\n export type Program<A = unknown, E = unknown, R extends AnyService = never> = WebEffectProgram<\n A,\n E,\n R\n >\n\n /** Extract a Program's success channel. */\n export type Value<Program extends WebEffectProgram<any, any, AnyService>> = EffectSuccess<Program>\n\n /** Extract a Program's typed failure channel. */\n export type Failure<Program extends WebEffectProgram<any, any, AnyService>> = EffectError<Program>\n}\n"],"mappings":";;;;AAOA,MAAM,0BAA0B;;AA+BhC,IAAa,8BAAb,cAAiD,UAAU;CACzD,YAAY,QAAgB;EAC1B,MAAM,2CAA2C,QAAQ;EACzD,KAAK,OAAO;CACd;AACF;AAEA,MAAM,YAAY,UAAoC,OAAO,UAAU,YAAY,UAAU;AAE7F,MAAM,cAAc,UAClB,OAAO,UAAU;AAYnB,MAAM,aAAa,UAA4B;CAC7C,IAAI,CAAC,SAAS,KAAK,GACjB,OAAO;CAIT,MAAM,YAAY;CAElB,OACE,WAAW,UAAU,MAAM,KAC3B,WAAW,UAAU,MAAM,KAC3B,WAAW,UAAU,GAAG,KACxB,WAAW,UAAU,YAAY,KACjC,WAAW,UAAU,GAAG,KACxB,WAAW,UAAU,GAAG,KACxB,WAAW,UAAU,OAAO;AAEhC;AAEA,MAAM,UAAU,UAA4B;CAC1C,IAAI,UAAU,MACZ,OAAO;CAGT,IAAI,CAAC,SAAS,KAAK,GACjB,OAAO;CAIT,MAAM,YAAY;CAElB,OACE,OAAO,UAAU,WAAW,aAC5B,WAAW,UAAU,MAAM,KAC3B,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