@catbee/utils 0.0.5 → 0.0.6

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 (201) hide show
  1. package/LICENSE +21 -201
  2. package/README.md +222 -4
  3. package/build/esm/config.d.ts +88 -3
  4. package/build/esm/config.js +97 -1
  5. package/build/esm/config.js.map +1 -1
  6. package/build/esm/index.d.ts +4 -0
  7. package/build/esm/index.js +27 -0
  8. package/build/esm/index.js.map +1 -1
  9. package/build/esm/servers/server.builder.d.ts +625 -0
  10. package/build/esm/servers/server.builder.js +722 -0
  11. package/build/esm/servers/server.builder.js.map +1 -0
  12. package/build/esm/servers/server.d.ts +256 -0
  13. package/build/esm/servers/server.js +1211 -0
  14. package/build/esm/servers/server.js.map +1 -0
  15. package/build/esm/types/api-response.d.ts +5 -7
  16. package/build/esm/types/api-response.js +23 -0
  17. package/build/esm/types/api-response.js.map +1 -1
  18. package/build/esm/types/index.d.ts +125 -0
  19. package/build/esm/types/index.js +25 -0
  20. package/build/esm/types/index.js.map +1 -0
  21. package/build/esm/types/server.d.ts +285 -0
  22. package/build/esm/types/server.js +25 -0
  23. package/build/esm/types/server.js.map +1 -0
  24. package/build/esm/utils/array.utils.js +23 -0
  25. package/build/esm/utils/array.utils.js.map +1 -1
  26. package/build/esm/utils/async.utils.js +23 -0
  27. package/build/esm/utils/async.utils.js.map +1 -1
  28. package/build/esm/utils/cache.utils.js +23 -0
  29. package/build/esm/utils/cache.utils.js.map +1 -1
  30. package/build/esm/utils/context-store.utils.js +23 -0
  31. package/build/esm/utils/context-store.utils.js.map +1 -1
  32. package/build/esm/utils/crypto.utils.js +23 -0
  33. package/build/esm/utils/crypto.utils.js.map +1 -1
  34. package/build/esm/utils/decorators.utils.js +23 -1
  35. package/build/esm/utils/decorators.utils.js.map +1 -1
  36. package/build/esm/utils/dir.utils.js +23 -0
  37. package/build/esm/utils/dir.utils.js.map +1 -1
  38. package/build/esm/utils/env.utils.js +23 -0
  39. package/build/esm/utils/env.utils.js.map +1 -1
  40. package/build/esm/utils/exception.utils.js +31 -8
  41. package/build/esm/utils/exception.utils.js.map +1 -1
  42. package/build/esm/utils/fs.utils.js +23 -0
  43. package/build/esm/utils/fs.utils.js.map +1 -1
  44. package/build/esm/utils/http-status-codes.js +23 -0
  45. package/build/esm/utils/http-status-codes.js.map +1 -1
  46. package/build/esm/utils/id.utils.js +23 -0
  47. package/build/esm/utils/id.utils.js.map +1 -1
  48. package/build/esm/utils/logger.utils.d.ts +11 -0
  49. package/build/esm/utils/logger.utils.js +46 -3
  50. package/build/esm/utils/logger.utils.js.map +1 -1
  51. package/build/esm/utils/middleware.utils.d.ts +2 -0
  52. package/build/esm/utils/middleware.utils.js +59 -49
  53. package/build/esm/utils/middleware.utils.js.map +1 -1
  54. package/build/esm/utils/obj.utils.d.ts +10 -3
  55. package/build/esm/utils/obj.utils.js +225 -15
  56. package/build/esm/utils/obj.utils.js.map +1 -1
  57. package/build/esm/utils/request.utils.js +23 -0
  58. package/build/esm/utils/request.utils.js.map +1 -1
  59. package/build/esm/utils/response.utils.d.ts +15 -1
  60. package/build/esm/utils/response.utils.js +51 -0
  61. package/build/esm/utils/response.utils.js.map +1 -1
  62. package/build/esm/utils/string.utils.js +23 -0
  63. package/build/esm/utils/string.utils.js.map +1 -1
  64. package/build/esm/utils/url.utils.js +23 -0
  65. package/build/esm/utils/url.utils.js.map +1 -1
  66. package/build/esm/utils/validate.utils.d.ts +7 -0
  67. package/build/esm/utils/validate.utils.js +35 -2
  68. package/build/esm/utils/validate.utils.js.map +1 -1
  69. package/build/esnext/config.d.ts +88 -3
  70. package/build/esnext/config.js +97 -1
  71. package/build/esnext/config.js.map +1 -1
  72. package/build/esnext/index.d.ts +4 -0
  73. package/build/esnext/index.js +27 -0
  74. package/build/esnext/index.js.map +1 -1
  75. package/build/esnext/servers/server.builder.d.ts +625 -0
  76. package/build/esnext/servers/server.builder.js +677 -0
  77. package/build/esnext/servers/server.builder.js.map +1 -0
  78. package/build/esnext/servers/server.d.ts +256 -0
  79. package/build/esnext/servers/server.js +918 -0
  80. package/build/esnext/servers/server.js.map +1 -0
  81. package/build/esnext/types/api-response.d.ts +5 -7
  82. package/build/esnext/types/api-response.js +23 -0
  83. package/build/esnext/types/api-response.js.map +1 -1
  84. package/build/esnext/types/index.d.ts +125 -0
  85. package/build/esnext/types/index.js +25 -0
  86. package/build/esnext/types/index.js.map +1 -0
  87. package/build/esnext/types/server.d.ts +285 -0
  88. package/build/esnext/types/server.js +25 -0
  89. package/build/esnext/types/server.js.map +1 -0
  90. package/build/esnext/utils/array.utils.js +23 -0
  91. package/build/esnext/utils/array.utils.js.map +1 -1
  92. package/build/esnext/utils/async.utils.js +23 -0
  93. package/build/esnext/utils/async.utils.js.map +1 -1
  94. package/build/esnext/utils/cache.utils.js +23 -0
  95. package/build/esnext/utils/cache.utils.js.map +1 -1
  96. package/build/esnext/utils/context-store.utils.js +23 -0
  97. package/build/esnext/utils/context-store.utils.js.map +1 -1
  98. package/build/esnext/utils/crypto.utils.js +23 -0
  99. package/build/esnext/utils/crypto.utils.js.map +1 -1
  100. package/build/esnext/utils/decorators.utils.js +23 -1
  101. package/build/esnext/utils/decorators.utils.js.map +1 -1
  102. package/build/esnext/utils/dir.utils.js +23 -0
  103. package/build/esnext/utils/dir.utils.js.map +1 -1
  104. package/build/esnext/utils/env.utils.js +23 -0
  105. package/build/esnext/utils/env.utils.js.map +1 -1
  106. package/build/esnext/utils/exception.utils.js +30 -7
  107. package/build/esnext/utils/exception.utils.js.map +1 -1
  108. package/build/esnext/utils/fs.utils.js +23 -0
  109. package/build/esnext/utils/fs.utils.js.map +1 -1
  110. package/build/esnext/utils/http-status-codes.js +23 -0
  111. package/build/esnext/utils/http-status-codes.js.map +1 -1
  112. package/build/esnext/utils/id.utils.js +23 -0
  113. package/build/esnext/utils/id.utils.js.map +1 -1
  114. package/build/esnext/utils/logger.utils.d.ts +11 -0
  115. package/build/esnext/utils/logger.utils.js +46 -3
  116. package/build/esnext/utils/logger.utils.js.map +1 -1
  117. package/build/esnext/utils/middleware.utils.d.ts +2 -0
  118. package/build/esnext/utils/middleware.utils.js +55 -49
  119. package/build/esnext/utils/middleware.utils.js.map +1 -1
  120. package/build/esnext/utils/obj.utils.d.ts +10 -3
  121. package/build/esnext/utils/obj.utils.js +176 -12
  122. package/build/esnext/utils/obj.utils.js.map +1 -1
  123. package/build/esnext/utils/request.utils.js +23 -0
  124. package/build/esnext/utils/request.utils.js.map +1 -1
  125. package/build/esnext/utils/response.utils.d.ts +15 -1
  126. package/build/esnext/utils/response.utils.js +51 -0
  127. package/build/esnext/utils/response.utils.js.map +1 -1
  128. package/build/esnext/utils/string.utils.js +23 -0
  129. package/build/esnext/utils/string.utils.js.map +1 -1
  130. package/build/esnext/utils/url.utils.js +23 -0
  131. package/build/esnext/utils/url.utils.js.map +1 -1
  132. package/build/esnext/utils/validate.utils.d.ts +7 -0
  133. package/build/esnext/utils/validate.utils.js +33 -0
  134. package/build/esnext/utils/validate.utils.js.map +1 -1
  135. package/build/src/config.d.ts +88 -3
  136. package/build/src/config.js +98 -2
  137. package/build/src/config.js.map +1 -1
  138. package/build/src/index.d.ts +4 -0
  139. package/build/src/index.js +27 -0
  140. package/build/src/index.js.map +1 -1
  141. package/build/src/servers/server.builder.d.ts +625 -0
  142. package/build/src/servers/server.builder.js +681 -0
  143. package/build/src/servers/server.builder.js.map +1 -0
  144. package/build/src/servers/server.d.ts +256 -0
  145. package/build/src/servers/server.js +958 -0
  146. package/build/src/servers/server.js.map +1 -0
  147. package/build/src/types/api-response.d.ts +5 -7
  148. package/build/src/types/api-response.js +23 -0
  149. package/build/src/types/api-response.js.map +1 -1
  150. package/build/src/types/index.d.ts +125 -0
  151. package/build/src/types/index.js +26 -0
  152. package/build/src/types/index.js.map +1 -0
  153. package/build/src/types/server.d.ts +285 -0
  154. package/build/src/types/server.js +26 -0
  155. package/build/src/types/server.js.map +1 -0
  156. package/build/src/utils/array.utils.js +23 -0
  157. package/build/src/utils/array.utils.js.map +1 -1
  158. package/build/src/utils/async.utils.js +23 -0
  159. package/build/src/utils/async.utils.js.map +1 -1
  160. package/build/src/utils/cache.utils.js +23 -0
  161. package/build/src/utils/cache.utils.js.map +1 -1
  162. package/build/src/utils/context-store.utils.js +23 -0
  163. package/build/src/utils/context-store.utils.js.map +1 -1
  164. package/build/src/utils/crypto.utils.js +23 -0
  165. package/build/src/utils/crypto.utils.js.map +1 -1
  166. package/build/src/utils/decorators.utils.js +23 -1
  167. package/build/src/utils/decorators.utils.js.map +1 -1
  168. package/build/src/utils/dir.utils.js +23 -0
  169. package/build/src/utils/dir.utils.js.map +1 -1
  170. package/build/src/utils/env.utils.js +23 -0
  171. package/build/src/utils/env.utils.js.map +1 -1
  172. package/build/src/utils/exception.utils.js +30 -7
  173. package/build/src/utils/exception.utils.js.map +1 -1
  174. package/build/src/utils/fs.utils.js +23 -0
  175. package/build/src/utils/fs.utils.js.map +1 -1
  176. package/build/src/utils/http-status-codes.js +23 -0
  177. package/build/src/utils/http-status-codes.js.map +1 -1
  178. package/build/src/utils/id.utils.js +23 -0
  179. package/build/src/utils/id.utils.js.map +1 -1
  180. package/build/src/utils/logger.utils.d.ts +11 -0
  181. package/build/src/utils/logger.utils.js +47 -4
  182. package/build/src/utils/logger.utils.js.map +1 -1
  183. package/build/src/utils/middleware.utils.d.ts +2 -0
  184. package/build/src/utils/middleware.utils.js +54 -48
  185. package/build/src/utils/middleware.utils.js.map +1 -1
  186. package/build/src/utils/obj.utils.d.ts +10 -3
  187. package/build/src/utils/obj.utils.js +177 -12
  188. package/build/src/utils/obj.utils.js.map +1 -1
  189. package/build/src/utils/request.utils.js +23 -0
  190. package/build/src/utils/request.utils.js.map +1 -1
  191. package/build/src/utils/response.utils.d.ts +15 -1
  192. package/build/src/utils/response.utils.js +52 -0
  193. package/build/src/utils/response.utils.js.map +1 -1
  194. package/build/src/utils/string.utils.js +23 -0
  195. package/build/src/utils/string.utils.js.map +1 -1
  196. package/build/src/utils/url.utils.js +23 -0
  197. package/build/src/utils/url.utils.js.map +1 -1
  198. package/build/src/utils/validate.utils.d.ts +7 -0
  199. package/build/src/utils/validate.utils.js +36 -2
  200. package/build/src/utils/validate.utils.js.map +1 -1
  201. package/package.json +35 -9
