jimpex 10.0.2 → 11.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 (346) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +7 -9
  3. package/dist/app/index.d.ts +1 -1
  4. package/dist/app/index.js +1 -22
  5. package/dist/app/index.js.map +1 -1
  6. package/dist/app/jimpex.d.ts +1 -1
  7. package/dist/app/jimpex.js +100 -131
  8. package/dist/app/jimpex.js.map +1 -1
  9. package/dist/controllers/common/config.d.ts +2 -2
  10. package/dist/controllers/common/config.js +12 -39
  11. package/dist/controllers/common/config.js.map +1 -1
  12. package/dist/controllers/common/health.d.ts +4 -4
  13. package/dist/controllers/common/health.js +20 -47
  14. package/dist/controllers/common/health.js.map +1 -1
  15. package/dist/controllers/common/index.d.ts +1 -1
  16. package/dist/controllers/common/index.js +3 -26
  17. package/dist/controllers/common/index.js.map +1 -1
  18. package/dist/controllers/common/statics.d.ts +3 -3
  19. package/dist/controllers/common/statics.js +32 -65
  20. package/dist/controllers/common/statics.js.map +1 -1
  21. package/dist/controllers/index.d.ts +1 -1
  22. package/dist/controllers/index.js +2 -24
  23. package/dist/controllers/index.js.map +1 -1
  24. package/dist/controllers/utils/gateway.d.ts +5 -5
  25. package/dist/controllers/utils/gateway.js +70 -91
  26. package/dist/controllers/utils/gateway.js.map +1 -1
  27. package/dist/controllers/utils/index.d.ts +1 -1
  28. package/dist/controllers/utils/index.js +1 -22
  29. package/dist/controllers/utils/index.js.map +1 -1
  30. package/dist/{index-C6I3NCC-.d.ts → index-BlSpNHox.d.ts} +13 -13
  31. package/dist/index.d.ts +3 -3
  32. package/dist/index.js +6 -32
  33. package/dist/index.js.map +1 -1
  34. package/dist/middlewares/common/errorHandler.d.ts +5 -5
  35. package/dist/middlewares/common/errorHandler.js +31 -56
  36. package/dist/middlewares/common/errorHandler.js.map +1 -1
  37. package/dist/middlewares/common/forceHTTPS.d.ts +1 -1
  38. package/dist/middlewares/common/forceHTTPS.js +8 -35
  39. package/dist/middlewares/common/forceHTTPS.js.map +1 -1
  40. package/dist/middlewares/common/hsts.d.ts +1 -1
  41. package/dist/middlewares/common/hsts.js +12 -39
  42. package/dist/middlewares/common/hsts.js.map +1 -1
  43. package/dist/middlewares/common/index.d.ts +3 -3
  44. package/dist/middlewares/common/index.js +3 -26
  45. package/dist/middlewares/common/index.js.map +1 -1
  46. package/dist/middlewares/html/fastHTML.d.ts +4 -4
  47. package/dist/middlewares/html/fastHTML.js +43 -66
  48. package/dist/middlewares/html/fastHTML.js.map +1 -1
  49. package/dist/middlewares/html/index.d.ts +2 -2
  50. package/dist/middlewares/html/index.js +2 -24
  51. package/dist/middlewares/html/index.js.map +1 -1
  52. package/dist/middlewares/html/showHTML.d.ts +3 -3
  53. package/dist/middlewares/html/showHTML.js +25 -52
  54. package/dist/middlewares/html/showHTML.js.map +1 -1
  55. package/dist/middlewares/index.d.ts +4 -4
  56. package/dist/middlewares/index.js +3 -26
  57. package/dist/middlewares/index.js.map +1 -1
  58. package/dist/middlewares/utils/index.d.ts +3 -3
  59. package/dist/middlewares/utils/index.js +1 -22
  60. package/dist/middlewares/utils/index.js.map +1 -1
  61. package/dist/middlewares/utils/versionValidator.d.ts +5 -5
  62. package/dist/middlewares/utils/versionValidator.js +24 -51
  63. package/dist/middlewares/utils/versionValidator.js.map +1 -1
  64. package/dist/services/common/appError.d.ts +2 -2
  65. package/dist/services/common/appError.js +18 -46
  66. package/dist/services/common/appError.js.map +1 -1
  67. package/dist/services/common/httpError.d.ts +2 -2
  68. package/dist/services/common/httpError.js +7 -33
  69. package/dist/services/common/httpError.js.map +1 -1
  70. package/dist/services/common/index.d.ts +1 -1
  71. package/dist/services/common/index.js +14 -42
  72. package/dist/services/common/index.js.map +1 -1
  73. package/dist/services/common/sendFile.d.ts +1 -1
  74. package/dist/services/common/sendFile.js +4 -29
  75. package/dist/services/common/sendFile.js.map +1 -1
  76. package/dist/services/frontend/frontendFs.d.ts +2 -2
  77. package/dist/services/frontend/frontendFs.js +12 -49
  78. package/dist/services/frontend/frontendFs.js.map +1 -1
  79. package/dist/services/frontend/index.d.ts +2 -2
  80. package/dist/services/frontend/index.js +8 -34
  81. package/dist/services/frontend/index.js.map +1 -1
  82. package/dist/services/html/htmlGenerator.d.ts +5 -5
  83. package/dist/services/html/htmlGenerator.js +46 -75
  84. package/dist/services/html/htmlGenerator.js.map +1 -1
  85. package/dist/services/html/index.d.ts +2 -2
  86. package/dist/services/html/index.js +8 -34
  87. package/dist/services/html/index.js.map +1 -1
  88. package/dist/services/http/apiClient.d.ts +1 -1
  89. package/dist/services/http/apiClient.js +23 -48
  90. package/dist/services/http/apiClient.js.map +1 -1
  91. package/dist/services/http/http.d.ts +5 -5
  92. package/dist/services/http/http.js +23 -60
  93. package/dist/services/http/http.js.map +1 -1
  94. package/dist/services/http/index.d.ts +2 -2
  95. package/dist/services/http/index.js +14 -42
  96. package/dist/services/http/index.js.map +1 -1
  97. package/dist/services/http/responsesBuilder.d.ts +4 -4
  98. package/dist/services/http/responsesBuilder.js +13 -40
  99. package/dist/services/http/responsesBuilder.js.map +1 -1
  100. package/dist/services/index.d.ts +3 -3
  101. package/dist/services/index.js +5 -30
  102. package/dist/services/index.js.map +1 -1
  103. package/dist/services/utils/ensureBearerToken.d.ts +2 -2
  104. package/dist/services/utils/ensureBearerToken.js +15 -42
  105. package/dist/services/utils/ensureBearerToken.js.map +1 -1
  106. package/dist/services/utils/index.d.ts +1 -1
  107. package/dist/services/utils/index.js +8 -34
  108. package/dist/services/utils/index.js.map +1 -1
  109. package/dist/types/events.d.ts +1 -1
  110. package/dist/types/events.js +0 -16
  111. package/dist/types/events.js.map +1 -1
  112. package/dist/types/express.js +0 -16
  113. package/dist/types/express.js.map +1 -1
  114. package/dist/types/http.js +0 -16
  115. package/dist/types/http.js.map +1 -1
  116. package/dist/types/index.d.ts +1 -1
  117. package/dist/types/index.js +6 -32
  118. package/dist/types/index.js.map +1 -1
  119. package/dist/types/options.d.ts +1 -1
  120. package/dist/types/options.js +0 -16
  121. package/dist/types/options.js.map +1 -1
  122. package/dist/types/utils.js +0 -16
  123. package/dist/types/utils.js.map +1 -1
  124. package/dist/types/wootils.js +0 -16
  125. package/dist/types/wootils.js.map +1 -1
  126. package/dist/utils/fns/index.js +4 -28
  127. package/dist/utils/fns/index.js.map +1 -1
  128. package/dist/utils/fns/others.js +2 -26
  129. package/dist/utils/fns/others.js.map +1 -1
  130. package/dist/utils/fns/routes.js +4 -31
  131. package/dist/utils/fns/routes.js.map +1 -1
  132. package/dist/utils/fns/statuses.js +3 -37
  133. package/dist/utils/fns/statuses.js.map +1 -1
  134. package/dist/utils/fns/text.js +2 -26
  135. package/dist/utils/fns/text.js.map +1 -1
  136. package/dist/utils/index.d.ts +1 -1
  137. package/dist/utils/index.js +2 -24
  138. package/dist/utils/index.js.map +1 -1
  139. package/dist/utils/wrappers.d.ts +1 -1
  140. package/dist/utils/wrappers.js +20 -48
  141. package/dist/utils/wrappers.js.map +1 -1
  142. package/eslint.config.js +19 -0
  143. package/examples/basic/app.ts +4 -4
  144. package/examples/basic/controller.ts +2 -2
  145. package/examples/basic/index.ts +4 -4
  146. package/examples/basic/middleware.ts +2 -2
  147. package/examples/basic/service.ts +1 -1
  148. package/package.json +61 -49
  149. package/pnpm-workspace.yaml +4 -0
  150. package/src/app/index.ts +1 -1
  151. package/src/app/jimpex.ts +23 -20
  152. package/src/controllers/common/config.ts +4 -4
  153. package/src/controllers/common/health.ts +9 -5
  154. package/src/controllers/common/index.ts +3 -3
  155. package/src/controllers/common/statics.ts +12 -7
  156. package/src/controllers/index.ts +2 -2
  157. package/src/controllers/utils/gateway.ts +8 -8
  158. package/src/controllers/utils/index.ts +1 -1
  159. package/src/index.ts +6 -6
  160. package/src/middlewares/common/errorHandler.ts +9 -5
  161. package/src/middlewares/common/forceHTTPS.ts +2 -2
  162. package/src/middlewares/common/hsts.ts +2 -2
  163. package/src/middlewares/common/index.ts +3 -3
  164. package/src/middlewares/html/fastHTML.ts +14 -5
  165. package/src/middlewares/html/index.ts +2 -2
  166. package/src/middlewares/html/showHTML.ts +8 -4
  167. package/src/middlewares/index.ts +3 -3
  168. package/src/middlewares/utils/index.ts +1 -1
  169. package/src/middlewares/utils/versionValidator.ts +6 -6
  170. package/src/services/common/appError.ts +1 -1
  171. package/src/services/common/httpError.ts +2 -2
  172. package/src/services/common/index.ts +7 -7
  173. package/src/services/common/sendFile.ts +2 -2
  174. package/src/services/frontend/frontendFs.ts +3 -3
  175. package/src/services/frontend/index.ts +3 -3
  176. package/src/services/html/htmlGenerator.ts +11 -13
  177. package/src/services/html/index.ts +3 -3
  178. package/src/services/http/apiClient.ts +3 -3
  179. package/src/services/http/http.ts +5 -5
  180. package/src/services/http/index.ts +7 -7
  181. package/src/services/http/responsesBuilder.ts +5 -5
  182. package/src/services/index.ts +5 -5
  183. package/src/services/utils/ensureBearerToken.ts +4 -4
  184. package/src/services/utils/index.ts +3 -3
  185. package/src/types/events.ts +8 -8
  186. package/src/types/http.ts +1 -1
  187. package/src/types/index.ts +6 -6
  188. package/src/types/options.ts +2 -2
  189. package/src/types/utils.ts +4 -4
  190. package/src/utils/fns/index.ts +4 -4
  191. package/src/utils/fns/routes.ts +1 -1
  192. package/src/utils/index.ts +2 -2
  193. package/src/utils/wrappers.ts +6 -6
  194. package/tsconfig.json +9 -4
  195. package/tsup.config.ts +1 -2
  196. package/vitest.config.ts +24 -0
  197. package/dist/app/index.d.mts +0 -14
  198. package/dist/app/jimpex.d.mts +0 -14
  199. package/dist/controllers/common/config.d.mts +0 -79
  200. package/dist/controllers/common/health.d.mts +0 -83
  201. package/dist/controllers/common/index.d.mts +0 -22
  202. package/dist/controllers/common/statics.d.mts +0 -223
  203. package/dist/controllers/index.d.mts +0 -25
  204. package/dist/controllers/utils/gateway.d.mts +0 -725
  205. package/dist/controllers/utils/index.d.mts +0 -17
  206. package/dist/esm/app/index.js +0 -2
  207. package/dist/esm/app/index.js.map +0 -1
  208. package/dist/esm/app/jimpex.js +0 -640
  209. package/dist/esm/app/jimpex.js.map +0 -1
  210. package/dist/esm/chunk-V6TY7KAL.js +0 -8
  211. package/dist/esm/chunk-V6TY7KAL.js.map +0 -1
  212. package/dist/esm/controllers/common/config.js +0 -80
  213. package/dist/esm/controllers/common/config.js.map +0 -1
  214. package/dist/esm/controllers/common/health.js +0 -88
  215. package/dist/esm/controllers/common/health.js.map +0 -1
  216. package/dist/esm/controllers/common/index.js +0 -4
  217. package/dist/esm/controllers/common/index.js.map +0 -1
  218. package/dist/esm/controllers/common/statics.js +0 -226
  219. package/dist/esm/controllers/common/statics.js.map +0 -1
  220. package/dist/esm/controllers/index.js +0 -3
  221. package/dist/esm/controllers/index.js.map +0 -1
  222. package/dist/esm/controllers/utils/gateway.js +0 -559
  223. package/dist/esm/controllers/utils/gateway.js.map +0 -1
  224. package/dist/esm/controllers/utils/index.js +0 -2
  225. package/dist/esm/controllers/utils/index.js.map +0 -1
  226. package/dist/esm/index.js +0 -7
  227. package/dist/esm/index.js.map +0 -1
  228. package/dist/esm/middlewares/common/errorHandler.js +0 -116
  229. package/dist/esm/middlewares/common/errorHandler.js.map +0 -1
  230. package/dist/esm/middlewares/common/forceHTTPS.js +0 -52
  231. package/dist/esm/middlewares/common/forceHTTPS.js.map +0 -1
  232. package/dist/esm/middlewares/common/hsts.js +0 -74
  233. package/dist/esm/middlewares/common/hsts.js.map +0 -1
  234. package/dist/esm/middlewares/common/index.js +0 -4
  235. package/dist/esm/middlewares/common/index.js.map +0 -1
  236. package/dist/esm/middlewares/html/fastHTML.js +0 -157
  237. package/dist/esm/middlewares/html/fastHTML.js.map +0 -1
  238. package/dist/esm/middlewares/html/index.js +0 -3
  239. package/dist/esm/middlewares/html/index.js.map +0 -1
  240. package/dist/esm/middlewares/html/showHTML.js +0 -100
  241. package/dist/esm/middlewares/html/showHTML.js.map +0 -1
  242. package/dist/esm/middlewares/index.js +0 -4
  243. package/dist/esm/middlewares/index.js.map +0 -1
  244. package/dist/esm/middlewares/utils/index.js +0 -2
  245. package/dist/esm/middlewares/utils/index.js.map +0 -1
  246. package/dist/esm/middlewares/utils/versionValidator.js +0 -135
  247. package/dist/esm/middlewares/utils/versionValidator.js.map +0 -1
  248. package/dist/esm/services/common/appError.js +0 -98
  249. package/dist/esm/services/common/appError.js.map +0 -1
  250. package/dist/esm/services/common/httpError.js +0 -28
  251. package/dist/esm/services/common/httpError.js.map +0 -1
  252. package/dist/esm/services/common/index.js +0 -17
  253. package/dist/esm/services/common/index.js.map +0 -1
  254. package/dist/esm/services/common/sendFile.js +0 -27
  255. package/dist/esm/services/common/sendFile.js.map +0 -1
  256. package/dist/esm/services/frontend/frontendFs.js +0 -66
  257. package/dist/esm/services/frontend/frontendFs.js.map +0 -1
  258. package/dist/esm/services/frontend/index.js +0 -11
  259. package/dist/esm/services/frontend/index.js.map +0 -1
  260. package/dist/esm/services/html/htmlGenerator.js +0 -192
  261. package/dist/esm/services/html/htmlGenerator.js.map +0 -1
  262. package/dist/esm/services/html/index.js +0 -11
  263. package/dist/esm/services/html/index.js.map +0 -1
  264. package/dist/esm/services/http/apiClient.js +0 -94
  265. package/dist/esm/services/http/apiClient.js.map +0 -1
  266. package/dist/esm/services/http/http.js +0 -180
  267. package/dist/esm/services/http/http.js.map +0 -1
  268. package/dist/esm/services/http/index.js +0 -17
  269. package/dist/esm/services/http/index.js.map +0 -1
  270. package/dist/esm/services/http/responsesBuilder.js +0 -152
  271. package/dist/esm/services/http/responsesBuilder.js.map +0 -1
  272. package/dist/esm/services/index.js +0 -6
  273. package/dist/esm/services/index.js.map +0 -1
  274. package/dist/esm/services/utils/ensureBearerToken.js +0 -94
  275. package/dist/esm/services/utils/ensureBearerToken.js.map +0 -1
  276. package/dist/esm/services/utils/index.js +0 -11
  277. package/dist/esm/services/utils/index.js.map +0 -1
  278. package/dist/esm/types/events.js +0 -1
  279. package/dist/esm/types/events.js.map +0 -1
  280. package/dist/esm/types/express.js +0 -1
  281. package/dist/esm/types/express.js.map +0 -1
  282. package/dist/esm/types/http.js +0 -1
  283. package/dist/esm/types/http.js.map +0 -1
  284. package/dist/esm/types/index.js +0 -7
  285. package/dist/esm/types/index.js.map +0 -1
  286. package/dist/esm/types/options.js +0 -1
  287. package/dist/esm/types/options.js.map +0 -1
  288. package/dist/esm/types/utils.js +0 -1
  289. package/dist/esm/types/utils.js.map +0 -1
  290. package/dist/esm/types/wootils.js +0 -1
  291. package/dist/esm/types/wootils.js.map +0 -1
  292. package/dist/esm/utils/fns/index.js +0 -5
  293. package/dist/esm/utils/fns/index.js.map +0 -1
  294. package/dist/esm/utils/fns/others.js +0 -6
  295. package/dist/esm/utils/fns/others.js.map +0 -1
  296. package/dist/esm/utils/fns/routes.js +0 -25
  297. package/dist/esm/utils/fns/routes.js.map +0 -1
  298. package/dist/esm/utils/fns/statuses.js +0 -6
  299. package/dist/esm/utils/fns/statuses.js.map +0 -1
  300. package/dist/esm/utils/fns/text.js +0 -6
  301. package/dist/esm/utils/fns/text.js.map +0 -1
  302. package/dist/esm/utils/index.js +0 -3
  303. package/dist/esm/utils/index.js.map +0 -1
  304. package/dist/esm/utils/wrappers.js +0 -41
  305. package/dist/esm/utils/wrappers.js.map +0 -1
  306. package/dist/index-Bwf7JHu9.d.mts +0 -1287
  307. package/dist/index.d.mts +0 -47
  308. package/dist/middlewares/common/errorHandler.d.mts +0 -132
  309. package/dist/middlewares/common/forceHTTPS.d.mts +0 -69
  310. package/dist/middlewares/common/hsts.d.mts +0 -110
  311. package/dist/middlewares/common/index.d.mts +0 -22
  312. package/dist/middlewares/html/fastHTML.d.mts +0 -180
  313. package/dist/middlewares/html/index.d.mts +0 -21
  314. package/dist/middlewares/html/showHTML.d.mts +0 -127
  315. package/dist/middlewares/index.d.mts +0 -30
  316. package/dist/middlewares/utils/index.d.mts +0 -20
  317. package/dist/middlewares/utils/versionValidator.d.mts +0 -215
  318. package/dist/services/common/appError.d.mts +0 -139
  319. package/dist/services/common/httpError.d.mts +0 -80
  320. package/dist/services/common/index.d.mts +0 -47
  321. package/dist/services/common/sendFile.d.mts +0 -102
  322. package/dist/services/frontend/frontendFs.d.mts +0 -96
  323. package/dist/services/frontend/index.d.mts +0 -40
  324. package/dist/services/html/htmlGenerator.d.mts +0 -237
  325. package/dist/services/html/index.d.mts +0 -43
  326. package/dist/services/http/apiClient.d.mts +0 -170
  327. package/dist/services/http/http.d.mts +0 -182
  328. package/dist/services/http/index.d.mts +0 -51
  329. package/dist/services/http/responsesBuilder.d.mts +0 -179
  330. package/dist/services/index.d.mts +0 -33
  331. package/dist/services/utils/ensureBearerToken.d.mts +0 -158
  332. package/dist/services/utils/index.d.mts +0 -44
  333. package/dist/types/events.d.mts +0 -14
  334. package/dist/types/express.d.mts +0 -10
  335. package/dist/types/http.d.mts +0 -82
  336. package/dist/types/index.d.mts +0 -14
  337. package/dist/types/options.d.mts +0 -14
  338. package/dist/types/utils.d.mts +0 -48
  339. package/dist/types/wootils.d.mts +0 -4
  340. package/dist/utils/fns/index.d.mts +0 -5
  341. package/dist/utils/fns/others.d.mts +0 -17
  342. package/dist/utils/fns/routes.d.mts +0 -39
  343. package/dist/utils/fns/statuses.d.mts +0 -45
  344. package/dist/utils/fns/text.d.mts +0 -9
  345. package/dist/utils/index.d.mts +0 -19
  346. package/dist/utils/wrappers.d.mts +0 -14
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../../src/services/html/htmlGenerator.ts"],"sourcesContent":["import { get } from '@homer0/object-utils';\nimport { deepAssignWithOverwrite } from '@homer0/deep-assign';\nimport { deferred, type DeferredPromise } from '@homer0/deferred';\nimport { providerCreator } from '../../utils';\nimport type { Config, Logger } from '../../types';\nimport type { FrontendFs } from '../frontend';\n/**\n * The options to customize a {@link HTMLGenerator} instance.\n *\n * @group Services/HTMLGenerator\n */\nexport type HTMLGeneratorOptions = {\n /**\n * The name of the file it should use as template.\n *\n * @default 'index.tpl.html'\n */\n template: string;\n /**\n * The name of the generated file.\n *\n * @default 'index.html'\n */\n file: string;\n /**\n * If `true`, it won't log messages on the terminal when generating the file.\n *\n * @default false\n */\n silent: boolean;\n /**\n * Whether or not to delete the tempalte after generating the file.\n *\n * @default true\n */\n deleteTemplateAfter: boolean;\n /**\n * The placeholder string where the information will be written.\n *\n * @default /\\{\\{appConfi(?:guration)?\\}\\}/\n */\n replacePlaceholder: string | RegExp;\n /**\n * A regular expression for dynamic placeholders that will be replaced by values when\n * the file is generated.\n *\n * @default /\\{\\{(.*?)\\}\\}/gi\n */\n placeholderExpression: RegExp;\n /**\n * The name of the variable that will have the information on the file.\n *\n * @default 'appConfig'\n */\n variableName: string;\n /**\n * A list of settings from the app configuration that will be used as the information to\n * inject on the file.\n *\n * @default ['features', 'version', 'postMessagesPrefix']\n */\n configKeys: string[];\n};\n/**\n * An external service that can be used to provide the values the generator will replace\n * in the template.\n *\n * @group Services/HTMLGenerator\n */\nexport type HTMLGeneratorValuesService = {\n /**\n * A function that will be called to get the values to replace in the template.\n *\n * @param options The service customization options.\n */\n getValues: (options: HTMLGeneratorOptions) => Promise<Record<string, unknown>>;\n};\n/**\n * The options to construct a {@link HTMLGenerator}.\n *\n * @group Services/HTMLGenerator\n */\nexport type HTMLGeneratorConstructorOptions = Partial<HTMLGeneratorOptions> & {\n /**\n * A dictionary with the dependencies to inject.\n */\n inject: {\n config: Config;\n logger: Logger;\n frontendFs: FrontendFs;\n /**\n * A service that can provide the values to replace in the template. If specified, the\n * values from `configKeys` will be ignored.\n */\n valuesService?: HTMLGeneratorValuesService;\n };\n};\n/**\n * Custom options for the provider that will register an instance of {@link HTMLGenerator}\n * as a service.\n *\n * @group Services/HTMLGenerator\n */\nexport type HTMLGeneratorProviderOptions = Partial<HTMLGeneratorOptions> & {\n /**\n * The name that will be used to register the service on the container. This is to allow\n * multiple \"instances\" of the service to be created.\n *\n * @default 'htmlGenerator'\n */\n serviceName?: string;\n /**\n * The name of a service that the generator will use in order to read the values that\n * will be replaced on the template. If the service is available, the values from\n * `configKeys` will be ignored.\n *\n * @default 'htmlGeneratorValues'\n */\n valuesServiceName?: string;\n};\n/**\n * This is a utility service that generates an HTML file with custom information when the\n * application is started.\n *\n * @group Services\n * @group Services/HTMLGenerator\n */\nexport class HTMLGenerator {\n /**\n * The service customization options.\n */\n protected readonly _options: HTMLGeneratorOptions;\n /**\n * The application configuration service, to get the settings specified by the\n * `configKeys` option.\n */\n protected readonly _config: Config;\n /**\n * The service that logs messages on the terminal, in case the `silent` option is `false`.\n */\n protected readonly _logger: Logger;\n /**\n * The service that interacts with the filesystem.\n */\n protected readonly _frontendFs: FrontendFs;\n /**\n * A service that can provide values to be replaced in the template.\n */\n protected readonly _valuesService?: HTMLGeneratorValuesService;\n /**\n * Whether or not the file was already generated.\n */\n protected _fileReady: boolean = false;\n /**\n * A deferred promise to return when another service asks if the file has been\n * generated. Once this sevice finishes generating the file, the promise will be\n * resolved for all implementations that hold a reference to this deferred.\n */\n protected _fileDeferred?: DeferredPromise<void>;\n /**\n * @param options The options to construct the class.\n * @throws If `valuesService` is specified but it doesn't have a `getValues`\n * method.\n */\n constructor({\n inject: { config, logger, frontendFs, valuesService },\n ...options\n }: HTMLGeneratorConstructorOptions) {\n this._config = config;\n this._logger = logger;\n this._frontendFs = frontendFs;\n this._valuesService = valuesService;\n this._options = deepAssignWithOverwrite(\n {\n template: 'index.tpl.html',\n file: 'index.html',\n silent: false,\n deleteTemplateAfter: true,\n replacePlaceholder: /\\{\\{appConfig(?:uration)?\\}\\}/,\n placeholderExpression: /\\{\\{(.*?)\\}\\}/gi,\n variableName: 'appConfig',\n configKeys: ['features', 'version', 'postMessagesPrefix'],\n },\n options,\n );\n\n if (this._valuesService && typeof this._valuesService.getValues !== 'function') {\n throw new Error('The HTMLGenerator values service must have a `getValues` method');\n }\n }\n /**\n * Gets a promise that will be resolved when the file has been generated.\n */\n whenReady(): Promise<void> {\n return this._fileDeferred ? this._fileDeferred.promise : Promise.resolve();\n }\n /**\n * Generates the HTML file.\n */\n async generateHTML(): Promise<void> {\n // The file is already generated, and since this is async, return the promise.\n if (this._fileReady) return undefined;\n // If the file is not ready, but the deferred exists, return the reference to the promise.\n if (this._fileDeferred) return this._fileDeferred.promise;\n // Create the deferred promise.\n this._fileDeferred = deferred<void>();\n const { template, deleteTemplateAfter, file, silent } = this._options;\n try {\n // Get the template.\n const templateContents = await this._frontendFs.read(template);\n // Get the values to replace.\n const values = await this._getValues();\n // Replace/process the template.\n const html = this._processHTML(templateContents, values);\n // Write it in the filesystem.\n await this._frontendFs.write(file, html);\n if (!silent) {\n this._logger.success(`The HTML file was successfully generated (${file})`);\n }\n // Delete the template, if specified by the options.\n if (deleteTemplateAfter) {\n await this._frontendFs.delete(template);\n if (!silent) {\n this._logger.info(`The HTML template was successfully removed (${template})`);\n }\n }\n\n // Switch the flag, resolve the deferred promise, and delete it.\n this._fileReady = true;\n this._fileDeferred!.resolve();\n this._fileDeferred = undefined;\n return undefined;\n } catch (error) {\n this._fileDeferred!.reject(error);\n this._fileDeferred = undefined;\n if (!silent) {\n this._logger.error('There was an error while generating the HTML');\n }\n throw error;\n }\n }\n /**\n * Gets the customization options.\n */\n get options(): Readonly<HTMLGeneratorOptions> {\n return deepAssignWithOverwrite({}, this._options);\n }\n /**\n * Helper method to get the values that will be replaced in the template. If a \"values\n * service\" was specified in the constructor, it will get the values from there,\n * otherwise, it will use the `configKeys` option to get the values from the\n * application configuration.\n */\n protected _getValues(): Promise<Record<string, unknown>> {\n if (this._valuesService) {\n return this._valuesService.getValues(this._options);\n }\n\n const { configKeys } = this._options;\n if (configKeys && configKeys.length) {\n return Promise.resolve(this._config.get(configKeys));\n }\n\n return Promise.resolve({});\n }\n /**\n * Processes the HTML template by replacing the placeholders with the actual values.\n *\n * @param template The template for the HTML file.\n * @param values The values dictionary that should be replaced in the template.\n */\n protected _processHTML(template: string, values: Record<string, unknown>) {\n const { replacePlaceholder, placeholderExpression, variableName } = this._options;\n const htmlObject = JSON.stringify(values);\n let code = template.replace(\n replacePlaceholder,\n `window.${variableName} = ${htmlObject}`,\n );\n const matches: Array<{ string: string; value: string }> = [];\n let match = placeholderExpression.exec(code);\n while (match) {\n const [string, value] = match;\n if (string && value) {\n matches.push({\n string,\n value,\n });\n }\n\n match = placeholderExpression.exec(code);\n }\n\n matches.forEach((info) => {\n code = code.replace(info.string, String(get(values, info.value)));\n });\n\n return code;\n }\n}\n/**\n * The service provider that once registered on the container will set an instance of\n * {@link HTMLGenerator} as the `htmlGenerator` service. it will also hook itself to the\n * `after-start` event of the application in order to trigger the generator of the HTML\n * file.\n *\n * @example\n *\n * <caption>Basic usage</caption>\n *\n * // Register it on the container\n * container.register(htmlGeneratorProvider);\n * // Getting access to the service instance\n * const htmlGenerator = container.get<HTMLGenerator>('htmlGenerator');\n *\n * @example\n *\n * <caption>Using with custom options</caption>\n *\n * container.register(\n * htmlGeneratorProvider({\n * serviceName: 'myHtmlGenerator',\n * valuesServiceName: 'myValuesService',\n * template: 'my-template.tpl.html',\n * }),\n * );\n *\n * @group Providers\n * @group Services/HTMLGenerator\n */\nexport const htmlGeneratorProvider = providerCreator(\n (options: HTMLGeneratorProviderOptions = {}) =>\n (app) => {\n const {\n serviceName = 'htmlGenerator',\n valuesServiceName = 'htmlGeneratorValues',\n ...rest\n } = options;\n app.set(\n serviceName,\n () =>\n new HTMLGenerator({\n inject: {\n config: app.get('config'),\n logger: app.get('logger'),\n frontendFs: app.get('frontendFs'),\n valuesService: app.try(valuesServiceName),\n },\n ...rest,\n }),\n );\n\n app.once('afterStart', () => {\n app.get<HTMLGenerator>(serviceName).generateHTML();\n });\n },\n);\n"],"mappings":";;;AAAA,SAAS,WAAW;AACpB,SAAS,+BAA+B;AACxC,SAAS,gBAAsC;AAC/C,SAAS,uBAAuB;AA4HzB,MAAM,cAAc;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAqCzB,YAAY;AAAA,IACV,QAAQ,EAAE,QAAQ,QAAQ,YAAY,cAAc;AAAA,IACpD,GAAG;AAAA,EACL,GAAoC;AApCpC;AAAA;AAAA;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B,gBAAQ,KAAK;AAAA,UACX;AAAA,UACA;AAAA,QACF,CAAC;AAAA,MACH;AAEA,cAAQ,sBAAsB,KAAK,IAAI;AAAA,IACzC;AAEA,YAAQ,QAAQ,CAAC,SAAS;AACxB,aAAO,KAAK,QAAQ,KAAK,QAAQ,OAAO,IAAI,QAAQ,KAAK,KAAK,CAAC,CAAC;AAAA,IAClE,CAAC;AAED,WAAO;AAAA,EACT;AACF;AA+BO,MAAM,wBAAwB;AAAA,EACnC,CAAC,UAAwC,CAAC,MACxC,CAAC,QAAQ;AACP,UAAM;AAAA,MACJ,cAAc;AAAA,MACd,oBAAoB;AAAA,MACpB,GAAG;AAAA,IACL,IAAI;AACJ,QAAI;AAAA,MACF;AAAA,MACA,MACE,IAAI,cAAc;AAAA,QAChB,QAAQ;AAAA,UACN,QAAQ,IAAI,IAAI,QAAQ;AAAA,UACxB,QAAQ,IAAI,IAAI,QAAQ;AAAA,UACxB,YAAY,IAAI,IAAI,YAAY;AAAA,UAChC,eAAe,IAAI,IAAI,iBAAiB;AAAA,QAC1C;AAAA,QACA,GAAG;AAAA,MACL,CAAC;AAAA,IACL;AAEA,QAAI,KAAK,cAAc,MAAM;AAC3B,UAAI,IAAmB,WAAW,EAAE,aAAa;AAAA,IACnD,CAAC;AAAA,EACH;AACJ;","names":[]}
@@ -1,11 +0,0 @@
1
- import "../../chunk-V6TY7KAL.js";
2
- import { providers } from "../../utils";
3
- import { htmlGeneratorProvider } from "./htmlGenerator";
4
- const htmlServicesProvider = providers({
5
- htmlGeneratorProvider
6
- });
7
- export * from "./htmlGenerator";
8
- export {
9
- htmlServicesProvider
10
- };
11
- //# sourceMappingURL=index.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../../src/services/html/index.ts"],"sourcesContent":["import { providers } from '../../utils';\nimport { htmlGeneratorProvider } from './htmlGenerator';\n/**\n * Registers all the HTML services on the container.\n *\n * - {@link HTMLGenerator | htmlGenerator}\n *\n * @example\n *\n * // Register the collection on the container\n * container.register(htmlServicesProvider);\n * // Getting access to one the services instance\n * const htmlGenerator = container.get<HTMLGenerator>('htmlGenerator');\n *\n * @group Providers\n */\nexport const htmlServicesProvider = providers({\n htmlGeneratorProvider,\n});\n\nexport * from './htmlGenerator';\n"],"mappings":";AAAA,SAAS,iBAAiB;AAC1B,SAAS,6BAA6B;AAe/B,MAAM,uBAAuB,UAAU;AAAA,EAC5C;AACF,CAAC;AAED,cAAc;","names":[]}
@@ -1,94 +0,0 @@
1
- import {
2
- __publicField
3
- } from "../../chunk-V6TY7KAL.js";
4
- import {
5
- APIClient as APIClientBase
6
- } from "@homer0/api-utils";
7
- import { deepAssignWithOverwrite } from "@homer0/deep-assign";
8
- import { providerCreator } from "../../utils";
9
- class APIClient extends APIClientBase {
10
- /**
11
- * @param options The options to construct the class.
12
- */
13
- constructor({ inject: { http, HTTPError }, ...rest }) {
14
- const { endpoints, gateway, url } = rest;
15
- const useEndpoints = endpoints || gateway;
16
- const apiConfig = {
17
- url,
18
- endpoints: useEndpoints
19
- };
20
- super({
21
- ...apiConfig,
22
- fetchClient: http.fetch
23
- });
24
- /**
25
- * The service that makes the requests to the API.
26
- */
27
- __publicField(this, "_http");
28
- /**
29
- * The class to generate possible errors in the requests.
30
- */
31
- __publicField(this, "_HTTPError");
32
- /**
33
- * The configuration of the API it uses.
34
- */
35
- __publicField(this, "_apiConfig");
36
- this._http = http;
37
- this._HTTPError = HTTPError;
38
- this._apiConfig = deepAssignWithOverwrite({}, apiConfig);
39
- }
40
- /**
41
- * The configuration for the API.
42
- */
43
- get apiConfig() {
44
- return deepAssignWithOverwrite({}, this._apiConfig);
45
- }
46
- /**
47
- * Tries to obtain a message from an error caused on a failed request.
48
- *
49
- * @param response The response from the failed request.
50
- */
51
- _getErrorMessageFromResponse(response) {
52
- const res = response;
53
- if (res.error) return res.error;
54
- if (res.data) {
55
- if (res.data.message) return res.data.message;
56
- if (res.data.error) return res.data.error;
57
- }
58
- return "Unexpected error";
59
- }
60
- /**
61
- * Generates an {@link _HTTPError} from the response of a failed request.
62
- *
63
- * @param response The response from the failed request.
64
- * @param status The status code of the response.
65
- */
66
- formatError(response, status) {
67
- return new this._HTTPError(this._getErrorMessageFromResponse(response), status);
68
- }
69
- }
70
- const apiClientProvider = providerCreator(
71
- (options = {}) => (app) => {
72
- const defaultName = "apiClient";
73
- const { serviceName = defaultName, clientClass: ClientClass = APIClient } = options;
74
- let { configSetting } = options;
75
- if (!configSetting) {
76
- configSetting = serviceName === defaultName ? "api" : serviceName;
77
- }
78
- app.set(
79
- serviceName,
80
- () => new ClientClass({
81
- inject: {
82
- http: app.get("http"),
83
- HTTPError: app.get("HTTPError")
84
- },
85
- ...app.getConfig(configSetting)
86
- })
87
- );
88
- }
89
- );
90
- export {
91
- APIClient,
92
- apiClientProvider
93
- };
94
- //# sourceMappingURL=apiClient.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../../src/services/http/apiClient.ts"],"sourcesContent":["import {\n APIClient as APIClientBase,\n type ErrorResponse,\n type APIClientOptions,\n type FetchClient,\n} from '@homer0/api-utils';\nimport { deepAssignWithOverwrite } from '@homer0/deep-assign';\nimport { providerCreator } from '../../utils';\nimport type { HTTP } from './http';\nimport type { HTTPErrorClass } from '../common';\n\nexport type { ErrorResponse };\n/**\n * The required settings needed to create the an API client.\n *\n * @group Services/APIClient\n */\nexport type APIClientConfig = Pick<APIClientOptions, 'url' | 'endpoints'>;\n/**\n * A dictionary of endpoints for the API client.\n * This is declared as standalone because it needs to reference them multiple times.\n *\n * @group Services/APIClient\n */\nexport type EndpointsType = APIClientOptions['endpoints'];\n/**\n * The format the settings needs to have in the application configuration in order to\n * create a valid API client.\n * The settings may include the endpoints dictionary in the `endpoints` property, or the\n * gateway `property`, with `endpoints` always having priority if both exists.\n * The reason for the `gateway` property to be valid, is in case the application also\n * implements a {@link GatewayController}, using the same property for both things will\n * help reduce the amount of duplicated definitions.\n *\n * @group Services/APIClient\n */\nexport type APIClientSettings = Omit<APIClientConfig, 'endpoints'> &\n (\n | {\n endpoints: EndpointsType;\n gateway?: EndpointsType;\n }\n | {\n endpoints?: EndpointsType;\n gateway: EndpointsType;\n }\n );\n/**\n * The options to construct a {@link APIClient}.\n *\n * @group Services/APIClient\n */\nexport type APIClientConstructorOptions = APIClientSettings & {\n /**\n * A dictionary with the dependencies to inject.\n */\n inject: {\n http: HTTP;\n HTTPError: HTTPErrorClass;\n };\n};\n/**\n * An API client for the application to use. What makes this service special is that it\n * formats received errors using the {@link _HTTPError} class, and as fetch client, it\n * uses the {@link HTTP} service, allowing the application to to internally handle all the\n * requests and responses.\n *\n * The only reason to use the class directly is if you want to subclass it, as you would\n * normally just register the {@link apiClientProvider}.\n *\n * @group Services\n * @group Services/APIClient\n */\nexport class APIClient extends APIClientBase {\n /**\n * The service that makes the requests to the API.\n */\n protected readonly _http: HTTP;\n /**\n * The class to generate possible errors in the requests.\n */\n protected readonly _HTTPError: HTTPErrorClass;\n /**\n * The configuration of the API it uses.\n */\n protected readonly _apiConfig: APIClientConfig;\n /**\n * @param options The options to construct the class.\n */\n constructor({ inject: { http, HTTPError }, ...rest }: APIClientConstructorOptions) {\n const { endpoints, gateway, url } = rest;\n const useEndpoints = (endpoints || gateway)!;\n const apiConfig = {\n url,\n endpoints: useEndpoints,\n };\n super({\n ...apiConfig,\n fetchClient: http.fetch as unknown as FetchClient,\n });\n\n this._http = http;\n this._HTTPError = HTTPError;\n this._apiConfig = deepAssignWithOverwrite({}, apiConfig);\n }\n /**\n * The configuration for the API.\n */\n get apiConfig(): Readonly<APIClientConfig> {\n return deepAssignWithOverwrite({}, this._apiConfig);\n }\n /**\n * Tries to obtain a message from an error caused on a failed request.\n *\n * @param response The response from the failed request.\n */\n protected _getErrorMessageFromResponse(response: unknown) {\n const res = response as {\n error?: string;\n data?: {\n message?: string;\n error?: string;\n };\n };\n if (res.error) return res.error;\n if (res.data) {\n if (res.data.message) return res.data.message;\n if (res.data.error) return res.data.error;\n }\n\n return 'Unexpected error';\n }\n /**\n * Generates an {@link _HTTPError} from the response of a failed request.\n *\n * @param response The response from the failed request.\n * @param status The status code of the response.\n */\n protected override formatError<ResponseType extends ErrorResponse>(\n response: ResponseType,\n status: number,\n ): Error {\n return new this._HTTPError(this._getErrorMessageFromResponse(response), status);\n }\n}\n/**\n * The options for the provider creator that registers an {@link APIClient} in the\n * container.\n * These options allow the application to register multiple instances for different APIs.\n *\n * @group Services/APIClient\n */\nexport type APIClientProviderOptions = {\n /**\n * The name of the service that will be registered into the app.\n *\n * @default 'apiClient'\n */\n serviceName?: string;\n /**\n * The name of the configuration setting that has the API information.\n *\n * @default 'api'\n */\n configSetting?: string;\n /**\n * The class the service will instantiate. It has to extend {@link APIClient}.\n *\n * @default APIClient\n */\n clientClass?: typeof APIClient;\n};\n/**\n * The provider creator to register an instance of {@link APIClient} on the container.\n *\n * @example\n *\n * <caption>Basic usage</caption>\n *\n * // Register it on the container\n * container.register(apiClientProvider);\n * // Getting access to the service instance\n * const apiClient = container.get<APIClient>('apiClient');\n *\n * @example\n *\n * <caption>With custom options</caption>\n *\n * container.register(\n * apiClientProvider({\n * serviceName: 'myApiClient',\n * configSetting: 'myApi',\n * }),\n * );\n *\n * @group Providers\n * @group Services/APIClient\n */\nexport const apiClientProvider = providerCreator(\n (options: APIClientProviderOptions = {}) =>\n (app) => {\n const defaultName = 'apiClient';\n const { serviceName = defaultName, clientClass: ClientClass = APIClient } = options;\n let { configSetting } = options;\n if (!configSetting) {\n configSetting = serviceName === defaultName ? 'api' : serviceName;\n }\n\n app.set(\n serviceName,\n () =>\n new ClientClass({\n inject: {\n http: app.get('http'),\n HTTPError: app.get('HTTPError'),\n },\n ...app.getConfig<APIClientSettings>(configSetting!),\n }),\n );\n },\n);\n"],"mappings":";;;AAAA;AAAA,EACE,aAAa;AAAA,OAIR;AACP,SAAS,+BAA+B;AACxC,SAAS,uBAAuB;AAkEzB,MAAM,kBAAkB,cAAc;AAAA;AAAA;AAAA;AAAA,EAgB3C,YAAY,EAAE,Q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,MACE,IAAI,YAAY;AAAA,QACd,QAAQ;AAAA,UACN,MAAM,IAAI,IAAI,MAAM;AAAA,UACpB,WAAW,IAAI,IAAI,WAAW;AAAA,QAChC;AAAA,QACA,GAAG,IAAI,UAA6B,aAAc;AAAA,MACpD,CAAC;AAAA,IACL;AAAA,EACF;AACJ;","names":[]}
@@ -1,180 +0,0 @@
1
- import {
2
- __publicField
3
- } from "../../chunk-V6TY7KAL.js";
4
- import urijs from "urijs";
5
- import { deepAssignWithOverwrite } from "@homer0/deep-assign";
6
- import { provider } from "../../utils";
7
- class HTTP {
8
- /**
9
- * @param options The options to construct the class.
10
- */
11
- constructor({ inject: { logger, nodeFetch }, ...options }) {
12
- /**
13
- * The service used to log information in the terminal.
14
- */
15
- __publicField(this, "_logger");
16
- /**
17
- * The node-fetch library. Since it's an ESM only module, Jimpex loads it on boot and makes
18
- * it available on the container.
19
- */
20
- __publicField(this, "_nodeFetch");
21
- /**
22
- * The service customization options.
23
- */
24
- __publicField(this, "_options");
25
- this._logger = logger;
26
- this._nodeFetch = nodeFetch;
27
- this._options = deepAssignWithOverwrite(
28
- {
29
- logRequests: false
30
- },
31
- options
32
- );
33
- this.fetch = this.fetch.bind(this);
34
- }
35
- /**
36
- * Makes a fetch request.
37
- *
38
- * @param url The URL to fetch.
39
- * @param options The custom options for the request.
40
- */
41
- async fetch(url, options = {}) {
42
- let useURL = url;
43
- if (options.qs) {
44
- useURL = urijs(url).query(options.qs).toString();
45
- }
46
- const fetchOptions = {
47
- method: (options.method || "get").toUpperCase(),
48
- body: options.body
49
- };
50
- let defaultHeaders;
51
- if (options.req) {
52
- defaultHeaders = this.getCustomHeadersFromRequest(options.req);
53
- const ip = this.getIPFromRequest(options.req);
54
- if (ip) {
55
- defaultHeaders["x-forwarded-for"] = ip;
56
- }
57
- }
58
- const headers = {
59
- ...defaultHeaders,
60
- ...options.headers
61
- };
62
- if (Object.keys(headers).length) {
63
- fetchOptions.headers = this.normalizeHeaders(headers);
64
- }
65
- const { logRequests } = this._options;
66
- if (logRequests) {
67
- this._logRequest(useURL, fetchOptions);
68
- }
69
- const response = await this._nodeFetch(useURL, fetchOptions);
70
- if (logRequests) {
71
- this._logResponse(response);
72
- }
73
- return response;
74
- }
75
- /**
76
- * Tries to get the IP address from a given request.
77
- *
78
- * @param req The request from which it will try to obtain the IP address.
79
- */
80
- getIPFromRequest(req) {
81
- const headerValue = req.headers["x-forwarded-for"];
82
- if (headerValue) {
83
- return String(headerValue);
84
- }
85
- return req?.connection?.remoteAddress || req?.socket?.remoteAddress;
86
- }
87
- /**
88
- * Creates a dictionary with all the custom headers a request has. By custom header it
89
- * means all the headers which name start with `x-`.
90
- *
91
- * @param req The request from which it will try to get the headers.
92
- * @param options The options to customize the behavior with certain headers.
93
- */
94
- getCustomHeadersFromRequest(req, options = {}) {
95
- const { includeXForwardedHeaders = false } = options;
96
- return Object.keys(req.headers).reduce((acc, headerName) => {
97
- if (headerName.startsWith("x-") && (includeXForwardedHeaders || !headerName.startsWith("x-forwarded-"))) {
98
- acc[headerName] = req.headers[headerName];
99
- }
100
- return acc;
101
- }, {});
102
- }
103
- /**
104
- * It takes a dictionary of headers and normalize the names so each word will start with
105
- * an upper case character. This is helpful in case you added custom headers and didn't
106
- * care about the casing, or when copying headers from a server request, as they all
107
- * come tranformed into lower case.
108
- *
109
- * @param headers The dictionary of headers to normalize.
110
- */
111
- normalizeHeaders(headers) {
112
- return Object.keys(headers).reduce((acc, name) => {
113
- const newName = name.split("-").map((part) => part.replace(/^(\w)/, (_, letter) => letter.toUpperCase())).join("-");
114
- acc[newName] = headers[name];
115
- return acc;
116
- }, {});
117
- }
118
- /**
119
- * The customization options.
120
- */
121
- get options() {
122
- return deepAssignWithOverwrite({}, this._options);
123
- }
124
- /**
125
- * Logs a request information into the terminal.
126
- *
127
- * @param url The request URL.
128
- * @param options The options for the request.
129
- */
130
- _logRequest(url, options) {
131
- const { method, headers } = options;
132
- const prefix = "REQUEST> ";
133
- const lines = ["--->>", `${prefix}${method} ${url}`];
134
- if (headers) {
135
- Object.keys(headers).forEach((header) => {
136
- const value = headers[header];
137
- lines.push(`${prefix}${header}: ${value}`);
138
- });
139
- }
140
- if (options.body) {
141
- lines.push(`${prefix}body: "${options.body}"`);
142
- }
143
- this._logger.info(lines);
144
- }
145
- /**
146
- * Logs a response information into the terminal.
147
- *
148
- * @param response The response to log.
149
- */
150
- _logResponse(response) {
151
- const prefix = "RESPONSE> ";
152
- const lines = [
153
- "<<---",
154
- `${prefix}${response.url}`,
155
- `${prefix}status: ${response.status}`
156
- ];
157
- response.headers.forEach((value, header) => {
158
- lines.push(`${prefix}${header}: ${value}`);
159
- });
160
- this._logger.info(lines);
161
- }
162
- }
163
- const httpProvider = provider((app) => {
164
- app.set("http", () => {
165
- const config = app.getConfig();
166
- const logRequests = config.get("debug.logRequests") === true;
167
- return new HTTP({
168
- inject: {
169
- logger: app.get("logger"),
170
- nodeFetch: app.get("node-fetch")
171
- },
172
- logRequests
173
- });
174
- });
175
- });
176
- export {
177
- HTTP,
178
- httpProvider
179
- };
180
- //# sourceMappingURL=http.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../../src/services/http/http.ts"],"sourcesContent":["import urijs from 'urijs';\nimport type { RequestInit, BodyInit } from 'node-fetch';\nimport { deepAssignWithOverwrite } from '@homer0/deep-assign';\nimport { provider } from '../../utils';\nimport { Logger, Request, HTTPResponse, NodeFetch } from '../../types';\n\n/**\n * The options to customize the service.\n *\n * @group Services/HTTP\n */\nexport type HTTPOptions = {\n /**\n * Whether or not the service should log the requests and their responses.\n */\n logRequests?: boolean;\n};\n/**\n * The options to construct a {@link HTTP}.\n *\n * @group Services/HTTP\n */\nexport type HTTPContructorOptions = Partial<HTTPOptions> & {\n /**\n * A dictionary with the dependencies to inject.\n */\n inject: {\n logger: Logger;\n nodeFetch: NodeFetch;\n };\n};\n/**\n * The allowed formats for the body of a request.\n *\n * @group Services/HTTP\n */\nexport type HTTPFetchBody = string | Record<string | number, unknown> | BodyInit;\n/**\n * The options for a request.\n *\n * @group Services/HTTP\n */\nexport type HTTPFetchOptions = {\n /**\n * The HTTP method.\n *\n * @default 'GET'\n */\n method?: string;\n /**\n * The headers dictionary.\n */\n headers?: Record<string, string>;\n /**\n * The body of the request.\n */\n body?: HTTPFetchBody;\n /**\n * A dictionary of query string parameters.\n */\n qs?: Record<string, unknown>;\n /**\n * A request object generated by the application. This can be used to copy information\n * like custom headers or the IP (for the X-Forwarded-For header).\n */\n req?: Request;\n};\n/**\n * The options for the method that extracts custom headers from a request.\n *\n * @group Services/HTTP\n */\nexport type GetCustomHeadersFromRequestOptions = {\n /**\n * Since the method considers all headers that start with `x-` as custom headers,\n * setting this to `false` is the only way to exclude `x-forwarded-` headers from the\n * list.\n *\n * @default false\n */\n includeXForwardedHeaders?: boolean;\n};\n/**\n * A set of utilities to work with HTTP requests and responses.\n *\n * @group Services\n * @group Services/HTTP\n */\nexport class HTTP {\n /**\n * The service used to log information in the terminal.\n */\n protected readonly _logger: Logger;\n /**\n * The node-fetch 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 _nodeFetch: NodeFetch;\n /**\n * The service customization options.\n */\n protected readonly _options: HTTPOptions;\n /**\n * @param options The options to construct the class.\n */\n constructor({ inject: { logger, nodeFetch }, ...options }: HTTPContructorOptions) {\n this._logger = logger;\n this._nodeFetch = nodeFetch;\n this._options = deepAssignWithOverwrite(\n {\n logRequests: false,\n },\n options,\n );\n\n this.fetch = this.fetch.bind(this);\n }\n /**\n * Makes a fetch request.\n *\n * @param url The URL to fetch.\n * @param options The custom options for the request.\n */\n async fetch(url: string, options: HTTPFetchOptions = {}): Promise<HTTPResponse> {\n let useURL = url;\n if (options.qs) {\n useURL = urijs(url).query(options.qs).toString();\n }\n\n const fetchOptions: RequestInit = {\n method: (options.method || 'get').toUpperCase(),\n body: options.body as BodyInit,\n };\n\n let defaultHeaders: Record<string, string> | undefined;\n if (options.req) {\n defaultHeaders = this.getCustomHeadersFromRequest(options.req);\n const ip = this.getIPFromRequest(options.req);\n if (ip) {\n defaultHeaders['x-forwarded-for'] = ip;\n }\n }\n const headers = {\n ...defaultHeaders,\n ...options.headers,\n };\n\n if (Object.keys(headers).length) {\n fetchOptions.headers = this.normalizeHeaders(headers);\n }\n\n const { logRequests } = this._options;\n if (logRequests) {\n this._logRequest(useURL, fetchOptions);\n }\n\n const response = await this._nodeFetch(useURL, fetchOptions);\n if (logRequests) {\n this._logResponse(response);\n }\n\n return response;\n }\n /**\n * Tries to get the IP address from a given request.\n *\n * @param req The request from which it will try to obtain the IP address.\n */\n getIPFromRequest(req: Request): string | undefined {\n const headerValue = req.headers['x-forwarded-for'];\n if (headerValue) {\n return String(headerValue);\n }\n\n return req?.connection?.remoteAddress || req?.socket?.remoteAddress;\n }\n /**\n * Creates a dictionary with all the custom headers a request has. By custom header it\n * means all the headers which name start with `x-`.\n *\n * @param req The request from which it will try to get the headers.\n * @param options The options to customize the behavior with certain headers.\n */\n getCustomHeadersFromRequest(\n req: Request,\n options: GetCustomHeadersFromRequestOptions = {},\n ): Record<string, string> {\n const { includeXForwardedHeaders = false } = options;\n return Object.keys(req.headers).reduce<Record<string, string>>((acc, headerName) => {\n if (\n headerName.startsWith('x-') &&\n (includeXForwardedHeaders || !headerName.startsWith('x-forwarded-'))\n ) {\n acc[headerName] = req.headers[headerName] as string;\n }\n return acc;\n }, {});\n }\n /**\n * It takes a dictionary of headers and normalize the names so each word will start with\n * an upper case character. This is helpful in case you added custom headers and didn't\n * care about the casing, or when copying headers from a server request, as they all\n * come tranformed into lower case.\n *\n * @param headers The dictionary of headers to normalize.\n */\n normalizeHeaders(headers: Record<string, string>): Record<string, string> {\n return Object.keys(headers).reduce<Record<string, string>>((acc, name) => {\n const newName = name\n .split('-')\n .map((part) => part.replace(/^(\\w)/, (_, letter) => letter.toUpperCase()))\n .join('-');\n\n acc[newName] = headers[name]!;\n return acc;\n }, {});\n }\n /**\n * The customization options.\n */\n get options(): Readonly<HTTPOptions> {\n return deepAssignWithOverwrite({}, this._options);\n }\n /**\n * Logs a request information into the terminal.\n *\n * @param url The request URL.\n * @param options The options for the request.\n */\n protected _logRequest(url: string, options: RequestInit): void {\n const { method, headers } = options;\n const prefix = 'REQUEST> ';\n const lines = ['--->>', `${prefix}${method} ${url}`];\n if (headers) {\n Object.keys(headers).forEach((header) => {\n const value = headers[header as keyof typeof headers];\n lines.push(`${prefix}${header}: ${value}`);\n });\n }\n\n if (options.body) {\n lines.push(`${prefix}body: \"${options.body}\"`);\n }\n\n this._logger.info(lines);\n }\n /**\n * Logs a response information into the terminal.\n *\n * @param response The response to log.\n */\n protected _logResponse(response: HTTPResponse) {\n const prefix = 'RESPONSE> ';\n const lines = [\n '<<---',\n `${prefix}${response.url}`,\n `${prefix}status: ${response.status}`,\n ];\n\n response.headers.forEach((value, header) => {\n lines.push(`${prefix}${header}: ${value}`);\n });\n\n this._logger.info(lines);\n }\n}\n/**\n * The service provider that once registered on the container will set an instance of\n * {@link HTTP} as the `http` service. The provider also checks the `debug.logRequests`\n * setting on the application configuration in order to enable or not the logging of\n * requests/responses.\n *\n * @example\n *\n * // Register it on the container\n * container.register(httpProvider);\n * // Getting access to the service instance\n * const http = container.get<HTTP>('http');\n *\n * @group Providers\n * @group Services/HTTP\n */\nexport const httpProvider = provider((app) => {\n app.set('http', () => {\n const config = app.getConfig();\n const logRequests = config.get<boolean | undefined>('debug.logRequests') === true;\n return new HTTP({\n inject: {\n logger: app.get('logger'),\n nodeFetch: app.get('node-fetch'),\n },\n logRequests,\n });\n });\n});\n"],"mappings":";;;AAAA,OAAO,WAAW;AAElB,SAAS,+BAA+B;AACxC,SAAS,gBAAgB;AAqFlB,MAAM,KAAK;AAAA;AAAA;AAAA;AAAA,EAiBhB,YAAY,EAAE,QAAQ,EAAE,QAAQ,UAAU,GAAG,GAAG,QAAQ,GAA0B;AAblF;AAAA;AAAA;AAAA,wBAAmB;AAKnB;AAAA;AAAA;AAAA;AAAA,wBAAmB;AAIn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,MAAM,KAAK,KAAK,EAAE;AAAA,MAC3C,CAAC;AAAA,IACH;AAEA,QAAI,QAAQ,MAAM;AAChB,YAAM,KAAK,GAAG,MAAM,UAAU,QAAQ,IAAI,GAAG;AAAA,IAC/C;AAEA,SAAK,QAAQ,KAAK,KAAK;AAAA,EACzB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMU,aAAa,UAAwB;AAC7C,UAAM,SAAS;AACf,UAAM,QAAQ;AAAA,MACZ;AAAA,MACA,GAAG,MAAM,GAAG,SAAS,GAAG;AAAA,MACxB,GAAG,MAAM,WAAW,SAAS,MAAM;AAAA,IACrC;AAEA,aAAS,QAAQ,QAAQ,CAAC,OAAO,WAAW;AAC1C,YAAM,KAAK,GAAG,MAAM,GAAG,MAAM,KAAK,KAAK,EAAE;AAAA,IAC3C,CAAC;AAED,SAAK,QAAQ,KAAK,KAAK;AAAA,EACzB;AACF;AAiBO,MAAM,eAAe,SAAS,CAAC,QAAQ;AAC5C,MAAI,IAAI,QAAQ,MAAM;AACpB,UAAM,SAAS,IAAI,UAAU;AAC7B,UAAM,cAAc,OAAO,IAAyB,mBAAmB,MAAM;AAC7E,WAAO,IAAI,KAAK;AAAA,MACd,QAAQ;AAAA,QACN,QAAQ,IAAI,IAAI,QAAQ;AAAA,QACxB,WAAW,IAAI,IAAI,YAAY;AAAA,MACjC;AAAA,MACA;AAAA,IACF,CAAC;AAAA,EACH,CAAC;AACH,CAAC;","names":[]}
@@ -1,17 +0,0 @@
1
- import "../../chunk-V6TY7KAL.js";
2
- import { providers } from "../../utils";
3
- import { apiClientProvider } from "./apiClient";
4
- import { httpProvider } from "./http";
5
- import { responsesBuilderProvider } from "./responsesBuilder";
6
- const httpServicesProvider = providers({
7
- apiClientProvider,
8
- httpProvider,
9
- responsesBuilderProvider
10
- });
11
- export * from "./apiClient";
12
- export * from "./http";
13
- export * from "./responsesBuilder";
14
- export {
15
- httpServicesProvider
16
- };
17
- //# sourceMappingURL=index.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../../src/services/http/index.ts"],"sourcesContent":["import { providers } from '../../utils';\nimport { apiClientProvider } from './apiClient';\nimport { httpProvider } from './http';\nimport { responsesBuilderProvider } from './responsesBuilder';\n/**\n * Registers all the HTTP services on the container.\n *\n * - {@link APIClient | apiClient}\n * - {@link HTTP | http}\n * - {@link ResponsesBuilder | responsesBuilder}\n *\n * @example\n *\n * // Register the collection on the container\n * container.register(httpServicesProvider);\n * // Getting access to one the services instance\n * const apiClient = container.get<APIClient>('apiClient');\n *\n * @group Providers\n */\nexport const httpServicesProvider = providers({\n apiClientProvider,\n httpProvider,\n responsesBuilderProvider,\n});\n\nexport * from './apiClient';\nexport * from './http';\nexport * from './responsesBuilder';\n"],"mappings":";AAAA,SAAS,iBAAiB;AAC1B,SAAS,yBAAyB;AAClC,SAAS,oBAAoB;AAC7B,SAAS,gCAAgC;AAiBlC,MAAM,uBAAuB,UAAU;AAAA,EAC5C;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAED,cAAc;AACd,cAAc;AACd,cAAc;","names":[]}
@@ -1,152 +0,0 @@
1
- import {
2
- __publicField
3
- } from "../../chunk-V6TY7KAL.js";
4
- import { provider } from "../../utils";
5
- const DEFAULT_CLOSE_DELAY_FOR_POST_MESSAGE = 700;
6
- class ResponsesBuilder {
7
- /**
8
- * @param options The options to construct the service.
9
- */
10
- constructor({ inject: { config, statuses } }) {
11
- /**
12
- * The application configuration, to get the `version` and the `postMessagesPrefix`.
13
- */
14
- __publicField(this, "_config");
15
- /**
16
- * The uility service to get HTTP status codes.
17
- */
18
- __publicField(this, "_statuses");
19
- this._config = config;
20
- this._statuses = statuses;
21
- }
22
- /**
23
- * Generates and send an HTML response that emits a post message.
24
- * The post message will be prefixed with the value of the configuration setting
25
- * `postMessagesPrefix`.
26
- *
27
- * @param options The options to customize how the HTML is generated.
28
- */
29
- htmlPostMessage(options) {
30
- const {
31
- res,
32
- title,
33
- message,
34
- status,
35
- target = "window.opener",
36
- close = true,
37
- closeDelay = DEFAULT_CLOSE_DELAY_FOR_POST_MESSAGE
38
- } = options;
39
- const prefix = this._config.get("postMessagesPrefix") ?? "";
40
- const closeCode = close ? `setTimeout(function() { window.close(); }, ${closeDelay});` : "";
41
- const html = this._htmlTemplate(
42
- title,
43
- `
44
- (function() {
45
- if (${target}) {
46
- ${target}.postMessage('${prefix}${message}', '*');
47
- ${closeCode}
48
- }
49
- })();
50
- `
51
- );
52
- const useStatus = typeof status === "undefined" ? this._statuses("ok") : this._normalizeStatus(status);
53
- res.setHeader("Content-Type", "text/html");
54
- res.setHeader("Cache-Control", "no-cache, max-age=0, must-revalidate, no-store");
55
- res.status(useStatus);
56
- res.write(html);
57
- res.end();
58
- }
59
- /**
60
- * Generates and sends a JSON response.
61
- *
62
- * @param options The options to customize how the JSON is generated.
63
- * @example
64
- *
65
- * <caption>The generated looks like this.</caption>
66
- *
67
- * {
68
- * metadata: {
69
- * version: 'dev',
70
- * status: 200,
71
- * },
72
- * data: { foo: 'bar' },
73
- * }
74
- *
75
- */
76
- json(options) {
77
- const { res, data, status, metadata = {} } = options;
78
- const useStatus = typeof status === "undefined" ? this._statuses("ok") : this._normalizeStatus(status);
79
- res.status(useStatus);
80
- res.json({
81
- metadata: {
82
- version: this._config.get("version"),
83
- status: useStatus,
84
- ...metadata
85
- },
86
- data
87
- });
88
- res.end();
89
- }
90
- /**
91
- * Generates a basic HTML template for the service to use when generating a post message
92
- * response.
93
- *
94
- * @param title The HTML `<title />` attribute.
95
- * @param code Javascript code to be wrapped on a `<script />` tag.
96
- */
97
- _htmlTemplate(title, code) {
98
- return `
99
- <!DOCTYPE html>
100
- <html>
101
- <head>
102
- <meta charset="utf-8" />
103
- <meta http-equiv="x-ua-compatible" content="ie=edge" />
104
- <meta name="viewport" content="width=device-width, initial-scale=1" />
105
- <title>${title}</title>
106
- </head>
107
- <body>
108
- <script type="text/javascript">
109
- ${code}
110
- </script>
111
- </body>
112
- </html>
113
- `;
114
- }
115
- /**
116
- * Utility method used to make sure a recevied status is a valid status code. If the
117
- * status is a string, the method will try to find the code from the `statuses` package.
118
- *
119
- * @param status The status to normalize.
120
- * @returns If `status` is a string, but there's no valid code, it will return 200.
121
- */
122
- _normalizeStatus(status) {
123
- let useStatus;
124
- try {
125
- if (typeof status === "string") {
126
- useStatus = this._statuses(status);
127
- } else {
128
- this._statuses(status);
129
- useStatus = status;
130
- }
131
- } catch {
132
- useStatus = this._statuses("ok");
133
- }
134
- return useStatus;
135
- }
136
- }
137
- const responsesBuilderProvider = provider((app) => {
138
- app.set(
139
- "responsesBuilder",
140
- () => new ResponsesBuilder({
141
- inject: {
142
- config: app.getConfig(),
143
- statuses: app.get("statuses")
144
- }
145
- })
146
- );
147
- });
148
- export {
149
- ResponsesBuilder,
150
- responsesBuilderProvider
151
- };
152
- //# sourceMappingURL=responsesBuilder.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../../src/services/http/responsesBuilder.ts"],"sourcesContent":["import type { Config, Response } from '../../types';\nimport { provider, type Statuses } from '../../utils';\n/**\n * The options to construct a {@link ResponsesBuilder}.\n *\n * @group Services/ResponsesBuilder\n */\nexport type ResponsesBuilderConstructorOptions = {\n /**\n * A dictionary with the dependencies to inject.\n */\n inject: {\n config: Config;\n statuses: Statuses;\n };\n};\n/**\n * The options to build a response for a post message.\n *\n * @group Services/ResponsesBuilder\n */\nexport type HTMLPostMessageResponseOptions = {\n /**\n * The response object generated by the application.\n */\n res: Response;\n /**\n * The title for the HTML.\n */\n title: string;\n /**\n * The contents of the post message.\n */\n message: string;\n /**\n * The status code for the response.\n *\n * @default 200\n */\n status?: number | string;\n /**\n * From which object will the `postMessage` method called from.\n *\n * @default 'window.opener'\n */\n target?: string;\n /**\n * Whether or not to call `window.close` after sending the message.\n *\n * @default true\n */\n close?: boolean;\n /**\n * In case `close` is set to `true`, this option is to specify how many milliseconds\n * should be waited before closing the window.\n *\n * @default 700\n */\n closeDelay?: number;\n};\n/**\n * The options to build a reponse for JSON.\n *\n * @group Services/ResponsesBuilder\n */\nexport type JSONResponseOptions = {\n /**\n * The response object generated by the application.\n */\n res: Response;\n /**\n * The actual data for the response. It will be added in a `data` property.\n */\n data: unknown;\n /**\n * The status code for the response.\n *\n * @default 200\n */\n status?: number | string;\n /**\n * Extra information to include inside the `metadata` object.\n */\n metadata?: object;\n};\n/**\n * The default time to wait before closing a window, in case it's enabled.\n */\nconst DEFAULT_CLOSE_DELAY_FOR_POST_MESSAGE = 700;\n/**\n * A utility service to build responses.\n *\n * @group Services\n * @group Services/ResponsesBuilder\n */\nexport class ResponsesBuilder {\n /**\n * The application configuration, to get the `version` and the `postMessagesPrefix`.\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 service.\n */\n constructor({ inject: { config, statuses } }: ResponsesBuilderConstructorOptions) {\n this._config = config;\n this._statuses = statuses;\n }\n /**\n * Generates and send an HTML response that emits a post message.\n * The post message will be prefixed with the value of the configuration setting\n * `postMessagesPrefix`.\n *\n * @param options The options to customize how the HTML is generated.\n */\n htmlPostMessage(options: HTMLPostMessageResponseOptions): void {\n const {\n res,\n title,\n message,\n status,\n target = 'window.opener',\n close = true,\n closeDelay = DEFAULT_CLOSE_DELAY_FOR_POST_MESSAGE,\n } = options;\n const prefix = this._config.get<string | undefined>('postMessagesPrefix') ?? '';\n const closeCode = close\n ? `setTimeout(function() { window.close(); }, ${closeDelay});`\n : '';\n\n const html = this._htmlTemplate(\n title,\n `\n (function() {\n if (${target}) {\n ${target}.postMessage('${prefix}${message}', '*');\n ${closeCode}\n }\n })();\n `,\n );\n\n const useStatus =\n typeof status === 'undefined'\n ? (this._statuses('ok') as number)\n : this._normalizeStatus(status);\n\n res.setHeader('Content-Type', 'text/html');\n res.setHeader('Cache-Control', 'no-cache, max-age=0, must-revalidate, no-store');\n res.status(useStatus);\n res.write(html);\n res.end();\n }\n /**\n * Generates and sends a JSON response.\n *\n * @param options The options to customize how the JSON is generated.\n * @example\n *\n * <caption>The generated looks like this.</caption>\n *\n * {\n * metadata: {\n * version: 'dev',\n * status: 200,\n * },\n * data: { foo: 'bar' },\n * }\n *\n */\n json(options: JSONResponseOptions): void {\n const { res, data, status, metadata = {} } = options;\n const useStatus =\n typeof status === 'undefined'\n ? (this._statuses('ok') as number)\n : this._normalizeStatus(status);\n\n res.status(useStatus);\n res.json({\n metadata: {\n version: this._config.get<string>('version'),\n status: useStatus,\n ...metadata,\n },\n data,\n });\n res.end();\n }\n /**\n * Generates a basic HTML template for the service to use when generating a post message\n * response.\n *\n * @param title The HTML `<title />` attribute.\n * @param code Javascript code to be wrapped on a `<script />` tag.\n */\n protected _htmlTemplate(title: string, code: string): string {\n return `\n <!DOCTYPE html>\n <html>\n <head>\n <meta charset=\"utf-8\" />\n <meta http-equiv=\"x-ua-compatible\" content=\"ie=edge\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <title>${title}</title>\n </head>\n <body>\n <script type=\"text/javascript\">\n ${code}\n </script>\n </body>\n </html>\n `;\n }\n /**\n * Utility method used to make sure a recevied status is a valid status code. If the\n * status is a string, the method will try to find the code from the `statuses` package.\n *\n * @param status The status to normalize.\n * @returns If `status` is a string, but there's no valid code, it will return 200.\n */\n protected _normalizeStatus(status: number | string): number {\n let useStatus: number;\n try {\n if (typeof status === 'string') {\n useStatus = this._statuses(status) as number;\n } else {\n this._statuses(status);\n useStatus = status;\n }\n } catch {\n useStatus = this._statuses('ok') as number;\n }\n\n return useStatus;\n }\n}\n/**\n * The service provider that once registered on the container will set an instance of\n * {@link ResponsesBuilder} as the `responsesBuilder` service.\n *\n * @example\n *\n * // Register it on the container\n * container.register(responsesBuilderProvider);\n * // Getting access to the service instance\n * const responsesBuilder = container.get<ResponsesBuilder>('responsesBuilder');\n *\n * @group Providers\n * @group Services/ResponsesBuilder\n */\nexport const responsesBuilderProvider = provider((app) => {\n app.set(\n 'responsesBuilder',\n () =>\n new ResponsesBuilder({\n inject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b,KAAK,UAAU,IAAI,IACpB,KAAK,iBAAiB,MAAM;AAElC,QAAI,OAAO,SAAS;AACpB,QAAI,KAAK;AAAA,MACP,UAAU;AAAA,QACR,SAAS,KAAK,QAAQ,IAAY,SAAS;AAAA,QAC3C,QAAQ;AAAA,QACR,GAAG;AAAA,MACL;AAAA,MACA;AAAA,IACF,CAAC;AACD,QAAI,IAAI;AAAA,EACV;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQU,cAAc,OAAe,MAAsB;AAC3D,WAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAOQ,KAAK;AAAA;AAAA;AAAA;AAAA,YAIZ,IAAI;AAAA;AAAA;AAAA;AAAA;AAAA,EAKd;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQU,iBAAiB,QAAiC;AAC1D,QAAI;AACJ,QAAI;AACF,UAAI,OAAO,WAAW,UAAU;AAC9B,oBAAY,KAAK,UAAU,MAAM;AAAA,MACnC,OAAO;AACL,aAAK,UAAU,MAAM;AACrB,oBAAY;AAAA,MACd;AAAA,IACF,QAAQ;AACN,kBAAY,KAAK,UAAU,IAAI;AAAA,IACjC;AAEA,WAAO;AAAA,EACT;AACF;AAeO,MAAM,2BAA2B,SAAS,CAAC,QAAQ;AACxD,MAAI;AAAA,IACF;AAAA,IACA,MACE,IAAI,iBAAiB;AAAA,MACnB,QAAQ;AAAA,QACN,QAAQ,IAAI,UAAU;AAAA,QACtB,UAAU,IAAI,IAAI,UAAU;AAAA,MAC9B;AAAA,IACF,CAAC;AAAA,EACL;AACF,CAAC;","names":[]}
@@ -1,6 +0,0 @@
1
- export * from "./common";
2
- export * from "./frontend";
3
- export * from "./html";
4
- export * from "./http";
5
- export * from "./utils";
6
- //# sourceMappingURL=index.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../src/services/index.ts"],"sourcesContent":["export * from './common';\nexport * from './frontend';\nexport * from './html';\nexport * from './http';\nexport * from './utils';\n"],"mappings":"AAAA,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;","names":[]}