jimpex 8.0.0 → 10.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (215) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +2 -2
  3. package/dist/app/index.d.mts +14 -0
  4. package/dist/app/index.d.ts +5 -4
  5. package/dist/app/index.js +4 -0
  6. package/dist/app/jimpex.d.mts +14 -0
  7. package/dist/app/jimpex.d.ts +3 -2
  8. package/dist/app/jimpex.js +238 -2
  9. package/dist/app/jimpex.js.map +1 -1
  10. package/dist/controllers/common/config.d.mts +79 -0
  11. package/dist/controllers/common/config.d.ts +4 -3
  12. package/dist/controllers/common/config.js +18 -0
  13. package/dist/controllers/common/config.js.map +1 -1
  14. package/dist/controllers/common/health.d.mts +83 -0
  15. package/dist/controllers/common/health.d.ts +5 -4
  16. package/dist/controllers/common/health.js +18 -0
  17. package/dist/controllers/common/health.js.map +1 -1
  18. package/dist/controllers/common/index.d.mts +22 -0
  19. package/dist/controllers/common/index.d.ts +5 -4
  20. package/dist/controllers/common/index.js +6 -0
  21. package/dist/controllers/common/statics.d.mts +223 -0
  22. package/dist/controllers/common/statics.d.ts +13 -5
  23. package/dist/controllers/common/statics.js +60 -3
  24. package/dist/controllers/common/statics.js.map +1 -1
  25. package/dist/controllers/index.d.mts +25 -0
  26. package/dist/controllers/index.d.ts +5 -4
  27. package/dist/controllers/index.js +5 -0
  28. package/dist/controllers/utils/gateway.d.mts +725 -0
  29. package/dist/controllers/utils/gateway.d.ts +5 -4
  30. package/dist/controllers/utils/gateway.js +155 -0
  31. package/dist/controllers/utils/gateway.js.map +1 -1
  32. package/dist/controllers/utils/index.d.mts +17 -0
  33. package/dist/controllers/utils/index.d.ts +4 -3
  34. package/dist/controllers/utils/index.js +4 -0
  35. package/dist/esm/app/jimpex.js +235 -3
  36. package/dist/esm/app/jimpex.js.map +1 -1
  37. package/dist/esm/{chunk-T2T6Q22Z.js → chunk-F3FYYIAV.js} +1 -1
  38. package/dist/esm/controllers/common/config.js +19 -1
  39. package/dist/esm/controllers/common/config.js.map +1 -1
  40. package/dist/esm/controllers/common/health.js +19 -1
  41. package/dist/esm/controllers/common/health.js.map +1 -1
  42. package/dist/esm/controllers/common/statics.js +57 -4
  43. package/dist/esm/controllers/common/statics.js.map +1 -1
  44. package/dist/esm/controllers/utils/gateway.js +156 -1
  45. package/dist/esm/controllers/utils/gateway.js.map +1 -1
  46. package/dist/esm/middlewares/common/errorHandler.js +25 -1
  47. package/dist/esm/middlewares/common/errorHandler.js.map +1 -1
  48. package/dist/esm/middlewares/common/forceHTTPS.js +13 -1
  49. package/dist/esm/middlewares/common/forceHTTPS.js.map +1 -1
  50. package/dist/esm/middlewares/common/hsts.js +22 -1
  51. package/dist/esm/middlewares/common/hsts.js.map +1 -1
  52. package/dist/esm/middlewares/html/fastHTML.js +55 -1
  53. package/dist/esm/middlewares/html/fastHTML.js.map +1 -1
  54. package/dist/esm/middlewares/html/showHTML.js +33 -1
  55. package/dist/esm/middlewares/html/showHTML.js.map +1 -1
  56. package/dist/esm/middlewares/utils/versionValidator.js +35 -1
  57. package/dist/esm/middlewares/utils/versionValidator.js.map +1 -1
  58. package/dist/esm/services/common/appError.js +48 -2
  59. package/dist/esm/services/common/appError.js.map +1 -1
  60. package/dist/esm/services/common/httpError.js +10 -1
  61. package/dist/esm/services/common/httpError.js.map +1 -1
  62. package/dist/esm/services/common/index.js +1 -1
  63. package/dist/esm/services/common/sendFile.js +1 -1
  64. package/dist/esm/services/frontend/frontendFs.js +29 -1
  65. package/dist/esm/services/frontend/frontendFs.js.map +1 -1
  66. package/dist/esm/services/frontend/index.js +1 -1
  67. package/dist/esm/services/html/htmlGenerator.js +51 -1
  68. package/dist/esm/services/html/htmlGenerator.js.map +1 -1
  69. package/dist/esm/services/html/index.js +1 -1
  70. package/dist/esm/services/http/apiClient.js +27 -1
  71. package/dist/esm/services/http/apiClient.js.map +1 -1
  72. package/dist/esm/services/http/http.js +60 -5
  73. package/dist/esm/services/http/http.js.map +1 -1
  74. package/dist/esm/services/http/index.js +1 -1
  75. package/dist/esm/services/http/responsesBuilder.js +49 -2
  76. package/dist/esm/services/http/responsesBuilder.js.map +1 -1
  77. package/dist/esm/services/utils/ensureBearerToken.js +17 -1
  78. package/dist/esm/services/utils/ensureBearerToken.js.map +1 -1
  79. package/dist/esm/services/utils/index.js +1 -1
  80. package/dist/esm/utils/fns/others.js +1 -1
  81. package/dist/esm/utils/fns/routes.js +1 -1
  82. package/dist/esm/utils/fns/routes.js.map +1 -1
  83. package/dist/esm/utils/fns/statuses.js +1 -1
  84. package/dist/esm/utils/fns/text.js +1 -1
  85. package/dist/esm/utils/wrappers.js +1 -1
  86. package/dist/index-Bwf7JHu9.d.mts +1287 -0
  87. package/dist/{jimpex-7eaee271.d.ts → index-C6I3NCC-.d.ts} +15 -6
  88. package/dist/index.d.mts +47 -0
  89. package/dist/index.d.ts +3 -2
  90. package/dist/index.js +9 -0
  91. package/dist/middlewares/common/errorHandler.d.mts +132 -0
  92. package/dist/middlewares/common/errorHandler.d.ts +5 -4
  93. package/dist/middlewares/common/errorHandler.js +24 -0
  94. package/dist/middlewares/common/errorHandler.js.map +1 -1
  95. package/dist/middlewares/common/forceHTTPS.d.mts +69 -0
  96. package/dist/middlewares/common/forceHTTPS.d.ts +6 -5
  97. package/dist/middlewares/common/forceHTTPS.js +12 -0
  98. package/dist/middlewares/common/forceHTTPS.js.map +1 -1
  99. package/dist/middlewares/common/hsts.d.mts +110 -0
  100. package/dist/middlewares/common/hsts.d.ts +6 -5
  101. package/dist/middlewares/common/hsts.js +21 -0
  102. package/dist/middlewares/common/hsts.js.map +1 -1
  103. package/dist/middlewares/common/index.d.mts +22 -0
  104. package/dist/middlewares/common/index.d.ts +4 -3
  105. package/dist/middlewares/common/index.js +6 -0
  106. package/dist/middlewares/html/fastHTML.d.mts +180 -0
  107. package/dist/middlewares/html/fastHTML.d.ts +5 -5
  108. package/dist/middlewares/html/fastHTML.js +54 -0
  109. package/dist/middlewares/html/fastHTML.js.map +1 -1
  110. package/dist/middlewares/html/index.d.mts +21 -0
  111. package/dist/middlewares/html/index.d.ts +4 -4
  112. package/dist/middlewares/html/index.js +5 -0
  113. package/dist/middlewares/html/showHTML.d.mts +127 -0
  114. package/dist/middlewares/html/showHTML.d.ts +5 -5
  115. package/dist/middlewares/html/showHTML.js +32 -0
  116. package/dist/middlewares/html/showHTML.js.map +1 -1
  117. package/dist/middlewares/index.d.mts +30 -0
  118. package/dist/middlewares/index.d.ts +4 -4
  119. package/dist/middlewares/index.js +6 -0
  120. package/dist/middlewares/utils/index.d.mts +20 -0
  121. package/dist/middlewares/utils/index.d.ts +4 -3
  122. package/dist/middlewares/utils/index.js +4 -0
  123. package/dist/middlewares/utils/versionValidator.d.mts +215 -0
  124. package/dist/middlewares/utils/versionValidator.d.ts +5 -4
  125. package/dist/middlewares/utils/versionValidator.js +34 -0
  126. package/dist/middlewares/utils/versionValidator.js.map +1 -1
  127. package/dist/services/common/appError.d.mts +139 -0
  128. package/dist/services/common/appError.d.ts +5 -4
  129. package/dist/services/common/appError.js +47 -1
  130. package/dist/services/common/appError.js.map +1 -1
  131. package/dist/services/common/httpError.d.mts +80 -0
  132. package/dist/services/common/httpError.d.ts +5 -4
  133. package/dist/services/common/httpError.js +9 -0
  134. package/dist/services/common/httpError.js.map +1 -1
  135. package/dist/services/common/index.d.mts +47 -0
  136. package/dist/services/common/index.d.ts +4 -4
  137. package/dist/services/common/index.js +4 -1
  138. package/dist/services/common/sendFile.d.mts +102 -0
  139. package/dist/services/common/sendFile.d.ts +4 -4
  140. package/dist/services/frontend/frontendFs.d.mts +96 -0
  141. package/dist/services/frontend/frontendFs.d.ts +4 -4
  142. package/dist/services/frontend/frontendFs.js +32 -0
  143. package/dist/services/frontend/frontendFs.js.map +1 -1
  144. package/dist/services/frontend/index.d.mts +40 -0
  145. package/dist/services/frontend/index.d.ts +4 -4
  146. package/dist/services/frontend/index.js +2 -1
  147. package/dist/services/html/htmlGenerator.d.mts +237 -0
  148. package/dist/services/html/htmlGenerator.d.ts +3 -3
  149. package/dist/services/html/htmlGenerator.js +50 -0
  150. package/dist/services/html/htmlGenerator.js.map +1 -1
  151. package/dist/services/html/index.d.mts +43 -0
  152. package/dist/services/html/index.d.ts +4 -4
  153. package/dist/services/html/index.js +2 -1
  154. package/dist/services/http/apiClient.d.mts +170 -0
  155. package/dist/services/http/apiClient.d.ts +5 -4
  156. package/dist/services/http/apiClient.js +26 -0
  157. package/dist/services/http/apiClient.js.map +1 -1
  158. package/dist/services/http/http.d.mts +182 -0
  159. package/dist/services/http/http.d.ts +15 -8
  160. package/dist/services/http/http.js +63 -4
  161. package/dist/services/http/http.js.map +1 -1
  162. package/dist/services/http/index.d.mts +51 -0
  163. package/dist/services/http/index.d.ts +4 -3
  164. package/dist/services/http/index.js +4 -1
  165. package/dist/services/http/responsesBuilder.d.mts +179 -0
  166. package/dist/services/http/responsesBuilder.d.ts +4 -3
  167. package/dist/services/http/responsesBuilder.js +48 -1
  168. package/dist/services/http/responsesBuilder.js.map +1 -1
  169. package/dist/services/index.d.mts +33 -0
  170. package/dist/services/index.d.ts +4 -4
  171. package/dist/services/index.js +8 -0
  172. package/dist/services/utils/ensureBearerToken.d.mts +158 -0
  173. package/dist/services/utils/ensureBearerToken.d.ts +6 -5
  174. package/dist/services/utils/ensureBearerToken.js +16 -0
  175. package/dist/services/utils/ensureBearerToken.js.map +1 -1
  176. package/dist/services/utils/index.d.mts +44 -0
  177. package/dist/services/utils/index.d.ts +4 -3
  178. package/dist/services/utils/index.js +2 -1
  179. package/dist/types/events.d.mts +14 -0
  180. package/dist/types/events.d.ts +5 -4
  181. package/dist/types/express.d.mts +10 -0
  182. package/dist/types/express.d.ts +1 -1
  183. package/dist/types/http.d.mts +82 -0
  184. package/dist/types/http.d.ts +5 -2
  185. package/dist/types/http.js.map +1 -1
  186. package/dist/types/index.d.mts +14 -0
  187. package/dist/types/index.d.ts +2 -2
  188. package/dist/types/index.js +9 -0
  189. package/dist/types/options.d.mts +14 -0
  190. package/dist/types/options.d.ts +4 -3
  191. package/dist/types/utils.d.mts +48 -0
  192. package/dist/types/utils.d.ts +1 -1
  193. package/dist/types/wootils.d.mts +4 -0
  194. package/dist/utils/fns/index.d.mts +5 -0
  195. package/dist/utils/fns/index.js +7 -0
  196. package/dist/utils/fns/others.d.mts +17 -0
  197. package/dist/utils/fns/routes.d.mts +39 -0
  198. package/dist/utils/fns/routes.js.map +1 -1
  199. package/dist/utils/fns/statuses.d.mts +45 -0
  200. package/dist/utils/fns/statuses.d.ts +1 -1
  201. package/dist/utils/fns/statuses.js +4 -0
  202. package/dist/utils/fns/statuses.js.map +1 -1
  203. package/dist/utils/fns/text.d.mts +9 -0
  204. package/dist/utils/index.d.mts +19 -0
  205. package/dist/utils/index.d.ts +5 -4
  206. package/dist/utils/index.js +5 -0
  207. package/dist/utils/wrappers.d.mts +14 -0
  208. package/dist/utils/wrappers.d.ts +4 -3
  209. package/package.json +50 -49
  210. package/src/app/jimpex.ts +15 -2
  211. package/src/controllers/common/statics.ts +13 -2
  212. package/src/controllers/utils/gateway.ts +4 -0
  213. package/src/services/http/http.ts +13 -4
  214. package/src/types/http.ts +3 -0
  215. /package/dist/esm/{chunk-T2T6Q22Z.js.map → chunk-F3FYYIAV.js.map} +0 -0
