@navios/di 0.5.1 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/CHANGELOG.md +145 -0
  2. package/README.md +196 -219
  3. package/docs/README.md +69 -11
  4. package/docs/api-reference.md +281 -117
  5. package/docs/container.md +220 -56
  6. package/docs/examples/request-scope-example.mts +2 -2
  7. package/docs/factory.md +3 -8
  8. package/docs/getting-started.md +37 -8
  9. package/docs/migration.md +318 -37
  10. package/docs/request-contexts.md +263 -175
  11. package/docs/scopes.md +79 -42
  12. package/lib/browser/index.d.mts +1577 -0
  13. package/lib/browser/index.d.mts.map +1 -0
  14. package/lib/browser/index.mjs +3013 -0
  15. package/lib/browser/index.mjs.map +1 -0
  16. package/lib/index-7jfWsiG4.d.mts +1211 -0
  17. package/lib/index-7jfWsiG4.d.mts.map +1 -0
  18. package/lib/index-DW3K5sOX.d.cts +1206 -0
  19. package/lib/index-DW3K5sOX.d.cts.map +1 -0
  20. package/lib/index.cjs +389 -0
  21. package/lib/index.cjs.map +1 -0
  22. package/lib/index.d.cts +376 -0
  23. package/lib/index.d.cts.map +1 -0
  24. package/lib/index.d.mts +371 -78
  25. package/lib/index.d.mts.map +1 -0
  26. package/lib/index.mjs +325 -63
  27. package/lib/index.mjs.map +1 -1
  28. package/lib/testing/index.cjs +9 -0
  29. package/lib/testing/index.d.cts +2 -0
  30. package/lib/testing/index.d.mts +2 -2
  31. package/lib/testing/index.mjs +2 -72
  32. package/lib/testing-BG_fa9TJ.mjs +2656 -0
  33. package/lib/testing-BG_fa9TJ.mjs.map +1 -0
  34. package/lib/testing-DIaIRiJz.cjs +2896 -0
  35. package/lib/testing-DIaIRiJz.cjs.map +1 -0
  36. package/package.json +29 -7
  37. package/project.json +2 -2
  38. package/src/__tests__/async-local-storage.browser.spec.mts +240 -0
  39. package/src/__tests__/async-local-storage.spec.mts +333 -0
  40. package/src/__tests__/container.spec.mts +30 -25
  41. package/src/__tests__/e2e.browser.spec.mts +790 -0
  42. package/src/__tests__/e2e.spec.mts +1222 -0
  43. package/src/__tests__/factory.spec.mts +1 -1
  44. package/src/__tests__/get-injectors.spec.mts +1 -1
  45. package/src/__tests__/injectable.spec.mts +1 -1
  46. package/src/__tests__/injection-token.spec.mts +1 -1
  47. package/src/__tests__/library-findings.spec.mts +563 -0
  48. package/src/__tests__/registry.spec.mts +2 -2
  49. package/src/__tests__/request-scope.spec.mts +266 -274
  50. package/src/__tests__/service-instantiator.spec.mts +18 -17
  51. package/src/__tests__/service-locator-event-bus.spec.mts +9 -9
  52. package/src/__tests__/service-locator-manager.spec.mts +15 -15
  53. package/src/__tests__/service-locator.spec.mts +167 -244
  54. package/src/__tests__/unified-api.spec.mts +27 -27
  55. package/src/__type-tests__/factory.spec-d.mts +2 -2
  56. package/src/__type-tests__/inject.spec-d.mts +2 -2
  57. package/src/__type-tests__/injectable.spec-d.mts +1 -1
  58. package/src/browser.mts +16 -0
  59. package/src/container/container.mts +319 -0
  60. package/src/container/index.mts +2 -0
  61. package/src/container/scoped-container.mts +350 -0
  62. package/src/decorators/factory.decorator.mts +4 -4
  63. package/src/decorators/injectable.decorator.mts +5 -5
  64. package/src/errors/di-error.mts +12 -5
  65. package/src/errors/index.mts +0 -8
  66. package/src/index.mts +156 -15
  67. package/src/interfaces/container.interface.mts +82 -0
  68. package/src/interfaces/factory.interface.mts +2 -2
  69. package/src/interfaces/index.mts +1 -0
  70. package/src/internal/context/async-local-storage.mts +120 -0
  71. package/src/internal/context/factory-context.mts +18 -0
  72. package/src/internal/context/index.mts +3 -0
  73. package/src/{request-context-holder.mts → internal/context/request-context.mts} +40 -27
  74. package/src/internal/context/resolution-context.mts +63 -0
  75. package/src/internal/context/sync-local-storage.mts +51 -0
  76. package/src/internal/core/index.mts +5 -0
  77. package/src/internal/core/instance-resolver.mts +641 -0
  78. package/src/{service-instantiator.mts → internal/core/instantiator.mts} +31 -27
  79. package/src/internal/core/invalidator.mts +437 -0
  80. package/src/internal/core/service-locator.mts +202 -0
  81. package/src/{token-processor.mts → internal/core/token-processor.mts} +79 -60
  82. package/src/{base-instance-holder-manager.mts → internal/holder/base-holder-manager.mts} +91 -21
  83. package/src/internal/holder/holder-manager.mts +85 -0
  84. package/src/internal/holder/holder-storage.interface.mts +116 -0
  85. package/src/internal/holder/index.mts +6 -0
  86. package/src/internal/holder/instance-holder.mts +109 -0
  87. package/src/internal/holder/request-storage.mts +134 -0
  88. package/src/internal/holder/singleton-storage.mts +105 -0
  89. package/src/internal/index.mts +4 -0
  90. package/src/internal/lifecycle/circular-detector.mts +77 -0
  91. package/src/internal/lifecycle/index.mts +2 -0
  92. package/src/{service-locator-event-bus.mts → internal/lifecycle/lifecycle-event-bus.mts} +11 -4
  93. package/src/testing/__tests__/test-container.spec.mts +2 -2
  94. package/src/testing/test-container.mts +4 -4
  95. package/src/token/index.mts +2 -0
  96. package/src/{injection-token.mts → token/injection-token.mts} +1 -1
  97. package/src/{registry.mts → token/registry.mts} +1 -1
  98. package/src/utils/get-injectable-token.mts +1 -1
  99. package/src/utils/get-injectors.mts +32 -15
  100. package/src/utils/types.mts +1 -1
  101. package/tsdown.config.mts +67 -0
  102. package/lib/_tsup-dts-rollup.d.mts +0 -1283
  103. package/lib/_tsup-dts-rollup.d.ts +0 -1283
  104. package/lib/chunk-2M576LCC.mjs +0 -2043
  105. package/lib/chunk-2M576LCC.mjs.map +0 -1
  106. package/lib/index.d.ts +0 -78
  107. package/lib/index.js +0 -2127
  108. package/lib/index.js.map +0 -1
  109. package/lib/testing/index.d.ts +0 -2
  110. package/lib/testing/index.js +0 -2060
  111. package/lib/testing/index.js.map +0 -1
  112. package/lib/testing/index.mjs.map +0 -1
  113. package/src/container.mts +0 -227
  114. package/src/factory-context.mts +0 -8
  115. package/src/instance-resolver.mts +0 -559
  116. package/src/request-context-manager.mts +0 -149
  117. package/src/service-invalidator.mts +0 -429
  118. package/src/service-locator-instance-holder.mts +0 -70
  119. package/src/service-locator-manager.mts +0 -85
  120. package/src/service-locator.mts +0 -246
  121. package/tsup.config.mts +0 -12
  122. /package/src/{injector.mts → injectors.mts} +0 -0
