injeca 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +251 -14
- package/dist/decision-BXZu3N1O.mjs +1356 -0
- package/dist/decision-BXZu3N1O.mjs.map +1 -0
- package/dist/{global-C0Nk0pU8.mjs → global-B5N-d-TO.mjs} +1024 -1214
- package/dist/global-B5N-d-TO.mjs.map +1 -0
- package/dist/{global-B9Bk2EG2.d.mts → global-DPfe26g5.d.mts} +81 -17
- package/dist/global.d.mts +1 -1
- package/dist/global.mjs +1 -1
- package/dist/{index-DXguNx2M.d.mts → index-DTYp044J.d.mts} +139 -19
- package/dist/index.d.mts +40 -15
- package/dist/index.mjs +55 -23
- package/dist/index.mjs.map +1 -1
- package/dist/testing.d.mts +31 -1
- package/dist/testing.mjs +60 -2
- package/dist/testing.mjs.map +1 -1
- package/package.json +5 -5
- package/dist/decision-odiPb2Au.mjs +0 -194
- package/dist/decision-odiPb2Au.mjs.map +0 -1
- package/dist/global-C0Nk0pU8.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"decision-BXZu3N1O.mjs","names":["emptyMetadata","emptyPolicy"],"sources":["../src/diagnostics/errors.ts","../src/helpers/signals.ts","../src/helpers/error-from.ts","../src/graph/resolvers/exports.ts","../src/graph/resolvers/exclusive.ts","../src/graph/resolvers/resolvers.ts","../src/graph/nodes/container.ts","../src/helpers/deferred.ts","../src/helpers/without-undefined.ts","../src/graph/observers.ts","../src/graph/resolvers/condition.ts","../src/graph/resolvers/plain.ts","../src/graph/resolvers/fallback.ts","../src/graph/status.ts","../src/graph/nodes/service.ts","../src/graph/nodes/consumer.ts","../src/types/keys.ts","../src/primitives/keys.ts","../src/graph/nodes/edge.ts","../src/graph/nodes/policy.ts","../src/graph/nodes/definition.ts","../src/graph/nodes/registration.ts","../src/graph/nodes/reservation.ts","../src/primitives/decision.ts"],"sourcesContent":["import type { ServiceExplanation } from '../types/service'\n\nexport type InjecaErrorCode\n = | 'build-after-dispose'\n | 'duplicate-service'\n | 'hook-outside-build'\n | 'hook-timeout'\n | 'invalid-argument'\n | 'invalid-decision'\n | 'service-failed'\n | 'replace-while-stopping'\n | 'stale-registration'\n | 'start-timeout'\n | 'transaction-incomplete'\n | 'wait-timeout'\n\nexport interface InjecaErrorOptions {\n cause?: unknown\n}\n\n/**\n * The base class of all injeca errors. Use `code` to identify an error. The message text is not stable.\n */\nexport class InjecaError extends Error {\n readonly code: InjecaErrorCode\n\n constructor(code: InjecaErrorCode, message: string, options?: InjecaErrorOptions) {\n super(message, options)\n this.name = 'InjecaError'\n this.code = code\n }\n}\n\n/** A started container already has a current registration for the key. */\nexport class DuplicateServiceError extends InjecaError {\n declare readonly code: 'duplicate-service'\n\n constructor(message: string, options?: InjecaErrorOptions) {\n super('duplicate-service', message, options)\n this.name = 'DuplicateServiceError'\n }\n}\n\n/** A registration is no longer the current registration of its service. */\nexport class StaleRegistrationError extends InjecaError {\n declare readonly code: 'stale-registration'\n\n constructor(message: string, options?: InjecaErrorOptions) {\n super('stale-registration', message, options)\n this.name = 'StaleRegistrationError'\n }\n}\n\n/** A hook returned a decision from another run, or a kind that the hook does not accept. */\nexport class InvalidDecisionError extends InjecaError {\n declare readonly code: 'invalid-decision'\n\n constructor(message: string, options?: InjecaErrorOptions) {\n super('invalid-decision', message, options)\n this.name = 'InvalidDecisionError'\n }\n}\n\n/** A caller used a container or an instance after its disposal started. */\nexport class BuildAfterDisposeError extends InjecaError {\n declare readonly code: 'build-after-dispose'\n\n constructor(message: string, options?: InjecaErrorOptions) {\n super('build-after-dispose', message, options)\n this.name = 'BuildAfterDisposeError'\n }\n}\n\n/** `on` was called after `build` settled. */\nexport class HookOutsideBuildError extends InjecaError {\n declare readonly code: 'hook-outside-build'\n\n constructor(message: string, options?: InjecaErrorOptions) {\n super('hook-outside-build', message, options)\n this.name = 'HookOutsideBuildError'\n }\n}\n\n/** A transaction commit found a declared service without `provide`. */\nexport class TransactionIncompleteError extends InjecaError {\n declare readonly code: 'transaction-incomplete'\n\n constructor(message: string, options?: InjecaErrorOptions) {\n super('transaction-incomplete', message, options)\n this.name = 'TransactionIncompleteError'\n }\n}\n\n/** A `start` or `stop` hook did not settle before its configured timeout. */\nexport class HookTimeoutError extends InjecaError {\n declare readonly code: 'hook-timeout'\n readonly hook: 'start' | 'stop'\n readonly timeoutMs: number\n\n constructor(message: string, hook: 'start' | 'stop', timeoutMs: number, options?: InjecaErrorOptions) {\n super('hook-timeout', message, options)\n this.name = 'HookTimeoutError'\n this.hook = hook\n this.timeoutMs = timeoutMs\n }\n}\n\n/** `replace` was called on a service in `stopping`. */\nexport class ReplaceWhileStoppingError extends InjecaError {\n declare readonly code: 'replace-while-stopping'\n\n constructor(message: string, options?: InjecaErrorOptions) {\n super('replace-while-stopping', message, options)\n this.name = 'ReplaceWhileStoppingError'\n }\n}\n\n/** `start()` did not reach `running` for every service before its configured timeout. */\nexport class StartTimeoutError extends InjecaError {\n declare readonly code: 'start-timeout'\n /** One entry for each service or invocation that is not `running`. */\n readonly explanations: readonly ServiceExplanation[]\n\n constructor(message: string, explanations: readonly ServiceExplanation[], options?: InjecaErrorOptions) {\n super('start-timeout', message, options)\n this.name = 'StartTimeoutError'\n this.explanations = explanations\n }\n}\n\n/** `waitFor()` found the service in `failed`, or waiting for a required provider in `failed`. `cause` is the failure. */\nexport class ServiceFailedError extends InjecaError {\n declare readonly code: 'service-failed'\n /** The key name that the caller waited for. */\n readonly key: string\n\n constructor(message: string, key: string, options?: InjecaErrorOptions) {\n super('service-failed', message, options)\n this.name = 'ServiceFailedError'\n this.key = key\n }\n}\n\n/** `waitFor()` or `resolve()` did not match before its configured timeout. */\nexport class WaitTimeoutError extends InjecaError {\n declare readonly code: 'wait-timeout'\n\n constructor(message: string, options?: InjecaErrorOptions) {\n super('wait-timeout', message, options)\n this.name = 'WaitTimeoutError'\n }\n}\n\n/** A caller passed a value with the wrong shape, or reading a caller-owned property failed. */\nexport class InvalidArgumentError extends InjecaError {\n declare readonly code: 'invalid-argument'\n\n constructor(message: string, options?: InjecaErrorOptions) {\n super('invalid-argument', message, options)\n this.name = 'InvalidArgumentError'\n }\n}\n","import { endBatch, setActiveSub, startBatch } from 'alien-signals'\n\nexport type ReactiveOwner = ReturnType<typeof setActiveSub>\n\nexport interface WritableSignal<T> {\n (): T\n (value: T): void\n}\n\n/**\n * Runs `fn` with tracking paused.\n *\n * The tracking rule: each entry point pauses tracking once. The entry points are the public API calls, the reconciler drain, timer callbacks, and the calls of user callbacks.\n * Code inside an entry point reads signals directly. Only the bodies of `computed` and `effect` track.\n * A promise continuation starts with no active subscriber, so it needs no extra pause.\n */\nexport function untracked<T>(fn: () => T): T {\n const previous = setActiveSub(undefined)\n try {\n return fn()\n }\n finally {\n setActiveSub(previous)\n }\n}\n\n/** Writes signals in one batch. Effects see one consistent change. */\nexport function batch(fn: () => void): void {\n startBatch()\n try {\n fn()\n }\n finally {\n endBatch()\n }\n}\n\n/** Runs `fn` with `owner` as the active subscriber, so effects that `fn` creates belong to `owner`. */\nexport function withOwner<T>(owner: ReactiveOwner, fn: () => T): T {\n const previous = setActiveSub(owner)\n try {\n return fn()\n }\n finally {\n setActiveSub(previous)\n }\n}\n","/**\n * Makes one error from collected errors. One error keeps its identity. More than one error becomes an `AggregateError`.\n *\n * The result is `unknown`, because a thrown value is not always an `Error`.\n */\nexport function errorFrom(errors: readonly unknown[], message: string): unknown {\n return errors.length === 1 ? errors[0] : new AggregateError(errors, message)\n}\n\n/** The message of a thrown value: `message` of an `Error` or a `DOMException`, else `String(value)`. */\nexport function messageOf(value: unknown): string {\n if (typeof value === 'object' && value !== null && typeof (value as { readonly message?: unknown }).message === 'string')\n return (value as { readonly message: string }).message\n\n return String(value)\n}\n","import type { WritableSignal } from '../../helpers/signals'\nimport type { ContainerNode, ServiceNode } from '../graph'\n\nimport { signal } from 'alien-signals'\n\n// Exported registrations. A registration with `export` lives in its container. It is also a candidate in the resolution area of the parent container.\n// `nodes/container.ts` writes the exports at publish and release. `resolvers.ts` reads them in the candidate walk. `exclusive.ts` reads the area.\n\n/** Returns the signal of the exported services of `keyName` that the child containers of `container` publish. It creates the signal on first read, so that resolution can track it. */\nexport function exportsOf(container: ContainerNode, keyName: string): WritableSignal<readonly ServiceNode[]> {\n let exports = container.signals.exports.get(keyName)\n if (!exports) {\n exports = signal<readonly ServiceNode[]>(Object.freeze([]))\n container.signals.exports.set(keyName, exports)\n }\n\n return exports\n}\n\n/**\n * The container whose resolution area a registration belongs to.\n * An exported registration belongs to the area of its parent container. A registration of a root container has no parent, so `export` has no effect there.\n */\nexport function areaOf(service: ServiceNode): ContainerNode {\n return (service.exported && service.container.parent) || service.container\n}\n","import type { WritableSignal } from '../../helpers/signals'\nimport type { ContainerNode, Runtime, ServiceNode } from '../graph'\n\nimport { computed, signal } from 'alien-signals'\n\nimport { areaOf } from './exports'\n\n/** Tells whether `ancestor` is `container` or an ancestor of it, with no container in between that isolates `keyName`. */\nfunction reaches(container: ContainerNode, ancestor: ContainerNode, keyName: string): boolean {\n for (let current: ContainerNode | undefined = container; current; current = current.parent) {\n if (current === ancestor)\n return true\n if (current.isolated.has(keyName))\n return false\n }\n\n return false\n}\n\n/**\n * Tells whether two containers share a resolution area of `keyName`.\n * A resolution area is the container that has the key, with its descendants that do not isolate the key.\n * For an exported registration, the caller passes the parent container. See `areaOf`.\n */\nexport function sameArea(a: ContainerNode, b: ContainerNode, keyName: string): boolean {\n return reaches(a, b, keyName) || reaches(b, a, keyName)\n}\n\n/** The published services of `keyName` in all containers of the runtime. */\nexport function declarationsOf(runtime: Runtime, keyName: string): WritableSignal<ReadonlySet<ServiceNode>> {\n let declarations = runtime.declarations.get(keyName)\n if (!declarations) {\n declarations = signal<ReadonlySet<ServiceNode>>(new Set())\n runtime.declarations.set(keyName, declarations)\n }\n\n return declarations\n}\n\nexport function addDeclaration(service: ServiceNode): void {\n const declarations = declarationsOf(service.container.runtime, service.name)\n if (!declarations().has(service))\n declarations(new Set([...declarations(), service]))\n}\n\nexport function removeDeclaration(service: ServiceNode): void {\n const declarations = declarationsOf(service.container.runtime, service.name)\n if (declarations().has(service))\n declarations(new Set([...declarations()].filter(other => other !== service)))\n}\n\nfunction sameList(a: readonly ServiceNode[], b: readonly ServiceNode[]): boolean {\n return a.length === b.length && a.every((service, index) => service === b[index])\n}\n\nconst none: readonly ServiceNode[] = Object.freeze([])\n\n/**\n * Creates the conflict of a service: the other present declarations of its key in the same resolution area, when the key is exclusive.\n *\n * The result depends only on the set of declarations. The order of the registrations has no effect.\n * Only one registration of a key exists in one container, so a rival is always in another container.\n * An exported registration counts in the resolution area of its parent container. So two sibling exports of one exclusive key conflict, and an export conflicts with a registration of the parent.\n * A service of a `perConsumer` registration has no conflict of its own. It follows the conflict of its registration.\n */\nexport function createRivals(service: ServiceNode): () => readonly ServiceNode[] {\n if (service.template)\n return () => service.template?.signals.rivals() ?? none\n if (service.kind !== 'service')\n return () => none\n\n return computed<readonly ServiceNode[]>((previous) => {\n const rivals = [...declarationsOf(service.container.runtime, service.name)()]\n .filter(other => other.container !== service.container\n && other.signals.present()\n && (service.exclusive || other.exclusive)\n && sameArea(areaOf(service), areaOf(other), service.name))\n .sort((a, b) => a.seq - b.seq)\n\n return previous && sameList(previous, rivals) ? previous : rivals\n })\n}\n\n/** Tells whether the key of the service has more than one declaration in its resolution area. */\nexport function inConflict(service: ServiceNode): boolean {\n return service.signals.rivals().length > 0\n}\n","import type { WritableSignal } from '../../helpers/signals'\nimport type { ContainerNode, DependencyEdge, InstanceNode, Resolution, ResolutionConsumer, ServiceNode } from '../graph'\n\nimport { signal } from 'alien-signals'\n\nimport { exportsOf } from './exports'\n\n/** Returns the slot signal of `keyName` in `container`. It creates the slot on first read, so that resolution can track it. */\nexport function slotOf(container: ContainerNode, keyName: string): WritableSignal<ServiceNode | undefined> {\n let slot = container.signals.slots.get(keyName)\n if (!slot) {\n slot = signal<ServiceNode | undefined>(undefined)\n container.signals.slots.set(keyName, slot)\n }\n\n return slot\n}\n\n/**\n * Lists the registrations of `keyName` that a consumer in `container` can see, nearest first.\n *\n * At each level, from `container` up through its ancestors, the candidates are the registration of that container, then the exports of its child containers in creation order.\n * The walk ends at a container that isolates the key. So an isolated key also hides the exports of the siblings.\n * A service does not resolve itself. A consumer service of a `perConsumer` registration does not resolve its registration.\n */\nexport function candidatesOf(container: ContainerNode, keyName: string, consumer?: ResolutionConsumer): ServiceNode[] {\n const candidates: ServiceNode[] = []\n const add = (candidate: ServiceNode | undefined): void => {\n if (candidate && candidate !== consumer && candidate !== consumer?.template && !candidates.includes(candidate))\n candidates.push(candidate)\n }\n for (let current: ContainerNode | undefined = container; current; current = current.parent) {\n add(slotOf(current, keyName)())\n for (const exported of exportsOf(current, keyName)())\n add(exported)\n if (current.isolated.has(keyName))\n break\n }\n\n return candidates\n}\n\n/** The service that serves `registration` for a consumer in `container`. A `perConsumer` registration has one for each consumer container, or none yet. */\nexport function serviceFor(registration: ServiceNode, container: ContainerNode): ServiceNode | undefined {\n return registration.perConsumer ? registration.signals.consumers().get(container) : registration\n}\n\n/** A selected provider: the registration that a consumer sees, and the service that serves it. */\nexport interface Selection {\n readonly registration: ServiceNode\n /** The service of a `perConsumer` registration for the consumer container. It is `undefined` until the reconciler creates it. */\n readonly provider: ServiceNode | undefined\n}\n\n/**\n * Selects the provider of `keyName` for a consumer in `container`.\n *\n * A nearer registration shadows an ancestor only while it is `running`. Until then, the first serving registration wins.\n * If no registration serves, the nearest one is selected. So shadowing never leaves a gap.\n */\nexport function selectProvider(container: ContainerNode, keyName: string, consumer?: ResolutionConsumer): Selection | undefined {\n const candidates = candidatesOf(container, keyName, consumer)\n for (const registration of candidates) {\n const provider = serviceFor(registration, container)\n if (provider?.signals.serving())\n return { registration, provider }\n }\n\n const [nearest] = candidates\n return nearest ? { registration: nearest, provider: serviceFor(nearest, container) } : undefined\n}\n\n/** Finds the service for `keyName` that a consumer in `container` sees. A `perConsumer` registration without a service for the container gives the registration. */\nexport function findProvider(container: ContainerNode, keyName: string, consumer?: ResolutionConsumer): ServiceNode | undefined {\n const selection = selectProvider(container, keyName, consumer)\n return selection && (selection.provider ?? selection.registration)\n}\n\n/** `ready` and `degraded` count as available. A provider outside `running` has no status and is not available. */\nexport function isAvailable(provider: ServiceNode): boolean {\n const status = provider.signals.effective()\n return status !== undefined && status.status !== 'unavailable'\n}\n\n/** The current resolution of the edge. */\nexport function resolutionOf(service: ServiceNode, edge: DependencyEdge): Resolution {\n return service.signals.resolutions.get(edge.name)?.() ?? { kind: 'missing' }\n}\n\n/** The instance of the edge, when it resolves. */\nexport function resolvedInstance(service: ServiceNode, edge: DependencyEdge): InstanceNode | undefined {\n const resolution = resolutionOf(service, edge)\n return resolution.kind === 'resolved' ? resolution.instance : undefined\n}\n\n/** Tells whether each required edge resolves to an available provider. A pending service builds only then. */\nexport function requiredAvailable(service: ServiceNode): boolean {\n return service.edges.every((edge) => {\n if (edge.optional)\n return true\n\n const resolution = resolutionOf(service, edge)\n return resolution.kind === 'resolved' && isAvailable(resolution.provider)\n })\n}\n\n/** Tells whether a required edge no longer resolves: its provider was withdrawn, or it does not run. */\nexport function requiredWithdrawn(service: ServiceNode): boolean {\n return service.edges.some(edge => !edge.optional && resolvedInstance(service, edge) === undefined)\n}\n\n/** Tells whether the current resolution of a required edge differs from the bindings of `instance`. */\nexport function requiredChanged(service: ServiceNode, instance: InstanceNode): boolean {\n return service.edges.some(edge => !edge.optional && resolvedInstance(service, edge) !== instance.bindings.get(edge.name))\n}\n\n/** A build is discarded when its target is lost, a required dependency changed during the build, or the key went into conflict. */\nexport function buildLost(service: ServiceNode, instance: InstanceNode): boolean {\n return !service.signals.present() || !service.signals.active() || service.signals.rivals().length > 0 || requiredChanged(service, instance)\n}\n\n/** The identity of the dependency set: the revision and the instance id of each resolved required dependency. */\nexport function epochOf(service: ServiceNode, pick: (edge: DependencyEdge) => InstanceNode | undefined): string {\n const ids = service.edges\n .filter(edge => !edge.optional)\n .map(edge => `${edge.name}=${pick(edge)?.id ?? ''}`)\n\n return [String(service.revision), ...ids].join('|')\n}\n\n/**\n * Finds the failure that blocks a pending service: a required provider in `failed`, directly or through pending providers.\n */\nexport function blockingFailure(service: ServiceNode, visited = new Set<ServiceNode>()): { readonly error: unknown } | undefined {\n visited.add(service)\n for (const edge of service.edges) {\n if (edge.optional)\n continue\n\n const resolution = resolutionOf(service, edge)\n if (resolution.kind !== 'not-running' || visited.has(resolution.provider))\n continue\n\n const provider = resolution.provider\n const phase = provider.signals.phase()\n if (phase === 'failed')\n return provider.failure\n if (phase === 'pending') {\n const failure = blockingFailure(provider, visited)\n if (failure)\n return failure\n }\n }\n\n return undefined\n}\n","import type { Container } from '../../types'\nimport type { ContainerNode, ServiceNode } from '../graph'\n\nimport { BuildAfterDisposeError, InvalidArgumentError } from '../../diagnostics/errors'\nimport { errorFrom } from '../../helpers/error-from'\nimport { batch, untracked } from '../../helpers/signals'\nimport { addDeclaration } from '../resolvers/exclusive'\nimport { exportsOf } from '../resolvers/exports'\nimport { slotOf } from '../resolvers/resolvers'\n\nconst nodes = new WeakMap<Container, ContainerNode>()\n\n/** Connects the public container object to its node. `createContainer` calls it once. */\nexport function registerNode(container: Container, node: ContainerNode): void {\n nodes.set(container, node)\n}\n\n/** Returns the internal node of a container from `createContainer`. */\nexport function nodeOf(container: Container): ContainerNode {\n const node = typeof container === 'object' && container !== null ? nodes.get(container) : undefined\n if (!node)\n throw new InvalidArgumentError('The value is not a container from createContainer.')\n\n return node\n}\n\nexport function assertActive(container: ContainerNode, action: string): void {\n if (container.state !== 'active')\n throw new BuildAfterDisposeError(`Cannot ${action} after the container disposal started.`)\n}\n\n/** Lists `container` and its descendants that were started, through started containers only. `start()` and `stop()` apply to them. */\nexport function affectedContainers(container: ContainerNode): ContainerNode[] {\n const result = [container]\n for (const child of container.children) {\n if (child.enrolled)\n result.push(...affectedContainers(child))\n }\n\n return result\n}\n\n/** Lists `container` and all its descendants. */\nexport function subtreeOf(container: ContainerNode): ContainerNode[] {\n return [container, ...[...container.children].flatMap(subtreeOf)]\n}\n\n/**\n * Adds an exported service to the exports of its parent container, in container creation order.\n * It takes the place of an earlier service of the same container, for example at the swap of a replacement.\n */\nfunction addExport(service: ServiceNode): void {\n const parent = service.container.parent\n if (!service.exported || !parent)\n return\n\n const exports = exportsOf(parent, service.name)\n const current = exports()\n if (current.includes(service))\n return\n\n exports(Object.freeze([...current.filter(other => other.container !== service.container), service].sort((a, b) => a.container.seq - b.container.seq)))\n}\n\nfunction removeExport(service: ServiceNode): void {\n const parent = service.container.parent\n if (!service.exported || !parent)\n return\n\n const exports = exportsOf(parent, service.name)\n if (exports().includes(service))\n exports(Object.freeze(exports().filter(other => other !== service)))\n}\n\n/**\n * Makes `service` visible to consumers: the slot of its key, or the consumer map of its `perConsumer` registration.\n * An exported service is also visible in the resolution area of the parent container.\n * An exclusive conflict counts each published service with a key.\n */\nexport function publishService(service: ServiceNode): void {\n const { template } = service\n if (template) {\n const consumers = template.signals.consumers()\n if (consumers.get(service.container) !== service)\n template.signals.consumers(new Map([...consumers, [service.container, service]]))\n return\n }\n\n slotOf(service.container, service.name)(service)\n addExport(service)\n addDeclaration(service)\n}\n\n/**\n * Clears the slot and marks the service absent. The reconciler stops it after its holders release it.\n * A `perConsumer` registration also releases the service of each consumer container.\n */\nexport function releaseService(service: ServiceNode): void {\n service.signals.present(false)\n if (service.kind !== 'service' || service.template)\n return\n\n for (const consumer of service.signals.consumers().values())\n consumer.signals.present(false)\n\n const slot = slotOf(service.container, service.name)\n if (slot() === service)\n slot(undefined)\n removeExport(service)\n}\n\n/** Waits until `service` is `withdrawn`. Rejects with its teardown errors. */\nexport async function awaitWithdrawal(service: ServiceNode): Promise<void> {\n const errors = await service.withdrawal.promise\n if (errors.length > 0)\n throw errorFrom(errors, `Withdrawal of '${service.name}' failed.`)\n}\n\n/** Releases a service or an invocation. Returns `false` when it is already withdrawn. */\nexport function releasePresent(service: ServiceNode): boolean {\n return untracked(() => {\n // A stale registration cannot change the service or a newer service in the same slot.\n if (!service.signals.present())\n return false\n\n batch(() => releaseService(service))\n return true\n })\n}\n","export interface Deferred<T> {\n readonly promise: Promise<T>\n resolve: (value: T) => void\n}\n\nexport function createDeferred<T>(): Deferred<T> {\n let resolve!: (value: T) => void\n const promise = new Promise<T>((done) => {\n resolve = done\n })\n\n return { promise, resolve }\n}\n","import { isUndefined, omitBy } from 'es-toolkit'\n\n/** The fields of `T` that are not `undefined`, each one optional. */\nexport type DefinedFields<T> = { [K in keyof T]?: Exclude<T[K], undefined> }\n\n/** Copies `fields` without the fields that are `undefined`. Spread the result to add optional fields to a record. */\nexport function withoutUndefined<T extends Record<string, unknown>>(fields: T): DefinedFields<T> {\n return omitBy(fields, isUndefined) as DefinedFields<T>\n}\n","import type { ErrorObserveRecord, ObserveRecord, WaitAbortedObserveRecord } from '../types'\nimport type { ContainerNode, Observer, ServiceNode } from './graph'\n\nimport { messageOf } from '../helpers/error-from'\n\nfunction within(container: ContainerNode, ancestor: ContainerNode): boolean {\n for (let current: ContainerNode | undefined = container; current; current = current.parent) {\n if (current === ancestor)\n return true\n }\n\n return false\n}\n\n/** The active observers of `container`: the observers of the container and of its ancestors. */\nfunction targetsOf(container: ContainerNode, source?: Observer): Observer[] {\n return [...container.runtime.observers].filter(observer => observer !== source && observer.active && within(container, observer.container))\n}\n\nfunction send(container: ContainerNode, targets: readonly Observer[], record: ObserveRecord): void {\n container.runtime.deliveries.deliver(targets.map(observer => ({\n run: () => {\n if (observer.active && observer.container.state !== 'disposed')\n observer.callback(record)\n },\n onError: (error: unknown) => {\n // An error about an error record is dropped. Else a failing observer can loop forever.\n if (record.type !== 'error')\n reportCallbackError(observer.container, record.key, error, 'An observe callback threw.', observer)\n },\n })))\n}\n\n/** Sends `record` to the observers of `container`. */\nexport function emitRecord(container: ContainerNode, record: ObserveRecord): void {\n // The targets are fixed now. An observer that subscribes later gets its replay, not this record.\n const targets = targetsOf(container)\n if (targets.length === 0)\n return\n\n send(container, targets, Object.freeze(record))\n}\n\n/** Reports a callback error as an `error` record. An error from an observe callback does not go back to that callback. */\nexport function reportCallbackError(container: ContainerNode, key: string, error: unknown, reason: string, source?: Observer): void {\n const record: ErrorObserveRecord = { type: 'error', key, owner: container.owner, instanceId: undefined, reason, error }\n send(container, targetsOf(container, source), record)\n}\n\n/** Sends a `wait-aborted` record for each service of `services`: the `signal` of `call` aborted before the service stopped. */\nexport function recordAbortedWait(services: readonly ServiceNode[], call: WaitAbortedObserveRecord['call'], reason: unknown): void {\n const message = messageOf(reason)\n for (const service of services) {\n emitRecord(service.container, {\n type: 'wait-aborted',\n key: service.name,\n owner: service.container.owner,\n instanceId: service.signals.instance()?.id,\n call,\n phase: service.signals.phase(),\n reason: message,\n abortReason: reason,\n })\n }\n}\n","import type { ProviderInfo, ResolutionCondition } from '../../types'\nimport type { DependencyEdge, ResolutionConsumer, ServiceNode } from '../graph'\n\nimport { untracked } from '../../helpers/signals'\nimport { reportCallbackError } from '../observers'\n\n/**\n * The verdict of each condition for each provider registration.\n * The input of a condition is frozen, and a condition must be pure. So each pair runs once, and a throw is reported once.\n */\nconst verdicts = new WeakMap<ResolutionCondition, WeakMap<ServiceNode, boolean>>()\n\n/** The read-only information about a provider registration that a condition gets. */\nexport function providerInfo(registration: ServiceNode): ProviderInfo {\n return Object.freeze({ key: registration.name, owner: registration.container.owner, metadata: registration.metadata })\n}\n\n/**\n * Tells whether `condition` accepts the provider registration.\n * A thrown error counts as `false` and goes to the observe stream of the consumer.\n */\nexport function acceptsProvider(consumer: ResolutionConsumer, keyName: string, condition: ResolutionCondition, registration: ServiceNode): boolean {\n let byProvider = verdicts.get(condition)\n if (!byProvider) {\n byProvider = new WeakMap()\n verdicts.set(condition, byProvider)\n }\n\n const known = byProvider.get(registration)\n if (known !== undefined)\n return known\n\n let verdict: boolean\n try {\n // A condition is a user callback.\n verdict = untracked(() => condition(providerInfo(registration))) === true\n }\n catch (error) {\n verdict = false\n // The resolution runs inside a computed value. The record goes out after it, so that no observer runs inside the computation.\n queueMicrotask(() => reportCallbackError(consumer.container, consumer.name, error, `A resolution condition for '${keyName}' threw. It counts as false.`))\n }\n byProvider.set(registration, verdict)\n\n return verdict\n}\n\n/** The resolution conditions that a candidate of `edge` must pass: the condition of the edge, then the condition of the candidate. */\nexport function conditionsOf(edge: DependencyEdge | undefined, keyName: string): readonly ResolutionCondition[] {\n const conditions: ResolutionCondition[] = []\n if (edge?.condition)\n conditions.push(edge.condition)\n const own = edge?.candidateConditions?.[keyName]\n if (own)\n conditions.push(own)\n\n return conditions\n}\n\n/** Tells whether the provider registration passes each condition of the candidate `keyName` of `edge`. */\nexport function acceptsCandidate(consumer: ResolutionConsumer, edge: DependencyEdge | undefined, keyName: string, registration: ServiceNode): boolean {\n return conditionsOf(edge, keyName).every(condition => acceptsProvider(consumer, keyName, condition, registration))\n}\n","import type { DependencyEdge, Resolution, ResolutionConsumer } from '../graph'\n\nimport { acceptsCandidate } from './condition'\nimport { selectProvider } from './resolvers'\n\n/**\n * Resolves one key name: the selected provider, and its instance when the provider serves.\n * A provider in conflict, or one that a condition of `edge` for `keyName` rejects, does not resolve.\n */\nexport function resolveKey(consumer: ResolutionConsumer, keyName: string, edge?: DependencyEdge): Resolution {\n const selection = selectProvider(consumer.scope, keyName, consumer)\n if (!selection)\n return { kind: 'missing' }\n\n const { registration, provider } = selection\n const rivals = registration.signals.rivals()\n if (rivals.length > 0)\n return { kind: 'conflict', provider: registration, rivals }\n if (!acceptsCandidate(consumer, edge, keyName, registration))\n return { kind: 'rejected', provider: registration }\n if (!provider)\n return { kind: 'not-running', provider: registration }\n\n const instance = provider.signals.instance()\n if (!provider.signals.serving() || !instance)\n return { kind: 'not-running', provider }\n\n return { kind: 'resolved', provider, instance }\n}\n\n/** Resolves a plain or an optional edge. It has one candidate key. */\nexport function resolvePlain(consumer: ResolutionConsumer, edge: DependencyEdge): Resolution {\n const [keyName] = edge.candidates\n return keyName === undefined ? { kind: 'missing' } : resolveKey(consumer, keyName, edge)\n}\n","import type { DependencyEdge, Resolution, ResolutionConsumer } from '../graph'\n\nimport { resolveKey } from './plain'\nimport { isAvailable } from './resolvers'\n\n/**\n * Resolves a `firstAvailable` edge. The first serving and available candidate that passes its conditions wins. A rejected candidate is skipped.\n * If no serving candidate is available, the first serving candidate stays selected, so that a running dependent does not lose it.\n * Without a serving candidate, the edge reports the first candidate that exists.\n */\nexport function resolveFallback(consumer: ResolutionConsumer, edge: DependencyEdge): Resolution {\n let firstUnresolved: Resolution | undefined\n let firstServing: Resolution | undefined\n for (const keyName of edge.candidates) {\n const resolution = resolveKey(consumer, keyName, edge)\n if (resolution.kind === 'missing')\n continue\n if (resolution.kind !== 'resolved') {\n firstUnresolved ??= resolution\n continue\n }\n\n if (isAvailable(resolution.provider))\n return resolution\n firstServing ??= resolution\n }\n\n return firstServing ?? firstUnresolved ?? { kind: 'missing' }\n}\n","import type { ServicePhase, ServiceStatus, StatusCause } from '../types'\nimport type { DependencyEdge, InstanceNode, Resolution, ServiceNode, StatusValue } from './graph'\n\nimport { computed } from 'alien-signals'\n\nimport { withoutUndefined } from '../helpers/without-undefined'\nimport { emitRecord } from './observers'\n\nconst statusRank: Readonly<Record<ServiceStatus, number>> = { ready: 0, degraded: 1, unavailable: 2 }\n\n/** Tells whether `a` is worse than `b`. The order is `ready`, then `degraded`, then `unavailable`. */\nexport function worseThan(a: ServiceStatus, b: ServiceStatus): boolean {\n return statusRank[a] > statusRank[b]\n}\n\nfunction sameCause(a: StatusCause | undefined, b: StatusCause | undefined): boolean {\n if (a === b)\n return true\n if (!a || !b)\n return false\n\n return a.key === b.key && a.owner === b.owner && a.status === b.status && a.reason === b.reason && sameCause(a.cause, b.cause)\n}\n\n/** Tells whether two status values have the same status, reason, and cause. */\nexport function sameStatus(a: StatusValue | undefined, b: StatusValue | undefined): boolean {\n if (a === b)\n return true\n if (!a || !b)\n return false\n\n return a.status === b.status && a.reason === b.reason && sameCause(a.cause, b.cause)\n}\n\nexport function statusFields(status: StatusValue): { reason?: string, cause?: StatusCause } {\n return withoutUndefined({ reason: status.reason, cause: status.cause })\n}\n\n/** The cause that a dependent reports when `provider` makes its effective status worse. */\nexport function causeOf(provider: ServiceNode, status: StatusValue): StatusCause {\n return Object.freeze({\n key: provider.name,\n owner: provider.container.owner,\n status: status.status,\n ...withoutUndefined({ reason: status.reason, cause: status.cause }),\n })\n}\n\nexport interface EffectiveStatusInput {\n readonly phase: () => ServicePhase\n readonly instance: () => InstanceNode | undefined\n readonly edges: readonly DependencyEdge[]\n readonly resolutions: ReadonlyMap<string, () => Resolution>\n}\n\n/**\n * Creates the effective status of a service: the worst of the own status and the effective status of each required dependency.\n * An optional dependency does not count. It is `undefined` outside `running`.\n */\nexport function createEffectiveStatus(input: EffectiveStatusInput): () => StatusValue | undefined {\n const { phase, instance, edges, resolutions } = input\n\n return computed<StatusValue | undefined>((previous) => {\n const current = instance()\n if (phase() !== 'running' || !current)\n return undefined\n\n let result: StatusValue = current.signals.own()\n for (const edge of edges) {\n if (edge.optional)\n continue\n\n const resolution = resolutions.get(edge.name)?.()\n if (resolution?.kind !== 'resolved')\n continue\n\n const dependency = resolution.provider.signals.effective()\n if (dependency && worseThan(dependency.status, result.status))\n result = { status: dependency.status, cause: causeOf(resolution.provider, dependency) }\n }\n\n return previous && sameStatus(previous, result) ? previous : result\n })\n}\n\n/** Reports a change of the effective status. The status effect of each service calls it. */\nexport function reportStatus(service: ServiceNode, next: StatusValue | undefined): void {\n const previous = service.reportedStatus\n service.reportedStatus = next\n if (!next || sameStatus(previous, next))\n return\n\n emitRecord(service.container, {\n type: 'status',\n key: service.name,\n owner: service.container.owner,\n instanceId: service.signals.instance()?.id,\n from: previous?.status,\n to: next.status,\n ...statusFields(next),\n })\n}\n","import type { DecisionKind } from '../../primitives/decision'\nimport type { OwnerRecord, ServiceMetadata, ServicePhase } from '../../types'\nimport type { BuildFunction, ContainerNode, DependencyEdge, InstanceNode, Policy, RegistrationNode, Resolution, ServiceKind, ServiceNode, SwapState, TransactionNode } from '../graph'\n\nimport { computed, effect, signal } from 'alien-signals'\n\nimport { createDeferred } from '../../helpers/deferred'\nimport { batch, untracked, withOwner } from '../../helpers/signals'\nimport { withoutUndefined } from '../../helpers/without-undefined'\nimport { emitRecord } from '../observers'\nimport { createRivals } from '../resolvers/exclusive'\nimport { resolveFallback } from '../resolvers/fallback'\nimport { resolvePlain } from '../resolvers/plain'\nimport { requiredWithdrawn } from '../resolvers/resolvers'\nimport { createEffectiveStatus, reportStatus } from '../status'\n\nexport interface PhaseDetails {\n readonly reason?: string\n readonly decision?: DecisionKind\n}\n\n/** Writes the phase and sends the change to the observe stream. */\nexport function setPhase(service: ServiceNode, to: ServicePhase, details: PhaseDetails = {}): void {\n const from = service.signals.phase()\n if (from === to)\n return\n\n batch(() => {\n service.signals.phase(to)\n if (service.kind === 'resolver')\n return\n\n emitRecord(service.container, {\n type: 'phase',\n key: service.name,\n owner: service.container.owner,\n instanceId: service.signals.instance()?.id,\n from,\n to,\n ...withoutUndefined({ reason: details.reason, decision: details.decision }),\n })\n })\n}\n\nfunction sameResolution(a: Resolution, b: Resolution): boolean {\n if (a.kind !== b.kind)\n return false\n\n switch (a.kind) {\n case 'missing':\n return true\n case 'not-running':\n case 'rejected':\n return 'provider' in b && a.provider === b.provider\n case 'conflict':\n return b.kind === 'conflict' && a.provider === b.provider && a.rivals === b.rivals\n case 'resolved':\n return b.kind === 'resolved' && a.provider === b.provider && a.instance === b.instance\n }\n}\n\n/** Creates the resolution of one declared edge. It keeps the previous value when nothing changed. */\nfunction resolveEdge(consumer: ServiceNode, edge: DependencyEdge): () => Resolution {\n return computed<Resolution>((previous) => {\n const next = edge.fallback ? resolveFallback(consumer, edge) : resolvePlain(consumer, edge)\n return previous && sameResolution(previous, next) ? previous : next\n })\n}\n\nexport interface CreateServiceInput {\n readonly container: ContainerNode\n readonly kind: ServiceKind\n readonly name: string\n readonly edges: readonly DependencyEdge[]\n readonly build: BuildFunction\n readonly metadata?: ServiceMetadata\n /** The retry and timeout options of the registration. An invocation has none. */\n readonly policy?: Policy\n readonly exclusive?: boolean\n /** `true` for an exported registration. A consumer service of a `perConsumer` registration is never exported. */\n readonly exported?: boolean\n readonly perConsumer?: boolean\n readonly template?: ServiceNode\n readonly consumer?: OwnerRecord\n readonly transaction?: TransactionNode\n readonly registration?: RegistrationNode\n /** Set for a new service that replaces another service after it completes `start`. */\n readonly swap?: SwapState\n /** The first phase. It defaults to `pending`. A transaction starts its services in `declared`. */\n readonly phase?: ServicePhase\n /** The place in registration order. A rebuild successor keeps the place of the service that it replaces. */\n readonly seq?: number\n}\n\nconst emptyMetadata = Object.freeze({})\nconst emptyPolicy: Policy = Object.freeze({})\n\n/**\n * Creates a service with its signals, its derived values, and its effects.\n *\n * The main effect reads the derived values of the service and only marks the service dirty.\n * The status effect sends each change of the effective status to the observe stream.\n */\nexport function createService(input: CreateServiceInput): ServiceNode {\n const { container } = input\n const { runtime } = container\n const present = signal(true)\n const phase = signal<ServicePhase>(input.phase ?? 'pending')\n const instance = signal<InstanceNode | undefined>(undefined)\n // A resolver always converges. It exists only while its `resolve` call waits.\n const demanded = signal(input.kind === 'resolver')\n const subscribers = signal<ReadonlySet<object>>(new Set())\n const resolutions = new Map<string, () => Resolution>()\n\n const effective = createEffectiveStatus({ phase, instance, edges: input.edges, resolutions })\n // The conflict reads the service, so it is created after the service object.\n let rivals: () => readonly ServiceNode[] = () => []\n\n const service: ServiceNode = {\n seq: input.seq ?? runtime.nextSeq(),\n kind: input.kind,\n name: input.name,\n container,\n scope: input.template?.container ?? container,\n edges: input.edges,\n build: input.build,\n metadata: input.metadata ?? emptyMetadata,\n policy: input.policy ?? emptyPolicy,\n exclusive: input.exclusive ?? false,\n exported: input.template === undefined && (input.exported ?? false),\n perConsumer: input.perConsumer ?? false,\n template: input.template,\n consumer: input.consumer,\n registration: input.registration,\n swap: input.swap,\n replacedBy: undefined,\n successor: undefined,\n transaction: input.transaction,\n revision: 0,\n signals: {\n present,\n phase,\n instance,\n demanded,\n subscribers,\n // Only a service with a key can be demanded. An invocation waits for `start()`.\n active: computed(() => container.signals.started() || (input.kind !== 'invocation' && (demanded() || subscribers().size > 0))),\n serving: computed(() => present() && phase() === 'running'),\n resolutions,\n effective,\n rivals: () => rivals(),\n consumers: signal<ReadonlyMap<ContainerNode, ServiceNode>>(new Map()),\n targetLost: computed(() => !present() || !service.signals.active() || service.signals.rivals().length > 0 || requiredWithdrawn(service)),\n },\n busy: false,\n stopIntent: {},\n parkedEpoch: undefined,\n failure: undefined,\n demanders: new Set(),\n teardownErrors: [],\n withdrawal: createDeferred<readonly unknown[]>(),\n reportedStatus: undefined,\n disposeEffects: () => {},\n }\n\n for (const edge of input.edges)\n resolutions.set(edge.name, resolveEdge(service, edge))\n rivals = createRivals(service)\n\n const stopMain = withOwner(container.reactiveOwner, () => effect(() => {\n present()\n phase()\n service.signals.active()\n service.signals.rivals()\n instance()?.signals.holders()\n // A new service that waits to replace another one follows the old service.\n service.swap?.target.signals.present()\n for (const resolution of resolutions.values()) {\n const current = resolution()\n // A provider that is not running yet can still fail. A pending `resolve` call needs to see that.\n if (current.kind === 'not-running')\n current.provider.signals.phase()\n // A pending service waits for an available provider. A running one handles status changes.\n if (current.kind === 'resolved')\n current.provider.signals.effective()\n }\n\n runtime.reconciler.markDirty(service)\n }))\n\n const stopStatus = input.kind === 'resolver'\n ? () => {}\n : withOwner(container.reactiveOwner, () => effect(() => {\n const status = effective()\n // The report reads the instance. It must not track it.\n untracked(() => reportStatus(service, status))\n }))\n\n service.disposeEffects = () => {\n stopMain()\n stopStatus()\n }\n\n return service\n}\n","import type { ServicePhase } from '../../types'\nimport type { ContainerNode, ServiceNode } from '../graph'\n\nimport { batch } from '../../helpers/signals'\nimport { publishService } from './container'\nimport { createService, setPhase } from './service'\n\n/** The phases of a consumer service that lead to a build outcome. */\nconst waitingPhases: ReadonlySet<ServicePhase> = new Set<ServicePhase>(['pending', 'building', 'starting', 'retrying'])\n\n/**\n * Returns the service of a `perConsumer` registration for one consumer container. It creates the service on first use.\n *\n * The service lives in the consumer container, so it disposes with that container. Its build context has the owner of the container as `consumer`.\n * It returns `undefined` when the registration is withdrawn or the container disposal started.\n *\n * `demander` is the dependent, the `resolve` call, or the subscription that needs the service.\n * A failed service builds again for a demander that did not get a build since the service last ran. So a new demand retries a failed consumer service.\n */\nexport function ensureConsumerService(registration: ServiceNode, container: ContainerNode, demander: object): ServiceNode | undefined {\n const existing = registration.signals.consumers().get(container)\n if (existing) {\n if (existing.signals.phase() === 'failed' && existing.signals.present() && !existing.demanders.has(demander)) {\n existing.demanders.add(demander)\n existing.failure = undefined\n setPhase(existing, 'pending', { reason: 'A new demand tries the failed consumer service again.' })\n existing.container.runtime.reconciler.markDirty(existing)\n }\n else if (waitingPhases.has(existing.signals.phase())) {\n // The demander gets the outcome of the build in progress.\n existing.demanders.add(demander)\n }\n return existing\n }\n if (!registration.signals.present() || container.state !== 'active')\n return undefined\n\n let service: ServiceNode | undefined\n batch(() => {\n service = createService({\n container,\n kind: 'service',\n name: registration.name,\n edges: registration.edges,\n build: registration.build,\n metadata: registration.metadata,\n policy: registration.policy,\n exclusive: registration.exclusive,\n template: registration,\n consumer: container.owner,\n })\n service.demanders.add(demander)\n container.services.add(service)\n publishService(service)\n })\n\n return service\n}\n\n/**\n * Makes `subscription` demand the consumer service of `registration` for `container`, so that it builds also before `start()`.\n * Returns the service, or `undefined` when it cannot exist. `releaseConsumerDemand` ends the demand.\n */\nexport function demandConsumerService(registration: ServiceNode, container: ContainerNode, subscription: object): ServiceNode | undefined {\n const service = ensureConsumerService(registration, container, subscription)\n if (service && !service.signals.subscribers().has(subscription))\n service.signals.subscribers(new Set([...service.signals.subscribers(), subscription]))\n\n return service\n}\n\n/** Ends the demand of `subscription` on `service`. */\nexport function releaseConsumerDemand(service: ServiceNode, subscription: object): void {\n const subscribers = service.signals.subscribers()\n if (subscribers.has(subscription))\n service.signals.subscribers(new Set([...subscribers].filter(other => other !== subscription)))\n}\n","import type { OwnerRecord, ServiceStatus } from './service'\n\ndeclare const providedType: unique symbol\ndeclare const optionalType: unique symbol\ndeclare const fallbackType: unique symbol\ndeclare const conditionalType: unique symbol\n\nexport const optionalBrand: unique symbol = Symbol('injeca.optional')\nexport const fallbackBrand: unique symbol = Symbol('injeca.fallback')\nexport const conditionBrand: unique symbol = Symbol('injeca.condition')\n\nexport type DependencyMap = Record<string, any>\n\n/**\n * A typed identity for a service. `provide` and `defineKey` return one.\n */\nexport interface ProvidedKey<Key, T, _D extends DependencyMap | undefined> {\n key: Key\n /** `true` for a key from `defineKey(name, { exclusive: true })`. Only one provider can exist in its resolution area. */\n readonly exclusive?: boolean\n /** Carries the value type. It has no value at run time. */\n readonly [providedType]?: T\n}\n\n/** A key name, a key from `defineKey`, or the result of `provide`. */\nexport type KeyReference = string | ProvidedKey<string, unknown, DependencyMap | undefined>\n\nexport interface KeyOptions {\n /** Makes an exclusive key. Two or more providers in one resolution area all go to `conflict`. */\n readonly exclusive?: boolean\n}\n\n/** A frozen record on a registration. Resolution conditions and graph queries read it. */\nexport type ServiceMetadata = Readonly<Record<string, unknown>>\n\n/** The read-only information about a provider that a resolution condition gets. */\nexport interface ProviderInfo {\n /** The key name of the provider. */\n readonly key: string\n /** The owner record of the container of the provider. */\n readonly owner: OwnerRecord\n readonly metadata: ServiceMetadata\n}\n\n/** A resolution condition from `where`. It must be pure and synchronous. A thrown error counts as `false`. */\nexport type ResolutionCondition = (provider: ProviderInfo) => boolean\n\nexport type ProvidedBy<T> = string & { __providedType?: T }\n\n/** A dependency marker from `optional(key)`. A missing provider gives `undefined` and does not keep the dependent `pending`. */\nexport interface OptionalDependency<T> {\n readonly [optionalBrand]: true\n /** The names of the keys, in order. More than one name comes from `optional(firstAvailable(...))`. */\n readonly dependencies: readonly string[]\n /** The resolution condition from `where`, when the marker has one. It filters each candidate. */\n readonly condition?: ResolutionCondition\n /** The resolution conditions of single candidates, from `firstAvailable(where(key, condition), ...)`, by key name. */\n readonly candidateConditions?: Readonly<Record<string, ResolutionCondition>>\n /** Carries the value type. It has no value at run time. */\n readonly [optionalType]?: T\n}\n\n/** A required dependency marker from `where(key, condition)`. A provider that the condition rejects does not resolve. */\nexport interface ConditionalDependency<T> {\n readonly [conditionBrand]: true\n /** The name of the key. */\n readonly dependencies: readonly string[]\n readonly condition: ResolutionCondition\n /** Carries the value type. It has no value at run time. */\n readonly [conditionalType]?: T\n}\n\n/**\n * A fallback dependency marker from `firstAvailable(...keys)`. It resolves to the first available provider in the list.\n * A resolution condition filters the candidates. The selection is the first available candidate that passes.\n */\nexport interface FallbackDependency<T> {\n readonly [fallbackBrand]: true\n /** The names of the keys, in order of preference. */\n readonly dependencies: readonly string[]\n /** The resolution condition from `where(firstAvailable(...), condition)`. It filters each candidate. */\n readonly condition?: ResolutionCondition\n /** The resolution conditions of single candidates, from `firstAvailable(where(key, condition), ...)`, by key name. */\n readonly candidateConditions?: Readonly<Record<string, ResolutionCondition>>\n /** Carries the value type. It has no value at run time. */\n readonly [fallbackType]?: T\n}\n\n/** One value of a `dependsOn` declaration: a name, a key, an optional marker, a fallback marker, or a condition marker. */\nexport type DependencyDeclaration = string | ProvidedKey<string, unknown, DependencyMap | undefined> | OptionalDependency<unknown> | FallbackDependency<unknown> | ConditionalDependency<unknown>\n\nexport type DependencyDeclarations = Record<string, DependencyDeclaration>\n\n/** The resolved value of an optional dependency. */\nexport interface OptionalValue<T> {\n readonly value: T\n readonly status: ServiceStatus\n}\n\nexport type InferProvided<T>\n = T extends ProvidedKey<any, infer P, any>\n ? P\n : T extends ProvidedBy<infer P>\n ? P\n : T extends ConditionalDependency<infer P>\n ? P\n : never\n\n/** A required dependency is its value. An optional dependency is `{ value, status }` or `undefined`. */\nexport type ResolveDependencyDeclaration<Deps extends DependencyDeclarations> = {\n [K in keyof Deps]: Deps[K] extends OptionalDependency<infer T>\n ? OptionalValue<T> | undefined\n : Deps[K] extends FallbackDependency<infer T>\n ? T\n : Deps[K] extends ConditionalDependency<infer T>\n ? T\n : Deps[K] extends ProvidedKey<any, infer T, any>\n ? T\n : Deps[K] extends ProvidedBy<infer T>\n ? T\n : any\n}\n","import type { ConditionalDependency, DependencyMap, FallbackDependency, InferProvided, KeyOptions, OptionalDependency, ProvidedBy, ProvidedKey, ResolutionCondition } from '../types'\n\nimport { InvalidArgumentError } from '../diagnostics/errors'\nimport { conditionBrand, fallbackBrand, optionalBrand } from '../types'\n\ntype KeyLike<T = unknown> = ProvidedKey<string, T, DependencyMap | undefined> | ProvidedBy<T>\n\nfunction assertName(name: unknown): asserts name is string {\n if (typeof name !== 'string' || name.length === 0 || name.trim() !== name)\n throw new InvalidArgumentError(`A key name must be a non-empty string without outer whitespace. Got ${JSON.stringify(name)}.`)\n}\n\nfunction readKeyOptions(options: unknown): boolean {\n if (options === undefined)\n return false\n if (typeof options !== 'object' || options === null)\n throw new InvalidArgumentError('The options of defineKey must be an object.')\n\n let exclusive: unknown\n try {\n exclusive = (options as KeyOptions).exclusive\n }\n catch (error) {\n throw new InvalidArgumentError('Cannot read the options of defineKey.', { cause: error })\n }\n if (exclusive !== undefined && typeof exclusive !== 'boolean')\n throw new InvalidArgumentError('The exclusive option of defineKey must be a boolean.')\n\n return exclusive === true\n}\n\n/**\n * Creates a typed key without a provider. A consumer can depend on it now. `provide(key, ...)` registers a provider later.\n *\n * With `options.exclusive`, the key can have only one provider in its resolution area. Two or more providers all go to `conflict`.\n */\nexport function defineKey<T>(name: string, options?: KeyOptions): ProvidedKey<string, T, undefined> {\n assertName(name)\n return readKeyOptions(options) ? Object.freeze({ key: name, exclusive: true }) : Object.freeze({ key: name })\n}\n\n/** Tells whether a key from `provide` or `defineKey` is exclusive. A name is not. Reading a caller-owned property happens once, inside a narrow `try`. */\nexport function isExclusiveKey(key: unknown): boolean {\n if (typeof key !== 'object' || key === null)\n return false\n\n try {\n return (key as KeyOptions).exclusive === true\n }\n catch (error) {\n throw new InvalidArgumentError('Cannot read the exclusive property of the key.', { cause: error })\n }\n}\n\nexport function normalizeName(nameOrProvidedKey: string | ProvidedKey<any, any, any>): string {\n if (typeof nameOrProvidedKey === 'object' && nameOrProvidedKey !== null && 'key' in nameOrProvidedKey) {\n return (nameOrProvidedKey as ProvidedKey<any, any, any>).key as string\n }\n\n return nameOrProvidedKey as string\n}\n\nconst optionalMarkers = new WeakSet<object>()\nconst fallbackMarkers = new WeakSet<object>()\nconst conditionMarkers = new WeakSet<object>()\n\nexport function isConditionalDependency(value: unknown): value is ConditionalDependency<unknown> {\n return typeof value === 'object' && value !== null && conditionMarkers.has(value)\n}\n\nexport function isFallbackDependency(value: unknown): value is FallbackDependency<unknown> {\n return typeof value === 'object' && value !== null && fallbackMarkers.has(value)\n}\n\n/** The candidate conditions of a marker, without empty records. */\nfunction withCandidateConditions(candidateConditions: Readonly<Record<string, ResolutionCondition>> | undefined): { readonly candidateConditions?: Readonly<Record<string, ResolutionCondition>> } {\n return candidateConditions && Object.keys(candidateConditions).length > 0 ? { candidateConditions } : {}\n}\n\n/**\n * Marks a fallback dependency. It resolves to the first provider in the list whose effective status is available.\n *\n * A change of the selection is a change of identity: the dependent gets `dependency-change`.\n * It is required, unless it is wrapped in `optional()`.\n * A `where(key, condition)` marker in the list filters that candidate only. `where(firstAvailable(...), condition)` filters each candidate.\n * The selection is the first available candidate that passes its conditions.\n */\nexport function firstAvailable<const Keys extends readonly (KeyLike | ConditionalDependency<unknown>)[]>(...keys: Keys): FallbackDependency<InferProvided<Keys[number]>> {\n if (keys.length === 0)\n throw new InvalidArgumentError('firstAvailable() needs at least one key.')\n\n const candidateConditions: Record<string, ResolutionCondition> = {}\n const dependencies = keys.map((key) => {\n if (isConditionalDependency(key)) {\n const [name] = key.dependencies\n candidateConditions[name!] = key.condition\n return name!\n }\n if (isFallbackDependency(key) || isOptionalDependency(key))\n throw new InvalidArgumentError('firstAvailable() accepts keys, names, and where() markers.')\n\n const name = normalizeName(key as KeyLike)\n assertName(name)\n return name\n })\n if (new Set(dependencies).size !== dependencies.length)\n throw new InvalidArgumentError(`firstAvailable() got the same key more than once: ${dependencies.join(', ')}.`)\n\n return fallbackMarker(Object.freeze(dependencies), undefined, Object.freeze(candidateConditions))\n}\n\nfunction fallbackMarker<T>(dependencies: readonly string[], condition: ResolutionCondition | undefined, candidateConditions: Readonly<Record<string, ResolutionCondition>> | undefined): FallbackDependency<T> {\n const marker: FallbackDependency<T> = Object.freeze({\n [fallbackBrand]: true as const,\n dependencies,\n ...(condition ? { condition } : {}),\n ...withCandidateConditions(candidateConditions),\n })\n fallbackMarkers.add(marker)\n\n return marker\n}\n\nfunction optionalMarker<T>(dependencies: readonly string[], condition: ResolutionCondition | undefined, candidateConditions?: Readonly<Record<string, ResolutionCondition>>): OptionalDependency<T> {\n const marker: OptionalDependency<T> = Object.freeze({\n [optionalBrand]: true as const,\n dependencies,\n ...(condition ? { condition } : {}),\n ...withCandidateConditions(candidateConditions),\n })\n optionalMarkers.add(marker)\n\n return marker\n}\n\n/**\n * Marks an optional dependency. The dependent gets `{ value, status }`, or `undefined` when no provider runs.\n * It also accepts a `firstAvailable` marker and a `where` marker, with their conditions.\n */\nexport function optional<T>(dependency: KeyLike<T> | FallbackDependency<T> | ConditionalDependency<T>): OptionalDependency<T> {\n if (isFallbackDependency(dependency))\n return optionalMarker(dependency.dependencies, dependency.condition, dependency.candidateConditions)\n if (isConditionalDependency(dependency))\n return optionalMarker(dependency.dependencies, dependency.condition)\n\n const name = normalizeName(dependency as KeyLike<T>)\n assertName(name)\n return optionalMarker(Object.freeze([name]), undefined)\n}\n\n/**\n * Adds a resolution condition to a dependency. The condition gets the key, the owner, and the metadata of the provider.\n *\n * If it returns `false`, the dependency does not resolve. A required dependency keeps the dependent `pending`. An optional one is `undefined`.\n * The condition must be pure and synchronous. A thrown error counts as `false` and goes to the observe stream.\n * Wrap the result in `optional()`, or pass an `optional()` marker, to combine the two.\n *\n * For a `firstAvailable` marker, the condition filters each candidate. The selection is the first available candidate that passes.\n * A candidate that `firstAvailable(where(key, other), ...)` filters must pass both conditions.\n */\nexport function where<T>(dependency: OptionalDependency<T>, condition: ResolutionCondition): OptionalDependency<T>\nexport function where<T>(dependency: FallbackDependency<T>, condition: ResolutionCondition): FallbackDependency<T>\nexport function where<T>(dependency: KeyLike<T>, condition: ResolutionCondition): ConditionalDependency<T>\nexport function where<T>(dependency: KeyLike<T> | OptionalDependency<T> | FallbackDependency<T>, condition: ResolutionCondition): ConditionalDependency<T> | OptionalDependency<T> | FallbackDependency<T> {\n if (typeof condition !== 'function')\n throw new InvalidArgumentError('The condition of where() is not a function.')\n if (isOptionalDependency(dependency)) {\n if (dependency.condition)\n throw new InvalidArgumentError('The optional dependency already has a condition.')\n return optionalMarker<T>(dependency.dependencies, condition, dependency.candidateConditions)\n }\n if (isFallbackDependency(dependency)) {\n if (dependency.condition)\n throw new InvalidArgumentError('The fallback dependency already has a condition.')\n return fallbackMarker<T>(dependency.dependencies, condition, dependency.candidateConditions)\n }\n if (isConditionalDependency(dependency))\n throw new InvalidArgumentError('where() accepts a key, a name, an optional() marker, or a firstAvailable() marker.')\n\n const name = normalizeName(dependency as KeyLike<T>)\n assertName(name)\n const marker: ConditionalDependency<T> = Object.freeze({ [conditionBrand]: true as const, dependencies: Object.freeze([name]), condition })\n conditionMarkers.add(marker)\n\n return marker\n}\n\nexport function isOptionalDependency(value: unknown): value is OptionalDependency<unknown> {\n return typeof value === 'object' && value !== null && optionalMarkers.has(value)\n}\n","import type { ProvidedKey, ResolutionCondition } from '../../types'\nimport type { DependencyEdge } from '../graph'\n\nimport { InvalidArgumentError } from '../../diagnostics/errors'\nimport { isConditionalDependency, isFallbackDependency, isOptionalDependency, normalizeName } from '../../primitives/keys'\n\nfunction edgeOf(name: string, candidates: readonly string[], optional: boolean, fallback: boolean, condition?: ResolutionCondition, candidateConditions?: Readonly<Record<string, ResolutionCondition>>): DependencyEdge {\n return Object.freeze({\n name,\n keyName: candidates.join(' | '),\n candidates,\n optional,\n fallback,\n ...(condition ? { condition } : {}),\n ...(candidateConditions ? { candidateConditions } : {}),\n })\n}\n\n/**\n * Reads a `dependsOn` declaration into edges. Reading a caller-owned property happens once, inside a narrow `try`.\n */\nexport function readEdges(owner: string, dependsOn: unknown): readonly DependencyEdge[] {\n if (dependsOn === undefined || dependsOn === null)\n return Object.freeze([])\n if (typeof dependsOn !== 'object')\n throw new InvalidArgumentError(`The dependsOn option of '${owner}' is not an object.`)\n\n let entries: [string, unknown][]\n try {\n entries = Object.entries(dependsOn)\n }\n catch (error) {\n throw new InvalidArgumentError(`Cannot read the dependsOn option of '${owner}'.`, { cause: error })\n }\n\n return Object.freeze(entries.map(([name, dependency]): DependencyEdge => {\n if (isOptionalDependency(dependency))\n return edgeOf(name, dependency.dependencies, true, dependency.dependencies.length > 1, dependency.condition, dependency.candidateConditions)\n if (isConditionalDependency(dependency))\n return edgeOf(name, dependency.dependencies, false, false, dependency.condition)\n if (isFallbackDependency(dependency))\n return edgeOf(name, dependency.dependencies, false, true, dependency.condition, dependency.candidateConditions)\n if (typeof dependency === 'string' || (typeof dependency === 'object' && dependency !== null && 'key' in dependency)) {\n const keyName = normalizeName(dependency as string | ProvidedKey<string, unknown, undefined>)\n if (typeof keyName === 'string' && keyName.length > 0)\n return edgeOf(name, Object.freeze([keyName]), false, false)\n }\n\n throw new InvalidArgumentError(`The dependency '${name}' of '${owner}' is not a name, a key, an optional marker, a fallback marker, or a condition marker.`)\n }))\n}\n","import type { TimeoutHandler } from '../../types'\nimport type { ContainerNode, Policy, ServiceNode } from '../graph'\n\nimport { InvalidArgumentError } from '../../diagnostics/errors'\n\nconst emptyPolicy: Policy = Object.freeze({})\n\n/** The policy option fields as read from the caller, before the checks. */\nexport interface PolicyFields {\n readonly maxAttempts: unknown\n readonly timeouts: unknown\n readonly onTimeout: unknown\n}\n\nfunction readMaxAttempts(owner: string, value: unknown): number | undefined {\n if (value !== undefined && (typeof value !== 'number' || !Number.isInteger(value) || value < 1))\n throw new InvalidArgumentError(`The maxAttempts option of ${owner} must be an integer of 1 or more. Got ${String(value)}.`)\n\n return value\n}\n\nfunction readTimeout(owner: string, hook: 'start' | 'stop', value: unknown): number | undefined {\n if (value !== undefined && (typeof value !== 'number' || !Number.isFinite(value) || value < 0))\n throw new InvalidArgumentError(`The timeouts.${hook} option of ${owner} must be a finite number of 0 or more. Got ${String(value)}.`)\n\n return value\n}\n\nfunction readTimeouts(owner: string, value: unknown): Policy['timeouts'] {\n if (value === undefined)\n return undefined\n if (typeof value !== 'object' || value === null)\n throw new InvalidArgumentError(`The timeouts option of ${owner} must be an object.`)\n\n let fields: { start: unknown, stop: unknown }\n try {\n const source = value as Record<string, unknown>\n fields = { start: source.start, stop: source.stop }\n }\n catch (error) {\n throw new InvalidArgumentError(`Cannot read the timeouts option of ${owner}.`, { cause: error })\n }\n\n const start = readTimeout(owner, 'start', fields.start)\n const stop = readTimeout(owner, 'stop', fields.stop)\n return Object.freeze({ ...(start === undefined ? {} : { start }), ...(stop === undefined ? {} : { stop }) })\n}\n\n/**\n * Checks the retry and timeout options that a caller gave. `owner` names the caller in the messages, for example `'voice.speech'`.\n * A field that is `undefined` takes the value of `inherit`, so that a replacement keeps it.\n */\nexport function readPolicy(owner: string, fields: PolicyFields, inherit?: Policy): Policy {\n const maxAttempts = readMaxAttempts(owner, fields.maxAttempts) ?? inherit?.maxAttempts\n const timeouts = readTimeouts(owner, fields.timeouts) ?? inherit?.timeouts\n if (fields.onTimeout !== undefined && typeof fields.onTimeout !== 'function')\n throw new InvalidArgumentError(`The onTimeout option of ${owner} must be a function.`)\n const onTimeout = (fields.onTimeout as TimeoutHandler | undefined) ?? inherit?.onTimeout\n\n if (maxAttempts === undefined && timeouts === undefined && onTimeout === undefined)\n return emptyPolicy\n\n return Object.freeze({\n ...(maxAttempts === undefined ? {} : { maxAttempts }),\n ...(timeouts === undefined ? {} : { timeouts }),\n ...(onTimeout === undefined ? {} : { onTimeout }),\n })\n}\n\n/** The value of the nearest container, from `container` up to the root, that sets it. */\nfunction fromContainers<T>(container: ContainerNode | undefined, pick: (policy: Policy) => T | undefined): T | undefined {\n for (let current = container; current; current = current.parent) {\n const value = pick(current.policy)\n if (value !== undefined)\n return value\n }\n\n return undefined\n}\n\n/** The attempt limit of a requeue: the decision, then the service, then the containers. `undefined` means no limit. */\nexport function maxAttemptsOf(service: ServiceNode, fromDecision: number | undefined): number | undefined {\n return fromDecision ?? service.policy.maxAttempts ?? fromContainers(service.container, policy => policy.maxAttempts)\n}\n\n/** The timeout of a hook: the service, then the containers. `undefined` means no timeout. */\nexport function timeoutOf(service: ServiceNode, hook: 'start' | 'stop'): number | undefined {\n return service.policy.timeouts?.[hook] ?? fromContainers(service.container, policy => policy.timeouts?.[hook])\n}\n\n/** The `onTimeout` handler: the service, then the containers. */\nexport function timeoutHandlerOf(service: ServiceNode): TimeoutHandler | undefined {\n return service.policy.onTimeout ?? fromContainers(service.container, policy => policy.onTimeout)\n}\n","import type { ServiceMetadata } from '../../types'\nimport type { BuildFunction, Policy, ServiceDefinition } from '../graph'\n\nimport { InvalidArgumentError } from '../../diagnostics/errors'\nimport { readEdges } from './edge'\nimport { readPolicy } from './policy'\n\nconst emptyMetadata: ServiceMetadata = Object.freeze({})\n\nfunction readMetadata(name: string, metadata: unknown, fallback: ServiceMetadata | undefined): ServiceMetadata {\n if (metadata === undefined)\n return fallback ?? emptyMetadata\n if (typeof metadata !== 'object' || metadata === null || Array.isArray(metadata))\n throw new InvalidArgumentError(`The metadata option of '${name}' must be a record.`)\n\n try {\n return Object.freeze({ ...metadata })\n }\n catch (error) {\n throw new InvalidArgumentError(`Cannot read the metadata option of '${name}'.`, { cause: error })\n }\n}\n\n/**\n * Reads the options of one registration once: the function shorthand, or the object form.\n * Reading caller-owned properties happens inside a narrow `try`. `inherit` gives the metadata and each policy field when the options have none.\n * A replacement keeps `perConsumer` and `export` of its registration, so it ignores these fields of the definition.\n */\nexport function readDefinition(name: string, option: unknown, inherit?: { readonly metadata: ServiceMetadata, readonly policy: Policy }): ServiceDefinition {\n let build: unknown\n let dependsOn: unknown\n let metadata: unknown\n let perConsumer: unknown\n let exported: unknown\n let policy: { maxAttempts: unknown, timeouts: unknown, onTimeout: unknown }\n try {\n const object: { build?: unknown, dependsOn?: unknown, metadata?: unknown, perConsumer?: unknown, export?: unknown, maxAttempts?: unknown, timeouts?: unknown, onTimeout?: unknown } = typeof option === 'function'\n ? { build: option }\n : typeof option === 'object' && option !== null ? option : {}\n build = object.build\n dependsOn = object.dependsOn\n metadata = object.metadata\n perConsumer = object.perConsumer\n exported = object.export\n policy = { maxAttempts: object.maxAttempts, timeouts: object.timeouts, onTimeout: object.onTimeout }\n }\n catch (error) {\n throw new InvalidArgumentError(`Cannot read the provide options of '${name}'.`, { cause: error })\n }\n if (typeof build !== 'function')\n throw new InvalidArgumentError(`The build option of '${name}' is not a function.`)\n if (perConsumer !== undefined && typeof perConsumer !== 'boolean')\n throw new InvalidArgumentError(`The perConsumer option of '${name}' must be a boolean.`)\n if (exported !== undefined && typeof exported !== 'boolean')\n throw new InvalidArgumentError(`The export option of '${name}' must be a boolean.`)\n\n return {\n edges: readEdges(name, dependsOn),\n build: build as BuildFunction,\n metadata: readMetadata(name, metadata, inherit?.metadata),\n perConsumer: perConsumer === true,\n exported: exported === true,\n policy: readPolicy(`'${name}'`, policy, inherit?.policy),\n }\n}\n","import type { ContainerNode, RegistrationNode, ServiceNode } from '../graph'\n\nimport { batch, untracked } from '../../helpers/signals'\nimport { releaseService } from './container'\n\nexport function createRegistration(container: ContainerNode, name: string, exclusive: boolean): RegistrationNode {\n return { container, name, exclusive, current: undefined, pending: undefined }\n}\n\n/**\n * The published service of a registration that is still current, or `undefined` for a stale registration.\n * A registration is stale after its own withdrawal, or after a newer `provide` of the same key in the same container.\n */\nexport function currentService(registration: RegistrationNode): ServiceNode | undefined {\n const service = registration.current\n return service?.signals.present() ? service : undefined\n}\n\n/** Cancels the replacement that waits for its swap. The old service does not change. */\nexport function cancelPending(registration: RegistrationNode): void {\n const pending = registration.pending\n if (!pending)\n return\n\n registration.pending = undefined\n pending.swap?.settle({ kind: 'cancelled' })\n releaseService(pending)\n}\n\n/** Cancels the successor that waits to replace `service`, for example a make-before-break rebuild. `service` does not change. */\nexport function cancelSuccessor(service: ServiceNode): void {\n const successor = service.successor\n if (!successor)\n return\n\n service.successor = undefined\n successor.swap?.settle({ kind: 'cancelled' })\n releaseService(successor)\n}\n\n/** Releases the current service of a registration and cancels its pending replacement. Returns the service, or `undefined` for a stale registration. */\nexport function releaseRegistration(registration: RegistrationNode): ServiceNode | undefined {\n return untracked(() => {\n const current = currentService(registration)\n if (current) {\n batch(() => {\n cancelPending(registration)\n releaseService(current)\n })\n }\n\n return current\n })\n}\n","import type { TransactionEntry, TransactionNode } from '../graph'\n\nimport { batch } from '../../helpers/signals'\nimport { addDeclaration, removeDeclaration } from '../resolvers/exclusive'\nimport { createService } from './service'\n\n/**\n * Reserves the exclusive key of a transaction entry until the commit or the abort.\n *\n * The reservation is a declaration without a slot. Consumers cannot resolve it. An exclusive conflict counts it, so a provider of the key in another container of the resolution area goes to `conflict`.\n * The reservation of an exported key counts in the resolution area of the parent container, as the published service does.\n * A plain key needs no reservation. In the same container, `provide` checks the open transactions and fails with `duplicate-service`.\n */\nexport function reserveKey(transaction: TransactionNode, entry: TransactionEntry): void {\n if (!entry.exclusive || entry.replace)\n return\n // A `tx.provide` with `export` after a `tx.declare` moves the reservation to the resolution area of the parent container.\n if (entry.reservation?.exported === entry.exported)\n return\n releaseReservation(entry)\n\n batch(() => {\n const reservation = createService({\n container: transaction.container,\n kind: 'service',\n name: entry.name,\n edges: [],\n build: () => undefined,\n exclusive: true,\n exported: entry.exported,\n phase: 'declared',\n transaction,\n })\n entry.reservation = reservation\n addDeclaration(reservation)\n })\n}\n\n/** Removes the reservation of a transaction entry. The commit calls it in the batch of its publish. */\nexport function releaseReservation(entry: TransactionEntry): void {\n const reservation = entry.reservation\n if (!reservation)\n return\n\n entry.reservation = undefined\n batch(() => {\n reservation.signals.present(false)\n removeDeclaration(reservation)\n })\n reservation.disposeEffects()\n}\n\n/** Removes the reservations of all entries of a transaction. */\nexport function releaseReservations(transaction: TransactionNode): void {\n batch(() => {\n for (const entry of transaction.entries.values())\n releaseReservation(entry)\n })\n}\n\n/** Tells whether an open or committing transaction of the container, other than `except`, has an entry that reserves `name`. */\nexport function reservedBy(transactions: Iterable<TransactionNode>, name: string, except?: TransactionNode): TransactionNode | undefined {\n for (const transaction of transactions) {\n if (transaction === except || (transaction.state !== 'open' && transaction.state !== 'committing'))\n continue\n\n const entry = transaction.entries.get(name)\n if (entry && !entry.replace)\n return transaction\n }\n\n return undefined\n}\n","import { InvalidDecisionError } from '../diagnostics/errors'\n\n/** The hooks that `on` registers in `build` and in an invocation callback. */\nexport type ServiceHook = 'start' | 'stop' | 'dependency-change' | 'dependency-status-change'\n\n/** The hooks that run when a dependency changes. Their context has `dependsOn` and `changes`. */\nexport type DependencyHook = 'dependency-change' | 'dependency-status-change'\n\nexport interface DecisionOptions {\n readonly reason?: string\n}\n\nexport interface ExponentialBackoff {\n readonly kind: 'exponential'\n readonly initial: number\n readonly max: number\n readonly jitter?: number\n}\n\nexport interface RequeueOptions extends DecisionOptions {\n /** A fixed delay in milliseconds. */\n readonly after?: number\n readonly backoff?: ExponentialBackoff\n readonly maxAttempts?: number\n}\n\n/** The fields that injeca fills from the hook context. */\nexport interface DecisionSource {\n /** The name of the service, or of the invocation. */\n readonly service: string\n readonly instanceId: string\n readonly hook: ServiceHook\n readonly attempt: number\n /** The time of the container clock when `decide` created the decision. */\n readonly issuedAt: number\n}\n\nexport interface HandledDecision extends DecisionSource, DecisionOptions {\n readonly kind: 'handled'\n}\n\nexport interface RebuildDecision extends DecisionSource, DecisionOptions {\n readonly kind: 'rebuild'\n}\n\nexport interface RequeueDecision extends DecisionSource, RequeueOptions {\n readonly kind: 'requeue'\n}\n\nexport interface StopDecision extends DecisionSource, DecisionOptions {\n readonly kind: 'stop'\n}\n\nexport interface FailDecision extends DecisionSource, DecisionOptions {\n readonly kind: 'fail'\n readonly error: unknown\n}\n\n/**\n * The value that a hook returns to tell injeca what to do next. Only `decide` in the hook context creates it.\n */\nexport type Decision = HandledDecision | RebuildDecision | RequeueDecision | StopDecision | FailDecision\n\nexport type DecisionKind = Decision['kind']\n\n/** The decision kinds that a hook accepts. */\nexport type HookDecisionKind<H extends ServiceHook>\n = H extends 'start'\n ? 'handled' | 'requeue' | 'stop' | 'fail'\n : H extends 'stop'\n ? 'handled' | 'fail'\n : DecisionKind\n\n/** The decisions that a hook accepts. */\nexport type DecisionFor<H extends ServiceHook> = Extract<Decision, { readonly kind: HookDecisionKind<H> }>\n\n/**\n * The value that a hook handler can return.\n *\n * A decision tells injeca what to do next. Any other value, for example the result of `app.listen()`, selects the default of the hook.\n * So the shorthand `on('start', () => app.listen(port))` type-checks.\n * The `decide` of each hook has only the methods that the hook accepts. A decision from another run fails at run time with `invalid-decision`.\n */\nexport type HookResult<_H extends ServiceHook = ServiceHook> = unknown\n\n/** All decision constructors. A hook context has only the constructors that its hook accepts. */\nexport interface Decide {\n readonly handled: (options?: DecisionOptions) => HandledDecision\n readonly rebuild: (options?: DecisionOptions) => RebuildDecision\n readonly requeue: (options?: RequeueOptions) => RequeueDecision\n readonly stop: (options?: DecisionOptions) => StopDecision\n readonly fail: (error: unknown, options?: DecisionOptions) => FailDecision\n}\n\n/** The `decide` object of a hook context. A method that the hook does not accept is a type error. */\nexport type DecideFor<H extends ServiceHook> = Pick<Decide, HookDecisionKind<H>>\n\n/**\n * One run of one hook handler. Each decision is bound to the run that created it.\n *\n * @internal\n */\nexport interface HookRun {\n readonly service: string\n readonly instanceId: string\n readonly hook: ServiceHook\n readonly attempt: number\n readonly now: () => number\n}\n\nconst issued = new WeakMap<object, HookRun>()\n\nfunction reasonFrom(options: DecisionOptions | undefined): { reason?: string } {\n return options?.reason === undefined ? {} : { reason: options.reason }\n}\n\n/** Creates the `decide` object of one run. */\nexport function createDecide(run: HookRun): Decide {\n function issue<T extends Decision>(fields: Omit<T, keyof DecisionSource>): T {\n const decision = Object.freeze({\n ...fields,\n service: run.service,\n instanceId: run.instanceId,\n hook: run.hook,\n attempt: run.attempt,\n issuedAt: run.now(),\n }) as T\n issued.set(decision, run)\n return decision\n }\n\n return Object.freeze({\n handled: (options?: DecisionOptions) => issue<HandledDecision>({ kind: 'handled', ...reasonFrom(options) }),\n rebuild: (options?: DecisionOptions) => issue<RebuildDecision>({ kind: 'rebuild', ...reasonFrom(options) }),\n requeue: (options?: RequeueOptions) => issue<RequeueDecision>({\n kind: 'requeue',\n ...reasonFrom(options),\n ...(options?.after === undefined ? {} : { after: options.after }),\n ...(options?.backoff === undefined ? {} : { backoff: Object.freeze({ ...options.backoff }) }),\n ...(options?.maxAttempts === undefined ? {} : { maxAttempts: options.maxAttempts }),\n }),\n stop: (options?: DecisionOptions) => issue<StopDecision>({ kind: 'stop', ...reasonFrom(options) }),\n fail: (error: unknown, options?: DecisionOptions) => issue<FailDecision>({ kind: 'fail', error, ...reasonFrom(options) }),\n })\n}\n\nconst validKinds: Readonly<Record<ServiceHook, ReadonlySet<DecisionKind>>> = {\n 'start': new Set(['handled', 'requeue', 'stop', 'fail']),\n 'stop': new Set(['handled', 'fail']),\n 'dependency-change': new Set(['handled', 'rebuild', 'requeue', 'stop', 'fail']),\n 'dependency-status-change': new Set(['handled', 'rebuild', 'requeue', 'stop', 'fail']),\n}\n\n/** The decision for `undefined`. A `dependency-change` handler without a decision gets the default: rebuild. */\nexport function defaultDecision(run: HookRun): Decision {\n const decide = createDecide(run)\n return run.hook === 'dependency-change' ? decide.rebuild() : decide.handled()\n}\n\n/**\n * Checks the value that a hook handler returned. It gives `undefined` for a value that `decide` did not create, so that the caller applies the default.\n * This keeps a shorthand such as `on('start', () => app.listen(port))` valid.\n *\n * @throws {InvalidDecisionError} when another run created the decision, or when the hook does not accept its kind.\n */\nexport function validateDecision(run: HookRun, value: unknown): Decision | undefined {\n const owner = typeof value === 'object' && value !== null ? issued.get(value) : undefined\n if (!owner)\n return undefined\n if (owner !== run)\n throw new InvalidDecisionError(`The '${run.hook}' hook of '${run.service}' returned a decision from another run: the '${owner.hook}' hook of '${owner.service}', instance '${owner.instanceId}', attempt ${owner.attempt}.`)\n\n const decision = value as Decision\n if (!validKinds[run.hook].has(decision.kind))\n throw new InvalidDecisionError(`The '${run.hook}' hook cannot return a '${decision.kind}' decision.`)\n\n return decision\n}\n"],"mappings":";;;;;;AAuBA,IAAa,cAAb,cAAiC,MAAM;CACrC;CAEA,YAAY,MAAuB,SAAiB,SAA8B;EAChF,MAAM,SAAS,OAAO;EACtB,KAAK,OAAO;EACZ,KAAK,OAAO;CACd;AACF;;AAGA,IAAa,wBAAb,cAA2C,YAAY;CAGrD,YAAY,SAAiB,SAA8B;EACzD,MAAM,qBAAqB,SAAS,OAAO;EAC3C,KAAK,OAAO;CACd;AACF;;AAGA,IAAa,yBAAb,cAA4C,YAAY;CAGtD,YAAY,SAAiB,SAA8B;EACzD,MAAM,sBAAsB,SAAS,OAAO;EAC5C,KAAK,OAAO;CACd;AACF;;AAGA,IAAa,uBAAb,cAA0C,YAAY;CAGpD,YAAY,SAAiB,SAA8B;EACzD,MAAM,oBAAoB,SAAS,OAAO;EAC1C,KAAK,OAAO;CACd;AACF;;AAGA,IAAa,yBAAb,cAA4C,YAAY;CAGtD,YAAY,SAAiB,SAA8B;EACzD,MAAM,uBAAuB,SAAS,OAAO;EAC7C,KAAK,OAAO;CACd;AACF;;AAGA,IAAa,wBAAb,cAA2C,YAAY;CAGrD,YAAY,SAAiB,SAA8B;EACzD,MAAM,sBAAsB,SAAS,OAAO;EAC5C,KAAK,OAAO;CACd;AACF;;AAGA,IAAa,6BAAb,cAAgD,YAAY;CAG1D,YAAY,SAAiB,SAA8B;EACzD,MAAM,0BAA0B,SAAS,OAAO;EAChD,KAAK,OAAO;CACd;AACF;;AAGA,IAAa,mBAAb,cAAsC,YAAY;CAEhD;CACA;CAEA,YAAY,SAAiB,MAAwB,WAAmB,SAA8B;EACpG,MAAM,gBAAgB,SAAS,OAAO;EACtC,K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