@catbee/utils 0.0.8-rc.1 → 0.0.8-rc.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (280) hide show
  1. package/build/{esnext → cjs}/config.d.ts +0 -1
  2. package/build/{src → cjs}/config.js +0 -1
  3. package/build/{esnext → cjs}/index.d.ts +0 -1
  4. package/build/{src → cjs}/index.js +0 -1
  5. package/build/{esnext → cjs}/servers/server.builder.d.ts +0 -1
  6. package/build/{src → cjs}/servers/server.builder.js +10 -13
  7. package/build/{src → cjs}/servers/server.d.ts +0 -1
  8. package/build/{src → cjs}/servers/server.js +83 -75
  9. package/build/{src → cjs}/types/api-response.d.ts +0 -1
  10. package/build/{src → cjs}/types/api-response.js +0 -1
  11. package/build/{src → cjs}/types/index.d.ts +0 -1
  12. package/build/{src → cjs}/types/index.js +0 -1
  13. package/build/{src → cjs}/types/server.d.ts +0 -1
  14. package/build/{src → cjs}/types/server.js +0 -1
  15. package/build/{src → cjs}/utils/array.utils.d.ts +0 -1
  16. package/build/{src → cjs}/utils/array.utils.js +0 -1
  17. package/build/{src → cjs}/utils/async.utils.d.ts +0 -1
  18. package/build/{src → cjs}/utils/async.utils.js +2 -3
  19. package/build/{esnext → cjs}/utils/cache.utils.d.ts +0 -1
  20. package/build/{src → cjs}/utils/cache.utils.js +7 -6
  21. package/build/{esnext → cjs}/utils/context-store.utils.d.ts +1 -2
  22. package/build/{src → cjs}/utils/context-store.utils.js +10 -9
  23. package/build/{esnext → cjs}/utils/crypto.utils.d.ts +0 -1
  24. package/build/{src → cjs}/utils/crypto.utils.js +5 -3
  25. package/build/{src → cjs}/utils/date.utils.d.ts +0 -1
  26. package/build/{src → cjs}/utils/date.utils.js +1 -2
  27. package/build/{src → cjs}/utils/decorators.utils.d.ts +30 -27
  28. package/build/{src → cjs}/utils/decorators.utils.js +169 -30
  29. package/build/{esnext → cjs}/utils/dir.utils.d.ts +0 -1
  30. package/build/{src → cjs}/utils/dir.utils.js +6 -7
  31. package/build/{esnext → cjs}/utils/env.utils.d.ts +0 -1
  32. package/build/{src → cjs}/utils/env.utils.js +5 -8
  33. package/build/{src → cjs}/utils/exception.utils.d.ts +0 -1
  34. package/build/{src → cjs}/utils/exception.utils.js +2 -1
  35. package/build/{src → cjs}/utils/fs.utils.d.ts +0 -1
  36. package/build/{src → cjs}/utils/fs.utils.js +12 -13
  37. package/build/{esnext → cjs}/utils/http-status-codes.d.ts +0 -1
  38. package/build/{src → cjs}/utils/http-status-codes.js +0 -1
  39. package/build/{esnext → cjs}/utils/id.utils.d.ts +0 -1
  40. package/build/{src → cjs}/utils/id.utils.js +0 -1
  41. package/build/{src → cjs}/utils/logger.utils.d.ts +0 -1
  42. package/build/{src → cjs}/utils/logger.utils.js +10 -6
  43. package/build/{esnext → cjs}/utils/middleware.utils.d.ts +0 -1
  44. package/build/{src → cjs}/utils/middleware.utils.js +16 -17
  45. package/build/{esnext → cjs}/utils/obj.utils.d.ts +0 -1
  46. package/build/{src → cjs}/utils/obj.utils.js +1 -2
  47. package/build/{src → cjs}/utils/performance.utils.d.ts +0 -1
  48. package/build/{src → cjs}/utils/performance.utils.js +6 -4
  49. package/build/{esnext → cjs}/utils/request.utils.d.ts +0 -1
  50. package/build/{src → cjs}/utils/request.utils.js +7 -3
  51. package/build/{esnext → cjs}/utils/response.utils.d.ts +0 -1
  52. package/build/{src → cjs}/utils/response.utils.js +42 -28
  53. package/build/{esnext → cjs}/utils/stream.utils.d.ts +0 -1
  54. package/build/{src → cjs}/utils/stream.utils.js +0 -1
  55. package/build/{esnext → cjs}/utils/string.utils.d.ts +0 -1
  56. package/build/{src → cjs}/utils/string.utils.js +0 -1
  57. package/build/{src → cjs}/utils/type.utils.d.ts +0 -1
  58. package/build/{src → cjs}/utils/type.utils.js +2 -3
  59. package/build/{src → cjs}/utils/url.utils.d.ts +0 -1
  60. package/build/{src → cjs}/utils/url.utils.js +8 -9
  61. package/build/{src → cjs}/utils/validate.utils.d.ts +0 -1
  62. package/build/{src → cjs}/utils/validate.utils.js +2 -3
  63. package/build/esm/config.d.ts +0 -1
  64. package/build/esm/config.js +6 -7
  65. package/build/esm/index.d.ts +0 -1
  66. package/build/esm/index.js +0 -1
  67. package/build/esm/servers/server.builder.d.ts +0 -1
  68. package/build/esm/servers/server.builder.js +99 -147
  69. package/build/esm/servers/server.d.ts +0 -1
  70. package/build/esm/servers/server.js +591 -876
  71. package/build/esm/types/api-response.d.ts +0 -1
  72. package/build/esm/types/api-response.js +0 -1
  73. package/build/esm/types/index.d.ts +0 -1
  74. package/build/esm/types/index.js +0 -1
  75. package/build/esm/types/server.d.ts +0 -1
  76. package/build/esm/types/server.js +0 -1
  77. package/build/esm/utils/array.utils.d.ts +0 -1
  78. package/build/esm/utils/array.utils.js +48 -86
  79. package/build/esm/utils/async.utils.d.ts +0 -1
  80. package/build/esm/utils/async.utils.js +247 -524
  81. package/build/esm/utils/cache.utils.d.ts +0 -1
  82. package/build/esm/utils/cache.utils.js +96 -301
  83. package/build/esm/utils/context-store.utils.d.ts +1 -2
  84. package/build/esm/utils/context-store.utils.js +62 -79
  85. package/build/esm/utils/crypto.utils.d.ts +0 -1
  86. package/build/esm/utils/crypto.utils.js +78 -175
  87. package/build/esm/utils/date.utils.d.ts +0 -1
  88. package/build/esm/utils/date.utils.js +47 -53
  89. package/build/esm/utils/decorators.utils.d.ts +30 -27
  90. package/build/esm/utils/decorators.utils.js +417 -461
  91. package/build/esm/utils/dir.utils.d.ts +0 -1
  92. package/build/esm/utils/dir.utils.js +264 -786
  93. package/build/esm/utils/env.utils.d.ts +0 -1
  94. package/build/esm/utils/env.utils.js +180 -271
  95. package/build/esm/utils/exception.utils.d.ts +0 -1
  96. package/build/esm/utils/exception.utils.js +112 -289
  97. package/build/esm/utils/fs.utils.d.ts +0 -1
  98. package/build/esm/utils/fs.utils.js +169 -401
  99. package/build/esm/utils/http-status-codes.d.ts +0 -1
  100. package/build/esm/utils/http-status-codes.js +0 -1
  101. package/build/esm/utils/id.utils.d.ts +0 -1
  102. package/build/esm/utils/id.utils.js +5 -9
  103. package/build/esm/utils/logger.utils.d.ts +0 -1
  104. package/build/esm/utils/logger.utils.js +34 -71
  105. package/build/esm/utils/middleware.utils.d.ts +0 -1
  106. package/build/esm/utils/middleware.utils.js +65 -155
  107. package/build/esm/utils/obj.utils.d.ts +0 -1
  108. package/build/esm/utils/obj.utils.js +69 -176
  109. package/build/esm/utils/performance.utils.d.ts +0 -1
  110. package/build/esm/utils/performance.utils.js +92 -195
  111. package/build/esm/utils/request.utils.d.ts +0 -1
  112. package/build/esm/utils/request.utils.js +41 -74
  113. package/build/esm/utils/response.utils.d.ts +0 -1
  114. package/build/esm/utils/response.utils.js +84 -107
  115. package/build/esm/utils/stream.utils.d.ts +0 -1
  116. package/build/esm/utils/stream.utils.js +38 -113
  117. package/build/esm/utils/string.utils.d.ts +0 -1
  118. package/build/esm/utils/string.utils.js +6 -11
  119. package/build/esm/utils/type.utils.d.ts +0 -1
  120. package/build/esm/utils/type.utils.js +8 -12
  121. package/build/esm/utils/url.utils.d.ts +0 -1
  122. package/build/esm/utils/url.utils.js +49 -127
  123. package/build/esm/utils/validate.utils.d.ts +0 -1
  124. package/build/esm/utils/validate.utils.js +23 -40
  125. package/package.json +288 -63
  126. package/build/esm/config.js.map +0 -1
  127. package/build/esm/index.js.map +0 -1
  128. package/build/esm/servers/server.builder.js.map +0 -1
  129. package/build/esm/servers/server.js.map +0 -1
  130. package/build/esm/types/api-response.js.map +0 -1
  131. package/build/esm/types/index.js.map +0 -1
  132. package/build/esm/types/server.js.map +0 -1
  133. package/build/esm/utils/array.utils.js.map +0 -1
  134. package/build/esm/utils/async.utils.js.map +0 -1
  135. package/build/esm/utils/cache.utils.js.map +0 -1
  136. package/build/esm/utils/context-store.utils.js.map +0 -1
  137. package/build/esm/utils/crypto.utils.js.map +0 -1
  138. package/build/esm/utils/date.utils.js.map +0 -1
  139. package/build/esm/utils/decorators.utils.js.map +0 -1
  140. package/build/esm/utils/dir.utils.js.map +0 -1
  141. package/build/esm/utils/env.utils.js.map +0 -1
  142. package/build/esm/utils/exception.utils.js.map +0 -1
  143. package/build/esm/utils/fs.utils.js.map +0 -1
  144. package/build/esm/utils/http-status-codes.js.map +0 -1
  145. package/build/esm/utils/id.utils.js.map +0 -1
  146. package/build/esm/utils/logger.utils.js.map +0 -1
  147. package/build/esm/utils/middleware.utils.js.map +0 -1
  148. package/build/esm/utils/obj.utils.js.map +0 -1
  149. package/build/esm/utils/performance.utils.js.map +0 -1
  150. package/build/esm/utils/request.utils.js.map +0 -1
  151. package/build/esm/utils/response.utils.js.map +0 -1
  152. package/build/esm/utils/stream.utils.js.map +0 -1
  153. package/build/esm/utils/string.utils.js.map +0 -1
  154. package/build/esm/utils/type.utils.js.map +0 -1
  155. package/build/esm/utils/url.utils.js.map +0 -1
  156. package/build/esm/utils/validate.utils.js.map +0 -1
  157. package/build/esnext/config.js +0 -133
  158. package/build/esnext/config.js.map +0 -1
  159. package/build/esnext/index.js +0 -50
  160. package/build/esnext/index.js.map +0 -1
  161. package/build/esnext/servers/server.builder.js +0 -657
  162. package/build/esnext/servers/server.builder.js.map +0 -1
  163. package/build/esnext/servers/server.d.ts +0 -256
  164. package/build/esnext/servers/server.js +0 -955
  165. package/build/esnext/servers/server.js.map +0 -1
  166. package/build/esnext/types/api-response.d.ts +0 -152
  167. package/build/esnext/types/api-response.js +0 -34
  168. package/build/esnext/types/api-response.js.map +0 -1
  169. package/build/esnext/types/index.d.ts +0 -125
  170. package/build/esnext/types/index.js +0 -25
  171. package/build/esnext/types/index.js.map +0 -1
  172. package/build/esnext/types/server.d.ts +0 -268
  173. package/build/esnext/types/server.js +0 -25
  174. package/build/esnext/types/server.js.map +0 -1
  175. package/build/esnext/utils/array.utils.d.ts +0 -168
  176. package/build/esnext/utils/array.utils.js +0 -345
  177. package/build/esnext/utils/array.utils.js.map +0 -1
  178. package/build/esnext/utils/async.utils.d.ts +0 -265
  179. package/build/esnext/utils/async.utils.js +0 -620
  180. package/build/esnext/utils/async.utils.js.map +0 -1
  181. package/build/esnext/utils/cache.utils.js +0 -293
  182. package/build/esnext/utils/cache.utils.js.map +0 -1
  183. package/build/esnext/utils/context-store.utils.js +0 -289
  184. package/build/esnext/utils/context-store.utils.js.map +0 -1
  185. package/build/esnext/utils/crypto.utils.js +0 -276
  186. package/build/esnext/utils/crypto.utils.js.map +0 -1
  187. package/build/esnext/utils/date.utils.d.ts +0 -159
  188. package/build/esnext/utils/date.utils.js +0 -384
  189. package/build/esnext/utils/date.utils.js.map +0 -1
  190. package/build/esnext/utils/decorators.utils.d.ts +0 -508
  191. package/build/esnext/utils/decorators.utils.js +0 -877
  192. package/build/esnext/utils/decorators.utils.js.map +0 -1
  193. package/build/esnext/utils/dir.utils.js +0 -477
  194. package/build/esnext/utils/dir.utils.js.map +0 -1
  195. package/build/esnext/utils/env.utils.js +0 -785
  196. package/build/esnext/utils/env.utils.js.map +0 -1
  197. package/build/esnext/utils/exception.utils.d.ts +0 -230
  198. package/build/esnext/utils/exception.utils.js +0 -381
  199. package/build/esnext/utils/exception.utils.js.map +0 -1
  200. package/build/esnext/utils/fs.utils.d.ts +0 -164
  201. package/build/esnext/utils/fs.utils.js +0 -349
  202. package/build/esnext/utils/fs.utils.js.map +0 -1
  203. package/build/esnext/utils/http-status-codes.js +0 -295
  204. package/build/esnext/utils/http-status-codes.js.map +0 -1
  205. package/build/esnext/utils/id.utils.js +0 -84
  206. package/build/esnext/utils/id.utils.js.map +0 -1
  207. package/build/esnext/utils/logger.utils.d.ts +0 -160
  208. package/build/esnext/utils/logger.utils.js +0 -300
  209. package/build/esnext/utils/logger.utils.js.map +0 -1
  210. package/build/esnext/utils/middleware.utils.js +0 -236
  211. package/build/esnext/utils/middleware.utils.js.map +0 -1
  212. package/build/esnext/utils/obj.utils.js +0 -413
  213. package/build/esnext/utils/obj.utils.js.map +0 -1
  214. package/build/esnext/utils/performance.utils.d.ts +0 -136
  215. package/build/esnext/utils/performance.utils.js +0 -271
  216. package/build/esnext/utils/performance.utils.js.map +0 -1
  217. package/build/esnext/utils/request.utils.js +0 -186
  218. package/build/esnext/utils/request.utils.js.map +0 -1
  219. package/build/esnext/utils/response.utils.js +0 -247
  220. package/build/esnext/utils/response.utils.js.map +0 -1
  221. package/build/esnext/utils/stream.utils.js +0 -210
  222. package/build/esnext/utils/stream.utils.js.map +0 -1
  223. package/build/esnext/utils/string.utils.js +0 -165
  224. package/build/esnext/utils/string.utils.js.map +0 -1
  225. package/build/esnext/utils/type.utils.d.ts +0 -90
  226. package/build/esnext/utils/type.utils.js +0 -187
  227. package/build/esnext/utils/type.utils.js.map +0 -1
  228. package/build/esnext/utils/url.utils.d.ts +0 -141
  229. package/build/esnext/utils/url.utils.js +0 -304
  230. package/build/esnext/utils/url.utils.js.map +0 -1
  231. package/build/esnext/utils/validate.utils.d.ts +0 -177
  232. package/build/esnext/utils/validate.utils.js +0 -320
  233. package/build/esnext/utils/validate.utils.js.map +0 -1
  234. package/build/src/config.d.ts +0 -122
  235. package/build/src/config.js.map +0 -1
  236. package/build/src/index.d.ts +0 -27
  237. package/build/src/index.js.map +0 -1
  238. package/build/src/servers/server.builder.d.ts +0 -508
  239. package/build/src/servers/server.builder.js.map +0 -1
  240. package/build/src/servers/server.js.map +0 -1
  241. package/build/src/types/api-response.js.map +0 -1
  242. package/build/src/types/index.js.map +0 -1
  243. package/build/src/types/server.js.map +0 -1
  244. package/build/src/utils/array.utils.js.map +0 -1
  245. package/build/src/utils/async.utils.js.map +0 -1
  246. package/build/src/utils/cache.utils.d.ts +0 -153
  247. package/build/src/utils/cache.utils.js.map +0 -1
  248. package/build/src/utils/context-store.utils.d.ts +0 -189
  249. package/build/src/utils/context-store.utils.js.map +0 -1
  250. package/build/src/utils/crypto.utils.d.ts +0 -160
  251. package/build/src/utils/crypto.utils.js.map +0 -1
  252. package/build/src/utils/date.utils.js.map +0 -1
  253. package/build/src/utils/decorators.utils.js.map +0 -1
  254. package/build/src/utils/dir.utils.d.ts +0 -196
  255. package/build/src/utils/dir.utils.js.map +0 -1
  256. package/build/src/utils/env.utils.d.ts +0 -377
  257. package/build/src/utils/env.utils.js.map +0 -1
  258. package/build/src/utils/exception.utils.js.map +0 -1
  259. package/build/src/utils/fs.utils.js.map +0 -1
  260. package/build/src/utils/http-status-codes.d.ts +0 -266
  261. package/build/src/utils/http-status-codes.js.map +0 -1
  262. package/build/src/utils/id.utils.d.ts +0 -36
  263. package/build/src/utils/id.utils.js.map +0 -1
  264. package/build/src/utils/logger.utils.js.map +0 -1
  265. package/build/src/utils/middleware.utils.d.ts +0 -100
  266. package/build/src/utils/middleware.utils.js.map +0 -1
  267. package/build/src/utils/obj.utils.d.ts +0 -124
  268. package/build/src/utils/obj.utils.js.map +0 -1
  269. package/build/src/utils/performance.utils.js.map +0 -1
  270. package/build/src/utils/request.utils.d.ts +0 -86
  271. package/build/src/utils/request.utils.js.map +0 -1
  272. package/build/src/utils/response.utils.d.ts +0 -163
  273. package/build/src/utils/response.utils.js.map +0 -1
  274. package/build/src/utils/stream.utils.d.ts +0 -88
  275. package/build/src/utils/stream.utils.js.map +0 -1
  276. package/build/src/utils/string.utils.d.ts +0 -93
  277. package/build/src/utils/string.utils.js.map +0 -1
  278. package/build/src/utils/type.utils.js.map +0 -1
  279. package/build/src/utils/url.utils.js.map +0 -1
  280. package/build/src/utils/validate.utils.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"dir.utils.js","sourceRoot":"","sources":["../../../src/utils/dir.utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,GAAG,MAAM,aAAa,CAAC;AAC9B,OAAO,IAAI,MAAM,MAAM,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cesContent":["/*\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;IAn0BC;;;;OAIG;IACI,SAAK,GAAZ;QACE,OAAO,GAAG,CAAC,GAAG,CAAC,UAAU,EAAE,WAAW,CAAC,WAAW,CAAC,KAAK,WAAW,CAAC,WAAW,CAAC;IAClF,CAAC;IAED;;;;OAIG;IACI,UAAM,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B;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,qBAAqB,CAAC;;IACtD,CAAC;IACH,mCAAC;AAAD,CAAC,AARD,CAAkD,aAAa,GAQ9D;;AAED;;;GAGG;AACH;IAA2C,yCAAa;IACtD;;OAEG;IACH,+BAAY,OAAgC;QAAhC,wBAAA,EAAA,wBAAgC;QAC1C,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,CAAC,KAAc;IAC5C,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC9B,OAAO,KAAK,CAAC;IACf,CAAC;IAED,IAAI,KAAK,YAAY,KAAK,EAAE,CAAC;QAC3B,OAAO,KAAK,CAAC,OAAO,CAAC;IACvB,CAAC;IAED,IAAI,aAAa,CAAC,KAAK,CAAC,EAAE,CAAC;QACzB,OAAO,KAAK,CAAC,OAAO,CAAC;IACvB,CAAC;IAED,OAAO,wBAAwB,CAAC;AAClC,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,iBAAiB,CAC/B,OAAU;IADZ,iBAwBC;IArBC,OAAO;QAAO,cAAsB;aAAtB,UAAsB,EAAtB,qBAAsB,EAAtB,IAAsB;YAAtB,yBAAsB;;;;;;;;wBAEzB,qBAAM,OAAO,wCAAI,IAAI,YAAC;4BAA7B,sBAAO,SAAsB,EAAC;;;wBAE9B,IAAI,WAAW,CAAC,KAAG,CAAC,EAAE,CAAC;4BACrB,MAAM,KAAG,CAAC;wBACZ,CAAC;wBAED,0DAA0D;wBAC1D,SAAS,EAAE,CAAC,KAAK,CAAC,EAAE,GAAG,OAAA,EAAE,EAAE,yBAAyB,CAAC,CAAC;wBAGlD,WAAS,eAAe,CAAC,qBAAqB,CAAC;wBACnD,IAAI,aAAa,CAAC,KAAG,CAAC,IAAI,OAAO,KAAG,CAAC,MAAM,KAAK,QAAQ,EAAE,CAAC;4BACzD,QAAM,GAAG,KAAG,CAAC,MAAM,CAAC;wBACtB,CAAC;wBAED,gCAAgC;wBAChC,MAAM,eAAe,CAAC,QAAM,EAAE,eAAe,CAAC,KAAG,CAAC,CAAC,CAAC;;;;;KAEvD,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 { 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,MAAM,CAAC,IAAI,CAAC,EAAA;;oBAArB,SAAqB,CAAC;oBACtB,sBAAO,IAAI,EAAC;;;oBAEZ,sBAAO,KAAK,EAAC;;;;;CAEhB;AAED;;;;;;GAMG;AACH,MAAM,UAAgB,YAAY,CAAU,IAAY;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* 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;IAEd;;OAEG;IACH,qFAAyB,CAAA;IAEzB;;OAEG;IACH,mEAAgB,CAAA;IAEhB;;OAEG;IACH,qEAAiB,CAAA;IAEjB,cAAc;IACd;;OAEG;IACH,mDAAQ,CAAA;IAER;;OAEG;IACH,6DAAa,CAAA;I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AoC,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"]}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iBAAiB,CAAC,QAA6B,EAAE,YAAyB;IACxF,IAAM,MAAM,GAAG,YAAY,IAAI,SAAS,EAAE,CAAC;IAC3C,OAAO,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;AAChC,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,mBAAmB,CAAC,SAAiB,EAAE,iBAA2C;IAA3C,kCAAA,EAAA,sBAA2C;IAChG,IAAM,MAAM,GAAG,iBAAiB,YAC9B,SAAS,WAAA,IACN,iBAAiB,EACpB,CAAC;IAEH,IAAI,CAAC;QACH,YAAY,CAAC,GAAG,CAAC,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC7C,CAAC;IAAC,WAAM,CAAC;QACP,8CAA8C;QAC9C,MAAM,CAAC,KAAK,CAAC,uEAAuE,CAAC,CAAC;IACxF,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,QAAQ,CAAC,KAAsB,EAAE,OAAgB,EAAE,OAA6B;IAC9F,IAAM,MAAM,GAAG,SAAS,EAAE,CAAC;IAE3B,IAAM,MAAM,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IACzE,IAAM,UAAU,yBACX,OAAO,KACV,KAAK,EAAE,MAAM,GACd,CAAC;IAEF,MAAM,CAAC,KAAK,CAAC,UAAU,EAAE,OAAO,IAAI,MAAM,CAAC,OAAO,CAAC,CAAC;AACtD,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 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,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAK5D;;;;;;;;;GASG;AACH,MAAM,UAAU,SAAS,CAAC,OAIzB;IACC,IAAM,UAAU,GAAG,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,UAAU,KAAI,cAA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,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"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"obj.utils.js","sourceRoot":"","sources":["../../../src/utils/obj.utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH;;;;;GAKG;AACH,MAAM,UAAU,UAAU,CAAC,GAAqB;IAC9C,OAAO,CAAC,CAAC,GAAG,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC;AAC3E,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,IAAI,CAAsC,GAAM,EAAE,IAAS;IACzE,OAAO,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,GAAG,CAAC,UAAA,GAAG,IAAI,OAAA,CAAC,GAAG,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC,EAAf,CAAe,CAAC,CAAe,CAAC;AAC5E,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,IAAI,CAAsC,GAAM,EAAE,IAAS;IACzE,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,UAAC,EAAK;YAAL,KAAA,aAAK,EAAJ,GAAG,QAAA;QAAM,OAAA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AAC,CAAC,CAAC,GAAG,CAAC;QAE9D,IAAI,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;YACpB,sBAAQ,WAAW,UAAK,WAAW,CAAC,KAAK,EAAE,WAAW,CAAC,UAAE;QAC3D,CAAC;QAED,OAAO,CAAC,WAAW,CAAC,CAAC;IACvB,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/**\n * Checks whether the object has no own enumerable properties.\n *\n * @param {Record<any, any>} obj - The object to check.\n * @returns {boolean} True if the object is empty, false otherwise.\n */\nexport function isObjEmpty(obj: Record<any, any>): boolean {\n return !!obj && typeof obj === 'object' && Object.keys(obj).length === 0;\n}\n\n/**\n * Returns a new object with only the specified keys picked.\n *\n * @template T\n * @template K\n * @param {T} obj - The source object.\n * @param {K[]} keys - Keys to pick from the object.\n * @returns {Pick<T, K>} New object with picked keys.\n */\nexport function pick<T extends object, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> {\n return Object.fromEntries(keys.map(key => [key, obj[key]])) as Pick<T, K>;\n}\n\n/**\n * Returns a new object with the specified keys omitted.\n *\n * @template T\n * @template K\n * @param {T} obj - The source object.\n * @param {K[]} keys - Keys to omit from the object.\n * @returns {Omit<T, K>} New object without omitted keys.\n */\nexport function omit<T extends object, K extends keyof T>(obj: T, keys: K[]): Omit<T, K> {\n return Object.fromEntries(Object.entries(obj).filter(([key]) => !keys.includes(key as K))) as Omit<T, K>;\n}\n\n/**\n * Deeply merges multiple objects into the target object (mutates and returns the target object, not pure).\n *\n * @template T\n * @param {T} target - The object to merge into (will be mutated).\n * @param {...any[]} sources - The objects to merge from.\n * @returns {T} The merged object (same as target).\n */\nexport function deepObjMerge<T extends object>(target: T, ...sources: any[]): T {\n if (!sources.length) return target;\n\n const seen = new WeakMap();\n seen.set(target, target);\n\n for (const s of sources) {\n if (s && typeof s === 'object') {\n seen.set(s, target);\n }\n }\n\n function deepClone(value: any): any {\n if (value === null || typeof value !== 'object') return value;\n\n if (seen.has(value)) return seen.get(value);\n\n // Date\n if (value instanceof Date) {\n return new Date(value.getTime());\n }\n\n // Array\n if (Array.isArray(value)) {\n const clone: any[] = [];\n seen.set(value, clone);\n value.forEach((item, i) => (clone[i] = deepClone(item)));\n return clone;\n }\n\n // Set\n if (value instanceof Set) {\n const clone = new Set();\n seen.set(value, clone);\n value.forEach(item => clone.add(deepClone(item)));\n return clone;\n }\n\n // Map\n if (value instanceof Map) {\n const clone = new Map();\n seen.set(value, clone);\n value.forEach((val, key) => clone.set(key, deepClone(val)));\n return clone;\n }\n\n // RegExp\n if (value instanceof RegExp) {\n return new RegExp(value.source, value.flags);\n }\n\n // ArrayBuffer\n if (value instanceof ArrayBuffer) {\n return value.slice(0);\n }\n\n // TypedArrays\n if (ArrayBuffer.isView(value) && !(value instanceof DataView)) {\n const typed = value as any; // cast for TS\n const ctor = typed.constructor;\n // List of standard TypedArray constructors\n const typedArrayCtors = [\n Int8Array,\n Uint8Array,\n Uint8ClampedArray,\n Int16Array,\n Uint16Array,\n Int32Array,\n Uint32Array,\n Float32Array,\n Float64Array,\n BigInt64Array,\n BigUint64Array\n ].filter(Boolean); // filter out undefined (for environments without BigInt)\n const typedArrayCtorSet = new Set(typedArrayCtors);\n if (typeof ctor === 'function' && typedArrayCtorSet.has(ctor)) {\n // Defensive: ensure buffer is an ArrayBuffer and slice is available\n const buffer = typed.buffer && typeof typed.buffer.slice === 'function' ? typed.buffer.slice(0) : typed.buffer;\n const clone = new ctor(buffer, typed.byteOffset, typed.length);\n seen.set(value, clone);\n return clone;\n } else if (typeof typed.slice === 'function') {\n // Fallback: try using slice if available (e.g., Node.js Buffer)\n const clone = typed.slice();\n seen.set(value, clone);\n return clone;\n } else {\n // Could not safely clone, throw an error for better debugging\n throw new Error(\n 'Cannot deep clone unknown TypedArray type: ' + (typed && typed.constructor && typed.constructor.name)\n );\n }\n }\n\n const clone = Object.create(Object.getPrototypeOf(value));\n seen.set(value, clone);\n\n Reflect.ownKeys(value).forEach(key => {\n const descriptor = Object.getOwnPropertyDescriptor(value, key)!;\n if (descriptor.get || descriptor.set) {\n Object.defineProperty(clone, key, descriptor);\n } else {\n (clone as any)[key] = deepClone((value as any)[key]);\n }\n });\n\n return clone;\n }\n\n function mergeProp(target: any, source: any, key: string | symbol): void {\n const targetValue = target[key];\n const sourceValue = source[key];\n\n // Ignore undefined in source\n if (sourceValue === undefined) return;\n\n // Primitives → overwrite directly\n if (sourceValue === null || typeof sourceValue !== 'object') {\n target[key] = sourceValue;\n return;\n }\n\n // Arrays → replace (lodash behavior)\n if (Array.isArray(sourceValue)) {\n target[key] = deepClone(sourceValue);\n return;\n }\n\n // Special cloneable objects\n if (\n sourceValue instanceof Date ||\n sourceValue instanceof RegExp ||\n sourceValue instanceof Set ||\n sourceValue instanceof Map ||\n sourceValue instanceof ArrayBuffer ||\n (ArrayBuffer.isView(sourceValue) && !(sourceValue instanceof DataView))\n ) {\n target[key] = deepClone(sourceValue);\n return;\n }\n\n // Plain objects → recursive merge\n if (isPlainObject(sourceValue) && isPlainObject(targetValue)) {\n for (const k of Reflect.ownKeys(sourceValue)) {\n mergeProp(targetValue, sourceValue, k);\n }\n return;\n }\n\n // Default → overwrite with clone\n target[key] = deepClone(sourceValue);\n }\n\n for (const source of sources) {\n if (source == null) continue;\n\n for (const key of Reflect.ownKeys(source)) {\n mergeProp(target, source, key);\n }\n }\n\n return target;\n}\n\n/**\n * Checks if a value is a plain object (i.e., not an array, null, or a built-in object).\n *\n * @param value - The value to check.\n * @returns True if the value is a plain object, false otherwise.\n */\nexport function isPlainObject(value: any): value is Record<string, any> {\n if (typeof value !== 'object' || value === null) return false;\n if (Array.isArray(value)) return false;\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n/**\n * Flattens a nested object using dot notation for keys (e.g., `{a: {b: 1}}` → `{ \"a.b\": 1 }`).\n *\n * @template T\n * @param {T} obj - The object to flatten.\n * @param {string} [prefix=\"\"] - Optional prefix for nested keys (used internally).\n * @returns {Record<string, any>} A new object with flattened keys.\n */\nexport function flattenObject<T extends Record<string, any>>(obj: T, prefix = ''): Record<string, any> {\n return Object.entries(obj).reduce((acc: Record<string, any>, [key, value]) => {\n const newKey = prefix ? `${prefix}.${key}` : key;\n\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n Object.assign(acc, flattenObject(value, newKey));\n } else {\n acc[newKey] = value;\n }\n\n return acc;\n }, {});\n}\n\n/**\n * Safely gets the value of a deeply nested key in an object using dot/bracket notation path.\n *\n * @template T\n * @param {T} obj - The object to extract from.\n * @param {string} path - String path using dot and/or bracket notation (e.g., 'user.friends[0].name').\n * @returns {any} The value at the given path, or undefined if not found.\n */\nexport function getValueByPath<T extends object>(obj: T, path: string) {\n if (!obj || typeof obj !== 'object') return undefined;\n\n // Convert path like \"a.b[0].c\" into [\"a\", \"b\", \"0\", \"c\"]\n const parts = path\n .replace(/\\[(\\d+)\\]/g, '.$1') // convert [0] to .0\n .split('.')\n .filter(Boolean); // remove empty strings\n\n return parts.reduce((acc: any, key: string) => acc?.[key], obj);\n}\n\n/**\n * Sets a value at a deeply nested key in an object using dot/bracket notation path.\n * Creates intermediate objects and arrays as needed.\n *\n * @template T\n * @param {T} obj - The object to modify.\n * @param {string} path - String path using dot and/or bracket notation (e.g., 'user.friends[0].name').\n * @param {any} value - The value to set at the path.\n * @returns {T} The modified object.\n */\nexport function setValueByPath<T extends object>(obj: T, path: string, value: any): T {\n if (!obj || typeof obj !== 'object') return obj;\n\n // Convert path like \"a.b[0].c\" into [\"a\", \"b\", \"0\", \"c\"]\n const parts = path\n .replace(/\\[(\\d+)\\]/g, '.$1') // convert [0] to .0\n .split('.')\n .filter(Boolean); // remove empty strings\n\n // Handle empty path\n if (parts.length === 0) return obj;\n\n let current: any = obj;\n\n // Navigate to the parent of the target property\n for (let i = 0; i < parts.length - 1; i++) {\n const key = parts[i];\n const isArrayIndex = !isNaN(Number(parts[i + 1]));\n\n if (current[key] === undefined) {\n // Create intermediate object or array based on next key type\n current[key] = isArrayIndex ? [] : {};\n }\n\n current = current[key];\n }\n\n // Set the value at the final key\n const finalKey = parts[parts.length - 1];\n current[finalKey] = value;\n\n return obj;\n}\n\n/**\n * Performs a deep equality check between two objects.\n *\n * @param {any} a - First value to compare.\n * @param {any} b - Second value to compare.\n * @returns {boolean} True if values are deeply equal.\n */\nexport function isEqual(a: any, b: any): boolean {\n // Check if primitives or references to the same object\n if (a === b) return true;\n\n // Check if either is null/undefined or not an object\n if (a == null || b == null || typeof a !== 'object' || typeof b !== 'object') {\n return false;\n }\n\n // Handle Date objects\n if (a instanceof Date && b instanceof Date) {\n return a.getTime() === b.getTime();\n }\n\n // If one is Date but the other isn't\n if (a instanceof Date || b instanceof Date) {\n return false;\n }\n\n // Handle arrays\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false;\n\n // Check each element\n for (let i = 0; i < a.length; i++) {\n if (!isEqual(a[i], b[i])) return false;\n }\n\n return true;\n }\n\n // If one is Array but the other isn't\n if (Array.isArray(a) || Array.isArray(b)) {\n return false;\n }\n\n // Compare object keys\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) return false;\n\n // Check if every key in A exists in B and has the same value\n return keysA.every(key => Object.prototype.hasOwnProperty.call(b, key) && isEqual(a[key], b[key]));\n}\n\n/**\n * Filters object properties based on a predicate function.\n *\n * @template T\n * @param {T} obj - The source object.\n * @param {(value: any, key: string, obj: T) => boolean} predicate - Filter function.\n * @returns {Partial<T>} New object with filtered properties.\n */\nexport function filterObject<T extends object>(\n obj: T,\n predicate: (value: any, key: string, obj: T) => boolean\n): Partial<T> {\n return Object.fromEntries(Object.entries(obj).filter(([key, value]) => predicate(value, key, obj))) as Partial<T>;\n}\n\n/**\n * Maps object values to new values using a mapping function.\n *\n * @template T\n * @template U\n * @param {T} obj - The source object.\n * @param {(value: any, key: string, obj: T) => U} mapFn - Mapping function.\n * @returns {Record<keyof T, U>} New object with mapped values.\n */\nexport function mapObject<T extends object, U>(\n obj: T,\n mapFn: (value: any, key: string, obj: T) => U\n): Record<keyof T, U> {\n return Object.fromEntries(Object.entries(obj).map(([key, value]) => [key, mapFn(value, key, obj)])) as Record<\n keyof T,\n U\n >;\n}\n\n/**\n * Recursively freezes an object and all its properties.\n * Makes an object immutable.\n *\n * @template T\n * @param {T} obj - The object to freeze.\n * @returns {Readonly<T>} The frozen object.\n */\nexport function deepFreeze<T extends object>(obj: T): Readonly<T> {\n // Freeze primitive properties\n Object.freeze(obj);\n\n // Recursively freeze nested objects\n for (const prop of Object.getOwnPropertyNames(obj)) {\n const value = (obj as any)[prop];\n if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {\n deepFreeze(value);\n }\n }\n\n return obj;\n}\n\n/**\n * Safely checks if a value is an object (not null, not array).\n *\n * @param {unknown} value - Value to check.\n * @returns {boolean} True if value is a non-null, non-array object.\n */\nexport function isObject(value: unknown): value is Record<string, any> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/**\n * Gets all paths in an object using dot notation.\n *\n * @param {Record<string, any>} obj - Object to analyze.\n * @param {string} [parentPath=\"\"] - Internal param for recursion.\n * @returns {string[]} Array of all paths in dot notation.\n */\nexport function getAllPaths(obj: Record<string, any>, parentPath: string = ''): string[] {\n if (!isObject(obj)) return [];\n\n return Object.entries(obj).flatMap(([key, value]) => {\n const currentPath = parentPath ? `${parentPath}.${key}` : key;\n\n if (isObject(value)) {\n return [currentPath, ...getAllPaths(value, currentPath)];\n }\n\n return [currentPath];\n });\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"performance.utils.js","sourceRoot":"","sources":["../../../src/utils/performance.utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AA8B3C;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,UAAU,QAAQ,CAAI,EAAW,EAAE,OAA2B;IAA3B,wBAAA,EAAA,YAA2B;IAC1D,IAAA,KAA6E,OAAO,MAA7C,EAAvC,KAAK,mBAAG,EAAE,CAAC,IAAI,IAAI,oBAAoB,KAAA,EAAE,KAAoC,OAAO,IAAhC,EAAX,GAAG,mBAAG,KAAK,KAAA,EAAE,KAAuB,OAAO,SAAZ,EAAlB,QAAQ,mBAAG,OAAO,KAAA,CAAa;IAE7F,IAAM,SAAS,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC;IACpC,IAAM,MAAM,GAAG,EAAE,EAAE,CAAC;IACpB,IAAM,OAAO,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC;IAElC,IAAM,UAAU,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AAC,WAAW,EAAE,GAAG,CAAC,EAAE,CAAC;YAC3D,IAAI,CAAC,GAAG,CAAC,GAAI,WAAmB,CAAC,GAAG,CAAC,GAAI,YAAoB,CAAC,GAAG,CAAC,CAAC;QACrE,CAAC;IACH,CAAC;IAED,IAAI,GAAG,EAAE,CAAC;QACR,SAAS,EAAE,CAAC,IAAI,CACd;YACE,KAAK,OAAA;YACL,YAAY,EAAE,YAAY;YAC1B,WAAW,EAAE,WAAW;YACxB,UAAU,EAAE,IAAI;SACjB,EACD,2BAAoB,KAAK,CAAE,CAC5B,CAAC;IACJ,CAAC;IAED,OAAO;QACL,MAAM,QAAA;QACN,WAAW,EAAE;YACX,MAAM,EAAE,YAAY;YACpB,KAAK,EAAE,WAAW;YAClB,IAAI,MAAA;SACL;KACF,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 { TTLCache } from './cache.utils';\nimport { getLogger } from './logger.utils';\n\n/**\n * Options for timing function execution.\n */\nexport interface TimingOptions {\n /** Optional label for the timing (defaults to function name) */\n label?: string;\n /** Whether to log the timing (default: false) */\n log?: boolean;\n /** Log level to use if logging is enabled (default: 'debug') */\n logLevel?: 'trace' | 'debug' | 'info' | 'warn' | 'error';\n}\n\n/**\n * Result of a timing operation.\n */\nexport interface TimingResult {\n /** Duration in milliseconds */\n durationMs: number;\n /** Duration in seconds */\n durationSec: number;\n /** Start timestamp */\n startTime: number;\n /** End timestamp */\n endTime: number;\n /** Label used for the timing */\n label: string;\n}\n\n/**\n * Measure the execution time of a synchronous function.\n *\n * @param fn - Function to measure\n * @param options - Timing options\n * @returns Result containing the return value and timing information\n *\n * @example\n * ```typescript\n * const { result, timing } = timeSync(() => {\n * // Some expensive operation\n * return computeResult();\n * }, { label: 'Computation', log: true });\n *\n * console.log(`Result: ${result}, took ${timing.durationMs}ms`);\n * ```\n */\nexport function timeSync<T>(fn: () => T, options: TimingOptions = {}): { result: T; timing: TimingResult } {\n const { label = fn.name || 'anonymous function', log = false, logLevel = 'debug' } = options;\n\n const startTime = performance.now();\n const result = fn();\n const endTime = performance.now();\n\n const durationMs = endTime - startTime;\n const durationSec = durationMs / 1000;\n\n const timing: TimingResult = {\n durationMs,\n durationSec,\n startTime,\n endTime,\n label\n };\n\n if (log) {\n const logger = getLogger();\n const message = `${label} completed in ${durationMs.toFixed(2)}ms`;\n\n switch (logLevel) {\n case 'trace':\n logger.trace({ timing }, message);\n break;\n case 'debug':\n logger.debug({ timing }, message);\n break;\n case 'info':\n logger.info({ timing }, message);\n break;\n case 'warn':\n logger.warn({ timing }, message);\n break;\n case 'error':\n logger.error({ timing }, message);\n break;\n default:\n logger.debug({ timing }, message);\n break;\n }\n }\n\n return { result, timing };\n}\n\n/**\n * Measure the execution time of an asynchronous function.\n *\n * @param fn - Async function to measure\n * @param options - Timing options\n * @returns Promise resolving to result and timing information\n *\n * @example\n * ```typescript\n * const { result, timing } = await timeAsync(async () => {\n * // Some expensive async operation\n * const data = await fetchData();\n * return processData(data);\n * }, { label: 'API Request', log: true });\n *\n * console.log(`Fetched ${result.length} items in ${timing.durationSec.toFixed(2)}s`);\n * ```\n */\nexport async function timeAsync<T>(\n fn: () => Promise<T>,\n options: TimingOptions = {}\n): Promise<{ result: T; timing: TimingResult }> {\n const { label = fn.name || 'anonymous async function', log = false, logLevel = 'debug' } = options;\n\n const startTime = performance.now();\n const result = await fn();\n const endTime = performance.now();\n\n const durationMs = endTime - startTime;\n const durationSec = durationMs / 1000;\n\n const timing: TimingResult = {\n durationMs,\n durationSec,\n startTime,\n endTime,\n label\n };\n\n if (log) {\n const logger = getLogger();\n const message = `${label} completed in ${durationMs.toFixed(2)}ms`;\n\n switch (logLevel) {\n case 'trace':\n logger.trace({ timing }, message);\n break;\n case 'debug':\n logger.debug({ timing }, message);\n break;\n case 'info':\n logger.info({ timing }, message);\n break;\n case 'warn':\n logger.warn({ timing }, message);\n break;\n case 'error':\n logger.error({ timing }, message);\n break;\n default:\n logger.debug({ timing }, message);\n break;\n }\n }\n\n return { result, timing };\n}\n\n/**\n * Create a timing decorator for class methods.\n *\n * @param options - Timing options\n * @returns Method decorator\n *\n * @example\n * ```typescript\n * class DataService {\n * @timed({ log: true, logLevel: 'info' })\n * async fetchData() {\n * // ...implementation\n * }\n * }\n * ```\n */\nexport function timed(options: TimingOptions = {}) {\n return function (target: any, propertyKeyOrContext: string | symbol | any, descriptor?: PropertyDescriptor): void {\n let propertyKey: string | symbol;\n let actualDescriptor: PropertyDescriptor;\n\n // ESNext decorator: second argument is context object\n if (typeof propertyKeyOrContext === 'object' && propertyKeyOrContext !== null && 'name' in propertyKeyOrContext) {\n propertyKey = propertyKeyOrContext.name;\n actualDescriptor = descriptor ?? Object.getOwnPropertyDescriptor(target, propertyKey)!;\n } else {\n // Legacy decorator: second argument is property key\n propertyKey = propertyKeyOrContext;\n actualDescriptor = descriptor ?? Object.getOwnPropertyDescriptor(target, propertyKey)!;\n }\n\n const originalMethod = actualDescriptor.value;\n\n actualDescriptor.value = function (...args: any[]) {\n const methodOptions = {\n ...options,\n label: options.label || `${target.constructor.name}.${String(propertyKey)}`\n };\n\n if (originalMethod.constructor.name === 'AsyncFunction') {\n return timeAsync(() => originalMethod.apply(this, args), methodOptions).then(({ result }) => result);\n } else {\n return timeSync(() => originalMethod.apply(this, args), methodOptions).result;\n }\n };\n\n // For legacy decorators, assign the new descriptor\n if (descriptor) {\n descriptor.value = actualDescriptor.value;\n } else {\n Object.defineProperty(target, propertyKey, actualDescriptor);\n }\n // No return needed for method decorators\n };\n}\n\n/**\n * Memoize function results with optional TTL and max cache size.\n *\n * @param fn - Function to memoize\n * @param options - Memoization options\n * @returns Memoized function\n *\n * @example\n * ```typescript\n * // Cache results for 30 seconds, with a maximum of 100 entries\n * const cachedFetch = memoize(\n * async (url) => {\n * const response = await fetch(url);\n * return response.json();\n * },\n * { ttl: 30000, maxSize: 100, cacheKey: (url) => url }\n * );\n * ```\n */\nexport function memoize<T, Args extends any[]>(\n fn: (...args: Args) => T,\n options: {\n /** Time-to-live in milliseconds (default: indefinite) */\n ttl?: number;\n /** Maximum cache size (default: unlimited) */\n maxSize?: number;\n /** Function to generate a cache key from arguments */\n cacheKey?: (...args: Args) => string;\n /** Auto-cleanup interval in milliseconds (default: disabled) */\n autoCleanupMs?: number;\n } = {}\n) {\n const { ttl, maxSize, autoCleanupMs, cacheKey = (...args) => JSON.stringify(args) } = options;\n\n // Create a properly configured TTLCache instance\n const cache = new TTLCache<string, T>({\n ttlMs: ttl,\n maxSize: maxSize,\n autoCleanupMs: autoCleanupMs\n });\n\n return function (...args: Args): T {\n const key = cacheKey(...args);\n\n // Try to get from cache first - TTLCache handles expiration internally\n const cachedValue = cache.get(key);\n if (cachedValue !== undefined) {\n return cachedValue;\n }\n\n // Calculate the value and store in cache with configured TTL\n const value = fn(...args);\n cache.set(key, value);\n return value;\n };\n}\n\n/**\n * Track memory usage for a function execution.\n *\n * @param fn - Function to track\n * @param options - Memory tracking options\n * @returns Result and memory usage information\n */\nexport function trackMemoryUsage<T>(\n fn: () => T,\n options: {\n /** Whether to log the memory usage (default: false) */\n log?: boolean;\n /** Label for the memory tracking (default: function name) */\n label?: string;\n } = {}\n): { result: T; memoryUsage: { before: NodeJS.MemoryUsage; after: NodeJS.MemoryUsage; diff: Record<string, number> } } {\n const { log = false, label = fn.name || 'anonymous function' } = options;\n\n // Collect garbage before measuring (optional)\n if (global.gc) {\n global.gc();\n }\n\n const beforeMemory = process.memoryUsage();\n const result = fn();\n const afterMemory = process.memoryUsage();\n\n // Calculate differences\n const diff: Record<string, number> = {};\n for (const key in afterMemory) {\n if (Object.prototype.hasOwnProperty.call(afterMemory, key)) {\n diff[key] = (afterMemory as any)[key] - (beforeMemory as any)[key];\n }\n }\n\n if (log) {\n getLogger().info(\n {\n label,\n memoryBefore: beforeMemory,\n memoryAfter: afterMemory,\n memoryDiff: diff\n },\n `Memory usage for ${label}`\n );\n }\n\n return {\n result,\n memoryUsage: {\n before: beforeMemory,\n after: afterMemory,\n diff\n }\n };\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"request.utils.js","sourceRoot":"","sources":["../../../src/utils/request.utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;;;;;;;;;;;;;;;;;;;;;;;AAIH,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAiCxD;;;;;GAKG;AACH,MAAM,CAAC,IAAM,mBAAmB,GAAG,UAAS,GAAY;IACtD,IAAM,KAAK,GAAG,GAAG,CAAC,KAA0C,CAAC;IAE7D,uBAAuB;IACjB,IAAA,KAAkB,uBAAuB,CAAC,KAAK,EAAE,CAAC,EAAE,EAAE,EAAE,GAAG,CAAC,EAA1D,IAAI,UAAA,EAAE,KAAK,WAA+C,CAAC;IAC7D,IAAA,KAAwB,iBAAiB,CAAC,KAAK,EAAE,EAAE,CAAC,EAAl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A,cAAc,CAAA,8CAAA,0EAAE,CAAC;YAAhC,IAAM,KAAK,2BAAA;YACd,IAAI,KAAK,IAAI,KAAK,EAAE,CAAC;gBACnB,OAAO,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC;YAChC,CAAC;QACH,CAAC;;;;;;;;;IAED,OAAO,OAAO,CAAC;AACjB,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 { Request } from 'express';\nimport { SortDirection, WithPagination } from '../types/api-response';\nimport { BadRequestException } from './exception.utils';\n\n/**\n * Options for parsing and validating request parameters.\n */\nexport interface ValidationOptions {\n /** Whether to throw an error on validation failure */\n throwOnError?: boolean;\n\n /** Custom error message for validation failures */\n errorMessage?: string;\n\n /** Default value to use if parameter is missing */\n defaultValue?: any;\n\n /** Whether the parameter is required */\n required?: boolean;\n}\n\n/**\n * Result of a parameter validation operation.\n */\nexport interface ValidationResult<T> {\n /** Whether validation was successful */\n isValid: boolean;\n\n /** The validated and potentially transformed value */\n value: T | null;\n\n /** Error message if validation failed */\n error?: string;\n}\n\n/**\n * Extracts pagination, sorting, and optional search params from a request.\n *\n * @param req - Express request\n * @returns Object containing validated pagination, sorting, and additional query params\n */\nexport const getPaginationParams = <T = {}>(req: Request): WithPagination<T> => {\n const query = req.query as Record<string, string | string[]>;\n\n // Extract page & limit\n const { page, limit } = extractPaginationParams(query, 1, 20, 100);\n const { sortBy, sortOrder } = extractSortParams(query, []);\n\n // Optional search param\n const search = typeof query.search === 'string' ? query.search : undefined;\n\n return {\n ...(query as T),\n page,\n limit,\n sortBy,\n sortOrder: sortOrder as SortDirection,\n search\n };\n};\n\n/**\n * Safely parses a string parameter to a number.\n *\n * @param value - String value to parse\n * @param options - Validation options\n * @returns Validation result containing the parsed number or error\n */\nexport function parseNumberParam(value: string | undefined, options: ValidationOptions = {}): ValidationResult<number> {\n const { throwOnError = false, errorMessage = 'Invalid number parameter', defaultValue, required = false } = options;\n\n // Handle undefined case\n if (value === undefined) {\n if (required) {\n const error = `Required number parameter is missing`;\n if (throwOnError) throw new BadRequestException(error);\n return { isValid: false, value: null, error };\n }\n\n return {\n isValid: defaultValue !== undefined,\n value: defaultValue !== undefined ? defaultValue : null,\n error: defaultValue === undefined ? 'Missing parameter with no default' : undefined\n };\n }\n\n // Parse and validate the number\n const num = Number(value);\n if (isNaN(num)) {\n if (throwOnError) throw new BadRequestException(errorMessage);\n return { isValid: false, value: null, error: errorMessage };\n }\n\n return { isValid: true, value: num };\n}\n\n/**\n * Safely parses a string parameter to a boolean.\n *\n * @param value - String value to parse\n * @param options - Validation options\n * @returns Validation result containing the parsed boolean or error\n */\nexport function parseBooleanParam(\n value: string | undefined,\n options: ValidationOptions = {}\n): ValidationResult<boolean> {\n const { throwOnError = false, errorMessage = 'Invalid boolean parameter', defaultValue, required = false } = options;\n\n // Handle undefined case\n if (value === undefined) {\n if (required) {\n const error = `Required boolean parameter is missing`;\n if (throwOnError) throw new BadRequestException(error);\n return { isValid: false, value: null, error };\n }\n\n return {\n isValid: defaultValue !== undefined,\n value: defaultValue !== undefined ? defaultValue : null,\n error: defaultValue === undefined ? 'Missing parameter with no default' : undefined\n };\n }\n\n // Parse the boolean value with various allowed formats\n const lowercaseValue = value.toLowerCase();\n if (['true', 't', 'yes', 'y', '1'].includes(lowercaseValue)) {\n return { isValid: true, value: true };\n }\n\n if (['false', 'f', 'no', 'n', '0'].includes(lowercaseValue)) {\n return { isValid: true, value: false };\n }\n\n if (throwOnError) throw new BadRequestException(errorMessage);\n return { isValid: false, value: null, error: errorMessage };\n}\n\n/**\n * Extracts pagination parameters from request query parameters.\n *\n * @param query - Query parameters object\n * @param defaultPage - Default page number if not specified (defaults to 1)\n * @param defaultLimit - Default per page size if not specified (defaults to 20)\n * @param maxLimitSize - Maximum allowed per page size (defaults to 100)\n * @returns Object containing validated page and limit\n */\nexport function extractPaginationParams(\n query: Record<string, string | string[]>,\n defaultPage: number = 1,\n defaultLimit: number = 20,\n maxLimitSize: number = 100\n): { page: number; limit: number } {\n // Parse page parameter\n const pageParam = typeof query.page === 'string' ? query.page : undefined;\n const pageResult = parseNumberParam(pageParam, { defaultValue: defaultPage });\n\n // Parse limit parameter\n const limitParam = typeof query.limit === 'string' ? query.limit : undefined;\n const limitResult = parseNumberParam(limitParam, { defaultValue: defaultLimit });\n\n // Ensure valid values (handle 0 → fallback to default)\n const page = pageResult.value && pageResult.value > 0 ? pageResult.value : defaultPage;\n\n const limit = limitResult.value && limitResult.value > 0 ? Math.min(limitResult.value, maxLimitSize) : defaultLimit;\n\n return { page, limit };\n}\n\n/**\n * Extracts sorting parameters from request query parameters.\n *\n * @param query - Query parameters object\n * @param allowedFields - Array of field names that are allowed to be sorted\n * @param defaultSort - Default sort configuration if not specified\n * @returns Object containing sort field and direction\n */\nexport function extractSortParams(\n query: Record<string, string | string[]>,\n allowedFields: string[],\n defaultSort: { sortBy: string; sortOrder: 'asc' | 'desc' } = { sortBy: 'createdAt', sortOrder: 'desc' }\n): { sortBy: string; sortOrder: 'asc' | 'desc' } {\n let sortBy = defaultSort.sortBy;\n let sortOrder: 'asc' | 'desc' = defaultSort.sortOrder;\n\n // Extract from `sortBy` or `sort`\n if (typeof query.sortBy === 'string') {\n sortBy = query.sortBy;\n } else if (Array.isArray(query.sortBy)) {\n sortBy = query.sortBy[0];\n } else if (typeof query.sort === 'string') {\n sortBy = query.sort.startsWith('-') ? query.sort.slice(1) : query.sort;\n sortOrder = query.sort.startsWith('-') ? 'desc' : 'asc';\n } else if (Array.isArray(query.sort)) {\n sortBy = query.sort[0].startsWith('-') ? query.sort[0].slice(1) : query.sort[0];\n sortOrder = query.sort[0].startsWith('-') ? 'desc' : 'asc';\n }\n\n // Explicit sortOrder (overrides inferred one if valid)\n if (typeof query.sortOrder === 'string') {\n const order = query.sortOrder.toLowerCase();\n if (order === 'asc' || order === 'desc') {\n sortOrder = order;\n }\n }\n\n // Validate field\n if (allowedFields.length && !allowedFields.includes(sortBy)) {\n sortBy = defaultSort.sortBy;\n }\n\n return { sortBy, sortOrder };\n}\n\n/**\n * Extracts filter parameters from query parameters based on allowed filter fields.\n *\n * @param query - Query parameters object\n * @param allowedFilters - Array of field names that are allowed to be used as filters\n * @returns Object containing the filters as key-value pairs\n */\nexport function extractFilterParams(\n query: Record<string, string | string[]>,\n allowedFilters: string[]\n): Record<string, string | string[]> {\n const filters: Record<string, string | string[]> = {};\n\n // Find filter parameters in the query\n for (const field of allowedFilters) {\n if (field in query) {\n filters[field] = query[field];\n }\n }\n\n return filters;\n}\n"]}