@navios/di 0.5.1 → 0.6.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.
Files changed (123) hide show
  1. package/CHANGELOG.md +146 -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 +3012 -0
  15. package/lib/browser/index.mjs.map +1 -0
  16. package/lib/index-S_qX2VLI.d.mts +1211 -0
  17. package/lib/index-S_qX2VLI.d.mts.map +1 -0
  18. package/lib/index-fKPuT65j.d.cts +1206 -0
  19. package/lib/index-fKPuT65j.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-BMGmmxH7.cjs +2895 -0
  33. package/lib/testing-BMGmmxH7.cjs.map +1 -0
  34. package/lib/testing-DCXz8AJD.mjs +2655 -0
  35. package/lib/testing-DCXz8AJD.mjs.map +1 -0
  36. package/package.json +23 -1
  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__/errors.spec.mts +6 -6
  44. package/src/__tests__/factory.spec.mts +1 -1
  45. package/src/__tests__/get-injectors.spec.mts +1 -1
  46. package/src/__tests__/injectable.spec.mts +1 -1
  47. package/src/__tests__/injection-token.spec.mts +1 -1
  48. package/src/__tests__/library-findings.spec.mts +563 -0
  49. package/src/__tests__/registry.spec.mts +2 -2
  50. package/src/__tests__/request-scope.spec.mts +266 -274
  51. package/src/__tests__/service-instantiator.spec.mts +18 -17
  52. package/src/__tests__/service-locator-event-bus.spec.mts +9 -9
  53. package/src/__tests__/service-locator-manager.spec.mts +15 -15
  54. package/src/__tests__/service-locator.spec.mts +167 -244
  55. package/src/__tests__/unified-api.spec.mts +27 -27
  56. package/src/__type-tests__/factory.spec-d.mts +2 -2
  57. package/src/__type-tests__/inject.spec-d.mts +2 -2
  58. package/src/__type-tests__/injectable.spec-d.mts +1 -1
  59. package/src/browser.mts +16 -0
  60. package/src/container/container.mts +319 -0
  61. package/src/container/index.mts +2 -0
  62. package/src/container/scoped-container.mts +350 -0
  63. package/src/decorators/factory.decorator.mts +4 -4
  64. package/src/decorators/injectable.decorator.mts +5 -5
  65. package/src/errors/di-error.mts +13 -7
  66. package/src/errors/index.mts +0 -8
  67. package/src/index.mts +156 -15
  68. package/src/interfaces/container.interface.mts +82 -0
  69. package/src/interfaces/factory.interface.mts +2 -2
  70. package/src/interfaces/index.mts +1 -0
  71. package/src/internal/context/async-local-storage.mts +120 -0
  72. package/src/internal/context/factory-context.mts +18 -0
  73. package/src/internal/context/index.mts +3 -0
  74. package/src/{request-context-holder.mts → internal/context/request-context.mts} +40 -27
  75. package/src/internal/context/resolution-context.mts +63 -0
  76. package/src/internal/context/sync-local-storage.mts +51 -0
  77. package/src/internal/core/index.mts +5 -0
  78. package/src/internal/core/instance-resolver.mts +641 -0
  79. package/src/{service-instantiator.mts → internal/core/instantiator.mts} +31 -27
  80. package/src/internal/core/invalidator.mts +437 -0
  81. package/src/internal/core/service-locator.mts +202 -0
  82. package/src/{token-processor.mts → internal/core/token-processor.mts} +79 -60
  83. package/src/{base-instance-holder-manager.mts → internal/holder/base-holder-manager.mts} +91 -21
  84. package/src/internal/holder/holder-manager.mts +85 -0
  85. package/src/internal/holder/holder-storage.interface.mts +116 -0
  86. package/src/internal/holder/index.mts +6 -0
  87. package/src/internal/holder/instance-holder.mts +109 -0
  88. package/src/internal/holder/request-storage.mts +134 -0
  89. package/src/internal/holder/singleton-storage.mts +105 -0
  90. package/src/internal/index.mts +4 -0
  91. package/src/internal/lifecycle/circular-detector.mts +77 -0
  92. package/src/internal/lifecycle/index.mts +2 -0
  93. package/src/{service-locator-event-bus.mts → internal/lifecycle/lifecycle-event-bus.mts} +11 -4
  94. package/src/testing/__tests__/test-container.spec.mts +2 -2
  95. package/src/testing/test-container.mts +4 -4
  96. package/src/token/index.mts +2 -0
  97. package/src/{injection-token.mts → token/injection-token.mts} +1 -1
  98. package/src/{registry.mts → token/registry.mts} +1 -1
  99. package/src/utils/get-injectable-token.mts +1 -1
  100. package/src/utils/get-injectors.mts +32 -15
  101. package/src/utils/types.mts +1 -1
  102. package/tsdown.config.mts +67 -0
  103. package/lib/_tsup-dts-rollup.d.mts +0 -1283
  104. package/lib/_tsup-dts-rollup.d.ts +0 -1283
  105. package/lib/chunk-2M576LCC.mjs +0 -2043
  106. package/lib/chunk-2M576LCC.mjs.map +0 -1
  107. package/lib/index.d.ts +0 -78
  108. package/lib/index.js +0 -2127
  109. package/lib/index.js.map +0 -1
  110. package/lib/testing/index.d.ts +0 -2
  111. package/lib/testing/index.js +0 -2060
  112. package/lib/testing/index.js.map +0 -1
  113. package/lib/testing/index.mjs.map +0 -1
  114. package/src/container.mts +0 -227
  115. package/src/factory-context.mts +0 -8
  116. package/src/instance-resolver.mts +0 -559
  117. package/src/request-context-manager.mts +0 -149
  118. package/src/service-invalidator.mts +0 -429
  119. package/src/service-locator-instance-holder.mts +0 -70
  120. package/src/service-locator-manager.mts +0 -85
  121. package/src/service-locator.mts +0 -246
  122. package/tsup.config.mts +0 -12
  123. /package/src/{injector.mts → injectors.mts} +0 -0
