jimpex 7.0.1 → 8.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 (388) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/LICENSE +1 -1
  3. package/README.md +446 -434
  4. package/dist/app/index.d.ts +13 -0
  5. package/dist/app/index.js +19 -0
  6. package/dist/app/index.js.map +1 -0
  7. package/dist/app/jimpex.d.ts +13 -0
  8. package/dist/app/jimpex.js +440 -0
  9. package/dist/app/jimpex.js.map +1 -0
  10. package/dist/controllers/common/config.d.ts +78 -0
  11. package/dist/controllers/common/config.js +89 -0
  12. package/dist/controllers/common/config.js.map +1 -0
  13. package/dist/controllers/common/health.d.ts +82 -0
  14. package/dist/controllers/common/health.js +97 -0
  15. package/dist/controllers/common/health.js.map +1 -0
  16. package/dist/controllers/common/index.d.ts +21 -0
  17. package/dist/controllers/common/index.js +21 -0
  18. package/dist/controllers/common/index.js.map +1 -0
  19. package/dist/controllers/common/statics.d.ts +215 -0
  20. package/dist/controllers/common/statics.js +202 -0
  21. package/dist/controllers/common/statics.js.map +1 -0
  22. package/dist/controllers/index.d.ts +24 -0
  23. package/dist/controllers/index.js +20 -0
  24. package/dist/controllers/index.js.map +1 -0
  25. package/dist/controllers/utils/gateway.d.ts +724 -0
  26. package/dist/controllers/utils/gateway.js +425 -0
  27. package/dist/controllers/utils/gateway.js.map +1 -0
  28. package/dist/controllers/utils/index.d.ts +16 -0
  29. package/dist/controllers/utils/index.js +19 -0
  30. package/dist/controllers/utils/index.js.map +1 -0
  31. package/dist/esm/app/index.js +2 -0
  32. package/dist/esm/app/index.js.map +1 -0
  33. package/dist/esm/app/jimpex.js +415 -0
  34. package/dist/esm/app/jimpex.js.map +1 -0
  35. package/dist/esm/chunk-T2T6Q22Z.js +11 -0
  36. package/dist/esm/chunk-T2T6Q22Z.js.map +1 -0
  37. package/dist/esm/controllers/common/config.js +62 -0
  38. package/dist/esm/controllers/common/config.js.map +1 -0
  39. package/dist/esm/controllers/common/health.js +70 -0
  40. package/dist/esm/controllers/common/health.js.map +1 -0
  41. package/dist/esm/controllers/common/index.js +4 -0
  42. package/dist/esm/controllers/common/index.js.map +1 -0
  43. package/dist/esm/controllers/common/statics.js +173 -0
  44. package/dist/esm/controllers/common/statics.js.map +1 -0
  45. package/dist/esm/controllers/index.js +3 -0
  46. package/dist/esm/controllers/index.js.map +1 -0
  47. package/dist/esm/controllers/utils/gateway.js +404 -0
  48. package/dist/esm/controllers/utils/gateway.js.map +1 -0
  49. package/dist/esm/controllers/utils/index.js +2 -0
  50. package/dist/esm/controllers/utils/index.js.map +1 -0
  51. package/dist/esm/index.js +7 -0
  52. package/dist/esm/index.js.map +1 -0
  53. package/dist/esm/middlewares/common/errorHandler.js +92 -0
  54. package/dist/esm/middlewares/common/errorHandler.js.map +1 -0
  55. package/dist/esm/middlewares/common/forceHTTPS.js +41 -0
  56. package/dist/esm/middlewares/common/forceHTTPS.js.map +1 -0
  57. package/dist/esm/middlewares/common/hsts.js +53 -0
  58. package/dist/esm/middlewares/common/hsts.js.map +1 -0
  59. package/dist/esm/middlewares/common/index.js +4 -0
  60. package/dist/esm/middlewares/common/index.js.map +1 -0
  61. package/dist/esm/middlewares/html/fastHTML.js +104 -0
  62. package/dist/esm/middlewares/html/fastHTML.js.map +1 -0
  63. package/dist/esm/middlewares/html/index.js +3 -0
  64. package/dist/esm/middlewares/html/index.js.map +1 -0
  65. package/dist/esm/middlewares/html/showHTML.js +68 -0
  66. package/dist/esm/middlewares/html/showHTML.js.map +1 -0
  67. package/dist/esm/middlewares/index.js +4 -0
  68. package/dist/esm/middlewares/index.js.map +1 -0
  69. package/dist/esm/middlewares/utils/index.js +2 -0
  70. package/dist/esm/middlewares/utils/index.js.map +1 -0
  71. package/dist/esm/middlewares/utils/versionValidator.js +101 -0
  72. package/dist/esm/middlewares/utils/versionValidator.js.map +1 -0
  73. package/dist/esm/services/common/appError.js +52 -0
  74. package/dist/esm/services/common/appError.js.map +1 -0
  75. package/dist/esm/services/common/httpError.js +19 -0
  76. package/dist/esm/services/common/httpError.js.map +1 -0
  77. package/dist/esm/services/common/index.js +17 -0
  78. package/dist/esm/services/common/index.js.map +1 -0
  79. package/dist/esm/services/common/sendFile.js +27 -0
  80. package/dist/esm/services/common/sendFile.js.map +1 -0
  81. package/dist/esm/services/frontend/frontendFs.js +38 -0
  82. package/dist/esm/services/frontend/frontendFs.js.map +1 -0
  83. package/dist/esm/services/frontend/index.js +11 -0
  84. package/dist/esm/services/frontend/index.js.map +1 -0
  85. package/dist/esm/services/html/htmlGenerator.js +144 -0
  86. package/dist/esm/services/html/htmlGenerator.js.map +1 -0
  87. package/dist/esm/services/html/index.js +11 -0
  88. package/dist/esm/services/html/index.js.map +1 -0
  89. package/dist/esm/services/http/apiClient.js +71 -0
  90. package/dist/esm/services/http/apiClient.js.map +1 -0
  91. package/dist/esm/services/http/http.js +125 -0
  92. package/dist/esm/services/http/http.js.map +1 -0
  93. package/dist/esm/services/http/index.js +17 -0
  94. package/dist/esm/services/http/index.js.map +1 -0
  95. package/dist/esm/services/http/responsesBuilder.js +105 -0
  96. package/dist/esm/services/http/responsesBuilder.js.map +1 -0
  97. package/dist/esm/services/index.js +6 -0
  98. package/dist/esm/services/index.js.map +1 -0
  99. package/dist/esm/services/utils/ensureBearerToken.js +78 -0
  100. package/dist/esm/services/utils/ensureBearerToken.js.map +1 -0
  101. package/dist/esm/services/utils/index.js +11 -0
  102. package/dist/esm/services/utils/index.js.map +1 -0
  103. package/dist/esm/types/events.js +1 -0
  104. package/dist/esm/types/events.js.map +1 -0
  105. package/dist/esm/types/express.js +1 -0
  106. package/dist/esm/types/express.js.map +1 -0
  107. package/dist/esm/types/http.js +1 -0
  108. package/dist/esm/types/http.js.map +1 -0
  109. package/dist/esm/types/index.js +7 -0
  110. package/dist/esm/types/index.js.map +1 -0
  111. package/dist/esm/types/options.js +1 -0
  112. package/dist/esm/types/options.js.map +1 -0
  113. package/dist/esm/types/utils.js +1 -0
  114. package/dist/esm/types/utils.js.map +1 -0
  115. package/dist/esm/types/wootils.js +1 -0
  116. package/dist/esm/types/wootils.js.map +1 -0
  117. package/dist/esm/utils/fns/index.js +5 -0
  118. package/dist/esm/utils/fns/index.js.map +1 -0
  119. package/dist/esm/utils/fns/others.js +6 -0
  120. package/dist/esm/utils/fns/others.js.map +1 -0
  121. package/dist/esm/utils/fns/routes.js +25 -0
  122. package/dist/esm/utils/fns/routes.js.map +1 -0
  123. package/dist/esm/utils/fns/statuses.js +6 -0
  124. package/dist/esm/utils/fns/statuses.js.map +1 -0
  125. package/dist/esm/utils/fns/text.js +6 -0
  126. package/dist/esm/utils/fns/text.js.map +1 -0
  127. package/dist/esm/utils/index.js +3 -0
  128. package/dist/esm/utils/index.js.map +1 -0
  129. package/dist/esm/utils/wrappers.js +41 -0
  130. package/dist/esm/utils/wrappers.js.map +1 -0
  131. package/dist/index.d.ts +46 -0
  132. package/dist/index.js +24 -0
  133. package/dist/index.js.map +1 -0
  134. package/dist/jimpex-7eaee271.d.ts +1278 -0
  135. package/dist/middlewares/common/errorHandler.d.ts +131 -0
  136. package/dist/middlewares/common/errorHandler.js +119 -0
  137. package/dist/middlewares/common/errorHandler.js.map +1 -0
  138. package/dist/middlewares/common/forceHTTPS.d.ts +68 -0
  139. package/dist/middlewares/common/forceHTTPS.js +68 -0
  140. package/dist/middlewares/common/forceHTTPS.js.map +1 -0
  141. package/dist/middlewares/common/hsts.d.ts +109 -0
  142. package/dist/middlewares/common/hsts.js +80 -0
  143. package/dist/middlewares/common/hsts.js.map +1 -0
  144. package/dist/middlewares/common/index.d.ts +21 -0
  145. package/dist/middlewares/common/index.js +21 -0
  146. package/dist/middlewares/common/index.js.map +1 -0
  147. package/dist/middlewares/html/fastHTML.d.ts +180 -0
  148. package/dist/middlewares/html/fastHTML.js +131 -0
  149. package/dist/middlewares/html/fastHTML.js.map +1 -0
  150. package/dist/middlewares/html/index.d.ts +21 -0
  151. package/dist/middlewares/html/index.js +20 -0
  152. package/dist/middlewares/html/index.js.map +1 -0
  153. package/dist/middlewares/html/showHTML.d.ts +127 -0
  154. package/dist/middlewares/html/showHTML.js +95 -0
  155. package/dist/middlewares/html/showHTML.js.map +1 -0
  156. package/dist/middlewares/index.d.ts +30 -0
  157. package/dist/middlewares/index.js +21 -0
  158. package/dist/middlewares/index.js.map +1 -0
  159. package/dist/middlewares/utils/index.d.ts +19 -0
  160. package/dist/middlewares/utils/index.js +19 -0
  161. package/dist/middlewares/utils/index.js.map +1 -0
  162. package/dist/middlewares/utils/versionValidator.d.ts +214 -0
  163. package/dist/middlewares/utils/versionValidator.js +128 -0
  164. package/dist/middlewares/utils/versionValidator.js.map +1 -0
  165. package/dist/services/common/appError.d.ts +138 -0
  166. package/dist/services/common/appError.js +80 -0
  167. package/dist/services/common/appError.js.map +1 -0
  168. package/dist/services/common/httpError.d.ts +79 -0
  169. package/dist/services/common/httpError.js +44 -0
  170. package/dist/services/common/httpError.js.map +1 -0
  171. package/dist/services/common/index.d.ts +47 -0
  172. package/dist/services/common/index.js +41 -0
  173. package/dist/services/common/index.js.map +1 -0
  174. package/dist/services/common/sendFile.d.ts +102 -0
  175. package/dist/services/common/sendFile.js +51 -0
  176. package/dist/services/common/sendFile.js.map +1 -0
  177. package/dist/services/frontend/frontendFs.d.ts +96 -0
  178. package/dist/services/frontend/frontendFs.js +71 -0
  179. package/dist/services/frontend/frontendFs.js.map +1 -0
  180. package/dist/services/frontend/index.d.ts +40 -0
  181. package/dist/services/frontend/index.js +35 -0
  182. package/dist/services/frontend/index.js.map +1 -0
  183. package/dist/services/html/htmlGenerator.d.ts +237 -0
  184. package/dist/services/html/htmlGenerator.js +171 -0
  185. package/dist/services/html/htmlGenerator.js.map +1 -0
  186. package/dist/services/html/index.d.ts +43 -0
  187. package/dist/services/html/index.js +35 -0
  188. package/dist/services/html/index.js.map +1 -0
  189. package/dist/services/http/apiClient.d.ts +169 -0
  190. package/dist/services/http/apiClient.js +96 -0
  191. package/dist/services/http/apiClient.js.map +1 -0
  192. package/dist/services/http/http.d.ts +175 -0
  193. package/dist/services/http/http.js +158 -0
  194. package/dist/services/http/http.js.map +1 -0
  195. package/dist/services/http/index.d.ts +50 -0
  196. package/dist/services/http/index.js +41 -0
  197. package/dist/services/http/index.js.map +1 -0
  198. package/dist/services/http/responsesBuilder.d.ts +178 -0
  199. package/dist/services/http/responsesBuilder.js +132 -0
  200. package/dist/services/http/responsesBuilder.js.map +1 -0
  201. package/dist/services/index.d.ts +33 -0
  202. package/dist/services/index.js +23 -0
  203. package/dist/services/index.js.map +1 -0
  204. package/dist/services/utils/ensureBearerToken.d.ts +157 -0
  205. package/dist/services/utils/ensureBearerToken.js +105 -0
  206. package/dist/services/utils/ensureBearerToken.js.map +1 -0
  207. package/dist/services/utils/index.d.ts +43 -0
  208. package/dist/services/utils/index.js +35 -0
  209. package/dist/services/utils/index.js.map +1 -0
  210. package/dist/types/events.d.ts +13 -0
  211. package/dist/types/events.js +17 -0
  212. package/dist/types/events.js.map +1 -0
  213. package/dist/types/express.d.ts +10 -0
  214. package/dist/types/express.js +17 -0
  215. package/dist/types/express.js.map +1 -0
  216. package/dist/types/http.d.ts +79 -0
  217. package/dist/types/http.js +17 -0
  218. package/dist/types/http.js.map +1 -0
  219. package/dist/types/index.d.ts +14 -0
  220. package/dist/types/index.js +24 -0
  221. package/dist/types/index.js.map +1 -0
  222. package/dist/types/options.d.ts +13 -0
  223. package/dist/types/options.js +17 -0
  224. package/dist/types/options.js.map +1 -0
  225. package/dist/types/utils.d.ts +48 -0
  226. package/dist/types/utils.js +17 -0
  227. package/dist/types/utils.js.map +1 -0
  228. package/dist/types/wootils.d.ts +4 -0
  229. package/dist/types/wootils.js +17 -0
  230. package/dist/types/wootils.js.map +1 -0
  231. package/dist/utils/fns/index.d.ts +5 -0
  232. package/dist/utils/fns/index.js +22 -0
  233. package/dist/utils/fns/index.js.map +1 -0
  234. package/dist/utils/fns/others.d.ts +17 -0
  235. package/dist/utils/fns/others.js +29 -0
  236. package/dist/utils/fns/others.js.map +1 -0
  237. package/dist/utils/fns/routes.d.ts +39 -0
  238. package/dist/utils/fns/routes.js +51 -0
  239. package/dist/utils/fns/routes.js.map +1 -0
  240. package/dist/utils/fns/statuses.d.ts +45 -0
  241. package/dist/utils/fns/statuses.js +35 -0
  242. package/dist/utils/fns/statuses.js.map +1 -0
  243. package/dist/utils/fns/text.d.ts +9 -0
  244. package/dist/utils/fns/text.js +29 -0
  245. package/dist/utils/fns/text.js.map +1 -0
  246. package/dist/utils/index.d.ts +18 -0
  247. package/dist/utils/index.js +20 -0
  248. package/dist/utils/index.js.map +1 -0
  249. package/dist/utils/wrappers.d.ts +13 -0
  250. package/dist/utils/wrappers.js +68 -0
  251. package/dist/utils/wrappers.js.map +1 -0
  252. package/examples/basic/404.html +12 -0
  253. package/examples/basic/README.md +30 -0
  254. package/examples/basic/app.ts +18 -0
  255. package/examples/basic/controller.ts +45 -0
  256. package/examples/basic/index.ts +19 -0
  257. package/examples/basic/middleware.ts +13 -0
  258. package/examples/basic/service.ts +11 -0
  259. package/package.json +59 -38
  260. package/src/app/index.ts +1 -0
  261. package/src/app/jimpex.ts +743 -0
  262. package/src/controllers/common/config.ts +115 -0
  263. package/src/controllers/common/health.ts +128 -0
  264. package/src/controllers/common/index.ts +3 -0
  265. package/src/controllers/common/statics.ts +380 -0
  266. package/src/controllers/index.ts +2 -0
  267. package/src/controllers/utils/gateway.ts +1186 -0
  268. package/src/controllers/utils/index.ts +1 -0
  269. package/src/index.ts +6 -0
  270. package/src/middlewares/common/errorHandler.ts +203 -0
  271. package/src/middlewares/common/forceHTTPS.ts +83 -0
  272. package/src/middlewares/common/hsts.ts +135 -0
  273. package/src/middlewares/common/index.ts +3 -0
  274. package/src/middlewares/html/fastHTML.ts +255 -0
  275. package/src/middlewares/html/index.ts +2 -0
  276. package/src/middlewares/html/showHTML.ts +165 -0
  277. package/src/middlewares/index.ts +3 -0
  278. package/src/middlewares/utils/index.ts +1 -0
  279. package/src/middlewares/utils/versionValidator.ts +289 -0
  280. package/src/services/common/appError.ts +158 -0
  281. package/src/services/common/httpError.ts +74 -0
  282. package/src/services/common/index.ts +29 -0
  283. package/src/services/common/sendFile.ts +106 -0
  284. package/src/services/frontend/frontendFs.ts +101 -0
  285. package/src/services/frontend/index.ts +21 -0
  286. package/src/services/html/htmlGenerator.ts +356 -0
  287. package/src/services/html/index.ts +21 -0
  288. package/src/services/http/apiClient.ts +221 -0
  289. package/src/services/http/http.ts +286 -0
  290. package/src/services/http/index.ts +29 -0
  291. package/src/services/http/responsesBuilder.ts +265 -0
  292. package/src/services/index.ts +5 -0
  293. package/src/services/utils/ensureBearerToken.ts +202 -0
  294. package/src/services/utils/index.ts +21 -0
  295. package/src/types/events.ts +303 -0
  296. package/src/types/express.ts +21 -0
  297. package/src/types/http.ts +77 -0
  298. package/src/types/index.ts +6 -0
  299. package/src/types/options.ts +248 -0
  300. package/src/types/utils.ts +52 -0
  301. package/src/types/wootils.ts +4 -0
  302. package/src/utils/fns/index.ts +4 -0
  303. package/src/utils/fns/others.ts +15 -0
  304. package/src/utils/fns/routes.ts +64 -0
  305. package/src/utils/fns/statuses.ts +44 -0
  306. package/src/utils/fns/text.ts +8 -0
  307. package/src/utils/index.ts +2 -0
  308. package/src/utils/wrappers.ts +537 -0
  309. package/tsconfig.json +5 -8
  310. package/tsup.config.ts +10 -0
  311. package/src/app/index.js +0 -692
  312. package/src/constants/eventNames.js +0 -48
  313. package/src/constants/index.js +0 -7
  314. package/src/controllers/common/configuration.js +0 -116
  315. package/src/controllers/common/health.js +0 -79
  316. package/src/controllers/common/index.js +0 -7
  317. package/src/controllers/common/statics.js +0 -336
  318. package/src/controllers/index.js +0 -9
  319. package/src/controllers/utils/gateway.js +0 -1039
  320. package/src/controllers/utils/index.js +0 -3
  321. package/src/index.js +0 -30
  322. package/src/middlewares/common/errorHandler.js +0 -185
  323. package/src/middlewares/common/forceHTTPS.js +0 -80
  324. package/src/middlewares/common/hsts.js +0 -122
  325. package/src/middlewares/common/index.js +0 -7
  326. package/src/middlewares/html/fastHTML.js +0 -298
  327. package/src/middlewares/html/index.js +0 -5
  328. package/src/middlewares/html/showHTML.js +0 -167
  329. package/src/middlewares/index.js +0 -11
  330. package/src/middlewares/utils/index.js +0 -3
  331. package/src/middlewares/utils/versionValidator.js +0 -261
  332. package/src/services/common/appError.js +0 -136
  333. package/src/services/common/httpError.js +0 -60
  334. package/src/services/common/index.js +0 -25
  335. package/src/services/common/sendFile.js +0 -68
  336. package/src/services/frontend/frontendFs.js +0 -85
  337. package/src/services/frontend/index.js +0 -17
  338. package/src/services/html/htmlGenerator.js +0 -391
  339. package/src/services/html/index.js +0 -17
  340. package/src/services/http/apiClient.js +0 -148
  341. package/src/services/http/http.js +0 -256
  342. package/src/services/http/index.js +0 -25
  343. package/src/services/http/responsesBuilder.js +0 -193
  344. package/src/services/index.js +0 -15
  345. package/src/services/utils/ensureBearerToken.js +0 -147
  346. package/src/services/utils/index.js +0 -19
  347. package/src/types.js +0 -377
  348. package/src/utils/functions.js +0 -78
  349. package/src/utils/wrappers.js +0 -131
  350. package/types/app/index.d.ts +0 -417
  351. package/types/constants/eventNames.d.ts +0 -93
  352. package/types/constants/index.d.ts +0 -2
  353. package/types/controllers/common/configuration.d.ts +0 -71
  354. package/types/controllers/common/health.d.ts +0 -55
  355. package/types/controllers/common/index.d.ts +0 -4
  356. package/types/controllers/common/statics.d.ts +0 -271
  357. package/types/controllers/index.d.ts +0 -3
  358. package/types/controllers/utils/gateway.d.ts +0 -947
  359. package/types/controllers/utils/index.d.ts +0 -2
  360. package/types/index.d.ts +0 -15
  361. package/types/middlewares/common/errorHandler.d.ts +0 -143
  362. package/types/middlewares/common/forceHTTPS.d.ts +0 -64
  363. package/types/middlewares/common/hsts.d.ts +0 -111
  364. package/types/middlewares/common/index.d.ts +0 -4
  365. package/types/middlewares/html/fastHTML.d.ts +0 -238
  366. package/types/middlewares/html/index.d.ts +0 -3
  367. package/types/middlewares/html/showHTML.d.ts +0 -128
  368. package/types/middlewares/index.d.ts +0 -4
  369. package/types/middlewares/utils/index.d.ts +0 -2
  370. package/types/middlewares/utils/versionValidator.d.ts +0 -247
  371. package/types/services/common/appError.d.ts +0 -89
  372. package/types/services/common/httpError.d.ts +0 -37
  373. package/types/services/common/index.d.ts +0 -18
  374. package/types/services/common/sendFile.d.ts +0 -56
  375. package/types/services/frontend/frontendFs.d.ts +0 -72
  376. package/types/services/frontend/index.d.ts +0 -3
  377. package/types/services/html/htmlGenerator.d.ts +0 -298
  378. package/types/services/html/index.d.ts +0 -3
  379. package/types/services/http/apiClient.d.ts +0 -141
  380. package/types/services/http/http.d.ts +0 -159
  381. package/types/services/http/index.d.ts +0 -18
  382. package/types/services/http/responsesBuilder.d.ts +0 -140
  383. package/types/services/index.d.ts +0 -6
  384. package/types/services/utils/ensureBearerToken.d.ts +0 -137
  385. package/types/services/utils/index.d.ts +0 -16
  386. package/types/types.d.ts +0 -280
  387. package/types/utils/functions.d.ts +0 -55
  388. package/types/utils/wrappers.d.ts +0 -127