@@ -1 +1 @@
1
- {"version":3,"file":"dir.utils.js","sourceRoot":"","sources":["../../../src/utils/dir.utils.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,GAAG,MAAM,aAAa,CAAC;AAC9B,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,EAAE,WAAW,EAAE,MAAM,QAAQ,CAAC;AAErC;;;;;;GAMG;AACH,MAAM,UAAgB,SAAS,CAAC,OAAe;;;;wBAC7C,qBAAM,GAAG,CAAC,KAAK,CAAC,OAAO,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,EAAA;;oBAA7C,SAA6C,CAAC;;;;;CAC/C;AAED;;;;;;;GAOG;AACH,MAAM,UAAgB,SAAS;wDAAC,OAAe,EAAE,SAAiB;;;QAAjB,0BAAA,EAAA,iBAAiB;;;wBAChD,qBAAM,GAAG,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,aAAa,EAAE,IAAI,EAAE,CAAC,EAAA;;oBAA7D,OAAO,GAAG,SAAmD;oBAC7D,KAAK,GAAa,EAAE,CAAC;;;;oBAEP,YAAA,SAAA,OAAO,CAAA;;;;oBAAhB,KAAK;oBACR,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC;yBAE5C,KAAK,CAAC,MAAM,EAAE,EAAd,wBAAc;oBACh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AAM,OAAO,CAAC,SAAS,CAAC,SAAS,CAAC,EAAA;;oBADlC,4CAA4C;oBAC5C,SAAkC,CAAC;;;;;;;;;;;;;;;;;yBAInC,CAAA,cAAc,KAAK,MAAM,CAAA,EAAzB,yBAAyB;oBAGb,qBAAM,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,EAAA;;oBAA/B,KAAK,GAAG,SAAuB;oBAC/B,SAAS,GAAG;wBAChB,IAAI,EAAE,OAAO;wBACb,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC;wBAC5B,WAAW,EAAE,IAAI;wBACjB,KAAK,OAAA;qBACN,CAAC;oBACF,qBAAM,OAAO,CAAC,SAAS,CAAC,SAAS,CAAC,EAAA;;oBAAlC,SAAkC,CAAC;;;;;;CAEtC","sourcesContent":["import 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
+ {"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,CAAC;AACxB,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,EAAE,WAAW,EAAE,MAAM,QAAQ,CAAC;AAErC;;;;;;GAMG;AACH,MAAM,UAAgB,SAAS,CAAC,OAAe;;;;wBAC7C,qBAAM,GAAG,CAAC,KAAK,CAAC,OAAO,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,EAAA;;oBAA7C,SAA6C,CAAC;;;;;CAC/C;AAED;;;;;;;GAOG;AACH,MAAM,UAAgB,SAAS;wDAAC,OAAe,EAAE,SAAiB;;;QAAjB,0BAAA,EAAA,iBAAiB;;;wBAChD,qBAAM,GAAG,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,aAAa,EAAE,IAAI,EAAE,CAAC,EAAA;;oBAA7D,OAAO,GAAG,SAAmD;oBAC7D,KAAK,GAAa,EAAE,CAAC;;;;oBAEP,YAAA,SAAA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,OAAO,CAAC,EAAA;;oBADjC,iDAAiD;oBACjD,SAAiC,CAAC;oBAClC,qBAAM,OAAO,CAAC,SAAS,CAAC,SAAS,CAAC,EAAA;;oBAAlC,SAAkC,CAAC;;;;gBAGrC,4CAA4C;gBAC5C,qBAAM,OAAO,CAAC,SAAS,CAAC,SAAS,CAAC,EAAA;;oBADlC,4CAA4C;oBAC5C,SAAkC,CAAC;;;;;;;;;;;;;;;;;yBAInC,CAAA,cAAc,KAAK,MAAM,CAAA,EAAzB,yBAAyB;oBAGb,qBAAM,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,EAAA;;oBAA/B,KAAK,GAAG,SAAuB;oBAC/B,SAAS,GAAG;wBAChB,IAAI,EAAE,OAAO;wBACb,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC;wBAC5B,WAAW,EAAE,IAAI;wBACjB,KAAK,OAAA;qBACN,CAAC;oBACF,qBAAM,OAAO,CAAC,SAAS,CAAC,SAAS,CAAC,EAAA;;oBAAlC,SAAkC,CAAC;;;;;;CAEtC","sourcesContent":["/*\n * The MIT License\n *\n * Copyright (c) 2025 Catbee Technologies\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,3 +1,26 @@
1
+ /*
2
+ * The MIT License
3
+ *
4
+ * Copyright (c) 2025 Catbee Technologies
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
1
24
  var __read = (this && this.__read) || function (o, n) {
2
25
  var m = typeof Symbol === "function" && o[Symbol.iterator];
3
26
  if (!m) return o;
@@ -1 +1 @@
1
- {"version":3,"file":"env.utils.js","sourceRoot":"","sources":["../../../src/utils/env.utils.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,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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AM,QAAQ,WAAA;gBACjB,IAAI,QAAQ,CAAC,QAAQ,CAAC,WAAI,GAAG,CAAE,CAAC,EAAE,CAAC;oBACjC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;gBAC9B,CAAC;YACH,CAAC;;;;;;;;;IACH,CAAC;IAED;;;OAGG;IACI,cAAU,GAAjB;QACE,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC;IACrB,CAAC;IAr0BD,sEAAsE;IACvD,SAAK,GAAqB,IAAI,GAAG,EAAE,CAAC;IAq0BrD,UAAC;CAAA,AAv0BD,IAu0BC;SAv0BY,GAAG","sourcesContent":["/* 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
+ {"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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,UAAc,GAAW;;QACvB,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QACxB,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;;YAEvB,+CAA+C;YAC/C,KAAuB,IAAA,KAAA,SAAA,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,CAAA,gBAAA,4BAAE,CAAC;gBAAtC,IAAM,QAAQ,WAAA;gBACjB,IAAI,QAAQ,CAAC,QAAQ,CAAC,WAAI,GAAG,CAAE,CAAC,EAAE,CAAC;oBACjC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;gBAC9B,CAAC;YACH,CAAC;;;;;;;;;IACH,CAAC;IAED;;;OAGG;IACI,cAAU,GAAjB;QACE,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC;IACrB,CAAC;IAr0BD,sEAAsE;IACvD,SAAK,GAAqB,IAAI,GAAG,EAAE,CAAC;IAq0BrD,UAAC;CAAA,AAv0BD,IAu0BC;SAv0BY,GAAG","sourcesContent":["/*\n * The MIT License\n *\n * Copyright (c) 2025 Catbee Technologies\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,3 +1,26 @@
1
+ /*
2
+ * The MIT License
3
+ *
4
+ * Copyright (c) 2025 Catbee Technologies
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
1
24
  var __extends = (this && this.__extends) || (function () {
2
25
  var extendStatics = function (d, b) {
3
26
  extendStatics = Object.setPrototypeOf ||
@@ -507,7 +530,7 @@ export function withErrorHandling(handler) {
507
530
  args[_i] = arguments[_i];
508
531
  }
509
532
  return __awaiter(_this, void 0, void 0, function () {
510
- var error_1, status_1;
533
+ var err_1, status_1;
511
534
  return __generator(this, function (_a) {
512
535
  switch (_a.label) {
513
536
  case 0:
@@ -515,18 +538,18 @@ export function withErrorHandling(handler) {
515
538
  return [4 /*yield*/, handler.apply(void 0, __spreadArray([], __read(args), false))];
516
539
  case 1: return [2 /*return*/, _a.sent()];
517
540
  case 2:
518
- error_1 = _a.sent();
519
- if (isHttpError(error_1)) {
520
- throw error_1;
541
+ err_1 = _a.sent();
542
+ if (isHttpError(err_1)) {
543
+ throw err_1;
521
544
  }
522
545
  // Log the original error (consider using a proper logger)
523
- getLogger().error({ error: error_1 }, 'Caught error in handler');
546
+ getLogger().error({ err: err_1 }, 'Caught error in handler');
524
547
  status_1 = HttpStatusCodes.INTERNAL_SERVER_ERROR;
525
- if (hasErrorShape(error_1) && typeof error_1.status === 'number') {
526
- status_1 = error_1.status;
548
+ if (hasErrorShape(err_1) && typeof err_1.status === 'number') {
549
+ status_1 = err_1.status;
527
550
  }
528
551
  // Create appropriate HTTP error
529
- throw createHttpError(status_1, getErrorMessage(error_1));
552
+ throw createHttpError(status_1, getErrorMessage(err_1));
530
553
  case 3: return [2 /*return*/];
531
554
  }
532
555
  });
@@ -1 +1 @@
1
- {"version":3,"file":"exception.utils.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M,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,OAAK,CAAC,EAAE,CAAC;4BACvB,MAAM,OAAK,CAAC;wBACd,CAAC;wBAED,0DAA0D;wBAC1D,SAAS,EAAE,CAAC,KAAK,CAAC,EAAE,KAAK,SAAA,EAAE,EAAE,yBAAyB,CAAC,CAAC;wBAGpD,WAAS,eAAe,CAAC,qBAAqB,CAAC;wBACnD,IAAI,aAAa,CAAC,OAAK,CAAC,IAAI,OAAO,OAAK,CAAC,MAAM,KAAK,QAAQ,EAAE,CAAC;4BAC7D,QAAM,GAAG,OAAK,CAAC,MAAM,CAAC;wBACxB,CAAC;wBAED,gCAAgC;wBAChC,MAAM,eAAe,CAAC,QAAM,EAAE,eAAe,CAAC,OAAK,CAAC,CAAC,CAAC;;;;;KAEzD,CAAC;AACJ,CAAC","sourcesContent":["import { 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 (error) {\n if (isHttpError(error)) {\n throw error;\n }\n\n // Log the original error (consider using a proper logger)\n getLogger().error({ error }, '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(error) && typeof error.status === 'number') {\n status = error.status;\n }\n\n // Create appropriate HTTP error\n throw createHttpError(status, getErrorMessage(error));\n }\n };\n}\n"]}
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;AAA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AO,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\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"]}