@tsed/common 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 (409) hide show
  1. package/lib/cjs/builder/PlatformBuilder.js +275 -0
  2. package/lib/cjs/builder/PlatformBuilder.js.map +1 -0
  3. package/lib/cjs/builder/PlatformControllerBuilder.js +85 -0
  4. package/lib/cjs/builder/PlatformControllerBuilder.js.map +1 -0
  5. package/lib/cjs/config/index.js +7 -0
  6. package/lib/cjs/config/index.js.map +1 -0
  7. package/lib/cjs/config/interfaces/ConverterSettings.js +3 -0
  8. package/lib/cjs/config/interfaces/ConverterSettings.js.map +1 -0
  9. package/lib/cjs/config/interfaces/EndpointDirectoriesSettings.js +3 -0
  10. package/lib/cjs/config/interfaces/EndpointDirectoriesSettings.js.map +1 -0
  11. package/lib/cjs/config/interfaces/PlatformLoggerSettings.js +3 -0
  12. package/lib/cjs/config/interfaces/PlatformLoggerSettings.js.map +1 -0
  13. package/lib/cjs/config/interfaces/PlatformMulterSettings.js +3 -0
  14. package/lib/cjs/config/interfaces/PlatformMulterSettings.js.map +1 -0
  15. package/lib/cjs/config/interfaces/PlatformStaticsSettings.js +3 -0
  16. package/lib/cjs/config/interfaces/PlatformStaticsSettings.js.map +1 -0
  17. package/lib/cjs/config/interfaces/index.js +8 -0
  18. package/lib/cjs/config/interfaces/index.js.map +1 -0
  19. package/lib/cjs/config/services/PlatformConfiguration.js +181 -0
  20. package/lib/cjs/config/services/PlatformConfiguration.js.map +1 -0
  21. package/lib/cjs/constants/routerOptions.js +5 -0
  22. package/lib/cjs/constants/routerOptions.js.map +1 -0
  23. package/lib/cjs/decorators/httpServer.js +32 -0
  24. package/lib/cjs/decorators/httpServer.js.map +1 -0
  25. package/lib/cjs/decorators/httpsServer.js +32 -0
  26. package/lib/cjs/decorators/httpsServer.js.map +1 -0
  27. package/lib/cjs/decorators/index.js +26 -0
  28. package/lib/cjs/decorators/index.js.map +1 -0
  29. package/lib/cjs/decorators/method/acceptMime.js +28 -0
  30. package/lib/cjs/decorators/method/acceptMime.js.map +1 -0
  31. package/lib/cjs/decorators/multer/index.js +7 -0
  32. package/lib/cjs/decorators/multer/index.js.map +1 -0
  33. package/lib/cjs/decorators/multer/multerFileSize.js +35 -0
  34. package/lib/cjs/decorators/multer/multerFileSize.js.map +1 -0
  35. package/lib/cjs/decorators/multer/multerOptions.js +52 -0
  36. package/lib/cjs/decorators/multer/multerOptions.js.map +1 -0
  37. package/lib/cjs/decorators/multer/multipartFile.js +78 -0
  38. package/lib/cjs/decorators/multer/multipartFile.js.map +1 -0
  39. package/lib/cjs/decorators/params/error.js +20 -0
  40. package/lib/cjs/decorators/params/error.js.map +1 -0
  41. package/lib/cjs/decorators/params/next.js +21 -0
  42. package/lib/cjs/decorators/params/next.js.map +1 -0
  43. package/lib/cjs/decorators/params/request.js +39 -0
  44. package/lib/cjs/decorators/params/request.js.map +1 -0
  45. package/lib/cjs/decorators/params/response.js +33 -0
  46. package/lib/cjs/decorators/params/response.js.map +1 -0
  47. package/lib/cjs/domain/AnyToPromiseWithCtx.js +27 -0
  48. package/lib/cjs/domain/AnyToPromiseWithCtx.js.map +1 -0
  49. package/lib/cjs/domain/ControllerProvider.js +51 -0
  50. package/lib/cjs/domain/ControllerProvider.js.map +1 -0
  51. package/lib/cjs/domain/EndpointMetadata.js +70 -0
  52. package/lib/cjs/domain/EndpointMetadata.js.map +1 -0
  53. package/lib/cjs/domain/HandlerMetadata.js +57 -0
  54. package/lib/cjs/domain/HandlerMetadata.js.map +1 -0
  55. package/lib/cjs/domain/PlatformContext.js +92 -0
  56. package/lib/cjs/domain/PlatformContext.js.map +1 -0
  57. package/lib/cjs/domain/PlatformRouteDetails.js +24 -0
  58. package/lib/cjs/domain/PlatformRouteDetails.js.map +1 -0
  59. package/lib/cjs/domain/index.js +10 -0
  60. package/lib/cjs/domain/index.js.map +1 -0
  61. package/lib/cjs/index.js +34 -0
  62. package/lib/cjs/index.js.map +1 -0
  63. package/lib/cjs/interfaces/AfterInit.js +3 -0
  64. package/lib/cjs/interfaces/AfterInit.js.map +1 -0
  65. package/lib/cjs/interfaces/AfterListen.js +3 -0
  66. package/lib/cjs/interfaces/AfterListen.js.map +1 -0
  67. package/lib/cjs/interfaces/AfterRoutesInit.js +3 -0
  68. package/lib/cjs/interfaces/AfterRoutesInit.js.map +1 -0
  69. package/lib/cjs/interfaces/BeforeInit.js +3 -0
  70. package/lib/cjs/interfaces/BeforeInit.js.map +1 -0
  71. package/lib/cjs/interfaces/BeforeListen.js +3 -0
  72. package/lib/cjs/interfaces/BeforeListen.js.map +1 -0
  73. package/lib/cjs/interfaces/BeforeRoutesInit.js +3 -0
  74. package/lib/cjs/interfaces/BeforeRoutesInit.js.map +1 -0
  75. package/lib/cjs/interfaces/HandlerType.js +17 -0
  76. package/lib/cjs/interfaces/HandlerType.js.map +1 -0
  77. package/lib/cjs/interfaces/IncomingEvent.js +3 -0
  78. package/lib/cjs/interfaces/IncomingEvent.js.map +1 -0
  79. package/lib/cjs/interfaces/OnReady.js +3 -0
  80. package/lib/cjs/interfaces/OnReady.js.map +1 -0
  81. package/lib/cjs/interfaces/OnRequest.js +3 -0
  82. package/lib/cjs/interfaces/OnRequest.js.map +1 -0
  83. package/lib/cjs/interfaces/OnResponse.js +3 -0
  84. package/lib/cjs/interfaces/OnResponse.js.map +1 -0
  85. package/lib/cjs/interfaces/OnRoutesInit.js +3 -0
  86. package/lib/cjs/interfaces/OnRoutesInit.js.map +1 -0
  87. package/lib/cjs/interfaces/PathType.js +3 -0
  88. package/lib/cjs/interfaces/PathType.js.map +1 -0
  89. package/lib/cjs/interfaces/PlatformAdapter.js +3 -0
  90. package/lib/cjs/interfaces/PlatformAdapter.js.map +1 -0
  91. package/lib/cjs/interfaces/PlatformRouteOptions.js +3 -0
  92. package/lib/cjs/interfaces/PlatformRouteOptions.js.map +1 -0
  93. package/lib/cjs/interfaces/ResponseErrorObject.js +3 -0
  94. package/lib/cjs/interfaces/ResponseErrorObject.js.map +1 -0
  95. package/lib/cjs/interfaces/Route.js +3 -0
  96. package/lib/cjs/interfaces/Route.js.map +1 -0
  97. package/lib/cjs/interfaces/index.js +21 -0
  98. package/lib/cjs/interfaces/index.js.map +1 -0
  99. package/lib/cjs/middlewares/PlatformAcceptMimesMiddleware.js +37 -0
  100. package/lib/cjs/middlewares/PlatformAcceptMimesMiddleware.js.map +1 -0
  101. package/lib/cjs/middlewares/PlatformMulterMiddleware.js +55 -0
  102. package/lib/cjs/middlewares/PlatformMulterMiddleware.js.map +1 -0
  103. package/lib/cjs/middlewares/__mock__/FakeCtrl.js +12 -0
  104. package/lib/cjs/middlewares/__mock__/FakeCtrl.js.map +1 -0
  105. package/lib/cjs/middlewares/bindEndpointMiddleware.js +13 -0
  106. package/lib/cjs/middlewares/bindEndpointMiddleware.js.map +1 -0
  107. package/lib/cjs/middlewares/index.js +7 -0
  108. package/lib/cjs/middlewares/index.js.map +1 -0
  109. package/lib/cjs/services/FakeRawDriver.js +26 -0
  110. package/lib/cjs/services/FakeRawDriver.js.map +1 -0
  111. package/lib/cjs/services/Platform.js +107 -0
  112. package/lib/cjs/services/Platform.js.map +1 -0
  113. package/lib/cjs/services/PlatformApplication.js +34 -0
  114. package/lib/cjs/services/PlatformApplication.js.map +1 -0
  115. package/lib/cjs/services/PlatformHandler.js +233 -0
  116. package/lib/cjs/services/PlatformHandler.js.map +1 -0
  117. package/lib/cjs/services/PlatformMiddlewaresChain.js +34 -0
  118. package/lib/cjs/services/PlatformMiddlewaresChain.js.map +1 -0
  119. package/lib/cjs/services/PlatformRequest.js +138 -0
  120. package/lib/cjs/services/PlatformRequest.js.map +1 -0
  121. package/lib/cjs/services/PlatformResponse.js +271 -0
  122. package/lib/cjs/services/PlatformResponse.js.map +1 -0
  123. package/lib/cjs/services/PlatformRouter.js +126 -0
  124. package/lib/cjs/services/PlatformRouter.js.map +1 -0
  125. package/lib/cjs/services/PlatformTest.js +166 -0
  126. package/lib/cjs/services/PlatformTest.js.map +1 -0
  127. package/lib/cjs/services/index.js +12 -0
  128. package/lib/cjs/services/index.js.map +1 -0
  129. package/lib/cjs/utils/createContext.js +38 -0
  130. package/lib/cjs/utils/createContext.js.map +1 -0
  131. package/lib/cjs/utils/createHandlerMetadata.js +49 -0
  132. package/lib/cjs/utils/createHandlerMetadata.js.map +1 -0
  133. package/lib/cjs/utils/createHttpServer.js +34 -0
  134. package/lib/cjs/utils/createHttpServer.js.map +1 -0
  135. package/lib/cjs/utils/createHttpsServer.js +34 -0
  136. package/lib/cjs/utils/createHttpsServer.js.map +1 -0
  137. package/lib/cjs/utils/createInjector.js +38 -0
  138. package/lib/cjs/utils/createInjector.js.map +1 -0
  139. package/lib/cjs/utils/getConfiguration.js +42 -0
  140. package/lib/cjs/utils/getConfiguration.js.map +1 -0
  141. package/lib/cjs/utils/getStaticsOptions.js +21 -0
  142. package/lib/cjs/utils/getStaticsOptions.js.map +1 -0
  143. package/lib/cjs/utils/index.js +11 -0
  144. package/lib/cjs/utils/index.js.map +1 -0
  145. package/lib/cjs/utils/listenServer.js +21 -0
  146. package/lib/cjs/utils/listenServer.js.map +1 -0
  147. package/lib/cjs/utils/mapReturnedResponse.js +15 -0
  148. package/lib/cjs/utils/mapReturnedResponse.js.map +1 -0
  149. package/lib/cjs/utils/printRoutes.js +36 -0
  150. package/lib/cjs/utils/printRoutes.js.map +1 -0
  151. package/lib/cjs/utils/setResponseHeaders.js +35 -0
  152. package/lib/cjs/utils/setResponseHeaders.js.map +1 -0
  153. package/lib/cjs/utils/useCtxHandler.js +15 -0
  154. package/lib/cjs/utils/useCtxHandler.js.map +1 -0
  155. package/lib/esm/builder/PlatformBuilder.js +271 -0
  156. package/lib/esm/builder/PlatformBuilder.js.map +1 -0
  157. package/lib/esm/builder/PlatformControllerBuilder.js +79 -0
  158. package/lib/esm/builder/PlatformControllerBuilder.js.map +1 -0
  159. package/lib/esm/config/index.js +4 -0
  160. package/lib/esm/config/index.js.map +1 -0
  161. package/lib/esm/config/interfaces/ConverterSettings.js +2 -0
  162. package/lib/esm/config/interfaces/ConverterSettings.js.map +1 -0
  163. package/lib/esm/config/interfaces/EndpointDirectoriesSettings.js +2 -0
  164. package/lib/esm/config/interfaces/EndpointDirectoriesSettings.js.map +1 -0
  165. package/lib/esm/config/interfaces/PlatformLoggerSettings.js +2 -0
  166. package/lib/esm/config/interfaces/PlatformLoggerSettings.js.map +1 -0
  167. package/lib/esm/config/interfaces/PlatformMulterSettings.js +2 -0
  168. package/lib/esm/config/interfaces/PlatformMulterSettings.js.map +1 -0
  169. package/lib/esm/config/interfaces/PlatformStaticsSettings.js +2 -0
  170. package/lib/esm/config/interfaces/PlatformStaticsSettings.js.map +1 -0
  171. package/lib/esm/config/interfaces/index.js +5 -0
  172. package/lib/esm/config/interfaces/index.js.map +1 -0
  173. package/lib/esm/config/services/PlatformConfiguration.js +178 -0
  174. package/lib/esm/config/services/PlatformConfiguration.js.map +1 -0
  175. package/lib/esm/constants/routerOptions.js +2 -0
  176. package/lib/esm/constants/routerOptions.js.map +1 -0
  177. package/lib/esm/decorators/httpServer.js +28 -0
  178. package/lib/esm/decorators/httpServer.js.map +1 -0
  179. package/lib/esm/decorators/httpsServer.js +28 -0
  180. package/lib/esm/decorators/httpsServer.js.map +1 -0
  181. package/lib/esm/decorators/index.js +14 -0
  182. package/lib/esm/decorators/index.js.map +1 -0
  183. package/lib/esm/decorators/method/acceptMime.js +24 -0
  184. package/lib/esm/decorators/method/acceptMime.js.map +1 -0
  185. package/lib/esm/decorators/multer/index.js +4 -0
  186. package/lib/esm/decorators/multer/index.js.map +1 -0
  187. package/lib/esm/decorators/multer/multerFileSize.js +31 -0
  188. package/lib/esm/decorators/multer/multerFileSize.js.map +1 -0
  189. package/lib/esm/decorators/multer/multerOptions.js +48 -0
  190. package/lib/esm/decorators/multer/multerOptions.js.map +1 -0
  191. package/lib/esm/decorators/multer/multipartFile.js +74 -0
  192. package/lib/esm/decorators/multer/multipartFile.js.map +1 -0
  193. package/lib/esm/decorators/params/error.js +16 -0
  194. package/lib/esm/decorators/params/error.js.map +1 -0
  195. package/lib/esm/decorators/params/next.js +17 -0
  196. package/lib/esm/decorators/params/next.js.map +1 -0
  197. package/lib/esm/decorators/params/request.js +34 -0
  198. package/lib/esm/decorators/params/request.js.map +1 -0
  199. package/lib/esm/decorators/params/response.js +28 -0
  200. package/lib/esm/decorators/params/response.js.map +1 -0
  201. package/lib/esm/domain/AnyToPromiseWithCtx.js +23 -0
  202. package/lib/esm/domain/AnyToPromiseWithCtx.js.map +1 -0
  203. package/lib/esm/domain/ControllerProvider.js +47 -0
  204. package/lib/esm/domain/ControllerProvider.js.map +1 -0
  205. package/lib/esm/domain/EndpointMetadata.js +67 -0
  206. package/lib/esm/domain/EndpointMetadata.js.map +1 -0
  207. package/lib/esm/domain/HandlerMetadata.js +53 -0
  208. package/lib/esm/domain/HandlerMetadata.js.map +1 -0
  209. package/lib/esm/domain/PlatformContext.js +88 -0
  210. package/lib/esm/domain/PlatformContext.js.map +1 -0
  211. package/lib/esm/domain/PlatformRouteDetails.js +20 -0
  212. package/lib/esm/domain/PlatformRouteDetails.js.map +1 -0
  213. package/lib/esm/domain/index.js +7 -0
  214. package/lib/esm/domain/index.js.map +1 -0
  215. package/lib/esm/index.js +28 -0
  216. package/lib/esm/index.js.map +1 -0
  217. package/lib/esm/interfaces/AfterInit.js +2 -0
  218. package/lib/esm/interfaces/AfterInit.js.map +1 -0
  219. package/lib/esm/interfaces/AfterListen.js +2 -0
  220. package/lib/esm/interfaces/AfterListen.js.map +1 -0
  221. package/lib/esm/interfaces/AfterRoutesInit.js +2 -0
  222. package/lib/esm/interfaces/AfterRoutesInit.js.map +1 -0
  223. package/lib/esm/interfaces/BeforeInit.js +2 -0
  224. package/lib/esm/interfaces/BeforeInit.js.map +1 -0
  225. package/lib/esm/interfaces/BeforeListen.js +2 -0
  226. package/lib/esm/interfaces/BeforeListen.js.map +1 -0
  227. package/lib/esm/interfaces/BeforeRoutesInit.js +2 -0
  228. package/lib/esm/interfaces/BeforeRoutesInit.js.map +1 -0
  229. package/lib/esm/interfaces/HandlerType.js +14 -0
  230. package/lib/esm/interfaces/HandlerType.js.map +1 -0
  231. package/lib/esm/interfaces/IncomingEvent.js +2 -0
  232. package/lib/esm/interfaces/IncomingEvent.js.map +1 -0
  233. package/lib/esm/interfaces/OnReady.js +2 -0
  234. package/lib/esm/interfaces/OnReady.js.map +1 -0
  235. package/lib/esm/interfaces/OnRequest.js +2 -0
  236. package/lib/esm/interfaces/OnRequest.js.map +1 -0
  237. package/lib/esm/interfaces/OnResponse.js +2 -0
  238. package/lib/esm/interfaces/OnResponse.js.map +1 -0
  239. package/lib/esm/interfaces/OnRoutesInit.js +2 -0
  240. package/lib/esm/interfaces/OnRoutesInit.js.map +1 -0
  241. package/lib/esm/interfaces/PathType.js +2 -0
  242. package/lib/esm/interfaces/PathType.js.map +1 -0
  243. package/lib/esm/interfaces/PlatformAdapter.js +2 -0
  244. package/lib/esm/interfaces/PlatformAdapter.js.map +1 -0
  245. package/lib/esm/interfaces/PlatformRouteOptions.js +2 -0
  246. package/lib/esm/interfaces/PlatformRouteOptions.js.map +1 -0
  247. package/lib/esm/interfaces/ResponseErrorObject.js +2 -0
  248. package/lib/esm/interfaces/ResponseErrorObject.js.map +1 -0
  249. package/lib/esm/interfaces/Route.js +2 -0
  250. package/lib/esm/interfaces/Route.js.map +1 -0
  251. package/lib/esm/interfaces/index.js +18 -0
  252. package/lib/esm/interfaces/index.js.map +1 -0
  253. package/lib/esm/middlewares/PlatformAcceptMimesMiddleware.js +34 -0
  254. package/lib/esm/middlewares/PlatformAcceptMimesMiddleware.js.map +1 -0
  255. package/lib/esm/middlewares/PlatformMulterMiddleware.js +52 -0
  256. package/lib/esm/middlewares/PlatformMulterMiddleware.js.map +1 -0
  257. package/lib/esm/middlewares/__mock__/FakeCtrl.js +9 -0
  258. package/lib/esm/middlewares/__mock__/FakeCtrl.js.map +1 -0
  259. package/lib/esm/middlewares/bindEndpointMiddleware.js +9 -0
  260. package/lib/esm/middlewares/bindEndpointMiddleware.js.map +1 -0
  261. package/lib/esm/middlewares/index.js +4 -0
  262. package/lib/esm/middlewares/index.js.map +1 -0
  263. package/lib/esm/services/FakeRawDriver.js +22 -0
  264. package/lib/esm/services/FakeRawDriver.js.map +1 -0
  265. package/lib/esm/services/Platform.js +104 -0
  266. package/lib/esm/services/Platform.js.map +1 -0
  267. package/lib/esm/services/PlatformApplication.js +31 -0
  268. package/lib/esm/services/PlatformApplication.js.map +1 -0
  269. package/lib/esm/services/PlatformHandler.js +230 -0
  270. package/lib/esm/services/PlatformHandler.js.map +1 -0
  271. package/lib/esm/services/PlatformMiddlewaresChain.js +31 -0
  272. package/lib/esm/services/PlatformMiddlewaresChain.js.map +1 -0
  273. package/lib/esm/services/PlatformRequest.js +135 -0
  274. package/lib/esm/services/PlatformRequest.js.map +1 -0
  275. package/lib/esm/services/PlatformResponse.js +268 -0
  276. package/lib/esm/services/PlatformResponse.js.map +1 -0
  277. package/lib/esm/services/PlatformRouter.js +123 -0
  278. package/lib/esm/services/PlatformRouter.js.map +1 -0
  279. package/lib/esm/services/PlatformTest.js +162 -0
  280. package/lib/esm/services/PlatformTest.js.map +1 -0
  281. package/lib/esm/services/index.js +9 -0
  282. package/lib/esm/services/index.js.map +1 -0
  283. package/lib/esm/utils/createContext.js +34 -0
  284. package/lib/esm/utils/createContext.js.map +1 -0
  285. package/lib/esm/utils/createHandlerMetadata.js +45 -0
  286. package/lib/esm/utils/createHandlerMetadata.js.map +1 -0
  287. package/lib/esm/utils/createHttpServer.js +29 -0
  288. package/lib/esm/utils/createHttpServer.js.map +1 -0
  289. package/lib/esm/utils/createHttpsServer.js +29 -0
  290. package/lib/esm/utils/createHttpsServer.js.map +1 -0
  291. package/lib/esm/utils/createInjector.js +34 -0
  292. package/lib/esm/utils/createInjector.js.map +1 -0
  293. package/lib/esm/utils/getConfiguration.js +38 -0
  294. package/lib/esm/utils/getConfiguration.js.map +1 -0
  295. package/lib/esm/utils/getStaticsOptions.js +17 -0
  296. package/lib/esm/utils/getStaticsOptions.js.map +1 -0
  297. package/lib/esm/utils/index.js +8 -0
  298. package/lib/esm/utils/index.js.map +1 -0
  299. package/lib/esm/utils/listenServer.js +17 -0
  300. package/lib/esm/utils/listenServer.js.map +1 -0
  301. package/lib/esm/utils/mapReturnedResponse.js +11 -0
  302. package/lib/esm/utils/mapReturnedResponse.js.map +1 -0
  303. package/lib/esm/utils/printRoutes.js +32 -0
  304. package/lib/esm/utils/printRoutes.js.map +1 -0
  305. package/lib/esm/utils/setResponseHeaders.js +31 -0
  306. package/lib/esm/utils/setResponseHeaders.js.map +1 -0
  307. package/lib/esm/utils/useCtxHandler.js +11 -0
  308. package/lib/esm/utils/useCtxHandler.js.map +1 -0
  309. package/lib/{builder → types/builder}/PlatformBuilder.d.ts +25 -30
  310. package/lib/types/builder/PlatformControllerBuilder.d.ts +17 -0
  311. package/lib/{config → types/config}/index.d.ts +0 -0
  312. package/lib/{config → types/config}/interfaces/ConverterSettings.d.ts +0 -0
  313. package/lib/{config → types/config}/interfaces/EndpointDirectoriesSettings.d.ts +0 -0
  314. package/lib/{config → types/config}/interfaces/PlatformLoggerSettings.d.ts +0 -16
  315. package/lib/{config → types/config}/interfaces/PlatformMulterSettings.d.ts +0 -0
  316. package/lib/{config → types/config}/interfaces/PlatformStaticsSettings.d.ts +1 -0
  317. package/lib/{config → types/config}/interfaces/index.d.ts +17 -2
  318. package/lib/{config → types/config}/services/PlatformConfiguration.d.ts +13 -11
  319. package/lib/{constants → types/constants}/routerOptions.d.ts +0 -0
  320. package/lib/{decorators → types/decorators}/httpServer.d.ts +1 -0
  321. package/lib/{decorators → types/decorators}/httpsServer.d.ts +1 -0
  322. package/lib/{decorators → types/decorators}/index.d.ts +1 -5
  323. package/lib/{decorators → types/decorators}/method/acceptMime.d.ts +0 -0
  324. package/lib/{decorators → types/decorators}/multer/index.d.ts +0 -0
  325. package/lib/{decorators → types/decorators}/multer/multerFileSize.d.ts +0 -0
  326. package/lib/{decorators → types/decorators}/multer/multerOptions.d.ts +0 -0
  327. package/lib/{decorators → types/decorators}/multer/multipartFile.d.ts +0 -0
  328. package/lib/{decorators → types/decorators}/params/error.d.ts +0 -0
  329. package/lib/{decorators → types/decorators}/params/next.d.ts +0 -0
  330. package/lib/{decorators → types/decorators}/params/request.d.ts +0 -0
  331. package/lib/{decorators → types/decorators}/params/response.d.ts +0 -0
  332. package/lib/{domain → types/domain}/AnyToPromiseWithCtx.d.ts +0 -0
  333. package/lib/types/domain/ControllerProvider.d.ts +24 -0
  334. package/lib/{domain → types/domain}/EndpointMetadata.d.ts +3 -42
  335. package/lib/{domain → types/domain}/HandlerMetadata.d.ts +2 -2
  336. package/lib/{domain → types/domain}/PlatformContext.d.ts +1 -1
  337. package/lib/{domain → types/domain}/PlatformRouteDetails.d.ts +4 -10
  338. package/lib/{domain → types/domain}/index.d.ts +0 -0
  339. package/lib/{index.d.ts → types/index.d.ts} +2 -3
  340. package/lib/{interfaces → types/interfaces}/AfterInit.d.ts +0 -0
  341. package/lib/{interfaces → types/interfaces}/AfterListen.d.ts +0 -0
  342. package/lib/{interfaces → types/interfaces}/AfterRoutesInit.d.ts +0 -0
  343. package/lib/{interfaces → types/interfaces}/BeforeInit.d.ts +0 -0
  344. package/lib/{interfaces → types/interfaces}/BeforeListen.d.ts +0 -0
  345. package/lib/{interfaces → types/interfaces}/BeforeRoutesInit.d.ts +0 -0
  346. package/lib/{interfaces → types/interfaces}/HandlerType.d.ts +0 -0
  347. package/lib/{interfaces → types/interfaces}/IncomingEvent.d.ts +0 -0
  348. package/lib/{interfaces → types/interfaces}/OnReady.d.ts +0 -0
  349. package/lib/{interfaces → types/interfaces}/OnRequest.d.ts +0 -0
  350. package/lib/{interfaces → types/interfaces}/OnResponse.d.ts +0 -0
  351. package/lib/{interfaces → types/interfaces}/OnRoutesInit.d.ts +0 -0
  352. package/lib/{interfaces → types/interfaces}/PathType.d.ts +0 -0
  353. package/lib/types/interfaces/PlatformAdapter.d.ts +19 -0
  354. package/lib/{interfaces → types/interfaces}/PlatformRouteOptions.d.ts +5 -3
  355. package/lib/{interfaces → types/interfaces}/ResponseErrorObject.d.ts +0 -0
  356. package/lib/{interfaces → types/interfaces}/Route.d.ts +0 -0
  357. package/lib/{interfaces → types/interfaces}/index.d.ts +1 -2
  358. package/lib/{middlewares → types/middlewares}/PlatformAcceptMimesMiddleware.d.ts +0 -0
  359. package/lib/{middlewares → types/middlewares}/PlatformMulterMiddleware.d.ts +0 -0
  360. package/lib/{middlewares/data → types/middlewares/__mock__}/FakeCtrl.d.ts +0 -0
  361. package/lib/{middlewares → types/middlewares}/bindEndpointMiddleware.d.ts +0 -0
  362. package/lib/{middlewares → types/middlewares}/index.d.ts +0 -1
  363. package/lib/{services → types/services}/FakeRawDriver.d.ts +0 -0
  364. package/lib/{services → types/services}/Platform.d.ts +12 -6
  365. package/lib/{services → types/services}/PlatformApplication.d.ts +0 -0
  366. package/lib/{services → types/services}/PlatformHandler.d.ts +3 -8
  367. package/lib/types/services/PlatformMiddlewaresChain.d.ts +6 -0
  368. package/lib/{services → types/services}/PlatformRequest.d.ts +2 -1
  369. package/lib/{services → types/services}/PlatformResponse.d.ts +4 -4
  370. package/lib/{services → types/services}/PlatformRouter.d.ts +4 -3
  371. package/lib/{services → types/services}/PlatformTest.d.ts +7 -6
  372. package/lib/{services → types/services}/index.d.ts +1 -1
  373. package/lib/{utils → types/utils}/createContext.d.ts +0 -0
  374. package/lib/{utils → types/utils}/createHandlerMetadata.d.ts +0 -0
  375. package/lib/types/utils/createHttpServer.d.ts +4 -0
  376. package/lib/types/utils/createHttpsServer.d.ts +4 -0
  377. package/lib/types/utils/createInjector.d.ts +7 -0
  378. package/lib/types/utils/getConfiguration.d.ts +2 -0
  379. package/lib/types/utils/getStaticsOptions.d.ts +5 -0
  380. package/lib/{utils → types/utils}/index.d.ts +0 -1
  381. package/lib/types/utils/listenServer.d.ts +7 -0
  382. package/lib/{utils → types/utils}/mapReturnedResponse.d.ts +0 -0
  383. package/lib/{utils → types/utils}/printRoutes.d.ts +0 -0
  384. package/lib/{utils → types/utils}/setResponseHeaders.d.ts +0 -0
  385. package/lib/{utils → types/utils}/useCtxHandler.d.ts +0 -0
  386. package/package.json +29 -24
  387. package/tsconfig.compile.esm.json +23 -0
  388. package/lib/PlatformModule.d.ts +0 -15
  389. package/lib/builder/PlatformControllerBuilder.d.ts +0 -19
  390. package/lib/decorators/class/controller.d.ts +0 -43
  391. package/lib/decorators/method/endpointFn.d.ts +0 -8
  392. package/lib/decorators/method/location.d.ts +0 -1
  393. package/lib/decorators/method/redirect.d.ts +0 -1
  394. package/lib/decorators/method/route.d.ts +0 -128
  395. package/lib/domain/ControllerProvider.d.ts +0 -54
  396. package/lib/index.js +0 -3990
  397. package/lib/index.js.map +0 -1
  398. package/lib/index.modern.js +0 -3870
  399. package/lib/index.modern.js.map +0 -1
  400. package/lib/interfaces/PlatformRouterMethods.d.ts +0 -10
  401. package/lib/middlewares/PlatformLogMiddleware.d.ts +0 -44
  402. package/lib/registries/ControllerRegistry.d.ts +0 -1
  403. package/lib/services/ConverterService.d.ts +0 -27
  404. package/lib/utils/createHttpServer.d.ts +0 -3
  405. package/lib/utils/createHttpsServer.d.ts +0 -3
  406. package/lib/utils/createInjector.d.ts +0 -2
  407. package/lib/utils/createPlatformApplication.d.ts +0 -2
  408. package/lib/utils/getControllerPath.d.ts +0 -2
  409. package/lib/utils/listenServer.d.ts +0 -10
