@vielzeug/conduit 3.0.0 → 26.10.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/dist/conduit.cjs +1 -1
- package/dist/conduit.cjs.map +1 -1
- package/dist/conduit.iife.js +1 -1
- package/dist/conduit.iife.js.map +1 -1
- package/dist/conduit.js +1 -1
- package/dist/conduit.js.map +1 -1
- package/dist/container.cjs +1 -1
- package/dist/container.cjs.map +1 -1
- package/dist/container.d.ts +2 -2
- package/dist/container.d.ts.map +1 -1
- package/dist/container.js +1 -201
- package/dist/container.js.map +1 -1
- package/dist/errors.cjs +1 -1
- package/dist/errors.cjs.map +1 -1
- package/dist/errors.d.ts +1 -14
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +1 -51
- package/dist/errors.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -4
- package/dist/types.cjs +1 -1
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.ts +19 -11
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +1 -26
- package/dist/types.js.map +1 -1
- package/package.json +5 -5
package/dist/container.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"container.cjs","names":[],"sources":["../src/container.ts"],"sourcesContent":["import {\n ConduitCircularDependencyError,\n ConduitDisposedError,\n ConduitDisposeError,\n ConduitDuplicateRegistrationError,\n ConduitError,\n ConduitProviderNotFoundError,\n ConduitScopedResolutionError,\n} from './errors.js';\nimport type {\n Container,\n FactoryProvider,\n InferServices,\n Lifetime,\n Provider,\n ScopeToken,\n ServiceMap,\n Token,\n ValueProvider,\n} from './types.js';\nimport { disposalSignalToken } from './types.js';\n\ntype Disposer = (value: unknown) => Promise<void> | void;\n\ntype ValueRegistration<T> = Readonly<{\n dispose?: Disposer;\n kind: 'value';\n value: T;\n}>;\n\ntype FactoryRegistration<T = unknown> = Readonly<{\n factory: (...values: unknown[]) => Promise<T> | T;\n dependencies: readonly Token<unknown>[];\n dispose?: Disposer;\n kind: 'factory';\n lifetime: Lifetime;\n}>;\n\ntype Registration<T = unknown> = FactoryRegistration<T> | ValueRegistration<T>;\ntype OwnedResource = Readonly<{ dispose?: Disposer; value: unknown }>;\ntype CacheEntry = { promise: Promise<unknown>; resolved: boolean; value?: unknown };\ntype Lifecycle = 'active' | 'disposed' | 'disposing';\n\nclass ContainerImpl implements Container {\n #cache = new Map<FactoryRegistration<unknown>, CacheEntry>();\n #children = new Set<ContainerImpl>();\n #cleanupFailures: unknown[] = [];\n #disposalController = new AbortController();\n #inFlight = new Set<Promise<unknown>>();\n #lifecycle: Lifecycle = 'active';\n #disposePromise?: Promise<void>;\n #owned: OwnedResource[] = [];\n #parent?: ContainerImpl;\n #registry = new Map<Token<unknown>, Registration<unknown>>();\n #scope?: ScopeToken;\n readonly name: string;\n\n constructor(\n parent: ContainerImpl | undefined,\n providers: readonly Provider<any, any>[],\n options: { name?: string; scope?: ScopeToken },\n ) {\n this.#parent = parent;\n this.#scope = options.scope;\n\n if (parent) parent.#children.add(this);\n\n this.name = options.name ?? (parent ? `${parent.name}:${options.scope?.description ?? 'child'}` : 'root');\n this.#registry.set(disposalSignalToken, { kind: 'value', value: this.disposalSignal });\n\n try {\n this.#registerProviders(providers);\n this.#validateGraph();\n this.#claimValues();\n } catch (error) {\n if (parent) parent.#children.delete(this);\n this.#registry.clear();\n throw error;\n }\n }\n\n get disposalSignal(): AbortSignal {\n return this.#disposalController.signal;\n }\n\n get disposed(): boolean {\n return this.#lifecycle === 'disposed';\n }\n\n has<T>(token: Token<T>): boolean {\n this.#assertActive();\n\n return this.#lookup(token) !== undefined;\n }\n\n resolve<T>(token: Token<T>): Promise<T>;\n resolve<M extends ServiceMap>(map: M): Promise<InferServices<M>>;\n async resolve<T, M extends ServiceMap>(input: Token<T> | M): Promise<InferServices<M> | T> {\n this.#assertActive();\n\n if (typeof input === 'symbol') return this.#resolve(input, []);\n if (typeof input !== 'object' || input === null || Array.isArray(input)) {\n throw new ConduitError('resolve() requires a token or service map');\n }\n\n const entries = Object.keys(input) as (keyof M & string)[];\n const values = await Promise.all(entries.map((key) => this.#resolve(input[key] as Token<unknown>, [])));\n const services = {} as InferServices<M>;\n\n entries.forEach((key, index) => {\n Object.defineProperty(services, key, {\n configurable: true,\n enumerable: true,\n value: values[index],\n writable: true,\n });\n });\n\n return services;\n }\n\n createScope(\n scope?: ScopeToken,\n options?: { readonly name?: string; readonly providers?: readonly Provider<any, any>[] },\n ): Container {\n this.#assertActive();\n\n return new ContainerImpl(this, options?.providers ?? [], { name: options?.name, scope });\n }\n\n dispose(): Promise<void> {\n if (this.#lifecycle === 'disposed') return Promise.resolve();\n\n if (this.#disposePromise) return this.#disposePromise;\n\n this.#lifecycle = 'disposing';\n this.#disposalController.abort();\n this.#disposePromise = this.#finishDisposal();\n\n return this.#disposePromise;\n }\n\n async [Symbol.asyncDispose](): Promise<void> {\n await this.dispose();\n }\n\n async #finishDisposal(): Promise<void> {\n const childOutcomes = await Promise.allSettled([...this.#children].map((child) => child.dispose()));\n\n await Promise.allSettled([...this.#inFlight]);\n\n const failures = [\n ...this.#cleanupFailures,\n ...childOutcomes.flatMap((outcome) => {\n if (outcome.status !== 'rejected') return [];\n\n return outcome.reason instanceof ConduitDisposeError ? outcome.reason.errors : [outcome.reason];\n }),\n ];\n\n for (const resource of [...this.#owned].reverse()) {\n if (!resource.dispose) continue;\n\n try {\n await resource.dispose(resource.value);\n } catch (error) {\n failures.push(error);\n }\n }\n\n this.#cache.clear();\n this.#children.clear();\n this.#cleanupFailures = [];\n this.#owned = [];\n this.#registry.clear();\n\n if (this.#parent) this.#parent.#children.delete(this);\n\n this.#lifecycle = 'disposed';\n\n if (failures.length) throw new ConduitDisposeError(failures);\n }\n\n #assertActive(): void {\n if (this.#lifecycle !== 'active') throw new ConduitDisposedError(this.name);\n }\n\n #assertUnregistered(token: Token<unknown>): void {\n if (this.#registry.has(token)) throw new ConduitDuplicateRegistrationError(token);\n }\n\n #registerProviders(providers: readonly Provider<any, any>[]): void {\n if (!Array.isArray(providers)) throw new ConduitError('Container providers must be an array');\n\n for (const input of providers) {\n if (typeof input !== 'object' || input === null || Array.isArray(input)) {\n throw new ConduitError('Each provider must be an object');\n }\n\n const provider = input as Provider;\n const hasDependencies = Object.hasOwn(provider, 'dependencies');\n const hasFactory = Object.hasOwn(provider, 'factory');\n const hasValue = Object.hasOwn(provider, 'value');\n\n if (typeof provider.token !== 'symbol') throw new ConduitError('Each provider requires a token');\n if (provider.dispose !== undefined && typeof provider.dispose !== 'function') {\n throw new ConduitError(`Provider \"${provider.token.description ?? 'anonymous'}\" has an invalid disposer`);\n }\n if (\n hasValue === hasFactory ||\n hasValue === hasDependencies ||\n (hasValue && Object.hasOwn(provider, 'lifetime'))\n ) {\n throw new ConduitError(\n `Provider \"${provider.token.description ?? 'anonymous'}\" must define exactly one value or factory`,\n );\n }\n\n this.#assertUnregistered(provider.token);\n\n if (hasFactory) {\n const factory = provider as FactoryProvider<unknown>;\n\n if (\n !Array.isArray(factory.dependencies) ||\n factory.dependencies.some((dependency) => typeof dependency !== 'symbol')\n ) {\n throw new ConduitError(\n `Factory provider \"${provider.token.description ?? 'anonymous'}\" has invalid dependencies`,\n );\n }\n if (typeof factory.factory !== 'function') {\n throw new ConduitError(`Factory provider \"${provider.token.description ?? 'anonymous'}\" requires a factory`);\n }\n if (\n factory.lifetime !== undefined &&\n factory.lifetime !== 'singleton' &&\n factory.lifetime !== 'transient' &&\n typeof factory.lifetime !== 'symbol'\n ) {\n throw new ConduitError(\n `Factory provider \"${provider.token.description ?? 'anonymous'}\" has an invalid lifetime`,\n );\n }\n\n this.#registry.set(provider.token, {\n dependencies: Object.freeze([...factory.dependencies]),\n dispose: factory.dispose as Disposer | undefined,\n factory: factory.factory as (...values: unknown[]) => Promise<unknown> | unknown,\n kind: 'factory',\n lifetime: factory.lifetime ?? 'singleton',\n });\n } else {\n const valueProvider = provider as ValueProvider<unknown>;\n\n this.#registry.set(provider.token, {\n dispose: valueProvider.dispose as Disposer | undefined,\n kind: 'value',\n value: valueProvider.value,\n });\n }\n }\n }\n\n #claimValues(): void {\n for (const registration of this.#registry.values()) {\n if (registration.kind === 'value' && registration.dispose) {\n this.#owned.push({ dispose: registration.dispose, value: registration.value });\n }\n }\n }\n\n #lookup<T>(token: Token<T>): { owner: ContainerImpl; registration: Registration<T> } | undefined {\n const local = this.#registry.get(token) as Registration<T> | undefined;\n\n if (local) return { owner: this, registration: local };\n\n if (!this.#parent) return undefined;\n\n return this.#parent.#lookup(token);\n }\n\n #factories(): { owner: ContainerImpl; registration: FactoryRegistration; token: Token<unknown> }[] {\n const parentFactories = this.#parent ? this.#parent.#factories() : [];\n const localFactories = [...this.#registry].flatMap(([token, registration]) =>\n registration.kind === 'factory' ? [{ owner: this, registration, token }] : [],\n );\n\n return [...parentFactories, ...localFactories];\n }\n\n #validateGraph(): void {\n for (const { owner, registration, token } of this.#factories()) {\n owner.#validatePath(token, registration, new Set(), []);\n }\n }\n\n #validatePath(\n token: Token<unknown>,\n registration: FactoryRegistration,\n visiting: Set<Token<unknown>>,\n path: Token<unknown>[],\n ): void {\n if (visiting.has(token)) throw new ConduitCircularDependencyError([...path, token]);\n\n visiting.add(token);\n\n for (const dependency of registration.dependencies) {\n const found = this.#lookup(dependency);\n\n if (!found) throw new ConduitProviderNotFoundError(dependency, this.name);\n\n if (found.registration.kind === 'factory') {\n if (registration.lifetime === 'singleton' && found.registration.lifetime === 'transient') {\n throw new ConduitError(\n `Singleton \"${token.description ?? 'anonymous'}\" cannot depend on a transient factory`,\n );\n }\n if (registration.lifetime === 'singleton' && typeof found.registration.lifetime === 'symbol') {\n throw new ConduitScopedResolutionError(token, found.registration.lifetime);\n }\n if (\n typeof registration.lifetime === 'symbol' &&\n typeof found.registration.lifetime === 'symbol' &&\n registration.lifetime !== found.registration.lifetime\n ) {\n throw new ConduitScopedResolutionError(token, found.registration.lifetime);\n }\n\n found.owner.#validatePath(dependency, found.registration, visiting, [...path, token]);\n }\n }\n\n visiting.delete(token);\n }\n\n async #resolve<T>(token: Token<T>, path: Token<unknown>[]): Promise<T> {\n if (path.includes(token)) throw new ConduitCircularDependencyError([...path, token]);\n\n const found = this.#lookup(token);\n\n if (!found) throw new ConduitProviderNotFoundError(token, this.name);\n\n const registration = found.registration;\n\n if (registration.kind === 'value') return registration.value as T;\n\n const owner = this.#ownerFor(found.owner, registration, token);\n\n if (registration.lifetime === 'transient') {\n return owner.#track(owner.#create(registration, owner, [...path, token])) as Promise<T>;\n }\n\n const existing = owner.#cache.get(registration);\n\n if (existing?.resolved) return existing.value as T;\n if (existing) return existing.promise as Promise<T>;\n\n const entry = { promise: Promise.resolve(), resolved: false } as CacheEntry;\n const creation = owner.#create(registration, owner, [...path, token]).then(\n (value) => {\n entry.resolved = true;\n entry.value = value;\n return value;\n },\n (error) => {\n if (owner.#cache.get(registration) === entry) owner.#cache.delete(registration);\n throw error;\n },\n );\n\n entry.promise = owner.#track(creation);\n owner.#cache.set(registration, entry);\n\n return entry.promise as Promise<T>;\n }\n\n #ownerFor(owner: ContainerImpl, registration: FactoryRegistration, token: Token<unknown>): ContainerImpl {\n if (registration.lifetime === 'singleton') return owner;\n if (registration.lifetime === 'transient') return this;\n\n const scopeOwner = this.#scopeOwner(registration.lifetime as ScopeToken);\n\n if (!scopeOwner) throw new ConduitScopedResolutionError(token, registration.lifetime as ScopeToken);\n\n return scopeOwner;\n }\n\n #scopeOwner(scope: ScopeToken): ContainerImpl | undefined {\n if (this.#scope === scope) return this;\n\n return this.#parent ? this.#parent.#scopeOwner(scope) : undefined;\n }\n\n #track<T>(promise: Promise<T>): Promise<T> {\n this.#inFlight.add(promise);\n void promise.then(\n () => this.#inFlight.delete(promise),\n () => this.#inFlight.delete(promise),\n );\n return promise;\n }\n\n async #create(registration: FactoryRegistration, owner: ContainerImpl, path: Token<unknown>[]): Promise<unknown> {\n const value = await Promise.all(\n registration.dependencies.map((dependency) => owner.#resolve(dependency, path)),\n ).then((dependencies) => registration.factory(...dependencies));\n\n if (owner.#lifecycle !== 'active') {\n if (registration.dispose) {\n try {\n await registration.dispose(value);\n } catch (error) {\n owner.#cleanupFailures.push(error);\n }\n }\n\n throw new ConduitDisposedError(owner.name);\n }\n\n if (registration.dispose) owner.#owned.push({ dispose: registration.dispose, value });\n\n return value;\n }\n}\n\nexport function createContainer(\n providers: readonly Provider<any, any>[],\n options?: { readonly name?: string },\n): Container {\n return new ContainerImpl(undefined, providers, { name: options?.name });\n}\n"],"mappings":"yDA2CA,IAAM,EAAN,MAAM,CAAmC,CACvC,GAAS,IAAI,IACb,GAAY,IAAI,IAChB,GAA8B,CAAC,EAC/B,GAAsB,IAAI,gBAC1B,GAAY,IAAI,IAChB,GAAwB,SACxB,GACA,GAA0B,CAAC,EAC3B,GACA,GAAY,IAAI,IAChB,GACA,KAEA,YACE,EACA,EACA,EACA,CACA,KAAK,GAAU,EACf,KAAK,GAAS,EAAQ,MAElB,GAAQ,EAAO,GAAU,IAAI,IAAI,EAErC,KAAK,KAAO,EAAQ,OAAS,EAAS,GAAG,EAAO,KAAK,GAAG,EAAQ,OAAO,aAAe,UAAY,QAClG,KAAK,GAAU,IAAI,EAAA,oBAAqB,CAAE,KAAM,QAAS,MAAO,KAAK,cAAe,CAAC,EAErF,GAAI,CACF,KAAK,GAAmB,CAAS,EACjC,KAAK,GAAe,EACpB,KAAK,GAAa,CACpB,OAAS,EAAO,CAGd,MAFI,GAAQ,EAAO,GAAU,OAAO,IAAI,EACxC,KAAK,GAAU,MAAM,EACf,CACR,CACF,CAEA,IAAI,gBAA8B,CAChC,OAAO,KAAK,GAAoB,MAClC,CAEA,IAAI,UAAoB,CACtB,OAAO,KAAK,KAAe,UAC7B,CAEA,IAAO,EAA0B,CAG/B,OAFA,KAAK,GAAc,EAEZ,KAAK,GAAQ,CAAK,IAAM,IAAA,EACjC,CAIA,MAAM,QAAiC,EAAoD,CAGzF,GA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EAC1D,CAEA,GAAU,EAAiC,CAMzC,OALA,KAAK,GAAU,IAAI,CAAO,EAC1B,EAAa,SACL,KAAK,GAAU,OAAO,CAAO,MAC7B,KAAK,GAAU,OAAO,CAAO,CACrC,EACO,CACT,CAEA,KAAM,GAAQ,EAAmC,EAAsB,EAA0C,CAC/G,IAAM,EAAQ,MAAM,QAAQ,IAC1B,EAAa,aAAa,IAAK,GAAe,EAAM,GAAS,EAAY,CAAI,CAAC,CAChF,CAAC,CAAC,KAAM,GAAiB,EAAa,QAAQ,GAAG,CAAY,CAAC,EAE9D,GAAI,EAAM,KAAe,SAAU,CACjC,GAAI,EAAa,QACf,GAAI,CACF,MAAM,EAAa,QAAQ,CAAK,CAClC,OAAS,EAAO,CACd,EAAM,GAAiB,KAAK,CAAK,CACnC,CAGF,MAAM,IAAI,EAAA,qBAAqB,EAAM,IAAI,CAC3C,CAIA,OAFI,EAAa,SAAS,EAAM,GAAO,KAAK,CAAE,QAAS,EAAa,QAAS,OAAM,CAAC,EAE7E,CACT,CACF,EAEA,SAAgB,EACd,EACA,EACW,CACX,OAAO,IAAI,EAAc,IAAA,GAAW,EAAW,CAAE,KAAM,GAAS,IAAK,CAAC,CACxE"}
|
|
1
|
+
{"version":3,"file":"container.cjs","names":[],"sources":["../src/container.ts"],"sourcesContent":["import {\n ConduitCircularDependencyError,\n ConduitDisposedError,\n ConduitDisposeError,\n ConduitDuplicateRegistrationError,\n ConduitError,\n ConduitProviderNotFoundError,\n} from './errors.js';\nimport type {\n AnyProvider,\n Container,\n CreateScopeOptions,\n FactoryProvider,\n InferServices,\n Lifetime,\n Provider,\n ServiceMap,\n Token,\n ValueProvider,\n} from './types.js';\nimport { disposalSignalToken } from './types.js';\n\ntype Disposer = (value: unknown) => Promise<void> | void;\n\ntype ValueRegistration<T> = Readonly<{\n dispose?: Disposer;\n kind: 'value';\n value: T;\n}>;\n\ntype FactoryRegistration<T = unknown> = Readonly<{\n factory: (...values: unknown[]) => Promise<T> | T;\n dependencies: readonly Token<unknown>[];\n dispose?: Disposer;\n kind: 'factory';\n lifetime: Lifetime;\n}>;\n\ntype Registration<T = unknown> = FactoryRegistration<T> | ValueRegistration<T>;\ntype OwnedResource = Readonly<{ dispose?: Disposer; value: unknown }>;\ntype CacheEntry = { promise: Promise<unknown>; resolved: boolean; value?: unknown };\ntype Lifecycle = 'active' | 'disposed' | 'disposing';\n\nclass ContainerImpl implements Container {\n #cache = new Map<FactoryRegistration<unknown>, CacheEntry>();\n #children = new Set<ContainerImpl>();\n #cleanupFailures: unknown[] = [];\n #disposalController = new AbortController();\n #inFlight = new Set<Promise<unknown>>();\n #lifecycle: Lifecycle = 'active';\n #disposePromise?: Promise<void>;\n #owned: OwnedResource[] = [];\n #parent?: ContainerImpl;\n #registry = new Map<Token<unknown>, Registration<unknown>>();\n readonly name: string;\n\n constructor(parent: ContainerImpl | undefined, providers: readonly AnyProvider[], options: CreateScopeOptions) {\n this.#parent = parent;\n\n if (parent) parent.#children.add(this);\n\n this.name = options.name ?? (parent ? `${parent.name}:child` : 'root');\n this.#registry.set(disposalSignalToken, { kind: 'value', value: this.disposalSignal });\n\n try {\n this.#registerProviders(providers);\n this.#validateGraph();\n this.#claimValues();\n } catch (error) {\n if (parent) parent.#children.delete(this);\n this.#registry.clear();\n throw error;\n }\n }\n\n get disposalSignal(): AbortSignal {\n return this.#disposalController.signal;\n }\n\n get disposed(): boolean {\n return this.#lifecycle === 'disposed';\n }\n\n has<T>(token: Token<T>): boolean {\n this.#assertActive();\n\n return this.#lookup(token) !== undefined;\n }\n\n resolve<T>(token: Token<T>): Promise<T>;\n resolve<M extends ServiceMap>(map: M): Promise<InferServices<M>>;\n async resolve<T, M extends ServiceMap>(input: Token<T> | M): Promise<InferServices<M> | T> {\n this.#assertActive();\n\n if (typeof input === 'symbol') return this.#resolve(input, []);\n if (typeof input !== 'object' || input === null || Array.isArray(input)) {\n throw new ConduitError('resolve() requires a token or service map');\n }\n\n const entries = Object.keys(input) as (keyof M & string)[];\n const values = await Promise.all(entries.map((key) => this.#resolve(input[key] as Token<unknown>, [])));\n const services = {} as InferServices<M>;\n\n entries.forEach((key, index) => {\n Object.defineProperty(services, key, {\n configurable: true,\n enumerable: true,\n value: values[index],\n writable: true,\n });\n });\n\n return services;\n }\n\n createScope(options: CreateScopeOptions = {}): Container {\n this.#assertActive();\n\n return new ContainerImpl(this, options.providers ?? [], { name: options.name });\n }\n\n dispose(): Promise<void> {\n if (this.#lifecycle === 'disposed') return Promise.resolve();\n\n if (this.#disposePromise) return this.#disposePromise;\n\n this.#lifecycle = 'disposing';\n this.#disposalController.abort();\n this.#disposePromise = this.#finishDisposal();\n\n return this.#disposePromise;\n }\n\n async [Symbol.asyncDispose](): Promise<void> {\n await this.dispose();\n }\n\n async #finishDisposal(): Promise<void> {\n const childOutcomes = await Promise.allSettled([...this.#children].map((child) => child.dispose()));\n\n await Promise.allSettled([...this.#inFlight]);\n\n const failures = [\n ...this.#cleanupFailures,\n ...childOutcomes.flatMap((outcome) => {\n if (outcome.status !== 'rejected') return [];\n\n return outcome.reason instanceof ConduitDisposeError ? outcome.reason.errors : [outcome.reason];\n }),\n ];\n\n for (const resource of [...this.#owned].reverse()) {\n if (!resource.dispose) continue;\n\n try {\n await resource.dispose(resource.value);\n } catch (error) {\n failures.push(error);\n }\n }\n\n this.#cache.clear();\n this.#children.clear();\n this.#cleanupFailures = [];\n this.#owned = [];\n this.#registry.clear();\n\n if (this.#parent) this.#parent.#children.delete(this);\n\n this.#lifecycle = 'disposed';\n\n if (failures.length) throw new ConduitDisposeError(failures);\n }\n\n #assertActive(): void {\n if (this.#lifecycle !== 'active') throw new ConduitDisposedError(this.name);\n }\n\n #assertUnregistered(token: Token<unknown>): void {\n if (this.#registry.has(token)) throw new ConduitDuplicateRegistrationError(token);\n }\n\n #registerProviders(providers: readonly AnyProvider[]): void {\n if (!Array.isArray(providers)) throw new ConduitError('Container providers must be an array');\n\n for (const input of providers) {\n if (typeof input !== 'object' || input === null || Array.isArray(input)) {\n throw new ConduitError('Each provider must be an object');\n }\n\n const provider = input as Provider;\n const hasDependencies = Object.hasOwn(provider, 'dependencies');\n const hasFactory = Object.hasOwn(provider, 'factory');\n const hasValue = Object.hasOwn(provider, 'value');\n\n if (typeof provider.token !== 'symbol') throw new ConduitError('Each provider requires a token');\n if (provider.dispose !== undefined && typeof provider.dispose !== 'function') {\n throw new ConduitError(`Provider \"${provider.token.description ?? 'anonymous'}\" has an invalid disposer`);\n }\n if (\n hasValue === hasFactory ||\n hasValue === hasDependencies ||\n (hasValue && Object.hasOwn(provider, 'lifetime'))\n ) {\n throw new ConduitError(\n `Provider \"${provider.token.description ?? 'anonymous'}\" must define exactly one value or factory`,\n );\n }\n\n this.#assertUnregistered(provider.token);\n\n if (hasFactory) {\n const factory = provider as FactoryProvider<unknown>;\n\n if (\n !Array.isArray(factory.dependencies) ||\n factory.dependencies.some((dependency) => typeof dependency !== 'symbol')\n ) {\n throw new ConduitError(\n `Factory provider \"${provider.token.description ?? 'anonymous'}\" has invalid dependencies`,\n );\n }\n if (typeof factory.factory !== 'function') {\n throw new ConduitError(`Factory provider \"${provider.token.description ?? 'anonymous'}\" requires a factory`);\n }\n if (factory.lifetime !== undefined && factory.lifetime !== 'singleton' && factory.lifetime !== 'transient') {\n throw new ConduitError(\n `Factory provider \"${provider.token.description ?? 'anonymous'}\" has an invalid lifetime`,\n );\n }\n\n this.#registry.set(provider.token, {\n dependencies: Object.freeze([...factory.dependencies]),\n dispose: factory.dispose as Disposer | undefined,\n factory: factory.factory as (...values: unknown[]) => Promise<unknown> | unknown,\n kind: 'factory',\n lifetime: factory.lifetime ?? 'singleton',\n });\n } else {\n const valueProvider = provider as ValueProvider<unknown>;\n\n this.#registry.set(provider.token, {\n dispose: valueProvider.dispose as Disposer | undefined,\n kind: 'value',\n value: valueProvider.value,\n });\n }\n }\n }\n\n #claimValues(): void {\n for (const registration of this.#registry.values()) {\n if (registration.kind === 'value' && registration.dispose) {\n this.#owned.push({ dispose: registration.dispose, value: registration.value });\n }\n }\n }\n\n #lookup<T>(token: Token<T>): { owner: ContainerImpl; registration: Registration<T> } | undefined {\n const local = this.#registry.get(token) as Registration<T> | undefined;\n\n if (local) return { owner: this, registration: local };\n\n if (!this.#parent) return undefined;\n\n return this.#parent.#lookup(token);\n }\n\n #factories(): { owner: ContainerImpl; registration: FactoryRegistration; token: Token<unknown> }[] {\n const parentFactories = this.#parent ? this.#parent.#factories() : [];\n const localFactories = [...this.#registry].flatMap(([token, registration]) =>\n registration.kind === 'factory' ? [{ owner: this, registration, token }] : [],\n );\n\n return [...parentFactories, ...localFactories];\n }\n\n #validateGraph(): void {\n for (const { owner, registration, token } of this.#factories()) {\n owner.#validatePath(token, registration, new Set(), []);\n }\n }\n\n #validatePath(\n token: Token<unknown>,\n registration: FactoryRegistration,\n visiting: Set<Token<unknown>>,\n path: Token<unknown>[],\n ): void {\n if (visiting.has(token)) throw new ConduitCircularDependencyError([...path, token]);\n\n visiting.add(token);\n\n for (const dependency of registration.dependencies) {\n const found = this.#lookup(dependency);\n\n if (!found) throw new ConduitProviderNotFoundError(dependency, this.name);\n\n if (found.registration.kind === 'factory') {\n if (registration.lifetime === 'singleton' && found.registration.lifetime === 'transient') {\n throw new ConduitError(\n `Singleton \"${token.description ?? 'anonymous'}\" cannot depend on a transient factory`,\n );\n }\n\n found.owner.#validatePath(dependency, found.registration, visiting, [...path, token]);\n }\n }\n\n visiting.delete(token);\n }\n\n async #resolve<T>(token: Token<T>, path: Token<unknown>[]): Promise<T> {\n if (path.includes(token)) throw new ConduitCircularDependencyError([...path, token]);\n\n const found = this.#lookup(token);\n\n if (!found) throw new ConduitProviderNotFoundError(token, this.name);\n\n const registration = found.registration;\n\n if (registration.kind === 'value') return registration.value as T;\n\n if (registration.lifetime === 'transient') {\n return this.#track(this.#create(registration, this, [...path, token])) as Promise<T>;\n }\n\n const owner = found.owner;\n const existing = owner.#cache.get(registration);\n\n if (existing?.resolved) return existing.value as T;\n if (existing) return existing.promise as Promise<T>;\n\n const entry = { promise: Promise.resolve(), resolved: false } as CacheEntry;\n const creation = owner.#create(registration, owner, [...path, token]).then(\n (value) => {\n entry.resolved = true;\n entry.value = value;\n return value;\n },\n (error) => {\n if (owner.#cache.get(registration) === entry) owner.#cache.delete(registration);\n throw error;\n },\n );\n\n entry.promise = owner.#track(creation);\n owner.#cache.set(registration, entry);\n\n return entry.promise as Promise<T>;\n }\n\n #track<T>(promise: Promise<T>): Promise<T> {\n this.#inFlight.add(promise);\n void promise.then(\n () => this.#inFlight.delete(promise),\n () => this.#inFlight.delete(promise),\n );\n return promise;\n }\n\n async #create(registration: FactoryRegistration, owner: ContainerImpl, path: Token<unknown>[]): Promise<unknown> {\n const value = await Promise.all(\n registration.dependencies.map((dependency) => owner.#resolve(dependency, path)),\n ).then((dependencies) => registration.factory(...dependencies));\n\n if (owner.#lifecycle !== 'active') {\n if (registration.dispose) {\n try {\n await registration.dispose(value);\n } catch (error) {\n owner.#cleanupFailures.push(error);\n }\n }\n\n throw new ConduitDisposedError(owner.name);\n }\n\n if (registration.dispose) owner.#owned.push({ dispose: registration.dispose, value });\n\n return value;\n }\n}\n\nexport function createContainer(providers: readonly AnyProvider[], options?: { readonly name?: string }): Container {\n return new ContainerImpl(undefined, providers, { name: options?.name });\n}\n"],"mappings":"yDA2CA,IAAM,EAAN,MAAM,aAAmC,CACvC,GAAS,IAAI,IACb,GAAY,IAAI,IAChB,GAA8B,CAAC,EAC/B,GAAsB,IAAI,gBAC1B,GAAY,IAAI,IAChB,GAAwB,SACxB,GACA,GAA0B,CAAC,EAC3B,GACA,GAAY,IAAI,IAChB,KAEA,YAAY,EAAmC,EAAmC,EAA6B,CAC7G,KAAK,GAAU,EAEX,GAAQ,EAAO,GAAU,IAAI,IAAI,EAErC,KAAK,KAAO,EAAQ,OAAS,EAAS,GAAG,EAAO,KAAK,QAAU,QAC/D,KAAK,GAAU,IAAI,EAAA,oBAAqB,CAAE,KAAM,QAAS,MAAO,KAAK,cAAe,CAAC,E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EAAQ,MAAM,QAAQ,IAC1B,EAAa,aAAa,IAAK,GAAe,EAAM,GAAS,EAAY,CAAI,CAAC,CAChF,CAAC,CAAC,KAAM,GAAiB,EAAa,QAAQ,GAAG,CAAY,CAAC,EAE9D,GAAI,EAAM,KAAe,SAAU,CACjC,GAAI,EAAa,QACf,GAAI,CACF,MAAM,EAAa,QAAQ,CAAK,CAClC,OAAS,EAAO,CACd,EAAM,GAAiB,KAAK,CAAK,CACnC,CAGF,MAAM,IAAI,EAAA,qBAAqB,EAAM,IAAI,CAC3C,CAIA,OAFI,EAAa,SAAS,EAAM,GAAO,KAAK,CAAE,QAAS,EAAa,QAAS,OAAM,CAAC,EAE7E,CACT,CACF,EAEA,SAAgB,gBAAgB,EAAmC,EAAiD,CAClH,OAAO,IAAI,EAAc,IAAA,GAAW,EAAW,CAAE,KAAM,GAAS,IAAK,CAAC,CACxE"}
|
package/dist/container.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
export declare function createContainer(providers: readonly
|
|
1
|
+
import type { AnyProvider, Container } from './types.js';
|
|
2
|
+
export declare function createContainer(providers: readonly AnyProvider[], options?: {
|
|
3
3
|
readonly name?: string;
|
|
4
4
|
}): Container;
|
|
5
5
|
//# sourceMappingURL=container.d.ts.map
|
package/dist/container.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"container.d.ts","sourceRoot":"","sources":["../src/container.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"container.d.ts","sourceRoot":"","sources":["../src/container.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EACV,WAAW,EACX,SAAS,EASV,MAAM,YAAY,CAAC;AA6WpB,wBAAgB,eAAe,CAAC,SAAS,EAAE,SAAS,WAAW,EAAE,EAAE,OAAO,CAAC,EAAE;IAAE,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,CAElH"}
|
package/dist/container.js
CHANGED
|
@@ -1,202 +1,2 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { disposalSignalToken as s } from "./types.js";
|
|
3
|
-
//#region src/container.ts
|
|
4
|
-
var c = class c {
|
|
5
|
-
#e = /* @__PURE__ */ new Map();
|
|
6
|
-
#t = /* @__PURE__ */ new Set();
|
|
7
|
-
#n = [];
|
|
8
|
-
#r = new AbortController();
|
|
9
|
-
#i = /* @__PURE__ */ new Set();
|
|
10
|
-
#a = "active";
|
|
11
|
-
#o;
|
|
12
|
-
#s = [];
|
|
13
|
-
#c;
|
|
14
|
-
#l = /* @__PURE__ */ new Map();
|
|
15
|
-
#u;
|
|
16
|
-
name;
|
|
17
|
-
constructor(e, t, n) {
|
|
18
|
-
this.#c = e, this.#u = n.scope, e && e.#t.add(this), this.name = n.name ?? (e ? `${e.name}:${n.scope?.description ?? "child"}` : "root"), this.#l.set(s, {
|
|
19
|
-
kind: "value",
|
|
20
|
-
value: this.disposalSignal
|
|
21
|
-
});
|
|
22
|
-
try {
|
|
23
|
-
this.#m(t), this.#v(), this.#h();
|
|
24
|
-
} catch (t) {
|
|
25
|
-
throw e && e.#t.delete(this), this.#l.clear(), t;
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
|
-
get disposalSignal() {
|
|
29
|
-
return this.#r.signal;
|
|
30
|
-
}
|
|
31
|
-
get disposed() {
|
|
32
|
-
return this.#a === "disposed";
|
|
33
|
-
}
|
|
34
|
-
has(e) {
|
|
35
|
-
return this.#f(), this.#g(e) !== void 0;
|
|
36
|
-
}
|
|
37
|
-
async resolve(e) {
|
|
38
|
-
if (this.#f(), typeof e == "symbol") return this.#b(e, []);
|
|
39
|
-
if (typeof e != "object" || !e || Array.isArray(e)) throw new i("resolve() requires a token or service map");
|
|
40
|
-
let t = Object.keys(e), n = await Promise.all(t.map((t) => this.#b(e[t], []))), r = {};
|
|
41
|
-
return t.forEach((e, t) => {
|
|
42
|
-
Object.defineProperty(r, e, {
|
|
43
|
-
configurable: !0,
|
|
44
|
-
enumerable: !0,
|
|
45
|
-
value: n[t],
|
|
46
|
-
writable: !0
|
|
47
|
-
});
|
|
48
|
-
}), r;
|
|
49
|
-
}
|
|
50
|
-
createScope(e, t) {
|
|
51
|
-
return this.#f(), new c(this, t?.providers ?? [], {
|
|
52
|
-
name: t?.name,
|
|
53
|
-
scope: e
|
|
54
|
-
});
|
|
55
|
-
}
|
|
56
|
-
dispose() {
|
|
57
|
-
return this.#a === "disposed" ? Promise.resolve() : this.#o ? this.#o : (this.#a = "disposing", this.#r.abort(), this.#o = this.#d(), this.#o);
|
|
58
|
-
}
|
|
59
|
-
async [Symbol.asyncDispose]() {
|
|
60
|
-
await this.dispose();
|
|
61
|
-
}
|
|
62
|
-
async #d() {
|
|
63
|
-
let e = await Promise.allSettled([...this.#t].map((e) => e.dispose()));
|
|
64
|
-
await Promise.allSettled([...this.#i]);
|
|
65
|
-
let n = [...this.#n, ...e.flatMap((e) => e.status === "rejected" ? e.reason instanceof t ? e.reason.errors : [e.reason] : [])];
|
|
66
|
-
for (let e of [...this.#s].reverse()) if (e.dispose) try {
|
|
67
|
-
await e.dispose(e.value);
|
|
68
|
-
} catch (e) {
|
|
69
|
-
n.push(e);
|
|
70
|
-
}
|
|
71
|
-
if (this.#e.clear(), this.#t.clear(), this.#n = [], this.#s = [], this.#l.clear(), this.#c && this.#c.#t.delete(this), this.#a = "disposed", n.length) throw new t(n);
|
|
72
|
-
}
|
|
73
|
-
#f() {
|
|
74
|
-
if (this.#a !== "active") throw new n(this.name);
|
|
75
|
-
}
|
|
76
|
-
#p(e) {
|
|
77
|
-
if (this.#l.has(e)) throw new r(e);
|
|
78
|
-
}
|
|
79
|
-
#m(e) {
|
|
80
|
-
if (!Array.isArray(e)) throw new i("Container providers must be an array");
|
|
81
|
-
for (let t of e) {
|
|
82
|
-
if (typeof t != "object" || !t || Array.isArray(t)) throw new i("Each provider must be an object");
|
|
83
|
-
let e = t, n = Object.hasOwn(e, "dependencies"), r = Object.hasOwn(e, "factory"), a = Object.hasOwn(e, "value");
|
|
84
|
-
if (typeof e.token != "symbol") throw new i("Each provider requires a token");
|
|
85
|
-
if (e.dispose !== void 0 && typeof e.dispose != "function") throw new i(`Provider "${e.token.description ?? "anonymous"}" has an invalid disposer`);
|
|
86
|
-
if (a === r || a === n || a && Object.hasOwn(e, "lifetime")) throw new i(`Provider "${e.token.description ?? "anonymous"}" must define exactly one value or factory`);
|
|
87
|
-
if (this.#p(e.token), r) {
|
|
88
|
-
let t = e;
|
|
89
|
-
if (!Array.isArray(t.dependencies) || t.dependencies.some((e) => typeof e != "symbol")) throw new i(`Factory provider "${e.token.description ?? "anonymous"}" has invalid dependencies`);
|
|
90
|
-
if (typeof t.factory != "function") throw new i(`Factory provider "${e.token.description ?? "anonymous"}" requires a factory`);
|
|
91
|
-
if (t.lifetime !== void 0 && t.lifetime !== "singleton" && t.lifetime !== "transient" && typeof t.lifetime != "symbol") throw new i(`Factory provider "${e.token.description ?? "anonymous"}" has an invalid lifetime`);
|
|
92
|
-
this.#l.set(e.token, {
|
|
93
|
-
dependencies: Object.freeze([...t.dependencies]),
|
|
94
|
-
dispose: t.dispose,
|
|
95
|
-
factory: t.factory,
|
|
96
|
-
kind: "factory",
|
|
97
|
-
lifetime: t.lifetime ?? "singleton"
|
|
98
|
-
});
|
|
99
|
-
} else {
|
|
100
|
-
let t = e;
|
|
101
|
-
this.#l.set(e.token, {
|
|
102
|
-
dispose: t.dispose,
|
|
103
|
-
kind: "value",
|
|
104
|
-
value: t.value
|
|
105
|
-
});
|
|
106
|
-
}
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
#h() {
|
|
110
|
-
for (let e of this.#l.values()) e.kind === "value" && e.dispose && this.#s.push({
|
|
111
|
-
dispose: e.dispose,
|
|
112
|
-
value: e.value
|
|
113
|
-
});
|
|
114
|
-
}
|
|
115
|
-
#g(e) {
|
|
116
|
-
let t = this.#l.get(e);
|
|
117
|
-
if (t) return {
|
|
118
|
-
owner: this,
|
|
119
|
-
registration: t
|
|
120
|
-
};
|
|
121
|
-
if (this.#c) return this.#c.#g(e);
|
|
122
|
-
}
|
|
123
|
-
#_() {
|
|
124
|
-
let e = this.#c ? this.#c.#_() : [], t = [...this.#l].flatMap(([e, t]) => t.kind === "factory" ? [{
|
|
125
|
-
owner: this,
|
|
126
|
-
registration: t,
|
|
127
|
-
token: e
|
|
128
|
-
}] : []);
|
|
129
|
-
return [...e, ...t];
|
|
130
|
-
}
|
|
131
|
-
#v() {
|
|
132
|
-
for (let { owner: e, registration: t, token: n } of this.#_()) e.#y(n, t, /* @__PURE__ */ new Set(), []);
|
|
133
|
-
}
|
|
134
|
-
#y(t, n, r, s) {
|
|
135
|
-
if (r.has(t)) throw new e([...s, t]);
|
|
136
|
-
r.add(t);
|
|
137
|
-
for (let e of n.dependencies) {
|
|
138
|
-
let c = this.#g(e);
|
|
139
|
-
if (!c) throw new a(e, this.name);
|
|
140
|
-
if (c.registration.kind === "factory") {
|
|
141
|
-
if (n.lifetime === "singleton" && c.registration.lifetime === "transient") throw new i(`Singleton "${t.description ?? "anonymous"}" cannot depend on a transient factory`);
|
|
142
|
-
if (n.lifetime === "singleton" && typeof c.registration.lifetime == "symbol" || typeof n.lifetime == "symbol" && typeof c.registration.lifetime == "symbol" && n.lifetime !== c.registration.lifetime) throw new o(t, c.registration.lifetime);
|
|
143
|
-
c.owner.#y(e, c.registration, r, [...s, t]);
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
r.delete(t);
|
|
147
|
-
}
|
|
148
|
-
async #b(t, n) {
|
|
149
|
-
if (n.includes(t)) throw new e([...n, t]);
|
|
150
|
-
let r = this.#g(t);
|
|
151
|
-
if (!r) throw new a(t, this.name);
|
|
152
|
-
let i = r.registration;
|
|
153
|
-
if (i.kind === "value") return i.value;
|
|
154
|
-
let o = this.#x(r.owner, i, t);
|
|
155
|
-
if (i.lifetime === "transient") return o.#C(o.#w(i, o, [...n, t]));
|
|
156
|
-
let s = o.#e.get(i);
|
|
157
|
-
if (s?.resolved) return s.value;
|
|
158
|
-
if (s) return s.promise;
|
|
159
|
-
let c = {
|
|
160
|
-
promise: Promise.resolve(),
|
|
161
|
-
resolved: !1
|
|
162
|
-
}, l = o.#w(i, o, [...n, t]).then((e) => (c.resolved = !0, c.value = e, e), (e) => {
|
|
163
|
-
throw o.#e.get(i) === c && o.#e.delete(i), e;
|
|
164
|
-
});
|
|
165
|
-
return c.promise = o.#C(l), o.#e.set(i, c), c.promise;
|
|
166
|
-
}
|
|
167
|
-
#x(e, t, n) {
|
|
168
|
-
if (t.lifetime === "singleton") return e;
|
|
169
|
-
if (t.lifetime === "transient") return this;
|
|
170
|
-
let r = this.#S(t.lifetime);
|
|
171
|
-
if (!r) throw new o(n, t.lifetime);
|
|
172
|
-
return r;
|
|
173
|
-
}
|
|
174
|
-
#S(e) {
|
|
175
|
-
return this.#u === e ? this : this.#c ? this.#c.#S(e) : void 0;
|
|
176
|
-
}
|
|
177
|
-
#C(e) {
|
|
178
|
-
return this.#i.add(e), e.then(() => this.#i.delete(e), () => this.#i.delete(e)), e;
|
|
179
|
-
}
|
|
180
|
-
async #w(e, t, r) {
|
|
181
|
-
let i = await Promise.all(e.dependencies.map((e) => t.#b(e, r))).then((t) => e.factory(...t));
|
|
182
|
-
if (t.#a !== "active") {
|
|
183
|
-
if (e.dispose) try {
|
|
184
|
-
await e.dispose(i);
|
|
185
|
-
} catch (e) {
|
|
186
|
-
t.#n.push(e);
|
|
187
|
-
}
|
|
188
|
-
throw new n(t.name);
|
|
189
|
-
}
|
|
190
|
-
return e.dispose && t.#s.push({
|
|
191
|
-
dispose: e.dispose,
|
|
192
|
-
value: i
|
|
193
|
-
}), i;
|
|
194
|
-
}
|
|
195
|
-
};
|
|
196
|
-
function l(e, t) {
|
|
197
|
-
return new c(void 0, e, { name: t?.name });
|
|
198
|
-
}
|
|
199
|
-
//#endregion
|
|
200
|
-
export { l as createContainer };
|
|
201
|
-
|
|
1
|
+
import{ConduitCircularDependencyError as e,ConduitDisposeError as t,ConduitDisposedError as n,ConduitDuplicateRegistrationError as r,ConduitError as i,ConduitProviderNotFoundError as a}from"./errors.js";import{disposalSignalToken as o}from"./types.js";var s=class ContainerImpl{#e=new Map;#t=new Set;#n=[];#r=new AbortController;#i=new Set;#a=`active`;#o;#s=[];#c;#l=new Map;name;constructor(e,t,n){this.#c=e,e&&e.#t.add(this),this.name=n.name??(e?`${e.name}:child`:`root`),this.#l.set(o,{kind:`value`,value:this.disposalSignal});try{this.#p(t),this.#_(),this.#m()}catch(t){throw e&&e.#t.delete(this),this.#l.clear(),t}}get disposalSignal(){return this.#r.signal}get disposed(){return this.#a===`disposed`}has(e){return this.#d(),this.#h(e)!==void 0}async resolve(e){if(this.#d(),typeof e==`symbol`)return this.#y(e,[]);if(typeof e!=`object`||!e||Array.isArray(e))throw new i(`resolve() requires a token or service map`);let t=Object.keys(e),n=await Promise.all(t.map(t=>this.#y(e[t],[]))),r={};return t.forEach((e,t)=>{Object.defineProperty(r,e,{configurable:!0,enumerable:!0,value:n[t],writable:!0})}),r}createScope(e={}){return this.#d(),new ContainerImpl(this,e.providers??[],{name:e.name})}dispose(){return this.#a===`disposed`?Promise.resolve():this.#o?this.#o:(this.#a=`disposing`,this.#r.abort(),this.#o=this.#u(),this.#o)}async[Symbol.asyncDispose](){await this.dispose()}async#u(){let e=await Promise.allSettled([...this.#t].map(e=>e.dispose()));await Promise.allSettled([...this.#i]);let n=[...this.#n,...e.flatMap(e=>e.status===`rejected`?e.reason instanceof t?e.reason.errors:[e.reason]:[])];for(let e of[...this.#s].reverse())if(e.dispose)try{await e.dispose(e.value)}catch(e){n.push(e)}if(this.#e.clear(),this.#t.clear(),this.#n=[],this.#s=[],this.#l.clear(),this.#c&&this.#c.#t.delete(this),this.#a=`disposed`,n.length)throw new t(n)}#d(){if(this.#a!==`active`)throw new n(this.name)}#f(e){if(this.#l.has(e))throw new r(e)}#p(e){if(!Array.isArray(e))throw new i(`Container providers must be an array`);for(let t of e){if(typeof t!=`object`||!t||Array.isArray(t))throw new i(`Each provider must be an object`);let e=t,n=Object.hasOwn(e,`dependencies`),r=Object.hasOwn(e,`factory`),a=Object.hasOwn(e,`value`);if(typeof e.token!=`symbol`)throw new i(`Each provider requires a token`);if(e.dispose!==void 0&&typeof e.dispose!=`function`)throw new i(`Provider "${e.token.description??`anonymous`}" has an invalid disposer`);if(a===r||a===n||a&&Object.hasOwn(e,`lifetime`))throw new i(`Provider "${e.token.description??`anonymous`}" must define exactly one value or factory`);if(this.#f(e.token),r){let t=e;if(!Array.isArray(t.dependencies)||t.dependencies.some(e=>typeof e!=`symbol`))throw new i(`Factory provider "${e.token.description??`anonymous`}" has invalid dependencies`);if(typeof t.factory!=`function`)throw new i(`Factory provider "${e.token.description??`anonymous`}" requires a factory`);if(t.lifetime!==void 0&&t.lifetime!==`singleton`&&t.lifetime!==`transient`)throw new i(`Factory provider "${e.token.description??`anonymous`}" has an invalid lifetime`);this.#l.set(e.token,{dependencies:Object.freeze([...t.dependencies]),dispose:t.dispose,factory:t.factory,kind:`factory`,lifetime:t.lifetime??`singleton`})}else{let t=e;this.#l.set(e.token,{dispose:t.dispose,kind:`value`,value:t.value})}}}#m(){for(let e of this.#l.values())e.kind===`value`&&e.dispose&&this.#s.push({dispose:e.dispose,value:e.value})}#h(e){let t=this.#l.get(e);if(t)return{owner:this,registration:t};if(this.#c)return this.#c.#h(e)}#g(){let e=this.#c?this.#c.#g():[],t=[...this.#l].flatMap(([e,t])=>t.kind===`factory`?[{owner:this,registration:t,token:e}]:[]);return[...e,...t]}#_(){for(let{owner:e,registration:t,token:n}of this.#g())e.#v(n,t,new Set,[])}#v(t,n,r,o){if(r.has(t))throw new e([...o,t]);r.add(t);for(let e of n.dependencies){let s=this.#h(e);if(!s)throw new a(e,this.name);if(s.registration.kind===`factory`){if(n.lifetime===`singleton`&&s.registration.lifetime===`transient`)throw new i(`Singleton "${t.description??`anonymous`}" cannot depend on a transient factory`);s.owner.#v(e,s.registration,r,[...o,t])}}r.delete(t)}async#y(t,n){if(n.includes(t))throw new e([...n,t]);let r=this.#h(t);if(!r)throw new a(t,this.name);let i=r.registration;if(i.kind===`value`)return i.value;if(i.lifetime===`transient`)return this.#b(this.#x(i,this,[...n,t]));let o=r.owner,s=o.#e.get(i);if(s?.resolved)return s.value;if(s)return s.promise;let c={promise:Promise.resolve(),resolved:!1},l=o.#x(i,o,[...n,t]).then(e=>(c.resolved=!0,c.value=e,e),e=>{throw o.#e.get(i)===c&&o.#e.delete(i),e});return c.promise=o.#b(l),o.#e.set(i,c),c.promise}#b(e){return this.#i.add(e),e.then(()=>this.#i.delete(e),()=>this.#i.delete(e)),e}async#x(e,t,r){let i=await Promise.all(e.dependencies.map(e=>t.#y(e,r))).then(t=>e.factory(...t));if(t.#a!==`active`){if(e.dispose)try{await e.dispose(i)}catch(e){t.#n.push(e)}throw new n(t.name)}return e.dispose&&t.#s.push({dispose:e.dispose,value:i}),i}};function createContainer(e,t){return new s(void 0,e,{name:t?.name})}export{createContainer};
|
|
202
2
|
//# sourceMappingURL=container.js.map
|
package/dist/container.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"container.js","names":[],"sources":["../src/container.ts"],"sourcesContent":["import {\n ConduitCircularDependencyError,\n ConduitDisposedError,\n ConduitDisposeError,\n ConduitDuplicateRegistrationError,\n ConduitError,\n ConduitProviderNotFoundError,\n ConduitScopedResolutionError,\n} from './errors.js';\nimport type {\n Container,\n FactoryProvider,\n InferServices,\n Lifetime,\n Provider,\n ScopeToken,\n ServiceMap,\n Token,\n ValueProvider,\n} from './types.js';\nimport { disposalSignalToken } from './types.js';\n\ntype Disposer = (value: unknown) => Promise<void> | void;\n\ntype ValueRegistration<T> = Readonly<{\n dispose?: Disposer;\n kind: 'value';\n value: T;\n}>;\n\ntype FactoryRegistration<T = unknown> = Readonly<{\n factory: (...values: unknown[]) => Promise<T> | T;\n dependencies: readonly Token<unknown>[];\n dispose?: Disposer;\n kind: 'factory';\n lifetime: Lifetime;\n}>;\n\ntype Registration<T = unknown> = FactoryRegistration<T> | ValueRegistration<T>;\ntype OwnedResource = Readonly<{ dispose?: Disposer; value: unknown }>;\ntype CacheEntry = { promise: Promise<unknown>; resolved: boolean; value?: unknown };\ntype Lifecycle = 'active' | 'disposed' | 'disposing';\n\nclass ContainerImpl implements Container {\n #cache = new Map<FactoryRegistration<unknown>, CacheEntry>();\n #children = new Set<ContainerImpl>();\n #cleanupFailures: unknown[] = [];\n #disposalController = new AbortController();\n #inFlight = new Set<Promise<unknown>>();\n #lifecycle: Lifecycle = 'active';\n #disposePromise?: Promise<void>;\n #owned: OwnedResource[] = [];\n #parent?: ContainerImpl;\n #registry = new Map<Token<unknown>, Registration<unknown>>();\n #scope?: ScopeToken;\n readonly name: string;\n\n constructor(\n parent: ContainerImpl | undefined,\n providers: readonly Provider<any, any>[],\n options: { name?: string; scope?: ScopeToken },\n ) {\n this.#parent = parent;\n this.#scope = options.scope;\n\n if (parent) parent.#children.add(this);\n\n this.name = options.name ?? (parent ? `${parent.name}:${options.scope?.description ?? 'child'}` : 'root');\n this.#registry.set(disposalSignalToken, { kind: 'value', value: this.disposalSignal });\n\n try {\n this.#registerProviders(providers);\n this.#validateGraph();\n this.#claimValues();\n } catch (error) {\n if (parent) parent.#children.delete(this);\n this.#registry.clear();\n throw error;\n }\n }\n\n get disposalSignal(): AbortSignal {\n return this.#disposalController.signal;\n }\n\n get disposed(): boolean {\n return this.#lifecycle === 'disposed';\n }\n\n has<T>(token: Token<T>): boolean {\n this.#assertActive();\n\n return this.#lookup(token) !== undefined;\n }\n\n resolve<T>(token: Token<T>): Promise<T>;\n resolve<M extends ServiceMap>(map: M): Promise<InferServices<M>>;\n async resolve<T, M extends ServiceMap>(input: Token<T> | M): Promise<InferServices<M> | T> {\n this.#assertActive();\n\n if (typeof input === 'symbol') return this.#resolve(input, []);\n if (typeof input !== 'object' || input === null || Array.isArray(input)) {\n throw new ConduitError('resolve() requires a token or service map');\n }\n\n const entries = Object.keys(input) as (keyof M & string)[];\n const values = await Promise.all(entries.map((key) => this.#resolve(input[key] as Token<unknown>, [])));\n const services = {} as InferServices<M>;\n\n entries.forEach((key, index) => {\n Object.defineProperty(services, key, {\n configurable: true,\n enumerable: true,\n value: values[index],\n writable: true,\n });\n });\n\n return services;\n }\n\n createScope(\n scope?: ScopeToken,\n options?: { readonly name?: string; readonly providers?: readonly Provider<any, any>[] },\n ): Container {\n this.#assertActive();\n\n return new ContainerImpl(this, options?.providers ?? [], { name: options?.name, scope });\n }\n\n dispose(): Promise<void> {\n if (this.#lifecycle === 'disposed') return Promise.resolve();\n\n if (this.#disposePromise) return this.#disposePromise;\n\n this.#lifecycle = 'disposing';\n this.#disposalController.abort();\n this.#disposePromise = this.#finishDisposal();\n\n return this.#disposePromise;\n }\n\n async [Symbol.asyncDispose](): Promise<void> {\n await this.dispose();\n }\n\n async #finishDisposal(): Promise<void> {\n const childOutcomes = await Promise.allSettled([...this.#children].map((child) => child.dispose()));\n\n await Promise.allSettled([...this.#inFlight]);\n\n const failures = [\n ...this.#cleanupFailures,\n ...childOutcomes.flatMap((outcome) => {\n if (outcome.status !== 'rejected') return [];\n\n return outcome.reason instanceof ConduitDisposeError ? outcome.reason.errors : [outcome.reason];\n }),\n ];\n\n for (const resource of [...this.#owned].reverse()) {\n if (!resource.dispose) continue;\n\n try {\n await resource.dispose(resource.value);\n } catch (error) {\n failures.push(error);\n }\n }\n\n this.#cache.clear();\n this.#children.clear();\n this.#cleanupFailures = [];\n this.#owned = [];\n this.#registry.clear();\n\n if (this.#parent) this.#parent.#children.delete(this);\n\n this.#lifecycle = 'disposed';\n\n if (failures.length) throw new ConduitDisposeError(failures);\n }\n\n #assertActive(): void {\n if (this.#lifecycle !== 'active') throw new ConduitDisposedError(this.name);\n }\n\n #assertUnregistered(token: Token<unknown>): void {\n if (this.#registry.has(token)) throw new ConduitDuplicateRegistrationError(token);\n }\n\n #registerProviders(providers: readonly Provider<any, any>[]): void {\n if (!Array.isArray(providers)) throw new ConduitError('Container providers must be an array');\n\n for (const input of providers) {\n if (typeof input !== 'object' || input === null || Array.isArray(input)) {\n throw new ConduitError('Each provider must be an object');\n }\n\n const provider = input as Provider;\n const hasDependencies = Object.hasOwn(provider, 'dependencies');\n const hasFactory = Object.hasOwn(provider, 'factory');\n const hasValue = Object.hasOwn(provider, 'value');\n\n if (typeof provider.token !== 'symbol') throw new ConduitError('Each provider requires a token');\n if (provider.dispose !== undefined && typeof provider.dispose !== 'function') {\n throw new ConduitError(`Provider \"${provider.token.description ?? 'anonymous'}\" has an invalid disposer`);\n }\n if (\n hasValue === hasFactory ||\n hasValue === hasDependencies ||\n (hasValue && Object.hasOwn(provider, 'lifetime'))\n ) {\n throw new ConduitError(\n `Provider \"${provider.token.description ?? 'anonymous'}\" must define exactly one value or factory`,\n );\n }\n\n this.#assertUnregistered(provider.token);\n\n if (hasFactory) {\n const factory = provider as FactoryProvider<unknown>;\n\n if (\n !Array.isArray(factory.dependencies) ||\n factory.dependencies.some((dependency) => typeof dependency !== 'symbol')\n ) {\n throw new ConduitError(\n `Factory provider \"${provider.token.description ?? 'anonymous'}\" has invalid dependencies`,\n );\n }\n if (typeof factory.factory !== 'function') {\n throw new ConduitError(`Factory provider \"${provider.token.description ?? 'anonymous'}\" requires a factory`);\n }\n if (\n factory.lifetime !== undefined &&\n factory.lifetime !== 'singleton' &&\n factory.lifetime !== 'transient' &&\n typeof factory.lifetime !== 'symbol'\n ) {\n throw new ConduitError(\n `Factory provider \"${provider.token.description ?? 'anonymous'}\" has an invalid lifetime`,\n );\n }\n\n this.#registry.set(provider.token, {\n dependencies: Object.freeze([...factory.dependencies]),\n dispose: factory.dispose as Disposer | undefined,\n factory: factory.factory as (...values: unknown[]) => Promise<unknown> | unknown,\n kind: 'factory',\n lifetime: factory.lifetime ?? 'singleton',\n });\n } else {\n const valueProvider = provider as ValueProvider<unknown>;\n\n this.#registry.set(provider.token, {\n dispose: valueProvider.dispose as Disposer | undefined,\n kind: 'value',\n value: valueProvider.value,\n });\n }\n }\n }\n\n #claimValues(): void {\n for (const registration of this.#registry.values()) {\n if (registration.kind === 'value' && registration.dispose) {\n this.#owned.push({ dispose: registration.dispose, value: registration.value });\n }\n }\n }\n\n #lookup<T>(token: Token<T>): { owner: ContainerImpl; registration: Registration<T> } | undefined {\n const local = this.#registry.get(token) as Registration<T> | undefined;\n\n if (local) return { owner: this, registration: local };\n\n if (!this.#parent) return undefined;\n\n return this.#parent.#lookup(token);\n }\n\n #factories(): { owner: ContainerImpl; registration: FactoryRegistration; token: Token<unknown> }[] {\n const parentFactories = this.#parent ? this.#parent.#factories() : [];\n const localFactories = [...this.#registry].flatMap(([token, registration]) =>\n registration.kind === 'factory' ? [{ owner: this, registration, token }] : [],\n );\n\n return [...parentFactories, ...localFactories];\n }\n\n #validateGraph(): void {\n for (const { owner, registration, token } of this.#factories()) {\n owner.#validatePath(token, registration, new Set(), []);\n }\n }\n\n #validatePath(\n token: Token<unknown>,\n registration: FactoryRegistration,\n visiting: Set<Token<unknown>>,\n path: Token<unknown>[],\n ): void {\n if (visiting.has(token)) throw new ConduitCircularDependencyError([...path, token]);\n\n visiting.add(token);\n\n for (const dependency of registration.dependencies) {\n const found = this.#lookup(dependency);\n\n if (!found) throw new ConduitProviderNotFoundError(dependency, this.name);\n\n if (found.registration.kind === 'factory') {\n if (registration.lifetime === 'singleton' && found.registration.lifetime === 'transient') {\n throw new ConduitError(\n `Singleton \"${token.description ?? 'anonymous'}\" cannot depend on a transient factory`,\n );\n }\n if (registration.lifetime === 'singleton' && typeof found.registration.lifetime === 'symbol') {\n throw new ConduitScopedResolutionError(token, found.registration.lifetime);\n }\n if (\n typeof registration.lifetime === 'symbol' &&\n typeof found.registration.lifetime === 'symbol' &&\n registration.lifetime !== found.registration.lifetime\n ) {\n throw new ConduitScopedResolutionError(token, found.registration.lifetime);\n }\n\n found.owner.#validatePath(dependency, found.registration, visiting, [...path, token]);\n }\n }\n\n visiting.delete(token);\n }\n\n async #resolve<T>(token: Token<T>, path: Token<unknown>[]): Promise<T> {\n if (path.includes(token)) throw new ConduitCircularDependencyError([...path, token]);\n\n const found = this.#lookup(token);\n\n if (!found) throw new ConduitProviderNotFoundError(token, this.name);\n\n const registration = found.registration;\n\n if (registration.kind === 'value') return registration.value as T;\n\n const owner = this.#ownerFor(found.owner, registration, token);\n\n if (registration.lifetime === 'transient') {\n return owner.#track(owner.#create(registration, owner, [...path, token])) as Promise<T>;\n }\n\n const existing = owner.#cache.get(registration);\n\n if (existing?.resolved) return existing.value as T;\n if (existing) return existing.promise as Promise<T>;\n\n const entry = { promise: Promise.resolve(), resolved: false } as CacheEntry;\n const creation = owner.#create(registration, owner, [...path, token]).then(\n (value) => {\n entry.resolved = true;\n entry.value = value;\n return value;\n },\n (error) => {\n if (owner.#cache.get(registration) === entry) owner.#cache.delete(registration);\n throw error;\n },\n );\n\n entry.promise = owner.#track(creation);\n owner.#cache.set(registration, entry);\n\n return entry.promise as Promise<T>;\n }\n\n #ownerFor(owner: ContainerImpl, registration: FactoryRegistration, token: Token<unknown>): ContainerImpl {\n if (registration.lifetime === 'singleton') return owner;\n if (registration.lifetime === 'transient') return this;\n\n const scopeOwner = this.#scopeOwner(registration.lifetime as ScopeToken);\n\n if (!scopeOwner) throw new ConduitScopedResolutionError(token, registration.lifetime as ScopeToken);\n\n return scopeOwner;\n }\n\n #scopeOwner(scope: ScopeToken): ContainerImpl | undefined {\n if (this.#scope === scope) return this;\n\n return this.#parent ? this.#parent.#scopeOwner(scope) : undefined;\n }\n\n #track<T>(promise: Promise<T>): Promise<T> {\n this.#inFlight.add(promise);\n void promise.then(\n () => this.#inFlight.delete(promise),\n () => this.#inFlight.delete(promise),\n );\n return promise;\n }\n\n async #create(registration: FactoryRegistration, owner: ContainerImpl, path: Token<unknown>[]): Promise<unknown> {\n const value = await Promise.all(\n registration.dependencies.map((dependency) => owner.#resolve(dependency, path)),\n ).then((dependencies) => registration.factory(...dependencies));\n\n if (owner.#lifecycle !== 'active') {\n if (registration.dispose) {\n try {\n await registration.dispose(value);\n } catch (error) {\n owner.#cleanupFailures.push(error);\n }\n }\n\n throw new ConduitDisposedError(owner.name);\n }\n\n if (registration.dispose) owner.#owned.push({ dispose: registration.dispose, value });\n\n return value;\n }\n}\n\nexport function createContainer(\n providers: readonly Provider<any, any>[],\n options?: { readonly name?: string },\n): Container {\n return new ContainerImpl(undefined, providers, { name: options?.name });\n}\n"],"mappings":";;;AA2CA,IAAM,IAAN,MAAM,EAAmC;CACvC,qBAAS,IAAI,IAA8C;CAC3D,qBAAY,IAAI,IAAmB;CACnC,KAA8B,CAAC;CAC/B,KAAsB,IAAI,gBAAgB;CAC1C,qBAAY,IAAI,IAAsB;CACtC,KAAwB;CACxB;CACA,KAA0B,CAAC;CAC3B;CACA,qBAAY,IAAI,IAA2C;CAC3D;CACA;CAEA,YACE,GACA,GACA,GACA;EAOA,AANA,KAAK,KAAU,GACf,KAAK,KAAS,EAAQ,OAElB,KAAQ,EAAO,GAAU,IAAI,IAAI,GAErC,KAAK,OAAO,EAAQ,SAAS,IAAS,GAAG,EAAO,KAAK,GAAG,EAAQ,OAAO,eAAe,YAAY,SAClG,KAAK,GAAU,IAAI,GAAqB;GAAE,MAAM;GAAS,OAAO,KAAK;EAAe,CAAC;EAErF,IAAI;GAGF,AAFA,KAAK,GAAmB,CAAS,GACjC,KAAK,GAAe,GACpB,KAAK,GAAa;EACpB,SAAS,GAAO;GAGd,MAFI,KAAQ,EAAO,GAAU,OAAO,IAAI,GACxC,KAAK,GAAU,MAAM,GACf;EACR;CACF;CAEA,IAAI,iBAA8B;EAChC,OAAO,KAAK,GAAoB;CAClC;CAEA,IAAI,WAAoB;EACtB,OAAO,KAAK,OAAe;CAC7B;CAEA,IAAO,GAA0B;EAG/B,OAFA,KAAK,GAAc,GAEZ,KAAK,GAAQ,CAAK,MAAM,KAAA;CACjC;CAIA,MAAM,QAAiC,GAAoD;EAGzF,IAFA,KAAK,GAAc,GAEf,OAAO,KAA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ACT;CAEA,MAAM,GAAQ,GAAmC,GAAsB,GAA0C;EAC/G,IAAM,IAAQ,MAAM,QAAQ,IAC1B,EAAa,aAAa,KAAK,MAAe,EAAM,GAAS,GAAY,CAAI,CAAC,CAChF,CAAC,CAAC,MAAM,MAAiB,EAAa,QAAQ,GAAG,CAAY,CAAC;EAE9D,IAAI,EAAM,OAAe,UAAU;GACjC,IAAI,EAAa,SACf,IAAI;IACF,MAAM,EAAa,QAAQ,CAAK;GAClC,SAAS,GAAO;IACd,EAAM,GAAiB,KAAK,CAAK;GACnC;GAGF,MAAM,IAAI,EAAqB,EAAM,IAAI;EAC3C;EAIA,OAFI,EAAa,WAAS,EAAM,GAAO,KAAK;GAAE,SAAS,EAAa;GAAS;EAAM,CAAC,GAE7E;CACT;AACF;AAEA,SAAgB,EACd,GACA,GACW;CACX,OAAO,IAAI,EAAc,KAAA,GAAW,GAAW,EAAE,MAAM,GAAS,KAAK,CAAC;AACxE"}
|
|
1
|
+
{"version":3,"file":"container.js","names":[],"sources":["../src/container.ts"],"sourcesContent":["import {\n ConduitCircularDependencyError,\n ConduitDisposedError,\n ConduitDisposeError,\n ConduitDuplicateRegistrationError,\n ConduitError,\n ConduitProviderNotFoundError,\n} from './errors.js';\nimport type {\n AnyProvider,\n Container,\n CreateScopeOptions,\n FactoryProvider,\n InferServices,\n Lifetime,\n Provider,\n ServiceMap,\n Token,\n ValueProvider,\n} from './types.js';\nimport { disposalSignalToken } from './types.js';\n\ntype Disposer = (value: unknown) => Promise<void> | void;\n\ntype ValueRegistration<T> = Readonly<{\n dispose?: Disposer;\n kind: 'value';\n value: T;\n}>;\n\ntype FactoryRegistration<T = unknown> = Readonly<{\n factory: (...values: unknown[]) => Promise<T> | T;\n dependencies: readonly Token<unknown>[];\n dispose?: Disposer;\n kind: 'factory';\n lifetime: Lifetime;\n}>;\n\ntype Registration<T = unknown> = FactoryRegistration<T> | ValueRegistration<T>;\ntype OwnedResource = Readonly<{ dispose?: Disposer; value: unknown }>;\ntype CacheEntry = { promise: Promise<unknown>; resolved: boolean; value?: unknown };\ntype Lifecycle = 'active' | 'disposed' | 'disposing';\n\nclass ContainerImpl implements Container {\n #cache = new Map<FactoryRegistration<unknown>, CacheEntry>();\n #children = new Set<ContainerImpl>();\n #cleanupFailures: unknown[] = [];\n #disposalController = new AbortController();\n #inFlight = new Set<Promise<unknown>>();\n #lifecycle: Lifecycle = 'active';\n #disposePromise?: Promise<void>;\n #owned: OwnedResource[] = [];\n #parent?: ContainerImpl;\n #registry = new Map<Token<unknown>, Registration<unknown>>();\n readonly name: string;\n\n constructor(parent: ContainerImpl | undefined, providers: readonly AnyProvider[], options: CreateScopeOptions) {\n this.#parent = parent;\n\n if (parent) parent.#children.add(this);\n\n this.name = options.name ?? (parent ? `${parent.name}:child` : 'root');\n this.#registry.set(disposalSignalToken, { kind: 'value', value: this.disposalSignal });\n\n try {\n this.#registerProviders(providers);\n this.#validateGraph();\n this.#claimValues();\n } catch (error) {\n if (parent) parent.#children.delete(this);\n this.#registry.clear();\n throw error;\n }\n }\n\n get disposalSignal(): AbortSignal {\n return this.#disposalController.signal;\n }\n\n get disposed(): boolean {\n return this.#lifecycle === 'disposed';\n }\n\n has<T>(token: Token<T>): boolean {\n this.#assertActive();\n\n return this.#lookup(token) !== undefined;\n }\n\n resolve<T>(token: Token<T>): Promise<T>;\n resolve<M extends ServiceMap>(map: M): Promise<InferServices<M>>;\n async resolve<T, M extends ServiceMap>(input: Token<T> | M): Promise<InferServices<M> | T> {\n this.#assertActive();\n\n if (typeof input === 'symbol') return this.#resolve(input, []);\n if (typeof input !== 'object' || input === null || Array.isArray(input)) {\n throw new ConduitError('resolve() requires a token or service map');\n }\n\n const entries = Object.keys(input) as (keyof M & string)[];\n const values = await Promise.all(entries.map((key) => this.#resolve(input[key] as Token<unknown>, [])));\n const services = {} as InferServices<M>;\n\n entries.forEach((key, index) => {\n Object.defineProperty(services, key, {\n configurable: true,\n enumerable: true,\n value: values[index],\n writable: true,\n });\n });\n\n return services;\n }\n\n createScope(options: CreateScopeOptions = {}): Container {\n this.#assertActive();\n\n return new ContainerImpl(this, options.providers ?? [], { name: options.name });\n }\n\n dispose(): Promise<void> {\n if (this.#lifecycle === 'disposed') return Promise.resolve();\n\n if (this.#disposePromise) return this.#disposePromise;\n\n this.#lifecycle = 'disposing';\n this.#disposalController.abort();\n this.#disposePromise = this.#finishDisposal();\n\n return this.#disposePromise;\n }\n\n async [Symbol.asyncDispose](): Promise<void> {\n await this.dispose();\n }\n\n async #finishDisposal(): Promise<void> {\n const childOutcomes = await Promise.allSettled([...this.#children].map((child) => child.dispose()));\n\n await Promise.allSettled([...this.#inFlight]);\n\n const failures = [\n ...this.#cleanupFailures,\n ...childOutcomes.flatMap((outcome) => {\n if (outcome.status !== 'rejected') return [];\n\n return outcome.reason instanceof ConduitDisposeError ? outcome.reason.errors : [outcome.reason];\n }),\n ];\n\n for (const resource of [...this.#owned].reverse()) {\n if (!resource.dispose) continue;\n\n try {\n await resource.dispose(resource.value);\n } catch (error) {\n failures.push(error);\n }\n }\n\n this.#cache.clear();\n this.#children.clear();\n this.#cleanupFailures = [];\n this.#owned = [];\n this.#registry.clear();\n\n if (this.#parent) this.#parent.#children.delete(this);\n\n this.#lifecycle = 'disposed';\n\n if (failures.length) throw new ConduitDisposeError(failures);\n }\n\n #assertActive(): void {\n if (this.#lifecycle !== 'active') throw new ConduitDisposedError(this.name);\n }\n\n #assertUnregistered(token: Token<unknown>): void {\n if (this.#registry.has(token)) throw new ConduitDuplicateRegistrationError(token);\n }\n\n #registerProviders(providers: readonly AnyProvider[]): void {\n if (!Array.isArray(providers)) throw new ConduitError('Container providers must be an array');\n\n for (const input of providers) {\n if (typeof input !== 'object' || input === null || Array.isArray(input)) {\n throw new ConduitError('Each provider must be an object');\n }\n\n const provider = input as Provider;\n const hasDependencies = Object.hasOwn(provider, 'dependencies');\n const hasFactory = Object.hasOwn(provider, 'factory');\n const hasValue = Object.hasOwn(provider, 'value');\n\n if (typeof provider.token !== 'symbol') throw new ConduitError('Each provider requires a token');\n if (provider.dispose !== undefined && typeof provider.dispose !== 'function') {\n throw new ConduitError(`Provider \"${provider.token.description ?? 'anonymous'}\" has an invalid disposer`);\n }\n if (\n hasValue === hasFactory ||\n hasValue === hasDependencies ||\n (hasValue && Object.hasOwn(provider, 'lifetime'))\n ) {\n throw new ConduitError(\n `Provider \"${provider.token.description ?? 'anonymous'}\" must define exactly one value or factory`,\n );\n }\n\n this.#assertUnregistered(provider.token);\n\n if (hasFactory) {\n const factory = provider as FactoryProvider<unknown>;\n\n if (\n !Array.isArray(factory.dependencies) ||\n factory.dependencies.some((dependency) => typeof dependency !== 'symbol')\n ) {\n throw new ConduitError(\n `Factory provider \"${provider.token.description ?? 'anonymous'}\" has invalid dependencies`,\n );\n }\n if (typeof factory.factory !== 'function') {\n throw new ConduitError(`Factory provider \"${provider.token.description ?? 'anonymous'}\" requires a factory`);\n }\n if (factory.lifetime !== undefined && factory.lifetime !== 'singleton' && factory.lifetime !== 'transient') {\n throw new ConduitError(\n `Factory provider \"${provider.token.description ?? 'anonymous'}\" has an invalid lifetime`,\n );\n }\n\n this.#registry.set(provider.token, {\n dependencies: Object.freeze([...factory.dependencies]),\n dispose: factory.dispose as Disposer | undefined,\n factory: factory.factory as (...values: unknown[]) => Promise<unknown> | unknown,\n kind: 'factory',\n lifetime: factory.lifetime ?? 'singleton',\n });\n } else {\n const valueProvider = provider as ValueProvider<unknown>;\n\n this.#registry.set(provider.token, {\n dispose: valueProvider.dispose as Disposer | undefined,\n kind: 'value',\n value: valueProvider.value,\n });\n }\n }\n }\n\n #claimValues(): void {\n for (const registration of this.#registry.values()) {\n if (registration.kind === 'value' && registration.dispose) {\n this.#owned.push({ dispose: registration.dispose, value: registration.value });\n }\n }\n }\n\n #lookup<T>(token: Token<T>): { owner: ContainerImpl; registration: Registration<T> } | undefined {\n const local = this.#registry.get(token) as Registration<T> | undefined;\n\n if (local) return { owner: this, registration: local };\n\n if (!this.#parent) return undefined;\n\n return this.#parent.#lookup(token);\n }\n\n #factories(): { owner: ContainerImpl; registration: FactoryRegistration; token: Token<unknown> }[] {\n const parentFactories = this.#parent ? this.#parent.#factories() : [];\n const localFactories = [...this.#registry].flatMap(([token, registration]) =>\n registration.kind === 'factory' ? [{ owner: this, registration, token }] : [],\n );\n\n return [...parentFactories, ...localFactories];\n }\n\n #validateGraph(): void {\n for (const { owner, registration, token } of this.#factories()) {\n owner.#validatePath(token, registration, new Set(), []);\n }\n }\n\n #validatePath(\n token: Token<unknown>,\n registration: FactoryRegistration,\n visiting: Set<Token<unknown>>,\n path: Token<unknown>[],\n ): void {\n if (visiting.has(token)) throw new ConduitCircularDependencyError([...path, token]);\n\n visiting.add(token);\n\n for (const dependency of registration.dependencies) {\n const found = this.#lookup(dependency);\n\n if (!found) throw new ConduitProviderNotFoundError(dependency, this.name);\n\n if (found.registration.kind === 'factory') {\n if (registration.lifetime === 'singleton' && found.registration.lifetime === 'transient') {\n throw new ConduitError(\n `Singleton \"${token.description ?? 'anonymous'}\" cannot depend on a transient factory`,\n );\n }\n\n found.owner.#validatePath(dependency, found.registration, visiting, [...path, token]);\n }\n }\n\n visiting.delete(token);\n }\n\n async #resolve<T>(token: Token<T>, path: Token<unknown>[]): Promise<T> {\n if (path.includes(token)) throw new ConduitCircularDependencyError([...path, token]);\n\n const found = this.#lookup(token);\n\n if (!found) throw new ConduitProviderNotFoundError(token, this.name);\n\n const registration = found.registration;\n\n if (registration.kind === 'value') return registration.value as T;\n\n if (registration.lifetime === 'transient') {\n return this.#track(this.#create(registration, this, [...path, token])) as Promise<T>;\n }\n\n const owner = found.owner;\n const existing = owner.#cache.get(registration);\n\n if (existing?.resolved) return existing.value as T;\n if (existing) return existing.promise as Promise<T>;\n\n const entry = { promise: Promise.resolve(), resolved: false } as CacheEntry;\n const creation = owner.#create(registration, owner, [...path, token]).then(\n (value) => {\n entry.resolved = true;\n entry.value = value;\n return value;\n },\n (error) => {\n if (owner.#cache.get(registration) === entry) owner.#cache.delete(registration);\n throw error;\n },\n );\n\n entry.promise = owner.#track(creation);\n owner.#cache.set(registration, entry);\n\n return entry.promise as Promise<T>;\n }\n\n #track<T>(promise: Promise<T>): Promise<T> {\n this.#inFlight.add(promise);\n void promise.then(\n () => this.#inFlight.delete(promise),\n () => this.#inFlight.delete(promise),\n );\n return promise;\n }\n\n async #create(registration: FactoryRegistration, owner: ContainerImpl, path: Token<unknown>[]): Promise<unknown> {\n const value = await Promise.all(\n registration.dependencies.map((dependency) => owner.#resolve(dependency, path)),\n ).then((dependencies) => registration.factory(...dependencies));\n\n if (owner.#lifecycle !== 'active') {\n if (registration.dispose) {\n try {\n await registration.dispose(value);\n } catch (error) {\n owner.#cleanupFailures.push(error);\n }\n }\n\n throw new ConduitDisposedError(owner.name);\n }\n\n if (registration.dispose) owner.#owned.push({ dispose: registration.dispose, value });\n\n return value;\n }\n}\n\nexport function createContainer(providers: readonly AnyProvider[], options?: { readonly name?: string }): Container {\n return new ContainerImpl(undefined, providers, { name: options?.name });\n}\n"],"mappings":"4PA2CA,IAAM,EAAN,MAAM,aAAmC,CACvC,GAAS,IAAI,IACb,GAAY,IAAI,IAChB,GAA8B,CAAC,EAC/B,GAAsB,IAAI,gBAC1B,GAAY,IAAI,IAChB,GAAwB,SACxB,GACA,GAA0B,CAAC,EAC3B,GACA,GAAY,IAAI,IAChB,KAEA,YAAY,EAAmC,EAAmC,EAA6B,CAC7G,KAAK,GAAU,EAEX,GAAQ,EAAO,GAAU,IAAI,IAAI,EAErC,KAAK,KAAO,EAAQ,OAAS,EAAS,GAAG,EAAO,KAAK,QAAU,QAC/D,KAAK,GAAU,IAAI,EAAqB,CAAE,KAAM,QAAS,MAAO,KAAK,cAAe,CAAC,EAErF,GAAI,CACF,KAAK,GAAmB,CAAS,EACjC,KAAK,GAAe,EACpB,KAAK,GAAa,CACpB,OAAS,EAAO,CAGd,MAFI,GAAQ,EAAO,GAAU,OAAO,IAAI,EACxC,KAAK,GAAU,MAAM,EACf,CACR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CACnC,CAGF,MAAM,IAAI,EAAqB,EAAM,IAAI,CAC3C,CAIA,OAFI,EAAa,SAAS,EAAM,GAAO,KAAK,CAAE,QAAS,EAAa,QAAS,OAAM,CAAC,EAE7E,CACT,CACF,EAEA,SAAgB,gBAAgB,EAAmC,EAAiD,CAClH,OAAO,IAAI,EAAc,IAAA,GAAW,EAAW,CAAE,KAAM,GAAS,IAAK,CAAC,CACxE"}
|
package/dist/errors.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function
|
|
1
|
+
function tokenName(e){return e.description??`anonymous`}var ConduitError=class extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},ConduitCircularDependencyError=class extends ConduitError{cycle;constructor(e){super(`Circular dependency detected: ${e.map(tokenName).join(` -> `)}`),this.cycle=Object.freeze([...e])}},ConduitProviderNotFoundError=class extends ConduitError{containerName;token;constructor(e,t){super(`No provider registered for token: ${tokenName(e)} (in container '${t}')`),this.containerName=t,this.token=e}},ConduitDuplicateRegistrationError=class extends ConduitError{token;constructor(e){super(`Token "${tokenName(e)}" is already registered.`),this.token=e}},ConduitDisposedError=class extends ConduitError{containerName;constructor(e){super(`Cannot use disposed container '${e}'.`),this.containerName=e}},ConduitDisposeError=class extends ConduitError{errors;constructor(e){super(`Container disposal failed with ${e.length} cleanup error${e.length===1?``:`s`}.`),this.errors=Object.freeze([...e])}};exports.ConduitCircularDependencyError=ConduitCircularDependencyError,exports.ConduitDisposeError=ConduitDisposeError,exports.ConduitDisposedError=ConduitDisposedError,exports.ConduitDuplicateRegistrationError=ConduitDuplicateRegistrationError,exports.ConduitError=ConduitError,exports.ConduitProviderNotFoundError=ConduitProviderNotFoundError;
|
|
2
2
|
//# sourceMappingURL=errors.cjs.map
|
package/dist/errors.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.cjs","names":[],"sources":["../src/errors.ts"],"sourcesContent":["import type {
|
|
1
|
+
{"version":3,"file":"errors.cjs","names":[],"sources":["../src/errors.ts"],"sourcesContent":["import type { Token } from './types.js';\n\nfunction tokenName(token: Token<unknown>): string {\n return token.description ?? 'anonymous';\n}\n\nexport class ConduitError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport class ConduitCircularDependencyError extends ConduitError {\n readonly cycle: readonly Token<unknown>[];\n\n constructor(cycle: readonly Token<unknown>[]) {\n super(`Circular dependency detected: ${cycle.map(tokenName).join(' -> ')}`);\n this.cycle = Object.freeze([...cycle]);\n }\n}\n\nexport class ConduitProviderNotFoundError extends ConduitError {\n readonly containerName: string;\n readonly token: Token<unknown>;\n\n constructor(token: Token<unknown>, containerName: string) {\n super(`No provider registered for token: ${tokenName(token)} (in container '${containerName}')`);\n this.containerName = containerName;\n this.token = token;\n }\n}\n\nexport class ConduitDuplicateRegistrationError extends ConduitError {\n readonly token: Token<unknown>;\n\n constructor(token: Token<unknown>) {\n super(`Token \"${tokenName(token)}\" is already registered.`);\n this.token = token;\n }\n}\n\nexport class ConduitDisposedError extends ConduitError {\n readonly containerName: string;\n\n constructor(containerName: string) {\n super(`Cannot use disposed container '${containerName}'.`);\n this.containerName = containerName;\n }\n}\n\nexport class ConduitDisposeError extends ConduitError {\n readonly errors: readonly unknown[];\n\n constructor(errors: readonly unknown[]) {\n super(`Container disposal failed with ${errors.length} cleanup error${errors.length === 1 ? '' : 's'}.`);\n this.errors = Object.freeze([...errors]);\n }\n}\n"],"mappings":"AAEA,SAAS,UAAU,EAA+B,CAChD,OAAO,EAAM,aAAe,WAC9B,CAEA,IAAa,aAAb,cAAkC,KAAM,CACtC,YAAY,EAAiB,EAAwB,CACnD,MAAM,EAAS,CAAO,EACtB,KAAK,KAAO,WAAW,KACvB,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CACF,EAEa,+BAAb,cAAoD,YAAa,CAC/D,MAEA,YAAY,EAAkC,CAC5C,MAAM,iCAAiC,EAAM,IAAI,SAAS,CAAC,CAAC,KAAK,MAAM,GAAG,EAC1E,KAAK,MAAQ,OAAO,OAAO,CAAC,GAAG,CAAK,CAAC,CACvC,CACF,EAEa,6BAAb,cAAkD,YAAa,CAC7D,cACA,MAEA,YAAY,EAAuB,EAAuB,CACxD,MAAM,qCAAqC,UAAU,CAAK,EAAE,kBAAkB,EAAc,GAAG,EAC/F,KAAK,cAAgB,EACrB,KAAK,MAAQ,CACf,CACF,EAEa,kCAAb,cAAuD,YAAa,CAClE,MAEA,YAAY,EAAuB,CACjC,MAAM,UAAU,UAAU,CAAK,EAAE,yBAAyB,EAC1D,KAAK,MAAQ,CACf,CACF,EAEa,qBAAb,cAA0C,YAAa,CACrD,cAEA,YAAY,EAAuB,CACjC,MAAM,kCAAkC,EAAc,GAAG,EACzD,KAAK,cAAgB,CACvB,CACF,EAEa,oBAAb,cAAyC,YAAa,CACpD,OAEA,YAAY,EAA4B,CACtC,MAAM,kCAAkC,EAAO,OAAO,gBAAgB,EAAO,SAAW,EAAI,GAAK,IAAI,EAAE,EACvG,KAAK,OAAS,OAAO,OAAO,CAAC,GAAG,CAAM,CAAC,CACzC,CACF"}
|
package/dist/errors.d.ts
CHANGED
|
@@ -1,38 +1,25 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
export declare function tokenName(token: Token<unknown>): string;
|
|
1
|
+
import type { Token } from './types.js';
|
|
3
2
|
export declare class ConduitError extends Error {
|
|
4
|
-
protected static readonly errorName: string;
|
|
5
3
|
constructor(message: string, options?: ErrorOptions);
|
|
6
4
|
}
|
|
7
5
|
export declare class ConduitCircularDependencyError extends ConduitError {
|
|
8
|
-
protected static readonly errorName = "ConduitCircularDependencyError";
|
|
9
6
|
readonly cycle: readonly Token<unknown>[];
|
|
10
7
|
constructor(cycle: readonly Token<unknown>[]);
|
|
11
8
|
}
|
|
12
9
|
export declare class ConduitProviderNotFoundError extends ConduitError {
|
|
13
|
-
protected static readonly errorName = "ConduitProviderNotFoundError";
|
|
14
10
|
readonly containerName: string;
|
|
15
11
|
readonly token: Token<unknown>;
|
|
16
12
|
constructor(token: Token<unknown>, containerName: string);
|
|
17
13
|
}
|
|
18
14
|
export declare class ConduitDuplicateRegistrationError extends ConduitError {
|
|
19
|
-
protected static readonly errorName = "ConduitDuplicateRegistrationError";
|
|
20
15
|
readonly token: Token<unknown>;
|
|
21
16
|
constructor(token: Token<unknown>);
|
|
22
17
|
}
|
|
23
|
-
export declare class ConduitScopedResolutionError extends ConduitError {
|
|
24
|
-
protected static readonly errorName = "ConduitScopedResolutionError";
|
|
25
|
-
readonly requiredScope: ScopeToken;
|
|
26
|
-
readonly token: Token<unknown>;
|
|
27
|
-
constructor(token: Token<unknown>, requiredScope: ScopeToken);
|
|
28
|
-
}
|
|
29
18
|
export declare class ConduitDisposedError extends ConduitError {
|
|
30
|
-
protected static readonly errorName = "ConduitDisposedError";
|
|
31
19
|
readonly containerName: string;
|
|
32
20
|
constructor(containerName: string);
|
|
33
21
|
}
|
|
34
22
|
export declare class ConduitDisposeError extends ConduitError {
|
|
35
|
-
protected static readonly errorName = "ConduitDisposeError";
|
|
36
23
|
readonly errors: readonly unknown[];
|
|
37
24
|
constructor(errors: readonly unknown[]);
|
|
38
25
|
}
|
package/dist/errors.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,
|
|
1
|
+
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAMxC,qBAAa,YAAa,SAAQ,KAAK;gBACzB,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,YAAY;CAKpD;AAED,qBAAa,8BAA+B,SAAQ,YAAY;IAC9D,QAAQ,CAAC,KAAK,EAAE,SAAS,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC;gBAE9B,KAAK,EAAE,SAAS,KAAK,CAAC,OAAO,CAAC,EAAE;CAI7C;AAED,qBAAa,4BAA6B,SAAQ,YAAY;IAC5D,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,KAAK,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;gBAEnB,KAAK,EAAE,KAAK,CAAC,OAAO,CAAC,EAAE,aAAa,EAAE,MAAM;CAKzD;AAED,qBAAa,iCAAkC,SAAQ,YAAY;IACjE,QAAQ,CAAC,KAAK,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;gBAEnB,KAAK,EAAE,KAAK,CAAC,OAAO,CAAC;CAIlC;AAED,qBAAa,oBAAqB,SAAQ,YAAY;IACpD,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;gBAEnB,aAAa,EAAE,MAAM;CAIlC;AAED,qBAAa,mBAAoB,SAAQ,YAAY;IACnD,QAAQ,CAAC,MAAM,EAAE,SAAS,OAAO,EAAE,CAAC;gBAExB,MAAM,EAAE,SAAS,OAAO,EAAE;CAIvC"}
|
package/dist/errors.js
CHANGED
|
@@ -1,52 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
function e(e) {
|
|
3
|
-
return e.description ?? "anonymous";
|
|
4
|
-
}
|
|
5
|
-
var t = class extends Error {
|
|
6
|
-
static errorName = "ConduitError";
|
|
7
|
-
constructor(e, t) {
|
|
8
|
-
super(e, t), this.name = new.target.errorName, Object.setPrototypeOf(this, new.target.prototype);
|
|
9
|
-
}
|
|
10
|
-
}, n = class extends t {
|
|
11
|
-
static errorName = "ConduitCircularDependencyError";
|
|
12
|
-
cycle;
|
|
13
|
-
constructor(t) {
|
|
14
|
-
super(`Circular dependency detected: ${t.map(e).join(" -> ")}`), this.cycle = Object.freeze([...t]);
|
|
15
|
-
}
|
|
16
|
-
}, r = class extends t {
|
|
17
|
-
static errorName = "ConduitProviderNotFoundError";
|
|
18
|
-
containerName;
|
|
19
|
-
token;
|
|
20
|
-
constructor(t, n) {
|
|
21
|
-
super(`No provider registered for token: ${e(t)} (in container '${n}')`), this.containerName = n, this.token = t;
|
|
22
|
-
}
|
|
23
|
-
}, i = class extends t {
|
|
24
|
-
static errorName = "ConduitDuplicateRegistrationError";
|
|
25
|
-
token;
|
|
26
|
-
constructor(t) {
|
|
27
|
-
super(`Token "${e(t)}" is already registered.`), this.token = t;
|
|
28
|
-
}
|
|
29
|
-
}, a = class extends t {
|
|
30
|
-
static errorName = "ConduitScopedResolutionError";
|
|
31
|
-
requiredScope;
|
|
32
|
-
token;
|
|
33
|
-
constructor(t, n) {
|
|
34
|
-
super(`Token "${e(t)}" requires scope "${n.description ?? "anonymous"}".`), this.requiredScope = n, this.token = t;
|
|
35
|
-
}
|
|
36
|
-
}, o = class extends t {
|
|
37
|
-
static errorName = "ConduitDisposedError";
|
|
38
|
-
containerName;
|
|
39
|
-
constructor(e) {
|
|
40
|
-
super(`Cannot use disposed container '${e}'.`), this.containerName = e;
|
|
41
|
-
}
|
|
42
|
-
}, s = class extends t {
|
|
43
|
-
static errorName = "ConduitDisposeError";
|
|
44
|
-
errors;
|
|
45
|
-
constructor(e) {
|
|
46
|
-
super(`Container disposal failed with ${e.length} cleanup error${e.length === 1 ? "" : "s"}.`), this.errors = Object.freeze([...e]);
|
|
47
|
-
}
|
|
48
|
-
};
|
|
49
|
-
//#endregion
|
|
50
|
-
export { n as ConduitCircularDependencyError, s as ConduitDisposeError, o as ConduitDisposedError, i as ConduitDuplicateRegistrationError, t as ConduitError, r as ConduitProviderNotFoundError, a as ConduitScopedResolutionError, e as tokenName };
|
|
51
|
-
|
|
1
|
+
function tokenName(e){return e.description??`anonymous`}var ConduitError=class extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},ConduitCircularDependencyError=class extends ConduitError{cycle;constructor(e){super(`Circular dependency detected: ${e.map(tokenName).join(` -> `)}`),this.cycle=Object.freeze([...e])}},ConduitProviderNotFoundError=class extends ConduitError{containerName;token;constructor(e,t){super(`No provider registered for token: ${tokenName(e)} (in container '${t}')`),this.containerName=t,this.token=e}},ConduitDuplicateRegistrationError=class extends ConduitError{token;constructor(e){super(`Token "${tokenName(e)}" is already registered.`),this.token=e}},ConduitDisposedError=class extends ConduitError{containerName;constructor(e){super(`Cannot use disposed container '${e}'.`),this.containerName=e}},ConduitDisposeError=class extends ConduitError{errors;constructor(e){super(`Container disposal failed with ${e.length} cleanup error${e.length===1?``:`s`}.`),this.errors=Object.freeze([...e])}};export{ConduitCircularDependencyError,ConduitDisposeError,ConduitDisposedError,ConduitDuplicateRegistrationError,ConduitError,ConduitProviderNotFoundError};
|
|
52
2
|
//# sourceMappingURL=errors.js.map
|
package/dist/errors.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["import type {
|
|
1
|
+
{"version":3,"file":"errors.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["import type { Token } from './types.js';\n\nfunction tokenName(token: Token<unknown>): string {\n return token.description ?? 'anonymous';\n}\n\nexport class ConduitError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport class ConduitCircularDependencyError extends ConduitError {\n readonly cycle: readonly Token<unknown>[];\n\n constructor(cycle: readonly Token<unknown>[]) {\n super(`Circular dependency detected: ${cycle.map(tokenName).join(' -> ')}`);\n this.cycle = Object.freeze([...cycle]);\n }\n}\n\nexport class ConduitProviderNotFoundError extends ConduitError {\n readonly containerName: string;\n readonly token: Token<unknown>;\n\n constructor(token: Token<unknown>, containerName: string) {\n super(`No provider registered for token: ${tokenName(token)} (in container '${containerName}')`);\n this.containerName = containerName;\n this.token = token;\n }\n}\n\nexport class ConduitDuplicateRegistrationError extends ConduitError {\n readonly token: Token<unknown>;\n\n constructor(token: Token<unknown>) {\n super(`Token \"${tokenName(token)}\" is already registered.`);\n this.token = token;\n }\n}\n\nexport class ConduitDisposedError extends ConduitError {\n readonly containerName: string;\n\n constructor(containerName: string) {\n super(`Cannot use disposed container '${containerName}'.`);\n this.containerName = containerName;\n }\n}\n\nexport class ConduitDisposeError extends ConduitError {\n readonly errors: readonly unknown[];\n\n constructor(errors: readonly unknown[]) {\n super(`Container disposal failed with ${errors.length} cleanup error${errors.length === 1 ? '' : 's'}.`);\n this.errors = Object.freeze([...errors]);\n }\n}\n"],"mappings":"AAEA,SAAS,UAAU,EAA+B,CAChD,OAAO,EAAM,aAAe,WAC9B,CAEA,IAAa,aAAb,cAAkC,KAAM,CACtC,YAAY,EAAiB,EAAwB,CACnD,MAAM,EAAS,CAAO,EACtB,KAAK,KAAO,WAAW,KACvB,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CACF,EAEa,+BAAb,cAAoD,YAAa,CAC/D,MAEA,YAAY,EAAkC,CAC5C,MAAM,iCAAiC,EAAM,IAAI,SAAS,CAAC,CAAC,KAAK,MAAM,GAAG,EAC1E,KAAK,MAAQ,OAAO,OAAO,CAAC,GAAG,CAAK,CAAC,CACvC,CACF,EAEa,6BAAb,cAAkD,YAAa,CAC7D,cACA,MAEA,YAAY,EAAuB,EAAuB,CACxD,MAAM,qCAAqC,UAAU,CAAK,EAAE,kBAAkB,EAAc,GAAG,EAC/F,KAAK,cAAgB,EACrB,KAAK,MAAQ,CACf,CACF,EAEa,kCAAb,cAAuD,YAAa,CAClE,MAEA,YAAY,EAAuB,CACjC,MAAM,UAAU,UAAU,CAAK,EAAE,yBAAyB,EAC1D,KAAK,MAAQ,CACf,CACF,EAEa,qBAAb,cAA0C,YAAa,CACrD,cAEA,YAAY,EAAuB,CACjC,MAAM,kCAAkC,EAAc,GAAG,EACzD,KAAK,cAAgB,CACvB,CACF,EAEa,oBAAb,cAAyC,YAAa,CACpD,OAEA,YAAY,EAA4B,CACtC,MAAM,kCAAkC,EAAO,OAAO,gBAAgB,EAAO,SAAW,EAAI,GAAK,IAAI,EAAE,EACvG,KAAK,OAAS,OAAO,OAAO,CAAC,GAAG,CAAM,CAAC,CACzC,CACF"}
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./errors.cjs"),t=require("./types.cjs"),n=require("./container.cjs");exports.ConduitCircularDependencyError=e.ConduitCircularDependencyError,exports.ConduitDisposeError=e.ConduitDisposeError,exports.ConduitDisposedError=e.ConduitDisposedError,exports.ConduitDuplicateRegistrationError=e.ConduitDuplicateRegistrationError,exports.ConduitError=e.ConduitError,exports.ConduitProviderNotFoundError=e.ConduitProviderNotFoundError,exports.
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./errors.cjs"),t=require("./types.cjs"),n=require("./container.cjs");exports.ConduitCircularDependencyError=e.ConduitCircularDependencyError,exports.ConduitDisposeError=e.ConduitDisposeError,exports.ConduitDisposedError=e.ConduitDisposedError,exports.ConduitDuplicateRegistrationError=e.ConduitDuplicateRegistrationError,exports.ConduitError=e.ConduitError,exports.ConduitProviderNotFoundError=e.ConduitProviderNotFoundError,exports.createContainer=n.createContainer,exports.disposalSignalToken=t.disposalSignalToken,exports.factoryProvider=t.factoryProvider,exports.token=t.token,exports.valueProvider=t.valueProvider;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export { createContainer } from './container.js';
|
|
2
|
-
export { ConduitCircularDependencyError, ConduitDisposedError, ConduitDisposeError, ConduitDuplicateRegistrationError, ConduitError, ConduitProviderNotFoundError,
|
|
3
|
-
export type { Container, FactoryOptions, FactoryProvider, InferServices, InferTokens, Lifetime, Provider,
|
|
4
|
-
export { disposalSignalToken, factoryProvider,
|
|
2
|
+
export { ConduitCircularDependencyError, ConduitDisposedError, ConduitDisposeError, ConduitDuplicateRegistrationError, ConduitError, ConduitProviderNotFoundError, } from './errors.js';
|
|
3
|
+
export type { AnyProvider, Container, CreateScopeOptions, FactoryOptions, FactoryProvider, InferServices, InferTokens, Lifetime, Provider, ServiceMap, Token, ValueOptions, ValueProvider, } from './types.js';
|
|
4
|
+
export { disposalSignalToken, factoryProvider, token, valueProvider } from './types.js';
|
|
5
5
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AACjD,OAAO,EACL,8BAA8B,EAC9B,oBAAoB,EACpB,mBAAmB,EACnB,iCAAiC,EACjC,YAAY,EACZ,4BAA4B,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AACjD,OAAO,EACL,8BAA8B,EAC9B,oBAAoB,EACpB,mBAAmB,EACnB,iCAAiC,EACjC,YAAY,EACZ,4BAA4B,GAC7B,MAAM,aAAa,CAAC;AACrB,YAAY,EACV,WAAW,EACX,SAAS,EACT,kBAAkB,EAClB,cAAc,EACd,eAAe,EACf,aAAa,EACb,WAAW,EACX,QAAQ,EACR,QAAQ,EACR,UAAU,EACV,KAAK,EACL,YAAY,EACZ,aAAa,GACd,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,mBAAmB,EAAE,eAAe,EAAE,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC"}
|