@@ -1,1283 +0,0 @@
1
- import { z } from 'zod/v4';
2
- import type { ZodObject } from 'zod/v4';
3
- import type { ZodOptional } from 'zod/v4';
4
- import type { ZodRecord } from 'zod/v4';
5
- import type { ZodType } from 'zod/v4';
6
-
7
- declare type AnyInjectableType = ClassType | InjectionToken<any, any> | BoundInjectionToken<any, any> | FactoryInjectionToken<any, any>;
8
- export { AnyInjectableType }
9
- export { AnyInjectableType as AnyInjectableType_alias_1 }
10
-
11
- declare const asyncInject: Injectors['asyncInject'];
12
- export { asyncInject }
13
- export { asyncInject as asyncInject_alias_1 }
14
-
15
- declare type BaseInjectionTokenSchemaType = ZodObject | ZodRecord;
16
- export { BaseInjectionTokenSchemaType }
17
- export { BaseInjectionTokenSchemaType as BaseInjectionTokenSchemaType_alias_1 }
18
-
19
- /**
20
- * Abstract base class that provides common functionality for managing ServiceLocatorInstanceHolder objects.
21
- * This class contains shared patterns used by both RequestContextHolder and ServiceLocatorManager.
22
- */
23
- declare abstract class BaseInstanceHolderManager {
24
- protected readonly logger: Console | null;
25
- protected readonly _holders: Map<string, ServiceLocatorInstanceHolder>;
26
- constructor(logger?: Console | null);
27
- /**
28
- * Protected getter for accessing the holders map from subclasses.
29
- */
30
- protected get holders(): Map<string, ServiceLocatorInstanceHolder>;
31
- /**
32
- * Abstract method to get a holder by name. Each implementation defines its own return type
33
- * based on their specific error handling and validation needs.
34
- */
35
- abstract get(name: string): any;
36
- /**
37
- * Abstract method to set a holder by name. Each implementation may have different validation logic.
38
- */
39
- abstract set(name: string, holder: ServiceLocatorInstanceHolder): void;
40
- /**
41
- * Abstract method to check if a holder exists. Each implementation may have different validation logic.
42
- */
43
- abstract has(name: string): any;
44
- /**
45
- * Deletes a holder by name.
46
- * @param name The name of the holder to delete
47
- * @returns true if the holder was deleted, false if it didn't exist
48
- */
49
- delete(name: string): boolean;
50
- /**
51
- * Filters holders based on a predicate function.
52
- * @param predicate Function to test each holder
53
- * @returns A new Map containing only the holders that match the predicate
54
- */
55
- filter(predicate: (value: ServiceLocatorInstanceHolder<any>, key: string) => boolean): Map<string, ServiceLocatorInstanceHolder>;
56
- /**
57
- * Clears all holders from this manager.
58
- */
59
- clear(): void;
60
- /**
61
- * Gets the number of holders currently managed.
62
- */
63
- size(): number;
64
- /**
65
- * Creates a new holder with Creating status and a deferred creation promise.
66
- * This is useful for creating placeholder holders that can be fulfilled later.
67
- * @param name The name of the instance
68
- * @param type The injectable type
69
- * @param scope The injectable scope
70
- * @param deps Optional set of dependencies
71
- * @returns A tuple containing the deferred promise and the holder
72
- */
73
- createCreatingHolder<Instance>(name: string, type: InjectableType, scope: InjectableScope, deps?: Set<string>): [
74
- ReturnType<typeof Promise.withResolvers<[undefined, Instance]>>,
75
- ServiceLocatorInstanceHolder<Instance>
76
- ];
77
- /**
78
- * Creates a new holder with Created status and an actual instance.
79
- * This is useful for creating holders that already have their instance ready.
80
- * @param name The name of the instance
81
- * @param instance The actual instance to store
82
- * @param type The injectable type
83
- * @param scope The injectable scope
84
- * @param deps Optional set of dependencies
85
- * @returns The created holder
86
- */
87
- protected createCreatedHolder<Instance>(name: string, instance: Instance, type: InjectableType, scope: InjectableScope, deps?: Set<string>): ServiceLocatorInstanceHolder<Instance>;
88
- /**
89
- * Gets all holder names currently managed.
90
- */
91
- getAllNames(): string[];
92
- /**
93
- * Gets all holders currently managed.
94
- */
95
- getAllHolders(): ServiceLocatorInstanceHolder[];
96
- /**
97
- * Checks if this manager has any holders.
98
- */
99
- isEmpty(): boolean;
100
- }
101
- export { BaseInstanceHolderManager }
102
- export { BaseInstanceHolderManager as BaseInstanceHolderManager_alias_1 }
103
-
104
- declare class BoundInjectionToken<T, S extends InjectionTokenSchemaType> {
105
- readonly token: InjectionToken<T, S>;
106
- readonly value: z.input<S>;
107
- id: string;
108
- name: string | symbol | ClassType;
109
- schema: InjectionTokenSchemaType;
110
- constructor(token: InjectionToken<T, S>, value: z.input<S>);
111
- toString(): string;
112
- }
113
- export { BoundInjectionToken }
114
- export { BoundInjectionToken as BoundInjectionToken_alias_1 }
115
-
116
- declare type ChannelEmitter<Events extends EventsConfig, Ns extends string, E extends EventsNames<Events>> = {
117
- emit<Args extends EventsArgs<Events, E>>(ns: Ns, event: E, ...args: Args): Promise<any>;
118
- };
119
- export { ChannelEmitter }
120
- export { ChannelEmitter as ChannelEmitter_alias_1 }
121
-
122
- declare type ClassType = new (...args: any[]) => any;
123
- export { ClassType }
124
- export { ClassType as ClassType_alias_1 }
125
-
126
- declare type ClassTypeWithArgument<Arg> = new (arg: Arg) => any;
127
- export { ClassTypeWithArgument }
128
- export { ClassTypeWithArgument as ClassTypeWithArgument_alias_1 }
129
-
130
- declare type ClassTypeWithInstance<T> = new (...args: any[]) => T;
131
- export { ClassTypeWithInstance }
132
- export { ClassTypeWithInstance as ClassTypeWithInstance_alias_1 }
133
-
134
- declare type ClassTypeWithInstanceAndArgument<T, Arg> = new (arg: Arg) => T;
135
- export { ClassTypeWithInstanceAndArgument }
136
- export { ClassTypeWithInstanceAndArgument as ClassTypeWithInstanceAndArgument_alias_1 }
137
-
138
- declare type ClassTypeWithInstanceAndOptionalArgument<T, Arg> = new (arg?: Arg) => T;
139
- export { ClassTypeWithInstanceAndOptionalArgument }
140
- export { ClassTypeWithInstanceAndOptionalArgument as ClassTypeWithInstanceAndOptionalArgument_alias_1 }
141
-
142
- declare type ClassTypeWithOptionalArgument<Arg> = new (arg?: Arg) => any;
143
- export { ClassTypeWithOptionalArgument }
144
- export { ClassTypeWithOptionalArgument as ClassTypeWithOptionalArgument_alias_1 }
145
-
146
- declare type ClassTypeWithoutArguments = new () => any;
147
- export { ClassTypeWithoutArguments }
148
- export { ClassTypeWithoutArguments as ClassTypeWithoutArguments_alias_1 }
149
-
150
- export declare interface ClearAllOptions {
151
- /** Whether to also clear request contexts (default: true) */
152
- clearRequestContexts?: boolean;
153
- /** Maximum number of invalidation rounds to prevent infinite loops (default: 10) */
154
- maxRounds?: number;
155
- /** Whether to wait for all services to settle before starting (default: true) */
156
- waitForSettlement?: boolean;
157
- }
158
-
159
- /**
160
- * Container class that provides a simplified public API for dependency injection.
161
- * It wraps a ServiceLocator instance and provides convenient methods for getting instances.
162
- */
163
- declare class Container {
164
- protected readonly registry: Registry;
165
- protected readonly logger: Console | null;
166
- protected readonly injectors: Injectors;
167
- private readonly serviceLocator;
168
- constructor(registry?: Registry, logger?: Console | null, injectors?: Injectors);
169
- private registerSelf;
170
- /**
171
- * Gets an instance from the container.
172
- * This method has the same type signature as the inject method from get-injectors.mts
173
- */
174
- get<T extends ClassType>(token: T): InstanceType<T> extends Factorable<infer R> ? Promise<R> : Promise<InstanceType<T>>;
175
- get<T, S extends InjectionTokenSchemaType>(token: InjectionToken<T, S>, args: z.input<S>): Promise<T>;
176
- 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';
177
- get<T>(token: InjectionToken<T, undefined>): Promise<T>;
178
- get<T>(token: BoundInjectionToken<T, any>): Promise<T>;
179
- get<T>(token: FactoryInjectionToken<T, any>): Promise<T>;
180
- /**
181
- * Gets the underlying ServiceLocator instance for advanced usage
182
- */
183
- getServiceLocator(): ServiceLocator;
184
- /**
185
- * Invalidates a service and its dependencies
186
- */
187
- invalidate(service: unknown): Promise<void>;
188
- /**
189
- * Gets a service holder by instance (reverse lookup)
190
- */
191
- private getHolderByInstance;
192
- private getRequestHolderByInstance;
193
- /**
194
- * Checks if a service is registered in the container
195
- */
196
- isRegistered(token: any): boolean;
197
- /**
198
- * Disposes the container and cleans up all resources
199
- */
200
- dispose(): Promise<void>;
201
- /**
202
- * Waits for all pending operations to complete
203
- */
204
- ready(): Promise<void>;
205
- /**
206
- * Begins a new request context with the given parameters.
207
- * @param requestId Unique identifier for this request
208
- * @param metadata Optional metadata for the request
209
- * @param priority Priority for resolution (higher = more priority)
210
- * @returns The created request context holder
211
- */
212
- beginRequest(requestId: string, metadata?: Record<string, any>, priority?: number): RequestContextHolder;
213
- /**
214
- * Ends a request context and cleans up all associated instances.
215
- * @param requestId The request ID to end
216
- */
217
- endRequest(requestId: string): Promise<void>;
218
- /**
219
- * Gets the current request context.
220
- * @returns The current request context holder or null
221
- */
222
- getCurrentRequestContext(): RequestContextHolder | null;
223
- /**
224
- * Sets the current request context.
225
- * @param requestId The request ID to set as current
226
- */
227
- setCurrentRequestContext(requestId: string): void;
228
- /**
229
- * Clears all instances and bindings from the container.
230
- * This is useful for testing or resetting the container state.
231
- */
232
- clear(): Promise<void>;
233
- }
234
- export { Container }
235
- export { Container as Container_alias_1 }
236
-
237
- /**
238
- * Creates a new request context holder with the given parameters.
239
- */
240
- declare function createRequestContextHolder(requestId: string, priority?: number, initialMetadata?: Record<string, any>): RequestContextHolder;
241
- export { createRequestContextHolder }
242
- export { createRequestContextHolder as createRequestContextHolder_alias_1 }
243
-
244
- declare const defaultInjectors: Injectors;
245
- export { defaultInjectors }
246
- export { defaultInjectors as defaultInjectors_alias_1 }
247
-
248
- /**
249
- * Default implementation of RequestContextHolder.
250
- */
251
- declare class DefaultRequestContextHolder extends BaseInstanceHolderManager implements RequestContextHolder {
252
- readonly requestId: string;
253
- readonly priority: number;
254
- readonly metadata: Map<string, any>;
255
- readonly createdAt: number;
256
- constructor(requestId: string, priority?: number, initialMetadata?: Record<string, any>);
257
- /**
258
- * Public getter for holders to maintain interface compatibility.
259
- */
260
- get holders(): Map<string, ServiceLocatorInstanceHolder>;
261
- /**
262
- * Gets a holder by name. For RequestContextHolder, this is a simple lookup.
263
- */
264
- get(name: string): ServiceLocatorInstanceHolder | undefined;
265
- /**
266
- * Sets a holder by name.
267
- */
268
- set(name: string, holder: ServiceLocatorInstanceHolder): void;
269
- /**
270
- * Checks if a holder exists by name.
271
- */
272
- has(name: string): boolean;
273
- addInstance(instanceName: string | InjectionToken<any, undefined>, instance: any, holder?: ServiceLocatorInstanceHolder): void;
274
- clear(): void;
275
- getMetadata(key: string): any | undefined;
276
- setMetadata(key: string, value: any): void;
277
- }
278
- export { DefaultRequestContextHolder }
279
- export { DefaultRequestContextHolder as DefaultRequestContextHolder_alias_1 }
280
-
281
- declare class DIError extends Error {
282
- readonly code: DIErrorCode;
283
- readonly context?: Record<string, unknown>;
284
- constructor(code: DIErrorCode, message: string, context?: Record<string, unknown>);
285
- static factoryNotFound(name: string): DIError;
286
- static factoryTokenNotResolved(token: string | symbol | unknown): DIError;
287
- static instanceNotFound(name: string): DIError;
288
- static instanceDestroying(name: string): DIError;
289
- static unknown(message: string | Error, context?: Record<string, unknown>): DIError;
290
- }
291
- export { DIError }
292
- export { DIError as DIError_alias_1 }
293
- export { DIError as DIError_alias_2 }
294
- export { DIError as FactoryNotFound }
295
- export { DIError as FactoryNotFound_alias_1 }
296
- export { DIError as FactoryTokenNotResolved }
297
- export { DIError as FactoryTokenNotResolved_alias_1 }
298
- export { DIError as InstanceDestroying }
299
- export { DIError as InstanceDestroying_alias_1 }
300
- export { DIError as InstanceNotFound }
301
- export { DIError as InstanceNotFound_alias_1 }
302
- export { DIError as UnknownError }
303
- export { DIError as UnknownError_alias_1 }
304
-
305
- declare enum DIErrorCode {
306
- FactoryNotFound = "FactoryNotFound",
307
- FactoryTokenNotResolved = "FactoryTokenNotResolved",
308
- InstanceNotFound = "InstanceNotFound",
309
- InstanceDestroying = "InstanceDestroying",
310
- UnknownError = "UnknownError"
311
- }
312
- export { DIErrorCode }
313
- export { DIErrorCode as DIErrorCode_alias_1 }
314
- export { DIErrorCode as DIErrorCode_alias_2 }
315
- export { DIErrorCode as ErrorsEnum }
316
- export { DIErrorCode as ErrorsEnum_alias_1 }
317
-
318
- declare class EventEmitter<Events extends EventsConfig = {}> implements EventEmitterInterface<Events> {
319
- private listeners;
320
- on<E extends EventsNames<Events>, Args extends EventsArgs<Events, E>>(event: E, listener: (...args: Args) => void | Promise<void>): () => void;
321
- off<E extends EventsNames<Events>, Args extends EventsArgs<Events, E>>(event: E, listener: (...args: Args) => void | Promise<void>): void;
322
- once<E extends EventsNames<Events>, Args extends EventsArgs<Events, E>>(event: E, listener: (...args: Args) => void | Promise<void>): () => void;
323
- emit<E extends EventsNames<Events>, Args extends EventsArgs<Events, E>>(event: E, ...args: Args): Promise<any>;
324
- }
325
- export { EventEmitter }
326
- export { EventEmitter as EventEmitter_alias_1 }
327
-
328
- declare interface EventEmitterInterface<Events extends EventsConfig> {
329
- on<E extends EventsNames<Events>, Args extends EventsArgs<Events, E>>(event: E, listener: (...args: Args) => void | Promise<void>): () => void;
330
- emit<E extends EventsNames<Events>, Args extends EventsArgs<Events, E>>(event: E, ...args: Args): void | Promise<void>;
331
- }
332
- export { EventEmitterInterface }
333
- export { EventEmitterInterface as EventEmitterInterface_alias_1 }
334
-
335
- declare type EventsArgs<Events extends EventsConfig, Name extends EventsNames<Events>> = Events[Name] extends any[] ? Events[Name] : [];
336
- export { EventsArgs }
337
- export { EventsArgs as EventsArgs_alias_1 }
338
-
339
- declare type EventsConfig = {
340
- [event: string]: any[];
341
- };
342
- export { EventsConfig }
343
- export { EventsConfig as EventsConfig_alias_1 }
344
-
345
- declare type EventsNames<Events extends EventsConfig> = Exclude<keyof Events, symbol | number>;
346
- export { EventsNames }
347
- export { EventsNames as EventsNames_alias_1 }
348
-
349
- declare interface Factorable<T> {
350
- create(ctx?: FactoryContext): Promise<T> | T;
351
- }
352
- export { Factorable }
353
- export { Factorable as Factorable_alias_1 }
354
- export { Factorable as Factorable_alias_2 }
355
-
356
- declare interface FactorableWithArgs<T, A extends InjectionTokenSchemaType> {
357
- create(ctx?: FactoryContext, ...args: [z.output<A>]): Promise<T> | T;
358
- }
359
- export { FactorableWithArgs }
360
- export { FactorableWithArgs as FactorableWithArgs_alias_1 }
361
- export { FactorableWithArgs as FactorableWithArgs_alias_2 }
362
-
363
- declare function Factory<R>(options?: {
364
- scope?: InjectableScope;
365
- registry?: Registry;
366
- }): <T extends ClassTypeWithInstance<Factorable<R>>>(target: T, context?: ClassDecoratorContext) => T;
367
-
368
- declare function Factory<R, S>(options: {
369
- scope?: InjectableScope;
370
- token: InjectionToken<R, S>;
371
- registry?: Registry;
372
- }): R extends undefined ? never : S extends InjectionTokenSchemaType ? <T extends ClassTypeWithInstance<FactorableWithArgs<R, S>>>(// #2.2.1 Token have a schema
373
- target: T, context?: ClassDecoratorContext) => T : S extends undefined ? <T extends ClassTypeWithInstance<Factorable<R>>>(// #2.3.1 Token without a schema
374
- target: T, context?: ClassDecoratorContext) => T : never;
375
- export { Factory }
376
- export { Factory as Factory_alias_1 }
377
- export { Factory as Factory_alias_2 }
378
-
379
- declare interface FactoryContext {
380
- inject: Injectors['asyncInject'];
381
- locator: ServiceLocator;
382
- addDestroyListener: (listener: () => void) => void;
383
- }
384
- export { FactoryContext }
385
- export { FactoryContext as FactoryContext_alias_1 }
386
-
387
- declare class FactoryInjectionToken<T, S extends InjectionTokenSchemaType> {
388
- readonly token: InjectionToken<T, S>;
389
- readonly factory: (ctx: FactoryContext) => Promise<z.input<S>>;
390
- value?: z.input<S>;
391
- resolved: boolean;
392
- id: string;
393
- name: string | symbol | ClassType;
394
- schema: InjectionTokenSchemaType;
395
- constructor(token: InjectionToken<T, S>, factory: (ctx: FactoryContext) => Promise<z.input<S>>);
396
- resolve(ctx: FactoryContext): Promise<z.input<S>>;
397
- toString(): string;
398
- }
399
- export { FactoryInjectionToken }
400
- export { FactoryInjectionToken as FactoryInjectionToken_alias_1 }
401
-
402
- declare interface FactoryOptions {
403
- scope?: InjectableScope;
404
- token?: InjectionToken<any, any>;
405
- registry?: Registry;
406
- }
407
- export { FactoryOptions }
408
- export { FactoryOptions as FactoryOptions_alias_1 }
409
- export { FactoryOptions as FactoryOptions_alias_2 }
410
-
411
- declare type FactoryRecord<Instance = any, Schema = any> = {
412
- scope: InjectableScope;
413
- originalToken: InjectionToken<Instance, Schema>;
414
- target: ClassType;
415
- type: InjectableType;
416
- };
417
- export { FactoryRecord }
418
- export { FactoryRecord as FactoryRecord_alias_1 }
419
-
420
- declare function getInjectableToken<R>(target: ClassType): R extends {
421
- create(...args: any[]): infer V;
422
- } ? InjectionToken<V> : InjectionToken<R>;
423
- export { getInjectableToken }
424
- export { getInjectableToken as getInjectableToken_alias_1 }
425
- export { getInjectableToken as getInjectableToken_alias_2 }
426
-
427
- declare function getInjectors(): Injectors;
428
- export { getInjectors }
429
- export { getInjectors as getInjectors_alias_1 }
430
- export { getInjectors as getInjectors_alias_2 }
431
-
432
- declare const globalRegistry: Registry;
433
- export { globalRegistry }
434
- export { globalRegistry as globalRegistry_alias_1 }
435
-
436
- declare const inject: Injectors['inject'];
437
- export { inject }
438
- export { inject as inject_alias_1 }
439
-
440
- declare function Injectable(): <T extends ClassTypeWithoutArguments>(target: T, context?: ClassDecoratorContext) => T;
441
-
442
- declare function Injectable(options: {
443
- scope?: InjectableScope;
444
- registry: Registry;
445
- }): <T extends ClassTypeWithoutArguments>(target: T, context?: ClassDecoratorContext) => T;
446
-
447
- declare function Injectable(options: {
448
- scope: InjectableScope;
449
- }): <T extends ClassTypeWithoutArguments>(target: T, context?: ClassDecoratorContext) => T;
450
-
451
- declare function Injectable<Schema extends InjectionTokenSchemaType>(options: {
452
- scope?: InjectableScope;
453
- schema: Schema;
454
- registry?: Registry;
455
- }): <T extends ClassTypeWithArgument<z.output<Schema>>>(target: T, context?: ClassDecoratorContext) => T;
456
-
457
- declare function Injectable<Type, Schema>(options: {
458
- scope?: InjectableScope;
459
- token: InjectionToken<Type, Schema>;
460
- registry?: Registry;
461
- }): Schema extends BaseInjectionTokenSchemaType ? Type extends undefined ? <T extends ClassTypeWithArgument<z.output<Schema>>>(// #3.1.1 Typeless token
462
- target: T, context?: ClassDecoratorContext) => T : <T extends ClassTypeWithInstanceAndArgument<Type, z.output<Schema>>>(// #3.1.2 Typed token
463
- target: T, context?: ClassDecoratorContext) => T : Schema extends OptionalInjectionTokenSchemaType ? Type extends undefined ? <T extends ClassTypeWithOptionalArgument<z.output<Schema>>>(// #3.2.1 Typeless token
464
- target: T, context?: ClassDecoratorContext) => T : <T extends ClassTypeWithInstanceAndOptionalArgument<Type, z.output<Schema>>>(target: T, context?: ClassDecoratorContext) => T : Schema extends undefined ? <R extends ClassTypeWithInstance<Type>>(// #3.3.1 Token must have a type
465
- target: R, context?: ClassDecoratorContext) => R : never;
466
- export { Injectable }
467
- export { Injectable as Injectable_alias_1 }
468
- export { Injectable as Injectable_alias_2 }
469
-
470
- declare interface InjectableOptions {
471
- scope?: InjectableScope;
472
- token?: InjectionToken<any, any>;
473
- schema?: InjectionTokenSchemaType;
474
- registry?: Registry;
475
- }
476
- export { InjectableOptions }
477
- export { InjectableOptions as InjectableOptions_alias_1 }
478
- export { InjectableOptions as InjectableOptions_alias_2 }
479
-
480
- declare enum InjectableScope {
481
- /**
482
- * Singleton scope: The instance is created once and shared across the application.
483
- */
484
- Singleton = "Singleton",
485
- /**
486
- * Instance scope: A new instance is created for each injection.
487
- */
488
- Transient = "Transient",
489
- /**
490
- * Request scope: The instance is created once per request and shared within that request context.
491
- */
492
- Request = "Request"
493
- }
494
- export { InjectableScope }
495
- export { InjectableScope as InjectableScope_alias_1 }
496
- export { InjectableScope as InjectableScope_alias_2 }
497
-
498
- declare const InjectableTokenMeta: unique symbol;
499
- export { InjectableTokenMeta }
500
- export { InjectableTokenMeta as InjectableTokenMeta_alias_1 }
501
- export { InjectableTokenMeta as InjectableTokenMeta_alias_2 }
502
-
503
- declare enum InjectableType {
504
- Class = "Class",
505
- Factory = "Factory"
506
- }
507
- export { InjectableType }
508
- export { InjectableType as InjectableType_alias_1 }
509
- export { InjectableType as InjectableType_alias_2 }
510
-
511
- 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> {
512
- readonly name: string | symbol | ClassType;
513
- readonly schema: ZodObject | undefined;
514
- id: `${string}-${string}-${string}-${string}-${string}`;
515
- private formattedName;
516
- constructor(name: string | symbol | ClassType, schema: ZodObject | undefined);
517
- static create<T extends ClassType>(name: T): InjectionToken<InstanceType<T>, undefined>;
518
- 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>;
519
- static create<T>(name: string | symbol): InjectionToken<T, undefined>;
520
- static create<T, Schema extends InjectionTokenSchemaType>(name: string | any, schema: Schema): InjectionToken<T, Schema>;
521
- static bound<T, S extends InjectionTokenSchemaType>(token: InjectionToken<T, S>, value: z.input<S>): BoundInjectionToken<T, S>;
522
- static factory<T, S extends InjectionTokenSchemaType>(token: InjectionToken<T, S>, factory: (ctx: FactoryContext) => Promise<z.input<S>>): FactoryInjectionToken<T, S>;
523
- static refineType<T>(token: BoundInjectionToken<any, any>): BoundInjectionToken<T, any>;
524
- toString(): string;
525
- }
526
- export { InjectionToken }
527
- export { InjectionToken as InjectionToken_alias_1 }
528
-
529
- declare type InjectionTokenSchemaType = BaseInjectionTokenSchemaType | OptionalInjectionTokenSchemaType;
530
- export { InjectionTokenSchemaType }
531
- export { InjectionTokenSchemaType as InjectionTokenSchemaType_alias_1 }
532
-
533
- declare type InjectionTokenType = InjectionToken<any, any> | BoundInjectionToken<any, any> | FactoryInjectionToken<any, any>;
534
- export { InjectionTokenType }
535
- export { InjectionTokenType as InjectionTokenType_alias_1 }
536
-
537
- declare interface Injectors {
538
- asyncInject<T extends ClassTypeWithoutArguments>(token: T): InstanceType<T> extends Factorable<infer R> ? Promise<R> : Promise<InstanceType<T>>;
539
- asyncInject<Args, T extends ClassTypeWithArgument<Args>>(token: T, args: Args): Promise<InstanceType<T>>;
540
- asyncInject<Schema extends InjectionTokenSchemaType, R, T extends FactorableWithArgs<R, Schema>>(token: T, args: z.input<Schema>): Promise<R>;
541
- asyncInject<T, S extends InjectionTokenSchemaType>(token: InjectionToken<T, S>, args: z.input<S>): Promise<T>;
542
- 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';
543
- asyncInject<T>(token: InjectionToken<T, undefined>): Promise<T>;
544
- asyncInject<T>(token: BoundInjectionToken<T, any>): Promise<T>;
545
- asyncInject<T>(token: FactoryInjectionToken<T, any>): Promise<T>;
546
- inject<T extends ClassTypeWithoutArguments>(token: T): InstanceType<T> extends Factorable<infer R> ? R : InstanceType<T>;
547
- inject<Args, T extends ClassTypeWithArgument<Args>>(token: T, args: Args): InstanceType<T>;
548
- inject<Schema extends InjectionTokenSchemaType, R, T extends FactorableWithArgs<R, Schema>>(token: T, args: z.input<Schema>): R;
549
- inject<T, S extends InjectionTokenSchemaType>(token: InjectionToken<T, S>, args: z.input<S>): T;
550
- 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';
551
- inject<T>(token: InjectionToken<T, undefined>): T;
552
- inject<T>(token: BoundInjectionToken<T, any>): T;
553
- inject<T>(token: FactoryInjectionToken<T, any>): T;
554
- /**
555
- * Optional injection that returns null if the service fails to initialize
556
- * or is not available. This is useful when you want to inject a service
557
- * that may not be configured or may fail gracefully.
558
- *
559
- * @example
560
- * ```ts
561
- * class MyService {
562
- * constructor() {
563
- * const optionalService = optional(OptionalServiceToken)
564
- * // optionalService will be null if initialization fails
565
- * if (optionalService) {
566
- * optionalService.doSomething()
567
- * }
568
- * }
569
- * }
570
- * ```
571
- */
572
- optional<T extends ClassType>(token: T): (InstanceType<T> extends Factorable<infer R> ? R : InstanceType<T>) | null;
573
- optional<T, S extends InjectionTokenSchemaType>(token: InjectionToken<T, S>, args: z.input<S>): T | null;
574
- 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';
575
- optional<T>(token: InjectionToken<T, undefined>): T | null;
576
- optional<T>(token: BoundInjectionToken<T, any>): T | null;
577
- optional<T>(token: FactoryInjectionToken<T, any>): T | null;
578
- wrapSyncInit(cb: () => any): (injectState?: InjectState) => [any, Promise<any>[], InjectState];
579
- provideFactoryContext(context: FactoryContext | null): FactoryContext | null;
580
- }
581
- export { Injectors }
582
- export { Injectors as Injectors_alias_1 }
583
- export { Injectors as Injectors_alias_2 }
584
-
585
- declare type InjectRequest = {
586
- token: InjectionToken<any> | BoundInjectionToken<any, any> | FactoryInjectionToken<any, any> | ClassType;
587
- promise: Promise<any>;
588
- readonly result: any;
589
- readonly error: Error | null;
590
- };
591
- export { InjectRequest }
592
- export { InjectRequest as InjectRequest_alias_1 }
593
- export { InjectRequest as InjectRequest_alias_2 }
594
-
595
- declare interface InjectState {
596
- currentIndex: number;
597
- isFrozen: boolean;
598
- requests: InjectRequest[];
599
- }
600
- export { InjectState }
601
- export { InjectState as InjectState_alias_1 }
602
- export { InjectState as InjectState_alias_2 }
603
-
604
- /**
605
- * InstanceResolver handles instance resolution, creation, and lifecycle management.
606
- * Extracted from ServiceLocator to improve separation of concerns.
607
- */
608
- export declare class InstanceResolver {
609
- private readonly registry;
610
- private readonly manager;
611
- private readonly serviceInstantiator;
612
- private readonly tokenProcessor;
613
- private readonly logger;
614
- private readonly serviceLocator;
615
- constructor(registry: Registry, manager: ServiceLocatorManager, serviceInstantiator: ServiceInstantiator, tokenProcessor: TokenProcessor, logger: (Console | null) | undefined, serviceLocator: ServiceLocator);
616
- /**
617
- * Resolves an instance for the given token and arguments.
618
- */
619
- resolveInstance(token: AnyInjectableType, args?: any, requestContext?: RequestContextHolder): Promise<[undefined, any] | [DIError]>;
620
- /**
621
- * Gets a synchronous instance (for sync operations).
622
- */
623
- getSyncInstance<Instance, Schema extends InjectionTokenSchemaType | undefined>(token: AnyInjectableType, args: Schema extends ZodObject ? z.input<Schema> : Schema extends ZodOptional<ZodObject> ? z.input<Schema> | undefined : undefined, currentRequestContext: RequestContextHolder | null): Instance | null;
624
- /**
625
- * Internal method to resolve token args and create instance name.
626
- * Handles factory token resolution and validation.
627
- */
628
- private resolveTokenAndPrepareInstanceName;
629
- /**
630
- * Gets an instance by its instance name, handling all the logic after instance name creation.
631
- */
632
- private retrieveOrCreateInstanceByInstanceName;
633
- /**
634
- * Attempts to retrieve an existing instance, handling request-scoped and singleton instances.
635
- * Returns null if no instance exists and a new one should be created.
636
- */
637
- private tryGetExistingInstance;
638
- /**
639
- * Attempts to get a request-scoped instance if applicable.
640
- */
641
- private tryGetRequestScopedInstance;
642
- /**
643
- * Attempts to get a singleton instance from the manager.
644
- */
645
- private tryGetSingletonInstance;
646
- /**
647
- * Waits for an instance holder to be ready and returns the appropriate result.
648
- */
649
- private waitForInstanceReady;
650
- /**
651
- * Creates a new instance for the given token and arguments.
652
- */
653
- private createNewInstance;
654
- /**
655
- * Instantiates a service from the registry using the service instantiator.
656
- */
657
- private instantiateServiceFromRegistry;
658
- /**
659
- * Handles the result of service instantiation.
660
- */
661
- private handleInstantiationResult;
662
- /**
663
- * Handles successful service instantiation.
664
- */
665
- private handleInstantiationSuccess;
666
- /**
667
- * Handles service instantiation errors.
668
- */
669
- private handleInstantiationError;
670
- /**
671
- * Stores an instance holder based on its scope.
672
- */
673
- private storeInstanceByScope;
674
- /**
675
- * Creates a factory context for dependency injection during service instantiation.
676
- */
677
- private createFactoryContext;
678
- }
679
-
680
- declare type IsUnion<T> = [T] extends [UnionToIntersection<T>] ? false : true;
681
- export { IsUnion }
682
- export { IsUnion as IsUnion_alias_1 }
683
- export { IsUnion as IsUnion_alias_2 }
684
-
685
- declare 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 : '';
686
- export { Join }
687
- export { Join as Join_alias_1 }
688
- export { Join as Join_alias_2 }
689
-
690
- declare interface OnServiceDestroy {
691
- onServiceDestroy(): Promise<void> | void;
692
- }
693
- export { OnServiceDestroy }
694
- export { OnServiceDestroy as OnServiceDestroy_alias_1 }
695
- export { OnServiceDestroy as OnServiceDestroy_alias_2 }
696
-
697
- declare interface OnServiceInit {
698
- onServiceInit(): Promise<void> | void;
699
- }
700
- export { OnServiceInit }
701
- export { OnServiceInit as OnServiceInit_alias_1 }
702
- export { OnServiceInit as OnServiceInit_alias_2 }
703
-
704
- declare const optional: Injectors['optional'];
705
- export { optional }
706
- export { optional as optional_alias_1 }
707
-
708
- declare type OptionalInjectionTokenSchemaType = ZodOptional<ZodObject> | ZodOptional<ZodRecord>;
709
- export { OptionalInjectionTokenSchemaType }
710
- export { OptionalInjectionTokenSchemaType as OptionalInjectionTokenSchemaType_alias_1 }
711
-
712
- declare type PopUnion<U> = UnionToOvlds<U> extends (a: infer A) => void ? A : never;
713
- export { PopUnion }
714
- export { PopUnion as PopUnion_alias_1 }
715
- export { PopUnion as PopUnion_alias_2 }
716
-
717
- declare const provideFactoryContext: Injectors['provideFactoryContext'];
718
- export { provideFactoryContext }
719
- export { provideFactoryContext as provideFactoryContext_alias_1 }
720
-
721
- declare class Registry {
722
- private readonly parent?;
723
- private readonly factories;
724
- constructor(parent?: Registry | undefined);
725
- has(token: InjectionToken<any, any>): boolean;
726
- get<Instance, Schema>(token: InjectionToken<Instance, Schema>): FactoryRecord<Instance, Schema>;
727
- set<Instance, Schema>(token: InjectionToken<Instance, Schema>, scope: InjectableScope, target: ClassType, type: InjectableType): void;
728
- delete(token: InjectionToken<any, any>): void;
729
- }
730
- export { Registry }
731
- export { Registry as Registry_alias_1 }
732
-
733
- /**
734
- * Request context holder that manages pre-prepared instances for a specific request.
735
- * This allows for efficient instantiation of request-scoped services.
736
- */
737
- declare interface RequestContextHolder {
738
- /**
739
- * Unique identifier for this request context.
740
- */
741
- readonly requestId: string;
742
- /**
743
- * Instance holders for request-scoped services.
744
- */
745
- readonly holders: Map<string, ServiceLocatorInstanceHolder>;
746
- /**
747
- * Priority for resolution in FactoryContext.inject method.
748
- * Higher values take precedence.
749
- */
750
- readonly priority: number;
751
- /**
752
- * Request-specific metadata that can be used during instantiation.
753
- */
754
- readonly metadata: Map<string, any>;
755
- /**
756
- * Timestamp when this context was created.
757
- */
758
- readonly createdAt: number;
759
- /**
760
- * Adds a pre-prepared instance to this context.
761
- */
762
- addInstance(instanceName: string, instance: any, holder: ServiceLocatorInstanceHolder): void;
763
- /**
764
- * Adds a pre-prepared instance to this context.
765
- */
766
- addInstance(token: InjectionToken<any, undefined>, instance: any): void;
767
- /**
768
- * Gets an instance holder from this context.
769
- */
770
- get(instanceName: string): ServiceLocatorInstanceHolder | undefined;
771
- /**
772
- * Checks if this context has a pre-prepared instance.
773
- */
774
- has(instanceName: string): boolean;
775
- /**
776
- * Clears all instances and holders from this context.
777
- */
778
- clear(): void;
779
- /**
780
- * Gets metadata value by key.
781
- */
782
- getMetadata(key: string): any | undefined;
783
- /**
784
- * Sets metadata value by key.
785
- */
786
- setMetadata(key: string, value: any): void;
787
- /**
788
- * Filters holders based on a predicate function.
789
- */
790
- filter(predicate: (value: ServiceLocatorInstanceHolder<any>, key: string) => boolean): Map<string, ServiceLocatorInstanceHolder>;
791
- /**
792
- * Deletes a holder by name.
793
- */
794
- delete(name: string): boolean;
795
- /**
796
- * Gets the number of holders currently managed.
797
- */
798
- size(): number;
799
- /**
800
- * Checks if this manager has any holders.
801
- */
802
- isEmpty(): boolean;
803
- }
804
- export { RequestContextHolder }
805
- export { RequestContextHolder as RequestContextHolder_alias_1 }
806
-
807
- /**
808
- * RequestContextManager handles request context lifecycle management.
809
- * Extracted from ServiceLocator to improve separation of concerns.
810
- */
811
- export declare class RequestContextManager {
812
- private readonly logger;
813
- private readonly requestContexts;
814
- private currentRequestContext;
815
- constructor(logger?: Console | null);
816
- /**
817
- * Begins a new request context with the given parameters.
818
- * @param requestId Unique identifier for this request
819
- * @param metadata Optional metadata for the request
820
- * @param priority Priority for resolution (higher = more priority)
821
- * @returns The created request context holder
822
- */
823
- beginRequest(requestId: string, metadata?: Record<string, any>, priority?: number): RequestContextHolder;
824
- /**
825
- * Ends a request context and cleans up all associated instances.
826
- * @param requestId The request ID to end
827
- */
828
- endRequest(requestId: string): Promise<void>;
829
- /**
830
- * Gets the current request context.
831
- * @returns The current request context holder or null
832
- */
833
- getCurrentRequestContext(): RequestContextHolder | null;
834
- /**
835
- * Sets the current request context.
836
- * @param requestId The request ID to set as current
837
- */
838
- setCurrentRequestContext(requestId: string): void;
839
- /**
840
- * Gets all request contexts.
841
- * @returns Map of request contexts
842
- */
843
- getRequestContexts(): Map<string, RequestContextHolder>;
844
- /**
845
- * Clears all request contexts.
846
- */
847
- clearAllRequestContexts(): Promise<void>;
848
- }
849
-
850
- /**
851
- * ServiceInstantiator handles the instantiation of services based on registry records.
852
- * It replaces the hard-coded logic in Injectable and Factory decorators.
853
- */
854
- declare class ServiceInstantiator {
855
- private readonly injectors;
856
- constructor(injectors: Injectors);
857
- /**
858
- * Instantiates a service based on its registry record.
859
- * @param ctx The factory context for dependency injection
860
- * @param record The factory record from the registry
861
- * @param args Optional arguments for the service
862
- * @returns Promise resolving to [undefined, instance] or [error]
863
- */
864
- instantiateService<T>(ctx: FactoryContext, record: FactoryRecord<T, any>, args?: any): Promise<[undefined, T] | [Error]>;
865
- /**
866
- * Instantiates a class-based service (Injectable decorator).
867
- * @param ctx The factory context for dependency injection
868
- * @param record The factory record from the registry
869
- * @param args Optional arguments for the service constructor
870
- * @returns Promise resolving to [undefined, instance] or [error]
871
- */
872
- private instantiateClass;
873
- /**
874
- * Instantiates a factory-based service (Factory decorator).
875
- * @param ctx The factory context for dependency injection
876
- * @param record The factory record from the registry
877
- * @param args Optional arguments for the factory
878
- * @returns Promise resolving to [undefined, instance] or [error]
879
- */
880
- private instantiateFactory;
881
- }
882
- export { ServiceInstantiator }
883
- export { ServiceInstantiator as ServiceInstantiator_alias_1 }
884
-
885
- /**
886
- * ServiceInvalidator handles service invalidation, cleanup, and graceful clearing.
887
- * Extracted from ServiceLocator to improve separation of concerns.
888
- */
889
- export declare class ServiceInvalidator {
890
- private readonly manager;
891
- private readonly requestContextManager;
892
- private readonly eventBus;
893
- private readonly logger;
894
- constructor(manager: ServiceLocatorManager, requestContextManager: RequestContextManager, eventBus: ServiceLocatorEventBus, logger?: Console | null);
895
- /**
896
- * Invalidates a service and all its dependencies.
897
- */
898
- invalidate(service: string, round?: number): Promise<any>;
899
- /**
900
- * Gracefully clears all services in the ServiceLocator using invalidation logic.
901
- * This method respects service dependencies and ensures proper cleanup order.
902
- * Services that depend on others will be invalidated first, then their dependencies.
903
- */
904
- clearAll(options?: ClearAllOptions): Promise<void>;
905
- /**
906
- * Waits for all services to settle (either created, destroyed, or error state).
907
- */
908
- ready(): Promise<void>;
909
- /**
910
- * Invalidates a single holder based on its current status.
911
- */
912
- private invalidateHolder;
913
- /**
914
- * Invalidates a request-scoped holder based on its current status.
915
- */
916
- private invalidateRequestHolder;
917
- /**
918
- * Common invalidation logic for holders based on their status.
919
- */
920
- private invalidateHolderByStatus;
921
- /**
922
- * Destroys a holder and cleans up its resources.
923
- */
924
- private destroyHolder;
925
- /**
926
- * Destroys a request-scoped holder and cleans up its resources.
927
- */
928
- private destroyRequestHolder;
929
- /**
930
- * Common destroy logic for holders with customizable cleanup.
931
- */
932
- private destroyHolderWithCleanup;
933
- /**
934
- * Waits for a holder to settle (either created, destroyed, or error state).
935
- */
936
- private waitForHolderToSettle;
937
- /**
938
- * Clears services with dependency awareness, ensuring proper cleanup order.
939
- * Services with no dependencies are cleared first, then services that depend on them.
940
- */
941
- private clearServicesWithDependencyAwareness;
942
- /**
943
- * Finds services that are ready to be cleared in the current round.
944
- * A service is ready if all its dependencies have already been cleared.
945
- */
946
- private findServicesReadyForClearing;
947
- /**
948
- * Force clears services that couldn't be cleared through normal dependency resolution.
949
- * This handles edge cases like circular dependencies.
950
- */
951
- private forceClearServices;
952
- /**
953
- * Gets all service names currently managed by the ServiceLocator.
954
- */
955
- private getAllServiceNames;
956
- /**
957
- * Emits events to listeners for instance lifecycle events.
958
- */
959
- private emitInstanceEvent;
960
- }
961
-
962
- declare class ServiceLocator {
963
- private readonly registry;
964
- private readonly logger;
965
- private readonly injectors;
966
- private readonly eventBus;
967
- private readonly manager;
968
- private readonly serviceInstantiator;
969
- private readonly tokenProcessor;
970
- private readonly requestContextManager;
971
- private readonly serviceInvalidator;
972
- private readonly instanceResolver;
973
- constructor(registry?: Registry, logger?: Console | null, injectors?: Injectors);
974
- getEventBus(): ServiceLocatorEventBus;
975
- getManager(): ServiceLocatorManager;
976
- getRequestContexts(): Map<string, RequestContextHolder>;
977
- getRequestContextManager(): RequestContextManager;
978
- getServiceInvalidator(): ServiceInvalidator;
979
- getInstanceIdentifier(token: AnyInjectableType, args?: any): string;
980
- getInstance(token: AnyInjectableType, args?: any, onPrepare?: (data: {
981
- instanceName: string;
982
- actualToken: any;
983
- validatedArgs?: any;
984
- }) => void): Promise<any[]>;
985
- getOrThrowInstance<Instance>(token: AnyInjectableType, args: any): Promise<Instance>;
986
- getSyncInstance<Instance, Schema extends InjectionTokenSchemaType | undefined>(token: AnyInjectableType, args: Schema extends ZodObject ? z.input<Schema> : Schema extends ZodOptional<ZodObject> ? z.input<Schema> | undefined : undefined): Instance | null;
987
- invalidate(service: string, round?: number): Promise<any>;
988
- /**
989
- * Gracefully clears all services in the ServiceLocator using invalidation logic.
990
- * This method respects service dependencies and ensures proper cleanup order.
991
- * Services that depend on others will be invalidated first, then their dependencies.
992
- *
993
- * @param options Optional configuration for the clearing process
994
- * @returns Promise that resolves when all services have been cleared
995
- */
996
- clearAll(options?: ClearAllOptions): Promise<void>;
997
- /**
998
- * Begins a new request context with the given parameters.
999
- * @param requestId Unique identifier for this request
1000
- * @param metadata Optional metadata for the request
1001
- * @param priority Priority for resolution (higher = more priority)
1002
- * @returns The created request context holder
1003
- */
1004
- beginRequest(requestId: string, metadata?: Record<string, any>, priority?: number): RequestContextHolder;
1005
- /**
1006
- * Ends a request context and cleans up all associated instances.
1007
- * @param requestId The request ID to end
1008
- */
1009
- endRequest(requestId: string): Promise<void>;
1010
- /**
1011
- * Gets the current request context.
1012
- * @returns The current request context holder or null
1013
- */
1014
- getCurrentRequestContext(): RequestContextHolder | null;
1015
- /**
1016
- * Sets the current request context.
1017
- * @param requestId The request ID to set as current
1018
- */
1019
- setCurrentRequestContext(requestId: string): void;
1020
- /**
1021
- * Waits for all services to settle (either created, destroyed, or error state).
1022
- */
1023
- ready(): Promise<void>;
1024
- /**
1025
- * Helper method for TokenProcessor to access pre-prepared instances.
1026
- * This is needed for the factory context creation.
1027
- */
1028
- tryGetPrePreparedInstance(instanceName: string, contextHolder: RequestContextHolder | undefined, deps: Set<string>): any;
1029
- /**
1030
- * Helper method for InstanceResolver to generate instance names.
1031
- * This is needed for the factory context creation.
1032
- */
1033
- generateInstanceName(token: any, args: any): string;
1034
- }
1035
- export { ServiceLocator }
1036
- export { ServiceLocator as ServiceLocator_alias_1 }
1037
-
1038
- declare class ServiceLocatorEventBus {
1039
- private readonly logger;
1040
- private listeners;
1041
- constructor(logger?: Console | null);
1042
- on<Event extends string | `pre:${string}` | `post:${string}`>(ns: string, event: Event, listener: (event: Event) => void): () => void;
1043
- emit(key: string, event: string): Promise<PromiseSettledResult<any>[] | undefined>;
1044
- }
1045
- export { ServiceLocatorEventBus }
1046
- export { ServiceLocatorEventBus as ServiceLocatorEventBus_alias_1 }
1047
-
1048
- declare type ServiceLocatorInstanceDestroyListener = () => void | Promise<void>;
1049
- export { ServiceLocatorInstanceDestroyListener }
1050
- export { ServiceLocatorInstanceDestroyListener as ServiceLocatorInstanceDestroyListener_alias_1 }
1051
-
1052
- declare type ServiceLocatorInstanceEffect = () => void;
1053
- export { ServiceLocatorInstanceEffect }
1054
- export { ServiceLocatorInstanceEffect as ServiceLocatorInstanceEffect_alias_1 }
1055
-
1056
- declare type ServiceLocatorInstanceHolder<Instance = unknown> = ServiceLocatorInstanceHolderCreating<Instance> | ServiceLocatorInstanceHolderCreated<Instance> | ServiceLocatorInstanceHolderDestroying<Instance> | ServiceLocatorInstanceHolderError;
1057
- export { ServiceLocatorInstanceHolder }
1058
- export { ServiceLocatorInstanceHolder as ServiceLocatorInstanceHolder_alias_1 }
1059
-
1060
- declare interface ServiceLocatorInstanceHolderCreated<Instance> {
1061
- status: ServiceLocatorInstanceHolderStatus.Created;
1062
- name: string;
1063
- instance: Instance;
1064
- creationPromise: null;
1065
- destroyPromise: null;
1066
- type: InjectableType;
1067
- scope: InjectableScope;
1068
- deps: Set<string>;
1069
- destroyListeners: ServiceLocatorInstanceDestroyListener[];
1070
- createdAt: number;
1071
- }
1072
- export { ServiceLocatorInstanceHolderCreated }
1073
- export { ServiceLocatorInstanceHolderCreated as ServiceLocatorInstanceHolderCreated_alias_1 }
1074
-
1075
- declare interface ServiceLocatorInstanceHolderCreating<Instance> {
1076
- status: ServiceLocatorInstanceHolderStatus.Creating;
1077
- name: string;
1078
- instance: null;
1079
- creationPromise: Promise<[undefined, Instance]> | null;
1080
- destroyPromise: null;
1081
- type: InjectableType;
1082
- scope: InjectableScope;
1083
- deps: Set<string>;
1084
- destroyListeners: ServiceLocatorInstanceDestroyListener[];
1085
- createdAt: number;
1086
- }
1087
- export { ServiceLocatorInstanceHolderCreating }
1088
- export { ServiceLocatorInstanceHolderCreating as ServiceLocatorInstanceHolderCreating_alias_1 }
1089
-
1090
- declare interface ServiceLocatorInstanceHolderDestroying<Instance> {
1091
- status: ServiceLocatorInstanceHolderStatus.Destroying;
1092
- name: string;
1093
- instance: Instance | null;
1094
- creationPromise: null;
1095
- destroyPromise: Promise<void>;
1096
- type: InjectableType;
1097
- scope: InjectableScope;
1098
- deps: Set<string>;
1099
- destroyListeners: ServiceLocatorInstanceDestroyListener[];
1100
- createdAt: number;
1101
- }
1102
- export { ServiceLocatorInstanceHolderDestroying }
1103
- export { ServiceLocatorInstanceHolderDestroying as ServiceLocatorInstanceHolderDestroying_alias_1 }
1104
-
1105
- declare interface ServiceLocatorInstanceHolderError {
1106
- status: ServiceLocatorInstanceHolderStatus.Error;
1107
- name: string;
1108
- instance: Error;
1109
- creationPromise: null;
1110
- destroyPromise: null;
1111
- type: InjectableType;
1112
- scope: InjectableScope;
1113
- deps: Set<string>;
1114
- destroyListeners: ServiceLocatorInstanceDestroyListener[];
1115
- createdAt: number;
1116
- }
1117
- export { ServiceLocatorInstanceHolderError }
1118
- export { ServiceLocatorInstanceHolderError as ServiceLocatorInstanceHolderError_alias_1 }
1119
-
1120
- declare enum ServiceLocatorInstanceHolderStatus {
1121
- Created = "created",
1122
- Creating = "creating",
1123
- Destroying = "destroying",
1124
- Error = "error"
1125
- }
1126
- export { ServiceLocatorInstanceHolderStatus }
1127
- export { ServiceLocatorInstanceHolderStatus as ServiceLocatorInstanceHolderStatus_alias_1 }
1128
-
1129
- declare class ServiceLocatorManager extends BaseInstanceHolderManager {
1130
- constructor(logger?: Console | null);
1131
- get(name: string): [DIError, ServiceLocatorInstanceHolder] | [DIError] | [undefined, ServiceLocatorInstanceHolder];
1132
- set(name: string, holder: ServiceLocatorInstanceHolder): void;
1133
- has(name: string): [DIError] | [undefined, boolean];
1134
- /**
1135
- * Creates a new holder with Created status and an actual instance.
1136
- * This is useful for creating holders that already have their instance ready.
1137
- * @param name The name of the instance
1138
- * @param instance The actual instance to store
1139
- * @param type The injectable type
1140
- * @param scope The injectable scope
1141
- * @param deps Optional set of dependencies
1142
- * @returns The created holder
1143
- */
1144
- storeCreatedHolder<Instance>(name: string, instance: Instance, type: InjectableType, scope: InjectableScope, deps?: Set<string>): ServiceLocatorInstanceHolder<Instance>;
1145
- }
1146
- export { ServiceLocatorManager }
1147
- export { ServiceLocatorManager as ServiceLocatorManager_alias_1 }
1148
-
1149
- export declare const test1: string;
1150
-
1151
- export declare const test2: number;
1152
-
1153
- export declare const test3: boolean;
1154
-
1155
- export declare const test4: {
1156
- name: string;
1157
- };
1158
-
1159
- export declare const test5: object;
1160
-
1161
- /**
1162
- * A binding builder for the TestContainer that allows chaining binding operations.
1163
- */
1164
- declare class TestBindingBuilder<T> {
1165
- private readonly container;
1166
- private readonly token;
1167
- constructor(container: TestContainer, token: InjectionToken<T, any>);
1168
- /**
1169
- * Binds the token to a specific value.
1170
- * This is useful for testing with mock values or constants.
1171
- * @param value The value to bind to the token
1172
- */
1173
- toValue(value: T): TestContainer;
1174
- /**
1175
- * Binds the token to a class constructor.
1176
- * @param target The class constructor to bind to
1177
- */
1178
- toClass(target: ClassType): TestContainer;
1179
- }
1180
- export { TestBindingBuilder }
1181
- export { TestBindingBuilder as TestBindingBuilder_alias_1 }
1182
-
1183
- /**
1184
- * TestContainer extends the base Container with additional methods useful for testing.
1185
- * It provides a simplified API for binding values and classes during test setup.
1186
- */
1187
- declare class TestContainer extends Container {
1188
- constructor(registry?: Registry, logger?: Console | null, injectors?: Injectors);
1189
- /**
1190
- * Creates a binding builder for the given token.
1191
- * This allows chaining binding operations like bind(Token).toValue(value).
1192
- * @param token The injection token to bind
1193
- * @returns A TestBindingBuilder for chaining binding operations
1194
- */
1195
- bind<T>(token: ClassType): TestBindingBuilder<T>;
1196
- bind<T>(token: InjectionToken<T, any>): TestBindingBuilder<T>;
1197
- /**
1198
- * Binds a value directly to a token.
1199
- * This is a convenience method equivalent to bind(token).toValue(value).
1200
- * @param token The injection token to bind
1201
- * @param value The value to bind to the token
1202
- * @returns The TestContainer instance for chaining
1203
- */
1204
- bindValue<T>(token: ClassType, value: T): TestContainer;
1205
- bindValue<T>(token: InjectionToken<T, any>, value: T): TestContainer;
1206
- /**
1207
- * Binds a class to a token.
1208
- * This is a convenience method equivalent to bind(token).toClass(target).
1209
- * @param token The injection token to bind
1210
- * @param target The class constructor to bind to
1211
- * @returns The TestContainer instance for chaining
1212
- */
1213
- bindClass(token: ClassType, target: ClassType): TestContainer;
1214
- bindClass<T>(token: InjectionToken<T, any>, target: ClassType): TestContainer;
1215
- /**
1216
- * Creates a new TestContainer instance with the same configuration.
1217
- * This is useful for creating isolated test containers.
1218
- * @returns A new TestContainer instance
1219
- */
1220
- createChild(): TestContainer;
1221
- }
1222
- export { TestContainer }
1223
- export { TestContainer as TestContainer_alias_1 }
1224
-
1225
- /**
1226
- * TokenProcessor handles token validation, resolution, and instance name generation.
1227
- * Extracted from ServiceLocator to improve separation of concerns.
1228
- */
1229
- export declare class TokenProcessor {
1230
- private readonly logger;
1231
- constructor(logger?: Console | null);
1232
- /**
1233
- * Validates and resolves token arguments, handling factory token resolution and validation.
1234
- */
1235
- validateAndResolveTokenArgs(token: AnyInjectableType, args?: any): [
1236
- DIError | undefined,
1237
- {
1238
- actualToken: InjectionTokenType;
1239
- validatedArgs?: any;
1240
- }
1241
- ];
1242
- /**
1243
- * Generates a unique instance name based on token and arguments.
1244
- */
1245
- generateInstanceName(token: InjectionTokenType, args: any): string;
1246
- /**
1247
- * Formats a single argument value for instance name generation.
1248
- */
1249
- formatArgValue(value: any): string;
1250
- /**
1251
- * Creates a factory context for dependency injection during service instantiation.
1252
- * @param serviceLocator Reference to the service locator for dependency resolution
1253
- */
1254
- createFactoryContext(serviceLocator: ServiceLocator): FactoryContext & {
1255
- getDestroyListeners: () => (() => void)[];
1256
- deps: Set<string>;
1257
- };
1258
- /**
1259
- * Tries to get a pre-prepared instance from request contexts.
1260
- */
1261
- tryGetPrePreparedInstance(instanceName: string, contextHolder: RequestContextHolder | undefined, deps: Set<string>, currentRequestContext: RequestContextHolder | null): any;
1262
- }
1263
-
1264
- declare type UnionToArray<T, A extends unknown[] = []> = IsUnion<T> extends true ? UnionToArray<Exclude<T, PopUnion<T>>, [PopUnion<T>, ...A]> : [T, ...A];
1265
- export { UnionToArray }
1266
- export { UnionToArray as UnionToArray_alias_1 }
1267
- export { UnionToArray as UnionToArray_alias_2 }
1268
-
1269
- declare type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never;
1270
- export { UnionToIntersection }
1271
- export { UnionToIntersection as UnionToIntersection_alias_1 }
1272
- export { UnionToIntersection as UnionToIntersection_alias_2 }
1273
-
1274
- declare type UnionToOvlds<U> = UnionToIntersection<U extends any ? (f: U) => void : never>;
1275
- export { UnionToOvlds }
1276
- export { UnionToOvlds as UnionToOvlds_alias_1 }
1277
- export { UnionToOvlds as UnionToOvlds_alias_2 }
1278
-
1279
- declare const wrapSyncInit: Injectors['wrapSyncInit'];
1280
- export { wrapSyncInit }
1281
- export { wrapSyncInit as wrapSyncInit_alias_1 }
1282
-
1283
- export { }