@navios/di 0.4.1 → 0.5.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 (128) hide show
  1. package/README.md +211 -1
  2. package/coverage/clover.xml +1912 -1277
  3. package/coverage/coverage-final.json +37 -28
  4. package/coverage/docs/examples/basic-usage.mts.html +1 -1
  5. package/coverage/docs/examples/factory-pattern.mts.html +1 -1
  6. package/coverage/docs/examples/index.html +1 -1
  7. package/coverage/docs/examples/injection-tokens.mts.html +1 -1
  8. package/coverage/docs/examples/request-scope-example.mts.html +1 -1
  9. package/coverage/docs/examples/service-lifecycle.mts.html +1 -1
  10. package/coverage/index.html +71 -41
  11. package/coverage/lib/_tsup-dts-rollup.d.mts.html +682 -43
  12. package/coverage/lib/index.d.mts.html +7 -4
  13. package/coverage/lib/index.html +5 -5
  14. package/coverage/lib/testing/index.d.mts.html +91 -0
  15. package/coverage/lib/testing/index.html +116 -0
  16. package/coverage/src/base-instance-holder-manager.mts.html +589 -0
  17. package/coverage/src/container.mts.html +257 -74
  18. package/coverage/src/decorators/factory.decorator.mts.html +1 -1
  19. package/coverage/src/decorators/index.html +1 -1
  20. package/coverage/src/decorators/index.mts.html +1 -1
  21. package/coverage/src/decorators/injectable.decorator.mts.html +20 -20
  22. package/coverage/src/enums/index.html +1 -1
  23. package/coverage/src/enums/index.mts.html +1 -1
  24. package/coverage/src/enums/injectable-scope.enum.mts.html +1 -1
  25. package/coverage/src/enums/injectable-type.enum.mts.html +1 -1
  26. package/coverage/src/errors/di-error.mts.html +292 -0
  27. package/coverage/src/errors/errors.enum.mts.html +30 -21
  28. package/coverage/src/errors/factory-not-found.mts.html +31 -22
  29. package/coverage/src/errors/factory-token-not-resolved.mts.html +29 -26
  30. package/coverage/src/errors/index.html +56 -41
  31. package/coverage/src/errors/index.mts.html +15 -9
  32. package/coverage/src/errors/instance-destroying.mts.html +31 -22
  33. package/coverage/src/errors/instance-expired.mts.html +31 -22
  34. package/coverage/src/errors/instance-not-found.mts.html +31 -22
  35. package/coverage/src/errors/unknown-error.mts.html +31 -43
  36. package/coverage/src/event-emitter.mts.html +14 -14
  37. package/coverage/src/factory-context.mts.html +1 -1
  38. package/coverage/src/index.html +121 -46
  39. package/coverage/src/index.mts.html +7 -4
  40. package/coverage/src/injection-token.mts.html +28 -28
  41. package/coverage/src/injector.mts.html +1 -1
  42. package/coverage/src/instance-resolver.mts.html +1762 -0
  43. package/coverage/src/interfaces/factory.interface.mts.html +1 -1
  44. package/coverage/src/interfaces/index.html +1 -1
  45. package/coverage/src/interfaces/index.mts.html +1 -1
  46. package/coverage/src/interfaces/on-service-destroy.interface.mts.html +1 -1
  47. package/coverage/src/interfaces/on-service-init.interface.mts.html +1 -1
  48. package/coverage/src/registry.mts.html +28 -28
  49. package/coverage/src/request-context-holder.mts.html +183 -102
  50. package/coverage/src/request-context-manager.mts.html +532 -0
  51. package/coverage/src/service-instantiator.mts.html +49 -49
  52. package/coverage/src/service-invalidator.mts.html +1372 -0
  53. package/coverage/src/service-locator-event-bus.mts.html +48 -48
  54. package/coverage/src/service-locator-instance-holder.mts.html +2 -14
  55. package/coverage/src/service-locator-manager.mts.html +71 -335
  56. package/coverage/src/service-locator.mts.html +240 -2328
  57. package/coverage/src/symbols/index.html +1 -1
  58. package/coverage/src/symbols/index.mts.html +1 -1
  59. package/coverage/src/symbols/injectable-token.mts.html +1 -1
  60. package/coverage/src/testing/index.html +131 -0
  61. package/coverage/src/testing/index.mts.html +88 -0
  62. package/coverage/src/testing/test-container.mts.html +445 -0
  63. package/coverage/src/token-processor.mts.html +607 -0
  64. package/coverage/src/utils/defer.mts.html +28 -214
  65. package/coverage/src/utils/get-injectable-token.mts.html +7 -7
  66. package/coverage/src/utils/get-injectors.mts.html +99 -99
  67. package/coverage/src/utils/index.html +15 -15
  68. package/coverage/src/utils/index.mts.html +4 -7
  69. package/coverage/src/utils/types.mts.html +1 -1
  70. package/docs/injectable.md +51 -11
  71. package/docs/scopes.md +63 -29
  72. package/lib/_tsup-dts-rollup.d.mts +447 -212
  73. package/lib/_tsup-dts-rollup.d.ts +447 -212
  74. package/lib/chunk-44F3LXW5.mjs +2043 -0
  75. package/lib/chunk-44F3LXW5.mjs.map +1 -0
  76. package/lib/index.d.mts +6 -4
  77. package/lib/index.d.ts +6 -4
  78. package/lib/index.js +1199 -773
  79. package/lib/index.js.map +1 -1
  80. package/lib/index.mjs +4 -1599
  81. package/lib/index.mjs.map +1 -1
  82. package/lib/testing/index.d.mts +2 -0
  83. package/lib/testing/index.d.ts +2 -0
  84. package/lib/testing/index.js +2060 -0
  85. package/lib/testing/index.js.map +1 -0
  86. package/lib/testing/index.mjs +73 -0
  87. package/lib/testing/index.mjs.map +1 -0
  88. package/package.json +11 -1
  89. package/src/__tests__/container.spec.mts +47 -13
  90. package/src/__tests__/errors.spec.mts +53 -27
  91. package/src/__tests__/injectable.spec.mts +73 -0
  92. package/src/__tests__/request-scope.spec.mts +0 -2
  93. package/src/__tests__/service-locator-manager.spec.mts +12 -82
  94. package/src/__tests__/service-locator.spec.mts +1009 -1
  95. package/src/__type-tests__/inject.spec-d.mts +30 -7
  96. package/src/__type-tests__/injectable.spec-d.mts +76 -37
  97. package/src/base-instance-holder-manager.mts +2 -9
  98. package/src/container.mts +70 -10
  99. package/src/decorators/injectable.decorator.mts +29 -5
  100. package/src/errors/di-error.mts +69 -0
  101. package/src/errors/index.mts +9 -7
  102. package/src/injection-token.mts +1 -0
  103. package/src/injector.mts +2 -0
  104. package/src/instance-resolver.mts +559 -0
  105. package/src/request-context-holder.mts +0 -2
  106. package/src/request-context-manager.mts +149 -0
  107. package/src/service-invalidator.mts +429 -0
  108. package/src/service-locator-instance-holder.mts +0 -4
  109. package/src/service-locator-manager.mts +10 -40
  110. package/src/service-locator.mts +86 -782
  111. package/src/testing/README.md +80 -0
  112. package/src/testing/__tests__/test-container.spec.mts +173 -0
  113. package/src/testing/index.mts +1 -0
  114. package/src/testing/test-container.mts +120 -0
  115. package/src/token-processor.mts +174 -0
  116. package/src/utils/get-injectors.mts +161 -24
  117. package/src/utils/index.mts +0 -1
  118. package/src/utils/types.mts +12 -8
  119. package/tsup.config.mts +1 -1
  120. package/src/__tests__/defer.spec.mts +0 -166
  121. package/src/errors/errors.enum.mts +0 -8
  122. package/src/errors/factory-not-found.mts +0 -8
  123. package/src/errors/factory-token-not-resolved.mts +0 -10
  124. package/src/errors/instance-destroying.mts +0 -8
  125. package/src/errors/instance-expired.mts +0 -8
  126. package/src/errors/instance-not-found.mts +0 -8
  127. package/src/errors/unknown-error.mts +0 -15
  128. package/src/utils/defer.mts +0 -73
