better-effect 0.12.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +327 -7
- package/dist/adapters/iti.d.mts +3 -3
- package/dist/bun.d.mts +43 -0
- package/dist/bun.d.mts.map +1 -0
- package/dist/bun.mjs +40 -0
- package/dist/bun.mjs.map +1 -0
- package/dist/{context-BUEf1qjL.mjs → context-BphfFUMO.mjs} +4 -2
- package/dist/context-BphfFUMO.mjs.map +1 -0
- package/dist/current-request-CIU7AHhF.d.mts +22 -0
- package/dist/current-request-CIU7AHhF.d.mts.map +1 -0
- package/dist/current-request-DDKNyymv.mjs +20 -0
- package/dist/current-request-DDKNyymv.mjs.map +1 -0
- package/dist/{signal-D2UTcaaG.mjs → disposable-CP-Q2H3l.mjs} +4 -52
- package/dist/disposable-CP-Q2H3l.mjs.map +1 -0
- package/dist/{effect-CK4YZaX0.mjs → effect-CPdV7Yv8.mjs} +2 -2
- package/dist/{effect-CK4YZaX0.mjs.map → effect-CPdV7Yv8.mjs.map} +1 -1
- package/dist/hono.d.mts +7 -5
- package/dist/hono.d.mts.map +1 -1
- package/dist/hono.mjs +88 -30
- package/dist/hono.mjs.map +1 -1
- package/dist/{index-heuaRmXR.d.mts → index-AiKM71-u.d.mts} +3 -1
- package/dist/{index-heuaRmXR.d.mts.map → index-AiKM71-u.d.mts.map} +1 -1
- package/dist/{index-GYJ4qm9K.d.mts → index-BodMy6rO.d.mts} +6 -5
- package/dist/index-BodMy6rO.d.mts.map +1 -0
- package/dist/{index-CX6iAoCB.d.mts → index-CCi07kUw.d.mts} +2 -2
- package/dist/{index-CX6iAoCB.d.mts.map → index-CCi07kUw.d.mts.map} +1 -1
- package/dist/{index-BMdU_Z72.d.mts → index-DAKn0qHk.d.mts} +4 -3
- package/dist/index-DAKn0qHk.d.mts.map +1 -0
- package/dist/{index-B1nH4luq.d.mts → index-cXgyMa0v.d.mts} +6 -20
- package/dist/index-cXgyMa0v.d.mts.map +1 -0
- package/dist/index.d.mts +6 -5
- package/dist/index.mjs +7 -6
- package/dist/index.mjs.map +1 -1
- package/dist/{layer-D56fRdLt.mjs → layer-D16GKxuX.mjs} +4 -4
- package/dist/layer-D16GKxuX.mjs.map +1 -0
- package/dist/next.d.mts +116 -0
- package/dist/next.d.mts.map +1 -0
- package/dist/next.mjs +68 -0
- package/dist/next.mjs.map +1 -0
- package/dist/{node-context-lggRF4bR.mjs → node-context-Ca18oNSg.mjs} +2 -2
- package/dist/{node-context-lggRF4bR.mjs.map → node-context-Ca18oNSg.mjs.map} +1 -1
- package/dist/{node-context-DWsCUBRa.d.mts → node-context-DczjAcrX.d.mts} +2 -2
- package/dist/{node-context-DWsCUBRa.d.mts.map → node-context-DczjAcrX.d.mts.map} +1 -1
- package/dist/node.d.mts +4 -4
- package/dist/node.mjs +4 -4
- package/dist/observer-9nhbL7Pr.d.mts +68 -0
- package/dist/observer-9nhbL7Pr.d.mts.map +1 -0
- package/dist/opentelemetry.d.mts +94 -0
- package/dist/opentelemetry.d.mts.map +1 -0
- package/dist/opentelemetry.mjs +453 -0
- package/dist/opentelemetry.mjs.map +1 -0
- package/dist/{outcome-CB43bnFW.d.mts → outcome-DI8LPIQ4.d.mts} +14 -69
- package/dist/outcome-DI8LPIQ4.d.mts.map +1 -0
- package/dist/{program-metadata-DhQCCirO.mjs → program-metadata-BxjGkT17.mjs} +3 -3
- package/dist/{program-metadata-DhQCCirO.mjs.map → program-metadata-BxjGkT17.mjs.map} +1 -1
- package/dist/runtime/explicit.d.mts +1 -1
- package/dist/runtime/explicit.mjs +1 -1
- package/dist/runtime/node.d.mts +2 -2
- package/dist/runtime/node.mjs +2 -2
- package/dist/{runtime-CBMrX8Wl.mjs → runtime-C_55ofnL.mjs} +42 -27
- package/dist/runtime-C_55ofnL.mjs.map +1 -0
- package/dist/signal-nfgFyNCk.mjs +52 -0
- package/dist/signal-nfgFyNCk.mjs.map +1 -0
- package/dist/{standard-services-GBZ32tll.mjs → standard-services-vnGIafkS.mjs} +3 -17
- package/dist/standard-services-vnGIafkS.mjs.map +1 -0
- package/dist/standard-services.d.mts +3 -2
- package/dist/standard-services.mjs +3 -2
- package/dist/testing.d.mts +6 -5
- package/dist/testing.d.mts.map +1 -1
- package/dist/testing.mjs +6 -6
- package/dist/types-oihI-ESv.d.mts +54 -0
- package/dist/types-oihI-ESv.d.mts.map +1 -0
- package/dist/web-Bq3MfMrj.mjs +147 -0
- package/dist/web-Bq3MfMrj.mjs.map +1 -0
- package/dist/web.d.mts +47 -0
- package/dist/web.d.mts.map +1 -0
- package/dist/web.mjs +2 -0
- package/package.json +33 -2
- package/dist/context-BUEf1qjL.mjs.map +0 -1
- package/dist/index-B1nH4luq.d.mts.map +0 -1
- package/dist/index-BMdU_Z72.d.mts.map +0 -1
- package/dist/index-GYJ4qm9K.d.mts.map +0 -1
- package/dist/layer-D56fRdLt.mjs.map +0 -1
- package/dist/outcome-CB43bnFW.d.mts.map +0 -1
- package/dist/runtime-CBMrX8Wl.mjs.map +0 -1
- package/dist/signal-D2UTcaaG.mjs.map +0 -1
- package/dist/standard-services-GBZ32tll.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"layer-D16GKxuX.mjs","names":["Constructor"],"sources":["../src/service/runtime.ts","../src/service/service.ts","../src/layer/internal.ts","../src/layer/layer.ts"],"sourcesContent":["import { ServiceRuntimeNotConfiguredError } from './errors'\nimport { captureServiceTag } from './tag'\n\nimport { RuntimeContextNotConfiguredError } from '../runtime/errors'\n\nimport {\n currentRuntimeContext,\n getRuntimeContext,\n makeRuntimeContext,\n runRuntimeContext\n} from '../runtime/context'\n\nimport { defaultRuntimeContextStorage } from '../runtime/default'\n\nimport type { AnyServiceToken } from './types'\n\nimport type { RuntimeContextStorage } from '../runtime/context'\n\n/** Resolves class-backed Service tokens for a runtime execution. */\nexport interface ServiceResolver {\n /** Resolve a token to its corresponding Service instance. */\n resolve<T extends AnyServiceToken>(token: T): InstanceType<T> | PromiseLike<InstanceType<T>>\n}\n\n/** Provides the resolver context used by Service tokens during execution. */\nexport class ServiceRuntime {\n /**\n * Run a callback with a resolver available to `yield* Service` expressions.\n *\n * The context is scoped to the callback and is restored afterward.\n *\n * @example\n * ```ts\n * const value = ServiceRuntime.run(resolver, () => {\n * return ServiceRuntime.resolve(Database)\n * })\n * ```\n */\n static run<A>(\n resolver: ServiceResolver,\n program: () => A,\n storage: RuntimeContextStorage = defaultRuntimeContextStorage\n ): A {\n const current = getRuntimeContext(storage)\n const context = makeRuntimeContext(\n resolver,\n current?.scope,\n current?.resolver === resolver ? current.resolutionPath : [],\n current?.signal,\n current?.resolver === resolver ? current : undefined,\n current?.executionId\n )\n\n return runRuntimeContext(storage, context, program)\n }\n\n /** Return the resolver active in the current execution context. */\n static current(): ServiceResolver {\n let context\n\n try {\n context = currentRuntimeContext()\n } catch (cause) {\n if (cause instanceof RuntimeContextNotConfiguredError) {\n throw new ServiceRuntimeNotConfiguredError()\n }\n\n throw cause\n }\n\n if (!context.resolver) {\n throw new ServiceRuntimeNotConfiguredError()\n }\n\n return context.resolver\n }\n\n /** Resolve a Service token using the active resolver. */\n static async resolve<T extends AnyServiceToken>(token: T): Promise<InstanceType<T>> {\n captureServiceTag(token)\n const resolver = ServiceRuntime.current()\n\n return await resolver.resolve(token)\n }\n}\n","import { ServiceRuntime } from './runtime'\nimport { registerServiceTag, validateServiceTag } from './tag'\n\nimport type { ServiceRequirement } from '../effect/types'\n\nimport type {\n AnyService,\n AnyServiceToken,\n ServiceClass,\n ServiceContract,\n ServiceIdentity,\n ServiceIdentityTypeId,\n ServiceInstance,\n ServiceRequirements,\n ServiceTag,\n ServiceToken,\n ServiceTokenOf\n} from './types'\n\ntype ServiceTagLiteral<Tag extends string> = string extends Tag\n ? never\n : Tag extends ''\n ? never\n : Tag\n\ninterface ServiceFactory<Self> {\n <const Tag extends string>(\n tag: ServiceTagLiteral<Tag>\n ): (abstract new () => ServiceIdentity<Tag>) & {\n readonly name: string\n readonly serviceTag: Tag\n } & {\n readonly of: Service.FactoryOf<Self, Tag>\n readonly [Symbol.asyncIterator]: (\n this: ServiceToken<Tag, Self & ServiceIdentity<Tag>>\n ) => AsyncGenerator<ServiceRequirement<Self>, Self, unknown>\n }\n}\n\n/**\n * Declare a class-backed Service with a stable string-literal identity.\n *\n * The returned class is simultaneously the implementation type, the runtime\n * dependency token, and the value yielded by `yield*` in an Effect generator.\n * The explicit self type preserves exact instance inference, while the second\n * call captures the tag as a literal for Layer composition and diagnostics.\n *\n * @example\n * ```ts\n * class Database extends Service<Database>()('Database') {\n * query(): string {\n * return 'ok'\n * }\n * }\n *\n * const database = yield* Database\n * database.query()\n * ```\n *\n * @typeParam Self The instance type implemented by the declared Service.\n */\nexport function Service<Self>(): ServiceFactory<Self> {\n return function <const Tag extends string>(tag: ServiceTagLiteral<Tag>) {\n validateServiceTag(tag)\n\n abstract class BaseService implements ServiceIdentity<Tag> {\n /** The stable logical identity used by Layers and resolver backends. */\n static readonly serviceTag: Tag = tag\n declare readonly [ServiceIdentityTypeId]: Tag\n\n /**\n * Type-check a structural implementation of this Service.\n *\n * This is an identity helper. It returns the supplied value unchanged\n * and does not invoke a constructor or modify its prototype.\n *\n * @example\n * ```ts\n * class Database extends Service<Database>()('Database') {\n * query(sql: string): string {\n * return sql\n * }\n * }\n *\n * const database = Database.of({\n * query: (sql) => `Result: ${sql}`\n * })\n *\n * database.query('SELECT 1')\n * // 'Result: SELECT 1'\n * // database is the original object, not an instance of Database\n * ```\n */\n static of(this: void, implementation: ServiceContract<Self & ServiceIdentity<Tag>>): Self {\n // SAFETY: ServiceContract removes only the phantom marker; this boundary restores Self.\n return implementation as Self\n }\n\n /** Resolve this Service from the resolver active in the current runtime. */\n // oxlint-disable-next-line require-yield\n static async *[Symbol.asyncIterator](\n this: ServiceToken<Tag, Self & ServiceIdentity<Tag>>\n ): AsyncGenerator<ServiceRequirement<Self>, Self, unknown> {\n return await ServiceRuntime.resolve(this)\n }\n }\n\n registerServiceTag(BaseService, tag)\n\n return BaseService\n }\n}\n\n/** Type-level aliases for Service tokens and their instance contracts. */\nexport declare namespace Service {\n /** The widened Service instance constraint. */\n export type Any = AnyService\n\n /** A class-backed Service token with a stable tag and instance contract. */\n export type Token<Tag extends string = string, Instance extends AnyService = any> = ServiceToken<\n Tag,\n Instance\n >\n\n /** A constructible Service class with a stable tag and instance contract. */\n export type Class<\n Tag extends string = string,\n Instance extends AnyService = AnyService\n > = ServiceClass<Tag, Instance>\n\n /** Extract the instance represented by a Service token. */\n export type Instance<T extends AnyServiceToken> = ServiceInstance<T>\n\n /** Extract the stable tag represented by a Service instance. */\n export type Tag<S extends AnyService> = ServiceTag<S>\n\n /** A branded Service instance identity with a stable tag. */\n export type Identity<Tag extends string = string> = ServiceIdentity<Tag>\n\n /** Remove the internal identity marker from a Service implementation contract. */\n export type Contract<S extends AnyService> = ServiceContract<S>\n\n /** Extract the Service token represented by a branded Service instance. */\n export type TokenOf<S extends AnyService> = ServiceTokenOf<S>\n\n /** Declaration bridge for the recursive structural `Service.of` signature. */\n export type FactoryOf<Self, Tag extends string> = (\n this: void,\n implementation: ServiceContract<Self & ServiceIdentity<Tag>>\n ) => Self\n\n /** Extract Effect Service requirements from a Service instance. */\n export type Requirements<S extends AnyService> = ServiceRequirements<S>\n}\n","import { LayerGeneratorYieldError } from './errors'\n\nimport type { ServiceRequirement } from '../effect/types'\nimport type { ServiceClass } from '../service'\n\nimport type { LayerGenerator } from './types'\n\nexport const runLayerGenerator = async <\n S extends ServiceClass<any, any>,\n Yield extends ServiceRequirement<unknown>\n>(\n service: S,\n factory: LayerGenerator<S, Yield>\n): Promise<InstanceType<S>> => {\n const iterator = factory()\n\n const state = await iterator.next()\n\n if (!state.done) {\n try {\n // SAFETY: The iterator is closed only to discard an invalid yield; its return value is ignored.\n await iterator.return(undefined as never)\n } finally {\n // oxlint-disable-next-line no-unsafe-finally\n throw new LayerGeneratorYieldError(service)\n }\n }\n\n // SAFETY: The public generator boundary accepts only the requested Service contract.\n return state.value as InstanceType<S>\n}\n","import type { ServiceRequirement } from '../effect/types'\nimport { ServiceRuntime } from '../service'\nimport { captureServiceTag } from '../service/tag'\nimport type { AnyService, ServiceClass, ServiceContract, ServiceRequirements } from '../service'\nimport { ResourceNotDisposableError } from '../scope'\nimport { getDisposeFinalizer } from '../scope/disposable'\n\nimport type { DisposableResource, ScopeFinalizer, ScopeOutcome } from '../scope'\nimport type { Covariant, Invariant } from '../internal/variance'\nimport type { MaybePromise } from '../utils/types'\n\nimport { DuplicateServiceError, ServiceTagCollisionError } from './errors'\nimport { runLayerGenerator } from './internal'\nimport { captureLayerRegistrationTag } from './registration'\n\nimport type {\n LayerInput,\n CompleteInput,\n LayerResult,\n MergeResult,\n OverrideLayerResult,\n ValidateLayerInput,\n ValidateLayerTuple,\n ValidateOverrides,\n ProvidedEnvironment,\n RequiredEnvironment\n} from './inference'\nimport type { ProviderEntry } from './metadata'\nimport type { LayerGenerator, LayerGeneratorRequirements, LayerRegistration } from './types'\n\ndeclare const LayerTypeId: unique symbol\n\ninterface LayerVariance<in out Provided, out Required> {\n readonly _Provided: Invariant<Provided>\n readonly _Required: Covariant<Required>\n}\n\ntype CapturedLayerAcquisition = {\n readonly instance: unknown\n readonly release: ScopeFinalizer\n}\n\ninterface LayerProvider extends LayerRegistration {\n /** The tag captured before this provider can cross an asynchronous boundary. */\n readonly serviceTag: string\n\n /** Provider storage deliberately erases the concrete instance type. */\n // oxlint-disable-next-line anti-slop/no-unknown-parameters\n readonly release?: (instance: unknown, outcome: ScopeOutcome) => MaybePromise<void>\n\n /** Capture acquisition-local cleanup without retaining the acquired instance. */\n readonly acquireWithRelease?: () => MaybePromise<CapturedLayerAcquisition>\n}\n\n/** A Service class whose constructor can be called without arguments. */\ntype DefaultConstructibleServiceClass<\n Tag extends string = string,\n Instance extends AnyService = AnyService\n> = ServiceClass<Tag, Instance> & (new () => Instance)\n\ntype IsUnion<Type, Candidate = Type> = Type extends unknown\n ? [Candidate] extends [Type]\n ? false\n : true\n : never\n\ntype InvalidUnionAliasToken = {\n readonly __betterEffectUnionLayerAliasToken: unique symbol\n}\n\ntype RejectUnionAliasToken<Token> = IsUnion<Token> extends true ? InvalidUnionAliasToken : unknown\n\ntype LayerAliasOptions<From extends ServiceClass<any, any>, To extends ServiceClass<any, any>> = {\n readonly from: From\n readonly to: To\n} & RejectUnionAliasToken<From> &\n RejectUnionAliasToken<To> &\n ([ServiceContract<InstanceType<From>>] extends [ServiceContract<InstanceType<To>>]\n ? unknown\n : {\n readonly __betterEffectIncompatibleLayerAlias: unique symbol\n })\n\n/**\n * Declarative collection of Service providers.\n *\n * A Layer describes how to acquire implementations; it does not execute\n * providers until a `Runtime` is created. Use `merge` to compose distinct\n * providers and `override` when replacing an existing provider intentionally.\n *\n * @example\n * ```ts\n * const AppLive = Layer.merge(\n * Layer.succeed(Database, database),\n * Layer.make(UserRepository)\n * )\n *\n * const runtime = await Runtime.make(AppLive, backend)\n * ```\n */\nexport class Layer<\n in out Provided extends AnyService = AnyService,\n out Required extends AnyService = AnyService\n> {\n declare readonly [LayerTypeId]: LayerVariance<Provided, Required>\n\n /** The provider registrations retained by this Layer. */\n readonly providers: readonly LayerProvider[]\n\n private constructor(providers: readonly LayerProvider[]) {\n this.providers = Object.freeze(\n providers.map((provider) =>\n Object.freeze({\n ...provider,\n serviceTag: captureLayerRegistrationTag(provider)\n })\n )\n )\n }\n\n /** A stable provider-free Layer for composition roots with no Services. */\n static readonly empty: Layer<never, never> = Object.freeze(new Layer<never, never>([]))\n\n /** Create a Layer that lazily acquires a Service instance. */\n static make<S extends DefaultConstructibleServiceClass<any, any>>(\n service: S\n ): LayerResult<ProviderEntry<InstanceType<S>, ServiceRequirements<InstanceType<S>>>>\n\n static make<S extends ServiceClass<any, any>>(\n service: S,\n acquire: () => MaybePromise<ServiceContract<InstanceType<S>>>\n ): LayerResult<ProviderEntry<InstanceType<S>, ServiceRequirements<InstanceType<S>>>>\n\n static make<S extends ServiceClass<any, any>>(\n service: S,\n acquire?: () => MaybePromise<ServiceContract<InstanceType<S>>>\n ): LayerResult<ProviderEntry<InstanceType<S>, ServiceRequirements<InstanceType<S>>>> {\n const serviceTag = captureServiceTag(service)\n const defaultAcquire = (): InstanceType<S> => {\n // SAFETY: The no-argument overload constrains `service` to a default constructible class.\n const Constructor = service as new () => InstanceType<S>\n\n return new Constructor()\n }\n\n const normalizedAcquire = normalizeAcquire<S>(acquire ?? defaultAcquire)\n\n // SAFETY: Runtime storage erases only the concrete provider metadata; the public constructor result restores its typed provenance.\n return new Layer([\n {\n service,\n serviceTag,\n acquire: normalizedAcquire\n }\n ]) as LayerResult<ProviderEntry<InstanceType<S>, ServiceRequirements<InstanceType<S>>>>\n }\n\n /** Create a Layer from an already-constructed Service instance. */\n static succeed<S extends ServiceClass<any, any>>(\n service: S,\n instance: ServiceContract<InstanceType<S>>\n ): LayerResult<ProviderEntry<InstanceType<S>, ServiceRequirements<InstanceType<S>>>> {\n const serviceTag = captureServiceTag(service)\n const normalizedAcquire = normalizeAcquire<S>(() => instance)\n\n // SAFETY: The structural instance has been checked against the requested Service contract.\n return new Layer([\n {\n service,\n serviceTag,\n acquire: normalizedAcquire\n }\n ]) as LayerResult<ProviderEntry<InstanceType<S>, ServiceRequirements<InstanceType<S>>>>\n }\n\n /** Alias a source Service under a compatible target contract. */\n static alias<From extends ServiceClass<any, any>, To extends ServiceClass<any, any>>(\n options: LayerAliasOptions<From, To>\n ): LayerResult<\n ProviderEntry<InstanceType<To>, InstanceType<From> | ServiceRequirements<InstanceType<To>>>\n > {\n const { from, to } = options\n void captureServiceTag(from)\n\n // Keep alias acquisition in the normal Layer generator path so Runtime supplies the active resolver and resolution diagnostics.\n // oxlint-disable-next-line require-yield\n const alias = Layer.gen(to, async function* () {\n const source = await ServiceRuntime.resolve(from)\n\n // SAFETY: LayerAliasOptions checks that the source implementation satisfies the target contract.\n return source as ServiceContract<InstanceType<To>>\n })\n\n // SAFETY: The alias factory resolves the declared source token before returning the target contract.\n return alias as LayerResult<\n ProviderEntry<InstanceType<To>, InstanceType<From> | ServiceRequirements<InstanceType<To>>>\n >\n }\n\n /** Define a provider with Runtime-root cleanup. */\n static scoped<S extends ServiceClass<any, any>>(\n service: S,\n acquire: () => MaybePromise<ServiceContract<InstanceType<S>>>,\n release: (instance: InstanceType<S>, outcome: ScopeOutcome) => MaybePromise<void>\n ): LayerResult<ProviderEntry<InstanceType<S>, ServiceRequirements<InstanceType<S>>>> {\n const serviceTag = captureServiceTag(service)\n\n // SAFETY: The public callbacks constrain acquisition and release to the requested Service.\n return new Layer([\n {\n service,\n serviceTag,\n acquire: normalizeAcquire<S>(acquire),\n release: (instance, outcome) => {\n // SAFETY: The backend invokes release with the instance acquired for this token.\n return release(instance as InstanceType<S>, outcome)\n }\n }\n ]) as LayerResult<ProviderEntry<InstanceType<S>, ServiceRequirements<InstanceType<S>>>>\n }\n\n /** Define a provider with Runtime-root cleanup through its disposal protocol. */\n static scopedDisposable<S extends ServiceClass<any, any>>(\n service: S,\n acquire: () => MaybePromise<ServiceContract<InstanceType<S>> & DisposableResource>\n ): LayerResult<ProviderEntry<InstanceType<S>, ServiceRequirements<InstanceType<S>>>> {\n const acquireWithRelease = async (): Promise<CapturedLayerAcquisition> => {\n const instance = await acquire()\n const finalizer = getDisposeFinalizer(instance)\n\n if (!finalizer) {\n throw new ResourceNotDisposableError()\n }\n\n return { instance, release: finalizer }\n }\n\n const serviceTag = captureServiceTag(service)\n\n // SAFETY: The public callback constrains the acquired value and this runtime-only carrier is erased at the Layer boundary.\n return new Layer([\n {\n service,\n serviceTag,\n acquire: async () => (await acquireWithRelease()).instance,\n acquireWithRelease\n }\n ]) as LayerResult<ProviderEntry<InstanceType<S>, ServiceRequirements<InstanceType<S>>>>\n }\n\n /** Define a provider whose acquisition can yield contextual Services. */\n static scopedGen<S extends ServiceClass<any, any>, Yield extends ServiceRequirement<unknown>>(\n service: S,\n factory: LayerGenerator<S, Yield>,\n release: (instance: InstanceType<S>, outcome: ScopeOutcome) => MaybePromise<void>\n ): LayerResult<ProviderEntry<InstanceType<S>, LayerGeneratorRequirements<S, Yield>>> {\n const serviceTag = captureServiceTag(service)\n\n // SAFETY: The generator and release callback are checked against the requested Service.\n return new Layer([\n {\n service,\n serviceTag,\n acquire: () => runLayerGenerator(service, factory),\n release: (instance, outcome) => {\n // SAFETY: The backend invokes release with the instance acquired for this token.\n return release(instance as InstanceType<S>, outcome)\n }\n }\n ]) as LayerResult<ProviderEntry<InstanceType<S>, LayerGeneratorRequirements<S, Yield>>>\n }\n\n /** Define a provider whose acquisition can yield contextual Services. */\n static gen<S extends ServiceClass<any, any>, Yield extends ServiceRequirement<unknown>>(\n service: S,\n factory: LayerGenerator<S, Yield>\n ): LayerResult<ProviderEntry<InstanceType<S>, LayerGeneratorRequirements<S, Yield>>> {\n const serviceTag = captureServiceTag(service)\n\n // SAFETY: The generator result is normalized to the requested Service at the runtime boundary.\n return new Layer([\n {\n service,\n serviceTag,\n acquire: () => runLayerGenerator(service, factory)\n }\n ]) as LayerResult<ProviderEntry<InstanceType<S>, LayerGeneratorRequirements<S, Yield>>>\n }\n\n /** Compose Layers without replacing providers. */\n static merge<const Layers extends readonly LayerInput[]>(\n ...layers: Layers & ValidateLayerTuple<Layers>\n ): MergeResult<Layers> {\n const providers = new Map<string, LayerProvider>()\n\n for (const layer of layers) {\n for (const provider of layer.providers) {\n const service = provider.service\n const serviceTag = captureLayerRegistrationTag(provider)\n const existing = providers.get(serviceTag)\n\n if (existing) {\n if (existing.service !== service) {\n throw new ServiceTagCollisionError(existing.service, service)\n }\n\n throw new DuplicateServiceError(service)\n }\n\n providers.set(serviceTag, provider)\n }\n }\n\n // SAFETY: The heterogeneous provider list is erased only at this internal storage boundary.\n return new Layer([...providers.values()]) as MergeResult<Layers>\n }\n\n /** Mark a Layer composition root as complete without changing its runtime value. */\n static complete<L extends LayerInput>(layer: L & CompleteInput<L>): L {\n return layer\n }\n\n /** Replace providers in a base Layer, using tag identity and compatible contracts. */\n static override<Base extends LayerInput>(\n base: Base & ValidateLayerInput<Base>\n ): OverrideLayerResult<Base, readonly []>\n\n static override<\n Base extends LayerInput,\n const Overrides extends readonly [LayerInput, ...LayerInput[]]\n >(\n base: Base & ValidateLayerInput<Base>,\n ...overrides: Overrides & ValidateOverrides<Base, Overrides>\n ): OverrideLayerResult<Base, Overrides>\n\n static override<Base extends LayerInput, const Overrides extends readonly LayerInput[]>(\n base: Base & ValidateLayerInput<Base>,\n ...overrides: Overrides & ValidateOverrides<Base, Overrides>\n ): OverrideLayerResult<Base, Overrides>\n\n static override(base: LayerInput, ...overrides: readonly LayerInput[]): Layer<any, any> {\n const providers = new Map<string, LayerProvider>()\n\n for (const provider of base.providers) {\n providers.set(captureLayerRegistrationTag(provider), provider)\n }\n\n for (const layer of overrides) {\n for (const provider of layer.providers) {\n providers.set(captureLayerRegistrationTag(provider), provider)\n }\n }\n\n // SAFETY: Runtime provider replacement preserves the computed override metadata.\n return new Layer([...providers.values()]) as Layer<any, any>\n }\n}\n\n// TypeScript's `readonly` does not affect the runtime property descriptor. Keep\n// the class field's enumerable behavior while locking the singleton binding.\nObject.defineProperty(Layer, 'empty', {\n value: Layer.empty,\n writable: false,\n enumerable: true,\n configurable: false\n})\n\nconst normalizeAcquire =\n <S extends ServiceClass<any, any>>(\n acquire: () => MaybePromise<ServiceContract<InstanceType<S>>>\n ): (() => MaybePromise<InstanceType<S>>) =>\n () => {\n // SAFETY: ServiceContract removes only the declaration-only identity; runtime values are unchanged.\n return acquire() as MaybePromise<InstanceType<S>>\n }\n\n/** Type-level aliases for inspecting Layer environments and completeness. */\nexport declare namespace Layer {\n /** The widened Layer shape accepted by generic Layer infrastructure. */\n export type Any = LayerInput\n\n /** Extract the branded Service instances provided by a Layer. */\n export type Provided<L extends LayerInput> = ProvidedEnvironment<L>\n\n /** Extract the external Service requirements of a Layer. */\n export type Required<L extends LayerInput> = RequiredEnvironment<L>\n\n /** Extract the Services still missing from a Layer composition. */\n export type Missing<L extends LayerInput> = RequiredEnvironment<L>\n\n /** Validate a Layer's requirements and input shape. */\n export type Complete<L extends LayerInput> = CompleteInput<L>\n}\n"],"mappings":"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"}
|
package/dist/next.d.mts
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { A as ProgramFromGenerator, C as EffectError, D as EffectYield, E as EffectSuccess, M as AnyService, k as Program } from "./index-AiKM71-u.mjs";
|
|
2
|
+
import { j as MissingDependencies, v as ExecutionMissing, w as ProvidedEnvironment, y as LayerInput } from "./outcome-DI8LPIQ4.mjs";
|
|
3
|
+
import { l as Runtime } from "./index-BodMy6rO.mjs";
|
|
4
|
+
import { t as CurrentRequest } from "./current-request-CIU7AHhF.mjs";
|
|
5
|
+
import { c as WebJsonValue, u as WebRequestLayerChecks } from "./types-oihI-ESv.mjs";
|
|
6
|
+
import { Result } from "better-result";
|
|
7
|
+
//#region src/next/types.d.ts
|
|
8
|
+
/** Route parameters exposed by Next.js App Router contexts. */
|
|
9
|
+
type NextEffectParams = {
|
|
10
|
+
readonly [key: string]: string | readonly string[] | undefined;
|
|
11
|
+
};
|
|
12
|
+
/** The explicit context passed to an App Router Route Handler factory. */
|
|
13
|
+
type NextEffectContext<Params extends object = NextEffectParams> = {
|
|
14
|
+
readonly params: Promise<Params>;
|
|
15
|
+
};
|
|
16
|
+
/** A native Route Handler function returned by this adapter. */
|
|
17
|
+
type NextRouteHandler<Context extends object = NextEffectContext> = (request: Request, context: Context) => Promise<Response>;
|
|
18
|
+
/** A native Web Response returned synchronously or asynchronously by a policy. */
|
|
19
|
+
type ResponseLike = Response | PromiseLike<Response>;
|
|
20
|
+
/** The value passed to a Next success policy. */
|
|
21
|
+
type NextEffectSuccess<A = unknown> = {
|
|
22
|
+
readonly value: A;
|
|
23
|
+
};
|
|
24
|
+
/** A lazy Result-valued Program accepted by the Next boundary. */
|
|
25
|
+
type NextEffectProgram<A = unknown, E = unknown, R extends AnyService = never> = Program<A, E, R>;
|
|
26
|
+
/** @internal */
|
|
27
|
+
type AnyProgram = NextEffectProgram<any, any, AnyService>;
|
|
28
|
+
/** @internal */
|
|
29
|
+
type AnyResult = Result<any, any>;
|
|
30
|
+
/** The request Layer installed when no custom Layer is supplied. */
|
|
31
|
+
type DefaultRequestLayer = ReturnType<typeof CurrentRequest.layer>;
|
|
32
|
+
/** Services available to a route Program after its request Layer is installed. */
|
|
33
|
+
type AvailableServices<Provided extends AnyService, RequestLayer extends LayerInput> = Provided | InstanceType<typeof CurrentRequest> | ProvidedEnvironment<RequestLayer>;
|
|
34
|
+
/** Validate a request Layer against a Runtime and the built-in CurrentRequest provider. */
|
|
35
|
+
type NextRequestLayerChecks<Provided extends AnyService, RequestLayer extends LayerInput> = WebRequestLayerChecks<Provided, RequestLayer>;
|
|
36
|
+
type InvalidFailure<Actual, Expected> = {
|
|
37
|
+
readonly __betterEffectInvalidNextFailure: {
|
|
38
|
+
readonly actual: Actual;
|
|
39
|
+
readonly expected: Expected;
|
|
40
|
+
};
|
|
41
|
+
};
|
|
42
|
+
type FailureCheck<Failure, Actual> = [Actual] extends [Failure] ? unknown : InvalidFailure<Actual, Failure>;
|
|
43
|
+
/** Services and failures checked for one route Program. */
|
|
44
|
+
type NextProgramChecks<Provided extends AnyService, RequestLayer extends LayerInput, Program extends AnyProgram, Failure = unknown> = (ExecutionMissing<AvailableServices<Provided, RequestLayer>, Program> extends never ? unknown : MissingDependencies<ExecutionMissing<AvailableServices<Provided, RequestLayer>, Program>>) & FailureCheck<Failure, EffectError<Program>>;
|
|
45
|
+
/** A route Program after its Service and Failure channels have been checked. */
|
|
46
|
+
type CompleteNextProgram<Provided extends AnyService, RequestLayer extends LayerInput, Program extends AnyProgram, Failure = unknown> = Program & NextProgramChecks<Provided, RequestLayer, Program, Failure>;
|
|
47
|
+
/** Convert a route Program factory into a checked factory at the public boundary. */
|
|
48
|
+
type NextHandlerFactory<Context extends object, Provided extends AnyService, RequestLayer extends LayerInput, Failure, ProgramFactory extends (request: Request, context: Context) => AnyProgram> = ProgramFactory & ([ReturnType<ProgramFactory>] extends [CompleteNextProgram<Provided, RequestLayer, ReturnType<ProgramFactory>, Failure>] ? unknown : (request: Request, context: Context) => CompleteNextProgram<Provided, RequestLayer, ReturnType<ProgramFactory>, Failure>);
|
|
49
|
+
/** A generator body used by `NextEffect.gen`. */
|
|
50
|
+
type GeneratorBody<Context extends object, Yield extends EffectYield, Returned extends AnyResult> = (request: Request, context: Context) => Generator<Yield, Returned, unknown> | AsyncGenerator<Yield, Returned, unknown>;
|
|
51
|
+
/** Options shared by every Route Handler created by a NextEffect instance. */
|
|
52
|
+
type NextEffectOptions<Failure = unknown, RequestLayer extends LayerInput = ReturnType<typeof CurrentRequest.layer>, Context extends object = NextEffectContext> = {
|
|
53
|
+
/** Build a request-local Layer once for each native Request. */
|
|
54
|
+
readonly requestLayer?: (request: Request, context: Context) => RequestLayer;
|
|
55
|
+
/** Convert a successful value to a native Response. */
|
|
56
|
+
readonly onSuccess?: (result: NextEffectSuccess<unknown>, request: Request, context: Context) => ResponseLike;
|
|
57
|
+
/** Convert a typed Program failure to a native Response. */
|
|
58
|
+
readonly onFailure?: (error: Failure, request: Request, context: Context) => ResponseLike;
|
|
59
|
+
};
|
|
60
|
+
/** Options for one typed route success policy. */
|
|
61
|
+
type NextEffectRouteSuccessPolicy<A, Context extends object> = {
|
|
62
|
+
/** Handle the success value directly and return a native Response. */
|
|
63
|
+
readonly respond: (value: A, request: Request, context: Context) => ResponseLike;
|
|
64
|
+
readonly serialize?: never;
|
|
65
|
+
readonly onSuccess?: never;
|
|
66
|
+
} | {
|
|
67
|
+
readonly respond?: never;
|
|
68
|
+
/** Convert the success value to the JSON-safe body wrapped by WebEffect. */
|
|
69
|
+
readonly serialize: (value: A, request: Request, context: Context) => WebJsonValue;
|
|
70
|
+
readonly onSuccess?: never;
|
|
71
|
+
} | {
|
|
72
|
+
readonly respond?: never;
|
|
73
|
+
readonly serialize?: never;
|
|
74
|
+
/** Replace the shared success policy for this route. */
|
|
75
|
+
readonly onSuccess: (result: NextEffectSuccess<A>, request: Request, context: Context) => ResponseLike;
|
|
76
|
+
} | {
|
|
77
|
+
/** Use the shared or default success policy for this route. */
|
|
78
|
+
readonly respond?: never;
|
|
79
|
+
readonly serialize?: never;
|
|
80
|
+
readonly onSuccess?: never;
|
|
81
|
+
};
|
|
82
|
+
type NextEffectRouteOptions<A, Context extends object = NextEffectContext> = NextEffectRouteSuccessPolicy<A, Context>;
|
|
83
|
+
/** Service and Failure checks for a generator-created route Program. */
|
|
84
|
+
type NextGeneratorChecks<Provided extends AnyService, RequestLayer extends LayerInput, Yield extends EffectYield, Returned extends AnyResult, Failure = unknown> = NextProgramChecks<Provided, RequestLayer, ProgramFromGenerator<Yield, Returned>, Failure>;
|
|
85
|
+
//#endregion
|
|
86
|
+
//#region src/next/next-effect.d.ts
|
|
87
|
+
/** Run Result-valued Programs inside one Runtime boundary per Next request. */
|
|
88
|
+
declare class NextEffect<Provided extends AnyService = AnyService, Failure = unknown, RequestLayer extends LayerInput = DefaultRequestLayer, Context extends object = NextEffectContext> {
|
|
89
|
+
readonly runtime: Runtime<Provided>;
|
|
90
|
+
private readonly onSuccess;
|
|
91
|
+
private readonly onFailure;
|
|
92
|
+
private readonly requestLayer;
|
|
93
|
+
private constructor();
|
|
94
|
+
/** Bind an application-owned Runtime to App Router Route Handler factories. */
|
|
95
|
+
static make<Provided extends AnyService, Failure = unknown, RequestLayer extends LayerInput = DefaultRequestLayer, Context extends object = NextEffectContext>(runtime: Runtime<Provided>, options?: NextEffectOptions<Failure, RequestLayer, Context> & NextRequestLayerChecks<Provided, RequestLayer>): NextEffect<Provided, Failure, RequestLayer, Context>;
|
|
96
|
+
/** Create a native Route Handler from an explicit Request/context Program factory. */
|
|
97
|
+
handler<Program extends AnyProgram>(makeProgram: (request: Request, context: Context) => CompleteNextProgram<Provided, RequestLayer, Program, Failure>, options?: NextEffectRouteOptions<EffectSuccess<Program>, Context>): NextRouteHandler<Context>;
|
|
98
|
+
handler<const HandlerContext extends object, const ProgramFactory extends (request: Request, context: HandlerContext) => AnyProgram>(makeProgram: NextHandlerFactory<HandlerContext, Provided, RequestLayer, Failure, ProgramFactory>, options?: NextEffectRouteOptions<EffectSuccess<ReturnType<ProgramFactory>>, HandlerContext>): NextRouteHandler<HandlerContext>;
|
|
99
|
+
/** Create a native Route Handler from a Request/context generator body. */
|
|
100
|
+
gen<const HandlerContext extends object = Context, const Yield extends EffectYield = EffectYield, const Returned extends AnyResult = AnyResult>(body: GeneratorBody<HandlerContext, Yield, Returned> & NextGeneratorChecks<Provided, RequestLayer, Yield, Returned, Failure>, options?: NextEffectRouteOptions<EffectSuccess<ProgramFromGenerator<Yield, Returned>>, HandlerContext>): NextRouteHandler<HandlerContext>;
|
|
101
|
+
gen<const CustomContext extends object, const CustomYield extends EffectYield, const CustomReturned extends AnyResult>(body: GeneratorBody<CustomContext, CustomYield, CustomReturned> & NextGeneratorChecks<Provided, RequestLayer, CustomYield, CustomReturned, Failure>, options?: NextEffectRouteOptions<EffectSuccess<ProgramFromGenerator<CustomYield, CustomReturned>>, CustomContext>): NextRouteHandler<CustomContext>;
|
|
102
|
+
private makeHandler;
|
|
103
|
+
}
|
|
104
|
+
declare namespace NextEffect {
|
|
105
|
+
/** Options shared by all handlers created from a bound Runtime. */
|
|
106
|
+
type Options<Failure = unknown, RequestLayer extends LayerInput = DefaultRequestLayer, Context extends object = NextEffectContext> = NextEffectOptions<Failure, RequestLayer, Context>;
|
|
107
|
+
/** A typed per-route success policy. */
|
|
108
|
+
type RouteOptions<A, Context extends object = NextEffectContext> = NextEffectRouteOptions<A, Context>;
|
|
109
|
+
/** The explicit App Router context passed to route factories. */
|
|
110
|
+
type Context<Params extends object = NextEffectParams> = NextEffectContext<Params>;
|
|
111
|
+
/** The native handler returned by `handler` and `gen`. */
|
|
112
|
+
type Handler<Context extends object = NextEffectContext> = NextRouteHandler<Context>;
|
|
113
|
+
}
|
|
114
|
+
//#endregion
|
|
115
|
+
export { NextEffect, type NextEffectContext, type NextEffectOptions, type NextEffectParams, type NextEffectProgram, type NextEffectRouteOptions, type NextEffectSuccess, type NextRouteHandler, type ResponseLike };
|
|
116
|
+
//# sourceMappingURL=next.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"next.d.mts","names":[],"sources":["../src/next/types.ts","../src/next/next-effect.ts"],"mappings":"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"}
|
package/dist/next.mjs
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { t as Effect } from "./effect-CPdV7Yv8.mjs";
|
|
2
|
+
import { t as WebEffect } from "./web-Bq3MfMrj.mjs";
|
|
3
|
+
import { Result } from "better-result";
|
|
4
|
+
//#region src/next/next-effect.ts
|
|
5
|
+
const routeSuccessPolicyNames = [
|
|
6
|
+
"respond",
|
|
7
|
+
"serialize",
|
|
8
|
+
"onSuccess"
|
|
9
|
+
];
|
|
10
|
+
const assertExclusiveRouteSuccessPolicy = (options) => {
|
|
11
|
+
const configuredPolicies = routeSuccessPolicyNames.filter((name) => options[name] !== void 0);
|
|
12
|
+
if (configuredPolicies.length > 1) throw new TypeError(`NextEffect route options must configure at most one success policy; received ${configuredPolicies.join(", ")}`);
|
|
13
|
+
};
|
|
14
|
+
/** Run Result-valued Programs inside one Runtime boundary per Next request. */
|
|
15
|
+
var NextEffect = class NextEffect {
|
|
16
|
+
runtime;
|
|
17
|
+
onSuccess;
|
|
18
|
+
onFailure;
|
|
19
|
+
requestLayer;
|
|
20
|
+
constructor(runtime, options) {
|
|
21
|
+
this.runtime = runtime;
|
|
22
|
+
this.onSuccess = options.onSuccess;
|
|
23
|
+
this.onFailure = options.onFailure;
|
|
24
|
+
this.requestLayer = options.requestLayer;
|
|
25
|
+
}
|
|
26
|
+
/** Bind an application-owned Runtime to App Router Route Handler factories. */
|
|
27
|
+
static make(runtime, options) {
|
|
28
|
+
return new NextEffect(runtime, options ?? {});
|
|
29
|
+
}
|
|
30
|
+
handler(...args) {
|
|
31
|
+
const makeProgram = args[0];
|
|
32
|
+
const options = args[1] ?? {};
|
|
33
|
+
return this.makeHandler(makeProgram, options);
|
|
34
|
+
}
|
|
35
|
+
gen(...args) {
|
|
36
|
+
const body = args[0];
|
|
37
|
+
const options = args[1] ?? {};
|
|
38
|
+
return this.makeHandler((request, context) => {
|
|
39
|
+
return Effect.fn(() => body(request, context));
|
|
40
|
+
}, options);
|
|
41
|
+
}
|
|
42
|
+
makeHandler(makeProgram, routeOptions) {
|
|
43
|
+
assertExclusiveRouteSuccessPolicy(routeOptions);
|
|
44
|
+
return async (request, context) => {
|
|
45
|
+
const program = makeProgram(request, context);
|
|
46
|
+
const effectiveProgram = routeOptions.serialize !== void 0 ? async () => {
|
|
47
|
+
const result = await program();
|
|
48
|
+
if (Result.isError(result)) return result;
|
|
49
|
+
return Result.ok(routeOptions.serialize(result.value, request, context));
|
|
50
|
+
} : program;
|
|
51
|
+
const webOptions = {};
|
|
52
|
+
if (this.requestLayer !== void 0) webOptions.requestLayer = () => this.requestLayer(request, context);
|
|
53
|
+
if (routeOptions.respond !== void 0) webOptions.onSuccess = ({ value }) => routeOptions.respond(value, request, context);
|
|
54
|
+
else if (routeOptions.onSuccess !== void 0) webOptions.onSuccess = (result) => routeOptions.onSuccess(result, request, context);
|
|
55
|
+
else if (this.onSuccess !== void 0) webOptions.onSuccess = (result) => {
|
|
56
|
+
return this.onSuccess(result, request, context);
|
|
57
|
+
};
|
|
58
|
+
if (this.onFailure !== void 0) webOptions.onFailure = (error) => {
|
|
59
|
+
return this.onFailure(error, request, context);
|
|
60
|
+
};
|
|
61
|
+
return await WebEffect.handle(this.runtime, request, effectiveProgram, webOptions);
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
//#endregion
|
|
66
|
+
export { NextEffect };
|
|
67
|
+
|
|
68
|
+
//# sourceMappingURL=next.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"next.mjs","names":[],"sources":["../src/next/next-effect.ts"],"sourcesContent":["/* oxlint-disable anti-slop/no-object-parameters -- the private boundary erases arbitrary framework context types after public overload validation. */\n/* oxlint-disable anti-slop/no-unknown-parameters -- response policy values are opaque until WebEffect validates them. */\n/* oxlint-disable anti-slop/no-unsafe-dictionary-type -- the private WebEffect options object is populated only by checked policies. */\n\nimport { Result } from 'better-result'\n\nimport { Effect } from '../effect'\nimport type { EffectSuccess, EffectYield, ProgramFromGenerator } from '../effect/types'\nimport type { LayerInput } from '../layer/inference'\nimport type { Runtime } from '../runtime'\nimport type { AnyService } from '../service'\nimport { WebEffect } from '../web'\nimport type {\n AnyProgram,\n AnyResult,\n DefaultRequestLayer,\n GeneratorBody,\n NextEffectContext,\n NextEffectOptions,\n NextEffectParams,\n NextEffectRouteOptions,\n NextGeneratorChecks,\n CompleteNextProgram,\n NextHandlerFactory,\n NextRequestLayerChecks,\n NextRouteHandler\n} from './types'\n\nconst routeSuccessPolicyNames = ['respond', 'serialize', 'onSuccess'] as const\n\nconst assertExclusiveRouteSuccessPolicy = (\n options: NextEffectRouteOptions<unknown, object>\n): void => {\n const configuredPolicies = routeSuccessPolicyNames.filter((name) => options[name] !== undefined)\n\n if (configuredPolicies.length > 1) {\n throw new TypeError(\n `NextEffect route options must configure at most one success policy; received ${configuredPolicies.join(', ')}`\n )\n }\n}\n\n/** Run Result-valued Programs inside one Runtime boundary per Next request. */\nexport class NextEffect<\n Provided extends AnyService = AnyService,\n Failure = unknown,\n RequestLayer extends LayerInput = DefaultRequestLayer,\n Context extends object = NextEffectContext\n> {\n readonly runtime: Runtime<Provided>\n\n private readonly onSuccess: NextEffectOptions<Failure, RequestLayer, Context>['onSuccess']\n\n private readonly onFailure: NextEffectOptions<Failure, RequestLayer, Context>['onFailure']\n\n private readonly requestLayer: NextEffectOptions<Failure, RequestLayer, Context>['requestLayer']\n\n private constructor(\n runtime: Runtime<Provided>,\n options: NextEffectOptions<Failure, RequestLayer, Context>\n ) {\n this.runtime = runtime\n this.onSuccess = options.onSuccess\n this.onFailure = options.onFailure\n this.requestLayer = options.requestLayer\n }\n\n /** Bind an application-owned Runtime to App Router Route Handler factories. */\n static make<\n Provided extends AnyService,\n Failure = unknown,\n RequestLayer extends LayerInput = DefaultRequestLayer,\n Context extends object = NextEffectContext\n >(\n runtime: Runtime<Provided>,\n options?: NextEffectOptions<Failure, RequestLayer, Context> &\n NextRequestLayerChecks<Provided, RequestLayer>\n ): NextEffect<Provided, Failure, RequestLayer, Context> {\n return new NextEffect(runtime, options ?? {})\n }\n\n /** Create a native Route Handler from an explicit Request/context Program factory. */\n handler<Program extends AnyProgram>(\n makeProgram: (\n request: Request,\n context: Context\n ) => CompleteNextProgram<Provided, RequestLayer, Program, Failure>,\n options?: NextEffectRouteOptions<EffectSuccess<Program>, Context>\n ): NextRouteHandler<Context>\n handler<\n const HandlerContext extends object,\n const ProgramFactory extends (request: Request, context: HandlerContext) => AnyProgram\n >(\n makeProgram: NextHandlerFactory<\n HandlerContext,\n Provided,\n RequestLayer,\n Failure,\n ProgramFactory\n >,\n options?: NextEffectRouteOptions<EffectSuccess<ReturnType<ProgramFactory>>, HandlerContext>\n ): NextRouteHandler<HandlerContext>\n handler(...args: unknown[]): NextRouteHandler<object> {\n // SAFETY: The public overloads restrict the first argument to a checked Program factory.\n const makeProgram = args[0] as (request: Request, context: object) => AnyProgram\n // SAFETY: The public overloads restrict the optional second argument to route options.\n const options = (args[1] ?? {}) as NextEffectRouteOptions<unknown, object>\n\n return this.makeHandler(makeProgram, options)\n }\n\n /** Create a native Route Handler from a Request/context generator body. */\n gen<\n const HandlerContext extends object = Context,\n const Yield extends EffectYield = EffectYield,\n const Returned extends AnyResult = AnyResult\n >(\n body: GeneratorBody<HandlerContext, Yield, Returned> &\n NextGeneratorChecks<Provided, RequestLayer, Yield, Returned, Failure>,\n options?: NextEffectRouteOptions<\n EffectSuccess<ProgramFromGenerator<Yield, Returned>>,\n HandlerContext\n >\n ): NextRouteHandler<HandlerContext>\n gen<\n const CustomContext extends object,\n const CustomYield extends EffectYield,\n const CustomReturned extends AnyResult\n >(\n body: GeneratorBody<CustomContext, CustomYield, CustomReturned> &\n NextGeneratorChecks<Provided, RequestLayer, CustomYield, CustomReturned, Failure>,\n options?: NextEffectRouteOptions<\n EffectSuccess<ProgramFromGenerator<CustomYield, CustomReturned>>,\n CustomContext\n >\n ): NextRouteHandler<CustomContext>\n gen(...args: unknown[]): NextRouteHandler<object> {\n // SAFETY: The public overloads restrict the first argument to a checked generator body.\n const body = args[0] as GeneratorBody<object, EffectYield, AnyResult>\n // SAFETY: The public overloads restrict the optional second argument to route options.\n const options = (args[1] ?? {}) as NextEffectRouteOptions<unknown, object>\n\n return this.makeHandler((request, context) => {\n // SAFETY: Effect.fn accepts the sync or async generator supplied by the public overload.\n const program = Effect.fn(\n // SAFETY: The public overloads accept both sync and async generator bodies; the runtime invokes the resulting Program asynchronously.\n () => body(request, context) as AsyncGenerator<EffectYield, AnyResult, unknown>\n )\n\n // SAFETY: The public overloads validate the generator's Result, failure, and Service channels.\n return program as AnyProgram\n }, options)\n }\n\n private makeHandler(\n makeProgram: (request: Request, context: object) => AnyProgram,\n routeOptions: NextEffectRouteOptions<unknown, object>\n ): NextRouteHandler<object> {\n assertExclusiveRouteSuccessPolicy(routeOptions)\n\n return async (request, context) => {\n const program = makeProgram(request, context)\n const shouldSerialize = routeOptions.serialize !== undefined\n const effectiveProgram = shouldSerialize\n ? async () => {\n const result = await program()\n\n if (Result.isError(result)) {\n return result\n }\n\n return Result.ok(routeOptions.serialize!(result.value, request, context))\n }\n : program\n const webOptions: Record<string, unknown> = {}\n\n if (this.requestLayer !== undefined) {\n // SAFETY: The public handler overloads pair this runtime context with the configured Context type.\n webOptions.requestLayer = () => this.requestLayer!(request, context as Context)\n }\n\n if (routeOptions.respond !== undefined) {\n webOptions.onSuccess = ({ value }: { readonly value: unknown }) =>\n routeOptions.respond!(value, request, context)\n } else if (routeOptions.onSuccess !== undefined) {\n webOptions.onSuccess = (result: { readonly value: unknown }) =>\n routeOptions.onSuccess!(result, request, context)\n } else if (this.onSuccess !== undefined) {\n webOptions.onSuccess = (result: { readonly value: unknown }) => {\n // SAFETY: The public handler overloads pair this runtime context with the configured Context type.\n return this.onSuccess!(result, request, context as Context)\n }\n }\n\n if (this.onFailure !== undefined) {\n webOptions.onFailure = (error: unknown) => {\n // SAFETY: Runtime WebEffect failures are the checked Failure channel of the route Program.\n return this.onFailure!(error as Failure, request, context as Context)\n }\n }\n\n // SAFETY: Public overloads validate the Program, request Layer, Failure, and Response policy before this erased WebEffect call.\n return await WebEffect.handle(\n // SAFETY: The Runtime's concrete Service union is intentionally erased for WebEffect's internal heterogeneous boundary.\n // oxlint-disable-next-line anti-slop/no-chained-type-assertions -- this is the adapter's single generic erasure.\n this.runtime as unknown as Runtime<AnyService>,\n request,\n // SAFETY: The effective Program is either the checked Program or a private serializer wrapper that preserves its Result error channel.\n effectiveProgram as AnyProgram,\n // SAFETY: The erased WebEffect options are built exclusively from the validated route policies above.\n webOptions as never\n )\n }\n }\n}\n\nexport declare namespace NextEffect {\n /** Options shared by all handlers created from a bound Runtime. */\n export type Options<\n Failure = unknown,\n RequestLayer extends LayerInput = DefaultRequestLayer,\n Context extends object = NextEffectContext\n > = NextEffectOptions<Failure, RequestLayer, Context>\n\n /** A typed per-route success policy. */\n export type RouteOptions<A, Context extends object = NextEffectContext> = NextEffectRouteOptions<\n A,\n Context\n >\n\n /** The explicit App Router context passed to route factories. */\n export type Context<Params extends object = NextEffectParams> = NextEffectContext<Params>\n\n /** The native handler returned by `handler` and `gen`. */\n export type Handler<Context extends object = NextEffectContext> = NextRouteHandler<Context>\n}\n"],"mappings":";;;;AA4BA,MAAM,0BAA0B;CAAC;CAAW;CAAa;AAAW;AAEpE,MAAM,qCACJ,YACS;CACT,MAAM,qBAAqB,wBAAwB,QAAQ,SAAS,QAAQ,UAAU,KAAA,CAAS;CAE/F,IAAI,mBAAmB,SAAS,GAC9B,MAAM,IAAI,UACR,gFAAgF,mBAAmB,KAAK,IAAI,GAC9G;AAEJ;;AAGA,IAAa,aAAb,MAAa,WAKX;CACA;CAEA;CAEA;CAEA;CAEA,YACE,SACA,SACA;EACA,KAAK,UAAU;EACf,KAAK,YAAY,QAAQ;EACzB,KAAK,YAAY,QAAQ;EACzB,KAAK,eAAe,QAAQ;CAC9B;;CAGA,OAAO,KAML,SACA,SAEsD;EACtD,OAAO,IAAI,WAAW,SAAS,WAAW,CAAC,CAAC;CAC9C;CAuBA,QAAQ,GAAG,MAA2C;EAEpD,MAAM,cAAc,KAAK;EAEzB,MAAM,UAAW,KAAK,MAAM,CAAC;EAE7B,OAAO,KAAK,YAAY,aAAa,OAAO;CAC9C;CA2BA,IAAI,GAAG,MAA2C;EAEhD,MAAM,OAAO,KAAK;EAElB,MAAM,UAAW,KAAK,MAAM,CAAC;EAE7B,OAAO,KAAK,aAAa,SAAS,YAAY;GAQ5C,OANgB,OAAO,SAEf,KAAK,SAAS,OAAO,CAIhB;EACf,GAAG,OAAO;CACZ;CAEA,YACE,aACA,cAC0B;EAC1B,kCAAkC,YAAY;EAE9C,OAAO,OAAO,SAAS,YAAY;GACjC,MAAM,UAAU,YAAY,SAAS,OAAO;GAE5C,MAAM,mBADkB,aAAa,cAAc,KAAA,IAE/C,YAAY;IACV,MAAM,SAAS,MAAM,QAAQ;IAE7B,IAAI,OAAO,QAAQ,MAAM,GACvB,OAAO;IAGT,OAAO,OAAO,GAAG,aAAa,UAAW,OAAO,OAAO,SAAS,OAAO,CAAC;GAC1E,IACA;GACJ,MAAM,aAAsC,CAAC;GAE7C,IAAI,KAAK,iBAAiB,KAAA,GAExB,WAAW,qBAAqB,KAAK,aAAc,SAAS,OAAkB;GAGhF,IAAI,aAAa,YAAY,KAAA,GAC3B,WAAW,aAAa,EAAE,YACxB,aAAa,QAAS,OAAO,SAAS,OAAO;QAC1C,IAAI,aAAa,cAAc,KAAA,GACpC,WAAW,aAAa,WACtB,aAAa,UAAW,QAAQ,SAAS,OAAO;QAC7C,IAAI,KAAK,cAAc,KAAA,GAC5B,WAAW,aAAa,WAAwC;IAE9D,OAAO,KAAK,UAAW,QAAQ,SAAS,OAAkB;GAC5D;GAGF,IAAI,KAAK,cAAc,KAAA,GACrB,WAAW,aAAa,UAAmB;IAEzC,OAAO,KAAK,UAAW,OAAkB,SAAS,OAAkB;GACtE;GAIF,OAAO,MAAM,UAAU,OAGrB,KAAK,SACL,SAEA,kBAEA,UACF;EACF;CACF;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { f as setRuntimeContextFrameCarrier, h as RuntimeContextNotConfiguredError, m as withActiveRuntimeContextStorage, r as currentRuntimeContextFrame } from "./context-
|
|
1
|
+
import { f as setRuntimeContextFrameCarrier, h as RuntimeContextNotConfiguredError, m as withActiveRuntimeContextStorage, r as currentRuntimeContextFrame } from "./context-BphfFUMO.mjs";
|
|
2
2
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
3
3
|
//#region src/runtime/node-context.ts
|
|
4
4
|
const asyncLocalStorage = new AsyncLocalStorage();
|
|
@@ -22,4 +22,4 @@ const nodeRuntimeContextStorage = new NodeRuntimeContextStorage();
|
|
|
22
22
|
//#endregion
|
|
23
23
|
export { nodeRuntimeContextStorage as n, NodeRuntimeContextStorage as t };
|
|
24
24
|
|
|
25
|
-
//# sourceMappingURL=node-context-
|
|
25
|
+
//# sourceMappingURL=node-context-Ca18oNSg.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node-context-
|
|
1
|
+
{"version":3,"file":"node-context-Ca18oNSg.mjs","names":[],"sources":["../src/runtime/node-context.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks'\n\nimport { RuntimeContextNotConfiguredError } from './errors'\n\nimport {\n currentRuntimeContextFrame,\n setRuntimeContextFrameCarrier,\n withActiveRuntimeContextStorage\n} from './context'\n\nimport type {\n ActiveRuntimeContextFrame,\n RuntimeContext,\n RuntimeContextFrameCarrier,\n RuntimeContextStorage\n} from './context'\n\nconst asyncLocalStorage = new AsyncLocalStorage<ActiveRuntimeContextFrame>()\n\nconst frameCarrier: RuntimeContextFrameCarrier = {\n run: (frame, program) => asyncLocalStorage.run(frame, program),\n current: () => asyncLocalStorage.getStore()\n}\n\nsetRuntimeContextFrameCarrier(frameCarrier)\n\n/** RuntimeContextStorage backed by Node/Bun async context propagation. */\nexport class NodeRuntimeContextStorage implements RuntimeContextStorage {\n run<A>(context: RuntimeContext, program: () => A): A {\n return withActiveRuntimeContextStorage(this, context, program)\n }\n\n current(): RuntimeContext {\n const frame = currentRuntimeContextFrame()\n\n if (!frame || frame.storage !== this) {\n throw new RuntimeContextNotConfiguredError()\n }\n\n return frame.context\n }\n}\n\n/** Shared Node/Bun storage used by the compatibility APIs and default Runtime. */\nexport const nodeRuntimeContextStorage = new NodeRuntimeContextStorage()\n\nexport { RuntimeContextNotConfiguredError } from './errors'\n\nexport type { RuntimeContext, RuntimeContextStorage } from './context'\n"],"mappings":";;;AAiBA,MAAM,oBAAoB,IAAI,kBAA6C;AAO3E,8BAA8B;CAJ5B,MAAM,OAAO,YAAY,kBAAkB,IAAI,OAAO,OAAO;CAC7D,eAAe,kBAAkB,SAAS;AAGH,CAAC;;AAG1C,IAAa,4BAAb,MAAwE;CACtE,IAAO,SAAyB,SAAqB;EACnD,OAAO,gCAAgC,MAAM,SAAS,OAAO;CAC/D;CAEA,UAA0B;EACxB,MAAM,QAAQ,2BAA2B;EAEzC,IAAI,CAAC,SAAS,MAAM,YAAY,MAC9B,MAAM,IAAI,iCAAiC;EAG7C,OAAO,MAAM;CACf;AACF;;AAGA,MAAa,4BAA4B,IAAI,0BAA0B"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { c as RuntimeContextStorage, s as RuntimeContext } from "./index-
|
|
1
|
+
import { c as RuntimeContextStorage, s as RuntimeContext } from "./index-AiKM71-u.mjs";
|
|
2
2
|
//#region src/runtime/node-context.d.ts
|
|
3
3
|
/** RuntimeContextStorage backed by Node/Bun async context propagation. */
|
|
4
4
|
declare class NodeRuntimeContextStorage implements RuntimeContextStorage {
|
|
@@ -9,4 +9,4 @@ declare class NodeRuntimeContextStorage implements RuntimeContextStorage {
|
|
|
9
9
|
declare const nodeRuntimeContextStorage: NodeRuntimeContextStorage;
|
|
10
10
|
//#endregion
|
|
11
11
|
export { nodeRuntimeContextStorage as n, NodeRuntimeContextStorage as t };
|
|
12
|
-
//# sourceMappingURL=node-context-
|
|
12
|
+
//# sourceMappingURL=node-context-DczjAcrX.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node-context-
|
|
1
|
+
{"version":3,"file":"node-context-DczjAcrX.d.mts","names":[],"sources":["../src/runtime/node-context.ts"],"mappings":";;;cA2Ba,qCAAqC;EAChD,IAAI,GAAG,SAAS,gBAAgB,eAAe,IAAI;EAInD,WAAW;;;cAYA,2BAAyB"}
|
package/dist/node.d.mts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { C as EffectError, E as EffectSuccess, c as RuntimeContextStorage, s as RuntimeContext } from "./index-
|
|
2
|
-
import {
|
|
1
|
+
import { C as EffectError, E as EffectSuccess, c as RuntimeContextStorage, s as RuntimeContext } from "./index-AiKM71-u.mjs";
|
|
2
|
+
import { _ as CompleteInput, d as LayerBackend, h as CompleteExecution, r as RuntimeOptions, w as ProvidedEnvironment, y as LayerInput } from "./outcome-DI8LPIQ4.mjs";
|
|
3
3
|
import { t as RuntimeContextNotConfiguredError } from "./errors-BKcsQ0ip.mjs";
|
|
4
|
-
import "./index-
|
|
5
|
-
import { n as nodeRuntimeContextStorage, t as NodeRuntimeContextStorage } from "./node-context-
|
|
4
|
+
import "./index-CCi07kUw.mjs";
|
|
5
|
+
import { n as nodeRuntimeContextStorage, t as NodeRuntimeContextStorage } from "./node-context-DczjAcrX.mjs";
|
|
6
6
|
import { Result } from "better-result";
|
|
7
7
|
//#region src/runtime/node-runtime.d.ts
|
|
8
8
|
/** Process signals supported by the Node.js/Bun process boundary. */
|
package/dist/node.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { h as RuntimeContextNotConfiguredError } from "./context-
|
|
2
|
-
import { n as nodeRuntimeContextStorage, t as NodeRuntimeContextStorage } from "./node-context-
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
1
|
+
import { h as RuntimeContextNotConfiguredError } from "./context-BphfFUMO.mjs";
|
|
2
|
+
import { n as nodeRuntimeContextStorage, t as NodeRuntimeContextStorage } from "./node-context-Ca18oNSg.mjs";
|
|
3
|
+
import { t as Runtime } from "./runtime-C_55ofnL.mjs";
|
|
4
|
+
import { n as linkAbortSignals } from "./signal-nfgFyNCk.mjs";
|
|
5
5
|
import { Err, Ok } from "better-result";
|
|
6
6
|
//#region src/runtime/node-runtime.ts
|
|
7
7
|
const DEFAULT_SIGNALS = ["SIGINT", "SIGTERM"];
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { N as AnyServiceToken, _ as ScopeCloseError, h as ScopeOutcome, u as Scope } from "./index-AiKM71-u.mjs";
|
|
2
|
+
//#region src/utils/types.d.ts
|
|
3
|
+
type MaybePromise<T> = T | PromiseLike<T>;
|
|
4
|
+
//#endregion
|
|
5
|
+
//#region src/runtime/observer.d.ts
|
|
6
|
+
/** Event emitted after a Service resolution attempt settles. */
|
|
7
|
+
type RuntimeServiceResolveEvent = {
|
|
8
|
+
readonly service: AnyServiceToken;
|
|
9
|
+
readonly resolutionPath: readonly AnyServiceToken[];
|
|
10
|
+
readonly outcome: ScopeOutcome;
|
|
11
|
+
/** Runtime execution owner, omitted for warmup and other root activity. */
|
|
12
|
+
readonly executionId?: string;
|
|
13
|
+
};
|
|
14
|
+
/** Event emitted after a provider acquisition attempt settles. */
|
|
15
|
+
type RuntimeServiceAcquireEvent = {
|
|
16
|
+
readonly service: AnyServiceToken;
|
|
17
|
+
readonly resolutionPath: readonly AnyServiceToken[];
|
|
18
|
+
readonly outcome: ScopeOutcome;
|
|
19
|
+
/** Runtime execution owner, omitted for warmup and other root activity. */
|
|
20
|
+
readonly executionId?: string;
|
|
21
|
+
};
|
|
22
|
+
/** Values supplied to one Runtime execution for diagnostic correlation. */
|
|
23
|
+
type RuntimeExecutionAttributes = Readonly<Record<string, unknown>>;
|
|
24
|
+
/** Metadata shared by the start and end events for one execution. */
|
|
25
|
+
type RuntimeExecutionMetadata = {
|
|
26
|
+
readonly executionId: string;
|
|
27
|
+
readonly name?: string;
|
|
28
|
+
readonly attributes?: RuntimeExecutionAttributes;
|
|
29
|
+
/** Monotonic host timestamp captured immediately before the Program starts. */
|
|
30
|
+
readonly startedAt: number;
|
|
31
|
+
};
|
|
32
|
+
/** Event emitted immediately before a program starts in an execution Scope. */
|
|
33
|
+
type RuntimeExecutionStartEvent = RuntimeExecutionMetadata & {
|
|
34
|
+
readonly scope: Scope;
|
|
35
|
+
};
|
|
36
|
+
/** Event emitted after a program and its execution Scope settle. */
|
|
37
|
+
type RuntimeExecutionEndEvent = RuntimeExecutionMetadata & {
|
|
38
|
+
readonly scope: Scope;
|
|
39
|
+
/** The program outcome used to run execution-scope cleanup. */
|
|
40
|
+
readonly outcome: ScopeOutcome;
|
|
41
|
+
/** Execution-scope cleanup failure, without changing the primary program outcome. */
|
|
42
|
+
readonly cleanupFailure?: ScopeCloseError;
|
|
43
|
+
/** Monotonic elapsed time for the Program and its execution cleanup. */
|
|
44
|
+
readonly durationMs: number;
|
|
45
|
+
};
|
|
46
|
+
/** Event emitted after a Layer provider release callback settles. */
|
|
47
|
+
type RuntimeResourceReleaseEvent = {
|
|
48
|
+
readonly service: AnyServiceToken;
|
|
49
|
+
readonly outcome: ScopeOutcome;
|
|
50
|
+
readonly error?: unknown;
|
|
51
|
+
/** Runtime execution owner, omitted for Runtime-root cleanup. */
|
|
52
|
+
readonly executionId?: string;
|
|
53
|
+
};
|
|
54
|
+
/** Optional best-effort hooks for Runtime lifecycle and resolution events. */
|
|
55
|
+
type RuntimeObserver = {
|
|
56
|
+
readonly onServiceResolve?: (event: RuntimeServiceResolveEvent) => MaybePromise<void>;
|
|
57
|
+
readonly onServiceAcquire?: (event: RuntimeServiceAcquireEvent) => MaybePromise<void>;
|
|
58
|
+
readonly onExecutionStart?: (event: RuntimeExecutionStartEvent) => MaybePromise<void>;
|
|
59
|
+
readonly onExecutionEnd?: (event: RuntimeExecutionEndEvent) => MaybePromise<void>;
|
|
60
|
+
readonly onResourceRelease?: (event: RuntimeResourceReleaseEvent) => MaybePromise<void>;
|
|
61
|
+
};
|
|
62
|
+
/** Compose best-effort Runtime observers into one observer. */
|
|
63
|
+
declare const RuntimeObserver: {
|
|
64
|
+
compose: (...observers: readonly RuntimeObserver[]) => RuntimeObserver;
|
|
65
|
+
};
|
|
66
|
+
//#endregion
|
|
67
|
+
export { RuntimeObserver as a, RuntimeServiceResolveEvent as c, RuntimeExecutionStartEvent as i, MaybePromise as l, RuntimeExecutionEndEvent as n, RuntimeResourceReleaseEvent as o, RuntimeExecutionMetadata as r, RuntimeServiceAcquireEvent as s, RuntimeExecutionAttributes as t };
|
|
68
|
+
//# sourceMappingURL=observer-9nhbL7Pr.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"observer-9nhbL7Pr.d.mts","names":[],"sources":["../src/utils/types.ts","../src/runtime/observer.ts"],"mappings":";;KAAY,aAAa,KAAK,IAAI,YAAY;;;;KCMlC;WACD,SAAS;WACT,yBAAyB;WACzB,SAAS;;WAET;;;KAIC;WACD,SAAS;WACT,yBAAyB;WACzB,SAAS;;WAET;;;KAKC,6BAA6B,SAAS;;KAGtC;WACD;WACA;WAEA,aAAa;;WAEb;;;KAIC,6BAA6B;WAC9B,OAAO;;;KAIN,2BAA2B;WAC5B,OAAO;;WAEP,SAAS;;WAET,iBAAiB;;WAEjB;;;KAIC;WACD,SAAS;WACT,SAAS;WACT;;WAEA;;;KAIC;WACD,oBAAoB,OAAO,+BAA+B;WAC1D,oBAAoB,OAAO,+BAA+B;WAC1D,oBAAoB,OAAO,+BAA+B;WAC1D,kBAAkB,OAAO,6BAA6B;WACtD,qBAAqB,OAAO,gCAAgC;;;cAI1D;EACa,aAAA,oBAAS,sBAAoB"}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { a as RuntimeObserver, c as RuntimeServiceResolveEvent, i as RuntimeExecutionStartEvent, n as RuntimeExecutionEndEvent, o as RuntimeResourceReleaseEvent, s as RuntimeServiceAcquireEvent, t as RuntimeExecutionAttributes } from "./observer-9nhbL7Pr.mjs";
|
|
2
|
+
import { AttributeValue, Tracer, TracerProvider } from "@opentelemetry/api";
|
|
3
|
+
//#region src/opentelemetry/index.d.ts
|
|
4
|
+
/** Controls how Service lifecycle events are represented in telemetry. */
|
|
5
|
+
type ServiceTelemetryMode = 'off' | 'events' | 'spans';
|
|
6
|
+
/** Attribute values accepted by the OpenTelemetry adapter. */
|
|
7
|
+
type OpenTelemetryAttributes = Readonly<Record<string, AttributeValue>>;
|
|
8
|
+
/** A deliberately small, already-sanitized failure representation. */
|
|
9
|
+
type OpenTelemetryFailure = string | {
|
|
10
|
+
readonly message?: string;
|
|
11
|
+
readonly attributes?: OpenTelemetryAttributes;
|
|
12
|
+
};
|
|
13
|
+
/** Select safe execution attributes explicitly before they reach a span. */
|
|
14
|
+
type OpenTelemetryExecutionAttributesSanitizer = (attributes: RuntimeExecutionAttributes) => OpenTelemetryAttributes | undefined;
|
|
15
|
+
/** Select safe failure details explicitly before they reach a span. */
|
|
16
|
+
type OpenTelemetryFailureSanitizer = (cause: unknown) => OpenTelemetryFailure | undefined;
|
|
17
|
+
type OpenTelemetryRuntimeObserverBaseOptions = {
|
|
18
|
+
/** Use an existing tracer. The adapter never registers a global provider. */
|
|
19
|
+
readonly tracer?: Tracer;
|
|
20
|
+
/** Resolve a tracer from an existing provider without registering it globally. */
|
|
21
|
+
readonly provider?: TracerProvider;
|
|
22
|
+
/** Tracer name used only when `provider` is supplied. */
|
|
23
|
+
readonly tracerName?: string;
|
|
24
|
+
/** Optional instrumentation version used only when `provider` is supplied. */
|
|
25
|
+
readonly tracerVersion?: string;
|
|
26
|
+
/** Service resolution policy. Defaults to `off`. */
|
|
27
|
+
readonly serviceResolution?: ServiceTelemetryMode;
|
|
28
|
+
/** Record explicitly sanitized failure details in addition to setting status. */
|
|
29
|
+
readonly recordFailures?: boolean;
|
|
30
|
+
/** Explicitly sanitize arbitrary execution attributes. */
|
|
31
|
+
readonly sanitizeExecutionAttributes?: OpenTelemetryExecutionAttributesSanitizer;
|
|
32
|
+
/** Copy only these execution attribute keys, dropping unsupported values. */
|
|
33
|
+
readonly executionAttributeAllowlist?: readonly string[];
|
|
34
|
+
/** Explicitly sanitize a failure before recording it. */
|
|
35
|
+
readonly sanitizeFailure?: OpenTelemetryFailureSanitizer;
|
|
36
|
+
/** Maximum length for attribute keys and string values. Defaults to 256. */
|
|
37
|
+
readonly maxAttributeLength?: number;
|
|
38
|
+
/** Maximum number of copied execution or failure attributes. Defaults to 32. */
|
|
39
|
+
readonly maxAttributeCount?: number;
|
|
40
|
+
/** Maximum number of Service tags retained in a resolution path. Defaults to 16. */
|
|
41
|
+
readonly maxResolutionPathLength?: number;
|
|
42
|
+
};
|
|
43
|
+
/** Configuration for an observer backed by an existing OpenTelemetry tracer/provider. */
|
|
44
|
+
type OpenTelemetryRuntimeObserverOptions = (OpenTelemetryRuntimeObserverBaseOptions & {
|
|
45
|
+
readonly tracer: Tracer;
|
|
46
|
+
readonly provider?: never;
|
|
47
|
+
}) | (OpenTelemetryRuntimeObserverBaseOptions & {
|
|
48
|
+
readonly provider: TracerProvider;
|
|
49
|
+
readonly tracer?: never;
|
|
50
|
+
});
|
|
51
|
+
/**
|
|
52
|
+
* Best-effort RuntimeObserver adapter for an existing OpenTelemetry tracer.
|
|
53
|
+
*
|
|
54
|
+
* The adapter never installs a global provider, SDK, context manager, or
|
|
55
|
+
* exporter. All observer hooks are synchronous and isolate tracer failures.
|
|
56
|
+
*/
|
|
57
|
+
declare class OpenTelemetryRuntimeObserver implements RuntimeObserver {
|
|
58
|
+
private readonly tracer;
|
|
59
|
+
private readonly options;
|
|
60
|
+
private readonly limits;
|
|
61
|
+
private readonly executionSpans;
|
|
62
|
+
private readonly serviceResolution;
|
|
63
|
+
private readonly recordFailures;
|
|
64
|
+
private disposed;
|
|
65
|
+
constructor(options: OpenTelemetryRuntimeObserverOptions);
|
|
66
|
+
static make(options: OpenTelemetryRuntimeObserverOptions): OpenTelemetryRuntimeObserver;
|
|
67
|
+
readonly onExecutionStart: (event: RuntimeExecutionStartEvent) => void;
|
|
68
|
+
readonly onExecutionEnd: (event: RuntimeExecutionEndEvent) => void;
|
|
69
|
+
readonly onServiceResolve: (event: RuntimeServiceResolveEvent) => void;
|
|
70
|
+
readonly onServiceAcquire: (event: RuntimeServiceAcquireEvent) => void;
|
|
71
|
+
readonly onResourceRelease: (event: RuntimeResourceReleaseEvent) => void;
|
|
72
|
+
/** End any spans whose malformed or missing end event left them pending. */
|
|
73
|
+
dispose(): void;
|
|
74
|
+
[Symbol.dispose](): void;
|
|
75
|
+
[Symbol.asyncDispose](): Promise<void>;
|
|
76
|
+
private safely;
|
|
77
|
+
private startSpan;
|
|
78
|
+
private ownsExecutionSpan;
|
|
79
|
+
private claimExecutionSpan;
|
|
80
|
+
private endExecutionSpan;
|
|
81
|
+
private finishPendingExecution;
|
|
82
|
+
private startExecution;
|
|
83
|
+
private endExecution;
|
|
84
|
+
private finishExecution;
|
|
85
|
+
private findCorrelatedExecution;
|
|
86
|
+
private observeService;
|
|
87
|
+
private findExecutionId;
|
|
88
|
+
private observeCorrelatedService;
|
|
89
|
+
private observeStandaloneService;
|
|
90
|
+
private finishServiceSpan;
|
|
91
|
+
}
|
|
92
|
+
//#endregion
|
|
93
|
+
export { OpenTelemetryAttributes, OpenTelemetryExecutionAttributesSanitizer, OpenTelemetryFailure, OpenTelemetryFailureSanitizer, OpenTelemetryRuntimeObserver, OpenTelemetryRuntimeObserverOptions, ServiceTelemetryMode };
|
|
94
|
+
//# sourceMappingURL=opentelemetry.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"opentelemetry.d.mts","names":[],"sources":["../src/opentelemetry/index.ts"],"mappings":";;;;KAuBY;;KAGA,0BAA0B,SAAS,eAAe;;KAGlD;WAGG;WACA,aAAa;;;KAIhB,6CACV,YAAY,+BACT;;KAGO,iCAAiC,mBAAmB;KAE3D;;WAEM,SAAS;;WAET,WAAW;;WAEX;;WAEA;;WAEA,oBAAoB;;WAEpB;;WAEA,8BAA8B;;WAE9B;;WAEA,kBAAkB;;WAElB;;WAEA;;WAEA;;;KAIC,uCACP;WACU,QAAQ;WACR;MAEV;WACU,UAAU;WACV;;;;;;;;cAgmBF,wCAAwC;mBAClC;mBAEA;mBAEA;mBAEA;mBAEA;mBAEA;UAET;EAEI,YAAA,SAAS;SAYd,KAAK,SAAS,sCAAsC;WAIlD,mBAAoB,OAAO;WAI3B,iBAAkB,OAAO;WAIzB,mBAAoB,OAAO;WAI3B,mBAAoB,OAAO;WAI3B,oBAAqB,OAAO;;EAKrC;GAoBC,OAAO;GAID,OAAO,iBAAiB;UAIvB;UAYA;UAsBA;UAIA;UASA;UAMA;UAMA;UAyDA;UAiBA;UAgCA;UASA;UAiCA;UAIA;UA0BA;UAuBA"}
|