@tsed/di 7.0.0-alpha.1 → 7.0.0-beta.3

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 (282) hide show
  1. package/lib/cjs/constants/index.js +7 -0
  2. package/lib/cjs/constants/index.js.map +1 -0
  3. package/lib/cjs/decorators/configuration.js +24 -0
  4. package/lib/cjs/decorators/configuration.js.map +1 -0
  5. package/lib/cjs/decorators/constant.js +55 -0
  6. package/lib/cjs/decorators/constant.js.map +1 -0
  7. package/lib/cjs/decorators/controller.js +53 -0
  8. package/lib/cjs/decorators/controller.js.map +1 -0
  9. package/lib/cjs/decorators/index.js +19 -0
  10. package/lib/cjs/decorators/index.js.map +1 -0
  11. package/lib/cjs/decorators/inject.js +79 -0
  12. package/lib/cjs/decorators/inject.js.map +1 -0
  13. package/lib/cjs/decorators/injectable.js +34 -0
  14. package/lib/cjs/decorators/injectable.js.map +1 -0
  15. package/lib/cjs/decorators/intercept.js +28 -0
  16. package/lib/cjs/decorators/intercept.js.map +1 -0
  17. package/lib/cjs/decorators/interceptor.js +21 -0
  18. package/lib/cjs/decorators/interceptor.js.map +1 -0
  19. package/lib/cjs/decorators/lazyInject.js +71 -0
  20. package/lib/cjs/decorators/lazyInject.js.map +1 -0
  21. package/lib/cjs/decorators/module.js +31 -0
  22. package/lib/cjs/decorators/module.js.map +1 -0
  23. package/lib/cjs/decorators/opts.js +54 -0
  24. package/lib/cjs/decorators/opts.js.map +1 -0
  25. package/lib/cjs/decorators/overrideProvider.js +17 -0
  26. package/lib/cjs/decorators/overrideProvider.js.map +1 -0
  27. package/lib/cjs/decorators/scope.js +16 -0
  28. package/lib/cjs/decorators/scope.js.map +1 -0
  29. package/lib/cjs/decorators/service.js +18 -0
  30. package/lib/cjs/decorators/service.js.map +1 -0
  31. package/lib/cjs/decorators/useOpts.js +65 -0
  32. package/lib/cjs/decorators/useOpts.js.map +1 -0
  33. package/lib/cjs/decorators/value.js +55 -0
  34. package/lib/cjs/decorators/value.js.map +1 -0
  35. package/lib/cjs/domain/Container.js +72 -0
  36. package/lib/cjs/domain/Container.js.map +1 -0
  37. package/lib/cjs/domain/ContextLogger.js +85 -0
  38. package/lib/cjs/domain/ContextLogger.js.map +1 -0
  39. package/lib/cjs/domain/DIContext.js +45 -0
  40. package/lib/cjs/domain/DIContext.js.map +1 -0
  41. package/lib/cjs/domain/InjectablePropertyType.js +12 -0
  42. package/lib/cjs/domain/InjectablePropertyType.js.map +1 -0
  43. package/lib/cjs/domain/LocalsContainer.js +55 -0
  44. package/lib/cjs/domain/LocalsContainer.js.map +1 -0
  45. package/lib/cjs/domain/Provider.js +122 -0
  46. package/lib/cjs/domain/Provider.js.map +1 -0
  47. package/lib/cjs/domain/ProviderScope.js +10 -0
  48. package/lib/cjs/domain/ProviderScope.js.map +1 -0
  49. package/lib/cjs/domain/ProviderType.js +15 -0
  50. package/lib/cjs/domain/ProviderType.js.map +1 -0
  51. package/lib/cjs/domain/index.js +12 -0
  52. package/lib/cjs/domain/index.js.map +1 -0
  53. package/lib/cjs/errors/InjectionError.js +58 -0
  54. package/lib/cjs/errors/InjectionError.js.map +1 -0
  55. package/lib/cjs/errors/UndefinedTokenError.js +11 -0
  56. package/lib/cjs/errors/UndefinedTokenError.js.map +1 -0
  57. package/lib/cjs/index.js +21 -0
  58. package/lib/cjs/index.js.map +1 -0
  59. package/lib/cjs/interfaces/DIConfigurationOptions.js +3 -0
  60. package/lib/cjs/interfaces/DIConfigurationOptions.js.map +1 -0
  61. package/lib/cjs/interfaces/DILogger.js +3 -0
  62. package/lib/cjs/interfaces/DILogger.js.map +1 -0
  63. package/lib/cjs/interfaces/DIResolver.js +3 -0
  64. package/lib/cjs/interfaces/DIResolver.js.map +1 -0
  65. package/lib/cjs/interfaces/IProvider.js +3 -0
  66. package/lib/cjs/interfaces/IProvider.js.map +1 -0
  67. package/lib/cjs/interfaces/InjectableProperties.js +3 -0
  68. package/lib/cjs/interfaces/InjectableProperties.js.map +1 -0
  69. package/lib/cjs/interfaces/InterceptorContext.js +3 -0
  70. package/lib/cjs/interfaces/InterceptorContext.js.map +1 -0
  71. package/lib/cjs/interfaces/InterceptorMethods.js +3 -0
  72. package/lib/cjs/interfaces/InterceptorMethods.js.map +1 -0
  73. package/lib/cjs/interfaces/InvokeOptions.js +3 -0
  74. package/lib/cjs/interfaces/InvokeOptions.js.map +1 -0
  75. package/lib/cjs/interfaces/OnDestroy.js +3 -0
  76. package/lib/cjs/interfaces/OnDestroy.js.map +1 -0
  77. package/lib/cjs/interfaces/OnInit.js +3 -0
  78. package/lib/cjs/interfaces/OnInit.js.map +1 -0
  79. package/lib/cjs/interfaces/RegistrySettings.js +3 -0
  80. package/lib/cjs/interfaces/RegistrySettings.js.map +1 -0
  81. package/lib/cjs/interfaces/ResolvedInvokeOptions.js +3 -0
  82. package/lib/cjs/interfaces/ResolvedInvokeOptions.js.map +1 -0
  83. package/lib/cjs/interfaces/TokenProvider.js +3 -0
  84. package/lib/cjs/interfaces/TokenProvider.js.map +1 -0
  85. package/lib/cjs/interfaces/index.js +18 -0
  86. package/lib/cjs/interfaces/index.js.map +1 -0
  87. package/lib/cjs/registries/GlobalProviders.js +124 -0
  88. package/lib/cjs/registries/GlobalProviders.js.map +1 -0
  89. package/lib/cjs/registries/ProviderRegistry.js +85 -0
  90. package/lib/cjs/registries/ProviderRegistry.js.map +1 -0
  91. package/lib/cjs/services/DIConfiguration.js +129 -0
  92. package/lib/cjs/services/DIConfiguration.js.map +1 -0
  93. package/lib/cjs/services/DILogger.js +13 -0
  94. package/lib/cjs/services/DILogger.js.map +1 -0
  95. package/lib/cjs/services/DITest.js +108 -0
  96. package/lib/cjs/services/DITest.js.map +1 -0
  97. package/lib/cjs/services/InjectorService.js +566 -0
  98. package/lib/cjs/services/InjectorService.js.map +1 -0
  99. package/lib/cjs/utils/colors.js +10 -0
  100. package/lib/cjs/utils/colors.js.map +1 -0
  101. package/lib/cjs/utils/createContainer.js +14 -0
  102. package/lib/cjs/utils/createContainer.js.map +1 -0
  103. package/lib/cjs/utils/data/Test1.js +8 -0
  104. package/lib/cjs/utils/data/Test1.js.map +1 -0
  105. package/lib/cjs/utils/data/Test2.js +8 -0
  106. package/lib/cjs/utils/data/Test2.js.map +1 -0
  107. package/lib/cjs/utils/getConfiguration.js +20 -0
  108. package/lib/cjs/utils/getConfiguration.js.map +1 -0
  109. package/lib/cjs/utils/setLoggerLevel.js +16 -0
  110. package/lib/cjs/utils/setLoggerLevel.js.map +1 -0
  111. package/lib/esm/constants/index.js +4 -0
  112. package/lib/esm/constants/index.js.map +1 -0
  113. package/lib/esm/decorators/configuration.js +20 -0
  114. package/lib/esm/decorators/configuration.js.map +1 -0
  115. package/lib/esm/decorators/constant.js +51 -0
  116. package/lib/esm/decorators/constant.js.map +1 -0
  117. package/lib/esm/decorators/controller.js +49 -0
  118. package/lib/esm/decorators/controller.js.map +1 -0
  119. package/lib/esm/decorators/index.js +16 -0
  120. package/lib/esm/decorators/index.js.map +1 -0
  121. package/lib/esm/decorators/inject.js +74 -0
  122. package/lib/esm/decorators/inject.js.map +1 -0
  123. package/lib/esm/decorators/injectable.js +30 -0
  124. package/lib/esm/decorators/injectable.js.map +1 -0
  125. package/lib/esm/decorators/intercept.js +24 -0
  126. package/lib/esm/decorators/intercept.js.map +1 -0
  127. package/lib/esm/decorators/interceptor.js +17 -0
  128. package/lib/esm/decorators/interceptor.js.map +1 -0
  129. package/lib/esm/decorators/lazyInject.js +66 -0
  130. package/lib/esm/decorators/lazyInject.js.map +1 -0
  131. package/lib/esm/decorators/module.js +27 -0
  132. package/lib/esm/decorators/module.js.map +1 -0
  133. package/lib/esm/decorators/opts.js +50 -0
  134. package/lib/esm/decorators/opts.js.map +1 -0
  135. package/lib/esm/decorators/overrideProvider.js +13 -0
  136. package/lib/esm/decorators/overrideProvider.js.map +1 -0
  137. package/lib/esm/decorators/scope.js +12 -0
  138. package/lib/esm/decorators/scope.js.map +1 -0
  139. package/lib/esm/decorators/service.js +14 -0
  140. package/lib/esm/decorators/service.js.map +1 -0
  141. package/lib/esm/decorators/useOpts.js +61 -0
  142. package/lib/esm/decorators/useOpts.js.map +1 -0
  143. package/lib/esm/decorators/value.js +51 -0
  144. package/lib/esm/decorators/value.js.map +1 -0
  145. package/lib/esm/domain/Container.js +68 -0
  146. package/lib/esm/domain/Container.js.map +1 -0
  147. package/lib/esm/domain/ContextLogger.js +81 -0
  148. package/lib/esm/domain/ContextLogger.js.map +1 -0
  149. package/lib/esm/domain/DIContext.js +41 -0
  150. package/lib/esm/domain/DIContext.js.map +1 -0
  151. package/lib/esm/domain/InjectablePropertyType.js +9 -0
  152. package/lib/esm/domain/InjectablePropertyType.js.map +1 -0
  153. package/lib/esm/domain/LocalsContainer.js +51 -0
  154. package/lib/esm/domain/LocalsContainer.js.map +1 -0
  155. package/lib/esm/domain/Provider.js +118 -0
  156. package/lib/esm/domain/Provider.js.map +1 -0
  157. package/lib/esm/domain/ProviderScope.js +7 -0
  158. package/lib/esm/domain/ProviderScope.js.map +1 -0
  159. package/lib/esm/domain/ProviderType.js +12 -0
  160. package/lib/esm/domain/ProviderType.js.map +1 -0
  161. package/lib/esm/domain/index.js +9 -0
  162. package/lib/esm/domain/index.js.map +1 -0
  163. package/lib/esm/errors/InjectionError.js +54 -0
  164. package/lib/esm/errors/InjectionError.js.map +1 -0
  165. package/lib/esm/errors/UndefinedTokenError.js +7 -0
  166. package/lib/esm/errors/UndefinedTokenError.js.map +1 -0
  167. package/lib/esm/index.js +18 -0
  168. package/lib/esm/index.js.map +1 -0
  169. package/lib/esm/interfaces/DIConfigurationOptions.js +2 -0
  170. package/lib/esm/interfaces/DIConfigurationOptions.js.map +1 -0
  171. package/lib/esm/interfaces/DILogger.js +2 -0
  172. package/lib/esm/interfaces/DILogger.js.map +1 -0
  173. package/lib/esm/interfaces/DIResolver.js +2 -0
  174. package/lib/esm/interfaces/DIResolver.js.map +1 -0
  175. package/lib/esm/interfaces/IProvider.js +2 -0
  176. package/lib/esm/interfaces/IProvider.js.map +1 -0
  177. package/lib/esm/interfaces/InjectableProperties.js +2 -0
  178. package/lib/esm/interfaces/InjectableProperties.js.map +1 -0
  179. package/lib/esm/interfaces/InterceptorContext.js +2 -0
  180. package/lib/esm/interfaces/InterceptorContext.js.map +1 -0
  181. package/lib/esm/interfaces/InterceptorMethods.js +2 -0
  182. package/lib/esm/interfaces/InterceptorMethods.js.map +1 -0
  183. package/lib/esm/interfaces/InvokeOptions.js +2 -0
  184. package/lib/esm/interfaces/InvokeOptions.js.map +1 -0
  185. package/lib/esm/interfaces/OnDestroy.js +2 -0
  186. package/lib/esm/interfaces/OnDestroy.js.map +1 -0
  187. package/lib/esm/interfaces/OnInit.js +2 -0
  188. package/lib/esm/interfaces/OnInit.js.map +1 -0
  189. package/lib/esm/interfaces/RegistrySettings.js +2 -0
  190. package/lib/esm/interfaces/RegistrySettings.js.map +1 -0
  191. package/lib/esm/interfaces/ResolvedInvokeOptions.js +2 -0
  192. package/lib/esm/interfaces/ResolvedInvokeOptions.js.map +1 -0
  193. package/lib/esm/interfaces/TokenProvider.js +2 -0
  194. package/lib/esm/interfaces/TokenProvider.js.map +1 -0
  195. package/lib/esm/interfaces/index.js +15 -0
  196. package/lib/esm/interfaces/index.js.map +1 -0
  197. package/lib/esm/registries/GlobalProviders.js +120 -0
  198. package/lib/esm/registries/GlobalProviders.js.map +1 -0
  199. package/lib/esm/registries/ProviderRegistry.js +80 -0
  200. package/lib/esm/registries/ProviderRegistry.js.map +1 -0
  201. package/lib/esm/services/DIConfiguration.js +125 -0
  202. package/lib/esm/services/DIConfiguration.js.map +1 -0
  203. package/lib/esm/services/DILogger.js +11 -0
  204. package/lib/esm/services/DILogger.js.map +1 -0
  205. package/lib/esm/services/DITest.js +104 -0
  206. package/lib/esm/services/DITest.js.map +1 -0
  207. package/lib/esm/services/InjectorService.js +563 -0
  208. package/lib/esm/services/InjectorService.js.map +1 -0
  209. package/lib/esm/utils/colors.js +7 -0
  210. package/lib/esm/utils/colors.js.map +1 -0
  211. package/lib/esm/utils/createContainer.js +10 -0
  212. package/lib/esm/utils/createContainer.js.map +1 -0
  213. package/lib/esm/utils/data/Test1.js +4 -0
  214. package/lib/esm/utils/data/Test1.js.map +1 -0
  215. package/lib/esm/utils/data/Test2.js +4 -0
  216. package/lib/esm/utils/data/Test2.js.map +1 -0
  217. package/lib/esm/utils/getConfiguration.js +16 -0
  218. package/lib/esm/utils/getConfiguration.js.map +1 -0
  219. package/lib/esm/utils/setLoggerLevel.js +12 -0
  220. package/lib/esm/utils/setLoggerLevel.js.map +1 -0
  221. package/lib/{constants → types/constants}/index.d.ts +0 -0
  222. package/lib/{decorators → types/decorators}/configuration.d.ts +0 -0
  223. package/lib/{decorators → types/decorators}/constant.d.ts +0 -0
  224. package/lib/types/decorators/controller.d.ts +43 -0
  225. package/lib/{decorators → types/decorators}/index.d.ts +2 -0
  226. package/lib/{decorators → types/decorators}/inject.d.ts +2 -0
  227. package/lib/{decorators → types/decorators}/injectable.d.ts +2 -1
  228. package/lib/{decorators → types/decorators}/intercept.d.ts +0 -0
  229. package/lib/{decorators → types/decorators}/interceptor.d.ts +0 -0
  230. package/lib/types/decorators/lazyInject.d.ts +43 -0
  231. package/lib/{decorators → types/decorators}/module.d.ts +0 -0
  232. package/lib/{decorators → types/decorators}/opts.d.ts +0 -0
  233. package/lib/{decorators → types/decorators}/overrideProvider.d.ts +0 -0
  234. package/lib/{decorators → types/decorators}/scope.d.ts +0 -0
  235. package/lib/{decorators → types/decorators}/service.d.ts +0 -0
  236. package/lib/{decorators → types/decorators}/useOpts.d.ts +0 -0
  237. package/lib/{decorators → types/decorators}/value.d.ts +0 -0
  238. package/lib/{domain → types/domain}/Container.d.ts +2 -3
  239. package/lib/{domain → types/domain}/ContextLogger.d.ts +5 -1
  240. package/lib/{domain → types/domain}/DIContext.d.ts +6 -7
  241. package/lib/{domain → types/domain}/InjectablePropertyType.d.ts +0 -0
  242. package/lib/{domain → types/domain}/LocalsContainer.d.ts +0 -0
  243. package/lib/{domain → types/domain}/Provider.d.ts +17 -3
  244. package/lib/{domain → types/domain}/ProviderScope.d.ts +0 -0
  245. package/lib/{domain → types/domain}/ProviderType.d.ts +0 -0
  246. package/lib/{domain → types/domain}/index.d.ts +0 -0
  247. package/lib/{errors → types/errors}/InjectionError.d.ts +0 -0
  248. package/lib/{errors → types/errors}/UndefinedTokenError.d.ts +0 -0
  249. package/lib/{index.d.ts → types/index.d.ts} +1 -0
  250. package/lib/{interfaces → types/interfaces}/DIConfigurationOptions.d.ts +0 -0
  251. package/lib/{interfaces → types/interfaces}/DILogger.d.ts +0 -0
  252. package/lib/{interfaces → types/interfaces}/DIResolver.d.ts +0 -0
  253. package/lib/{interfaces → types/interfaces}/IProvider.d.ts +0 -0
  254. package/lib/{interfaces → types/interfaces}/InjectableProperties.d.ts +8 -4
  255. package/lib/{interfaces → types/interfaces}/InterceptorContext.d.ts +0 -0
  256. package/lib/{interfaces → types/interfaces}/InterceptorMethods.d.ts +0 -0
  257. package/lib/{interfaces → types/interfaces}/InvokeOptions.d.ts +0 -0
  258. package/lib/{interfaces → types/interfaces}/OnDestroy.d.ts +0 -0
  259. package/lib/{interfaces → types/interfaces}/OnInit.d.ts +0 -0
  260. package/lib/{interfaces → types/interfaces}/RegistrySettings.d.ts +6 -2
  261. package/lib/types/interfaces/ResolvedInvokeOptions.d.ts +12 -0
  262. package/lib/{interfaces → types/interfaces}/TokenProvider.d.ts +0 -0
  263. package/lib/{interfaces → types/interfaces}/index.d.ts +1 -0
  264. package/lib/{registries → types/registries}/GlobalProviders.d.ts +5 -1
  265. package/lib/{registries → types/registries}/ProviderRegistry.d.ts +0 -0
  266. package/lib/{services → types/services}/DIConfiguration.d.ts +0 -0
  267. package/lib/{services → types/services}/DILogger.d.ts +0 -0
  268. package/lib/{services → types/services}/DITest.d.ts +5 -1
  269. package/lib/{services → types/services}/InjectorService.d.ts +31 -14
  270. package/lib/types/utils/colors.d.ts +5 -0
  271. package/lib/{utils → types/utils}/createContainer.d.ts +0 -0
  272. package/lib/types/utils/data/Test1.d.ts +3 -0
  273. package/lib/types/utils/data/Test2.d.ts +3 -0
  274. package/lib/{utils → types/utils}/getConfiguration.d.ts +0 -0
  275. package/lib/{utils → types/utils}/setLoggerLevel.d.ts +0 -0
  276. package/package.json +15 -11
  277. package/readme.md +1 -1
  278. package/tsconfig.compile.esm.json +24 -0
  279. package/lib/index.js +0 -2271
  280. package/lib/index.js.map +0 -1
  281. package/lib/index.modern.js +0 -2235
  282. package/lib/index.modern.js.map +0 -1