@@ -0,0 +1,2060 @@
1
+ 'use strict';
2
+
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
7
+ var __typeError = (msg) => {
8
+ throw TypeError(msg);
9
+ };
10
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
11
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
12
+ var __decoratorStart = (base) => [, , , __create(base?.[__knownSymbol("metadata")] ?? null)];
13
+ var __decoratorStrings = ["class", "method", "getter", "setter", "accessor", "field", "value", "get", "set"];
14
+ var __expectFn = (fn) => fn !== void 0 && typeof fn !== "function" ? __typeError("Function expected") : fn;
15
+ var __decoratorContext = (kind, name, done, metadata, fns) => ({ kind: __decoratorStrings[kind], name, metadata, addInitializer: (fn) => done._ ? __typeError("Already initialized") : fns.push(__expectFn(fn || null)) });
16
+ var __decoratorMetadata = (array, target) => __defNormalProp(target, __knownSymbol("metadata"), array[3]);
17
+ var __runInitializers = (array, flags, self, value) => {
18
+ for (var i = 0, fns = array[flags >> 1], n = fns && fns.length; i < n; i++) fns[i].call(self) ;
19
+ return value;
20
+ };
21
+ var __decorateElement = (array, flags, name, decorators, target, extra) => {
22
+ var it, done, ctx, k = flags & 7, p = false;
23
+ var j = 0;
24
+ var extraInitializers = array[j] || (array[j] = []);
25
+ var desc = k && ((target = target.prototype), k < 5 && (k > 3 || !p) && __getOwnPropDesc(target , name));
26
+ __name(target, name);
27
+ for (var i = decorators.length - 1; i >= 0; i--) {
28
+ ctx = __decoratorContext(k, name, done = {}, array[3], extraInitializers);
29
+ it = (0, decorators[i])(target, ctx), done._ = 1;
30
+ __expectFn(it) && (target = it);
31
+ }
32
+ return __decoratorMetadata(array, target), desc && __defProp(target, name, desc), p ? k ^ 4 ? extra : desc : target;
33
+ };
34
+
35
+ // src/injection-token.mts
36
+ var InjectionToken = class _InjectionToken {
37
+ constructor(name, schema) {
38
+ this.name = name;
39
+ this.schema = schema;
40
+ }
41
+ id = globalThis.crypto.randomUUID();
42
+ formattedName = null;
43
+ static create(name, schema) {
44
+ return new _InjectionToken(name, schema);
45
+ }
46
+ static bound(token, value) {
47
+ return new BoundInjectionToken(token, value);
48
+ }
49
+ static factory(token, factory) {
50
+ return new FactoryInjectionToken(token, factory);
51
+ }
52
+ static refineType(token) {
53
+ return token;
54
+ }
55
+ toString() {
56
+ if (this.formattedName) {
57
+ return this.formattedName;
58
+ }
59
+ const { name } = this;
60
+ if (typeof name === "function") {
61
+ const className = name.name;
62
+ this.formattedName = `${className}(${this.id})`;
63
+ } else if (typeof name === "symbol") {
64
+ this.formattedName = `${name.toString()}(${this.id})`;
65
+ } else {
66
+ this.formattedName = `${name}(${this.id})`;
67
+ }
68
+ return this.formattedName;
69
+ }
70
+ };
71
+ var BoundInjectionToken = class {
72
+ constructor(token, value) {
73
+ this.token = token;
74
+ this.value = value;
75
+ this.name = token.name;
76
+ this.id = token.id;
77
+ this.schema = token.schema;
78
+ }
79
+ id;
80
+ name;
81
+ schema;
82
+ toString() {
83
+ return this.token.toString();
84
+ }
85
+ };
86
+ var FactoryInjectionToken = class {
87
+ constructor(token, factory) {
88
+ this.token = token;
89
+ this.factory = factory;
90
+ this.name = token.name;
91
+ this.id = token.id;
92
+ this.schema = token.schema;
93
+ }
94
+ value;
95
+ resolved = false;
96
+ id;
97
+ name;
98
+ schema;
99
+ async resolve(ctx) {
100
+ if (!this.value) {
101
+ this.value = await this.factory(ctx);
102
+ this.resolved = true;
103
+ }
104
+ return this.value;
105
+ }
106
+ toString() {
107
+ return this.token.toString();
108
+ }
109
+ };
110
+
111
+ // src/registry.mts
112
+ var Registry = class {
113
+ constructor(parent) {
114
+ this.parent = parent;
115
+ }
116
+ factories = /* @__PURE__ */ new Map();
117
+ has(token) {
118
+ if (this.factories.has(token.id)) {
119
+ return true;
120
+ }
121
+ if (this.parent) {
122
+ return this.parent.has(token);
123
+ }
124
+ return false;
125
+ }
126
+ get(token) {
127
+ const factory = this.factories.get(token.id);
128
+ if (!factory) {
129
+ if (this.parent) {
130
+ return this.parent.get(token);
131
+ }
132
+ throw new Error(`[Registry] No factory found for ${token.toString()}`);
133
+ }
134
+ return factory;
135
+ }
136
+ set(token, scope, target, type) {
137
+ this.factories.set(token.id, { scope, originalToken: token, target, type });
138
+ }
139
+ delete(token) {
140
+ this.factories.delete(token.id);
141
+ }
142
+ };
143
+ var globalRegistry = new Registry();
144
+
145
+ // src/symbols/injectable-token.mts
146
+ var InjectableTokenMeta = Symbol.for("InjectableTokenMeta");
147
+
148
+ // src/decorators/injectable.decorator.mts
149
+ function Injectable({
150
+ scope = "Singleton" /* Singleton */,
151
+ token,
152
+ schema,
153
+ registry = globalRegistry
154
+ } = {}) {
155
+ return (target, context) => {
156
+ if (context && context.kind !== "class" || target instanceof Function && !context) {
157
+ throw new Error(
158
+ "[ServiceLocator] @Injectable decorator can only be used on classes."
159
+ );
160
+ }
161
+ if (schema && token) {
162
+ throw new Error(
163
+ "[ServiceLocator] @Injectable decorator cannot have both a token and a schema"
164
+ );
165
+ }
166
+ let injectableToken = token ?? InjectionToken.create(target, schema);
167
+ registry.set(injectableToken, scope, target, "Class" /* Class */);
168
+ target[InjectableTokenMeta] = injectableToken;
169
+ return target;
170
+ };
171
+ }
172
+
173
+ // src/utils/get-injectors.mts
174
+ function getInjectors() {
175
+ let currentFactoryContext = null;
176
+ function provideFactoryContext2(context) {
177
+ const original = currentFactoryContext;
178
+ currentFactoryContext = context;
179
+ return original;
180
+ }
181
+ function getFactoryContext() {
182
+ if (!currentFactoryContext) {
183
+ throw new Error(
184
+ "[Injector] Trying to access injection context outside of a injectable context"
185
+ );
186
+ }
187
+ return currentFactoryContext;
188
+ }
189
+ let promiseCollector = null;
190
+ let injectState = null;
191
+ function getRequest(token, args) {
192
+ if (!injectState) {
193
+ throw new Error(
194
+ "[Injector] Trying to make a request outside of a injectable context"
195
+ );
196
+ }
197
+ if (injectState.isFrozen) {
198
+ const idx = injectState.currentIndex++;
199
+ const request2 = injectState.requests[idx];
200
+ if (request2.token !== token) {
201
+ throw new Error(
202
+ `[Injector] Wrong token order. Expected ${request2.token.toString()} but got ${token.toString()}`
203
+ );
204
+ }
205
+ return request2;
206
+ }
207
+ let result = null;
208
+ let error = null;
209
+ const promise = getFactoryContext().inject(token, args).then((r) => {
210
+ result = r;
211
+ return r;
212
+ }).catch((e) => {
213
+ error = e;
214
+ });
215
+ const request = {
216
+ token,
217
+ promise,
218
+ get result() {
219
+ return result;
220
+ },
221
+ get error() {
222
+ return error;
223
+ }
224
+ };
225
+ injectState.requests.push(request);
226
+ injectState.currentIndex++;
227
+ return request;
228
+ }
229
+ function asyncInject2(token, args) {
230
+ if (!injectState) {
231
+ throw new Error(
232
+ "[Injector] Trying to access inject outside of a injectable context"
233
+ );
234
+ }
235
+ const realToken = token[InjectableTokenMeta] ?? token;
236
+ const request = getRequest(realToken, args);
237
+ return request.promise.then((result) => {
238
+ if (request.error) {
239
+ throw request.error;
240
+ }
241
+ return result;
242
+ });
243
+ }
244
+ function wrapSyncInit2(cb) {
245
+ return (previousState) => {
246
+ const promises = [];
247
+ const originalPromiseCollector = promiseCollector;
248
+ const originalInjectState = injectState;
249
+ injectState = previousState ? {
250
+ ...previousState,
251
+ currentIndex: 0
252
+ } : {
253
+ currentIndex: 0,
254
+ isFrozen: false,
255
+ requests: []
256
+ };
257
+ promiseCollector = (promise) => {
258
+ promises.push(promise);
259
+ };
260
+ const result = cb();
261
+ promiseCollector = originalPromiseCollector;
262
+ const newInjectState = {
263
+ ...injectState,
264
+ isFrozen: true
265
+ };
266
+ injectState = originalInjectState;
267
+ return [result, promises, newInjectState];
268
+ };
269
+ }
270
+ function inject2(token, args) {
271
+ const realToken = token[InjectableTokenMeta] ?? token;
272
+ if (!injectState) {
273
+ throw new Error(
274
+ "[Injector] Trying to access inject outside of a injectable context"
275
+ );
276
+ }
277
+ const instance = getFactoryContext().locator.getSyncInstance(
278
+ realToken,
279
+ args
280
+ );
281
+ if (!instance) {
282
+ const request = getRequest(realToken, args);
283
+ if (request.error) {
284
+ throw request.error;
285
+ } else if (request.result) {
286
+ return request.result;
287
+ }
288
+ if (promiseCollector) {
289
+ promiseCollector(request.promise);
290
+ }
291
+ return new Proxy(
292
+ {},
293
+ {
294
+ get() {
295
+ throw new Error(
296
+ `[Injector] Trying to access ${realToken.toString()} before it's initialized, please move the code to a onServiceInit method`
297
+ );
298
+ }
299
+ }
300
+ );
301
+ }
302
+ return instance;
303
+ }
304
+ function optional2(token, args) {
305
+ try {
306
+ return inject2(token, args);
307
+ } catch {
308
+ return null;
309
+ }
310
+ }
311
+ const injectors = {
312
+ asyncInject: asyncInject2,
313
+ inject: inject2,
314
+ optional: optional2,
315
+ wrapSyncInit: wrapSyncInit2,
316
+ provideFactoryContext: provideFactoryContext2
317
+ };
318
+ return injectors;
319
+ }
320
+
321
+ // src/utils/get-injectable-token.mts
322
+ function getInjectableToken(target) {
323
+ const token = target[InjectableTokenMeta];
324
+ if (!token) {
325
+ throw new Error(
326
+ `[ServiceLocator] Class ${target.name} is not decorated with @Injectable.`
327
+ );
328
+ }
329
+ return token;
330
+ }
331
+
332
+ // src/injector.mts
333
+ var defaultInjectors = getInjectors();
334
+
335
+ // src/errors/di-error.mts
336
+ var DIError = class _DIError extends Error {
337
+ code;
338
+ context;
339
+ constructor(code, message, context) {
340
+ super(message);
341
+ this.name = "DIError";
342
+ this.code = code;
343
+ this.context = context;
344
+ }
345
+ // Static factory methods for common error types
346
+ static factoryNotFound(name) {
347
+ return new _DIError(
348
+ "FactoryNotFound" /* FactoryNotFound */,
349
+ `Factory ${name} not found`,
350
+ { name }
351
+ );
352
+ }
353
+ static factoryTokenNotResolved(token) {
354
+ return new _DIError(
355
+ "FactoryTokenNotResolved" /* FactoryTokenNotResolved */,
356
+ `Factory token not resolved: ${token?.toString() ?? "unknown"}`,
357
+ { token }
358
+ );
359
+ }
360
+ static instanceNotFound(name) {
361
+ return new _DIError(
362
+ "InstanceNotFound" /* InstanceNotFound */,
363
+ `Instance ${name} not found`,
364
+ { name }
365
+ );
366
+ }
367
+ static instanceDestroying(name) {
368
+ return new _DIError(
369
+ "InstanceDestroying" /* InstanceDestroying */,
370
+ `Instance ${name} destroying`,
371
+ { name }
372
+ );
373
+ }
374
+ static unknown(message, context) {
375
+ if (message instanceof Error) {
376
+ return new _DIError("UnknownError" /* UnknownError */, message.message, {
377
+ ...context,
378
+ parent: message
379
+ });
380
+ }
381
+ return new _DIError("UnknownError" /* UnknownError */, message, context);
382
+ }
383
+ };
384
+
385
+ // src/instance-resolver.mts
386
+ var InstanceResolver = class {
387
+ constructor(registry, manager, serviceInstantiator, tokenProcessor, logger = null, serviceLocator) {
388
+ this.registry = registry;
389
+ this.manager = manager;
390
+ this.serviceInstantiator = serviceInstantiator;
391
+ this.tokenProcessor = tokenProcessor;
392
+ this.logger = logger;
393
+ this.serviceLocator = serviceLocator;
394
+ }
395
+ /**
396
+ * Resolves an instance for the given token and arguments.
397
+ */
398
+ async resolveInstance(token, args, requestContext) {
399
+ const [err, data] = await this.resolveTokenAndPrepareInstanceName(
400
+ token,
401
+ args
402
+ );
403
+ if (err) {
404
+ return [err];
405
+ }
406
+ const {
407
+ instanceName,
408
+ validatedArgs,
409
+ realToken
410
+ } = data;
411
+ const [error, holder] = await this.retrieveOrCreateInstanceByInstanceName(
412
+ instanceName,
413
+ realToken,
414
+ validatedArgs,
415
+ requestContext
416
+ );
417
+ if (error) {
418
+ return [error];
419
+ }
420
+ return [void 0, holder.instance];
421
+ }
422
+ /**
423
+ * Gets a synchronous instance (for sync operations).
424
+ */
425
+ getSyncInstance(token, args, currentRequestContext) {
426
+ const [err, { actualToken, validatedArgs }] = this.tokenProcessor.validateAndResolveTokenArgs(token, args);
427
+ if (err) {
428
+ return null;
429
+ }
430
+ const instanceName = this.tokenProcessor.generateInstanceName(
431
+ actualToken,
432
+ validatedArgs
433
+ );
434
+ if (currentRequestContext) {
435
+ const requestHolder = currentRequestContext.get(instanceName);
436
+ if (requestHolder) {
437
+ return requestHolder.instance;
438
+ }
439
+ }
440
+ const [error, holder] = this.manager.get(instanceName);
441
+ if (error) {
442
+ return null;
443
+ }
444
+ return holder.instance;
445
+ }
446
+ /**
447
+ * Internal method to resolve token args and create instance name.
448
+ * Handles factory token resolution and validation.
449
+ */
450
+ async resolveTokenAndPrepareInstanceName(token, args) {
451
+ const [err, { actualToken, validatedArgs }] = this.tokenProcessor.validateAndResolveTokenArgs(token, args);
452
+ if (err instanceof DIError && err.code === "UnknownError" /* UnknownError */) {
453
+ return [err];
454
+ } else if (err instanceof DIError && err.code === "FactoryTokenNotResolved" /* FactoryTokenNotResolved */ && actualToken instanceof FactoryInjectionToken) {
455
+ this.logger?.log(
456
+ `[InstanceResolver]#resolveTokenAndPrepareInstanceName() Factory token not resolved, resolving it`
457
+ );
458
+ await actualToken.resolve(this.createFactoryContext());
459
+ return this.resolveTokenAndPrepareInstanceName(token);
460
+ }
461
+ const instanceName = this.tokenProcessor.generateInstanceName(
462
+ actualToken,
463
+ validatedArgs
464
+ );
465
+ const realToken = actualToken instanceof BoundInjectionToken || actualToken instanceof FactoryInjectionToken ? actualToken.token : actualToken;
466
+ return [void 0, { instanceName, validatedArgs, actualToken, realToken }];
467
+ }
468
+ /**
469
+ * Gets an instance by its instance name, handling all the logic after instance name creation.
470
+ */
471
+ async retrieveOrCreateInstanceByInstanceName(instanceName, realToken, realArgs, requestContext) {
472
+ const existingHolder = await this.tryGetExistingInstance(
473
+ instanceName,
474
+ realToken,
475
+ requestContext
476
+ );
477
+ if (existingHolder) {
478
+ return existingHolder;
479
+ }
480
+ const result = await this.createNewInstance(
481
+ instanceName,
482
+ realToken,
483
+ realArgs,
484
+ requestContext
485
+ );
486
+ if (result[0]) {
487
+ return [result[0]];
488
+ }
489
+ const [, holder] = result;
490
+ return this.waitForInstanceReady(holder);
491
+ }
492
+ /**
493
+ * Attempts to retrieve an existing instance, handling request-scoped and singleton instances.
494
+ * Returns null if no instance exists and a new one should be created.
495
+ */
496
+ async tryGetExistingInstance(instanceName, realToken, requestContext) {
497
+ const requestResult = await this.tryGetRequestScopedInstance(
498
+ instanceName,
499
+ realToken,
500
+ requestContext
501
+ );
502
+ if (requestResult) {
503
+ return requestResult;
504
+ }
505
+ return this.tryGetSingletonInstance(instanceName);
506
+ }
507
+ /**
508
+ * Attempts to get a request-scoped instance if applicable.
509
+ */
510
+ async tryGetRequestScopedInstance(instanceName, realToken, requestContext) {
511
+ if (!this.registry.has(realToken)) {
512
+ return null;
513
+ }
514
+ const record = this.registry.get(realToken);
515
+ if (record.scope !== "Request" /* Request */) {
516
+ return null;
517
+ }
518
+ if (!requestContext) {
519
+ this.logger?.log(
520
+ `[InstanceResolver] No current request context available for request-scoped service ${instanceName}`
521
+ );
522
+ return [
523
+ DIError.unknown(
524
+ `No current request context available for request-scoped service ${instanceName}`
525
+ )
526
+ ];
527
+ }
528
+ const requestHolder = requestContext.get(instanceName);
529
+ if (!requestHolder) {
530
+ return null;
531
+ }
532
+ return this.waitForInstanceReady(requestHolder);
533
+ }
534
+ /**
535
+ * Attempts to get a singleton instance from the manager.
536
+ */
537
+ async tryGetSingletonInstance(instanceName) {
538
+ const [error, holder] = this.manager.get(instanceName);
539
+ if (!error) {
540
+ return this.waitForInstanceReady(holder);
541
+ }
542
+ switch (error.code) {
543
+ case "InstanceDestroying" /* InstanceDestroying */:
544
+ this.logger?.log(
545
+ `[InstanceResolver] Instance ${instanceName} is being destroyed, waiting...`
546
+ );
547
+ await holder?.destroyPromise;
548
+ return this.tryGetSingletonInstance(instanceName);
549
+ case "InstanceNotFound" /* InstanceNotFound */:
550
+ return null;
551
+ // Instance doesn't exist, should create new one
552
+ default:
553
+ return [error];
554
+ }
555
+ }
556
+ /**
557
+ * Waits for an instance holder to be ready and returns the appropriate result.
558
+ */
559
+ async waitForInstanceReady(holder) {
560
+ switch (holder.status) {
561
+ case "creating" /* Creating */:
562
+ await holder.creationPromise;
563
+ return this.waitForInstanceReady(holder);
564
+ case "destroying" /* Destroying */:
565
+ return [DIError.instanceDestroying(holder.name)];
566
+ case "error" /* Error */:
567
+ return [holder.instance];
568
+ case "created" /* Created */:
569
+ return [void 0, holder];
570
+ default:
571
+ return [DIError.instanceNotFound("unknown")];
572
+ }
573
+ }
574
+ /**
575
+ * Creates a new instance for the given token and arguments.
576
+ */
577
+ async createNewInstance(instanceName, realToken, args, requestContext) {
578
+ this.logger?.log(
579
+ `[InstanceResolver]#createNewInstance() Creating instance for ${instanceName}`
580
+ );
581
+ if (this.registry.has(realToken)) {
582
+ return this.instantiateServiceFromRegistry(
583
+ instanceName,
584
+ realToken,
585
+ args,
586
+ requestContext
587
+ );
588
+ } else {
589
+ return [DIError.factoryNotFound(realToken.name.toString())];
590
+ }
591
+ }
592
+ /**
593
+ * Instantiates a service from the registry using the service instantiator.
594
+ */
595
+ instantiateServiceFromRegistry(instanceName, token, args, requestContext) {
596
+ this.logger?.log(
597
+ `[InstanceResolver]#instantiateServiceFromRegistry(): Creating instance for ${instanceName} from abstract factory`
598
+ );
599
+ const ctx = this.createFactoryContext();
600
+ let record = this.registry.get(token);
601
+ let { scope, type } = record;
602
+ const [deferred, holder] = this.manager.createCreatingHolder(
603
+ instanceName,
604
+ type,
605
+ scope,
606
+ ctx.deps
607
+ );
608
+ this.serviceInstantiator.instantiateService(ctx, record, args).then(async ([error, instance]) => {
609
+ await this.handleInstantiationResult(
610
+ instanceName,
611
+ holder,
612
+ ctx,
613
+ deferred,
614
+ scope,
615
+ error,
616
+ instance,
617
+ requestContext
618
+ );
619
+ }).catch(async (error) => {
620
+ await this.handleInstantiationError(
621
+ instanceName,
622
+ holder,
623
+ deferred,
624
+ scope,
625
+ error
626
+ );
627
+ });
628
+ this.storeInstanceByScope(scope, instanceName, holder, requestContext);
629
+ return [void 0, holder];
630
+ }
631
+ /**
632
+ * Handles the result of service instantiation.
633
+ */
634
+ async handleInstantiationResult(instanceName, holder, ctx, deferred, scope, error, instance, _requestContext) {
635
+ holder.destroyListeners = ctx.getDestroyListeners();
636
+ holder.creationPromise = null;
637
+ if (error) {
638
+ await this.handleInstantiationError(
639
+ instanceName,
640
+ holder,
641
+ deferred,
642
+ scope,
643
+ error
644
+ );
645
+ } else {
646
+ await this.handleInstantiationSuccess(
647
+ instanceName,
648
+ holder,
649
+ ctx,
650
+ deferred,
651
+ instance
652
+ );
653
+ }
654
+ }
655
+ /**
656
+ * Handles successful service instantiation.
657
+ */
658
+ async handleInstantiationSuccess(instanceName, holder, ctx, deferred, instance) {
659
+ holder.instance = instance;
660
+ holder.status = "created" /* Created */;
661
+ if (ctx.deps.size > 0) {
662
+ ctx.deps.forEach((dependency) => {
663
+ holder.destroyListeners.push(
664
+ this.serviceLocator.getEventBus().on(dependency, "destroy", () => {
665
+ this.logger?.log(
666
+ `[InstanceResolver] Dependency ${dependency} destroyed, invalidating ${instanceName}`
667
+ );
668
+ this.serviceLocator.getServiceInvalidator().invalidate(instanceName);
669
+ })
670
+ );
671
+ });
672
+ }
673
+ this.logger?.log(
674
+ `[InstanceResolver] Instance ${instanceName} created successfully`
675
+ );
676
+ deferred.resolve([void 0, instance]);
677
+ }
678
+ /**
679
+ * Handles service instantiation errors.
680
+ */
681
+ async handleInstantiationError(instanceName, holder, deferred, scope, error) {
682
+ this.logger?.error(
683
+ `[InstanceResolver] Error creating instance for ${instanceName}`,
684
+ error
685
+ );
686
+ holder.status = "error" /* Error */;
687
+ holder.instance = error;
688
+ holder.creationPromise = null;
689
+ if (scope === "Singleton" /* Singleton */) {
690
+ this.logger?.log(
691
+ `[InstanceResolver] Singleton ${instanceName} failed, will be invalidated`
692
+ );
693
+ this.serviceLocator.getServiceInvalidator().invalidate(instanceName);
694
+ }
695
+ deferred.reject(error);
696
+ }
697
+ /**
698
+ * Stores an instance holder based on its scope.
699
+ */
700
+ storeInstanceByScope(scope, instanceName, holder, requestContext) {
701
+ switch (scope) {
702
+ case "Singleton" /* Singleton */:
703
+ this.logger?.debug(
704
+ `[InstanceResolver] Setting singleton instance for ${instanceName}`
705
+ );
706
+ this.manager.set(instanceName, holder);
707
+ break;
708
+ case "Request" /* Request */:
709
+ if (requestContext) {
710
+ this.logger?.debug(
711
+ `[InstanceResolver] Setting request-scoped instance for ${instanceName}`
712
+ );
713
+ requestContext.addInstance(instanceName, holder.instance, holder);
714
+ }
715
+ break;
716
+ }
717
+ }
718
+ /**
719
+ * Creates a factory context for dependency injection during service instantiation.
720
+ */
721
+ createFactoryContext() {
722
+ return this.tokenProcessor.createFactoryContext(this.serviceLocator);
723
+ }
724
+ };
725
+
726
+ // src/base-instance-holder-manager.mts
727
+ var BaseInstanceHolderManager = class {
728
+ constructor(logger = null) {
729
+ this.logger = logger;
730
+ this._holders = /* @__PURE__ */ new Map();
731
+ }
732
+ _holders;
733
+ /**
734
+ * Protected getter for accessing the holders map from subclasses.
735
+ */
736
+ get holders() {
737
+ return this._holders;
738
+ }
739
+ /**
740
+ * Deletes a holder by name.
741
+ * @param name The name of the holder to delete
742
+ * @returns true if the holder was deleted, false if it didn't exist
743
+ */
744
+ delete(name) {
745
+ return this._holders.delete(name);
746
+ }
747
+ /**
748
+ * Filters holders based on a predicate function.
749
+ * @param predicate Function to test each holder
750
+ * @returns A new Map containing only the holders that match the predicate
751
+ */
752
+ filter(predicate) {
753
+ return new Map(
754
+ [...this._holders].filter(([key, value]) => predicate(value, key))
755
+ );
756
+ }
757
+ /**
758
+ * Clears all holders from this manager.
759
+ */
760
+ clear() {
761
+ this._holders.clear();
762
+ }
763
+ /**
764
+ * Gets the number of holders currently managed.
765
+ */
766
+ size() {
767
+ return this._holders.size;
768
+ }
769
+ /**
770
+ * Creates a new holder with Creating status and a deferred creation promise.
771
+ * This is useful for creating placeholder holders that can be fulfilled later.
772
+ * @param name The name of the instance
773
+ * @param type The injectable type
774
+ * @param scope The injectable scope
775
+ * @param deps Optional set of dependencies
776
+ * @returns A tuple containing the deferred promise and the holder
777
+ */
778
+ createCreatingHolder(name, type, scope, deps = /* @__PURE__ */ new Set()) {
779
+ const deferred = Promise.withResolvers();
780
+ const holder = {
781
+ status: "creating" /* Creating */,
782
+ name,
783
+ instance: null,
784
+ creationPromise: deferred.promise,
785
+ destroyPromise: null,
786
+ type,
787
+ scope,
788
+ deps,
789
+ destroyListeners: [],
790
+ createdAt: Date.now()
791
+ };
792
+ return [deferred, holder];
793
+ }
794
+ /**
795
+ * Creates a new holder with Created status and an actual instance.
796
+ * This is useful for creating holders that already have their instance ready.
797
+ * @param name The name of the instance
798
+ * @param instance The actual instance to store
799
+ * @param type The injectable type
800
+ * @param scope The injectable scope
801
+ * @param deps Optional set of dependencies
802
+ * @returns The created holder
803
+ */
804
+ createCreatedHolder(name, instance, type, scope, deps = /* @__PURE__ */ new Set()) {
805
+ const holder = {
806
+ status: "created" /* Created */,
807
+ name,
808
+ instance,
809
+ creationPromise: null,
810
+ destroyPromise: null,
811
+ type,
812
+ scope,
813
+ deps,
814
+ destroyListeners: [],
815
+ createdAt: Date.now()
816
+ };
817
+ return holder;
818
+ }
819
+ /**
820
+ * Gets all holder names currently managed.
821
+ */
822
+ getAllNames() {
823
+ return Array.from(this._holders.keys());
824
+ }
825
+ /**
826
+ * Gets all holders currently managed.
827
+ */
828
+ getAllHolders() {
829
+ return Array.from(this._holders.values());
830
+ }
831
+ /**
832
+ * Checks if this manager has any holders.
833
+ */
834
+ isEmpty() {
835
+ return this._holders.size === 0;
836
+ }
837
+ };
838
+
839
+ // src/request-context-holder.mts
840
+ var DefaultRequestContextHolder = class extends BaseInstanceHolderManager {
841
+ constructor(requestId, priority = 100, initialMetadata) {
842
+ super(null);
843
+ this.requestId = requestId;
844
+ this.priority = priority;
845
+ if (initialMetadata) {
846
+ Object.entries(initialMetadata).forEach(([key, value]) => {
847
+ this.metadata.set(key, value);
848
+ });
849
+ }
850
+ }
851
+ metadata = /* @__PURE__ */ new Map();
852
+ createdAt = Date.now();
853
+ /**
854
+ * Public getter for holders to maintain interface compatibility.
855
+ */
856
+ get holders() {
857
+ return this._holders;
858
+ }
859
+ /**
860
+ * Gets a holder by name. For RequestContextHolder, this is a simple lookup.
861
+ */
862
+ get(name) {
863
+ return this._holders.get(name);
864
+ }
865
+ /**
866
+ * Sets a holder by name.
867
+ */
868
+ set(name, holder) {
869
+ this._holders.set(name, holder);
870
+ }
871
+ /**
872
+ * Checks if a holder exists by name.
873
+ */
874
+ has(name) {
875
+ return this._holders.has(name);
876
+ }
877
+ addInstance(instanceName, instance, holder) {
878
+ if (instanceName instanceof InjectionToken) {
879
+ const name = instanceName.toString();
880
+ const createdHolder = this.createCreatedHolder(
881
+ name,
882
+ instance,
883
+ "Class" /* Class */,
884
+ "Singleton" /* Singleton */,
885
+ /* @__PURE__ */ new Set()
886
+ );
887
+ this._holders.set(name, createdHolder);
888
+ } else {
889
+ if (!holder) {
890
+ throw new Error("Holder is required when adding an instance by name");
891
+ }
892
+ this._holders.set(instanceName, holder);
893
+ }
894
+ }
895
+ clear() {
896
+ super.clear();
897
+ this.metadata.clear();
898
+ }
899
+ getMetadata(key) {
900
+ return this.metadata.get(key);
901
+ }
902
+ setMetadata(key, value) {
903
+ this.metadata.set(key, value);
904
+ }
905
+ };
906
+
907
+ // src/request-context-manager.mts
908
+ var RequestContextManager = class {
909
+ constructor(logger = null) {
910
+ this.logger = logger;
911
+ }
912
+ requestContexts = /* @__PURE__ */ new Map();
913
+ currentRequestContext = null;
914
+ /**
915
+ * Begins a new request context with the given parameters.
916
+ * @param requestId Unique identifier for this request
917
+ * @param metadata Optional metadata for the request
918
+ * @param priority Priority for resolution (higher = more priority)
919
+ * @returns The created request context holder
920
+ */
921
+ beginRequest(requestId, metadata, priority = 100) {
922
+ if (this.requestContexts.has(requestId)) {
923
+ throw new Error(
924
+ `[RequestContextManager] Request context ${requestId} already exists`
925
+ );
926
+ }
927
+ const contextHolder = new DefaultRequestContextHolder(
928
+ requestId,
929
+ priority,
930
+ metadata
931
+ );
932
+ this.requestContexts.set(requestId, contextHolder);
933
+ this.currentRequestContext = contextHolder;
934
+ this.logger?.log(
935
+ `[RequestContextManager] Started request context: ${requestId}`
936
+ );
937
+ return contextHolder;
938
+ }
939
+ /**
940
+ * Ends a request context and cleans up all associated instances.
941
+ * @param requestId The request ID to end
942
+ */
943
+ async endRequest(requestId) {
944
+ const contextHolder = this.requestContexts.get(requestId);
945
+ if (!contextHolder) {
946
+ this.logger?.warn(
947
+ `[RequestContextManager] Request context ${requestId} not found`
948
+ );
949
+ return;
950
+ }
951
+ this.logger?.log(
952
+ `[RequestContextManager] Ending request context: ${requestId}`
953
+ );
954
+ const cleanupPromises = [];
955
+ for (const [, holder] of contextHolder.holders) {
956
+ if (holder.destroyListeners.length > 0) {
957
+ cleanupPromises.push(
958
+ Promise.all(holder.destroyListeners.map((listener) => listener()))
959
+ );
960
+ }
961
+ }
962
+ await Promise.all(cleanupPromises);
963
+ contextHolder.clear();
964
+ this.requestContexts.delete(requestId);
965
+ if (this.currentRequestContext === contextHolder) {
966
+ this.currentRequestContext = Array.from(this.requestContexts.values()).at(-1) ?? null;
967
+ }
968
+ this.logger?.log(
969
+ `[RequestContextManager] Request context ${requestId} ended`
970
+ );
971
+ }
972
+ /**
973
+ * Gets the current request context.
974
+ * @returns The current request context holder or null
975
+ */
976
+ getCurrentRequestContext() {
977
+ return this.currentRequestContext;
978
+ }
979
+ /**
980
+ * Sets the current request context.
981
+ * @param requestId The request ID to set as current
982
+ */
983
+ setCurrentRequestContext(requestId) {
984
+ const contextHolder = this.requestContexts.get(requestId);
985
+ if (!contextHolder) {
986
+ throw new Error(
987
+ `[RequestContextManager] Request context ${requestId} not found`
988
+ );
989
+ }
990
+ this.currentRequestContext = contextHolder;
991
+ }
992
+ /**
993
+ * Gets all request contexts.
994
+ * @returns Map of request contexts
995
+ */
996
+ getRequestContexts() {
997
+ return this.requestContexts;
998
+ }
999
+ /**
1000
+ * Clears all request contexts.
1001
+ */
1002
+ async clearAllRequestContexts() {
1003
+ const requestIds = Array.from(this.requestContexts.keys());
1004
+ if (requestIds.length === 0) {
1005
+ this.logger?.log("[RequestContextManager] No request contexts to clear");
1006
+ return;
1007
+ }
1008
+ this.logger?.log(
1009
+ `[RequestContextManager] Clearing ${requestIds.length} request contexts: ${requestIds.join(", ")}`
1010
+ );
1011
+ for (const requestId of requestIds) {
1012
+ try {
1013
+ await this.endRequest(requestId);
1014
+ } catch (error) {
1015
+ this.logger?.error(
1016
+ `[RequestContextManager] Error clearing request context ${requestId}:`,
1017
+ error
1018
+ );
1019
+ }
1020
+ }
1021
+ }
1022
+ };
1023
+
1024
+ // src/service-instantiator.mts
1025
+ var ServiceInstantiator = class {
1026
+ constructor(injectors) {
1027
+ this.injectors = injectors;
1028
+ }
1029
+ /**
1030
+ * Instantiates a service based on its registry record.
1031
+ * @param ctx The factory context for dependency injection
1032
+ * @param record The factory record from the registry
1033
+ * @param args Optional arguments for the service
1034
+ * @returns Promise resolving to [undefined, instance] or [error]
1035
+ */
1036
+ async instantiateService(ctx, record, args = void 0) {
1037
+ try {
1038
+ switch (record.type) {
1039
+ case "Class" /* Class */:
1040
+ return this.instantiateClass(ctx, record, args);
1041
+ case "Factory" /* Factory */:
1042
+ return this.instantiateFactory(ctx, record, args);
1043
+ default:
1044
+ throw new Error(
1045
+ `[ServiceInstantiator] Unknown service type: ${record.type}`
1046
+ );
1047
+ }
1048
+ } catch (error) {
1049
+ return [error instanceof Error ? error : new Error(String(error))];
1050
+ }
1051
+ }
1052
+ /**
1053
+ * Instantiates a class-based service (Injectable decorator).
1054
+ * @param ctx The factory context for dependency injection
1055
+ * @param record The factory record from the registry
1056
+ * @param args Optional arguments for the service constructor
1057
+ * @returns Promise resolving to [undefined, instance] or [error]
1058
+ */
1059
+ async instantiateClass(ctx, record, args) {
1060
+ try {
1061
+ const tryLoad = this.injectors.wrapSyncInit(() => {
1062
+ const original = this.injectors.provideFactoryContext(ctx);
1063
+ let result = new record.target(...args ? [args] : []);
1064
+ this.injectors.provideFactoryContext(original);
1065
+ return result;
1066
+ });
1067
+ let [instance, promises, injectState] = tryLoad();
1068
+ if (promises.length > 0) {
1069
+ const results = await Promise.allSettled(promises);
1070
+ if (results.some((result) => result.status === "rejected")) {
1071
+ throw new Error(
1072
+ `[ServiceInstantiator] Service ${record.target.name} cannot be instantiated.`
1073
+ );
1074
+ }
1075
+ const newRes = tryLoad(injectState);
1076
+ instance = newRes[0];
1077
+ promises = newRes[1];
1078
+ }
1079
+ if (promises.length > 0) {
1080
+ console.error(`[ServiceInstantiator] ${record.target.name} has problem with it's definition.
1081
+
1082
+ One or more of the dependencies are registered as a InjectableScope.Instance and are used with inject.
1083
+
1084
+ Please use inject asyncInject of inject to load those dependencies.`);
1085
+ throw new Error(
1086
+ `[ServiceInstantiator] Service ${record.target.name} cannot be instantiated.`
1087
+ );
1088
+ }
1089
+ if ("onServiceInit" in instance) {
1090
+ await instance.onServiceInit();
1091
+ }
1092
+ if ("onServiceDestroy" in instance) {
1093
+ ctx.addDestroyListener(async () => {
1094
+ await instance.onServiceDestroy();
1095
+ });
1096
+ }
1097
+ return [void 0, instance];
1098
+ } catch (error) {
1099
+ return [error instanceof Error ? error : new Error(String(error))];
1100
+ }
1101
+ }
1102
+ /**
1103
+ * Instantiates a factory-based service (Factory decorator).
1104
+ * @param ctx The factory context for dependency injection
1105
+ * @param record The factory record from the registry
1106
+ * @param args Optional arguments for the factory
1107
+ * @returns Promise resolving to [undefined, instance] or [error]
1108
+ */
1109
+ async instantiateFactory(ctx, record, args) {
1110
+ try {
1111
+ const tryLoad = this.injectors.wrapSyncInit(() => {
1112
+ const original = this.injectors.provideFactoryContext(ctx);
1113
+ let result = new record.target();
1114
+ this.injectors.provideFactoryContext(original);
1115
+ return result;
1116
+ });
1117
+ let [builder, promises, injectState] = tryLoad();
1118
+ if (promises.length > 0) {
1119
+ const results = await Promise.allSettled(promises);
1120
+ if (results.some((result) => result.status === "rejected")) {
1121
+ throw new Error(
1122
+ `[ServiceInstantiator] Service ${record.target.name} cannot be instantiated.`
1123
+ );
1124
+ }
1125
+ const newRes = tryLoad(injectState);
1126
+ builder = newRes[0];
1127
+ promises = newRes[1];
1128
+ }
1129
+ if (promises.length > 0) {
1130
+ console.error(`[ServiceInstantiator] ${record.target.name} has problem with it's definition.
1131
+
1132
+ One or more of the dependencies are registered as a InjectableScope.Instance and are used with inject.
1133
+
1134
+ Please use asyncInject instead of inject to load those dependencies.`);
1135
+ throw new Error(
1136
+ `[ServiceInstantiator] Service ${record.target.name} cannot be instantiated.`
1137
+ );
1138
+ }
1139
+ if (typeof builder.create !== "function") {
1140
+ throw new Error(
1141
+ `[ServiceInstantiator] Factory ${record.target.name} does not implement the create method.`
1142
+ );
1143
+ }
1144
+ const instance = await builder.create(ctx, args);
1145
+ return [void 0, instance];
1146
+ } catch (error) {
1147
+ return [error instanceof Error ? error : new Error(String(error))];
1148
+ }
1149
+ }
1150
+ };
1151
+
1152
+ // src/service-invalidator.mts
1153
+ var ServiceInvalidator = class {
1154
+ constructor(manager, requestContextManager, eventBus, logger = null) {
1155
+ this.manager = manager;
1156
+ this.requestContextManager = requestContextManager;
1157
+ this.eventBus = eventBus;
1158
+ this.logger = logger;
1159
+ }
1160
+ /**
1161
+ * Invalidates a service and all its dependencies.
1162
+ */
1163
+ invalidate(service, round = 1) {
1164
+ this.logger?.log(
1165
+ `[ServiceInvalidator] Starting invalidation process for ${service}`
1166
+ );
1167
+ const [, toInvalidate] = this.manager.get(service);
1168
+ const promises = [];
1169
+ if (toInvalidate) {
1170
+ promises.push(this.invalidateHolder(service, toInvalidate, round));
1171
+ }
1172
+ const requestContexts = this.requestContextManager.getRequestContexts();
1173
+ for (const [requestId, requestContext] of requestContexts.entries()) {
1174
+ const holder = requestContext.get(service);
1175
+ if (holder) {
1176
+ this.logger?.log(
1177
+ `[ServiceInvalidator] Invalidating request-scoped instance ${service} in request ${requestId}`
1178
+ );
1179
+ promises.push(
1180
+ this.invalidateRequestHolder(requestId, service, holder, round)
1181
+ );
1182
+ }
1183
+ }
1184
+ return Promise.all(promises);
1185
+ }
1186
+ /**
1187
+ * Gracefully clears all services in the ServiceLocator using invalidation logic.
1188
+ * This method respects service dependencies and ensures proper cleanup order.
1189
+ * Services that depend on others will be invalidated first, then their dependencies.
1190
+ */
1191
+ async clearAll(options = {}) {
1192
+ const {
1193
+ clearRequestContexts = true,
1194
+ maxRounds = 10,
1195
+ waitForSettlement = true
1196
+ } = options;
1197
+ this.logger?.log(
1198
+ "[ServiceInvalidator] Starting graceful clearing of all services"
1199
+ );
1200
+ if (waitForSettlement) {
1201
+ this.logger?.log(
1202
+ "[ServiceInvalidator] Waiting for all services to settle..."
1203
+ );
1204
+ await this.ready();
1205
+ }
1206
+ const allServiceNames = this.getAllServiceNames();
1207
+ if (allServiceNames.length === 0) {
1208
+ this.logger?.log("[ServiceInvalidator] No singleton services to clear");
1209
+ } else {
1210
+ this.logger?.log(
1211
+ `[ServiceInvalidator] Found ${allServiceNames.length} services to clear: ${allServiceNames.join(", ")}`
1212
+ );
1213
+ await this.clearServicesWithDependencyAwareness(
1214
+ allServiceNames,
1215
+ maxRounds
1216
+ );
1217
+ }
1218
+ if (clearRequestContexts) {
1219
+ await this.requestContextManager.clearAllRequestContexts();
1220
+ }
1221
+ this.logger?.log("[ServiceInvalidator] Graceful clearing completed");
1222
+ }
1223
+ /**
1224
+ * Waits for all services to settle (either created, destroyed, or error state).
1225
+ */
1226
+ async ready() {
1227
+ const holders = Array.from(this.manager.filter(() => true)).map(
1228
+ ([, holder]) => holder
1229
+ );
1230
+ await Promise.all(
1231
+ holders.map((holder) => this.waitForHolderToSettle(holder))
1232
+ );
1233
+ }
1234
+ /**
1235
+ * Invalidates a single holder based on its current status.
1236
+ */
1237
+ async invalidateHolder(key, holder, round) {
1238
+ await this.invalidateHolderByStatus(holder, round, {
1239
+ context: key,
1240
+ isRequestScoped: false,
1241
+ onCreationError: () => this.logger?.error(
1242
+ `[ServiceInvalidator] ${key} creation triggered too many invalidation rounds`
1243
+ ),
1244
+ onRecursiveInvalidate: () => this.invalidate(key, round + 1),
1245
+ onDestroy: () => this.destroyHolder(key, holder)
1246
+ });
1247
+ }
1248
+ /**
1249
+ * Invalidates a request-scoped holder based on its current status.
1250
+ */
1251
+ async invalidateRequestHolder(requestId, instanceName, holder, round) {
1252
+ await this.invalidateHolderByStatus(holder, round, {
1253
+ context: `Request-scoped ${instanceName} in ${requestId}`,
1254
+ isRequestScoped: true,
1255
+ onCreationError: () => this.logger?.error(
1256
+ `[ServiceInvalidator] Request-scoped ${instanceName} in ${requestId} creation triggered too many invalidation rounds`
1257
+ ),
1258
+ onRecursiveInvalidate: () => this.invalidateRequestHolder(
1259
+ requestId,
1260
+ instanceName,
1261
+ holder,
1262
+ round + 1
1263
+ ),
1264
+ onDestroy: () => this.destroyRequestHolder(requestId, instanceName, holder)
1265
+ });
1266
+ }
1267
+ /**
1268
+ * Common invalidation logic for holders based on their status.
1269
+ */
1270
+ async invalidateHolderByStatus(holder, round, options) {
1271
+ switch (holder.status) {
1272
+ case "destroying" /* Destroying */:
1273
+ await holder.destroyPromise;
1274
+ break;
1275
+ case "creating" /* Creating */:
1276
+ await holder.creationPromise;
1277
+ if (round > 3) {
1278
+ options.onCreationError();
1279
+ return;
1280
+ }
1281
+ await options.onRecursiveInvalidate();
1282
+ break;
1283
+ default:
1284
+ await options.onDestroy();
1285
+ break;
1286
+ }
1287
+ }
1288
+ /**
1289
+ * Destroys a holder and cleans up its resources.
1290
+ */
1291
+ async destroyHolder(key, holder) {
1292
+ await this.destroyHolderWithCleanup(holder, {
1293
+ context: key,
1294
+ logMessage: `[ServiceInvalidator] Invalidating ${key} and notifying listeners`,
1295
+ cleanup: () => this.manager.delete(key),
1296
+ eventName: key
1297
+ });
1298
+ }
1299
+ /**
1300
+ * Destroys a request-scoped holder and cleans up its resources.
1301
+ */
1302
+ async destroyRequestHolder(requestId, instanceName, holder) {
1303
+ await this.destroyHolderWithCleanup(holder, {
1304
+ context: `Request-scoped ${instanceName} in ${requestId}`,
1305
+ logMessage: `[ServiceInvalidator] Invalidating request-scoped ${instanceName} in ${requestId} and notifying listeners`,
1306
+ cleanup: () => {
1307
+ const requestContext = this.requestContextManager.getRequestContexts().get(requestId);
1308
+ if (requestContext) {
1309
+ requestContext.delete(instanceName);
1310
+ }
1311
+ },
1312
+ eventName: instanceName
1313
+ });
1314
+ }
1315
+ /**
1316
+ * Common destroy logic for holders with customizable cleanup.
1317
+ */
1318
+ async destroyHolderWithCleanup(holder, options) {
1319
+ holder.status = "destroying" /* Destroying */;
1320
+ this.logger?.log(options.logMessage);
1321
+ holder.destroyPromise = Promise.all(
1322
+ holder.destroyListeners.map((listener) => listener())
1323
+ ).then(async () => {
1324
+ holder.destroyListeners = [];
1325
+ holder.deps.clear();
1326
+ options.cleanup();
1327
+ await this.emitInstanceEvent(options.eventName, "destroy");
1328
+ });
1329
+ await holder.destroyPromise;
1330
+ }
1331
+ /**
1332
+ * Waits for a holder to settle (either created, destroyed, or error state).
1333
+ */
1334
+ async waitForHolderToSettle(holder) {
1335
+ switch (holder.status) {
1336
+ case "creating" /* Creating */:
1337
+ await holder.creationPromise;
1338
+ break;
1339
+ case "destroying" /* Destroying */:
1340
+ await holder.destroyPromise;
1341
+ break;
1342
+ }
1343
+ }
1344
+ /**
1345
+ * Clears services with dependency awareness, ensuring proper cleanup order.
1346
+ * Services with no dependencies are cleared first, then services that depend on them.
1347
+ */
1348
+ async clearServicesWithDependencyAwareness(serviceNames, maxRounds) {
1349
+ const clearedServices = /* @__PURE__ */ new Set();
1350
+ let round = 1;
1351
+ while (clearedServices.size < serviceNames.length && round <= maxRounds) {
1352
+ this.logger?.log(
1353
+ `[ServiceInvalidator] Clearing round ${round}/${maxRounds}, ${clearedServices.size}/${serviceNames.length} services cleared`
1354
+ );
1355
+ const servicesToClearThisRound = this.findServicesReadyForClearing(
1356
+ serviceNames,
1357
+ clearedServices
1358
+ );
1359
+ if (servicesToClearThisRound.length === 0) {
1360
+ const remainingServices = serviceNames.filter(
1361
+ (name) => !clearedServices.has(name)
1362
+ );
1363
+ if (remainingServices.length > 0) {
1364
+ this.logger?.warn(
1365
+ `[ServiceInvalidator] No services ready for clearing, forcing cleanup of remaining: ${remainingServices.join(", ")}`
1366
+ );
1367
+ await this.forceClearServices(remainingServices);
1368
+ remainingServices.forEach((name) => clearedServices.add(name));
1369
+ }
1370
+ break;
1371
+ }
1372
+ const clearPromises = servicesToClearThisRound.map(
1373
+ async (serviceName) => {
1374
+ try {
1375
+ await this.invalidate(serviceName, round);
1376
+ clearedServices.add(serviceName);
1377
+ this.logger?.log(
1378
+ `[ServiceInvalidator] Successfully cleared service: ${serviceName}`
1379
+ );
1380
+ } catch (error) {
1381
+ this.logger?.error(
1382
+ `[ServiceInvalidator] Error clearing service ${serviceName}:`,
1383
+ error
1384
+ );
1385
+ clearedServices.add(serviceName);
1386
+ }
1387
+ }
1388
+ );
1389
+ await Promise.all(clearPromises);
1390
+ round++;
1391
+ }
1392
+ if (clearedServices.size < serviceNames.length) {
1393
+ this.logger?.warn(
1394
+ `[ServiceInvalidator] Clearing completed after ${maxRounds} rounds, but ${serviceNames.length - clearedServices.size} services may not have been properly cleared`
1395
+ );
1396
+ }
1397
+ }
1398
+ /**
1399
+ * Finds services that are ready to be cleared in the current round.
1400
+ * A service is ready if all its dependencies have already been cleared.
1401
+ */
1402
+ findServicesReadyForClearing(allServiceNames, clearedServices) {
1403
+ return allServiceNames.filter((serviceName) => {
1404
+ if (clearedServices.has(serviceName)) {
1405
+ return false;
1406
+ }
1407
+ const [error, holder] = this.manager.get(serviceName);
1408
+ if (error) {
1409
+ return true;
1410
+ }
1411
+ const hasUnclearedDependencies = Array.from(holder.deps).some(
1412
+ (dep) => !clearedServices.has(dep)
1413
+ );
1414
+ return !hasUnclearedDependencies;
1415
+ });
1416
+ }
1417
+ /**
1418
+ * Force clears services that couldn't be cleared through normal dependency resolution.
1419
+ * This handles edge cases like circular dependencies.
1420
+ */
1421
+ async forceClearServices(serviceNames) {
1422
+ const promises = serviceNames.map(async (serviceName) => {
1423
+ try {
1424
+ const [error, holder] = this.manager.get(serviceName);
1425
+ if (!error && holder) {
1426
+ await this.destroyHolder(serviceName, holder);
1427
+ }
1428
+ } catch (error) {
1429
+ this.logger?.error(
1430
+ `[ServiceInvalidator] Error force clearing service ${serviceName}:`,
1431
+ error
1432
+ );
1433
+ }
1434
+ });
1435
+ await Promise.all(promises);
1436
+ }
1437
+ /**
1438
+ * Gets all service names currently managed by the ServiceLocator.
1439
+ */
1440
+ getAllServiceNames() {
1441
+ return this.manager.getAllNames();
1442
+ }
1443
+ /**
1444
+ * Emits events to listeners for instance lifecycle events.
1445
+ */
1446
+ emitInstanceEvent(name, event = "create") {
1447
+ this.logger?.log(
1448
+ `[ServiceInvalidator]#emitInstanceEvent() Notifying listeners for ${name} with event ${event}`
1449
+ );
1450
+ return this.eventBus.emit(name, event);
1451
+ }
1452
+ };
1453
+
1454
+ // src/service-locator-event-bus.mts
1455
+ var ServiceLocatorEventBus = class {
1456
+ constructor(logger = null) {
1457
+ this.logger = logger;
1458
+ }
1459
+ listeners = /* @__PURE__ */ new Map();
1460
+ on(ns, event, listener) {
1461
+ this.logger?.debug(`[ServiceLocatorEventBus]#on(): ns:${ns} event:${event}`);
1462
+ if (!this.listeners.has(ns)) {
1463
+ this.listeners.set(ns, /* @__PURE__ */ new Map());
1464
+ }
1465
+ const nsEvents = this.listeners.get(ns);
1466
+ if (!nsEvents.has(event)) {
1467
+ nsEvents.set(event, /* @__PURE__ */ new Set());
1468
+ }
1469
+ nsEvents.get(event).add(listener);
1470
+ return () => {
1471
+ nsEvents.get(event).delete(listener);
1472
+ if (nsEvents.get(event)?.size === 0) {
1473
+ nsEvents.delete(event);
1474
+ }
1475
+ if (nsEvents.size === 0) {
1476
+ this.listeners.delete(ns);
1477
+ }
1478
+ };
1479
+ }
1480
+ async emit(key, event) {
1481
+ if (!this.listeners.has(key)) {
1482
+ return;
1483
+ }
1484
+ const events = this.listeners.get(key);
1485
+ this.logger?.debug(`[ServiceLocatorEventBus]#emit(): ${key}:${event}`);
1486
+ const res = await Promise.allSettled(
1487
+ [...events.get(event) ?? []].map((listener) => listener(event))
1488
+ ).then((results) => {
1489
+ const res2 = results.filter((result) => result.status === "rejected").map((result) => {
1490
+ this.logger?.warn(
1491
+ `[ServiceLocatorEventBus]#emit(): ${key}:${event} rejected with`,
1492
+ result.reason
1493
+ );
1494
+ return result;
1495
+ });
1496
+ if (res2.length > 0) {
1497
+ return Promise.reject(res2);
1498
+ }
1499
+ return results;
1500
+ });
1501
+ return res;
1502
+ }
1503
+ };
1504
+
1505
+ // src/service-locator-manager.mts
1506
+ var ServiceLocatorManager = class extends BaseInstanceHolderManager {
1507
+ constructor(logger = null) {
1508
+ super(logger);
1509
+ }
1510
+ get(name) {
1511
+ const holder = this._holders.get(name);
1512
+ if (holder) {
1513
+ if (holder.status === "destroying" /* Destroying */) {
1514
+ this.logger?.log(
1515
+ `[ServiceLocatorManager]#getInstanceHolder() Instance ${holder.name} is destroying`
1516
+ );
1517
+ return [DIError.instanceDestroying(holder.name), holder];
1518
+ } else if (holder.status === "error" /* Error */) {
1519
+ this.logger?.log(
1520
+ `[ServiceLocatorManager]#getInstanceHolder() Instance ${holder.name} is in error state`
1521
+ );
1522
+ return [holder.instance, holder];
1523
+ }
1524
+ return [void 0, holder];
1525
+ } else {
1526
+ this.logger?.log(
1527
+ `[ServiceLocatorManager]#getInstanceHolder() Instance ${name} not found`
1528
+ );
1529
+ return [DIError.instanceNotFound(name)];
1530
+ }
1531
+ }
1532
+ set(name, holder) {
1533
+ this._holders.set(name, holder);
1534
+ }
1535
+ has(name) {
1536
+ const [error, holder] = this.get(name);
1537
+ if (!error) {
1538
+ return [void 0, true];
1539
+ }
1540
+ if (error.code === "InstanceDestroying" /* InstanceDestroying */) {
1541
+ return [error];
1542
+ }
1543
+ return [void 0, !!holder];
1544
+ }
1545
+ // delete and filter methods are inherited from BaseInstanceHolderManager
1546
+ // createCreatingHolder method is inherited from BaseInstanceHolderManager
1547
+ /**
1548
+ * Creates a new holder with Created status and an actual instance.
1549
+ * This is useful for creating holders that already have their instance ready.
1550
+ * @param name The name of the instance
1551
+ * @param instance The actual instance to store
1552
+ * @param type The injectable type
1553
+ * @param scope The injectable scope
1554
+ * @param deps Optional set of dependencies
1555
+ * @returns The created holder
1556
+ */
1557
+ storeCreatedHolder(name, instance, type, scope, deps = /* @__PURE__ */ new Set()) {
1558
+ const holder = this.createCreatedHolder(name, instance, type, scope, deps);
1559
+ this._holders.set(name, holder);
1560
+ return holder;
1561
+ }
1562
+ };
1563
+
1564
+ // src/token-processor.mts
1565
+ var TokenProcessor = class {
1566
+ constructor(logger = null) {
1567
+ this.logger = logger;
1568
+ }
1569
+ /**
1570
+ * Validates and resolves token arguments, handling factory token resolution and validation.
1571
+ */
1572
+ validateAndResolveTokenArgs(token, args) {
1573
+ let actualToken = token;
1574
+ if (typeof token === "function") {
1575
+ actualToken = getInjectableToken(token);
1576
+ }
1577
+ let realArgs = args;
1578
+ if (actualToken instanceof BoundInjectionToken) {
1579
+ realArgs = actualToken.value;
1580
+ } else if (actualToken instanceof FactoryInjectionToken) {
1581
+ if (actualToken.resolved) {
1582
+ realArgs = actualToken.value;
1583
+ } else {
1584
+ return [DIError.factoryTokenNotResolved(token.name), { actualToken }];
1585
+ }
1586
+ }
1587
+ if (!actualToken.schema) {
1588
+ return [void 0, { actualToken, validatedArgs: realArgs }];
1589
+ }
1590
+ const validatedArgs = actualToken.schema?.safeParse(realArgs);
1591
+ if (validatedArgs && !validatedArgs.success) {
1592
+ this.logger?.error(
1593
+ `[TokenProcessor]#validateAndResolveTokenArgs(): Error validating args for ${actualToken.name.toString()}`,
1594
+ validatedArgs.error
1595
+ );
1596
+ return [DIError.unknown(validatedArgs.error), { actualToken }];
1597
+ }
1598
+ return [void 0, { actualToken, validatedArgs: validatedArgs?.data }];
1599
+ }
1600
+ /**
1601
+ * Generates a unique instance name based on token and arguments.
1602
+ */
1603
+ generateInstanceName(token, args) {
1604
+ if (!args) {
1605
+ return token.toString();
1606
+ }
1607
+ const formattedArgs = Object.entries(args).sort(([keyA], [keyB]) => keyA.localeCompare(keyB)).map(([key, value]) => `${key}=${this.formatArgValue(value)}`).join(",");
1608
+ return `${token.toString()}:${formattedArgs.replaceAll(/"/g, "").replaceAll(/:/g, "=")}`;
1609
+ }
1610
+ /**
1611
+ * Formats a single argument value for instance name generation.
1612
+ */
1613
+ formatArgValue(value) {
1614
+ if (typeof value === "function") {
1615
+ return `fn_${value.name}(${value.length})`;
1616
+ }
1617
+ if (typeof value === "symbol") {
1618
+ return value.toString();
1619
+ }
1620
+ return JSON.stringify(value).slice(0, 40);
1621
+ }
1622
+ /**
1623
+ * Creates a factory context for dependency injection during service instantiation.
1624
+ * @param serviceLocator Reference to the service locator for dependency resolution
1625
+ */
1626
+ createFactoryContext(serviceLocator) {
1627
+ const destroyListeners = /* @__PURE__ */ new Set();
1628
+ const deps = /* @__PURE__ */ new Set();
1629
+ function addDestroyListener(listener) {
1630
+ destroyListeners.add(listener);
1631
+ }
1632
+ function getDestroyListeners() {
1633
+ return Array.from(destroyListeners);
1634
+ }
1635
+ return {
1636
+ // @ts-expect-error This is correct type
1637
+ async inject(token, args) {
1638
+ const [error, instance] = await serviceLocator.getInstance(
1639
+ token,
1640
+ args,
1641
+ ({ instanceName }) => {
1642
+ deps.add(instanceName);
1643
+ }
1644
+ );
1645
+ if (error) {
1646
+ throw error;
1647
+ }
1648
+ return instance;
1649
+ },
1650
+ addDestroyListener,
1651
+ getDestroyListeners,
1652
+ locator: serviceLocator,
1653
+ deps
1654
+ };
1655
+ }
1656
+ /**
1657
+ * Tries to get a pre-prepared instance from request contexts.
1658
+ */
1659
+ tryGetPrePreparedInstance(instanceName, contextHolder, deps, currentRequestContext) {
1660
+ if (contextHolder && contextHolder.priority > 0) {
1661
+ const prePreparedInstance = contextHolder.get(instanceName)?.instance;
1662
+ if (prePreparedInstance !== void 0) {
1663
+ this.logger?.debug(
1664
+ `[TokenProcessor] Using pre-prepared instance ${instanceName} from request context ${contextHolder.requestId}`
1665
+ );
1666
+ deps.add(instanceName);
1667
+ return prePreparedInstance;
1668
+ }
1669
+ }
1670
+ if (currentRequestContext && currentRequestContext !== contextHolder) {
1671
+ const prePreparedInstance = currentRequestContext.get(instanceName)?.instance;
1672
+ if (prePreparedInstance !== void 0) {
1673
+ this.logger?.debug(
1674
+ `[TokenProcessor] Using pre-prepared instance ${instanceName} from current request context ${currentRequestContext.requestId}`
1675
+ );
1676
+ deps.add(instanceName);
1677
+ return prePreparedInstance;
1678
+ }
1679
+ }
1680
+ return void 0;
1681
+ }
1682
+ };
1683
+
1684
+ // src/service-locator.mts
1685
+ var ServiceLocator = class {
1686
+ constructor(registry = globalRegistry, logger = null, injectors = defaultInjectors) {
1687
+ this.registry = registry;
1688
+ this.logger = logger;
1689
+ this.injectors = injectors;
1690
+ this.eventBus = new ServiceLocatorEventBus(logger);
1691
+ this.manager = new ServiceLocatorManager(logger);
1692
+ this.serviceInstantiator = new ServiceInstantiator(injectors);
1693
+ this.tokenProcessor = new TokenProcessor(logger);
1694
+ this.requestContextManager = new RequestContextManager(logger);
1695
+ this.serviceInvalidator = new ServiceInvalidator(
1696
+ this.manager,
1697
+ this.requestContextManager,
1698
+ this.eventBus,
1699
+ logger
1700
+ );
1701
+ this.instanceResolver = new InstanceResolver(
1702
+ this.registry,
1703
+ this.manager,
1704
+ this.serviceInstantiator,
1705
+ this.tokenProcessor,
1706
+ logger,
1707
+ this
1708
+ );
1709
+ }
1710
+ eventBus;
1711
+ manager;
1712
+ serviceInstantiator;
1713
+ tokenProcessor;
1714
+ requestContextManager;
1715
+ serviceInvalidator;
1716
+ instanceResolver;
1717
+ // ============================================================================
1718
+ // PUBLIC METHODS
1719
+ // ============================================================================
1720
+ getEventBus() {
1721
+ return this.eventBus;
1722
+ }
1723
+ getManager() {
1724
+ return this.manager;
1725
+ }
1726
+ getRequestContexts() {
1727
+ return this.requestContextManager.getRequestContexts();
1728
+ }
1729
+ getRequestContextManager() {
1730
+ return this.requestContextManager;
1731
+ }
1732
+ getServiceInvalidator() {
1733
+ return this.serviceInvalidator;
1734
+ }
1735
+ getInstanceIdentifier(token, args) {
1736
+ const [err, { actualToken, validatedArgs }] = this.tokenProcessor.validateAndResolveTokenArgs(token, args);
1737
+ if (err) {
1738
+ throw err;
1739
+ }
1740
+ return this.tokenProcessor.generateInstanceName(actualToken, validatedArgs);
1741
+ }
1742
+ async getInstance(token, args, onPrepare) {
1743
+ const [err, data] = await this.instanceResolver.resolveInstance(
1744
+ token,
1745
+ args,
1746
+ this.requestContextManager.getCurrentRequestContext() || void 0
1747
+ );
1748
+ if (err) {
1749
+ return [err];
1750
+ }
1751
+ if (onPrepare) {
1752
+ const instanceName = this.getInstanceIdentifier(token, args);
1753
+ const [tokenErr, { actualToken, validatedArgs }] = this.tokenProcessor.validateAndResolveTokenArgs(token, args);
1754
+ if (!tokenErr) {
1755
+ onPrepare({ instanceName, actualToken, validatedArgs });
1756
+ }
1757
+ }
1758
+ return [void 0, data];
1759
+ }
1760
+ async getOrThrowInstance(token, args) {
1761
+ const [error, instance] = await this.getInstance(token, args);
1762
+ if (error) {
1763
+ throw error;
1764
+ }
1765
+ return instance;
1766
+ }
1767
+ getSyncInstance(token, args) {
1768
+ return this.instanceResolver.getSyncInstance(
1769
+ token,
1770
+ args,
1771
+ this.requestContextManager.getCurrentRequestContext()
1772
+ );
1773
+ }
1774
+ invalidate(service, round = 1) {
1775
+ return this.serviceInvalidator.invalidate(service, round);
1776
+ }
1777
+ /**
1778
+ * Gracefully clears all services in the ServiceLocator using invalidation logic.
1779
+ * This method respects service dependencies and ensures proper cleanup order.
1780
+ * Services that depend on others will be invalidated first, then their dependencies.
1781
+ *
1782
+ * @param options Optional configuration for the clearing process
1783
+ * @returns Promise that resolves when all services have been cleared
1784
+ */
1785
+ async clearAll(options = {}) {
1786
+ return this.serviceInvalidator.clearAll(options);
1787
+ }
1788
+ // ============================================================================
1789
+ // REQUEST CONTEXT MANAGEMENT
1790
+ // ============================================================================
1791
+ /**
1792
+ * Begins a new request context with the given parameters.
1793
+ * @param requestId Unique identifier for this request
1794
+ * @param metadata Optional metadata for the request
1795
+ * @param priority Priority for resolution (higher = more priority)
1796
+ * @returns The created request context holder
1797
+ */
1798
+ beginRequest(requestId, metadata, priority = 100) {
1799
+ return this.requestContextManager.beginRequest(
1800
+ requestId,
1801
+ metadata,
1802
+ priority
1803
+ );
1804
+ }
1805
+ /**
1806
+ * Ends a request context and cleans up all associated instances.
1807
+ * @param requestId The request ID to end
1808
+ */
1809
+ async endRequest(requestId) {
1810
+ return this.requestContextManager.endRequest(requestId);
1811
+ }
1812
+ /**
1813
+ * Gets the current request context.
1814
+ * @returns The current request context holder or null
1815
+ */
1816
+ getCurrentRequestContext() {
1817
+ return this.requestContextManager.getCurrentRequestContext();
1818
+ }
1819
+ /**
1820
+ * Sets the current request context.
1821
+ * @param requestId The request ID to set as current
1822
+ */
1823
+ setCurrentRequestContext(requestId) {
1824
+ return this.requestContextManager.setCurrentRequestContext(requestId);
1825
+ }
1826
+ /**
1827
+ * Waits for all services to settle (either created, destroyed, or error state).
1828
+ */
1829
+ async ready() {
1830
+ return this.serviceInvalidator.ready();
1831
+ }
1832
+ /**
1833
+ * Helper method for TokenProcessor to access pre-prepared instances.
1834
+ * This is needed for the factory context creation.
1835
+ */
1836
+ tryGetPrePreparedInstance(instanceName, contextHolder, deps) {
1837
+ return this.tokenProcessor.tryGetPrePreparedInstance(
1838
+ instanceName,
1839
+ contextHolder,
1840
+ deps,
1841
+ this.requestContextManager.getCurrentRequestContext()
1842
+ );
1843
+ }
1844
+ /**
1845
+ * Helper method for InstanceResolver to generate instance names.
1846
+ * This is needed for the factory context creation.
1847
+ */
1848
+ generateInstanceName(token, args) {
1849
+ return this.tokenProcessor.generateInstanceName(token, args);
1850
+ }
1851
+ };
1852
+
1853
+ // src/container.mts
1854
+ var _Container_decorators, _init;
1855
+ _Container_decorators = [Injectable()];
1856
+ var _Container = class _Container {
1857
+ constructor(registry = globalRegistry, logger = null, injectors = defaultInjectors) {
1858
+ this.registry = registry;
1859
+ this.logger = logger;
1860
+ this.injectors = injectors;
1861
+ this.serviceLocator = new ServiceLocator(registry, logger, injectors);
1862
+ this.registerSelf();
1863
+ }
1864
+ serviceLocator;
1865
+ registerSelf() {
1866
+ const token = getInjectableToken(_Container);
1867
+ const instanceName = this.serviceLocator.getInstanceIdentifier(token);
1868
+ this.serviceLocator.getManager().storeCreatedHolder(
1869
+ instanceName,
1870
+ this,
1871
+ "Class" /* Class */,
1872
+ "Singleton" /* Singleton */
1873
+ );
1874
+ }
1875
+ async get(token, args) {
1876
+ return this.serviceLocator.getOrThrowInstance(token, args);
1877
+ }
1878
+ /**
1879
+ * Gets the underlying ServiceLocator instance for advanced usage
1880
+ */
1881
+ getServiceLocator() {
1882
+ return this.serviceLocator;
1883
+ }
1884
+ /**
1885
+ * Invalidates a service and its dependencies
1886
+ */
1887
+ async invalidate(service) {
1888
+ const holder = this.getHolderByInstance(service);
1889
+ if (holder) {
1890
+ await this.serviceLocator.invalidate(holder.name);
1891
+ } else {
1892
+ const requestHolder = this.getRequestHolderByInstance(service);
1893
+ if (requestHolder) {
1894
+ await this.serviceLocator.invalidate(requestHolder.name);
1895
+ }
1896
+ }
1897
+ }
1898
+ /**
1899
+ * Gets a service holder by instance (reverse lookup)
1900
+ */
1901
+ getHolderByInstance(instance) {
1902
+ const holderMap = Array.from(
1903
+ this.serviceLocator.getManager().filter((holder) => holder.instance === instance).values()
1904
+ );
1905
+ return holderMap.length > 0 ? holderMap[0] : null;
1906
+ }
1907
+ getRequestHolderByInstance(instance) {
1908
+ const requestContexts = this.serviceLocator.getRequestContextManager().getRequestContexts();
1909
+ if (requestContexts) {
1910
+ for (const requestContext of requestContexts.values()) {
1911
+ for (const holder of requestContext.holders.values()) {
1912
+ if (holder.instance === instance) {
1913
+ return holder;
1914
+ }
1915
+ }
1916
+ }
1917
+ }
1918
+ return null;
1919
+ }
1920
+ /**
1921
+ * Checks if a service is registered in the container
1922
+ */
1923
+ isRegistered(token) {
1924
+ try {
1925
+ return this.serviceLocator.getInstanceIdentifier(token) !== null;
1926
+ } catch {
1927
+ return false;
1928
+ }
1929
+ }
1930
+ /**
1931
+ * Disposes the container and cleans up all resources
1932
+ */
1933
+ async dispose() {
1934
+ await this.serviceLocator.clearAll();
1935
+ }
1936
+ /**
1937
+ * Waits for all pending operations to complete
1938
+ */
1939
+ async ready() {
1940
+ await this.serviceLocator.ready();
1941
+ }
1942
+ // ============================================================================
1943
+ // REQUEST CONTEXT MANAGEMENT
1944
+ // ============================================================================
1945
+ /**
1946
+ * Begins a new request context with the given parameters.
1947
+ * @param requestId Unique identifier for this request
1948
+ * @param metadata Optional metadata for the request
1949
+ * @param priority Priority for resolution (higher = more priority)
1950
+ * @returns The created request context holder
1951
+ */
1952
+ beginRequest(requestId, metadata, priority = 100) {
1953
+ return this.serviceLocator.beginRequest(requestId, metadata, priority);
1954
+ }
1955
+ /**
1956
+ * Ends a request context and cleans up all associated instances.
1957
+ * @param requestId The request ID to end
1958
+ */
1959
+ async endRequest(requestId) {
1960
+ await this.serviceLocator.endRequest(requestId);
1961
+ }
1962
+ /**
1963
+ * Gets the current request context.
1964
+ * @returns The current request context holder or null
1965
+ */
1966
+ getCurrentRequestContext() {
1967
+ return this.serviceLocator.getCurrentRequestContext();
1968
+ }
1969
+ /**
1970
+ * Sets the current request context.
1971
+ * @param requestId The request ID to set as current
1972
+ */
1973
+ setCurrentRequestContext(requestId) {
1974
+ this.serviceLocator.setCurrentRequestContext(requestId);
1975
+ }
1976
+ /**
1977
+ * Clears all instances and bindings from the container.
1978
+ * This is useful for testing or resetting the container state.
1979
+ */
1980
+ clear() {
1981
+ return this.serviceLocator.clearAll();
1982
+ }
1983
+ };
1984
+ _init = __decoratorStart(null);
1985
+ _Container = __decorateElement(_init, 0, "Container", _Container_decorators, _Container);
1986
+ __runInitializers(_init, 1, _Container);
1987
+ var Container = _Container;
1988
+
1989
+ // src/testing/test-container.mts
1990
+ var TestBindingBuilder = class {
1991
+ constructor(container, token) {
1992
+ this.container = container;
1993
+ this.token = token;
1994
+ }
1995
+ /**
1996
+ * Binds the token to a specific value.
1997
+ * This is useful for testing with mock values or constants.
1998
+ * @param value The value to bind to the token
1999
+ */
2000
+ toValue(value) {
2001
+ const instanceName = this.container.getServiceLocator().getInstanceIdentifier(this.token);
2002
+ this.container.getServiceLocator().getManager().storeCreatedHolder(
2003
+ instanceName,
2004
+ value,
2005
+ "Class" /* Class */,
2006
+ "Singleton" /* Singleton */
2007
+ );
2008
+ return this.container;
2009
+ }
2010
+ /**
2011
+ * Binds the token to a class constructor.
2012
+ * @param target The class constructor to bind to
2013
+ */
2014
+ toClass(target) {
2015
+ this.container["registry"].set(
2016
+ this.token,
2017
+ "Singleton" /* Singleton */,
2018
+ target,
2019
+ "Class" /* Class */
2020
+ );
2021
+ return this.container;
2022
+ }
2023
+ };
2024
+ var _TestContainer_decorators, _init2, _a;
2025
+ _TestContainer_decorators = [Injectable()];
2026
+ var _TestContainer = class _TestContainer extends (_a = Container) {
2027
+ constructor(registry = globalRegistry, logger = null, injectors = void 0) {
2028
+ super(registry, logger, injectors);
2029
+ }
2030
+ bind(token) {
2031
+ let realToken = token;
2032
+ if (typeof token === "function") {
2033
+ realToken = getInjectableToken(token);
2034
+ }
2035
+ return new TestBindingBuilder(this, realToken);
2036
+ }
2037
+ bindValue(token, value) {
2038
+ return this.bind(token).toValue(value);
2039
+ }
2040
+ bindClass(token, target) {
2041
+ return this.bind(token).toClass(target);
2042
+ }
2043
+ /**
2044
+ * Creates a new TestContainer instance with the same configuration.
2045
+ * This is useful for creating isolated test containers.
2046
+ * @returns A new TestContainer instance
2047
+ */
2048
+ createChild() {
2049
+ return new _TestContainer(this.registry, this.logger, this.injectors);
2050
+ }
2051
+ };
2052
+ _init2 = __decoratorStart(_a);
2053
+ _TestContainer = __decorateElement(_init2, 0, "TestContainer", _TestContainer_decorators, _TestContainer);
2054
+ __runInitializers(_init2, 1, _TestContainer);
2055
+ var TestContainer = _TestContainer;
2056
+
2057
+ exports.TestBindingBuilder = TestBindingBuilder;
2058
+ exports.TestContainer = TestContainer;
2059
+ //# sourceMappingURL=index.js.map
2060
+ //# sourceMappingURL=index.js.map