@tsed/di 7.0.0-beta.15 → 7.0.0-beta.18

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 (67) hide show
  1. package/coverage.json +6 -0
  2. package/jest.config.js +1 -6
  3. package/lib/cjs/decorators/inject.js +2 -2
  4. package/lib/cjs/decorators/inject.js.map +1 -1
  5. package/lib/cjs/domain/ContextLogger.js +9 -22
  6. package/lib/cjs/domain/ContextLogger.js.map +1 -1
  7. package/lib/cjs/domain/DIContext.js +45 -21
  8. package/lib/cjs/domain/DIContext.js.map +1 -1
  9. package/lib/cjs/domain/LocalsContainer.js +3 -46
  10. package/lib/cjs/domain/LocalsContainer.js.map +1 -1
  11. package/lib/cjs/domain/Provider.js +9 -0
  12. package/lib/cjs/domain/Provider.js.map +1 -1
  13. package/lib/cjs/index.js +1 -1
  14. package/lib/cjs/index.js.map +1 -1
  15. package/lib/cjs/interfaces/AlterRunInContext.js.map +1 -1
  16. package/lib/cjs/interfaces/InjectableProperties.js.map +1 -1
  17. package/lib/cjs/registries/GlobalProviders.js +1 -0
  18. package/lib/cjs/registries/GlobalProviders.js.map +1 -1
  19. package/lib/cjs/registries/ProviderRegistry.js +1 -1
  20. package/lib/cjs/registries/ProviderRegistry.js.map +1 -1
  21. package/lib/cjs/services/DITest.js +1 -1
  22. package/lib/cjs/services/DITest.js.map +1 -1
  23. package/lib/cjs/services/InjectorService.js +24 -13
  24. package/lib/cjs/services/InjectorService.js.map +1 -1
  25. package/lib/cjs/utils/asyncHookContext.js +42 -0
  26. package/lib/cjs/utils/asyncHookContext.js.map +1 -0
  27. package/lib/esm/decorators/inject.js +1 -1
  28. package/lib/esm/decorators/inject.js.map +1 -1
  29. package/lib/esm/domain/ContextLogger.js +9 -22
  30. package/lib/esm/domain/ContextLogger.js.map +1 -1
  31. package/lib/esm/domain/DIContext.js +44 -20
  32. package/lib/esm/domain/DIContext.js.map +1 -1
  33. package/lib/esm/domain/LocalsContainer.js +3 -46
  34. package/lib/esm/domain/LocalsContainer.js.map +1 -1
  35. package/lib/esm/domain/Provider.js +10 -1
  36. package/lib/esm/domain/Provider.js.map +1 -1
  37. package/lib/esm/index.js +1 -1
  38. package/lib/esm/index.js.map +1 -1
  39. package/lib/esm/interfaces/AlterRunInContext.js.map +1 -1
  40. package/lib/esm/interfaces/InjectableProperties.js.map +1 -1
  41. package/lib/esm/registries/GlobalProviders.js +1 -0
  42. package/lib/esm/registries/GlobalProviders.js.map +1 -1
  43. package/lib/esm/registries/ProviderRegistry.js +1 -1
  44. package/lib/esm/registries/ProviderRegistry.js.map +1 -1
  45. package/lib/esm/services/DITest.js +1 -1
  46. package/lib/esm/services/DITest.js.map +1 -1
  47. package/lib/esm/services/InjectorService.js +25 -14
  48. package/lib/esm/services/InjectorService.js.map +1 -1
  49. package/lib/esm/utils/asyncHookContext.js +33 -0
  50. package/lib/esm/utils/asyncHookContext.js.map +1 -0
  51. package/lib/types/domain/ContextLogger.d.ts +4 -6
  52. package/lib/types/domain/DIContext.d.ts +17 -20
  53. package/lib/types/domain/LocalsContainer.d.ts +3 -22
  54. package/lib/types/domain/Provider.d.ts +2 -1
  55. package/lib/types/index.d.ts +1 -1
  56. package/lib/types/interfaces/AlterRunInContext.d.ts +1 -2
  57. package/lib/types/interfaces/InjectableProperties.d.ts +2 -1
  58. package/lib/types/registries/GlobalProviders.d.ts +6 -5
  59. package/lib/types/registries/ProviderRegistry.d.ts +2 -1
  60. package/lib/types/services/InjectorService.d.ts +6 -5
  61. package/lib/types/utils/asyncHookContext.d.ts +14 -0
  62. package/package.json +5 -5
  63. package/lib/cjs/utils/runInContext.js +0 -32
  64. package/lib/cjs/utils/runInContext.js.map +0 -1
  65. package/lib/esm/utils/runInContext.js +0 -25
  66. package/lib/esm/utils/runInContext.js.map +0 -1
  67. package/lib/types/utils/runInContext.d.ts +0 -7
@@ -44,6 +44,7 @@ let InjectorService = InjectorService_1 = class InjectorService extends Containe
44
44
  logger = console;
45
45
  resolvedConfiguration = false;
46
46
  #cache = new LocalsContainer_1.LocalsContainer();