package/lib/index.js DELETED
@@ -1,2271 +0,0 @@
1
- var core = require('@tsed/core');
2
- var logger = require('@tsed/logger');
3
- var tslib = require('tslib');
4
- var chalk = require('chalk');
5
-
6
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
7
-
8
- var chalk__default = /*#__PURE__*/_interopDefaultLegacy(chalk);
9
-
10
- const INJECTABLE_PROP = "DI:INJECTABLE_PROP";
11
- const DI_PARAMS = "DI:PARAMS";
12
- const DI_PARAM_OPTIONS = "DI:PARAM:OPTIONS";
13
-
14
- function _extends() {
15
- _extends = Object.assign || function (target) {
16
- for (var i = 1; i < arguments.length; i++) {
17
- var source = arguments[i];
18
-
19
- for (var key in source) {
20
- if (Object.prototype.hasOwnProperty.call(source, key)) {
21
- target[key] = source[key];
22
- }
23
- }
24
- }
25
-
26
- return target;
27
- };
28
-
29
- return _extends.apply(this, arguments);
30
- }
31
-
32
- function _objectWithoutPropertiesLoose(source, excluded) {
33
- if (source == null) return {};
34
- var target = {};
35
- var sourceKeys = Object.keys(source);
36
- var key, i;
37
-
38
- for (i = 0; i < sourceKeys.length; i++) {
39
- key = sourceKeys[i];
40
- if (excluded.indexOf(key) >= 0) continue;
41
- target[key] = source[key];
42
- }
43
-
44
- return target;
45
- }
46
-
47
- var id = 0;
48
-
49
- function _classPrivateFieldLooseKey(name) {
50
- return "__private_" + id++ + "_" + name;
51
- }
52
-
53
- function _classPrivateFieldLooseBase(receiver, privateKey) {
54
- if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) {
55
- throw new TypeError("attempted to use private field on non-instance");
56
- }
57
-
58
- return receiver;
59
- }
60
-
61
- exports.ProviderScope = void 0;
62
-
63
- (function (ProviderScope) {
64
- ProviderScope["SINGLETON"] = "singleton";
65
- ProviderScope["REQUEST"] = "request";
66
- ProviderScope["INSTANCE"] = "instance";
67
- })(exports.ProviderScope || (exports.ProviderScope = {}));
68
-
69
- exports.ProviderType = void 0;
70
-
71
- (function (ProviderType) {
72
- ProviderType["VALUE"] = "value";
73
- ProviderType["FACTORY"] = "factory";
74
- ProviderType["SERVICE"] = "service";
75
- ProviderType["PROVIDER"] = "provider";
76
- ProviderType["MODULE"] = "module";
77
- ProviderType["CONTROLLER"] = "controller";
78
- ProviderType["INTERCEPTOR"] = "interceptor";
79
- ProviderType["MIDDLEWARE"] = "middleware";
80
- })(exports.ProviderType || (exports.ProviderType = {}));
81
-
82
- var _provide = /*#__PURE__*/_classPrivateFieldLooseKey("provide");
83
-
84
- var _store = /*#__PURE__*/_classPrivateFieldLooseKey("store");
85
-
86
- var _tokenStore = /*#__PURE__*/_classPrivateFieldLooseKey("tokenStore");
87
-
88
- class Provider {
89
- constructor(token, options = {}) {
90
- Object.defineProperty(this, _provide, {
91
- writable: true,
92
- value: void 0
93
- });
94
- Object.defineProperty(this, _store, {
95
- writable: true,
96
- value: void 0
97
- });
98
- Object.defineProperty(this, _tokenStore, {
99
- writable: true,
100
- value: void 0
101
- });
102
- this.type = exports.ProviderType.PROVIDER;
103
- this.provide = token;
104
- this.useClass = token;
105
- Object.assign(this, options);
106
- }
107
-
108
- get token() {
109
- return _classPrivateFieldLooseBase(this, _provide)[_provide];
110
- }
111
-
112
- get provide() {
113
- return _classPrivateFieldLooseBase(this, _provide)[_provide];
114
- }
115
-
116
- set provide(value) {
117
- if (value) {
118
- _classPrivateFieldLooseBase(this, _provide)[_provide] = core.getClassOrSymbol(value);
119
- _classPrivateFieldLooseBase(this, _tokenStore)[_tokenStore] = _classPrivateFieldLooseBase(this, _store)[_store] = core.Store.from(value);
120
- }
121
- }
122
-
123
- get useClass() {
124
- return this._useClass;
125
- }
126
- /**
127
- * Create a new store if the given value is a class. Otherwise the value is ignored.
128
- * @param value
129
- */
130
-
131
-
132
- set useClass(value) {
133
- if (core.isClass(value)) {
134
- this._useClass = core.classOf(value);
135
- _classPrivateFieldLooseBase(this, _store)[_store] = core.Store.from(value);
136
- }
137
- }
138
-
139
- get className() {
140
- return this.name;
141
- }
142
-
143
- get name() {
144
- return core.nameOf(this.provide);
145
- }
146
-
147
- get store() {
148
- return _classPrivateFieldLooseBase(this, _store)[_store];
149
- }
150
- /**
151
- * Get the scope of the provider.
152
- *
153
- * ::: tip Note
154
- * Async provider is always a SINGLETON
155
- * :::
156
- *
157
- * @returns {boolean}
158
- */
159
-
160
-
161
- get scope() {
162
- if (this.isAsync()) {
163
- return exports.ProviderScope.SINGLETON;
164
- }
165
-
166
- return this.get("scope");
167
- }
168
- /**
169
- * Change the scope value of the provider.
170
- * @param scope
171
- */
172
-
173
-
174
- set scope(scope) {
175
- this.store.set("scope", scope);
176
- }
177
-
178
- get configuration() {
179
- return this.get("configuration");
180
- }
181
-
182
- set configuration(configuration) {
183
- this.store.set("configuration", configuration);
184
- }
185
-
186
- get(key) {
187
- return this.store.get(key) || _classPrivateFieldLooseBase(this, _tokenStore)[_tokenStore].get(key);
188
- }
189
-
190
- isAsync() {
191
- return !!this.useAsyncFactory;
192
- }
193
-
194
- clone() {
195
- return new (core.classOf(this))(_classPrivateFieldLooseBase(this, _provide)[_provide], this);
196
- }
197
-
198
- toString() {
199
- return ["Token", this.name, this.useClass && core.nameOf(this.useClass), this.useFactory && "Factory", this.useValue && "Value", this.useAsyncFactory && "AsyncFactory"].filter(Boolean).join(":");
200
- }
201
-
202
- }
203
-
204
- var _settings = /*#__PURE__*/_classPrivateFieldLooseKey("settings");
205
-
206
- class GlobalProviderRegistry extends Map {
207
- constructor() {
208
- super(...arguments);
209
- Object.defineProperty(this, _settings, {
210
- writable: true,
211
- value: void 0
212
- });
213
- _classPrivateFieldLooseBase(this, _settings)[_settings] = new Map();
214
- }
215
-
216
- /**
217
- * The get() method returns a specified element from a Map object.
218
- * @param key Required. The key of the element to return from the Map object.
219
- * @returns {T} Returns the element associated with the specified key or undefined if the key can't be found in the Map object.
220
- */
221
- get(key) {
222
- return super.get(core.getClassOrSymbol(key));
223
- }
224
- /**
225
- * The has() method returns a boolean indicating whether an element with the specified key exists or not.
226
- * @param key
227
- * @returns {boolean}
228
- */
229
-
230
-
231
- has(key) {
232
- return super.has(core.getClassOrSymbol(key));
233
- }
234
- /**
235
- * The set() method adds or updates an element with a specified key and value to a Map object.
236
- * @param key Required. The key of the element to add to the Map object.
237
- * @param metadata Required. The value of the element to add to the Map object.
238
- */
239
-
240
-
241
- set(key, metadata) {
242
- super.set(core.getClassOrSymbol(key), metadata);
243
- return this;
244
- }
245
- /**
246
- *
247
- * @param target
248
- * @param options
249
- */
250
-
251
-
252
- merge(target, options) {
253
- const meta = this.createIfNotExists(target, options);
254
- Object.keys(options).forEach(key => {
255
- meta[key] = options[key];
256
- });
257
- this.set(target, meta);
258
- }
259
- /**
260
- * The delete() method removes the specified element from a Map object.
261
- * @param key Required. The key of the element to remove from the Map object.
262
- * @returns {boolean} Returns true if an element in the Map object existed and has been removed, or false if the element does not exist.
263
- */
264
-
265
-
266
- delete(key) {
267
- return super.delete(core.getClassOrSymbol(key));
268
- }
269
-
270
- createRegistry(type, model, options = {}) {
271
- const defaultOptions = this.getRegistrySettings(type);
272
- options = Object.assign(defaultOptions, _extends({}, options, {
273
- model
274
- }));
275
-
276
- _classPrivateFieldLooseBase(this, _settings)[_settings].set(type, options);
277
-
278
- return this;
279
- }
280
-
281
- onInvoke(provider, locals, deps) {
282
- const settings = _classPrivateFieldLooseBase(this, _settings)[_settings].get(provider.type);
283
-
284
- if (settings != null && settings.onInvoke) {
285
- settings.onInvoke(provider, locals, deps);
286
- }
287
- }
288
-
289
- getRegistrySettings(target) {
290
- let type = "provider";
291
-
292
- if (typeof target === "string") {
293
- type = target;
294
- } else {
295
- const provider = this.get(target);
296
-
297
- if (provider) {
298
- type = provider.type;
299
- }
300
- }
301
-
302
- return _classPrivateFieldLooseBase(this, _settings)[_settings].get(type) || {
303
- model: Provider
304
- };
305
- }
306
-
307
- createRegisterFn(type) {
308
- return (provider, instance) => {
309
- // istanbul ignore next
310
- if (!provider.provide) {
311
- provider = {
312
- provide: provider
313
- };
314
- }
315
-
316
- provider = Object.assign({
317
- instance
318
- }, provider, {
319
- type
320
- });
321
- this.merge(provider.provide, provider);
322
- };
323
- }
324
- /**
325
- *
326
- * @param key
327
- * @param options
328
- */
329
-
330
-
331
- createIfNotExists(key, options) {
332
- const type = options.type || exports.ProviderType.PROVIDER;
333
-
334
- if (!this.has(key)) {
335
- const {
336
- model = Provider
337
- } = _classPrivateFieldLooseBase(this, _settings)[_settings].get(type) || {};
338
- const item = new model(key);
339
- this.set(key, item);
340
- }
341
-
342
- return this.get(key);
343
- }
344
-
345
- }
346
- /**
347
- *
348
- * @type {GlobalProviders}
349
- */
350
- // tslint:disable-next-line: variable-name
351
-
352
- const GlobalProviders = new GlobalProviderRegistry();
353
-
354
- class LocalsContainer extends Map {
355
- /**
356
- * Emit an event to all service. See service [lifecycle hooks](/docs/services.md#lifecycle-hooks).
357
- * @param eventName The event name to emit at all services.
358
- * @param args List of the parameters to give to each services.
359
- * @returns {Promise<any[]>} A list of promises.
360
- */
361
- async emit(eventName, ...args) {
362
- for (const handler of this.getListeners(eventName)) {
363
- await handler(...args);
364
- }
365
- }
366
- /**
367
- * @param eventName
368
- * @param value
369
- * @param args
370
- */
371
-
372
-
373
- alter(eventName, value, ...args) {
374
- for (const handler of this.getListeners(eventName)) {
375
- value = handler(value, ...args);
376
- }
377
-
378
- return value;
379
- }
380
- /**
381
- * @param eventName
382
- * @param value
383
- * @param args
384
- */
385
-
386
-
387
- async alterAsync(eventName, value, ...args) {
388
- for (const handler of this.getListeners(eventName)) {
389
- value = handler(value, ...args);
390
- }
391
-
392
- return value;
393
- }
394
-
395
- toArray() {
396
- return [...this.values()];
397
- }
398
-
399
- async destroy() {
400
- await this.emit("$onDestroy");
401
- this.clear();
402
- }
403
-
404
- getListeners(event) {
405
- return this.toArray().reduce((listeners, instance) => {
406
- if (typeof instance === "object" && instance && event in instance) {
407
- return listeners.concat(instance[event].bind(instance));
408
- }
409
-
410
- return listeners;
411
- }, []);
412
- }
413
-
414
- }
415
-
416
- class Container extends LocalsContainer {
417
- /**
418
- *
419
- * @param token
420
- * @param settings
421
- */
422
- add(token, settings = {}) {
423
- const provider = GlobalProviders.has(token) ? GlobalProviders.get(token).clone() : new Provider(token);
424
- Object.assign(provider, settings);
425
- return super.set(token, provider);
426
- }
427
- /**
428
- * Add a provider to the
429
- * @param token
430
- * @param settings
431
- */
432
-
433
-
434
- addProvider(token, settings = {}) {
435
- return this.add(token, settings);
436
- }
437
- /**
438
- *
439
- * @param token
440
- */
441
-
442
-
443
- hasProvider(token) {
444
- return super.has(token);
445
- }
446
- /**
447
- * Add a provider to the
448
- * @param token
449
- * @param provider
450
- */
451
-
452
-
453
- setProvider(token, provider) {
454
- return super.set(token, provider);
455
- }
456
- /**
457
- * The getProvider() method returns a specified element from a Map object.
458
- * @returns {T} Returns the element associated with the specified key or undefined if the key can't be found in the Map object.
459
- * @param token
460
- */
461
-
462
-
463
- getProvider(token) {
464
- return super.get(token);
465
- }
466
- /**
467
- * Get all providers registered in the injector container.
468
- *
469
- * @param {ProviderType} type Filter the list by the given ProviderType.
470
- * @returns {[TokenProvider , Provider<any>][]}
471
- */
472
-
473
-
474
- getProviders(type) {
475
- return Array.from(this).filter(([_, provider]) => type ? provider.type === type : true).map(([_, provider]) => provider);
476
- }
477
-
478
- addProviders(container) {
479
- container.forEach(provider => {
480
- if (!this.hasProvider(provider.provide)) {
481
- this.setProvider(provider.provide, provider.clone());
482
- }
483
- });
484
- }
485
-
486
- }
487
-
488
- exports.InjectablePropertyType = void 0;
489
-
490
- (function (InjectablePropertyType) {
491
- InjectablePropertyType["METHOD"] = "method";
492
- InjectablePropertyType["PROPERTY"] = "property";
493
- InjectablePropertyType["CONSTANT"] = "constant";
494
- InjectablePropertyType["VALUE"] = "value";
495
- InjectablePropertyType["INTERCEPTOR"] = "interceptor";
496
- })(exports.InjectablePropertyType || (exports.InjectablePropertyType = {}));
497
-
498
- var _additionalProps = /*#__PURE__*/_classPrivateFieldLooseKey("additionalProps");
499
-
500
- var _dateStart = /*#__PURE__*/_classPrivateFieldLooseKey("dateStart");
501
-
502
- var _ignoreLog = /*#__PURE__*/_classPrivateFieldLooseKey("ignoreLog");
503
-
504
- var _stack = /*#__PURE__*/_classPrivateFieldLooseKey("stack");
505
-
506
- var _level = /*#__PURE__*/_classPrivateFieldLooseKey("level");
507
-
508
- class ContextLogger {
509
- constructor(logger$1, {
510
- id,
511
- url = "",
512
- dateStart = new Date(),
513
- ignoreUrlPatterns = [],
514
- minimalRequestPicker,
515
- completeRequestPicker,
516
- level = "all",
517
- maxStackSize = 30,
518
- ignoreLog,
519
- additionalProps
520
- }) {
521
- Object.defineProperty(this, _additionalProps, {
522
- writable: true,
523
- value: void 0
524
- });
525
- Object.defineProperty(this, _dateStart, {
526
- writable: true,
527
- value: void 0
528
- });
529
- Object.defineProperty(this, _ignoreLog, {
530
- writable: true,
531
- value: void 0
532
- });
533
- Object.defineProperty(this, _stack, {
534
- writable: true,
535
- value: void 0
536
- });
537
- Object.defineProperty(this, _level, {
538
- writable: true,
539
- value: void 0
540
- });
541
- this.logger = logger$1;
542
- _classPrivateFieldLooseBase(this, _stack)[_stack] = [];
543
- this.id = id;
544
- this.url = url;
545
- _classPrivateFieldLooseBase(this, _additionalProps)[_additionalProps] = additionalProps || {};
546
- _classPrivateFieldLooseBase(this, _dateStart)[_dateStart] = dateStart;
547
-
548
- _classPrivateFieldLooseBase(this, _ignoreLog)[_ignoreLog] = ignoreLog || (() => false);
549
-
550
- this.minimalRequestPicker = minimalRequestPicker || (l => l);
551
-
552
- this.completeRequestPicker = completeRequestPicker || (l => l); // @ts-ignore
553
-
554
-
555
- _classPrivateFieldLooseBase(this, _level)[_level] = logger.levels()[level.toUpperCase()] || logger.levels().ALL;
556
- this.maxStackSize = maxStackSize;
557
- }
558
-
559
- info(obj) {
560
- this.run(logger.levels().INFO, obj, obj => this.minimalRequestPicker(this.getData(obj)));
561
- return this;
562
- }
563
-
564
- debug(obj, withRequest = true) {
565
- this.run(logger.levels().DEBUG, obj, obj => {
566
- obj = this.getData(obj);
567
- return withRequest ? this.completeRequestPicker(obj) : obj;
568
- });
569
- return this;
570
- }
571
-
572
- warn(obj) {
573
- this.run(logger.levels().WARN, obj, obj => this.completeRequestPicker(this.getData(obj)));
574
- return this;
575
- }
576
-
577
- error(obj) {
578
- this.run(logger.levels().ERROR, obj, obj => this.completeRequestPicker(this.getData(obj)));
579
- return this;
580
- }
581
-
582
- trace(obj) {
583
- this.run(logger.levels().TRACE, obj, obj => this.completeRequestPicker(this.getData(obj)));
584
- return this;
585
- }
586
-
587
- flush() {
588
- if (_classPrivateFieldLooseBase(this, _stack)[_stack].length) {
589
- _classPrivateFieldLooseBase(this, _stack)[_stack].forEach(({
590
- level,
591
- data
592
- }) => {
593
- this.logger[level](data);
594
- });
595
-
596
- _classPrivateFieldLooseBase(this, _stack)[_stack] = [];
597
- }
598
- }
599
-
600
- isLevelEnabled(otherLevel) {
601
- return _classPrivateFieldLooseBase(this, _level)[_level].isLessThanOrEqualTo(otherLevel);
602
- }
603
-
604
- destroy() {
605
- this.flush();
606
- this.logger = undefined;
607
- _classPrivateFieldLooseBase(this, _stack)[_stack] = undefined;
608
- }
609
- /**
610
- * Return the duration between the time when LogIncomingRequest has handle the request and now.
611
- * @returns {number}
612
- */
613
-
614
-
615
- getDuration() {
616
- return new Date().getTime() - _classPrivateFieldLooseBase(this, _dateStart)[_dateStart].getTime();
617
- }
618
-
619
- getData(obj) {
620
- if (typeof obj === "string") {
621
- obj = {
622
- message: obj
623
- };
624
- }
625
-
626
- return _extends({}, _classPrivateFieldLooseBase(this, _additionalProps)[_additionalProps], {
627
- reqId: this.id,
628
- time: new Date(),
629
- duration: this.getDuration()
630
- }, obj);
631
- }
632
-
633
- run(level, obj, mapper) {
634
- if (!this.isLevelEnabled(level)) {
635
- return;
636
- }
637
-
638
- if (!_classPrivateFieldLooseBase(this, _ignoreLog)[_ignoreLog](obj)) {
639
- _classPrivateFieldLooseBase(this, _stack)[_stack].push({
640
- level: level.levelStr.toLowerCase(),
641
- data: mapper(obj)
642
- });
643
- }
644
-
645
- if (this.maxStackSize < _classPrivateFieldLooseBase(this, _stack)[_stack].length) {
646
- this.flush();
647
- }
648
- }
649
-
650
- }
651
-
652
- const _excluded$1 = ["id", "injector", "logger", "ignoreLog"];
653
-
654
- var _container = /*#__PURE__*/_classPrivateFieldLooseKey("container");
655
-
656
- var _injector = /*#__PURE__*/_classPrivateFieldLooseKey("injector");
657
-
658
- class DIContext extends Map {
659
- constructor(_ref) {
660
- let {
661
- id,
662
- injector,
663
- logger,
664
- ignoreLog
665
- } = _ref,
666
- options = _objectWithoutPropertiesLoose(_ref, _excluded$1);
667
-
668
- super();
669
- /**
670
- * Date when request have been handled by the server. @@RequestLogger@@ use this date to log request duration.
671
- */
672
-
673
- Object.defineProperty(this, _container, {
674
- writable: true,
675
- value: void 0
676
- });
677
- Object.defineProperty(this, _injector, {
678
- writable: true,
679
- value: void 0
680
- });
681
- this.dateStart = new Date();
682
- _classPrivateFieldLooseBase(this, _container)[_container] = new LocalsContainer();
683
- this.id = id;
684
- injector && (_classPrivateFieldLooseBase(this, _injector)[_injector] = injector);
685
- this.logger = new ContextLogger(logger, _extends({}, options, {
686
- dateStart: this.dateStart,
687
- id,
688
- ignoreLog
689
- }));
690
- }
691
-
692
- /**
693
- * The request container used by the Ts.ED DI. It contain all services annotated with `@Scope(ProviderScope.REQUEST)`
694
- */
695
- get container() {
696
- return _classPrivateFieldLooseBase(this, _container)[_container];
697
- }
698
- /**
699
- *
700
- */
701
-
702
-
703
- get injector() {
704
- return _classPrivateFieldLooseBase(this, _injector)[_injector];
705
- }
706
-
707
- get env() {
708
- return this.injector.settings.env;
709
- }
710
-
711
- async destroy() {
712
- await this.container.destroy();
713
- this.logger.destroy(); // @ts-ignore
714
-
715
- delete this.logger;
716
- }
717
-
718
- async emit(eventName, ...args) {
719
- var _this$injector;
720
-
721
- return (_this$injector = this.injector) == null ? void 0 : _this$injector.emit(eventName, ...args);
722
- }
723
-
724
- }
725
-
726
- /**
727
- *
728
- * @param {"request" | "singleton" | ProviderScope} scope
729
- * @returns {Function}
730
- * @constructor
731
- */
732
-
733
- function Scope(scope = exports.ProviderScope.REQUEST) {
734
- return core.StoreSet("scope", scope);
735
- }
736
-
737
- /**
738
- *
739
- */
740
-
741
- GlobalProviders.createRegistry(exports.ProviderType.CONTROLLER, Provider);
742
- /**
743
- * Register a provider configuration.
744
- * @param {IProvider<any>} provider
745
- */
746
-
747
- function registerProvider(provider) {
748
- if (!provider.provide) {
749
- throw new Error("Provider.provide is required");
750
- }
751
-
752
- GlobalProviders.merge(provider.provide, provider);
753
- }
754
- /**
755
- * Add a new value in the `ProviderRegistry`.
756
- *
757
- * #### Example with symbol definition
758
- *
759
- *
760
- * ```typescript
761
- * import {registerValue, InjectorService} from "@tsed/di";
762
- *
763
- * const MyValue = Symbol.from("MyValue")
764
- *
765
- * registerValue({token: MyValue, useValue: "myValue"});
766
- *
767
- * @Service()
768
- * export class OtherService {
769
- * constructor(@Inject(MyValue) myValue: string){
770
- * console.log(myValue); /// "myValue"
771
- * }
772
- * }
773
- * ```
774
- */
775
-
776
- const registerValue = (provider, value) => {
777
- if (!provider.provide) {
778
- provider = {
779
- provide: provider
780
- };
781
- }
782
-
783
- provider = Object.assign({
784
- scope: exports.ProviderScope.SINGLETON,
785
- useValue: value
786
- }, provider, {
787
- type: exports.ProviderType.VALUE
788
- });
789
- GlobalProviders.merge(provider.provide, provider);
790
- };
791
- /**
792
- * Add a new controller in the `ProviderRegistry`. This controller will be built when `InjectorService` will be loaded.
793
- *
794
- * #### Example
795
- *
796
- * ```typescript
797
- * import {registerController, InjectorService} from "@tsed/di";
798
- *
799
- * export default class MyController {
800
- * constructor(){}
801
- * transform() {
802
- * return "test";
803
- * }
804
- * }
805
- *
806
- * registerController({provide: MyController});
807
- * // or
808
- * registerController(MyController);
809
- *
810
- * const injector = new InjectorService();
811
- * injector.load();
812
- *
813
- * const myController = injector.get<MyController>(MyController);
814
- * myController.getFoo(); // test
815
- * ```
816
- *
817
- * @param provider Provider configuration.
818
- */
819
-
820
- const registerController = GlobalProviders.createRegisterFn(exports.ProviderType.CONTROLLER);
821
-
822
- /**
823
- * The decorators `@Injectable()` declare a new service can be injected in other service, controller, interceptor, etc.. on there `constructor`.
824
- * All classes annotated with `@Injectable()` are built one time, excepted if you change the default provider configuration.
825
- *
826
- * <<< @/docs/snippets/providers/getting-started-injectable.ts
827
- *
828
- * ::: tip
829
- * `@Injectable()` use the `reflect-metadata` to collect and inject the built provided to other services.
830
- * :::
831
- *
832
- * ### Options
833
- *
834
- * - type (@@ProviderType@@ or `string`): Kind of provider. (Default: `ProviderType.PROVIDER`)
835
- * - scope (@@ProviderScope@): Kind of provider. (Default: `ProviderScope.SINGLETON`)
836
- * - deps (`Type<any>`): List of class or provider which will be injected to the constructor (Note: This options override default metadata generated by Typescript).
837
- *
838
- * @returns {Function}
839
- * @decorator
840
- */
841
-
842
- function Injectable(options = {}) {
843
- return provide => {
844
- registerProvider(_extends({}, options, {
845
- provide
846
- }));
847
- };
848
- }
849
-
850
- /**
851
- * The decorators `@Service()` declare a new service can be injected in other service or controller on there `constructor`.
852
- * All services annotated with `@Service()` are constructed one time.
853
- *
854
- * > `@Service()` use the `reflect-metadata` to collect and inject service on controllers or other services.
855
- *
856
- * @returns {Function}
857
- * @decorator
858
- */
859
-
860
- function Service() {
861
- return Injectable();
862
- }
863
-
864
- /**
865
- * Override a provider which is already registered in ProviderRegistry.
866
- * @returns {Function}
867
- * @decorators
868
- * @param originalProvider
869
- */
870
-
871
- function OverrideProvider(originalProvider) {
872
- return target => {
873
- GlobalProviders.get(originalProvider).useClass = target;
874
- };
875
- }
876
-
877
- /**
878
- * Inject a provider to another provider.
879
- *
880
- * Use this decorator to inject a custom provider on constructor parameter or property.
881
- *
882
- * ```typescript
883
- * @Injectable()
884
- * export class MyService {
885
- * @Inject(CONNECTION)
886
- * connection: CONNECTION;
887
- * }
888
- * ```
889
- *
890
- * @param symbol
891
- * @param onGet Use the given name method to inject
892
- * @returns {Function}
893
- * @decorator
894
- */
895
-
896
- function Inject(symbol, onGet) {
897
- return (target, propertyKey, descriptor) => {
898
- const bindingType = core.decoratorTypeOf([target, propertyKey, descriptor]);
899
-
900
- switch (bindingType) {
901
- case core.DecoratorTypes.PARAM:
902
- case core.DecoratorTypes.PARAM_CTOR:
903
- if (symbol) {
904
- const paramTypes = core.Metadata.getParamTypes(target, propertyKey);
905
- paramTypes[descriptor] = symbol;
906
- core.Metadata.setParamTypes(target, propertyKey, paramTypes);
907
- }
908
-
909
- break;
910
-
911
- case core.DecoratorTypes.PROP:
912
- core.Store.from(target).merge(INJECTABLE_PROP, {
913
- [propertyKey]: {
914
- bindingType,
915
- propertyKey,
916
- onGet,
917
- useType: symbol || core.Metadata.getType(target, propertyKey)
918
- }
919
- });
920
- break;
921
-
922
- case core.DecoratorTypes.METHOD:
923
- core.Store.from(target).merge(INJECTABLE_PROP, {
924
- [propertyKey]: {
925
- bindingType,
926
- propertyKey
927
- }
928
- });
929
- return descriptor;
930
-
931
- default:
932
- throw new core.UnsupportedDecoratorType(Inject, [target, propertyKey, descriptor]);
933
- }
934
- };
935
- }
936
-
937
- /**
938
- * Return value from Configuration.
939
- *
940
- * ## Example
941
- *
942
- * ```typescript
943
- * import {Env} from "@tsed/core";
944
- * import {Constant, Value} from "@tsed/di";
945
- *
946
- * export class MyClass {
947
- *
948
- * @Constant("env")
949
- * env: Env;
950
- *
951
- * @Value("swagger.path")
952
- * swaggerPath: string;
953
- *
954
- * @Value("swagger.path", "defaultValue")
955
- * swaggerPath: string;
956
- *
957
- * constructor() {
958
- * console.log(this.swaggerPath) // undefined. Not available on constructor
959
- * }
960
- *
961
- * $onInit() {
962
- * console.log(this.swaggerPath) // something
963
- * }
964
- * }
965
- * ```
966
- *
967
- * @param {string} expression
968
- * @param defaultValue
969
- * @returns {(targetClass: any, attributeName: string) => any}
970
- * @decorator
971
- */
972
-
973
- function Constant(expression, defaultValue) {
974
- return (target, propertyKey) => {
975
- core.Store.from(target).merge(INJECTABLE_PROP, {
976
- [propertyKey]: {
977
- bindingType: exports.InjectablePropertyType.CONSTANT,
978
- propertyKey,
979
- expression,
980
- defaultValue
981
- }
982
- });
983
- };
984
- }
985
-
986
- /**
987
- * Return value from Configuration.
988
- *
989
- * ## Example
990
- *
991
- * ```typescript
992
- * import {Env} from "@tsed/core";
993
- * import {Constant, Value} from "@tsed/di";
994
- *
995
- * export class MyClass {
996
- *
997
- * @Constant("env")
998
- * env: Env;
999
- *
1000
- * @Value("swagger.path")
1001
- * swaggerPath: string;
1002
- *
1003
- * @Value("swagger.path", "defaultValue")
1004
- * swaggerPath: string;
1005
- *
1006
- * constructor() {
1007
- * console.log(this.swaggerPath) // undefined. Not available on constructor
1008
- * }
1009
- *
1010
- * $onInit() {
1011
- * console.log(this.swaggerPath) // something
1012
- * }
1013
- * }
1014
- * ```
1015
- *
1016
- * @param expression
1017
- * @param defaultValue
1018
- * @returns {(targetClass: any, attributeName: string) => any}
1019
- * @decorator
1020
- */
1021
-
1022
- function Value(expression, defaultValue) {
1023
- return (target, propertyKey) => {
1024
- core.Store.from(target).merge(INJECTABLE_PROP, {
1025
- [propertyKey]: {
1026
- bindingType: exports.InjectablePropertyType.VALUE,
1027
- propertyKey,
1028
- expression,
1029
- defaultValue
1030
- }
1031
- });
1032
- };
1033
- }
1034
-
1035
- /**
1036
- * Attaches interceptor to method call and executes the before and after methods
1037
- *
1038
- * @param interceptor
1039
- * @param options
1040
- * @decorator
1041
- */
1042
-
1043
- function Intercept(interceptor, options) {
1044
- return (target, propertyKey, descriptor) => {
1045
- core.Store.from(target).merge(INJECTABLE_PROP, {
1046
- [propertyKey]: {
1047
- bindingType: exports.InjectablePropertyType.INTERCEPTOR,
1048
- propertyKey,
1049
- useType: interceptor,
1050
- options
1051
- }
1052
- });
1053
- return descriptor;
1054
- };
1055
- }
1056
-
1057
- /**
1058
- * The decorators `@Service()` declare a new service can be injected in other service or controller on there `constructor`.
1059
- * All services annotated with `@Service()` are constructed one time.
1060
- *
1061
- * > `@Service()` use the `reflect-metadata` to collect and inject service on controllers or other services.
1062
- *
1063
- * @returns {Function}
1064
- * @decorator
1065
- */
1066
-
1067
- function Interceptor() {
1068
- return Injectable({
1069
- type: exports.ProviderType.INTERCEPTOR
1070
- });
1071
- }
1072
-
1073
- /**
1074
- * Get or set Configuration on a class.
1075
- *
1076
- * @decorator
1077
- */
1078
-
1079
- function Configuration(configuration = {}) {
1080
- return (...args) => {
1081
- switch (core.decoratorTypeOf(args)) {
1082
- case core.DecoratorTypes.CLASS:
1083
- core.StoreSet("configuration", configuration)(args[0]);
1084
- break;
1085
-
1086
- default:
1087
- case core.DecoratorTypes.PARAM_CTOR:
1088
- return Inject(Configuration)(args[0], args[1], args[2]);
1089
- }
1090
- };
1091
- }
1092
-
1093
- const _excluded = ["scopes", "imports", "resolvers", "deps", "scope"];
1094
- /**
1095
- * Declare a new Ts.ED module
1096
- *
1097
- * ## Options
1098
- * - imports: List of Provider which must be built by injector before invoking the module
1099
- * - resolvers: List of external DI must be used to resolve unknown provider
1100
- * - deps: List of provider must be injected to the module constructor (explicit declaration)
1101
- *
1102
- * @param options
1103
- * @decorator
1104
- */
1105
-
1106
- function Module(options = {}) {
1107
- const {
1108
- imports,
1109
- resolvers,
1110
- deps
1111
- } = options,
1112
- configuration = _objectWithoutPropertiesLoose(options, _excluded);
1113
-
1114
- return core.useDecorators(Configuration(configuration), Injectable({
1115
- type: exports.ProviderType.MODULE,
1116
- scope: exports.ProviderScope.SINGLETON,
1117
- imports,
1118
- deps,
1119
- injectable: false,
1120
- resolvers
1121
- }));
1122
- }
1123
-
1124
- /**
1125
- * Get instance options. This options depending on his invocation context.
1126
- *
1127
- * ```typescript
1128
- * import {Injectable, Opts, UseOpts} from "@tsed/di";
1129
- *
1130
- * @Injectable()
1131
- * class MyConfigurableService {
1132
- * source: string;
1133
- * constructor(@Opts options: any = {}) {
1134
- * console.log("Hello ", options.source); // log: Hello Service1 then Hello Service2
1135
- *
1136
- * this.source = options.source;
1137
- * }
1138
- * }
1139
- *
1140
- * @Injectable()
1141
- * class MyService1 {
1142
- * constructor(@UseOpts({source: 'Service1'}) service: MyConfigurableService) {
1143
- * console.log(service.source) // log: Service1
1144
- * }
1145
- * }
1146
- *
1147
- * @Injectable()
1148
- * class MyService2 {
1149
- * constructor(@UseOpts({source: 'Service2'}) service: MyConfigurableService) {
1150
- * console.log(service.source) // log: Service2
1151
- * }
1152
- * }
1153
- * ```
1154
- *
1155
- * ::: warning
1156
- * Using @@Opts@@ decorator on a constructor parameter change the Scope of the provider to `ProviderScope.INSTANCE`.
1157
- * :::
1158
- *
1159
- * @param target
1160
- * @param propertyKey
1161
- * @param index
1162
- * @decorator
1163
- */
1164
-
1165
- function Opts(target, propertyKey, index) {
1166
- Scope(exports.ProviderScope.INSTANCE)(core.classOf(target));
1167
- Inject(DI_PARAM_OPTIONS)(target, propertyKey, index);
1168
- }
1169
-
1170
- /**
1171
- * Add options to invoke the Service.
1172
- *
1173
- * ```typescript
1174
- * import {Injectable, Opts, UseOpts} from "@tsed/di";
1175
- *
1176
- * @Injectable()
1177
- * class MyConfigurableService {
1178
- * source: string;
1179
- * constructor(@Opts options: any = {}) {
1180
- * console.log("Hello ", options.source); // log: Hello Service1 then Hello Service2
1181
- *
1182
- * this.source = options.source;
1183
- * }
1184
- * }
1185
- *
1186
- * @Injectable()
1187
- * class MyService1 {
1188
- * constructor(@UseOpts({source: 'Service1'}) service: MyConfigurableService) {
1189
- * console.log(service.source) // log: Service1
1190
- * }
1191
- * }
1192
- *
1193
- * @Injectable()
1194
- * class MyService2 {
1195
- * constructor(@UseOpts({source: 'Service2'}) service: MyConfigurableService) {
1196
- * console.log(service.source) // log: Service2
1197
- * }
1198
- * }
1199
- * ```
1200
- *
1201
- * ::: warning
1202
- * Using @@Opts@@ decorator on a constructor parameter change the Scope of the provider to `ProviderScope.INSTANCE`.
1203
- * :::
1204
- *
1205
- * @returns {Function}
1206
- * @decorator
1207
- * @param options
1208
- */
1209
-
1210
- function UseOpts(options) {
1211
- return (target, propertyKey, index) => {
1212
- const bindingType = core.decoratorTypeOf([target, propertyKey, index]);
1213
-
1214
- switch (bindingType) {
1215
- case core.DecoratorTypes.PARAM_CTOR:
1216
- core.Store.from(target).merge(`${DI_PARAM_OPTIONS}:${index}`, options);
1217
- break;
1218
-
1219
- case core.DecoratorTypes.PROP:
1220
- core.Store.from(target).merge(INJECTABLE_PROP, {
1221
- [propertyKey]: {
1222
- options
1223
- }
1224
- });
1225
- break;
1226
-
1227
- default:
1228
- throw new core.UnsupportedDecoratorType(UseOpts, [target, propertyKey, index]);
1229
- }
1230
- };
1231
- }
1232
-
1233
- class InjectionError extends Error {
1234
- constructor(token, origin) {
1235
- super(core.isString(origin) ? origin : "");
1236
- this.name = "INJECTION_ERROR";
1237
- this.tokens = [];
1238
- this.tokens = [token];
1239
-
1240
- if (origin) {
1241
- if (core.isString(origin)) {
1242
- this.origin = {
1243
- message: origin,
1244
- stack: this.stack
1245
- };
1246
- } else {
1247
- if (origin.tokens) {
1248
- this.tokens = this.tokens.concat(origin.tokens);
1249
- this.origin = origin.origin;
1250
- } else {
1251
- this.origin = origin;
1252
- this.stack = origin.stack;
1253
- }
1254
- }
1255
- }
1256
-
1257
- const originMessage = this.origin ? "\nOrigin: " + this.origin.message : "";
1258
- const tokensMessage = this.tokens.map(token => core.nameOf(token)).join(" > ");
1259
- this.message = `Injection failed on ${tokensMessage}${originMessage}`;
1260
- }
1261
-
1262
- static throwInjectorError(token, currentDependency, error) {
1263
- if (currentDependency && core.isClass(token)) {
1264
- error.message = printDependencyInjectionError(token, _extends({}, currentDependency, {
1265
- message: error.message
1266
- }));
1267
- }
1268
-
1269
- throw new InjectionError(token, error);
1270
- }
1271
-
1272
- }
1273
-
1274
- function printDependencyInjectionError(token, options) {
1275
- let erroredArg = "";
1276
- const args = core.getConstructorArgNames(token).map((arg, index) => {
1277
- if (options.index === index) {
1278
- erroredArg = arg;
1279
- arg = chalk__default['default'].red(arg);
1280
- }
1281
-
1282
- return `${arg}: ${core.nameOf(options.deps[index])}`;
1283
- }).join(", ");
1284
- const signature = core.nameOf(token) + "->constructor(" + args + ")";
1285
- const indexOf = signature.indexOf(erroredArg) - 5;
1286
-
1287
- const drawline = indexOf => " ".repeat(indexOf) + chalk__default['default'].red("^" + "‾".repeat(erroredArg.length - 1));
1288
-
1289
- return "Unable to inject dependency. " + options.message + "\n\n" + signature + "\n" + (indexOf > -1 ? drawline(indexOf) : "");
1290
- }
1291
-
1292
- class UndefinedTokenError extends Error {
1293
- constructor() {
1294
- super("Given token is undefined. Have you enabled emitDecoratorMetadata in your tsconfig.json or decorated your class with @Injectable, @Service, ... decorator ?");
1295
- this.name = "UNDEFINED_TOKEN_ERROR";
1296
- }
1297
-
1298
- }
1299
-
1300
- function createContainer(rootModule) {
1301
- const container = new Container(GlobalProviders.entries());
1302
-
1303
- if (rootModule) {
1304
- container.delete(rootModule);
1305
- }
1306
-
1307
- return container;
1308
- }
1309
-
1310
- class DIConfiguration {
1311
- constructor(initialProps = {}) {
1312
- this.default = new Map();
1313
- this.map = new Map();
1314
- Object.entries(_extends({
1315
- scopes: {},
1316
- resolvers: [],
1317
- imports: []
1318
- }, initialProps)).forEach(([key, value]) => {
1319
- this.default.set(key, value);
1320
- });
1321
- return core.proxyDelegation(this, {
1322
- ownKeys(target) {
1323
- return [...target.default.keys(), ...target.map.keys()];
1324
- }
1325
-
1326
- });
1327
- }
1328
-
1329
- get scopes() {
1330
- return this.getRaw("scopes");
1331
- }
1332
-
1333
- set scopes(value) {
1334
- this.setRaw("scopes", value);
1335
- }
1336
-
1337
- get resolvers() {
1338
- return this.getRaw("resolvers");
1339
- }
1340
-
1341
- set resolvers(resolvers) {
1342
- this.setRaw("resolvers", resolvers);
1343
- }
1344
-
1345
- get imports() {
1346
- return this.getRaw("imports");
1347
- }
1348
-
1349
- set imports(imports) {
1350
- this.setRaw("imports", imports);
1351
- }
1352
- /**
1353
- *
1354
- * @param callbackfn
1355
- * @param thisArg
1356
- */
1357
-
1358
-
1359
- forEach(callbackfn, thisArg) {
1360
- return new Set([...Array.from(this.default.keys()), ...Array.from(this.map.keys())]).forEach(key => {
1361
- callbackfn(this.getRaw(key), key, this.map);
1362
- }, thisArg);
1363
- }
1364
- /**
1365
- *
1366
- * @param propertyKey
1367
- * @param value
1368
- */
1369
-
1370
-
1371
- set(propertyKey, value) {
1372
- if (typeof propertyKey === "string") {
1373
- this.setRaw(propertyKey, value);
1374
- } else {
1375
- Object.entries(propertyKey).forEach(([key, value]) => {
1376
- this[key] = value;
1377
- });
1378
- }
1379
-
1380
- return this;
1381
- }
1382
-
1383
- setRaw(propertyKey, value) {
1384
- core.setValue(this.map, propertyKey, value);
1385
- return this;
1386
- }
1387
- /**
1388
- *
1389
- * @param propertyKey
1390
- * @param defaultValue
1391
- * @returns {undefined|any}
1392
- */
1393
-
1394
-
1395
- get(propertyKey, defaultValue) {
1396
- return this.resolve(this.getRaw(propertyKey, defaultValue));
1397
- }
1398
-
1399
- getRaw(propertyKey, defaultValue) {
1400
- const value = core.getValue(this.map, propertyKey);
1401
-
1402
- if (value !== undefined) {
1403
- return value;
1404
- }
1405
-
1406
- return core.getValue(this.default, propertyKey, defaultValue);
1407
- }
1408
-
1409
- merge(obj) {
1410
- Object.entries(obj).forEach(([key, value]) => {
1411
- const descriptor = Object.getOwnPropertyDescriptor(DIConfiguration.prototype, key);
1412
- const originalValue = this.get(key);
1413
- value = core.deepMerge(value, originalValue);
1414
-
1415
- if (descriptor && !["default", "set", "map", "get"].includes(key)) {
1416
- this[key] = value;
1417
- }
1418
- });
1419
- }
1420
- /**
1421
- *
1422
- * @param value
1423
- * @returns {any}
1424
- */
1425
-
1426
-
1427
- resolve(value) {
1428
- if (typeof value === "object" && value !== null) {
1429
- if (![Array, Object].includes(core.classOf(value))) {
1430
- return value;
1431
- }
1432
-
1433
- return Object.entries(value).reduce((o, [k, v]) => {
1434
- // @ts-ignore
1435
- o[k] = this.resolve(v);
1436
- return o;
1437
- }, Array.isArray(value) ? [] : {});
1438
- }
1439
-
1440
- if (typeof value === "string") {
1441
- const replacer = (match, key) => core.getValue(this.map, key);
1442
-
1443
- return value.replace(/\${([\w.]+)}/gi, replacer).replace(/<([\w.]+)>/gi, replacer).replace(/{{([\w.]+)}}/gi, replacer);
1444
- }
1445
-
1446
- return value;
1447
- }
1448
-
1449
- build() {
1450
- this.forEach((value, key) => this.map.set(key, this.resolve(value)));
1451
- this.set = this.setRaw;
1452
-
1453
- this.get = this.getRaw = (propertyKey, defaultValue) => core.getValue(this.map, propertyKey, defaultValue);
1454
- }
1455
-
1456
- }
1457
-
1458
- var InjectorService_1;
1459
- /**
1460
- * This service contain all services collected by `@Service` or services declared manually with `InjectorService.factory()` or `InjectorService.service()`.
1461
- *
1462
- * ### Example:
1463
- *
1464
- * ```typescript
1465
- * import {InjectorService} from "@tsed/di";
1466
- *
1467
- * // Import the services (all services are decorated with @Service()";
1468
- * import MyService1 from "./services/service1";
1469
- * import MyService2 from "./services/service2";
1470
- * import MyService3 from "./services/service3";
1471
- *
1472
- * // When all services is imported you can load InjectorService.
1473
- * const injector = new InjectorService()
1474
- *
1475
- * await injector.load();
1476
- *
1477
- * const myService1 = injector.get<MyService1>(MyServcice1);
1478
- * ```
1479
- */
1480
-
1481
- exports.InjectorService = InjectorService_1 = class InjectorService extends Container {
1482
- constructor() {
1483
- super();
1484
- this.settings = new DIConfiguration();
1485
- this.logger = console;
1486
- this.resolvedConfiguration = false;
1487
- const provider = this.addProvider(InjectorService_1).getProvider(InjectorService_1);
1488
- provider.instance = this;
1489
- }
1490
-
1491
- get resolvers() {
1492
- return this.settings.resolvers;
1493
- }
1494
-
1495
- get scopes() {
1496
- return this.settings.scopes || {};
1497
- }
1498
- /**
1499
- * Retrieve default scope for a given provider.
1500
- * @param provider
1501
- */
1502
-
1503
-
1504
- scopeOf(provider) {
1505
- return provider.scope || this.scopes[provider.type] || exports.ProviderScope.SINGLETON;
1506
- }
1507
- /**
1508
- * Clone a provider from GlobalProviders and the given token. forkProvider method build automatically the provider if the instance parameter ins't given.
1509
- * @param token
1510
- * @param settings
1511
- */
1512
-
1513
-
1514
- forkProvider(token, settings = {}) {
1515
- if (!this.hasProvider(token)) {
1516
- this.addProvider(token);
1517
- }
1518
-
1519
- const provider = this.getProvider(token);
1520
- Object.assign(provider, settings);
1521
- provider.instance = this.invoke(token);
1522
- return provider;
1523
- }
1524
- /**
1525
- * Return a list of instance build by the injector.
1526
- */
1527
-
1528
-
1529
- toArray() {
1530
- return super.toArray().map(provider => provider.instance);
1531
- }
1532
- /**
1533
- * Get a service or factory already constructed from his symbol or class.
1534
- *
1535
- * #### Example
1536
- *
1537
- * ```typescript
1538
- * import {InjectorService} from "@tsed/di";
1539
- * import MyService from "./services";
1540
- *
1541
- * class OtherService {
1542
- * constructor(injectorService: InjectorService) {
1543
- * const myService = injectorService.get<MyService>(MyService);
1544
- * }
1545
- * }
1546
- * ```
1547
- *
1548
- * @param token The class or symbol registered in InjectorService.
1549
- * @param options
1550
- * @returns {boolean}
1551
- */
1552
-
1553
-
1554
- get(token, options = {}) {
1555
- var _super$get;
1556
-
1557
- const instance = (_super$get = super.get(core.getClassOrSymbol(token))) == null ? void 0 : _super$get.instance;
1558
-
1559
- if (instance !== undefined) {
1560
- return instance;
1561
- }
1562
-
1563
- if (!this.hasProvider(token)) {
1564
- for (const resolver of this.resolvers) {
1565
- const result = resolver.get(token, options);
1566
-
1567
- if (result !== undefined) {
1568
- return result;
1569
- }
1570
- }
1571
- }
1572
- }
1573
- /**
1574
- * The has() method returns a boolean indicating whether an element with the specified key exists or not.
1575
- * @returns {boolean}
1576
- * @param token
1577
- */
1578
-
1579
-
1580
- has(token) {
1581
- return super.has(core.getClassOrSymbol(token)) && this.get(token) !== undefined;
1582
- }
1583
- /**
1584
- * Invoke the class and inject all services that required by the class constructor.
1585
- *
1586
- * #### Example
1587
- *
1588
- * ```typescript
1589
- * import {InjectorService} from "@tsed/di";
1590
- * import MyService from "./services";
1591
- *
1592
- * class OtherService {
1593
- * constructor(injectorService: InjectorService) {
1594
- * const myService = injectorService.invoke<MyService>(MyService);
1595
- * }
1596
- * }
1597
- * ```
1598
- *
1599
- * @param token The injectable class to invoke. Class parameters are injected according constructor signature.
1600
- * @param locals Optional object. If preset then any argument Class are read from this object first, before the `InjectorService` is consulted.
1601
- * @param options
1602
- * @returns {T} The class constructed.
1603
- */
1604
-
1605
-
1606
- invoke(token, locals = new LocalsContainer(), options = {}) {
1607
- const provider = this.ensureProvider(token);
1608
- let instance;
1609
- !locals.has(Configuration) && locals.set(Configuration, this.settings);
1610
-
1611
- if (locals.has(token)) {
1612
- return locals.get(token);
1613
- }
1614
-
1615
- if (token === DI_PARAM_OPTIONS) {
1616
- return {};
1617
- }
1618
-
1619
- if (!provider || options.rebuild) {
1620
- instance = this.resolve(token, locals, options);
1621
- this.hasProvider(token) && (this.getProvider(token).instance = instance);
1622
- return instance;
1623
- }
1624
-
1625
- switch (this.scopeOf(provider)) {
1626
- case exports.ProviderScope.SINGLETON:
1627
- if (!this.has(token)) {
1628
- provider.instance = this.resolve(token, locals, options);
1629
-
1630
- if (provider.isAsync()) {
1631
- provider.instance.then(instance => {
1632
- provider.instance = instance;
1633
- });
1634
- }
1635
- }
1636
-
1637
- instance = this.get(token);
1638
- break;
1639
-
1640
- case exports.ProviderScope.REQUEST:
1641
- instance = this.resolve(token, locals, options);
1642
- locals.set(token, instance);
1643
- break;
1644
-
1645
- case exports.ProviderScope.INSTANCE:
1646
- instance = this.resolve(provider.provide, locals, options);
1647
- break;
1648
- }
1649
-
1650
- return instance;
1651
- }
1652
- /**
1653
- * Build only providers which are asynchronous.
1654
- */
1655
-
1656
-
1657
- async loadAsync(locals = new LocalsContainer()) {
1658
- for (const [, provider] of this) {
1659
- if (!locals.has(provider.token)) {
1660
- if (provider.isAsync()) {
1661
- await this.invoke(provider.token, locals);
1662
- }
1663
-
1664
- if (provider.instance) {
1665
- locals.set(provider.token, provider.instance);
1666
- }
1667
- }
1668
- }
1669
-
1670
- return locals;
1671
- }
1672
-
1673
- loadSync(locals = new LocalsContainer()) {
1674
- for (const [, provider] of this) {
1675
- if (!locals.has(provider.token) && this.scopeOf(provider) === exports.ProviderScope.SINGLETON) {
1676
- this.invoke(provider.token, locals);
1677
- }
1678
-
1679
- if (provider.instance !== undefined) {
1680
- locals.set(provider.token, provider.instance);
1681
- }
1682
- }
1683
-
1684
- return locals;
1685
- }
1686
- /**
1687
- * Boostrap injector from container and resolve configuration.
1688
- *
1689
- * @param container
1690
- */
1691
-
1692
-
1693
- bootstrap(container = createContainer()) {
1694
- // Clone all providers in the container
1695
- this.addProviders(container); // Resolve all configuration
1696
-
1697
- this.resolveConfiguration();
1698
- return this;
1699
- }
1700
- /**
1701
- * Build all providers from given container (or GlobalProviders) and emit `$onInit` event.
1702
- *
1703
- * @param container
1704
- * @param rootModule
1705
- */
1706
-
1707
-
1708
- async load(container = createContainer(), rootModule) {
1709
- this.bootstrap(container); // build async and sync provider
1710
-
1711
- let locals = await this.loadAsync();
1712
-
1713
- if (rootModule) {
1714
- await this.invoke(rootModule);
1715
- } // load sync provider
1716
-
1717
-
1718
- locals = this.loadSync(locals);
1719
- await locals.emit("$onInit");
1720
- return locals;
1721
- }
1722
- /**
1723
- * Load all configurations registered on providers
1724
- */
1725
-
1726
-
1727
- resolveConfiguration() {
1728
- if (this.resolvedConfiguration) {
1729
- return;
1730
- }
1731
-
1732
- const mergedConfiguration = new Map();
1733
- super.forEach(provider => {
1734
- if (provider.configuration) {
1735
- Object.entries(provider.configuration).forEach(([key, value]) => {
1736
- value = mergedConfiguration.has(key) ? core.deepMerge(mergedConfiguration.get(key), value) : core.deepClone(value);
1737
- mergedConfiguration.set(key, value);
1738
- });
1739
- }
1740
-
1741
- if (provider.resolvers) {
1742
- this.resolvers.push(...provider.resolvers);
1743
- }
1744
- });
1745
- mergedConfiguration.forEach((value, key) => {
1746
- this.settings[key] = core.deepMerge(value, this.settings[key]);
1747
- });
1748
- this.settings.build();
1749
- this.resolvedConfiguration = true;
1750
- }
1751
- /**
1752
- *
1753
- * @param instance
1754
- * @param locals
1755
- * @param options
1756
- */
1757
-
1758
-
1759
- bindInjectableProperties(instance, locals, options) {
1760
- const properties = core.ancestorsOf(core.classOf(instance)).reduce((properties, target) => {
1761
- const store = core.Store.from(target);
1762
- return _extends({}, properties, store.get(INJECTABLE_PROP) || {});
1763
- }, {});
1764
- Object.values(properties).forEach(definition => {
1765
- switch (definition.bindingType) {
1766
- case exports.InjectablePropertyType.METHOD:
1767
- this.bindMethod(instance, definition);
1768
- break;
1769
-
1770
- case exports.InjectablePropertyType.PROPERTY:
1771
- this.bindProperty(instance, definition, locals, options);
1772
- break;
1773
-
1774
- case exports.InjectablePropertyType.CONSTANT:
1775
- this.bindConstant(instance, definition);
1776
- break;
1777
-
1778
- case exports.InjectablePropertyType.VALUE:
1779
- this.bindValue(instance, definition);
1780
- break;
1781
-
1782
- case exports.InjectablePropertyType.INTERCEPTOR:
1783
- this.bindInterceptor(instance, definition);
1784
- break;
1785
- }
1786
- });
1787
- }
1788
- /**
1789
- *
1790
- * @param instance
1791
- * @param {string} propertyKey
1792
- */
1793
-
1794
-
1795
- bindMethod(instance, {
1796
- propertyKey
1797
- }) {
1798
- const target = core.classOf(instance);
1799
- const originalMethod = instance[propertyKey];
1800
- const deps = core.Metadata.getParamTypes(core.prototypeOf(target), propertyKey);
1801
-
1802
- instance[propertyKey] = () => {
1803
- const services = deps.map(dependency => this.get(dependency));
1804
- return originalMethod.call(instance, ...services);
1805
- };
1806
- }
1807
- /**
1808
- * Create an injectable property.
1809
- *
1810
- * @param instance
1811
- * @param {string} propertyKey
1812
- * @param {any} useType
1813
- * @param onGet
1814
- * @param options
1815
- * @param locals
1816
- * @param invokeOptions
1817
- */
1818
-
1819
-
1820
- bindProperty(instance, {
1821
- propertyKey,
1822
- useType,
1823
- onGet = f => f,
1824
- options
1825
- }, locals, invokeOptions) {
1826
- invokeOptions = _extends({}, invokeOptions);
1827
- locals.set(DI_PARAM_OPTIONS, _extends({}, options));
1828
- let bean = this.invoke(useType, locals, invokeOptions);
1829
- locals.delete(DI_PARAM_OPTIONS);
1830
-
1831
- if (core.isPromise(bean)) {
1832
- bean.then(result => {
1833
- bean = result;
1834
- });
1835
- }
1836
-
1837
- Object.defineProperty(instance, propertyKey, {
1838
- get: () => onGet(bean)
1839
- });
1840
- }
1841
- /**
1842
- *
1843
- * @param instance
1844
- * @param {string} propertyKey
1845
- * @param {any} useType
1846
- */
1847
-
1848
-
1849
- bindValue(instance, {
1850
- propertyKey,
1851
- expression,
1852
- defaultValue
1853
- }) {
1854
- const descriptor = {
1855
- get: () => this.settings.get(expression) || defaultValue,
1856
- set: value => this.settings.set(expression, value),
1857
- enumerable: true,
1858
- configurable: true
1859
- };
1860
- Object.defineProperty(instance, propertyKey, descriptor);
1861
- }
1862
- /**
1863
- *
1864
- * @param instance
1865
- * @param {string} propertyKey
1866
- * @param {any} useType
1867
- */
1868
-
1869
-
1870
- bindConstant(instance, {
1871
- propertyKey,
1872
- expression,
1873
- defaultValue
1874
- }) {
1875
- const clone = o => {
1876
- if (o) {
1877
- return Object.freeze(core.deepClone(o));
1878
- }
1879
-
1880
- return defaultValue;
1881
- };
1882
-
1883
- const descriptor = {
1884
- get: () => clone(this.settings.get(expression)),
1885
- enumerable: true,
1886
- configurable: true
1887
- };
1888
- Object.defineProperty(instance, propertyKey, descriptor);
1889
- return descriptor;
1890
- }
1891
- /**
1892
- *
1893
- * @param instance
1894
- * @param propertyKey
1895
- * @param useType
1896
- * @param options
1897
- */
1898
-
1899
-
1900
- bindInterceptor(instance, {
1901
- propertyKey,
1902
- useType,
1903
- options
1904
- }) {
1905
- const target = core.classOf(instance);
1906
- const originalMethod = instance[propertyKey];
1907
-
1908
- instance[propertyKey] = (...args) => {
1909
- const next = err => {
1910
- if (!err) {
1911
- return originalMethod.apply(instance, args);
1912
- }
1913
-
1914
- throw err;
1915
- };
1916
-
1917
- const context = {
1918
- target,
1919
- propertyKey,
1920
- args,
1921
- options,
1922
- next
1923
- };
1924
- const interceptor = this.get(useType);
1925
- return interceptor.intercept(_extends({}, context, {
1926
- options
1927
- }), next);
1928
- };
1929
- }
1930
- /**
1931
- * Allow handler hack for AsyncHookContext plugin.
1932
- * @param ctx
1933
- * @param cb
1934
- * @protected
1935
- */
1936
-
1937
-
1938
- runInContext(ctx, cb) {
1939
- return cb();
1940
- }
1941
-
1942
- ensureProvider(token) {
1943
- if (!this.hasProvider(token) && GlobalProviders.has(token)) {
1944
- this.addProvider(token);
1945
- }
1946
-
1947
- return this.getProvider(token);
1948
- }
1949
- /**
1950
- * Invoke a class method and inject service.
1951
- *
1952
- * #### IInjectableMethod options
1953
- *
1954
- * * **target**: Optional. The class instance.
1955
- * * **methodName**: `string` Optional. The method name.
1956
- * * **designParamTypes**: `any[]` Optional. List of injectable types.
1957
- * * **locals**: `Map<Function, any>` Optional. If preset then any argument Class are read from this object first, before the `InjectorService` is consulted.
1958
- *
1959
- * #### Example
1960
- *
1961
- * @param target
1962
- * @param locals
1963
- * @param options
1964
- * @private
1965
- */
1966
-
1967
-
1968
- resolve(target, locals, options = {}) {
1969
- const {
1970
- token,
1971
- deps,
1972
- construct,
1973
- isBindable,
1974
- imports,
1975
- provider
1976
- } = this.mapInvokeOptions(target, locals, options);
1977
-
1978
- if (provider) {
1979
- GlobalProviders.onInvoke(provider, locals, deps);
1980
- }
1981
-
1982
- let instance;
1983
- let currentDependency = false;
1984
-
1985
- try {
1986
- const invokeDependency = parent => (token, index) => {
1987
- currentDependency = {
1988
- token,
1989
- index,
1990
- deps
1991
- };
1992
-
1993
- if (token !== DI_PARAM_OPTIONS) {
1994
- var _provider$store;
1995
-
1996
- const options = provider == null ? void 0 : (_provider$store = provider.store) == null ? void 0 : _provider$store.get(`${DI_PARAM_OPTIONS}:${index}`);
1997
- locals.set(DI_PARAM_OPTIONS, options || {});
1998
- }
1999
-
2000
- return core.isInheritedFrom(token, Provider, 1) ? provider : this.invoke(token, locals, {
2001
- parent
2002
- });
2003
- }; // Invoke manually imported providers
2004
-
2005
-
2006
- imports.forEach(invokeDependency()); // Inject dependencies
2007
-
2008
- const services = deps.map(invokeDependency(token));
2009
- currentDependency = false;
2010
- instance = construct(services);
2011
- } catch (error) {
2012
- InjectionError.throwInjectorError(token, currentDependency, error);
2013
- }
2014
-
2015
- if (instance === undefined) {
2016
- throw new InjectionError(token, `Unable to create new instance from undefined value. Check your provider declaration for ${core.nameOf(token)}`);
2017
- }
2018
-
2019
- if (instance && isBindable) {
2020
- this.bindInjectableProperties(instance, locals, options);
2021
- }
2022
-
2023
- return instance;
2024
- }
2025
- /**
2026
- * Create options to invoke a provider or class.
2027
- * @param token
2028
- * @param locals
2029
- * @param options
2030
- */
2031
-
2032
-
2033
- mapInvokeOptions(token, locals, options) {
2034
- let imports = options.imports;
2035
- let deps = options.deps;
2036
- let scope = options.scope;
2037
- let construct;
2038
- let isBindable = false;
2039
-
2040
- if (!token) {
2041
- throw new UndefinedTokenError();
2042
- }
2043
-
2044
- let provider;
2045
-
2046
- if (!this.hasProvider(token)) {
2047
- provider = new Provider(token);
2048
- this.resolvers.forEach(resolver => {
2049
- const result = resolver.get(token, locals.get(DI_PARAM_OPTIONS));
2050
-
2051
- if (result !== undefined) {
2052
- provider.useFactory = () => result;
2053
- }
2054
- });
2055
- } else {
2056
- provider = this.getProvider(token);
2057
- }
2058
-
2059
- scope = scope || this.scopeOf(provider);
2060
- deps = deps || provider.deps;
2061
- imports = imports || provider.imports;
2062
-
2063
- if (provider.useValue !== undefined) {
2064
- construct = () => core.isFunction(provider.useValue) ? provider.useValue() : provider.useValue;
2065
- } else if (provider.useFactory) {
2066
- construct = deps => provider.useFactory(...deps);
2067
- } else if (provider.useAsyncFactory) {
2068
- construct = deps => provider.useAsyncFactory(...deps);
2069
- } else {
2070
- // useClass
2071
- isBindable = true;
2072
- deps = deps || core.Metadata.getParamTypes(provider.useClass);
2073
-
2074
- construct = deps => new provider.useClass(...deps);
2075
- }
2076
-
2077
- return {
2078
- token,
2079
- scope: scope || core.Store.from(token).get("scope") || exports.ProviderScope.SINGLETON,
2080
- deps: deps || [],
2081
- imports: imports || [],
2082
- isBindable,
2083
- construct,
2084
- provider
2085
- };
2086
- }
2087
-
2088
- };
2089
- exports.InjectorService = InjectorService_1 = tslib.__decorate([Injectable({
2090
- scope: exports.ProviderScope.SINGLETON,
2091
- global: true
2092
- }), tslib.__metadata("design:paramtypes", [])], exports.InjectorService);
2093
-
2094
- registerProvider({
2095
- provide: logger.Logger,
2096
- deps: [exports.InjectorService],
2097
-
2098
- useFactory(injector) {
2099
- return injector.logger;
2100
- }
2101
-
2102
- });
2103
-
2104
- /**
2105
- * @ignore
2106
- * @param injector
2107
- */
2108
- function setLoggerLevel(injector) {
2109
- var _injector$settings$lo;
2110
-
2111
- const level = (_injector$settings$lo = injector.settings.logger) == null ? void 0 : _injector$settings$lo.level;
2112
-
2113
- if (level) {
2114
- injector.logger.level = level;
2115
- }
2116
- }
2117
-
2118
- /**
2119
- * Tool to run test with lightweight DI sandbox.
2120
- */
2121
-
2122
- class DITest {
2123
- static get injector() {
2124
- if (DITest._injector) {
2125
- return DITest._injector;
2126
- }
2127
- /* istanbul ignore next */
2128
-
2129
-
2130
- throw new Error("PlatformTest.injector is not initialized. Use PlatformTest.create(): Promise before PlatformTest.invoke() or PlatformTest.injector.\n" + "Example:\n" + "before(async () => {\n" + " await PlatformTest.create()\n" + " await PlatformTest.invoke(MyService, [])\n" + "})");
2131
- }
2132
-
2133
- static set injector(injector) {
2134
- DITest._injector = injector;
2135
- }
2136
-
2137
- static hasInjector() {
2138
- return !!DITest._injector;
2139
- }
2140
-
2141
- static async create(settings = {}) {
2142
- DITest.injector = DITest.createInjector(settings);
2143
- const container = new Container();
2144
- DITest.injector.bootstrap(container);
2145
- await DITest.injector.load(container);
2146
- }
2147
- /**
2148
- * Create a new injector with the right default services
2149
- */
2150
-
2151
-
2152
- static createInjector(settings = {}) {
2153
- const injector = new exports.InjectorService();
2154
- injector.logger = logger.$log; // @ts-ignore
2155
-
2156
- injector.settings.set(DITest.configure(settings));
2157
- setLoggerLevel(injector);
2158
- return injector;
2159
- }
2160
- /**
2161
- * Resets the test injector of the test context, so it won't pollute your next test. Call this in your `tearDown` logic.
2162
- */
2163
-
2164
-
2165
- static async reset() {
2166
- if (DITest.hasInjector()) {
2167
- await DITest.injector.destroy();
2168
- DITest._injector = null;
2169
- }
2170
- }
2171
- /**
2172
- * Invoke a provider and return a fresh instance
2173
- * @param target
2174
- * @param providers
2175
- */
2176
-
2177
-
2178
- static invoke(target, providers = []) {
2179
- const locals = new LocalsContainer();
2180
- providers.forEach(p => {
2181
- locals.set(p.token, p.use);
2182
- });
2183
- locals.set(exports.InjectorService, DITest.injector);
2184
- const instance = DITest.injector.invoke(target, locals, {
2185
- rebuild: true
2186
- });
2187
-
2188
- if (instance && instance.$onInit) {
2189
- // await instance.$onInit();
2190
- const result = instance.$onInit();
2191
-
2192
- if (result instanceof Promise) {
2193
- return result.then(() => instance);
2194
- }
2195
- }
2196
-
2197
- return instance;
2198
- }
2199
- /**
2200
- * Return the instance from injector registry
2201
- * @param target
2202
- * @param options
2203
- */
2204
-
2205
-
2206
- static get(target, options = {}) {
2207
- return DITest.injector.get(target, options);
2208
- }
2209
-
2210
- static configure(settings = {}) {
2211
- return _extends({}, settings, {
2212
- env: core.getValue(settings, "env", core.Env.TEST),
2213
- logger: _extends({}, core.getValue(settings, "logger", {}), {
2214
- level: core.getValue(settings, "logger.level", "off")
2215
- })
2216
- });
2217
- }
2218
-
2219
- }
2220
- DITest._injector = null;
2221
-
2222
- function getConfiguration(module, configuration = {}) {
2223
- const store = core.Store.from(module).get("configuration") || {};
2224
-
2225
- const config = _extends({}, store, configuration);
2226
-
2227
- if (store.mount && configuration.mount) {
2228
- config.mount = core.deepMerge(store.mount, configuration.mount);
2229
- }
2230
-
2231
- if (store.componentsScan && configuration.componentsScan) {
2232
- config.componentsScan = [...store.componentsScan, ...configuration.componentsScan];
2233
- }
2234
-
2235
- return config;
2236
- }
2237
-
2238
- exports.Configuration = Configuration;
2239
- exports.Constant = Constant;
2240
- exports.Container = Container;
2241
- exports.ContextLogger = ContextLogger;
2242
- exports.DIConfiguration = DIConfiguration;
2243
- exports.DIContext = DIContext;
2244
- exports.DITest = DITest;
2245
- exports.DI_PARAMS = DI_PARAMS;
2246
- exports.DI_PARAM_OPTIONS = DI_PARAM_OPTIONS;
2247
- exports.GlobalProviderRegistry = GlobalProviderRegistry;
2248
- exports.GlobalProviders = GlobalProviders;
2249
- exports.INJECTABLE_PROP = INJECTABLE_PROP;
2250
- exports.Inject = Inject;
2251
- exports.Injectable = Injectable;
2252
- exports.InjectionError = InjectionError;
2253
- exports.Intercept = Intercept;
2254
- exports.Interceptor = Interceptor;
2255
- exports.LocalsContainer = LocalsContainer;
2256
- exports.Module = Module;
2257
- exports.Opts = Opts;
2258
- exports.OverrideProvider = OverrideProvider;
2259
- exports.Provider = Provider;
2260
- exports.Scope = Scope;
2261
- exports.Service = Service;
2262
- exports.UndefinedTokenError = UndefinedTokenError;
2263
- exports.UseOpts = UseOpts;
2264
- exports.Value = Value;
2265
- exports.createContainer = createContainer;
2266
- exports.getConfiguration = getConfiguration;
2267
- exports.registerController = registerController;
2268
- exports.registerProvider = registerProvider;
2269
- exports.registerValue = registerValue;
2270
- exports.setLoggerLevel = setLoggerLevel;
2271
- //# sourceMappingURL=index.js.map