@@ -1,18 +1,36 @@
1
1
  import {
2
2
  __publicField
3
- } from "../../chunk-T2T6Q22Z.js";
3
+ } from "../../chunk-F3FYYIAV.js";
4
4
  import { controller } from "../../utils";
5
5
  class HealthController {
6
+ /**
7
+ * @param options The options to construct the controller.
8
+ */
6
9
  constructor({ inject }) {
10
+ /**
11
+ * The function that returns the health status of the application.
12
+ */
7
13
  __publicField(this, "_getHealthStatus");
14
+ /**
15
+ * The service in charge or building the responses.
16
+ */
8
17
  __publicField(this, "_responsesBuilder");
18
+ /**
19
+ * The service in charge of the configuration.
20
+ */
9
21
  __publicField(this, "_config");
22
+ /**
23
+ * The uility service to get HTTP status codes.
24
+ */
10
25
  __publicField(this, "_statuses");
11
26
  this._getHealthStatus = inject.getHealthStatus;
12
27
  this._responsesBuilder = inject.responsesBuilder;
13
28
  this._config = inject.config;
14
29
  this._statuses = inject.statuses;
15
30
  }
31
+ /**
32
+ * Creates the middleware the shows the application health status.
33
+ */
16
34
  showHealth() {
17
35
  return async (_, res) => {
18
36
  const healthStatus = await this._getHealthStatus();
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/controllers/common/health.ts"],"sourcesContent":["import { controller, type Statuses } from '../../utils';\nimport type { ResponsesBuilder } from '../../services';\nimport type { JimpexHealthStatus, Config, AsyncExpressMiddleware } from '../../types';\n/**\n * A function that will return the health status of the application.\n *\n * @group Controllers/Health\n */\nexport type GetHealthStatus = () => Promise<JimpexHealthStatus>;\n/**\n * The options to contruct a {@link HealthController}.\n *\n * @group Controllers/Health\n */\nexport type HealthControllerOptions = {\n /**\n * A dictionary with the dependencies to inject.\n */\n inject: {\n getHealthStatus: GetHealthStatus;\n responsesBuilder: ResponsesBuilder;\n config: Config;\n statuses: Statuses;\n };\n};\n/**\n * The controller class that shows the application health status.\n *\n * @group Controller Classes\n * @group Controllers/Health\n * @prettierignore\n */\nexport class HealthController {\n /**\n * The function that returns the health status of the application.\n */\n protected readonly _getHealthStatus: GetHealthStatus;\n /**\n * The service in charge or building the responses.\n */\n protected readonly _responsesBuilder: ResponsesBuilder;\n /**\n * The service in charge of the configuration.\n */\n protected readonly _config: Config;\n /**\n * The uility service to get HTTP status codes.\n */\n protected readonly _statuses: Statuses;\n /**\n * @param options The options to construct the controller.\n */\n constructor({ inject }: HealthControllerOptions) {\n this._getHealthStatus = inject.getHealthStatus;\n this._responsesBuilder = inject.responsesBuilder;\n this._config = inject.config;\n this._statuses = inject.statuses;\n }\n /**\n * Creates the middleware the shows the application health status.\n */\n showHealth(): AsyncExpressMiddleware {\n return async (_, res) => {\n const healthStatus = await this._getHealthStatus();\n let isHealthy: boolean;\n let extras: Record<string, unknown>;\n if (typeof healthStatus === 'boolean') {\n isHealthy = healthStatus;\n extras = {};\n } else {\n if (typeof healthStatus.isHealthy === 'boolean') {\n isHealthy = healthStatus.isHealthy;\n } else if (healthStatus.services) {\n isHealthy = Object.values(healthStatus.services).every(\n (value) => value === true,\n );\n } else {\n isHealthy = true;\n }\n\n extras = {\n ...healthStatus.services,\n };\n }\n\n const { name: config, version } = this._config.get<{\n name: string;\n version: string;\n }>(['name', 'version']);\n\n const status = isHealthy\n ? this._statuses('ok')\n : this._statuses('service unavailable');\n\n this._responsesBuilder.json({\n res,\n status,\n data: {\n isHealthy,\n status,\n config,\n version,\n ...extras,\n },\n });\n };\n }\n}\n/**\n * The controller that once mounted, it will add an endpoint to show the application\n * health status.\n *\n * @group Controllers\n * @group Controllers/Health\n */\nexport const healthController = controller((app) => {\n const router = app.getRouter();\n const ctrl = new HealthController({\n inject: {\n getHealthStatus: app.isHealthy.bind(app),\n responsesBuilder: app.get('responsesBuilder'),\n config: app.get('config'),\n statuses: app.get('statuses'),\n },\n });\n\n return router.get('/', ctrl.showHealth());\n});\n"],"mappings":";;;AAAA,SAAS,kBAAiC;AAgCnC,MAAM,iBAAiB;AAAA,EAoB5B,YAAY,EAAE,OAAO,GAA4B;AAhBjD,wBAAmB;AAInB,wBAAmB;AAInB,wBAAmB;AAInB,wBAAmB;AAKjB,SAAK,mBAAmB,OAAO;AAC/B,SAAK,oBAAoB,OAAO;AAChC,SAAK,UAAU,OAAO;AACtB,SAAK,YAAY,OAAO;AAAA,EAC1B;AAAA,EAIA,aAAqC;AACnC,WAAO,OAAO,GAAG,QAAQ;AACvB,YAAM,eAAe,MAAM,KAAK,iBAAiB;AACjD,UAAI;AACJ,UAAI;AACJ,UAAI,OAAO,iBAAiB,WAAW;AACrC,oBAAY;AACZ,iBAAS,CAAC;AAAA,MACZ,OAAO;AACL,YAAI,OAAO,aAAa,cAAc,WAAW;AAC/C,sBAAY,aAAa;AAAA,QAC3B,WAAW,aAAa,UAAU;AAChC,sBAAY,OAAO,OAAO,aAAa,QAAQ,EAAE;AAAA,YAC/C,CAAC,UAAU,UAAU;AAAA,UACvB;AAAA,QACF,OAAO;AACL,sBAAY;AAAA,QACd;AAEA,iBAAS;AAAA,UACP,GAAG,aAAa;AAAA,QAClB;AAAA,MACF;AAEA,YAAM,EAAE,MAAM,QAAQ,QAAQ,IAAI,KAAK,QAAQ,IAG5C,CAAC,QAAQ,SAAS,CAAC;AAEtB,YAAM,SAAS,YACX,KAAK,UAAU,IAAI,IACnB,KAAK,UAAU,qBAAqB;AAExC,WAAK,kBAAkB,KAAK;AAAA,QAC1B;AAAA,QACA;AAAA,QACA,MAAM;AAAA,UACJ;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA,GAAG;AAAA,QACL;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AACF;AAQO,MAAM,mBAAmB,WAAW,CAAC,QAAQ;AAClD,QAAM,SAAS,IAAI,UAAU;AAC7B,QAAM,OAAO,IAAI,iBAAiB;AAAA,IAChC,QAAQ;AAAA,MACN,iBAAiB,IAAI,UAAU,KAAK,GAAG;AAAA,MACvC,kBAAkB,IAAI,IAAI,kBAAkB;AAAA,MAC5C,QAAQ,IAAI,IAAI,QAAQ;AAAA,MACxB,UAAU,IAAI,IAAI,UAAU;AAAA,IAC9B;AAAA,EACF,CAAC;AAED,SAAO,OAAO,IAAI,KAAK,KAAK,WAAW,CAAC;AAC1C,CAAC;","names":[]}
1
+ {"version":3,"sources":["../../../../src/controllers/common/health.ts"],"sourcesContent":["import { controller, type Statuses } from '../../utils';\nimport type { ResponsesBuilder } from '../../services';\nimport type { JimpexHealthStatus, Config, AsyncExpressMiddleware } from '../../types';\n/**\n * A function that will return the health status of the application.\n *\n * @group Controllers/Health\n */\nexport type GetHealthStatus = () => Promise<JimpexHealthStatus>;\n/**\n * The options to contruct a {@link HealthController}.\n *\n * @group Controllers/Health\n */\nexport type HealthControllerOptions = {\n /**\n * A dictionary with the dependencies to inject.\n */\n inject: {\n getHealthStatus: GetHealthStatus;\n responsesBuilder: ResponsesBuilder;\n config: Config;\n statuses: Statuses;\n };\n};\n/**\n * The controller class that shows the application health status.\n *\n * @group Controller Classes\n * @group Controllers/Health\n * @prettierignore\n */\nexport class HealthController {\n /**\n * The function that returns the health status of the application.\n */\n protected readonly _getHealthStatus: GetHealthStatus;\n /**\n * The service in charge or building the responses.\n */\n protected readonly _responsesBuilder: ResponsesBuilder;\n /**\n * The service in charge of the configuration.\n */\n protected readonly _config: Config;\n /**\n * The uility service to get HTTP status codes.\n */\n protected readonly _statuses: Statuses;\n /**\n * @param options The options to construct the controller.\n */\n constructor({ inject }: HealthControllerOptions) {\n this._getHealthStatus = inject.getHealthStatus;\n this._responsesBuilder = inject.responsesBuilder;\n this._config = inject.config;\n this._statuses = inject.statuses;\n }\n /**\n * Creates the middleware the shows the application health status.\n */\n showHealth(): AsyncExpressMiddleware {\n return async (_, res) => {\n const healthStatus = await this._getHealthStatus();\n let isHealthy: boolean;\n let extras: Record<string, unknown>;\n if (typeof healthStatus === 'boolean') {\n isHealthy = healthStatus;\n extras = {};\n } else {\n if (typeof healthStatus.isHealthy === 'boolean') {\n isHealthy = healthStatus.isHealthy;\n } else if (healthStatus.services) {\n isHealthy = Object.values(healthStatus.services).every(\n (value) => value === true,\n );\n } else {\n isHealthy = true;\n }\n\n extras = {\n ...healthStatus.services,\n };\n }\n\n const { name: config, version } = this._config.get<{\n name: string;\n version: string;\n }>(['name', 'version']);\n\n const status = isHealthy\n ? this._statuses('ok')\n : this._statuses('service unavailable');\n\n this._responsesBuilder.json({\n res,\n status,\n data: {\n isHealthy,\n status,\n config,\n version,\n ...extras,\n },\n });\n };\n }\n}\n/**\n * The controller that once mounted, it will add an endpoint to show the application\n * health status.\n *\n * @group Controllers\n * @group Controllers/Health\n */\nexport const healthController = controller((app) => {\n const router = app.getRouter();\n const ctrl = new HealthController({\n inject: {\n getHealthStatus: app.isHealthy.bind(app),\n responsesBuilder: app.get('responsesBuilder'),\n config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AAA,IACH;AAAA,EACF;AACF;AAQO,MAAM,mBAAmB,WAAW,CAAC,QAAQ;AAClD,QAAM,SAAS,IAAI,UAAU;AAC7B,QAAM,OAAO,IAAI,iBAAiB;AAAA,IAChC,QAAQ;AAAA,MACN,iBAAiB,IAAI,UAAU,KAAK,GAAG;AAAA,MACvC,kBAAkB,IAAI,IAAI,kBAAkB;AAAA,MAC5C,QAAQ,IAAI,IAAI,QAAQ;AAAA,MACxB,UAAU,IAAI,IAAI,UAAU;AAAA,IAC9B;AAAA,EACF,CAAC;AAED,SAAO,OAAO,IAAI,KAAK,KAAK,WAAW,CAAC;AAC1C,CAAC;","names":[]}
@@ -1,8 +1,7 @@
1
1
  import {
2
2
  __publicField
3
- } from "../../chunk-T2T6Q22Z.js";
3
+ } from "../../chunk-F3FYYIAV.js";
4
4
  import * as path from "path";
5
- import * as mime from "mime";
6
5
  import { deepAssignWithOverwrite } from "@homer0/deep-assign";
7
6
  import {
8
7
  controllerCreator,
@@ -10,11 +9,30 @@ import {
10
9
  notUndefined
11
10
  } from "../../utils";
12
11
  class StaticsController {
12
+ /**
13
+ * @param options The options to construct the controller.
14
+ */
13
15
  constructor({ inject, ...options }) {
16
+ /**
17
+ * The service that serves static files.
18
+ */
14
19
  __publicField(this, "_sendFile");
20
+ /**
21
+ * The MIME type library. Since it's an ESM only module, Jimpex loads it on boot and makes
22
+ * it available on the container.
23
+ */
24
+ __publicField(this, "_mime");
25
+ /**
26
+ * The controller customization options.
27
+ */
15
28
  __publicField(this, "_options");
29
+ /**
30
+ * A dictionary with the formatted definitions of the files that will be served.
31
+ * It uses the files' routes as keys, for easy access in the middleware.
32
+ */
16
33
  __publicField(this, "files");
17
34
  this._sendFile = inject.sendFile;
35
+ this._mime = inject.mime;
18
36
  this._options = this._validateOptions(
19
37
  deepAssignWithOverwrite(
20
38
  {
@@ -33,6 +51,13 @@ class StaticsController {
33
51
  );
34
52
  this.files = this._createFiles();
35
53
  }
54
+ /**
55
+ * Mounts the middlewares in the router in order to serve the files.
56
+ *
57
+ * @param router A reference to the application router.
58
+ * @param middlewares A list of extra middlewares to execute before the file
59
+ * middleware.
60
+ */
36
61
  addRoutes(router, middlewares = []) {
37
62
  const { methods } = this._options;
38
63
  const use = methods.all ? ["all"] : Object.keys(methods).reduce((acc, name) => {
@@ -51,14 +76,22 @@ class StaticsController {
51
76
  });
52
77
  return router;
53
78
  }
79
+ /**
80
+ * The controller options.
81
+ */
54
82
  get options() {
55
83
  return { ...this._options };
56
84
  }
85
+ /**
86
+ * Generates the middleware that will serve the file.
87
+ *
88
+ * @param file The definition of the file to serve.
89
+ */
57
90
  _getMiddleware(file) {
58
91
  return (_, res, next) => {
59
92
  const extension = path.parse(file.path).ext.substring(1);
60
93
  const headers = {
61
- "Content-Type": mime.getType(extension) || "text/html",
94
+ "Content-Type": this._mime.getType(extension) || "text/html",
62
95
  ...file.headers
63
96
  };
64
97
  Object.entries(headers).forEach(([key, value]) => {
@@ -71,6 +104,11 @@ class StaticsController {
71
104
  });
72
105
  };
73
106
  }
107
+ /**
108
+ * Mounts the middleware(s) for a file in the router.
109
+ *
110
+ * @param options The information of the file and how it needs to be added.
111
+ */
74
112
  _addRoute({
75
113
  router,
76
114
  method,
@@ -81,6 +119,16 @@ class StaticsController {
81
119
  const { route } = file;
82
120
  router[method](route, [...middlewares, fileMiddleware]);
83
121
  }
122
+ /**
123
+ * Validates and formats the options sent to the constructor in order to get the final
124
+ * set that will be stored in the controller.
125
+ *
126
+ * @param options The options to validate.
127
+ * @throws If no files are specified.
128
+ * @throws If methods is not defined.
129
+ * @throws If no methods are enabled.
130
+ * @throws If there's an invalid HTTP method.
131
+ */
84
132
  _validateOptions(options) {
85
133
  if (!options.files || !options.files.length) {
86
134
  throw new Error("You need to specify a list of files");
@@ -120,6 +168,10 @@ class StaticsController {
120
168
  methods: newMethods
121
169
  };
122
170
  }
171
+ /**
172
+ * Parses the files received from the constructor's options, and formats them into
173
+ * proper definitions the controller can use.
174
+ */
123
175
  _createFiles() {
124
176
  const { files, paths } = this._options;
125
177
  const routePath = removeSlashes(paths.route, false, true);
@@ -150,7 +202,8 @@ const staticsController = controllerCreator(
150
202
  const router = app.getRouter();
151
203
  const ctrl = new StaticsController({
152
204
  inject: {
153
- sendFile: app.get("sendFile")
205
+ sendFile: app.get("sendFile"),
206
+ mime: app.get("mime")
154
207
  },
155
208
  ...options
156
209
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/controllers/common/statics.ts"],"sourcesContent":["import * as path from 'path';\nimport * as mime from 'mime';\nimport { deepAssignWithOverwrite } from '@homer0/deep-assign';\nimport {\n controllerCreator,\n removeSlashes,\n notUndefined,\n type MiddlewareLike,\n} from '../../utils';\nimport type { SendFile } from '../../services';\nimport type { Jimpex } from '../../app';\nimport type { DeepPartial, ExpressMiddleware, Router, RouterMethod } from '../../types';\n/**\n * The definition for each file the controller handles.\n *\n * @group Controllers/Statics\n */\nexport type StaticsControllerFile = {\n /**\n * The route, relative to the controller root, to the file.\n */\n route: string;\n /**\n * The path to the file in the filesystem. Since the file is served using the\n * {@link SendFile} service, whether the file is relative to the project root or the\n * application executable depends on how the service is configured (relative to the\n * executable by default).\n */\n path: string;\n /**\n * A dictionary of headers for the response.\n */\n headers?: Record<string, string>;\n};\n/**\n * These are like \"master paths\" that get prepended to all the file paths and routes the\n * controller use.\n *\n * @group Controllers/Statics\n */\nexport type StaticsControllerPathsOptions = {\n /**\n * A custom route to prefix all the file routes with.\n */\n route: string;\n /**\n * A custom path to prefix all the file paths with.\n */\n source: string;\n};\n/**\n * The options to customize the controller.\n *\n * @group Controllers/Statics\n */\nexport type StaticsControllerOptions = {\n /**\n * A list of filenames, or definitions for the files to handle.\n */\n files: Array<string | StaticsControllerFile>;\n /**\n * A dictionary with the allowed router (HTTP) methods the controller can use to serve\n * the files. If `all` is set to `true`, the rest of the values will be ignored.\n *\n * @default {get: true, all: false}\n */\n methods: Partial<Record<RouterMethod, boolean>>;\n /**\n * The \"master paths\" the controller can use to prefix the file paths and routes.\n *\n * @default {route: '', source: './',}\n */\n paths: StaticsControllerPathsOptions;\n};\n/**\n * The options to construct a {@link StaticsController}.\n *\n * @group Controllers/Statics\n */\nexport type StaticsControllerConstructorOptions =\n DeepPartial<StaticsControllerOptions> & {\n /**\n * A dictionary with the dependencies to inject.\n */\n inject: {\n sendFile: SendFile;\n };\n };\n/**\n * A function to generate a list of middlewares that can be executed before the tontroller\n * main middleware.\n *\n * @group Controllers/Statics\n */\nexport type StaticsControllerGetMiddlewaresFn = (app: Jimpex) => MiddlewareLike[];\n/**\n * The options for the controller creator that mounts {@link StaticsController}.\n *\n * @group Controllers/Statics\n */\nexport type StaticsControllerCreatorOptions = DeepPartial<StaticsControllerOptions> & {\n /**\n * A function to generate a list of middlewares that can be executed before the\n * tontroller main middleware.\n */\n getMiddlewares?: StaticsControllerGetMiddlewaresFn;\n};\n/**\n * The options for {@link StaticsController._addRoute}.\n *\n * @access protected\n * @group Controllers/Statics\n */\nexport type AddStaticRouteOptions = {\n /**\n * The reference for the router in which the middlewares will be added.\n */\n router: Router;\n /**\n * The router method in which the middlewares will be added.\n */\n method: RouterMethod;\n /**\n * The definition of the file to serve.\n */\n file: StaticsControllerFile;\n /**\n * The middleware created by {@link StaticsController}, that will serve the file.\n */\n fileMiddleware: ExpressMiddleware;\n /**\n * A list of extra middlewares to execute before the file middleware.\n */\n middlewares: ExpressMiddleware[];\n};\n\n/**\n * The controller class that allows the application to serve specific files from any\n * folder to any route without the need of mounting directories as \"static\".\n *\n * @group Controller Classes\n * @group Controllers/Statics\n * @prettierignore\n */\nexport class StaticsController {\n /**\n * The service that serves static files.\n */\n protected readonly _sendFile: SendFile;\n /**\n * The controller customization options.\n */\n protected _options: StaticsControllerOptions;\n /**\n * A dictionary with the formatted definitions of the files that will be served.\n * It uses the files' routes as keys, for easy access in the middleware.\n */\n protected files: Record<string, StaticsControllerFile>;\n /**\n * @param options The options to construct the controller.\n */\n constructor({ inject, ...options }: StaticsControllerConstructorOptions) {\n this._sendFile = inject.sendFile;\n this._options = this._validateOptions(\n deepAssignWithOverwrite(\n {\n files: ['favicon.ico', 'index.html'],\n methods: options.methods || {\n all: false,\n get: true,\n },\n paths: {\n route: '',\n source: './',\n },\n },\n options,\n ),\n );\n this.files = this._createFiles();\n }\n /**\n * Mounts the middlewares in the router in order to serve the files.\n *\n * @param router A reference to the application router.\n * @param middlewares A list of extra middlewares to execute before the file\n * middleware.\n */\n addRoutes(router: Router, middlewares: ExpressMiddleware[] = []): Router {\n const { methods } = this._options;\n const use: RouterMethod[] = methods.all\n ? ['all']\n : Object.keys(methods).reduce<RouterMethod[]>((acc, name) => {\n const methodName = name as RouterMethod;\n if (methods[methodName]) {\n acc.push(methodName);\n }\n\n return acc;\n }, []);\n\n Object.keys(this.files).forEach((route) => {\n const file = this.files[route as keyof typeof this.files]!;\n const fileMiddleware = this._getMiddleware(file);\n use.forEach((method) =>\n this._addRoute({ router, method, file, fileMiddleware, middlewares }),\n );\n });\n\n return router;\n }\n /**\n * The controller options.\n */\n get options(): Readonly<StaticsControllerOptions> {\n return { ...this._options };\n }\n /**\n * Generates the middleware that will serve the file.\n *\n * @param file The definition of the file to serve.\n */\n protected _getMiddleware(file: StaticsControllerFile): ExpressMiddleware {\n return (_, res, next) => {\n const extension = path.parse(file.path).ext.substring(1);\n const headers = {\n 'Content-Type': mime.getType(extension) || 'text/html',\n ...file.headers,\n };\n\n Object.entries(headers).forEach(([key, value]) => {\n res.setHeader(key, value);\n });\n\n this._sendFile({\n res,\n filepath: file.path,\n next,\n });\n };\n }\n /**\n * Mounts the middleware(s) for a file in the router.\n *\n * @param options The information of the file and how it needs to be added.\n */\n protected _addRoute({\n router,\n method,\n file,\n fileMiddleware,\n middlewares,\n }: AddStaticRouteOptions): void {\n const { route } = file;\n router[method](route, [...middlewares, fileMiddleware]);\n }\n /**\n * Validates and formats the options sent to the constructor in order to get the final\n * set that will be stored in the controller.\n *\n * @param options The options to validate.\n * @throws If no files are specified.\n * @throws If methods is not defined.\n * @throws If no methods are enabled.\n * @throws If there's an invalid HTTP method.\n */\n protected _validateOptions(\n options: StaticsControllerOptions,\n ): StaticsControllerOptions {\n if (!options.files || !options.files.length) {\n throw new Error('You need to specify a list of files');\n }\n\n if (!options.methods) {\n throw new Error('You need to specify which HTTP methods are allowed for the files');\n }\n\n const methods = Object.keys(options.methods) as RouterMethod[];\n\n const atLeastOne = methods.some((method) => options.methods[method]);\n if (!atLeastOne) {\n throw new Error('You need to enable at least one HTTP method to serve the files');\n }\n\n const allowedMethods: RouterMethod[] = [\n 'all',\n 'get',\n 'head',\n 'post',\n 'patch',\n 'put',\n 'delete',\n 'connect',\n 'options',\n 'trace',\n ];\n\n const invalid = methods.find(\n (method) => !allowedMethods.includes(method.toLowerCase() as RouterMethod),\n );\n\n if (invalid) {\n throw new Error(`${invalid} is not a valid HTTP method`);\n }\n\n const newMethods = methods.reduce<Record<string, boolean>>((acc, method) => {\n acc[method.toLowerCase()] = !!options.methods[method];\n return acc;\n }, {});\n\n return {\n ...options,\n methods: newMethods,\n };\n }\n /**\n * Parses the files received from the constructor's options, and formats them into\n * proper definitions the controller can use.\n */\n protected _createFiles(): Record<string, StaticsControllerFile> {\n const { files, paths } = this._options;\n const routePath = removeSlashes(paths.route, false, true);\n return files.reduce<Record<string, StaticsControllerFile>>((acc, file) => {\n let src;\n let route;\n let headers;\n if (typeof file === 'object') {\n ({ route, path: src, headers } = file);\n } else {\n src = file;\n route = file;\n }\n\n src = path.join(paths.source, src);\n route = removeSlashes(route, true, false);\n route = `${routePath}/${route}`;\n acc[route] = {\n path: src,\n route,\n headers: headers || {},\n };\n\n return acc;\n }, {});\n }\n}\n/**\n * A controller that allows the application to server specific files from any folder to\n * any route without the need of mounting directories as \"static\" folders.\n *\n * @group Controllers\n * @group Controllers/Statics\n */\nexport const staticsController = controllerCreator(\n ({ getMiddlewares, ...options }: StaticsControllerCreatorOptions = {}) =>\n (app) => {\n const router = app.getRouter();\n const ctrl = new StaticsController({\n inject: {\n sendFile: app.get('sendFile'),\n },\n ...options,\n });\n\n let useMiddlewares: ExpressMiddleware[] | undefined;\n if (getMiddlewares) {\n useMiddlewares = getMiddlewares(app)\n .map((middleware) => {\n if ('middleware' in middleware) {\n return middleware.connect(app) as ExpressMiddleware | undefined;\n }\n\n return middleware as ExpressMiddleware;\n })\n .filter(notUndefined);\n }\n\n return ctrl.addRoutes(router, useMiddlewares);\n },\n);\n"],"mappings":";;;AAAA,YAAY,UAAU;AACtB,YAAY,UAAU;AACtB,SAAS,+BAA+B;AACxC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAwIA,MAAM,kBAAkB;AAAA,EAiB7B,YAAY,EAAE,WAAW,QAAQ,GAAwC;AAbzE,wBAAmB;AAInB,wBAAU;AAKV,wBAAU;AAKR,SAAK,YAAY,OAAO;AACxB,SAAK,WAAW,KAAK;AAAA,MACnB;AAAA,QACE;AAAA,UACE,OAAO,CAAC,eAAe,YAAY;AAAA,UACnC,SAAS,QAAQ,WAAW;AAAA,YAC1B,KAAK;AAAA,YACL,KAAK;AAAA,UACP;AAAA,UACA,OAAO;AAAA,YACL,OAAO;AAAA,YACP,QAAQ;AAAA,UACV;AAAA,QACF;AAAA,QACA;AAAA,MACF;AAAA,IACF;AACA,SAAK,QAAQ,KAAK,aAAa;AAAA,EACjC;AAAA,EAQA,UAAU,QAAgB,cAAmC,CAAC,GAAW;AACvE,UAAM,EAAE,QAAQ,IAAI,KAAK;AACzB,UAAM,MAAsB,QAAQ,MAChC,CAAC,KAAK,IACN,OAAO,KAAK,OAAO,EAAE,OAAuB,CAAC,KAAK,SAAS;AACzD,YAAM,aAAa;AACnB,UAAI,QAAQ,aAAa;AACvB,YAAI,KAAK,UAAU;AAAA,MACrB;AAEA,aAAO;AAAA,IACT,GAAG,CAAC,CAAC;AAET,WAAO,KAAK,KAAK,KAAK,EAAE,QAAQ,CAAC,UAAU;AACzC,YAAM,OAAO,KAAK,MAAM;AACxB,YAAM,iBAAiB,KAA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AI,UAAU;AAC7B,UAAM,OAAO,IAAI,kBAAkB;AAAA,MACjC,QAAQ;AAAA,QACN,UAAU,IAAI,IAAI,UAAU;AAAA,MAC9B;AAAA,MACA,GAAG;AAAA,IACL,CAAC;AAED,QAAI;AACJ,QAAI,gBAAgB;AAClB,uBAAiB,eAAe,GAAG,EAChC,IAAI,CAAC,eAAe;AACnB,YAAI,gBAAgB,YAAY;AAC9B,iBAAO,WAAW,QAAQ,GAAG;AAAA,QAC/B;AAEA,eAAO;AAAA,MACT,CAAC,EACA,OAAO,YAAY;AAAA,IACxB;AAEA,WAAO,KAAK,UAAU,QAAQ,cAAc;AAAA,EAC9C;AACJ;","names":[]}
1
+ {"version":3,"sources":["../../../../src/controllers/common/statics.ts"],"sourcesContent":["import * as path from 'path';\nimport type mime from 'mime';\nimport { deepAssignWithOverwrite } from '@homer0/deep-assign';\nimport {\n controllerCreator,\n removeSlashes,\n notUndefined,\n type MiddlewareLike,\n} from '../../utils';\nimport type { SendFile } from '../../services';\nimport type { Jimpex } from '../../app';\nimport type { DeepPartial, ExpressMiddleware, Router, RouterMethod } from '../../types';\n\ntype Mime = typeof mime;\n\n/**\n * The definition for each file the controller handles.\n *\n * @group Controllers/Statics\n */\nexport type StaticsControllerFile = {\n /**\n * The route, relative to the controller root, to the file.\n */\n route: string;\n /**\n * The path to the file in the filesystem. Since the file is served using the\n * {@link SendFile} service, whether the file is relative to the project root or the\n * application executable depends on how the service is configured (relative to the\n * executable by default).\n */\n path: string;\n /**\n * A dictionary of headers for the response.\n */\n headers?: Record<string, string>;\n};\n/**\n * These are like \"master paths\" that get prepended to all the file paths and routes the\n * controller use.\n *\n * @group Controllers/Statics\n */\nexport type StaticsControllerPathsOptions = {\n /**\n * A custom route to prefix all the file routes with.\n */\n route: string;\n /**\n * A custom path to prefix all the file paths with.\n */\n source: string;\n};\n/**\n * The options to customize the controller.\n *\n * @group Controllers/Statics\n */\nexport type StaticsControllerOptions = {\n /**\n * A list of filenames, or definitions for the files to handle.\n */\n files: Array<string | StaticsControllerFile>;\n /**\n * A dictionary with the allowed router (HTTP) methods the controller can use to serve\n * the files. If `all` is set to `true`, the rest of the values will be ignored.\n *\n * @default {get: true, all: false}\n */\n methods: Partial<Record<RouterMethod, boolean>>;\n /**\n * The \"master paths\" the controller can use to prefix the file paths and routes.\n *\n * @default {route: '', source: './',}\n */\n paths: StaticsControllerPathsOptions;\n};\n/**\n * The options to construct a {@link StaticsController}.\n *\n * @group Controllers/Statics\n */\nexport type StaticsControllerConstructorOptions =\n DeepPartial<StaticsControllerOptions> & {\n /**\n * A dictionary with the dependencies to inject.\n */\n inject: {\n sendFile: SendFile;\n mime: Mime;\n };\n };\n/**\n * A function to generate a list of middlewares that can be executed before the tontroller\n * main middleware.\n *\n * @group Controllers/Statics\n */\nexport type StaticsControllerGetMiddlewaresFn = (app: Jimpex) => MiddlewareLike[];\n/**\n * The options for the controller creator that mounts {@link StaticsController}.\n *\n * @group Controllers/Statics\n */\nexport type StaticsControllerCreatorOptions = DeepPartial<StaticsControllerOptions> & {\n /**\n * A function to generate a list of middlewares that can be executed before the\n * tontroller main middleware.\n */\n getMiddlewares?: StaticsControllerGetMiddlewaresFn;\n};\n/**\n * The options for {@link StaticsController._addRoute}.\n *\n * @access protected\n * @group Controllers/Statics\n */\nexport type AddStaticRouteOptions = {\n /**\n * The reference for the router in which the middlewares will be added.\n */\n router: Router;\n /**\n * The router method in which the middlewares will be added.\n */\n method: RouterMethod;\n /**\n * The definition of the file to serve.\n */\n file: StaticsControllerFile;\n /**\n * The middleware created by {@link StaticsController}, that will serve the file.\n */\n fileMiddleware: ExpressMiddleware;\n /**\n * A list of extra middlewares to execute before the file middleware.\n */\n middlewares: ExpressMiddleware[];\n};\n\n/**\n * The controller class that allows the application to serve specific files from any\n * folder to any route without the need of mounting directories as \"static\".\n *\n * @group Controller Classes\n * @group Controllers/Statics\n * @prettierignore\n */\nexport class StaticsController {\n /**\n * The service that serves static files.\n */\n protected readonly _sendFile: SendFile;\n /**\n * The MIME type library. Since it's an ESM only module, Jimpex loads it on boot and makes\n * it available on the container.\n */\n protected readonly _mime: Mime;\n /**\n * The controller customization options.\n */\n protected _options: StaticsControllerOptions;\n /**\n * A dictionary with the formatted definitions of the files that will be served.\n * It uses the files' routes as keys, for easy access in the middleware.\n */\n protected files: Record<string, StaticsControllerFile>;\n /**\n * @param options The options to construct the controller.\n */\n constructor({ inject, ...options }: StaticsControllerConstructorOptions) {\n this._sendFile = inject.sendFile;\n this._mime = inject.mime;\n this._options = this._validateOptions(\n deepAssignWithOverwrite(\n {\n files: ['favicon.ico', 'index.html'],\n methods: options.methods || {\n all: false,\n get: true,\n },\n paths: {\n route: '',\n source: './',\n },\n },\n options,\n ),\n );\n this.files = this._createFiles();\n }\n /**\n * Mounts the middlewares in the router in order to serve the files.\n *\n * @param router A reference to the application router.\n * @param middlewares A list of extra middlewares to execute before the file\n * middleware.\n */\n addRoutes(router: Router, middlewares: ExpressMiddleware[] = []): Router {\n const { methods } = this._options;\n const use: RouterMethod[] = methods.all\n ? ['all']\n : Object.keys(methods).reduce<RouterMethod[]>((acc, name) => {\n const methodName = name as RouterMethod;\n if (methods[methodName]) {\n acc.push(methodName);\n }\n\n return acc;\n }, []);\n\n Object.keys(this.files).forEach((route) => {\n const file = this.files[route as keyof typeof this.files]!;\n const fileMiddleware = this._getMiddleware(file);\n use.forEach((method) =>\n this._addRoute({ router, method, file, fileMiddleware, middlewares }),\n );\n });\n\n return router;\n }\n /**\n * The controller options.\n */\n get options(): Readonly<StaticsControllerOptions> {\n return { ...this._options };\n }\n /**\n * Generates the middleware that will serve the file.\n *\n * @param file The definition of the file to serve.\n */\n protected _getMiddleware(file: StaticsControllerFile): ExpressMiddleware {\n return (_, res, next) => {\n const extension = path.parse(file.path).ext.substring(1);\n const headers = {\n 'Content-Type': this._mime.getType(extension) || 'text/html',\n ...file.headers,\n };\n\n Object.entries(headers).forEach(([key, value]) => {\n res.setHeader(key, value);\n });\n\n this._sendFile({\n res,\n filepath: file.path,\n next,\n });\n };\n }\n /**\n * Mounts the middleware(s) for a file in the router.\n *\n * @param options The information of the file and how it needs to be added.\n */\n protected _addRoute({\n router,\n method,\n file,\n fileMiddleware,\n middlewares,\n }: AddStaticRouteOptions): void {\n const { route } = file;\n router[method](route, [...middlewares, fileMiddleware]);\n }\n /**\n * Validates and formats the options sent to the constructor in order to get the final\n * set that will be stored in the controller.\n *\n * @param options The options to validate.\n * @throws If no files are specified.\n * @throws If methods is not defined.\n * @throws If no methods are enabled.\n * @throws If there's an invalid HTTP method.\n */\n protected _validateOptions(\n options: StaticsControllerOptions,\n ): StaticsControllerOptions {\n if (!options.files || !options.files.length) {\n throw new Error('You need to specify a list of files');\n }\n\n if (!options.methods) {\n throw new Error('You need to specify which HTTP methods are allowed for the files');\n }\n\n const methods = Object.keys(options.methods) as RouterMethod[];\n\n const atLeastOne = methods.some((method) => options.methods[method]);\n if (!atLeastOne) {\n throw new Error('You need to enable at least one HTTP method to serve the files');\n }\n\n const allowedMethods: RouterMethod[] = [\n 'all',\n 'get',\n 'head',\n 'post',\n 'patch',\n 'put',\n 'delete',\n 'connect',\n 'options',\n 'trace',\n ];\n\n const invalid = methods.find(\n (method) => !allowedMethods.includes(method.toLowerCase() as RouterMethod),\n );\n\n if (invalid) {\n throw new Error(`${invalid} is not a valid HTTP method`);\n }\n\n const newMethods = methods.reduce<Record<string, boolean>>((acc, method) => {\n acc[method.toLowerCase()] = !!options.methods[method];\n return acc;\n }, {});\n\n return {\n ...options,\n methods: newMethods,\n };\n }\n /**\n * Parses the files received from the constructor's options, and formats them into\n * proper definitions the controller can use.\n */\n protected _createFiles(): Record<string, StaticsControllerFile> {\n const { files, paths } = this._options;\n const routePath = removeSlashes(paths.route, false, true);\n return files.reduce<Record<string, StaticsControllerFile>>((acc, file) => {\n let src;\n let route;\n let headers;\n if (typeof file === 'object') {\n ({ route, path: src, headers } = file);\n } else {\n src = file;\n route = file;\n }\n\n src = path.join(paths.source, src);\n route = removeSlashes(route, true, false);\n route = `${routePath}/${route}`;\n acc[route] = {\n path: src,\n route,\n headers: headers || {},\n };\n\n return acc;\n }, {});\n }\n}\n/**\n * A controller that allows the application to server specific files from any folder to\n * any route without the need of mounting directories as \"static\" folders.\n *\n * @group Controllers\n * @group Controllers/Statics\n */\nexport const staticsController = controllerCreator(\n ({ getMiddlewares, ...options }: StaticsControllerCreatorOptions = {}) =>\n (app) => {\n const router = app.getRouter();\n const ctrl = new StaticsController({\n inject: {\n sendFile: app.get('sendFile'),\n mime: app.get('mime'),\n },\n ...options,\n });\n\n let useMiddlewares: ExpressMiddleware[] | undefined;\n if (getMiddlewares) {\n useMiddlewares = getMiddlewares(app)\n .map((middleware) => {\n if ('middleware' in middleware) {\n return middleware.connect(app) as ExpressMiddleware | undefined;\n }\n\n return middleware as ExpressMiddleware;\n })\n .filter(notUndefined);\n }\n\n return ctrl.addRoutes(router, useMiddlewares);\n },\n);\n"],"mappings":";;;AAAA,YAAY,UAAU;AAEtB,SAAS,+BAA+B;AACxC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AA4IA,MAAM,kBAAkB;AAAA;AAAA;AAAA;AAAA,EAsB7B,YAAY,EAAE,QAAQ,GAAG,QAAQ,GAAwC;AAlBzE;AAAA;AAAA;AAAA,wBAAmB;AAKnB;AAAA;AAAA;AAAA;AAAA,wBAAmB;AAInB;AAAA;AAAA;AAAA,wBAAU;AAKV;AAAA;AAAA;AAAA;AAAA,wBAAU;AAKR,SAAK,YAAY,OAAO;AACxB,SAAK,QAAQ,OAAO;AACpB,SAAK,WAAW,KAAK;AAAA,MACnB;AAAA,QACE;AAAA,UACE,OAAO,CAAC,eAAe,YAAY;AAAA,UACnC,SAAS,QAAQ,WAAW;AAAA,YAC1B,KAAK;AAAA,YACL,KAAK;AAAA,UACP;AAAA,UACA,OAAO;AAAA,YACL,OAAO;AAAA,YACP,QAAQ;AAAA,UACV;AAAA,QACF;AAAA,QACA;AAAA,MACF;AAAA,IACF;AACA,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unk-T2T6Q22Z.js";
3
+ } from "../../chunk-F3FYYIAV.js";
4
4
  import { deepAssignWithOverwrite } from "@homer0/deep-assign";
5
5
  import { flat, unflat } from "@homer0/object-utils";
6
6
  import {
@@ -11,21 +11,59 @@ import {
11
11
  notUndefined
12
12
  } from "../../utils";
13
13
  class GatewayController {
14
+ /**
15
+ * @param options The options to construct the controller.
16
+ */
14
17
  constructor({
15
18
  inject,
16
19
  route,
17
20
  gatewayConfig,
18
21
  ...options
19
22
  }) {
23
+ /**
24
+ * The service that makes HTTP requests.
25
+ */
20
26
  __publicField(this, "http");
27
+ /**
28
+ * A function to get a possible helper service. This is injected as a "getter" to not
29
+ * interrupt the DIC "lifecycle": controllers are initialized right when the app
30
+ * starts, and injecting a reference would force the service to be initialized too,
31
+ * even if a request is not being made.
32
+ */
21
33
  __publicField(this, "_getHelperService");
34
+ /**
35
+ * The information, url and endpoints, for the gateway the controller will make requests to.
36
+ */
22
37
  __publicField(this, "_gatewayConfig");
38
+ /**
39
+ * The route in which the controller is mounted.
40
+ */
23
41
  __publicField(this, "_route");
42
+ /**
43
+ * A regular expression that will be used to remove the controller route from a
44
+ * request path. This will allow the main middleware to extract the path to where the
45
+ * request should be made.
46
+ */
24
47
  __publicField(this, "_routeExpression");
48
+ /**
49
+ * The controller customization options.
50
+ */
25
51
  __publicField(this, "_options");
52
+ /**
53
+ * A flat dictionary with the endpoints information.
54
+ */
26
55
  __publicField(this, "_endpoints");
56
+ /**
57
+ * The entry URL for the API client configuration the controller can generate.
58
+ */
27
59
  __publicField(this, "_apiConfigUrl");
60
+ /**
61
+ * The generated endpoints for the API client configuration the controller can generate.
62
+ */
28
63
  __publicField(this, "_apiConfigEndpoints");
64
+ /**
65
+ * The list of routes the controller can handle.
66
+ */
29
67
  __publicField(this, "_routes");
30
68
  this.http = inject.http;
31
69
  this._getHelperService = inject.getHelperService || (() => void 0);
@@ -60,6 +98,11 @@ class GatewayController {
60
98
  this._apiConfigUrl = url;
61
99
  this._apiConfigEndpoints = endpoints;
62
100
  }
101
+ /**
102
+ * Generates an API client configuration based on the controller routes.
103
+ *
104
+ * @param options The options to customize the generated configuration.
105
+ */
63
106
  getAPIConfig({
64
107
  setting,
65
108
  placeholders = {}
@@ -82,6 +125,13 @@ class GatewayController {
82
125
  }
83
126
  };
84
127
  }
128
+ /**
129
+ * Mounts the middlewares in the router in order to make the requests.
130
+ *
131
+ * @param router A reference to the application router.
132
+ * @param middlewares A list of extra middlewares to execute before the gateway
133
+ * middleware.
134
+ */
85
135
  addRoutes(router, middlewares = []) {
86
136
  this._routes.forEach((route) => {
87
137
  route.methods.forEach((info) => {
@@ -96,12 +146,24 @@ class GatewayController {
96
146
  });
97
147
  return router;
98
148
  }
149
+ /**
150
+ * The customization options.
151
+ */
99
152
  get options() {
100
153
  return { ...this._options };
101
154
  }
155
+ /**
156
+ * The configuration for the gateway the controller will make requests to.
157
+ */
102
158
  get gatewayConfig() {
103
159
  return { ...this._gatewayConfig };
104
160
  }
161
+ /**
162
+ * Generates a middleware that will make the request to an endpoint and stream the
163
+ * response.
164
+ *
165
+ * @param endpoint The information of the endpoint the middleware will handle.
166
+ */
105
167
  _createGatewayMiddleware(endpoint) {
106
168
  return async (req, res, next) => {
107
169
  const {
@@ -166,6 +228,9 @@ class GatewayController {
166
228
  ...helperBasePayload
167
229
  });
168
230
  if (shouldStream) {
231
+ if (response.body === null) {
232
+ throw new Error("The response body is null");
233
+ }
169
234
  res.status(response.status);
170
235
  response.headers.forEach((value, name) => {
171
236
  if (!headersOptions.remove.includes(name)) {
@@ -189,6 +254,11 @@ class GatewayController {
189
254
  }
190
255
  };
191
256
  }
257
+ /**
258
+ * Mounts the middleware(s) for an endpoint in the router.
259
+ *
260
+ * @param options The information of the endpoint and how it needs to be added.
261
+ */
192
262
  _addRoute({
193
263
  router,
194
264
  method,
@@ -198,6 +268,9 @@ class GatewayController {
198
268
  }) {
199
269
  router[method](route, [...middlewares, gatewayMiddleware]);
200
270
  }
271
+ /**
272
+ * Formats the endpoints for the gateway into a flat dictionary without nesting.
273
+ */
201
274
  _formatEndpoints() {
202
275
  return flat({
203
276
  target: this._gatewayConfig.gateway,
@@ -207,6 +280,13 @@ class GatewayController {
207
280
  }
208
281
  });
209
282
  }
283
+ /**
284
+ * Based on the information from the endpoints, this method will create the routes the
285
+ * controller will later add on a router.
286
+ *
287
+ * @throws If there's more than one endpoint using the same path with the same HTTP
288
+ * method.
289
+ */
210
290
  _createRoutes() {
211
291
  const routes = {};
212
292
  Object.keys(this._endpoints).forEach((name) => {
@@ -256,6 +336,18 @@ class GatewayController {
256
336
  };
257
337
  });
258
338
  }
339
+ /**
340
+ * This is a "proxy method" to call the helper service's function that can modify an
341
+ * endpoint request before it gets made.
342
+ *
343
+ * The reason this is a "proxy method" is in case the controller gets subclassed and
344
+ * "used itself as a helper" instead of relying on a difference one.
345
+ *
346
+ * If the helper doesn't implement `reduceEndpointRequest`, it will just return
347
+ * information for the request.
348
+ *
349
+ * @param options The information of the request and the reference to the helper.
350
+ */
259
351
  _reduceEndpointRequest({
260
352
  helper,
261
353
  ...options
@@ -265,6 +357,18 @@ class GatewayController {
265
357
  }
266
358
  return Promise.resolve(options.endpointReq);
267
359
  }
360
+ /**
361
+ * This is a "proxy method" to call the helper service's function that can modify an
362
+ * endpoint response before it gets processed.
363
+ *
364
+ * The reason this is a "proxy method" is in case the controller gets subclassed and
365
+ * "used itself as a helper" instead of relying on a difference one.
366
+ *
367
+ * If the helper doesn't implement `reduceEndpointResponse`, it will just return
368
+ * information for the response.
369
+ *
370
+ * @param options The information of the response and the reference to the helper.
371
+ */
268
372
  _reduceEndpointResponse({
269
373
  helper,
270
374
  ...options
@@ -274,6 +378,18 @@ class GatewayController {
274
378
  }
275
379
  return Promise.resolve(options.endpointRes);
276
380
  }
381
+ /**
382
+ * This is a "proxy method" to call the helper service's function that can decide if an
383
+ * endpoint response should be streamed or not.
384
+ *
385
+ * The reason this is a "proxy method" is in case the controller gets subclassed and
386
+ * "used itself as a helper" instead of relying on a difference one.
387
+ *
388
+ * If the helper doesn't implement `shouldStreamEndpointResponse`, it will just return
389
+ * `true`.
390
+ *
391
+ * @param options The information of the response and the reference to the helper.
392
+ */
277
393
  _shouldStreamEndpointResponse({
278
394
  helper,
279
395
  ...options
@@ -283,6 +399,19 @@ class GatewayController {
283
399
  }
284
400
  return Promise.resolve(true);
285
401
  }
402
+ /**
403
+ * This is a "proxy method" to call the helper service's function that handles a
404
+ * response in case it already said that a response shouldn't be streamed.
405
+ *
406
+ * The reason this is a "proxy method" is in case the controller gets subclassed and
407
+ * "used itself as a helper" instead of relying on a difference one.
408
+ *
409
+ * If the helper doesn't implement `shouldStreamEndpointResponse`, it will throw an
410
+ * error.
411
+ *
412
+ * @param options The information of the response and the reference to the helper.
413
+ * @throws If the helper doesn't implement `handleEndpointResponse`.
414
+ */
286
415
  _handleEndpointResponse({
287
416
  helper,
288
417
  ...options
@@ -292,6 +421,18 @@ class GatewayController {
292
421
  }
293
422
  return helper.handleEndpointResponse(options);
294
423
  }
424
+ /**
425
+ * This is a "proxy method" to call the helper service's function that handles an error
426
+ * on an endpoint request.
427
+ *
428
+ * The reason this is a "proxy method" is in case the controller gets subclassed and
429
+ * "used itself as a helper" instead of relying on a difference one.
430
+ *
431
+ * If the helper doesn't implement `handleEndpointError`, it will just send the error to
432
+ * the next middleware/error handler.
433
+ *
434
+ * @param options The information of the response and the reference to the helper.
435
+ */
295
436
  _handleEndpointError({
296
437
  helper,
297
438
  ...options
@@ -301,6 +442,11 @@ class GatewayController {
301
442
  }
302
443
  return options.next(options.error);
303
444
  }
445
+ /**
446
+ * Validates and formats the customization options sent to the controller.
447
+ *
448
+ * @param options The options sent to the constructor.
449
+ */
304
450
  _formatOptions(options) {
305
451
  if (options.root) {
306
452
  const root = removeSlashes(options.root).trim();
@@ -308,6 +454,12 @@ class GatewayController {
308
454
  }
309
455
  return options;
310
456
  }
457
+ /**
458
+ * Validates a router/HTTP method that the controller intends to use for an endpoint. If
459
+ * it's not valid, it will return `all`.
460
+ *
461
+ * @param method The HTTP method for the endpoint.
462
+ */
311
463
  _validateHTTPMethod(method) {
312
464
  const newMethod = method.toLowerCase();
313
465
  return [
@@ -322,6 +474,9 @@ class GatewayController {
322
474
  "trace"
323
475
  ].includes(newMethod) ? newMethod : "all";
324
476
  }
477
+ /**
478
+ * Creates the API client configuration based on the controller routes.
479
+ */
325
480
  _createAPIConfig() {
326
481
  let endpoints;
327
482
  const { root } = this._options;