@@ -0,0 +1,1211 @@
1
+ import { ZodObject, ZodOptional, ZodRecord, ZodType, z } from "zod/v4";
2
+
3
+ //#region src/utils/types.d.mts
4
+ type Join<TElements, TSeparator extends string> = TElements extends Readonly<[infer First, ...infer Rest]> ? Rest extends ReadonlyArray<string> ? First extends string ? `${First}${Rest extends [] ? '' : TSeparator}${Join<Rest, TSeparator>}` : never : never : '';
5
+ type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
6
+ type UnionToOvlds<U> = UnionToIntersection<U extends any ? (f: U) => void : never>;
7
+ type PopUnion<U> = UnionToOvlds<U> extends ((a: infer A) => void) ? A : never;
8
+ type IsUnion<T> = [T] extends [UnionToIntersection<T>] ? false : true;
9
+ type UnionToArray<T, A extends unknown[] = []> = IsUnion<T> extends true ? UnionToArray<Exclude<T, PopUnion<T>>, [PopUnion<T>, ...A]> : [T, ...A];
10
+ type InjectRequest = {
11
+ token: InjectionToken<any> | BoundInjectionToken<any, any> | FactoryInjectionToken<any, any> | ClassType;
12
+ promise: Promise<any>;
13
+ readonly result: any;
14
+ readonly error: Error | null;
15
+ };
16
+ interface InjectState {
17
+ currentIndex: number;
18
+ isFrozen: boolean;
19
+ requests: InjectRequest[];
20
+ }
21
+ //#endregion
22
+ //#region src/interfaces/factory.interface.d.mts
23
+ interface Factorable<T> {
24
+ create(ctx?: FactoryContext): Promise<T> | T;
25
+ }
26
+ interface FactorableWithArgs<T, A extends InjectionTokenSchemaType> {
27
+ create(ctx?: FactoryContext, ...args: [z.output<A>]): Promise<T> | T;
28
+ }
29
+ //#endregion
30
+ //#region src/interfaces/container.interface.d.mts
31
+ /**
32
+ * Interface for dependency injection containers.
33
+ * Both Container and ScopedContainer implement this interface,
34
+ * allowing them to be used interchangeably in factory contexts.
35
+ */
36
+ interface IContainer {
37
+ /**
38
+ * Gets an instance from the container.
39
+ */
40
+ get<T extends ClassType>(token: T): InstanceType<T> extends Factorable<infer R> ? Promise<R> : Promise<InstanceType<T>>;
41
+ get<T extends ClassTypeWithArgument<R>, R>(token: T, args: R): Promise<InstanceType<T>>;
42
+ get<T, S extends InjectionTokenSchemaType>(token: InjectionToken<T, S>, args: z.input<S>): Promise<T>;
43
+ get<T, S extends InjectionTokenSchemaType, R extends boolean>(token: InjectionToken<T, S, R>): R extends false ? Promise<T> : S extends ZodType<infer Type> ? `Error: Your token requires args: ${Join<UnionToArray<keyof Type>, ', '>}` : 'Error: Your token requires args';
44
+ get<T>(token: InjectionToken<T, undefined>): Promise<T>;
45
+ get<T>(token: BoundInjectionToken<T, any>): Promise<T>;
46
+ get<T>(token: FactoryInjectionToken<T, any>): Promise<T>;
47
+ /**
48
+ * Invalidates a service and its dependencies.
49
+ */
50
+ invalidate(service: unknown): Promise<void>;
51
+ /**
52
+ * Checks if a service is registered in the container.
53
+ */
54
+ isRegistered(token: any): boolean;
55
+ /**
56
+ * Disposes the container and cleans up all resources.
57
+ */
58
+ dispose(): Promise<void>;
59
+ /**
60
+ * Waits for all pending operations to complete.
61
+ */
62
+ ready(): Promise<void>;
63
+ /**
64
+ * @internal
65
+ * Attempts to get an instance synchronously if it already exists.
66
+ * Returns null if the instance doesn't exist or is not ready.
67
+ * Used internally by the inject system for synchronous property initialization.
68
+ */
69
+ tryGetSync<T>(token: any, args?: any): T | null;
70
+ }
71
+ //#endregion
72
+ //#region src/utils/get-injectors.d.mts
73
+ interface Injectors {
74
+ asyncInject<T extends ClassTypeWithoutArguments>(token: T): InstanceType<T> extends Factorable<infer R> ? Promise<R> : Promise<InstanceType<T>>;
75
+ asyncInject<Args, T extends ClassTypeWithArgument<Args>>(token: T, args: Args): Promise<InstanceType<T>>;
76
+ asyncInject<Schema extends InjectionTokenSchemaType, R, T extends FactorableWithArgs<R, Schema>>(token: T, args: z.input<Schema>): Promise<R>;
77
+ asyncInject<T, S extends InjectionTokenSchemaType>(token: InjectionToken<T, S>, args: z.input<S>): Promise<T>;
78
+ asyncInject<T, S extends InjectionTokenSchemaType, R extends boolean>(token: InjectionToken<T, S, R>): R extends false ? Promise<T> : S extends ZodType<infer Type> ? `Error: Your token requires args: ${Join<UnionToArray<keyof Type>, ', '>}` : 'Error: Your token requires args';
79
+ asyncInject<T>(token: InjectionToken<T, undefined>): Promise<T>;
80
+ asyncInject<T>(token: BoundInjectionToken<T, any>): Promise<T>;
81
+ asyncInject<T>(token: FactoryInjectionToken<T, any>): Promise<T>;
82
+ inject<T extends ClassTypeWithoutArguments>(token: T): InstanceType<T> extends Factorable<infer R> ? R : InstanceType<T>;
83
+ inject<Args, T extends ClassTypeWithArgument<Args>>(token: T, args: Args): InstanceType<T>;
84
+ inject<Schema extends InjectionTokenSchemaType, R, T extends FactorableWithArgs<R, Schema>>(token: T, args: z.input<Schema>): R;
85
+ inject<T, S extends InjectionTokenSchemaType>(token: InjectionToken<T, S>, args: z.input<S>): T;
86
+ inject<T, S extends InjectionTokenSchemaType, R extends boolean>(token: InjectionToken<T, S, R>): R extends false ? T : S extends ZodType<infer Type> ? `Error: Your token requires args: ${Join<UnionToArray<keyof Type>, ', '>}` : 'Error: Your token requires args';
87
+ inject<T>(token: InjectionToken<T, undefined>): T;
88
+ inject<T>(token: BoundInjectionToken<T, any>): T;
89
+ inject<T>(token: FactoryInjectionToken<T, any>): T;
90
+ /**
91
+ * Optional injection that returns null if the service fails to initialize
92
+ * or is not available. This is useful when you want to inject a service
93
+ * that may not be configured or may fail gracefully.
94
+ *
95
+ * @example
96
+ * ```ts
97
+ * class MyService {
98
+ * constructor() {
99
+ * const optionalService = optional(OptionalServiceToken)
100
+ * // optionalService will be null if initialization fails
101
+ * if (optionalService) {
102
+ * optionalService.doSomething()
103
+ * }
104
+ * }
105
+ * }
106
+ * ```
107
+ */
108
+ optional<T extends ClassType>(token: T): (InstanceType<T> extends Factorable<infer R> ? R : InstanceType<T>) | null;
109
+ optional<T, S extends InjectionTokenSchemaType>(token: InjectionToken<T, S>, args: z.input<S>): T | null;
110
+ optional<T, S extends InjectionTokenSchemaType, R extends boolean>(token: InjectionToken<T, S, R>): R extends false ? T | null : S extends ZodType<infer Type> ? `Error: Your token requires args: ${Join<UnionToArray<keyof Type>, ', '>}` : 'Error: Your token requires args';
111
+ optional<T>(token: InjectionToken<T, undefined>): T | null;
112
+ optional<T>(token: BoundInjectionToken<T, any>): T | null;
113
+ optional<T>(token: FactoryInjectionToken<T, any>): T | null;
114
+ wrapSyncInit(cb: () => any): (injectState?: InjectState) => [any, Promise<any>[], InjectState];
115
+ provideFactoryContext(context: FactoryContext | null): FactoryContext | null;
116
+ }
117
+ declare function getInjectors(): Injectors;
118
+ //#endregion
119
+ //#region src/utils/get-injectable-token.d.mts
120
+ declare function getInjectableToken<R>(target: ClassType): R extends {
121
+ create(...args: any[]): infer V;
122
+ } ? InjectionToken<V> : InjectionToken<R>;
123
+ //#endregion
124
+ //#region src/internal/context/factory-context.d.mts
125
+ /**
126
+ * Context provided to factory functions during service instantiation.
127
+ *
128
+ * Provides access to dependency injection (via inject), the container,
129
+ * and lifecycle hooks for cleanup.
130
+ */
131
+ interface FactoryContext {
132
+ inject: Injectors['asyncInject'];
133
+ /**
134
+ * The container instance for dependency resolution.
135
+ * This may be either a Container or ScopedContainer.
136
+ */
137
+ container: IContainer;
138
+ addDestroyListener: (listener: () => void) => void;
139
+ }
140
+ //#endregion
141
+ //#region src/token/injection-token.d.mts
142
+ type ClassType = new (...args: any[]) => any;
143
+ type ClassTypeWithoutArguments = new () => any;
144
+ type ClassTypeWithArgument<Arg> = new (arg: Arg) => any;
145
+ type ClassTypeWithOptionalArgument<Arg> = new (arg?: Arg) => any;
146
+ type ClassTypeWithInstance<T> = new (...args: any[]) => T;
147
+ type ClassTypeWithInstanceAndArgument<T, Arg> = new (arg: Arg) => T;
148
+ type ClassTypeWithInstanceAndOptionalArgument<T, Arg> = new (arg?: Arg) => T;
149
+ type BaseInjectionTokenSchemaType = ZodObject | ZodRecord;
150
+ type OptionalInjectionTokenSchemaType = ZodOptional<ZodObject> | ZodOptional<ZodRecord>;
151
+ type InjectionTokenSchemaType = BaseInjectionTokenSchemaType | OptionalInjectionTokenSchemaType;
152
+ declare class InjectionToken<T, S extends InjectionTokenSchemaType | unknown = unknown, Required extends boolean = (S extends ZodOptional<ZodObject> ? false : S extends ZodOptional<ZodRecord> ? false : S extends ZodObject ? true : S extends ZodRecord ? true : false)> {
153
+ readonly name: string | symbol | ClassType;
154
+ readonly schema: ZodObject | undefined;
155
+ id: `${string}-${string}-${string}-${string}-${string}`;
156
+ private formattedName;
157
+ constructor(name: string | symbol | ClassType, schema: ZodObject | undefined);
158
+ static create<T extends ClassType>(name: T): InjectionToken<InstanceType<T>, undefined>;
159
+ static create<T extends ClassType, Schema extends InjectionTokenSchemaType>(name: T, schema: Schema): Schema['_def']['type'] extends 'ZodOptional' ? InjectionToken<InstanceType<T>, Schema, false> : InjectionToken<InstanceType<T>, Schema, true>;
160
+ static create<T>(name: string | symbol): InjectionToken<T, undefined>;
161
+ static create<T, Schema extends InjectionTokenSchemaType>(name: string | any, schema: Schema): InjectionToken<T, Schema>;
162
+ static bound<T, S extends InjectionTokenSchemaType>(token: InjectionToken<T, S>, value: z.input<S>): BoundInjectionToken<T, S>;
163
+ static factory<T, S extends InjectionTokenSchemaType>(token: InjectionToken<T, S>, factory: (ctx: FactoryContext) => Promise<z.input<S>>): FactoryInjectionToken<T, S>;
164
+ static refineType<T>(token: BoundInjectionToken<any, any>): BoundInjectionToken<T, any>;
165
+ toString(): string;
166
+ }
167
+ declare class BoundInjectionToken<T, S extends InjectionTokenSchemaType> {
168
+ readonly token: InjectionToken<T, S>;
169
+ readonly value: z.input<S>;
170
+ id: string;
171
+ name: string | symbol | ClassType;
172
+ schema: InjectionTokenSchemaType;
173
+ constructor(token: InjectionToken<T, S>, value: z.input<S>);
174
+ toString(): string;
175
+ }
176
+ declare class FactoryInjectionToken<T, S extends InjectionTokenSchemaType> {
177
+ readonly token: InjectionToken<T, S>;
178
+ readonly factory: (ctx: FactoryContext) => Promise<z.input<S>>;
179
+ value?: z.input<S>;
180
+ resolved: boolean;
181
+ id: string;
182
+ name: string | symbol | ClassType;
183
+ schema: InjectionTokenSchemaType;
184
+ constructor(token: InjectionToken<T, S>, factory: (ctx: FactoryContext) => Promise<z.input<S>>);
185
+ resolve(ctx: FactoryContext): Promise<z.input<S>>;
186
+ toString(): string;
187
+ }
188
+ type AnyInjectableType = ClassType | InjectionToken<any, any> | BoundInjectionToken<any, any> | FactoryInjectionToken<any, any>;
189
+ type InjectionTokenType = InjectionToken<any, any> | BoundInjectionToken<any, any> | FactoryInjectionToken<any, any>;
190
+ //#endregion
191
+ //#region src/enums/injectable-scope.enum.d.mts
192
+ declare enum InjectableScope {
193
+ /**
194
+ * Singleton scope: The instance is created once and shared across the application.
195
+ */
196
+ Singleton = "Singleton",
197
+ /**
198
+ * Instance scope: A new instance is created for each injection.
199
+ */
200
+ Transient = "Transient",
201
+ /**
202
+ * Request scope: The instance is created once per request and shared within that request context.
203
+ */
204
+ Request = "Request",
205
+ }
206
+ //#endregion
207
+ //#region src/enums/injectable-type.enum.d.mts
208
+ declare enum InjectableType {
209
+ Class = "Class",
210
+ Factory = "Factory",
211
+ }
212
+ //#endregion
213
+ //#region src/token/registry.d.mts
214
+ type FactoryRecord<Instance = any, Schema = any> = {
215
+ scope: InjectableScope;
216
+ originalToken: InjectionToken<Instance, Schema>;
217
+ target: ClassType;
218
+ type: InjectableType;
219
+ };
220
+ declare class Registry {
221
+ private readonly parent?;
222
+ private readonly factories;
223
+ constructor(parent?: Registry | undefined);
224
+ has(token: InjectionToken<any, any>): boolean;
225
+ get<Instance, Schema>(token: InjectionToken<Instance, Schema>): FactoryRecord<Instance, Schema>;
226
+ set<Instance, Schema>(token: InjectionToken<Instance, Schema>, scope: InjectableScope, target: ClassType, type: InjectableType): void;
227
+ delete(token: InjectionToken<any, any>): void;
228
+ }
229
+ declare const globalRegistry: Registry;
230
+ //#endregion
231
+ //#region src/errors/di-error.d.mts
232
+ declare enum DIErrorCode {
233
+ FactoryNotFound = "FactoryNotFound",
234
+ FactoryTokenNotResolved = "FactoryTokenNotResolved",
235
+ InstanceNotFound = "InstanceNotFound",
236
+ InstanceDestroying = "InstanceDestroying",
237
+ CircularDependency = "CircularDependency",
238
+ UnknownError = "UnknownError",
239
+ }
240
+ declare class DIError extends Error {
241
+ readonly code: DIErrorCode;
242
+ readonly message: string;
243
+ readonly context?: Record<string, unknown>;
244
+ constructor(code: DIErrorCode, message: string, context?: Record<string, unknown>);
245
+ static factoryNotFound(name: string): DIError;
246
+ static factoryTokenNotResolved(token: string | symbol | unknown): DIError;
247
+ static instanceNotFound(name: string): DIError;
248
+ static instanceDestroying(name: string): DIError;
249
+ static unknown(message: string | Error, context?: Record<string, unknown>): DIError;
250
+ static circularDependency(cycle: string[]): DIError;
251
+ }
252
+ //#endregion
253
+ //#region src/internal/holder/instance-holder.d.mts
254
+ /**
255
+ * Represents the lifecycle status of an instance holder.
256
+ */
257
+ declare enum InstanceStatus {
258
+ /** Instance has been successfully created and is ready for use */
259
+ Created = "created",
260
+ /** Instance is currently being created (async initialization in progress) */
261
+ Creating = "creating",
262
+ /** Instance is being destroyed (cleanup in progress) */
263
+ Destroying = "destroying",
264
+ /** Instance creation failed with an error */
265
+ Error = "error",
266
+ }
267
+ /** Callback function for instance effects */
268
+ type InstanceEffect = () => void;
269
+ /** Callback function for instance destruction listeners */
270
+ type InstanceDestroyListener = () => void | Promise<void>;
271
+ /**
272
+ * Instance holder in the Creating state.
273
+ * The instance is null while creation is in progress.
274
+ */
275
+ interface InstanceHolderCreating<Instance> {
276
+ status: InstanceStatus.Creating;
277
+ name: string;
278
+ instance: null;
279
+ creationPromise: Promise<[undefined, Instance]> | null;
280
+ destroyPromise: null;
281
+ type: InjectableType;
282
+ scope: InjectableScope;
283
+ deps: Set<string>;
284
+ destroyListeners: InstanceDestroyListener[];
285
+ createdAt: number;
286
+ /** Tracks which services this holder is currently waiting for (for circular dependency detection) */
287
+ waitingFor: Set<string>;
288
+ }
289
+ /**
290
+ * Instance holder in the Created state.
291
+ * The instance is available and ready for use.
292
+ */
293
+ interface InstanceHolderCreated<Instance> {
294
+ status: InstanceStatus.Created;
295
+ name: string;
296
+ instance: Instance;
297
+ creationPromise: null;
298
+ destroyPromise: null;
299
+ type: InjectableType;
300
+ scope: InjectableScope;
301
+ deps: Set<string>;
302
+ destroyListeners: InstanceDestroyListener[];
303
+ createdAt: number;
304
+ /** Tracks which services this holder is currently waiting for (for circular dependency detection) */
305
+ waitingFor: Set<string>;
306
+ }
307
+ /**
308
+ * Instance holder in the Destroying state.
309
+ * The instance may still be available but is being cleaned up.
310
+ */
311
+ interface InstanceHolderDestroying<Instance> {
312
+ status: InstanceStatus.Destroying;
313
+ name: string;
314
+ instance: Instance | null;
315
+ creationPromise: null;
316
+ destroyPromise: Promise<void>;
317
+ type: InjectableType;
318
+ scope: InjectableScope;
319
+ deps: Set<string>;
320
+ destroyListeners: InstanceDestroyListener[];
321
+ createdAt: number;
322
+ /** Tracks which services this holder is currently waiting for (for circular dependency detection) */
323
+ waitingFor: Set<string>;
324
+ }
325
+ /**
326
+ * Instance holder in the Error state.
327
+ * The instance field contains the error that occurred during creation.
328
+ */
329
+ interface InstanceHolderError {
330
+ status: InstanceStatus.Error;
331
+ name: string;
332
+ instance: Error;
333
+ creationPromise: null;
334
+ destroyPromise: null;
335
+ type: InjectableType;
336
+ scope: InjectableScope;
337
+ deps: Set<string>;
338
+ destroyListeners: InstanceDestroyListener[];
339
+ createdAt: number;
340
+ /** Tracks which services this holder is currently waiting for (for circular dependency detection) */
341
+ waitingFor: Set<string>;
342
+ }
343
+ /**
344
+ * Holds the state of a service instance throughout its lifecycle.
345
+ *
346
+ * Tracks creation/destruction promises, dependency relationships,
347
+ * destroy listeners, and current status (Creating, Created, Destroying, Error).
348
+ */
349
+ type InstanceHolder<Instance = unknown> = InstanceHolderCreating<Instance> | InstanceHolderCreated<Instance> | InstanceHolderDestroying<Instance> | InstanceHolderError;
350
+ //#endregion
351
+ //#region src/internal/holder/holder-storage.interface.d.mts
352
+ /**
353
+ * Result type for holder retrieval operations.
354
+ * - [undefined, holder] - Holder found successfully
355
+ * - [DIError, holder?] - Error occurred (holder may be available for waiting)
356
+ * - null - No holder exists
357
+ */
358
+ type HolderGetResult<T = unknown> = [undefined, InstanceHolder<T>] | [DIError, InstanceHolder<T>?] | null;
359
+ /**
360
+ * Interface for abstracting holder storage operations.
361
+ *
362
+ * Enables unified instance resolution logic regardless of where
363
+ * holders are stored (singleton manager, request context, etc.).
364
+ * This is the key abstraction for the Storage Strategy pattern.
365
+ */
366
+ interface IHolderStorage {
367
+ /**
368
+ * The scope this storage handles.
369
+ */
370
+ readonly scope: InjectableScope;
371
+ /**
372
+ * Retrieves an existing holder by instance name.
373
+ *
374
+ * @param instanceName The unique identifier for the instance
375
+ * @returns
376
+ * - [undefined, holder] if found and ready/creating
377
+ * - [DIError, holder?] if found but in error/destroying state
378
+ * - null if not found
379
+ */
380
+ get<T = unknown>(instanceName: string): HolderGetResult<T>;
381
+ /**
382
+ * Stores a holder by instance name.
383
+ *
384
+ * @param instanceName The unique identifier for the instance
385
+ * @param holder The holder to store
386
+ */
387
+ set(instanceName: string, holder: InstanceHolder): void;
388
+ /**
389
+ * Deletes a holder by instance name.
390
+ *
391
+ * @param instanceName The unique identifier for the instance
392
+ * @returns true if the holder was deleted, false if it didn't exist
393
+ */
394
+ delete(instanceName: string): boolean;
395
+ /**
396
+ * Creates a new holder in "Creating" state with a deferred promise.
397
+ * The holder is NOT automatically stored - call set() to store it.
398
+ *
399
+ * @param instanceName The unique identifier for the instance
400
+ * @param type The injectable type
401
+ * @param deps The set of dependency names
402
+ * @returns A tuple containing the deferred promise resolver and the holder
403
+ */
404
+ createHolder<T>(instanceName: string, type: InjectableType, deps: Set<string>): [ReturnType<typeof Promise.withResolvers<[undefined, T]>>, InstanceHolder<T>];
405
+ /**
406
+ * Checks if this storage should be used for the given scope.
407
+ */
408
+ handles(scope: InjectableScope): boolean;
409
+ /**
410
+ * Gets all instance names in this storage.
411
+ */
412
+ getAllNames(): string[];
413
+ /**
414
+ * Iterates over all holders with a callback.
415
+ *
416
+ * @param callback Function called for each holder with (name, holder)
417
+ */
418
+ forEach(callback: (name: string, holder: InstanceHolder) => void): void;
419
+ /**
420
+ * Finds a holder by its instance value (reverse lookup).
421
+ *
422
+ * @param instance The instance to search for
423
+ * @returns The holder if found, null otherwise
424
+ */
425
+ findByInstance(instance: unknown): InstanceHolder | null;
426
+ /**
427
+ * Finds all instance names that depend on the given instance name.
428
+ *
429
+ * @param instanceName The instance name to find dependents for
430
+ * @returns Array of instance names that have this instance as a dependency
431
+ */
432
+ findDependents(instanceName: string): string[];
433
+ }
434
+ //#endregion
435
+ //#region src/internal/holder/base-holder-manager.d.mts
436
+ /**
437
+ * Result type for waitForHolderReady.
438
+ * Returns either [undefined, holder] on success or [error] on failure.
439
+ */
440
+ type HolderReadyResult<T> = [undefined, InstanceHolder<T>] | [DIError];
441
+ /**
442
+ * Abstract base class providing common functionality for managing InstanceHolder objects.
443
+ *
444
+ * Provides shared patterns for holder storage, creation, and lifecycle management
445
+ * used by both singleton (HolderManager) and request-scoped (RequestContext) managers.
446
+ */
447
+ declare abstract class BaseHolderManager {
448
+ protected readonly logger: Console | null;
449
+ protected readonly _holders: Map<string, InstanceHolder>;
450
+ constructor(logger?: Console | null);
451
+ /**
452
+ * Protected getter for accessing the holders map from subclasses.
453
+ */
454
+ protected get holders(): Map<string, InstanceHolder>;
455
+ /**
456
+ * Abstract method to get a holder by name. Each implementation defines its own return type
457
+ * based on their specific error handling and validation needs.
458
+ */
459
+ abstract get(name: string): any;
460
+ /**
461
+ * Abstract method to set a holder by name. Each implementation may have different validation logic.
462
+ */
463
+ abstract set(name: string, holder: InstanceHolder): void;
464
+ /**
465
+ * Abstract method to check if a holder exists. Each implementation may have different validation logic.
466
+ */
467
+ abstract has(name: string): any;
468
+ /**
469
+ * Deletes a holder by name.
470
+ * @param name The name of the holder to delete
471
+ * @returns true if the holder was deleted, false if it didn't exist
472
+ */
473
+ delete(name: string): boolean;
474
+ /**
475
+ * Filters holders based on a predicate function.
476
+ * @param predicate Function to test each holder
477
+ * @returns A new Map containing only the holders that match the predicate
478
+ */
479
+ filter(predicate: (value: InstanceHolder<any>, key: string) => boolean): Map<string, InstanceHolder>;
480
+ /**
481
+ * Clears all holders from this manager.
482
+ */
483
+ clear(): void;
484
+ /**
485
+ * Gets the number of holders currently managed.
486
+ */
487
+ size(): number;
488
+ /**
489
+ * Creates a new holder with Creating status and a deferred creation promise.
490
+ * This is useful for creating placeholder holders that can be fulfilled later.
491
+ * @param name The name of the instance
492
+ * @param type The injectable type
493
+ * @param scope The injectable scope
494
+ * @param deps Optional set of dependencies
495
+ * @returns A tuple containing the deferred promise and the holder
496
+ */
497
+ createCreatingHolder<Instance>(name: string, type: InjectableType, scope: InjectableScope, deps?: Set<string>): [ReturnType<typeof Promise.withResolvers<[undefined, Instance]>>, InstanceHolder<Instance>];
498
+ /**
499
+ * Creates a new holder with Created status and an actual instance.
500
+ * This is useful for creating holders that already have their instance ready.
501
+ * @param name The name of the instance
502
+ * @param instance The actual instance to store
503
+ * @param type The injectable type
504
+ * @param scope The injectable scope
505
+ * @param deps Optional set of dependencies
506
+ * @returns The created holder
507
+ */
508
+ protected createCreatedHolder<Instance>(name: string, instance: Instance, type: InjectableType, scope: InjectableScope, deps?: Set<string>): InstanceHolder<Instance>;
509
+ /**
510
+ * Gets all holder names currently managed.
511
+ */
512
+ getAllNames(): string[];
513
+ /**
514
+ * Gets all holders currently managed.
515
+ */
516
+ getAllHolders(): InstanceHolder[];
517
+ /**
518
+ * Checks if this manager has any holders.
519
+ */
520
+ isEmpty(): boolean;
521
+ /**
522
+ * Waits for a holder to be ready and returns the appropriate result.
523
+ * This is a shared utility used by both singleton and request-scoped resolution.
524
+ *
525
+ * @param holder The holder to wait for
526
+ * @param waiterHolder Optional holder that is doing the waiting (for circular dependency detection)
527
+ * @param getHolder Optional function to retrieve holders by name (required if waiterHolder is provided)
528
+ * @returns A promise that resolves with [undefined, holder] on success or [DIError] on failure
529
+ */
530
+ static waitForHolderReady<T>(holder: InstanceHolder<T>, waiterHolder?: InstanceHolder, getHolder?: (name: string) => InstanceHolder | undefined): Promise<HolderReadyResult<T>>;
531
+ }
532
+ //#endregion
533
+ //#region src/internal/context/request-context.d.mts
534
+ /**
535
+ * Interface for request context that manages pre-prepared instances for a specific request.
536
+ *
537
+ * Provides isolated storage for request-scoped services, enabling efficient
538
+ * instantiation and cleanup within the lifecycle of a single request.
539
+ */
540
+ interface RequestContext {
541
+ /**
542
+ * Unique identifier for this request context.
543
+ */
544
+ readonly requestId: string;
545
+ /**
546
+ * Instance holders for request-scoped services.
547
+ */
548
+ readonly holders: Map<string, InstanceHolder>;
549
+ /**
550
+ * Priority for resolution in FactoryContext.inject method.
551
+ * Higher values take precedence.
552
+ */
553
+ readonly priority: number;
554
+ /**
555
+ * Request-specific metadata that can be used during instantiation.
556
+ */
557
+ readonly metadata: Map<string, any>;
558
+ /**
559
+ * Timestamp when this context was created.
560
+ */
561
+ readonly createdAt: number;
562
+ /**
563
+ * Adds a pre-prepared instance to this context.
564
+ */
565
+ addInstance(instanceName: string, instance: any, holder: InstanceHolder): void;
566
+ /**
567
+ * Adds a pre-prepared instance to this context.
568
+ */
569
+ addInstance(token: InjectionToken<any, undefined>, instance: any): void;
570
+ /**
571
+ * Gets an instance holder from this context.
572
+ */
573
+ get(instanceName: string): InstanceHolder | undefined;
574
+ /**
575
+ * Sets an instance holder by name.
576
+ */
577
+ set(instanceName: string, holder: InstanceHolder): void;
578
+ /**
579
+ * Checks if this context has a pre-prepared instance.
580
+ */
581
+ has(instanceName: string): boolean;
582
+ /**
583
+ * Clears all instances and holders from this context.
584
+ */
585
+ clear(): void;
586
+ /**
587
+ * Gets metadata value by key.
588
+ */
589
+ getMetadata(key: string): any | undefined;
590
+ /**
591
+ * Sets metadata value by key.
592
+ */
593
+ setMetadata(key: string, value: any): void;
594
+ /**
595
+ * Filters holders based on a predicate function.
596
+ */
597
+ filter(predicate: (value: InstanceHolder<any>, key: string) => boolean): Map<string, InstanceHolder>;
598
+ /**
599
+ * Deletes a holder by name.
600
+ */
601
+ delete(name: string): boolean;
602
+ /**
603
+ * Gets the number of holders currently managed.
604
+ */
605
+ size(): number;
606
+ /**
607
+ * Checks if this manager has any holders.
608
+ */
609
+ isEmpty(): boolean;
610
+ }
611
+ /** @deprecated Use RequestContext instead */
612
+ type RequestContextHolder = RequestContext;
613
+ /**
614
+ * Default implementation of RequestContext.
615
+ *
616
+ * Extends BaseHolderManager to provide holder management functionality
617
+ * with request-specific metadata and lifecycle support.
618
+ */
619
+ declare class DefaultRequestContext extends BaseHolderManager implements RequestContext {
620
+ readonly requestId: string;
621
+ readonly priority: number;
622
+ readonly metadata: Map<string, any>;
623
+ readonly createdAt: number;
624
+ constructor(requestId: string, priority?: number, initialMetadata?: Record<string, any>);
625
+ /**
626
+ * Public getter for holders to maintain interface compatibility.
627
+ */
628
+ get holders(): Map<string, InstanceHolder>;
629
+ /**
630
+ * Gets a holder by name. For RequestContext, this is a simple lookup.
631
+ */
632
+ get(name: string): InstanceHolder | undefined;
633
+ /**
634
+ * Sets a holder by name.
635
+ */
636
+ set(name: string, holder: InstanceHolder): void;
637
+ /**
638
+ * Checks if a holder exists by name.
639
+ */
640
+ has(name: string): boolean;
641
+ addInstance(instanceName: string | InjectionToken<any, undefined>, instance: any, holder?: InstanceHolder): void;
642
+ clear(): void;
643
+ getMetadata(key: string): any | undefined;
644
+ setMetadata(key: string, value: any): void;
645
+ }
646
+ /**
647
+ * Creates a new request context with the given parameters.
648
+ */
649
+ declare function createRequestContext(requestId: string, priority?: number, initialMetadata?: Record<string, any>): RequestContext;
650
+ //#endregion
651
+ //#region src/container/scoped-container.d.mts
652
+ /**
653
+ * Request-scoped dependency injection container.
654
+ *
655
+ * Wraps a parent Container and provides isolated request-scoped instances
656
+ * while delegating singleton and transient resolution to the parent.
657
+ * This design eliminates race conditions that can occur with async operations
658
+ * when multiple requests are processed concurrently.
659
+ */
660
+ declare class ScopedContainer implements IContainer {
661
+ private readonly parent;
662
+ private readonly registry;
663
+ readonly requestId: string;
664
+ private readonly requestContextHolder;
665
+ private readonly holderStorage;
666
+ private disposed;
667
+ constructor(parent: Container, registry: Registry, requestId: string, metadata?: Record<string, any>, priority?: number);
668
+ /**
669
+ * Gets the request context holder for this scoped container.
670
+ */
671
+ getRequestContextHolder(): RequestContext;
672
+ /**
673
+ * Gets the holder storage for this scoped container.
674
+ * Used by InstanceResolver for request-scoped resolution.
675
+ */
676
+ getHolderStorage(): IHolderStorage;
677
+ /**
678
+ * Gets the request ID for this scoped container.
679
+ */
680
+ getRequestId(): string;
681
+ /**
682
+ * Gets the parent container.
683
+ */
684
+ getParent(): Container;
685
+ /**
686
+ * Gets metadata from the request context.
687
+ */
688
+ getMetadata(key: string): any | undefined;
689
+ /**
690
+ * Sets metadata on the request context.
691
+ */
692
+ setMetadata(key: string, value: any): void;
693
+ /**
694
+ * Adds a pre-prepared instance to the request context.
695
+ */
696
+ addInstance(token: InjectionToken<any, undefined>, instance: any): void;
697
+ /**
698
+ * Gets an instance from the container.
699
+ * Request-scoped services are resolved from this container's context.
700
+ * All other services are delegated to the parent container.
701
+ */
702
+ get<T extends ClassType>(token: T): InstanceType<T> extends Factorable<infer R> ? Promise<R> : Promise<InstanceType<T>>;
703
+ get<T extends ClassTypeWithArgument<R>, R>(token: T, args: R): Promise<InstanceType<T>>;
704
+ get<T, S extends InjectionTokenSchemaType>(token: InjectionToken<T, S>, args: z.input<S>): Promise<T>;
705
+ get<T, S extends InjectionTokenSchemaType, R extends boolean>(token: InjectionToken<T, S, R>): R extends false ? Promise<T> : S extends ZodType<infer Type> ? `Error: Your token requires args: ${Join<UnionToArray<keyof Type>, ', '>}` : 'Error: Your token requires args';
706
+ get<T>(token: InjectionToken<T, undefined>): Promise<T>;
707
+ get<T>(token: BoundInjectionToken<T, any>): Promise<T>;
708
+ get<T>(token: FactoryInjectionToken<T, any>): Promise<T>;
709
+ /**
710
+ * Invalidates a service and its dependencies.
711
+ * For request-scoped services, invalidation is handled within this context.
712
+ */
713
+ invalidate(service: unknown): Promise<void>;
714
+ /**
715
+ * Checks if a service is registered.
716
+ */
717
+ isRegistered(token: any): boolean;
718
+ /**
719
+ * Disposes this scoped container and cleans up all request-scoped instances.
720
+ * This is an alias for endRequest() for IContainer compatibility.
721
+ */
722
+ dispose(): Promise<void>;
723
+ /**
724
+ * Ends the request and cleans up all request-scoped instances.
725
+ * Uses the invalidation system to properly cascade to dependent singletons.
726
+ */
727
+ endRequest(): Promise<void>;
728
+ /**
729
+ * Waits for all pending operations to complete.
730
+ */
731
+ ready(): Promise<void>;
732
+ /**
733
+ * @internal
734
+ * Attempts to get an instance synchronously if it already exists and is ready.
735
+ * For request-scoped services, checks this container's context first.
736
+ * For other services, delegates to the parent container.
737
+ *
738
+ * Returns null if the instance doesn't exist or is not yet ready (still creating).
739
+ */
740
+ tryGetSync<T>(token: any, args?: any): T | null;
741
+ /**
742
+ * Checks if a token is for a request-scoped service.
743
+ */
744
+ private isRequestScoped;
745
+ /**
746
+ * Resolves a request-scoped service from this container's context.
747
+ * Uses locking to prevent duplicate initialization during concurrent resolution.
748
+ */
749
+ private resolveRequestScoped;
750
+ /**
751
+ * Stores an instance in the request context.
752
+ * Called by Container during request-scoped service resolution.
753
+ */
754
+ storeRequestInstance(instanceName: string, instance: any, holder: InstanceHolder): void;
755
+ /**
756
+ * Gets an existing instance from the request context.
757
+ * Called by Container during resolution to check for existing instances.
758
+ */
759
+ getRequestInstance(instanceName: string): InstanceHolder | undefined;
760
+ /**
761
+ * Generates a prefixed event name for request-scoped services.
762
+ * Format: {requestId}:{instanceName}
763
+ */
764
+ getPrefixedEventName(instanceName: string): string;
765
+ }
766
+ //#endregion
767
+ //#region src/internal/lifecycle/lifecycle-event-bus.d.mts
768
+ /**
769
+ * Event bus for service lifecycle events (create, destroy, etc.).
770
+ *
771
+ * Enables loose coupling between services by allowing them to subscribe
772
+ * to lifecycle events of their dependencies without direct references.
773
+ * Used primarily for invalidation cascading.
774
+ */
775
+ declare class LifecycleEventBus {
776
+ private readonly logger;
777
+ private listeners;
778
+ constructor(logger?: Console | null);
779
+ on<Event extends string | `pre:${string}` | `post:${string}`>(ns: string, event: Event, listener: (event: Event) => void): () => void;
780
+ emit(key: string, event: string): Promise<PromiseSettledResult<any>[] | undefined>;
781
+ }
782
+ //#endregion
783
+ //#region src/internal/holder/holder-manager.d.mts
784
+ /**
785
+ * Manages the storage and retrieval of singleton instance holders.
786
+ *
787
+ * Provides CRUD operations and filtering for the holder map.
788
+ * Handles holder state validation (destroying, error states) on retrieval.
789
+ */
790
+ declare class HolderManager extends BaseHolderManager {
791
+ constructor(logger?: Console | null);
792
+ get(name: string): [DIError, InstanceHolder] | [DIError] | [undefined, InstanceHolder];
793
+ set(name: string, holder: InstanceHolder): void;
794
+ has(name: string): [DIError] | [undefined, boolean];
795
+ /**
796
+ * Creates a new holder with Created status and stores it.
797
+ * This is useful for creating holders that already have their instance ready.
798
+ * @param name The name of the instance
799
+ * @param instance The actual instance to store
800
+ * @param type The injectable type
801
+ * @param scope The injectable scope
802
+ * @param deps Optional set of dependencies
803
+ * @returns The created holder
804
+ */
805
+ storeCreatedHolder<Instance>(name: string, instance: Instance, type: InjectableType, scope: InjectableScope, deps?: Set<string>): InstanceHolder<Instance>;
806
+ }
807
+ //#endregion
808
+ //#region src/internal/core/invalidator.d.mts
809
+ interface ClearAllOptions {
810
+ /** Maximum number of invalidation rounds to prevent infinite loops (default: 10) */
811
+ maxRounds?: number;
812
+ /** Whether to wait for all services to settle before starting (default: true) */
813
+ waitForSettlement?: boolean;
814
+ }
815
+ interface InvalidationOptions {
816
+ /** Whether to emit events after invalidation (default: true for singletons) */
817
+ emitEvents?: boolean;
818
+ /** Custom event emitter function */
819
+ onInvalidated?: (instanceName: string) => Promise<void>;
820
+ /** Whether to cascade invalidation to dependents (default: true) */
821
+ cascade?: boolean;
822
+ /** Internal: tracks services being invalidated in the current call chain to prevent circular loops */
823
+ _invalidating?: Set<string>;
824
+ }
825
+ /**
826
+ * Manages graceful service cleanup with dependency-aware invalidation.
827
+ *
828
+ * Ensures services are destroyed in the correct order based on their dependencies.
829
+ * Works with any IHolderStorage implementation, enabling unified invalidation
830
+ * for both singleton and request-scoped services.
831
+ */
832
+ declare class Invalidator {
833
+ private readonly eventBus;
834
+ private readonly logger;
835
+ private readonly storage;
836
+ constructor(manager: HolderManager, eventBus: LifecycleEventBus | null, logger?: Console | null);
837
+ /**
838
+ * Invalidates a service and all its dependencies.
839
+ * Works with the configured storage (singleton by default).
840
+ */
841
+ invalidate(service: string, round?: number): Promise<any>;
842
+ /**
843
+ * Invalidates a service using a specific storage.
844
+ * This allows request-scoped invalidation using a RequestStorage.
845
+ *
846
+ * @param service The instance name to invalidate
847
+ * @param storage The storage to use for this invalidation
848
+ * @param round Current invalidation round (for recursion limiting)
849
+ * @param options Additional options for invalidation behavior
850
+ */
851
+ invalidateWithStorage(service: string, storage: IHolderStorage, round?: number, options?: InvalidationOptions): Promise<void>;
852
+ /**
853
+ * Gracefully clears all services using invalidation logic.
854
+ * This method respects service dependencies and ensures proper cleanup order.
855
+ * Services that depend on others will be invalidated first, then their dependencies.
856
+ */
857
+ clearAll(options?: ClearAllOptions): Promise<void>;
858
+ /**
859
+ * Gracefully clears all services in a specific storage.
860
+ * This allows clearing request-scoped services using a RequestStorage.
861
+ */
862
+ clearAllWithStorage(storage: IHolderStorage, options?: ClearAllOptions): Promise<void>;
863
+ /**
864
+ * Waits for all services to settle (either created, destroyed, or error state).
865
+ */
866
+ ready(): Promise<void>;
867
+ /**
868
+ * Waits for all services in a specific storage to settle.
869
+ */
870
+ readyWithStorage(storage: IHolderStorage): Promise<void>;
871
+ /**
872
+ * Invalidates a single holder using a specific storage.
873
+ */
874
+ private invalidateHolderWithStorage;
875
+ /**
876
+ * Common invalidation logic for holders based on their status.
877
+ */
878
+ private invalidateHolderByStatus;
879
+ /**
880
+ * Destroys a holder using a specific storage.
881
+ */
882
+ private destroyHolderWithStorage;
883
+ /**
884
+ * Waits for a holder to settle (either created, destroyed, or error state).
885
+ */
886
+ private waitForHolderToSettle;
887
+ /**
888
+ * Clears services with dependency awareness for a specific storage.
889
+ */
890
+ private clearServicesWithDependencyAwarenessForStorage;
891
+ /**
892
+ * Finds services that are ready to be cleared in the current round.
893
+ * A service is ready if all its dependencies have already been cleared.
894
+ */
895
+ private findServicesReadyForClearingInStorage;
896
+ /**
897
+ * Force clears services that couldn't be cleared through normal dependency resolution.
898
+ * This handles edge cases like circular dependencies.
899
+ */
900
+ private forceClearServicesInStorage;
901
+ /**
902
+ * Emits events to listeners for instance lifecycle events.
903
+ */
904
+ private emitInstanceEvent;
905
+ }
906
+ //#endregion
907
+ //#region src/internal/core/token-processor.d.mts
908
+ /**
909
+ * Handles token validation, normalization, and instance name generation.
910
+ *
911
+ * Provides utilities for resolving tokens to their underlying InjectionToken,
912
+ * validating arguments against schemas, and generating unique instance identifiers.
913
+ */
914
+ declare class TokenProcessor {
915
+ private readonly logger;
916
+ constructor(logger?: Console | null);
917
+ /**
918
+ * Normalizes a token to an InjectionToken.
919
+ * Handles class constructors by getting their injectable token.
920
+ *
921
+ * @param token A class constructor, InjectionToken, BoundInjectionToken, or FactoryInjectionToken
922
+ * @returns The normalized InjectionTokenType
923
+ */
924
+ normalizeToken(token: AnyInjectableType): InjectionTokenType;
925
+ /**
926
+ * Gets the underlying "real" token from wrapped tokens.
927
+ * For BoundInjectionToken and FactoryInjectionToken, returns the wrapped token.
928
+ * For other tokens, returns the token itself.
929
+ *
930
+ * @param token The token to unwrap
931
+ * @returns The underlying InjectionToken
932
+ */
933
+ getRealToken<T = unknown>(token: InjectionTokenType): InjectionToken<T>;
934
+ /**
935
+ * Convenience method that normalizes a token and then gets the real token.
936
+ * Useful for checking registry entries where you need the actual registered token.
937
+ *
938
+ * @param token Any injectable type
939
+ * @returns The underlying InjectionToken
940
+ */
941
+ getRegistryToken<T = unknown>(token: AnyInjectableType): InjectionToken<T>;
942
+ /**
943
+ * Validates and resolves token arguments, handling factory token resolution and validation.
944
+ */
945
+ validateAndResolveTokenArgs(token: AnyInjectableType, args?: any): [DIError | undefined, {
946
+ actualToken: InjectionTokenType;
947
+ validatedArgs?: any;
948
+ }];
949
+ /**
950
+ * Generates a unique instance name based on token and arguments.
951
+ */
952
+ generateInstanceName(token: InjectionTokenType, args: any): string;
953
+ /**
954
+ * Formats a single argument value for instance name generation.
955
+ */
956
+ formatArgValue(value: any): string;
957
+ /**
958
+ * Creates a factory context for dependency injection during service instantiation.
959
+ * @param container The container instance (Container or ScopedContainer) for dependency resolution
960
+ * @param onDependencyResolved Callback when a dependency is resolved, receives the instance name
961
+ */
962
+ createFactoryContext(container: IContainer, onDependencyResolved?: (instanceName: string) => void): FactoryContext & {
963
+ getDestroyListeners: () => (() => void)[];
964
+ deps: Set<string>;
965
+ };
966
+ }
967
+ //#endregion
968
+ //#region src/internal/core/service-locator.d.mts
969
+ /**
970
+ * Core DI engine that coordinates service instantiation, resolution, and lifecycle.
971
+ *
972
+ * Acts as the central orchestrator for dependency injection operations,
973
+ * delegating to specialized components (InstanceResolver, Instantiator, Invalidator)
974
+ * for specific tasks.
975
+ */
976
+ declare class ServiceLocator {
977
+ private readonly registry;
978
+ private readonly logger;
979
+ private readonly injectors;
980
+ private readonly eventBus;
981
+ private readonly manager;
982
+ private readonly instantiator;
983
+ private readonly tokenProcessor;
984
+ private readonly invalidator;
985
+ private readonly instanceResolver;
986
+ constructor(registry?: Registry, logger?: Console | null, injectors?: Injectors);
987
+ getEventBus(): LifecycleEventBus;
988
+ getManager(): HolderManager;
989
+ getInvalidator(): Invalidator;
990
+ getTokenProcessor(): TokenProcessor;
991
+ getInstanceIdentifier(token: AnyInjectableType, args?: any): string;
992
+ /**
993
+ * Gets or creates an instance for the given token.
994
+ * @param token The injection token
995
+ * @param args Optional arguments
996
+ * @param contextContainer The container to use for creating FactoryContext
997
+ */
998
+ getInstance(token: AnyInjectableType, args: any, contextContainer: IContainer): Promise<any[]>;
999
+ /**
1000
+ * Gets or throws an instance for the given token.
1001
+ * @param token The injection token
1002
+ * @param args Optional arguments
1003
+ * @param contextContainer The container to use for creating FactoryContext
1004
+ */
1005
+ getOrThrowInstance<Instance>(token: AnyInjectableType, args: any, contextContainer: IContainer): Promise<Instance>;
1006
+ /**
1007
+ * Resolves a request-scoped service for a ScopedContainer.
1008
+ * The service will be stored in the ScopedContainer's request context.
1009
+ *
1010
+ * @param token The injection token
1011
+ * @param args Optional arguments
1012
+ * @param scopedContainer The ScopedContainer that owns the request context
1013
+ */
1014
+ resolveRequestScoped(token: AnyInjectableType, args: any, scopedContainer: ScopedContainer): Promise<any>;
1015
+ getSyncInstance<Instance, Schema extends InjectionTokenSchemaType | undefined>(token: AnyInjectableType, args: Schema extends ZodObject ? z.input<Schema> : Schema extends ZodOptional<ZodObject> ? z.input<Schema> | undefined : undefined, contextContainer: IContainer): Instance | null;
1016
+ invalidate(service: string, round?: number): Promise<any>;
1017
+ /**
1018
+ * Gracefully clears all services in the ServiceLocator using invalidation logic.
1019
+ * This method respects service dependencies and ensures proper cleanup order.
1020
+ * Services that depend on others will be invalidated first, then their dependencies.
1021
+ *
1022
+ * @param options Optional configuration for the clearing process
1023
+ * @returns Promise that resolves when all services have been cleared
1024
+ */
1025
+ clearAll(options?: ClearAllOptions): Promise<void>;
1026
+ /**
1027
+ * Waits for all services to settle (either created, destroyed, or error state).
1028
+ */
1029
+ ready(): Promise<void>;
1030
+ /**
1031
+ * Helper method for InstanceResolver to generate instance names.
1032
+ * This is needed for the factory context creation.
1033
+ */
1034
+ generateInstanceName(token: any, args: any): string;
1035
+ }
1036
+ //#endregion
1037
+ //#region src/container/container.d.mts
1038
+ /**
1039
+ * Main dependency injection container.
1040
+ *
1041
+ * Provides a simplified public API for dependency injection, wrapping
1042
+ * a ServiceLocator instance. Handles singleton and transient services directly,
1043
+ * while request-scoped services require using beginRequest() to create a ScopedContainer.
1044
+ */
1045
+ declare class Container implements IContainer {
1046
+ protected readonly registry: Registry;
1047
+ protected readonly logger: Console | null;
1048
+ protected readonly injectors: Injectors;
1049
+ private readonly serviceLocator;
1050
+ private readonly activeRequestIds;
1051
+ constructor(registry?: Registry, logger?: Console | null, injectors?: Injectors);
1052
+ private registerSelf;
1053
+ /**
1054
+ * Gets an instance from the container.
1055
+ * This method has the same type signature as the inject method from get-injectors.mts
1056
+ *
1057
+ * NOTE: Request-scoped services cannot be resolved directly from Container.
1058
+ * Use beginRequest() to create a ScopedContainer for request-scoped services.
1059
+ */
1060
+ get<T extends ClassType>(token: T): InstanceType<T> extends Factorable<infer R> ? Promise<R> : Promise<InstanceType<T>>;
1061
+ get<T extends ClassTypeWithArgument<R>, R>(token: T, args: R): Promise<InstanceType<T>>;
1062
+ get<T, S extends InjectionTokenSchemaType>(token: InjectionToken<T, S>, args: z.input<S>): Promise<T>;
1063
+ get<T, S extends InjectionTokenSchemaType, R extends boolean>(token: InjectionToken<T, S, R>): R extends false ? Promise<T> : S extends ZodType<infer Type> ? `Error: Your token requires args: ${Join<UnionToArray<keyof Type>, ', '>}` : 'Error: Your token requires args';
1064
+ get<T>(token: InjectionToken<T, undefined>): Promise<T>;
1065
+ get<T>(token: BoundInjectionToken<T, any>): Promise<T>;
1066
+ get<T>(token: FactoryInjectionToken<T, any>): Promise<T>;
1067
+ /**
1068
+ * Gets an instance with a specific container context.
1069
+ * Used by ScopedContainer to delegate singleton/transient resolution
1070
+ * while maintaining the correct container context for nested inject() calls.
1071
+ *
1072
+ * @internal
1073
+ */
1074
+ getWithContext(token: ClassType | InjectionToken<any> | BoundInjectionToken<any, any> | FactoryInjectionToken<any, any>, args: unknown, contextContainer: IContainer): Promise<any>;
1075
+ /**
1076
+ * Resolves a request-scoped service for a ScopedContainer.
1077
+ * The service will be stored in the ScopedContainer's request context.
1078
+ *
1079
+ * @internal
1080
+ */
1081
+ resolveForRequest(token: ClassType | InjectionToken<any> | BoundInjectionToken<any, any> | FactoryInjectionToken<any, any>, args: unknown, scopedContainer: ScopedContainer): Promise<any>;
1082
+ /**
1083
+ * Gets the underlying ServiceLocator instance for advanced usage
1084
+ */
1085
+ getServiceLocator(): ServiceLocator;
1086
+ /**
1087
+ * Gets the registry
1088
+ */
1089
+ getRegistry(): Registry;
1090
+ /**
1091
+ * Invalidates a service and its dependencies
1092
+ */
1093
+ invalidate(service: unknown): Promise<void>;
1094
+ /**
1095
+ * Gets a service holder by instance (reverse lookup)
1096
+ */
1097
+ private getHolderByInstance;
1098
+ /**
1099
+ * Checks if a service is registered in the container
1100
+ */
1101
+ isRegistered(token: any): boolean;
1102
+ /**
1103
+ * Disposes the container and cleans up all resources
1104
+ */
1105
+ dispose(): Promise<void>;
1106
+ /**
1107
+ * Waits for all pending operations to complete
1108
+ */
1109
+ ready(): Promise<void>;
1110
+ /**
1111
+ * @internal
1112
+ * Attempts to get an instance synchronously if it already exists.
1113
+ * Returns null if the instance doesn't exist or is not ready.
1114
+ */
1115
+ tryGetSync<T>(token: any, args?: any): T | null;
1116
+ /**
1117
+ * Begins a new request context and returns a ScopedContainer.
1118
+ *
1119
+ * The ScopedContainer provides isolated request-scoped service resolution
1120
+ * while delegating singleton and transient services to this Container.
1121
+ *
1122
+ * @param requestId Unique identifier for this request
1123
+ * @param metadata Optional metadata for the request
1124
+ * @param priority Priority for resolution (higher = more priority)
1125
+ * @returns A ScopedContainer for this request
1126
+ */
1127
+ beginRequest(requestId: string, metadata?: Record<string, any>, priority?: number): ScopedContainer;
1128
+ /**
1129
+ * Removes a request ID from the active set.
1130
+ * Called by ScopedContainer when the request ends.
1131
+ *
1132
+ * @internal
1133
+ */
1134
+ removeActiveRequest(requestId: string): void;
1135
+ /**
1136
+ * Gets the set of active request IDs.
1137
+ */
1138
+ getActiveRequestIds(): ReadonlySet<string>;
1139
+ /**
1140
+ * Checks if a request ID is currently active.
1141
+ */
1142
+ hasActiveRequest(requestId: string): boolean;
1143
+ /**
1144
+ * Clears all instances and bindings from the container.
1145
+ * This is useful for testing or resetting the container state.
1146
+ */
1147
+ clear(): Promise<void>;
1148
+ }
1149
+ //#endregion
1150
+ //#region src/testing/test-container.d.mts
1151
+ /**
1152
+ * A binding builder for the TestContainer that allows chaining binding operations.
1153
+ */
1154
+ declare class TestBindingBuilder<T> {
1155
+ private readonly container;
1156
+ private readonly token;
1157
+ constructor(container: TestContainer, token: InjectionToken<T, any>);
1158
+ /**
1159
+ * Binds the token to a specific value.
1160
+ * This is useful for testing with mock values or constants.
1161
+ * @param value The value to bind to the token
1162
+ */
1163
+ toValue(value: T): TestContainer;
1164
+ /**
1165
+ * Binds the token to a class constructor.
1166
+ * @param target The class constructor to bind to
1167
+ */
1168
+ toClass(target: ClassType): TestContainer;
1169
+ }
1170
+ /**
1171
+ * TestContainer extends the base Container with additional methods useful for testing.
1172
+ * It provides a simplified API for binding values and classes during test setup.
1173
+ */
1174
+ declare class TestContainer extends Container {
1175
+ constructor(registry?: Registry, logger?: Console | null, injectors?: Injectors);
1176
+ /**
1177
+ * Creates a binding builder for the given token.
1178
+ * This allows chaining binding operations like bind(Token).toValue(value).
1179
+ * @param token The injection token to bind
1180
+ * @returns A TestBindingBuilder for chaining binding operations
1181
+ */
1182
+ bind<T>(token: ClassType): TestBindingBuilder<T>;
1183
+ bind<T>(token: InjectionToken<T, any>): TestBindingBuilder<T>;
1184
+ /**
1185
+ * Binds a value directly to a token.
1186
+ * This is a convenience method equivalent to bind(token).toValue(value).
1187
+ * @param token The injection token to bind
1188
+ * @param value The value to bind to the token
1189
+ * @returns The TestContainer instance for chaining
1190
+ */
1191
+ bindValue<T>(token: ClassType, value: T): TestContainer;
1192
+ bindValue<T>(token: InjectionToken<T, any>, value: T): TestContainer;
1193
+ /**
1194
+ * Binds a class to a token.
1195
+ * This is a convenience method equivalent to bind(token).toClass(target).
1196
+ * @param token The injection token to bind
1197
+ * @param target The class constructor to bind to
1198
+ * @returns The TestContainer instance for chaining
1199
+ */
1200
+ bindClass(token: ClassType, target: ClassType): TestContainer;
1201
+ bindClass<T>(token: InjectionToken<T, any>, target: ClassType): TestContainer;
1202
+ /**
1203
+ * Creates a new TestContainer instance with the same configuration.
1204
+ * This is useful for creating isolated test containers.
1205
+ * @returns A new TestContainer instance
1206
+ */
1207
+ createChild(): TestContainer;
1208
+ }
1209
+ //#endregion
1210
+ export { Factorable as $, globalRegistry as A, ClassTypeWithInstanceAndOptionalArgument as B, InstanceHolderDestroying as C, DIErrorCode as D, DIError as E, BoundInjectionToken as F, InjectionTokenSchemaType as G, ClassTypeWithoutArguments as H, ClassType as I, FactoryContext as J, InjectionTokenType as K, ClassTypeWithArgument as L, InjectableScope as M, AnyInjectableType as N, FactoryRecord as O, BaseInjectionTokenSchemaType as P, IContainer as Q, ClassTypeWithInstance as R, InstanceHolderCreating as S, InstanceStatus as T, FactoryInjectionToken as U, ClassTypeWithOptionalArgument as V, InjectionToken as W, Injectors as X, getInjectableToken as Y, getInjectors as Z, IHolderStorage as _, TokenProcessor as a, PopUnion as at, InstanceHolder as b, LifecycleEventBus as c, UnionToOvlds as ct, RequestContext as d, FactorableWithArgs as et, RequestContextHolder as f, HolderGetResult as g, HolderReadyResult as h, ServiceLocator as i, Join as it, InjectableType as j, Registry as k, ScopedContainer as l, BaseHolderManager as m, TestContainer as n, InjectState as nt, Invalidator as o, UnionToArray as ot, createRequestContext as p, OptionalInjectionTokenSchemaType as q, Container as r, IsUnion as rt, HolderManager as s, UnionToIntersection as st, TestBindingBuilder as t, InjectRequest as tt, DefaultRequestContext as u, InstanceDestroyListener as v, InstanceHolderError as w, InstanceHolderCreated as x, InstanceEffect as y, ClassTypeWithInstanceAndArgument as z };
1211
+ //# sourceMappingURL=index-7jfWsiG4.d.mts.map