@znight/core 0.4.0 → 0.5.1
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/dist/index.d.mts +62 -2
- package/dist/index.mjs +10 -3
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
- package/src/errors.ts +10 -1
- package/src/hooks.ts +57 -0
- package/src/index.ts +3 -0
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["ErrorCodes","marker","parameterMarker"],"sources":["../src/errors.ts","../src/utils.ts","../src/aop.ts","../src/tokens.ts","../src/container-errors.ts","../src/definition.ts","../src/slot.ts","../src/graph.ts","../src/lifecycle.ts","../src/metadata.ts","../src/runtime-errors.ts","../src/scope.ts","../src/container.ts","../src/hooks.ts","../src/logger.ts","../src/process.ts","../src/application.ts","../src/decorators.ts","../src/params.ts","../src/plugin.ts"],"sourcesContent":["/**\n * Error codes shared by the compiler (build-time diagnostics) and the runtime (`ZnightError`).\n * Documented in docs/internals/architecture.md (§4.8) and docs/reference/error-codes.md.\n *\n * Ranges (the catalogue is closed: third-party packages get no `ZNIGHT` code):\n * - `ZNIGHT001`–`ZNIGHT029`: the core, the compiler and the features shipped in 0.1 (http,\n * messaging, config, observability).\n * - From `ZNIGHT030`, each first-party package reserves a block of ten: `ZNIGHT030`–`039`\n * `@znight/openapi`, `ZNIGHT040`–`049` `@znight/schedule`, `ZNIGHT050`–`059` `@znight/websocket`\n * (reserved), `ZNIGHT060`–`069` `@znight/graphql`.\n *\n * Within a range, codes are allocated in order without gaps. A package uses its block for its own\n * failure modes, with one catch-all code for invalid usage and options, and reuses a lower code\n * when the meaning is the same (a decorator on the wrong target is always `ZNIGHT005`). Codes never\n * change meaning.\n */\nexport const ErrorCode = {\n /** Missing provider for a required dependency. */\n MissingProvider: 'ZNIGHT001',\n /** Circular dependency in the provider graph. */\n CircularDependency: 'ZNIGHT002',\n /** A singleton depends (directly or through transient providers) on a request-scoped provider. */\n ScopeMismatch: 'ZNIGHT003',\n /** Several providers for the exact same type without qualifier or `@Primary`. */\n DuplicateProvider: 'ZNIGHT004',\n /** Invalid decorator usage. */\n InvalidDecorator: 'ZNIGHT005',\n /** Missing required configuration value. */\n MissingConfig: 'ZNIGHT006',\n /** Invalid route definition. */\n InvalidRoute: 'ZNIGHT007',\n /** Several candidates for an interface or base type without `@Primary`. */\n AmbiguousInjection: 'ZNIGHT008',\n /** Invalid lifecycle hook. */\n InvalidLifecycleHook: 'ZNIGHT009',\n /** The type of an injection point cannot be resolved. */\n UnresolvableType: 'ZNIGHT010',\n /** Invalid message consumer definition. */\n InvalidConsumer: 'ZNIGHT011',\n /** Invalid config property. */\n InvalidConfig: 'ZNIGHT012',\n /** Request-scoped provider resolved outside of a request scope. */\n NoActiveScope: 'ZNIGHT013',\n /** Async factory on a non-singleton provider. */\n AsyncNonSingleton: 'ZNIGHT014',\n /** A provider factory threw or rejected. */\n InstantiationFailed: 'ZNIGHT015',\n /** The container was modified after `init()`. */\n ContainerSealed: 'ZNIGHT016',\n /** Non-primitive input injected without a validation schema. */\n UnvalidatedInput: 'ZNIGHT017',\n /** Incompatible versions (metadata format, packages, compiler extension API). */\n VersionMismatch: 'ZNIGHT018',\n /** Provider unreachable from any root. */\n UnusedProvider: 'ZNIGHT019',\n /** The generated module is imported by a provider module (ESM cycle). */\n GeneratedModuleCycle: 'ZNIGHT020',\n /** A lifecycle hook or shutdown step failed or timed out. */\n LifecycleFailed: 'ZNIGHT021',\n /** A source file could not be parsed. */\n SyntaxError: 'ZNIGHT022',\n /**\n * A route has no decision of a required route decorator group (build time), or a decision that\n * no guard of its chain enforces (boot). `@znight/http`, RFC 0001.\n */\n MissingRouteDecision: 'ZNIGHT023',\n\n // ZNIGHT030–039: @znight/openapi (RFC 0002)\n /**\n * Invalid OpenAPI definition: `@OpenApiDocument` options, `@Api*` usage, static values,\n * `securityScheme()`; at runtime, `OpenApiPlugin` options, missing metadata, stale prebuilt file.\n */\n InvalidOpenApiDefinition: 'ZNIGHT030',\n /** The success response of a route cannot be documented and no `@ApiResponse` covers it. */\n UndocumentedResponse: 'ZNIGHT031',\n /** A documented type has no JSON Schema, or does not serialise as declared. */\n UnrepresentableType: 'ZNIGHT032',\n /** Two OpenAPI operations have the same id. */\n DuplicateOperationId: 'ZNIGHT033',\n /** Two different declarations or schemas for one OpenAPI component name. */\n SchemaNameConflict: 'ZNIGHT034',\n /** The OpenAPI documentation of a route contradicts the route. */\n InconsistentOperation: 'ZNIGHT035',\n /** Invalid OpenAPI security requirement or security decision. */\n InvalidSecurityRequirement: 'ZNIGHT036',\n /** A schema could not be converted to JSON Schema while the OpenAPI document was assembled. */\n SchemaConversionFailed: 'ZNIGHT037',\n\n // ZNIGHT040–049: @znight/schedule (RFC 0004)\n /**\n * Invalid schedule: cron expression, duration, time zone, job options or method signature; at\n * runtime, `SchedulePlugin` options, job overrides, metadata, `parseCron` / `registry.add*`.\n */\n InvalidSchedule: 'ZNIGHT040',\n /** Two jobs share a name. */\n DuplicateJob: 'ZNIGHT041',\n /** No job has this name (job override, `registry.trigger` / `remove`). */\n UnknownJob: 'ZNIGHT042',\n /** A job requires a lock but `SchedulePlugin` has no lock store. */\n MissingLockStore: 'ZNIGHT043',\n /** A scheduled run was aborted (`ctx.signal.reason`, `JobAbortedError`); never thrown by the framework. */\n JobAborted: 'ZNIGHT044',\n\n // ZNIGHT060–069: @znight/graphql (RFC 0005, RFC 0007)\n /** A TypeScript type cannot be mapped to a GraphQL type, or a resolver lacks the annotation it needs. */\n InvalidGraphQLType: 'ZNIGHT060',\n /** Two declarations or root fields share a GraphQL name, or a name is invalid or reserved. */\n GraphQLNameConflict: 'ZNIGHT061',\n /**\n * Invalid resolver structure: `@ResolveField` without `@Parent()`, a subscription not returning an\n * async iterable, no `@Query`, inherited handlers, resolvers in a compiled library.\n */\n InvalidResolver: 'ZNIGHT062',\n /**\n * Invalid input position: a type used as input and output, a getter, a union, a cycle of non-null\n * input fields, a default value not matching its type.\n */\n InvalidGraphQLInput: 'ZNIGHT063',\n /** The members of a GraphQL union (or the implementations of an interface) cannot be told apart at runtime. */\n UnresolvableAbstractType: 'ZNIGHT064',\n /**\n * Invalid loader: `@Loader()` on a type that is not `Loader<L>`, `L` not a `BatchLoad`; at runtime,\n * a batch function returning another number of values than keys.\n */\n InvalidLoader: 'ZNIGHT065',\n /**\n * Invalid GraphQL setup at boot: malformed or version-skewed metadata, invalid schema, invalid\n * `GraphQLPlugin` options, missing `HttpPlugin`, scalar name mismatch.\n */\n InvalidGraphQLSetup: 'ZNIGHT066',\n /**\n * Invalid schema-first SDL (RFC 0007): no `.graphql` file matches, a syntax error, a graphql-js\n * schema validation error, a scalar without `scalar()` definition, an unsupported construct.\n */\n InvalidGraphQLSdl: 'ZNIGHT067',\n /**\n * Schema-first resolvers do not match the SDL (RFC 0007): a field without resolver, a resolver,\n * type or argument the SDL does not declare, a signature that does not conform to the SDL types.\n */\n GraphQLSchemaMismatch: 'ZNIGHT068',\n} as const\n\nexport type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode]\n\n/** Short human readable description of every error code. */\nexport const ERROR_DESCRIPTIONS: Readonly<Record<ErrorCode, string>> = {\n ZNIGHT001: 'Missing provider: a required dependency has no provider',\n ZNIGHT002: 'Circular dependency detected in the provider graph',\n ZNIGHT003: 'Scope mismatch: a singleton cannot depend on a request-scoped provider',\n ZNIGHT004: 'Duplicate provider: several providers for the same type without qualifier or @Primary',\n ZNIGHT005: 'Invalid decorator usage',\n ZNIGHT006: 'Missing required configuration value',\n ZNIGHT007: 'Invalid route definition',\n ZNIGHT008: 'Ambiguous injection: several candidates without @Primary',\n ZNIGHT009: 'Invalid lifecycle hook',\n ZNIGHT010: 'Unresolvable injection type',\n ZNIGHT011: 'Invalid message consumer definition',\n ZNIGHT012: 'Invalid config property',\n ZNIGHT013: 'Request-scoped provider resolved outside of a request scope',\n ZNIGHT014: 'Async factory on a non-singleton provider',\n ZNIGHT015: 'Provider instantiation failed',\n ZNIGHT016: 'Container sealed: providers cannot be registered or overridden after init()',\n ZNIGHT017: 'Unvalidated input: non-primitive input injected without a schema',\n ZNIGHT018: 'Version mismatch',\n ZNIGHT019: 'Unused provider: unreachable from any root',\n ZNIGHT020: 'The generated module is imported by a provider module (ESM cycle)',\n ZNIGHT021: 'Lifecycle hook or shutdown step failed or timed out',\n ZNIGHT022: 'Syntax error: a source file could not be parsed',\n ZNIGHT023: 'Missing route decision: a route has no decision of a required group, or no guard enforces it',\n ZNIGHT030: 'Invalid OpenAPI definition',\n ZNIGHT031: 'Undocumented response: the success response of a route cannot be documented',\n ZNIGHT032: 'Unrepresentable type: a documented type has no JSON Schema or does not serialise as declared',\n ZNIGHT033: 'Duplicate OpenAPI operation id',\n ZNIGHT034: 'Schema name conflict: two different schemas for one OpenAPI component name',\n ZNIGHT035: 'Inconsistent operation: the OpenAPI documentation contradicts the route',\n ZNIGHT036: 'Invalid OpenAPI security requirement',\n ZNIGHT037: 'Schema conversion failed: a schema could not be converted to JSON Schema',\n ZNIGHT040: 'Invalid schedule: cron expression, duration, time zone, options or job signature',\n ZNIGHT041: 'Duplicate job: two jobs share a name',\n ZNIGHT042: 'Unknown job: no job has this name',\n ZNIGHT043: 'Missing lock store: a job requires a lock but SchedulePlugin has no store',\n ZNIGHT044: 'Job aborted: a scheduled run was aborted (timeout, lost lock, removal or shutdown)',\n ZNIGHT060: 'Invalid GraphQL type: a TypeScript type cannot be mapped to a GraphQL type',\n ZNIGHT061: 'GraphQL name conflict: two types or root fields share a name, or a name is invalid or reserved',\n ZNIGHT062: 'Invalid resolver: the structure of a GraphQL resolver is invalid',\n ZNIGHT063: 'Invalid GraphQL input: a type cannot be used in an input position',\n ZNIGHT064: 'Unresolvable abstract type: the members of a GraphQL union or interface cannot be told apart at runtime',\n ZNIGHT065: 'Invalid loader: not a Loader of a BatchLoad provider, or a batch returning the wrong number of values',\n ZNIGHT066: 'Invalid GraphQL setup: metadata, schema, GraphQLPlugin options, driver or HttpPlugin missing',\n ZNIGHT067: 'Invalid GraphQL SDL: the schema-first .graphql files cannot be read, parsed or validated',\n ZNIGHT068: 'GraphQL schema mismatch: schema-first resolvers do not cover or conform to the SDL',\n}\n\nexport interface ZnightErrorOptions extends ErrorOptions {\n /** Suggestions displayed under the error message. */\n readonly hints?: readonly string[]\n}\n\n/** Base class of every error thrown by Znight at runtime. */\nexport class ZnightError extends Error {\n readonly code: ErrorCode\n readonly hints: readonly string[]\n\n constructor(code: ErrorCode, message: string, options: ZnightErrorOptions = {}) {\n super(`${code}: ${message}`, options)\n this.name = 'ZnightError'\n this.code = code\n this.hints = options.hints ?? []\n }\n}\n","/** Internal helpers (not part of the public API). */\n\n/** Whether `value` is a promise-like object (has a callable `then`). */\nexport function isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n value !== null &&\n (typeof value === 'object' || typeof value === 'function') &&\n typeof (value as { then?: unknown }).then === 'function'\n )\n}\n\n/** Message of any thrown value. */\nexport function errorMessage(error: unknown): string {\n if (error instanceof Error) return error.message\n if (typeof error === 'string') return error\n try {\n return String(error)\n } catch {\n return Object.prototype.toString.call(error)\n }\n}\n\n/** Whether the runtime runs in development mode (`NODE_ENV !== 'production'`). */\nexport function isDevelopment(): boolean {\n return globalThis.process?.env?.['NODE_ENV'] !== 'production'\n}\n\n/** Monotonic clock in milliseconds. */\nexport function now(): number {\n return performance.now()\n}\n","import type { MethodInterception } from './metadata.ts'\n\nimport { ErrorCode, ZnightError } from './errors.ts'\nimport { isDevelopment, isThenable } from './utils.ts'\n\n/** A call to an intercepted method, as seen by a {@link MethodInterceptor}. */\nexport interface MethodInvocation {\n /** The instance the method is called on. */\n readonly target: object\n /** Name of the provider (display name) the method belongs to. */\n readonly className: string\n readonly methodName: string\n /** Arguments of this call (as passed to this interceptor). */\n readonly args: readonly unknown[]\n /** Whether the intercepted method is async: interceptors must then return a promise. */\n readonly isAsync: boolean\n /**\n * Calls the next interceptor, or the original method for the innermost one, with `args` (default:\n * the current arguments) and returns its result. May be called several times (retries).\n */\n proceed(args?: readonly unknown[]): unknown\n}\n\n/**\n * A provider wrapping method calls (`@Intercept(MyInterceptor, options)`). It must return the value\n * of `invocation.proceed()` (or a replacement): a promise for async methods, a plain value for\n * synchronous ones.\n *\n * ```ts\n * @Injectable()\n * export class TimingInterceptor implements MethodInterceptor<{ label?: string }> {\n * async intercept(invocation: MethodInvocation, options: { label?: string }) {\n * const start = performance.now()\n * try { return await invocation.proceed() }\n * finally { console.log(options.label ?? invocation.methodName, performance.now() - start) }\n * }\n * }\n * ```\n */\nexport interface MethodInterceptor<O = unknown> {\n intercept(invocation: MethodInvocation, options: O): unknown\n}\n\n/** One interceptor of a chain with its options. */\nexport interface InterceptorLink {\n readonly interceptor: MethodInterceptor\n readonly options?: unknown\n}\n\nexport interface InterceptMethodOptions {\n /** Name used in messages and exposed as `invocation.className`. Default: the constructor name. */\n readonly className?: string\n /** Whether the method is async. Default: `false`. */\n readonly async?: boolean\n /**\n * Throw when an interceptor returns a thenable for a synchronous method.\n * Default: `true` unless `NODE_ENV === 'production'`.\n */\n readonly checkSync?: boolean\n}\n\ntype Method = (this: unknown, ...args: unknown[]) => unknown\n\nclass Chain {\n readonly original: Method\n readonly links: readonly InterceptorLink[]\n readonly className: string\n readonly methodName: string\n readonly isAsync: boolean\n readonly checkSync: boolean\n\n constructor(\n original: Method,\n links: readonly InterceptorLink[],\n className: string,\n methodName: string,\n isAsync: boolean,\n checkSync: boolean,\n ) {\n this.original = original\n this.links = links\n this.className = className\n this.methodName = methodName\n this.isAsync = isAsync\n this.checkSync = checkSync\n }\n\n call(index: number, target: object, args: readonly unknown[]): unknown {\n if (index === this.links.length) return this.original.apply(target, args as unknown[])\n const link = this.links[index] as InterceptorLink\n const invocation = new Invocation(this, index, target, args)\n const result = link.interceptor.intercept(invocation, link.options)\n if (this.checkSync && !this.isAsync && result !== invocation.lastResult && isThenable(result)) {\n throw new ZnightError(\n ErrorCode.InvalidDecorator,\n `Interceptor ${interceptorName(link.interceptor)} returned a promise for the synchronous method ` +\n `${this.className}.${this.methodName}()`,\n { hints: ['Make the method async, or return invocation.proceed() synchronously from the interceptor'] },\n )\n }\n return result\n }\n}\n\nclass Invocation implements MethodInvocation {\n readonly target: object\n readonly args: readonly unknown[]\n /** Last value returned by `proceed()` (lets the sync check accept pass-through thenables). */\n lastResult: unknown = undefined\n readonly #chain: Chain\n readonly #index: number\n\n constructor(chain: Chain, index: number, target: object, args: readonly unknown[]) {\n this.#chain = chain\n this.#index = index\n this.target = target\n this.args = args\n }\n\n get className(): string {\n return this.#chain.className\n }\n\n get methodName(): string {\n return this.#chain.methodName\n }\n\n get isAsync(): boolean {\n return this.#chain.isAsync\n }\n\n proceed(args?: readonly unknown[]): unknown {\n this.lastResult = this.#chain.call(this.#index + 1, this.target, args ?? this.args)\n return this.lastResult\n }\n}\n\nfunction interceptorName(interceptor: MethodInterceptor): string {\n const name = (interceptor as { constructor?: { name?: unknown } }).constructor?.name\n return typeof name === 'string' && name !== '' && name !== 'Object' ? name : '<anonymous interceptor>'\n}\n\nfunction assertInterceptor(value: unknown, where: string): asserts value is MethodInterceptor {\n if (\n value === null ||\n (typeof value !== 'object' && typeof value !== 'function') ||\n typeof (value as { intercept?: unknown }).intercept !== 'function'\n ) {\n throw new ZnightError(ErrorCode.InvalidDecorator, `${where}: the interceptor has no intercept() method`, {\n hints: ['Interceptors passed to @Intercept() must implement MethodInterceptor'],\n })\n }\n}\n\n/**\n * Wraps `target[methodName]` with `chain` (first link = outermost interceptor). The wrapper is\n * installed as an own, non-enumerable property of `target` (no Proxy): `#private` fields keep\n * working and calls through `this` (self-invocation) are intercepted too.\n *\n * @throws ZnightError (ZNIGHT005) when the method or an interceptor is invalid.\n */\nexport function interceptMethod(\n target: object,\n methodName: string,\n chain: readonly InterceptorLink[],\n options: InterceptMethodOptions = {},\n): void {\n const className = options.className ?? (target.constructor?.name || 'Object')\n const original: unknown = (target as Record<string, unknown>)[methodName]\n if (typeof original !== 'function') {\n throw new ZnightError(ErrorCode.InvalidDecorator, `Cannot intercept ${className}.${methodName}: it is not a method`)\n }\n if (chain.length === 0) return\n for (const link of chain) assertInterceptor(link.interceptor, `Cannot intercept ${className}.${methodName}()`)\n const compiled = new Chain(\n original as Method,\n [...chain],\n className,\n methodName,\n options.async ?? false,\n options.checkSync ?? isDevelopment(),\n )\n const wrapper = function (this: unknown, ...args: unknown[]): unknown {\n return compiled.call(0, this === undefined || this === null ? target : (this as object), args)\n }\n Object.defineProperty(wrapper, 'name', { value: methodName, configurable: true })\n Object.defineProperty(target, methodName, { value: wrapper, writable: true, configurable: true, enumerable: false })\n}\n\n/**\n * Applies the interceptors of a provider definition to a freshly created instance. `deps` are the\n * resolved dependencies of the provider (`InterceptorBinding.dep` indexes into them).\n */\nexport function applyInterceptors(\n target: object,\n interceptions: Readonly<Record<string, MethodInterception>>,\n deps: readonly unknown[],\n className?: string,\n): void {\n const name = className ?? (target.constructor?.name || 'Object')\n for (const [methodName, interception] of Object.entries(interceptions)) {\n const links: InterceptorLink[] = []\n for (const binding of interception.chain) {\n if (binding.dep < 0 || binding.dep >= deps.length) {\n throw new ZnightError(\n ErrorCode.InvalidDecorator,\n `Cannot intercept ${name}.${methodName}(): interceptor dependency #${binding.dep} does not exist`,\n )\n }\n const interceptor = deps[binding.dep]\n assertInterceptor(interceptor, `Cannot intercept ${name}.${methodName}()`)\n links.push({ interceptor, options: binding.options })\n }\n interceptMethod(target, methodName, links, { className: name, async: interception.async })\n }\n}\n","import type { ProviderClass, Token } from './metadata.ts'\n\ndeclare const tokenType: unique symbol\n\n/**\n * A {@link Token} carrying the type of the value it identifies. It is a plain string at runtime;\n * the type parameter only exists for the type checker:\n *\n * ```ts\n * export const ClockToken: TypedToken<Clock> = token<Clock>('@acme/time#Clock')\n * container.registerValue(ClockToken, systemClock) // value checked against Clock\n * const clock = container.get(ClockToken) // Clock\n * ```\n */\nexport type TypedToken<T> = Token & { readonly [tokenType]?: T }\n\n/**\n * A class used as a lookup key, matched through its `prototype` (accepts classes with private or\n * protected constructors, which are not assignable to {@link ProviderClass}).\n */\nexport interface ClassKey<T = unknown> {\n readonly prototype: T\n}\n\n/** Anything the container accepts to look a provider up: a token, an alias, a display name or a class. */\nexport type ProviderKey<T = unknown> = TypedToken<T> | ProviderClass<T> | ClassKey<T>\n\n/** Declares a {@link TypedToken}. Zero runtime cost: returns `id` unchanged. */\nexport function token<T>(id: string): TypedToken<T> {\n return id\n}\n\n/** Tokens under which `@znight/core` exposes its own objects to the container. */\nexport const CoreTokens: {\n /** The {@link Container} itself. */\n readonly Container: Token\n /** The running `Application` (registered by `Application.create`). */\n readonly Application: Token\n /** The application `Hooks` (registered by `Application.create`). */\n readonly Hooks: Token\n /** The live application `CoreLogger` (registered by `Application.create`). */\n readonly Logger: Token\n} = Object.freeze({\n Container: '@znight/core#Container',\n Application: '@znight/core#Application',\n Hooks: '@znight/core#Hooks',\n Logger: '@znight/core#CoreLogger',\n})\n\n/**\n * Human readable name of a token: the part after the last `#`\n * (`src/users/user.service.ts#UserService` → `UserService`, `src/db.ts#DbFactory.createPool` →\n * `DbFactory.createPool`). Tokens without `#` are returned unchanged.\n */\nexport function displayName(token: Token): string {\n const index = token.lastIndexOf('#')\n return index === -1 ? token : token.slice(index + 1)\n}\n\n/** Formats a dependency path with display names: `UserController -> UserService -> Database`. */\nexport function formatPath(tokens: readonly Token[]): string {\n return tokens.map(displayName).join(' -> ')\n}\n\n/** `UserService (src/users/user.service.ts#UserService)`, or just the token when it has no `#`. */\nexport function describeToken(token: Token): string {\n const name = displayName(token)\n return name === token ? token : `${name} (${token})`\n}\n\n/** Describes any provider key for error messages. */\nexport function describeKey(key: unknown): string {\n if (typeof key === 'string') return describeToken(key)\n if (typeof key === 'function') return `class ${key.name || '<anonymous>'}`\n return String(key)\n}\n","/** Error factories of the container (internal): one place for codes, messages and hints. */\n\nimport type { ZnightMetadata } from './metadata.ts'\nimport type { Slot } from './slot.ts'\n\nimport { ErrorCode, ZnightError } from './errors.ts'\nimport { describeKey, describeToken } from './tokens.ts'\n\n/** Why a resolution cannot proceed, from the container status. */\nexport type Unavailability = 'open' | 'failed' | 'disposed'\n\nexport function invalidMetadataError(): ZnightError {\n return new ZnightError(\n ErrorCode.VersionMismatch,\n 'Invalid metadata: expected the object generated by @znight/compiler ({ version, providers, resolutionOrder })',\n )\n}\n\nexport function metadataVersionError(metadata: ZnightMetadata, expected: number): ZnightError {\n const compiler = metadata.compiler === undefined ? '' : ` (generated by @znight/compiler ${metadata.compiler})`\n return new ZnightError(\n ErrorCode.VersionMismatch,\n `Unsupported metadata version ${String(metadata.version)}${compiler}: @znight/core expects version ${expected}`,\n { hints: ['Regenerate the metadata (znight generate) with a @znight/compiler version matching @znight/core'] },\n )\n}\n\nfunction providedBy(slot: Slot | undefined): string {\n const plugin = slot?.external?.providedBy\n return plugin === undefined ? '' : ` (provided by ${plugin})`\n}\n\nexport function notFoundError(key: unknown, slot?: Slot): ZnightError {\n const hints: string[] = []\n const plugin = slot?.external?.providedBy\n if (plugin !== undefined) hints.push(`Add ${plugin} to Application.create({ plugins })`)\n if (typeof key === 'function') {\n hints.push(`Decorate ${key.name || 'the class'} with @Injectable() and regenerate the metadata (znight generate)`)\n } else {\n hints.push('Supply it with Application.create({ providers }) or container.registerValue()')\n }\n return new ZnightError(ErrorCode.MissingProvider, `No provider for ${describeKey(key)}${providedBy(slot)}`, {\n hints,\n })\n}\n\nexport function unknownClassError(action: string, key: unknown): ZnightError {\n return new ZnightError(\n ErrorCode.MissingProvider,\n `Cannot ${action} ${describeKey(key)}: it is not a known provider`,\n {\n hints: ['Pass the provider token, or a class registered in the compiled metadata'],\n },\n )\n}\n\nexport function ambiguousNameError(name: string, matches: readonly Slot[]): ZnightError {\n return new ZnightError(\n ErrorCode.AmbiguousInjection,\n `\"${name}\" is ambiguous: it matches ${matches.map(slot => slot.token).join(', ')}`,\n { hints: ['Use the class or the full token instead of the display name'] },\n )\n}\n\nexport function noScopeError(slot: Slot): ZnightError {\n return new ZnightError(\n ErrorCode.NoActiveScope,\n `${describeToken(slot.token)} is request-scoped and was resolved outside of a request scope`,\n {\n hints: [\n 'Resolve it inside container.runInScope()',\n 'In singletons, inject it as Lazy<T> and call get() during the request',\n ],\n },\n )\n}\n\nexport function closedScopeError(slot: Slot): ZnightError {\n return new ZnightError(\n ErrorCode.NoActiveScope,\n `${describeToken(slot.token)} was resolved in a request scope that is already closed`,\n { hints: ['Await every asynchronous operation of a request inside the runInScope() callback'] },\n )\n}\n\nexport function missingScopeValueError(slot: Slot): ZnightError {\n return new ZnightError(\n ErrorCode.NoActiveScope,\n `No value for the request-scoped ${describeToken(slot.token)} in the current scope${providedBy(slot)}`,\n { hints: ['Pass it to container.runInScope(fn, [[token, value]]) or set it with currentScope().set()'] },\n )\n}\n\nexport function sealedError(action: string, key: unknown): ZnightError {\n return new ZnightError(\n ErrorCode.ContainerSealed,\n `Cannot ${action} ${describeKey(key)}: the container is sealed (init() has been called)`,\n { hints: ['Register providers, values and overrides before init(), e.g. in Plugin.register()'] },\n )\n}\n\nexport function duplicateRegistrationError(action: string, slot: Slot): ZnightError {\n return new ZnightError(\n ErrorCode.DuplicateProvider,\n `Cannot ${action} ${describeToken(slot.token)}: it is already registered by ${slot.origin ?? 'another registration'}`,\n { hints: ['Use container.override() (or Application.create({ overrides })) to replace a provider'] },\n )\n}\n\nexport function compiledProviderError(action: string, slot: Slot): ZnightError {\n const source = slot.compiledSource\n const where = source === undefined ? '' : ` declared at ${source.file}:${source.line}:${source.column}`\n return new ZnightError(\n ErrorCode.DuplicateProvider,\n `Cannot ${action} ${describeToken(slot.token)}: it is a compiled provider${where}`,\n { hints: ['Use container.override() to replace a compiled provider'] },\n )\n}\n\nexport function unavailableError(slot: Slot, reason: Unavailability): ZnightError {\n switch (reason) {\n case 'disposed':\n return new ZnightError(\n ErrorCode.InstantiationFailed,\n `Cannot resolve ${slot.displayName}: the container has been disposed`,\n )\n case 'failed':\n return new ZnightError(\n ErrorCode.InstantiationFailed,\n `Cannot resolve ${slot.displayName}: the container failed to initialise`,\n )\n default:\n return new ZnightError(\n ErrorCode.InstantiationFailed,\n `Cannot resolve ${slot.displayName}: the container is not initialised`,\n { hints: ['Call `await container.init()` (or use Application.create()) first'] },\n )\n }\n}\n\nexport function reentrantCreationError(slot: Slot): ZnightError {\n return new ZnightError(\n ErrorCode.CircularDependency,\n `Circular dependency: ${slot.displayName} was requested while it is being instantiated`,\n { hints: ['Do not call Lazy<T>.get() from a constructor or factory: call it later (e.g. in onStart())'] },\n )\n}\n\nexport function notReadyError(slot: Slot): ZnightError {\n return new ZnightError(\n ErrorCode.InstantiationFailed,\n `${slot.displayName} is not ready yet: its async factory is still running`,\n { hints: ['Call Lazy<T>.get() after init() completed (e.g. in onStart())'] },\n )\n}\n\nexport function failedProviderError(slot: Slot): ZnightError {\n return new ZnightError(ErrorCode.InstantiationFailed, `${slot.displayName} failed to initialise`)\n}\n\nexport function asyncOnDemandError(slot: Slot, declared: boolean): ZnightError {\n return new ZnightError(\n ErrorCode.InstantiationFailed,\n declared\n ? `Cannot create ${slot.displayName} on demand: its factory is async`\n : `Cannot create ${slot.displayName} on demand: its factory returned a promise`,\n {\n hints: [\n declared\n ? 'Include it in init({ only }) so that it is created during initialisation'\n : 'Declare it async and include it in init({ only })',\n ],\n },\n )\n}\n","import type { ProviderDefinition, Token } from './metadata.ts'\n\nimport { ErrorCode, ZnightError } from './errors.ts'\nimport { describeToken } from './tokens.ts'\n\nconst SCOPES: ReadonlySet<string> = new Set(['singleton', 'request', 'transient'])\n\n/** Whether `value` has the shape of a {@link ProviderDefinition} (`{ scope, deps, factory }`). */\nexport function isProviderDefinition(value: unknown): value is ProviderDefinition {\n if (value === null || typeof value !== 'object') return false\n const candidate = value as Partial<ProviderDefinition>\n return (\n typeof candidate.factory === 'function' &&\n Array.isArray(candidate.deps) &&\n typeof candidate.scope === 'string' &&\n SCOPES.has(candidate.scope)\n )\n}\n\n/**\n * Checks the shape of a provider definition.\n *\n * @throws ZnightError ZNIGHT005 for a malformed definition, ZNIGHT014 for an async non-singleton.\n */\nexport function validateDefinition(token: Token, definition: ProviderDefinition): void {\n if (!isProviderDefinition(definition)) {\n throw new ZnightError(\n ErrorCode.InvalidDecorator,\n `Invalid provider definition for ${describeToken(token)}: expected { scope, deps, factory }`,\n )\n }\n if (definition.async === true && definition.scope !== 'singleton') {\n throw new ZnightError(\n ErrorCode.AsyncNonSingleton,\n `${describeToken(token)} has an async factory but is ${definition.scope}-scoped`,\n { hints: ['Only singletons may have async factories'] },\n )\n }\n}\n","/**\n * Internal model of the container: one {@link Slot} per canonical token. Not part of the public API.\n */\nimport type { ExternalDefinition, ProviderDefinition, SourceLocation, Token } from './metadata.ts'\n\nimport { displayName } from './tokens.ts'\n\n// Binding modes\nexport const UNBOUND = 0\nexport const VALUE = 1\nexport const SINGLETON = 2\nexport const REQUEST = 3\nexport const TRANSIENT = 4\n\n// Singleton states (values are always READY)\nexport const IDLE = 0\nexport const CREATING = 1\nexport const PENDING = 2\nexport const READY = 3\nexport const FAILED = 4\nexport const DISPOSED = 5\n\n/**\n * Precedence levels of a binding (higher wins):\n * `override` > plugin `register`/`registerValue` > `Application.create({ providers })` > built-in > compiled.\n */\nexport const LEVEL_UNBOUND = -1\nexport const LEVEL_COMPILED = 0\nexport const LEVEL_BUILTIN = 1\nexport const LEVEL_APPLICATION = 2\nexport const LEVEL_PLUGIN = 3\nexport const LEVEL_OVERRIDE = 4\n\n// Dependency kinds\nexport const DEP_REQUIRED = 0\nexport const DEP_OPTIONAL = 1\nexport const DEP_MULTI = 2\nexport const DEP_LAZY = 3\n\n/** A resolved {@link import('./metadata.ts').DependencyRef}. */\nexport interface DepPlan {\n readonly kind: number\n /** Target (required, optional, lazy). */\n readonly slot: Slot | undefined\n /** Targets (multi). */\n readonly slots: readonly Slot[] | undefined\n}\n\nexport class Slot {\n readonly token: Token\n readonly displayName: string\n /** Precedence level of the current binding. */\n level: number = LEVEL_UNBOUND\n mode: number = UNBOUND\n definition: ProviderDefinition | undefined = undefined\n /**\n * Class the token designates (class of its first provider definition, or of a built-in), kept when\n * a value replaces the binding: matches class keys looked up by name (see `Container#findByName`).\n */\n cls: object | undefined = undefined\n /** `true` when the token is a provider of the compiled metadata (even if replaced since). */\n compiled = false\n /** Source location of the compiled provider, when the metadata includes it. */\n compiledSource: SourceLocation | undefined = undefined\n external: ExternalDefinition | undefined = undefined\n /** Who bound the slot (for messages): `plugin \"http\"`, `Application providers`, `override`... */\n origin: string | undefined = undefined\n state: number = IDLE\n instance: unknown = undefined\n promise: Promise<void> | undefined = undefined\n /** Resolved dependencies, in definition order. */\n plan: readonly DepPlan[] | undefined = undefined\n /** Hard dependency edges (required, optional, multi; not lazy). */\n edges: readonly Slot[] = []\n /** Lazy dependency targets. */\n lazyEdges: readonly Slot[] = []\n /** Singletons that must be ready before this provider can be created (through transients). */\n waits: readonly Slot[] = []\n /** Position in the merged resolution order (-1 when not ordered). */\n order = -1\n /** DFS color during ordering (0 white, 1 gray, 2 black). */\n mark = 0\n /** Whether resolving this slot requires an active request scope. */\n needsScope = false\n\n constructor(token: Token) {\n this.token = token\n this.displayName = displayName(token)\n }\n\n /** Whether the slot has a definition the container instantiates. */\n get isProvider(): boolean {\n return this.mode >= SINGLETON\n }\n\n /** Whether an unbound slot can still be resolved (request external read from the scope, or optional external). */\n get isSatisfiedExternally(): boolean {\n const external = this.external\n return external !== undefined && (external.scope === 'request' || external.optional === true)\n }\n}\n\n/** Mode of a provider definition. */\nexport function modeOf(definition: ProviderDefinition): number {\n switch (definition.scope) {\n case 'request':\n return REQUEST\n case 'transient':\n return TRANSIENT\n default:\n return SINGLETON\n }\n}\n","/**\n * Graph algorithms of the container (internal): dependency plans, merged topological order,\n * scope validation, closures and missing dependencies. Everything is O(providers + edges).\n */\n\nimport type { DependencyRef, Token } from './metadata.ts'\n\nimport { ErrorCode, ZnightError } from './errors.ts'\nimport {\n DEP_LAZY,\n DEP_MULTI,\n DEP_OPTIONAL,\n DEP_REQUIRED,\n type DepPlan,\n REQUEST,\n SINGLETON,\n type Slot,\n TRANSIENT,\n UNBOUND,\n} from './slot.ts'\nimport { describeToken, formatPath } from './tokens.ts'\n\nconst WHITE = 0\nconst GRAY = 1\nconst BLACK = 2\n\n/** Resolves the dependencies of a provider slot into a plan and dependency edges. */\nexport function buildPlan(slot: Slot, lookup: (token: Token) => Slot): void {\n const definition = slot.definition\n if (definition === undefined) return\n const plan: DepPlan[] = []\n const edges: Slot[] = []\n const lazyEdges: Slot[] = []\n definition.deps.forEach((ref: DependencyRef, index) => {\n if (typeof ref === 'string') {\n const target = lookup(ref)\n plan.push({ kind: DEP_REQUIRED, slot: target, slots: undefined })\n edges.push(target)\n } else if (ref !== null && typeof ref === 'object' && 'multi' in ref && Array.isArray(ref.multi)) {\n const targets = ref.multi.map(lookup)\n plan.push({ kind: DEP_MULTI, slot: undefined, slots: targets })\n edges.push(...targets)\n } else if (ref !== null && typeof ref === 'object' && 'lazy' in ref && typeof ref.lazy === 'string') {\n const target = lookup(ref.lazy)\n plan.push({ kind: DEP_LAZY, slot: target, slots: undefined })\n lazyEdges.push(target)\n } else if (ref !== null && typeof ref === 'object' && 'token' in ref && typeof ref.token === 'string') {\n const target = lookup(ref.token)\n plan.push({ kind: DEP_OPTIONAL, slot: target, slots: undefined })\n edges.push(target)\n } else {\n throw new ZnightError(\n ErrorCode.InvalidDecorator,\n `Invalid dependency #${index} of ${describeToken(slot.token)}: ${safeJson(ref)}`,\n { hints: ['Expected a token, { token, optional: true }, { multi: [...] } or { lazy: token }'] },\n )\n }\n })\n slot.plan = plan\n slot.edges = edges\n slot.lazyEdges = lazyEdges\n}\n\n/**\n * Depth-first topological sort over hard edges (lazy edges are ignored: `Lazy<T>` breaks cycles).\n * Visiting `base` in order keeps the compiled `resolutionOrder` unchanged and inserts runtime\n * definitions right before their first dependent.\n *\n * @throws ZnightError (ZNIGHT002) on a cycle.\n */\nexport function computeOrder(base: Iterable<Slot>): Slot[] {\n const order: Slot[] = []\n const stack: Slot[] = []\n const cursors: number[] = []\n for (const root of base) {\n if (!root.isProvider || root.mark !== WHITE) continue\n root.mark = GRAY\n stack.push(root)\n cursors.push(0)\n while (stack.length > 0) {\n const top = stack.length - 1\n const slot = stack[top] as Slot\n const cursor = cursors[top] as number\n if (cursor < slot.edges.length) {\n cursors[top] = cursor + 1\n const next = slot.edges[cursor] as Slot\n if (!next.isProvider || next.mark === BLACK) continue\n if (next.mark === GRAY) throw cycleError([...stack.slice(stack.indexOf(next)), next])\n next.mark = GRAY\n stack.push(next)\n cursors.push(0)\n } else {\n slot.mark = BLACK\n slot.order = order.length\n order.push(slot)\n stack.pop()\n cursors.pop()\n }\n }\n }\n return order\n}\n\nfunction cycleError(cycle: readonly Slot[]): ZnightError {\n const path = cycle.map(slot => slot.token)\n return new ZnightError(ErrorCode.CircularDependency, `Circular dependency: ${formatPath(path)}`, {\n hints: [\n 'Inject one of these dependencies as Lazy<T> and call get() when needed',\n `Tokens: ${path.slice(0, -1).join(', ')}`,\n ],\n })\n}\n\n/** Whether resolving `slot` requires an active request scope. */\nfunction requiresScope(slot: Slot): boolean {\n if (slot.isProvider) return slot.needsScope\n return slot.mode === UNBOUND && slot.external?.scope === 'request'\n}\n\n/**\n * Computes `needsScope` and `waits` (singletons to wait for, through transients) for every slot of\n * `order` (dependencies first).\n *\n * @throws ZnightError (ZNIGHT003) when a singleton depends on request-scoped state.\n */\nexport function analyseScopes(order: readonly Slot[]): void {\n for (const slot of order) {\n let needsScope = slot.mode === REQUEST\n let waits: Set<Slot> | undefined\n for (const dep of slot.edges) {\n if (requiresScope(dep)) {\n if (slot.mode === SINGLETON) throw scopeMismatchError(slot, dep)\n needsScope = true\n }\n if (dep.mode === SINGLETON) {\n waits ??= new Set()\n waits.add(dep)\n } else if (dep.mode === TRANSIENT && dep.waits.length > 0) {\n waits ??= new Set()\n for (const wait of dep.waits) waits.add(wait)\n }\n }\n slot.needsScope = needsScope\n slot.waits = waits === undefined ? [] : [...waits]\n }\n}\n\nfunction scopeMismatchError(singleton: Slot, dep: Slot): ZnightError {\n const path = [singleton.token]\n let current: Slot | undefined = dep\n while (current !== undefined && !path.includes(current.token)) {\n path.push(current.token)\n if (current.mode !== TRANSIENT) break\n current = current.edges.find(requiresScope)\n }\n const target = path[path.length - 1] as Token\n return new ZnightError(\n ErrorCode.ScopeMismatch,\n `Scope mismatch: singleton ${singleton.displayName} depends on request-scoped ${describeToken(target)} (${formatPath(path)})`,\n {\n hints: [\n `Inject it as Lazy<T> and call get() inside the request, or make ${singleton.displayName} request-scoped`,\n ],\n },\n )\n}\n\n/** Every slot reachable from `roots` through hard and lazy edges (roots included). */\nexport function closureOf(roots: Iterable<Slot>): Set<Slot> {\n const seen = new Set<Slot>()\n const queue = [...roots]\n for (let index = 0; index < queue.length; index++) {\n const slot = queue[index] as Slot\n if (seen.has(slot)) continue\n seen.add(slot)\n for (const edge of slot.edges) if (!seen.has(edge)) queue.push(edge)\n for (const edge of slot.lazyEdges) if (!seen.has(edge)) queue.push(edge)\n }\n return seen\n}\n\n/** Whether `slot` cannot be resolved at all (unbound and not satisfiable from a scope or as optional). */\nexport function isMissing(slot: Slot): boolean {\n return slot.mode === UNBOUND && !slot.isSatisfiedExternally\n}\n\n/** Missing required dependencies of `slots`, with the providers requiring them (in encounter order). */\nexport function findMissing(slots: Iterable<Slot>): Map<Slot, Slot[]> {\n const missing = new Map<Slot, Slot[]>()\n const record = (target: Slot, dependent: Slot): void => {\n if (!isMissing(target)) return\n const dependents = missing.get(target)\n if (dependents === undefined) missing.set(target, [dependent])\n else if (!dependents.includes(dependent)) dependents.push(dependent)\n }\n for (const slot of slots) {\n if (slot.plan === undefined) continue\n for (const dep of slot.plan) {\n if (dep.kind === DEP_REQUIRED || dep.kind === DEP_LAZY) record(dep.slot as Slot, slot)\n else if (dep.kind === DEP_MULTI) for (const target of dep.slots as readonly Slot[]) record(target, slot)\n }\n }\n return missing\n}\n\n/** ZNIGHT001 listing every missing dependency, its dependents and the plugin expected to provide it. */\nexport function missingProvidersError(missing: ReadonlyMap<Slot, readonly Slot[]>): ZnightError {\n const lines: string[] = []\n const plugins = new Set<string>()\n for (const [slot, dependents] of missing) {\n let line = ` - ${describeToken(slot.token)}`\n const providedBy = slot.external?.providedBy\n if (providedBy !== undefined) {\n line += `, provided by ${providedBy}`\n plugins.add(providedBy)\n }\n line +=\n dependents.length === 0\n ? ', requested by init({ only })'\n : `, required by ${dependents.map(dependent => dependent.displayName).join(', ')}`\n lines.push(line)\n }\n const count = missing.size\n const hints = [...plugins].map(plugin => `Add ${plugin} to Application.create({ plugins })`)\n hints.push('Supply values with Application.create({ providers }) or container.registerValue()')\n return new ZnightError(\n ErrorCode.MissingProvider,\n `${count === 1 ? 'A required provider is' : `${count} required providers are`} missing:\\n${lines.join('\\n')}`,\n { hints },\n )\n}\n\n/**\n * A dependency path ending with `target`, starting from a provider nothing depends on (used to\n * explain why `target` was instantiated).\n */\nexport function dependentPath(target: Slot, providers: Iterable<Slot>): Token[] {\n const dependents = new Map<Slot, Slot>()\n for (const slot of providers) {\n for (const edge of slot.edges) if (!dependents.has(edge)) dependents.set(edge, slot)\n }\n const path: Slot[] = [target]\n let current = dependents.get(target)\n while (current !== undefined && !path.includes(current)) {\n path.unshift(current)\n current = dependents.get(current)\n }\n return path.map(slot => slot.token)\n}\n\nfunction safeJson(value: unknown): string {\n try {\n return JSON.stringify(value) ?? String(value)\n } catch {\n return String(value)\n }\n}\n","import type { LifecycleHook } from './metadata.ts'\n\nimport { ErrorCode, ZnightError } from './errors.ts'\n\n/**\n * Called by `app.start()` on every instantiated singleton, in resolution order (dependencies\n * first), before plugins start accepting traffic.\n */\nexport interface OnStart {\n onStart(): void | Promise<void>\n}\n\n/** Called by `app.start()` once every provider and plugin has started. */\nexport interface OnReady {\n onReady(): void | Promise<void>\n}\n\n/**\n * Called by `app.stop()` on every started singleton, in reverse resolution order, after plugins\n * stopped accepting traffic. Pairs with {@link OnStart}: resources acquired in a constructor or a\n * factory should be released by a dispose method (`@Provides({ dispose })`) or\n * `[Symbol.asyncDispose]()`, which run even when the application was never started.\n */\nexport interface OnStop {\n onStop(): void | Promise<void>\n}\n\ntype Callable = (this: unknown) => unknown\n\nfunction methodOf(instance: unknown, key: PropertyKey): Callable | undefined {\n if (instance === null || (typeof instance !== 'object' && typeof instance !== 'function')) return undefined\n const value: unknown = (instance as Record<PropertyKey, unknown>)[key]\n return typeof value === 'function' ? (value as Callable) : undefined\n}\n\n/** Whether `instance` implements `hook` (duck typing: a method with that name exists). */\nexport function hasLifecycleHook(instance: unknown, hook: LifecycleHook): boolean {\n return methodOf(instance, hook) !== undefined\n}\n\n/** Calls `hook` on `instance` when it implements it. Returns what the hook returned (or `undefined`). */\nexport function callLifecycleHook(instance: unknown, hook: LifecycleHook): unknown {\n const method = methodOf(instance, hook)\n return method === undefined ? undefined : method.call(instance)\n}\n\n/**\n * Whether {@link disposeInstance} has something to call: the `disposeMethod` when given, otherwise\n * `[Symbol.asyncDispose]` or `[Symbol.dispose]`.\n */\nexport function isDisposable(instance: unknown, disposeMethod?: string): boolean {\n if (disposeMethod !== undefined) return true\n return methodOf(instance, Symbol.asyncDispose) !== undefined || methodOf(instance, Symbol.dispose) !== undefined\n}\n\n/**\n * Releases `instance`: calls `disposeMethod` when given (`@Provides({ dispose: 'end' })`), otherwise\n * `[Symbol.asyncDispose]()`, otherwise `[Symbol.dispose]()`. Only the first applicable one is called.\n *\n * @throws ZnightError (ZNIGHT021) when `disposeMethod` is not a method of `instance`.\n */\nexport function disposeInstance(instance: unknown, disposeMethod?: string): unknown {\n if (disposeMethod !== undefined) {\n const method = methodOf(instance, disposeMethod)\n if (method === undefined) {\n throw new ZnightError(\n ErrorCode.LifecycleFailed,\n `Cannot dispose ${describeInstance(instance)}: it has no method \"${disposeMethod}\"`,\n { hints: ['Check the `dispose` option of the provider (@Provides({ dispose }))'] },\n )\n }\n return method.call(instance)\n }\n const asyncDispose = methodOf(instance, Symbol.asyncDispose)\n if (asyncDispose !== undefined) return asyncDispose.call(instance)\n const dispose = methodOf(instance, Symbol.dispose)\n if (dispose !== undefined) return dispose.call(instance)\n return undefined\n}\n\nfunction describeInstance(instance: unknown): string {\n if (instance === null || instance === undefined) return String(instance)\n const name = (instance as { constructor?: { name?: unknown } }).constructor?.name\n return typeof name === 'string' && name !== '' ? `an instance of ${name}` : `a ${typeof instance}`\n}\n","/**\n * Runtime metadata contract.\n *\n * `@znight/compiler` analyzes the application at build time and generates a module exporting a\n * {@link ZnightMetadata} object (`__ZNIGHT_METADATA__`). The runtime (container, plugins) only ever\n * consumes this object: there is no reflection and no decorator metadata at runtime.\n *\n * This file is the single source of truth shared by the compiler (which emits code matching these\n * types) and every runtime package. See docs/internals/architecture.md §3. Any field whose absence\n * changes runtime behaviour requires bumping {@link METADATA_VERSION}.\n */\n\n/** Version of the metadata format produced by the compiler and accepted by the runtime. */\nexport const METADATA_VERSION = 1\n\n/**\n * Unique, stable identifier of a provider: the canonical identity of the declaration that defines it.\n *\n * - application class: `src/users/user.service.ts#UserService`\n * - package export: `@acme/auth#JwtService`, `@znight/observability#Logger`\n * - `@Provides` method: `src/db/db.factory.ts#DbFactory.createPool`\n */\nexport type Token = string\n\n/**\n * Lifetime of a provider instance.\n * - `singleton`: one instance for the whole application (default)\n * - `request`: one instance per scope (see `Container.runInScope`)\n * - `transient`: a new instance every time it is injected or resolved\n */\nexport type Scope = 'singleton' | 'request' | 'transient'\n\n/** Lifecycle hooks a singleton may implement (detected at runtime by duck typing). */\nexport type LifecycleHook = 'onStart' | 'onReady' | 'onStop'\n\n/**\n * A dependency in a provider's `deps` list:\n * - `Token`: required dependency\n * - `{ token, optional: true }`: `undefined` when no provider/value exists\n * - `{ multi: [...] }`: array of instances, in the given order\n * - `{ lazy: token }`: a {@link Lazy} handle resolved at call time in the current scope\n */\nexport type DependencyRef =\n | Token\n | { readonly token: Token; readonly optional: true }\n | { readonly multi: readonly Token[] }\n | { readonly lazy: Token }\n\n/** Handle injected for `Lazy<T>` parameters: resolves the dependency when `get()` is called. */\nexport interface Lazy<T> {\n get(): T\n}\n\n/**\n * Factory generated by the compiler. Receives resolved dependencies in the same order as\n * {@link ProviderDefinition.deps}.\n */\n// biome-ignore lint/suspicious/noExplicitAny: generated factories receive heterogeneously typed dependencies\nexport type ProviderFactory<T = unknown> = (deps: any[]) => T | Promise<T>\n\n/** Location of a declaration in the user's source code (path relative to the project root, 1-based). */\nexport interface SourceLocation {\n readonly file: string\n readonly line: number\n readonly column: number\n}\n\n/** One interceptor applied to a method: `dep` is an index in {@link ProviderDefinition.deps}. */\nexport interface InterceptorBinding {\n readonly dep: number\n readonly options?: unknown\n}\n\n/** Interceptor chain of a method. The first binding is the outermost interceptor. */\nexport interface MethodInterception {\n /** Whether the intercepted method is async (`async` keyword or `Promise` return type). */\n readonly async: boolean\n readonly chain: readonly InterceptorBinding[]\n}\n\n/** Constructor of a provider class (abstract classes allowed for typing purposes). */\nexport type ProviderClass<T = unknown> = abstract new (...args: never[]) => T\n\n/** Runtime definition of a single provider. */\nexport interface ProviderDefinition<T = unknown> {\n readonly scope: Scope\n /** Class reference, when the provider is a class. Enables `container.get(MyClass)`. */\n readonly class?: ProviderClass<T>\n /** Dependencies passed positionally to {@link factory}. */\n readonly deps: readonly DependencyRef[]\n readonly factory: ProviderFactory<T>\n /** `true` when the factory returns a promise. Only allowed for singletons. */\n readonly async?: boolean\n /** Method interceptors (AOP), applied by the container right after {@link factory}. */\n readonly interceptors?: Readonly<Record<string, MethodInterception>>\n /** Name of a method to call on shutdown, for objects without `onStop`/`Symbol.asyncDispose`. */\n readonly dispose?: string\n /** Qualifier set with `@Named()`. */\n readonly name?: string\n /** Set with `@Primary()`. */\n readonly primary?: boolean\n readonly source?: SourceLocation\n}\n\n/**\n * A token the compiled code depends on but that is supplied at runtime (by a plugin through\n * `container.registerValue()` / `container.register()`, or by `Application.create({ providers })`).\n */\nexport interface ExternalDefinition {\n readonly token: Token\n /** Scope of the supplied value. Request-scoped externals are read from the active scope. Default: singleton. */\n readonly scope?: Scope\n /** Name of the plugin expected to provide it (used in error messages). */\n readonly providedBy?: string\n readonly optional?: boolean\n}\n\n/**\n * Feature-specific metadata (HTTP routes, message consumers, config classes...).\n * Packages augment this interface with their own key:\n *\n * ```ts\n * declare module '@znight/core' {\n * interface ZnightExtensionsMetadata { http?: HttpMetadata }\n * }\n * ```\n */\nexport interface ZnightExtensionsMetadata {\n readonly [extension: string]: unknown\n}\n\n/** The complete metadata generated by `@znight/compiler`. */\nexport interface ZnightMetadata {\n /** Format version of this object, see {@link METADATA_VERSION}. */\n readonly version: number\n /** Version of `@znight/compiler` that generated this object. */\n readonly compiler?: string\n readonly providers: Readonly<Record<Token, ProviderDefinition>>\n /** Every provider token, topologically sorted: dependencies always come before their dependents. */\n readonly resolutionOrder: readonly Token[]\n /** Alternative tokens (provided types, interfaces, base classes) pointing to a provider token. */\n readonly aliases?: Readonly<Record<Token, Token>>\n readonly externals?: readonly ExternalDefinition[]\n readonly extensions?: ZnightExtensionsMetadata\n}\n","import type { SourceLocation, Token } from './metadata.ts'\n\nimport { type ErrorCode, ErrorCode as ErrorCodes, ZnightError, type ZnightErrorOptions } from './errors.ts'\nimport { displayName, formatPath } from './tokens.ts'\nimport { errorMessage } from './utils.ts'\n\n/**\n * ZNIGHT015: a provider factory threw or rejected.\n *\n * Carries the failing token, the dependency path that led to it (outermost first, the failing token\n * last), the source location of the provider when the metadata includes it, and the original error\n * as `cause`.\n */\nexport class InstantiationError extends ZnightError {\n /** Token of the provider whose factory failed. */\n readonly token: Token\n /** Dependency path from the outermost dependent to {@link token} (inclusive). */\n readonly path: readonly Token[]\n /** Location of the provider declaration, when known. */\n readonly source: SourceLocation | undefined\n\n constructor(token: Token, path: readonly Token[], cause: unknown, source?: SourceLocation) {\n const lines = [`Failed to instantiate ${displayName(token)}: ${errorMessage(cause)}`, ` token: ${token}`]\n if (source !== undefined) lines.push(` at: ${source.file}:${source.line}:${source.column}`)\n if (path.length > 1) lines.push(` dependency path: ${formatPath(path)}`)\n super(ErrorCodes.InstantiationFailed, lines.join('\\n'), { cause })\n this.token = token\n this.path = path\n this.source = source\n }\n\n /** A copy of this error whose path is prefixed with `parents` (used while unwinding a resolution). */\n withParents(parents: readonly Token[]): InstantiationError {\n if (parents.length === 0) return this\n const error = new InstantiationError(this.token, [...parents, ...this.path], this.cause, this.source)\n const suppressed = getSuppressedErrors(this)\n if (suppressed.length > 0) addSuppressedErrors(error, suppressed)\n return error\n }\n}\n\n/**\n * A {@link ZnightError} grouping several failures (e.g. every shutdown step that failed). Exposes\n * `errors` like the standard `AggregateError`, while keeping a Znight `code`.\n */\nexport class ZnightAggregateError extends ZnightError {\n readonly errors: readonly unknown[]\n\n constructor(code: ErrorCode, message: string, errors: readonly unknown[], options: ZnightErrorOptions = {}) {\n const details = errors.map((error, index) => ` ${index + 1}. ${errorMessage(error)}`)\n super(code, [message, ...details].join('\\n'), options)\n this.errors = errors\n }\n}\n\nconst SUPPRESSED = 'suppressed'\n\n/**\n * Errors that happened while handling `error` (rollback/cleanup failures, concurrent failures) and\n * that were attached to it instead of being thrown. Empty when there are none.\n */\nexport function getSuppressedErrors(error: unknown): readonly unknown[] {\n if (error === null || (typeof error !== 'object' && typeof error !== 'function')) return []\n const value: unknown = Object.hasOwn(error, SUPPRESSED) ? (error as Record<string, unknown>)[SUPPRESSED] : undefined\n return Array.isArray(value) ? value : []\n}\n\n/** Attaches `errors` to `error` (see {@link getSuppressedErrors}). Primitives cannot carry them. */\nexport function addSuppressedErrors(error: unknown, errors: readonly unknown[]): void {\n if (errors.length === 0) return\n if (error === null || (typeof error !== 'object' && typeof error !== 'function')) return\n const all = [...getSuppressedErrors(error), ...errors]\n try {\n Object.defineProperty(error, SUPPRESSED, { value: all, enumerable: true, configurable: true, writable: true })\n } catch {\n // frozen or exotic error objects cannot carry the extra information: nothing else to do\n }\n}\n\n/** Wraps a non-Znight error into a ZNIGHT021 error mentioning `step`; Znight errors are returned as is. */\nexport function lifecycleError(step: string, error: unknown): ZnightError {\n if (error instanceof ZnightError) return error\n return new ZnightError(ErrorCodes.LifecycleFailed, `${step} failed: ${errorMessage(error)}`, { cause: error })\n}\n","import type { Token } from './metadata.ts'\nimport type { ProviderKey } from './tokens.ts'\n\n/**\n * The values of the active request scope (see `Container.runInScope`). Keys are tokens (aliases and\n * classes known to the container are accepted and normalised). Holds the seed values passed to\n * `runInScope` and the request-scoped instances created in the scope.\n */\nexport interface ScopeContext {\n /** The value stored for `key` in this scope, without creating anything. */\n get<T = unknown>(key: ProviderKey<T>): T | undefined\n /** Whether a value is stored for `key` in this scope. */\n has(key: ProviderKey): boolean\n /** Stores a value for `key`: request-scoped resolutions of `key` return it from now on. */\n set<T>(key: ProviderKey<T>, value: T): void\n /** `true` once the `runInScope` callback has settled and the scope instances were disposed. */\n readonly closed: boolean\n}\n\n/** A request-scoped instance created by the container, disposed when its scope closes. */\nexport interface ScopedInstance {\n readonly token: Token\n readonly instance: unknown\n readonly dispose: string | undefined\n}\n\n/** Implementation of {@link ScopeContext} used by the container (internal). */\nexport class RequestScope implements ScopeContext {\n readonly created: ScopedInstance[] = []\n closed = false\n readonly #canonical: (key: ProviderKey) => Token\n #values: Map<Token, unknown> | undefined\n /** Seed values not yet in {@link values}: canonical tokens and values, alternately. */\n #seeds: readonly unknown[] | undefined\n\n /** `seeds`: canonical tokens and their values, alternately (copied into {@link values} on first use). */\n constructor(canonical: (key: ProviderKey) => Token, seeds?: readonly unknown[]) {\n this.#canonical = canonical\n this.#seeds = seeds\n }\n\n /** The values of the scope by canonical token: the seeds, then what was set or created in it. */\n get values(): Map<Token, unknown> {\n let values = this.#values\n if (values === undefined) {\n values = new Map()\n const seeds = this.#seeds\n if (seeds !== undefined) {\n for (let index = 0; index < seeds.length; index += 2) values.set(seeds[index] as Token, seeds[index + 1])\n this.#seeds = undefined\n }\n this.#values = values\n }\n return values\n }\n\n get<T = unknown>(key: ProviderKey<T>): T | undefined {\n return this.values.get(this.#canonical(key)) as T | undefined\n }\n\n has(key: ProviderKey): boolean {\n return this.values.has(this.#canonical(key))\n }\n\n set<T>(key: ProviderKey<T>, value: T): void {\n this.values.set(this.#canonical(key), value)\n }\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\n\nimport { applyInterceptors } from './aop.ts'\nimport {\n ambiguousNameError,\n asyncOnDemandError,\n closedScopeError,\n compiledProviderError,\n duplicateRegistrationError,\n failedProviderError,\n invalidMetadataError,\n metadataVersionError,\n missingScopeValueError,\n noScopeError,\n notFoundError,\n notReadyError,\n reentrantCreationError,\n sealedError,\n unavailableError,\n unknownClassError,\n} from './container-errors.ts'\nimport { isProviderDefinition, validateDefinition } from './definition.ts'\nimport { ErrorCode, ZnightError } from './errors.ts'\nimport {\n analyseScopes,\n buildPlan,\n closureOf,\n computeOrder,\n dependentPath,\n findMissing,\n isMissing,\n missingProvidersError,\n} from './graph.ts'\nimport { disposeInstance } from './lifecycle.ts'\nimport {\n type ExternalDefinition,\n type Lazy,\n METADATA_VERSION,\n type ProviderClass,\n type ProviderDefinition,\n type Token,\n type ZnightMetadata,\n} from './metadata.ts'\nimport { addSuppressedErrors, InstantiationError, lifecycleError, ZnightAggregateError } from './runtime-errors.ts'\nimport { RequestScope, type ScopeContext, type ScopedInstance } from './scope.ts'\nimport {\n CREATING,\n DEP_LAZY,\n DEP_MULTI,\n DEP_OPTIONAL,\n DEP_REQUIRED,\n type DepPlan,\n DISPOSED,\n FAILED,\n IDLE,\n LEVEL_APPLICATION,\n LEVEL_BUILTIN,\n LEVEL_COMPILED,\n LEVEL_OVERRIDE,\n LEVEL_PLUGIN,\n modeOf,\n PENDING,\n READY,\n REQUEST,\n SINGLETON,\n Slot,\n TRANSIENT,\n UNBOUND,\n VALUE,\n} from './slot.ts'\nimport { type ClassKey, CoreTokens, displayName, type ProviderKey, type TypedToken } from './tokens.ts'\nimport { errorMessage, isThenable } from './utils.ts'\n\n/** Options of {@link Container.init}. */\nexport interface InitOptions {\n /**\n * Instantiate only these providers and their dependency closure. Other singletons are created on\n * first use (synchronously; async factories must be part of the closure).\n */\n readonly only?: readonly ProviderKey[]\n}\n\n/** An instantiated singleton managed by the container (see {@link Container.instances}). */\nexport interface ManagedInstance {\n readonly token: Token\n readonly displayName: string\n readonly instance: unknown\n readonly definition: ProviderDefinition\n /** Disposes the instance once (dispose method, `Symbol.asyncDispose` or `Symbol.dispose`). */\n dispose(): Promise<void>\n}\n\n/** Seed values of a request scope: token-keyed pairs (aliases and known classes are accepted). */\nexport type ScopeValues = Iterable<readonly [ProviderKey, unknown]>\n\n/**\n * A request scope opened with {@link Container.openScope}: its owner runs code in it with\n * {@link OpenedScope.run} and ends it with {@link OpenedScope.close}. The callback-free form of\n * {@link Container.runInScope}, for hot paths that stay synchronous as long as their work is (the\n * HTTP pipeline): no promise is created unless something is asynchronous.\n */\nexport interface OpenedScope {\n /** The values of the scope (what `currentScope()` returns in {@link run}). */\n readonly context: ScopeContext\n /**\n * Calls `fn(...args)` in the scope and returns its result. The code it runs and the asynchronous\n * continuations it creates (awaits, promise callbacks, timers) see the scope, like the callback\n * of `runInScope`. May be called several times until the scope is closed.\n */\n run<A extends readonly unknown[], R>(fn: (...args: A) => R, ...args: A): R\n /**\n * Closes the scope (a later resolution of a request-scoped provider in it throws ZNIGHT013) and\n * disposes the instances created in it, in reverse creation order. Returns `undefined` when no\n * instance was created (nothing to wait for), otherwise a promise rejecting with ZNIGHT021 when a\n * disposal fails. Idempotent: later calls return the first result.\n */\n close(): Promise<void> | undefined\n}\n\ntype Status = 'open' | 'initializing' | 'ready' | 'failed' | 'disposed'\n\ninterface InitRun {\n failed: boolean\n readonly errors: unknown[]\n readonly inflight: Promise<void>[]\n}\n\ninterface ContainerInternals {\n bindBuiltin(container: Container, token: Token, value: unknown, cls?: object): void\n setOrigin(container: Container, origin: string | undefined): void\n}\n\nlet internals: ContainerInternals\n\n/**\n * The dependency injection container. It consumes the metadata generated by `@znight/compiler`:\n * no reflection happens at runtime, factories are called in a precomputed order and resolving a\n * singleton is a single `Map` lookup.\n *\n * ```ts\n * const container = Container.create(__ZNIGHT_METADATA__)\n * container.registerValue('@acme/clock#Clock', systemClock)\n * await container.init()\n * const users = container.get(UserService)\n * ```\n *\n * Precedence of bindings: `override()` > plugin `register()`/`registerValue()` >\n * `Application.create({ providers })` (`provide()`) > compiled providers. Registrations are only\n * possible before `init()` (ZNIGHT016).\n */\nexport class Container {\n /** The metadata this container was created from. */\n readonly metadata: ZnightMetadata\n /** Canonical slots, in insertion order (compiled providers first). */\n readonly #slots = new Map<Token, Slot>()\n /** Every lookup key (tokens, aliases, classes, cached display names) → slot. */\n readonly #lookup = new Map<unknown, Slot>()\n /** Alias token → canonical slot (used to index alias display names). */\n readonly #aliases = new Map<Token, Slot>()\n readonly #storage = new AsyncLocalStorage<RequestScope>()\n /** Instantiated singletons, in creation order. */\n readonly #created: Slot[] = []\n #order: readonly Slot[] = []\n #names: Map<string, Slot[]> | undefined\n #status: Status = 'open'\n #sealed = false\n #planned = false\n // biome-ignore lint/style/useReadonlyClassProperties: assigned through the internals accessor (static block)\n #origin: string | undefined\n #initPromise: Promise<void> | undefined\n #disposePromise: Promise<void> | undefined\n\n static {\n internals = {\n bindBuiltin: (container, token, value, cls) => container.#bindBuiltin(token, value, cls),\n setOrigin: (container, origin) => {\n container.#origin = origin\n },\n }\n }\n\n private constructor(metadata: ZnightMetadata) {\n this.metadata = metadata\n for (const [token, definition] of Object.entries(metadata.providers)) {\n validateDefinition(token, definition)\n const slot = this.#slot(token)\n slot.compiled = true\n slot.compiledSource = definition.source\n this.#applyDefinition(slot, definition, LEVEL_COMPILED, 'the compiled metadata')\n }\n if (metadata.aliases !== undefined) this.#indexAliases(metadata.aliases)\n for (const external of metadata.externals ?? []) this.#declareExternal(external)\n this.#bindBuiltin(CoreTokens.Container, this, Container)\n }\n\n /**\n * Creates a container from compiled metadata.\n *\n * @throws ZnightError (ZNIGHT018) when the metadata format version is not supported.\n */\n static create(metadata: ZnightMetadata): Container {\n if (\n metadata === null ||\n typeof metadata !== 'object' ||\n metadata.providers === null ||\n typeof metadata.providers !== 'object' ||\n !Array.isArray(metadata.resolutionOrder)\n ) {\n throw invalidMetadataError()\n }\n if (metadata.version !== METADATA_VERSION) throw metadataVersionError(metadata, METADATA_VERSION)\n return new Container(metadata)\n }\n\n // ---------------------------------------------------------------------------------------------\n // Registration\n // ---------------------------------------------------------------------------------------------\n\n /**\n * Registers a runtime provider definition (plugin precedence). It may depend on compiled tokens.\n *\n * @throws ZnightError ZNIGHT016 after `init()`, ZNIGHT004 when the token is a compiled provider or\n * is already registered, ZNIGHT005/ZNIGHT014 for an invalid definition.\n */\n register<T>(token: TypedToken<T>, definition: ProviderDefinition<NoInfer<T>>): void {\n this.#assertOpen('register', token)\n validateDefinition(token, definition)\n this.#bind(token, LEVEL_PLUGIN, 'register', (slot, origin) =>\n this.#applyDefinition(slot, definition, LEVEL_PLUGIN, origin),\n )\n }\n\n /**\n * Registers a value (plugin precedence), typically for an external declared in the metadata.\n * Ignored when the token is overridden.\n *\n * @throws ZnightError ZNIGHT016 after `init()`, ZNIGHT004 when the token is a compiled provider or\n * is already registered.\n */\n registerValue<T>(token: TypedToken<T>, value: NoInfer<T>): void {\n this.#bind(token, LEVEL_PLUGIN, 'register a value for', (slot, origin) =>\n this.#applyValue(slot, value, LEVEL_PLUGIN, origin),\n )\n }\n\n /**\n * Declares an external token supplied at runtime (like `metadata.externals`). A request-scoped\n * external is read from the active scope (`runInScope` seed values).\n */\n registerExternal(external: ExternalDefinition): void {\n this.#assertOpen('declare the external', external.token)\n this.#declareExternal(external)\n }\n\n /**\n * Supplies a value with application precedence (`Application.create({ providers })`): replaces a\n * compiled provider, is superseded by plugin registrations and overrides.\n */\n provide<T>(key: ProviderKey<T>, value: NoInfer<T>): void {\n this.#bind(key, LEVEL_APPLICATION, 'provide', (slot, origin) =>\n this.#applyValue(slot, value, LEVEL_APPLICATION, origin),\n )\n }\n\n /**\n * Replaces a provider (highest precedence, typically in tests). `key` may be a token, an alias or\n * a class (aliases are resolved first). `valueOrDefinition` is used as a provider definition when\n * it has the shape of one (`{ scope, deps, factory }`), as a value otherwise.\n */\n override<T>(key: ProviderKey<T>, valueOrDefinition: NoInfer<T> | ProviderDefinition<NoInfer<T>>): void {\n this.#bind(key, LEVEL_OVERRIDE, 'override', (slot, origin) => {\n if (isProviderDefinition(valueOrDefinition)) {\n validateDefinition(slot.token, valueOrDefinition)\n this.#applyDefinition(slot, valueOrDefinition, LEVEL_OVERRIDE, origin)\n } else {\n this.#applyValue(slot, valueOrDefinition, LEVEL_OVERRIDE, origin)\n }\n })\n }\n\n // ---------------------------------------------------------------------------------------------\n // Initialisation\n // ---------------------------------------------------------------------------------------------\n\n /**\n * Seals the container, validates the merged graph (missing providers ZNIGHT001, cycles ZNIGHT002,\n * scope mismatches ZNIGHT003) and instantiates singletons. A factory starts as soon as its\n * dependencies are ready, so independent async singletons are created concurrently. On failure,\n * created instances are disposed in reverse creation order and the first error is rethrown\n * (ZNIGHT015 for factory errors, with other failures attached, see `getSuppressedErrors`).\n *\n * Calling `init()` again returns the promise of the first call.\n */\n init(options: InitOptions = {}): Promise<void> {\n if (this.#initPromise !== undefined) return this.#initPromise\n if (this.#disposePromise !== undefined) {\n return Promise.reject(\n new ZnightError(ErrorCode.InstantiationFailed, 'Cannot initialise a container that has been disposed'),\n )\n }\n this.#sealed = true\n this.#status = 'initializing'\n this.#initPromise = this.#initialize(options)\n return this.#initPromise\n }\n\n async #initialize(options: InitOptions): Promise<void> {\n try {\n const roots = options.only?.map(key => this.#rootSlot(key))\n const lookup = (token: Token): Slot => this.#lookup.get(token) ?? this.#slot(token)\n for (const slot of [...this.#slots.values()]) if (slot.isProvider) buildPlan(slot, lookup)\n const order = computeOrder(this.#baseOrder())\n analyseScopes(order)\n this.#order = order\n this.#planned = true\n\n const closure = roots === undefined ? undefined : closureOf(roots)\n const missing = findMissing(closure ?? order)\n for (const root of roots ?? []) if (isMissing(root) && !missing.has(root)) missing.set(root, [])\n if (missing.size > 0) throw missingProvidersError(missing)\n\n const singletons = order.filter(slot => slot.mode === SINGLETON && (closure === undefined || closure.has(slot)))\n await this.#instantiate(singletons)\n this.#status = 'ready'\n } catch (error) {\n this.#status = 'failed'\n throw error\n }\n }\n\n *#baseOrder(): Iterable<Slot> {\n for (const token of this.metadata.resolutionOrder) {\n const slot = this.#slots.get(token)\n if (slot !== undefined) yield slot\n }\n yield* this.#slots.values()\n }\n\n async #instantiate(singletons: readonly Slot[]): Promise<void> {\n const run: InitRun = { failed: false, errors: [], inflight: [] }\n for (const slot of singletons) {\n if (run.failed) break\n if (slot.state === IDLE) this.#schedule(slot, run)\n }\n await Promise.all(run.inflight)\n if (!run.failed) return\n const cleanup = await this.#rollback()\n const [first, ...others] = run.errors\n addSuppressedErrors(first, [...others, ...cleanup])\n throw first\n }\n\n /** Starts `slot` now, or as soon as the singletons it waits for are ready. */\n #schedule(slot: Slot, run: InitRun): void {\n const waits: Promise<void>[] = []\n for (const dep of slot.waits) {\n // not reachable with a topological order: schedule the dependency first rather than fail obscurely\n if (dep.state === IDLE) this.#schedule(dep, run)\n const state: number = dep.state\n if (state === READY) continue\n if (state !== PENDING || dep.promise === undefined) return // a dependency failed: the run is failing\n waits.push(dep.promise)\n }\n if (waits.length === 0) {\n const promise = this.#start(slot, run)\n if (promise !== undefined) run.inflight.push(promise)\n return\n }\n slot.state = PENDING\n const promise = Promise.all(waits).then(() => {\n slot.state = IDLE\n return run.failed ? undefined : this.#start(slot, run)\n })\n slot.promise = promise\n run.inflight.push(promise)\n }\n\n /** Calls the factory of a singleton during `init()`. Never throws: failures are recorded in `run`. */\n #start(slot: Slot, run: InitRun): Promise<void> | undefined {\n const definition = slot.definition as ProviderDefinition\n slot.state = CREATING\n let deps: unknown[]\n let result: unknown\n try {\n deps = this.#resolveDeps(slot)\n } catch (error) {\n this.#fail(slot, this.#initError(slot, error, false), run)\n return undefined\n }\n try {\n result = definition.factory(deps)\n } catch (error) {\n this.#fail(slot, this.#initError(slot, error, true), run)\n return undefined\n }\n if (!isThenable(result)) {\n this.#complete(slot, result, deps, run)\n return undefined\n }\n slot.state = PENDING\n const promise = Promise.resolve(result).then(\n instance => this.#complete(slot, instance, deps, run),\n (error: unknown) => this.#fail(slot, this.#initError(slot, error, true), run),\n )\n slot.promise = promise\n return promise\n }\n\n #complete(slot: Slot, instance: unknown, deps: readonly unknown[], run: InitRun): void {\n slot.instance = instance\n slot.state = READY\n slot.promise = undefined\n this.#created.push(slot)\n const interceptors = slot.definition?.interceptors\n if (interceptors === undefined) return\n try {\n applyInterceptors(instance as object, interceptors, deps, slot.displayName)\n } catch (error) {\n // the instance exists: it stays registered as created so the rollback disposes it\n run.failed = true\n run.errors.push(this.#initError(slot, error, true))\n }\n }\n\n #fail(slot: Slot, error: unknown, run: InitRun): void {\n slot.state = FAILED\n slot.promise = undefined\n run.failed = true\n run.errors.push(error)\n }\n\n #initError(slot: Slot, error: unknown, fromFactory: boolean): unknown {\n const path = dependentPath(slot, this.#order)\n if (fromFactory) return new InstantiationError(slot.token, path, error, slot.definition?.source)\n if (error instanceof InstantiationError) return error.withParents(path)\n return error\n }\n\n async #rollback(): Promise<unknown[]> {\n const errors: unknown[] = []\n for (let index = this.#created.length - 1; index >= 0; index--) {\n const slot = this.#created[index] as Slot\n try {\n const result = this.#disposeSlot(slot)\n if (result !== undefined) await result\n } catch (error) {\n errors.push(lifecycleError(`Disposing ${slot.displayName}`, error))\n }\n }\n return errors\n }\n\n // ---------------------------------------------------------------------------------------------\n // Resolution\n // ---------------------------------------------------------------------------------------------\n\n /**\n * Resolves a provider by class, token, alias or unique display name (`'UserService'`).\n *\n * @throws ZnightError ZNIGHT001 (no provider), ZNIGHT008 (ambiguous display name), ZNIGHT013\n * (request-scoped provider outside of a scope), ZNIGHT015 (factory failure or container not\n * initialised).\n */\n get<T>(key: ProviderClass<T>): T\n get<T>(key: ClassKey<T>): T\n get<T = unknown>(key: TypedToken<T>): T\n get(key: ProviderKey): unknown {\n const slot = this.#lookup.get(key)\n if (slot !== undefined && slot.state === READY) return slot.instance\n return this.#resolveKey(key, slot, false)\n }\n\n /** Like {@link get}, but returns `undefined` when no provider exists for `key`. */\n getOptional<T>(key: ProviderClass<T>): T | undefined\n getOptional<T>(key: ClassKey<T>): T | undefined\n getOptional<T = unknown>(key: TypedToken<T>): T | undefined\n getOptional(key: ProviderKey): unknown {\n const slot = this.#lookup.get(key)\n if (slot !== undefined && slot.state === READY) return slot.instance\n return this.#resolveKey(key, slot, true)\n }\n\n /**\n * Whether `key` can be resolved: a provider or value is bound to it, or the active scope holds a\n * value for it. An ambiguous display name returns `false`.\n */\n has(key: ProviderKey): boolean {\n const slot = this.#lookup.get(key) ?? this.#findByName(key, false)\n const scope = this.#storage.getStore()\n if (slot === undefined) return typeof key === 'string' && (scope?.values.has(key) ?? false)\n if (slot.mode !== UNBOUND) return true\n return scope?.values.has(slot.token) ?? false\n }\n\n /** Canonical token of a class (or alias / display name), `undefined` when unknown. */\n tokenOf(key: ProviderKey): Token | undefined {\n return (this.#lookup.get(key) ?? this.#findByName(key, false))?.token\n }\n\n /** Instantiated singletons (created by the container, not registered values), in resolution order. */\n instances(): ManagedInstance[] {\n const result: ManagedInstance[] = []\n for (const slot of this.#order) {\n if (slot.mode === SINGLETON && slot.state === READY) result.push(this.#managed(slot))\n }\n return result\n }\n\n #managed(slot: Slot): ManagedInstance {\n return {\n token: slot.token,\n displayName: slot.displayName,\n instance: slot.instance,\n definition: slot.definition as ProviderDefinition,\n dispose: async (): Promise<void> => {\n await this.#disposeSlot(slot)\n },\n }\n }\n\n #resolveKey(key: ProviderKey, found: Slot | undefined, optional: boolean): unknown {\n const slot = found ?? this.#findByName(key, true)\n if (slot !== undefined) return this.#resolve(slot, optional)\n if (typeof key === 'string') {\n const scope = this.#storage.getStore()\n if (scope?.values.has(key)) return scope.values.get(key)\n }\n if (optional) return undefined\n throw notFoundError(key)\n }\n\n #resolve(slot: Slot, optional: boolean): unknown {\n switch (slot.mode) {\n case VALUE:\n return slot.instance\n case SINGLETON:\n return slot.state === READY ? slot.instance : this.#createOnDemand(slot)\n case REQUEST:\n return this.#resolveRequest(slot)\n case TRANSIENT:\n this.#assertResolvable(slot)\n return this.#create(slot)\n default:\n return this.#resolveUnbound(slot, optional)\n }\n }\n\n #resolveDeps(slot: Slot): unknown[] {\n const plan = slot.plan as readonly DepPlan[]\n const deps = new Array<unknown>(plan.length)\n for (let index = 0; index < plan.length; index++) deps[index] = this.#resolveDep(plan[index] as DepPlan)\n return deps\n }\n\n #resolveDep(dep: DepPlan): unknown {\n switch (dep.kind) {\n case DEP_REQUIRED:\n return this.#resolve(dep.slot as Slot, false)\n case DEP_OPTIONAL:\n return this.#resolve(dep.slot as Slot, true)\n case DEP_MULTI:\n return (dep.slots as readonly Slot[]).map(target => this.#resolve(target, false))\n case DEP_LAZY:\n return this.#lazy(dep.slot as Slot)\n default:\n return undefined\n }\n }\n\n #lazy(slot: Slot): Lazy<unknown> {\n return { get: () => this.#resolve(slot, false) }\n }\n\n /** Instantiates a request-scoped or transient provider (synchronous factories only). */\n #create(slot: Slot): unknown {\n const definition = slot.definition as ProviderDefinition\n let deps: unknown[]\n try {\n deps = this.#resolveDeps(slot)\n } catch (error) {\n throw error instanceof InstantiationError ? error.withParents([slot.token]) : error\n }\n let instance: unknown\n try {\n instance = definition.factory(deps)\n } catch (error) {\n throw new InstantiationError(slot.token, [slot.token], error, definition.source)\n }\n if (definition.interceptors !== undefined) {\n try {\n applyInterceptors(instance as object, definition.interceptors, deps, slot.displayName)\n } catch (error) {\n throw new InstantiationError(slot.token, [slot.token], error, definition.source)\n }\n }\n return instance\n }\n\n #resolveRequest(slot: Slot): unknown {\n const scope = this.#storage.getStore()\n if (scope === undefined) throw noScopeError(slot)\n if (scope.closed) throw closedScopeError(slot)\n const values = scope.values\n const existing = values.get(slot.token)\n if (existing !== undefined || values.has(slot.token)) return existing\n this.#assertResolvable(slot)\n const instance = this.#create(slot)\n values.set(slot.token, instance)\n scope.created.push({ token: slot.token, instance, dispose: slot.definition?.dispose })\n return instance\n }\n\n #resolveUnbound(slot: Slot, optional: boolean): unknown {\n const scope = this.#storage.getStore()\n if (scope?.values.has(slot.token)) return scope.values.get(slot.token)\n const external = slot.external\n if (external?.scope === 'request') {\n if (scope === undefined) throw noScopeError(slot)\n if (optional || external.optional === true) return undefined\n throw missingScopeValueError(slot)\n }\n if (optional || external?.optional === true) return undefined\n throw notFoundError(slot.token, slot)\n }\n\n /**\n * Creates a singleton synchronously outside of the `init()` schedule (lazy access, `init({ only })`).\n * Like during `init()`, the factory runs outside of any request scope: a singleton belongs to the\n * application, so the timers, sockets and promises it creates must not capture the scope of the\n * request that happens to use it first.\n */\n #createOnDemand(slot: Slot): unknown {\n if (this.#storage.getStore() !== undefined) return this.#storage.exit(() => this.#createOnDemand(slot))\n switch (slot.state) {\n case CREATING:\n throw reentrantCreationError(slot)\n case PENDING:\n throw notReadyError(slot)\n case FAILED:\n throw failedProviderError(slot)\n case DISPOSED:\n throw unavailableError(slot, 'disposed')\n default:\n break\n }\n this.#assertResolvable(slot)\n for (const dep of slot.waits) if (dep.state !== READY) this.#createOnDemand(dep)\n const definition = slot.definition as ProviderDefinition\n if (definition.async === true) throw asyncOnDemandError(slot, true)\n slot.state = CREATING\n let deps: unknown[]\n let result: unknown\n try {\n deps = this.#resolveDeps(slot)\n } catch (error) {\n slot.state = IDLE\n throw error instanceof InstantiationError ? error.withParents([slot.token]) : error\n }\n try {\n result = definition.factory(deps)\n } catch (error) {\n slot.state = IDLE\n throw new InstantiationError(slot.token, [slot.token], error, definition.source)\n }\n if (isThenable(result)) {\n slot.state = IDLE\n // undeclared async factory: release whatever it produces, the caller gets an error\n Promise.resolve(result).then(\n instance => disposeQuietly(instance, definition.dispose),\n () => undefined,\n )\n throw asyncOnDemandError(slot, false)\n }\n if (definition.interceptors !== undefined) {\n try {\n applyInterceptors(result as object, definition.interceptors, deps, slot.displayName)\n } catch (error) {\n slot.state = IDLE\n disposeQuietly(result, definition.dispose)\n throw new InstantiationError(slot.token, [slot.token], error, definition.source)\n }\n }\n slot.instance = result\n slot.state = READY\n this.#created.push(slot)\n return result\n }\n\n #assertResolvable(slot: Slot): void {\n const status = this.#status\n if (status === 'ready' || (status === 'initializing' && this.#planned)) return\n throw unavailableError(slot, status === 'disposed' || status === 'failed' ? status : 'open')\n }\n\n // ---------------------------------------------------------------------------------------------\n // Request scope\n // ---------------------------------------------------------------------------------------------\n\n /**\n * Runs `fn` in a new request scope seeded with `values`. Request-scoped providers and\n * request-scoped externals resolved inside `fn` (including asynchronously) are bound to this\n * scope. When `fn` settles, the instances created in the scope are disposed in reverse creation\n * order. Scopes are isolated from each other (nested calls open a fresh scope).\n *\n * Rejects with the error of `fn` (disposal errors attached), or with ZNIGHT021 when only the\n * disposal failed.\n */\n async runInScope<R>(fn: () => R | Promise<R>, values?: ScopeValues): Promise<R> {\n const scope = new RequestScope(this.#canonical)\n if (values !== undefined) for (const [key, value] of values) scope.values.set(this.#canonical(key), value)\n let result: R\n try {\n result = await this.#storage.run(scope, fn)\n } catch (error) {\n addSuppressedErrors(error, await this.#closeScope(scope))\n throw error\n }\n if (scope.created.length === 0) {\n scope.closed = true\n return result\n }\n const errors = await this.#closeScope(scope)\n if (errors.length > 0) {\n throw new ZnightAggregateError(\n ErrorCode.LifecycleFailed,\n `Failed to dispose ${errors.length} request-scoped instance(s)`,\n errors,\n )\n }\n return result\n }\n\n /**\n * Opens a request scope seeded with `values`, like {@link runInScope}, but without running\n * anything: the caller runs code in it (`run`) and closes it (`close`) when the work it started\n * is over. Request-scoped providers resolved in it are disposed by `close`, which must be called.\n */\n openScope(values?: ScopeValues): OpenedScope {\n let seeds: unknown[] | undefined\n if (values !== undefined) {\n seeds = []\n for (const [key, value] of values) seeds.push(this.#canonical(key), value)\n }\n return new ScopeHandle(this.#storage, new RequestScope(this.#canonical, seeds), this.#closeScopeFn)\n }\n\n /** The active request scope, if any. */\n currentScope(): ScopeContext | undefined {\n return this.#storage.getStore()\n }\n\n readonly #closeScopeFn = (scope: RequestScope): Promise<unknown[]> => this.#closeScope(scope)\n\n async #closeScope(scope: RequestScope): Promise<unknown[]> {\n scope.closed = true\n const errors: unknown[] = []\n for (let index = scope.created.length - 1; index >= 0; index--) {\n const created = scope.created[index] as ScopedInstance\n try {\n const result = disposeInstance(created.instance, created.dispose)\n if (isThenable(result)) await result\n } catch (error) {\n errors.push(lifecycleError(`Disposing the request-scoped ${displayName(created.token)}`, error))\n }\n }\n return errors\n }\n\n readonly #canonical = (key: ProviderKey): Token => {\n const slot = this.#lookup.get(key) ?? this.#findByName(key, false)\n if (slot !== undefined) return slot.token\n if (typeof key === 'string') return key\n throw notFoundError(key)\n }\n\n // ---------------------------------------------------------------------------------------------\n // Disposal\n // ---------------------------------------------------------------------------------------------\n\n /**\n * Disposes every instantiated singleton in reverse resolution order (dispose method from the\n * definition, `Symbol.asyncDispose` or `Symbol.dispose`). Lifecycle `onStop` hooks are run by the\n * Application, not here. Idempotent; waits for an in-progress `init()`. Registered values are\n * owned by whoever registered them and are not disposed.\n *\n * @throws ZnightAggregateError (ZNIGHT021) listing every disposal failure.\n */\n dispose(): Promise<void> {\n this.#disposePromise ??= this.#disposeAll()\n return this.#disposePromise\n }\n\n async #disposeAll(): Promise<void> {\n this.#sealed = true\n if (this.#initPromise !== undefined) {\n try {\n await this.#initPromise\n } catch {\n // a failed init already rolled back what it created\n }\n }\n const errors: unknown[] = []\n for (let index = this.#order.length - 1; index >= 0; index--) {\n const slot = this.#order[index] as Slot\n try {\n const result = this.#disposeSlot(slot)\n if (result !== undefined) await result\n } catch (error) {\n errors.push(lifecycleError(`Disposing ${slot.displayName}`, error))\n }\n }\n for (const slot of this.#slots.values()) if (slot.mode === SINGLETON && slot.state === IDLE) slot.state = DISPOSED\n this.#status = 'disposed'\n if (errors.length > 0) {\n throw new ZnightAggregateError(\n ErrorCode.LifecycleFailed,\n `Failed to dispose ${errors.length} provider(s)`,\n errors,\n )\n }\n }\n\n #disposeSlot(slot: Slot): Promise<unknown> | undefined {\n if (slot.mode !== SINGLETON || slot.state !== READY) return undefined\n slot.state = DISPOSED\n const instance = slot.instance\n slot.instance = undefined\n const result = disposeInstance(instance, slot.definition?.dispose)\n return isThenable(result) ? Promise.resolve(result) : undefined\n }\n\n // ---------------------------------------------------------------------------------------------\n // Bindings\n // ---------------------------------------------------------------------------------------------\n\n #slot(token: Token): Slot {\n let slot = this.#slots.get(token)\n if (slot === undefined) {\n slot = new Slot(token)\n this.#slots.set(token, slot)\n if (!this.#lookup.has(token)) this.#lookup.set(token, slot)\n }\n return slot\n }\n\n #indexAliases(aliases: Readonly<Record<Token, Token>>): void {\n const targets = new Map<Token, Token>(Object.entries(aliases))\n for (const [alias, target] of targets) {\n let canonical = target\n const seen = new Set<Token>([alias])\n while (!this.#slots.has(canonical) && targets.has(canonical) && !seen.has(canonical)) {\n seen.add(canonical)\n canonical = targets.get(canonical) as Token\n }\n const slot = this.#lookup.get(canonical) ?? this.#slot(canonical)\n this.#aliases.set(alias, slot)\n if (!this.#lookup.has(alias)) this.#lookup.set(alias, slot)\n }\n }\n\n #declareExternal(external: ExternalDefinition): void {\n if (typeof external?.token !== 'string') {\n throw new ZnightError(ErrorCode.InvalidDecorator, `Invalid external definition: ${errorMessage(external)}`)\n }\n const slot = this.#lookup.get(external.token) ?? this.#slot(external.token)\n slot.external = external\n this.#names = undefined\n }\n\n #bindBuiltin(token: Token, value: unknown, cls?: object): void {\n this.#bind(token, LEVEL_BUILTIN, 'register', (slot, origin) => this.#applyValue(slot, value, LEVEL_BUILTIN, origin))\n if (cls === undefined) return\n const slot = this.#slot(token)\n slot.cls ??= cls\n if (!this.#lookup.has(cls)) this.#lookup.set(cls, slot)\n }\n\n #assertOpen(action: string, key: unknown): void {\n if (this.#sealed) throw sealedError(action, key)\n }\n\n #bind(key: ProviderKey, level: number, action: string, apply: (slot: Slot, origin: string) => void): void {\n this.#assertOpen(action, key)\n const slot = this.#registrationSlot(key, action)\n if (slot.level > level) return\n if (slot.level === level && level !== LEVEL_OVERRIDE && level !== LEVEL_BUILTIN) {\n throw duplicateRegistrationError(action, slot)\n }\n if (level === LEVEL_PLUGIN && slot.compiled) throw compiledProviderError(action, slot)\n apply(slot, this.#originOf(level))\n }\n\n #originOf(level: number): string {\n switch (level) {\n case LEVEL_BUILTIN:\n return '@znight/core'\n case LEVEL_APPLICATION:\n return 'Application.create({ providers })'\n case LEVEL_PLUGIN:\n return this.#origin ?? 'container.register()'\n case LEVEL_OVERRIDE:\n return 'an override'\n default:\n return 'the compiled metadata'\n }\n }\n\n #registrationSlot(key: ProviderKey, action: string): Slot {\n const slot = this.#lookup.get(key)\n if (slot !== undefined) return slot\n if (typeof key === 'string') return this.#slot(key)\n const byName = this.#findByName(key, true)\n if (byName !== undefined) return byName\n throw unknownClassError(action, key)\n }\n\n #applyDefinition(slot: Slot, definition: ProviderDefinition, level: number, origin: string): void {\n slot.mode = modeOf(definition)\n slot.definition = definition\n slot.instance = undefined\n slot.state = IDLE\n slot.level = level\n slot.origin = origin\n if (definition.class !== undefined) {\n slot.cls ??= definition.class\n if (!this.#lookup.has(definition.class)) this.#lookup.set(definition.class, slot)\n }\n this.#names = undefined\n }\n\n #applyValue(slot: Slot, value: unknown, level: number, origin: string): void {\n slot.mode = VALUE\n slot.definition = undefined\n slot.instance = value\n slot.state = READY\n slot.level = level\n slot.origin = origin\n this.#names = undefined\n }\n\n #rootSlot(key: ProviderKey): Slot {\n const slot = this.#lookup.get(key) ?? this.#findByName(key, true)\n if (slot === undefined) throw notFoundError(key)\n return slot\n }\n\n /**\n * Display-name (or class-name) lookup. A class key only keeps the candidates of its hierarchy (see\n * `classMatch`): those known to be of that class win over those whose class is unknown. Ambiguity\n * throws ZNIGHT008 when `strict`.\n */\n #findByName(key: unknown, strict: boolean): Slot | undefined {\n let name: string\n if (typeof key === 'string') name = key\n else if (typeof key === 'function' && typeof key.name === 'string' && key.name !== '') name = key.name\n else return undefined\n const candidates = this.#nameIndex().get(name)\n if (candidates === undefined) return undefined\n const matches = typeof key === 'function' ? classCandidates(candidates, key) : candidates\n if (matches.length === 1) {\n const slot = matches[0] as Slot\n if (this.#sealed) this.#lookup.set(key, slot)\n return slot\n }\n if (matches.length === 0 || !strict) return undefined\n throw ambiguousNameError(name, matches)\n }\n\n #nameIndex(): Map<string, Slot[]> {\n if (this.#names !== undefined) return this.#names\n const index = new Map<string, Slot[]>()\n const add = (name: string, slot: Slot): void => {\n const list = index.get(name)\n if (list === undefined) index.set(name, [slot])\n else if (!list.includes(slot)) list.push(slot)\n }\n for (const slot of this.#slots.values()) {\n if (slot.mode !== UNBOUND || slot.external !== undefined) add(slot.displayName, slot)\n }\n for (const [alias, slot] of this.#aliases) add(displayName(alias), slot)\n this.#names = index\n return index\n }\n}\n\n/** Binds `value` under `token` with built-in precedence (internal, used by Application). */\nexport function bindBuiltin(container: Container, token: Token, value: unknown, cls?: object): void {\n internals.bindBuiltin(container, token, value, cls)\n}\n\n/** Sets the label of subsequent plugin registrations, for error messages (internal). */\nexport function setRegistrationOrigin(container: Container, origin: string | undefined): void {\n internals.setOrigin(container, origin)\n}\n\nconst CLASS_MISMATCH = 0\nconst CLASS_UNKNOWN = 1\nconst CLASS_MATCH = 2\n\n/**\n * The candidates of a class key: those of its hierarchy when there are some, otherwise those whose\n * class is unknown (an unbound external, a provider without a class, a value that is not an instance).\n */\nfunction classCandidates(candidates: readonly Slot[], cls: object): Slot[] {\n const matches: Slot[] = []\n const unknown: Slot[] = []\n for (const slot of candidates) {\n const match = classMatch(slot, cls)\n if (match === CLASS_MATCH) matches.push(slot)\n else if (match === CLASS_UNKNOWN) unknown.push(slot)\n }\n return matches.length > 0 ? matches : unknown\n}\n\n/**\n * How a slot relates to a class key: its class (definition class, or the class it was bound with,\n * which survives a value override) or its value is of the class (or a subclass), its class is\n * unrelated, or it cannot tell. A value that is not an instance of the class does not rule the slot\n * out: types are structural, so a fake declared with `implements` stands for a class without\n * extending it. Provider instances are not inspected, so the answer does not depend on whether the\n * singleton was already created.\n */\nfunction classMatch(slot: Slot, cls: object): number {\n const own = slot.definition?.class\n if (isSubclass(own, cls) || isSubclass(slot.cls, cls)) return CLASS_MATCH\n if (slot.mode === VALUE && isInstance(slot.instance, cls)) return CLASS_MATCH\n return own === undefined && slot.cls === undefined ? CLASS_UNKNOWN : CLASS_MISMATCH\n}\n\nfunction isSubclass(own: object | undefined, cls: object): boolean {\n return own !== undefined && (own === cls || isInstance((own as { prototype?: unknown }).prototype, cls))\n}\n\n/** `value instanceof cls` through the prototype chain only (no `Symbol.hasInstance`, never throws). */\nfunction isInstance(value: unknown, cls: object): boolean {\n const prototype: unknown = (cls as { prototype?: unknown }).prototype\n return (\n prototype !== null &&\n typeof prototype === 'object' &&\n value !== null &&\n (typeof value === 'object' || typeof value === 'function') &&\n Object.prototype.isPrototypeOf.call(prototype, value)\n )\n}\n\nfunction disposeQuietly(instance: unknown, method: string | undefined): void {\n try {\n const result = disposeInstance(instance, method)\n if (isThenable(result)) result.then(undefined, () => undefined)\n } catch {\n // best effort\n }\n}\n\n/** Implementation of {@link OpenedScope}. */\nclass ScopeHandle implements OpenedScope {\n readonly #storage: AsyncLocalStorage<RequestScope>\n readonly #scope: RequestScope\n readonly #dispose: (scope: RequestScope) => Promise<unknown[]>\n #closed = false\n #closing: Promise<void> | undefined\n\n constructor(\n storage: AsyncLocalStorage<RequestScope>,\n scope: RequestScope,\n dispose: (scope: RequestScope) => Promise<unknown[]>,\n ) {\n this.#storage = storage\n this.#scope = scope\n this.#dispose = dispose\n }\n\n get context(): ScopeContext {\n return this.#scope\n }\n\n run<A extends readonly unknown[], R>(fn: (...args: A) => R, ...args: A): R {\n return this.#storage.run(this.#scope, fn, ...args)\n }\n\n close(): Promise<void> | undefined {\n if (this.#closed) return this.#closing\n this.#closed = true\n const scope = this.#scope\n if (scope.created.length === 0) {\n scope.closed = true\n return undefined\n }\n this.#closing = this.#dispose(scope).then(errors => {\n if (errors.length > 0) {\n throw new ZnightAggregateError(\n ErrorCode.LifecycleFailed,\n `Failed to dispose ${errors.length} request-scoped instance(s)`,\n errors,\n )\n }\n })\n return this.#closing\n }\n}\n","import type { CoreLogger } from './logger.ts'\n\nimport { isThenable } from './utils.ts'\n\n/**\n * Typed registry of hook names and their event types. Third-party packages may augment it:\n *\n * ```ts\n * declare module '@znight/core' {\n * interface ZnightHooks {\n * 'http:request': HttpRequestEvent\n * }\n * }\n * ```\n */\nexport interface ZnightHooks {\n /** One HTTP request handled by `@znight/http` (wrapped with `hooks.run`). */\n 'http:request': HttpRequestEvent\n /** One message delivery handled by `@znight/messaging` (wrapped with `hooks.run`). */\n 'messaging:message': MessageDeliveryEvent\n /** One message published through `MessageBroker` of `@znight/messaging` (wrapped with `hooks.run`). */\n 'messaging:publish': MessagePublishEvent\n /**\n * One occurrence of a job of `@znight/schedule`: executed runs are wrapped with `hooks.run`, then\n * emitted; occurrences that do not execute (`skipped`, `not-acquired`, a lock store failure) are\n * only emitted. In the wrappers, `outcome` stays `undefined` when the job did not start (veto,\n * drop, a wrapper that threw first): see `ScheduledRunEvent.outcome`.\n */\n 'schedule:run': ScheduledRunEvent\n /**\n * One GraphQL operation handled by `@znight/graphql` (RFC 0005): a query or a mutation, or a whole\n * subscription from its start to its end. Wrapped with `hooks.run` when wrappers exist, then\n * emitted when listeners exist.\n */\n 'graphql:operation': GraphQLOperationEvent\n}\n\n/**\n * Instrumentation event of the `http:request` hook. Defined in core so that producers\n * (`@znight/http`) and observers (`@znight/observability`, user plugins) share one type.\n * Mutable fields are filled in by the producer while the request is processed.\n */\nexport interface HttpRequestEvent {\n readonly method: string\n /** Request path, without query string. */\n readonly path: string\n /** Matched route pattern (e.g. `/users/:id`), `undefined` when no route matched. */\n readonly route: string | undefined\n readonly requestId: string\n /** Lower-cased request headers. */\n readonly headers: Readonly<Record<string, string | undefined>>\n /** Adapter-neutral context (`HttpContext` from `@znight/http`). */\n readonly context: unknown\n /** `performance.now()` when the request started. */\n readonly startTime: number\n /** Final response status, set before `hooks.run` resolves. */\n status?: number\n /** Error thrown by the pipeline, if any (already mapped to `status`). */\n error?: unknown\n /** Response headers to add (e.g. trace context). */\n readonly responseHeaders: Record<string, string>\n}\n\n/**\n * Instrumentation event of the `messaging:publish` hook. Wrappers may add headers (e.g. W3C trace\n * context) before calling `next()`: they are sent with the message.\n */\nexport interface MessagePublishEvent {\n readonly queue: string\n readonly type: string | undefined\n readonly messageId: string\n /** Headers sent with the message (mutable until `next()` is called). */\n readonly headers: Record<string, string>\n /** `performance.now()` when the publication started. */\n readonly startTime: number\n /** Publication error, set before `next()` rejects in the wrappers. */\n error?: unknown\n}\n\n/** Instrumentation event of the `messaging:message` hook. */\nexport interface MessageDeliveryEvent {\n readonly queue: string\n readonly type: string | undefined\n readonly messageId: string\n /** 1-based delivery attempt. */\n readonly attempt: number\n readonly headers: Readonly<Record<string, string>>\n /** Display name of the consumer class. */\n readonly consumer: string\n /** Handler method, `undefined` when no handler matched. */\n readonly handler: string | undefined\n /** `InboundMessage` from `@znight/messaging`. */\n readonly message: unknown\n readonly startTime: number\n /** Outcome set before `hooks.run` resolves. */\n outcome?: 'ack' | 'retry' | 'dead-letter'\n error?: unknown\n}\n\n/** How a scheduled run was triggered (`ScheduledRunEvent.trigger`). */\nexport type ScheduledRunTrigger = 'schedule' | 'start' | 'manual' | 'queued'\n\n/** Outcome of a scheduled run (`ScheduledRunEvent.outcome`). */\nexport type ScheduledRunOutcome = 'completed' | 'failed' | 'skipped' | 'not-acquired'\n\n/** Why a scheduled run was aborted (`ScheduledRunEvent.aborted`, the `reason` of `JobAbortedError`). */\nexport type ScheduledRunAbortReason = 'timeout' | 'lock-lost' | 'removed' | 'shutdown'\n\n/**\n * Instrumentation event of the `schedule:run` hook, produced by `@znight/schedule` for every\n * occurrence of a job. Mutable fields are filled in by the producer.\n *\n * - **Listeners** (`hooks.on`) always see the final {@link ScheduledRunEvent.outcome}: the event is\n * emitted once the occurrence is settled.\n * - **Occurrences that never reach the wrappers** (`context` is `undefined`: skipped by the overlap\n * policy, `not-acquired`, a lock store failure, dropped while the lock lease was acquired) are\n * only emitted, with their `outcome`.\n * - **Runs handed to the job** (`context` is set) are wrapped with `hooks.run`, where `outcome` is\n * only known once the job settled, and stays `undefined` when the job did not start: see\n * {@link ScheduledRunEvent.outcome} for what a wrapper reads after `next()`.\n */\nexport interface ScheduledRunEvent {\n /** Job name (`digest.daily`, `OutboxJobs.flush`). */\n readonly job: string\n readonly kind: 'cron' | 'interval' | 'timeout'\n /** Display name of the host class; `undefined` for dynamic jobs. */\n readonly host: string | undefined\n /** Job method; `undefined` for dynamic jobs. */\n readonly method: string | undefined\n /** Unique id of the run. */\n readonly runId: string\n readonly trigger: ScheduledRunTrigger\n /** Epoch milliseconds of the occurrence (scheduler clock). */\n readonly scheduledAt: number\n /**\n * `JobContext` from `@znight/schedule`; `undefined` for an occurrence that never reached the\n * wrappers (set for a run vetoed or dropped by the wrappers).\n */\n readonly context: unknown\n /** `performance.now()` when the run started, or was dropped. */\n readonly startTime: number\n /**\n * Outcome of the run. Listeners always see it. In a `hooks.run` wrapper, it is `undefined` until\n * the job settles, then:\n *\n * - `'completed'` when `next()` resolves after the job ran;\n * - `'failed'`, with {@link ScheduledRunEvent.error}, when `next()` rejects because the job threw;\n * - still `undefined` when the job never started: a wrapper returned without calling `next()` (a\n * veto: `next()` of the outer wrappers resolves), the run was dropped while the wrappers waited\n * (the job was removed or paused, the scheduler stops: `next()` resolves, `aborted` may be set),\n * or a wrapper threw before calling `next()` (`next()` of the outer wrappers rejects with that\n * error).\n *\n * The producer settles an `undefined` outcome after `hooks.run`: `'skipped'` for a veto or a\n * drop, `'failed'` (with `error`) when a wrapper, or the opening of the run scope, threw before the\n * job (a wrapper that swallows that rejection turns it into `'skipped'`: rethrow it). A wrapper\n * that fails after `next()` does not change the outcome of the job (the scheduler logs that error\n * on its own). A wrapper that reports the outcome reads\n * `event.outcome ?? (nextRejected ? 'failed' : 'skipped')`.\n */\n outcome?: ScheduledRunOutcome\n /**\n * What the job threw or rejected with (`failed`), what a wrapper threw before the job (set after\n * `hooks.run`), or the lock store failure.\n */\n error?: unknown\n /** Set when the run's signal was aborted. */\n aborted?: ScheduledRunAbortReason\n}\n\n/** Type of a GraphQL operation (`GraphQLOperationEvent.operationType`). */\nexport type GraphQLOperationType = 'query' | 'mutation' | 'subscription'\n\n/**\n * How a GraphQL operation reached the server (`GraphQLOperationEvent.transport`): GraphQL over HTTP,\n * GraphQL over Server-Sent Events, GraphQL over WebSocket (`ws`, reserved for `graphql-ws`), or a\n * direct call (`execute()` / `subscribe()` of the plugin).\n */\nexport type GraphQLOperationTransport = 'http' | 'sse' | 'ws' | 'direct'\n\n/**\n * Outcome of a GraphQL operation (`GraphQLOperationEvent.outcome`):\n *\n * - `'success'`: executed, no error;\n * - `'partial'`: executed, with data and field errors;\n * - `'error'`: executed, without data (a non-null root field failed, or the execution threw);\n * - `'rejected'`: never executed (parse, validation, variable coercion or limit errors).\n */\nexport type GraphQLOperationOutcome = 'success' | 'partial' | 'error' | 'rejected'\n\n/** One error of a GraphQL response, as sent to the client (masked when it is unexpected). */\nexport interface GraphQLOperationError {\n readonly message: string\n /** `extensions.code` of the error (`FORBIDDEN`, `GRAPHQL_PARSE_FAILED`...). */\n readonly code: string | undefined\n /** Response path of the field that failed; absent for request errors. */\n readonly path?: readonly (string | number)[]\n}\n\n/**\n * Instrumentation event of the `graphql:operation` hook, produced by `@znight/graphql` (RFC 0005)\n * once per operation. For a subscription, it covers its whole life: wrappers see it start, and\n * `outcome` is set when it ends. Mutable fields are filled in by the producer before `hooks.run`\n * resolves; listeners see the final values.\n */\nexport interface GraphQLOperationEvent {\n /** `undefined` when the request was rejected before an operation was selected (parse error...). */\n readonly operationType: GraphQLOperationType | undefined\n /** `undefined` for an anonymous operation, or when none was selected. */\n readonly operationName: string | undefined\n /** SHA-256 (hex) of the query text, cached with the parsed document; `undefined` without a query. */\n readonly documentId: string | undefined\n readonly transport: GraphQLOperationTransport\n /**\n * The GraphQL driver that received the operation (RFC 0009): `'builtin'` for the built-in\n * transport and for direct calls, `'yoga'`, `'apollo'` or a third-party driver's name otherwise.\n */\n readonly driver: string\n readonly requestId: string\n /** `GraphQLContext` from `@znight/graphql`. */\n readonly context: unknown\n /** `performance.now()` when the operation started. */\n readonly startTime: number\n /** Outcome, set before `hooks.run` resolves. */\n outcome?: GraphQLOperationOutcome\n /** Errors of the response (field and request errors), set before `hooks.run` resolves. */\n errors?: readonly GraphQLOperationError[]\n}\n\n/** Name of a declared hook. */\nexport type HookName = keyof ZnightHooks\n\n/** Event type of hook `K`. */\nexport type HookEvent<K extends HookName> = ZnightHooks[K]\n\n/** Observer of a hook. Errors (thrown or rejected) are reported to the logger, never to the emitter. */\nexport type HookListener<K extends HookName> = (event: HookEvent<K>) => unknown\n\n/**\n * Middleware around a hooked operation (`hooks.run()`). Must call `next()` to run the inner\n * wrappers and the operation; `next()` resolves with the operation's result. The value returned by\n * the wrapper itself is ignored.\n */\nexport type HookWrapper<K extends HookName> = (event: HookEvent<K>, next: () => Promise<unknown>) => Promise<unknown>\n\nexport interface HooksOptions {\n /** Receives listener failures. Default: the console. */\n readonly logger?: CoreLogger\n}\n\ntype AnyListener = (event: unknown) => unknown\ntype AnyWrapper = (event: unknown, next: () => Promise<unknown>) => unknown\n\nconst EMPTY: readonly never[] = Object.freeze([])\n\n/**\n * Lightweight, typed event bus used by plugins to observe (`on`/`emit`) and wrap (`wrap`/`run`)\n * framework operations (`http:request`, `messaging:message`...). Registration is copy-on-write, so\n * emitting allocates nothing.\n */\nexport class Hooks {\n readonly #listeners = new Map<PropertyKey, readonly AnyListener[]>()\n readonly #wrappers = new Map<PropertyKey, readonly AnyWrapper[]>()\n readonly #logger: CoreLogger | undefined\n\n constructor(options: HooksOptions = {}) {\n this.#logger = options.logger\n }\n\n /** Adds a listener. Returns a function removing it (idempotent). */\n on<K extends HookName>(name: K, listener: HookListener<K>): () => void {\n return add(this.#listeners, name, listener as AnyListener)\n }\n\n /**\n * Calls every listener of `name` synchronously, in registration order. A failing listener\n * (thrown error or rejected promise) is reported to the logger and does not affect the others.\n */\n emit<K extends HookName>(name: K, event: HookEvent<K>): void {\n const listeners = this.#listeners.get(name)\n if (listeners === undefined) return\n for (const listener of listeners) {\n try {\n const result = listener(event)\n if (isThenable(result)) result.then(undefined, error => this.#report(name, error))\n } catch (error) {\n this.#report(name, error)\n }\n }\n }\n\n /** Adds a wrapper around operations run with {@link run}. Returns a function removing it (idempotent). */\n wrap<K extends HookName>(name: K, wrapper: HookWrapper<K>): () => void {\n return add(this.#wrappers, name, wrapper as AnyWrapper)\n }\n\n /**\n * Runs `fn` through the wrappers of `name` (onion model: the first registered wrapper is the\n * outermost) and resolves with the result of `fn`. Without wrappers, `fn` is called directly.\n * If a wrapper does not call `next()`, `fn` does not run and the promise resolves with `undefined`.\n */\n run<K extends HookName, R>(name: K, event: HookEvent<K>, fn: () => Promise<R>): Promise<R> {\n const wrappers = this.#wrappers.get(name) ?? EMPTY\n if (wrappers.length === 0) {\n try {\n return Promise.resolve(fn())\n } catch (error) {\n return Promise.reject(error)\n }\n }\n let result: R | undefined\n const dispatch = async (index: number): Promise<unknown> => {\n if (index === wrappers.length) {\n result = await fn()\n return result\n }\n const wrapper = wrappers[index] as AnyWrapper\n await wrapper(event, () => dispatch(index + 1))\n return result\n }\n return dispatch(0).then(() => result as R)\n }\n\n /** Whether `name` has listeners (lets emitters skip building costly events). */\n hasListeners(name: HookName): boolean {\n return (this.#listeners.get(name)?.length ?? 0) > 0\n }\n\n /** Whether `name` has wrappers. */\n hasWrappers(name: HookName): boolean {\n return (this.#wrappers.get(name)?.length ?? 0) > 0\n }\n\n #report(name: PropertyKey, error: unknown): void {\n const message = `Hook listener for \"${String(name)}\" failed`\n if (this.#logger === undefined) console.error(`[znight] ${message}`, error)\n else this.#logger.error(message, { hook: String(name), err: error })\n }\n}\n\nfunction add<F>(registry: Map<PropertyKey, readonly F[]>, name: PropertyKey, fn: F): () => void {\n registry.set(name, [...(registry.get(name) ?? EMPTY), fn])\n let active = true\n return () => {\n if (!active) return\n active = false\n const current = registry.get(name) ?? EMPTY\n const index = current.indexOf(fn)\n if (index === -1) return\n const next = [...current.slice(0, index), ...current.slice(index + 1)]\n if (next.length === 0) registry.delete(name)\n else registry.set(name, next)\n }\n}\n","/** Structured context attached to a log entry. */\nexport type LogContext = Readonly<Record<string, unknown>>\n\n/**\n * Minimal logger used by the core runtime and by plugins. `@znight/observability` replaces the\n * default console implementation with a structured (pino) logger through `app.setLogger()`.\n */\nexport interface CoreLogger {\n debug(message: string, context?: LogContext): void\n info(message: string, context?: LogContext): void\n warn(message: string, context?: LogContext): void\n error(message: string, context?: LogContext): void\n}\n\n/** Log levels, from the most to the least verbose. `silent` disables every entry. */\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent'\n\nconst LEVELS: Readonly<Record<LogLevel, number>> = { debug: 10, info: 20, warn: 30, error: 40, silent: 100 }\n\n/** The subset of `console` used by {@link createConsoleLogger}. */\nexport type ConsoleLike = Pick<Console, 'debug' | 'info' | 'warn' | 'error'>\n\nexport interface ConsoleLoggerOptions {\n /** Minimum level written. Default: `info`. */\n readonly level?: LogLevel\n /** Prefix of every message. Default: `[znight]`. */\n readonly prefix?: string\n /** Destination. Default: the global `console`. */\n readonly console?: ConsoleLike\n}\n\n/** Creates a {@link CoreLogger} writing to the console. Entries below `level` are dropped. */\nexport function createConsoleLogger(options: ConsoleLoggerOptions = {}): CoreLogger {\n const threshold = LEVELS[options.level ?? 'info']\n const prefix = options.prefix ?? '[znight]'\n const out = options.console ?? console\n const write = (level: Exclude<LogLevel, 'silent'>, message: string, context?: LogContext): void => {\n if (LEVELS[level] < threshold) return\n const text = prefix === '' ? message : `${prefix} ${message}`\n if (context === undefined || Object.keys(context).length === 0) out[level](text)\n else out[level](text, context)\n }\n return {\n debug: (message, context) => write('debug', message, context),\n info: (message, context) => write('info', message, context),\n warn: (message, context) => write('warn', message, context),\n error: (message, context) => write('error', message, context),\n }\n}\n\nfunction noop(): void {}\n\n/** A logger dropping every entry (useful in tests). */\nexport const silentLogger: CoreLogger = Object.freeze({ debug: noop, info: noop, warn: noop, error: noop })\n\n/**\n * A logger forwarding every call to a replaceable target. Plugins receive this instance, so a\n * logger installed later (e.g. by `@znight/observability`) is used by everyone immediately.\n */\nexport class DelegatingLogger implements CoreLogger {\n #target: CoreLogger\n\n constructor(target: CoreLogger) {\n this.#target = target\n }\n\n /** The logger currently receiving the entries. */\n get target(): CoreLogger {\n return this.#target\n }\n\n /** Replaces the logger receiving the entries. Passing the delegating logger itself is ignored. */\n setTarget(target: CoreLogger): void {\n if (target !== this) this.#target = target\n }\n\n debug(message: string, context?: LogContext): void {\n this.#target.debug(message, context)\n }\n\n info(message: string, context?: LogContext): void {\n this.#target.info(message, context)\n }\n\n warn(message: string, context?: LogContext): void {\n this.#target.warn(message, context)\n }\n\n error(message: string, context?: LogContext): void {\n this.#target.error(message, context)\n }\n}\n","import { ErrorCode, ZnightError } from './errors.ts'\nimport { isThenable } from './utils.ts'\n\n/** Signals the application can listen to for a graceful shutdown. */\nexport type ShutdownSignal = 'SIGINT' | 'SIGTERM' | 'SIGHUP' | 'SIGQUIT' | 'SIGBREAK' | 'SIGUSR1' | 'SIGUSR2'\n\n/**\n * The parts of `process` used by the application (signals, exit code, forced exit). Injectable for\n * tests through `Application.create({ shutdown: { process } })`.\n */\nexport interface ProcessLike {\n on(event: string, listener: (signal: string) => void): unknown\n off(event: string, listener: (signal: string) => void): unknown\n exit(code?: number): unknown\n exitCode?: number | string | null | undefined\n}\n\n/** The global `process`, when the runtime has one. */\nexport function defaultProcess(): ProcessLike | undefined {\n const candidate: unknown = (globalThis as { process?: unknown }).process\n if (candidate === null || typeof candidate !== 'object') return undefined\n const proc = candidate as Partial<ProcessLike>\n return typeof proc.on === 'function' && typeof proc.off === 'function' && typeof proc.exit === 'function'\n ? (proc as ProcessLike)\n : undefined\n}\n\n/** ZNIGHT021 raised when a lifecycle step exceeds its time budget. */\nexport class StepTimeoutError extends ZnightError {\n constructor(step: string, ms: number) {\n super(ErrorCode.LifecycleFailed, `${step} timed out after ${Math.round(ms)}ms`)\n }\n}\n\n/**\n * Longest delay a timer accepts (2^31 - 1 ms, about 24.8 days): Node and Bun clamp longer delays to\n * 1 ms. A longer budget (or `Infinity`) therefore means no timeout.\n */\nconst MAX_TIMEOUT_MS = 2_147_483_647\n\n/**\n * Runs `step` and resolves when it completes, or rejects with a {@link StepTimeoutError} after `ms`.\n * A synchronous step (or one resolving within the current tick of microtasks) always completes,\n * even with a zero budget. A step completing after its timeout is ignored. A budget above\n * {@link MAX_TIMEOUT_MS} (or `Infinity`) waits for the step without a timer.\n */\nexport function runWithTimeout(label: string, step: () => unknown, ms: number): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n let result: unknown\n try {\n result = step()\n } catch (error) {\n reject(error)\n return\n }\n if (!isThenable(result)) {\n resolve()\n return\n }\n let settled = false\n const timer =\n ms > MAX_TIMEOUT_MS\n ? undefined\n : setTimeout(() => {\n if (settled) return\n settled = true\n reject(new StepTimeoutError(label, ms))\n }, ms)\n result.then(\n () => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n resolve()\n },\n (error: unknown) => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n reject(error)\n },\n )\n })\n}\n","import type { LifecycleHook, ProviderClass, Token, ZnightMetadata } from './metadata.ts'\nimport type { Plugin, PluginContext, PluginHook } from './plugin.ts'\n\nimport { AsyncLocalStorage } from 'node:async_hooks'\n\nimport { bindBuiltin, Container, type InitOptions, type ManagedInstance, setRegistrationOrigin } from './container.ts'\nimport { ErrorCode, ZnightError } from './errors.ts'\nimport { Hooks } from './hooks.ts'\nimport { callLifecycleHook, hasLifecycleHook, isDisposable } from './lifecycle.ts'\nimport { type CoreLogger, createConsoleLogger, DelegatingLogger } from './logger.ts'\nimport { defaultProcess, type ProcessLike, runWithTimeout, type ShutdownSignal, StepTimeoutError } from './process.ts'\nimport { addSuppressedErrors, lifecycleError, ZnightAggregateError } from './runtime-errors.ts'\nimport { type ClassKey, CoreTokens, type ProviderKey, type TypedToken } from './tokens.ts'\nimport { errorMessage, now } from './utils.ts'\n\n/** Lifecycle state of an {@link Application}. */\nexport type ApplicationState = 'created' | 'starting' | 'ready' | 'stopping' | 'stopped' | 'failed'\n\n/** Values keyed by token or class: a `Map`, an iterable of pairs, or a record keyed by token. */\nexport type ProviderValues = Iterable<readonly [ProviderKey, unknown]> | Readonly<Record<Token, unknown>>\n\n/** Graceful shutdown settings. */\nexport interface ShutdownOptions {\n /** Signals stopping the application once started. Default: `['SIGINT', 'SIGTERM']`; `false` disables. */\n readonly signals?: readonly ShutdownSignal[] | false\n /**\n * Global deadline of `stop()`, in milliseconds. Default: 10 000. `Infinity` (or any value above\n * 2^31 - 1, the range of timers) means no deadline.\n */\n readonly timeoutMs?: number\n /**\n * Maximum duration of each shutdown step (hook or disposal), in milliseconds. Default: 5 000.\n * `Infinity` (or any value above 2^31 - 1) means no limit.\n */\n readonly hookTimeoutMs?: number\n /** Process used for signals, `exitCode` and forced exits. Default: the global `process`. */\n readonly process?: ProcessLike\n}\n\n/**\n * Hot module replacement handle (`import.meta.hot`). The dispose callback returns the `stop()`\n * promise, so that runtimes awaiting it (Vite's module runner, Bun) load the new module once the\n * application has stopped.\n */\nexport interface HotContext {\n dispose(callback: (data: unknown) => void | Promise<void>): void\n}\n\n/** Options of {@link Application.create}. */\nexport interface ApplicationOptions {\n /** The metadata generated by `@znight/compiler` (`__ZNIGHT_METADATA__`). */\n readonly metadata: ZnightMetadata\n readonly plugins?: readonly Plugin[]\n /** Values supplied by the application (externals, configuration...). Superseded by plugins. */\n readonly providers?: ProviderValues\n /** Replacements applied after plugins registered (highest precedence): values or provider definitions. */\n readonly overrides?: ProviderValues\n /** Initial logger. Default: a console logger (level `info`). Replace it later with `setLogger()`. */\n readonly logger?: CoreLogger\n readonly shutdown?: ShutdownOptions\n /** Forwarded to `container.init()` (e.g. `{ only: [UserController] }`). */\n readonly init?: InitOptions\n /** Pass `import.meta.hot` to stop the application when the module is replaced. */\n readonly hot?: HotContext\n}\n\nconst DEFAULT_SIGNALS: readonly ShutdownSignal[] = ['SIGINT', 'SIGTERM']\nconst DEFAULT_TIMEOUT_MS = 10_000\nconst DEFAULT_HOOK_TIMEOUT_MS = 5_000\nconst FORCED_EXIT_CODE = 130\n\n/**\n * Carries a marker through the async context of the start hook in progress, so that `stop()` can\n * tell a request coming from that hook (which must not wait for the start: the start waits for it).\n */\nconst startHookContext = new AsyncLocalStorage<object>()\n\n/**\n * A Znight application: a container built from the compiled metadata, plugins and the lifecycle\n * tying them together.\n *\n * ```ts\n * const app = await Application.create({\n * metadata: __ZNIGHT_METADATA__,\n * plugins: [HttpPlugin.configure({ port: 3000 })],\n * })\n * await app.start()\n * ```\n */\nexport class Application {\n readonly container: Container\n readonly hooks: Hooks\n readonly metadata: ZnightMetadata\n readonly #logger: DelegatingLogger\n readonly #plugins: readonly Plugin[]\n readonly #pluginsByName: ReadonlyMap<string, Plugin>\n readonly #context: PluginContext\n readonly #signals: readonly ShutdownSignal[]\n readonly #process: ProcessLike | undefined\n readonly #timeoutMs: number\n readonly #hookTimeoutMs: number\n #state: ApplicationState = 'created'\n #startPromise: Promise<void> | undefined\n #stopPromise: Promise<void> | undefined\n /** Plugins whose `register` was attempted (they all receive `onDispose`). */\n readonly #registered: Plugin[] = []\n /** Plugins whose `onStart` completed (they receive `onStop`). */\n readonly #startedPlugins: Plugin[] = []\n /** Providers whose `onStart` completed (they receive `onStop`). */\n readonly #startedProviders = new Set<Token>()\n #listening: readonly ShutdownSignal[] = []\n #signalReceived = false\n /** Marker of the start hook in progress (see `startHookContext`). */\n #startHookMarker: object | undefined\n /** A start hook called `stop()`: the remaining start hooks are skipped. */\n #startAborted = false\n /** Releases a `stop()` waiting for the start, when a start hook asks to stop in turn. */\n #releaseStopWait: (() => void) | undefined\n\n private constructor(options: ApplicationOptions) {\n const plugins = [...(options.plugins ?? [])]\n const byName = new Map<string, Plugin>()\n for (const plugin of plugins) {\n if (plugin === null || typeof plugin !== 'object' || typeof plugin.name !== 'string' || plugin.name === '') {\n throw new ZnightError(ErrorCode.InvalidDecorator, `Invalid plugin: ${errorMessage(plugin)} has no name`)\n }\n if (byName.has(plugin.name)) {\n throw new ZnightError(ErrorCode.DuplicateProvider, `Duplicate plugin \"${plugin.name}\"`, {\n hints: ['Each plugin can be added once to Application.create({ plugins })'],\n })\n }\n byName.set(plugin.name, plugin)\n }\n this.#plugins = plugins\n this.#pluginsByName = byName\n this.metadata = options.metadata\n this.container = Container.create(options.metadata)\n this.#logger = new DelegatingLogger(options.logger ?? createConsoleLogger())\n this.hooks = new Hooks({ logger: this.#logger })\n\n const shutdown = options.shutdown ?? {}\n this.#process = shutdown.process ?? defaultProcess()\n this.#signals = shutdown.signals === false ? [] : [...(shutdown.signals ?? DEFAULT_SIGNALS)]\n this.#timeoutMs = positive(shutdown.timeoutMs, DEFAULT_TIMEOUT_MS, 'shutdown.timeoutMs')\n this.#hookTimeoutMs = positive(shutdown.hookTimeoutMs, DEFAULT_HOOK_TIMEOUT_MS, 'shutdown.hookTimeoutMs')\n\n bindBuiltin(this.container, CoreTokens.Application, this, Application)\n bindBuiltin(this.container, CoreTokens.Hooks, this.hooks, Hooks)\n bindBuiltin(this.container, CoreTokens.Logger, this.#logger)\n\n this.#context = Object.freeze({\n app: this,\n container: this.container,\n metadata: this.metadata,\n hooks: this.hooks,\n logger: this.#logger,\n getPlugin: <P extends Plugin = Plugin>(name: string): P | undefined => this.getPlugin<P>(name),\n })\n }\n\n /**\n * Creates the container, supplies `providers`, runs plugins' `register` (in order), applies\n * `overrides`, initialises the container and runs plugins' `onBootstrap`. On failure everything\n * created so far is disposed (plugins receive `onDispose`) and the error is rethrown.\n */\n static async create(options: ApplicationOptions): Promise<Application> {\n const app = new Application(options)\n await app.#bootstrap(options)\n return app\n }\n\n /** Current lifecycle state. */\n get state(): ApplicationState {\n return this.#state\n }\n\n /** The application logger (live: follows {@link setLogger}). */\n get logger(): CoreLogger {\n return this.#logger\n }\n\n /** Plugins, in registration order. */\n get plugins(): readonly Plugin[] {\n return this.#plugins\n }\n\n /** Replaces the logger used by the core and every plugin holding `ctx.logger`. */\n setLogger(logger: CoreLogger): void {\n this.#logger.setTarget(logger)\n }\n\n /** A plugin of the application, by name. */\n getPlugin<P extends Plugin = Plugin>(name: string): P | undefined {\n return this.#pluginsByName.get(name) as P | undefined\n }\n\n /** Shortcut for `app.container.get(key)`. */\n get<T>(key: ProviderClass<T>): T\n get<T>(key: ClassKey<T>): T\n get<T = unknown>(key: TypedToken<T>): T\n get(key: ProviderKey): unknown {\n return this.container.get(key as TypedToken<unknown>)\n }\n\n async #bootstrap(options: ApplicationOptions): Promise<void> {\n const container = this.container\n try {\n if (options.providers !== undefined) {\n for (const [key, value] of entriesOf(options.providers)) container.provide(key, value)\n }\n for (const plugin of this.#plugins) {\n this.#registered.push(plugin)\n setRegistrationOrigin(container, `plugin \"${plugin.name}\"`)\n try {\n await this.#callPlugin(plugin, 'register')\n } finally {\n setRegistrationOrigin(container, undefined)\n }\n }\n if (options.overrides !== undefined) {\n for (const [key, value] of entriesOf(options.overrides)) container.override(key, value)\n }\n await container.init(options.init)\n for (const plugin of this.#plugins) await this.#callPlugin(plugin, 'onBootstrap')\n } catch (error) {\n this.#state = 'failed'\n // nothing was started yet: this disposes the providers and runs plugins' onDispose\n addSuppressedErrors(error, await this.#shutdown())\n throw error\n }\n // the HMR runtime awaits the returned promise before it loads the new module\n options.hot?.dispose(() =>\n this.stop().catch((error: unknown) => this.#logger.error('Failed to stop the application', { err: error })),\n )\n }\n\n // ---------------------------------------------------------------------------------------------\n // start / stop\n // ---------------------------------------------------------------------------------------------\n\n /**\n * Starts the application: providers' `onStart` (resolution order) → plugins' `onStart` →\n * providers' `onReady` → plugins' `onReady`, then `state === 'ready'`. Signal handlers are\n * installed when the start begins. On failure, what was started is stopped, everything is\n * disposed, `state === 'failed'` and the error is rethrown (cleanup errors attached).\n * Calling it while starting returns the same promise; once ready it resolves immediately.\n * When a start hook calls `stop()` (e.g. a job that ends its work in `onReady`), the remaining\n * start hooks are skipped and the promise resolves once the application is stopped.\n */\n start(): Promise<void> {\n switch (this.#state) {\n case 'created':\n this.#startPromise = this.#runStart()\n return this.#startPromise\n case 'starting':\n return this.#startPromise as Promise<void>\n case 'ready':\n return Promise.resolve()\n default:\n return Promise.reject(\n new ZnightError(ErrorCode.LifecycleFailed, `Cannot start the application: it is ${this.#state}`),\n )\n }\n }\n\n async #runStart(): Promise<void> {\n this.#state = 'starting'\n this.#installSignals()\n let completed: boolean\n try {\n completed = await this.#runStartHooks()\n } catch (error) {\n if (this.#startAborted) {\n // the shutdown requested by a start hook owns the cleanup\n await this.#settledStop()\n throw error\n }\n addSuppressedErrors(error, await this.#shutdown())\n this.#removeSignals()\n this.#state = 'failed'\n throw error\n }\n if (!completed) {\n await this.#settledStop()\n return\n }\n this.#state = 'ready'\n this.#logger.debug('Application started')\n }\n\n /** Runs the start hooks in order; `false` when one of them called `stop()` (the others are skipped). */\n async #runStartHooks(): Promise<boolean> {\n const providers = this.container.instances()\n for (const provider of providers) {\n if (!(await this.#startHook(() => this.#callProvider(provider, 'onStart')))) return false\n this.#startedProviders.add(provider.token)\n }\n for (const plugin of this.#plugins) {\n if (!(await this.#startHook(() => this.#callPlugin(plugin, 'onStart')))) return false\n this.#startedPlugins.push(plugin)\n }\n for (const provider of providers) {\n if (!(await this.#startHook(() => this.#callProvider(provider, 'onReady')))) return false\n }\n for (const plugin of this.#plugins) {\n if (!(await this.#startHook(() => this.#callPlugin(plugin, 'onReady')))) return false\n }\n return true\n }\n\n /**\n * Runs one start hook in an async context carrying a fresh marker, so that a `stop()` called from\n * it (or from work it awaits) is recognised. Returns `false` when the hook stopped the application.\n */\n async #startHook(hook: () => Promise<void>): Promise<boolean> {\n const marker = {}\n this.#startHookMarker = marker\n try {\n await startHookContext.run(marker, hook)\n } finally {\n this.#startHookMarker = undefined\n }\n return !this.#startAborted\n }\n\n /** Whether the caller runs in the async context of the start hook in progress. */\n #calledFromStartHook(): boolean {\n const marker = this.#startHookMarker\n return this.#state === 'starting' && marker !== undefined && startHookContext.getStore() === marker\n }\n\n /** Waits for the stop requested by a start hook; its errors belong to the caller of `stop()`. */\n async #settledStop(): Promise<void> {\n try {\n await this.#stopPromise\n } catch {\n // reported by the stop() promise\n }\n }\n\n /**\n * Stops the application (idempotent; waits for an in-progress `start()`):\n * plugins' `onStop` (reverse) → providers' `onStop` + disposal (reverse resolution order) →\n * plugins' `onDispose` (reverse). Every step is attempted, each within `hookTimeoutMs` and all\n * within `timeoutMs`; failures are collected into a ZnightAggregateError (ZNIGHT021). Signal\n * handlers are removed.\n *\n * Called from a start hook (`onStart`/`onReady` of a provider or plugin, or work it awaits), it\n * does not wait for the start, which waits for that hook: the shutdown runs right away, stopping\n * what completed its `onStart`, and the remaining start hooks are skipped.\n */\n stop(): Promise<void> {\n if (this.#calledFromStartHook()) {\n this.#startAborted = true\n this.#releaseStopWait?.() // a stop() already waiting for the start must not wait for this hook\n }\n this.#stopPromise ??= this.#runStop()\n return this.#stopPromise\n }\n\n async #runStop(): Promise<void> {\n if (this.#state === 'starting' && !this.#startAborted) await this.#waitForStart()\n if (this.#state === 'failed' || this.#state === 'stopped') {\n this.#removeSignals()\n return\n }\n this.#state = 'stopping'\n const errors = await this.#shutdown()\n this.#removeSignals()\n this.#state = 'stopped'\n if (errors.length > 0) {\n throw new ZnightAggregateError(\n ErrorCode.LifecycleFailed,\n `The application stopped with ${errors.length} error(s)`,\n errors,\n )\n }\n // after a signal, the end of the shutdown is reported at the level of \"Received SIGTERM\"\n if (this.#signalReceived) this.#logger.info('Application stopped')\n else this.#logger.debug('Application stopped')\n }\n\n /**\n * Resolves when the start in progress settles (a failed start already stopped and disposed\n * everything), or earlier when a start hook asks to stop (see `stop()`).\n */\n async #waitForStart(): Promise<void> {\n await new Promise<void>(resolve => {\n this.#releaseStopWait = resolve\n const done = (): void => resolve()\n this.#startPromise?.then(done, done)\n })\n this.#releaseStopWait = undefined\n }\n\n /**\n * The three shutdown phases (also used to roll back a failed create/start: only what was started\n * is stopped). Never throws: returns the errors of the failed steps.\n */\n async #shutdown(): Promise<unknown[]> {\n const errors: unknown[] = []\n const step = this.#stepRunner(errors)\n for (const plugin of [...this.#startedPlugins].reverse()) {\n if (typeof plugin.onStop === 'function') {\n await step(`Plugin \"${plugin.name}\" onStop()`, () => plugin.onStop?.(this.#context))\n }\n }\n for (const provider of this.container.instances().reverse()) {\n if (this.#startedProviders.has(provider.token) && hasLifecycleHook(provider.instance, 'onStop')) {\n await step(`${provider.displayName}.onStop()`, () => callLifecycleHook(provider.instance, 'onStop'))\n }\n if (isDisposable(provider.instance, provider.definition.dispose)) {\n await step(`Disposing ${provider.displayName}`, () => provider.dispose())\n } else {\n await provider.dispose()\n }\n }\n try {\n await this.container.dispose()\n } catch (error) {\n errors.push(...flatten(error))\n }\n for (const plugin of [...this.#registered].reverse()) {\n if (typeof plugin.onDispose === 'function') {\n await step(`Plugin \"${plugin.name}\" onDispose()`, () => plugin.onDispose?.(this.#context))\n }\n }\n this.#startedPlugins.length = 0\n this.#startedProviders.clear()\n return errors\n }\n\n /** Runs labelled steps with a per-step timeout inside a global deadline, collecting failures. */\n #stepRunner(errors: unknown[]): (label: string, fn: () => unknown) => Promise<void> {\n const deadline = now() + this.#timeoutMs\n return async (label, fn) => {\n const budget = Math.max(0, Math.min(this.#hookTimeoutMs, deadline - now()))\n try {\n await runWithTimeout(label, fn, budget)\n } catch (error) {\n const failure = error instanceof StepTimeoutError ? error : shutdownError(label, error)\n errors.push(failure)\n this.#logger.debug(`${label} failed`, { err: error })\n }\n }\n }\n\n async #callPlugin(plugin: Plugin, hook: PluginHook): Promise<void> {\n const fn = plugin[hook]\n if (typeof fn !== 'function') return\n try {\n await fn.call(plugin, this.#context)\n } catch (error) {\n throw lifecycleError(`Plugin \"${plugin.name}\" ${hook}()`, error)\n }\n }\n\n async #callProvider(provider: ManagedInstance, hook: LifecycleHook): Promise<void> {\n if (!hasLifecycleHook(provider.instance, hook)) return\n try {\n await callLifecycleHook(provider.instance, hook)\n } catch (error) {\n throw lifecycleError(`${provider.displayName}.${hook}()`, error)\n }\n }\n\n // ---------------------------------------------------------------------------------------------\n // Signals\n // ---------------------------------------------------------------------------------------------\n\n #installSignals(): void {\n const proc = this.#process\n if (proc === undefined || this.#signals.length === 0 || this.#listening.length > 0) return\n for (const signal of this.#signals) proc.on(signal, this.#onSignal)\n this.#listening = this.#signals\n }\n\n #removeSignals(): void {\n const proc = this.#process\n if (proc === undefined) return\n for (const signal of this.#listening) proc.off(signal, this.#onSignal)\n this.#listening = []\n }\n\n readonly #onSignal = (signal: string): void => {\n const proc = this.#process\n if (proc === undefined) return\n if (this.#signalReceived) {\n this.#logger.warn(`Received ${signal} again: forcing exit`)\n proc.exit(FORCED_EXIT_CODE)\n return\n }\n this.#signalReceived = true\n this.#logger.info(`Received ${signal}: shutting down gracefully`)\n // success is logged by the stop itself (\"Application stopped\")\n this.stop().catch((error: unknown) => {\n this.#logger.error('The application stopped with errors', { err: error })\n proc.exitCode = 1\n })\n }\n}\n\nfunction entriesOf(values: ProviderValues): Iterable<readonly [ProviderKey, unknown]> {\n if (typeof (values as Partial<Iterable<unknown>>)[Symbol.iterator] === 'function') {\n return values as Iterable<readonly [ProviderKey, unknown]>\n }\n return Object.entries(values)\n}\n\nfunction flatten(error: unknown): unknown[] {\n return error instanceof ZnightAggregateError ? [...error.errors] : [error]\n}\n\nfunction shutdownError(step: string, error: unknown): ZnightError {\n return new ZnightError(ErrorCode.LifecycleFailed, `${step} failed: ${errorMessage(error)}`, { cause: error })\n}\n\n/** A duration in milliseconds: a non-negative number, `Infinity` meaning no limit. */\nfunction positive(value: number | undefined, fallback: number, name: string): number {\n if (value === undefined) return fallback\n if (typeof value !== 'number' || Number.isNaN(value) || value < 0) {\n throw new ZnightError(\n ErrorCode.InvalidDecorator,\n `Invalid ${name}: expected a positive number of milliseconds (or Infinity), got ${value}`,\n )\n }\n return value\n}\n","/**\n * Marker decorators. They are read from the source code by `@znight/compiler` and do nothing at\n * runtime: every factory returns the same shared no-op function (and the Vite plugin strips them\n * from the bundle by default). They support TypeScript `experimentalDecorators` (class, method and\n * parameter positions); class and method markers also type-check as standard decorators.\n *\n * Arguments marked _static_ must be statically evaluable by the compiler (literals, `const`\n * references, simple expressions); see docs/internals/architecture.md §4.6.\n */\nimport type { MethodInterceptor } from './aop.ts'\nimport type { Scope } from './metadata.ts'\n\n/** A class constructor, as received by a class decorator. */\ntype AnyClass = abstract new (...args: never[]) => unknown\n\n/** Marker usable on a class. */\nexport type ClassMarker = (target: AnyClass, context?: ClassDecoratorContext) => void\n\n/** Marker usable on a method (instance or static). */\nexport type MethodMarker = (\n target: object,\n propertyKeyOrContext: string | symbol | ClassMethodDecoratorContext,\n descriptor?: PropertyDescriptor,\n) => void\n\n/** Marker usable on a constructor or method parameter (`experimentalDecorators` only). */\nexport type ParameterMarker = (target: object, propertyKey: string | symbol | undefined, parameterIndex: number) => void\n\n/** Options of {@link Injectable} (static). */\nexport interface InjectableOptions {\n /** Lifetime of the instances. Default: `singleton`. */\n readonly scope?: Scope\n /** Qualifier, as with {@link Named}. */\n readonly name?: string\n /** Preferred candidate when several providers match an injection point, as with {@link Primary}. */\n readonly primary?: boolean\n}\n\n/** Options of {@link Provides} (static). */\nexport interface ProvidesOptions extends InjectableOptions {\n /** Name of a method of the provided value called on shutdown (`'end'`, `'close'`...). */\n readonly dispose?: string\n}\n\n/** Class implementing {@link MethodInterceptor} with options `O`. */\nexport type InterceptorClass<O> = abstract new (...args: never[]) => MethodInterceptor<O>\n\n/** Options argument of {@link Intercept}: required when the interceptor options do not accept `undefined`. */\nexport type InterceptOptionsArgs<O> = undefined extends O ? [options?: NoInfer<O>] : [options: NoInfer<O>]\n\nfunction marker(): void {\n // intentionally empty: decorators are compile-time markers\n}\n\nconst classMarker: ClassMarker = marker\nconst methodMarker: MethodMarker = marker\nconst parameterMarker: ParameterMarker = marker\nconst classOrMethodMarker: ClassMarker & MethodMarker = marker\n\n/**\n * Declares a provider class. Its constructor parameters are injected.\n *\n * ```ts\n * @Injectable()\n * export class UserService {\n * constructor(private readonly repository: UserRepository) {}\n * }\n * ```\n */\nexport function Injectable(_options?: InjectableOptions): ClassMarker {\n return classMarker\n}\n\n/** Declares a singleton whose {@link Provides} methods produce providers. */\nexport function Factory(): ClassMarker {\n return classMarker\n}\n\n/**\n * Declares a provider produced by a method of a {@link Factory} class. The explicit return type is\n * the provided type (`Promise<T>` makes it async, singletons only); parameters are injected.\n *\n * ```ts\n * @Factory()\n * export class DbFactory {\n * @Provides({ dispose: 'end' })\n * async createPool(config: DbConfig): Promise<Pool> { ... }\n * }\n * ```\n */\nexport function Provides(_options?: ProvidesOptions): MethodMarker {\n return methodMarker\n}\n\n/** Injects the provider qualified with `name` (see {@link Named}). `name` is static. */\nexport function Inject(_name: string): ParameterMarker {\n return parameterMarker\n}\n\n/** Marks a dependency as optional: `undefined` is injected when no provider exists. */\nexport function Optional(): ParameterMarker {\n return parameterMarker\n}\n\n/** Sets the qualifier of a provider class or `@Provides` method. `name` is static. */\nexport function Named(_name: string): ClassMarker & MethodMarker {\n return classOrMethodMarker\n}\n\n/** Makes a provider the preferred candidate when several providers match an injection point. */\nexport function Primary(): ClassMarker & MethodMarker {\n return classOrMethodMarker\n}\n\n/**\n * Intercepts calls to a method with an interceptor provider (AOP). The top-most `@Intercept` is the\n * outermost interceptor.\n *\n * ```ts\n * @Intercept(TimingInterceptor, { label: 'users.find' })\n * async find(id: string): Promise<User> { ... }\n * ```\n */\nexport function Intercept<O>(_interceptor: InterceptorClass<O>, ..._options: InterceptOptionsArgs<O>): MethodMarker {\n return methodMarker\n}\n","/**\n * Custom parameter decorators (RFC 0010). `createParamDecorator` returns a marker decorator, read\n * by `@znight/compiler`, and keeps the resolvers that the generated `invoke` of each transport calls.\n */\nimport type { ParameterMarker } from './decorators.ts'\n\n/**\n * Resolver contexts by transport. Each transport package adds its own entry through declaration\n * merging (`http: HttpContext` in `@znight/http`, `graphql: ResolverContext`, `messaging:\n * InboundMessage`); a transport that is not installed has no entry.\n *\n * ```ts\n * declare module '@znight/core' {\n * interface ParamContexts {\n * http: HttpContext\n * }\n * }\n * ```\n */\n// biome-ignore lint/suspicious/noEmptyInterface: augmented by the transport packages (declaration merging)\nexport interface ParamContexts {}\n\n/** A provider computing the value of a parameter, in the scope of the call (RFC 0010 §4.6). */\nexport interface ParamResolver<C, T, D = undefined> {\n resolve(ctx: C, data: D): T | PromiseLike<T>\n}\n\n/** A resolver function: receives the context of its transport and the data argument of the use. */\nexport type ParamResolverFunction<C, T, D> = (ctx: C, data: D) => T | PromiseLike<T>\n\n/** The class of a provider implementing {@link ParamResolver} (bound at build time, resolved in the scope of the call). */\nexport type ParamResolverClass<C, T, D> = abstract new (...args: never[]) => ParamResolver<C, T, D>\n\n/** Computes the value of a parameter: a function, or the class of a provider implementing {@link ParamResolver}. */\nexport type ParamResolverOf<C, T, D> = ParamResolverFunction<C, T, D> | ParamResolverClass<C, T, D>\n\n/** The resolvers of a definition, by transport (keys of {@link ParamContexts}). */\nexport type ParamResolvers<T, D> = {\n readonly [K in keyof ParamContexts]?: ParamResolverOf<ParamContexts[K], T, D>\n}\n\n/** Arguments of a use: none when `D` is `undefined`, optional when `D` includes `undefined`, required otherwise. */\nexport type ParamDataArgs<D> = undefined extends D ? [data?: D] : [data: D]\n\n/** What {@link createParamDecorator} returns: the decorator (a no-op marker) and its resolvers, for generated code. */\nexport interface ParamDecorator<T, D = undefined> {\n (...data: ParamDataArgs<D>): ParameterMarker\n /** The resolvers of the definition, frozen. */\n readonly resolvers: ParamResolvers<T, D>\n}\n\n/**\n * The resolver function of a definition for a transport, as generated code calls it:\n * `(CurrentUser.resolvers.http as ParamFunctionOf<typeof CurrentUser, 'http'>)(ctx, undefined)`.\n * The compiler emits it only for function resolvers.\n */\nexport type ParamFunctionOf<P extends { readonly resolvers: object }, K extends keyof P['resolvers']> = Extract<\n NonNullable<P['resolvers'][K]>,\n // biome-ignore lint/suspicious/noExplicitAny: matches every function type, whatever its parameters\n (...args: any[]) => unknown\n>\n\nfunction marker(): void {\n // intentionally empty: decorators are compile-time markers\n}\n\nconst parameterMarker: ParameterMarker = marker\n\n/**\n * Defines a parameter decorator whose value is computed per call by a resolver of the handler's\n * transport (RFC 0010). `T` (required) is the injected type, checked at build time against every\n * decorated parameter; `D` is the type of the data argument (none by default). The definition must\n * be an exported top-level `const`: the generated module imports it.\n *\n * ```ts\n * export const CurrentUser = createParamDecorator<User>({\n * http: ctx => userOf(ctx.state),\n * graphql: ctx => userOf(ctx.operation.state),\n * })\n *\n * @Get('/me')\n * me(@CurrentUser() user: User) { ... }\n * ```\n */\nexport function createParamDecorator<T, D = undefined>(resolvers: ParamResolvers<T, D>): ParamDecorator<T, D> {\n const decorator = ((..._data: ParamDataArgs<D>): ParameterMarker => parameterMarker) as ParamDecorator<T, D>\n Object.defineProperty(decorator, 'resolvers', { value: Object.freeze({ ...resolvers }), enumerable: true })\n return decorator\n}\n","import type { Application } from './application.ts'\nimport type { Container } from './container.ts'\nimport type { Hooks } from './hooks.ts'\nimport type { CoreLogger } from './logger.ts'\nimport type { ZnightMetadata } from './metadata.ts'\nimport type { ProviderKey } from './tokens.ts'\n\n/**\n * A runtime feature (HTTP server, message consumers, configuration, observability...). Every hook\n * is optional and may be async. Hooks run in plugin order, stop hooks in reverse order.\n *\n * 1. `register`: provide externals (`ctx.container.registerValue()` / `register()`), before\n * `container.init()`.\n * 2. `onBootstrap`: after `container.init()`: register routes, consumers... (no traffic yet).\n * 3. `onStart`: start accepting traffic (listen, subscribe), after providers' `onStart`.\n * 4. `onReady`: everything started.\n * 5. `onStop`: stop accepting traffic and drain in-flight work, before providers stop.\n * 6. `onDispose`: release infrastructure (connections, flush buffers), after providers are disposed.\n */\nexport interface Plugin {\n /** Unique name (used by `getPlugin()` and in messages). */\n readonly name: string\n register?(ctx: PluginContext): void | Promise<void>\n onBootstrap?(ctx: PluginContext): void | Promise<void>\n onStart?(ctx: PluginContext): void | Promise<void>\n onReady?(ctx: PluginContext): void | Promise<void>\n onStop?(ctx: PluginContext): void | Promise<void>\n onDispose?(ctx: PluginContext): void | Promise<void>\n /**\n * The providers (classes or tokens) the plugin needs at boot although the metadata does not make\n * them entry points: classes given in its options (`HttpPlugin`'s global `guards`,\n * `interceptors`, `exceptionMappers`), or providers it derives from its own metadata section.\n *\n * Read by tools that restrict the boot to a few providers (`init: { only }`), such as `TestApp`\n * of `@znight/testing`: they create these providers at boot with their dependencies, because an\n * async factory cannot run on demand. The application itself never calls it.\n *\n * Called before the application is created (before `register`), possibly several times: it must\n * be cheap and side-effect free, and SHOULD NOT throw (report invalid options in `onBootstrap`).\n * Options given as a function of the container cannot be read yet: return what is known (`[]`).\n */\n initRoots?(context: PluginRootsContext): readonly ProviderKey[]\n}\n\n/** What {@link Plugin.initRoots} receives. */\nexport interface PluginRootsContext {\n /** The metadata the application will be created with. */\n readonly metadata: ZnightMetadata\n}\n\n/** Name of a {@link Plugin} hook. */\nexport type PluginHook = 'register' | 'onBootstrap' | 'onStart' | 'onReady' | 'onStop' | 'onDispose'\n\n/** What a plugin hook receives. */\nexport interface PluginContext {\n readonly app: Application\n readonly container: Container\n readonly metadata: ZnightMetadata\n readonly hooks: Hooks\n /** Live, delegating logger: always forwards to the logger currently installed on the application. */\n readonly logger: CoreLogger\n /** Another plugin of the application, by name. */\n getPlugin<P extends Plugin = Plugin>(name: string): P | undefined\n}\n\n/**\n * Plugin options given directly or computed from the container (evaluated in `onBootstrap`, once\n * every provider exists):\n *\n * ```ts\n * HttpPlugin.configure(c => ({ port: c.get(AppConfig).port }))\n * ```\n *\n * Options that are themselves a function cannot use this form.\n */\nexport type PluginOptions<O> = O | ((container: Container) => O)\n\n/** Resolves {@link PluginOptions}: calls the function form with the container, returns the others as is. */\nexport function resolveOptions<O>(options: PluginOptions<O>, container: Container): O {\n return typeof options === 'function' ? (options as (container: Container) => O)(container) : options\n}\n"],"mappings":";;;;;;;;;;;;;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ACT;;;;;;;;;;AAWA,SAAgB,UAAa,cAAmC,GAAG,UAAiD;CAClH,OAAO;AACT;;AC/DA,SAAS,SAAe,CAExB;AAEA,MAAM,kBAAmC;;;;;;;;;;;;;;;;;AAkBzC,SAAgB,qBAAuC,WAAuD;CAC5G,MAAM,cAAc,GAAG,UAA6C;CACpE,OAAO,eAAe,WAAW,aAAa;EAAE,OAAO,OAAO,OAAO,EAAE,GAAG,UAAU,CAAC;EAAG,YAAY;CAAK,CAAC;CAC1G,OAAO;AACT;;;ACVA,SAAgB,eAAkB,SAA2B,WAAyB;CACpF,OAAO,OAAO,YAAY,aAAc,QAAwC,SAAS,IAAI;AAC/F"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["ErrorCodes","marker","parameterMarker"],"sources":["../src/errors.ts","../src/utils.ts","../src/aop.ts","../src/tokens.ts","../src/container-errors.ts","../src/definition.ts","../src/slot.ts","../src/graph.ts","../src/lifecycle.ts","../src/metadata.ts","../src/runtime-errors.ts","../src/scope.ts","../src/container.ts","../src/hooks.ts","../src/logger.ts","../src/process.ts","../src/application.ts","../src/decorators.ts","../src/params.ts","../src/plugin.ts"],"sourcesContent":["/**\n * Error codes shared by the compiler (build-time diagnostics) and the runtime (`ZnightError`).\n * Documented in docs/internals/architecture.md (§4.8) and docs/reference/error-codes.md.\n *\n * Ranges (the catalogue is closed: third-party packages get no `ZNIGHT` code):\n * - `ZNIGHT001`–`ZNIGHT029`: the core, the compiler and the features shipped in 0.1 (http,\n * messaging, config, observability).\n * - From `ZNIGHT030`, each first-party package reserves a block of ten: `ZNIGHT030`–`039`\n * `@znight/openapi`, `ZNIGHT040`–`049` `@znight/schedule`, `ZNIGHT050`–`059` `@znight/websocket`\n * (reserved), `ZNIGHT060`–`069` `@znight/graphql`, `ZNIGHT070`–`079` `@znight/events`.\n *\n * Within a range, codes are allocated in order without gaps. A package uses its block for its own\n * failure modes, with one catch-all code for invalid usage and options, and reuses a lower code\n * when the meaning is the same (a decorator on the wrong target is always `ZNIGHT005`). Codes never\n * change meaning.\n */\nexport const ErrorCode = {\n /** Missing provider for a required dependency. */\n MissingProvider: 'ZNIGHT001',\n /** Circular dependency in the provider graph. */\n CircularDependency: 'ZNIGHT002',\n /** A singleton depends (directly or through transient providers) on a request-scoped provider. */\n ScopeMismatch: 'ZNIGHT003',\n /** Several providers for the exact same type without qualifier or `@Primary`. */\n DuplicateProvider: 'ZNIGHT004',\n /** Invalid decorator usage. */\n InvalidDecorator: 'ZNIGHT005',\n /** Missing required configuration value. */\n MissingConfig: 'ZNIGHT006',\n /** Invalid route definition. */\n InvalidRoute: 'ZNIGHT007',\n /** Several candidates for an interface or base type without `@Primary`. */\n AmbiguousInjection: 'ZNIGHT008',\n /** Invalid lifecycle hook. */\n InvalidLifecycleHook: 'ZNIGHT009',\n /** The type of an injection point cannot be resolved. */\n UnresolvableType: 'ZNIGHT010',\n /** Invalid message consumer definition. */\n InvalidConsumer: 'ZNIGHT011',\n /** Invalid config property. */\n InvalidConfig: 'ZNIGHT012',\n /** Request-scoped provider resolved outside of a request scope. */\n NoActiveScope: 'ZNIGHT013',\n /** Async factory on a non-singleton provider. */\n AsyncNonSingleton: 'ZNIGHT014',\n /** A provider factory threw or rejected. */\n InstantiationFailed: 'ZNIGHT015',\n /** The container was modified after `init()`. */\n ContainerSealed: 'ZNIGHT016',\n /** Non-primitive input injected without a validation schema. */\n UnvalidatedInput: 'ZNIGHT017',\n /** Incompatible versions (metadata format, packages, compiler extension API). */\n VersionMismatch: 'ZNIGHT018',\n /** Provider unreachable from any root. */\n UnusedProvider: 'ZNIGHT019',\n /** The generated module is imported by a provider module (ESM cycle). */\n GeneratedModuleCycle: 'ZNIGHT020',\n /** A lifecycle hook or shutdown step failed or timed out. */\n LifecycleFailed: 'ZNIGHT021',\n /** A source file could not be parsed. */\n SyntaxError: 'ZNIGHT022',\n /**\n * A route has no decision of a required route decorator group (build time), or a decision that\n * no guard of its chain enforces (boot). `@znight/http`, RFC 0001.\n */\n MissingRouteDecision: 'ZNIGHT023',\n\n // ZNIGHT030–039: @znight/openapi (RFC 0002)\n /**\n * Invalid OpenAPI definition: `@OpenApiDocument` options, `@Api*` usage, static values,\n * `securityScheme()`; at runtime, `OpenApiPlugin` options, missing metadata, stale prebuilt file.\n */\n InvalidOpenApiDefinition: 'ZNIGHT030',\n /** The success response of a route cannot be documented and no `@ApiResponse` covers it. */\n UndocumentedResponse: 'ZNIGHT031',\n /** A documented type has no JSON Schema, or does not serialise as declared. */\n UnrepresentableType: 'ZNIGHT032',\n /** Two OpenAPI operations have the same id. */\n DuplicateOperationId: 'ZNIGHT033',\n /** Two different declarations or schemas for one OpenAPI component name. */\n SchemaNameConflict: 'ZNIGHT034',\n /** The OpenAPI documentation of a route contradicts the route. */\n InconsistentOperation: 'ZNIGHT035',\n /** Invalid OpenAPI security requirement or security decision. */\n InvalidSecurityRequirement: 'ZNIGHT036',\n /** A schema could not be converted to JSON Schema while the OpenAPI document was assembled. */\n SchemaConversionFailed: 'ZNIGHT037',\n\n // ZNIGHT040–049: @znight/schedule (RFC 0004)\n /**\n * Invalid schedule: cron expression, duration, time zone, job options or method signature; at\n * runtime, `SchedulePlugin` options, job overrides, metadata, `parseCron` / `registry.add*`.\n */\n InvalidSchedule: 'ZNIGHT040',\n /** Two jobs share a name. */\n DuplicateJob: 'ZNIGHT041',\n /** No job has this name (job override, `registry.trigger` / `remove`). */\n UnknownJob: 'ZNIGHT042',\n /** A job requires a lock but `SchedulePlugin` has no lock store. */\n MissingLockStore: 'ZNIGHT043',\n /** A scheduled run was aborted (`ctx.signal.reason`, `JobAbortedError`); never thrown by the framework. */\n JobAborted: 'ZNIGHT044',\n\n // ZNIGHT060–069: @znight/graphql (RFC 0005, RFC 0007)\n /** A TypeScript type cannot be mapped to a GraphQL type, or a resolver lacks the annotation it needs. */\n InvalidGraphQLType: 'ZNIGHT060',\n /** Two declarations or root fields share a GraphQL name, or a name is invalid or reserved. */\n GraphQLNameConflict: 'ZNIGHT061',\n /**\n * Invalid resolver structure: `@ResolveField` without `@Parent()`, a subscription not returning an\n * async iterable, no `@Query`, inherited handlers, resolvers in a compiled library.\n */\n InvalidResolver: 'ZNIGHT062',\n /**\n * Invalid input position: a type used as input and output, a getter, a union, a cycle of non-null\n * input fields, a default value not matching its type.\n */\n InvalidGraphQLInput: 'ZNIGHT063',\n /** The members of a GraphQL union (or the implementations of an interface) cannot be told apart at runtime. */\n UnresolvableAbstractType: 'ZNIGHT064',\n /**\n * Invalid loader: `@Loader()` on a type that is not `Loader<L>`, `L` not a `BatchLoad`; at runtime,\n * a batch function returning another number of values than keys.\n */\n InvalidLoader: 'ZNIGHT065',\n /**\n * Invalid GraphQL setup at boot: malformed or version-skewed metadata, invalid schema, invalid\n * `GraphQLPlugin` options, missing `HttpPlugin`, scalar name mismatch.\n */\n InvalidGraphQLSetup: 'ZNIGHT066',\n /**\n * Invalid schema-first SDL (RFC 0007): no `.graphql` file matches, a syntax error, a graphql-js\n * schema validation error, a scalar without `scalar()` definition, an unsupported construct.\n */\n InvalidGraphQLSdl: 'ZNIGHT067',\n /**\n * Schema-first resolvers do not match the SDL (RFC 0007): a field without resolver, a resolver,\n * type or argument the SDL does not declare, a signature that does not conform to the SDL types.\n */\n GraphQLSchemaMismatch: 'ZNIGHT068',\n\n // ZNIGHT070–079: @znight/events (RFC 0011)\n /**\n * Invalid event listener: an `@OnEvent` method whose parameter is not a class (or a union of\n * classes), a generic or optional event, an event class the generated module cannot import, invalid\n * options, the NestJS string form, a detached listener depending on a request-scoped external.\n */\n InvalidEventListener: 'ZNIGHT070',\n} as const\n\nexport type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode]\n\n/** Short human readable description of every error code. */\nexport const ERROR_DESCRIPTIONS: Readonly<Record<ErrorCode, string>> = {\n ZNIGHT001: 'Missing provider: a required dependency has no provider',\n ZNIGHT002: 'Circular dependency detected in the provider graph',\n ZNIGHT003: 'Scope mismatch: a singleton cannot depend on a request-scoped provider',\n ZNIGHT004: 'Duplicate provider: several providers for the same type without qualifier or @Primary',\n ZNIGHT005: 'Invalid decorator usage',\n ZNIGHT006: 'Missing required configuration value',\n ZNIGHT007: 'Invalid route definition',\n ZNIGHT008: 'Ambiguous injection: several candidates without @Primary',\n ZNIGHT009: 'Invalid lifecycle hook',\n ZNIGHT010: 'Unresolvable injection type',\n ZNIGHT011: 'Invalid message consumer definition',\n ZNIGHT012: 'Invalid config property',\n ZNIGHT013: 'Request-scoped provider resolved outside of a request scope',\n ZNIGHT014: 'Async factory on a non-singleton provider',\n ZNIGHT015: 'Provider instantiation failed',\n ZNIGHT016: 'Container sealed: providers cannot be registered or overridden after init()',\n ZNIGHT017: 'Unvalidated input: non-primitive input injected without a schema',\n ZNIGHT018: 'Version mismatch',\n ZNIGHT019: 'Unused provider: unreachable from any root',\n ZNIGHT020: 'The generated module is imported by a provider module (ESM cycle)',\n ZNIGHT021: 'Lifecycle hook or shutdown step failed or timed out',\n ZNIGHT022: 'Syntax error: a source file could not be parsed',\n ZNIGHT023: 'Missing route decision: a route has no decision of a required group, or no guard enforces it',\n ZNIGHT030: 'Invalid OpenAPI definition',\n ZNIGHT031: 'Undocumented response: the success response of a route cannot be documented',\n ZNIGHT032: 'Unrepresentable type: a documented type has no JSON Schema or does not serialise as declared',\n ZNIGHT033: 'Duplicate OpenAPI operation id',\n ZNIGHT034: 'Schema name conflict: two different schemas for one OpenAPI component name',\n ZNIGHT035: 'Inconsistent operation: the OpenAPI documentation contradicts the route',\n ZNIGHT036: 'Invalid OpenAPI security requirement',\n ZNIGHT037: 'Schema conversion failed: a schema could not be converted to JSON Schema',\n ZNIGHT040: 'Invalid schedule: cron expression, duration, time zone, options or job signature',\n ZNIGHT041: 'Duplicate job: two jobs share a name',\n ZNIGHT042: 'Unknown job: no job has this name',\n ZNIGHT043: 'Missing lock store: a job requires a lock but SchedulePlugin has no store',\n ZNIGHT044: 'Job aborted: a scheduled run was aborted (timeout, lost lock, removal or shutdown)',\n ZNIGHT060: 'Invalid GraphQL type: a TypeScript type cannot be mapped to a GraphQL type',\n ZNIGHT061: 'GraphQL name conflict: two types or root fields share a name, or a name is invalid or reserved',\n ZNIGHT062: 'Invalid resolver: the structure of a GraphQL resolver is invalid',\n ZNIGHT063: 'Invalid GraphQL input: a type cannot be used in an input position',\n ZNIGHT064: 'Unresolvable abstract type: the members of a GraphQL union or interface cannot be told apart at runtime',\n ZNIGHT065: 'Invalid loader: not a Loader of a BatchLoad provider, or a batch returning the wrong number of values',\n ZNIGHT066: 'Invalid GraphQL setup: metadata, schema, GraphQLPlugin options, driver or HttpPlugin missing',\n ZNIGHT067: 'Invalid GraphQL SDL: the schema-first .graphql files cannot be read, parsed or validated',\n ZNIGHT068: 'GraphQL schema mismatch: schema-first resolvers do not cover or conform to the SDL',\n ZNIGHT070: 'Invalid event listener: an @OnEvent method does not listen to a class, or its options are invalid',\n}\n\nexport interface ZnightErrorOptions extends ErrorOptions {\n /** Suggestions displayed under the error message. */\n readonly hints?: readonly string[]\n}\n\n/** Base class of every error thrown by Znight at runtime. */\nexport class ZnightError extends Error {\n readonly code: ErrorCode\n readonly hints: readonly string[]\n\n constructor(code: ErrorCode, message: string, options: ZnightErrorOptions = {}) {\n super(`${code}: ${message}`, options)\n this.name = 'ZnightError'\n this.code = code\n this.hints = options.hints ?? []\n }\n}\n","/** Internal helpers (not part of the public API). */\n\n/** Whether `value` is a promise-like object (has a callable `then`). */\nexport function isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n value !== null &&\n (typeof value === 'object' || typeof value === 'function') &&\n typeof (value as { then?: unknown }).then === 'function'\n )\n}\n\n/** Message of any thrown value. */\nexport function errorMessage(error: unknown): string {\n if (error instanceof Error) return error.message\n if (typeof error === 'string') return error\n try {\n return String(error)\n } catch {\n return Object.prototype.toString.call(error)\n }\n}\n\n/** Whether the runtime runs in development mode (`NODE_ENV !== 'production'`). */\nexport function isDevelopment(): boolean {\n return globalThis.process?.env?.['NODE_ENV'] !== 'production'\n}\n\n/** Monotonic clock in milliseconds. */\nexport function now(): number {\n return performance.now()\n}\n","import type { MethodInterception } from './metadata.ts'\n\nimport { ErrorCode, ZnightError } from './errors.ts'\nimport { isDevelopment, isThenable } from './utils.ts'\n\n/** A call to an intercepted method, as seen by a {@link MethodInterceptor}. */\nexport interface MethodInvocation {\n /** The instance the method is called on. */\n readonly target: object\n /** Name of the provider (display name) the method belongs to. */\n readonly className: string\n readonly methodName: string\n /** Arguments of this call (as passed to this interceptor). */\n readonly args: readonly unknown[]\n /** Whether the intercepted method is async: interceptors must then return a promise. */\n readonly isAsync: boolean\n /**\n * Calls the next interceptor, or the original method for the innermost one, with `args` (default:\n * the current arguments) and returns its result. May be called several times (retries).\n */\n proceed(args?: readonly unknown[]): unknown\n}\n\n/**\n * A provider wrapping method calls (`@Intercept(MyInterceptor, options)`). It must return the value\n * of `invocation.proceed()` (or a replacement): a promise for async methods, a plain value for\n * synchronous ones.\n *\n * ```ts\n * @Injectable()\n * export class TimingInterceptor implements MethodInterceptor<{ label?: string }> {\n * async intercept(invocation: MethodInvocation, options: { label?: string }) {\n * const start = performance.now()\n * try { return await invocation.proceed() }\n * finally { console.log(options.label ?? invocation.methodName, performance.now() - start) }\n * }\n * }\n * ```\n */\nexport interface MethodInterceptor<O = unknown> {\n intercept(invocation: MethodInvocation, options: O): unknown\n}\n\n/** One interceptor of a chain with its options. */\nexport interface InterceptorLink {\n readonly interceptor: MethodInterceptor\n readonly options?: unknown\n}\n\nexport interface InterceptMethodOptions {\n /** Name used in messages and exposed as `invocation.className`. Default: the constructor name. */\n readonly className?: string\n /** Whether the method is async. Default: `false`. */\n readonly async?: boolean\n /**\n * Throw when an interceptor returns a thenable for a synchronous method.\n * Default: `true` unless `NODE_ENV === 'production'`.\n */\n readonly checkSync?: boolean\n}\n\ntype Method = (this: unknown, ...args: unknown[]) => unknown\n\nclass Chain {\n readonly original: Method\n readonly links: readonly InterceptorLink[]\n readonly className: string\n readonly methodName: string\n readonly isAsync: boolean\n readonly checkSync: boolean\n\n constructor(\n original: Method,\n links: readonly InterceptorLink[],\n className: string,\n methodName: string,\n isAsync: boolean,\n checkSync: boolean,\n ) {\n this.original = original\n this.links = links\n this.className = className\n this.methodName = methodName\n this.isAsync = isAsync\n this.checkSync = checkSync\n }\n\n call(index: number, target: object, args: readonly unknown[]): unknown {\n if (index === this.links.length) return this.original.apply(target, args as unknown[])\n const link = this.links[index] as InterceptorLink\n const invocation = new Invocation(this, index, target, args)\n const result = link.interceptor.intercept(invocation, link.options)\n if (this.checkSync && !this.isAsync && result !== invocation.lastResult && isThenable(result)) {\n throw new ZnightError(\n ErrorCode.InvalidDecorator,\n `Interceptor ${interceptorName(link.interceptor)} returned a promise for the synchronous method ` +\n `${this.className}.${this.methodName}()`,\n { hints: ['Make the method async, or return invocation.proceed() synchronously from the interceptor'] },\n )\n }\n return result\n }\n}\n\nclass Invocation implements MethodInvocation {\n readonly target: object\n readonly args: readonly unknown[]\n /** Last value returned by `proceed()` (lets the sync check accept pass-through thenables). */\n lastResult: unknown = undefined\n readonly #chain: Chain\n readonly #index: number\n\n constructor(chain: Chain, index: number, target: object, args: readonly unknown[]) {\n this.#chain = chain\n this.#index = index\n this.target = target\n this.args = args\n }\n\n get className(): string {\n return this.#chain.className\n }\n\n get methodName(): string {\n return this.#chain.methodName\n }\n\n get isAsync(): boolean {\n return this.#chain.isAsync\n }\n\n proceed(args?: readonly unknown[]): unknown {\n this.lastResult = this.#chain.call(this.#index + 1, this.target, args ?? this.args)\n return this.lastResult\n }\n}\n\nfunction interceptorName(interceptor: MethodInterceptor): string {\n const name = (interceptor as { constructor?: { name?: unknown } }).constructor?.name\n return typeof name === 'string' && name !== '' && name !== 'Object' ? name : '<anonymous interceptor>'\n}\n\nfunction assertInterceptor(value: unknown, where: string): asserts value is MethodInterceptor {\n if (\n value === null ||\n (typeof value !== 'object' && typeof value !== 'function') ||\n typeof (value as { intercept?: unknown }).intercept !== 'function'\n ) {\n throw new ZnightError(ErrorCode.InvalidDecorator, `${where}: the interceptor has no intercept() method`, {\n hints: ['Interceptors passed to @Intercept() must implement MethodInterceptor'],\n })\n }\n}\n\n/**\n * Wraps `target[methodName]` with `chain` (first link = outermost interceptor). The wrapper is\n * installed as an own, non-enumerable property of `target` (no Proxy): `#private` fields keep\n * working and calls through `this` (self-invocation) are intercepted too.\n *\n * @throws ZnightError (ZNIGHT005) when the method or an interceptor is invalid.\n */\nexport function interceptMethod(\n target: object,\n methodName: string,\n chain: readonly InterceptorLink[],\n options: InterceptMethodOptions = {},\n): void {\n const className = options.className ?? (target.constructor?.name || 'Object')\n const original: unknown = (target as Record<string, unknown>)[methodName]\n if (typeof original !== 'function') {\n throw new ZnightError(ErrorCode.InvalidDecorator, `Cannot intercept ${className}.${methodName}: it is not a method`)\n }\n if (chain.length === 0) return\n for (const link of chain) assertInterceptor(link.interceptor, `Cannot intercept ${className}.${methodName}()`)\n const compiled = new Chain(\n original as Method,\n [...chain],\n className,\n methodName,\n options.async ?? false,\n options.checkSync ?? isDevelopment(),\n )\n const wrapper = function (this: unknown, ...args: unknown[]): unknown {\n return compiled.call(0, this === undefined || this === null ? target : (this as object), args)\n }\n Object.defineProperty(wrapper, 'name', { value: methodName, configurable: true })\n Object.defineProperty(target, methodName, { value: wrapper, writable: true, configurable: true, enumerable: false })\n}\n\n/**\n * Applies the interceptors of a provider definition to a freshly created instance. `deps` are the\n * resolved dependencies of the provider (`InterceptorBinding.dep` indexes into them).\n */\nexport function applyInterceptors(\n target: object,\n interceptions: Readonly<Record<string, MethodInterception>>,\n deps: readonly unknown[],\n className?: string,\n): void {\n const name = className ?? (target.constructor?.name || 'Object')\n for (const [methodName, interception] of Object.entries(interceptions)) {\n const links: InterceptorLink[] = []\n for (const binding of interception.chain) {\n if (binding.dep < 0 || binding.dep >= deps.length) {\n throw new ZnightError(\n ErrorCode.InvalidDecorator,\n `Cannot intercept ${name}.${methodName}(): interceptor dependency #${binding.dep} does not exist`,\n )\n }\n const interceptor = deps[binding.dep]\n assertInterceptor(interceptor, `Cannot intercept ${name}.${methodName}()`)\n links.push({ interceptor, options: binding.options })\n }\n interceptMethod(target, methodName, links, { className: name, async: interception.async })\n }\n}\n","import type { ProviderClass, Token } from './metadata.ts'\n\ndeclare const tokenType: unique symbol\n\n/**\n * A {@link Token} carrying the type of the value it identifies. It is a plain string at runtime;\n * the type parameter only exists for the type checker:\n *\n * ```ts\n * export const ClockToken: TypedToken<Clock> = token<Clock>('@acme/time#Clock')\n * container.registerValue(ClockToken, systemClock) // value checked against Clock\n * const clock = container.get(ClockToken) // Clock\n * ```\n */\nexport type TypedToken<T> = Token & { readonly [tokenType]?: T }\n\n/**\n * A class used as a lookup key, matched through its `prototype` (accepts classes with private or\n * protected constructors, which are not assignable to {@link ProviderClass}).\n */\nexport interface ClassKey<T = unknown> {\n readonly prototype: T\n}\n\n/** Anything the container accepts to look a provider up: a token, an alias, a display name or a class. */\nexport type ProviderKey<T = unknown> = TypedToken<T> | ProviderClass<T> | ClassKey<T>\n\n/** Declares a {@link TypedToken}. Zero runtime cost: returns `id` unchanged. */\nexport function token<T>(id: string): TypedToken<T> {\n return id\n}\n\n/** Tokens under which `@znight/core` exposes its own objects to the container. */\nexport const CoreTokens: {\n /** The {@link Container} itself. */\n readonly Container: Token\n /** The running `Application` (registered by `Application.create`). */\n readonly Application: Token\n /** The application `Hooks` (registered by `Application.create`). */\n readonly Hooks: Token\n /** The live application `CoreLogger` (registered by `Application.create`). */\n readonly Logger: Token\n} = Object.freeze({\n Container: '@znight/core#Container',\n Application: '@znight/core#Application',\n Hooks: '@znight/core#Hooks',\n Logger: '@znight/core#CoreLogger',\n})\n\n/**\n * Human readable name of a token: the part after the last `#`\n * (`src/users/user.service.ts#UserService` → `UserService`, `src/db.ts#DbFactory.createPool` →\n * `DbFactory.createPool`). Tokens without `#` are returned unchanged.\n */\nexport function displayName(token: Token): string {\n const index = token.lastIndexOf('#')\n return index === -1 ? token : token.slice(index + 1)\n}\n\n/** Formats a dependency path with display names: `UserController -> UserService -> Database`. */\nexport function formatPath(tokens: readonly Token[]): string {\n return tokens.map(displayName).join(' -> ')\n}\n\n/** `UserService (src/users/user.service.ts#UserService)`, or just the token when it has no `#`. */\nexport function describeToken(token: Token): string {\n const name = displayName(token)\n return name === token ? token : `${name} (${token})`\n}\n\n/** Describes any provider key for error messages. */\nexport function describeKey(key: unknown): string {\n if (typeof key === 'string') return describeToken(key)\n if (typeof key === 'function') return `class ${key.name || '<anonymous>'}`\n return String(key)\n}\n","/** Error factories of the container (internal): one place for codes, messages and hints. */\n\nimport type { ZnightMetadata } from './metadata.ts'\nimport type { Slot } from './slot.ts'\n\nimport { ErrorCode, ZnightError } from './errors.ts'\nimport { describeKey, describeToken } from './tokens.ts'\n\n/** Why a resolution cannot proceed, from the container status. */\nexport type Unavailability = 'open' | 'failed' | 'disposed'\n\nexport function invalidMetadataError(): ZnightError {\n return new ZnightError(\n ErrorCode.VersionMismatch,\n 'Invalid metadata: expected the object generated by @znight/compiler ({ version, providers, resolutionOrder })',\n )\n}\n\nexport function metadataVersionError(metadata: ZnightMetadata, expected: number): ZnightError {\n const compiler = metadata.compiler === undefined ? '' : ` (generated by @znight/compiler ${metadata.compiler})`\n return new ZnightError(\n ErrorCode.VersionMismatch,\n `Unsupported metadata version ${String(metadata.version)}${compiler}: @znight/core expects version ${expected}`,\n { hints: ['Regenerate the metadata (znight generate) with a @znight/compiler version matching @znight/core'] },\n )\n}\n\nfunction providedBy(slot: Slot | undefined): string {\n const plugin = slot?.external?.providedBy\n return plugin === undefined ? '' : ` (provided by ${plugin})`\n}\n\nexport function notFoundError(key: unknown, slot?: Slot): ZnightError {\n const hints: string[] = []\n const plugin = slot?.external?.providedBy\n if (plugin !== undefined) hints.push(`Add ${plugin} to Application.create({ plugins })`)\n if (typeof key === 'function') {\n hints.push(`Decorate ${key.name || 'the class'} with @Injectable() and regenerate the metadata (znight generate)`)\n } else {\n hints.push('Supply it with Application.create({ providers }) or container.registerValue()')\n }\n return new ZnightError(ErrorCode.MissingProvider, `No provider for ${describeKey(key)}${providedBy(slot)}`, {\n hints,\n })\n}\n\nexport function unknownClassError(action: string, key: unknown): ZnightError {\n return new ZnightError(\n ErrorCode.MissingProvider,\n `Cannot ${action} ${describeKey(key)}: it is not a known provider`,\n {\n hints: ['Pass the provider token, or a class registered in the compiled metadata'],\n },\n )\n}\n\nexport function ambiguousNameError(name: string, matches: readonly Slot[]): ZnightError {\n return new ZnightError(\n ErrorCode.AmbiguousInjection,\n `\"${name}\" is ambiguous: it matches ${matches.map(slot => slot.token).join(', ')}`,\n { hints: ['Use the class or the full token instead of the display name'] },\n )\n}\n\nexport function noScopeError(slot: Slot): ZnightError {\n return new ZnightError(\n ErrorCode.NoActiveScope,\n `${describeToken(slot.token)} is request-scoped and was resolved outside of a request scope`,\n {\n hints: [\n 'Resolve it inside container.runInScope()',\n 'In singletons, inject it as Lazy<T> and call get() during the request',\n ],\n },\n )\n}\n\nexport function closedScopeError(slot: Slot): ZnightError {\n return new ZnightError(\n ErrorCode.NoActiveScope,\n `${describeToken(slot.token)} was resolved in a request scope that is already closed`,\n { hints: ['Await every asynchronous operation of a request inside the runInScope() callback'] },\n )\n}\n\nexport function missingScopeValueError(slot: Slot): ZnightError {\n return new ZnightError(\n ErrorCode.NoActiveScope,\n `No value for the request-scoped ${describeToken(slot.token)} in the current scope${providedBy(slot)}`,\n { hints: ['Pass it to container.runInScope(fn, [[token, value]]) or set it with currentScope().set()'] },\n )\n}\n\nexport function sealedError(action: string, key: unknown): ZnightError {\n return new ZnightError(\n ErrorCode.ContainerSealed,\n `Cannot ${action} ${describeKey(key)}: the container is sealed (init() has been called)`,\n { hints: ['Register providers, values and overrides before init(), e.g. in Plugin.register()'] },\n )\n}\n\nexport function duplicateRegistrationError(action: string, slot: Slot): ZnightError {\n return new ZnightError(\n ErrorCode.DuplicateProvider,\n `Cannot ${action} ${describeToken(slot.token)}: it is already registered by ${slot.origin ?? 'another registration'}`,\n { hints: ['Use container.override() (or Application.create({ overrides })) to replace a provider'] },\n )\n}\n\nexport function compiledProviderError(action: string, slot: Slot): ZnightError {\n const source = slot.compiledSource\n const where = source === undefined ? '' : ` declared at ${source.file}:${source.line}:${source.column}`\n return new ZnightError(\n ErrorCode.DuplicateProvider,\n `Cannot ${action} ${describeToken(slot.token)}: it is a compiled provider${where}`,\n { hints: ['Use container.override() to replace a compiled provider'] },\n )\n}\n\nexport function unavailableError(slot: Slot, reason: Unavailability): ZnightError {\n switch (reason) {\n case 'disposed':\n return new ZnightError(\n ErrorCode.InstantiationFailed,\n `Cannot resolve ${slot.displayName}: the container has been disposed`,\n )\n case 'failed':\n return new ZnightError(\n ErrorCode.InstantiationFailed,\n `Cannot resolve ${slot.displayName}: the container failed to initialise`,\n )\n default:\n return new ZnightError(\n ErrorCode.InstantiationFailed,\n `Cannot resolve ${slot.displayName}: the container is not initialised`,\n { hints: ['Call `await container.init()` (or use Application.create()) first'] },\n )\n }\n}\n\nexport function reentrantCreationError(slot: Slot): ZnightError {\n return new ZnightError(\n ErrorCode.CircularDependency,\n `Circular dependency: ${slot.displayName} was requested while it is being instantiated`,\n { hints: ['Do not call Lazy<T>.get() from a constructor or factory: call it later (e.g. in onStart())'] },\n )\n}\n\nexport function notReadyError(slot: Slot): ZnightError {\n return new ZnightError(\n ErrorCode.InstantiationFailed,\n `${slot.displayName} is not ready yet: its async factory is still running`,\n { hints: ['Call Lazy<T>.get() after init() completed (e.g. in onStart())'] },\n )\n}\n\nexport function failedProviderError(slot: Slot): ZnightError {\n return new ZnightError(ErrorCode.InstantiationFailed, `${slot.displayName} failed to initialise`)\n}\n\nexport function asyncOnDemandError(slot: Slot, declared: boolean): ZnightError {\n return new ZnightError(\n ErrorCode.InstantiationFailed,\n declared\n ? `Cannot create ${slot.displayName} on demand: its factory is async`\n : `Cannot create ${slot.displayName} on demand: its factory returned a promise`,\n {\n hints: [\n declared\n ? 'Include it in init({ only }) so that it is created during initialisation'\n : 'Declare it async and include it in init({ only })',\n ],\n },\n )\n}\n","import type { ProviderDefinition, Token } from './metadata.ts'\n\nimport { ErrorCode, ZnightError } from './errors.ts'\nimport { describeToken } from './tokens.ts'\n\nconst SCOPES: ReadonlySet<string> = new Set(['singleton', 'request', 'transient'])\n\n/** Whether `value` has the shape of a {@link ProviderDefinition} (`{ scope, deps, factory }`). */\nexport function isProviderDefinition(value: unknown): value is ProviderDefinition {\n if (value === null || typeof value !== 'object') return false\n const candidate = value as Partial<ProviderDefinition>\n return (\n typeof candidate.factory === 'function' &&\n Array.isArray(candidate.deps) &&\n typeof candidate.scope === 'string' &&\n SCOPES.has(candidate.scope)\n )\n}\n\n/**\n * Checks the shape of a provider definition.\n *\n * @throws ZnightError ZNIGHT005 for a malformed definition, ZNIGHT014 for an async non-singleton.\n */\nexport function validateDefinition(token: Token, definition: ProviderDefinition): void {\n if (!isProviderDefinition(definition)) {\n throw new ZnightError(\n ErrorCode.InvalidDecorator,\n `Invalid provider definition for ${describeToken(token)}: expected { scope, deps, factory }`,\n )\n }\n if (definition.async === true && definition.scope !== 'singleton') {\n throw new ZnightError(\n ErrorCode.AsyncNonSingleton,\n `${describeToken(token)} has an async factory but is ${definition.scope}-scoped`,\n { hints: ['Only singletons may have async factories'] },\n )\n }\n}\n","/**\n * Internal model of the container: one {@link Slot} per canonical token. Not part of the public API.\n */\nimport type { ExternalDefinition, ProviderDefinition, SourceLocation, Token } from './metadata.ts'\n\nimport { displayName } from './tokens.ts'\n\n// Binding modes\nexport const UNBOUND = 0\nexport const VALUE = 1\nexport const SINGLETON = 2\nexport const REQUEST = 3\nexport const TRANSIENT = 4\n\n// Singleton states (values are always READY)\nexport const IDLE = 0\nexport const CREATING = 1\nexport const PENDING = 2\nexport const READY = 3\nexport const FAILED = 4\nexport const DISPOSED = 5\n\n/**\n * Precedence levels of a binding (higher wins):\n * `override` > plugin `register`/`registerValue` > `Application.create({ providers })` > built-in > compiled.\n */\nexport const LEVEL_UNBOUND = -1\nexport const LEVEL_COMPILED = 0\nexport const LEVEL_BUILTIN = 1\nexport const LEVEL_APPLICATION = 2\nexport const LEVEL_PLUGIN = 3\nexport const LEVEL_OVERRIDE = 4\n\n// Dependency kinds\nexport const DEP_REQUIRED = 0\nexport const DEP_OPTIONAL = 1\nexport const DEP_MULTI = 2\nexport const DEP_LAZY = 3\n\n/** A resolved {@link import('./metadata.ts').DependencyRef}. */\nexport interface DepPlan {\n readonly kind: number\n /** Target (required, optional, lazy). */\n readonly slot: Slot | undefined\n /** Targets (multi). */\n readonly slots: readonly Slot[] | undefined\n}\n\nexport class Slot {\n readonly token: Token\n readonly displayName: string\n /** Precedence level of the current binding. */\n level: number = LEVEL_UNBOUND\n mode: number = UNBOUND\n definition: ProviderDefinition | undefined = undefined\n /**\n * Class the token designates (class of its first provider definition, or of a built-in), kept when\n * a value replaces the binding: matches class keys looked up by name (see `Container#findByName`).\n */\n cls: object | undefined = undefined\n /** `true` when the token is a provider of the compiled metadata (even if replaced since). */\n compiled = false\n /** Source location of the compiled provider, when the metadata includes it. */\n compiledSource: SourceLocation | undefined = undefined\n external: ExternalDefinition | undefined = undefined\n /** Who bound the slot (for messages): `plugin \"http\"`, `Application providers`, `override`... */\n origin: string | undefined = undefined\n state: number = IDLE\n instance: unknown = undefined\n promise: Promise<void> | undefined = undefined\n /** Resolved dependencies, in definition order. */\n plan: readonly DepPlan[] | undefined = undefined\n /** Hard dependency edges (required, optional, multi; not lazy). */\n edges: readonly Slot[] = []\n /** Lazy dependency targets. */\n lazyEdges: readonly Slot[] = []\n /** Singletons that must be ready before this provider can be created (through transients). */\n waits: readonly Slot[] = []\n /** Position in the merged resolution order (-1 when not ordered). */\n order = -1\n /** DFS color during ordering (0 white, 1 gray, 2 black). */\n mark = 0\n /** Whether resolving this slot requires an active request scope. */\n needsScope = false\n\n constructor(token: Token) {\n this.token = token\n this.displayName = displayName(token)\n }\n\n /** Whether the slot has a definition the container instantiates. */\n get isProvider(): boolean {\n return this.mode >= SINGLETON\n }\n\n /** Whether an unbound slot can still be resolved (request external read from the scope, or optional external). */\n get isSatisfiedExternally(): boolean {\n const external = this.external\n return external !== undefined && (external.scope === 'request' || external.optional === true)\n }\n}\n\n/** Mode of a provider definition. */\nexport function modeOf(definition: ProviderDefinition): number {\n switch (definition.scope) {\n case 'request':\n return REQUEST\n case 'transient':\n return TRANSIENT\n default:\n return SINGLETON\n }\n}\n","/**\n * Graph algorithms of the container (internal): dependency plans, merged topological order,\n * scope validation, closures and missing dependencies. Everything is O(providers + edges).\n */\n\nimport type { DependencyRef, Token } from './metadata.ts'\n\nimport { ErrorCode, ZnightError } from './errors.ts'\nimport {\n DEP_LAZY,\n DEP_MULTI,\n DEP_OPTIONAL,\n DEP_REQUIRED,\n type DepPlan,\n REQUEST,\n SINGLETON,\n type Slot,\n TRANSIENT,\n UNBOUND,\n} from './slot.ts'\nimport { describeToken, formatPath } from './tokens.ts'\n\nconst WHITE = 0\nconst GRAY = 1\nconst BLACK = 2\n\n/** Resolves the dependencies of a provider slot into a plan and dependency edges. */\nexport function buildPlan(slot: Slot, lookup: (token: Token) => Slot): void {\n const definition = slot.definition\n if (definition === undefined) return\n const plan: DepPlan[] = []\n const edges: Slot[] = []\n const lazyEdges: Slot[] = []\n definition.deps.forEach((ref: DependencyRef, index) => {\n if (typeof ref === 'string') {\n const target = lookup(ref)\n plan.push({ kind: DEP_REQUIRED, slot: target, slots: undefined })\n edges.push(target)\n } else if (ref !== null && typeof ref === 'object' && 'multi' in ref && Array.isArray(ref.multi)) {\n const targets = ref.multi.map(lookup)\n plan.push({ kind: DEP_MULTI, slot: undefined, slots: targets })\n edges.push(...targets)\n } else if (ref !== null && typeof ref === 'object' && 'lazy' in ref && typeof ref.lazy === 'string') {\n const target = lookup(ref.lazy)\n plan.push({ kind: DEP_LAZY, slot: target, slots: undefined })\n lazyEdges.push(target)\n } else if (ref !== null && typeof ref === 'object' && 'token' in ref && typeof ref.token === 'string') {\n const target = lookup(ref.token)\n plan.push({ kind: DEP_OPTIONAL, slot: target, slots: undefined })\n edges.push(target)\n } else {\n throw new ZnightError(\n ErrorCode.InvalidDecorator,\n `Invalid dependency #${index} of ${describeToken(slot.token)}: ${safeJson(ref)}`,\n { hints: ['Expected a token, { token, optional: true }, { multi: [...] } or { lazy: token }'] },\n )\n }\n })\n slot.plan = plan\n slot.edges = edges\n slot.lazyEdges = lazyEdges\n}\n\n/**\n * Depth-first topological sort over hard edges (lazy edges are ignored: `Lazy<T>` breaks cycles).\n * Visiting `base` in order keeps the compiled `resolutionOrder` unchanged and inserts runtime\n * definitions right before their first dependent.\n *\n * @throws ZnightError (ZNIGHT002) on a cycle.\n */\nexport function computeOrder(base: Iterable<Slot>): Slot[] {\n const order: Slot[] = []\n const stack: Slot[] = []\n const cursors: number[] = []\n for (const root of base) {\n if (!root.isProvider || root.mark !== WHITE) continue\n root.mark = GRAY\n stack.push(root)\n cursors.push(0)\n while (stack.length > 0) {\n const top = stack.length - 1\n const slot = stack[top] as Slot\n const cursor = cursors[top] as number\n if (cursor < slot.edges.length) {\n cursors[top] = cursor + 1\n const next = slot.edges[cursor] as Slot\n if (!next.isProvider || next.mark === BLACK) continue\n if (next.mark === GRAY) throw cycleError([...stack.slice(stack.indexOf(next)), next])\n next.mark = GRAY\n stack.push(next)\n cursors.push(0)\n } else {\n slot.mark = BLACK\n slot.order = order.length\n order.push(slot)\n stack.pop()\n cursors.pop()\n }\n }\n }\n return order\n}\n\nfunction cycleError(cycle: readonly Slot[]): ZnightError {\n const path = cycle.map(slot => slot.token)\n return new ZnightError(ErrorCode.CircularDependency, `Circular dependency: ${formatPath(path)}`, {\n hints: [\n 'Inject one of these dependencies as Lazy<T> and call get() when needed',\n `Tokens: ${path.slice(0, -1).join(', ')}`,\n ],\n })\n}\n\n/** Whether resolving `slot` requires an active request scope. */\nfunction requiresScope(slot: Slot): boolean {\n if (slot.isProvider) return slot.needsScope\n return slot.mode === UNBOUND && slot.external?.scope === 'request'\n}\n\n/**\n * Computes `needsScope` and `waits` (singletons to wait for, through transients) for every slot of\n * `order` (dependencies first).\n *\n * @throws ZnightError (ZNIGHT003) when a singleton depends on request-scoped state.\n */\nexport function analyseScopes(order: readonly Slot[]): void {\n for (const slot of order) {\n let needsScope = slot.mode === REQUEST\n let waits: Set<Slot> | undefined\n for (const dep of slot.edges) {\n if (requiresScope(dep)) {\n if (slot.mode === SINGLETON) throw scopeMismatchError(slot, dep)\n needsScope = true\n }\n if (dep.mode === SINGLETON) {\n waits ??= new Set()\n waits.add(dep)\n } else if (dep.mode === TRANSIENT && dep.waits.length > 0) {\n waits ??= new Set()\n for (const wait of dep.waits) waits.add(wait)\n }\n }\n slot.needsScope = needsScope\n slot.waits = waits === undefined ? [] : [...waits]\n }\n}\n\nfunction scopeMismatchError(singleton: Slot, dep: Slot): ZnightError {\n const path = [singleton.token]\n let current: Slot | undefined = dep\n while (current !== undefined && !path.includes(current.token)) {\n path.push(current.token)\n if (current.mode !== TRANSIENT) break\n current = current.edges.find(requiresScope)\n }\n const target = path[path.length - 1] as Token\n return new ZnightError(\n ErrorCode.ScopeMismatch,\n `Scope mismatch: singleton ${singleton.displayName} depends on request-scoped ${describeToken(target)} (${formatPath(path)})`,\n {\n hints: [\n `Inject it as Lazy<T> and call get() inside the request, or make ${singleton.displayName} request-scoped`,\n ],\n },\n )\n}\n\n/** Every slot reachable from `roots` through hard and lazy edges (roots included). */\nexport function closureOf(roots: Iterable<Slot>): Set<Slot> {\n const seen = new Set<Slot>()\n const queue = [...roots]\n for (let index = 0; index < queue.length; index++) {\n const slot = queue[index] as Slot\n if (seen.has(slot)) continue\n seen.add(slot)\n for (const edge of slot.edges) if (!seen.has(edge)) queue.push(edge)\n for (const edge of slot.lazyEdges) if (!seen.has(edge)) queue.push(edge)\n }\n return seen\n}\n\n/** Whether `slot` cannot be resolved at all (unbound and not satisfiable from a scope or as optional). */\nexport function isMissing(slot: Slot): boolean {\n return slot.mode === UNBOUND && !slot.isSatisfiedExternally\n}\n\n/** Missing required dependencies of `slots`, with the providers requiring them (in encounter order). */\nexport function findMissing(slots: Iterable<Slot>): Map<Slot, Slot[]> {\n const missing = new Map<Slot, Slot[]>()\n const record = (target: Slot, dependent: Slot): void => {\n if (!isMissing(target)) return\n const dependents = missing.get(target)\n if (dependents === undefined) missing.set(target, [dependent])\n else if (!dependents.includes(dependent)) dependents.push(dependent)\n }\n for (const slot of slots) {\n if (slot.plan === undefined) continue\n for (const dep of slot.plan) {\n if (dep.kind === DEP_REQUIRED || dep.kind === DEP_LAZY) record(dep.slot as Slot, slot)\n else if (dep.kind === DEP_MULTI) for (const target of dep.slots as readonly Slot[]) record(target, slot)\n }\n }\n return missing\n}\n\n/** ZNIGHT001 listing every missing dependency, its dependents and the plugin expected to provide it. */\nexport function missingProvidersError(missing: ReadonlyMap<Slot, readonly Slot[]>): ZnightError {\n const lines: string[] = []\n const plugins = new Set<string>()\n for (const [slot, dependents] of missing) {\n let line = ` - ${describeToken(slot.token)}`\n const providedBy = slot.external?.providedBy\n if (providedBy !== undefined) {\n line += `, provided by ${providedBy}`\n plugins.add(providedBy)\n }\n line +=\n dependents.length === 0\n ? ', requested by init({ only })'\n : `, required by ${dependents.map(dependent => dependent.displayName).join(', ')}`\n lines.push(line)\n }\n const count = missing.size\n const hints = [...plugins].map(plugin => `Add ${plugin} to Application.create({ plugins })`)\n hints.push('Supply values with Application.create({ providers }) or container.registerValue()')\n return new ZnightError(\n ErrorCode.MissingProvider,\n `${count === 1 ? 'A required provider is' : `${count} required providers are`} missing:\\n${lines.join('\\n')}`,\n { hints },\n )\n}\n\n/**\n * A dependency path ending with `target`, starting from a provider nothing depends on (used to\n * explain why `target` was instantiated).\n */\nexport function dependentPath(target: Slot, providers: Iterable<Slot>): Token[] {\n const dependents = new Map<Slot, Slot>()\n for (const slot of providers) {\n for (const edge of slot.edges) if (!dependents.has(edge)) dependents.set(edge, slot)\n }\n const path: Slot[] = [target]\n let current = dependents.get(target)\n while (current !== undefined && !path.includes(current)) {\n path.unshift(current)\n current = dependents.get(current)\n }\n return path.map(slot => slot.token)\n}\n\nfunction safeJson(value: unknown): string {\n try {\n return JSON.stringify(value) ?? String(value)\n } catch {\n return String(value)\n }\n}\n","import type { LifecycleHook } from './metadata.ts'\n\nimport { ErrorCode, ZnightError } from './errors.ts'\n\n/**\n * Called by `app.start()` on every instantiated singleton, in resolution order (dependencies\n * first), before plugins start accepting traffic.\n */\nexport interface OnStart {\n onStart(): void | Promise<void>\n}\n\n/** Called by `app.start()` once every provider and plugin has started. */\nexport interface OnReady {\n onReady(): void | Promise<void>\n}\n\n/**\n * Called by `app.stop()` on every started singleton, in reverse resolution order, after plugins\n * stopped accepting traffic. Pairs with {@link OnStart}: resources acquired in a constructor or a\n * factory should be released by a dispose method (`@Provides({ dispose })`) or\n * `[Symbol.asyncDispose]()`, which run even when the application was never started.\n */\nexport interface OnStop {\n onStop(): void | Promise<void>\n}\n\ntype Callable = (this: unknown) => unknown\n\nfunction methodOf(instance: unknown, key: PropertyKey): Callable | undefined {\n if (instance === null || (typeof instance !== 'object' && typeof instance !== 'function')) return undefined\n const value: unknown = (instance as Record<PropertyKey, unknown>)[key]\n return typeof value === 'function' ? (value as Callable) : undefined\n}\n\n/** Whether `instance` implements `hook` (duck typing: a method with that name exists). */\nexport function hasLifecycleHook(instance: unknown, hook: LifecycleHook): boolean {\n return methodOf(instance, hook) !== undefined\n}\n\n/** Calls `hook` on `instance` when it implements it. Returns what the hook returned (or `undefined`). */\nexport function callLifecycleHook(instance: unknown, hook: LifecycleHook): unknown {\n const method = methodOf(instance, hook)\n return method === undefined ? undefined : method.call(instance)\n}\n\n/**\n * Whether {@link disposeInstance} has something to call: the `disposeMethod` when given, otherwise\n * `[Symbol.asyncDispose]` or `[Symbol.dispose]`.\n */\nexport function isDisposable(instance: unknown, disposeMethod?: string): boolean {\n if (disposeMethod !== undefined) return true\n return methodOf(instance, Symbol.asyncDispose) !== undefined || methodOf(instance, Symbol.dispose) !== undefined\n}\n\n/**\n * Releases `instance`: calls `disposeMethod` when given (`@Provides({ dispose: 'end' })`), otherwise\n * `[Symbol.asyncDispose]()`, otherwise `[Symbol.dispose]()`. Only the first applicable one is called.\n *\n * @throws ZnightError (ZNIGHT021) when `disposeMethod` is not a method of `instance`.\n */\nexport function disposeInstance(instance: unknown, disposeMethod?: string): unknown {\n if (disposeMethod !== undefined) {\n const method = methodOf(instance, disposeMethod)\n if (method === undefined) {\n throw new ZnightError(\n ErrorCode.LifecycleFailed,\n `Cannot dispose ${describeInstance(instance)}: it has no method \"${disposeMethod}\"`,\n { hints: ['Check the `dispose` option of the provider (@Provides({ dispose }))'] },\n )\n }\n return method.call(instance)\n }\n const asyncDispose = methodOf(instance, Symbol.asyncDispose)\n if (asyncDispose !== undefined) return asyncDispose.call(instance)\n const dispose = methodOf(instance, Symbol.dispose)\n if (dispose !== undefined) return dispose.call(instance)\n return undefined\n}\n\nfunction describeInstance(instance: unknown): string {\n if (instance === null || instance === undefined) return String(instance)\n const name = (instance as { constructor?: { name?: unknown } }).constructor?.name\n return typeof name === 'string' && name !== '' ? `an instance of ${name}` : `a ${typeof instance}`\n}\n","/**\n * Runtime metadata contract.\n *\n * `@znight/compiler` analyzes the application at build time and generates a module exporting a\n * {@link ZnightMetadata} object (`__ZNIGHT_METADATA__`). The runtime (container, plugins) only ever\n * consumes this object: there is no reflection and no decorator metadata at runtime.\n *\n * This file is the single source of truth shared by the compiler (which emits code matching these\n * types) and every runtime package. See docs/internals/architecture.md §3. Any field whose absence\n * changes runtime behaviour requires bumping {@link METADATA_VERSION}.\n */\n\n/** Version of the metadata format produced by the compiler and accepted by the runtime. */\nexport const METADATA_VERSION = 1\n\n/**\n * Unique, stable identifier of a provider: the canonical identity of the declaration that defines it.\n *\n * - application class: `src/users/user.service.ts#UserService`\n * - package export: `@acme/auth#JwtService`, `@znight/observability#Logger`\n * - `@Provides` method: `src/db/db.factory.ts#DbFactory.createPool`\n */\nexport type Token = string\n\n/**\n * Lifetime of a provider instance.\n * - `singleton`: one instance for the whole application (default)\n * - `request`: one instance per scope (see `Container.runInScope`)\n * - `transient`: a new instance every time it is injected or resolved\n */\nexport type Scope = 'singleton' | 'request' | 'transient'\n\n/** Lifecycle hooks a singleton may implement (detected at runtime by duck typing). */\nexport type LifecycleHook = 'onStart' | 'onReady' | 'onStop'\n\n/**\n * A dependency in a provider's `deps` list:\n * - `Token`: required dependency\n * - `{ token, optional: true }`: `undefined` when no provider/value exists\n * - `{ multi: [...] }`: array of instances, in the given order\n * - `{ lazy: token }`: a {@link Lazy} handle resolved at call time in the current scope\n */\nexport type DependencyRef =\n | Token\n | { readonly token: Token; readonly optional: true }\n | { readonly multi: readonly Token[] }\n | { readonly lazy: Token }\n\n/** Handle injected for `Lazy<T>` parameters: resolves the dependency when `get()` is called. */\nexport interface Lazy<T> {\n get(): T\n}\n\n/**\n * Factory generated by the compiler. Receives resolved dependencies in the same order as\n * {@link ProviderDefinition.deps}.\n */\n// biome-ignore lint/suspicious/noExplicitAny: generated factories receive heterogeneously typed dependencies\nexport type ProviderFactory<T = unknown> = (deps: any[]) => T | Promise<T>\n\n/** Location of a declaration in the user's source code (path relative to the project root, 1-based). */\nexport interface SourceLocation {\n readonly file: string\n readonly line: number\n readonly column: number\n}\n\n/** One interceptor applied to a method: `dep` is an index in {@link ProviderDefinition.deps}. */\nexport interface InterceptorBinding {\n readonly dep: number\n readonly options?: unknown\n}\n\n/** Interceptor chain of a method. The first binding is the outermost interceptor. */\nexport interface MethodInterception {\n /** Whether the intercepted method is async (`async` keyword or `Promise` return type). */\n readonly async: boolean\n readonly chain: readonly InterceptorBinding[]\n}\n\n/** Constructor of a provider class (abstract classes allowed for typing purposes). */\nexport type ProviderClass<T = unknown> = abstract new (...args: never[]) => T\n\n/** Runtime definition of a single provider. */\nexport interface ProviderDefinition<T = unknown> {\n readonly scope: Scope\n /** Class reference, when the provider is a class. Enables `container.get(MyClass)`. */\n readonly class?: ProviderClass<T>\n /** Dependencies passed positionally to {@link factory}. */\n readonly deps: readonly DependencyRef[]\n readonly factory: ProviderFactory<T>\n /** `true` when the factory returns a promise. Only allowed for singletons. */\n readonly async?: boolean\n /** Method interceptors (AOP), applied by the container right after {@link factory}. */\n readonly interceptors?: Readonly<Record<string, MethodInterception>>\n /** Name of a method to call on shutdown, for objects without `onStop`/`Symbol.asyncDispose`. */\n readonly dispose?: string\n /** Qualifier set with `@Named()`. */\n readonly name?: string\n /** Set with `@Primary()`. */\n readonly primary?: boolean\n readonly source?: SourceLocation\n}\n\n/**\n * A token the compiled code depends on but that is supplied at runtime (by a plugin through\n * `container.registerValue()` / `container.register()`, or by `Application.create({ providers })`).\n */\nexport interface ExternalDefinition {\n readonly token: Token\n /** Scope of the supplied value. Request-scoped externals are read from the active scope. Default: singleton. */\n readonly scope?: Scope\n /** Name of the plugin expected to provide it (used in error messages). */\n readonly providedBy?: string\n readonly optional?: boolean\n}\n\n/**\n * Feature-specific metadata (HTTP routes, message consumers, config classes...).\n * Packages augment this interface with their own key:\n *\n * ```ts\n * declare module '@znight/core' {\n * interface ZnightExtensionsMetadata { http?: HttpMetadata }\n * }\n * ```\n */\nexport interface ZnightExtensionsMetadata {\n readonly [extension: string]: unknown\n}\n\n/** The complete metadata generated by `@znight/compiler`. */\nexport interface ZnightMetadata {\n /** Format version of this object, see {@link METADATA_VERSION}. */\n readonly version: number\n /** Version of `@znight/compiler` that generated this object. */\n readonly compiler?: string\n readonly providers: Readonly<Record<Token, ProviderDefinition>>\n /** Every provider token, topologically sorted: dependencies always come before their dependents. */\n readonly resolutionOrder: readonly Token[]\n /** Alternative tokens (provided types, interfaces, base classes) pointing to a provider token. */\n readonly aliases?: Readonly<Record<Token, Token>>\n readonly externals?: readonly ExternalDefinition[]\n readonly extensions?: ZnightExtensionsMetadata\n}\n","import type { SourceLocation, Token } from './metadata.ts'\n\nimport { type ErrorCode, ErrorCode as ErrorCodes, ZnightError, type ZnightErrorOptions } from './errors.ts'\nimport { displayName, formatPath } from './tokens.ts'\nimport { errorMessage } from './utils.ts'\n\n/**\n * ZNIGHT015: a provider factory threw or rejected.\n *\n * Carries the failing token, the dependency path that led to it (outermost first, the failing token\n * last), the source location of the provider when the metadata includes it, and the original error\n * as `cause`.\n */\nexport class InstantiationError extends ZnightError {\n /** Token of the provider whose factory failed. */\n readonly token: Token\n /** Dependency path from the outermost dependent to {@link token} (inclusive). */\n readonly path: readonly Token[]\n /** Location of the provider declaration, when known. */\n readonly source: SourceLocation | undefined\n\n constructor(token: Token, path: readonly Token[], cause: unknown, source?: SourceLocation) {\n const lines = [`Failed to instantiate ${displayName(token)}: ${errorMessage(cause)}`, ` token: ${token}`]\n if (source !== undefined) lines.push(` at: ${source.file}:${source.line}:${source.column}`)\n if (path.length > 1) lines.push(` dependency path: ${formatPath(path)}`)\n super(ErrorCodes.InstantiationFailed, lines.join('\\n'), { cause })\n this.token = token\n this.path = path\n this.source = source\n }\n\n /** A copy of this error whose path is prefixed with `parents` (used while unwinding a resolution). */\n withParents(parents: readonly Token[]): InstantiationError {\n if (parents.length === 0) return this\n const error = new InstantiationError(this.token, [...parents, ...this.path], this.cause, this.source)\n const suppressed = getSuppressedErrors(this)\n if (suppressed.length > 0) addSuppressedErrors(error, suppressed)\n return error\n }\n}\n\n/**\n * A {@link ZnightError} grouping several failures (e.g. every shutdown step that failed). Exposes\n * `errors` like the standard `AggregateError`, while keeping a Znight `code`.\n */\nexport class ZnightAggregateError extends ZnightError {\n readonly errors: readonly unknown[]\n\n constructor(code: ErrorCode, message: string, errors: readonly unknown[], options: ZnightErrorOptions = {}) {\n const details = errors.map((error, index) => ` ${index + 1}. ${errorMessage(error)}`)\n super(code, [message, ...details].join('\\n'), options)\n this.errors = errors\n }\n}\n\nconst SUPPRESSED = 'suppressed'\n\n/**\n * Errors that happened while handling `error` (rollback/cleanup failures, concurrent failures) and\n * that were attached to it instead of being thrown. Empty when there are none.\n */\nexport function getSuppressedErrors(error: unknown): readonly unknown[] {\n if (error === null || (typeof error !== 'object' && typeof error !== 'function')) return []\n const value: unknown = Object.hasOwn(error, SUPPRESSED) ? (error as Record<string, unknown>)[SUPPRESSED] : undefined\n return Array.isArray(value) ? value : []\n}\n\n/** Attaches `errors` to `error` (see {@link getSuppressedErrors}). Primitives cannot carry them. */\nexport function addSuppressedErrors(error: unknown, errors: readonly unknown[]): void {\n if (errors.length === 0) return\n if (error === null || (typeof error !== 'object' && typeof error !== 'function')) return\n const all = [...getSuppressedErrors(error), ...errors]\n try {\n Object.defineProperty(error, SUPPRESSED, { value: all, enumerable: true, configurable: true, writable: true })\n } catch {\n // frozen or exotic error objects cannot carry the extra information: nothing else to do\n }\n}\n\n/** Wraps a non-Znight error into a ZNIGHT021 error mentioning `step`; Znight errors are returned as is. */\nexport function lifecycleError(step: string, error: unknown): ZnightError {\n if (error instanceof ZnightError) return error\n return new ZnightError(ErrorCodes.LifecycleFailed, `${step} failed: ${errorMessage(error)}`, { cause: error })\n}\n","import type { Token } from './metadata.ts'\nimport type { ProviderKey } from './tokens.ts'\n\n/**\n * The values of the active request scope (see `Container.runInScope`). Keys are tokens (aliases and\n * classes known to the container are accepted and normalised). Holds the seed values passed to\n * `runInScope` and the request-scoped instances created in the scope.\n */\nexport interface ScopeContext {\n /** The value stored for `key` in this scope, without creating anything. */\n get<T = unknown>(key: ProviderKey<T>): T | undefined\n /** Whether a value is stored for `key` in this scope. */\n has(key: ProviderKey): boolean\n /** Stores a value for `key`: request-scoped resolutions of `key` return it from now on. */\n set<T>(key: ProviderKey<T>, value: T): void\n /** `true` once the `runInScope` callback has settled and the scope instances were disposed. */\n readonly closed: boolean\n}\n\n/** A request-scoped instance created by the container, disposed when its scope closes. */\nexport interface ScopedInstance {\n readonly token: Token\n readonly instance: unknown\n readonly dispose: string | undefined\n}\n\n/** Implementation of {@link ScopeContext} used by the container (internal). */\nexport class RequestScope implements ScopeContext {\n readonly created: ScopedInstance[] = []\n closed = false\n readonly #canonical: (key: ProviderKey) => Token\n #values: Map<Token, unknown> | undefined\n /** Seed values not yet in {@link values}: canonical tokens and values, alternately. */\n #seeds: readonly unknown[] | undefined\n\n /** `seeds`: canonical tokens and their values, alternately (copied into {@link values} on first use). */\n constructor(canonical: (key: ProviderKey) => Token, seeds?: readonly unknown[]) {\n this.#canonical = canonical\n this.#seeds = seeds\n }\n\n /** The values of the scope by canonical token: the seeds, then what was set or created in it. */\n get values(): Map<Token, unknown> {\n let values = this.#values\n if (values === undefined) {\n values = new Map()\n const seeds = this.#seeds\n if (seeds !== undefined) {\n for (let index = 0; index < seeds.length; index += 2) values.set(seeds[index] as Token, seeds[index + 1])\n this.#seeds = undefined\n }\n this.#values = values\n }\n return values\n }\n\n get<T = unknown>(key: ProviderKey<T>): T | undefined {\n return this.values.get(this.#canonical(key)) as T | undefined\n }\n\n has(key: ProviderKey): boolean {\n return this.values.has(this.#canonical(key))\n }\n\n set<T>(key: ProviderKey<T>, value: T): void {\n this.values.set(this.#canonical(key), value)\n }\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\n\nimport { applyInterceptors } from './aop.ts'\nimport {\n ambiguousNameError,\n asyncOnDemandError,\n closedScopeError,\n compiledProviderError,\n duplicateRegistrationError,\n failedProviderError,\n invalidMetadataError,\n metadataVersionError,\n missingScopeValueError,\n noScopeError,\n notFoundError,\n notReadyError,\n reentrantCreationError,\n sealedError,\n unavailableError,\n unknownClassError,\n} from './container-errors.ts'\nimport { isProviderDefinition, validateDefinition } from './definition.ts'\nimport { ErrorCode, ZnightError } from './errors.ts'\nimport {\n analyseScopes,\n buildPlan,\n closureOf,\n computeOrder,\n dependentPath,\n findMissing,\n isMissing,\n missingProvidersError,\n} from './graph.ts'\nimport { disposeInstance } from './lifecycle.ts'\nimport {\n type ExternalDefinition,\n type Lazy,\n METADATA_VERSION,\n type ProviderClass,\n type ProviderDefinition,\n type Token,\n type ZnightMetadata,\n} from './metadata.ts'\nimport { addSuppressedErrors, InstantiationError, lifecycleError, ZnightAggregateError } from './runtime-errors.ts'\nimport { RequestScope, type ScopeContext, type ScopedInstance } from './scope.ts'\nimport {\n CREATING,\n DEP_LAZY,\n DEP_MULTI,\n DEP_OPTIONAL,\n DEP_REQUIRED,\n type DepPlan,\n DISPOSED,\n FAILED,\n IDLE,\n LEVEL_APPLICATION,\n LEVEL_BUILTIN,\n LEVEL_COMPILED,\n LEVEL_OVERRIDE,\n LEVEL_PLUGIN,\n modeOf,\n PENDING,\n READY,\n REQUEST,\n SINGLETON,\n Slot,\n TRANSIENT,\n UNBOUND,\n VALUE,\n} from './slot.ts'\nimport { type ClassKey, CoreTokens, displayName, type ProviderKey, type TypedToken } from './tokens.ts'\nimport { errorMessage, isThenable } from './utils.ts'\n\n/** Options of {@link Container.init}. */\nexport interface InitOptions {\n /**\n * Instantiate only these providers and their dependency closure. Other singletons are created on\n * first use (synchronously; async factories must be part of the closure).\n */\n readonly only?: readonly ProviderKey[]\n}\n\n/** An instantiated singleton managed by the container (see {@link Container.instances}). */\nexport interface ManagedInstance {\n readonly token: Token\n readonly displayName: string\n readonly instance: unknown\n readonly definition: ProviderDefinition\n /** Disposes the instance once (dispose method, `Symbol.asyncDispose` or `Symbol.dispose`). */\n dispose(): Promise<void>\n}\n\n/** Seed values of a request scope: token-keyed pairs (aliases and known classes are accepted). */\nexport type ScopeValues = Iterable<readonly [ProviderKey, unknown]>\n\n/**\n * A request scope opened with {@link Container.openScope}: its owner runs code in it with\n * {@link OpenedScope.run} and ends it with {@link OpenedScope.close}. The callback-free form of\n * {@link Container.runInScope}, for hot paths that stay synchronous as long as their work is (the\n * HTTP pipeline): no promise is created unless something is asynchronous.\n */\nexport interface OpenedScope {\n /** The values of the scope (what `currentScope()` returns in {@link run}). */\n readonly context: ScopeContext\n /**\n * Calls `fn(...args)` in the scope and returns its result. The code it runs and the asynchronous\n * continuations it creates (awaits, promise callbacks, timers) see the scope, like the callback\n * of `runInScope`. May be called several times until the scope is closed.\n */\n run<A extends readonly unknown[], R>(fn: (...args: A) => R, ...args: A): R\n /**\n * Closes the scope (a later resolution of a request-scoped provider in it throws ZNIGHT013) and\n * disposes the instances created in it, in reverse creation order. Returns `undefined` when no\n * instance was created (nothing to wait for), otherwise a promise rejecting with ZNIGHT021 when a\n * disposal fails. Idempotent: later calls return the first result.\n */\n close(): Promise<void> | undefined\n}\n\ntype Status = 'open' | 'initializing' | 'ready' | 'failed' | 'disposed'\n\ninterface InitRun {\n failed: boolean\n readonly errors: unknown[]\n readonly inflight: Promise<void>[]\n}\n\ninterface ContainerInternals {\n bindBuiltin(container: Container, token: Token, value: unknown, cls?: object): void\n setOrigin(container: Container, origin: string | undefined): void\n}\n\nlet internals: ContainerInternals\n\n/**\n * The dependency injection container. It consumes the metadata generated by `@znight/compiler`:\n * no reflection happens at runtime, factories are called in a precomputed order and resolving a\n * singleton is a single `Map` lookup.\n *\n * ```ts\n * const container = Container.create(__ZNIGHT_METADATA__)\n * container.registerValue('@acme/clock#Clock', systemClock)\n * await container.init()\n * const users = container.get(UserService)\n * ```\n *\n * Precedence of bindings: `override()` > plugin `register()`/`registerValue()` >\n * `Application.create({ providers })` (`provide()`) > compiled providers. Registrations are only\n * possible before `init()` (ZNIGHT016).\n */\nexport class Container {\n /** The metadata this container was created from. */\n readonly metadata: ZnightMetadata\n /** Canonical slots, in insertion order (compiled providers first). */\n readonly #slots = new Map<Token, Slot>()\n /** Every lookup key (tokens, aliases, classes, cached display names) → slot. */\n readonly #lookup = new Map<unknown, Slot>()\n /** Alias token → canonical slot (used to index alias display names). */\n readonly #aliases = new Map<Token, Slot>()\n readonly #storage = new AsyncLocalStorage<RequestScope>()\n /** Instantiated singletons, in creation order. */\n readonly #created: Slot[] = []\n #order: readonly Slot[] = []\n #names: Map<string, Slot[]> | undefined\n #status: Status = 'open'\n #sealed = false\n #planned = false\n // biome-ignore lint/style/useReadonlyClassProperties: assigned through the internals accessor (static block)\n #origin: string | undefined\n #initPromise: Promise<void> | undefined\n #disposePromise: Promise<void> | undefined\n\n static {\n internals = {\n bindBuiltin: (container, token, value, cls) => container.#bindBuiltin(token, value, cls),\n setOrigin: (container, origin) => {\n container.#origin = origin\n },\n }\n }\n\n private constructor(metadata: ZnightMetadata) {\n this.metadata = metadata\n for (const [token, definition] of Object.entries(metadata.providers)) {\n validateDefinition(token, definition)\n const slot = this.#slot(token)\n slot.compiled = true\n slot.compiledSource = definition.source\n this.#applyDefinition(slot, definition, LEVEL_COMPILED, 'the compiled metadata')\n }\n if (metadata.aliases !== undefined) this.#indexAliases(metadata.aliases)\n for (const external of metadata.externals ?? []) this.#declareExternal(external)\n this.#bindBuiltin(CoreTokens.Container, this, Container)\n }\n\n /**\n * Creates a container from compiled metadata.\n *\n * @throws ZnightError (ZNIGHT018) when the metadata format version is not supported.\n */\n static create(metadata: ZnightMetadata): Container {\n if (\n metadata === null ||\n typeof metadata !== 'object' ||\n metadata.providers === null ||\n typeof metadata.providers !== 'object' ||\n !Array.isArray(metadata.resolutionOrder)\n ) {\n throw invalidMetadataError()\n }\n if (metadata.version !== METADATA_VERSION) throw metadataVersionError(metadata, METADATA_VERSION)\n return new Container(metadata)\n }\n\n // ---------------------------------------------------------------------------------------------\n // Registration\n // ---------------------------------------------------------------------------------------------\n\n /**\n * Registers a runtime provider definition (plugin precedence). It may depend on compiled tokens.\n *\n * @throws ZnightError ZNIGHT016 after `init()`, ZNIGHT004 when the token is a compiled provider or\n * is already registered, ZNIGHT005/ZNIGHT014 for an invalid definition.\n */\n register<T>(token: TypedToken<T>, definition: ProviderDefinition<NoInfer<T>>): void {\n this.#assertOpen('register', token)\n validateDefinition(token, definition)\n this.#bind(token, LEVEL_PLUGIN, 'register', (slot, origin) =>\n this.#applyDefinition(slot, definition, LEVEL_PLUGIN, origin),\n )\n }\n\n /**\n * Registers a value (plugin precedence), typically for an external declared in the metadata.\n * Ignored when the token is overridden.\n *\n * @throws ZnightError ZNIGHT016 after `init()`, ZNIGHT004 when the token is a compiled provider or\n * is already registered.\n */\n registerValue<T>(token: TypedToken<T>, value: NoInfer<T>): void {\n this.#bind(token, LEVEL_PLUGIN, 'register a value for', (slot, origin) =>\n this.#applyValue(slot, value, LEVEL_PLUGIN, origin),\n )\n }\n\n /**\n * Declares an external token supplied at runtime (like `metadata.externals`). A request-scoped\n * external is read from the active scope (`runInScope` seed values).\n */\n registerExternal(external: ExternalDefinition): void {\n this.#assertOpen('declare the external', external.token)\n this.#declareExternal(external)\n }\n\n /**\n * Supplies a value with application precedence (`Application.create({ providers })`): replaces a\n * compiled provider, is superseded by plugin registrations and overrides.\n */\n provide<T>(key: ProviderKey<T>, value: NoInfer<T>): void {\n this.#bind(key, LEVEL_APPLICATION, 'provide', (slot, origin) =>\n this.#applyValue(slot, value, LEVEL_APPLICATION, origin),\n )\n }\n\n /**\n * Replaces a provider (highest precedence, typically in tests). `key` may be a token, an alias or\n * a class (aliases are resolved first). `valueOrDefinition` is used as a provider definition when\n * it has the shape of one (`{ scope, deps, factory }`), as a value otherwise.\n */\n override<T>(key: ProviderKey<T>, valueOrDefinition: NoInfer<T> | ProviderDefinition<NoInfer<T>>): void {\n this.#bind(key, LEVEL_OVERRIDE, 'override', (slot, origin) => {\n if (isProviderDefinition(valueOrDefinition)) {\n validateDefinition(slot.token, valueOrDefinition)\n this.#applyDefinition(slot, valueOrDefinition, LEVEL_OVERRIDE, origin)\n } else {\n this.#applyValue(slot, valueOrDefinition, LEVEL_OVERRIDE, origin)\n }\n })\n }\n\n // ---------------------------------------------------------------------------------------------\n // Initialisation\n // ---------------------------------------------------------------------------------------------\n\n /**\n * Seals the container, validates the merged graph (missing providers ZNIGHT001, cycles ZNIGHT002,\n * scope mismatches ZNIGHT003) and instantiates singletons. A factory starts as soon as its\n * dependencies are ready, so independent async singletons are created concurrently. On failure,\n * created instances are disposed in reverse creation order and the first error is rethrown\n * (ZNIGHT015 for factory errors, with other failures attached, see `getSuppressedErrors`).\n *\n * Calling `init()` again returns the promise of the first call.\n */\n init(options: InitOptions = {}): Promise<void> {\n if (this.#initPromise !== undefined) return this.#initPromise\n if (this.#disposePromise !== undefined) {\n return Promise.reject(\n new ZnightError(ErrorCode.InstantiationFailed, 'Cannot initialise a container that has been disposed'),\n )\n }\n this.#sealed = true\n this.#status = 'initializing'\n this.#initPromise = this.#initialize(options)\n return this.#initPromise\n }\n\n async #initialize(options: InitOptions): Promise<void> {\n try {\n const roots = options.only?.map(key => this.#rootSlot(key))\n const lookup = (token: Token): Slot => this.#lookup.get(token) ?? this.#slot(token)\n for (const slot of [...this.#slots.values()]) if (slot.isProvider) buildPlan(slot, lookup)\n const order = computeOrder(this.#baseOrder())\n analyseScopes(order)\n this.#order = order\n this.#planned = true\n\n const closure = roots === undefined ? undefined : closureOf(roots)\n const missing = findMissing(closure ?? order)\n for (const root of roots ?? []) if (isMissing(root) && !missing.has(root)) missing.set(root, [])\n if (missing.size > 0) throw missingProvidersError(missing)\n\n const singletons = order.filter(slot => slot.mode === SINGLETON && (closure === undefined || closure.has(slot)))\n await this.#instantiate(singletons)\n this.#status = 'ready'\n } catch (error) {\n this.#status = 'failed'\n throw error\n }\n }\n\n *#baseOrder(): Iterable<Slot> {\n for (const token of this.metadata.resolutionOrder) {\n const slot = this.#slots.get(token)\n if (slot !== undefined) yield slot\n }\n yield* this.#slots.values()\n }\n\n async #instantiate(singletons: readonly Slot[]): Promise<void> {\n const run: InitRun = { failed: false, errors: [], inflight: [] }\n for (const slot of singletons) {\n if (run.failed) break\n if (slot.state === IDLE) this.#schedule(slot, run)\n }\n await Promise.all(run.inflight)\n if (!run.failed) return\n const cleanup = await this.#rollback()\n const [first, ...others] = run.errors\n addSuppressedErrors(first, [...others, ...cleanup])\n throw first\n }\n\n /** Starts `slot` now, or as soon as the singletons it waits for are ready. */\n #schedule(slot: Slot, run: InitRun): void {\n const waits: Promise<void>[] = []\n for (const dep of slot.waits) {\n // not reachable with a topological order: schedule the dependency first rather than fail obscurely\n if (dep.state === IDLE) this.#schedule(dep, run)\n const state: number = dep.state\n if (state === READY) continue\n if (state !== PENDING || dep.promise === undefined) return // a dependency failed: the run is failing\n waits.push(dep.promise)\n }\n if (waits.length === 0) {\n const promise = this.#start(slot, run)\n if (promise !== undefined) run.inflight.push(promise)\n return\n }\n slot.state = PENDING\n const promise = Promise.all(waits).then(() => {\n slot.state = IDLE\n return run.failed ? undefined : this.#start(slot, run)\n })\n slot.promise = promise\n run.inflight.push(promise)\n }\n\n /** Calls the factory of a singleton during `init()`. Never throws: failures are recorded in `run`. */\n #start(slot: Slot, run: InitRun): Promise<void> | undefined {\n const definition = slot.definition as ProviderDefinition\n slot.state = CREATING\n let deps: unknown[]\n let result: unknown\n try {\n deps = this.#resolveDeps(slot)\n } catch (error) {\n this.#fail(slot, this.#initError(slot, error, false), run)\n return undefined\n }\n try {\n result = definition.factory(deps)\n } catch (error) {\n this.#fail(slot, this.#initError(slot, error, true), run)\n return undefined\n }\n if (!isThenable(result)) {\n this.#complete(slot, result, deps, run)\n return undefined\n }\n slot.state = PENDING\n const promise = Promise.resolve(result).then(\n instance => this.#complete(slot, instance, deps, run),\n (error: unknown) => this.#fail(slot, this.#initError(slot, error, true), run),\n )\n slot.promise = promise\n return promise\n }\n\n #complete(slot: Slot, instance: unknown, deps: readonly unknown[], run: InitRun): void {\n slot.instance = instance\n slot.state = READY\n slot.promise = undefined\n this.#created.push(slot)\n const interceptors = slot.definition?.interceptors\n if (interceptors === undefined) return\n try {\n applyInterceptors(instance as object, interceptors, deps, slot.displayName)\n } catch (error) {\n // the instance exists: it stays registered as created so the rollback disposes it\n run.failed = true\n run.errors.push(this.#initError(slot, error, true))\n }\n }\n\n #fail(slot: Slot, error: unknown, run: InitRun): void {\n slot.state = FAILED\n slot.promise = undefined\n run.failed = true\n run.errors.push(error)\n }\n\n #initError(slot: Slot, error: unknown, fromFactory: boolean): unknown {\n const path = dependentPath(slot, this.#order)\n if (fromFactory) return new InstantiationError(slot.token, path, error, slot.definition?.source)\n if (error instanceof InstantiationError) return error.withParents(path)\n return error\n }\n\n async #rollback(): Promise<unknown[]> {\n const errors: unknown[] = []\n for (let index = this.#created.length - 1; index >= 0; index--) {\n const slot = this.#created[index] as Slot\n try {\n const result = this.#disposeSlot(slot)\n if (result !== undefined) await result\n } catch (error) {\n errors.push(lifecycleError(`Disposing ${slot.displayName}`, error))\n }\n }\n return errors\n }\n\n // ---------------------------------------------------------------------------------------------\n // Resolution\n // ---------------------------------------------------------------------------------------------\n\n /**\n * Resolves a provider by class, token, alias or unique display name (`'UserService'`).\n *\n * @throws ZnightError ZNIGHT001 (no provider), ZNIGHT008 (ambiguous display name), ZNIGHT013\n * (request-scoped provider outside of a scope), ZNIGHT015 (factory failure or container not\n * initialised).\n */\n get<T>(key: ProviderClass<T>): T\n get<T>(key: ClassKey<T>): T\n get<T = unknown>(key: TypedToken<T>): T\n get(key: ProviderKey): unknown {\n const slot = this.#lookup.get(key)\n if (slot !== undefined && slot.state === READY) return slot.instance\n return this.#resolveKey(key, slot, false)\n }\n\n /** Like {@link get}, but returns `undefined` when no provider exists for `key`. */\n getOptional<T>(key: ProviderClass<T>): T | undefined\n getOptional<T>(key: ClassKey<T>): T | undefined\n getOptional<T = unknown>(key: TypedToken<T>): T | undefined\n getOptional(key: ProviderKey): unknown {\n const slot = this.#lookup.get(key)\n if (slot !== undefined && slot.state === READY) return slot.instance\n return this.#resolveKey(key, slot, true)\n }\n\n /**\n * Whether `key` can be resolved: a provider or value is bound to it, or the active scope holds a\n * value for it. An ambiguous display name returns `false`.\n */\n has(key: ProviderKey): boolean {\n const slot = this.#lookup.get(key) ?? this.#findByName(key, false)\n const scope = this.#storage.getStore()\n if (slot === undefined) return typeof key === 'string' && (scope?.values.has(key) ?? false)\n if (slot.mode !== UNBOUND) return true\n return scope?.values.has(slot.token) ?? false\n }\n\n /** Canonical token of a class (or alias / display name), `undefined` when unknown. */\n tokenOf(key: ProviderKey): Token | undefined {\n return (this.#lookup.get(key) ?? this.#findByName(key, false))?.token\n }\n\n /** Instantiated singletons (created by the container, not registered values), in resolution order. */\n instances(): ManagedInstance[] {\n const result: ManagedInstance[] = []\n for (const slot of this.#order) {\n if (slot.mode === SINGLETON && slot.state === READY) result.push(this.#managed(slot))\n }\n return result\n }\n\n #managed(slot: Slot): ManagedInstance {\n return {\n token: slot.token,\n displayName: slot.displayName,\n instance: slot.instance,\n definition: slot.definition as ProviderDefinition,\n dispose: async (): Promise<void> => {\n await this.#disposeSlot(slot)\n },\n }\n }\n\n #resolveKey(key: ProviderKey, found: Slot | undefined, optional: boolean): unknown {\n const slot = found ?? this.#findByName(key, true)\n if (slot !== undefined) return this.#resolve(slot, optional)\n if (typeof key === 'string') {\n const scope = this.#storage.getStore()\n if (scope?.values.has(key)) return scope.values.get(key)\n }\n if (optional) return undefined\n throw notFoundError(key)\n }\n\n #resolve(slot: Slot, optional: boolean): unknown {\n switch (slot.mode) {\n case VALUE:\n return slot.instance\n case SINGLETON:\n return slot.state === READY ? slot.instance : this.#createOnDemand(slot)\n case REQUEST:\n return this.#resolveRequest(slot)\n case TRANSIENT:\n this.#assertResolvable(slot)\n return this.#create(slot)\n default:\n return this.#resolveUnbound(slot, optional)\n }\n }\n\n #resolveDeps(slot: Slot): unknown[] {\n const plan = slot.plan as readonly DepPlan[]\n const deps = new Array<unknown>(plan.length)\n for (let index = 0; index < plan.length; index++) deps[index] = this.#resolveDep(plan[index] as DepPlan)\n return deps\n }\n\n #resolveDep(dep: DepPlan): unknown {\n switch (dep.kind) {\n case DEP_REQUIRED:\n return this.#resolve(dep.slot as Slot, false)\n case DEP_OPTIONAL:\n return this.#resolve(dep.slot as Slot, true)\n case DEP_MULTI:\n return (dep.slots as readonly Slot[]).map(target => this.#resolve(target, false))\n case DEP_LAZY:\n return this.#lazy(dep.slot as Slot)\n default:\n return undefined\n }\n }\n\n #lazy(slot: Slot): Lazy<unknown> {\n return { get: () => this.#resolve(slot, false) }\n }\n\n /** Instantiates a request-scoped or transient provider (synchronous factories only). */\n #create(slot: Slot): unknown {\n const definition = slot.definition as ProviderDefinition\n let deps: unknown[]\n try {\n deps = this.#resolveDeps(slot)\n } catch (error) {\n throw error instanceof InstantiationError ? error.withParents([slot.token]) : error\n }\n let instance: unknown\n try {\n instance = definition.factory(deps)\n } catch (error) {\n throw new InstantiationError(slot.token, [slot.token], error, definition.source)\n }\n if (definition.interceptors !== undefined) {\n try {\n applyInterceptors(instance as object, definition.interceptors, deps, slot.displayName)\n } catch (error) {\n throw new InstantiationError(slot.token, [slot.token], error, definition.source)\n }\n }\n return instance\n }\n\n #resolveRequest(slot: Slot): unknown {\n const scope = this.#storage.getStore()\n if (scope === undefined) throw noScopeError(slot)\n if (scope.closed) throw closedScopeError(slot)\n const values = scope.values\n const existing = values.get(slot.token)\n if (existing !== undefined || values.has(slot.token)) return existing\n this.#assertResolvable(slot)\n const instance = this.#create(slot)\n values.set(slot.token, instance)\n scope.created.push({ token: slot.token, instance, dispose: slot.definition?.dispose })\n return instance\n }\n\n #resolveUnbound(slot: Slot, optional: boolean): unknown {\n const scope = this.#storage.getStore()\n if (scope?.values.has(slot.token)) return scope.values.get(slot.token)\n const external = slot.external\n if (external?.scope === 'request') {\n if (scope === undefined) throw noScopeError(slot)\n if (optional || external.optional === true) return undefined\n throw missingScopeValueError(slot)\n }\n if (optional || external?.optional === true) return undefined\n throw notFoundError(slot.token, slot)\n }\n\n /**\n * Creates a singleton synchronously outside of the `init()` schedule (lazy access, `init({ only })`).\n * Like during `init()`, the factory runs outside of any request scope: a singleton belongs to the\n * application, so the timers, sockets and promises it creates must not capture the scope of the\n * request that happens to use it first.\n */\n #createOnDemand(slot: Slot): unknown {\n if (this.#storage.getStore() !== undefined) return this.#storage.exit(() => this.#createOnDemand(slot))\n switch (slot.state) {\n case CREATING:\n throw reentrantCreationError(slot)\n case PENDING:\n throw notReadyError(slot)\n case FAILED:\n throw failedProviderError(slot)\n case DISPOSED:\n throw unavailableError(slot, 'disposed')\n default:\n break\n }\n this.#assertResolvable(slot)\n for (const dep of slot.waits) if (dep.state !== READY) this.#createOnDemand(dep)\n const definition = slot.definition as ProviderDefinition\n if (definition.async === true) throw asyncOnDemandError(slot, true)\n slot.state = CREATING\n let deps: unknown[]\n let result: unknown\n try {\n deps = this.#resolveDeps(slot)\n } catch (error) {\n slot.state = IDLE\n throw error instanceof InstantiationError ? error.withParents([slot.token]) : error\n }\n try {\n result = definition.factory(deps)\n } catch (error) {\n slot.state = IDLE\n throw new InstantiationError(slot.token, [slot.token], error, definition.source)\n }\n if (isThenable(result)) {\n slot.state = IDLE\n // undeclared async factory: release whatever it produces, the caller gets an error\n Promise.resolve(result).then(\n instance => disposeQuietly(instance, definition.dispose),\n () => undefined,\n )\n throw asyncOnDemandError(slot, false)\n }\n if (definition.interceptors !== undefined) {\n try {\n applyInterceptors(result as object, definition.interceptors, deps, slot.displayName)\n } catch (error) {\n slot.state = IDLE\n disposeQuietly(result, definition.dispose)\n throw new InstantiationError(slot.token, [slot.token], error, definition.source)\n }\n }\n slot.instance = result\n slot.state = READY\n this.#created.push(slot)\n return result\n }\n\n #assertResolvable(slot: Slot): void {\n const status = this.#status\n if (status === 'ready' || (status === 'initializing' && this.#planned)) return\n throw unavailableError(slot, status === 'disposed' || status === 'failed' ? status : 'open')\n }\n\n // ---------------------------------------------------------------------------------------------\n // Request scope\n // ---------------------------------------------------------------------------------------------\n\n /**\n * Runs `fn` in a new request scope seeded with `values`. Request-scoped providers and\n * request-scoped externals resolved inside `fn` (including asynchronously) are bound to this\n * scope. When `fn` settles, the instances created in the scope are disposed in reverse creation\n * order. Scopes are isolated from each other (nested calls open a fresh scope).\n *\n * Rejects with the error of `fn` (disposal errors attached), or with ZNIGHT021 when only the\n * disposal failed.\n */\n async runInScope<R>(fn: () => R | Promise<R>, values?: ScopeValues): Promise<R> {\n const scope = new RequestScope(this.#canonical)\n if (values !== undefined) for (const [key, value] of values) scope.values.set(this.#canonical(key), value)\n let result: R\n try {\n result = await this.#storage.run(scope, fn)\n } catch (error) {\n addSuppressedErrors(error, await this.#closeScope(scope))\n throw error\n }\n if (scope.created.length === 0) {\n scope.closed = true\n return result\n }\n const errors = await this.#closeScope(scope)\n if (errors.length > 0) {\n throw new ZnightAggregateError(\n ErrorCode.LifecycleFailed,\n `Failed to dispose ${errors.length} request-scoped instance(s)`,\n errors,\n )\n }\n return result\n }\n\n /**\n * Opens a request scope seeded with `values`, like {@link runInScope}, but without running\n * anything: the caller runs code in it (`run`) and closes it (`close`) when the work it started\n * is over. Request-scoped providers resolved in it are disposed by `close`, which must be called.\n */\n openScope(values?: ScopeValues): OpenedScope {\n let seeds: unknown[] | undefined\n if (values !== undefined) {\n seeds = []\n for (const [key, value] of values) seeds.push(this.#canonical(key), value)\n }\n return new ScopeHandle(this.#storage, new RequestScope(this.#canonical, seeds), this.#closeScopeFn)\n }\n\n /** The active request scope, if any. */\n currentScope(): ScopeContext | undefined {\n return this.#storage.getStore()\n }\n\n readonly #closeScopeFn = (scope: RequestScope): Promise<unknown[]> => this.#closeScope(scope)\n\n async #closeScope(scope: RequestScope): Promise<unknown[]> {\n scope.closed = true\n const errors: unknown[] = []\n for (let index = scope.created.length - 1; index >= 0; index--) {\n const created = scope.created[index] as ScopedInstance\n try {\n const result = disposeInstance(created.instance, created.dispose)\n if (isThenable(result)) await result\n } catch (error) {\n errors.push(lifecycleError(`Disposing the request-scoped ${displayName(created.token)}`, error))\n }\n }\n return errors\n }\n\n readonly #canonical = (key: ProviderKey): Token => {\n const slot = this.#lookup.get(key) ?? this.#findByName(key, false)\n if (slot !== undefined) return slot.token\n if (typeof key === 'string') return key\n throw notFoundError(key)\n }\n\n // ---------------------------------------------------------------------------------------------\n // Disposal\n // ---------------------------------------------------------------------------------------------\n\n /**\n * Disposes every instantiated singleton in reverse resolution order (dispose method from the\n * definition, `Symbol.asyncDispose` or `Symbol.dispose`). Lifecycle `onStop` hooks are run by the\n * Application, not here. Idempotent; waits for an in-progress `init()`. Registered values are\n * owned by whoever registered them and are not disposed.\n *\n * @throws ZnightAggregateError (ZNIGHT021) listing every disposal failure.\n */\n dispose(): Promise<void> {\n this.#disposePromise ??= this.#disposeAll()\n return this.#disposePromise\n }\n\n async #disposeAll(): Promise<void> {\n this.#sealed = true\n if (this.#initPromise !== undefined) {\n try {\n await this.#initPromise\n } catch {\n // a failed init already rolled back what it created\n }\n }\n const errors: unknown[] = []\n for (let index = this.#order.length - 1; index >= 0; index--) {\n const slot = this.#order[index] as Slot\n try {\n const result = this.#disposeSlot(slot)\n if (result !== undefined) await result\n } catch (error) {\n errors.push(lifecycleError(`Disposing ${slot.displayName}`, error))\n }\n }\n for (const slot of this.#slots.values()) if (slot.mode === SINGLETON && slot.state === IDLE) slot.state = DISPOSED\n this.#status = 'disposed'\n if (errors.length > 0) {\n throw new ZnightAggregateError(\n ErrorCode.LifecycleFailed,\n `Failed to dispose ${errors.length} provider(s)`,\n errors,\n )\n }\n }\n\n #disposeSlot(slot: Slot): Promise<unknown> | undefined {\n if (slot.mode !== SINGLETON || slot.state !== READY) return undefined\n slot.state = DISPOSED\n const instance = slot.instance\n slot.instance = undefined\n const result = disposeInstance(instance, slot.definition?.dispose)\n return isThenable(result) ? Promise.resolve(result) : undefined\n }\n\n // ---------------------------------------------------------------------------------------------\n // Bindings\n // ---------------------------------------------------------------------------------------------\n\n #slot(token: Token): Slot {\n let slot = this.#slots.get(token)\n if (slot === undefined) {\n slot = new Slot(token)\n this.#slots.set(token, slot)\n if (!this.#lookup.has(token)) this.#lookup.set(token, slot)\n }\n return slot\n }\n\n #indexAliases(aliases: Readonly<Record<Token, Token>>): void {\n const targets = new Map<Token, Token>(Object.entries(aliases))\n for (const [alias, target] of targets) {\n let canonical = target\n const seen = new Set<Token>([alias])\n while (!this.#slots.has(canonical) && targets.has(canonical) && !seen.has(canonical)) {\n seen.add(canonical)\n canonical = targets.get(canonical) as Token\n }\n const slot = this.#lookup.get(canonical) ?? this.#slot(canonical)\n this.#aliases.set(alias, slot)\n if (!this.#lookup.has(alias)) this.#lookup.set(alias, slot)\n }\n }\n\n #declareExternal(external: ExternalDefinition): void {\n if (typeof external?.token !== 'string') {\n throw new ZnightError(ErrorCode.InvalidDecorator, `Invalid external definition: ${errorMessage(external)}`)\n }\n const slot = this.#lookup.get(external.token) ?? this.#slot(external.token)\n slot.external = external\n this.#names = undefined\n }\n\n #bindBuiltin(token: Token, value: unknown, cls?: object): void {\n this.#bind(token, LEVEL_BUILTIN, 'register', (slot, origin) => this.#applyValue(slot, value, LEVEL_BUILTIN, origin))\n if (cls === undefined) return\n const slot = this.#slot(token)\n slot.cls ??= cls\n if (!this.#lookup.has(cls)) this.#lookup.set(cls, slot)\n }\n\n #assertOpen(action: string, key: unknown): void {\n if (this.#sealed) throw sealedError(action, key)\n }\n\n #bind(key: ProviderKey, level: number, action: string, apply: (slot: Slot, origin: string) => void): void {\n this.#assertOpen(action, key)\n const slot = this.#registrationSlot(key, action)\n if (slot.level > level) return\n if (slot.level === level && level !== LEVEL_OVERRIDE && level !== LEVEL_BUILTIN) {\n throw duplicateRegistrationError(action, slot)\n }\n if (level === LEVEL_PLUGIN && slot.compiled) throw compiledProviderError(action, slot)\n apply(slot, this.#originOf(level))\n }\n\n #originOf(level: number): string {\n switch (level) {\n case LEVEL_BUILTIN:\n return '@znight/core'\n case LEVEL_APPLICATION:\n return 'Application.create({ providers })'\n case LEVEL_PLUGIN:\n return this.#origin ?? 'container.register()'\n case LEVEL_OVERRIDE:\n return 'an override'\n default:\n return 'the compiled metadata'\n }\n }\n\n #registrationSlot(key: ProviderKey, action: string): Slot {\n const slot = this.#lookup.get(key)\n if (slot !== undefined) return slot\n if (typeof key === 'string') return this.#slot(key)\n const byName = this.#findByName(key, true)\n if (byName !== undefined) return byName\n throw unknownClassError(action, key)\n }\n\n #applyDefinition(slot: Slot, definition: ProviderDefinition, level: number, origin: string): void {\n slot.mode = modeOf(definition)\n slot.definition = definition\n slot.instance = undefined\n slot.state = IDLE\n slot.level = level\n slot.origin = origin\n if (definition.class !== undefined) {\n slot.cls ??= definition.class\n if (!this.#lookup.has(definition.class)) this.#lookup.set(definition.class, slot)\n }\n this.#names = undefined\n }\n\n #applyValue(slot: Slot, value: unknown, level: number, origin: string): void {\n slot.mode = VALUE\n slot.definition = undefined\n slot.instance = value\n slot.state = READY\n slot.level = level\n slot.origin = origin\n this.#names = undefined\n }\n\n #rootSlot(key: ProviderKey): Slot {\n const slot = this.#lookup.get(key) ?? this.#findByName(key, true)\n if (slot === undefined) throw notFoundError(key)\n return slot\n }\n\n /**\n * Display-name (or class-name) lookup. A class key only keeps the candidates of its hierarchy (see\n * `classMatch`): those known to be of that class win over those whose class is unknown. Ambiguity\n * throws ZNIGHT008 when `strict`.\n */\n #findByName(key: unknown, strict: boolean): Slot | undefined {\n let name: string\n if (typeof key === 'string') name = key\n else if (typeof key === 'function' && typeof key.name === 'string' && key.name !== '') name = key.name\n else return undefined\n const candidates = this.#nameIndex().get(name)\n if (candidates === undefined) return undefined\n const matches = typeof key === 'function' ? classCandidates(candidates, key) : candidates\n if (matches.length === 1) {\n const slot = matches[0] as Slot\n if (this.#sealed) this.#lookup.set(key, slot)\n return slot\n }\n if (matches.length === 0 || !strict) return undefined\n throw ambiguousNameError(name, matches)\n }\n\n #nameIndex(): Map<string, Slot[]> {\n if (this.#names !== undefined) return this.#names\n const index = new Map<string, Slot[]>()\n const add = (name: string, slot: Slot): void => {\n const list = index.get(name)\n if (list === undefined) index.set(name, [slot])\n else if (!list.includes(slot)) list.push(slot)\n }\n for (const slot of this.#slots.values()) {\n if (slot.mode !== UNBOUND || slot.external !== undefined) add(slot.displayName, slot)\n }\n for (const [alias, slot] of this.#aliases) add(displayName(alias), slot)\n this.#names = index\n return index\n }\n}\n\n/** Binds `value` under `token` with built-in precedence (internal, used by Application). */\nexport function bindBuiltin(container: Container, token: Token, value: unknown, cls?: object): void {\n internals.bindBuiltin(container, token, value, cls)\n}\n\n/** Sets the label of subsequent plugin registrations, for error messages (internal). */\nexport function setRegistrationOrigin(container: Container, origin: string | undefined): void {\n internals.setOrigin(container, origin)\n}\n\nconst CLASS_MISMATCH = 0\nconst CLASS_UNKNOWN = 1\nconst CLASS_MATCH = 2\n\n/**\n * The candidates of a class key: those of its hierarchy when there are some, otherwise those whose\n * class is unknown (an unbound external, a provider without a class, a value that is not an instance).\n */\nfunction classCandidates(candidates: readonly Slot[], cls: object): Slot[] {\n const matches: Slot[] = []\n const unknown: Slot[] = []\n for (const slot of candidates) {\n const match = classMatch(slot, cls)\n if (match === CLASS_MATCH) matches.push(slot)\n else if (match === CLASS_UNKNOWN) unknown.push(slot)\n }\n return matches.length > 0 ? matches : unknown\n}\n\n/**\n * How a slot relates to a class key: its class (definition class, or the class it was bound with,\n * which survives a value override) or its value is of the class (or a subclass), its class is\n * unrelated, or it cannot tell. A value that is not an instance of the class does not rule the slot\n * out: types are structural, so a fake declared with `implements` stands for a class without\n * extending it. Provider instances are not inspected, so the answer does not depend on whether the\n * singleton was already created.\n */\nfunction classMatch(slot: Slot, cls: object): number {\n const own = slot.definition?.class\n if (isSubclass(own, cls) || isSubclass(slot.cls, cls)) return CLASS_MATCH\n if (slot.mode === VALUE && isInstance(slot.instance, cls)) return CLASS_MATCH\n return own === undefined && slot.cls === undefined ? CLASS_UNKNOWN : CLASS_MISMATCH\n}\n\nfunction isSubclass(own: object | undefined, cls: object): boolean {\n return own !== undefined && (own === cls || isInstance((own as { prototype?: unknown }).prototype, cls))\n}\n\n/** `value instanceof cls` through the prototype chain only (no `Symbol.hasInstance`, never throws). */\nfunction isInstance(value: unknown, cls: object): boolean {\n const prototype: unknown = (cls as { prototype?: unknown }).prototype\n return (\n prototype !== null &&\n typeof prototype === 'object' &&\n value !== null &&\n (typeof value === 'object' || typeof value === 'function') &&\n Object.prototype.isPrototypeOf.call(prototype, value)\n )\n}\n\nfunction disposeQuietly(instance: unknown, method: string | undefined): void {\n try {\n const result = disposeInstance(instance, method)\n if (isThenable(result)) result.then(undefined, () => undefined)\n } catch {\n // best effort\n }\n}\n\n/** Implementation of {@link OpenedScope}. */\nclass ScopeHandle implements OpenedScope {\n readonly #storage: AsyncLocalStorage<RequestScope>\n readonly #scope: RequestScope\n readonly #dispose: (scope: RequestScope) => Promise<unknown[]>\n #closed = false\n #closing: Promise<void> | undefined\n\n constructor(\n storage: AsyncLocalStorage<RequestScope>,\n scope: RequestScope,\n dispose: (scope: RequestScope) => Promise<unknown[]>,\n ) {\n this.#storage = storage\n this.#scope = scope\n this.#dispose = dispose\n }\n\n get context(): ScopeContext {\n return this.#scope\n }\n\n run<A extends readonly unknown[], R>(fn: (...args: A) => R, ...args: A): R {\n return this.#storage.run(this.#scope, fn, ...args)\n }\n\n close(): Promise<void> | undefined {\n if (this.#closed) return this.#closing\n this.#closed = true\n const scope = this.#scope\n if (scope.created.length === 0) {\n scope.closed = true\n return undefined\n }\n this.#closing = this.#dispose(scope).then(errors => {\n if (errors.length > 0) {\n throw new ZnightAggregateError(\n ErrorCode.LifecycleFailed,\n `Failed to dispose ${errors.length} request-scoped instance(s)`,\n errors,\n )\n }\n })\n return this.#closing\n }\n}\n","import type { CoreLogger } from './logger.ts'\n\nimport { isThenable } from './utils.ts'\n\n/**\n * Typed registry of hook names and their event types. Third-party packages may augment it:\n *\n * ```ts\n * declare module '@znight/core' {\n * interface ZnightHooks {\n * 'http:request': HttpRequestEvent\n * }\n * }\n * ```\n */\nexport interface ZnightHooks {\n /** One HTTP request handled by `@znight/http` (wrapped with `hooks.run`). */\n 'http:request': HttpRequestEvent\n /** One message delivery handled by `@znight/messaging` (wrapped with `hooks.run`). */\n 'messaging:message': MessageDeliveryEvent\n /** One message published through `MessageBroker` of `@znight/messaging` (wrapped with `hooks.run`). */\n 'messaging:publish': MessagePublishEvent\n /**\n * One occurrence of a job of `@znight/schedule`: executed runs are wrapped with `hooks.run`, then\n * emitted; occurrences that do not execute (`skipped`, `not-acquired`, a lock store failure) are\n * only emitted. In the wrappers, `outcome` stays `undefined` when the job did not start (veto,\n * drop, a wrapper that threw first): see `ScheduledRunEvent.outcome`.\n */\n 'schedule:run': ScheduledRunEvent\n /**\n * One GraphQL operation handled by `@znight/graphql` (RFC 0005): a query or a mutation, or a whole\n * subscription from its start to its end. Wrapped with `hooks.run` when wrappers exist, then\n * emitted when listeners exist.\n */\n 'graphql:operation': GraphQLOperationEvent\n /**\n * One publication of `@znight/events` (`EventPublisher.publish()` or `emit()`) that matched at least\n * one listener (RFC 0011): wraps the inline phase with `hooks.run` when wrappers exist, then is\n * emitted when listeners exist. A publication without listener produces nothing.\n */\n 'events:publish': EventPublishEvent\n /**\n * One listener invocation of `@znight/events` (RFC 0011), inline or detached: wrapped with\n * `hooks.run` when wrappers exist, then emitted when listeners exist.\n */\n 'events:listener': EventListenerEvent\n}\n\n/**\n * Instrumentation event of the `http:request` hook. Defined in core so that producers\n * (`@znight/http`) and observers (`@znight/observability`, user plugins) share one type.\n * Mutable fields are filled in by the producer while the request is processed.\n */\nexport interface HttpRequestEvent {\n readonly method: string\n /** Request path, without query string. */\n readonly path: string\n /** Matched route pattern (e.g. `/users/:id`), `undefined` when no route matched. */\n readonly route: string | undefined\n readonly requestId: string\n /** Lower-cased request headers. */\n readonly headers: Readonly<Record<string, string | undefined>>\n /** Adapter-neutral context (`HttpContext` from `@znight/http`). */\n readonly context: unknown\n /** `performance.now()` when the request started. */\n readonly startTime: number\n /** Final response status, set before `hooks.run` resolves. */\n status?: number\n /** Error thrown by the pipeline, if any (already mapped to `status`). */\n error?: unknown\n /** Response headers to add (e.g. trace context). */\n readonly responseHeaders: Record<string, string>\n}\n\n/**\n * Instrumentation event of the `messaging:publish` hook. Wrappers may add headers (e.g. W3C trace\n * context) before calling `next()`: they are sent with the message.\n */\nexport interface MessagePublishEvent {\n readonly queue: string\n readonly type: string | undefined\n readonly messageId: string\n /** Headers sent with the message (mutable until `next()` is called). */\n readonly headers: Record<string, string>\n /** `performance.now()` when the publication started. */\n readonly startTime: number\n /** Publication error, set before `next()` rejects in the wrappers. */\n error?: unknown\n}\n\n/** Instrumentation event of the `messaging:message` hook. */\nexport interface MessageDeliveryEvent {\n readonly queue: string\n readonly type: string | undefined\n readonly messageId: string\n /** 1-based delivery attempt. */\n readonly attempt: number\n readonly headers: Readonly<Record<string, string>>\n /** Display name of the consumer class. */\n readonly consumer: string\n /** Handler method, `undefined` when no handler matched. */\n readonly handler: string | undefined\n /** `InboundMessage` from `@znight/messaging`. */\n readonly message: unknown\n readonly startTime: number\n /** Outcome set before `hooks.run` resolves. */\n outcome?: 'ack' | 'retry' | 'dead-letter'\n error?: unknown\n}\n\n/** How a scheduled run was triggered (`ScheduledRunEvent.trigger`). */\nexport type ScheduledRunTrigger = 'schedule' | 'start' | 'manual' | 'queued'\n\n/** Outcome of a scheduled run (`ScheduledRunEvent.outcome`). */\nexport type ScheduledRunOutcome = 'completed' | 'failed' | 'skipped' | 'not-acquired'\n\n/** Why a scheduled run was aborted (`ScheduledRunEvent.aborted`, the `reason` of `JobAbortedError`). */\nexport type ScheduledRunAbortReason = 'timeout' | 'lock-lost' | 'removed' | 'shutdown'\n\n/**\n * Instrumentation event of the `schedule:run` hook, produced by `@znight/schedule` for every\n * occurrence of a job. Mutable fields are filled in by the producer.\n *\n * - **Listeners** (`hooks.on`) always see the final {@link ScheduledRunEvent.outcome}: the event is\n * emitted once the occurrence is settled.\n * - **Occurrences that never reach the wrappers** (`context` is `undefined`: skipped by the overlap\n * policy, `not-acquired`, a lock store failure, dropped while the lock lease was acquired) are\n * only emitted, with their `outcome`.\n * - **Runs handed to the job** (`context` is set) are wrapped with `hooks.run`, where `outcome` is\n * only known once the job settled, and stays `undefined` when the job did not start: see\n * {@link ScheduledRunEvent.outcome} for what a wrapper reads after `next()`.\n */\nexport interface ScheduledRunEvent {\n /** Job name (`digest.daily`, `OutboxJobs.flush`). */\n readonly job: string\n readonly kind: 'cron' | 'interval' | 'timeout'\n /** Display name of the host class; `undefined` for dynamic jobs. */\n readonly host: string | undefined\n /** Job method; `undefined` for dynamic jobs. */\n readonly method: string | undefined\n /** Unique id of the run. */\n readonly runId: string\n readonly trigger: ScheduledRunTrigger\n /** Epoch milliseconds of the occurrence (scheduler clock). */\n readonly scheduledAt: number\n /**\n * `JobContext` from `@znight/schedule`; `undefined` for an occurrence that never reached the\n * wrappers (set for a run vetoed or dropped by the wrappers).\n */\n readonly context: unknown\n /** `performance.now()` when the run started, or was dropped. */\n readonly startTime: number\n /**\n * Outcome of the run. Listeners always see it. In a `hooks.run` wrapper, it is `undefined` until\n * the job settles, then:\n *\n * - `'completed'` when `next()` resolves after the job ran;\n * - `'failed'`, with {@link ScheduledRunEvent.error}, when `next()` rejects because the job threw;\n * - still `undefined` when the job never started: a wrapper returned without calling `next()` (a\n * veto: `next()` of the outer wrappers resolves), the run was dropped while the wrappers waited\n * (the job was removed or paused, the scheduler stops: `next()` resolves, `aborted` may be set),\n * or a wrapper threw before calling `next()` (`next()` of the outer wrappers rejects with that\n * error).\n *\n * The producer settles an `undefined` outcome after `hooks.run`: `'skipped'` for a veto or a\n * drop, `'failed'` (with `error`) when a wrapper, or the opening of the run scope, threw before the\n * job (a wrapper that swallows that rejection turns it into `'skipped'`: rethrow it). A wrapper\n * that fails after `next()` does not change the outcome of the job (the scheduler logs that error\n * on its own). A wrapper that reports the outcome reads\n * `event.outcome ?? (nextRejected ? 'failed' : 'skipped')`.\n */\n outcome?: ScheduledRunOutcome\n /**\n * What the job threw or rejected with (`failed`), what a wrapper threw before the job (set after\n * `hooks.run`), or the lock store failure.\n */\n error?: unknown\n /** Set when the run's signal was aborted. */\n aborted?: ScheduledRunAbortReason\n}\n\n/** Type of a GraphQL operation (`GraphQLOperationEvent.operationType`). */\nexport type GraphQLOperationType = 'query' | 'mutation' | 'subscription'\n\n/**\n * How a GraphQL operation reached the server (`GraphQLOperationEvent.transport`): GraphQL over HTTP,\n * GraphQL over Server-Sent Events, GraphQL over WebSocket (`ws`, reserved for `graphql-ws`), or a\n * direct call (`execute()` / `subscribe()` of the plugin).\n */\nexport type GraphQLOperationTransport = 'http' | 'sse' | 'ws' | 'direct'\n\n/**\n * Outcome of a GraphQL operation (`GraphQLOperationEvent.outcome`):\n *\n * - `'success'`: executed, no error;\n * - `'partial'`: executed, with data and field errors;\n * - `'error'`: executed, without data (a non-null root field failed, or the execution threw);\n * - `'rejected'`: never executed (parse, validation, variable coercion or limit errors).\n */\nexport type GraphQLOperationOutcome = 'success' | 'partial' | 'error' | 'rejected'\n\n/** One error of a GraphQL response, as sent to the client (masked when it is unexpected). */\nexport interface GraphQLOperationError {\n readonly message: string\n /** `extensions.code` of the error (`FORBIDDEN`, `GRAPHQL_PARSE_FAILED`...). */\n readonly code: string | undefined\n /** Response path of the field that failed; absent for request errors. */\n readonly path?: readonly (string | number)[]\n}\n\n/**\n * Instrumentation event of the `graphql:operation` hook, produced by `@znight/graphql` (RFC 0005)\n * once per operation. For a subscription, it covers its whole life: wrappers see it start, and\n * `outcome` is set when it ends. Mutable fields are filled in by the producer before `hooks.run`\n * resolves; listeners see the final values.\n */\nexport interface GraphQLOperationEvent {\n /** `undefined` when the request was rejected before an operation was selected (parse error...). */\n readonly operationType: GraphQLOperationType | undefined\n /** `undefined` for an anonymous operation, or when none was selected. */\n readonly operationName: string | undefined\n /** SHA-256 (hex) of the query text, cached with the parsed document; `undefined` without a query. */\n readonly documentId: string | undefined\n readonly transport: GraphQLOperationTransport\n /**\n * The GraphQL driver that received the operation (RFC 0009): `'builtin'` for the built-in\n * transport and for direct calls, `'yoga'`, `'apollo'` or a third-party driver's name otherwise.\n */\n readonly driver: string\n readonly requestId: string\n /** `GraphQLContext` from `@znight/graphql`. */\n readonly context: unknown\n /** `performance.now()` when the operation started. */\n readonly startTime: number\n /** Outcome, set before `hooks.run` resolves. */\n outcome?: GraphQLOperationOutcome\n /** Errors of the response (field and request errors), set before `hooks.run` resolves. */\n errors?: readonly GraphQLOperationError[]\n}\n\n/** How an application event was published (`EventPublishEvent.mode`). */\nexport type EventPublishMode = 'publish' | 'emit'\n\n/**\n * Instrumentation event of the `events:publish` hook, produced by `@znight/events` (RFC 0011) for a\n * publication that matched at least one listener. The wrappers surround the inline phase (the\n * detached listeners are scheduled after it succeeded); `error` and `failedListener` are set before\n * `next()` rejects.\n */\nexport interface EventPublishEvent {\n /** Class name of the event (`UserCreated`). */\n readonly event: string\n /** The published object. */\n readonly payload: object\n readonly mode: EventPublishMode\n /** Number of inline listeners matched. */\n readonly inline: number\n /** Number of detached listeners matched. */\n readonly detached: number\n /** `performance.now()` when the publication started. */\n readonly startTime: number\n /** First inline error, set before `next()` rejects in the wrappers. */\n error?: unknown\n /** `Class.method` of the inline listener that failed. */\n failedListener?: string\n}\n\n/**\n * Instrumentation event of the `events:listener` hook, produced by `@znight/events` (RFC 0011) for\n * every listener invocation. Inline listeners run in the publisher's async context, detached ones in\n * a fresh scope of their own; `error` is set before `next()` rejects.\n */\nexport interface EventListenerEvent {\n /** Class name of the event. */\n readonly event: string\n /** The published object. */\n readonly payload: object\n /** `Class.method` of the listener (`WelcomeMail.send`). */\n readonly listener: string\n readonly detached: boolean\n /** `performance.now()` when the invocation started. */\n readonly startTime: number\n /** What the listener threw or rejected with. */\n error?: unknown\n}\n\n/** Name of a declared hook. */\nexport type HookName = keyof ZnightHooks\n\n/** Event type of hook `K`. */\nexport type HookEvent<K extends HookName> = ZnightHooks[K]\n\n/** Observer of a hook. Errors (thrown or rejected) are reported to the logger, never to the emitter. */\nexport type HookListener<K extends HookName> = (event: HookEvent<K>) => unknown\n\n/**\n * Middleware around a hooked operation (`hooks.run()`). Must call `next()` to run the inner\n * wrappers and the operation; `next()` resolves with the operation's result. The value returned by\n * the wrapper itself is ignored.\n */\nexport type HookWrapper<K extends HookName> = (event: HookEvent<K>, next: () => Promise<unknown>) => Promise<unknown>\n\nexport interface HooksOptions {\n /** Receives listener failures. Default: the console. */\n readonly logger?: CoreLogger\n}\n\ntype AnyListener = (event: unknown) => unknown\ntype AnyWrapper = (event: unknown, next: () => Promise<unknown>) => unknown\n\nconst EMPTY: readonly never[] = Object.freeze([])\n\n/**\n * Lightweight, typed event bus used by plugins to observe (`on`/`emit`) and wrap (`wrap`/`run`)\n * framework operations (`http:request`, `messaging:message`...). Registration is copy-on-write, so\n * emitting allocates nothing.\n */\nexport class Hooks {\n readonly #listeners = new Map<PropertyKey, readonly AnyListener[]>()\n readonly #wrappers = new Map<PropertyKey, readonly AnyWrapper[]>()\n readonly #logger: CoreLogger | undefined\n\n constructor(options: HooksOptions = {}) {\n this.#logger = options.logger\n }\n\n /** Adds a listener. Returns a function removing it (idempotent). */\n on<K extends HookName>(name: K, listener: HookListener<K>): () => void {\n return add(this.#listeners, name, listener as AnyListener)\n }\n\n /**\n * Calls every listener of `name` synchronously, in registration order. A failing listener\n * (thrown error or rejected promise) is reported to the logger and does not affect the others.\n */\n emit<K extends HookName>(name: K, event: HookEvent<K>): void {\n const listeners = this.#listeners.get(name)\n if (listeners === undefined) return\n for (const listener of listeners) {\n try {\n const result = listener(event)\n if (isThenable(result)) result.then(undefined, error => this.#report(name, error))\n } catch (error) {\n this.#report(name, error)\n }\n }\n }\n\n /** Adds a wrapper around operations run with {@link run}. Returns a function removing it (idempotent). */\n wrap<K extends HookName>(name: K, wrapper: HookWrapper<K>): () => void {\n return add(this.#wrappers, name, wrapper as AnyWrapper)\n }\n\n /**\n * Runs `fn` through the wrappers of `name` (onion model: the first registered wrapper is the\n * outermost) and resolves with the result of `fn`. Without wrappers, `fn` is called directly.\n * If a wrapper does not call `next()`, `fn` does not run and the promise resolves with `undefined`.\n */\n run<K extends HookName, R>(name: K, event: HookEvent<K>, fn: () => Promise<R>): Promise<R> {\n const wrappers = this.#wrappers.get(name) ?? EMPTY\n if (wrappers.length === 0) {\n try {\n return Promise.resolve(fn())\n } catch (error) {\n return Promise.reject(error)\n }\n }\n let result: R | undefined\n const dispatch = async (index: number): Promise<unknown> => {\n if (index === wrappers.length) {\n result = await fn()\n return result\n }\n const wrapper = wrappers[index] as AnyWrapper\n await wrapper(event, () => dispatch(index + 1))\n return result\n }\n return dispatch(0).then(() => result as R)\n }\n\n /** Whether `name` has listeners (lets emitters skip building costly events). */\n hasListeners(name: HookName): boolean {\n return (this.#listeners.get(name)?.length ?? 0) > 0\n }\n\n /** Whether `name` has wrappers. */\n hasWrappers(name: HookName): boolean {\n return (this.#wrappers.get(name)?.length ?? 0) > 0\n }\n\n #report(name: PropertyKey, error: unknown): void {\n const message = `Hook listener for \"${String(name)}\" failed`\n if (this.#logger === undefined) console.error(`[znight] ${message}`, error)\n else this.#logger.error(message, { hook: String(name), err: error })\n }\n}\n\nfunction add<F>(registry: Map<PropertyKey, readonly F[]>, name: PropertyKey, fn: F): () => void {\n registry.set(name, [...(registry.get(name) ?? EMPTY), fn])\n let active = true\n return () => {\n if (!active) return\n active = false\n const current = registry.get(name) ?? EMPTY\n const index = current.indexOf(fn)\n if (index === -1) return\n const next = [...current.slice(0, index), ...current.slice(index + 1)]\n if (next.length === 0) registry.delete(name)\n else registry.set(name, next)\n }\n}\n","/** Structured context attached to a log entry. */\nexport type LogContext = Readonly<Record<string, unknown>>\n\n/**\n * Minimal logger used by the core runtime and by plugins. `@znight/observability` replaces the\n * default console implementation with a structured (pino) logger through `app.setLogger()`.\n */\nexport interface CoreLogger {\n debug(message: string, context?: LogContext): void\n info(message: string, context?: LogContext): void\n warn(message: string, context?: LogContext): void\n error(message: string, context?: LogContext): void\n}\n\n/** Log levels, from the most to the least verbose. `silent` disables every entry. */\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent'\n\nconst LEVELS: Readonly<Record<LogLevel, number>> = { debug: 10, info: 20, warn: 30, error: 40, silent: 100 }\n\n/** The subset of `console` used by {@link createConsoleLogger}. */\nexport type ConsoleLike = Pick<Console, 'debug' | 'info' | 'warn' | 'error'>\n\nexport interface ConsoleLoggerOptions {\n /** Minimum level written. Default: `info`. */\n readonly level?: LogLevel\n /** Prefix of every message. Default: `[znight]`. */\n readonly prefix?: string\n /** Destination. Default: the global `console`. */\n readonly console?: ConsoleLike\n}\n\n/** Creates a {@link CoreLogger} writing to the console. Entries below `level` are dropped. */\nexport function createConsoleLogger(options: ConsoleLoggerOptions = {}): CoreLogger {\n const threshold = LEVELS[options.level ?? 'info']\n const prefix = options.prefix ?? '[znight]'\n const out = options.console ?? console\n const write = (level: Exclude<LogLevel, 'silent'>, message: string, context?: LogContext): void => {\n if (LEVELS[level] < threshold) return\n const text = prefix === '' ? message : `${prefix} ${message}`\n if (context === undefined || Object.keys(context).length === 0) out[level](text)\n else out[level](text, context)\n }\n return {\n debug: (message, context) => write('debug', message, context),\n info: (message, context) => write('info', message, context),\n warn: (message, context) => write('warn', message, context),\n error: (message, context) => write('error', message, context),\n }\n}\n\nfunction noop(): void {}\n\n/** A logger dropping every entry (useful in tests). */\nexport const silentLogger: CoreLogger = Object.freeze({ debug: noop, info: noop, warn: noop, error: noop })\n\n/**\n * A logger forwarding every call to a replaceable target. Plugins receive this instance, so a\n * logger installed later (e.g. by `@znight/observability`) is used by everyone immediately.\n */\nexport class DelegatingLogger implements CoreLogger {\n #target: CoreLogger\n\n constructor(target: CoreLogger) {\n this.#target = target\n }\n\n /** The logger currently receiving the entries. */\n get target(): CoreLogger {\n return this.#target\n }\n\n /** Replaces the logger receiving the entries. Passing the delegating logger itself is ignored. */\n setTarget(target: CoreLogger): void {\n if (target !== this) this.#target = target\n }\n\n debug(message: string, context?: LogContext): void {\n this.#target.debug(message, context)\n }\n\n info(message: string, context?: LogContext): void {\n this.#target.info(message, context)\n }\n\n warn(message: string, context?: LogContext): void {\n this.#target.warn(message, context)\n }\n\n error(message: string, context?: LogContext): void {\n this.#target.error(message, context)\n }\n}\n","import { ErrorCode, ZnightError } from './errors.ts'\nimport { isThenable } from './utils.ts'\n\n/** Signals the application can listen to for a graceful shutdown. */\nexport type ShutdownSignal = 'SIGINT' | 'SIGTERM' | 'SIGHUP' | 'SIGQUIT' | 'SIGBREAK' | 'SIGUSR1' | 'SIGUSR2'\n\n/**\n * The parts of `process` used by the application (signals, exit code, forced exit). Injectable for\n * tests through `Application.create({ shutdown: { process } })`.\n */\nexport interface ProcessLike {\n on(event: string, listener: (signal: string) => void): unknown\n off(event: string, listener: (signal: string) => void): unknown\n exit(code?: number): unknown\n exitCode?: number | string | null | undefined\n}\n\n/** The global `process`, when the runtime has one. */\nexport function defaultProcess(): ProcessLike | undefined {\n const candidate: unknown = (globalThis as { process?: unknown }).process\n if (candidate === null || typeof candidate !== 'object') return undefined\n const proc = candidate as Partial<ProcessLike>\n return typeof proc.on === 'function' && typeof proc.off === 'function' && typeof proc.exit === 'function'\n ? (proc as ProcessLike)\n : undefined\n}\n\n/** ZNIGHT021 raised when a lifecycle step exceeds its time budget. */\nexport class StepTimeoutError extends ZnightError {\n constructor(step: string, ms: number) {\n super(ErrorCode.LifecycleFailed, `${step} timed out after ${Math.round(ms)}ms`)\n }\n}\n\n/**\n * Longest delay a timer accepts (2^31 - 1 ms, about 24.8 days): Node and Bun clamp longer delays to\n * 1 ms. A longer budget (or `Infinity`) therefore means no timeout.\n */\nconst MAX_TIMEOUT_MS = 2_147_483_647\n\n/**\n * Runs `step` and resolves when it completes, or rejects with a {@link StepTimeoutError} after `ms`.\n * A synchronous step (or one resolving within the current tick of microtasks) always completes,\n * even with a zero budget. A step completing after its timeout is ignored. A budget above\n * {@link MAX_TIMEOUT_MS} (or `Infinity`) waits for the step without a timer.\n */\nexport function runWithTimeout(label: string, step: () => unknown, ms: number): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n let result: unknown\n try {\n result = step()\n } catch (error) {\n reject(error)\n return\n }\n if (!isThenable(result)) {\n resolve()\n return\n }\n let settled = false\n const timer =\n ms > MAX_TIMEOUT_MS\n ? undefined\n : setTimeout(() => {\n if (settled) return\n settled = true\n reject(new StepTimeoutError(label, ms))\n }, ms)\n result.then(\n () => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n resolve()\n },\n (error: unknown) => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n reject(error)\n },\n )\n })\n}\n","import type { LifecycleHook, ProviderClass, Token, ZnightMetadata } from './metadata.ts'\nimport type { Plugin, PluginContext, PluginHook } from './plugin.ts'\n\nimport { AsyncLocalStorage } from 'node:async_hooks'\n\nimport { bindBuiltin, Container, type InitOptions, type ManagedInstance, setRegistrationOrigin } from './container.ts'\nimport { ErrorCode, ZnightError } from './errors.ts'\nimport { Hooks } from './hooks.ts'\nimport { callLifecycleHook, hasLifecycleHook, isDisposable } from './lifecycle.ts'\nimport { type CoreLogger, createConsoleLogger, DelegatingLogger } from './logger.ts'\nimport { defaultProcess, type ProcessLike, runWithTimeout, type ShutdownSignal, StepTimeoutError } from './process.ts'\nimport { addSuppressedErrors, lifecycleError, ZnightAggregateError } from './runtime-errors.ts'\nimport { type ClassKey, CoreTokens, type ProviderKey, type TypedToken } from './tokens.ts'\nimport { errorMessage, now } from './utils.ts'\n\n/** Lifecycle state of an {@link Application}. */\nexport type ApplicationState = 'created' | 'starting' | 'ready' | 'stopping' | 'stopped' | 'failed'\n\n/** Values keyed by token or class: a `Map`, an iterable of pairs, or a record keyed by token. */\nexport type ProviderValues = Iterable<readonly [ProviderKey, unknown]> | Readonly<Record<Token, unknown>>\n\n/** Graceful shutdown settings. */\nexport interface ShutdownOptions {\n /** Signals stopping the application once started. Default: `['SIGINT', 'SIGTERM']`; `false` disables. */\n readonly signals?: readonly ShutdownSignal[] | false\n /**\n * Global deadline of `stop()`, in milliseconds. Default: 10 000. `Infinity` (or any value above\n * 2^31 - 1, the range of timers) means no deadline.\n */\n readonly timeoutMs?: number\n /**\n * Maximum duration of each shutdown step (hook or disposal), in milliseconds. Default: 5 000.\n * `Infinity` (or any value above 2^31 - 1) means no limit.\n */\n readonly hookTimeoutMs?: number\n /** Process used for signals, `exitCode` and forced exits. Default: the global `process`. */\n readonly process?: ProcessLike\n}\n\n/**\n * Hot module replacement handle (`import.meta.hot`). The dispose callback returns the `stop()`\n * promise, so that runtimes awaiting it (Vite's module runner, Bun) load the new module once the\n * application has stopped.\n */\nexport interface HotContext {\n dispose(callback: (data: unknown) => void | Promise<void>): void\n}\n\n/** Options of {@link Application.create}. */\nexport interface ApplicationOptions {\n /** The metadata generated by `@znight/compiler` (`__ZNIGHT_METADATA__`). */\n readonly metadata: ZnightMetadata\n readonly plugins?: readonly Plugin[]\n /** Values supplied by the application (externals, configuration...). Superseded by plugins. */\n readonly providers?: ProviderValues\n /** Replacements applied after plugins registered (highest precedence): values or provider definitions. */\n readonly overrides?: ProviderValues\n /** Initial logger. Default: a console logger (level `info`). Replace it later with `setLogger()`. */\n readonly logger?: CoreLogger\n readonly shutdown?: ShutdownOptions\n /** Forwarded to `container.init()` (e.g. `{ only: [UserController] }`). */\n readonly init?: InitOptions\n /** Pass `import.meta.hot` to stop the application when the module is replaced. */\n readonly hot?: HotContext\n}\n\nconst DEFAULT_SIGNALS: readonly ShutdownSignal[] = ['SIGINT', 'SIGTERM']\nconst DEFAULT_TIMEOUT_MS = 10_000\nconst DEFAULT_HOOK_TIMEOUT_MS = 5_000\nconst FORCED_EXIT_CODE = 130\n\n/**\n * Carries a marker through the async context of the start hook in progress, so that `stop()` can\n * tell a request coming from that hook (which must not wait for the start: the start waits for it).\n */\nconst startHookContext = new AsyncLocalStorage<object>()\n\n/**\n * A Znight application: a container built from the compiled metadata, plugins and the lifecycle\n * tying them together.\n *\n * ```ts\n * const app = await Application.create({\n * metadata: __ZNIGHT_METADATA__,\n * plugins: [HttpPlugin.configure({ port: 3000 })],\n * })\n * await app.start()\n * ```\n */\nexport class Application {\n readonly container: Container\n readonly hooks: Hooks\n readonly metadata: ZnightMetadata\n readonly #logger: DelegatingLogger\n readonly #plugins: readonly Plugin[]\n readonly #pluginsByName: ReadonlyMap<string, Plugin>\n readonly #context: PluginContext\n readonly #signals: readonly ShutdownSignal[]\n readonly #process: ProcessLike | undefined\n readonly #timeoutMs: number\n readonly #hookTimeoutMs: number\n #state: ApplicationState = 'created'\n #startPromise: Promise<void> | undefined\n #stopPromise: Promise<void> | undefined\n /** Plugins whose `register` was attempted (they all receive `onDispose`). */\n readonly #registered: Plugin[] = []\n /** Plugins whose `onStart` completed (they receive `onStop`). */\n readonly #startedPlugins: Plugin[] = []\n /** Providers whose `onStart` completed (they receive `onStop`). */\n readonly #startedProviders = new Set<Token>()\n #listening: readonly ShutdownSignal[] = []\n #signalReceived = false\n /** Marker of the start hook in progress (see `startHookContext`). */\n #startHookMarker: object | undefined\n /** A start hook called `stop()`: the remaining start hooks are skipped. */\n #startAborted = false\n /** Releases a `stop()` waiting for the start, when a start hook asks to stop in turn. */\n #releaseStopWait: (() => void) | undefined\n\n private constructor(options: ApplicationOptions) {\n const plugins = [...(options.plugins ?? [])]\n const byName = new Map<string, Plugin>()\n for (const plugin of plugins) {\n if (plugin === null || typeof plugin !== 'object' || typeof plugin.name !== 'string' || plugin.name === '') {\n throw new ZnightError(ErrorCode.InvalidDecorator, `Invalid plugin: ${errorMessage(plugin)} has no name`)\n }\n if (byName.has(plugin.name)) {\n throw new ZnightError(ErrorCode.DuplicateProvider, `Duplicate plugin \"${plugin.name}\"`, {\n hints: ['Each plugin can be added once to Application.create({ plugins })'],\n })\n }\n byName.set(plugin.name, plugin)\n }\n this.#plugins = plugins\n this.#pluginsByName = byName\n this.metadata = options.metadata\n this.container = Container.create(options.metadata)\n this.#logger = new DelegatingLogger(options.logger ?? createConsoleLogger())\n this.hooks = new Hooks({ logger: this.#logger })\n\n const shutdown = options.shutdown ?? {}\n this.#process = shutdown.process ?? defaultProcess()\n this.#signals = shutdown.signals === false ? [] : [...(shutdown.signals ?? DEFAULT_SIGNALS)]\n this.#timeoutMs = positive(shutdown.timeoutMs, DEFAULT_TIMEOUT_MS, 'shutdown.timeoutMs')\n this.#hookTimeoutMs = positive(shutdown.hookTimeoutMs, DEFAULT_HOOK_TIMEOUT_MS, 'shutdown.hookTimeoutMs')\n\n bindBuiltin(this.container, CoreTokens.Application, this, Application)\n bindBuiltin(this.container, CoreTokens.Hooks, this.hooks, Hooks)\n bindBuiltin(this.container, CoreTokens.Logger, this.#logger)\n\n this.#context = Object.freeze({\n app: this,\n container: this.container,\n metadata: this.metadata,\n hooks: this.hooks,\n logger: this.#logger,\n getPlugin: <P extends Plugin = Plugin>(name: string): P | undefined => this.getPlugin<P>(name),\n })\n }\n\n /**\n * Creates the container, supplies `providers`, runs plugins' `register` (in order), applies\n * `overrides`, initialises the container and runs plugins' `onBootstrap`. On failure everything\n * created so far is disposed (plugins receive `onDispose`) and the error is rethrown.\n */\n static async create(options: ApplicationOptions): Promise<Application> {\n const app = new Application(options)\n await app.#bootstrap(options)\n return app\n }\n\n /** Current lifecycle state. */\n get state(): ApplicationState {\n return this.#state\n }\n\n /** The application logger (live: follows {@link setLogger}). */\n get logger(): CoreLogger {\n return this.#logger\n }\n\n /** Plugins, in registration order. */\n get plugins(): readonly Plugin[] {\n return this.#plugins\n }\n\n /** Replaces the logger used by the core and every plugin holding `ctx.logger`. */\n setLogger(logger: CoreLogger): void {\n this.#logger.setTarget(logger)\n }\n\n /** A plugin of the application, by name. */\n getPlugin<P extends Plugin = Plugin>(name: string): P | undefined {\n return this.#pluginsByName.get(name) as P | undefined\n }\n\n /** Shortcut for `app.container.get(key)`. */\n get<T>(key: ProviderClass<T>): T\n get<T>(key: ClassKey<T>): T\n get<T = unknown>(key: TypedToken<T>): T\n get(key: ProviderKey): unknown {\n return this.container.get(key as TypedToken<unknown>)\n }\n\n async #bootstrap(options: ApplicationOptions): Promise<void> {\n const container = this.container\n try {\n if (options.providers !== undefined) {\n for (const [key, value] of entriesOf(options.providers)) container.provide(key, value)\n }\n for (const plugin of this.#plugins) {\n this.#registered.push(plugin)\n setRegistrationOrigin(container, `plugin \"${plugin.name}\"`)\n try {\n await this.#callPlugin(plugin, 'register')\n } finally {\n setRegistrationOrigin(container, undefined)\n }\n }\n if (options.overrides !== undefined) {\n for (const [key, value] of entriesOf(options.overrides)) container.override(key, value)\n }\n await container.init(options.init)\n for (const plugin of this.#plugins) await this.#callPlugin(plugin, 'onBootstrap')\n } catch (error) {\n this.#state = 'failed'\n // nothing was started yet: this disposes the providers and runs plugins' onDispose\n addSuppressedErrors(error, await this.#shutdown())\n throw error\n }\n // the HMR runtime awaits the returned promise before it loads the new module\n options.hot?.dispose(() =>\n this.stop().catch((error: unknown) => this.#logger.error('Failed to stop the application', { err: error })),\n )\n }\n\n // ---------------------------------------------------------------------------------------------\n // start / stop\n // ---------------------------------------------------------------------------------------------\n\n /**\n * Starts the application: providers' `onStart` (resolution order) → plugins' `onStart` →\n * providers' `onReady` → plugins' `onReady`, then `state === 'ready'`. Signal handlers are\n * installed when the start begins. On failure, what was started is stopped, everything is\n * disposed, `state === 'failed'` and the error is rethrown (cleanup errors attached).\n * Calling it while starting returns the same promise; once ready it resolves immediately.\n * When a start hook calls `stop()` (e.g. a job that ends its work in `onReady`), the remaining\n * start hooks are skipped and the promise resolves once the application is stopped.\n */\n start(): Promise<void> {\n switch (this.#state) {\n case 'created':\n this.#startPromise = this.#runStart()\n return this.#startPromise\n case 'starting':\n return this.#startPromise as Promise<void>\n case 'ready':\n return Promise.resolve()\n default:\n return Promise.reject(\n new ZnightError(ErrorCode.LifecycleFailed, `Cannot start the application: it is ${this.#state}`),\n )\n }\n }\n\n async #runStart(): Promise<void> {\n this.#state = 'starting'\n this.#installSignals()\n let completed: boolean\n try {\n completed = await this.#runStartHooks()\n } catch (error) {\n if (this.#startAborted) {\n // the shutdown requested by a start hook owns the cleanup\n await this.#settledStop()\n throw error\n }\n addSuppressedErrors(error, await this.#shutdown())\n this.#removeSignals()\n this.#state = 'failed'\n throw error\n }\n if (!completed) {\n await this.#settledStop()\n return\n }\n this.#state = 'ready'\n this.#logger.debug('Application started')\n }\n\n /** Runs the start hooks in order; `false` when one of them called `stop()` (the others are skipped). */\n async #runStartHooks(): Promise<boolean> {\n const providers = this.container.instances()\n for (const provider of providers) {\n if (!(await this.#startHook(() => this.#callProvider(provider, 'onStart')))) return false\n this.#startedProviders.add(provider.token)\n }\n for (const plugin of this.#plugins) {\n if (!(await this.#startHook(() => this.#callPlugin(plugin, 'onStart')))) return false\n this.#startedPlugins.push(plugin)\n }\n for (const provider of providers) {\n if (!(await this.#startHook(() => this.#callProvider(provider, 'onReady')))) return false\n }\n for (const plugin of this.#plugins) {\n if (!(await this.#startHook(() => this.#callPlugin(plugin, 'onReady')))) return false\n }\n return true\n }\n\n /**\n * Runs one start hook in an async context carrying a fresh marker, so that a `stop()` called from\n * it (or from work it awaits) is recognised. Returns `false` when the hook stopped the application.\n */\n async #startHook(hook: () => Promise<void>): Promise<boolean> {\n const marker = {}\n this.#startHookMarker = marker\n try {\n await startHookContext.run(marker, hook)\n } finally {\n this.#startHookMarker = undefined\n }\n return !this.#startAborted\n }\n\n /** Whether the caller runs in the async context of the start hook in progress. */\n #calledFromStartHook(): boolean {\n const marker = this.#startHookMarker\n return this.#state === 'starting' && marker !== undefined && startHookContext.getStore() === marker\n }\n\n /** Waits for the stop requested by a start hook; its errors belong to the caller of `stop()`. */\n async #settledStop(): Promise<void> {\n try {\n await this.#stopPromise\n } catch {\n // reported by the stop() promise\n }\n }\n\n /**\n * Stops the application (idempotent; waits for an in-progress `start()`):\n * plugins' `onStop` (reverse) → providers' `onStop` + disposal (reverse resolution order) →\n * plugins' `onDispose` (reverse). Every step is attempted, each within `hookTimeoutMs` and all\n * within `timeoutMs`; failures are collected into a ZnightAggregateError (ZNIGHT021). Signal\n * handlers are removed.\n *\n * Called from a start hook (`onStart`/`onReady` of a provider or plugin, or work it awaits), it\n * does not wait for the start, which waits for that hook: the shutdown runs right away, stopping\n * what completed its `onStart`, and the remaining start hooks are skipped.\n */\n stop(): Promise<void> {\n if (this.#calledFromStartHook()) {\n this.#startAborted = true\n this.#releaseStopWait?.() // a stop() already waiting for the start must not wait for this hook\n }\n this.#stopPromise ??= this.#runStop()\n return this.#stopPromise\n }\n\n async #runStop(): Promise<void> {\n if (this.#state === 'starting' && !this.#startAborted) await this.#waitForStart()\n if (this.#state === 'failed' || this.#state === 'stopped') {\n this.#removeSignals()\n return\n }\n this.#state = 'stopping'\n const errors = await this.#shutdown()\n this.#removeSignals()\n this.#state = 'stopped'\n if (errors.length > 0) {\n throw new ZnightAggregateError(\n ErrorCode.LifecycleFailed,\n `The application stopped with ${errors.length} error(s)`,\n errors,\n )\n }\n // after a signal, the end of the shutdown is reported at the level of \"Received SIGTERM\"\n if (this.#signalReceived) this.#logger.info('Application stopped')\n else this.#logger.debug('Application stopped')\n }\n\n /**\n * Resolves when the start in progress settles (a failed start already stopped and disposed\n * everything), or earlier when a start hook asks to stop (see `stop()`).\n */\n async #waitForStart(): Promise<void> {\n await new Promise<void>(resolve => {\n this.#releaseStopWait = resolve\n const done = (): void => resolve()\n this.#startPromise?.then(done, done)\n })\n this.#releaseStopWait = undefined\n }\n\n /**\n * The three shutdown phases (also used to roll back a failed create/start: only what was started\n * is stopped). Never throws: returns the errors of the failed steps.\n */\n async #shutdown(): Promise<unknown[]> {\n const errors: unknown[] = []\n const step = this.#stepRunner(errors)\n for (const plugin of [...this.#startedPlugins].reverse()) {\n if (typeof plugin.onStop === 'function') {\n await step(`Plugin \"${plugin.name}\" onStop()`, () => plugin.onStop?.(this.#context))\n }\n }\n for (const provider of this.container.instances().reverse()) {\n if (this.#startedProviders.has(provider.token) && hasLifecycleHook(provider.instance, 'onStop')) {\n await step(`${provider.displayName}.onStop()`, () => callLifecycleHook(provider.instance, 'onStop'))\n }\n if (isDisposable(provider.instance, provider.definition.dispose)) {\n await step(`Disposing ${provider.displayName}`, () => provider.dispose())\n } else {\n await provider.dispose()\n }\n }\n try {\n await this.container.dispose()\n } catch (error) {\n errors.push(...flatten(error))\n }\n for (const plugin of [...this.#registered].reverse()) {\n if (typeof plugin.onDispose === 'function') {\n await step(`Plugin \"${plugin.name}\" onDispose()`, () => plugin.onDispose?.(this.#context))\n }\n }\n this.#startedPlugins.length = 0\n this.#startedProviders.clear()\n return errors\n }\n\n /** Runs labelled steps with a per-step timeout inside a global deadline, collecting failures. */\n #stepRunner(errors: unknown[]): (label: string, fn: () => unknown) => Promise<void> {\n const deadline = now() + this.#timeoutMs\n return async (label, fn) => {\n const budget = Math.max(0, Math.min(this.#hookTimeoutMs, deadline - now()))\n try {\n await runWithTimeout(label, fn, budget)\n } catch (error) {\n const failure = error instanceof StepTimeoutError ? error : shutdownError(label, error)\n errors.push(failure)\n this.#logger.debug(`${label} failed`, { err: error })\n }\n }\n }\n\n async #callPlugin(plugin: Plugin, hook: PluginHook): Promise<void> {\n const fn = plugin[hook]\n if (typeof fn !== 'function') return\n try {\n await fn.call(plugin, this.#context)\n } catch (error) {\n throw lifecycleError(`Plugin \"${plugin.name}\" ${hook}()`, error)\n }\n }\n\n async #callProvider(provider: ManagedInstance, hook: LifecycleHook): Promise<void> {\n if (!hasLifecycleHook(provider.instance, hook)) return\n try {\n await callLifecycleHook(provider.instance, hook)\n } catch (error) {\n throw lifecycleError(`${provider.displayName}.${hook}()`, error)\n }\n }\n\n // ---------------------------------------------------------------------------------------------\n // Signals\n // ---------------------------------------------------------------------------------------------\n\n #installSignals(): void {\n const proc = this.#process\n if (proc === undefined || this.#signals.length === 0 || this.#listening.length > 0) return\n for (const signal of this.#signals) proc.on(signal, this.#onSignal)\n this.#listening = this.#signals\n }\n\n #removeSignals(): void {\n const proc = this.#process\n if (proc === undefined) return\n for (const signal of this.#listening) proc.off(signal, this.#onSignal)\n this.#listening = []\n }\n\n readonly #onSignal = (signal: string): void => {\n const proc = this.#process\n if (proc === undefined) return\n if (this.#signalReceived) {\n this.#logger.warn(`Received ${signal} again: forcing exit`)\n proc.exit(FORCED_EXIT_CODE)\n return\n }\n this.#signalReceived = true\n this.#logger.info(`Received ${signal}: shutting down gracefully`)\n // success is logged by the stop itself (\"Application stopped\")\n this.stop().catch((error: unknown) => {\n this.#logger.error('The application stopped with errors', { err: error })\n proc.exitCode = 1\n })\n }\n}\n\nfunction entriesOf(values: ProviderValues): Iterable<readonly [ProviderKey, unknown]> {\n if (typeof (values as Partial<Iterable<unknown>>)[Symbol.iterator] === 'function') {\n return values as Iterable<readonly [ProviderKey, unknown]>\n }\n return Object.entries(values)\n}\n\nfunction flatten(error: unknown): unknown[] {\n return error instanceof ZnightAggregateError ? [...error.errors] : [error]\n}\n\nfunction shutdownError(step: string, error: unknown): ZnightError {\n return new ZnightError(ErrorCode.LifecycleFailed, `${step} failed: ${errorMessage(error)}`, { cause: error })\n}\n\n/** A duration in milliseconds: a non-negative number, `Infinity` meaning no limit. */\nfunction positive(value: number | undefined, fallback: number, name: string): number {\n if (value === undefined) return fallback\n if (typeof value !== 'number' || Number.isNaN(value) || value < 0) {\n throw new ZnightError(\n ErrorCode.InvalidDecorator,\n `Invalid ${name}: expected a positive number of milliseconds (or Infinity), got ${value}`,\n )\n }\n return value\n}\n","/**\n * Marker decorators. They are read from the source code by `@znight/compiler` and do nothing at\n * runtime: every factory returns the same shared no-op function (and the Vite plugin strips them\n * from the bundle by default). They support TypeScript `experimentalDecorators` (class, method and\n * parameter positions); class and method markers also type-check as standard decorators.\n *\n * Arguments marked _static_ must be statically evaluable by the compiler (literals, `const`\n * references, simple expressions); see docs/internals/architecture.md §4.6.\n */\nimport type { MethodInterceptor } from './aop.ts'\nimport type { Scope } from './metadata.ts'\n\n/** A class constructor, as received by a class decorator. */\ntype AnyClass = abstract new (...args: never[]) => unknown\n\n/** Marker usable on a class. */\nexport type ClassMarker = (target: AnyClass, context?: ClassDecoratorContext) => void\n\n/** Marker usable on a method (instance or static). */\nexport type MethodMarker = (\n target: object,\n propertyKeyOrContext: string | symbol | ClassMethodDecoratorContext,\n descriptor?: PropertyDescriptor,\n) => void\n\n/** Marker usable on a constructor or method parameter (`experimentalDecorators` only). */\nexport type ParameterMarker = (target: object, propertyKey: string | symbol | undefined, parameterIndex: number) => void\n\n/** Options of {@link Injectable} (static). */\nexport interface InjectableOptions {\n /** Lifetime of the instances. Default: `singleton`. */\n readonly scope?: Scope\n /** Qualifier, as with {@link Named}. */\n readonly name?: string\n /** Preferred candidate when several providers match an injection point, as with {@link Primary}. */\n readonly primary?: boolean\n}\n\n/** Options of {@link Provides} (static). */\nexport interface ProvidesOptions extends InjectableOptions {\n /** Name of a method of the provided value called on shutdown (`'end'`, `'close'`...). */\n readonly dispose?: string\n}\n\n/** Class implementing {@link MethodInterceptor} with options `O`. */\nexport type InterceptorClass<O> = abstract new (...args: never[]) => MethodInterceptor<O>\n\n/** Options argument of {@link Intercept}: required when the interceptor options do not accept `undefined`. */\nexport type InterceptOptionsArgs<O> = undefined extends O ? [options?: NoInfer<O>] : [options: NoInfer<O>]\n\nfunction marker(): void {\n // intentionally empty: decorators are compile-time markers\n}\n\nconst classMarker: ClassMarker = marker\nconst methodMarker: MethodMarker = marker\nconst parameterMarker: ParameterMarker = marker\nconst classOrMethodMarker: ClassMarker & MethodMarker = marker\n\n/**\n * Declares a provider class. Its constructor parameters are injected.\n *\n * ```ts\n * @Injectable()\n * export class UserService {\n * constructor(private readonly repository: UserRepository) {}\n * }\n * ```\n */\nexport function Injectable(_options?: InjectableOptions): ClassMarker {\n return classMarker\n}\n\n/** Declares a singleton whose {@link Provides} methods produce providers. */\nexport function Factory(): ClassMarker {\n return classMarker\n}\n\n/**\n * Declares a provider produced by a method of a {@link Factory} class. The explicit return type is\n * the provided type (`Promise<T>` makes it async, singletons only); parameters are injected.\n *\n * ```ts\n * @Factory()\n * export class DbFactory {\n * @Provides({ dispose: 'end' })\n * async createPool(config: DbConfig): Promise<Pool> { ... }\n * }\n * ```\n */\nexport function Provides(_options?: ProvidesOptions): MethodMarker {\n return methodMarker\n}\n\n/** Injects the provider qualified with `name` (see {@link Named}). `name` is static. */\nexport function Inject(_name: string): ParameterMarker {\n return parameterMarker\n}\n\n/** Marks a dependency as optional: `undefined` is injected when no provider exists. */\nexport function Optional(): ParameterMarker {\n return parameterMarker\n}\n\n/** Sets the qualifier of a provider class or `@Provides` method. `name` is static. */\nexport function Named(_name: string): ClassMarker & MethodMarker {\n return classOrMethodMarker\n}\n\n/** Makes a provider the preferred candidate when several providers match an injection point. */\nexport function Primary(): ClassMarker & MethodMarker {\n return classOrMethodMarker\n}\n\n/**\n * Intercepts calls to a method with an interceptor provider (AOP). The top-most `@Intercept` is the\n * outermost interceptor.\n *\n * ```ts\n * @Intercept(TimingInterceptor, { label: 'users.find' })\n * async find(id: string): Promise<User> { ... }\n * ```\n */\nexport function Intercept<O>(_interceptor: InterceptorClass<O>, ..._options: InterceptOptionsArgs<O>): MethodMarker {\n return methodMarker\n}\n","/**\n * Custom parameter decorators (RFC 0010). `createParamDecorator` returns a marker decorator, read\n * by `@znight/compiler`, and keeps the resolvers that the generated `invoke` of each transport calls.\n */\nimport type { ParameterMarker } from './decorators.ts'\n\n/**\n * Resolver contexts by transport. Each transport package adds its own entry through declaration\n * merging (`http: HttpContext` in `@znight/http`, `graphql: ResolverContext`, `messaging:\n * InboundMessage`); a transport that is not installed has no entry.\n *\n * ```ts\n * declare module '@znight/core' {\n * interface ParamContexts {\n * http: HttpContext\n * }\n * }\n * ```\n */\n// biome-ignore lint/suspicious/noEmptyInterface: augmented by the transport packages (declaration merging)\nexport interface ParamContexts {}\n\n/** A provider computing the value of a parameter, in the scope of the call (RFC 0010 §4.6). */\nexport interface ParamResolver<C, T, D = undefined> {\n resolve(ctx: C, data: D): T | PromiseLike<T>\n}\n\n/** A resolver function: receives the context of its transport and the data argument of the use. */\nexport type ParamResolverFunction<C, T, D> = (ctx: C, data: D) => T | PromiseLike<T>\n\n/** The class of a provider implementing {@link ParamResolver} (bound at build time, resolved in the scope of the call). */\nexport type ParamResolverClass<C, T, D> = abstract new (...args: never[]) => ParamResolver<C, T, D>\n\n/** Computes the value of a parameter: a function, or the class of a provider implementing {@link ParamResolver}. */\nexport type ParamResolverOf<C, T, D> = ParamResolverFunction<C, T, D> | ParamResolverClass<C, T, D>\n\n/** The resolvers of a definition, by transport (keys of {@link ParamContexts}). */\nexport type ParamResolvers<T, D> = {\n readonly [K in keyof ParamContexts]?: ParamResolverOf<ParamContexts[K], T, D>\n}\n\n/** Arguments of a use: none when `D` is `undefined`, optional when `D` includes `undefined`, required otherwise. */\nexport type ParamDataArgs<D> = undefined extends D ? [data?: D] : [data: D]\n\n/** What {@link createParamDecorator} returns: the decorator (a no-op marker) and its resolvers, for generated code. */\nexport interface ParamDecorator<T, D = undefined> {\n (...data: ParamDataArgs<D>): ParameterMarker\n /** The resolvers of the definition, frozen. */\n readonly resolvers: ParamResolvers<T, D>\n}\n\n/**\n * The resolver function of a definition for a transport, as generated code calls it:\n * `(CurrentUser.resolvers.http as ParamFunctionOf<typeof CurrentUser, 'http'>)(ctx, undefined)`.\n * The compiler emits it only for function resolvers.\n */\nexport type ParamFunctionOf<P extends { readonly resolvers: object }, K extends keyof P['resolvers']> = Extract<\n NonNullable<P['resolvers'][K]>,\n // biome-ignore lint/suspicious/noExplicitAny: matches every function type, whatever its parameters\n (...args: any[]) => unknown\n>\n\nfunction marker(): void {\n // intentionally empty: decorators are compile-time markers\n}\n\nconst parameterMarker: ParameterMarker = marker\n\n/**\n * Defines a parameter decorator whose value is computed per call by a resolver of the handler's\n * transport (RFC 0010). `T` (required) is the injected type, checked at build time against every\n * decorated parameter; `D` is the type of the data argument (none by default). The definition must\n * be an exported top-level `const`: the generated module imports it.\n *\n * ```ts\n * export const CurrentUser = createParamDecorator<User>({\n * http: ctx => userOf(ctx.state),\n * graphql: ctx => userOf(ctx.operation.state),\n * })\n *\n * @Get('/me')\n * me(@CurrentUser() user: User) { ... }\n * ```\n */\nexport function createParamDecorator<T, D = undefined>(resolvers: ParamResolvers<T, D>): ParamDecorator<T, D> {\n const decorator = ((..._data: ParamDataArgs<D>): ParameterMarker => parameterMarker) as ParamDecorator<T, D>\n Object.defineProperty(decorator, 'resolvers', { value: Object.freeze({ ...resolvers }), enumerable: true })\n return decorator\n}\n","import type { Application } from './application.ts'\nimport type { Container } from './container.ts'\nimport type { Hooks } from './hooks.ts'\nimport type { CoreLogger } from './logger.ts'\nimport type { ZnightMetadata } from './metadata.ts'\nimport type { ProviderKey } from './tokens.ts'\n\n/**\n * A runtime feature (HTTP server, message consumers, configuration, observability...). Every hook\n * is optional and may be async. Hooks run in plugin order, stop hooks in reverse order.\n *\n * 1. `register`: provide externals (`ctx.container.registerValue()` / `register()`), before\n * `container.init()`.\n * 2. `onBootstrap`: after `container.init()`: register routes, consumers... (no traffic yet).\n * 3. `onStart`: start accepting traffic (listen, subscribe), after providers' `onStart`.\n * 4. `onReady`: everything started.\n * 5. `onStop`: stop accepting traffic and drain in-flight work, before providers stop.\n * 6. `onDispose`: release infrastructure (connections, flush buffers), after providers are disposed.\n */\nexport interface Plugin {\n /** Unique name (used by `getPlugin()` and in messages). */\n readonly name: string\n register?(ctx: PluginContext): void | Promise<void>\n onBootstrap?(ctx: PluginContext): void | Promise<void>\n onStart?(ctx: PluginContext): void | Promise<void>\n onReady?(ctx: PluginContext): void | Promise<void>\n onStop?(ctx: PluginContext): void | Promise<void>\n onDispose?(ctx: PluginContext): void | Promise<void>\n /**\n * The providers (classes or tokens) the plugin needs at boot although the metadata does not make\n * them entry points: classes given in its options (`HttpPlugin`'s global `guards`,\n * `interceptors`, `exceptionMappers`), or providers it derives from its own metadata section.\n *\n * Read by tools that restrict the boot to a few providers (`init: { only }`), such as `TestApp`\n * of `@znight/testing`: they create these providers at boot with their dependencies, because an\n * async factory cannot run on demand. The application itself never calls it.\n *\n * Called before the application is created (before `register`), possibly several times: it must\n * be cheap and side-effect free, and SHOULD NOT throw (report invalid options in `onBootstrap`).\n * Options given as a function of the container cannot be read yet: return what is known (`[]`).\n */\n initRoots?(context: PluginRootsContext): readonly ProviderKey[]\n}\n\n/** What {@link Plugin.initRoots} receives. */\nexport interface PluginRootsContext {\n /** The metadata the application will be created with. */\n readonly metadata: ZnightMetadata\n}\n\n/** Name of a {@link Plugin} hook. */\nexport type PluginHook = 'register' | 'onBootstrap' | 'onStart' | 'onReady' | 'onStop' | 'onDispose'\n\n/** What a plugin hook receives. */\nexport interface PluginContext {\n readonly app: Application\n readonly container: Container\n readonly metadata: ZnightMetadata\n readonly hooks: Hooks\n /** Live, delegating logger: always forwards to the logger currently installed on the application. */\n readonly logger: CoreLogger\n /** Another plugin of the application, by name. */\n getPlugin<P extends Plugin = Plugin>(name: string): P | undefined\n}\n\n/**\n * Plugin options given directly or computed from the container (evaluated in `onBootstrap`, once\n * every provider exists):\n *\n * ```ts\n * HttpPlugin.configure(c => ({ port: c.get(AppConfig).port }))\n * ```\n *\n * Options that are themselves a function cannot use this form.\n */\nexport type PluginOptions<O> = O | ((container: Container) => O)\n\n/** Resolves {@link PluginOptions}: calls the function form with the container, returns the others as is. */\nexport function resolveOptions<O>(options: PluginOptions<O>, container: Container): O {\n return typeof options === 'function' ? (options as (container: Container) => O)(container) : options\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAgBA,MAAa,YAAY;;CAEvB,iBAAiB;;CAEjB,oBAAoB;;CAEpB,eAAe;;CAEf,mBAAmB;;CAEnB,kBAAkB;;CAElB,eAAe;;CAEf,cAAc;;CAEd,oBAAoB;;CAEpB,sBAAsB;;CAEtB,kBAAkB;;CAElB,iBAAiB;;CAEjB,eAAe;;CAEf,eAAe;;CAEf,mBAAmB;;CAEnB,qBAAqB;;CAErB,iBAAiB;;CAEjB,kBAAkB;;CAElB,iBAAiB;;CAEjB,gBAAgB;;CAEhB,sBAAsB;;CAEtB,iBAAiB;;CAEjB,aAAa;;;;;CAKb,sBAAsB;;;;;CAOtB,0BAA0B;;CAE1B,sBAAsB;;CAEtB,qBAAqB;;CAErB,sBAAsB;;CAEtB,oBAAoB;;CAEpB,uBAAuB;;CAEvB,4BAA4B;;CAE5B,wBAAwB;;;;;CAOxB,iBAAiB;;CAEjB,cAAc;;CAEd,YAAY;;CAEZ,kBAAkB;;CAElB,YAAY;;CAIZ,oBAAoB;;CAEpB,qBAAqB;;;;;CAKrB,iBAAiB;;;;;CAKjB,qBAAqB;;CAErB,0BAA0B;;;;;CAK1B,eAAe;;;;;CAKf,qBAAqB;;;;;CAKrB,mBAAmB;;;;;CAKnB,uBAAuB;;;;;;CAQvB,sBAAsB;AACxB;;AAKA,MAAa,qBAA0D;CACrE,WAAW;CACX,WAAW;CACX,WAAW;CACX,WAAW;CACX,WAAW;CACX,WAAW;CACX,WAAW;CACX,WAAW;CACX,WAAW;CACX,WAAW;CACX,WAAW;CACX,WAAW;CACX,WAAW;CACX,WAAW;CACX,WAAW;CACX,WAAW;CACX,WAAW;CACX,WA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