@catbee/utils 0.0.8-rc.0 → 0.0.8-rc.2

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 (281) hide show
  1. package/README.md +25 -1
  2. package/build/esm/config.d.ts +0 -1
  3. package/build/esm/config.js +6 -7
  4. package/build/esm/index.d.ts +0 -1
  5. package/build/esm/index.js +0 -1
  6. package/build/esm/servers/server.builder.d.ts +0 -1
  7. package/build/esm/servers/server.builder.js +99 -147
  8. package/build/esm/servers/server.d.ts +0 -1
  9. package/build/esm/servers/server.js +591 -876
  10. package/build/esm/types/api-response.d.ts +0 -1
  11. package/build/esm/types/api-response.js +0 -1
  12. package/build/esm/types/index.d.ts +0 -1
  13. package/build/esm/types/index.js +0 -1
  14. package/build/esm/types/server.d.ts +0 -1
  15. package/build/esm/types/server.js +0 -1
  16. package/build/esm/utils/array.utils.d.ts +0 -1
  17. package/build/esm/utils/array.utils.js +48 -86
  18. package/build/esm/utils/async.utils.d.ts +0 -1
  19. package/build/esm/utils/async.utils.js +247 -524
  20. package/build/esm/utils/cache.utils.d.ts +0 -1
  21. package/build/esm/utils/cache.utils.js +96 -301
  22. package/build/esm/utils/context-store.utils.d.ts +0 -1
  23. package/build/esm/utils/context-store.utils.js +62 -79
  24. package/build/esm/utils/crypto.utils.d.ts +0 -1
  25. package/build/esm/utils/crypto.utils.js +78 -175
  26. package/build/esm/utils/date.utils.d.ts +0 -1
  27. package/build/esm/utils/date.utils.js +47 -53
  28. package/build/esm/utils/decorators.utils.d.ts +201 -5
  29. package/build/esm/utils/decorators.utils.js +632 -285
  30. package/build/esm/utils/dir.utils.d.ts +0 -1
  31. package/build/esm/utils/dir.utils.js +264 -786
  32. package/build/esm/utils/env.utils.d.ts +0 -1
  33. package/build/esm/utils/env.utils.js +180 -271
  34. package/build/esm/utils/exception.utils.d.ts +0 -1
  35. package/build/esm/utils/exception.utils.js +112 -289
  36. package/build/esm/utils/fs.utils.d.ts +0 -1
  37. package/build/esm/utils/fs.utils.js +169 -401
  38. package/build/esm/utils/http-status-codes.d.ts +0 -1
  39. package/build/esm/utils/http-status-codes.js +0 -1
  40. package/build/esm/utils/id.utils.d.ts +0 -1
  41. package/build/esm/utils/id.utils.js +5 -9
  42. package/build/esm/utils/logger.utils.d.ts +0 -1
  43. package/build/esm/utils/logger.utils.js +34 -71
  44. package/build/esm/utils/middleware.utils.d.ts +0 -1
  45. package/build/esm/utils/middleware.utils.js +65 -155
  46. package/build/esm/utils/obj.utils.d.ts +0 -1
  47. package/build/esm/utils/obj.utils.js +69 -176
  48. package/build/esm/utils/performance.utils.d.ts +0 -1
  49. package/build/esm/utils/performance.utils.js +92 -195
  50. package/build/esm/utils/request.utils.d.ts +0 -1
  51. package/build/esm/utils/request.utils.js +41 -74
  52. package/build/esm/utils/response.utils.d.ts +0 -1
  53. package/build/esm/utils/response.utils.js +84 -107
  54. package/build/esm/utils/stream.utils.d.ts +0 -1
  55. package/build/esm/utils/stream.utils.js +38 -113
  56. package/build/esm/utils/string.utils.d.ts +0 -1
  57. package/build/esm/utils/string.utils.js +6 -11
  58. package/build/esm/utils/type.utils.d.ts +0 -1
  59. package/build/esm/utils/type.utils.js +8 -12
  60. package/build/esm/utils/url.utils.d.ts +0 -1
  61. package/build/esm/utils/url.utils.js +49 -127
  62. package/build/esm/utils/validate.utils.d.ts +0 -1
  63. package/build/esm/utils/validate.utils.js +23 -40
  64. package/package.json +3 -33
  65. package/build/esm/config.js.map +0 -1
  66. package/build/esm/index.js.map +0 -1
  67. package/build/esm/servers/server.builder.js.map +0 -1
  68. package/build/esm/servers/server.js.map +0 -1
  69. package/build/esm/types/api-response.js.map +0 -1
  70. package/build/esm/types/index.js.map +0 -1
  71. package/build/esm/types/server.js.map +0 -1
  72. package/build/esm/utils/array.utils.js.map +0 -1
  73. package/build/esm/utils/async.utils.js.map +0 -1
  74. package/build/esm/utils/cache.utils.js.map +0 -1
  75. package/build/esm/utils/context-store.utils.js.map +0 -1
  76. package/build/esm/utils/crypto.utils.js.map +0 -1
  77. package/build/esm/utils/date.utils.js.map +0 -1
  78. package/build/esm/utils/decorators.utils.js.map +0 -1
  79. package/build/esm/utils/dir.utils.js.map +0 -1
  80. package/build/esm/utils/env.utils.js.map +0 -1
  81. package/build/esm/utils/exception.utils.js.map +0 -1
  82. package/build/esm/utils/fs.utils.js.map +0 -1
  83. package/build/esm/utils/http-status-codes.js.map +0 -1
  84. package/build/esm/utils/id.utils.js.map +0 -1
  85. package/build/esm/utils/logger.utils.js.map +0 -1
  86. package/build/esm/utils/middleware.utils.js.map +0 -1
  87. package/build/esm/utils/obj.utils.js.map +0 -1
  88. package/build/esm/utils/performance.utils.js.map +0 -1
  89. package/build/esm/utils/request.utils.js.map +0 -1
  90. package/build/esm/utils/response.utils.js.map +0 -1
  91. package/build/esm/utils/stream.utils.js.map +0 -1
  92. package/build/esm/utils/string.utils.js.map +0 -1
  93. package/build/esm/utils/type.utils.js.map +0 -1
  94. package/build/esm/utils/url.utils.js.map +0 -1
  95. package/build/esm/utils/validate.utils.js.map +0 -1
  96. package/build/esnext/config.d.ts +0 -122
  97. package/build/esnext/config.js +0 -133
  98. package/build/esnext/config.js.map +0 -1
  99. package/build/esnext/index.d.ts +0 -27
  100. package/build/esnext/index.js +0 -50
  101. package/build/esnext/index.js.map +0 -1
  102. package/build/esnext/servers/server.builder.d.ts +0 -508
  103. package/build/esnext/servers/server.builder.js +0 -657
  104. package/build/esnext/servers/server.builder.js.map +0 -1
  105. package/build/esnext/servers/server.d.ts +0 -256
  106. package/build/esnext/servers/server.js +0 -955
  107. package/build/esnext/servers/server.js.map +0 -1
  108. package/build/esnext/types/api-response.d.ts +0 -152
  109. package/build/esnext/types/api-response.js +0 -34
  110. package/build/esnext/types/api-response.js.map +0 -1
  111. package/build/esnext/types/index.d.ts +0 -125
  112. package/build/esnext/types/index.js +0 -25
  113. package/build/esnext/types/index.js.map +0 -1
  114. package/build/esnext/types/server.d.ts +0 -268
  115. package/build/esnext/types/server.js +0 -25
  116. package/build/esnext/types/server.js.map +0 -1
  117. package/build/esnext/utils/array.utils.d.ts +0 -168
  118. package/build/esnext/utils/array.utils.js +0 -345
  119. package/build/esnext/utils/array.utils.js.map +0 -1
  120. package/build/esnext/utils/async.utils.d.ts +0 -265
  121. package/build/esnext/utils/async.utils.js +0 -620
  122. package/build/esnext/utils/async.utils.js.map +0 -1
  123. package/build/esnext/utils/cache.utils.d.ts +0 -153
  124. package/build/esnext/utils/cache.utils.js +0 -293
  125. package/build/esnext/utils/cache.utils.js.map +0 -1
  126. package/build/esnext/utils/context-store.utils.d.ts +0 -189
  127. package/build/esnext/utils/context-store.utils.js +0 -289
  128. package/build/esnext/utils/context-store.utils.js.map +0 -1
  129. package/build/esnext/utils/crypto.utils.d.ts +0 -160
  130. package/build/esnext/utils/crypto.utils.js +0 -276
  131. package/build/esnext/utils/crypto.utils.js.map +0 -1
  132. package/build/esnext/utils/date.utils.d.ts +0 -159
  133. package/build/esnext/utils/date.utils.js +0 -384
  134. package/build/esnext/utils/date.utils.js.map +0 -1
  135. package/build/esnext/utils/decorators.utils.d.ts +0 -315
  136. package/build/esnext/utils/decorators.utils.js +0 -504
  137. package/build/esnext/utils/decorators.utils.js.map +0 -1
  138. package/build/esnext/utils/dir.utils.d.ts +0 -196
  139. package/build/esnext/utils/dir.utils.js +0 -477
  140. package/build/esnext/utils/dir.utils.js.map +0 -1
  141. package/build/esnext/utils/env.utils.d.ts +0 -377
  142. package/build/esnext/utils/env.utils.js +0 -785
  143. package/build/esnext/utils/env.utils.js.map +0 -1
  144. package/build/esnext/utils/exception.utils.d.ts +0 -230
  145. package/build/esnext/utils/exception.utils.js +0 -381
  146. package/build/esnext/utils/exception.utils.js.map +0 -1
  147. package/build/esnext/utils/fs.utils.d.ts +0 -164
  148. package/build/esnext/utils/fs.utils.js +0 -349
  149. package/build/esnext/utils/fs.utils.js.map +0 -1
  150. package/build/esnext/utils/http-status-codes.d.ts +0 -266
  151. package/build/esnext/utils/http-status-codes.js +0 -295
  152. package/build/esnext/utils/http-status-codes.js.map +0 -1
  153. package/build/esnext/utils/id.utils.d.ts +0 -36
  154. package/build/esnext/utils/id.utils.js +0 -84
  155. package/build/esnext/utils/id.utils.js.map +0 -1
  156. package/build/esnext/utils/logger.utils.d.ts +0 -160
  157. package/build/esnext/utils/logger.utils.js +0 -300
  158. package/build/esnext/utils/logger.utils.js.map +0 -1
  159. package/build/esnext/utils/middleware.utils.d.ts +0 -100
  160. package/build/esnext/utils/middleware.utils.js +0 -236
  161. package/build/esnext/utils/middleware.utils.js.map +0 -1
  162. package/build/esnext/utils/obj.utils.d.ts +0 -124
  163. package/build/esnext/utils/obj.utils.js +0 -413
  164. package/build/esnext/utils/obj.utils.js.map +0 -1
  165. package/build/esnext/utils/performance.utils.d.ts +0 -136
  166. package/build/esnext/utils/performance.utils.js +0 -271
  167. package/build/esnext/utils/performance.utils.js.map +0 -1
  168. package/build/esnext/utils/request.utils.d.ts +0 -86
  169. package/build/esnext/utils/request.utils.js +0 -186
  170. package/build/esnext/utils/request.utils.js.map +0 -1
  171. package/build/esnext/utils/response.utils.d.ts +0 -163
  172. package/build/esnext/utils/response.utils.js +0 -247
  173. package/build/esnext/utils/response.utils.js.map +0 -1
  174. package/build/esnext/utils/stream.utils.d.ts +0 -88
  175. package/build/esnext/utils/stream.utils.js +0 -210
  176. package/build/esnext/utils/stream.utils.js.map +0 -1
  177. package/build/esnext/utils/string.utils.d.ts +0 -93
  178. package/build/esnext/utils/string.utils.js +0 -165
  179. package/build/esnext/utils/string.utils.js.map +0 -1
  180. package/build/esnext/utils/type.utils.d.ts +0 -90
  181. package/build/esnext/utils/type.utils.js +0 -187
  182. package/build/esnext/utils/type.utils.js.map +0 -1
  183. package/build/esnext/utils/url.utils.d.ts +0 -141
  184. package/build/esnext/utils/url.utils.js +0 -304
  185. package/build/esnext/utils/url.utils.js.map +0 -1
  186. package/build/esnext/utils/validate.utils.d.ts +0 -177
  187. package/build/esnext/utils/validate.utils.js +0 -320
  188. package/build/esnext/utils/validate.utils.js.map +0 -1
  189. package/build/src/config.d.ts +0 -122
  190. package/build/src/config.js +0 -138
  191. package/build/src/config.js.map +0 -1
  192. package/build/src/index.d.ts +0 -27
  193. package/build/src/index.js +0 -69
  194. package/build/src/index.js.map +0 -1
  195. package/build/src/servers/server.builder.d.ts +0 -508
  196. package/build/src/servers/server.builder.js +0 -661
  197. package/build/src/servers/server.builder.js.map +0 -1
  198. package/build/src/servers/server.d.ts +0 -256
  199. package/build/src/servers/server.js +0 -962
  200. package/build/src/servers/server.js.map +0 -1
  201. package/build/src/types/api-response.d.ts +0 -152
  202. package/build/src/types/api-response.js +0 -37
  203. package/build/src/types/api-response.js.map +0 -1
  204. package/build/src/types/index.d.ts +0 -125
  205. package/build/src/types/index.js +0 -26
  206. package/build/src/types/index.js.map +0 -1
  207. package/build/src/types/server.d.ts +0 -268
  208. package/build/src/types/server.js +0 -26
  209. package/build/src/types/server.js.map +0 -1
  210. package/build/src/utils/array.utils.d.ts +0 -168
  211. package/build/src/utils/array.utils.js +0 -364
  212. package/build/src/utils/array.utils.js.map +0 -1
  213. package/build/src/utils/async.utils.d.ts +0 -265
  214. package/build/src/utils/async.utils.js +0 -641
  215. package/build/src/utils/async.utils.js.map +0 -1
  216. package/build/src/utils/cache.utils.d.ts +0 -153
  217. package/build/src/utils/cache.utils.js +0 -297
  218. package/build/src/utils/cache.utils.js.map +0 -1
  219. package/build/src/utils/context-store.utils.d.ts +0 -189
  220. package/build/src/utils/context-store.utils.js +0 -296
  221. package/build/src/utils/context-store.utils.js.map +0 -1
  222. package/build/src/utils/crypto.utils.d.ts +0 -160
  223. package/build/src/utils/crypto.utils.js +0 -293
  224. package/build/src/utils/crypto.utils.js.map +0 -1
  225. package/build/src/utils/date.utils.d.ts +0 -159
  226. package/build/src/utils/date.utils.js +0 -396
  227. package/build/src/utils/date.utils.js.map +0 -1
  228. package/build/src/utils/decorators.utils.d.ts +0 -315
  229. package/build/src/utils/decorators.utils.js +0 -516
  230. package/build/src/utils/decorators.utils.js.map +0 -1
  231. package/build/src/utils/dir.utils.d.ts +0 -196
  232. package/build/src/utils/dir.utils.js +0 -501
  233. package/build/src/utils/dir.utils.js.map +0 -1
  234. package/build/src/utils/env.utils.d.ts +0 -377
  235. package/build/src/utils/env.utils.js +0 -789
  236. package/build/src/utils/env.utils.js.map +0 -1
  237. package/build/src/utils/exception.utils.d.ts +0 -230
  238. package/build/src/utils/exception.utils.js +0 -407
  239. package/build/src/utils/exception.utils.js.map +0 -1
  240. package/build/src/utils/fs.utils.d.ts +0 -164
  241. package/build/src/utils/fs.utils.js +0 -372
  242. package/build/src/utils/fs.utils.js.map +0 -1
  243. package/build/src/utils/http-status-codes.d.ts +0 -266
  244. package/build/src/utils/http-status-codes.js +0 -298
  245. package/build/src/utils/http-status-codes.js.map +0 -1
  246. package/build/src/utils/id.utils.d.ts +0 -36
  247. package/build/src/utils/id.utils.js +0 -91
  248. package/build/src/utils/id.utils.js.map +0 -1
  249. package/build/src/utils/logger.utils.d.ts +0 -160
  250. package/build/src/utils/logger.utils.js +0 -346
  251. package/build/src/utils/logger.utils.js.map +0 -1
  252. package/build/src/utils/middleware.utils.d.ts +0 -100
  253. package/build/src/utils/middleware.utils.js +0 -244
  254. package/build/src/utils/middleware.utils.js.map +0 -1
  255. package/build/src/utils/obj.utils.d.ts +0 -124
  256. package/build/src/utils/obj.utils.js +0 -429
  257. package/build/src/utils/obj.utils.js.map +0 -1
  258. package/build/src/utils/performance.utils.d.ts +0 -136
  259. package/build/src/utils/performance.utils.js +0 -278
  260. package/build/src/utils/performance.utils.js.map +0 -1
  261. package/build/src/utils/request.utils.d.ts +0 -86
  262. package/build/src/utils/request.utils.js +0 -195
  263. package/build/src/utils/request.utils.js.map +0 -1
  264. package/build/src/utils/response.utils.d.ts +0 -163
  265. package/build/src/utils/response.utils.js +0 -260
  266. package/build/src/utils/response.utils.js.map +0 -1
  267. package/build/src/utils/stream.utils.d.ts +0 -88
  268. package/build/src/utils/stream.utils.js +0 -218
  269. package/build/src/utils/stream.utils.js.map +0 -1
  270. package/build/src/utils/string.utils.d.ts +0 -93
  271. package/build/src/utils/string.utils.js +0 -179
  272. package/build/src/utils/string.utils.js.map +0 -1
  273. package/build/src/utils/type.utils.d.ts +0 -90
  274. package/build/src/utils/type.utils.js +0 -196
  275. package/build/src/utils/type.utils.js.map +0 -1
  276. package/build/src/utils/url.utils.d.ts +0 -141
  277. package/build/src/utils/url.utils.js +0 -317
  278. package/build/src/utils/url.utils.js.map +0 -1
  279. package/build/src/utils/validate.utils.d.ts +0 -177
  280. package/build/src/utils/validate.utils.js +0 -345
  281. package/build/src/utils/validate.utils.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"date.utils.js","sourceRoot":"","sources":["../../../src/utils/date.utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAcH;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,UAAU,UAAU,CAAC,IAAmB,EAAE,OAA+B;IAA/B,wBAAA,EAAA,YAA+B;IACrE,IAAA,KAA4C,OAAO,OAA9B,EAArB,MAAM,mBAAG,YAAY,KAAA,EAAE,MAAM,GAAe,OAAO,OAAtB,EAAE,QAAQ,GAAK,OAAO,SAAZ,CAAa;IAC5D,IAAM,CAAC,GAAG,IAAI,YAAY,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC;IAEvD,uCAAuC;IACvC,IAAI,MAAM,KAAK,YAAY,EAAE,CAAC;QAC5B,IAAM,IAAI,GAAG,CAAC,CAAC,WAAW,EAAE,CAAC;QAC7B,IAAM,EAAE,GAAG,MAAM,CAAC,CAAC,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;QACrD,IAAM,EAAE,GAAG,MAAM,CAAC,CAAC,CAAC,OAAO,EAAE,CAA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AC5C,IAAM,CAAC,GAAG,IAAI,YAAY,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;IAC3D,OAAO,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,GAAG,KAAK,CAAC,CAAC,IAAI,CAAC,GAAG,GAAG,KAAK,CAAC,CAAC;AACzD,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,WAAW,CAAC,IAAmB,EAAE,KAAc;IAC7D,IAAI,IAAI,YAAY,IAAI,EAAE,CAAC;QACzB,KAAK,GAAG,IAAI,CAAC,QAAQ,EAAE,CAAC;QACxB,IAAI,GAAG,IAAI,CAAC,WAAW,EAAE,CAAC;IAC5B,CAAC;IAED,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;QACxB,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAC;IAC7D,CAAC;IAED,OAAO,IAAI,IAAI,CAAC,IAAI,EAAE,KAAK,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC;AAChD,CAAC","sourcesContent":["/*\n * The MIT License\n *\n * Copyright (c) 2025 Catbee Technologies. https://catbee-utils.npm.hprasath.com/license\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n/**\n * Format options for the formatDate function\n */\nexport interface DateFormatOptions {\n /** Date format pattern (default: 'yyyy-MM-dd') */\n format?: string;\n /** Locale to use for formatting (default: system locale) */\n locale?: string | string[];\n /** Time zone to use (default: system time zone) */\n timeZone?: string;\n}\n\n/**\n * Format a date according to the specified format pattern.\n *\n * @param date - Date to format\n * @param options - Formatting options\n * @returns Formatted date string\n *\n * @example\n * ```typescript\n * // Format as ISO date\n * formatDate(new Date(), { format: 'yyyy-MM-dd' }); // '2023-05-15'\n *\n * // Format with time\n * formatDate(new Date(), { format: 'yyyy-MM-dd HH:mm:ss' }); // '2023-05-15 14:30:22'\n *\n * // Format with locale\n * formatDate(new Date(), { format: 'PPPP', locale: 'fr-FR' }); // 'lundi 15 mai 2023'\n * ```\n */\nexport function formatDate(date: Date | number, options: DateFormatOptions = {}): string {\n const { format = 'yyyy-MM-dd', locale, timeZone } = options;\n const d = date instanceof Date ? date : new Date(date);\n\n // Custom formatter for common patterns\n if (format === 'yyyy-MM-dd') {\n const yyyy = d.getFullYear();\n const mm = String(d.getMonth() + 1).padStart(2, '0');\n const dd = String(d.getDate()).padStart(2, '0');\n return `${yyyy}-${mm}-${dd}`;\n }\n if (format === 'yyyy-MM-dd HH:mm:ss') {\n const yyyy = d.getFullYear();\n const mm = String(d.getMonth() + 1).padStart(2, '0');\n const dd = String(d.getDate()).padStart(2, '0');\n const HH = String(d.getHours()).padStart(2, '0');\n const MM = String(d.getMinutes()).padStart(2, '0');\n const SS = String(d.getSeconds()).padStart(2, '0');\n return `${yyyy}-${mm}-${dd} ${HH}:${MM}:${SS}`;\n }\n if (format === 'relative') {\n return formatRelativeTime(date);\n }\n\n // Fallback to Intl.DateTimeFormat for other formats\n return new Intl.DateTimeFormat(locale, {\n timeZone,\n year: format.includes('yyyy') || format.includes('y') ? 'numeric' : undefined,\n month: format.includes('MM') || format.includes('M') ? 'numeric' : undefined,\n day: format.includes('dd') || format.includes('d') ? 'numeric' : undefined,\n hour: format.includes('HH') || format.includes('H') ? 'numeric' : undefined,\n minute: format.includes('mm') || format.includes('m') ? 'numeric' : undefined,\n second: format.includes('ss') || format.includes('s') ? 'numeric' : undefined,\n hour12: !format.includes('HH') && !format.includes('H')\n }).format(d);\n}\n\n/**\n * Format a date as relative time (e.g., \"5 minutes ago\", \"in 3 days\").\n *\n * @param date - Date to format\n * @param now - Reference date (default: current time)\n * @param locale - Locale to use for formatting\n * @returns Formatted relative time string\n */\nexport function formatRelativeTime(\n date: Date | number,\n now: Date | number = new Date(),\n locale?: string | string[]\n): string {\n const d1 = date instanceof Date ? date : new Date(date);\n const d2 = now instanceof Date ? now : new Date(now);\n\n const diffMs = d1.getTime() - d2.getTime();\n const diffSecs = Math.round(diffMs / 1000);\n const diffMins = Math.round(diffSecs / 60);\n const diffHours = Math.round(diffMins / 60);\n const diffDays = Math.round(diffHours / 24);\n const diffMonths = Math.round(diffDays / 30);\n const diffYears = Math.round(diffDays / 365);\n\n const formatter = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' });\n\n if (Math.abs(diffSecs) < 60) return formatter.format(diffSecs, 'second');\n if (Math.abs(diffMins) < 60) return formatter.format(diffMins, 'minute');\n if (Math.abs(diffHours) < 24) return formatter.format(diffHours, 'hour');\n if (Math.abs(diffDays) < 30) return formatter.format(diffDays, 'day');\n if (Math.abs(diffMonths) < 12) return formatter.format(diffMonths, 'month');\n return formatter.format(diffYears, 'year');\n}\n\n/**\n * Parse a date string or timestamp into a Date object.\n *\n * @param input - Date string or timestamp to parse\n * @param fallback - Fallback date if parsing fails\n * @returns Parsed Date object or fallback\n *\n * @example\n * ```typescript\n * parseDate('2023-05-15'); // Date object for May 15, 2023\n * parseDate('invalid', new Date()); // Returns current date as fallback\n * ```\n */\nexport function parseDate(input: string | number, fallback?: Date): Date | null {\n if (typeof input === 'number') {\n return new Date(input);\n }\n\n try {\n const date = new Date(input);\n // Check if date is valid\n if (isNaN(date.getTime())) {\n return fallback || null;\n }\n return date;\n } catch {\n return fallback || null;\n }\n}\n\n/**\n * Calculate the difference between two dates in the specified unit.\n *\n * @param date1 - First date\n * @param date2 - Second date (default: current time)\n * @param unit - Unit of time for the difference\n * @returns Difference in the specified unit\n *\n * @example\n * ```typescript\n * // Get difference in days\n * dateDiff(new Date('2023-05-15'), new Date('2023-05-10'), 'days'); // 5\n *\n * // Get difference in hours\n * dateDiff(new Date('2023-05-15T10:00:00'), new Date('2023-05-15T06:00:00'), 'hours'); // 4\n * ```\n */\nexport function dateDiff(\n date1: Date | number,\n date2: Date | number = new Date(),\n unit: 'milliseconds' | 'seconds' | 'minutes' | 'hours' | 'days' | 'months' | 'years' = 'days'\n): number {\n const d1 = date1 instanceof Date ? date1 : new Date(date1);\n const d2 = date2 instanceof Date ? date2 : new Date(date2);\n\n const diffMs = d1.getTime() - d2.getTime();\n\n switch (unit) {\n case 'milliseconds':\n return diffMs;\n case 'seconds':\n return diffMs / 1000;\n case 'minutes':\n return diffMs / (1000 * 60);\n case 'hours':\n return diffMs / (1000 * 60 * 60);\n case 'days':\n return diffMs / (1000 * 60 * 60 * 24);\n case 'months':\n return (d1.getFullYear() - d2.getFullYear()) * 12 + d1.getMonth() - d2.getMonth();\n case 'years':\n return d1.getFullYear() - d2.getFullYear();\n default:\n throw new Error(`Unsupported unit: ${unit}`);\n }\n}\n\n/**\n * Add a specified amount of time to a date.\n *\n * @param date - Base date\n * @param amount - Amount to add (can be negative)\n * @param unit - Unit of time to add\n * @returns New date with the addition\n *\n * @example\n * ```typescript\n * // Add 5 days\n * addToDate(new Date('2023-05-15'), 5, 'days'); // Date for May 20, 2023\n *\n * // Subtract 2 hours\n * addToDate(new Date('2023-05-15T10:00:00'), -2, 'hours'); // Date for May 15, 2023 08:00:00\n * ```\n */\nexport function addToDate(\n date: Date | number,\n amount: number,\n unit: 'milliseconds' | 'seconds' | 'minutes' | 'hours' | 'days' | 'months' | 'years'\n): Date {\n const d = date instanceof Date ? new Date(date) : new Date(date);\n\n switch (unit) {\n case 'milliseconds':\n d.setMilliseconds(d.getMilliseconds() + amount);\n break;\n case 'seconds':\n d.setSeconds(d.getSeconds() + amount);\n break;\n case 'minutes':\n d.setMinutes(d.getMinutes() + amount);\n break;\n case 'hours':\n d.setHours(d.getHours() + amount);\n break;\n case 'days':\n d.setDate(d.getDate() + amount);\n break;\n case 'months': {\n const origDate = d.getDate();\n const origMonth = d.getMonth();\n d.setDate(1); // Prevent overflow\n d.setMonth(origMonth + amount);\n const lastDay = new Date(d.getFullYear(), d.getMonth() + 1, 0).getDate();\n d.setDate(Math.min(origDate, lastDay));\n break;\n }\n case 'years':\n d.setFullYear(d.getFullYear() + amount);\n break;\n default:\n throw new Error(`Unsupported unit: ${unit}`);\n }\n\n return d;\n}\n\n/**\n * Get the start of a time period containing the specified date.\n *\n * @param date - Date to get the start from\n * @param unit - Time unit\n * @returns Date object representing the start of the time unit\n *\n * @example\n * ```typescript\n * // Get start of day (midnight)\n * startOf(new Date('2023-05-15T14:30:00'), 'day'); // Date for May 15, 2023 00:00:00\n *\n * // Get start of month\n * startOf(new Date('2023-05-15'), 'month'); // Date for May 1, 2023\n * ```\n */\nexport function startOf(\n date: Date | number,\n unit: 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year'\n): Date {\n const d = date instanceof Date ? new Date(date) : new Date(date);\n\n switch (unit) {\n case 'second':\n d.setMilliseconds(0);\n break;\n case 'minute':\n d.setSeconds(0, 0);\n break;\n case 'hour':\n d.setMinutes(0, 0, 0);\n break;\n case 'day':\n d.setHours(0, 0, 0, 0);\n break;\n case 'week':\n d.setHours(0, 0, 0, 0);\n d.setDate(d.getDate() - d.getDay());\n break;\n case 'month':\n d.setDate(1);\n d.setHours(0, 0, 0, 0);\n break;\n case 'quarter':\n d.setMonth(Math.floor(d.getMonth() / 3) * 3, 1);\n d.setHours(0, 0, 0, 0);\n break;\n case 'year':\n d.setMonth(0, 1);\n d.setHours(0, 0, 0, 0);\n break;\n default:\n throw new Error(`Unsupported unit: ${unit}`);\n }\n\n return d;\n}\n\n/**\n * Get the end of a time period containing the specified date.\n *\n * @param date - Date to get the end from\n * @param unit - Time unit\n * @returns Date object representing the end of the time unit\n *\n * @example\n * ```typescript\n * // Get end of day (23:59:59.999)\n * endOf(new Date('2023-05-15T14:30:00'), 'day'); // Date for May 15, 2023 23:59:59.999\n *\n * // Get end of month\n * endOf(new Date('2023-05-15'), 'month'); // Date for May 31, 2023 23:59:59.999\n * ```\n */\nexport function endOf(\n date: Date | number,\n unit: 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year'\n): Date {\n const d = date instanceof Date ? new Date(date) : new Date(date);\n\n switch (unit) {\n case 'second':\n d.setMilliseconds(999);\n break;\n case 'minute':\n d.setSeconds(59, 999);\n break;\n case 'hour':\n d.setMinutes(59, 59, 999);\n break;\n case 'day':\n d.setHours(23, 59, 59, 999);\n break;\n case 'week':\n d.setDate(d.getDate() - d.getDay() + 6);\n d.setHours(23, 59, 59, 999);\n break;\n case 'month':\n d.setMonth(d.getMonth() + 1, 0);\n d.setHours(23, 59, 59, 999);\n break;\n case 'quarter':\n d.setMonth(Math.floor(d.getMonth() / 3) * 3 + 3, 0);\n d.setHours(23, 59, 59, 999);\n break;\n case 'year':\n d.setMonth(11, 31);\n d.setHours(23, 59, 59, 999);\n break;\n default:\n throw new Error(`Unsupported unit: ${unit}`);\n }\n\n return d;\n}\n\n/**\n * Check if a date is between two other dates.\n *\n * @param date - Date to check\n * @param start - Start date of the range\n * @param end - End date of the range\n * @param inclusive - Whether the comparison should be inclusive of start/end\n * @returns True if the date is within the range\n *\n * @example\n * ```typescript\n * const date = new Date('2023-05-15');\n * const start = new Date('2023-05-10');\n * const end = new Date('2023-05-20');\n *\n * isBetween(date, start, end); // true\n * ```\n */\nexport function isBetween(\n date: Date | number,\n start: Date | number,\n end: Date | number,\n inclusive: boolean = true\n): boolean {\n const d = date instanceof Date ? date.getTime() : date;\n const s = start instanceof Date ? start.getTime() : start;\n const e = end instanceof Date ? end.getTime() : end;\n\n return inclusive ? d >= s && d <= e : d > s && d < e;\n}\n\n/**\n * Check if a year is a leap year.\n *\n * @param year - Year to check (or date object)\n * @returns True if the year is a leap year\n */\nexport function isLeapYear(year: number | Date): boolean {\n const y = year instanceof Date ? year.getFullYear() : year;\n return (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0;\n}\n\n/**\n * Get the number of days in a month.\n *\n * @param year - Year\n * @param month - Month (0-11)\n * @returns Number of days in the month\n */\nexport function daysInMonth(year: number | Date, month?: number): number {\n if (year instanceof Date) {\n month = year.getMonth();\n year = year.getFullYear();\n }\n\n if (month === undefined) {\n throw new Error('Month is required when year is a number');\n }\n\n return new Date(year, month + 1, 0).getDate();\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"decorators.utils.js","sourceRoot":"","sources":["../../../src/utils/decorators.utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKH,OAAO,kBAAkB,CAAC;AAC1B,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAEvD,gBAAgB;AAChB,IAAM,UAAU,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AACpC,IAAM,cAAc,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC;AAC7C,IAAM,UAAU,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AACpC,IAAM,aAAa,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC;AACzC,IAAM,UAAU,GAA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AAI,KAAK,IAAI,OAAO,EAAE,CAAC;gCACrE,WAAW,GAAG,OAAO,CAAC,GAAa,CAAC;gCACpC,cAAc,GAAI,OAAO,CAAC,UAAqB,IAAI,QAAQ,CAAC,UAAU,CAAC;gCAC7E,sBAAO,GAAG,CAAC,QAAQ,CAAC,cAAc,EAAE,WAAW,CAAC,EAAC;4BACnD,CAAC;4BAED,IAAI,CAAC,GAAG,CAAC,WAAW,IAAI,OAAO,OAAO,KAAK,WAAW,EAAE,CAAC;gCACvD,IAAI,QAAQ;oCAAE,MAAA,GAAG,CAAC,MAAM,oDAAG,QAAQ,CAAC,CAAC;;oCACrC,KAAqB,KAAA,SAAA,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,CAAA;wCAAjC,KAAA,mBAAM,EAAL,CAAC,QAAA,EAAE,CAAC,QAAA;wCAA8B,MAAA,GAAG,CAAC,GAAG,oDAAG,CAAC,EAAE,CAAC,CAAC,CAAC;qCAAA;;;;;;;;;gCAC9D,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;4BACpB,CAAC;;;;4BACgB,eAAA,SAAA,UAAU,CAAA;;;;4BAAhB,EAAE;4BAAgB,qBAAM,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,OAAO,CAAC,EAAA;;4BAA3B,SAA2B,CAAC;;;;;;;;;;;;;;;;;;;4BAEzD,IAAI,CAAC,KAAG,CAAC,CAAC;;;;;iBAEb,CAAC;YAEF,CAAA,KAAC,MAAc,CAAA,CAAC,MAAM,CAAC,wCAAC,QAAQ,GAAG,IAAI,UAAK,WAAW,YAAE,OAAO,WAAE;QACpE,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/*\n * The MIT License\n *\n * Copyright (c) 2025 Catbee Technologies. https://catbee-utils.npm.hprasath.com/license\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\nimport type { RequestHandler, Router } from 'express';\nimport 'reflect-metadata';\nimport { HttpStatusCodes } from './http-status-codes';\nimport { ForbiddenException } from './exception.utils';\n\n// Metadata keys\nconst ROUTES_KEY = Symbol('routes');\nconst MIDDLEWARE_KEY = Symbol('middlewares');\nconst PARAMS_KEY = Symbol('params');\nconst HTTP_CODE_KEY = Symbol('httpCode');\nconst HEADER_KEY = Symbol('headers');\nconst BEFORE_KEY = Symbol('before');\nconst AFTER_KEY = Symbol('after');\nconst ROLES_KEY = Symbol('roles');\nconst REDIRECT_KEY = Symbol('redirect');\n\n/**\n * Supported HTTP methods for route decorators\n */\ntype HttpMethod = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'options' | 'head' | 'trace' | 'connect';\n\n/**\n * Represents a route definition for controller methods\n */\ninterface RouteDefinition {\n /** The URL path for this route */\n path: string;\n /** HTTP method for this route */\n method: HttpMethod;\n /** Name of the handler method in the controller class */\n handlerName: string;\n}\n\n/**\n * Parameter decoration definition for method parameters\n */\ninterface ParamDefinition {\n /** Parameter position in method signature */\n index: number;\n /** Type of parameter (query, body, etc.) */\n type: 'query' | 'param' | 'body' | 'req' | 'res';\n /** Optional key for extracting specific property */\n key?: string;\n}\n\n/**\n * Factory function that creates HTTP method decorators.\n *\n * @param method - HTTP method to create decorator for\n * @returns A method decorator function\n */\nfunction createRouteDecorator(method: HttpMethod) {\n return (path: string): MethodDecorator => {\n return (target, propertyKey, descriptor) => {\n const routes: RouteDefinition[] = Reflect.getMetadata(ROUTES_KEY, target.constructor) || [];\n routes.push({\n path,\n method,\n handlerName: propertyKey as string\n });\n Reflect.defineMetadata(ROUTES_KEY, routes, target.constructor);\n };\n };\n}\n\n/**\n * Decorator for GET HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Get('/users')\n * getUsers() {\n * return this.userService.findAll();\n * }\n * ```\n */\nexport const Get = createRouteDecorator('get');\n\n/**\n * Decorator for POST HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Post('/users')\n * createUser(@Body() userData: any) {\n * return this.userService.create(userData);\n * }\n * ```\n */\nexport const Post = createRouteDecorator('post');\n\n/**\n * Decorator for PUT HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n */\nexport const Put = createRouteDecorator('put');\n\n/**\n * Decorator for PATCH HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n */\nexport const Patch = createRouteDecorator('patch');\n\n/**\n * Decorator for DELETE HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n */\nexport const Delete = createRouteDecorator('delete');\n\n/**\n * Decorator for OPTIONS HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n */\nexport const Options = createRouteDecorator('options');\n\n/**\n * Decorator for HEAD HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n */\nexport const Head = createRouteDecorator('head');\n\n/**\n * Decorator for TRACE HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n */\nexport const Trace = createRouteDecorator('trace');\n\n/**\n * Decorator for CONNECT HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n */\nexport const Connect = createRouteDecorator('connect');\n\n/**\n * Decorator that marks a class as a controller with a base path.\n * Used as the entry point for routing configuration.\n *\n * @param basePath - Base URL path for all routes in this controller\n * @returns Class decorator\n *\n * @example\n * ```ts\n * @Controller('/api/users')\n * class UserController {\n * // Controller methods...\n * }\n * ```\n */\nexport function Controller(basePath: string): ClassDecorator {\n return target => {\n Reflect.defineMetadata('basePath', basePath, target);\n };\n}\n\n/**\n * Decorator that applies middleware to a controller method.\n * Multiple middlewares can be applied and will execute in order.\n *\n * @param middlewares - Express middleware functions to apply\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Get('/protected')\n * @Use(authMiddleware, loggingMiddleware)\n * getProtectedResource() {\n * // This route is protected by auth middleware\n * }\n * ```\n */\nexport function Use(...middlewares: RequestHandler[]): MethodDecorator {\n return (target, propertyKey, _descriptor) => {\n const existing: RequestHandler[] = Reflect.getMetadata(MIDDLEWARE_KEY, target, propertyKey as string) || [];\n Reflect.defineMetadata(MIDDLEWARE_KEY, [...existing, ...middlewares], target, propertyKey as string);\n };\n}\n\n/**\n * Factory function that creates parameter decorators.\n *\n * @param type - Parameter type to extract from request\n * @param key - Optional fixed key for extraction\n * @returns Parameter decorator function\n */\nfunction createParamDecorator(type: ParamDefinition['type'], key?: string) {\n return (paramKey?: string): ParameterDecorator => {\n return (target, propertyKey, parameterIndex) => {\n const params: ParamDefinition[] = Reflect.getMetadata(PARAMS_KEY, target, propertyKey as string) || [];\n // Ensure parameters are ordered by index\n params.push({ index: parameterIndex, type, key: paramKey || key });\n params.sort((a, b) => a.index - b.index);\n Reflect.defineMetadata(PARAMS_KEY, params, target, propertyKey as string);\n };\n };\n}\n\n/**\n * Decorator that extracts query parameters from request.\n *\n * @param paramKey - Optional key to extract specific query parameter\n * @returns Parameter decorator\n *\n * @example\n * ```ts\n * @Get('/search')\n * search(@Query('term') searchTerm: string) {\n * // searchTerm will contain the value of req.query.term\n * }\n * ```\n */\nexport const Query = createParamDecorator('query');\n\n/**\n * Decorator that extracts route parameters from request.\n *\n * @param paramKey - Optional key to extract specific route parameter\n * @returns Parameter decorator\n *\n * @example\n * ```ts\n * @Get('/users/:id')\n * getUser(@Param('id') userId: string) {\n * // userId will contain the value of req.params.id\n * }\n * ```\n */\nexport const Param = createParamDecorator('param');\n\n/**\n * Decorator that extracts body or body property from request.\n *\n * @param paramKey - Optional key to extract specific body property\n * @returns Parameter decorator\n *\n * @example\n * ```ts\n * @Post('/users')\n * createUser(@Body() userData: any) {\n * // userData will contain the entire req.body\n * }\n *\n * @Post('/update')\n * updateName(@Body('name') name: string) {\n * // name will contain the value of req.body.name\n * }\n * ```\n */\nexport const Body = createParamDecorator('body');\n\n/**\n * Decorator that injects the entire request object.\n *\n * @returns Parameter decorator\n *\n * @example\n * ```ts\n * @Get('/complex')\n * complex(@Req() req: Request) {\n * // Access the full request object\n * console.log(req.headers);\n * }\n * ```\n */\nexport const Req = createParamDecorator('req');\n\n/**\n * Decorator that injects the response object.\n *\n * @returns Parameter decorator\n *\n * @example\n * ```ts\n * @Get('/custom')\n * custom(@Res() res: Response) {\n * // Direct access to response object\n * return res.status(201).send('Created');\n * }\n * ```\n */\nexport const Res = createParamDecorator('res');\n\n/**\n * Decorator that sets a custom HTTP status code for a response.\n *\n * @param status - HTTP status code to use\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Post('/users')\n * @HttpCode(201)\n * createUser(@Body() userData: any) {\n * // Response will have 201 Created status code\n * return { id: '123', ...userData };\n * }\n * ```\n */\nexport function HttpCode(status: number): MethodDecorator {\n return (target, propertyKey, _descriptor) => {\n Reflect.defineMetadata(HTTP_CODE_KEY, status, target, propertyKey as string);\n };\n}\n\n/**\n * Decorator that adds a custom HTTP header to the response.\n *\n * @param name - Header name\n * @param value - Header value\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Get('/data')\n * @Header('Cache-Control', 'max-age=60')\n * getData() {\n * // Response will include the Cache-Control header\n * return { data: '...' };\n * }\n * ```\n */\nexport function Header(name: string, value: string): MethodDecorator {\n return (target, propertyKey, _descriptor) => {\n const headers: Record<string, string> = Reflect.getMetadata(HEADER_KEY, target, propertyKey as string) || {};\n headers[name] = value;\n Reflect.defineMetadata(HEADER_KEY, headers, target, propertyKey as string);\n };\n}\n\n/**\n * Decorator that registers a function to run before route handler execution.\n * Useful for pre-processing or logging.\n *\n * @param fn - Function to execute before the handler\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Get('/users/:id')\n * @Before((req, res) => console.log(`Accessing user ${req.params.id}`))\n * getUser(@Param('id') id: string) {\n * // Function will log before this handler runs\n * }\n * ```\n */\nexport function Before(fn: Function): MethodDecorator {\n return (target, propertyKey, _descriptor) => {\n const hooks: Function[] = Reflect.getMetadata(BEFORE_KEY, target, propertyKey as string) || [];\n hooks.push(fn);\n Reflect.defineMetadata(BEFORE_KEY, hooks, target, propertyKey as string);\n };\n}\n\n/**\n * Decorator that registers a function to run after route handler execution.\n * Can access the handler's result.\n *\n * @param fn - Function to execute after the handler\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Get('/users/:id')\n * @After((req, res, result) => console.log(`User data sent: ${JSON.stringify(result)}`))\n * getUser(@Param('id') id: string) {\n * // After this handler, the function will log the returned data\n * return { id, name: 'Example' };\n * }\n * ```\n */\nexport function After(fn: Function): MethodDecorator {\n return (target, propertyKey, _descriptor) => {\n const hooks: Function[] = Reflect.getMetadata(AFTER_KEY, target, propertyKey as string) || [];\n hooks.push(fn);\n Reflect.defineMetadata(AFTER_KEY, hooks, target, propertyKey as string);\n };\n}\n\n/**\n * Decorator that requires specific roles for accessing a route.\n * Must be used with authentication middleware.\n *\n * @param roles - List of roles that can access this route\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Get('/admin/settings')\n * @Roles('admin', 'superuser')\n * getSettings() {\n * // Only admins and superusers can access\n * return { settings: [...] };\n * }\n * ```\n */\nexport function Roles(...roles: string[]): MethodDecorator {\n return (target, propertyKey, _descriptor) => {\n Reflect.defineMetadata(ROLES_KEY, roles, target, propertyKey as string);\n };\n}\n\n/**\n * Decorator that redirects to another URL.\n *\n * @param url - URL to redirect to (can be absolute or relative)\n * @param statusCode - HTTP status code for redirect (default: 302)\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Get('/old-path')\n * @Redirect('/new-path', 301)\n * redirectToNewPath() {\n * // This method won't be executed; automatic redirect happens\n * }\n *\n * @Get('/dynamic-redirect')\n * @Redirect()\n * getDynamicRedirect() {\n * // Return an object with url and optionally statusCode\n * return { url: '/calculated-path', statusCode: 307 };\n * }\n * ```\n */\nexport function Redirect(url?: string, statusCode: number = 302): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n // Store the redirect information in metadata\n Reflect.defineMetadata(REDIRECT_KEY, { url, statusCode }, target, propertyKey as string);\n return descriptor;\n };\n}\n\n/**\n * Registers all controller classes with the provided router.\n * This function processes all decorators and sets up the Express routes.\n *\n * @param router - Express router instance\n * @param controllers - Array of controller classes\n */\nexport function registerControllers(router: Router, controllers: any[]) {\n controllers.forEach(ControllerClass => {\n const instance = new ControllerClass();\n const basePath: string = Reflect.getMetadata('basePath', ControllerClass) || '';\n const routes: RouteDefinition[] = Reflect.getMetadata(ROUTES_KEY, ControllerClass) || [];\n\n routes.forEach(({ path, method, handlerName }) => {\n const middlewares: RequestHandler[] = Reflect.getMetadata(MIDDLEWARE_KEY, instance, handlerName) || [];\n const params: ParamDefinition[] = Reflect.getMetadata(PARAMS_KEY, instance, handlerName) || [];\n\n const httpCode: number | undefined = Reflect.getMetadata(HTTP_CODE_KEY, instance, handlerName);\n const headers: Record<string, string> = Reflect.getMetadata(HEADER_KEY, instance, handlerName) || {};\n const beforeHooks: Function[] = Reflect.getMetadata(BEFORE_KEY, instance, handlerName) || [];\n const afterHooks: Function[] = Reflect.getMetadata(AFTER_KEY, instance, handlerName) || [];\n const roles: string[] = Reflect.getMetadata(ROLES_KEY, instance, handlerName) || [];\n const redirect: { url?: string; statusCode: number } | undefined = Reflect.getMetadata(\n REDIRECT_KEY,\n instance,\n handlerName\n );\n\n const handler: RequestHandler = async (req, res, next) => {\n try {\n // Handle roles-based access control\n if (roles.length && !(req as any)?.user?.roles?.some((role: string) => roles.includes(role))) {\n res.status(HttpStatusCodes.FORBIDDEN).json(new ForbiddenException('Forbidden Insufficient Roles'));\n return;\n }\n\n // Process static redirect if configured\n if (redirect && redirect.url) {\n return res.redirect(redirect.statusCode, redirect.url);\n }\n\n for (const fn of beforeHooks) await fn(req, res);\n const args: any[] = [];\n if (params.length) {\n params.forEach(({ index, type, key }) => {\n switch (type) {\n case 'query':\n args[index] = key ? req.query[key] : req.query;\n break;\n case 'param':\n args[index] = key ? req.params[key] : req.params;\n break;\n case 'body':\n args[index] = key ? req.body?.[key] : req.body;\n break;\n case 'req':\n args[index] = req;\n break;\n case 'res':\n args[index] = res;\n break;\n }\n });\n }\n const result = (instance as any)[handlerName](...args);\n // Support both sync and async handlers\n const awaited = result instanceof Promise ? await result : result;\n\n // Handle dynamic redirects\n if (redirect && awaited && typeof awaited === 'object' && 'url' in awaited) {\n const redirectUrl = awaited.url as string;\n const redirectStatus = (awaited.statusCode as number) || redirect.statusCode;\n return res.redirect(redirectStatus, redirectUrl);\n }\n\n if (!res.headersSent && typeof awaited !== 'undefined') {\n if (httpCode) res.status?.(httpCode);\n for (const [k, v] of Object.entries(headers)) res.set?.(k, v);\n res.json(awaited);\n }\n for (const fn of afterHooks) await fn(req, res, awaited);\n } catch (err) {\n next(err);\n }\n };\n\n (router as any)[method](basePath + path, ...middlewares, handler);\n });\n });\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"dir.utils.js","sourceRoot":"","sources":["../../../src/utils/dir.utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AQ,CAAC,OAAO,CAAC;wBAC5B,WAAW,EAAE,IAAI;wBACjB,KAAK,OAAA;qBACN,CAAC;oBACF,qBAAM,OAAO,CAAC,SAAS,CAAC,SAAS,CAAC,EAAA;;oBAAlC,SAAkC,CAAC;;;;;;CAEtC","sourcesContent":["/*\n * The MIT License\n *\n * Copyright (c) 2025 Catbee Technologies. https://catbee-utils.npm.hprasath.com/license\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport os from 'os';\nimport fs from 'fs';\nimport fsp from 'fs/promises';\nimport path from 'path';\nimport { glob } from 'glob';\nimport { randomBytes } from 'crypto';\n\n/**\n * Ensures that a directory exists, creating parent directories if needed (like `mkdir -p`).\n *\n * @param {string} dirPath - The directory path to ensure.\n * @returns {Promise<void>} Resolves when the directory exists.\n * @throws {Error} If directory cannot be created.\n */\nexport async function ensureDir(dirPath: string): Promise<void> {\n await fsp.mkdir(dirPath, { recursive: true });\n}\n\n/**\n * Recursively lists all files in a directory.\n *\n * @param {string} dirPath - The base directory.\n * @param {boolean} [recursive=false] - Whether to recurse into subdirectories.\n * @returns {Promise<string[]>} Array of absolute file paths.\n * @throws {Error} If the directory cannot be read.\n */\nexport async function listFiles(dirPath: string, recursive = false): Promise<string[]> {\n const entries = await fsp.readdir(dirPath, { withFileTypes: true });\n const files: string[] = [];\n\n for (const entry of entries) {\n const fullPath = path.join(dirPath, entry.name);\n\n if (entry.isFile()) {\n files.push(fullPath);\n } else if (recursive && entry.isDirectory()) {\n const nestedFiles = await listFiles(fullPath, true);\n files.push(...nestedFiles);\n }\n }\n\n return files;\n}\n\n/**\n * Deletes a directory and all its contents recursively (like `rm -rf`).\n *\n * @param {string} dirPath - Directory to delete.\n * @returns {Promise<void>} Resolves when deletion is complete.\n * @throws {Error} If deletion fails.\n */\nexport async function deleteDirRecursive(dirPath: string): Promise<void> {\n await fsp.rm(dirPath, { recursive: true, force: true });\n}\n\n/**\n * Checks whether a given path is a directory.\n *\n * @param {string} pathStr - Path to check.\n * @returns {Promise<boolean>} True if the path is a directory, else false.\n */\nexport async function isDirectory(pathStr: string): Promise<boolean> {\n try {\n const stat = await fsp.stat(pathStr);\n return stat.isDirectory();\n } catch {\n return false;\n }\n}\n\n/**\n * Recursively copies a directory and all its contents to a destination.\n *\n * @param {string} src - Source directory path.\n * @param {string} dest - Destination directory path.\n * @returns {Promise<void>} Resolves when copy is complete.\n * @throws {Error} If source does not exist or copy fails.\n */\nexport async function copyDir(src: string, dest: string): Promise<void> {\n await ensureDir(dest);\n const entries = await fsp.readdir(src, { withFileTypes: true });\n\n for (const entry of entries) {\n const srcPath = path.join(src, entry.name);\n const destPath = path.join(dest, entry.name);\n\n if (entry.isDirectory()) {\n await copyDir(srcPath, destPath);\n } else {\n await fsp.copyFile(srcPath, destPath);\n }\n }\n}\n\n/**\n * Moves a directory to a new location by copying and deleting the original.\n *\n * @param {string} src - Source directory path.\n * @param {string} dest - Destination directory path.\n * @returns {Promise<void>} Resolves when move is complete.\n * @throws {Error} If copy or deletion fails.\n */\nexport async function moveDir(src: string, dest: string): Promise<void> {\n await copyDir(src, dest);\n await deleteDirRecursive(src);\n}\n\n/**\n * Empties a directory by deleting all files and subdirectories inside it.\n *\n * @param {string} dirPath - Path to the directory to empty.\n * @returns {Promise<void>} Resolves when the directory has been emptied.\n * @throws {Error} If files or subdirectories cannot be removed.\n */\nexport async function emptyDir(dirPath: string): Promise<void> {\n const entries = await fsp.readdir(dirPath, { withFileTypes: true });\n\n for (const entry of entries) {\n const entryPath = path.join(dirPath, entry.name);\n\n if (entry.isDirectory()) {\n await fsp.rm(entryPath, { recursive: true, force: true });\n } else {\n await fsp.unlink(entryPath);\n }\n }\n}\n\n/**\n * Calculates the total size (in bytes) of all files in a directory (recursive).\n *\n * @param {string} dirPath - Path to the directory.\n * @returns {Promise<number>} Total size in bytes.\n * @throws {Error} If any file stats cannot be read.\n */\nexport async function getDirSize(dirPath: string): Promise<number> {\n let total = 0;\n const entries = await fsp.readdir(dirPath, { withFileTypes: true });\n\n for (const entry of entries) {\n const entryPath = path.join(dirPath, entry.name);\n if (entry.isDirectory()) {\n total += await getDirSize(entryPath);\n } else {\n const stat = await fsp.stat(entryPath);\n total += stat.size;\n }\n }\n\n return total;\n}\n\n/**\n * Watches a directory for file changes and calls a callback on each event.\n *\n * @param {string} dirPath - Directory path to watch.\n * @param {(eventType: \"rename\" | \"change\", filename: string | null) => void} callback - Callback for each change event.\n * @returns {() => void} A function to stop watching the directory.\n */\nexport function watchDir(\n dirPath: string,\n callback: (eventType: 'rename' | 'change', filename: string | null) => void\n): () => void {\n const watcher = fs.watch(dirPath, (eventType, filename) => {\n callback(eventType, filename);\n });\n\n return () => watcher.close();\n}\n\n/**\n * Finds files matching a glob pattern.\n *\n * @param {string} pattern - Glob pattern to match files.\n * @param {object} [options] - Options for glob pattern matching.\n * @param {string} [options.cwd] - Current working directory for relative patterns.\n * @param {boolean} [options.dot=false] - Include dotfiles in matches.\n * @param {boolean} [options.nodir=true] - Only match files, not directories.\n * @returns {Promise<string[]>} Array of matched file paths.\n * @throws {Error} If pattern matching fails.\n */\nexport async function findFilesByPattern(\n pattern: string,\n options: { cwd?: string; dot?: boolean; nodir?: boolean } = {}\n): Promise<string[]> {\n const defaultOptions = { nodir: true, ...options };\n return glob(pattern, defaultOptions);\n}\n\n/**\n * Gets all subdirectories in a directory.\n *\n * @param {string} dirPath - The directory to search in.\n * @param {boolean} [recursive=false] - Whether to include subdirectories recursively.\n * @returns {Promise<string[]>} Array of absolute subdirectory paths.\n * @throws {Error} If directory cannot be read.\n */\nexport async function getSubdirectories(dirPath: string, recursive = false): Promise<string[]> {\n const entries = await fsp.readdir(dirPath, { withFileTypes: true });\n const dirs = entries.filter(entry => entry.isDirectory()).map(entry => path.join(dirPath, entry.name));\n\n if (recursive && dirs.length > 0) {\n const nestedDirs = await Promise.all(dirs.map(dir => getSubdirectories(dir, true)));\n return [...dirs, ...nestedDirs.flat()];\n }\n\n return dirs;\n}\n\n/**\n * Ensures a directory exists and is empty.\n *\n * @param {string} dirPath - Path to the directory.\n * @returns {Promise<void>} Resolves when the directory exists and is empty.\n * @throws {Error} If directory cannot be created or emptied.\n */\nexport async function ensureEmptyDir(dirPath: string): Promise<void> {\n if (await isDirectory(dirPath)) {\n await emptyDir(dirPath);\n } else {\n try {\n await fsp.unlink(dirPath);\n } catch (error) {\n // Ignore if file doesn't exist\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n }\n await ensureDir(dirPath);\n }\n}\n\n/**\n * Creates a temporary directory with optional auto-cleanup.\n *\n * @param {object} [options] - Options for the temporary directory.\n * @param {string} [options.prefix='tmp-'] - Prefix for the directory name.\n * @param {string} [options.parentDir=os.tmpdir()] - Parent directory.\n * @param {boolean} [options.cleanup=false] - Whether to register cleanup on process exit.\n * @returns {Promise<{ path: string, cleanup: () => Promise<void> }>} Object with directory path and cleanup function.\n * @throws {Error} If directory cannot be created.\n */\nexport async function createTempDir(\n options: { prefix?: string; parentDir?: string; cleanup?: boolean } = {}\n): Promise<{ path: string; cleanup: () => Promise<void> }> {\n const prefix = options.prefix || 'tmp-';\n const parentDir = options.parentDir || os.tmpdir();\n const dirName = `${prefix}${randomBytes(6).toString('hex')}`;\n const tempDirPath = path.join(parentDir, dirName);\n\n await ensureDir(tempDirPath);\n\n const cleanup = async () => {\n try {\n await deleteDirRecursive(tempDirPath);\n } catch {\n // Ignore cleanup errors\n }\n };\n\n if (options.cleanup) {\n process.once('exit', () => {\n try {\n fs.rmSync(tempDirPath, { recursive: true, force: true });\n } catch {\n // Ignore cleanup errors on exit\n }\n });\n\n // Handle signals for better cleanup\n ['SIGINT', 'SIGTERM', 'SIGUSR1', 'SIGUSR2'].forEach(signal => {\n process.once(signal as NodeJS.Signals, () => {\n cleanup().then(() => process.exit());\n });\n });\n }\n\n return { path: tempDirPath, cleanup };\n}\n\n/**\n * Finds the newest file in a directory.\n *\n * @param {string} dirPath - Directory to search.\n * @param {boolean} [recursive=false] - Whether to search subdirectories.\n * @returns {Promise<string | null>} Path to the newest file or null if no files.\n * @throws {Error} If directory cannot be read.\n */\nexport async function findNewestFile(dirPath: string, recursive = false): Promise<string | null> {\n const files = await listFiles(dirPath, recursive);\n if (files.length === 0) return null;\n\n const stats = await Promise.all(\n files.map(async file => ({\n path: file,\n mtime: (await fsp.stat(file)).mtime\n }))\n );\n\n return stats.sort((a, b) => b.mtime.getTime() - a.mtime.getTime())[0].path;\n}\n\n/**\n * Finds the oldest file in a directory.\n *\n * @param {string} dirPath - Directory to search.\n * @param {boolean} [recursive=false] - Whether to search subdirectories.\n * @returns {Promise<string | null>} Path to the oldest file or null if no files.\n * @throws {Error} If directory cannot be read.\n */\nexport async function findOldestFile(dirPath: string, recursive = false): Promise<string | null> {\n const files = await listFiles(dirPath, recursive);\n if (files.length === 0) return null;\n\n const stats = await Promise.all(\n files.map(async file => ({\n path: file,\n mtime: (await fsp.stat(file)).mtime\n }))\n );\n\n return stats.sort((a, b) => a.mtime.getTime() - b.mtime.getTime())[0].path;\n}\n\n/**\n * Finds files or directories in a directory matching a predicate function.\n *\n * @param {string} dirPath - Directory to search.\n * @param {(path: string, stat: fs.Stats) => boolean | Promise<boolean>} predicate - Function to test each path.\n * @param {boolean} [recursive=false] - Whether to search subdirectories.\n * @returns {Promise<string[]>} Array of matching paths.\n * @throws {Error} If directory cannot be read.\n */\nexport async function findInDir(\n dirPath: string,\n predicate: (path: string, stat: fs.Stats) => boolean | Promise<boolean>,\n recursive = false\n): Promise<string[]> {\n const entries = await fsp.readdir(dirPath, { withFileTypes: true });\n const results: string[] = [];\n\n for (const entry of entries) {\n const entryPath = path.join(dirPath, entry.name);\n const stat = await fsp.stat(entryPath);\n\n if (await predicate(entryPath, stat)) {\n results.push(entryPath);\n }\n\n if (recursive && entry.isDirectory()) {\n const nestedResults = await findInDir(entryPath, predicate, true);\n results.push(...nestedResults);\n }\n }\n\n return results;\n}\n\n/**\n * Watches a directory recursively for file changes.\n *\n * @param {string} dirPath - Base directory path to watch.\n * @param {(eventType: \"rename\" | \"change\", filename: string) => void} callback - Callback for each change event.\n * @param {boolean} [includeSubdirs=true] - Whether to watch subdirectories.\n * @returns {Promise<() => void>} A function to stop watching the directory.\n * @throws {Error} If directory cannot be watched.\n */\nexport async function watchDirRecursive(\n dirPath: string,\n callback: (eventType: 'rename' | 'change', filename: string) => void,\n includeSubdirs = true\n): Promise<() => void> {\n // Normalize the path to ensure consistent path separators\n const normalizedBasePath = path.normalize(dirPath);\n\n // Create watchers for the base dir and all subdirectories\n const watchers: fs.FSWatcher[] = [];\n\n // Helper function to add a watcher for a directory\n const addWatcher = (dir: string) => {\n try {\n const watcher = fs.watch(dir, (eventType, filename) => {\n if (!filename) return;\n\n const fullPath = path.join(dir, filename);\n // Make the path relative to the base directory\n const relativePath = path.relative(normalizedBasePath, fullPath);\n callback(eventType, relativePath);\n\n // If a new directory is created, we should watch it\n if (eventType === 'rename' && includeSubdirs) {\n setTimeout(async () => {\n try {\n if (await isDirectory(fullPath)) {\n addWatcher(fullPath);\n }\n } catch {\n // Ignore errors checking newly created items\n }\n }, 100);\n }\n });\n watchers.push(watcher);\n } catch {\n // Silently ignore directories we can't watch\n }\n };\n\n // Add watcher for the base directory\n addWatcher(normalizedBasePath);\n\n // If watching subdirectories, add watchers for all existing subdirectories\n if (includeSubdirs) {\n const subdirs = await getSubdirectories(normalizedBasePath, true);\n for (const subdir of subdirs) {\n addWatcher(subdir);\n }\n }\n\n // Return a function to close all watchers\n return () => {\n watchers.forEach(watcher => watcher.close());\n };\n}\n\n/**\n * Gets detailed directory statistics including file count, directory count, and size.\n *\n * @param {string} dirPath - Path to the directory.\n * @returns {Promise<{ fileCount: number, dirCount: number, totalSize: number }>} Directory statistics.\n * @throws {Error} If directory cannot be read.\n */\nexport async function getDirStats(\n dirPath: string\n): Promise<{ fileCount: number; dirCount: number; totalSize: number }> {\n let fileCount = 0;\n let dirCount = 0;\n let totalSize = 0;\n\n async function processDir(currentPath: string): Promise<void> {\n const entries = await fsp.readdir(currentPath, { withFileTypes: true });\n\n for (const entry of entries) {\n const entryPath = path.join(currentPath, entry.name);\n\n if (entry.isDirectory()) {\n dirCount++;\n await processDir(entryPath);\n } else if (entry.isFile()) {\n fileCount++;\n const stat = await fsp.stat(entryPath);\n totalSize += stat.size;\n }\n }\n }\n\n await processDir(dirPath);\n\n return { fileCount, dirCount, totalSize };\n}\n\n/**\n * Walks through a directory hierarchy, calling a visitor function for each entry.\n *\n * @param {string} dirPath - Starting directory path.\n * @param {object} options - Options for walking the directory.\n * @param {(entry: { path: string, name: string, isDirectory: boolean, stats: fs.Stats }) => boolean | void | Promise<boolean | void>} options.visitorFn -\n * Function called for each file/directory. Return false to skip a directory.\n * @param {'pre' | 'post'} [options.traversalOrder='pre'] - Whether to visit directories before or after their contents.\n * @throws {Error} If directory cannot be read.\n */\nexport async function walkDir(\n dirPath: string,\n options: {\n visitorFn: (entry: {\n path: string;\n name: string;\n isDirectory: boolean;\n stats: fs.Stats;\n }) => boolean | void | Promise<boolean | void>;\n traversalOrder?: 'pre' | 'post';\n }\n): Promise<void> {\n const traversalOrder = options.traversalOrder || 'pre';\n const entries = await fsp.readdir(dirPath, { withFileTypes: true });\n\n for (const entry of entries) {\n const entryPath = path.join(dirPath, entry.name);\n const stats = await fsp.stat(entryPath);\n const entryInfo = {\n path: entryPath,\n name: entry.name,\n isDirectory: entry.isDirectory(),\n stats\n };\n\n if (entry.isDirectory()) {\n // Pre-order: visit directory before its contents\n if (traversalOrder === 'pre') {\n const shouldContinue = await options.visitorFn(entryInfo);\n // If the visitor returns false, don't recurse into this directory\n if (shouldContinue !== false) {\n await walkDir(entryPath, options);\n }\n } else {\n // Post-order: visit directory after its contents\n await walkDir(entryPath, options);\n await options.visitorFn(entryInfo);\n }\n } else {\n // Files are always visited when encountered\n await options.visitorFn(entryInfo);\n }\n }\n\n if (traversalOrder === 'post') {\n // Only visit the root if this is the top-level call (not for subdirectories)\n // But since this function is always called recursively, always visit after children\n const stats = await fsp.stat(dirPath);\n const entryInfo = {\n path: dirPath,\n name: path.basename(dirPath),\n isDirectory: true,\n stats\n };\n await options.visitorFn(entryInfo);\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"env.utils.js","sourceRoot":"","sources":["../../../src/utils/env.utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,qCAAqC;AACrC,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AAC9C,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAE3C;;GAEG;AACH,MAAM,CAAN,IAAY,WAKX;AALD,WAAY,WAAW;IACrB,wCAAyB,CAAA;IACzB,0CAA2B,CAAA;IAC3B,kCAAmB,CAAA;IACnB,kCAAmB,CAAA;AACrB,CAAC,EALW,WAAW,KAAX,WAAW,QAKtB;AA4BD;;;GAGG;AACH;IAAA;IAu0BA,CAAC;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,WAAI,GAAG,CAAE,CAAC,EAAE,CAAC;oBACjC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;gBAC9B,CAAC;YACH,CAAC;;;;;;;;;IACH,CAAC;IAED;;;OAGG;IACI,cAAU,GAAjB;QACE,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC;IACrB,CAAC;IAr0BD,sEAAsE;IACvD,SAAK,GAAqB,IAAI,GAAG,EAAE,CAAC;IAq0BrD,UAAC;CAAA,AAv0BD,IAu0BC;SAv0BY,GAAG","sourcesContent":["/*\n * The MIT License\n *\n * Copyright (c) 2025 Catbee Technologies. https://catbee-utils.npm.hprasath.com/license\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n/* eslint-disable n/no-process-env */\nimport { existsSync, readFileSync } from 'fs';\nimport { isAbsolute, resolve } from 'path';\n\n/**\n * Enum representing valid application environments.\n */\nexport enum Environment {\n PRODUCTION = 'production',\n DEVELOPMENT = 'development',\n STAGING = 'staging',\n TESTING = 'testing'\n}\n\n/**\n * Options for validating URL environment variables\n */\nexport interface UrlOptions {\n /** List of allowed protocols (e.g., ['http', 'https']) */\n protocols?: string[];\n /** Whether a top-level domain is required (default: true) */\n requireTld?: boolean;\n /** Whether to allow IP addresses (default: true) */\n allowIp?: boolean;\n /** Whether to allow localhost (default: true) */\n allowLocalhost?: boolean;\n}\n\n/**\n * Options for validating path environment variables\n */\nexport interface PathOptions {\n /** Whether the path must exist on the filesystem (default: false) */\n mustExist?: boolean;\n /** Whether to convert relative paths to absolute (default: true) */\n makeAbsolute?: boolean;\n /** List of allowed file extensions */\n allowedExtensions?: string[];\n}\n\n/**\n * Utility class for accessing and managing environment variables.\n * Provides typed getters with fallback defaults and validation.\n */\nexport class Env {\n // Cache for parsed values to avoid repeated parsing of complex values\n private static cache: Map<string, any> = new Map();\n\n /**\n * Checks if the current NODE_ENV is 'development'.\n *\n * @returns {boolean} `true` if NODE_ENV is 'development', else `false`.\n */\n static isDev(): boolean {\n return Env.get('NODE_ENV', Environment.DEVELOPMENT) === Environment.DEVELOPMENT;\n }\n\n /**\n * Checks if the current NODE_ENV is 'production'.\n *\n * @returns {boolean} `true` if NODE_ENV is 'production', else `false`.\n */\n static isProd(): boolean {\n return Env.get('NODE_ENV', Environment.DEVELOPMENT) === Environment.PRODUCTION;\n }\n\n /**\n * Checks if the current NODE_ENV is 'testing'.\n *\n * @returns {boolean} `true` if NODE_ENV is 'testing', else `false`.\n */\n static isTest(): boolean {\n return Env.get('NODE_ENV', Environment.DEVELOPMENT) === Environment.TESTING;\n }\n\n /**\n * Checks if the current NODE_ENV is 'staging'.\n *\n * @returns {boolean} `true` if NODE_ENV is 'staging', else `false`.\n */\n static isStaging(): boolean {\n return Env.get('NODE_ENV', Environment.DEVELOPMENT) === Environment.STAGING;\n }\n\n /**\n * Sets an environment variable (only affects runtime memory).\n *\n * @param {string} key - The environment variable key.\n * @param {string} value - The value to set.\n */\n static set(key: string, value: string): void {\n process.env[key] = value;\n\n // Clear all cached values for this key with any prefix\n this.cache.delete(key);\n for (const cacheKey of [...this.cache.keys()]) {\n if (cacheKey.includes(`:${key}`)) {\n this.cache.delete(cacheKey);\n }\n }\n }\n\n /**\n * Returns all environment variables as an object.\n *\n * @returns {object} The current `process.env` object.\n */\n static getAll(): object {\n return process.env;\n }\n\n /**\n * Retrieves a string environment variable with a fallback default.\n * Supports variable expansion with ${VAR_NAME} syntax.\n *\n * @param {string} key - The environment variable key.\n * @param {string} [defaultValue] - Value to return if the key is missing.\n * @returns {string} The env value or the fallback.\n *\n * @example\n * // If DATABASE_URL is \"postgres://localhost:5432/${DB_NAME}\"\n * // and DB_NAME is \"myapp\"\n * const url = Env.get('DATABASE_URL', ''); // \"postgres://localhost:5432/myapp\"\n */\n static get(key: string, defaultValue: string): string {\n let value = process.env[key] ?? defaultValue;\n\n // Expand ${VAR} references\n if (value && value.includes('${')) {\n value = value.replace(/\\${([A-Za-z0-9_]+)}/g, (_, varName) => {\n return process.env[varName] ?? '';\n });\n }\n\n return value;\n }\n\n /**\n * Retrieves a string environment variable and throws if it's missing.\n *\n * @param {string} key - The environment variable key.\n * @returns {string} The environment variable's value.\n * @throws {Error} If the variable is not defined.\n */\n static getRequired(key: string): string {\n const value = process.env[key];\n if (value === undefined) {\n throw new Error(`Required environment variable '${key}' is missing`);\n }\n return Env.get(key, ''); // Use get to handle variable expansion\n }\n\n /**\n * Retrieves a value using a default generating function if the key doesn't exist.\n * Useful for expensive default calculations.\n *\n * @param {string} key - The environment variable key.\n * @param {() => string} defaultFn - Function that generates default value.\n * @returns {string} The environment value or generated default.\n *\n * @example\n * const hostname = Env.getWithDefault('HOSTNAME', () => {\n * // Only called if HOSTNAME is not set\n * return require('os').hostname();\n * });\n */\n static getWithDefault(key: string, defaultFn: () => string): string {\n if (Env.has(key)) {\n return Env.get(key, '');\n }\n return defaultFn();\n }\n\n /**\n * Retrieves an environment variable as a number, or returns a default.\n *\n * @param {string} key - The environment variable key.\n * @param {number} defaultValue - Fallback number if key is not present.\n * @returns {number} Parsed numeric value or default.\n * @throws {Error} If the value is not a valid number.\n */\n static getNumber(key: string, defaultValue: number): number {\n if (this.cache.has(`number:${key}`)) {\n return this.cache.get(`number:${key}`);\n }\n\n const value = process.env[key];\n if (value === undefined) {\n return defaultValue;\n }\n\n const numberValue = Number(value);\n if (isNaN(numberValue)) {\n throw new Error(`Environment variable '${key}' is not a valid number, got: \"${value}\"`);\n }\n\n this.cache.set(`number:${key}`, numberValue);\n return numberValue;\n }\n\n /**\n * Retrieves a required environment variable as a number.\n *\n * @param {string} key - The environment variable key.\n * @returns {number} Parsed number.\n * @throws {Error} If the value is missing or not a number.\n */\n static getNumberRequired(key: string): number {\n const value = process.env[key];\n if (value === undefined) {\n throw new Error(`Required environment variable '${key}' is missing`);\n }\n\n return Env.getNumber(key, 0); // The default is ignored since we know the key exists\n }\n\n /**\n * Retrieves an integer environment variable and validates it.\n *\n * @param {string} key - The environment variable key.\n * @param {number} defaultValue - Fallback number if key is not present.\n * @param {object} [options] - Validation options.\n * @param {number} [options.min] - Minimum allowed value.\n * @param {number} [options.max] - Maximum allowed value.\n * @returns {number} The parsed integer.\n *\n * @example\n * // Require PORT to be between 1000 and 9999\n * const port = Env.getInteger('PORT', 3000, { min: 1000, max: 9999 });\n */\n static getInteger(key: string, defaultValue: number, options: { min?: number; max?: number } = {}): number {\n const num = Env.getNumber(key, defaultValue);\n const intValue = Math.floor(num);\n\n if (intValue !== num) {\n throw new Error(`Environment variable '${key}' must be an integer, got: ${num}`);\n }\n\n if (options.min !== undefined && intValue < options.min) {\n throw new Error(`Environment variable '${key}' must be at least ${options.min}, got: ${intValue}`);\n }\n\n if (options.max !== undefined && intValue > options.max) {\n throw new Error(`Environment variable '${key}' must be at most ${options.max}, got: ${intValue}`);\n }\n\n return intValue;\n }\n\n /**\n * Retrieves an environment variable as a boolean.\n * Accepts `true`, `1`, `yes`, `on` as true; `false`, `0`, `no`, `off` as false.\n *\n * @param {string} key - The environment variable key.\n * @param {boolean} [defaultValue=false] - Optional fallback value if key is missing.\n * @returns {boolean} Parsed boolean.\n * @throws {Error} If the value is not a recognized boolean string.\n *\n * @example\n * // If DEBUG=yes\n * const isDebug = Env.getBoolean('DEBUG', false); // true\n */\n static getBoolean(key: string, defaultValue = false): boolean {\n if (this.cache.has(`bool:${key}`)) {\n return this.cache.get(`bool:${key}`);\n }\n\n const value = process.env[key];\n if (value === undefined) {\n return defaultValue;\n }\n\n const lowerValue = value.toLowerCase();\n if (['true', '1', 'yes', 'on'].includes(lowerValue)) {\n this.cache.set(`bool:${key}`, true);\n return true;\n }\n\n if (['false', '0', 'no', 'off'].includes(lowerValue)) {\n this.cache.set(`bool:${key}`, false);\n return false;\n }\n\n throw new Error(\n `Environment variable '${key}' is not a valid boolean, got: \"${value}\". Use true/false, yes/no, 1/0, or on/off.`\n );\n }\n\n /**\n * Retrieves a required environment variable as a boolean.\n *\n * @param {string} key - The environment variable key.\n * @returns {boolean} Parsed boolean value.\n * @throws {Error} If missing or invalid.\n */\n static getBooleanRequired(key: string): boolean {\n const value = process.env[key];\n if (value === undefined) {\n throw new Error(`Required environment variable '${key}' is missing`);\n }\n return Env.getBoolean(key);\n }\n\n /**\n * Parses a stringified JSON object from an environment variable.\n *\n * @typeParam T - The type to parse as (defaults to `object`).\n * @param {string} key - The environment variable key.\n * @param {T} defaultValue - Value to return if key is missing.\n * @returns {T} Parsed object or default.\n * @throws {Error} If the value is not valid JSON.\n *\n * @example\n * // If CONFIG='{\"debug\":true,\"api\":{\"url\":\"https://api.example.com\"}}'\n * const config = Env.getJSON('CONFIG', { debug: false });\n * // { debug: true, api: { url: \"https://api.example.com\" }}\n */\n static getJSON<T extends object = object>(key: string, defaultValue: T): T {\n if (this.cache.has(`json:${key}`)) {\n return this.cache.get(`json:${key}`);\n }\n\n const v = process.env[key];\n if (v === undefined) {\n return defaultValue;\n }\n\n try {\n const parsed = JSON.parse(v);\n this.cache.set(`json:${key}`, parsed);\n return parsed;\n } catch (error) {\n throw new Error(`Environment variable '${key}' is not valid JSON: ${(error as Error).message}`);\n }\n }\n\n /**\n * Parses a comma-separated string as an array.\n *\n * @typeParam T - The item type (optional, defaults to string).\n * @param {string} key - The environment variable key.\n * @param {T[]} [defaultValue=[]] - Array to return if value is empty or missing.\n * @param {string} [splitter=','] - Delimiter to split on.\n * @param {(item: string) => T} [transform] - Optional function to transform each item.\n * @returns {T[]} An array of items.\n *\n * @example\n * // If ALLOWED_IPS=127.0.0.1,192.168.1.1,10.0.0.1\n * const ips = Env.getArray('ALLOWED_IPS');\n * // [\"127.0.0.1\", \"192.168.1.1\", \"10.0.0.1\"]\n *\n * // With transformation function\n * const ports = Env.getArray('PORTS', [], ',', (p) => parseInt(p, 10));\n */\n static getArray<T = string>(\n key: string,\n defaultValue: T[] = [] as unknown as T[],\n splitter = ',',\n transform?: (item: string) => T\n ): T[] {\n const cacheKey = `array:${key}:${splitter}:${transform ? 'transformed' : 'raw'}`;\n if (this.cache.has(cacheKey)) {\n return this.cache.get(cacheKey);\n }\n\n const value = process.env[key];\n if (!value || value.trim() === '') {\n return defaultValue;\n }\n\n const items = value\n .split(splitter)\n .map(item => item.trim())\n .filter(item => item.length > 0);\n\n if (transform) {\n try {\n const result = items.map(transform);\n this.cache.set(cacheKey, result);\n return result;\n } catch (error) {\n throw new Error(`Failed to transform items in '${key}': ${(error as Error).message}`);\n }\n }\n\n const result = items as unknown as T[];\n this.cache.set(cacheKey, result);\n return result;\n }\n\n /**\n * Parses a comma-separated list of numbers.\n *\n * @param {string} key - The environment variable key.\n * @param {number[]} [defaultValue=[]] - Default value if not present.\n * @param {string} [splitter=','] - Delimiter to split on.\n * @returns {number[]} Array of parsed numbers.\n *\n * @example\n * // If ALLOWED_PORTS=80,443,3000,8080\n * const ports = Env.getNumberArray('ALLOWED_PORTS');\n * // [80, 443, 3000, 8080]\n */\n static getNumberArray(key: string, defaultValue: number[] = [], splitter = ','): number[] {\n return Env.getArray(key, defaultValue, splitter, item => {\n const num = Number(item);\n if (isNaN(num)) {\n throw new Error(`Value \"${item}\" in array '${key}' is not a valid number`);\n }\n return num;\n });\n }\n\n /**\n * Retrieves an enum-like environment variable value, validating against allowed values.\n *\n * @typeParam T - The allowed value type (string literal types).\n * @param {string} key - The environment variable key.\n * @param {T[]} allowedValues - Array of accepted string values.\n * @param {T} [defaultValue] - Optional fallback value.\n * @returns {T} The validated environment value.\n * @throws {Error} If missing or invalid.\n *\n * @example\n * // If LOG_LEVEL=debug\n * const level = Env.getEnum('LOG_LEVEL', ['debug', 'info', 'warn', 'error'] as const, 'info');\n * // 'debug' (typed as 'debug' | 'info' | 'warn' | 'error')\n */\n static getEnum<T extends string>(key: string, allowedValues: readonly T[], defaultValue: T): T {\n const value = process.env[key];\n\n if (!value) {\n return defaultValue;\n }\n\n if (!allowedValues.includes(value as T)) {\n throw new Error(\n `Environment variable '${key}' must be one of: ${allowedValues.join(', ')}. Received: \"${value}\"`\n );\n }\n\n return value as T;\n }\n\n /**\n * Retrieves an enum-like numeric environment variable.\n *\n * @param {string} key - The environment variable key.\n * @param {number[]} allowedValues - Array of accepted values.\n * @param {number} defaultValue - Default value if not present.\n * @returns {number} The validated value.\n *\n * @example\n * // If NODE_VERSION=16\n * const version = Env.getNumberEnum('NODE_VERSION', [14, 16, 18], 16);\n */\n static getNumberEnum(key: string, allowedValues: number[], defaultValue: number): number {\n const value = Env.getNumber(key, defaultValue);\n\n if (!allowedValues.includes(value)) {\n throw new Error(`Environment variable '${key}' must be one of: ${allowedValues.join(', ')}. Received: ${value}`);\n }\n\n return value;\n }\n\n /**\n * Retrieves a URL environment variable and validates it.\n *\n * @param {string} key - The environment variable key.\n * @param {string} [defaultValue] - Optional fallback value.\n * @param {UrlOptions} [options] - Validation options.\n * @returns {string} The validated URL.\n * @throws {Error} If URL is invalid.\n *\n * @example\n * // Validate API URL requires HTTPS\n * const apiUrl = Env.getUrl('API_URL', 'https://api.example.com', {\n * protocols: ['https'],\n * requireTld: true,\n * allowIp: false\n * });\n */\n static getUrl(key: string, defaultValue: string, options: UrlOptions = {}): string {\n const cacheKey = `url:${key}:${JSON.stringify(options)}`;\n if (this.cache.has(cacheKey)) {\n return this.cache.get(cacheKey);\n }\n\n const value = Env.get(key, defaultValue);\n if (!value) {\n throw new Error(`URL environment variable '${key}' is missing or empty`);\n }\n\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new Error(`Environment variable '${key}' is not a valid URL: \"${value}\"`);\n }\n\n // Validate protocol\n if (options.protocols && options.protocols.length > 0) {\n const protocol = url.protocol.replace(':', '');\n if (!options.protocols.includes(protocol)) {\n throw new Error(\n `Environment variable '${key}' must use one of the protocols: ${options.protocols.join(', ')}. Got: ${protocol}`\n );\n }\n }\n\n // Validate hostname\n const { hostname } = url;\n const isIp = /^(?:[0-9]{1,3}\\.){3}[0-9]{1,3}$/.test(hostname);\n const isLocalhost = hostname === 'localhost';\n\n // Check if hostname is an IP address when not allowed\n if (isIp && options.allowIp === false) {\n throw new Error(`Environment variable '${key}' cannot be an IP address: \"${hostname}\"`);\n }\n\n // Check if hostname is localhost when not allowed\n if (isLocalhost && options.allowLocalhost === false) {\n throw new Error(`Environment variable '${key}' cannot be localhost`);\n }\n\n // Check for TLD requirement - include localhost in check if requireTld is true and allowLocalhost is false\n if (options.requireTld === true) {\n if (isLocalhost && options.allowLocalhost !== false) {\n // Localhost is allowed, so no TLD check needed for it\n } else if (isIp && options.allowIp !== false) {\n // IP is allowed, so no TLD check needed for it\n } else if (!hostname.includes('.') || hostname.endsWith('.')) {\n throw new Error(`Environment variable '${key}' must have a valid host with TLD: \"${hostname}\"`);\n }\n }\n\n this.cache.set(cacheKey, value);\n return value;\n }\n\n /**\n * Retrieves an email environment variable and validates it.\n *\n * @param {string} key - The environment variable key.\n * @param {string} [defaultValue] - Optional fallback value.\n * @returns {string} The validated email address.\n * @throws {Error} If email is invalid.\n *\n * @example\n * const supportEmail = Env.getEmail('SUPPORT_EMAIL', 'support@example.com');\n */\n static getEmail(key: string, defaultValue: string): string {\n if (this.cache.has(`email:${key}`)) {\n return this.cache.get(`email:${key}`);\n }\n\n const value = Env.get(key, defaultValue);\n if (!value) {\n if (defaultValue === undefined) {\n throw new Error(`Email environment variable '${key}' is missing`);\n }\n return defaultValue;\n }\n\n // More comprehensive email validation regex\n const emailRegex =\n /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n\n if (!emailRegex.test(value)) {\n throw new Error(`Environment variable '${key}' is not a valid email address: \"${value}\"`);\n }\n\n this.cache.set(`email:${key}`, value);\n return value;\n }\n\n /**\n * Retrieves a path environment variable and validates it exists.\n *\n * @param {string} key - The environment variable key.\n * @param {string} [defaultValue] - Optional fallback value.\n * @param {PathOptions} [options] - Validation options.\n * @returns {string} The validated path.\n * @throws {Error} If path is invalid.\n *\n * @example\n * // Require that the path exists and is a .json file\n * const configPath = Env.getPath('CONFIG_PATH', './config.json', {\n * mustExist: true,\n * allowedExtensions: ['.json', '.yaml']\n * });\n */\n static getPath(key: string, defaultValue: string, options: PathOptions = {}): string {\n const cacheKey = `path:${key}:${JSON.stringify(options)}`;\n if (this.cache.has(cacheKey)) {\n return this.cache.get(cacheKey);\n }\n\n const value = Env.get(key, defaultValue);\n if (!value) {\n if (defaultValue === undefined) {\n throw new Error(`Path environment variable '${key}' is missing`);\n }\n return defaultValue;\n }\n\n const path = options.makeAbsolute !== false && !isAbsolute(value) ? resolve(process.cwd(), value) : value;\n\n // Validate path exists if required\n if (options.mustExist && !existsSync(path)) {\n throw new Error(`Path in environment variable '${key}' does not exist: \"${path}\"`);\n }\n\n // Validate file extension if specified\n if (options.allowedExtensions && options.allowedExtensions.length > 0) {\n const hasValidExtension = options.allowedExtensions.some(ext => path.toLowerCase().endsWith(ext.toLowerCase()));\n\n if (!hasValidExtension) {\n throw new Error(\n `Path in environment variable '${key}' must have one of these extensions: ${options.allowedExtensions.join(\n ', '\n )}. Got: \"${path}\"`\n );\n }\n }\n\n this.cache.set(cacheKey, path);\n return path;\n }\n\n /**\n * Retrieves a port environment variable and validates it.\n *\n * @param {string} key - The environment variable key.\n * @param {number} [defaultValue] - Optional fallback value.\n * @returns {number} The validated port number.\n * @throws {Error} If port is invalid.\n *\n * @example\n * const serverPort = Env.getPort('PORT', 3000);\n */\n static getPort(key: string, defaultValue: number): number {\n try {\n return Env.getInteger(key, defaultValue, { min: 0, max: 65535 });\n } catch (error) {\n // Rewrite the error message to match the expected pattern\n if ((error as Error).message.includes('must be at most 65535')) {\n throw new Error(`Environment variable '${key}' must be a valid port number (0-65535)`);\n }\n throw error;\n }\n }\n\n /**\n * Retrieves an ISO date string and converts it to a Date object.\n *\n * @param {string} key - The environment variable key.\n * @param {string|Date} [defaultValue] - Optional fallback value.\n * @returns {Date} The parsed Date object.\n *\n * @example\n * // If EXPIRY_DATE=2023-12-31T23:59:59Z\n * const expiryDate = Env.getDate('EXPIRY_DATE', new Date());\n */\n static getDate(key: string, defaultValue: string | Date = new Date()): Date {\n const value = Env.get(key, defaultValue instanceof Date ? defaultValue.toISOString() : defaultValue);\n\n if (!value) {\n return defaultValue instanceof Date ? defaultValue : new Date();\n }\n\n const date = new Date(value);\n if (isNaN(date.getTime())) {\n throw new Error(`Environment variable '${key}' is not a valid date: \"${value}\"`);\n }\n\n return date;\n }\n\n /**\n * Retrieves a duration string and converts it to milliseconds.\n * Supports formats like \"1d\", \"2h\", \"30m\", \"45s\", \"100ms\" or combinations like \"1h30m\".\n *\n * @param {string} key - The environment variable key.\n * @param {string|number} [defaultValue='0'] - Optional fallback value.\n * @returns {number} The duration in milliseconds.\n * @throws {Error} If duration format is invalid.\n *\n * @example\n * // If CACHE_TTL=2h30m\n * const cacheTtlMs = Env.getDuration('CACHE_TTL', '1h');\n * // 9000000 (2.5 hours in milliseconds)\n */\n static getDuration(key: string, defaultValue: string | number = '0'): number {\n const cacheKey = `duration:${key}`;\n if (this.cache.has(cacheKey)) {\n return this.cache.get(cacheKey);\n }\n\n const value = Env.get(key, String(defaultValue));\n if (!value) return 0;\n\n // Handle plain number input (assume milliseconds)\n if (/^\\d+$/.test(value)) {\n const ms = parseInt(value, 10);\n this.cache.set(cacheKey, ms);\n return ms;\n }\n\n // Enhanced duration parsing with more precise regex\n const durationRegex = /^(?:(\\d+)y)?(?:(\\d+)w)?(?:(\\d+)d)?(?:(\\d+)h)?(?:(\\d+)m)?(?:(\\d+)s)?(?:(\\d+)ms)?$/;\n const matches = value.match(durationRegex);\n\n if (!matches || matches[0] === '') {\n throw new Error(\n `Environment variable '${key}' has invalid duration format: \"${value}\". ` +\n `Use formats like 1y, 2w, 3d, 4h, 5m, 6s, or 7ms.`\n );\n }\n\n let ms = 0;\n\n if (matches[1]) ms += parseInt(matches[1], 10) * 31536000000; // years (approximate)\n if (matches[2]) ms += parseInt(matches[2], 10) * 604800000; // weeks\n if (matches[3]) ms += parseInt(matches[3], 10) * 86400000; // days\n if (matches[4]) ms += parseInt(matches[4], 10) * 3600000; // hours\n if (matches[5]) ms += parseInt(matches[5], 10) * 60000; // minutes\n if (matches[6]) ms += parseInt(matches[6], 10) * 1000; // seconds\n if (matches[7]) ms += parseInt(matches[7], 10); // milliseconds\n\n this.cache.set(cacheKey, ms);\n return ms;\n }\n\n /**\n * Gets all environment variables with sensitive values masked for safe logging.\n *\n * @param {string[]} [sensitiveKeys=['password', 'secret', 'key', 'token', 'auth']] - Keys to mask.\n * @returns {Record<string, string>} Environment variables with sensitive values masked.\n *\n * @example\n * console.log(Env.getSafeEnv(['password', 'secret', 'key']));\n * // { DATABASE_URL: \"postgres://...\", API_KEY: \"******\", ... }\n */\n static getSafeEnv(sensitiveKeys: string[] = ['password', 'secret', 'key', 'token', 'auth']): Record<string, string> {\n const safeEnv: Record<string, string> = {};\n\n for (const [key, value] of Object.entries(process.env)) {\n if (!value) continue;\n\n const isSensitive = sensitiveKeys.some(sensitiveKey => key.toLowerCase().includes(sensitiveKey.toLowerCase()));\n safeEnv[key] = isSensitive ? '******' : value;\n }\n\n return safeEnv;\n }\n\n /**\n * Loads environment variables from a .env file.\n * Does not override existing variables.\n *\n * @param {string} [path='.env'] - Path to the .env file.\n * @returns {Record<string, string>} Loaded environment variables.\n *\n * @example\n * // Load variables from .env.development\n * Env.loadFromFile('.env.development');\n */\n static loadFromFile(path: string = '.env'): Record<string, string> {\n if (!existsSync(path)) {\n throw new Error(`Environment file not found: \"${path}\"`);\n }\n\n const content = readFileSync(path, 'utf8');\n const variables: Record<string, string> = {};\n const lines = content.split(/\\r?\\n/);\n\n let i = 0;\n while (i < lines.length) {\n let line = lines[i].trim();\n\n // Skip empty lines or comment-only lines\n if (!line || line.startsWith('#')) {\n i++;\n continue;\n }\n\n const match = line.match(/^([^=]+)=(.*)$/);\n if (!match) {\n i++;\n continue;\n }\n\n const key = match[1].trim();\n let value = match[2].trim();\n\n // Remove inline comment for unquoted values\n if (!/^['\"]/.test(value)) {\n const hashIndex = value.indexOf(' #');\n if (hashIndex !== -1) {\n value = value.slice(0, hashIndex).trim();\n }\n }\n\n // Handle quoted values\n if ((value.startsWith('\"') || value.startsWith(\"'\")) && value.length > 1) {\n const quote = value[0];\n if (!value.endsWith(quote) || value.length === 1) {\n // multiline quoted\n let multilineValue = value.slice(1);\n i++;\n while (i < lines.length) {\n const nextLine = lines[i];\n if (nextLine.endsWith(quote)) {\n multilineValue += '\\n' + nextLine.slice(0, -1);\n break;\n } else {\n multilineValue += '\\n' + nextLine;\n }\n i++;\n }\n value = multilineValue;\n } else {\n // single-line quoted\n value = value.slice(1, -1);\n }\n } else {\n // Handle unquoted multiline: continue collecting until next key=value or empty line\n i++;\n while (i < lines.length && !lines[i].includes('=') && lines[i].trim() !== '') {\n value += '\\n' + lines[i];\n i++;\n }\n i--; // adjust for outer loop\n }\n\n if (!process.env[key]) {\n process.env[key] = value;\n variables[key] = value;\n }\n\n i++;\n }\n\n return variables;\n }\n\n /**\n * Checks whether the specified environment variable exists.\n *\n * @param {string} key - The environment variable key.\n * @returns {boolean} `true` if the variable is defined, otherwise `false`.\n */\n static has(key: string): boolean {\n return process.env[key] !== undefined;\n }\n\n /**\n * Deletes the given environment variable (useful in tests).\n *\n * @param {string} key - The environment variable key to delete.\n * @returns {void}\n */\n static delete(key: string): void {\n delete process.env[key];\n this.cache.delete(key);\n\n // Also clear all cached variations of this key\n for (const cacheKey of this.cache.keys()) {\n if (cacheKey.includes(`:${key}`)) {\n this.cache.delete(cacheKey);\n }\n }\n }\n\n /**\n * Clears the internal cache of parsed environment values.\n * Useful for testing or when environment variables might change.\n */\n static clearCache(): void {\n this.cache.clear();\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"exception.utils.js","sourceRoot":"","sources":["../../../src/utils/exception.utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAEjD;;;GAGG;AACH;IAA+B,6BAAa;IAC1C;;;;OAIG;IACH,mBAAY,MAAc,EAAE,OAAe;QACzC,YAAA,MAAK,YAAC,OAAO,CAAC,SAAC;QACf,KAAI,CAAC,MAAM,GAAG,MAAM,CAAC;;IACvB,CAAC;IACH,gBAAC;AAAD,CAAC,AAVD,CAA+B,aAAa,GAU3C;;AAED;;;GAGG;AACH;IAAkD,gDAAa;IAC7D;;OAEG;IACH,sCAAY,OAAyC;QAAzC,wBAAA,EAAA,iCAAyC;QACnD,YAAA,MAAK,YAAC,OAAO,CAAC,SAAC;QACf,KAAI,CAAC,MAAM,GAAG,eAAe,CAAC,qBAAq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","sourcesContent":["/*\n * The MIT License\n *\n * Copyright (c) 2025 Catbee Technologies. https://catbee-utils.npm.hprasath.com/license\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { HttpStatusCodes } from './http-status-codes';\nimport { getLogger } from './logger.utils';\nimport { ErrorResponse } from './response.utils';\n\n/**\n * Generic HTTP error class used for custom exceptions with any status code.\n * Inherit this when you need to throw errors dynamically at runtime.\n */\nexport class HttpError extends ErrorResponse {\n /**\n * Creates a new HTTP error instance.\n * @param status - A valid HTTP status code (e.g., 400, 500).\n * @param message - The error message to return to the client.\n */\n constructor(status: number, message: string) {\n super(message);\n this.status = status;\n }\n}\n\n/**\n * Represents a 500 Internal Server Error.\n * Use this for unexpected backend errors that are not caused by the client.\n */\nexport class InternalServerErrorException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Internal server error\".\n */\n constructor(message: string = 'Internal server error') {\n super(message);\n this.status = HttpStatusCodes.INTERNAL_SERVER_ERROR;\n }\n}\n\n/**\n * Represents a 401 Unauthorized Error.\n * Indicates that authentication is required and has failed or not been provided.\n */\nexport class UnauthorizedException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Unauthorized\".\n */\n constructor(message: string = 'Unauthorized') {\n super(message);\n this.status = HttpStatusCodes.UNAUTHORIZED;\n }\n}\n\n/**\n * Represents a 400 Bad Request Error.\n * Indicates that the client has sent invalid data (e.g., malformed request body).\n */\nexport class BadRequestException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Bad request\".\n */\n constructor(message: string = 'Bad request') {\n super(message);\n this.status = HttpStatusCodes.BAD_REQUEST;\n }\n}\n\n/**\n * Represents a 404 Not Found Error.\n * Used when a requested resource (e.g., user, file) could not be located.\n */\nexport class NotFoundException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Resource not found\".\n */\n constructor(message: string = 'Resource not found') {\n super(message);\n this.status = HttpStatusCodes.NOT_FOUND;\n }\n}\n\n/**\n * Represents a 403 Forbidden Error.\n * Indicates that the client is authenticated but not allowed to access the resource.\n */\nexport class ForbiddenException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Forbidden\".\n */\n constructor(message: string = 'Forbidden') {\n super(message);\n this.status = HttpStatusCodes.FORBIDDEN;\n }\n}\n\n/**\n * Represents a 409 Conflict Error.\n * Commonly used when a resource already exists or a versioning conflict occurs.\n */\nexport class ConflictException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Conflict\".\n */\n constructor(message: string = 'Conflict') {\n super(message);\n this.status = HttpStatusCodes.CONFLICT;\n }\n}\n\n/**\n * Represents a 502 Bad Gateway Error.\n * Used when the server receives an invalid response from an upstream server.\n */\nexport class BadGatewayException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Bad Gateway\".\n */\n constructor(message: string = 'Bad Gateway') {\n super(message);\n this.status = HttpStatusCodes.BAD_GATEWAY;\n }\n}\n\n/**\n * Represents a 429 Too Many Requests Error.\n * Returned when the client has hit a rate limit.\n */\nexport class TooManyRequestsException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Too many requests\".\n */\n constructor(message: string = 'Too many requests') {\n super(message);\n this.status = HttpStatusCodes.TOO_MANY_REQUESTS;\n }\n}\n\n/**\n * Represents a 503 Service Unavailable Error.\n * Indicates that the server is temporarily unavailable (e.g., for maintenance).\n */\nexport class ServiceUnavailableException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Service Unavailable\".\n */\n constructor(message: string = 'Service Unavailable') {\n super(message);\n this.status = HttpStatusCodes.SERVICE_UNAVAILABLE;\n }\n}\n\n/**\n * Represents a 504 Gateway Timeout Error.\n * Returned when the server acting as a gateway times out waiting for a response.\n */\nexport class GatewayTimeoutException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Gateway Timeout\".\n */\n constructor(message: string = 'Gateway Timeout') {\n super(message);\n this.status = HttpStatusCodes.GATEWAY_TIMEOUT;\n }\n}\n\n/**\n * Represents a 422 Unprocessable Entity Error.\n * Used when the server understands the content type but cannot process the contained instructions.\n */\nexport class UnprocessableEntityException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Unprocessable Entity\".\n * @param details - Optional validation details or additional error context.\n */\n constructor(\n message: string = 'Unprocessable Entity',\n public details?: Record<string, any>\n ) {\n super(message);\n this.status = HttpStatusCodes.UNPROCESSABLE_ENTITY;\n }\n}\n\n/**\n * Represents a 405 Method Not Allowed Error.\n * Used when the request method is not supported for the requested resource.\n */\nexport class MethodNotAllowedException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Method Not Allowed\".\n * @param allowedMethods - Optional array of allowed HTTP methods.\n */\n constructor(\n message: string = 'Method Not Allowed',\n public allowedMethods?: string[]\n ) {\n super(message);\n this.status = HttpStatusCodes.METHOD_NOT_ALLOWED;\n }\n}\n\n/**\n * Represents a 406 Not Acceptable Error.\n * Used when the server cannot produce a response matching the client's accepted content types.\n */\nexport class NotAcceptableException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Not Acceptable\".\n */\n constructor(message: string = 'Not Acceptable') {\n super(message);\n this.status = HttpStatusCodes.NOT_ACCEPTABLE;\n }\n}\n\n/**\n * Represents a 408 Request Timeout Error.\n * Used when the server times out waiting for the client to send a request.\n */\nexport class RequestTimeoutException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Request Timeout\".\n */\n constructor(message: string = 'Request Timeout') {\n super(message);\n this.status = HttpStatusCodes.REQUEST_TIMEOUT;\n }\n}\n\n/**\n * Represents a 415 Unsupported Media Type Error.\n * Used when the request's Content-Type is not supported.\n */\nexport class UnsupportedMediaTypeException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Unsupported Media Type\".\n */\n constructor(message: string = 'Unsupported Media Type') {\n super(message);\n this.status = HttpStatusCodes.UNSUPPORTED_MEDIA_TYPE;\n }\n}\n\n/**\n * Represents a 413 Payload Too Large Error.\n * Used when the request body exceeds server limits.\n */\nexport class PayloadTooLargeException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Payload Too Large\".\n */\n constructor(message: string = 'Payload Too Large') {\n super(message);\n this.status = HttpStatusCodes.PAYLOAD_TOO_LARGE;\n }\n}\n\n/**\n * Represents a 507 Insufficient Storage Error.\n * Used when the server has insufficient storage to complete the request.\n */\nexport class InsufficientStorageException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Insufficient Storage\".\n */\n constructor(message: string = 'Insufficient Storage') {\n super(message);\n this.status = HttpStatusCodes.INSUFFICIENT_STORAGE;\n }\n}\n\n/**\n * Checks if an error is an instance of HttpError or its subclasses.\n *\n * @param error - The error to check.\n * @returns True if the error is an HttpError, false otherwise.\n */\nexport function isHttpError(error: unknown): error is ErrorResponse {\n return error instanceof ErrorResponse;\n}\n\n/**\n * Creates an HTTP error with the specified status code and message.\n * Factory function for creating appropriate HTTP error instances.\n *\n * @param status - HTTP status code.\n * @param message - Optional custom error message.\n * @returns An instance of the appropriate HTTP error class.\n */\nexport function createHttpError(status: number, message?: string): ErrorResponse {\n switch (status) {\n case HttpStatusCodes.BAD_REQUEST:\n return new BadRequestException(message);\n case HttpStatusCodes.UNAUTHORIZED:\n return new UnauthorizedException(message);\n case HttpStatusCodes.FORBIDDEN:\n return new ForbiddenException(message);\n case HttpStatusCodes.NOT_FOUND:\n return new NotFoundException(message);\n case HttpStatusCodes.METHOD_NOT_ALLOWED:\n return new MethodNotAllowedException(message);\n case HttpStatusCodes.NOT_ACCEPTABLE:\n return new NotAcceptableException(message);\n case HttpStatusCodes.REQUEST_TIMEOUT:\n return new RequestTimeoutException(message);\n case HttpStatusCodes.CONFLICT:\n return new ConflictException(message);\n case HttpStatusCodes.GONE:\n return new HttpError(HttpStatusCodes.GONE, message || 'Gone');\n case HttpStatusCodes.PAYLOAD_TOO_LARGE:\n return new PayloadTooLargeException(message);\n case HttpStatusCodes.UNSUPPORTED_MEDIA_TYPE:\n return new UnsupportedMediaTypeException(message);\n case HttpStatusCodes.UNPROCESSABLE_ENTITY:\n return new UnprocessableEntityException(message);\n case HttpStatusCodes.TOO_MANY_REQUESTS:\n return new TooManyRequestsException(message);\n case HttpStatusCodes.INTERNAL_SERVER_ERROR:\n return new InternalServerErrorException(message);\n case HttpStatusCodes.BAD_GATEWAY:\n return new BadGatewayException(message);\n case HttpStatusCodes.SERVICE_UNAVAILABLE:\n return new ServiceUnavailableException(message);\n case HttpStatusCodes.GATEWAY_TIMEOUT:\n return new GatewayTimeoutException(message);\n case HttpStatusCodes.INSUFFICIENT_STORAGE:\n return new InsufficientStorageException(message);\n default:\n return new HttpError(status, message || `HTTP Error ${status}`);\n }\n}\n\n/**\n * Type guard to check if an object has specific error properties.\n *\n * @param error - The object to check.\n * @returns True if object has error-like structure.\n */\nexport function hasErrorShape(error: unknown): error is { message: string; status?: number; code?: string } {\n return (\n typeof error === 'object' && error !== null && 'message' in error && typeof (error as any).message === 'string'\n );\n}\n\n/**\n * Safely extracts message from any error type.\n *\n * @param error - Any error object or value.\n * @returns A string error message.\n */\nexport function getErrorMessage(error: unknown): string {\n if (typeof error === 'string') {\n return error;\n }\n\n if (error instanceof Error) {\n return error.message;\n }\n\n if (hasErrorShape(error)) {\n return error.message;\n }\n\n return 'Unknown error occurred';\n}\n\n/**\n * Wraps a function and transforms any errors into HTTP errors.\n * Useful for API handlers to ensure consistent error responses.\n *\n * @param handler - The async function to wrap.\n * @returns A function that always returns or throws an HTTP error.\n */\nexport function withErrorHandling<T extends (...args: any[]) => Promise<any>>(\n handler: T\n): (...args: Parameters<T>) => Promise<Awaited<ReturnType<T>>> {\n return async (...args: Parameters<T>) => {\n try {\n return await handler(...args);\n } catch (err) {\n if (isHttpError(err)) {\n throw err;\n }\n\n // Log the original error (consider using a proper logger)\n getLogger().error({ err }, 'Caught error in handler');\n\n // Extract status code if it exists, otherwise use 500\n let status = HttpStatusCodes.INTERNAL_SERVER_ERROR;\n if (hasErrorShape(err) && typeof err.status === 'number') {\n status = err.status;\n }\n\n // Create appropriate HTTP error\n throw createHttpError(status, getErrorMessage(err));\n }\n };\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"fs.utils.js","sourceRoot":"","sources":["../../../src/utils/fs.utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGH,OAAO,EAAE,MAAM,aAAa,CAAC;AAC7B,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAS,MAAM,IAAI,CAAC;AAChE,OAAO,EAAE,MAAM,EAAE,MAAM,IAAI,CAAC;AAC5B,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AAEpC;;;;;GAKG;AACH,MAAM,UAAgB,UAAU,CAAC,IAAY;;;;;;;oBAEzC,qBAAM,EAAE,CAAC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AAgB,cAAc,CAAC,IAAY;;;;;;;oBAEtC,qBAAM,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAA;wBAA9B,sBAAO,SAAuB,EAAC;;;oBAE/B,sBAAO,IAAI,EAAC;;;;;CAEf","sourcesContent":["/*\n * The MIT License\n *\n * Copyright (c) 2025 Catbee Technologies. https://catbee-utils.npm.hprasath.com/license\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { BufferEncoding } from './crypto.utils';\nimport fs from 'fs/promises';\nimport { createReadStream, createWriteStream, Stats } from 'fs';\nimport { tmpdir } from 'os';\nimport path from 'path';\nimport { pipeline } from 'stream/promises';\nimport { randomUUID } from 'crypto';\n\n/**\n * Checks whether a file or directory exists at the given path.\n *\n * @param {string} path - The file or directory path to check.\n * @returns {Promise<boolean>} Resolves to `true` if the path exists, `false` otherwise.\n */\nexport async function fileExists(path: string): Promise<boolean> {\n try {\n await fs.access(path);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Reads and parses a JSON file from the specified path.\n *\n * @typeParam T - The expected type of the parsed JSON object.\n * @param {string} path - The path to the JSON file.\n * @returns {Promise<T | null>} The parsed object, or `null` if reading or parsing fails.\n */\nexport async function readJsonFile<T = any>(path: string): Promise<T | null> {\n try {\n const data = await fs.readFile(path, 'utf-8');\n return JSON.parse(data) as T;\n } catch {\n return null;\n }\n}\n\n/**\n * Writes a JavaScript object to a file as formatted JSON.\n *\n * @param {string} path - The destination file path.\n * @param {any} data - The object to serialize and write.\n * @param {number} [space=2] - Number of spaces for JSON formatting.\n * @returns {Promise<void>} Resolves when writing is complete.\n */\nexport async function writeJsonFile(path: string, data: any, space = 2): Promise<void> {\n const json = JSON.stringify(data, null, space);\n await fs.writeFile(path, json, 'utf-8');\n}\n\n/**\n * Deletes a file if it exists.\n *\n * @param {string} path - The file path to delete.\n * @returns {Promise<boolean>} Resolves to `true` if the file was deleted or didn't exist, `false` if deletion failed.\n */\nexport async function deleteFileIfExists(path: string): Promise<boolean> {\n try {\n await fs.unlink(path);\n return true;\n } catch (err: any) {\n if (err.code === 'ENOENT') return true;\n return false;\n }\n}\n\n/**\n * Reads a text file from the specified path.\n *\n * @param {string} path - The path to the text file.\n * @param {BufferEncoding} [encoding=\"utf-8\"] - The encoding to use.\n * @returns {Promise<string | null>} The file contents, or `null` if reading fails.\n */\nexport async function readTextFile(path: string, encoding: BufferEncoding = 'utf-8'): Promise<string | null> {\n try {\n return await fs.readFile(path, encoding);\n } catch {\n return null;\n }\n}\n\n/**\n * Writes text content to a file.\n *\n * @param {string} path - The destination file path.\n * @param {string} content - The text content to write.\n * @param {BufferEncoding} [encoding=\"utf-8\"] - The encoding to use.\n * @returns {Promise<boolean>} Resolves to `true` if successful, `false` otherwise.\n */\nexport async function writeTextFile(\n path: string,\n content: string,\n encoding: BufferEncoding = 'utf-8'\n): Promise<boolean> {\n try {\n await fs.writeFile(path, content, encoding);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Appends text content to a file.\n *\n * @param {string} path - The file path to append to.\n * @param {string} content - The text content to append.\n * @param {BufferEncoding} [encoding=\"utf-8\"] - The encoding to use.\n * @returns {Promise<boolean>} Resolves to `true` if successful, `false` otherwise.\n */\nexport async function appendTextFile(\n path: string,\n content: string,\n encoding: BufferEncoding = 'utf-8'\n): Promise<boolean> {\n try {\n await fs.appendFile(path, content, encoding);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Copies a file from source to destination.\n *\n * @param {string} source - Source file path.\n * @param {string} destination - Destination file path.\n * @param {boolean} [overwrite=false] - Whether to overwrite if destination exists.\n * @returns {Promise<boolean>} Resolves to `true` if successful, `false` otherwise.\n */\nexport async function copyFile(source: string, destination: string, overwrite = false): Promise<boolean> {\n try {\n const flags = overwrite ? 0 : fs.constants.COPYFILE_EXCL;\n await fs.copyFile(source, destination, flags);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Renames/moves a file.\n *\n * @param {string} oldPath - Current file path.\n * @param {string} newPath - New file path.\n * @returns {Promise<boolean>} Resolves to `true` if successful, `false` otherwise.\n */\nexport async function moveFile(oldPath: string, newPath: string): Promise<boolean> {\n try {\n await fs.rename(oldPath, newPath);\n return true;\n } catch {\n // If rename fails (e.g., across devices), try copy+delete\n try {\n await fs.copyFile(oldPath, newPath);\n await fs.unlink(oldPath);\n return true;\n } catch {\n return false;\n }\n }\n}\n\n/**\n * Gets file stats if the file exists.\n *\n * @param {string} path - Path to the file.\n * @returns {Promise<fs.Stats | null>} File stats object or null if file doesn't exist.\n */\nexport async function getFileStats(path: string): Promise<Stats | null> {\n try {\n return await fs.stat(path);\n } catch {\n return null;\n }\n}\n\n/**\n * Creates a temporary file with optional content.\n *\n * @param {object} [options] - Options for creating the temp file.\n * @param {string} [options.prefix=\"tmp-\"] - Filename prefix.\n * @param {string} [options.extension=\"\"] - File extension.\n * @param {string} [options.dir] - Directory to create the file in (defaults to OS temp dir).\n * @param {string | Buffer} [options.content] - Optional content to write to the file.\n * @returns {Promise<string>} Path to the created temporary file.\n */\nexport async function createTempFile({\n prefix = 'tmp-',\n extension = '',\n dir = tmpdir(),\n content\n}: {\n prefix?: string;\n extension?: string;\n dir?: string;\n content?: string | Buffer;\n} = {}): Promise<string> {\n const ext = extension ? (extension.startsWith('.') ? extension : `.${extension}`) : '';\n const filename = `${prefix}${randomUUID()}${ext}`;\n const filepath = path.join(dir, filename);\n\n if (content) {\n await fs.writeFile(filepath, content);\n } else {\n await fs.writeFile(filepath, '');\n }\n\n return filepath;\n}\n\n/**\n * Streams a file from source to destination.\n * Useful for large files to avoid loading the entire file into memory.\n *\n * @param {string} source - Source file path.\n * @param {string} destination - Destination file path.\n * @returns {Promise<void>} Resolves when streaming completes.\n * @throws {Error} If streaming fails.\n */\nexport async function streamFile(source: string, destination: string): Promise<void> {\n const readStream = createReadStream(source);\n const writeStream = createWriteStream(destination);\n\n try {\n await pipeline(readStream, writeStream);\n } catch (error) {\n // Ensure both streams are closed in case of error\n readStream.destroy();\n writeStream.destroy();\n throw error;\n }\n}\n\n/**\n * Reads a directory and returns file names.\n *\n * @param {string} dirPath - Path to the directory.\n * @param {object} [options] - Options for reading the directory.\n * @param {boolean} [options.fullPaths=false] - Whether to return full paths.\n * @param {RegExp} [options.filter] - Optional regex to filter files.\n * @returns {Promise<string[]>} Array of file names or paths.\n * @throws {Error} If directory cannot be read.\n */\nexport async function readDirectory(\n dirPath: string,\n options: { fullPaths?: boolean; filter?: RegExp } = {}\n): Promise<string[]> {\n const files = await fs.readdir(dirPath);\n\n let result = files;\n\n if (options.filter) {\n result = result.filter(file => options.filter!.test(file));\n }\n\n if (options.fullPaths) {\n result = result.map(file => path.join(dirPath, file));\n }\n\n return result;\n}\n\n/**\n * Creates a directory if it doesn't exist.\n *\n * @param {string} dirPath - Path to the directory.\n * @param {boolean} [recursive=true] - Whether to create parent directories.\n * @returns {Promise<boolean>} Resolves to `true` if successful, `false` otherwise.\n */\nexport async function createDirectory(dirPath: string, recursive = true): Promise<boolean> {\n try {\n await fs.mkdir(dirPath, { recursive });\n return true;\n } catch (err: any) {\n // Consider it success if directory already exists\n return err.code === 'EEXIST';\n }\n}\n\n/**\n * Safely reads and parses a JSON file with error details.\n *\n * @typeParam T - The expected type of the parsed JSON object.\n * @param {string} path - The path to the JSON file.\n * @returns {Promise<{ data: T | null; error: Error | null }>} Object with data and error properties.\n */\nexport async function safeReadJsonFile<T = any>(path: string): Promise<{ data: T | null; error: Error | null }> {\n try {\n const content = await fs.readFile(path, 'utf-8');\n try {\n const data = JSON.parse(content) as T;\n return { data, error: null };\n } catch (error: any) {\n return {\n data: null,\n error: new Error(`Invalid JSON in file ${path}: ${error.message}`)\n };\n }\n } catch (error: any) {\n return {\n data: null,\n error: new Error(`Failed to read file ${path}: ${error.message}`)\n };\n }\n}\n\n/**\n * Checks if a path points to a file (not a directory).\n *\n * @param {string} path - Path to check.\n * @returns {Promise<boolean>} True if the path is a file, false otherwise.\n */\nexport async function isFile(path: string): Promise<boolean> {\n try {\n const stat = await fs.stat(path);\n return stat.isFile();\n } catch {\n return false;\n }\n}\n\n/**\n * Gets the size of a file in bytes.\n *\n * @param {string} path - Path to the file.\n * @returns {Promise<number>} Size in bytes or -1 if file doesn't exist.\n */\nexport async function getFileSize(path: string): Promise<number> {\n try {\n const stat = await fs.stat(path);\n return stat.size;\n } catch {\n return -1;\n }\n}\n\n/**\n * Reads a file as a Buffer.\n *\n * @param {string} path - Path to the file.\n * @returns {Promise<Buffer | null>} File contents as Buffer or null if reading fails.\n */\nexport async function readFileBuffer(path: string): Promise<Buffer | null> {\n try {\n return await fs.readFile(path);\n } catch {\n return null;\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"http-status-codes.js","sourceRoot":"","sources":["../../../src/utils/http-status-codes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH;;;GAGG;AACH,MAAM,CAAN,IAAY,eAwUX;AAxUD,WAAY,eAAe;IACzB,oBAAoB;IACpB;;OAEG;IACH,+DAAc,CAAA;I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IACH,uFAA0B,CAAA;IAE1B;;OAEG;IACH,2FAA4B,CAAA;IAE5B;;OAEG;IACH,6GAAqC,CAAA;IAErC;;OAEG;IACH,mFAAwB,CAAA;IAExB;;OAEG;IACH,qEAAiB,CAAA;IAEjB;;OAEG;IACH,2GAAoC,CAAA;IAEpC;;;OAGG;IACH,2EAAoB,CAAA;IAEpB;;OAEG;IACH,qFAAyB,CAAA;IAEzB;;OAEG;IACH,uFAA0B,CAAA;IAE1B;;OAEG;IACH,2DAAY,CAAA;IAEZ;;OAEG;IACH,iFAAuB,CAAA;IAEvB;;OAEG;IACH,+EAAsB,CAAA;IAEtB;;OAEG;IACH,yFAA2B,CAAA;IAE3B;;OAEG;IACH,iFAAuB,CAAA;IAEvB;;OAEG;IACH,6GAAqC,CAAA;IAErC;;OAEG;IACH,yGAAmC,CAAA;IAEnC,mBAAmB;IACnB;;OAEG;IACH,yFAA2B,CAAA;IAE3B;;OAEG;IACH,6EAAqB,CAAA;IAErB;;OAEG;IACH,qEAAiB,CAAA;IAEjB;;OAEG;IACH,qFAAyB,CAAA;IAEzB;;OAEG;IACH,6EAAqB,CAAA;IAErB;;OAEG;IACH,mGAAgC,CAAA;IAEhC;;OAEG;IACH,6FAA6B,CAAA;IAE7B;;OAEG;IACH,uFAA0B,CAAA;IAE1B;;OAEG;IACH,yEAAmB,CAAA;IAEnB;;OAEG;IACH,uEAAkB,CAAA;IAElB;;OAEG;IACH,6GAAqC,CAAA;AACvC,CAAC,EAxUW,eAAe,KAAf,eAAe,QAwU1B","sourcesContent":["/*\n * The MIT License\n *\n * Copyright (c) 2025 Catbee Technologies. https://catbee-utils.npm.hprasath.com/license\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n/**\n * Complete HTTP status codes enum with descriptions.\n * For use with API responses and error handling.\n */\nexport enum HttpStatusCodes {\n // 1xx Informational\n /**\n * The server has received the request headers and the client should proceed to send the request body.\n */\n CONTINUE = 100,\n\n /**\n * The server is switching protocols according to the client's request.\n */\n SWITCHING_PROTOCOLS = 101,\n\n /**\n * Server has received the request and is still processing it.\n */\n PROCESSING = 102,\n\n /**\n * The server is sending preliminary headers while preparing the final response.\n */\n EARLY_HINTS = 103,\n\n // 2xx Success\n /**\n * The request succeeded. The result meaning depends on the HTTP method used.\n */\n OK = 200,\n\n /**\n * The request succeeded and a new resource was created as a result.\n */\n CREATED = 201,\n\n /**\n * The request has been received but not yet acted upon.\n */\n ACCEPTED = 202,\n\n /**\n * The returned information is from a third-party source, not the origin server.\n */\n NON_AUTHORITATIVE_INFORMATION = 203,\n\n /**\n * The request succeeded but there's no content to send in the response.\n */\n NO_CONTENT = 204,\n\n /**\n * The client should reset the document view that caused this request.\n */\n RESET_CONTENT = 205,\n\n /**\n * The server is delivering only part of the resource due to a range header sent by the client.\n */\n PARTIAL_CONTENT = 206,\n\n /**\n * Conveys information about multiple resources, for complex operations.\n */\n MULTI_STATUS = 207,\n\n /**\n * The members of a DAV binding have already been enumerated and are not included in the response.\n */\n ALREADY_REPORTED = 208,\n\n /**\n * The server has fulfilled a request for the resource, and the response represents the result of one or more instance-manipulations.\n */\n IM_USED = 226,\n\n // 3xx Redirection\n /**\n * The request has more than one possible response and the client should choose one.\n */\n MULTIPLE_CHOICES = 300,\n\n /**\n * The resource has been permanently moved to a new URL.\n */\n MOVED_PERMANENTLY = 301,\n\n /**\n * The resource has been temporarily moved to another URL.\n */\n MOVED_TEMPORARILY = 302,\n\n /**\n * The response to the request can be found under another URI using the GET method.\n */\n SEE_OTHER = 303,\n\n /**\n * The resource hasn't been modified since the last request.\n */\n NOT_MODIFIED = 304,\n\n /**\n * @deprecated\n * Response must be accessed through a proxy.\n */\n USE_PROXY = 305,\n\n /**\n * The resource is temporarily available at a different URI, using the same HTTP method.\n */\n TEMPORARY_REDIRECT = 307,\n\n /**\n * The resource has been permanently moved to another URL, using the same HTTP method.\n */\n PERMANENT_REDIRECT = 308,\n\n // 4xx Client Error\n /**\n * The server cannot process the request due to a client error (malformed request).\n */\n BAD_REQUEST = 400,\n\n /**\n * Authentication is required and has failed or not been provided.\n */\n UNAUTHORIZED = 401,\n\n /**\n * Reserved for future use, originally intended for digital payment systems.\n */\n PAYMENT_REQUIRED = 402,\n\n /**\n * The client doesn't have permission to access the requested resource.\n */\n FORBIDDEN = 403,\n\n /**\n * The requested resource could not be found on the server.\n */\n NOT_FOUND = 404,\n\n /**\n * The request method is not supported for the requested resource.\n */\n METHOD_NOT_ALLOWED = 405,\n\n /**\n * The server can't provide a response matching the list of acceptable values in the client's headers.\n */\n NOT_ACCEPTABLE = 406,\n\n /**\n * Authentication by a proxy is required.\n */\n PROXY_AUTHENTICATION_REQUIRED = 407,\n\n /**\n * The server timed out waiting for the request.\n */\n REQUEST_TIMEOUT = 408,\n\n /**\n * The request conflicts with the current state of the server.\n */\n CONFLICT = 409,\n\n /**\n * The resource has been permanently deleted with no forwarding address.\n */\n GONE = 410,\n\n /**\n * The server requires a Content-Length header field.\n */\n LENGTH_REQUIRED = 411,\n\n /**\n * Preconditions in the client's headers failed.\n */\n PRECONDITION_FAILED = 412,\n\n /**\n * Request entity is larger than limits defined by server.\n */\n REQUEST_TOO_LONG = 413,\n\n /**\n * The request payload exceeds server size limits.\n * Modern equivalent of REQUEST_TOO_LONG.\n */\n PAYLOAD_TOO_LARGE = 413,\n\n /**\n * The URI requested is too long for the server to interpret.\n */\n REQUEST_URI_TOO_LONG = 414,\n\n /**\n * The server does not support the media type requested by the client.\n */\n UNSUPPORTED_MEDIA_TYPE = 415,\n\n /**\n * The range specified by the Range header cannot be fulfilled.\n */\n REQUESTED_RANGE_NOT_SATISFIABLE = 416,\n\n /**\n * The server cannot meet the expectations given in the Expect header.\n */\n EXPECTATION_FAILED = 417,\n\n /**\n * The server refuses to brew coffee because it is a teapot. (April Fools' joke)\n */\n IM_A_TEAPOT = 418,\n\n /**\n * The server cannot store the representation needed to complete the request.\n */\n INSUFFICIENT_SPACE_ON_RESOURCE = 419,\n\n /**\n * @deprecated\n * A method has failed - specific to Spring Framework.\n */\n METHOD_FAILURE = 420,\n\n /**\n * The server cannot produce a response for the requested URI scheme and authority.\n */\n MISDIRECTED_REQUEST = 421,\n\n /**\n * The request was well-formed but has semantic errors preventing processing.\n */\n UNPROCESSABLE_ENTITY = 422,\n\n /**\n * The requested resource is locked against access.\n */\n LOCKED = 423,\n\n /**\n * The request failed due to the failure of a previous request.\n */\n FAILED_DEPENDENCY = 424,\n\n /**\n * The client should switch to a different protocol.\n */\n UPGRADE_REQUIRED = 426,\n\n /**\n * The server requires conditional requests to prevent lost updates.\n */\n PRECONDITION_REQUIRED = 428,\n\n /**\n * The client has sent too many requests in a given time period (rate limiting).\n */\n TOO_MANY_REQUESTS = 429,\n\n /**\n * Request headers are too large for the server to process.\n */\n REQUEST_HEADER_FIELDS_TOO_LARGE = 431,\n\n /**\n * Resource cannot be legally provided (e.g., censored by government).\n */\n UNAVAILABLE_FOR_LEGAL_REASONS = 451,\n\n // 5xx Server Error\n /**\n * The server encountered an unexpected error preventing it from fulfilling the request.\n */\n INTERNAL_SERVER_ERROR = 500,\n\n /**\n * The server does not support the functionality required to fulfill the request.\n */\n NOT_IMPLEMENTED = 501,\n\n /**\n * The server, acting as a gateway, received an invalid response from an upstream server.\n */\n BAD_GATEWAY = 502,\n\n /**\n * The server is currently unable to handle the request due to temporary overload or maintenance.\n */\n SERVICE_UNAVAILABLE = 503,\n\n /**\n * The server, acting as a gateway, did not receive a timely response from an upstream server.\n */\n GATEWAY_TIMEOUT = 504,\n\n /**\n * The server does not support the HTTP protocol version used in the request.\n */\n HTTP_VERSION_NOT_SUPPORTED = 505,\n\n /**\n * Transparent content negotiation for the request resulted in circular reference.\n */\n VARIANT_ALSO_NEGOTIATES = 506,\n\n /**\n * The server cannot store the representation needed to complete the request.\n */\n INSUFFICIENT_STORAGE = 507,\n\n /**\n * The server detected an infinite loop while processing the request.\n */\n LOOP_DETECTED = 508,\n\n /**\n * Further extensions to the request are required for the server to fulfill it.\n */\n NOT_EXTENDED = 510,\n\n /**\n * The client needs to authenticate to gain network access.\n */\n NETWORK_AUTHENTICATION_REQUIRED = 511\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"id.utils.js","sourceRoot":"","sources":["../../../src/utils/id.utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,QAAQ,CAAC;AAEjD;;;;GAIG;AACH,MAAM,UAAU,IAAI;IAClB,OAAO,UAAU,EAAE,CAAC;AACtB,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,MAAM,CAAC,MAAmB;IAAnB,uBAAA,EAAA,WAAmB;IACxC,IAAI,MAAM,IAAI,CAAC;QAAE,OAAO,EAAE,CAAC;IAC3B,IAAI,EAAE,GAAG,EAAE,CAAC;IACZ,OAAO,EAAE,CAAC,MAAM,GAAG,MAAM,EAAE,CAAC;QAC1B,EAAE,IAAI,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;aAC3C,QAAQ,CAAC,WAAW,CAAC;aACrB,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;IAC3B,CAAC;IACD,OAAO,EAAE,CAAC,KAAK,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;AAC7B,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,SAAS,CAAC,UAAuB;IAAvB,2BAAA,EAAA,eAAuB;IAC/C,6DAA6D;IAC7D,kGAAkG;IAClG,OAAO,WAAW,CAAC,UAAU,CAAC;SAC3B,QAAQ,CAAC,KAAK,CAAC;SACf,QAAQ,CAAC,UAAU,GAAG,CAAC,EAAE,GAAG,CAAC;SAC7B,KAAK,CAAC,CAAC,EAAE,UAAU,GAAG,CAAC,CAAC,CAAC;AAC9B,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,SAAS,CAAC,GAAW,EAAE,GAAW;IAChD,IAAM,KAAK,GAAG,GAAG,GAAG,GAAG,GAAG,CAAC,CAAC;IAC5B,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,KAAK,CAAC,GAAG,GAAG,CAAC;AACjD,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,YAAY,CAAC,UAAuB;IAAvB,2BAAA,EAAA,eAAuB;IAClD,OAAO,WAAW,CAAC,UAAU,CAAC,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC;AACvD,CAAC","sourcesContent":["/*\n * The MIT License\n *\n * Copyright (c) 2025 Catbee Technologies. https://catbee-utils.npm.hprasath.com/license\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { randomUUID, randomBytes } from 'crypto';\n\n/**\n * Generates a UUID v4 string (RFC 4122).\n *\n * @returns {string} UUID v4 (e.g., 'c0de1234-5678-9abc-def0-123456789abc')\n */\nexport function uuid(): string {\n return randomUUID();\n}\n\n/**\n * Generates a nanoid-style random ID (URL-safe, customizable length).\n *\n * @param {number} length - Length of the ID (default: 21).\n * @returns {string} Nanoid-style random string.\n */\nexport function nanoId(length: number = 21): string {\n if (length <= 0) return '';\n let id = '';\n while (id.length < length) {\n id += randomBytes(Math.ceil((length * 3) / 4))\n .toString('base64url')\n .replace(/[+/=]/g, '');\n }\n return id.slice(0, length);\n}\n\n/**\n * Generates a cryptographically strong random hex string.\n *\n * @param {number} byteLength - Number of random bytes (default: 16 → 32 hex chars).\n * @returns {string} Random hex string.\n */\nexport function randomHex(byteLength: number = 16): string {\n // Use Node.js crypto for both Node and browser compatibility\n // Prefer randomBytes if available (Node), fallback to getRandomValues for browser (not used here)\n return randomBytes(byteLength)\n .toString('hex')\n .padStart(byteLength * 2, '0')\n .slice(0, byteLength * 2);\n}\n\n/**\n * Generates a random integer between min (inclusive) and max (inclusive).\n *\n * @param {number} min - Minimum value.\n * @param {number} max - Maximum value.\n * @returns {number} Random integer in range.\n */\nexport function randomInt(min: number, max: number): number {\n const range = max - min + 1;\n return Math.floor(Math.random() * range) + min;\n}\n\n/**\n * Generates a cryptographically strong random base64 string.\n *\n * @param {number} byteLength - Number of random bytes (default: 16).\n * @returns {string} Random base64 string (URL-safe, no padding).\n */\nexport function randomBase64(byteLength: number = 16): string {\n return randomBytes(byteLength).toString('base64url');\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"logger.utils.js","sourceRoot":"","sources":["../../../src/utils/logger.utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,OAAO,IAAI,EAAE,EAAiB,gBAAgB,EAAE,MAAM,MAAM,CAAC;AAE7D,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACnC,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAChE,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAElC;;GAEG;AACH,IAAM,iBAAiB,GAAG,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;AAY/C,2BAA2B;AAC3B,MAAM,CAAC,IAAM,sBAAsB,GAAG;IACpC,UAAU;IACV,QAAQ;IACR,OAAO;IACP,QAAQ;IACR,SAAS;IACT,MAAM;IACN,KAAK;IACL,cAAc;IACd,eAAe;IACf,eAAe;IACf,eAAe;CAChB,CAAC;AAEF;;GAEG;AACH,IAAI,kBAAkB,GAA2E,UAC/F,KAAK,EACL,IAAI,EACJ,eAAwC;IAAxC,gCAAA,EAAA,wCAAwC;IAExC,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IAE5C,IAAM,SAAS,GAAG,IAAI,CAAC,GAAG,CAAC,UAAA,CAAC,IAAI,OAAA,CAAC,CAAC,WAAW,EAAE,EAAf,CAAe,CAAC,CAAC;IACjD,IAAM,oBAAoB,GAAG,eAAe,CAAC,GAAG,CAAC,UAAA,CAAC,IAAI,OAAA,CAAC,CAAC,WAAW,EAAE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prasath.com/license\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport pino, { LoggerOptions, stdTimeFunctions } from 'pino';\nimport type { Logger as PinoLogger } from 'pino'; // Type-only import\nimport { config } from '../config';\nimport { ContextStore, StoreKeys } from './context-store.utils';\nimport { Env } from './env.utils';\n\n/**\n * Symbol used to store the root logger in the Node.js global object.\n */\nconst GLOBAL_LOGGER_KEY = Symbol.for('logger');\n\n/**\n * Logger type for application-wide logging.\n */\nexport type Logger = pino.Logger;\n\n/**\n * Logger levels for application-wide logging.\n */\nexport type LoggerLevels = pino.Level;\n\n// Default sensitive fields\nexport const defaultSensitiveFields = [\n 'password',\n 'secret',\n 'token',\n 'apiKey',\n 'api_key',\n 'auth',\n 'jwt',\n 'access_token',\n 'client_secret',\n 'session_token',\n 'refresh_token'\n];\n\n/**\n * The global censor function used by the logger.\n */\nlet globalRedactCensor: (value: unknown, path: string[], sensitiveFields?: string[]) => string = (\n value,\n path,\n sensitiveFields = defaultSensitiveFields\n) => {\n if (typeof value !== 'string') return '***';\n\n const lowerPath = path.map(p => p.toLowerCase());\n const lowerSensitiveFields = sensitiveFields.map(f => f.toLowerCase());\n\n if (lowerPath.some(p => lowerSensitiveFields.includes(p))) return '***';\n\n // Redact URLs\n if (lowerPath[0] === 'url') {\n return value.replace(new RegExp(`([?&](${lowerSensitiveFields.join('|')})=)[^&#]*`, 'gi'), '$1***');\n }\n\n if (lowerPath.some(p => p.includes('authorization') || p.includes('auth'))) {\n return value.replace(/^(\\S+)\\s+.+$/, '$1 ***') || '***';\n }\n\n // Redact sensitive fields - check each path segment against each sensitive field\n if (lowerPath.some(pathPart => lowerSensitiveFields.some(field => pathPart.includes(field)))) {\n return '***';\n }\n\n if (path.length > 0 && !['req', 'res', 'headers'].includes(lowerPath[0])) {\n return value;\n }\n\n return value;\n};\n\n/**\n * Sets the global redaction censor function used throughout the application for log redaction.\n *\n * Use this function to customize how sensitive data is redacted in logs. The provided function\n * will replace the default censor implementation.\n *\n * @example\n * ```typescript\n * // Custom censor that redacts only specific values\n * setRedactCensor((value, path, sensitiveFields) => {\n * if (path.includes('password')) return '***';\n * return value;\n * });\n * ```\n *\n * @param fn - The redaction censor function to use globally. This function receives:\n * - value: The data value to potentially redact\n * - path: Array of strings representing the path to the value in the object\n * - sensitiveFields: Optional array of field names to consider sensitive\n * @returns void\n */\nexport function setRedactCensor(fn: (value: unknown, path: string[], sensitiveFields?: string[]) => string) {\n globalRedactCensor = fn;\n}\n\n/**\n * Gets the current global redaction censor function used for log redaction.\n *\n * This function is called internally by the logger when determining how to redact\n * sensitive information. It can also be used to access the current censor implementation\n * for composition or extension.\n *\n * @example\n * ```typescript\n * const currentCensor = getRedactCensor();\n * // Create an enhanced censor that extends the current one\n * setRedactCensor((value, path, fields) => {\n * // Add custom logic before delegating to current censor\n * if (someCondition) return customHandling();\n * return currentCensor(value, path, fields);\n * });\n * ```\n *\n * @returns The current redaction censor function\n */\nexport function getRedactCensor() {\n return globalRedactCensor;\n}\n\n/**\n * Convenience function to redact sensitive data using the current global redact censor.\n *\n * This is a direct wrapper around the global censor function that simplifies usage\n * in application code without needing to access the censor function directly.\n *\n * @example\n * ```typescript\n * // Redact a potential sensitive value\n * const safeValue = redact(value, ['user', 'apiKey']);\n * ```\n *\n * @param value - The value to potentially redact\n * @param path - Array of strings representing the path to the value in the object\n * @param sensitiveFields - Optional array of field names to consider sensitive\n * @returns The redacted string value or \"***\" for redacted content\n */\nexport function redact(value: unknown, path: string[], sensitiveFields?: string[]) {\n return globalRedactCensor(value, path, sensitiveFields);\n}\n\n/**\n * Extends the current redaction function with additional fields to redact.\n *\n * This function wraps the existing censor while adding more fields to be considered\n * sensitive without replacing the entire redaction logic.\n *\n * @example\n * ```typescript\n * // Add custom fields to be redacted in all future redaction operations\n * addRedactFields(['customerId', 'accountNumber']);\n * ```\n *\n * @param fields - Array of additional field names to redact\n */\nexport function addRedactFields(fields: string[]) {\n const prev = globalRedactCensor;\n globalRedactCensor = (value, path, sensitiveFields = defaultSensitiveFields) =>\n prev(value, path, [...(sensitiveFields || []), ...fields]);\n}\n\n/**\n * Replaces the default list of sensitive fields with a new list.\n *\n * This is useful when you want complete control over what fields are considered\n * sensitive by default, rather than using the library's built-in list.\n *\n * @example\n * ```typescript\n * // Replace default sensitive fields with a custom list\n * setSensitiveFields(['password', 'ssn', 'creditCard']);\n * ```\n *\n * @param fields - Array of field names to set as the new default sensitive fields\n */\nexport function setSensitiveFields(fields: string[]) {\n defaultSensitiveFields.splice(0, defaultSensitiveFields.length, ...fields);\n}\n\n/**\n * Adds additional field names to the default sensitive fields list.\n *\n * This preserves the existing sensitive fields while adding new ones for\n * application-specific sensitive data.\n *\n * @example\n * ```typescript\n * // Add domain-specific sensitive fields to the default list\n * addSensitiveFields(['socialSecurityNumber', 'medicalRecordNumber']);\n * ```\n *\n * @param fields - Array of additional field names to add to the sensitive fields list\n */\nexport function addSensitiveFields(fields: string[]) {\n defaultSensitiveFields.push(...fields);\n}\n\n/**\n * Use an object compatible with either modern or legacy global scopes.\n */\nexport const _globalThis = typeof globalThis === 'object' ? globalThis : global;\nconst _global = _globalThis as unknown as { [GLOBAL_LOGGER_KEY]: PinoLogger };\n\n/**\n * Initializes the global root logger according to app configuration.\n *\n * - Sets log name, level, timestamp, and redaction for sensitive fields.\n * - Uses singleton in global symbol registry.\n */\nfunction setupLogger(): void {\n const logParams: LoggerOptions = {\n name: config.logger.name || '@catbee/utils',\n level: config.logger.level || 'info',\n redact: {\n paths: ['req.authorization', 'res.authorization', 'url', 'headers.authorization', 'headers.cookies'],\n censor: (value, path) => redact(value, path)\n },\n // serializers: {\n // req: pino.stdSerializers.req,\n // request: pino.stdSerializers.req,\n // res: pino.stdSerializers.res,\n // response: pino.stdSerializers.res,\n // err: pino.stdSerializers.err,\n // error: pino.stdSerializers.err\n // },\n timestamp: stdTimeFunctions.isoTime\n };\n\n const logger =\n config.logger.pretty && Env.isDev()\n ? pino(\n logParams,\n pino.transport({\n target: 'pino-pretty',\n options: {\n colorize: true,\n translateTime: 'SYS:standard',\n ignore: 'pid,hostname',\n singleLine: config.logger.singleLine,\n levelFirst: true\n }\n })\n )\n : pino(logParams);\n\n _global[GLOBAL_LOGGER_KEY] = logger;\n _global[GLOBAL_LOGGER_KEY]?.debug('Logger initialized');\n}\n\n/**\n * Retrieves the current logger instance:\n * - Returns a request-scoped logger from AsyncLocalStorage if available\n * - Falls back to the global (singleton) logger\n * - Initializes the global logger if not created yet\n *\n * @returns {Logger} The logger instance (request-bound or global root logger)\n */\nexport function getLogger(): PinoLogger {\n const logger = ContextStore.get<PinoLogger>(StoreKeys.LOGGER);\n if (logger) return logger;\n\n if (!_global[GLOBAL_LOGGER_KEY]) {\n setupLogger();\n }\n\n return _global[GLOBAL_LOGGER_KEY];\n}\n\n/**\n * Logger instance for the global context.\n * This logger is used for logging messages that are not tied to a specific request.\n */\nexport const logger = getLogger();\n\n/**\n * Creates a child logger with additional context.\n *\n * @param {Record<string, any>} bindings - Properties to attach to all log records\n * @param {Logger} [parentLogger] - Parent logger (defaults to current context logger or global)\n * @returns {Logger} Child logger with merged context\n */\nexport function createChildLogger(bindings: Record<string, any>, parentLogger?: PinoLogger): PinoLogger {\n const logger = parentLogger || getLogger();\n return logger.child(bindings);\n}\n\n/**\n * Creates a request-scoped logger with request ID and stores it in context\n *\n * @param {string} requestId - Unique request identifier\n * @param {object} [additionalContext] - Additional context to include in logs\n * @returns {Logger} Request-scoped logger instance\n */\nexport function createRequestLogger(requestId: string, additionalContext: Record<string, any> = {}): PinoLogger {\n const logger = createChildLogger({\n requestId,\n ...additionalContext\n });\n\n try {\n ContextStore.set(StoreKeys.LOGGER, logger);\n } catch {\n // Context not initialized, can't store logger\n logger.debug('Failed to store logger in context - AsyncLocalStorage not initialized');\n }\n\n return logger;\n}\n\n/**\n * Utility to safely log errors with proper stack trace extraction\n *\n * @param {Error|unknown} error - Error object to log\n * @param {string} [message] - Optional message to include\n * @param {Record<string, any>} [context] - Additional context properties\n */\nexport function logError(error: Error | unknown, message?: string, context?: Record<string, any>): void {\n const logger = getLogger();\n\n const errObj = error instanceof Error ? error : new Error(String(error));\n const logContext = {\n ...context,\n error: errObj\n };\n\n logger.error(logContext, message || errObj.message);\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"middleware.utils.js","sourceRoot":"","sources":["../../../src/utils/middleware.utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAClC,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,wBAAwB,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAC3E,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAE3C,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAChE,OAAO,EAAE,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,GAAG,KAAK,CAAC;;;;oBAEhC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC;oBAC5B,UAAU,GAAG,KAAK,CAAC;;;;;;;;;;;;;;;;;oBAGjB,MAAM,GAAG,UAAU,CAAC,CAAC,CAAC,eAAe,CAAC,EAAE,CAAC,CAAC,CAAC,eAAe,CAAC,mBAAmB,CAAC;oBAC/E,QAAQ,GAAG,QAAQ;wBACvB,CAAC,CAAC,EAAE,MAAM,EAAE,UAAU,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,WAAW,EAAE,MAAM,EAAE,OAAO,EAAE,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,EAAE;wBACnG,CAAC,CAAC,EAAE,MAAM,EAAE,UAAU,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC;oBAChD,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;;;;SACnC,CAAC;AACJ,CAAC","sourcesContent":["/*\n * The MIT License\n *\n * Copyright (c) 2025 Catbee Technologies. https://catbee-utils.npm.hprasath.com/license\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { uuid } from './id.utils';\nimport { HttpStatusCodes } from './http-status-codes';\nimport { createFinalErrorResponse, ErrorResponse } from './response.utils';\nimport { getLogger } from './logger.utils';\nimport type { Request, Response, NextFunction } from 'express';\nimport { ContextStore, StoreKeys } from './context-store.utils';\nimport { RequestTimeoutException } from './exception.utils';\nimport { ApiErrorResponse } from '../types/api-response';\n\nexport type Middleware = (req: Request, res: Response, next: NextFunction) => void | Promise<void>;\n\n/**\n * Attaches a unique request ID to each request.\n * Useful for request tracing and correlation between logs.\n *\n * @param {object} [options] - Configuration options\n * @param {string} [options.headerName='X-Request-ID'] - Header name for request ID\n * @param {boolean} [options.exposeHeader=true] - Whether to expose the header in response\n * @param {() => string} [options.generator] - Custom ID generator function\n * @returns {Middleware} Express-compatible middleware\n */\nexport function requestId(options?: {\n headerName?: string;\n exposeHeader?: boolean;\n generator?: () => string;\n}): Middleware {\n const headerName = options?.headerName || 'X-Request-ID';\n const exposeHeader = options?.exposeHeader !== false;\n const generateId = options?.generator || uuid;\n\n return (req, res, next) => {\n // Use existing request ID from header or generate a new one\n const existingId = req.headers[headerName.toLowerCase()];\n const id = (existingId as string) || generateId();\n\n // Attach ID to request object\n req.id = id;\n\n // Add ID to response headers\n if (exposeHeader) {\n res.setHeader(headerName, id);\n }\n\n next();\n };\n}\n\n/**\n * Measures request processing time and logs or adds it to response headers.\n *\n * @param {object} [options] - Configuration options\n * @param {boolean} [options.addHeader=true] - Whether to add X-Response-Time header\n * @param {boolean} [options.logOnComplete=false] - Whether to log timing info\n * @returns {Middleware} Express-compatible middleware\n */\nexport function responseTime(options?: { addHeader?: boolean; logOnComplete?: boolean }) {\n const addHeader = options?.addHeader !== false;\n const logOnComplete = options?.logOnComplete === true;\n\n return (req: Request, res: Response, next: NextFunction) => {\n const start = process.hrtime();\n\n // Function to calculate duration\n const getDuration = () => {\n const diff = process.hrtime(start);\n return (diff[0] * 1e3 + diff[1] * 1e-6).toFixed(2);\n };\n\n if (addHeader) {\n // Ensure header is set before response is sent\n const originalWriteHead = res.writeHead;\n res.writeHead = function (...args: any[]) {\n res.setHeader('X-Response-Time', `${getDuration()}ms`);\n return originalWriteHead.apply(this, args as any);\n };\n }\n\n if (logOnComplete) {\n res.on('finish', () => {\n getLogger().info(`${req.method} ${req.url} - ${getDuration()}ms`);\n });\n }\n\n next();\n };\n}\n\n/**\n * Request timeout middleware.\n * Aborts requests that take too long to process.\n *\n * @param {number} [timeoutMs=30000] - Timeout in milliseconds\n * @returns {Middleware} Express-compatible middleware\n */\nexport function timeout(timeoutMs: number = 30000): Middleware {\n return (_req, res, next) => {\n // Set timeout for the request\n const timer = setTimeout(() => {\n const response = new RequestTimeoutException('Request timed out');\n res.status(HttpStatusCodes.REQUEST_TIMEOUT).json(response);\n }, timeoutMs);\n\n // Clear timeout when response is sent\n res.on('finish', () => {\n clearTimeout(timer);\n });\n\n next();\n };\n}\n\n/**\n * Creates an Express middleware that initializes a per-request context.\n *\n * @param {object} [options] - Optional configuration\n * @param {string} [options.headerName='x-request-id'] - Header to look for request ID\n * @param {boolean} [options.autoLog=true] - Whether to log automatically when context is initialized\n * @returns {(req: Request, res: Response, next: NextFunction) => void} Express middleware function\n */\nexport function setupRequestContext(options: { headerName?: string; autoLog?: boolean } = {}): Middleware {\n const { headerName = 'x-request-id', autoLog = true } = options;\n return (req, _res, next) => {\n // Generate or use existing request ID\n const requestId = (req.headers[headerName] as string) || req?.['id'] || uuid();\n\n ContextStore.run({ [StoreKeys.REQUEST_ID]: requestId }, () => {\n // Create a child logger for this request\n const childLogger = getLogger().child({\n requestId,\n method: req.method,\n url: req.originalUrl || req.url\n });\n\n req.logger = childLogger;\n\n // Store logger in context\n ContextStore.set(StoreKeys.LOGGER, childLogger);\n\n if (autoLog) {\n req.logger.info('Request context initialized');\n }\n\n next();\n });\n };\n}\n\nexport interface ErrorHandlerOptions {\n /** Whether to log errors (default: true) */\n logErrors?: boolean;\n /** Whether to include error details in non-production (default: false) */\n includeDetails?: boolean;\n}\n\n/**\n * Global error handling middleware with enhanced features.\n *\n * @param {ErrorHandlerOptions} options - Error handler options\n * @param {boolean} [options.logErrors=true] - Whether to log errors\n * @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production\n * @returns Error middleware\n *\n * @example\n * import express from 'express';\n * import { errorHandler } from '@catbee/utils';\n *\n * const app = express();\n *\n * // Your routes\n * app.get('/ping', (req, res) => {\n * throw new Error('Something went wrong');\n * });\n *\n * // Error handler (must be last middleware)\n * app.use(errorHandler({ includeDetails: true }));\n *\n * app.listen(3000, () => {\n * console.log('Server running on port 3000');\n * });\n */\nexport function errorHandler(options?: ErrorHandlerOptions) {\n const logErrors = options?.logErrors !== false;\n const includeDetails = options?.includeDetails === true;\n\n return (err: any, req: Request, res: Response, _next: NextFunction) => {\n // Determine status code\n const status = err?.status || err?.statusCode || HttpStatusCodes.INTERNAL_SERVER_ERROR;\n\n // Log error if enabled\n if (logErrors) {\n getLogger().error({ err }, `${err.message || 'Unknown error'}`);\n }\n\n // Handle ErrorResponse instances (our custom error class)\n if (err instanceof ErrorResponse) {\n const result: ApiErrorResponse = {\n error: true,\n message: err.message,\n timestamp: err.timestamp,\n requestId: err?.requestId || req?.id || uuid(),\n status,\n path: req.originalUrl || req.url\n };\n\n if (includeDetails && err?.stack) {\n result.stack = err.stack.split('\\n').map((line: string) => line.trim());\n }\n return res.status(status).json(result);\n }\n\n // Handle any other errors\n return res\n .status(status)\n .json(createFinalErrorResponse(req, status, err?.message || 'Internal Server Error', err, { includeDetails }));\n };\n}\n\n/**\n * Health check middleware for service status and custom checks.\n *\n * @param {object} [options] - Health check options\n * @param {string} [options.path='/healthz'] - Health check endpoint path\n * @param {Array<{name: string; check: () => Promise<boolean> | boolean}>} [options.checks] - Custom health checks\n * @param {boolean} [options.detailed=true] - Show detailed check results\n * @returns {Middleware} Express-compatible middleware\n */\nexport function healthCheck(options?: {\n path?: string;\n checks?: Array<{ name: string; check: () => Promise<boolean> | boolean }>;\n detailed?: boolean;\n}): Middleware {\n const path = options?.path || '/healthz';\n const checks = options?.checks || [];\n const detailed = options?.detailed !== false;\n\n return async (req, res, next) => {\n if (req.path !== path) return next();\n const results: Record<string, boolean> = {};\n let allHealthy = true;\n for (const check of checks) {\n try {\n const result = await Promise.resolve(check.check());\n results[check.name] = !!result;\n if (!result) allHealthy = false;\n } catch {\n results[check.name] = false;\n allHealthy = false;\n }\n }\n const status = allHealthy ? HttpStatusCodes.OK : HttpStatusCodes.SERVICE_UNAVAILABLE;\n const response = detailed\n ? { status: allHealthy ? 'ok' : 'unhealthy', checks: results, timestamp: new Date().toISOString() }\n : { status: allHealthy ? 'ok' : 'unhealthy' };\n res.status(status).json(response);\n };\n}\n"]}