@@ -0,0 +1,169 @@
1
+ import * as _homer0_jimple from '@homer0/jimple';
2
+ import { J as Jimpex } from '../../jimpex-7eaee271.js';
3
+ import { HTTPErrorClass } from '../common/httpError.js';
4
+ import { HTTP } from './http.js';
5
+ import { APIClientOptions, APIClient as APIClient$1, ErrorResponse } from '@homer0/api-utils';
6
+ export { ErrorResponse } from '@homer0/api-utils';
7
+ import '@homer0/events-hub';
8
+ import '../../types/express.js';
9
+ import 'express';
10
+ import '../../types/http.js';
11
+ import 'https';
12
+ import 'http';
13
+ import 'spdy';
14
+ import 'node-fetch';
15
+ import '@homer0/simple-config';
16
+ import '../../types/utils.js';
17
+ import '@homer0/simple-logger';
18
+ import '../../utils/fns/statuses.js';
19
+ import 'statuses';
20
+ import '../common/appError.js';
21
+
22
+ /**
23
+ * The required settings needed to create the an API client.
24
+ *
25
+ * @group Services/APIClient
26
+ */
27
+ type APIClientConfig = Pick<APIClientOptions, 'url' | 'endpoints'>;
28
+ /**
29
+ * A dictionary of endpoints for the API client.
30
+ * This is declared as standalone because it needs to reference them multiple times.
31
+ *
32
+ * @group Services/APIClient
33
+ */
34
+ type EndpointsType = APIClientOptions['endpoints'];
35
+ /**
36
+ * The format the settings needs to have in the application configuration in order to
37
+ * create a valid API client.
38
+ * The settings may include the endpoints dictionary in the `endpoints` property, or the
39
+ * gateway `property`, with `endpoints` always having priority if both exists.
40
+ * The reason for the `gateway` property to be valid, is in case the application also
41
+ * implements a {@link GatewayController}, using the same property for both things will
42
+ * help reduce the amount of duplicated definitions.
43
+ *
44
+ * @group Services/APIClient
45
+ */
46
+ type APIClientSettings = Omit<APIClientConfig, 'endpoints'> & ({
47
+ endpoints: EndpointsType;
48
+ gateway?: EndpointsType;
49
+ } | {
50
+ endpoints?: EndpointsType;
51
+ gateway: EndpointsType;
52
+ });
53
+ /**
54
+ * The options to construct a {@link APIClient}.
55
+ *
56
+ * @group Services/APIClient
57
+ */
58
+ type APIClientConstructorOptions = APIClientSettings & {
59
+ /**
60
+ * A dictionary with the dependencies to inject.
61
+ */
62
+ inject: {
63
+ http: HTTP;
64
+ HTTPError: HTTPErrorClass;
65
+ };
66
+ };
67
+ /**
68
+ * An API client for the application to use. What makes this service special is that it
69
+ * formats received errors using the {@link _HTTPError} class, and as fetch client, it
70
+ * uses the {@link HTTP} service, allowing the application to to internally handle all the
71
+ * requests and responses.
72
+ *
73
+ * The only reason to use the class directly is if you want to subclass it, as you would
74
+ * normally just register the {@link apiClientProvider}.
75
+ *
76
+ * @group Services
77
+ * @group Services/APIClient
78
+ */
79
+ declare class APIClient extends APIClient$1 {
80
+ /**
81
+ * The service that makes the requests to the API.
82
+ */
83
+ protected readonly _http: HTTP;
84
+ /**
85
+ * The class to generate possible errors in the requests.
86
+ */
87
+ protected readonly _HTTPError: HTTPErrorClass;
88
+ /**
89
+ * The configuration of the API it uses.
90
+ */
91
+ protected readonly _apiConfig: APIClientConfig;
92
+ /**
93
+ * @param options The options to construct the class.
94
+ */
95
+ constructor({ inject: { http, HTTPError }, ...rest }: APIClientConstructorOptions);
96
+ /**
97
+ * The configuration for the API.
98
+ */
99
+ get apiConfig(): Readonly<APIClientConfig>;
100
+ /**
101
+ * Tries to obtain a message from an error caused on a failed request.
102
+ *
103
+ * @param response The response from the failed request.
104
+ */
105
+ protected _getErrorMessageFromResponse(response: unknown): string;
106
+ /**
107
+ * Generates an {@link _HTTPError} from the response of a failed request.
108
+ *
109
+ * @param response The response from the failed request.
110
+ * @param status The status code of the response.
111
+ */
112
+ protected formatError<ResponseType extends ErrorResponse>(response: ResponseType, status: number): Error;
113
+ }
114
+ /**
115
+ * The options for the provider creator that registers an {@link APIClient} in the
116
+ * container.
117
+ * These options allow the application to register multiple instances for different APIs.
118
+ *
119
+ * @group Services/APIClient
120
+ */
121
+ type APIClientProviderOptions = {
122
+ /**
123
+ * The name of the service that will be registered into the app.
124
+ *
125
+ * @default 'apiClient'
126
+ */
127
+ serviceName?: string;
128
+ /**
129
+ * The name of the configuration setting that has the API information.
130
+ *
131
+ * @default 'api'
132
+ */
133
+ configSetting?: string;
134
+ /**
135
+ * The class the service will instantiate. It has to extend {@link APIClient}.
136
+ *
137
+ * @default APIClient
138
+ */
139
+ clientClass?: typeof APIClient;
140
+ };
141
+ /**
142
+ * The provider creator to register an instance of {@link APIClient} on the container.
143
+ *
144
+ * @example
145
+ *
146
+ * <caption>Basic usage</caption>
147
+ *
148
+ * // Register it on the container
149
+ * container.register(apiClientProvider);
150
+ * // Getting access to the service instance
151
+ * const apiClient = container.get<APIClient>('apiClient');
152
+ *
153
+ * @example
154
+ *
155
+ * <caption>With custom options</caption>
156
+ *
157
+ * container.register(
158
+ * apiClientProvider({
159
+ * serviceName: 'myApiClient',
160
+ * configSetting: 'myApi',
161
+ * }),
162
+ * );
163
+ *
164
+ * @group Providers
165
+ * @group Services/APIClient
166
+ */
167
+ declare const apiClientProvider: _homer0_jimple.ResourceCreator<"provider", "register", (options?: APIClientProviderOptions) => (app: Jimpex) => void, _homer0_jimple.ProviderRegisterFn<Jimpex>>;
168
+
169
+ export { APIClient, APIClientConfig, APIClientConstructorOptions, APIClientProviderOptions, APIClientSettings, EndpointsType, apiClientProvider };
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+ var __publicField = (obj, key, value) => {
21
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
22
+ return value;
23
+ };
24
+ var apiClient_exports = {};
25
+ __export(apiClient_exports, {
26
+ APIClient: () => APIClient,
27
+ apiClientProvider: () => apiClientProvider
28
+ });
29
+ module.exports = __toCommonJS(apiClient_exports);
30
+ var import_api_utils = require("@homer0/api-utils");
31
+ var import_deep_assign = require("@homer0/deep-assign");
32
+ var import_utils = require("../../utils");
33
+ class APIClient extends import_api_utils.APIClient {
34
+ constructor({ inject: { http, HTTPError }, ...rest }) {
35
+ const { endpoints, gateway, url } = rest;
36
+ const useEndpoints = endpoints || gateway;
37
+ const apiConfig = {
38
+ url,
39
+ endpoints: useEndpoints
40
+ };
41
+ super({
42
+ ...apiConfig,
43
+ fetchClient: http.fetch
44
+ });
45
+ __publicField(this, "_http");
46
+ __publicField(this, "_HTTPError");
47
+ __publicField(this, "_apiConfig");
48
+ this._http = http;
49
+ this._HTTPError = HTTPError;
50
+ this._apiConfig = (0, import_deep_assign.deepAssignWithOverwrite)({}, apiConfig);
51
+ }
52
+ get apiConfig() {
53
+ return (0, import_deep_assign.deepAssignWithOverwrite)({}, this._apiConfig);
54
+ }
55
+ _getErrorMessageFromResponse(response) {
56
+ const res = response;
57
+ if (res.error)
58
+ return res.error;
59
+ if (res.data) {
60
+ if (res.data.message)
61
+ return res.data.message;
62
+ if (res.data.error)
63
+ return res.data.error;
64
+ }
65
+ return "Unexpected error";
66
+ }
67
+ formatError(response, status) {
68
+ return new this._HTTPError(this._getErrorMessageFromResponse(response), status);
69
+ }
70
+ }
71
+ const apiClientProvider = (0, import_utils.providerCreator)(
72
+ (options = {}) => (app) => {
73
+ const defaultName = "apiClient";
74
+ const { serviceName = defaultName, clientClass: ClientClass = APIClient } = options;
75
+ let { configSetting } = options;
76
+ if (!configSetting) {
77
+ configSetting = serviceName === defaultName ? "api" : serviceName;
78
+ }
79
+ app.set(
80
+ serviceName,
81
+ () => new ClientClass({
82
+ inject: {
83
+ http: app.get("http"),
84
+ HTTPError: app.get("HTTPError")
85
+ },
86
+ ...app.getConfig(configSetting)
87
+ })
88
+ );
89
+ }
90
+ );
91
+ // Annotate the CommonJS export names for ESM import in node:
92
+ 0 && (module.exports = {
93
+ APIClient,
94
+ apiClientProvider
95
+ });
96
+ //# sourceMappingURL=apiClient.js.map
@@ -0,0 +1 @@
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;AAAA;AAAA;AAAA;AAAA;AAAA,uBAKO;AACP,yBAAwC;AACxC,mBAAgC;AAkEzB,MAAM,kBAAkB,iBAAAA,UAAc;AAAA,EAgB3C,YAAY,EAAE,QAAQ,EAAE,MAAM,UAAU,MAAM,KAAK,GAAgC;AACjF,UAAM,EAAE,WAAW,SAAS,IAAI,IAAI;AACpC,UAAM,eAAgB,aAAa;AACnC,UAAM,YAAY;AAAA,MAChB;AAAA,MACA,WAAW;AAAA,IACb;AACA,UAAM;AAAA,MACJ,GAAG;AAAA,MACH,aAAa,KAAK;AAAA,IACpB,CAAC;AAtBH,wBAAmB;AAInB,wBAAmB;AAInB,wBAAmB;AAgBjB,SAAK,QAAQ;AACb,SAAK,aAAa;AAClB,SAAK,iBAAa,4CAAwB,CAAC,GAAG,SAAS;AAAA,EACzD;AAAA,EAIA,IAAI,YAAuC;AACzC,eAAO,4CAAwB,CAAC,GAAG,KAAK,UAAU;AAAA,EACpD;AAAA,EAMU,6BAA6B,UAAmB;AACxD,UAAM,MAAM;AAOZ,QAAI,IAAI;AAAO,aAAO,IAAI;AAC1B,QAAI,IAAI,MAAM;AACZ,UAAI,IAAI,KAAK;AAAS,eAAO,IAAI,KAAK;AACtC,UAAI,IAAI,KAAK;AAAO,eAAO,IAAI,KAAK;AAAA,IACtC;AAEA,WAAO;AAAA,EACT;AAAA,EAOmB,YACjB,UACA,QACO;AACP,WAAO,IAAI,KAAK,WAAW,KAAK,6BAA6B,QAAQ,GAAG,MAAM;AAAA,EAChF;AACF;AAsDO,MAAM,wBAAoB;AAAA,EAC/B,CAAC,UAAoC,CAAC,MACpC,CAAC,QAAQ;AACP,UAAM,cAAc;AACpB,UAAM,EAAE,cAAc,aAAa,aAAa,cAAc,UAAU,IAAI;AAC5E,QAAI,EAAE,cAAc,IAAI;AACxB,QAAI,CAAC,eAAe;AAClB,sBAAgB,gBAAgB,cAAc,QAAQ;AAAA,IACxD;AAEA,QAAI;AAAA,MACF;AAAA,MACA,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":["APIClientBase"]}
@@ -0,0 +1,175 @@
1
+ import * as _homer0_jimple from '@homer0/jimple';
2
+ import { J as Jimpex } from '../../jimpex-7eaee271.js';
3
+ import { Request } from 'express';
4
+ import { BodyInit, Response, RequestInit } from 'node-fetch';
5
+ import { SimpleLogger } from '@homer0/simple-logger';
6
+ import '@homer0/events-hub';
7
+ import '../../types/express.js';
8
+ import '../../types/http.js';
9
+ import 'https';
10
+ import 'http';
11
+ import 'spdy';
12
+ import '@homer0/simple-config';
13
+ import '../../types/utils.js';
14
+
15
+ /**
16
+ * The options to customize the service.
17
+ *
18
+ * @group Services/HTTP
19
+ */
20
+ type HTTPOptions = {
21
+ /**
22
+ * Whether or not the service should log the requests and their responses.
23
+ */
24
+ logRequests?: boolean;
25
+ };
26
+ /**
27
+ * The options to construct a {@link HTTP}.
28
+ *
29
+ * @group Services/HTTP
30
+ */
31
+ type HTTPContructorOptions = Partial<HTTPOptions> & {
32
+ /**
33
+ * A dictionary with the dependencies to inject.
34
+ */
35
+ inject: {
36
+ logger: SimpleLogger;
37
+ };
38
+ };
39
+ /**
40
+ * The allowed formats for the body of a request.
41
+ *
42
+ * @group Services/HTTP
43
+ */
44
+ type HTTPFetchBody = string | Record<string | number, unknown> | BodyInit;
45
+ /**
46
+ * The options for a request.
47
+ *
48
+ * @group Services/HTTP
49
+ */
50
+ type HTTPFetchOptions = {
51
+ /**
52
+ * The HTTP method.
53
+ *
54
+ * @default 'GET'
55
+ */
56
+ method?: string;
57
+ /**
58
+ * The headers dictionary.
59
+ */
60
+ headers?: Record<string, string>;
61
+ /**
62
+ * The body of the request.
63
+ */
64
+ body?: HTTPFetchBody;
65
+ /**
66
+ * A dictionary of query string parameters.
67
+ */
68
+ qs?: Record<string, unknown>;
69
+ /**
70
+ * A request object generated by the application. This can be used to copy information
71
+ * like custom headers or the IP (for the X-Forwarded-For header).
72
+ */
73
+ req?: Request;
74
+ };
75
+ /**
76
+ * The options for the method that extracts custom headers from a request.
77
+ *
78
+ * @group Services/HTTP
79
+ */
80
+ type GetCustomHeadersFromRequestOptions = {
81
+ /**
82
+ * Since the method considers all headers that start with `x-` as custom headers,
83
+ * setting this to `false` is the only way to exclude `x-forwarded-` headers from the
84
+ * list.
85
+ *
86
+ * @default false
87
+ */
88
+ includeXForwardedHeaders?: boolean;
89
+ };
90
+ /**
91
+ * A set of utilities to work with HTTP requests and responses.
92
+ *
93
+ * @group Services
94
+ * @group Services/HTTP
95
+ */
96
+ declare class HTTP {
97
+ /**
98
+ * The service used to log information in the terminal.
99
+ */
100
+ protected readonly _logger: SimpleLogger;
101
+ /**
102
+ * The service customization options.
103
+ */
104
+ protected readonly _options: HTTPOptions;
105
+ /**
106
+ * @param options The options to construct the class.
107
+ */
108
+ constructor({ inject: { logger }, ...options }: HTTPContructorOptions);
109
+ /**
110
+ * Makes a fetch request.
111
+ *
112
+ * @param url The URL to fetch.
113
+ * @param options The custom options for the request.
114
+ */
115
+ fetch(url: string, options?: HTTPFetchOptions): Promise<Response>;
116
+ /**
117
+ * Tries to get the IP address from a given request.
118
+ *
119
+ * @param req The request from which it will try to obtain the IP address.
120
+ */
121
+ getIPFromRequest(req: Request): string | undefined;
122
+ /**
123
+ * Creates a dictionary with all the custom headers a request has. By custom header it
124
+ * means all the headers which name start with `x-`.
125
+ *
126
+ * @param req The request from which it will try to get the headers.
127
+ * @param options The options to customize the behavior with certain headers.
128
+ */
129
+ getCustomHeadersFromRequest(req: Request, options?: GetCustomHeadersFromRequestOptions): Record<string, string>;
130
+ /**
131
+ * It takes a dictionary of headers and normalize the names so each word will start with
132
+ * an upper case character. This is helpful in case you added custom headers and didn't
133
+ * care about the casing, or when copying headers from a server request, as they all
134
+ * come tranformed into lower case.
135
+ *
136
+ * @param headers The dictionary of headers to normalize.
137
+ */
138
+ normalizeHeaders(headers: Record<string, string>): Record<string, string>;
139
+ /**
140
+ * The customization options.
141
+ */
142
+ get options(): Readonly<HTTPOptions>;
143
+ /**
144
+ * Logs a request information into the terminal.
145
+ *
146
+ * @param url The request URL.
147
+ * @param options The options for the request.
148
+ */
149
+ protected _logRequest(url: string, options: RequestInit): void;
150
+ /**
151
+ * Logs a response information into the terminal.
152
+ *
153
+ * @param response The response to log.
154
+ */
155
+ protected _logResponse(response: Response): void;
156
+ }
157
+ /**
158
+ * The service provider that once registered on the container will set an instance of
159
+ * {@link HTTP} as the `http` service. The provider also checks the `debug.logRequests`
160
+ * setting on the application configuration in order to enable or not the logging of
161
+ * requests/responses.
162
+ *
163
+ * @example
164
+ *
165
+ * // Register it on the container
166
+ * container.register(httpProvider);
167
+ * // Getting access to the service instance
168
+ * const http = container.get<HTTP>('http');
169
+ *
170
+ * @group Providers
171
+ * @group Services/HTTP
172
+ */
173
+ declare const httpProvider: _homer0_jimple.Resource<"provider", "register", _homer0_jimple.ProviderRegisterFn<Jimpex>>;
174
+
175
+ export { GetCustomHeadersFromRequestOptions, HTTP, HTTPContructorOptions, HTTPFetchBody, HTTPFetchOptions, HTTPOptions, httpProvider };
@@ -0,0 +1,158 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
23
+ mod
24
+ ));
25
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
26
+ var __publicField = (obj, key, value) => {
27
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
28
+ return value;
29
+ };
30
+ var http_exports = {};
31
+ __export(http_exports, {
32
+ HTTP: () => HTTP,
33
+ httpProvider: () => httpProvider
34
+ });
35
+ module.exports = __toCommonJS(http_exports);
36
+ var import_node_fetch = __toESM(require("node-fetch"));
37
+ var import_urijs = __toESM(require("urijs"));
38
+ var import_deep_assign = require("@homer0/deep-assign");
39
+ var import_utils = require("../../utils");
40
+ class HTTP {
41
+ constructor({ inject: { logger }, ...options }) {
42
+ __publicField(this, "_logger");
43
+ __publicField(this, "_options");
44
+ this._logger = logger;
45
+ this._options = (0, import_deep_assign.deepAssignWithOverwrite)(
46
+ {
47
+ logRequests: false
48
+ },
49
+ options
50
+ );
51
+ this.fetch = this.fetch.bind(this);
52
+ }
53
+ async fetch(url, options = {}) {
54
+ let useURL = url;
55
+ if (options.qs) {
56
+ useURL = (0, import_urijs.default)(url).query(options.qs).toString();
57
+ }
58
+ const fetchOptions = {
59
+ method: (options.method || "get").toUpperCase(),
60
+ body: options.body
61
+ };
62
+ let defaultHeaders;
63
+ if (options.req) {
64
+ defaultHeaders = this.getCustomHeadersFromRequest(options.req);
65
+ const ip = this.getIPFromRequest(options.req);
66
+ if (ip) {
67
+ defaultHeaders["x-forwarded-for"] = ip;
68
+ }
69
+ }
70
+ const headers = {
71
+ ...defaultHeaders,
72
+ ...options.headers
73
+ };
74
+ if (Object.keys(headers).length) {
75
+ fetchOptions.headers = this.normalizeHeaders(headers);
76
+ }
77
+ const { logRequests } = this._options;
78
+ if (logRequests) {
79
+ this._logRequest(useURL, fetchOptions);
80
+ }
81
+ const response = await (0, import_node_fetch.default)(useURL, fetchOptions);
82
+ if (logRequests) {
83
+ this._logResponse(response);
84
+ }
85
+ return response;
86
+ }
87
+ getIPFromRequest(req) {
88
+ const headerValue = req.headers["x-forwarded-for"];
89
+ if (headerValue) {
90
+ return String(headerValue);
91
+ }
92
+ return req?.connection?.remoteAddress || req?.socket?.remoteAddress;
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
+ normalizeHeaders(headers) {
104
+ return Object.keys(headers).reduce((acc, name) => {
105
+ const newName = name.split("-").map((part) => part.replace(/^(\w)/, (_, letter) => letter.toUpperCase())).join("-");
106
+ acc[newName] = headers[name];
107
+ return acc;
108
+ }, {});
109
+ }
110
+ get options() {
111
+ return (0, import_deep_assign.deepAssignWithOverwrite)({}, this._options);
112
+ }
113
+ _logRequest(url, options) {
114
+ const { method, headers } = options;
115
+ const prefix = "REQUEST> ";
116
+ const lines = ["--->>", `${prefix}${method} ${url}`];
117
+ if (headers) {
118
+ Object.keys(headers).forEach((header) => {
119
+ const value = headers[header];
120
+ lines.push(`${prefix}${header}: ${value}`);
121
+ });
122
+ }
123
+ if (options.body) {
124
+ lines.push(`${prefix}body: "${options.body}"`);
125
+ }
126
+ this._logger.info(lines);
127
+ }
128
+ _logResponse(response) {
129
+ const prefix = "RESPONSE> ";
130
+ const lines = [
131
+ "<<---",
132
+ `${prefix}${response.url}`,
133
+ `${prefix}status: ${response.status}`
134
+ ];
135
+ response.headers.forEach((value, header) => {
136
+ lines.push(`${prefix}${header}: ${value}`);
137
+ });
138
+ this._logger.info(lines);
139
+ }
140
+ }
141
+ const httpProvider = (0, import_utils.provider)((app) => {
142
+ app.set("http", () => {
143
+ const config = app.getConfig();
144
+ const logRequests = config.get("debug.logRequests") === true;
145
+ return new HTTP({
146
+ inject: {
147
+ logger: app.get("logger")
148
+ },
149
+ logRequests
150
+ });
151
+ });
152
+ });
153
+ // Annotate the CommonJS export names for ESM import in node:
154
+ 0 && (module.exports = {
155
+ HTTP,
156
+ httpProvider
157
+ });
158
+ //# sourceMappingURL=http.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/services/http/http.ts"],"sourcesContent":["import fetch, { type RequestInit, type BodyInit } from 'node-fetch';\nimport urijs from 'urijs';\nimport { deepAssignWithOverwrite } from '@homer0/deep-assign';\nimport { provider } from '../../utils';\nimport { Logger, Request, HTTPResponse } from '../../types';\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 };\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 service customization options.\n */\n protected readonly _options: HTTPOptions;\n /**\n * @param options The options to construct the class.\n */\n constructor({ inject: { logger }, ...options }: HTTPContructorOptions) {\n this._logger = logger;\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 fetch(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 },\n logRequests,\n });\n });\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,wBAAuD;AACvD,mBAAkB;AAClB,yBAAwC;AACxC,mBAAyB;AAmFlB,MAAM,KAAK;AAAA,EAYhB,YAAY,EAAE,QAAQ,EAAE,OAAO,MAAM,QAAQ,GAA0B;AARvE,wBAAmB;AAInB,wBAAmB;AAKjB,SAAK,UAAU;AACf,SAAK,eAAW;AAAA,MACd;AAAA,QACE,aAAa;AAAA,MACf;AAAA,MACA;AAAA,IACF;AAEA,SAAK,QAAQ,KAAK,MAAM,KAAK,IAAI;AAAA,EACnC;AAAA,EAOA,MAAM,MAAM,KAAa,UAA4B,CAAC,GAA0B;AAC9E,QAAI,SAAS;AACb,QAAI,QAAQ,IAAI;AACd,mBAAS,aAAAA,SAAM,GAAG,EAAE,MAAM,QAAQ,EAAE,EAAE,SAAS;AAAA,IACjD;AAEA,UAAM,eAA4B;AAAA,MAChC,SAAS,QAAQ,UAAU,OAAO,YAAY;AAAA,MAC9C,MAAM,QAAQ;AAAA,IAChB;AAEA,QAAI;AACJ,QAAI,QAAQ,KAAK;AACf,uBAAiB,KAAK,4BAA4B,QAAQ,GAAG;AAC7D,YAAM,KAAK,KAAK,iBAAiB,QAAQ,GAAG;AAC5C,UAAI,IAAI;AACN,uBAAe,qBAAqB;AAAA,MACtC;AAAA,IACF;AACA,UAAM,UAAU;AAAA,MACd,GAAG;AAAA,MACH,GAAG,QAAQ;AAAA,IACb;AAEA,QAAI,OAAO,KAAK,OAAO,EAAE,QAAQ;AAC/B,mBAAa,UAAU,KAAK,iBAAiB,OAAO;AAAA,IACtD;AAEA,UAAM,EAAE,YAAY,IAAI,KAAK;AAC7B,QAAI,aAAa;AACf,WAAK,YAAY,QAAQ,YAAY;AAAA,IACvC;AAEA,UAAM,WAAW,UAAM,kBAAAC,SAAM,QAAQ,YAAY;AACjD,QAAI,aAAa;AACf,WAAK,aAAa,QAAQ;AAAA,IAC5B;AAEA,WAAO;AAAA,EACT;AAAA,EAMA,iBAAiB,KAAkC;AACjD,UAAM,cAAc,IAAI,QAAQ;AAChC,QAAI,aAAa;AACf,aAAO,OAAO,WAAW;AAAA,IAC3B;AAEA,WAAO,KAAK,YAAY,iBAAiB,KAAK,QAAQ;AAAA,EACxD;AAAA,EAQA,4BACE,KACA,UAA8C,CAAC,GACvB;AACxB,UAAM,EAAE,2BAA2B,MAAM,IAAI;AAC7C,WAAO,OAAO,KAAK,IAAI,OAAO,EAAE,OAA+B,CAAC,KAAK,eAAe;AAClF,UACE,WAAW,WAAW,IAAI,MACzB,4BAA4B,CAAC,WAAW,WAAW,cAAc,IAClE;AACA,YAAI,cAAc,IAAI,QAAQ;AAAA,MAChC;AACA,aAAO;AAAA,IACT,GAAG,CAAC,CAAC;AAAA,EACP;AAAA,EASA,iBAAiB,SAAyD;AACxE,WAAO,OAAO,KAAK,OAAO,EAAE,OAA+B,CAAC,KAAK,SAAS;AACxE,YAAM,UAAU,KACb,MAAM,GAAG,EACT,IAAI,CAAC,SAAS,KAAK,QAAQ,SAAS,CAAC,GAAG,WAAW,OAAO,YAAY,CAAC,CAAC,EACxE,KAAK,GAAG;AAEX,UAAI,WAAW,QAAQ;AACvB,aAAO;AAAA,IACT,GAAG,CAAC,CAAC;AAAA,EACP;AAAA,EAIA,IAAI,UAAiC;AACnC,eAAO,4CAAwB,CAAC,GAAG,KAAK,QAAQ;AAAA,EAClD;AAAA,EAOU,YAAY,KAAa,SAA4B;AAC7D,UAAM,EAAE,QAAQ,QAAQ,IAAI;AAC5B,UAAM,SAAS;AACf,UAAM,QAAQ,CAAC,SAAS,GAAG,SAAS,UAAU,KAAK;AACnD,QAAI,SAAS;AACX,aAAO,KAAK,OAAO,EAAE,QAAQ,CAAC,WAAW;AACvC,cAAM,QAAQ,QAAQ;AACtB,cAAM,KAAK,GAAG,SAAS,WAAW,OAAO;AAAA,MAC3C,CAAC;AAAA,IACH;AAEA,QAAI,QAAQ,MAAM;AAChB,YAAM,KAAK,GAAG,gBAAgB,QAAQ,OAAO;AAAA,IAC/C;AAEA,SAAK,QAAQ,KAAK,KAAK;AAAA,EACzB;AAAA,EAMU,aAAa,UAAwB;AAC7C,UAAM,SAAS;AACf,UAAM,QAAQ;AAAA,MACZ;AAAA,MACA,GAAG,SAAS,SAAS;AAAA,MACrB,GAAG,iBAAiB,SAAS;AAAA,IAC/B;AAEA,aAAS,QAAQ,QAAQ,CAAC,OAAO,WAAW;AAC1C,YAAM,KAAK,GAAG,SAAS,WAAW,OAAO;AAAA,IAC3C,CAAC;AAED,SAAK,QAAQ,KAAK,KAAK;AAAA,EACzB;AACF;AAiBO,MAAM,mBAAe,uBAAS,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,MAC1B;AAAA,MACA;AAAA,IACF,CAAC;AAAA,EACH,CAAC;AACH,CAAC;","names":["urijs","fetch"]}