@@ -1,3870 +0,0 @@
1
- import { DIConfiguration, ProviderType, ProviderScope, Injectable, InjectorService, Configuration, Inject, Constant, Scope, DIContext, Provider, Module, setLoggerLevel, GlobalProviders, registerProvider, Container, createContainer, getConfiguration, registerController, DITest } from '@tsed/di';
2
- export * from '@tsed/di';
3
- import { Context, ParamTypes, ParamMetadata, PlatformParams, UseParam, mapParamsOptions } from '@tsed/platform-params';
4
- export * from '@tsed/platform-params';
5
- export * from '@tsed/platform-exceptions';
6
- import { PlatformResponseFilter } from '@tsed/platform-response-filter';
7
- export * from '@tsed/platform-response-filter';
8
- export * from '@tsed/platform-cache';
9
- import { Middleware, getMiddlewaresForHook, Use } from '@tsed/platform-middlewares';
10
- export * from '@tsed/platform-middlewares';
11
- import { renderView, PlatformViews } from '@tsed/platform-views';
12
- export * from '@tsed/platform-views';
13
- import { importProviders } from '@tsed/components-scan';
14
- export * from '@tsed/components-scan';
15
- import { $log, colorize } from '@tsed/logger';
16
- export { $log, Logger } from '@tsed/logger';
17
- import { __decorate, __metadata, __param } from 'tslib';
18
- import { Env, AnyToPromise, AnyToPromiseStatus, nameOf, Store, descriptorOf, classOf, prototypeOf, deepMerge, isFunction, Enumerable, DecoratorTypes, isStream, isBoolean, isNumber, isString, uniq, toMap, constructorOf, StoreMerge, Metadata, useDecorators, useMethodDecorators, isArrayOrArrayClass, isClass } from '@tsed/core';
19
- import { PerfLogger } from '@tsed/perf';
20
- import { Exception, NotAcceptable } from '@tsed/exceptions';
21
- import { JsonEntityStore, getOperationsStores, JsonEntityComponent, OperationMethods, Returns, Consumes, JsonEntityFn, Produces } from '@tsed/schema';
22
- export { Location, Redirect } from '@tsed/schema';
23
- import { serialize, deserialize } from '@tsed/json-mapper';
24
- import { promisify } from 'util';
25
- import Http, { ServerResponse, IncomingMessage } from 'http';
26
- import Https from 'https';
27
-
28
- function _extends() {
29
- _extends = Object.assign || function (target) {
30
- for (var i = 1; i < arguments.length; i++) {
31
- var source = arguments[i];
32
-
33
- for (var key in source) {
34
- if (Object.prototype.hasOwnProperty.call(source, key)) {
35
- target[key] = source[key];
36
- }
37
- }
38
- }
39
-
40
- return target;
41
- };
42
-
43
- return _extends.apply(this, arguments);
44
- }
45
-
46
- function _objectWithoutPropertiesLoose(source, excluded) {
47
- if (source == null) return {};
48
- var target = {};
49
- var sourceKeys = Object.keys(source);
50
- var key, i;
51
-
52
- for (i = 0; i < sourceKeys.length; i++) {
53
- key = sourceKeys[i];
54
- if (excluded.indexOf(key) >= 0) continue;
55
- target[key] = source[key];
56
- }
57
-
58
- return target;
59
- }
60
-
61
- var id = 0;
62
-
63
- function _classPrivateFieldLooseKey(name) {
64
- return "__private_" + id++ + "_" + name;
65
- }
66
-
67
- function _classPrivateFieldLooseBase(receiver, privateKey) {
68
- if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) {
69
- throw new TypeError("attempted to use private field on non-instance");
70
- }
71
-
72
- return receiver;
73
- }
74
-
75
- var PlatformConfiguration_1;
76
- const rootDir = process.cwd();
77
- /**
78
- * `PlatformConfiguration` contains all information about your Server configuration.
79
- */
80
-
81
- let PlatformConfiguration = PlatformConfiguration_1 = class PlatformConfiguration extends DIConfiguration {
82
- constructor() {
83
- super({
84
- rootDir,
85
- env: process.env.NODE_ENV || Env.DEV,
86
- httpPort: 8080,
87
- httpsPort: false,
88
- scopes: {
89
- [ProviderType.CONTROLLER]: ProviderScope.SINGLETON
90
- },
91
- logger: {
92
- debug: false,
93
- level: "info",
94
- logRequest: true,
95
- jsonIndentation: process.env.NODE_ENV === Env.PROD ? 0 : 2
96
- },
97
- errors: {
98
- headerName: "errors"
99
- },
100
- mount: {
101
- "/rest": "${rootDir}/controllers/**/*.ts"
102
- },
103
- exclude: ["**/*.spec.ts", "**/*.spec.js"],
104
- componentsScan: ["${rootDir}/mvc/**/*.ts", "${rootDir}/services/**/*.ts", "${rootDir}/middlewares/**/*.ts"]
105
- });
106
- }
107
-
108
- get version() {
109
- return this.getRaw("version");
110
- }
111
-
112
- set version(v) {
113
- this.setRaw("version", v);
114
- }
115
-
116
- get rootDir() {
117
- return this.getRaw("rootDir");
118
- }
119
-
120
- set rootDir(value) {
121
- this.setRaw("rootDir", value);
122
- }
123
-
124
- get port() {
125
- return this.httpPort;
126
- }
127
-
128
- set port(value) {
129
- this.httpPort = value;
130
- }
131
-
132
- get httpsOptions() {
133
- return this.getRaw("httpsOptions");
134
- }
135
-
136
- set httpsOptions(value) {
137
- this.setRaw("httpsOptions", value);
138
- }
139
-
140
- get httpPort() {
141
- return this.getRaw("httpPort");
142
- }
143
-
144
- set httpPort(value) {
145
- this.setRaw("httpPort", value);
146
- }
147
-
148
- get httpsPort() {
149
- return this.getRaw("httpsPort");
150
- }
151
-
152
- set httpsPort(value) {
153
- this.setRaw("httpsPort", value);
154
- }
155
-
156
- get env() {
157
- return this.getRaw("env");
158
- }
159
-
160
- set env(value) {
161
- this.setRaw("env", value);
162
- }
163
-
164
- get mount() {
165
- return this.get("mount");
166
- }
167
-
168
- set mount(value) {
169
- this.setRaw("mount", value);
170
- }
171
-
172
- get componentsScan() {
173
- return this.resolve(this.getRaw("componentsScan"));
174
- }
175
-
176
- set componentsScan(value) {
177
- this.setRaw("componentsScan", value);
178
- }
179
-
180
- get statics() {
181
- return this.getRaw("statics") || this.getRaw("serveStatic") || {};
182
- }
183
-
184
- set statics(value) {
185
- this.setRaw("statics", value);
186
- }
187
-
188
- get acceptMimes() {
189
- return this.getRaw("acceptMimes");
190
- }
191
-
192
- set acceptMimes(value) {
193
- this.setRaw("acceptMimes", value || []);
194
- }
195
-
196
- get debug() {
197
- return this.logger.level === "debug";
198
- }
199
-
200
- set debug(debug) {
201
- this.logger = _extends({}, this.logger, {
202
- level: debug ? "debug" : "info"
203
- });
204
- }
205
-
206
- get converter() {
207
- return this.get("converter") || {};
208
- }
209
-
210
- set converter(options) {
211
- this.setRaw("converter", options);
212
- }
213
-
214
- get logger() {
215
- return this.get("logger");
216
- }
217
-
218
- set logger(value) {
219
- const logger = _extends({}, this.logger, value);
220
-
221
- logger.debug = logger.level === "debug";
222
- this.setRaw("logger", logger);
223
- this.setRaw("debug", logger.debug);
224
-
225
- if (logger.format) {
226
- $log.appenders.set("stdout", {
227
- type: "stdout",
228
- levels: ["info", "debug"],
229
- layout: {
230
- type: "pattern",
231
- pattern: logger.format
232
- }
233
- });
234
- $log.appenders.set("stderr", {
235
- levels: ["trace", "fatal", "error", "warn"],
236
- type: "stderr",
237
- layout: {
238
- type: "pattern",
239
- pattern: logger.format
240
- }
241
- });
242
- }
243
- }
244
-
245
- get exclude() {
246
- return this.get("exclude");
247
- }
248
-
249
- set exclude(exclude) {
250
- this.setRaw("exclude", exclude);
251
- }
252
- /**
253
- *
254
- * @param addressPort
255
- * @returns {{address: string, port: number}}
256
- */
257
-
258
-
259
- static buildAddressAndPort(addressPort) {
260
- let address = "0.0.0.0";
261
- let port = addressPort;
262
-
263
- if (typeof addressPort === "string" && addressPort.indexOf(":") > -1) {
264
- [address, port] = addressPort.split(":");
265
- port = +port;
266
- }
267
-
268
- return {
269
- address,
270
- port: port
271
- };
272
- }
273
- /**
274
- *
275
- * @returns {string|number}
276
- */
277
-
278
-
279
- getHttpPort() {
280
- return PlatformConfiguration_1.buildAddressAndPort(this.getRaw("httpPort"));
281
- }
282
- /**
283
- *
284
- * @param settings
285
- */
286
-
287
-
288
- setHttpPort(settings) {
289
- this.setRaw("httpPort", `${settings.address}:${settings.port}`);
290
- }
291
- /**
292
- *
293
- * @returns {string|number}
294
- */
295
-
296
-
297
- getHttpsPort() {
298
- return PlatformConfiguration_1.buildAddressAndPort(this.getRaw("httpsPort"));
299
- }
300
- /**
301
- *
302
- * @param settings
303
- */
304
-
305
-
306
- setHttpsPort(settings) {
307
- this.setRaw("httpsPort", `${settings.address}:${settings.port}`);
308
- }
309
-
310
- };
311
- PlatformConfiguration = PlatformConfiguration_1 = __decorate([Injectable({
312
- scope: ProviderScope.SINGLETON,
313
- global: true
314
- }), __metadata("design:paramtypes", [])], PlatformConfiguration);
315
-
316
- /**
317
- * @ignore
318
- */
319
- function bindEndpointMiddleware(endpoint) {
320
- return ctx => {
321
- ctx.endpoint = endpoint;
322
- };
323
- }
324
-
325
- var PlatformLogMiddleware_1;
326
- /**
327
- * @middleware
328
- * @platform
329
- */
330
-
331
- let PlatformLogMiddleware = PlatformLogMiddleware_1 = class PlatformLogMiddleware {
332
- // tslint:disable-next-line: no-unused-variable
333
- constructor(injector) {
334
- this.settings = injector.settings.logger || {};
335
- this.settings.requestFields = this.settings.requestFields || PlatformLogMiddleware_1.DEFAULT_FIELDS;
336
-
337
- if (this.settings.level !== "off") {
338
- this.$onResponse = this.onLogEnd.bind(this);
339
- }
340
- }
341
- /**
342
- * Handle the request.
343
- */
344
-
345
-
346
- use(ctx) {
347
- this.configureRequest(ctx);
348
- this.onLogStart(ctx);
349
- }
350
- /**
351
- * The separate onLogStart() function will allow developer to overwrite the initial request log.
352
- * @param ctx
353
- */
354
-
355
-
356
- onLogStart(ctx) {
357
- const {
358
- debug,
359
- logRequest,
360
- logStart
361
- } = this.settings;
362
-
363
- if (logStart !== false) {
364
- if (debug) {
365
- ctx.logger.debug({
366
- event: "request.start"
367
- });
368
- } else if (logRequest) {
369
- ctx.logger.info({
370
- event: "request.start"
371
- });
372
- }
373
- }
374
- }
375
- /**
376
- * Called when the `$onResponse` is called by Ts.ED (through Express.end).
377
- */
378
-
379
-
380
- onLogEnd(ctx) {
381
- const {
382
- debug,
383
- logRequest,
384
- logEnd
385
- } = this.settings;
386
-
387
- if (logEnd !== false) {
388
- if (debug) {
389
- ctx.logger.debug({
390
- event: "request.end",
391
- status: ctx.response.statusCode,
392
- data: ctx.data
393
- });
394
- } else if (logRequest) {
395
- ctx.logger.info({
396
- event: "request.end",
397
- status: ctx.response.statusCode
398
- });
399
- }
400
- }
401
-
402
- ctx.logger.flush();
403
- }
404
- /**
405
- * Attach all information that will be necessary to log the request. Attach a new `request.log` object.
406
- */
407
-
408
-
409
- configureRequest(ctx) {
410
- ctx.logger.minimalRequestPicker = obj => _extends({}, this.minimalRequestPicker(ctx), obj);
411
-
412
- ctx.logger.completeRequestPicker = obj => _extends({}, this.requestToObject(ctx), obj);
413
- }
414
- /**
415
- * Return complete request info.
416
- * @returns {Object}
417
- * @param ctx
418
- */
419
-
420
-
421
- requestToObject(ctx) {
422
- const {
423
- request
424
- } = ctx;
425
- return {
426
- method: request.method,
427
- url: request.url,
428
- headers: request.headers,
429
- body: request.body,
430
- query: request.query,
431
- params: request.params
432
- };
433
- }
434
- /**
435
- * Return a filtered request from global configuration.
436
- * @returns {Object}
437
- * @param ctx
438
- */
439
-
440
-
441
- minimalRequestPicker(ctx) {
442
- const {
443
- requestFields
444
- } = this.settings;
445
- const info = this.requestToObject(ctx);
446
- return requestFields.reduce((acc, key) => {
447
- acc[key] = info[key];
448
- return acc;
449
- }, {});
450
- }
451
-
452
- };
453
- PlatformLogMiddleware.DEFAULT_FIELDS = ["reqId", "method", "url", "duration"];
454
-
455
- __decorate([__param(0, Context()), __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", void 0)], PlatformLogMiddleware.prototype, "use", null);
456
-
457
- PlatformLogMiddleware = PlatformLogMiddleware_1 = __decorate([Middleware(), __metadata("design:paramtypes", [InjectorService])], PlatformLogMiddleware);
458
-
459
- /**
460
- * @ignore
461
- */
462
- const createFakeRawDriver = () => {
463
- // istanbul ignore next
464
- function FakeRawDriver() {} // istanbul ignore next
465
-
466
-
467
- function use() {
468
- return this;
469
- }
470
-
471
- FakeRawDriver.use = use;
472
- FakeRawDriver.all = use;
473
- FakeRawDriver.get = use;
474
- FakeRawDriver.patch = use;
475
- FakeRawDriver.post = use;
476
- FakeRawDriver.put = use;
477
- FakeRawDriver.head = use;
478
- FakeRawDriver.delete = use;
479
- FakeRawDriver.options = use;
480
- return FakeRawDriver;
481
- };
482
-
483
- class AnyToPromiseWithCtx extends AnyToPromise {
484
- constructor({
485
- $ctx,
486
- err
487
- }) {
488
- super();
489
- this.$ctx = $ctx;
490
- this.err = err;
491
- }
492
-
493
- isDone() {
494
- const {
495
- $ctx
496
- } = this;
497
-
498
- if (!($ctx != null && $ctx.isDone())) {
499
- if ($ctx != null && $ctx.request.isAborted() || $ctx != null && $ctx.response.isDone()) {
500
- this.destroy();
501
-
502
- if (this.status === AnyToPromiseStatus.PENDING) {
503
- this.status = AnyToPromiseStatus.RESOLVED;
504
- }
505
- }
506
- }
507
-
508
- return super.isDone();
509
- }
510
-
511
- async call(cb) {
512
- return super.call(() => cb(this));
513
- }
514
-
515
- destroy() {
516
- // @ts-ignore
517
- delete this.$ctx;
518
- }
519
-
520
- isCanceledResponse(process) {
521
- return process === this.$ctx.getResponse();
522
- }
523
-
524
- }
525
-
526
- /**
527
- * @ignore
528
- */
529
- var HandlerType;
530
-
531
- (function (HandlerType) {
532
- HandlerType["CUSTOM"] = "custom";
533
- HandlerType["ENDPOINT"] = "endpoint";
534
- HandlerType["MIDDLEWARE"] = "middleware";
535
- HandlerType["ERR_MIDDLEWARE"] = "err:middleware";
536
- HandlerType["CTX_FN"] = "context";
537
- HandlerType["RAW_FN"] = "raw:middleware";
538
- HandlerType["RAW_ERR_FN"] = "raw:err:middleware";
539
- })(HandlerType || (HandlerType = {}));
540
-
541
- class HandlerMetadata {
542
- constructor(options) {
543
- this.injectable = false;
544
- this.type = HandlerType.RAW_FN;
545
- this.hasNextFunction = false;
546
- const {
547
- target,
548
- token,
549
- propertyKey,
550
- type,
551
- scope,
552
- routeOptions
553
- } = options;
554
- this.type = type || target.type || HandlerType.RAW_FN;
555
- this.scope = scope || ProviderScope.SINGLETON;
556
- this.routeOptions = routeOptions || {};
557
- const handler = propertyKey ? target.prototype[propertyKey] : target;
558
-
559
- if (propertyKey) {
560
- this.target = target;
561
- this.token = token;
562
- this.propertyKey = propertyKey;
563
- this.hasNextFunction = this.hasParamType(ParamTypes.NEXT_FN);
564
-
565
- if (this.hasParamType(ParamTypes.ERR)) {
566
- this.type = HandlerType.ERR_MIDDLEWARE;
567
- }
568
-
569
- this.injectable = ParamMetadata.getParams(target, propertyKey).length > 0;
570
- } else {
571
- this.handler = handler;
572
- }
573
-
574
- if (!this.injectable) {
575
- if (handler.length === 4) {
576
- this.type = HandlerType.RAW_ERR_FN;
577
- }
578
-
579
- this.hasNextFunction = handler.length >= 3;
580
- }
581
- }
582
-
583
- get hasErrorParam() {
584
- return this.type === HandlerType.ERR_MIDDLEWARE || this.type === HandlerType.RAW_ERR_FN;
585
- }
586
-
587
- getParams() {
588
- return ParamMetadata.getParams(this.target, this.propertyKey) || [];
589
- }
590
-
591
- hasParamType(paramType) {
592
- return this.getParams().findIndex(p => p.paramType === paramType) > -1;
593
- }
594
-
595
- isFinal() {
596
- var _this$routeOptions;
597
-
598
- return ((_this$routeOptions = this.routeOptions) == null ? void 0 : _this$routeOptions.isFinal) || false;
599
- }
600
-
601
- toString() {
602
- return [this.target && nameOf(this.target), this.propertyKey].filter(Boolean).join(".");
603
- }
604
-
605
- }
606
-
607
- var EndpointMetadata_1;
608
- /**
609
- * EndpointMetadata contains metadata about a controller and his method.
610
- * Each annotation (@Get, @Body...) attached to a method are stored in a endpoint.
611
- * EndpointMetadata convert this metadata to an array which contain arguments to call an Express method.
612
- *
613
- * Example :
614
- *
615
- * @Controller("/my-path")
616
- * provide MyClass {
617
- *
618
- * @Get("/")
619
- * @Authenticated()
620
- * public myMethod(){}
621
- * }
622
- *
623
- */
624
-
625
- let EndpointMetadata = EndpointMetadata_1 = class EndpointMetadata extends JsonEntityStore {
626
- constructor(options) {
627
- super(_extends({
628
- store: Store.fromMethod(options.target, options.propertyKey),
629
- descriptor: descriptorOf(options.target, options.propertyKey)
630
- }, options)); // LIFECYCLE
631
-
632
- this.beforeMiddlewares = [];
633
- this.middlewares = [];
634
- this.afterMiddlewares = [];
635
- this.statusCode = 200;
636
- const {
637
- beforeMiddlewares = [],
638
- middlewares = [],
639
- afterMiddlewares = []
640
- } = options;
641
- this.after(afterMiddlewares);
642
- this.before(beforeMiddlewares);
643
- this.use(middlewares);
644
- }
645
-
646
- get targetName() {
647
- return nameOf(this.token);
648
- }
649
-
650
- get params() {
651
- return Array.from(this.children.values());
652
- }
653
- /**
654
- * Return the JsonOperation
655
- */
656
-
657
-
658
- get operation() {
659
- return this._operation;
660
- }
661
-
662
- get operationPaths() {
663
- return this.operation.operationPaths;
664
- }
665
-
666
- get view() {
667
- return this.store.get("view");
668
- }
669
-
670
- set view(view) {
671
- this.store.set("view", view);
672
- }
673
-
674
- get acceptMimes() {
675
- return this.store.get("acceptMimes", []);
676
- }
677
-
678
- set acceptMimes(mimes) {
679
- this.store.set("acceptMimes", mimes);
680
- }
681
- /**
682
- * Get all endpoints from a given class and his parents.
683
- * @param {Type<any>} target
684
- * @returns {EndpointMetadata[]}
685
- */
686
-
687
-
688
- static getEndpoints(target) {
689
- const operations = getOperationsStores(target);
690
- return Array.from(operations.values()).map(endpoint => {
691
- endpoint = endpoint.clone();
692
- endpoint.token = classOf(target);
693
- return endpoint;
694
- });
695
- }
696
- /**
697
- * Get an endpoint.
698
- * @param target
699
- * @param propertyKey
700
- * @param descriptor
701
- */
702
-
703
-
704
- static get(target, propertyKey, descriptor) {
705
- descriptor = descriptor || descriptorOf(prototypeOf(target), propertyKey);
706
- return JsonEntityStore.from(prototypeOf(target), propertyKey, descriptor);
707
- }
708
-
709
- addOperationPath(method, path, options = {}) {
710
- return this.operation.addOperationPath(method, path, options);
711
- }
712
- /**
713
- * Find the a value at the controller level. Let this value be extended or overridden by the endpoint itself.
714
- *
715
- * @param key
716
- * @returns {any}
717
- */
718
-
719
-
720
- get(key) {
721
- const ctrlValue = Store.from(this.target).get(key);
722
- return deepMerge(ctrlValue, this.store.get(key));
723
- }
724
- /**
725
- * Append middlewares to the beforeMiddlewares list.
726
- * @param args
727
- * @returns {EndpointMetadata}
728
- */
729
-
730
-
731
- before(args) {
732
- this.beforeMiddlewares = this.beforeMiddlewares.concat(args).filter(isFunction);
733
- return this;
734
- }
735
- /**
736
- * Append middlewares to the afterMiddlewares list.
737
- * @param args
738
- * @returns {EndpointMetadata}
739
- */
740
-
741
-
742
- after(args) {
743
- this.afterMiddlewares = this.afterMiddlewares.concat(args).filter(isFunction);
744
- return this;
745
- }
746
- /**
747
- * Store all arguments collected via Annotation.
748
- * @param args
749
- */
750
-
751
-
752
- use(args) {
753
- this.middlewares = this.middlewares.concat(args).filter(isFunction);
754
- return this;
755
- }
756
-
757
- clone() {
758
- const endpoint = new EndpointMetadata_1(_extends({}, this, {
759
- target: this.target,
760
- propertyKey: this.propertyKey,
761
- descriptor: this.descriptor,
762
- store: this.store,
763
- children: this.children
764
- }));
765
- endpoint.collectionType = this.collectionType;
766
- endpoint._type = this._type;
767
- endpoint._operation = this.operation;
768
- endpoint._schema = this._schema;
769
- endpoint.middlewares = [...this.middlewares];
770
- endpoint.afterMiddlewares = [...this.afterMiddlewares];
771
- endpoint.beforeMiddlewares = [...this.beforeMiddlewares];
772
- return endpoint;
773
- }
774
-
775
- };
776
-
777
- __decorate([Enumerable(), __metadata("design:type", Array)], EndpointMetadata.prototype, "beforeMiddlewares", void 0);
778
-
779
- __decorate([Enumerable(), __metadata("design:type", Array)], EndpointMetadata.prototype, "middlewares", void 0);
780
-
781
- __decorate([Enumerable(), __metadata("design:type", Array)], EndpointMetadata.prototype, "afterMiddlewares", void 0);
782
-
783
- __decorate([Enumerable(), __metadata("design:type", Number)], EndpointMetadata.prototype, "statusCode", void 0);
784
-
785
- EndpointMetadata = EndpointMetadata_1 = __decorate([JsonEntityComponent(DecoratorTypes.METHOD), __metadata("design:paramtypes", [Object])], EndpointMetadata);
786
-
787
- function isMetadata(input) {
788
- return input instanceof HandlerMetadata;
789
- }
790
- /**
791
- * @ignore
792
- */
793
-
794
-
795
- function createHandlerMetadata(injector, obj, routeOptions = {}) {
796
- if (isMetadata(obj)) {
797
- return obj;
798
- }
799
-
800
- let options;
801
-
802
- if (obj instanceof EndpointMetadata) {
803
- const provider = injector.getProvider(obj.token);
804
- options = {
805
- token: provider.token,
806
- target: provider.useClass,
807
- scope: provider.scope,
808
- type: HandlerType.ENDPOINT,
809
- propertyKey: obj.propertyKey
810
- };
811
- } else {
812
- const provider = injector.getProvider(obj);
813
-
814
- if (provider) {
815
- options = {
816
- token: provider.token,
817
- target: provider.useClass,
818
- scope: provider.scope,
819
- type: HandlerType.MIDDLEWARE,
820
- propertyKey: "use"
821
- };
822
- } else {
823
- options = {
824
- target: obj
825
- };
826
- }
827
- }
828
-
829
- options.routeOptions = routeOptions;
830
- return new HandlerMetadata(options);
831
- }
832
-
833
- function mergeHeaders(specHeaders, headers) {
834
- return Object.entries(specHeaders).reduce((headers, [key, item]) => {
835
- key = key.toLowerCase();
836
- return _extends({}, headers, {
837
- [key]: headers[key] === undefined ? String(item.example) : headers[key]
838
- });
839
- }, headers);
840
- }
841
- /**
842
- * @ignore
843
- */
844
-
845
-
846
- function setResponseHeaders(ctx) {
847
- const {
848
- response,
849
- endpoint
850
- } = ctx;
851
- const {
852
- operation
853
- } = endpoint;
854
-
855
- if (response.isDone()) {
856
- return;
857
- }
858
-
859
- if (!response.hasStatus()) {
860
- // apply status only if the isn't already modified
861
- response.status(operation.getStatus());
862
- }
863
-
864
- const statusCode = response.statusCode;
865
- const headers = operation.getHeadersOf(response.statusCode);
866
- const mergedHeaders = mergeHeaders(headers, response.getHeaders());
867
- response.setHeaders(mergedHeaders);
868
-
869
- if (operation.isRedirection(statusCode)) {
870
- response.redirect(statusCode, String(mergedHeaders["location"]));
871
- }
872
- }
873
-
874
- var _converterSettings;
875
- let ConverterService = (_converterSettings = /*#__PURE__*/_classPrivateFieldLooseKey("converterSettings"), class ConverterService {
876
- constructor(injectorService, configuration) {
877
- Object.defineProperty(this, _converterSettings, {
878
- writable: true,
879
- value: void 0
880
- });
881
- this.injectorService = injectorService;
882
- _classPrivateFieldLooseBase(this, _converterSettings)[_converterSettings] = configuration.get("converter") || {};
883
- }
884
-
885
- /**
886
- * Convert instance to plainObject.
887
- *
888
- * @param obj
889
- * @param options
890
- */
891
- serialize(obj, options = {}) {
892
- return serialize(obj, _extends({
893
- useAlias: true,
894
- additionalProperties: _classPrivateFieldLooseBase(this, _converterSettings)[_converterSettings].additionalProperties === "accept"
895
- }, options));
896
- }
897
- /**
898
- * Convert a plainObject to targetType.
899
- *
900
- * ### Options
901
- *
902
- * - `ignoreCallback`: callback called for each object which will be deserialized. The callback can return a boolean to avoid the default converter behavior.
903
- * - `checkRequiredValue`: Disable the required check condition.
904
- *
905
- * @param obj Object source that will be deserialized
906
- * @param options Mapping options
907
- * @returns {any}
908
- */
909
-
910
-
911
- deserialize(obj, options = {}) {
912
- return deserialize(obj, _extends({
913
- useAlias: true,
914
- additionalProperties: _classPrivateFieldLooseBase(this, _converterSettings)[_converterSettings].additionalProperties === "accept"
915
- }, options));
916
- }
917
-
918
- });
919
- ConverterService = __decorate([Injectable(), __param(1, Configuration()), __metadata("design:paramtypes", [InjectorService, Object])], ConverterService);
920
-
921
- function shouldBeSent(data) {
922
- return Buffer.isBuffer(data) || isBoolean(data) || isNumber(data) || isString(data) || data === null;
923
- }
924
-
925
- function shouldBeSerialized(data) {
926
- return !(isStream(data) || shouldBeSent(data) || data === undefined);
927
- }
928
- /**
929
- * Platform Handler abstraction layer. Wrap original class method to a pure platform handler (Express, Koa, etc...).
930
- * @platform
931
- */
932
-
933
-
934
- let PlatformHandler = class PlatformHandler {
935
- constructor(injector, params) {
936
- this.injector = injector;
937
- this.params = params;
938
- }
939
- /**
940
- * Create a native middleware based on the given metadata and return an instance of AnyToPromiseWithCtx
941
- * @param input
942
- * @param options
943
- */
944
-
945
-
946
- createHandler(input, options = {}) {
947
- return this.createRawHandler(createHandlerMetadata(this.injector, input, options));
948
- }
949
- /**
950
- * Create injectable handler from the given provider
951
- * @param provider
952
- * @param propertyKey
953
- */
954
-
955
-
956
- createCustomHandler(provider, propertyKey) {
957
- const handler = this.compileHandler(new HandlerMetadata({
958
- token: provider.provide,
959
- target: provider.useClass,
960
- type: HandlerType.CUSTOM,
961
- scope: provider.scope,
962
- propertyKey
963
- }));
964
- return async function ($ctx, next) {
965
- return handler({
966
- $ctx,
967
- next
968
- });
969
- };
970
- }
971
- /**
972
- * Send the response to the consumer.
973
- * @param data
974
- * @param ctx
975
- * @protected
976
- */
977
-
978
-
979
- async flush(data, ctx) {
980
- const {
981
- response,
982
- endpoint
983
- } = ctx;
984
-
985
- if (endpoint) {
986
- if (endpoint.view) {
987
- data = await this.render(data, ctx);
988
- } else if (shouldBeSerialized(data)) {
989
- data = this.injector.get(ConverterService).serialize(data, _extends({}, endpoint.getResponseOptions(), {
990
- endpoint: true
991
- }));
992
- }
993
- }
994
-
995
- if (!response.isDone()) {
996
- const responseFilter = this.injector.get(PlatformResponseFilter);
997
- response.body(responseFilter.transform(data, ctx));
998
- }
999
- }
1000
-
1001
- compileHandler(metadata) {
1002
- var _this = this;
1003
-
1004
- if (metadata.type === HandlerType.CTX_FN) {
1005
- return async function (scope) {
1006
- // @ts-ignore
1007
- return _this.onCtxRequest(_extends({}, scope, {
1008
- handler: () => metadata.handler(scope.$ctx),
1009
- metadata
1010
- }));
1011
- };
1012
- }
1013
-
1014
- const promise = this.params.compileHandler({
1015
- token: metadata.token,
1016
- propertyKey: metadata.propertyKey,
1017
- getCustomArgs: metadata.injectable ? undefined : this.getDefaultArgs(metadata)
1018
- });
1019
- return async function (scope) {
1020
- const handler = await promise; // @ts-ignore
1021
-
1022
- return _this.onRequest(_extends({}, scope, {
1023
- handler,
1024
- metadata
1025
- }));
1026
- };
1027
- }
1028
-
1029
- async onCtxRequest(requestOptions) {
1030
- await requestOptions.handler(requestOptions);
1031
- return this.next(requestOptions);
1032
- }
1033
- /**
1034
- * Call handler when a request his handle
1035
- * @param requestOptions
1036
- */
1037
-
1038
-
1039
- async onRequest(requestOptions) {
1040
- var _this2 = this;
1041
-
1042
- const {
1043
- $ctx,
1044
- metadata,
1045
- err,
1046
- handler
1047
- } = requestOptions; // istanbul ignore next
1048
-
1049
- if (!$ctx) {
1050
- $log.error(`Endpoint ${metadata.toString()} is called but the response is already send to your consumer. Check your code and his middlewares please!`);
1051
- return;
1052
- }
1053
-
1054
- const resolver = new AnyToPromiseWithCtx({
1055
- $ctx,
1056
- err
1057
- });
1058
- return this.injector.runInContext($ctx, async function () {
1059
- try {
1060
- const {
1061
- state,
1062
- data,
1063
- status,
1064
- headers
1065
- } = await resolver.call(handler);
1066
-
1067
- if (state === AnyToPromiseStatus.RESOLVED) {
1068
- if (status) {
1069
- $ctx.response.status(status);
1070
- }
1071
-
1072
- if (headers) {
1073
- $ctx.response.setHeaders(headers);
1074
- }
1075
-
1076
- if (data !== undefined) {
1077
- $ctx.data = data;
1078
- } // Can be canceled by the handler itself
1079
-
1080
-
1081
- return await _this2.onSuccess($ctx.data, requestOptions);
1082
- }
1083
- } catch (er) {
1084
- return _this2.onError(er, requestOptions);
1085
- }
1086
- });
1087
- }
1088
-
1089
- async onError(er, requestOptions) {
1090
- const {
1091
- next,
1092
- $ctx
1093
- } = requestOptions;
1094
- $ctx.data = er;
1095
-
1096
- if (!next) {
1097
- throw er;
1098
- }
1099
-
1100
- return !$ctx.response.isHeadersSent() && next && next(er);
1101
- }
1102
- /**
1103
- * Manage success scenario
1104
- * @param data
1105
- * @param requestOptions
1106
- * @protected
1107
- */
1108
-
1109
-
1110
- async onSuccess(data, requestOptions) {
1111
- const {
1112
- metadata,
1113
- $ctx,
1114
- next
1115
- } = requestOptions; // TODO see this control is necessary
1116
- // istanbul ignore next
1117
-
1118
- if ($ctx.request.isAborted() || $ctx.response.isDone()) {
1119
- return;
1120
- } // set headers each times that an endpoint is called
1121
-
1122
-
1123
- if (metadata.type === HandlerType.ENDPOINT) {
1124
- this.setHeaders($ctx);
1125
- } // call returned middleware
1126
-
1127
-
1128
- if (isFunction(data) && !isStream(data)) {
1129
- return this.callReturnedMiddleware(data, $ctx, next);
1130
- }
1131
-
1132
- if (metadata.isFinal()) {
1133
- return this.flush(data, $ctx);
1134
- }
1135
-
1136
- return this.next(requestOptions);
1137
- }
1138
- /**
1139
- * Call the returned middleware by the handler.
1140
- * @param middleware
1141
- * @param ctx
1142
- * @param next
1143
- * @protected
1144
- */
1145
-
1146
-
1147
- callReturnedMiddleware(middleware, ctx, next) {
1148
- return middleware(ctx.getRequest(), ctx.getResponse(), next);
1149
- }
1150
- /**
1151
- * Render the view if the endpoint has a configured view.
1152
- * @param data
1153
- * @param ctx
1154
- * @protected
1155
- */
1156
-
1157
-
1158
- async render(data, ctx) {
1159
- return renderView(data, ctx);
1160
- }
1161
- /**
1162
- * create Raw handler
1163
- * @param metadata
1164
- */
1165
-
1166
-
1167
- createRawHandler(metadata) {
1168
- if ([HandlerType.RAW_ERR_FN, HandlerType.RAW_FN].includes(metadata.type)) {
1169
- return metadata.handler;
1170
- }
1171
-
1172
- const handler = this.compileHandler(metadata);
1173
- return async function (request, response, next) {
1174
- return handler({
1175
- next,
1176
- $ctx: request.$ctx
1177
- });
1178
- };
1179
- }
1180
- /**
1181
- * Set response headers
1182
- * @param ctx
1183
- * @protected
1184
- */
1185
-
1186
-
1187
- setHeaders(ctx) {
1188
- return setResponseHeaders(ctx);
1189
- }
1190
-
1191
- next(requestOptions) {
1192
- const {
1193
- $ctx,
1194
- next
1195
- } = requestOptions;
1196
- return !$ctx.response.isDone() && next && next();
1197
- }
1198
-
1199
- getDefaultArgs(metadata) {
1200
- return async function (scope) {
1201
- return [metadata.hasErrorParam && scope.err, scope.$ctx.request.request, scope.$ctx.response.response, metadata.hasNextFunction && scope.next].filter(Boolean);
1202
- };
1203
- }
1204
-
1205
- };
1206
- PlatformHandler = __decorate([Injectable({
1207
- scope: ProviderScope.SINGLETON
1208
- }), __metadata("design:paramtypes", [InjectorService, PlatformParams])], PlatformHandler);
1209
-
1210
- var PlatformRouter_1;
1211
- /**
1212
- * @ignore
1213
- */
1214
-
1215
- const PLATFORM_ROUTER_OPTIONS = Symbol.for("PlatformRouterOptions");
1216
- /**
1217
- * Platform Router abstraction layer.
1218
- * @platform
1219
- */
1220
-
1221
- let PlatformRouter = PlatformRouter_1 = class PlatformRouter {
1222
- constructor(platformHandler) {
1223
- this.platformHandler = platformHandler;
1224
- this.rawRouter = this.raw = PlatformRouter_1.createRawRouter();
1225
- }
1226
- /**
1227
- * Create a new instance of PlatformRouter
1228
- * @param injector
1229
- * @param routerOptions
1230
- */
1231
-
1232
-
1233
- static create(injector, routerOptions = {}) {
1234
- const locals = new Map();
1235
- locals.set(PLATFORM_ROUTER_OPTIONS, routerOptions);
1236
- return injector.invoke(PlatformRouter_1, locals);
1237
- }
1238
-
1239
- static createRawRouter() {
1240
- return createFakeRawDriver();
1241
- }
1242
-
1243
- callback() {
1244
- return this.raw;
1245
- }
1246
-
1247
- getRouter() {
1248
- return this.rawRouter;
1249
- }
1250
-
1251
- use(...handlers) {
1252
- // @ts-ignore
1253
- this.getRouter().use(...this.mapHandlers(handlers));
1254
- return this;
1255
- }
1256
-
1257
- addRoute(options) {
1258
- const {
1259
- method,
1260
- path,
1261
- handlers,
1262
- isFinal
1263
- } = options; // @ts-ignore
1264
-
1265
- this.getRouter()[method](path, ...this.mapHandlers(handlers, {
1266
- method,
1267
- path,
1268
- isFinal
1269
- }));
1270
- return this;
1271
- }
1272
-
1273
- all(path, ...handlers) {
1274
- return this.addRoute({
1275
- method: "all",
1276
- path,
1277
- handlers,
1278
- isFinal: true
1279
- });
1280
- }
1281
-
1282
- get(path, ...handlers) {
1283
- return this.addRoute({
1284
- method: "get",
1285
- path,
1286
- handlers,
1287
- isFinal: true
1288
- });
1289
- }
1290
-
1291
- post(path, ...handlers) {
1292
- return this.addRoute({
1293
- method: "post",
1294
- path,
1295
- handlers,
1296
- isFinal: true
1297
- });
1298
- }
1299
-
1300
- put(path, ...handlers) {
1301
- return this.addRoute({
1302
- method: "put",
1303
- path,
1304
- handlers,
1305
- isFinal: true
1306
- });
1307
- }
1308
-
1309
- delete(path, ...handlers) {
1310
- return this.addRoute({
1311
- method: "delete",
1312
- path,
1313
- handlers,
1314
- isFinal: true
1315
- });
1316
- }
1317
-
1318
- patch(path, ...handlers) {
1319
- return this.addRoute({
1320
- method: "patch",
1321
- path,
1322
- handlers,
1323
- isFinal: true
1324
- });
1325
- }
1326
-
1327
- head(path, ...handlers) {
1328
- return this.addRoute({
1329
- method: "head",
1330
- path,
1331
- handlers,
1332
- isFinal: true
1333
- });
1334
- }
1335
-
1336
- options(path, ...handlers) {
1337
- return this.addRoute({
1338
- method: "options",
1339
- path,
1340
- handlers,
1341
- isFinal: true
1342
- });
1343
- }
1344
-
1345
- statics(path, options) {
1346
- return this;
1347
- }
1348
-
1349
- multer(options) {
1350
- const m = require("multer")(options);
1351
-
1352
- const makePromise = (multer, name) => {
1353
- // istanbul ignore next
1354
- if (!multer[name]) return;
1355
- const fn = multer[name];
1356
-
1357
- multer[name] = function apply(...args) {
1358
- const middleware = Reflect.apply(fn, this, args);
1359
- return (req, res) => promisify(middleware)(req, res);
1360
- };
1361
- };
1362
-
1363
- makePromise(m, "any");
1364
- makePromise(m, "array");
1365
- makePromise(m, "fields");
1366
- makePromise(m, "none");
1367
- makePromise(m, "single");
1368
- return m;
1369
- }
1370
-
1371
- mapHandlers(handlers, options = {}) {
1372
- return handlers.reduce((list, handler, index) => {
1373
- if (typeof handler === "string") {
1374
- return list.concat(handler);
1375
- }
1376
-
1377
- if (handler instanceof PlatformRouter_1) {
1378
- return list.concat(handler.callback());
1379
- }
1380
-
1381
- return list.concat(this.platformHandler.createHandler(handler, _extends({}, options, {
1382
- isFinal: options.isFinal ? index === handlers.length - 1 : false
1383
- })));
1384
- }, []);
1385
- }
1386
-
1387
- };
1388
-
1389
- __decorate([Inject(), __metadata("design:type", InjectorService)], PlatformRouter.prototype, "injector", void 0);
1390
-
1391
- PlatformRouter = PlatformRouter_1 = __decorate([Injectable({
1392
- scope: ProviderScope.INSTANCE
1393
- }), __metadata("design:paramtypes", [PlatformHandler])], PlatformRouter);
1394
-
1395
- var PlatformApplication_1;
1396
- /**
1397
- * `PlatformApplication` is used to provide all routes collected by annotation `@Controller`.
1398
- *
1399
- * @platform
1400
- */
1401
-
1402
- let PlatformApplication = PlatformApplication_1 = class PlatformApplication extends PlatformRouter {
1403
- constructor(platformHandler) {
1404
- super(platformHandler);
1405
- this.rawApp = this.raw = PlatformApplication_1.createRawApp();
1406
- }
1407
-
1408
- static createRawApp() {
1409
- return createFakeRawDriver();
1410
- }
1411
-
1412
- getApp() {
1413
- return this.raw;
1414
- }
1415
-
1416
- };
1417
- PlatformApplication = PlatformApplication_1 = __decorate([Injectable({
1418
- scope: ProviderScope.SINGLETON
1419
- }), __metadata("design:paramtypes", [PlatformHandler])], PlatformApplication);
1420
-
1421
- var PlatformMulterMiddleware_1;
1422
- /**
1423
- * @middleware
1424
- */
1425
-
1426
- let PlatformMulterMiddleware = PlatformMulterMiddleware_1 = class PlatformMulterMiddleware {
1427
- async use(ctx) {
1428
- try {
1429
- const {
1430
- fields,
1431
- options = {}
1432
- } = ctx.endpoint.get(PlatformMulterMiddleware_1);
1433
-
1434
- const settings = _extends({}, this.settings, options);
1435
- /* istanbul ignore next */
1436
-
1437
-
1438
- if (settings.storage) {
1439
- delete settings.dest;
1440
- }
1441
-
1442
- const middleware = this.app.multer(settings).fields(this.getFields({
1443
- fields
1444
- }));
1445
- return await middleware(ctx.getRequest(), ctx.getResponse());
1446
- } catch (er) {
1447
- throw er.code ? new Exception(er.code, `${er.message} ${er.field || ""}`.trim()) : er;
1448
- }
1449
- }
1450
-
1451
- getFields(conf) {
1452
- return conf.fields.map(({
1453
- name,
1454
- maxCount
1455
- }) => ({
1456
- name,
1457
- maxCount
1458
- }));
1459
- }
1460
-
1461
- };
1462
-
1463
- __decorate([Constant("multer", {}), __metadata("design:type", Object)], PlatformMulterMiddleware.prototype, "settings", void 0);
1464
-
1465
- __decorate([Inject(), __metadata("design:type", PlatformApplication)], PlatformMulterMiddleware.prototype, "app", void 0);
1466
-
1467
- __decorate([__param(0, Context()), __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise)], PlatformMulterMiddleware.prototype, "use", null);
1468
-
1469
- PlatformMulterMiddleware = PlatformMulterMiddleware_1 = __decorate([Middleware()], PlatformMulterMiddleware);
1470
-
1471
- /**
1472
- * @middleware
1473
- * @platform
1474
- */
1475
-
1476
- let PlatformAcceptMimesMiddleware = class PlatformAcceptMimesMiddleware {
1477
- use(ctx) {
1478
- const {
1479
- endpoint,
1480
- request
1481
- } = ctx;
1482
- const mimes = uniq(((endpoint == null ? void 0 : endpoint.get("acceptMimes")) || []).concat(this.acceptMimes));
1483
-
1484
- if (mimes.length && !request.accepts(mimes)) {
1485
- throw new NotAcceptable(mimes.join(", "));
1486
- }
1487
- }
1488
-
1489
- };
1490
-
1491
- __decorate([Constant("acceptMimes", []), __metadata("design:type", Array)], PlatformAcceptMimesMiddleware.prototype, "acceptMimes", void 0);
1492
-
1493
- __decorate([__param(0, Context()), __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", void 0)], PlatformAcceptMimesMiddleware.prototype, "use", null);
1494
-
1495
- PlatformAcceptMimesMiddleware = __decorate([Middleware()], PlatformAcceptMimesMiddleware);
1496
-
1497
- /**
1498
- * Create Ts.ED context handler
1499
- * @param fn
1500
- * @ignore
1501
- */
1502
-
1503
- function useCtxHandler(fn) {
1504
- fn.type = HandlerType.CTX_FN;
1505
- return fn;
1506
- }
1507
-
1508
- /**
1509
- * @ignore
1510
- */
1511
-
1512
- function formatMethod(method) {
1513
- return (method === OperationMethods.CUSTOM ? "use" : method || "use").toLowerCase();
1514
- }
1515
- /**
1516
- * @ignore
1517
- */
1518
-
1519
-
1520
- class PlatformControllerBuilder {
1521
- constructor(provider) {
1522
- this.provider = provider;
1523
- }
1524
- /**
1525
- *
1526
- * @returns {any}
1527
- */
1528
-
1529
-
1530
- build(injector) {
1531
- const {
1532
- middlewares: {
1533
- useBefore
1534
- }
1535
- } = this.provider; // Controller lifecycle
1536
-
1537
- this.buildMiddlewares(useBefore) // Controller before-middleware
1538
- .buildEndpoints() // All endpoints and his middlewares
1539
- .buildChildrenCtrls(injector); // Children controllers
1540
-
1541
- return this.provider.getRouter();
1542
- }
1543
-
1544
- buildEndpoints() {
1545
- const {
1546
- endpoints
1547
- } = this.provider;
1548
- const operationPaths = new Map();
1549
-
1550
- const getKey = (method, path) => `${method}-${path}`;
1551
-
1552
- const updateFinalRouteState = key => {
1553
- if (operationPaths.has(key)) {
1554
- operationPaths.get(key).isFinal = false;
1555
- }
1556
- };
1557
-
1558
- const setFinalRoute = (key, operationPath) => {
1559
- operationPaths.set(key, operationPath);
1560
- operationPath.isFinal = true;
1561
- };
1562
-
1563
- endpoints.forEach(({
1564
- operation
1565
- }) => {
1566
- operation == null ? void 0 : operation.operationPaths.forEach(operationPath => {
1567
- if (operationPath.method !== OperationMethods.CUSTOM) {
1568
- const key = getKey(operationPath.method, operationPath.path);
1569
- updateFinalRouteState(key);
1570
- updateFinalRouteState(getKey(OperationMethods.ALL, operationPath.path));
1571
- setFinalRoute(key, operationPath);
1572
- }
1573
- });
1574
- });
1575
- endpoints.forEach(endpoint => {
1576
- this.buildEndpoint(endpoint);
1577
- });
1578
- return this;
1579
- }
1580
-
1581
- buildEndpoint(endpoint) {
1582
- const {
1583
- beforeMiddlewares,
1584
- middlewares: mldwrs,
1585
- afterMiddlewares,
1586
- operation
1587
- } = endpoint;
1588
- const {
1589
- middlewares: {
1590
- use,
1591
- useAfter
1592
- }
1593
- } = this.provider;
1594
- const router = this.provider.getRouter(); // Endpoint lifecycle
1595
-
1596
- let handlers = [];
1597
- const hasFiles = [...endpoint.children.values()].find(item => item.paramType === ParamTypes.FILES);
1598
- handlers = handlers.concat(useCtxHandler(bindEndpointMiddleware(endpoint))).concat(PlatformAcceptMimesMiddleware).concat(hasFiles && PlatformMulterMiddleware).concat(use) // Controller use-middlewares
1599
- .concat(beforeMiddlewares) // Endpoint before-middlewares
1600
- // .concat(endpoint.cache && PlatformCacheMiddleware)
1601
- .concat(mldwrs) // Endpoint middlewares
1602
- .concat(endpoint) // Endpoint metadata
1603
- .concat(afterMiddlewares) // Endpoint after-middlewares
1604
- .concat(useAfter) // Controller after middlewares (equivalent to afterEach)
1605
- .filter(item => !!item); // Add handlers to the router
1606
-
1607
- operation == null ? void 0 : operation.operationPaths.forEach(({
1608
- path,
1609
- method,
1610
- isFinal
1611
- }) => {
1612
- router.addRoute({
1613
- method: formatMethod(method),
1614
- path,
1615
- handlers,
1616
- isFinal
1617
- });
1618
- });
1619
-
1620
- if (!(operation != null && operation.operationPaths.size)) {
1621
- router.use(...handlers);
1622
- }
1623
- }
1624
-
1625
- buildChildrenCtrls(injector) {
1626
- const {
1627
- children
1628
- } = this.provider;
1629
- const router = this.provider.getRouter();
1630
- children.forEach(child => {
1631
- const provider = injector.getProvider(child);
1632
- /* istanbul ignore next */
1633
-
1634
- if (!provider) {
1635
- throw new Error("Controller component not found in the ControllerRegistry");
1636
- }
1637
-
1638
- new PlatformControllerBuilder(provider).build(injector);
1639
- router.use(provider.path, provider.getRouter());
1640
- });
1641
- }
1642
-
1643
- buildMiddlewares(middlewares) {
1644
- const router = this.provider.getRouter();
1645
- middlewares.filter(o => typeof o === "function").forEach(middleware => {
1646
- router.use(middleware);
1647
- });
1648
- return this;
1649
- }
1650
-
1651
- }
1652
-
1653
- /**
1654
- * Platform Request abstraction layer.
1655
- * @platform
1656
- */
1657
-
1658
- let PlatformRequest = class PlatformRequest {
1659
- constructor({
1660
- request
1661
- }) {
1662
- this.raw = request;
1663
- }
1664
-
1665
- get secure() {
1666
- return this.raw.secure;
1667
- }
1668
-
1669
- get host() {
1670
- return this.get("host");
1671
- }
1672
-
1673
- get protocol() {
1674
- return this.raw.protocol;
1675
- }
1676
- /**
1677
- * Get the url of the request.
1678
- *
1679
- * Is equivalent of `express.response.originalUrl || express.response.url`.
1680
- */
1681
-
1682
-
1683
- get url() {
1684
- return this.raw.originalUrl || this.raw.url;
1685
- }
1686
-
1687
- get headers() {
1688
- return this.raw.headers;
1689
- }
1690
-
1691
- get method() {
1692
- return this.raw.method;
1693
- }
1694
- /**
1695
- * Contains key-value pairs of data submitted in the request body. By default, it is `undefined`, and is populated when you use
1696
- * `body-parsing` middleware such as `express.json()` or `express.urlencoded()`.
1697
- */
1698
-
1699
-
1700
- get body() {
1701
- return this.raw.body;
1702
- }
1703
-
1704
- get rawBody() {
1705
- return this.raw.rawBody;
1706
- }
1707
- /**
1708
- * When using `cookie-parser` middleware, this property is an object that contains cookies sent by the request.
1709
- * If the request contains no cookies, it defaults to `{}`.
1710
- */
1711
-
1712
-
1713
- get cookies() {
1714
- return this.raw.cookies;
1715
- }
1716
- /**
1717
- * This property is an object containing properties mapped to the named route `parameters`.
1718
- * For example, if you have the route `/user/:name`, then the `name` property is available as `req.params.name`.
1719
- * This object defaults to `{}`.
1720
- */
1721
-
1722
-
1723
- get params() {
1724
- return this.raw.params;
1725
- }
1726
- /**
1727
- * This property is an object containing a property for each query string parameter in the route.
1728
- * When query parser is set to disabled, it is an empty object `{}`, otherwise it is the result of the configured query parser.
1729
- */
1730
-
1731
-
1732
- get query() {
1733
- return this.raw.query;
1734
- }
1735
- /**
1736
- * This property is an object containing a property for each session attributes set by any code.
1737
- * It require to install a middleware like express-session to work.
1738
- */
1739
-
1740
-
1741
- get session() {
1742
- return this.raw.session;
1743
- }
1744
-
1745
- get files() {
1746
- return this.raw.files;
1747
- }
1748
- /**
1749
- * Return the original request framework instance
1750
- */
1751
-
1752
-
1753
- get request() {
1754
- return this.getRequest();
1755
- }
1756
- /**
1757
- * Return the original request node.js instance
1758
- */
1759
-
1760
-
1761
- get req() {
1762
- return this.getReq();
1763
- }
1764
- /**
1765
- * Returns the HTTP request header specified by field. The match is case-insensitive.
1766
- *
1767
- * ```typescript
1768
- * request.get('Content-Type') // => "text/plain"
1769
- * ```
1770
- *
1771
- * @param name
1772
- */
1773
-
1774
-
1775
- get(name) {
1776
- return this.raw.get(name);
1777
- }
1778
-
1779
- accepts(mime) {
1780
- // @ts-ignore
1781
- return this.raw.accepts(mime);
1782
- }
1783
-
1784
- isAborted() {
1785
- return this.raw.aborted;
1786
- }
1787
-
1788
- destroy() {
1789
- // @ts-ignore
1790
- delete this.raw; // @ts-ignore
1791
-
1792
- delete this.response;
1793
- }
1794
- /**
1795
- * Return the Framework response object (express, koa, etc...)
1796
- */
1797
-
1798
-
1799
- getRequest() {
1800
- return this.raw;
1801
- }
1802
- /**
1803
- * Return the Node.js response object
1804
- */
1805
-
1806
-
1807
- getReq() {
1808
- return this.raw;
1809
- }
1810
-
1811
- };
1812
- PlatformRequest = __decorate([Injectable(), Scope(ProviderScope.INSTANCE), __metadata("design:paramtypes", [Object])], PlatformRequest);
1813
-
1814
- var PlatformResponse_1;
1815
-
1816
- const onFinished = require("on-finished");
1817
- /**
1818
- * Platform Response abstraction layer.
1819
- * @platform
1820
- */
1821
-
1822
-
1823
- let PlatformResponse = PlatformResponse_1 = class PlatformResponse {
1824
- constructor({
1825
- response
1826
- }) {
1827
- this.raw = response;
1828
- }
1829
- /**
1830
- * Get the current statusCode
1831
- */
1832
-
1833
-
1834
- get statusCode() {
1835
- return this.raw.statusCode;
1836
- }
1837
- /**
1838
- * An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any). Otherwise, this property is identical to app.locals.
1839
- *
1840
- * This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.
1841
- */
1842
-
1843
-
1844
- get locals() {
1845
- return this.raw.locals;
1846
- }
1847
- /**
1848
- * Return the original response framework instance
1849
- */
1850
-
1851
-
1852
- get response() {
1853
- return this.getResponse();
1854
- }
1855
- /**
1856
- * Return the original response node.js instance
1857
- */
1858
-
1859
-
1860
- get res() {
1861
- return this.getRes();
1862
- }
1863
-
1864
- static onFinished(res, cb) {
1865
- onFinished(res, cb);
1866
- }
1867
- /**
1868
- * Returns the HTTP response header specified by field. The match is case-insensitive.
1869
- *
1870
- * ```typescript
1871
- * response.get('Content-Type') // => "text/plain"
1872
- * ```
1873
- *
1874
- * @param name
1875
- */
1876
-
1877
-
1878
- get(name) {
1879
- return this.raw.get(name);
1880
- }
1881
-
1882
- getHeaders() {
1883
- return this.raw.getHeaders();
1884
- }
1885
- /**
1886
- * Return the Framework response object (express, koa, etc...)
1887
- */
1888
-
1889
-
1890
- getResponse() {
1891
- return this.raw;
1892
- }
1893
- /**
1894
- * Return the Node.js response object
1895
- */
1896
-
1897
-
1898
- getRes() {
1899
- return this.raw;
1900
- }
1901
-
1902
- hasStatus() {
1903
- return this.statusCode !== 200;
1904
- }
1905
- /**
1906
- * Sets the HTTP status for the response.
1907
- *
1908
- * @param status
1909
- */
1910
-
1911
-
1912
- status(status) {
1913
- this.raw.status(status);
1914
- return this;
1915
- }
1916
- /**
1917
- * Set header `field` to `val`, or pass
1918
- * an object of header fields.
1919
- *
1920
- * Examples:
1921
- * ```typescript
1922
- * response.setHeaders({ Accept: 'text/plain', 'X-API-Key': 'tobi' });
1923
- * ```
1924
- *
1925
- * Aliased as `res.header()`.
1926
- */
1927
-
1928
-
1929
- setHeaders(headers) {
1930
- // apply headers
1931
- Object.entries(headers).forEach(([key, item]) => {
1932
- this.setHeader(key, item);
1933
- });
1934
- return this;
1935
- }
1936
-
1937
- setHeader(key, item) {
1938
- if (key.toLowerCase() === "location") {
1939
- return this.location(String(item));
1940
- }
1941
-
1942
- this.raw.set(key, item);
1943
- return this;
1944
- }
1945
- /**
1946
- * Set `Content-Type` response header with `type` through `mime.lookup()`
1947
- * when it does not contain "/", or set the Content-Type to `type` otherwise.
1948
- *
1949
- * Examples:
1950
- *
1951
- * res.type('.html');
1952
- * res.type('html');
1953
- * res.type('json');
1954
- * res.type('application/json');
1955
- * res.type('png');
1956
- */
1957
-
1958
-
1959
- contentType(contentType) {
1960
- this.raw.contentType(contentType);
1961
- return this;
1962
- }
1963
-
1964
- contentLength(length) {
1965
- this.setHeader("Content-Length", length);
1966
- return this;
1967
- }
1968
-
1969
- getContentLength() {
1970
- if (this.get("Content-Length")) {
1971
- return parseInt(this.get("Content-Length"), 10) || 0;
1972
- }
1973
- }
1974
-
1975
- getContentType() {
1976
- return (this.get("Content-Type") || "").split(";")[0];
1977
- }
1978
- /**
1979
- * Sets the HTTP response Content-Disposition header field to “attachment”.
1980
- * If a filename is given, then it sets the Content-Type based on the extension name via res.type(), and sets the Content-Disposition “filename=” parameter.
1981
- *
1982
- * ```typescript
1983
- * res.attachment()
1984
- * // Content-Disposition: attachment
1985
- *
1986
- * res.attachment('path/to/logo.png')
1987
- * // Content-Disposition: attachment; filename="logo.png"
1988
- * // Content-Type: image/png
1989
- * ```
1990
- *
1991
- * @param filename
1992
- */
1993
-
1994
-
1995
- attachment(filename) {
1996
- this.raw.attachment(filename);
1997
- return this;
1998
- }
1999
- /**
2000
- * Redirects to the URL derived from the specified path, with specified status, a positive integer that corresponds to an [HTTP status code](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html).
2001
- * If not specified, status defaults to `302 Found`.
2002
- *
2003
- * @param status
2004
- * @param url
2005
- */
2006
-
2007
-
2008
- redirect(status, url) {
2009
- this.raw.redirect(status, url);
2010
- return this;
2011
- }
2012
- /**
2013
- * Sets the response Location HTTP header to the specified path parameter.
2014
- *
2015
- * @param location
2016
- */
2017
-
2018
-
2019
- location(location) {
2020
- this.raw.location(location);
2021
- return this;
2022
- }
2023
- /**
2024
- * Stream the given data.
2025
- *
2026
- * @param data
2027
- */
2028
-
2029
-
2030
- stream(data) {
2031
- data.pipe(this.raw);
2032
- return this;
2033
- }
2034
- /**
2035
- * Renders a view and sends the rendered HTML string to the client.
2036
- *
2037
- * @param path
2038
- * @param options
2039
- */
2040
-
2041
-
2042
- async render(path, options = {}) {
2043
- return this.platformViews.render(path, _extends({}, this.locals, options));
2044
- }
2045
- /**
2046
- * Send any data to your consumer.
2047
- *
2048
- * This method accept a ReadableStream, a plain object, boolean, string, number, null and undefined data.
2049
- * It choose the better way to send the data.
2050
- *
2051
- * @param data
2052
- */
2053
-
2054
-
2055
- body(data) {
2056
- this.data = data;
2057
-
2058
- if (data === undefined) {
2059
- this.raw.send();
2060
- return this;
2061
- }
2062
-
2063
- if (isStream(data)) {
2064
- this.stream(data);
2065
- return this;
2066
- }
2067
-
2068
- if (Buffer.isBuffer(data)) {
2069
- if (!this.getContentType()) {
2070
- this.contentType("application/octet-stream");
2071
- }
2072
-
2073
- this.contentLength(data.length);
2074
- this.raw.send(data);
2075
- return this;
2076
- }
2077
-
2078
- if (isBoolean(data) || isNumber(data) || isString(data) || data === null) {
2079
- this.raw.send(data);
2080
- return this;
2081
- }
2082
-
2083
- this.raw.json(data);
2084
- return this;
2085
- }
2086
-
2087
- getBody() {
2088
- return this.data;
2089
- }
2090
- /**
2091
- * Add a listener to handler the end of the request/response.
2092
- * @param cb
2093
- */
2094
-
2095
-
2096
- onEnd(cb) {
2097
- PlatformResponse_1.onFinished(this.getRes(), cb);
2098
- return this;
2099
- }
2100
-
2101
- isDone() {
2102
- if (!this.raw) {
2103
- return true;
2104
- }
2105
-
2106
- const res = this.getRes();
2107
- return Boolean(this.isHeadersSent() || res.writableEnded || res.writableFinished);
2108
- }
2109
-
2110
- destroy() {
2111
- // @ts-ignore
2112
- delete this.raw;
2113
- delete this.data; // @ts-ignore
2114
-
2115
- delete this.request;
2116
- }
2117
-
2118
- isHeadersSent() {
2119
- return this.getRes().headersSent;
2120
- }
2121
-
2122
- };
2123
- PlatformResponse = PlatformResponse_1 = __decorate([Injectable(), Scope(ProviderScope.INSTANCE), __metadata("design:paramtypes", [Object])], PlatformResponse);
2124
-
2125
- const _excluded$3 = ["event", "endpoint", "ignoreUrlPatterns", "ResponseKlass", "RequestKlass"];
2126
-
2127
- var _ignoreUrlPatterns = /*#__PURE__*/_classPrivateFieldLooseKey("ignoreUrlPatterns");
2128
-
2129
- class PlatformContext extends DIContext {
2130
- constructor(_ref) {
2131
- let {
2132
- event,
2133
- endpoint,
2134
- ignoreUrlPatterns = [],
2135
- ResponseKlass = PlatformResponse,
2136
- RequestKlass = PlatformRequest
2137
- } = _ref,
2138
- options = _objectWithoutPropertiesLoose(_ref, _excluded$3);
2139
-
2140
- super(_extends({}, options, {
2141
- ignoreLog: () => {
2142
- return _classPrivateFieldLooseBase(this, _ignoreUrlPatterns)[_ignoreUrlPatterns].find(reg => !!this.url.match(reg));
2143
- }
2144
- }));
2145
- Object.defineProperty(this, _ignoreUrlPatterns, {
2146
- writable: true,
2147
- value: void 0
2148
- });
2149
- _classPrivateFieldLooseBase(this, _ignoreUrlPatterns)[_ignoreUrlPatterns] = [];
2150
- endpoint && (this.endpoint = endpoint);
2151
- _classPrivateFieldLooseBase(this, _ignoreUrlPatterns)[_ignoreUrlPatterns] = ignoreUrlPatterns.map(pattern => typeof pattern === "string" ? new RegExp(pattern, "gi") : pattern);
2152
- this.response = new ResponseKlass(event);
2153
- this.request = new RequestKlass(event);
2154
- this.response.request = this.request;
2155
- this.request.response = this.response;
2156
- this.request.request.$ctx = this;
2157
- this.request.request.id = this.id;
2158
- this.logger.url = this.url;
2159
- this.container.set(PlatformResponse, this.response);
2160
- this.container.set(PlatformRequest, this.request);
2161
- this.container.set(PlatformContext, this);
2162
- this.response.setHeader("x-request-id", this.id);
2163
- }
2164
-
2165
- get url() {
2166
- return this.request.url;
2167
- }
2168
-
2169
- get app() {
2170
- return this.injector.get(PlatformApplication);
2171
- }
2172
-
2173
- async destroy() {
2174
- var _this$request, _this$request$request;
2175
-
2176
- await super.destroy();
2177
- (_this$request = this.request) == null ? true : (_this$request$request = _this$request.request) == null ? true : delete _this$request$request.$ctx;
2178
- this.response.destroy();
2179
- this.request.destroy(); // @ts-ignore
2180
-
2181
- delete this.endpoint; // @ts-ignore
2182
-
2183
- delete this.response; // @ts-ignore
2184
-
2185
- delete this.request;
2186
- }
2187
-
2188
- isDone() {
2189
- return !this.request || !this.response;
2190
- }
2191
- /**
2192
- * Return the framework request instance (Express, Koa, etc...)
2193
- */
2194
-
2195
-
2196
- getRequest() {
2197
- return this.request.getRequest();
2198
- }
2199
- /**
2200
- * Return the framework response instance (Express, Koa, etc...)
2201
- */
2202
-
2203
-
2204
- getResponse() {
2205
- return this.response.getResponse();
2206
- }
2207
- /**
2208
- * Get Node.js request
2209
- */
2210
-
2211
-
2212
- getReq() {
2213
- return this.request.getReq();
2214
- }
2215
- /**
2216
- * Get Node.js response
2217
- */
2218
-
2219
-
2220
- getRes() {
2221
- return this.response.getRes();
2222
- }
2223
- /**
2224
- * Return the original application instance.
2225
- */
2226
-
2227
-
2228
- getApp() {
2229
- return this.app.getApp();
2230
- }
2231
-
2232
- }
2233
-
2234
- class PlatformRouteDetails {
2235
- constructor({
2236
- provider,
2237
- endpoint,
2238
- method,
2239
- url
2240
- }) {
2241
- this.provider = provider;
2242
- this.endpoint = endpoint;
2243
- this.method = method;
2244
- this.url = url;
2245
- this.rawBody = !!endpoint.params.find(param => param.paramType === ParamTypes.RAW_BODY);
2246
- }
2247
-
2248
- get name() {
2249
- return `${this.endpoint.targetName}.${this.methodClassName}()`;
2250
- }
2251
-
2252
- get className() {
2253
- return this.endpoint.targetName;
2254
- }
2255
-
2256
- get methodClassName() {
2257
- return String(this.endpoint.propertyKey);
2258
- }
2259
-
2260
- get parameters() {
2261
- return this.endpoint.params;
2262
- }
2263
-
2264
- toJSON() {
2265
- return {
2266
- method: this.method,
2267
- name: this.name,
2268
- url: this.url,
2269
- className: this.className,
2270
- methodClassName: this.methodClassName,
2271
- parameters: this.parameters,
2272
- rawBody: this.rawBody
2273
- };
2274
- }
2275
-
2276
- }
2277
-
2278
- const ROUTER_OPTIONS = Symbol.for("ROUTER_OPTIONS");
2279
-
2280
- class ControllerProvider extends Provider {
2281
- constructor(provide, options = {}) {
2282
- super(provide, options);
2283
- this.type = ProviderType.CONTROLLER;
2284
- this.entity = JsonEntityStore.from(provide);
2285
- }
2286
-
2287
- get path() {
2288
- return this.entity.path;
2289
- }
2290
-
2291
- set path(path) {
2292
- this.entity.path = path;
2293
- }
2294
- /**
2295
- *
2296
- * @returns {EndpointMetadata[]}
2297
- */
2298
-
2299
-
2300
- get endpoints() {
2301
- return EndpointMetadata.getEndpoints(this.provide);
2302
- }
2303
-
2304
- get children() {
2305
- return this.store.get("childrenControllers", []);
2306
- }
2307
- /**
2308
- *
2309
- * @returns {ControllerProvider}
2310
- */
2311
-
2312
-
2313
- get parent() {
2314
- return this.store.get("parentController");
2315
- }
2316
- /**
2317
- *
2318
- */
2319
-
2320
-
2321
- get routerOptions() {
2322
- return this.store.get(ROUTER_OPTIONS) || {};
2323
- }
2324
- /**
2325
- *
2326
- * @param value
2327
- */
2328
-
2329
-
2330
- set routerOptions(value) {
2331
- this.store.set(ROUTER_OPTIONS, value);
2332
- }
2333
- /**
2334
- *
2335
- * @returns {any[]}
2336
- */
2337
-
2338
-
2339
- get middlewares() {
2340
- return Object.assign({
2341
- use: [],
2342
- useAfter: [],
2343
- useBefore: []
2344
- }, this.store.get("middlewares", {}));
2345
- }
2346
- /**
2347
- *
2348
- * @param middlewares
2349
- */
2350
-
2351
-
2352
- set middlewares(middlewares) {
2353
- const mdlwrs = this.middlewares;
2354
-
2355
- const concat = (key, a, b) => a[key] = a[key].concat(b[key]);
2356
-
2357
- Object.keys(middlewares).forEach(key => {
2358
- concat(key, mdlwrs, middlewares);
2359
- });
2360
- this.store.set("middlewares", mdlwrs);
2361
- }
2362
- /**
2363
- *
2364
- * @returns {boolean}
2365
- */
2366
-
2367
-
2368
- hasChildren() {
2369
- return !!this.children.length;
2370
- }
2371
- /**
2372
- *
2373
- * @returns {boolean}
2374
- */
2375
-
2376
-
2377
- hasParent() {
2378
- return !!this.store.get("parentController");
2379
- }
2380
-
2381
- getRouter() {
2382
- return this.router;
2383
- }
2384
-
2385
- setRouter(router) {
2386
- this.router = router;
2387
- return this;
2388
- }
2389
-
2390
- }
2391
-
2392
- function getControllerPath(basePath, provider) {
2393
- return (basePath === provider.path ? provider.path : (basePath || "") + provider.path).replace(/\/\//gi, "/");
2394
- }
2395
-
2396
- var _routes, _controllers;
2397
- /**
2398
- * `Platform` is used to provide all routes collected by annotation `@Controller`.
2399
- *
2400
- * @platform
2401
- */
2402
-
2403
- let Platform = (_routes = /*#__PURE__*/_classPrivateFieldLooseKey("routes"), _controllers = /*#__PURE__*/_classPrivateFieldLooseKey("controllers"), class Platform {
2404
- constructor(injector, platformApplication) {
2405
- Object.defineProperty(this, _routes, {
2406
- writable: true,
2407
- value: void 0
2408
- });
2409
- Object.defineProperty(this, _controllers, {
2410
- writable: true,
2411
- value: void 0
2412
- });
2413
- this.injector = injector;
2414
- this.platformApplication = platformApplication;
2415
- _classPrivateFieldLooseBase(this, _routes)[_routes] = [];
2416
- _classPrivateFieldLooseBase(this, _controllers)[_controllers] = [];
2417
- }
2418
-
2419
- get app() {
2420
- return this.platformApplication;
2421
- }
2422
-
2423
- get routes() {
2424
- return _classPrivateFieldLooseBase(this, _routes)[_routes];
2425
- }
2426
-
2427
- addRoutes(routes) {
2428
- routes.forEach(routeSettings => {
2429
- this.addRoute(routeSettings.route, routeSettings.token);
2430
- });
2431
- }
2432
-
2433
- addRoute(endpoint, token) {
2434
- const {
2435
- injector
2436
- } = this;
2437
-
2438
- if (injector.hasProvider(token)) {
2439
- const provider = injector.getProvider(token);
2440
-
2441
- if (provider.type === ProviderType.CONTROLLER) {
2442
- const route = getControllerPath(endpoint, provider);
2443
-
2444
- if (!provider.hasParent()) {
2445
- const routes = this.buildRoutes(route, provider);
2446
-
2447
- _classPrivateFieldLooseBase(this, _routes)[_routes].push(...routes);
2448
-
2449
- _classPrivateFieldLooseBase(this, _controllers)[_controllers].push({
2450
- route,
2451
- provider
2452
- });
2453
-
2454
- this.app.use(route, ...[].concat(provider.getRouter().callback()));
2455
- }
2456
- }
2457
- }
2458
-
2459
- return this;
2460
- }
2461
- /**
2462
- * Get all routes built by TsExpressDecorators and mounted on Express application.
2463
- * @returns {PlatformRouteDetails[]}
2464
- */
2465
-
2466
-
2467
- getRoutes() {
2468
- return _classPrivateFieldLooseBase(this, _routes)[_routes];
2469
- }
2470
-
2471
- getMountedControllers() {
2472
- return _classPrivateFieldLooseBase(this, _controllers)[_controllers];
2473
- }
2474
- /**
2475
- *
2476
- * @param ctrl
2477
- * @param endpointUrl
2478
- */
2479
-
2480
-
2481
- buildRoutes(endpointUrl, ctrl) {
2482
- const {
2483
- injector
2484
- } = this;
2485
- let routes = [];
2486
- routes = ctrl.children.map(ctrl => injector.getProvider(ctrl)).reduce((routes, provider) => {
2487
- return routes.concat(this.buildRoutes(`${endpointUrl}${provider.path}`, provider));
2488
- }, routes);
2489
- ctrl.endpoints.forEach(endpoint => {
2490
- endpoint.operationPaths.forEach(({
2491
- path,
2492
- method
2493
- }) => {
2494
- if (method) {
2495
- routes.push(new PlatformRouteDetails({
2496
- provider: ctrl,
2497
- endpoint,
2498
- method,
2499
- url: `${endpointUrl}${path || ""}`.replace(/\/\//gi, "/")
2500
- }));
2501
- }
2502
- });
2503
- });
2504
- return routes;
2505
- }
2506
-
2507
- });
2508
- Platform = __decorate([Injectable({
2509
- scope: ProviderScope.SINGLETON
2510
- }), __metadata("design:paramtypes", [InjectorService, PlatformApplication])], Platform);
2511
-
2512
- /**
2513
- * @ignore
2514
- */
2515
-
2516
- let PlatformModule = class PlatformModule {
2517
- constructor(injector, platform) {
2518
- this.injector = injector;
2519
- this.platform = platform;
2520
- this.createRoutersFromControllers();
2521
- }
2522
- /**
2523
- * Create routers from the collected controllers
2524
- */
2525
-
2526
-
2527
- createRoutersFromControllers() {
2528
- const {
2529
- injector
2530
- } = this;
2531
- return injector.getProviders(ProviderType.CONTROLLER).map(provider => {
2532
- provider.setRouter(PlatformRouter.create(injector, provider.routerOptions));
2533
-
2534
- if (!provider.hasParent()) {
2535
- return new PlatformControllerBuilder(provider).build(injector);
2536
- }
2537
- }).filter(Boolean);
2538
- }
2539
-
2540
- $$loadRoutes() {
2541
- const routes = this.injector.settings.get("routes");
2542
- this.platform.addRoutes(routes);
2543
- }
2544
-
2545
- };
2546
- PlatformModule = __decorate([Module({
2547
- imports: [InjectorService, ConverterService, Platform]
2548
- }), __metadata("design:paramtypes", [InjectorService, Platform])], PlatformModule);
2549
-
2550
- $log.name = "TSED";
2551
- function createInjector(settings = {}) {
2552
- const injector = new InjectorService();
2553
- injector.settings = createSettingsService(injector);
2554
- injector.logger = $log;
2555
- injector.settings.set(settings);
2556
- setLoggerLevel(injector);
2557
- return injector;
2558
- }
2559
-
2560
- function createSettingsService(injector) {
2561
- const provider = GlobalProviders.get(PlatformConfiguration).clone();
2562
- provider.instance = injector.invoke(provider.useClass);
2563
- injector.addProvider(PlatformConfiguration, provider);
2564
- return provider.instance;
2565
- }
2566
-
2567
- function createPlatformApplication(injector) {
2568
- injector.forkProvider(PlatformApplication);
2569
- }
2570
-
2571
- /**
2572
- * Inject the Http.Server instance.
2573
- *
2574
- * ### Example
2575
- *
2576
- * ```typescript
2577
- * import {HttpServer, Service} from "@tsed/common";
2578
- *
2579
- * @Service()
2580
- * export default class OtherService {
2581
- * constructor(@HttpServer httpServer: HttpServer) {}
2582
- * }
2583
- * ```
2584
- *
2585
- * > Note: TypeScript transform and store `HttpServer` as `Function` type in the metadata. So to inject a factory, you must use the `@Inject(type)` decorator.
2586
- *
2587
- * @param {Type<any>} target
2588
- * @param {string} targetKey
2589
- * @param {TypedPropertyDescriptor<Function> | number} descriptor
2590
- * @returns {any}
2591
- * @decorator
2592
- */
2593
-
2594
- function HttpServer(target, targetKey, descriptor) {
2595
- return Inject(HttpServer)(target, targetKey, descriptor);
2596
- }
2597
-
2598
- function listenServer(http, settings) {
2599
- const {
2600
- address,
2601
- port
2602
- } = settings;
2603
- const promise = new Promise((resolve, reject) => {
2604
- http.on("listening", resolve);
2605
- http.on("error", reject);
2606
- }).then(() => {
2607
- const port = http.address().port;
2608
- return {
2609
- address: settings.address,
2610
- port
2611
- };
2612
- });
2613
- http.listen(port, address);
2614
- return promise;
2615
- }
2616
-
2617
- function createHttpServer(injector) {
2618
- injector.forkProvider(HttpServer);
2619
- }
2620
- registerProvider({
2621
- provide: HttpServer,
2622
- deps: [PlatformApplication],
2623
- scope: ProviderScope.SINGLETON,
2624
- global: true,
2625
-
2626
- useFactory(platformApplication) {
2627
- return Http.createServer(platformApplication.callback());
2628
- }
2629
-
2630
- });
2631
- async function listenHttpServer(injector) {
2632
- const {
2633
- settings
2634
- } = injector;
2635
- const server = injector.get(HttpServer);
2636
-
2637
- if (settings.httpPort !== false && server) {
2638
- const {
2639
- address,
2640
- port
2641
- } = settings.getHttpPort();
2642
- injector.logger.debug(`Start server on http://${address}:${port}`);
2643
- const options = await listenServer(server, {
2644
- address,
2645
- port
2646
- });
2647
- settings.setHttpPort(options);
2648
- injector.logger.info(`Listen server on http://${options.address}:${options.port}`);
2649
- }
2650
- }
2651
-
2652
- /**
2653
- * Inject the Https.Server instance.
2654
- *
2655
- * ### Example
2656
- *
2657
- * ```typescript
2658
- * import {HttpsServer, Service} from "@tsed/common";
2659
- *
2660
- * @Service()
2661
- * export default class OtherService {
2662
- * constructor(@HttpsServer httpServer: HttpServer) {}
2663
- * }
2664
- * ```
2665
- *
2666
- * > Note: TypeScript transform and store `HttpsServer` as `Function` type in the metadata. So to inject a factory, you must use the `@Inject(type)` decorator.
2667
- *
2668
- * @param {Type<any>} target
2669
- * @param {string} targetKey
2670
- * @param {TypedPropertyDescriptor<Function> | number} descriptor
2671
- * @returns {any}
2672
- * @decorator
2673
- */
2674
-
2675
- function HttpsServer(target, targetKey, descriptor) {
2676
- return Inject(HttpsServer)(target, targetKey, descriptor);
2677
- }
2678
-
2679
- function createHttpsServer(injector) {
2680
- injector.forkProvider(HttpsServer);
2681
- }
2682
- registerProvider({
2683
- provide: HttpsServer,
2684
- deps: [PlatformApplication, Configuration],
2685
- scope: ProviderScope.SINGLETON,
2686
- global: true,
2687
-
2688
- useFactory(platformApplication, settings) {
2689
- const options = settings.httpsOptions;
2690
- return Https.createServer(options, platformApplication.callback());
2691
- }
2692
-
2693
- });
2694
- async function listenHttpsServer(injector) {
2695
- const {
2696
- settings
2697
- } = injector;
2698
- const server = injector.get(HttpsServer);
2699
-
2700
- if (settings.httpsPort !== false && server) {
2701
- const {
2702
- address,
2703
- port
2704
- } = settings.getHttpsPort();
2705
- injector.logger.debug(`Start server on https://${address}:${port}`);
2706
- const options = await listenServer(server, {
2707
- address,
2708
- port
2709
- });
2710
- settings.setHttpsPort(options);
2711
- injector.logger.info(`Listen server on https://${options.address}:${options.port}`);
2712
- }
2713
- }
2714
-
2715
- function printRoutes(routes) {
2716
- const mapColor = {
2717
- GET: "green",
2718
- POST: "yellow",
2719
- PUT: "blue",
2720
- DELETE: "red",
2721
- PATCH: "magenta",
2722
- ALL: "cyan"
2723
- };
2724
- const list = routes.map(route => {
2725
- const obj = route.toJSON();
2726
- const method = obj.method.toUpperCase();
2727
- obj.method = {
2728
- length: method.length,
2729
- toString: () => {
2730
- return colorize(method, mapColor[method]);
2731
- }
2732
- };
2733
- return obj;
2734
- });
2735
- const str = $log.drawTable(list, {
2736
- padding: 1,
2737
- header: {
2738
- method: "Method",
2739
- url: "Endpoint",
2740
- name: "Class method"
2741
- }
2742
- });
2743
- return "\n" + str.trim();
2744
- }
2745
-
2746
- const _excluded$2 = ["reqIdBuilder"];
2747
-
2748
- const uuidv4 = require("uuid").v4;
2749
-
2750
- const defaultReqIdBuilder = req => req.get("x-request-id") || uuidv4().replace(/-/gi, "");
2751
- /**
2752
- * Create the TsED context to wrap request, response, injector, etc...
2753
- * @param injector
2754
- * @ignore
2755
- */
2756
-
2757
-
2758
- function createContext(injector) {
2759
- var _injector$getProvider, _injector$getProvider2;
2760
-
2761
- const ResponseKlass = (_injector$getProvider = injector.getProvider(PlatformResponse)) == null ? void 0 : _injector$getProvider.useClass;
2762
- const RequestKlass = (_injector$getProvider2 = injector.getProvider(PlatformRequest)) == null ? void 0 : _injector$getProvider2.useClass;
2763
- const platformViews = injector.get(PlatformViews);
2764
-
2765
- const _injector$settings$lo = injector.settings.logger,
2766
- {
2767
- reqIdBuilder = defaultReqIdBuilder
2768
- } = _injector$settings$lo,
2769
- loggerOptions = _objectWithoutPropertiesLoose(_injector$settings$lo, _excluded$2);
2770
-
2771
- return async event => {
2772
- const ctx = new PlatformContext(_extends({
2773
- event,
2774
- id: reqIdBuilder(event.request),
2775
- logger: injector.logger
2776
- }, loggerOptions, {
2777
- injector,
2778
- ResponseKlass,
2779
- RequestKlass
2780
- }));
2781
- ctx.response.platformViews = platformViews;
2782
- ctx.response.onEnd(async () => {
2783
- await ctx.emit("$onResponse", ctx);
2784
- await ctx.destroy();
2785
- });
2786
- await ctx.emit("$onRequest", ctx);
2787
- return ctx;
2788
- };
2789
- }
2790
-
2791
- const SKIP_HOOKS = ["$beforeInit", "$afterInit", "$onInit", "$onMountingMiddlewares"];
2792
- const {
2793
- bind,
2794
- start,
2795
- end,
2796
- log
2797
- } = PerfLogger.get("bootstrap");
2798
- /**
2799
- * @platform
2800
- */
2801
-
2802
- var _rootModule = /*#__PURE__*/_classPrivateFieldLooseKey("rootModule");
2803
-
2804
- var _injector = /*#__PURE__*/_classPrivateFieldLooseKey("injector");
2805
-
2806
- var _providers = /*#__PURE__*/_classPrivateFieldLooseKey("providers");
2807
-
2808
- class PlatformBuilder {
2809
- constructor({
2810
- name,
2811
- providers
2812
- }) {
2813
- Object.defineProperty(this, _rootModule, {
2814
- writable: true,
2815
- value: void 0
2816
- });
2817
- Object.defineProperty(this, _injector, {
2818
- writable: true,
2819
- value: void 0
2820
- });
2821
- Object.defineProperty(this, _providers, {
2822
- writable: true,
2823
- value: void 0
2824
- });
2825
- this.name = "";
2826
- this.startedAt = new Date();
2827
- this.name = name;
2828
- _classPrivateFieldLooseBase(this, _providers)[_providers] = toMap(providers, "provide");
2829
- this.locals = new Container();
2830
- this.useProvider(PlatformHandler, _classPrivateFieldLooseBase(this, _providers)[_providers].get(PlatformHandler)).useProvider(PlatformResponse, _classPrivateFieldLooseBase(this, _providers)[_providers].get(PlatformResponse)).useProvider(PlatformRequest, _classPrivateFieldLooseBase(this, _providers)[_providers].get(PlatformRequest)).useProvider(PlatformRouter, _classPrivateFieldLooseBase(this, _providers)[_providers].get(PlatformRouter)).useProvider(PlatformApplication, _classPrivateFieldLooseBase(this, _providers)[_providers].get(PlatformApplication)).useProvider(Platform, _classPrivateFieldLooseBase(this, _providers)[_providers].get(Platform));
2831
- }
2832
-
2833
- get injector() {
2834
- return _classPrivateFieldLooseBase(this, _injector)[_injector];
2835
- }
2836
-
2837
- get rootModule() {
2838
- return _classPrivateFieldLooseBase(this, _rootModule)[_rootModule];
2839
- }
2840
-
2841
- get app() {
2842
- return this.injector.get(PlatformApplication);
2843
- }
2844
-
2845
- get platform() {
2846
- return this.injector.get(Platform);
2847
- }
2848
- /**
2849
- * Return the settings configured by the decorator @@Configuration@@.
2850
- *
2851
- * ```typescript
2852
- * @Configuration({
2853
- * rootDir: Path.resolve(__dirname),
2854
- * port: 8000,
2855
- * httpsPort: 8080,
2856
- * mount: {
2857
- * "/rest": "${rootDir}/controllers/**\/*.js"
2858
- * }
2859
- * })
2860
- * export class Server {
2861
- * $onInit(){
2862
- * console.log(this.settings); // {rootDir, port, httpsPort,...}
2863
- * }
2864
- * }
2865
- * ```
2866
- *
2867
- * @returns {PlatformConfiguration}
2868
- */
2869
-
2870
-
2871
- get settings() {
2872
- return this.injector.settings;
2873
- }
2874
-
2875
- get logger() {
2876
- return this.injector.logger;
2877
- }
2878
-
2879
- get disableBootstrapLog() {
2880
- return this.settings.logger.disableBootstrapLog;
2881
- }
2882
-
2883
- static build(platformBuildClass) {
2884
- return new platformBuildClass({
2885
- name: nameOf(platformBuildClass).replace("Platform", "").toLowerCase(),
2886
- providers: platformBuildClass.providers
2887
- });
2888
- }
2889
-
2890
- log(...data) {
2891
- return this.disableBootstrapLog && this.logger.info(...data);
2892
- }
2893
- /**
2894
- * Add classes to the components list
2895
- * @param classes
2896
- */
2897
-
2898
-
2899
- addComponents(classes) {
2900
- this.settings.componentsScan = this.settings.componentsScan.concat(classes);
2901
- return this;
2902
- }
2903
- /**
2904
- * Add classes decorated by @@Controller@@ to components container.
2905
- *
2906
- * ### Example
2907
- *
2908
- * ```typescript
2909
- * @Controller('/ctrl')
2910
- * class MyController{
2911
- * }
2912
- *
2913
- * platform.addControllers('/rest', [MyController])
2914
- * ```
2915
- *
2916
- * ::: tip
2917
- * If the MyController class isn't decorated, the class will be ignored.
2918
- * :::
2919
- *
2920
- * @param {string} endpoint
2921
- * @param {any[]} controllers
2922
- */
2923
-
2924
-
2925
- addControllers(endpoint, controllers) {
2926
- this.settings.mount[endpoint] = (this.settings.mount[endpoint] || []).concat(controllers);
2927
- }
2928
-
2929
- async runLifecycle() {
2930
- setLoggerLevel(this.injector);
2931
- await this.importProviders();
2932
- await this.loadInjector();
2933
- this.useContext();
2934
- this.useRouter();
2935
- await this.loadRoutes();
2936
- await this.logRoutes();
2937
- }
2938
-
2939
- async loadInjector() {
2940
- const {
2941
- injector
2942
- } = this;
2943
- await this.callHook("$beforeInit");
2944
- this.log("Build providers");
2945
- const container = createContainer(constructorOf(this.rootModule));
2946
- await injector.load(container, PlatformModule);
2947
- this.log("Settings and injector loaded");
2948
- await this.callHook("$afterInit");
2949
- }
2950
-
2951
- async listen() {
2952
- await this.callHook("$beforeListen");
2953
- await this.listenServers();
2954
- await this.callHook("$afterListen");
2955
- await this.ready();
2956
- end();
2957
- }
2958
-
2959
- async stop() {
2960
- await this.callHook("$onDestroy");
2961
- return this.injector.destroy();
2962
- }
2963
-
2964
- async ready() {
2965
- const {
2966
- startedAt
2967
- } = this;
2968
- await this.callHook("$onReady");
2969
- await this.injector.emit("$onServerReady");
2970
- this.log(`Started in ${new Date().getTime() - startedAt.getTime()} ms`);
2971
- }
2972
-
2973
- async callHook(hook, ...args) {
2974
- const {
2975
- injector,
2976
- rootModule
2977
- } = this;
2978
- log(hook);
2979
-
2980
- if (!injector.settings.logger.disableBootstrapLog) {
2981
- injector.logger.info(`\x1B[1mCall hook ${hook}\x1B[22m`);
2982
- } // call hook for the Server
2983
-
2984
-
2985
- if (hook in rootModule) {
2986
- await rootModule[hook](...args);
2987
- } // Load middlewares for the given hook
2988
-
2989
-
2990
- this.loadMiddlewaresFor(hook); // call hooks added by providers
2991
-
2992
- if (!SKIP_HOOKS.includes(hook)) {
2993
- await injector.emit(hook);
2994
- }
2995
- }
2996
-
2997
- async loadStatics() {
2998
- const {
2999
- settings
3000
- } = this;
3001
-
3002
- if (settings.statics) {
3003
- Object.entries(settings.statics).forEach(([path, items]) => {
3004
- [].concat(items).forEach(options => {
3005
- const opts = typeof options === "string" ? {
3006
- root: options
3007
- } : options;
3008
- this.platform.app.statics(path, opts);
3009
- });
3010
- });
3011
- }
3012
- }
3013
-
3014
- useProvider(token, settings) {
3015
- this.locals.addProvider(token, settings);
3016
- return this;
3017
- }
3018
-
3019
- async importProviders() {
3020
- this.injector.logger.debug("Scan components");
3021
- const providers = await importProviders(this.injector.settings, ["imports", "mount", "componentsScan"]);
3022
- const routes = providers.filter(provider => !!provider.route).map(({
3023
- route,
3024
- token
3025
- }) => ({
3026
- route,
3027
- token
3028
- }));
3029
- this.settings.set("routes", routes);
3030
- }
3031
- /**
3032
- * Load middlewares from configuration for the given hook
3033
- * @param hook
3034
- * @protected
3035
- */
3036
-
3037
-
3038
- loadMiddlewaresFor(hook) {
3039
- return getMiddlewaresForHook(hook, this.settings, "$beforeRoutesInit").forEach(({
3040
- use
3041
- }) => {
3042
- this.app.use(use);
3043
- });
3044
- }
3045
-
3046
- useRouter() {
3047
- return this;
3048
- }
3049
-
3050
- useContext() {
3051
- return this;
3052
- }
3053
-
3054
- async bootstrap(module, settings = {}) {
3055
- var _settings$logger;
3056
-
3057
- // istanbul ignore next
3058
- if ((_settings$logger = settings.logger) != null && _settings$logger.perf) {
3059
- start();
3060
- bind(this);
3061
- settings.logger = _extends({}, settings.logger, {
3062
- level: "off"
3063
- });
3064
- }
3065
-
3066
- this.createInjector(module, _extends({}, settings, {
3067
- PLATFORM_NAME: this.name
3068
- }));
3069
- this.createRootModule(module);
3070
- await this.runLifecycle();
3071
- return this;
3072
- }
3073
-
3074
- async listenServers() {
3075
- await Promise.all([listenHttpServer(this.injector), listenHttpsServer(this.injector)]);
3076
- }
3077
-
3078
- async logRoutes() {
3079
- const {
3080
- logger,
3081
- platform
3082
- } = this;
3083
-
3084
- if (!this.settings.logger.disableRoutesSummary && !this.disableBootstrapLog) {
3085
- logger.info("Routes mounted :");
3086
- logger.info(printRoutes(await this.injector.alterAsync("$logRoutes", platform.getRoutes())));
3087
- }
3088
- }
3089
-
3090
- async loadRoutes() {
3091
- // istanbul ignore next
3092
- if (this.settings.logger.level !== "off") {
3093
- this.app.use(PlatformLogMiddleware);
3094
- }
3095
-
3096
- this.log("Load routes");
3097
- await this.callHook("$beforeRoutesInit");
3098
- await this.callHook("$$loadRoutes");
3099
- await this.callHook("$onRoutesInit");
3100
- await this.loadStatics();
3101
- await this.callHook("$afterRoutesInit");
3102
- }
3103
-
3104
- createInjector(module, settings) {
3105
- const configuration = getConfiguration(module, settings);
3106
- _classPrivateFieldLooseBase(this, _injector)[_injector] = createInjector(configuration); // configure locals providers
3107
-
3108
- this.locals.forEach(provider => {
3109
- this.injector.addProvider(provider.token, provider);
3110
- });
3111
- createPlatformApplication(this.injector);
3112
- createHttpsServer(this.injector);
3113
- createHttpServer(this.injector);
3114
- }
3115
-
3116
- createRootModule(module) {
3117
- _classPrivateFieldLooseBase(this, _rootModule)[_rootModule] = this.injector.invoke(module);
3118
- this.injector.delete(constructorOf(_classPrivateFieldLooseBase(this, _rootModule)[_rootModule]));
3119
- this.injector.delete(classOf(_classPrivateFieldLooseBase(this, _rootModule)[_rootModule]));
3120
- }
3121
-
3122
- }
3123
-
3124
- /**
3125
- * Define multer option for all MultipartFile
3126
- *
3127
- * ```typescript
3128
- * import {Controller, Post, PlatformMulterFile, MultipartFile, MulterOptions} from "@tsed/common";
3129
- *
3130
- * @Controller('/')
3131
- * class MyCtrl {
3132
- * @Post('/file')
3133
- * private uploadFile(@MultipartFile("file1") file: PlatformMulterFile) {
3134
- *
3135
- * }
3136
- *
3137
- * @Post('/file')
3138
- * @MulterOptions({dest: "/other-dir"})
3139
- * private uploadFile(@MultipartFile("file1") file: PlatformMulterFile) {
3140
- *
3141
- * }
3142
- *
3143
- * @Post('/file2')
3144
- * @MulterOptions({dest: "/other-dir"})
3145
- * private uploadFile(@MultipartFile("file1") file: PlatformMulterFile, @MultipartFile("file2") file2: PlatformMulterFile) {
3146
- *
3147
- * }
3148
- *
3149
- * @Post('/files')
3150
- * private uploadFile(@MultipartFile("file1") files: PlatformMulterFile[]) {
3151
- *
3152
- * }
3153
- * }
3154
- * ```
3155
- *
3156
- * See the tutorial on the [multer configuration](/tutorials/multer.md).
3157
- *
3158
- * @param {multer.Options} options
3159
- * @returns {(target: any, propertyKey: string, descriptor: PropertyDescriptor) => PropertyDescriptor}
3160
- * @decorator
3161
- * @multer
3162
- */
3163
-
3164
- function MulterOptions(options) {
3165
- return (target, propertyKey, descriptor) => {
3166
- StoreMerge(PlatformMulterMiddleware, {
3167
- options
3168
- })(target, propertyKey, descriptor);
3169
- return descriptor;
3170
- };
3171
- }
3172
-
3173
- /**
3174
- * Define file size limit.
3175
- *
3176
- * ```typescript
3177
- * import {Controller, Post} from "@tsed/common";
3178
- * import {MulterOptions, MultipartFile} from "@tsed/common";
3179
- * import {Multer} from "@types/multer";
3180
- *
3181
- * type MulterFile = Express.Multer.File;
3182
- *
3183
- * @Controller('/')
3184
- * class MyCtrl {
3185
- * @Post('/file2')
3186
- * @MulterFileSize(1024) // (Ko). Applied for all fields
3187
- * private uploadFile(@MultipartFile("file1") file: MulterFile, @MultipartFile("file2") file2: MulterFile) {
3188
- *
3189
- * }
3190
- * }
3191
- * ```
3192
- *
3193
- * > See the tutorial on the [multer configuration](/tutorials/multer.md).
3194
- * @param fileSize
3195
- * @returns {(target: any, propertyKey: string, descriptor: PropertyDescriptor) => PropertyDescriptor}
3196
- * @decorator
3197
- * @multer
3198
- */
3199
-
3200
- function MulterFileSize(fileSize) {
3201
- return MulterOptions({
3202
- limits: {
3203
- fileSize
3204
- }
3205
- });
3206
- }
3207
-
3208
- function mapOptions$1(name, maxCount) {
3209
- return {
3210
- fields: [{
3211
- name,
3212
- maxCount
3213
- }]
3214
- };
3215
- }
3216
- /**
3217
- * Define a parameter as Multipart file.
3218
- *
3219
- * ```typescript
3220
- * import {Controller, Post} from "@tsed/common";
3221
- * import {MulterOptions, MultipartFile} from "@tsed/common";
3222
- * import {Multer} from "@types/multer";
3223
- *
3224
- * type MulterFile = Express.Multer.File;
3225
- *
3226
- * @Controller('/')
3227
- * class MyCtrl {
3228
- * @Post('/file')
3229
- * private uploadFile(@MultipartFile("file1") file: MulterFile) {
3230
- *
3231
- * }
3232
- *
3233
- * @Post('/file')
3234
- * @MulterOptions({dest: "/other-dir"})
3235
- * private uploadFile(@MultipartFile("file1") file: MulterFile) {
3236
- *
3237
- * }
3238
- *
3239
- * @Post('/file2')
3240
- * @MulterOptions({dest: "/other-dir"})
3241
- * private uploadFile(@MultipartFile("file1") file: MulterFile, @MultipartFile("file2") file2: MulterFile) {
3242
- *
3243
- * }
3244
- *
3245
- * @Post('/files')
3246
- * private uploadFile(@MultipartFile("file1") files: MulterFile[]) {
3247
- *
3248
- * }
3249
- * }
3250
- * ```
3251
- *
3252
- * > See the tutorial on the [multer configuration](/tutorials/multer.md).
3253
- *
3254
- * @param name
3255
- * @param maxCount
3256
- * @returns Function
3257
- * @decorator
3258
- * @input
3259
- */
3260
-
3261
-
3262
- function MultipartFile(name, maxCount) {
3263
- return (...args) => {
3264
- const [target, propertyKey, index] = args;
3265
- const multiple = Metadata.getParamTypes(target, propertyKey)[index] === Array;
3266
- name = typeof name === "object" ? undefined : name;
3267
- const expression = [name, !multiple && "0"].filter(Boolean).join(".");
3268
- const decorators = useDecorators(useMethodDecorators(Returns(400).Description(`<File too long | Too many parts | Too many files | Field name too long | Field value too long | Too many fields | Unexpected field> [fieldName] Example: File too long file1`), Consumes("multipart/form-data"), StoreMerge(PlatformMulterMiddleware, mapOptions$1(name, maxCount))), UseParam({
3269
- paramType: ParamTypes.FILES,
3270
- dataPath: "$ctx.request.files",
3271
- expression,
3272
- useValidation: true
3273
- }));
3274
- decorators(...args);
3275
- };
3276
- }
3277
-
3278
- /**
3279
- * This method is just like the `router.METHOD()` methods, except that it matches all HTTP methods (verbs).
3280
- *
3281
- * This method is extremely useful for mapping “global” logic for specific path prefixes or arbitrary matches.
3282
- * For example, if you placed the following route at the top of all other route definitions, it would require that
3283
- * all routes from that point on would require authentication, and automatically load a user.
3284
- * Keep in mind that these callbacks do not have to act as end points; loadUser can perform a task, then call next()
3285
- * to continue matching subsequent routes.
3286
- * @param path
3287
- * @param args
3288
- * @returns {Function}
3289
- * @decorator
3290
- * @operation
3291
- * @httpMethod
3292
- */
3293
-
3294
- function All(path = "/", ...args) {
3295
- return Use(...["all", path].concat(args));
3296
- }
3297
- /**
3298
- * This method is just like the `router.METHOD()` methods, except that it matches all HTTP methods (verbs).
3299
- *
3300
- * This method is extremely useful for mapping “global” logic for specific path prefixes or arbitrary matches.
3301
- * For example, if you placed the following route at the top of all other route definitions, it would require that
3302
- * all routes from that point on would require authentication, and automatically load a user.
3303
- * Keep in mind that these callbacks do not have to act as end points; loadUser can perform a task, then call next()
3304
- * to continue matching subsequent routes.
3305
- * @param path
3306
- * @param args
3307
- * @returns {Function}
3308
- * @decorator
3309
- * @operation
3310
- * @httpMethod
3311
- */
3312
-
3313
- function Get(path = "/", ...args) {
3314
- return Use(...["get", path].concat(args));
3315
- }
3316
- /**
3317
- * This method is just like the `router.METHOD()` methods, except that it matches all HTTP methods (verbs).
3318
- *
3319
- * This method is extremely useful for mapping “global” logic for specific path prefixes or arbitrary matches.
3320
- * For example, if you placed the following route at the top of all other route definitions, it would require that
3321
- * all routes from that point on would require authentication, and automatically load a user.
3322
- * Keep in mind that these callbacks do not have to act as end points; loadUser can perform a task, then call next()
3323
- * to continue matching subsequent routes.
3324
- * @param path
3325
- * @param args
3326
- * @returns {Function}
3327
- * @decorator
3328
- * @operation
3329
- * @httpMethod
3330
- */
3331
-
3332
- function Post(path = "/", ...args) {
3333
- return Use(...["post", path].concat(args));
3334
- }
3335
- /**
3336
- * This method is just like the `router.METHOD()` methods, except that it matches all HTTP methods (verbs).
3337
- *
3338
- * This method is extremely useful for mapping “global” logic for specific path prefixes or arbitrary matches.
3339
- * For example, if you placed the following route at the top of all other route definitions, it would require that
3340
- * all routes from that point on would require authentication, and automatically load a user.
3341
- * Keep in mind that these callbacks do not have to act as end points; loadUser can perform a task, then call next()
3342
- * to continue matching subsequent routes.
3343
- * @param path
3344
- * @param args
3345
- * @returns {Function}
3346
- * @decorator
3347
- * @operation
3348
- * @httpMethod
3349
- */
3350
-
3351
- function Put(path = "/", ...args) {
3352
- return Use(...["put", path].concat(args));
3353
- }
3354
- /**
3355
- * This method is just like the `router.METHOD()` methods, except that it matches all HTTP methods (verbs).
3356
- *
3357
- * This method is extremely useful for mapping “global” logic for specific path prefixes or arbitrary matches.
3358
- * For example, if you placed the following route at the top of all other route definitions, it would require that
3359
- * all routes from that point on would require authentication, and automatically load a user.
3360
- * Keep in mind that these callbacks do not have to act as end points; loadUser can perform a task, then call next()
3361
- * to continue matching subsequent routes.
3362
- * @param path
3363
- * @param args
3364
- * @returns {Function}
3365
- * @decorator
3366
- * @operation
3367
- * @httpMethod
3368
- */
3369
-
3370
- function Delete(path = "/", ...args) {
3371
- return Use(...["delete", path].concat(args));
3372
- }
3373
- /**
3374
- * This method is just like the `router.METHOD()` methods, except that it matches all HTTP methods (verbs).
3375
- *
3376
- * This method is extremely useful for mapping “global” logic for specific path prefixes or arbitrary matches.
3377
- * For example, if you placed the following route at the top of all other route definitions, it would require that
3378
- * all routes from that point on would require authentication, and automatically load a user.
3379
- * Keep in mind that these callbacks do not have to act as end points; loadUser can perform a task, then call next()
3380
- * to continue matching subsequent routes.
3381
- * @param path
3382
- * @param args
3383
- * @returns {Function}
3384
- * @decorator
3385
- * @operation
3386
- * @httpMethod
3387
- */
3388
-
3389
- function Head(path = "/", ...args) {
3390
- return Use(...["head", path].concat(args));
3391
- }
3392
- /**
3393
- * This method is just like the `router.METHOD()` methods, except that it matches all HTTP methods (verbs).
3394
- *
3395
- * This method is extremely useful for mapping “global” logic for specific path prefixes or arbitrary matches.
3396
- * For example, if you placed the following route at the top of all other route definitions, it would require that
3397
- * all routes from that point on would require authentication, and automatically load a user.
3398
- * Keep in mind that these callbacks do not have to act as end points; loadUser can perform a task, then call next()
3399
- * to continue matching subsequent routes.
3400
- * @param path
3401
- * @param args
3402
- * @returns {Function}
3403
- * @decorator
3404
- * @operation
3405
- * @httpMethod
3406
- */
3407
-
3408
- function Patch(path = "/", ...args) {
3409
- return Use(...["patch", path].concat(args));
3410
- }
3411
- /**
3412
- * This method is just like the `router.METHOD()` methods, except that it matches all HTTP methods (verbs).
3413
- *
3414
- * This method is extremely useful for mapping “global” logic for specific path prefixes or arbitrary matches.
3415
- * For example, if you placed the following route at the top of all other route definitions, it would require that
3416
- * all routes from that point on would require authentication, and automatically load a user.
3417
- * Keep in mind that these callbacks do not have to act as end points; loadUser can perform a task, then call next()
3418
- * to continue matching subsequent routes.
3419
- * @param path
3420
- * @param args
3421
- * @returns {Function}
3422
- * @decorator
3423
- * @operation
3424
- * @httpMethod
3425
- */
3426
-
3427
- function Options(path = "/", ...args) {
3428
- return Use(...["options", path].concat(args));
3429
- }
3430
-
3431
- /**
3432
- *
3433
- * @param fn
3434
- * @decorator
3435
- */
3436
-
3437
- function EndpointFn(fn) {
3438
- return JsonEntityFn(fn);
3439
- }
3440
-
3441
- /**
3442
- * Set a mime list which are acceptable and checks if the specified content types are acceptable, based on the request’s Accept HTTP header field.
3443
- *
3444
- * ```typescript
3445
- * @Controller('/mypath')
3446
- * export class MyCtrl {
3447
- *
3448
- * @Get('/')
3449
- * @AcceptMime('application/json')
3450
- * public getResource(){}
3451
- * }
3452
- * ```
3453
- *
3454
- * @param mimes
3455
- * @decorator
3456
- * @operation
3457
- * @response
3458
- */
3459
-
3460
- function AcceptMime(...mimes) {
3461
- return useDecorators(Produces(...mimes), EndpointFn(endpoint => {
3462
- endpoint.acceptMimes = mimes;
3463
- }));
3464
- }
3465
-
3466
- const _excluded$1 = ["children"];
3467
-
3468
- function mapOptions(options) {
3469
- if (typeof options === "string" || options instanceof RegExp || isArrayOrArrayClass(options)) {
3470
- return {
3471
- path: options
3472
- };
3473
- }
3474
-
3475
- return options;
3476
- }
3477
- /**
3478
- * Declare a new controller with his Rest path. His methods annotated will be collected to build the routing list.
3479
- * This routing listing will be built with the `express.Router` object.
3480
- *
3481
- * ::: tip
3482
- * See [Controllers](/docs/controllers.md) section for more details
3483
- * :::
3484
- *
3485
- * ```typescript
3486
- * @Controller("/calendars")
3487
- * export provide CalendarCtrl {
3488
- *
3489
- * @Get("/:id")
3490
- * public get(
3491
- * @Req() request: Req,
3492
- * @Res() response: Res,
3493
- * @Next() next: Next
3494
- * ): void {
3495
- *
3496
- * }
3497
- * }
3498
- * ```
3499
- *
3500
- * @param options
3501
- * @controller
3502
- * @decorator
3503
- * @classDecorator
3504
- */
3505
-
3506
-
3507
- function Controller(options) {
3508
- const _mapOptions = mapOptions(options),
3509
- {
3510
- children = []
3511
- } = _mapOptions,
3512
- opts = _objectWithoutPropertiesLoose(_mapOptions, _excluded$1);
3513
-
3514
- return target => {
3515
- registerController(_extends({
3516
- provide: target
3517
- }, opts));
3518
- Store.from(target).set("childrenControllers", children);
3519
- children.forEach(childToken => {
3520
- Store.from(childToken).set("parentController", target);
3521
- });
3522
- };
3523
- }
3524
-
3525
- function getParamType$1(target, propertyKey, parameterIndex) {
3526
- const type = Metadata.getOwnParamTypes(target, propertyKey)[parameterIndex];
3527
-
3528
- if (isClass(type)) {
3529
- if (nameOf(type) === "PlatformResponse") {
3530
- return {
3531
- paramType: ParamTypes.PLATFORM_RESPONSE,
3532
- dataPath: "$ctx.response"
3533
- };
3534
- }
3535
-
3536
- if (type === ServerResponse) {
3537
- return {
3538
- paramType: ParamTypes.NODE_RESPONSE,
3539
- dataPath: "$ctx.response.res"
3540
- };
3541
- }
3542
- }
3543
-
3544
- return {
3545
- paramType: ParamTypes.RESPONSE,
3546
- dataPath: "$ctx.response.response"
3547
- };
3548
- }
3549
-
3550
- function Response() {
3551
- return Res();
3552
- }
3553
- function Res() {
3554
- return (target, propertyKey, parameterIndex) => {
3555
- const {
3556
- paramType,
3557
- dataPath
3558
- } = getParamType$1(target, propertyKey, parameterIndex);
3559
- UseParam({
3560
- paramType,
3561
- dataPath
3562
- })(target, propertyKey, parameterIndex);
3563
- };
3564
- }
3565
-
3566
- function getParamType(target, propertyKey, parameterIndex) {
3567
- const type = Metadata.getOwnParamTypes(target, propertyKey)[parameterIndex];
3568
-
3569
- if (isClass(type)) {
3570
- if (nameOf(type) === "PlatformRequest") {
3571
- return {
3572
- paramType: ParamTypes.PLATFORM_REQUEST,
3573
- dataPath: "$ctx.request"
3574
- };
3575
- }
3576
-
3577
- if (type === IncomingMessage) {
3578
- return {
3579
- paramType: ParamTypes.NODE_REQUEST,
3580
- dataPath: "$ctx.request.req"
3581
- };
3582
- }
3583
- }
3584
-
3585
- return {
3586
- paramType: ParamTypes.REQUEST,
3587
- dataPath: "$ctx.request.request"
3588
- };
3589
- }
3590
-
3591
- function Request(...args) {
3592
- // @ts-ignore
3593
- return Req(...args);
3594
- }
3595
- function Req(...args) {
3596
- const {
3597
- expression,
3598
- useType,
3599
- useConverter = false,
3600
- useValidation = false
3601
- } = mapParamsOptions(args);
3602
- return (target, propertyKey, parameterIndex) => {
3603
- const {
3604
- paramType,
3605
- dataPath
3606
- } = getParamType(target, propertyKey, parameterIndex);
3607
- UseParam({
3608
- paramType,
3609
- dataPath,
3610
- expression,
3611
- useType,
3612
- useConverter,
3613
- useValidation
3614
- })(target, propertyKey, parameterIndex);
3615
- };
3616
- }
3617
-
3618
- /**
3619
- * Get the Next function (for express application and middleware).
3620
- *
3621
- * @decorator
3622
- * @operation
3623
- * @input
3624
- */
3625
-
3626
- function Next() {
3627
- return UseParam({
3628
- paramType: ParamTypes.NEXT_FN,
3629
- dataPath: "next",
3630
- useConverter: false,
3631
- useValidation: false
3632
- });
3633
- }
3634
-
3635
- /**
3636
- * @returns {Function}
3637
- * @decorator
3638
- * @operation
3639
- * @input
3640
- */
3641
-
3642
- function Err() {
3643
- return UseParam({
3644
- paramType: ParamTypes.ERR,
3645
- dataPath: "err",
3646
- useValidation: false,
3647
- useConverter: false
3648
- });
3649
- }
3650
-
3651
- const _excluded = ["use", "collection"];
3652
-
3653
- /**
3654
- * @ignore
3655
- */
3656
- function mapReturnedResponse(_ref) {
3657
- let {
3658
- use,
3659
- collection
3660
- } = _ref,
3661
- options = _objectWithoutPropertiesLoose(_ref, _excluded);
3662
-
3663
- return _extends({}, options, {
3664
- type: options.type || use,
3665
- collectionType: options.collectionType || collection
3666
- });
3667
- }
3668
-
3669
- /**
3670
- * @platform
3671
- */
3672
-
3673
- class PlatformTest extends DITest {
3674
- static async create(options = {}) {
3675
- DITest.injector = PlatformTest.createInjector(options);
3676
- const container = createContainer();
3677
- await DITest.injector.load(container, PlatformModule);
3678
- }
3679
- /**
3680
- * Create a new injector with the right default services
3681
- */
3682
-
3683
-
3684
- static createInjector(settings = {}) {
3685
- return createInjector(DITest.configure(settings));
3686
- }
3687
- /**
3688
- * Load the server silently without listening port and configure it on test profile.
3689
- * @decorator
3690
- * @param mod
3691
- * @param settings
3692
- * @returns {Promise<void>}
3693
- */
3694
-
3695
-
3696
- static bootstrap(mod, settings = {}) {
3697
- return async function before() {
3698
- let instance;
3699
- const platform = settings.platform || PlatformTest.platformBuilder;
3700
- /* istanbul ignore next */
3701
-
3702
- if (!platform) {
3703
- throw new Error("Platform type is not specified. Have you added at least `import @tsed/platform-express` (or equivalent) on your Server.ts ?");
3704
- } // @ts-ignore
3705
-
3706
-
3707
- instance = await PlatformBuilder.build(platform).bootstrap(mod, DITest.configure(settings));
3708
-
3709
- if (!settings.listen) {
3710
- await instance.callHook("$beforeListen");
3711
- await instance.callHook("$afterListen");
3712
- await instance.ready();
3713
- } else {
3714
- await instance.listen();
3715
- } // used by inject method
3716
-
3717
-
3718
- DITest.injector = instance.injector;
3719
- };
3720
- }
3721
- /**
3722
- * It injects services into the test function where you can alter, spy on, and manipulate them.
3723
- *
3724
- * The inject function has two parameters
3725
- *
3726
- * * an array of Service dependency injection tokens,
3727
- * * a test function whose parameters correspond exactly to each item in the injection token array.
3728
- *
3729
- * @param targets
3730
- * @param func
3731
- */
3732
-
3733
-
3734
- static inject(targets, func) {
3735
- return async function () {
3736
- if (!DITest.hasInjector()) {
3737
- await PlatformTest.create();
3738
- }
3739
-
3740
- const injector = DITest.injector;
3741
- const deps = [];
3742
-
3743
- for (const target of targets) {
3744
- deps.push(injector.has(target) ? injector.get(target) : await injector.invoke(target));
3745
- }
3746
-
3747
- return await func(...deps);
3748
- };
3749
- }
3750
- /**
3751
- * Return the raw application (express or koa).
3752
- * Use this callback with SuperTest.
3753
- *
3754
- * ```typescript
3755
- * let request: SuperTest.SuperTest<SuperTest.Test>;
3756
- * beforeEach(PlatformTest.bootstrap(Server, {
3757
- * mount: {
3758
- * "/rest": [ProductsController]
3759
- * }
3760
- * }));
3761
- * beforeEach(() => {
3762
- * request = SuperTest(PlatformTest.callback());
3763
- * });
3764
- * ```
3765
- */
3766
-
3767
-
3768
- static callback() {
3769
- var _DITest$injector$get;
3770
-
3771
- return (_DITest$injector$get = DITest.injector.get(PlatformApplication)) == null ? void 0 : _DITest$injector$get.callback();
3772
- }
3773
-
3774
- static createRequest(options = {}) {
3775
- return _extends({
3776
- headers: {},
3777
-
3778
- get(key) {
3779
- return this.headers[key.toLowerCase()];
3780
- },
3781
-
3782
- accepts(mime) {
3783
- return require("accepts")(this).types([].concat(mime));
3784
- }
3785
-
3786
- }, options);
3787
- }
3788
-
3789
- static createResponse(options = {}) {
3790
- return _extends({
3791
- headers: {},
3792
- locals: {},
3793
- statusCode: 200,
3794
-
3795
- status(code) {
3796
- this.statusCode = code;
3797
- return this;
3798
- },
3799
-
3800
- contentType(content) {
3801
- this.set("content-type", content);
3802
- },
3803
-
3804
- contentLength(content) {
3805
- this.set("content-length", content);
3806
- },
3807
-
3808
- redirect(status, path) {
3809
- this.statusCode = status;
3810
- this.set("location", path);
3811
- },
3812
-
3813
- location(path) {
3814
- this.set("location", path);
3815
- },
3816
-
3817
- get(key) {
3818
- return this.headers[key.toLowerCase()];
3819
- },
3820
-
3821
- getHeaders() {
3822
- return this.headers;
3823
- },
3824
-
3825
- set(key, value) {
3826
- this.headers[key.toLowerCase()] = value;
3827
- return this;
3828
- },
3829
-
3830
- send(data) {
3831
- this.data = data;
3832
- },
3833
-
3834
- json(data) {
3835
- this.data = data;
3836
- }
3837
-
3838
- }, options);
3839
- }
3840
-
3841
- static createRequestContext(options = {}) {
3842
- var _options$request, _options$event, _options$response, _options$event2;
3843
-
3844
- const event = {
3845
- request: (options == null ? void 0 : (_options$request = options.request) == null ? void 0 : _options$request.request) || (options == null ? void 0 : (_options$event = options.event) == null ? void 0 : _options$event.request) || PlatformTest.createRequest(),
3846
- response: (options == null ? void 0 : (_options$response = options.response) == null ? void 0 : _options$response.response) || (options == null ? void 0 : (_options$event2 = options.event) == null ? void 0 : _options$event2.response) || PlatformTest.createResponse()
3847
- };
3848
- const ctx = new PlatformContext(_extends({
3849
- id: "id",
3850
- injector: DITest.injector,
3851
- logger: DITest.injector.logger,
3852
- url: "/"
3853
- }, options, {
3854
- event
3855
- }));
3856
- ctx.response.platformViews = PlatformTest.get(PlatformViews);
3857
- return ctx;
3858
- }
3859
-
3860
- }
3861
-
3862
- GlobalProviders.createRegistry(ProviderType.CONTROLLER, ControllerProvider, {
3863
- onInvoke(provider, locals) {
3864
- locals.set(PlatformRouter, provider.getRouter());
3865
- }
3866
-
3867
- });
3868
-
3869
- export { AcceptMime, All, AnyToPromiseWithCtx, Controller, ControllerProvider, ConverterService, Delete, EndpointFn, EndpointMetadata, Err, Get, HandlerMetadata, HandlerType, Head, HttpServer, HttpsServer, MulterFileSize, MulterOptions, MultipartFile, Next, Options, PLATFORM_ROUTER_OPTIONS, Patch, Platform, PlatformAcceptMimesMiddleware, PlatformApplication, PlatformBuilder, PlatformConfiguration, PlatformContext, PlatformControllerBuilder, PlatformHandler, PlatformLogMiddleware, PlatformModule, PlatformMulterMiddleware, PlatformRequest, PlatformResponse, PlatformRouteDetails, PlatformRouter, PlatformTest, Post, Put, ROUTER_OPTIONS, Req, Request, Res, Response, bindEndpointMiddleware, createContext, createHttpServer, createHttpsServer, createInjector, createPlatformApplication, listenHttpServer, listenHttpsServer, listenServer, mapReturnedResponse, printRoutes, useCtxHandler };
3870
- //# sourceMappingURL=index.modern.js.map