47
+ #hooks = new core_1.Hooks();
47
48
  constructor() {
48
49
  super();
49
50
  this.#cache.set(InjectorService_1, this);
@@ -65,7 +66,7 @@ let InjectorService = InjectorService_1 = class InjectorService extends Containe
65
66
  * Return a list of instance build by the injector.
66
67
  */
67
68
  toArray() {
68
- return this.#cache.toArray();
69
+ return [...this.#cache.values()];
69
70
  }
70
71
  /**
71
72
  * Get a service or factory already constructed from his symbol or class.
@@ -165,6 +166,9 @@ let InjectorService = InjectorService_1 = class InjectorService extends Containe
165
166
  instance = this.resolve(token, locals, options);
166
167
  switch (this.scopeOf(provider)) {
167
168
  case ProviderScope_1.ProviderScope.SINGLETON:
169
+ if (provider.hooks && !options.rebuild) {
170
+ this.registerHooks(provider, instance);
171
+ }
168
172
  if (!provider.isAsync()) {
169
173
  this.#cache.set(token, instance);
170
174
  return instance;
@@ -177,7 +181,12 @@ let InjectorService = InjectorService_1 = class InjectorService extends Containe
177
181
  });
178
182
  return instance;
179
183
  case ProviderScope_1.ProviderScope.REQUEST:
180
- locals && locals.set(token, instance);
184
+ if (locals) {
185
+ locals.set(token, instance);
186
+ if (provider.hooks && provider.hooks.$onDestroy) {
187
+ locals.hooks.on("$onDestroy", (...args) => provider.hooks.$onDestroy(instance, ...args));
188
+ }
189
+ }
181
190
  return instance;
182
191
  }
183
192
  return instance;
@@ -300,7 +309,6 @@ let InjectorService = InjectorService_1 = class InjectorService extends Containe
300
309
  });
301
310
  }
302
311
  /**
303
- *
304
312
  * @param instance
305
313
  * @param {string} propertyKey
306
314
  */
@@ -413,11 +421,11 @@ let InjectorService = InjectorService_1 = class InjectorService extends Containe
413
421
  /**
414
422
  * Emit an event to all service. See service [lifecycle hooks](/docs/services.md#lifecycle-hooks).
415
423
  * @param eventName The event name to emit at all services.
416
- * @param args List of the parameters to give to each services.
424
+ * @param args List of the parameters to give to each service.
417
425
  * @returns {Promise<any[]>} A list of promises.
418
426
  */
419
427
  async emit(eventName, ...args) {
420
- return this.#cache.emit(eventName, ...args);
428
+ return this.#hooks.asyncEmit(eventName, args);
421
429
  }
422
430
  /**
423
431
  * @param eventName
@@ -425,7 +433,7 @@ let InjectorService = InjectorService_1 = class InjectorService extends Containe
425
433
  * @param args
426
434
  */
427
435
  alter(eventName, value, ...args) {
428
- return this.#cache.alter(eventName, value, ...args);
436
+ return this.#hooks.alter(eventName, value, args);
429
437
  }
430
438
  /**
431
439
  * @param eventName
@@ -433,10 +441,10 @@ let InjectorService = InjectorService_1 = class InjectorService extends Containe
433
441
  * @param args
434
442
  */
435
443
  async alterAsync(eventName, value, ...args) {
436
- return this.#cache.alterAsync(eventName, value, ...args);
444
+ return this.#hooks.asyncAlter(eventName, value, args);
437
445
  }
438
446
  async destroy() {
439
- await this.#cache.destroy();
447
+ await this.emit("$onDestroy");
440
448
  }
441
449
  ensureProvider(token) {
442
450
  if (!this.hasProvider(token) && GlobalProviders_1.GlobalProviders.has(token)) {
@@ -497,11 +505,6 @@ let InjectorService = InjectorService_1 = class InjectorService extends Containe
497
505
  if (instance && (0, core_1.isClass)((0, core_1.classOf)(instance))) {
498
506
  this.bindInjectableProperties(instance, locals, options);
499
507
  }
500
- if (instance && provider.hooks) {
501
- Object.entries(provider.hooks).forEach(([key, cb]) => {
502
- instance[key] = (...args) => cb(instance, ...args);
503
- });
504
- }
505
508
  return instance;
506
509
  }
507
510
  /**
@@ -560,6 +563,14 @@ let InjectorService = InjectorService_1 = class InjectorService extends Containe
560
563
  provider
561
564
  };
562
565
  }
566
+ registerHooks(provider, instance) {
567
+ if (provider.hooks) {
568
+ Object.entries(provider.hooks).forEach(([event, cb]) => {
569
+ const callback = (...args) => cb(this.get(provider.token) || instance, ...args);
570
+ this.#hooks.on(event, callback);
571
+ });
572
+ }
573
+ }
563
574
  };
564
575
  InjectorService = InjectorService_1 = tslib_1.__decorate([
565
576
  (0, injectable_1.Injectable)({
@@ -1 +1 @@
1
- {"version":3,"file":"InjectorService.js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zD,SAAS,GAAG,CAAC,IAAqB,EAAE,EAAE,CAAC,IAAI,QAAQ,CAAC,QAAQ,CAAC,GAAG,IAAI,CAAC,CAAC;SACvE;QAED,OAAO;YACL,KAAK;YACL,KAAK,EAAE,KAAK,IAAI,YAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,IAAI,6BAAa,CAAC,SAAS;YACzE,IAAI,EAAE,IAAK,IAAI,EAAE;YACjB,OAAO,EAAE,OAAO,IAAI,EAAE;YACtB,SAAS;YACT,QAAQ;SACT,CAAC;IACJ,CAAC;CACF,CAAA;AAhoBY,eAAe;IAJ3B,IAAA,uBAAU,EAAC;QACV,KAAK,EAAE,6BAAa,CAAC,SAAS;QAC9B,MAAM,EAAE,IAAI;KACb,CAAC;;GACW,eAAe,CAgoB3B;AAhoBY,0CAAe","sourcesContent":["import {\n ancestorsOf,\n catchError,\n classOf,\n deepClone,\n deepMerge,\n isClass,\n isFunction,\n isInheritedFrom,\n Metadata,\n nameOf,\n prototypeOf,\n Store\n} from \"@tsed/core\";\nimport {DI_PARAM_OPTIONS, INJECTABLE_PROP} from \"../constants/constants\";\nimport {Configuration} from \"../decorators/configuration\";\nimport {Injectable} from \"../decorators/injectable\";\nimport {Container} from \"../domain/Container\";\nimport {InjectablePropertyType} from \"../domain/InjectablePropertyType\";\nimport {LocalsContainer} from \"../domain/LocalsContainer\";\nimport {Provider} from \"../domain/Provider\";\nimport {ProviderScope} from \"../domain/ProviderScope\";\nimport {InjectionError} from \"../errors/InjectionError\";\nimport {UndefinedTokenError} from \"../errors/UndefinedTokenError\";\nimport {DILogger} from \"../interfaces/DILogger\";\nimport {InjectableProperties, InjectablePropertyOptions, InjectablePropertyValue} from \"../interfaces/InjectableProperties\";\nimport {InterceptorContext} from \"../interfaces/InterceptorContext\";\nimport {InterceptorMethods} from \"../interfaces/InterceptorMethods\";\nimport {InvokeOptions} from \"../interfaces/InvokeOptions\";\nimport {ResolvedInvokeOptions} from \"../interfaces/ResolvedInvokeOptions\";\nimport {TokenProvider} from \"../interfaces/TokenProvider\";\nimport {GlobalProviders} from \"../registries/GlobalProviders\";\nimport {createContainer} from \"../utils/createContainer\";\nimport {resolveControllers} from \"../utils/resolveControllers\";\nimport {DIConfiguration} from \"./DIConfiguration\";\n\n/**\n * This service contain all services collected by `@Service` or services declared manually with `InjectorService.factory()` or `InjectorService.service()`.\n *\n * ### Example:\n *\n * ```typescript\n * import {InjectorService} from \"@tsed/di\";\n *\n * // Import the services (all services are decorated with @Service()\";\n * import MyService1 from \"./services/service1\";\n * import MyService2 from \"./services/service2\";\n * import MyService3 from \"./services/service3\";\n *\n * // When all services are imported, you can load InjectorService.\n * const injector = new InjectorService()\n *\n * await injector.load();\n *\n * const myService1 = injector.get<MyService1>(MyServcice1);\n * ```\n */\n@Injectable({\n scope: ProviderScope.SINGLETON,\n global: true\n})\nexport class InjectorService extends Container {\n public settings: DIConfiguration = new DIConfiguration();\n public logger: DILogger = console;\n private resolvedConfiguration: boolean = false;\n #cache = new LocalsContainer();\n\n constructor() {\n super();\n this.#cache.set(InjectorService, this);\n }\n\n get resolvers() {\n return this.settings.resolvers!;\n }\n\n get scopes() {\n return this.settings.scopes || {};\n }\n\n /**\n * Retrieve default scope for a given provider.\n * @param provider\n */\n public scopeOf(provider: Provider) {\n return provider.scope || this.scopes[provider.type] || ProviderScope.SINGLETON;\n }\n\n /**\n * Return a list of instance build by the injector.\n */\n public toArray(): any[] {\n return this.#cache.toArray();\n }\n\n /**\n * Get a service or factory already constructed from his symbol or class.\n *\n * #### Example\n *\n * ```typescript\n * import {InjectorService} from \"@tsed/di\";\n * import MyService from \"./services\";\n *\n * class OtherService {\n * constructor(injectorService: InjectorService) {\n * const myService = injectorService.get<MyService>(MyService);\n * }\n * }\n * ```\n *\n * @param token The class or symbol registered in InjectorService.\n * @param options\n * @returns {boolean}\n */\n get<T = any>(token: TokenProvider<T>, options: any = {}): T | undefined {\n const instance = this.getInstance(token);\n\n if (instance !== undefined) {\n return instance;\n }\n\n if (!this.hasProvider(token)) {\n for (const resolver of this.resolvers) {\n const result = resolver.get(token, options);\n\n if (result !== undefined) {\n return result;\n }\n }\n }\n }\n\n /**\n * Return all instance of the same provider type\n * @param type\n */\n getAll(type: string) {\n return this.getProviders(type).map((provider) => {\n return this.get(provider.token);\n });\n }\n\n /**\n * The has() method returns a boolean indicating whether an element with the specified key exists or not.\n * @returns {boolean}\n * @param token\n */\n has(token: TokenProvider): boolean {\n return this.#cache.get(token) !== undefined;\n }\n\n /**\n * Invoke the class and inject all services that required by the class constructor.\n *\n * #### Example\n *\n * ```typescript\n * import {InjectorService} from \"@tsed/di\";\n * import MyService from \"./services\";\n *\n * class OtherService {\n * constructor(injectorService: InjectorService) {\n * const myService = injectorService.invoke<MyService>(MyService);\n * }\n * }\n * ```\n *\n * @param token The injectable class to invoke. Class parameters are injected according constructor signature.\n * @param locals Optional object. If preset then any argument Class are read from this object first, before the `InjectorService` is consulted.\n * @param options\n * @returns {T} The class constructed.\n */\n public invoke<T = any>(token: TokenProvider, locals?: Map<TokenProvider, any>, options: Partial<InvokeOptions<T>> = {}): T {\n let instance: any = locals ? locals.get(token) : undefined;\n\n if (instance !== undefined) {\n return instance;\n }\n\n if (token === Configuration) {\n return this.settings as unknown as T;\n }\n\n instance = !options.rebuild ? this.getInstance(token) : undefined;\n\n if (instance != undefined) {\n return instance;\n }\n\n if (token === DI_PARAM_OPTIONS) {\n return {} as T;\n }\n\n const provider = this.ensureProvider(token);\n\n if (!provider || options.rebuild) {\n instance = this.resolve(token, locals, options);\n\n if (this.hasProvider(token)) {\n this.#cache.set(token, instance);\n }\n\n return instance;\n }\n\n instance = this.resolve(token, locals, options);\n\n switch (this.scopeOf(provider)) {\n case ProviderScope.SINGLETON:\n if (!provider.isAsync()) {\n this.#cache.set(token, instance);\n return instance;\n }\n\n // store promise to lock token in cache\n this.#cache.set(token, instance);\n\n instance = instance.then((instance: any) => {\n this.#cache.set(token, instance);\n\n return instance;\n });\n\n return instance;\n\n case ProviderScope.REQUEST:\n locals && locals.set(token, instance);\n return instance;\n }\n\n return instance;\n }\n\n /**\n * Build only providers which are asynchronous.\n */\n async loadAsync() {\n for (const [, provider] of this) {\n if (!this.has(provider.token) && provider.isAsync()) {\n await this.invoke(provider.token);\n }\n }\n }\n\n loadSync() {\n for (const [, provider] of this) {\n if (!this.has(provider.token) && this.scopeOf(provider) === ProviderScope.SINGLETON) {\n this.invoke(provider.token);\n }\n }\n }\n\n /**\n * Boostrap injector from container and resolve configuration.\n *\n * @param container\n */\n bootstrap(container: Container = createContainer()) {\n // Clone all providers in the container\n this.addProviders(container);\n\n // Resolve all configuration\n this.resolveConfiguration();\n\n return this;\n }\n\n /**\n * Load injector from a given module\n * @param rootModule\n */\n loadModule(rootModule: TokenProvider) {\n this.settings.routes = this.settings.routes.concat(resolveControllers(this.settings));\n\n const container = createContainer();\n container.delete(rootModule);\n\n container.addProvider(rootModule, {\n type: \"server:module\",\n scope: ProviderScope.SINGLETON\n });\n\n return this.load(container);\n }\n\n /**\n * Build all providers from given container (or GlobalProviders) and emit `$onInit` event.\n *\n * @param container\n */\n async load(container: Container = createContainer()) {\n this.bootstrap(container);\n\n // build async and sync provider\n await this.loadAsync();\n\n // load sync provider\n this.loadSync();\n\n await this.emit(\"$beforeInit\");\n await this.emit(\"$onInit\");\n }\n\n /**\n * Load all configurations registered on providers\n */\n resolveConfiguration() {\n if (this.resolvedConfiguration) {\n return;\n }\n const mergedConfiguration = new Map();\n\n super.forEach((provider) => {\n if (provider.configuration && provider.type !== \"server:module\") {\n Object.entries(provider.configuration).forEach(([key, value]) => {\n if (![\"resolvers\", \"mount\", \"imports\"].includes(key)) {\n value = mergedConfiguration.has(key) ? deepMerge(mergedConfiguration.get(key), value) : deepClone(value);\n mergedConfiguration.set(key, value);\n }\n });\n }\n\n if (provider.resolvers) {\n this.settings.resolvers = this.settings.resolvers.concat(provider.resolvers);\n }\n });\n\n mergedConfiguration.forEach((value, key) => {\n this.settings.set(key, deepMerge(value, this.settings.get(key)));\n });\n\n this.resolvedConfiguration = true;\n }\n\n /**\n *\n * @param instance\n * @param locals\n * @param options\n */\n public bindInjectableProperties(instance: any, locals: Map<TokenProvider, any>, options: Partial<InvokeOptions>) {\n const properties: InjectableProperties = ancestorsOf(classOf(instance)).reduce((properties: any, target: any) => {\n const store = Store.from(target);\n\n return {\n ...properties,\n ...(store.get(INJECTABLE_PROP) || {})\n };\n }, {});\n\n Object.values(properties).forEach((definition) => {\n switch (definition.bindingType) {\n case InjectablePropertyType.METHOD:\n this.bindMethod(instance, definition);\n break;\n case InjectablePropertyType.PROPERTY:\n this.bindProperty(instance, definition, locals, options);\n break;\n case InjectablePropertyType.CONSTANT:\n this.bindConstant(instance, definition);\n break;\n case InjectablePropertyType.VALUE:\n this.bindValue(instance, definition);\n break;\n case InjectablePropertyType.INTERCEPTOR:\n this.bindInterceptor(instance, definition);\n break;\n }\n });\n }\n\n /**\n *\n * @param instance\n * @param {string} propertyKey\n */\n public bindMethod(instance: any, {propertyKey}: InjectablePropertyOptions) {\n const target = classOf(instance);\n const originalMethod = instance[propertyKey];\n const deps = Metadata.getParamTypes(prototypeOf(target), propertyKey);\n\n instance[propertyKey] = () => {\n const services = deps.map((dependency: any) => this.get(dependency));\n\n return originalMethod.call(instance, ...services);\n };\n }\n\n /**\n * Create an injectable property.\n *\n * @param instance\n * @param {string} propertyKey\n * @param {any} useType\n * @param resolver\n * @param options\n * @param locals\n * @param invokeOptions\n */\n public bindProperty(\n instance: any,\n {propertyKey, resolver, options = {}}: InjectablePropertyOptions,\n locals: Map<TokenProvider, any>,\n invokeOptions: Partial<InvokeOptions>\n ) {\n let get: () => any;\n\n get = resolver(this, locals, {...invokeOptions, options});\n\n catchError(() =>\n Object.defineProperty(instance, propertyKey, {\n get\n })\n );\n }\n\n /**\n *\n * @param instance\n * @param {string} propertyKey\n * @param {any} useType\n */\n public bindValue(instance: any, {propertyKey, expression, defaultValue}: InjectablePropertyValue) {\n const descriptor = {\n get: () => this.settings.get(expression) || defaultValue,\n set: (value: any) => this.settings.set(expression, value),\n enumerable: true,\n configurable: true\n };\n\n catchError(() => Object.defineProperty(instance, propertyKey, descriptor));\n }\n\n /**\n *\n * @param instance\n * @param {string} propertyKey\n * @param {any} useType\n */\n public bindConstant(instance: any, {propertyKey, expression, defaultValue}: InjectablePropertyValue) {\n let bean: any;\n\n const get = () => {\n if (bean !== undefined) {\n return bean;\n }\n\n const value = this.settings.get(expression, defaultValue);\n bean = Object.freeze(deepClone(value));\n\n return bean;\n };\n\n const descriptor = {\n get,\n enumerable: true,\n configurable: true\n };\n\n catchError(() => Object.defineProperty(instance, propertyKey, descriptor));\n }\n\n /**\n *\n * @param instance\n * @param propertyKey\n * @param useType\n * @param options\n */\n public bindInterceptor(instance: any, {propertyKey, useType, options}: InjectablePropertyOptions) {\n const target = classOf(instance);\n const originalMethod = instance[propertyKey];\n\n instance[propertyKey] = (...args: any[]) => {\n const next = (err?: Error) => {\n if (!err) {\n return originalMethod.apply(instance, args);\n }\n\n throw err;\n };\n\n const context: InterceptorContext<any> = {\n target,\n propertyKey,\n args,\n options,\n next\n };\n\n const interceptor = this.get<InterceptorMethods>(useType)!;\n\n return interceptor.intercept!(\n {\n ...context,\n options\n },\n next\n );\n };\n }\n\n async lazyInvoke<T = any>(token: TokenProvider) {\n let instance = this.getInstance(token);\n\n if (!instance) {\n instance = await this.invoke<T>(token);\n\n if (isFunction(instance?.$onInit)) {\n await instance.$onInit();\n }\n }\n\n return instance;\n }\n\n /**\n * Emit an event to all service. See service [lifecycle hooks](/docs/services.md#lifecycle-hooks).\n * @param eventName The event name to emit at all services.\n * @param args List of the parameters to give to each services.\n * @returns {Promise<any[]>} A list of promises.\n */\n public async emit(eventName: string, ...args: any[]) {\n return this.#cache.emit(eventName, ...args);\n }\n\n /**\n * @param eventName\n * @param value\n * @param args\n */\n public alter<T = any>(eventName: string, value: any, ...args: any[]): T {\n return this.#cache.alter(eventName, value, ...args);\n }\n\n /**\n * @param eventName\n * @param value\n * @param args\n */\n public async alterAsync<T = any>(eventName: string, value: any, ...args: any[]): Promise<T> {\n return this.#cache.alterAsync(eventName, value, ...args);\n }\n\n async destroy() {\n await this.#cache.destroy();\n }\n\n protected ensureProvider(token: TokenProvider): Provider | undefined {\n if (!this.hasProvider(token) && GlobalProviders.has(token)) {\n this.addProvider(token);\n }\n\n return this.getProvider(token)!;\n }\n\n protected getInstance(token: any) {\n return this.#cache.get(token);\n }\n\n /**\n * Invoke a class method and inject service.\n *\n * #### IInjectableMethod options\n *\n * * **target**: Optional. The class instance.\n * * **methodName**: `string` Optional. The method name.\n * * **designParamTypes**: `any[]` Optional. List of injectable types.\n * * **locals**: `Map<Function, any>` Optional. If preset then any argument Class are read from this object first, before the `InjectorService` is consulted.\n *\n * #### Example\n *\n * @param target\n * @param locals\n * @param options\n * @private\n */\n private resolve<T>(\n target: TokenProvider,\n locals: Map<TokenProvider, any> = new LocalsContainer(),\n options: Partial<InvokeOptions<T>> = {}\n ): T | Promise<T> {\n const resolvedOpts = this.mapInvokeOptions(target, locals, options);\n const {token, deps, construct, imports, provider} = resolvedOpts;\n\n if (provider) {\n GlobalProviders.onInvoke(provider, locals, {...resolvedOpts, injector: this});\n }\n\n let instance: any;\n let currentDependency: any = false;\n\n try {\n const invokeDependency =\n (parent?: any) =>\n (token: any, index: number): any => {\n currentDependency = {token, index, deps};\n\n if (token !== DI_PARAM_OPTIONS) {\n const options = provider?.store?.get(`${DI_PARAM_OPTIONS}:${index}`);\n\n locals.set(DI_PARAM_OPTIONS, options || {});\n }\n\n return isInheritedFrom(token, Provider, 1) ? provider : this.invoke(token, locals, {parent});\n };\n\n // Invoke manually imported providers\n imports.forEach(invokeDependency());\n\n // Inject dependencies\n const services = deps.map(invokeDependency(token));\n\n currentDependency = false;\n\n instance = construct(services);\n } catch (error) {\n InjectionError.throwInjectorError(token, currentDependency, error);\n }\n\n if (instance === undefined) {\n throw new InjectionError(\n token,\n `Unable to create new instance from undefined value. Check your provider declaration for ${nameOf(token)}`\n );\n }\n\n if (instance && isClass(classOf(instance))) {\n this.bindInjectableProperties(instance, locals, options);\n }\n\n if (instance && provider.hooks) {\n Object.entries(provider.hooks).forEach(([key, cb]) => {\n instance[key] = (...args: any[]) => cb(instance, ...args);\n });\n }\n\n return instance;\n }\n\n /**\n * Create options to invoke a provider or class.\n * @param token\n * @param locals\n * @param options\n */\n private mapInvokeOptions(token: TokenProvider, locals: Map<TokenProvider, any>, options: Partial<InvokeOptions>): ResolvedInvokeOptions {\n let imports: TokenProvider[] | undefined = options.imports;\n let deps: TokenProvider[] | undefined = options.deps;\n let scope = options.scope;\n let construct;\n\n if (!token) {\n throw new UndefinedTokenError();\n }\n\n let provider: Provider;\n\n if (!this.hasProvider(token)) {\n provider = new Provider(token);\n\n this.resolvers.forEach((resolver) => {\n const result = resolver.get(token, locals.get(DI_PARAM_OPTIONS));\n\n if (result !== undefined) {\n provider.useFactory = () => result;\n }\n });\n } else {\n provider = this.getProvider(token)!;\n }\n\n scope = scope || this.scopeOf(provider);\n deps = deps || provider.deps;\n imports = imports || provider.imports;\n\n if (provider.useValue !== undefined) {\n construct = () => (isFunction(provider.useValue) ? provider.useValue() : provider.useValue);\n } else if (provider.useFactory) {\n construct = (deps: TokenProvider[]) => provider.useFactory(...deps);\n } else if (provider.useAsyncFactory) {\n construct = async (deps: TokenProvider[]) => {\n deps = await Promise.all(deps);\n return provider.useAsyncFactory(...deps);\n };\n } else {\n // useClass\n deps = deps || Metadata.getParamTypes(provider.useClass);\n construct = (deps: TokenProvider[]) => new provider.useClass(...deps);\n }\n\n return {\n token,\n scope: scope || Store.from(token).get(\"scope\") || ProviderScope.SINGLETON,\n deps: deps! || [],\n imports: imports || [],\n construct,\n provider\n };\n }\n}\n"]}
1
+ {"version":3,"file":"InjectorService.js","sourceRoot":"","sources":["../../../src/services/InjectorService.ts"],"names":[],"mappings":";;;;;AAAA,qCAcoB;AACpB,sDAAyE;AACzE,+DAA0D;AAC1D,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,CAAC,CAAC;YACzD,SAAS,GAAG,CAAC,IAAqB,EAAE,EAAE,CAAC,IAAI,QAAQ,CAAC,QAAQ,CAAC,GAAG,IAAI,CAAC,CAAC;SACvE;QAED,OAAO;YACL,KAAK;YACL,KAAK,EAAE,KAAK,IAAI,YAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,IAAI,6BAAa,CAAC,SAAS;YACzE,IAAI,EAAE,IAAK,IAAI,EAAE;YACjB,OAAO,EAAE,OAAO,IAAI,EAAE;YACtB,SAAS;YACT,QAAQ;SACT,CAAC;IACJ,CAAC;IAEO,aAAa,CAAC,QAAkB,EAAE,QAAa;QACrD,IAAI,QAAQ,CAAC,KAAK,EAAE;YAClB,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,EAAE,EAAE;gBACrD,MAAM,QAAQ,GAAG,CAAC,GAAG,IAAW,EAAE,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,QAAQ,EAAE,GAAG,IAAI,CAAC,CAAC;gBAEvF,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;YAClC,CAAC,CAAC,CAAC;SACJ;IACH,CAAC;CACF,CAAA;AAhpBY,eAAe;IAJ3B,IAAA,uBAAU,EAAC;QACV,KAAK,EAAE,6BAAa,CAAC,SAAS;QAC9B,MAAM,EAAE,IAAI;KACb,CAAC;;GACW,eAAe,CAgpB3B;AAhpBY,0CAAe","sourcesContent":["import {\n ancestorsOf,\n catchError,\n classOf,\n deepClone,\n deepMerge,\n Hooks,\n isClass,\n isFunction,\n isInheritedFrom,\n Metadata,\n nameOf,\n prototypeOf,\n Store\n} from \"@tsed/core\";\nimport {DI_PARAM_OPTIONS, INJECTABLE_PROP} from \"../constants/constants\";\nimport {Configuration} from \"../decorators/configuration\";\nimport {Injectable} from \"../decorators/injectable\";\nimport {Container} from \"../domain/Container\";\nimport {InjectablePropertyType} from \"../domain/InjectablePropertyType\";\nimport {LocalsContainer} from \"../domain/LocalsContainer\";\nimport {Provider} from \"../domain/Provider\";\nimport {ProviderScope} from \"../domain/ProviderScope\";\nimport {InjectionError} from \"../errors/InjectionError\";\nimport {UndefinedTokenError} from \"../errors/UndefinedTokenError\";\nimport {DILogger} from \"../interfaces/DILogger\";\nimport {InjectableProperties, InjectablePropertyOptions, InjectablePropertyValue} from \"../interfaces/InjectableProperties\";\nimport {InterceptorContext} from \"../interfaces/InterceptorContext\";\nimport {InterceptorMethods} from \"../interfaces/InterceptorMethods\";\nimport {InvokeOptions} from \"../interfaces/InvokeOptions\";\nimport {ResolvedInvokeOptions} from \"../interfaces/ResolvedInvokeOptions\";\nimport {TokenProvider} from \"../interfaces/TokenProvider\";\nimport {GlobalProviders} from \"../registries/GlobalProviders\";\nimport {runInContext} from \"../utils/asyncHookContext\";\nimport {createContainer} from \"../utils/createContainer\";\nimport {resolveControllers} from \"../utils/resolveControllers\";\nimport {DIConfiguration} from \"./DIConfiguration\";\n\n/**\n * This service contain all services collected by `@Service` or services declared manually with `InjectorService.factory()` or `InjectorService.service()`.\n *\n * ### Example:\n *\n * ```typescript\n * import {InjectorService} from \"@tsed/di\";\n *\n * // Import the services (all services are decorated with @Service()\";\n * import MyService1 from \"./services/service1\";\n * import MyService2 from \"./services/service2\";\n * import MyService3 from \"./services/service3\";\n *\n * // When all services are imported, you can load InjectorService.\n * const injector = new InjectorService()\n *\n * await injector.load();\n *\n * const myService1 = injector.get<MyService1>(MyServcice1);\n * ```\n */\n@Injectable({\n scope: ProviderScope.SINGLETON,\n global: true\n})\nexport class InjectorService extends Container {\n public settings: DIConfiguration = new DIConfiguration();\n public logger: DILogger = console;\n private resolvedConfiguration: boolean = false;\n\n #cache = new LocalsContainer();\n #hooks = new Hooks();\n\n constructor() {\n super();\n this.#cache.set(InjectorService, this);\n }\n\n get resolvers() {\n return this.settings.resolvers!;\n }\n\n get scopes() {\n return this.settings.scopes || {};\n }\n\n /**\n * Retrieve default scope for a given provider.\n * @param provider\n */\n public scopeOf(provider: Provider) {\n return provider.scope || this.scopes[provider.type] || ProviderScope.SINGLETON;\n }\n\n /**\n * Return a list of instance build by the injector.\n */\n public toArray(): any[] {\n return [...this.#cache.values()];\n }\n\n /**\n * Get a service or factory already constructed from his symbol or class.\n *\n * #### Example\n *\n * ```typescript\n * import {InjectorService} from \"@tsed/di\";\n * import MyService from \"./services\";\n *\n * class OtherService {\n * constructor(injectorService: InjectorService) {\n * const myService = injectorService.get<MyService>(MyService);\n * }\n * }\n * ```\n *\n * @param token The class or symbol registered in InjectorService.\n * @param options\n * @returns {boolean}\n */\n get<T = any>(token: TokenProvider<T>, options: any = {}): T | undefined {\n const instance = this.getInstance(token);\n\n if (instance !== undefined) {\n return instance;\n }\n\n if (!this.hasProvider(token)) {\n for (const resolver of this.resolvers) {\n const result = resolver.get(token, options);\n\n if (result !== undefined) {\n return result;\n }\n }\n }\n }\n\n /**\n * Return all instance of the same provider type\n * @param type\n */\n getAll(type: string) {\n return this.getProviders(type).map((provider) => {\n return this.get(provider.token);\n });\n }\n\n /**\n * The has() method returns a boolean indicating whether an element with the specified key exists or not.\n * @returns {boolean}\n * @param token\n */\n has(token: TokenProvider): boolean {\n return this.#cache.get(token) !== undefined;\n }\n\n /**\n * Invoke the class and inject all services that required by the class constructor.\n *\n * #### Example\n *\n * ```typescript\n * import {InjectorService} from \"@tsed/di\";\n * import MyService from \"./services\";\n *\n * class OtherService {\n * constructor(injectorService: InjectorService) {\n * const myService = injectorService.invoke<MyService>(MyService);\n * }\n * }\n * ```\n *\n * @param token The injectable class to invoke. Class parameters are injected according constructor signature.\n * @param locals Optional object. If preset then any argument Class are read from this object first, before the `InjectorService` is consulted.\n * @param options\n * @returns {T} The class constructed.\n */\n public invoke<T = any>(token: TokenProvider, locals?: LocalsContainer, options: Partial<InvokeOptions<T>> = {}): T {\n let instance: any = locals ? locals.get(token) : undefined;\n\n if (instance !== undefined) {\n return instance;\n }\n\n if (token === Configuration) {\n return this.settings as unknown as T;\n }\n\n instance = !options.rebuild ? this.getInstance(token) : undefined;\n\n if (instance != undefined) {\n return instance;\n }\n\n if (token === DI_PARAM_OPTIONS) {\n return {} as T;\n }\n\n const provider = this.ensureProvider(token);\n\n if (!provider || options.rebuild) {\n instance = this.resolve(token, locals, options);\n\n if (this.hasProvider(token)) {\n this.#cache.set(token, instance);\n }\n\n return instance;\n }\n\n instance = this.resolve(token, locals, options);\n\n switch (this.scopeOf(provider)) {\n case ProviderScope.SINGLETON:\n if (provider.hooks && !options.rebuild) {\n this.registerHooks(provider, instance);\n }\n\n if (!provider.isAsync()) {\n this.#cache.set(token, instance);\n return instance;\n }\n\n // store promise to lock token in cache\n this.#cache.set(token, instance);\n\n instance = instance.then((instance: any) => {\n this.#cache.set(token, instance);\n\n return instance;\n });\n\n return instance;\n\n case ProviderScope.REQUEST:\n if (locals) {\n locals.set(token, instance);\n\n if (provider.hooks && provider.hooks.$onDestroy) {\n locals.hooks.on(\"$onDestroy\", (...args: any[]) => provider.hooks!.$onDestroy(instance, ...args));\n }\n }\n\n return instance;\n }\n\n return instance;\n }\n\n /**\n * Build only providers which are asynchronous.\n */\n async loadAsync() {\n for (const [, provider] of this) {\n if (!this.has(provider.token) && provider.isAsync()) {\n await this.invoke(provider.token);\n }\n }\n }\n\n loadSync() {\n for (const [, provider] of this) {\n if (!this.has(provider.token) && this.scopeOf(provider) === ProviderScope.SINGLETON) {\n this.invoke(provider.token);\n }\n }\n }\n\n /**\n * Boostrap injector from container and resolve configuration.\n *\n * @param container\n */\n bootstrap(container: Container = createContainer()) {\n // Clone all providers in the container\n this.addProviders(container);\n\n // Resolve all configuration\n this.resolveConfiguration();\n\n return this;\n }\n\n /**\n * Load injector from a given module\n * @param rootModule\n */\n loadModule(rootModule: TokenProvider) {\n this.settings.routes = this.settings.routes.concat(resolveControllers(this.settings));\n\n const container = createContainer();\n container.delete(rootModule);\n\n container.addProvider(rootModule, {\n type: \"server:module\",\n scope: ProviderScope.SINGLETON\n });\n\n return this.load(container);\n }\n\n /**\n * Build all providers from given container (or GlobalProviders) and emit `$onInit` event.\n *\n * @param container\n */\n async load(container: Container = createContainer()) {\n this.bootstrap(container);\n\n // build async and sync provider\n await this.loadAsync();\n\n // load sync provider\n this.loadSync();\n\n await this.emit(\"$beforeInit\");\n await this.emit(\"$onInit\");\n }\n\n /**\n * Load all configurations registered on providers\n */\n resolveConfiguration() {\n if (this.resolvedConfiguration) {\n return;\n }\n const mergedConfiguration = new Map();\n\n super.forEach((provider) => {\n if (provider.configuration && provider.type !== \"server:module\") {\n Object.entries(provider.configuration).forEach(([key, value]) => {\n if (![\"resolvers\", \"mount\", \"imports\"].includes(key)) {\n value = mergedConfiguration.has(key) ? deepMerge(mergedConfiguration.get(key), value) : deepClone(value);\n mergedConfiguration.set(key, value);\n }\n });\n }\n\n if (provider.resolvers) {\n this.settings.resolvers = this.settings.resolvers.concat(provider.resolvers);\n }\n });\n\n mergedConfiguration.forEach((value, key) => {\n this.settings.set(key, deepMerge(value, this.settings.get(key)));\n });\n\n this.resolvedConfiguration = true;\n }\n\n /**\n *\n * @param instance\n * @param locals\n * @param options\n */\n public bindInjectableProperties(instance: any, locals: LocalsContainer, options: Partial<InvokeOptions>) {\n const properties: InjectableProperties = ancestorsOf(classOf(instance)).reduce((properties: any, target: any) => {\n const store = Store.from(target);\n\n return {\n ...properties,\n ...(store.get(INJECTABLE_PROP) || {})\n };\n }, {});\n\n Object.values(properties).forEach((definition) => {\n switch (definition.bindingType) {\n case InjectablePropertyType.METHOD:\n this.bindMethod(instance, definition);\n break;\n case InjectablePropertyType.PROPERTY:\n this.bindProperty(instance, definition, locals, options);\n break;\n case InjectablePropertyType.CONSTANT:\n this.bindConstant(instance, definition);\n break;\n case InjectablePropertyType.VALUE:\n this.bindValue(instance, definition);\n break;\n case InjectablePropertyType.INTERCEPTOR:\n this.bindInterceptor(instance, definition);\n break;\n }\n });\n }\n\n /**\n * @param instance\n * @param {string} propertyKey\n */\n public bindMethod(instance: any, {propertyKey}: InjectablePropertyOptions) {\n const target = classOf(instance);\n const originalMethod = instance[propertyKey];\n const deps = Metadata.getParamTypes(prototypeOf(target), propertyKey);\n\n instance[propertyKey] = () => {\n const services = deps.map((dependency: any) => this.get(dependency));\n\n return originalMethod.call(instance, ...services);\n };\n }\n\n /**\n * Create an injectable property.\n *\n * @param instance\n * @param {string} propertyKey\n * @param {any} useType\n * @param resolver\n * @param options\n * @param locals\n * @param invokeOptions\n */\n public bindProperty(\n instance: any,\n {propertyKey, resolver, options = {}}: InjectablePropertyOptions,\n locals: LocalsContainer,\n invokeOptions: Partial<InvokeOptions>\n ) {\n let get: () => any;\n\n get = resolver(this, locals, {...invokeOptions, options});\n\n catchError(() =>\n Object.defineProperty(instance, propertyKey, {\n get\n })\n );\n }\n\n /**\n *\n * @param instance\n * @param {string} propertyKey\n * @param {any} useType\n */\n public bindValue(instance: any, {propertyKey, expression, defaultValue}: InjectablePropertyValue) {\n const descriptor = {\n get: () => this.settings.get(expression) || defaultValue,\n set: (value: any) => this.settings.set(expression, value),\n enumerable: true,\n configurable: true\n };\n\n catchError(() => Object.defineProperty(instance, propertyKey, descriptor));\n }\n\n /**\n *\n * @param instance\n * @param {string} propertyKey\n * @param {any} useType\n */\n public bindConstant(instance: any, {propertyKey, expression, defaultValue}: InjectablePropertyValue) {\n let bean: any;\n\n const get = () => {\n if (bean !== undefined) {\n return bean;\n }\n\n const value = this.settings.get(expression, defaultValue);\n bean = Object.freeze(deepClone(value));\n\n return bean;\n };\n\n const descriptor = {\n get,\n enumerable: true,\n configurable: true\n };\n\n catchError(() => Object.defineProperty(instance, propertyKey, descriptor));\n }\n\n /**\n *\n * @param instance\n * @param propertyKey\n * @param useType\n * @param options\n */\n public bindInterceptor(instance: any, {propertyKey, useType, options}: InjectablePropertyOptions) {\n const target = classOf(instance);\n const originalMethod = instance[propertyKey];\n\n instance[propertyKey] = (...args: any[]) => {\n const next = (err?: Error) => {\n if (!err) {\n return originalMethod.apply(instance, args);\n }\n\n throw err;\n };\n\n const context: InterceptorContext<any> = {\n target,\n propertyKey,\n args,\n options,\n next\n };\n\n const interceptor = this.get<InterceptorMethods>(useType)!;\n\n return interceptor.intercept!(\n {\n ...context,\n options\n },\n next\n );\n };\n }\n\n async lazyInvoke<T = any>(token: TokenProvider) {\n let instance = this.getInstance(token);\n\n if (!instance) {\n instance = await this.invoke<T>(token);\n\n if (isFunction(instance?.$onInit)) {\n await instance.$onInit();\n }\n }\n\n return instance;\n }\n\n /**\n * Emit an event to all service. See service [lifecycle hooks](/docs/services.md#lifecycle-hooks).\n * @param eventName The event name to emit at all services.\n * @param args List of the parameters to give to each service.\n * @returns {Promise<any[]>} A list of promises.\n */\n public async emit(eventName: string, ...args: any[]) {\n return this.#hooks.asyncEmit(eventName, args);\n }\n\n /**\n * @param eventName\n * @param value\n * @param args\n */\n public alter<T = any>(eventName: string, value: any, ...args: any[]): T {\n return this.#hooks.alter(eventName, value, args);\n }\n\n /**\n * @param eventName\n * @param value\n * @param args\n */\n public async alterAsync<T = any>(eventName: string, value: any, ...args: any[]): Promise<T> {\n return this.#hooks.asyncAlter(eventName, value, args);\n }\n\n async destroy() {\n await this.emit(\"$onDestroy\");\n }\n\n protected ensureProvider(token: TokenProvider): Provider | undefined {\n if (!this.hasProvider(token) && GlobalProviders.has(token)) {\n this.addProvider(token);\n }\n\n return this.getProvider(token)!;\n }\n\n protected getInstance(token: any) {\n return this.#cache.get(token);\n }\n\n /**\n * Invoke a class method and inject service.\n *\n * #### IInjectableMethod options\n *\n * * **target**: Optional. The class instance.\n * * **methodName**: `string` Optional. The method name.\n * * **designParamTypes**: `any[]` Optional. List of injectable types.\n * * **locals**: `Map<Function, any>` Optional. If preset then any argument Class are read from this object first, before the `InjectorService` is consulted.\n *\n * #### Example\n *\n * @param target\n * @param locals\n * @param options\n * @private\n */\n private resolve<T>(\n target: TokenProvider,\n locals: LocalsContainer = new LocalsContainer(),\n options: Partial<InvokeOptions<T>> = {}\n ): T | Promise<T> {\n const resolvedOpts = this.mapInvokeOptions(target, locals, options);\n const {token, deps, construct, imports, provider} = resolvedOpts;\n\n if (provider) {\n GlobalProviders.onInvoke(provider, locals, {...resolvedOpts, injector: this});\n }\n\n let instance: any;\n let currentDependency: any = false;\n\n try {\n const invokeDependency =\n (parent?: any) =>\n (token: any, index: number): any => {\n currentDependency = {token, index, deps};\n\n if (token !== DI_PARAM_OPTIONS) {\n const options = provider?.store?.get(`${DI_PARAM_OPTIONS}:${index}`);\n\n locals.set(DI_PARAM_OPTIONS, options || {});\n }\n\n return isInheritedFrom(token, Provider, 1) ? provider : this.invoke(token, locals, {parent});\n };\n\n // Invoke manually imported providers\n imports.forEach(invokeDependency());\n\n // Inject dependencies\n const services = deps.map(invokeDependency(token));\n\n currentDependency = false;\n\n instance = construct(services);\n } catch (error) {\n InjectionError.throwInjectorError(token, currentDependency, error);\n }\n\n if (instance === undefined) {\n throw new InjectionError(\n token,\n `Unable to create new instance from undefined value. Check your provider declaration for ${nameOf(token)}`\n );\n }\n\n if (instance && isClass(classOf(instance))) {\n this.bindInjectableProperties(instance, locals, options);\n }\n\n return instance;\n }\n\n /**\n * Create options to invoke a provider or class.\n * @param token\n * @param locals\n * @param options\n */\n private mapInvokeOptions(token: TokenProvider, locals: Map<TokenProvider, any>, options: Partial<InvokeOptions>): ResolvedInvokeOptions {\n let imports: TokenProvider[] | undefined = options.imports;\n let deps: TokenProvider[] | undefined = options.deps;\n let scope = options.scope;\n let construct;\n\n if (!token) {\n throw new UndefinedTokenError();\n }\n\n let provider: Provider;\n\n if (!this.hasProvider(token)) {\n provider = new Provider(token);\n\n this.resolvers.forEach((resolver) => {\n const result = resolver.get(token, locals.get(DI_PARAM_OPTIONS));\n\n if (result !== undefined) {\n provider.useFactory = () => result;\n }\n });\n } else {\n provider = this.getProvider(token)!;\n }\n\n scope = scope || this.scopeOf(provider);\n deps = deps || provider.deps;\n imports = imports || provider.imports;\n\n if (provider.useValue !== undefined) {\n construct = () => (isFunction(provider.useValue) ? provider.useValue() : provider.useValue);\n } else if (provider.useFactory) {\n construct = (deps: TokenProvider[]) => provider.useFactory(...deps);\n } else if (provider.useAsyncFactory) {\n construct = async (deps: TokenProvider[]) => {\n deps = await Promise.all(deps);\n return provider.useAsyncFactory(...deps);\n };\n } else {\n // useClass\n deps = deps || Metadata.getParamTypes(provider.useClass);\n construct = (deps: TokenProvider[]) => new provider.useClass(...deps);\n }\n\n return {\n token,\n scope: scope || Store.from(token).get(\"scope\") || ProviderScope.SINGLETON,\n deps: deps! || [],\n imports: imports || [],\n construct,\n provider\n };\n }\n\n private registerHooks(provider: Provider, instance: any) {\n if (provider.hooks) {\n Object.entries(provider.hooks).forEach(([event, cb]) => {\n const callback = (...args: any[]) => cb(this.get(provider.token) || instance, ...args);\n\n this.#hooks.on(event, callback);\n });\n }\n }\n}\n"]}
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.bindContext = exports.setContext = exports.runInContext = exports.getContext = exports.useContextRef = exports.getAsyncStore = void 0;
4
+ const async_hooks_1 = require("async_hooks");
5
+ const storage = new async_hooks_1.AsyncLocalStorage();
6
+ function getAsyncStore() {
7
+ return storage;
8
+ }
9
+ exports.getAsyncStore = getAsyncStore;
10
+ function useContextRef() {
11
+ return getAsyncStore().getStore();
12
+ }
13
+ exports.useContextRef = useContextRef;
14
+ function getContext() {
15
+ return useContextRef()?.current;
16
+ }
17
+ exports.getContext = getContext;
18
+ async function runInContext(ctx, cb, injector) {
19
+ const ref = useContextRef();
20
+ if (ref) {
21
+ ctx && setContext(ctx);
22
+ return cb();
23
+ }
24
+ else {
25
+ injector = ctx?.injector || injector;
26
+ cb = (await injector?.alterAsync("$alterRunInContext", cb)) || cb;
27
+ return storage.run({ current: ctx }, cb);
28
+ }
29
+ }
30
+ exports.runInContext = runInContext;
31
+ function setContext(ctx) {
32
+ const ref = useContextRef();
33
+ if (ref && !ref.current) {
34
+ ref.current = ctx;
35
+ }
36
+ }
37
+ exports.setContext = setContext;
38
+ function bindContext(cb) {
39
+ return async_hooks_1.AsyncResource.bind(cb);
40
+ }
41
+ exports.bindContext = bindContext;
42
+ //# sourceMappingURL=asyncHookContext.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"asyncHookContext.js","sourceRoot":"","sources":["../../../src/utils/asyncHookContext.ts"],"names":[],"mappings":";;;AAAA,6CAA6D;AAI7D,MAAM,OAAO,GAAwD,IAAI,+BAAiB,EAAE,CAAC;AAE7F,SAAgB,aAAa;IAC3B,OAAO,OAAO,CAAC;AACjB,CAAC;AAFD,sCAEC;AAED,SAAgB,aAAa;IAC3B,OAAO,aAAa,EAAE,CAAC,QAAQ,EAAE,CAAC;AACpC,CAAC;AAFD,sCAEC;AAED,SAAgB,UAAU;IACxB,OAAO,aAAa,EAAE,EAAE,OAAc,CAAC;AACzC,CAAC;AAFD,gCAEC;AAEM,KAAK,UAAU,YAAY,CAAC,GAA0B,EAAE,EAAO,EAAE,QAA0B;IAChG,MAAM,GAAG,GAAG,aAAa,EAAE,CAAC;IAE5B,IAAI,GAAG,EAAE;QACP,GAAG,IAAI,UAAU,CAAC,GAAG,CAAC,CAAC;QACvB,OAAO,EAAE,EAAE,CAAC;KACb;SAAM;QACL,QAAQ,GAAG,GAAG,EAAE,QAAQ,IAAI,QAAQ,CAAC;QACrC,EAAE,GAAG,CAAC,MAAM,QAAQ,EAAE,UAAU,CAAC,oBAAoB,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;QAElE,OAAO,OAAO,CAAC,GAAG,CAAC,EAAC,OAAO,EAAE,GAAG,EAAC,EAAE,EAAE,CAAC,CAAC;KACxC;AACH,CAAC;AAZD,oCAYC;AAED,SAAgB,UAAU,CAAC,GAAc;IACvC,MAAM,GAAG,GAAG,aAAa,EAAE,CAAC;IAE5B,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,OAAO,EAAE;QACvB,GAAG,CAAC,OAAO,GAAG,GAAG,CAAC;KACnB;AACH,CAAC;AAND,gCAMC;AAED,SAAgB,WAAW,CAAC,EAAO;IACjC,OAAO,2BAAa,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AAChC,CAAC;AAFD,kCAEC","sourcesContent":["import {AsyncLocalStorage, AsyncResource} from \"async_hooks\";\nimport type {DIContext} from \"../domain/DIContext\";\nimport type {InjectorService} from \"../services/InjectorService\";\n\nconst storage: AsyncLocalStorage<{current: DIContext | undefined}> = new AsyncLocalStorage();\n\nexport function getAsyncStore() {\n return storage;\n}\n\nexport function useContextRef() {\n return getAsyncStore().getStore();\n}\n\nexport function getContext<Context = DIContext>(): Context | undefined {\n return useContextRef()?.current as any;\n}\n\nexport async function runInContext(ctx: DIContext | undefined, cb: any, injector?: InjectorService) {\n const ref = useContextRef();\n\n if (ref) {\n ctx && setContext(ctx);\n return cb();\n } else {\n injector = ctx?.injector || injector;\n cb = (await injector?.alterAsync(\"$alterRunInContext\", cb)) || cb;\n\n return storage.run({current: ctx}, cb);\n }\n}\n\nexport function setContext(ctx: DIContext) {\n const ref = useContextRef();\n\n if (ref && !ref.current) {\n ref.current = ctx;\n }\n}\n\nexport function bindContext(cb: any) {\n return AsyncResource.bind(cb);\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { decoratorTypeOf, DecoratorTypes, isPromise, Metadata, Store, UnsupportedDecoratorType } from "@tsed/core";
2
2
  import { DI_PARAM_OPTIONS, INJECTABLE_PROP } from "../constants/constants.js";
3
- import { getContext } from "../utils/runInContext.js";
3
+ import { getContext } from "../utils/asyncHookContext.js";
4
4
  export function injectProperty(target, propertyKey, options) {
5
5
  Store.from(target).merge(INJECTABLE_PROP, {
6
6
  [propertyKey]: {
@@ -1 +1 @@
1
- {"version":3,"file":"inject.js","sourceRoot":"","sources":["../../../src/decorators/inject.ts"],"names":[],"mappings":"AAAA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;SACF,CAAC,CAAC;IACL,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import {decoratorTypeOf, DecoratorTypes, isPromise, Metadata, Store, UnsupportedDecoratorType} from \"@tsed/core\";\nimport {DI_PARAM_OPTIONS, INJECTABLE_PROP} from \"../constants/constants\";\nimport type {InjectablePropertyOptions} from \"../interfaces/InjectableProperties\";\nimport {getContext} from \"../utils/runInContext\";\n\nexport function injectProperty(target: any, propertyKey: string, options: Partial<InjectablePropertyOptions>) {\n Store.from(target).merge(INJECTABLE_PROP, {\n [propertyKey]: {\n bindingType: DecoratorTypes.PROP,\n propertyKey,\n ...options\n }\n });\n}\n\n/**\n * Inject a provider to another provider.\n *\n * Use this decorator to inject a custom provider on constructor parameter or property.\n *\n * ```typescript\n * @Injectable()\n * export class MyService {\n * @Inject(CONNECTION)\n * connection: CONNECTION;\n * }\n * ```\n *\n * @param symbol\n * @param onGet Use the given name method to inject\n * @returns {Function}\n * @decorator\n */\nexport function Inject(symbol?: any, onGet = (bean: any) => bean): Function {\n return (target: any, propertyKey: string, descriptor: TypedPropertyDescriptor<Function> | number): any | void => {\n const bindingType = decoratorTypeOf([target, propertyKey, descriptor]);\n\n switch (bindingType) {\n case DecoratorTypes.PARAM:\n case DecoratorTypes.PARAM_CTOR:\n if (symbol) {\n const paramTypes = Metadata.getParamTypes(target, propertyKey);\n\n paramTypes[descriptor as number] = symbol;\n Metadata.setParamTypes(target, propertyKey, paramTypes);\n }\n break;\n\n case DecoratorTypes.PROP:\n injectProperty(target, propertyKey, {\n resolver(injector, locals, {options, ...invokeOptions}) {\n locals.set(DI_PARAM_OPTIONS, {...options});\n\n let bean: any;\n\n if (!bean) {\n const useType = symbol || Metadata.getType(target, propertyKey);\n bean = injector.invoke(useType, locals, invokeOptions);\n locals.delete(DI_PARAM_OPTIONS);\n }\n\n if (isPromise(bean)) {\n bean.then((result: any) => {\n bean = result;\n });\n }\n\n return () => onGet(bean);\n }\n });\n break;\n\n case DecoratorTypes.METHOD:\n Store.from(target).merge(INJECTABLE_PROP, {\n [propertyKey]: {\n bindingType,\n propertyKey\n }\n });\n\n return descriptor;\n\n default:\n throw new UnsupportedDecoratorType(Inject, [target, propertyKey, descriptor]);\n }\n };\n}\n\n/**\n * Inject a context like PlatformContext or any BaseContext.\n *\n * ```typescript\n * @Injectable()\n * export class MyService {\n * @InjectContext()\n * ctx?: Context;\n * }\n * ```\n *\n * @returns {Function}\n * @decorator\n */\nexport function InjectContext(): PropertyDecorator {\n return (target: any, propertyKey: string): any | void => {\n injectProperty(target, propertyKey, {\n resolver() {\n return () => getContext();\n }\n });\n };\n}\n"]}
1
+ {"version":3,"file":"inject.js","sourceRoot":"","sources":["../../../src/decorators/inject.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,eAAe,EAAE,cAAc,EAAE,SAAS,EAAE,QAAQ,EAAE,KAAK,EAAE,wBAAwB,EAAC,MAAM,YAAY,CAAC;AACjH,OAAO,EAAC,gBAAgB,EAAE,eAAe,EAAC,MAAM,wBAAwB,CAAC;AAEzE,OAAO,EAAC,UAAU,EAAC,MAAM,2BAA2B,CAAC;AAErD,MAAM,UAAU,cAAc,CAAC,MAAW,EAAE,WAAmB,EAAE,OAA2C;IAC1G,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,CAAC,eAAe,EAAE;QACxC,CAAC,WAAW,CAAC,EAAE;YACb,WAAW,EAAE,cAAc,CAAC,IAAI;YAChC,WAAW;YACX,GAAG,OAAO;SACX;KACF,CAAC,CAAC;AACL,CAAC;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,UAAU,MAAM,CAAC,MAAY,EAAE,QAAQ,CAAC,IAAS,EAAE,EAAE,CAAC,IAAI;IAC9D,OAAO,CAAC,MAAW,EAAE,WAAmB,EAAE,UAAsD,EAAc,EAAE;QAC9G,MAAM,WAAW,GAAG,eAAe,CAAC,CAAC,MAAM,EAAE,WAAW,EAAE,UAAU,CAAC,CAAC,CAAC;QAEvE,QAAQ,WA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xC,CAAC,WAAW,CAAC,EAAE;wBACb,WAAW;wBACX,WAAW;qBACZ;iBACF,CAAC,CAAC;gBAEH,OAAO,UAAU,CAAC;YAEpB;gBACE,MAAM,IAAI,wBAAwB,CAAC,MAAM,EAAE,CAAC,MAAM,EAAE,WAAW,EAAE,UAAU,CAAC,CAAC,CAAC;SACjF;IACH,CAAC,CAAC;AACJ,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,aAAa;IAC3B,OAAO,CAAC,MAAW,EAAE,WAAmB,EAAc,EAAE;QACtD,cAAc,CAAC,MAAM,EAAE,WAAW,EAAE;YAClC,QAAQ;gBACN,OAAO,GAAG,EAAE,CAAC,UAAU,EAAE,CAAC;YAC5B,CAAC;SACF,CAAC,CAAC;IACL,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import {decoratorTypeOf, DecoratorTypes, isPromise, Metadata, Store, UnsupportedDecoratorType} from \"@tsed/core\";\nimport {DI_PARAM_OPTIONS, INJECTABLE_PROP} from \"../constants/constants\";\nimport type {InjectablePropertyOptions} from \"../interfaces/InjectableProperties\";\nimport {getContext} from \"../utils/asyncHookContext\";\n\nexport function injectProperty(target: any, propertyKey: string, options: Partial<InjectablePropertyOptions>) {\n Store.from(target).merge(INJECTABLE_PROP, {\n [propertyKey]: {\n bindingType: DecoratorTypes.PROP,\n propertyKey,\n ...options\n }\n });\n}\n\n/**\n * Inject a provider to another provider.\n *\n * Use this decorator to inject a custom provider on constructor parameter or property.\n *\n * ```typescript\n * @Injectable()\n * export class MyService {\n * @Inject(CONNECTION)\n * connection: CONNECTION;\n * }\n * ```\n *\n * @param symbol\n * @param onGet Use the given name method to inject\n * @returns {Function}\n * @decorator\n */\nexport function Inject(symbol?: any, onGet = (bean: any) => bean): Function {\n return (target: any, propertyKey: string, descriptor: TypedPropertyDescriptor<Function> | number): any | void => {\n const bindingType = decoratorTypeOf([target, propertyKey, descriptor]);\n\n switch (bindingType) {\n case DecoratorTypes.PARAM:\n case DecoratorTypes.PARAM_CTOR:\n if (symbol) {\n const paramTypes = Metadata.getParamTypes(target, propertyKey);\n\n paramTypes[descriptor as number] = symbol;\n Metadata.setParamTypes(target, propertyKey, paramTypes);\n }\n break;\n\n case DecoratorTypes.PROP:\n injectProperty(target, propertyKey, {\n resolver(injector, locals, {options, ...invokeOptions}) {\n locals.set(DI_PARAM_OPTIONS, {...options});\n\n let bean: any;\n\n if (!bean) {\n const useType = symbol || Metadata.getType(target, propertyKey);\n bean = injector.invoke(useType, locals, invokeOptions);\n locals.delete(DI_PARAM_OPTIONS);\n }\n\n if (isPromise(bean)) {\n bean.then((result: any) => {\n bean = result;\n });\n }\n\n return () => onGet(bean);\n }\n });\n break;\n\n case DecoratorTypes.METHOD:\n Store.from(target).merge(INJECTABLE_PROP, {\n [propertyKey]: {\n bindingType,\n propertyKey\n }\n });\n\n return descriptor;\n\n default:\n throw new UnsupportedDecoratorType(Inject, [target, propertyKey, descriptor]);\n }\n };\n}\n\n/**\n * Inject a context like PlatformContext or any BaseContext.\n *\n * ```typescript\n * @Injectable()\n * export class MyService {\n * @InjectContext()\n * ctx?: Context;\n * }\n * ```\n *\n * @returns {Function}\n * @decorator\n */\nexport function InjectContext(): PropertyDecorator {\n return (target: any, propertyKey: string): any | void => {\n injectProperty(target, propertyKey, {\n resolver() {\n return () => getContext();\n }\n });\n };\n}\n"]}
@@ -2,28 +2,21 @@ import { Hooks } from "@tsed/core";
2
2
  import { levels } from "@tsed/logger";
3
3
  const LEVELS = levels();
4
4
  export class ContextLogger {
5
- $ctx;
6
5
  dateStart;
6
+ id;
7
7
  #additionalProps;
8
+ maxStackSize;
9
+ level;
8
10
  #hooks;
9
- #maxStackSize;
10
11
  #stack;
11
- #level;
12
12
  #logger;
13
- constructor($ctx) {
14
- this.$ctx = $ctx;
15
- const { logger, dateStart = new Date(), level = "all", maxStackSize = 30, additionalProps } = $ctx.opts;
13
+ constructor({ id, logger, dateStart = new Date(), level = "all", maxStackSize = 30, additionalProps }) {
16
14
  this.dateStart = dateStart;
15
+ this.id = id;
17
16
  this.#logger = logger;
18
17
  this.#additionalProps = additionalProps;
19
- this.#level = (LEVELS[level.toUpperCase()] || LEVELS.ALL);
20
- this.#maxStackSize = maxStackSize;
21
- }
22
- get id() {
23
- return this.$ctx.id;
24
- }
25
- set maxStackSize(maxStackSize) {
26
- this.#maxStackSize = maxStackSize;
18
+ this.level = (LEVELS[level.toUpperCase()] || LEVELS.ALL);
19
+ this.maxStackSize = maxStackSize;
27
20
  }
28
21
  get hooks() {
29
22
  return (this.#hooks = this.#hooks || new Hooks());
@@ -66,13 +59,7 @@ export class ContextLogger {
66
59
  }
67
60
  }
68
61
  isLevelEnabled(otherLevel) {
69
- return this.#level.isLessThanOrEqualTo(otherLevel);
70
- }
71
- destroy() {
72
- this.flush();
73
- this.#maxStackSize = 0;
74
- this.#stack = [];
75
- this.#logger = null;
62
+ return this.level.isLessThanOrEqualTo(otherLevel);
76
63
  }
77
64
  /**
78
65
  * Return the duration between the time when LogIncomingRequest has handle the request and now.
@@ -97,7 +84,7 @@ export class ContextLogger {
97
84
  obj = this.hooks.alter("log", this.getData(obj), [levelStr, withRequest]);
98
85
  this.stack.push({ level: levelStr, data: obj });
99
86
  }
100
- if (this.#maxStackSize < this.stack.length) {
87
+ if (this.maxStackSize < this.stack.length) {
101
88
  this.flush();
102
89
  }
103
90
  }
@@ -1 +1 @@
1
- {"version":3,"file":"ContextLogger.js","sourceRoot":"","sources":["../../../src/domain/ContextLogger.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,KAAK,EAAC,MAAM,YAAY,CAAC;AACjC,OAAO,EAAC,MAAM,EAAW,MAAM,cAAc,CAAC;AAY9C,MAAM,MAAM,GAA6B,MAAM,EAAE,CAAC;AAElD,MAAM,OAAO,aAAa;IAUH;IATZ,SAAS,CAAO;IAChB,gBAAgB,CAA2B;IAEpD,MAAM,CAAS;IACf,aAAa,CAAS;IACtB,MAAM,CAAS;IACf,MAAM,CAAW;IACjB,OAAO,C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LogLevel} from \"@tsed/logger\";\nimport {DILogger} from \"../interfaces/DILogger\";\nimport type {DIContext} from \"./DIContext\";\n\nexport interface ContextLoggerOptions extends Record<string, any> {\n id: string;\n logger?: DILogger;\n level?: \"debug\" | \"info\" | \"warn\" | \"error\" | \"off\" | \"all\";\n maxStackSize?: number;\n additionalProps?: Record<any, any>;\n}\n\nconst LEVELS: Record<string, LogLevel> = levels();\n\nexport class ContextLogger {\n readonly dateStart: Date;\n readonly #additionalProps?: Record<string, unknown>;\n\n #hooks?: Hooks;\n #maxStackSize: number;\n #stack?: any[];\n #level: LogLevel;\n #logger: any;\n\n constructor(readonly $ctx: DIContext) {\n const {logger, dateStart = new Date(), level = \"all\", maxStackSize = 30, additionalProps} = $ctx.opts;\n this.dateStart = dateStart;\n this.#logger = logger;\n this.#additionalProps = additionalProps;\n this.#level = (LEVELS[level.toUpperCase()] || LEVELS.ALL) as LogLevel;\n this.#maxStackSize = maxStackSize;\n }\n\n get id() {\n return this.$ctx.id;\n }\n\n set maxStackSize(maxStackSize: number) {\n this.#maxStackSize = maxStackSize;\n }\n\n get hooks() {\n return (this.#hooks = this.#hooks || new Hooks());\n }\n\n private get stack() {\n return (this.#stack = this.#stack || []);\n }\n\n alterLog(cb: (data: any, level: \"debug\" | \"info\" | \"warn\" | \"error\" | \"off\" | \"all\", withRequest: boolean) => any) {\n return this.hooks.on(\"log\", cb);\n }\n\n alterIgnoreLog(cb: (ignore: boolean, data: any) => boolean) {\n return this.hooks.on(\"ignore\", cb);\n }\n\n info(obj: any) {\n this.run(levels().INFO, obj);\n return this;\n }\n\n debug(obj: any, withRequest: boolean = true) {\n this.run(levels().DEBUG, obj, withRequest);\n return this;\n }\n\n warn(obj: any) {\n this.run(levels().WARN, obj);\n return this;\n }\n\n error(obj: any) {\n this.run(levels().ERROR, obj);\n return this;\n }\n\n trace(obj: any) {\n this.run(levels().TRACE, obj);\n return this;\n }\n\n public flush() {\n if (this.stack.length) {\n this.stack.forEach(({level, data}: any) => {\n this.#logger[level](data);\n });\n\n this.#stack = [];\n }\n }\n\n public isLevelEnabled(otherLevel: string | LogLevel) {\n return this.#level.isLessThanOrEqualTo(otherLevel);\n }\n\n destroy() {\n this.flush();\n this.#maxStackSize = 0;\n this.#stack = [];\n this.#logger = null;\n }\n\n /**\n * Return the duration between the time when LogIncomingRequest has handle the request and now.\n * @returns {number}\n */\n protected getDuration(): number {\n return new Date().getTime() - this.dateStart.getTime();\n }\n\n protected getData(obj: any) {\n if (typeof obj === \"string\") {\n obj = {message: obj};\n }\n\n return {...this.#additionalProps, reqId: this.id, time: new Date(), duration: this.getDuration(), ...obj};\n }\n\n protected run(level: LogLevel, obj: any, withRequest?: boolean) {\n if (!this.isLevelEnabled(level)) {\n return;\n }\n\n const ignore = this.#hooks?.alter(\"ignore\", false, [obj]);\n\n if (!ignore) {\n const levelStr = level.levelStr.toLowerCase();\n\n obj = this.hooks.alter(\"log\", this.getData(obj), [levelStr, withRequest]);\n\n this.stack.push({level: levelStr, data: obj});\n }\n\n if (this.#maxStackSize < this.stack.length) {\n this.flush();\n }\n }\n}\n"]}
1
+ {"version":3,"file":"ContextLogger.js","sourceRoot":"","sources":["../../../src/domain/ContextLogger.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,KAAK,EAAC,MAAM,YAAY,CAAC;AACjC,OAAO,EAAC,MAAM,EAAW,MAAM,cAAc,CAAC;AAY9C,MAAM,MAAM,GAA6B,MAAM,EAAE,CAAC;AAElD,MAAM,OAAO,aAAa;IACf,SAAS,CAAO;IAChB,EAAE,CAAS;IACX,gBAAgB,CAA2B;IAEpD,YAAY,CAAS;IACrB,KAAK,CAAW;IAEhB,MAAM,CAAS;IACf,MAAM,CAAS;IACf,OAAO,CAAM;IAEb,YAAY,EAAC,EAAE,EAAE,MAAM,EAAE,SAAS,GAAG,IAAI,IAAI,EAAE,EAAE,KAAK,GAAG,KAAK,EAAE,YAAY,GAAG,EAAE,EAAE,eAAe,EAAuB;QACvH,IAAI,CAAC,SAA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CAAC,KAAK,CAAC,EAAE;YAC/B,OAAO;SACR;QAED,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,QAAQ,EAAE,KAAK,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;QAE1D,IAAI,CAAC,MAAM,EAAE;YACX,MAAM,QAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC;YAE9C,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,EAAE,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,QAAQ,EAAE,WAAW,CAAC,CAAC,CAAC;YAE1E,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAC,KAAK,EAAE,QAAQ,EAAE,IAAI,EAAE,GAAG,EAAC,CAAC,CAAC;SAC/C;QAED,IAAI,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE;YACzC,IAAI,CAAC,KAAK,EAAE,CAAC;SACd;IACH,CAAC;CACF","sourcesContent":["import {Hooks} from \"@tsed/core\";\nimport {levels, LogLevel} from \"@tsed/logger\";\nimport {DILogger} from \"../interfaces/DILogger\";\nimport type {DIContext} from \"./DIContext\";\n\nexport interface ContextLoggerOptions extends Record<string, any> {\n id: string;\n logger?: DILogger;\n level?: \"debug\" | \"info\" | \"warn\" | \"error\" | \"off\" | \"all\";\n maxStackSize?: number;\n additionalProps?: Record<any, any>;\n}\n\nconst LEVELS: Record<string, LogLevel> = levels();\n\nexport class ContextLogger {\n readonly dateStart: Date;\n readonly id: string;\n readonly #additionalProps?: Record<string, unknown>;\n\n maxStackSize: number;\n level: LogLevel;\n\n #hooks?: Hooks;\n #stack?: any[];\n #logger: any;\n\n constructor({id, logger, dateStart = new Date(), level = \"all\", maxStackSize = 30, additionalProps}: ContextLoggerOptions) {\n this.dateStart = dateStart;\n this.id = id;\n this.#logger = logger;\n this.#additionalProps = additionalProps;\n this.level = (LEVELS[level.toUpperCase()] || LEVELS.ALL) as LogLevel;\n this.maxStackSize = maxStackSize;\n }\n\n get hooks() {\n return (this.#hooks = this.#hooks || new Hooks());\n }\n\n private get stack() {\n return (this.#stack = this.#stack || []);\n }\n\n alterLog(cb: (data: any, level: \"debug\" | \"info\" | \"warn\" | \"error\" | \"off\" | \"all\", withRequest: boolean) => any) {\n return this.hooks.on(\"log\", cb);\n }\n\n alterIgnoreLog(cb: (ignore: boolean, data: any) => boolean) {\n return this.hooks.on(\"ignore\", cb);\n }\n\n info(obj: any) {\n this.run(levels().INFO, obj);\n return this;\n }\n\n debug(obj: any, withRequest: boolean = true) {\n this.run(levels().DEBUG, obj, withRequest);\n return this;\n }\n\n warn(obj: any) {\n this.run(levels().WARN, obj);\n return this;\n }\n\n error(obj: any) {\n this.run(levels().ERROR, obj);\n return this;\n }\n\n trace(obj: any) {\n this.run(levels().TRACE, obj);\n return this;\n }\n\n public flush() {\n if (this.stack.length) {\n this.stack.forEach(({level, data}: any) => {\n this.#logger[level](data);\n });\n\n this.#stack = [];\n }\n }\n\n public isLevelEnabled(otherLevel: string | LogLevel) {\n return this.level.isLessThanOrEqualTo(otherLevel);\n }\n\n /**\n * Return the duration between the time when LogIncomingRequest has handle the request and now.\n * @returns {number}\n */\n protected getDuration(): number {\n return new Date().getTime() - this.dateStart.getTime();\n }\n\n protected getData(obj: any) {\n if (typeof obj === \"string\") {\n obj = {message: obj};\n }\n\n return {...this.#additionalProps, reqId: this.id, time: new Date(), duration: this.getDuration(), ...obj};\n }\n\n protected run(level: LogLevel, obj: any, withRequest?: boolean) {\n if (!this.isLevelEnabled(level)) {\n return;\n }\n\n const ignore = this.#hooks?.alter(\"ignore\", false, [obj]);\n\n if (!ignore) {\n const levelStr = level.levelStr.toLowerCase();\n\n obj = this.hooks.alter(\"log\", this.getData(obj), [levelStr, withRequest]);\n\n this.stack.push({level: levelStr, data: obj});\n }\n\n if (this.maxStackSize < this.stack.length) {\n this.flush();\n }\n }\n}\n"]}
@@ -1,22 +1,20 @@
1
- import { runInContext } from "../utils/runInContext.js";
1
+ import { runInContext } from "../utils/asyncHookContext.js";
2
2
  import { ContextLogger } from "./ContextLogger.js";
3
3
  import { LocalsContainer } from "./LocalsContainer.js";
4
- export class DIContext extends Map {
5
- options;
4
+ export class DIContext {
6
5
  opts;
7
- /**
8
- * The request container used by the Ts.ED DI. It contain all services annotated with `@Scope(ProviderScope.REQUEST)`
9
- */
10
- container = new LocalsContainer();
6
+ #container;
7
+ #cache;
8
+ #logger;
9
+ constructor(opts) {
10
+ this.opts = opts;
11
+ }
11
12
  /**
12
13
  * Logger attached to the context request.
13
14
  */
14
- logger;
15
- constructor(options) {
16
- super();
17
- this.options = options;
18
- this.opts = options;
19
- this.logger = new ContextLogger(this);
15
+ get logger() {
16
+ this.#logger = this.#logger || new ContextLogger(this.opts);
17
+ return this.#logger;
20
18
  }
21
19
  /**
22
20
  * Request id generated by @@contextMiddleware@@.
@@ -54,20 +52,46 @@ export class DIContext extends Map {
54
52
  get env() {
55
53
  return this.injector.settings.get("env");
56
54
  }
55
+ /**
56
+ * The request container used by the Ts.ED DI. It contains all services annotated with `@Scope(ProviderScope.REQUEST)`
57
+ */
58
+ get container() {
59
+ return (this.#container = this.#container || new LocalsContainer());
60
+ }
57
61
  async destroy() {
58
- await this.container.destroy();
59
- this.logger.destroy();
60
- this.opts = {
61
- id: this.opts.id
62
- };
63
- this.container = null;
62
+ return Promise.all([this.#container?.destroy(), this.#logger?.flush()]);
64
63
  }
65
64
  async emit(eventName, ...args) {
66
65
  return this.injector?.emit(eventName, ...args);
67
66
  }
68
67
  async runInContext(next) {
69
- next = (await this.injector?.alterAsync("$alterRunInContext", next, this)) || next;
70
68
  return runInContext(this, next);
71
69
  }
70
+ cache(key, cb) {
71
+ if (!this.has(key)) {
72
+ this.set(key, cb());
73
+ }
74
+ return this.get(key);
75
+ }
76
+ async cacheAsync(key, cb) {
77
+ if (!this.has(key)) {
78
+ this.set(key, await cb());
79
+ }
80
+ return this.get(key);
81
+ }
82
+ delete(key) {
83
+ return !!this.#cache?.delete(key);
84
+ }
85
+ get(key) {
86
+ return this.#cache?.get(key);
87
+ }
88
+ has(key) {
89
+ return !!this.#cache?.has(key);
90
+ }
91
+ set(key, value) {
92
+ this.#cache = this.#cache || new Map();
93
+ this.#cache.set(key, value);
94
+ return this;
95
+ }
72
96
  }
73
97
  //# sourceMappingURL=DIContext.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"DIContext.js","sourceRoot":"","sources":["../../../src/domain/DIContext.ts"],"names":[],"mappings":"AAEA,OAAO,EAAC,YAAY,EAAC,MAAM,uBAAuB,CAAC;AACnD,OAAO,EAAC,aAAa,EAAuB,MAAM,iBAAiB,CAAC;AACpE,OAAO,EAAC,eAAe,EAAC,MAAM,mBAAmB,CAAC;AAkBlD,MAAM,OAAO,SAAU,SAAQ,GAAa;IAcrB;IAXrB,IAAI,CAAmB;IAEvB;;OAEG;IACI,SAAS,GAAG,IAAI,eAAe,EAAO,CAAC;IAC9C;;OAEG;IACM,MAAM,CAAgB;IAE/B,YAAqB,OAAyB;QAC5C,KAAK,EAAE,CAAC;QADW,YAAO,GAAP,OAAO,CAAkB;QAE5C,IAAI,CAAC,IAAI,GAAG,OAAO,CAAC;QACpB,IAAI,CAAC,MAAM,GAAG,IAAI,aAAa,CAAC,IAAI,CAAC,CAAC;IACxC,CAAC;IAED;;;;;;;;;;;;;;;;;;;;;;;OAuBG;IACH,IAAI,EAAE;QACJ,OAAO,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;IACtB,CAAC;IAED,IAAI,SAAS;QACX,OAAO,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC;IAC/B,CAAC;IAED,IAAI,QAAQ;QACV,OAAO,IAAI,CAAC,IAAI,CAAC,QAAS,CAAC;IAC7B,CAAC;IAED,IAAI,GAAG;QACL,OAAO,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IAC3C,CAAC;IAED,KAAK,CAAC,OAAO;QACX,MAAM,IAAI,CAAC,SAAS,CAAC,OAAO,EAAE,CAAC;QAC/B,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;QACtB,IAAI,CAAC,IAAI,GAAG;YACV,EAAE,EAAE,IAAI,CAAC,IAAI,CAAC,EAAE;SACV,CAAC;QACT,IAAI,CAAC,SAAS,GAAG,IAAW,CAAC;IAC/B,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,SAAiB,EAAE,GAAG,IAAW;QAC1C,OAAO,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,SAAS,EAAE,GAAG,IAAI,CAAC,CAAC;IACjD,CAAC;IAED,KAAK,CAAC,YAAY,CAAC,IAAc;QAC/B,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,QAAQ,EAAE,UAAU,CAAC,oBAAoB,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,IAAI,IAAI,CAAC;QAEnF,OAAO,YAAY,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAClC,CAAC;CACF","sourcesContent":["import type {Env} from \"@tsed/core\";\nimport {InjectorService} from \"../services/InjectorService\";\nimport {runInContext} from \"../utils/runInContext\";\nimport {ContextLogger, ContextLoggerOptions} from \"./ContextLogger\";\nimport {LocalsContainer} from \"./LocalsContainer\";\n\nexport interface ContextMethods extends Map<any, any> {\n readonly id: string;\n readonly logger: ContextLogger;\n readonly injector: InjectorService;\n readonly container: LocalsContainer;\n readonly env: Env;\n\n destroy(): any;\n}\n\nexport interface DIContextOptions extends Omit<ContextLoggerOptions, \"dateStart\"> {\n id: string;\n injector: InjectorService;\n logger: any;\n}\n\nexport class DIContext extends Map<any, any> implements ContextMethods {\n [x: string]: any;\n\n opts: DIContextOptions;\n\n /**\n * The request container used by the Ts.ED DI. It contain all services annotated with `@Scope(ProviderScope.REQUEST)`\n */\n public container = new LocalsContainer<any>();\n /**\n * Logger attached to the context request.\n */\n readonly logger: ContextLogger;\n\n constructor(readonly options: DIContextOptions) {\n super();\n this.opts = options;\n this.logger = new ContextLogger(this);\n }\n\n /**\n * Request id generated by @@contextMiddleware@@.\n *\n * ::: tip\n * By default Ts.ED generate uuid like that `uuidv4().replace(/-/gi, \"\"))`.\n * Dash are removed to simplify tracking logs in Kibana\n * :::\n *\n * ::: tip\n * Request id can by customized by changing the server configuration.\n *\n * ```typescript\n * @Configuration({\n * logger: {\n * reqIdBuilder: createUniqId // give your own id generator function\n * }\n * })\n * class Server {\n *\n * }\n * ```\n * :::\n *\n */\n get id() {\n return this.opts.id;\n }\n\n get dateStart() {\n return this.logger.dateStart;\n }\n\n get injector(): InjectorService {\n return this.opts.injector!;\n }\n\n get env() {\n return this.injector.settings.get(\"env\");\n }\n\n async destroy() {\n await this.container.destroy();\n this.logger.destroy();\n this.opts = {\n id: this.opts.id\n } as any;\n this.container = null as any;\n }\n\n async emit(eventName: string, ...args: any[]) {\n return this.injector?.emit(eventName, ...args);\n }\n\n async runInContext(next: Function) {\n next = (await this.injector?.alterAsync(\"$alterRunInContext\", next, this)) || next;\n\n return runInContext(this, next);\n }\n}\n\nexport type BaseContext = DIContext & TsED.Context;\n"]}
1
+ {"version":3,"file":"DIContext.js","sourceRoot":"","sources":["../../../src/domain/DIContext.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,YAAY,EAAC,MAAM,2BAA2B,CAAC;AACvD,OAAO,EAAC,aAAa,EAAuB,MAAM,iBAAiB,CAAC;AACpE,OAAO,EAAC,eAAe,EAAC,MAAM,mBAAmB,CAAC;AAQlD,MAAM,OAAO,SAAS;IAOD;IAJnB,UAAU,CAAmB;IAC7B,MAAM,CAAiB;IACvB,OAAO,CAAiB;IAExB,YAAmB,IAAsB;QAAtB,SAAI,GAAJ,IAAI,CAAkB;IAAG,CAAC;IAE7C;;OAEG;IACH,IAAI,MAAM;QACR,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,IAAI,IAAI,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC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,KAAK,CAAC,UAAU,CAAc,GAAW,EAAE,EAAwB;QACjE,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE;YAClB,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE,CAAC,CAAC;SAC3B;QAED,OAAO,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACvB,CAAC;IAED,MAAM,CAAC,GAAQ;QACb,OAAO,CAAC,CAAC,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC;IACpC,CAAC;IAED,GAAG,CAAU,GAAQ;QACnB,OAAO,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC;IAC/B,CAAC;IAED,GAAG,CAAC,GAAQ;QACV,OAAO,CAAC,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC;IACjC,CAAC;IAED,GAAG,CAAC,GAAQ,EAAE,KAAU;QACtB,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,IAAI,IAAI,GAAG,EAAY,CAAC;QACjD,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QAC5B,OAAO,IAAI,CAAC;IACd,CAAC;CACF","sourcesContent":["import {InjectorService} from \"../services/InjectorService\";\nimport {runInContext} from \"../utils/asyncHookContext\";\nimport {ContextLogger, ContextLoggerOptions} from \"./ContextLogger\";\nimport {LocalsContainer} from \"./LocalsContainer\";\n\nexport interface DIContextOptions extends Omit<ContextLoggerOptions, \"dateStart\"> {\n id: string;\n injector: InjectorService;\n logger: any;\n}\n\nexport class DIContext {\n [x: string]: any;\n\n #container?: LocalsContainer;\n #cache?: Map<any, any>;\n #logger?: ContextLogger;\n\n constructor(public opts: DIContextOptions) {}\n\n /**\n * Logger attached to the context request.\n */\n get logger() {\n this.#logger = this.#logger || new ContextLogger(this.opts);\n return this.#logger;\n }\n\n /**\n * Request id generated by @@contextMiddleware@@.\n *\n * ::: tip\n * By default Ts.ED generate uuid like that `uuidv4().replace(/-/gi, \"\"))`.\n * Dash are removed to simplify tracking logs in Kibana\n * :::\n *\n * ::: tip\n * Request id can by customized by changing the server configuration.\n *\n * ```typescript\n * @Configuration({\n * logger: {\n * reqIdBuilder: createUniqId // give your own id generator function\n * }\n * })\n * class Server {\n *\n * }\n * ```\n * :::\n *\n */\n get id() {\n return this.opts.id;\n }\n\n get dateStart() {\n return this.logger.dateStart;\n }\n\n get injector(): InjectorService {\n return this.opts.injector!;\n }\n\n get env() {\n return this.injector.settings.get(\"env\");\n }\n\n /**\n * The request container used by the Ts.ED DI. It contains all services annotated with `@Scope(ProviderScope.REQUEST)`\n */\n get container() {\n return (this.#container = this.#container || new LocalsContainer());\n }\n\n async destroy(): Promise<any> {\n return Promise.all([this.#container?.destroy(), this.#logger?.flush()]);\n }\n\n async emit(eventName: string, ...args: any[]) {\n return this.injector?.emit(eventName, ...args);\n }\n\n async runInContext(next: Function) {\n return runInContext(this, next);\n }\n\n cache<Value = any>(key: string, cb: () => Value): Value {\n if (!this.has(key)) {\n this.set(key, cb());\n }\n\n return this.get(key);\n }\n\n async cacheAsync<Value = any>(key: string, cb: () => Promise<Value>): Promise<Value> {\n if (!this.has(key)) {\n this.set(key, await cb());\n }\n\n return this.get(key);\n }\n\n delete(key: any): boolean {\n return !!this.#cache?.delete(key);\n }\n\n get<T = any>(key: any): T {\n return this.#cache?.get(key);\n }\n\n has(key: any): boolean {\n return !!this.#cache?.has(key);\n }\n\n set(key: any, value: any): this {\n this.#cache = this.#cache || new Map<any, any>();\n this.#cache.set(key, value);\n return this;\n }\n}\n\nexport type BaseContext = DIContext & TsED.Context;\n"]}
@@ -1,51 +1,8 @@
1
+ import { Hooks } from "@tsed/core";
1
2
  export class LocalsContainer extends Map {
2
- /**
3
- * Emit an event to all service. See service [lifecycle hooks](/docs/services.md#lifecycle-hooks).
4
- * @param eventName The event name to emit at all services.
5
- * @param args List of the parameters to give to each services.
6
- * @returns {Promise<any[]>} A list of promises.
7
- */
8
- async emit(eventName, ...args) {
9
- for (const handler of this.getListeners(eventName)) {
10
- await handler(...args);
11
- }
12
- }
13
- /**
14
- * @param eventName
15
- * @param value
16
- * @param args
17
- */
18
- alter(eventName, value, ...args) {
19
- for (const handler of this.getListeners(eventName)) {
20
- value = handler(value, ...args);
21
- }
22
- return value;
23
- }
24
- /**
25
- * @param eventName
26
- * @param value
27
- * @param args
28
- */
29
- async alterAsync(eventName, value, ...args) {
30
- for (const handler of this.getListeners(eventName)) {
31
- value = handler(value, ...args);
32
- }
33
- return value;
34
- }
35
- toArray() {
36
- return [...this.values()];
37
- }
3
+ hooks = new Hooks();
38
4
  async destroy() {
39
- await this.emit("$onDestroy");
40
- this.clear();
41
- }
42
- getListeners(event) {
43
- return this.toArray().reduce((listeners, instance) => {
44
- if (typeof instance === "object" && instance && event in instance) {
45
- return listeners.concat(instance[event].bind(instance));
46
- }
47
- return listeners;
48
- }, []);
5
+ await this.hooks.asyncEmit("$onDestroy");
49
6
  }
50
7
  }
51
8
  //# sourceMappingURL=LocalsContainer.js.map