@tsed/di 6.87.1 → 6.89.0

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