@catbee/utils 0.0.1 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. package/README.md +303 -107
  2. package/build/esm/config.d.ts +13 -1
  3. package/build/esm/config.js +16 -4
  4. package/build/esm/config.js.map +1 -1
  5. package/build/esm/index.d.ts +20 -18
  6. package/build/esm/index.js +20 -18
  7. package/build/esm/index.js.map +1 -1
  8. package/build/esm/types/api-response.d.ts +83 -1
  9. package/build/esm/types/api-response.js.map +1 -1
  10. package/build/esm/utils/array.utils.d.ts +65 -2
  11. package/build/esm/utils/array.utils.js +147 -20
  12. package/build/esm/utils/array.utils.js.map +1 -1
  13. package/build/esm/utils/async.utils.d.ts +56 -1
  14. package/build/esm/utils/async.utils.js +166 -11
  15. package/build/esm/utils/async.utils.js.map +1 -1
  16. package/build/esm/utils/cache.utils.d.ts +67 -4
  17. package/build/esm/utils/cache.utils.js +210 -28
  18. package/build/esm/utils/cache.utils.js.map +1 -1
  19. package/build/esm/utils/context-store.utils.d.ts +102 -1
  20. package/build/esm/utils/context-store.utils.js +185 -3
  21. package/build/esm/utils/context-store.utils.js.map +1 -1
  22. package/build/esm/utils/crypto.utils.d.ts +110 -8
  23. package/build/esm/utils/crypto.utils.js +298 -23
  24. package/build/esm/utils/crypto.utils.js.map +1 -1
  25. package/build/esm/utils/decorators.utils.d.ts +40 -0
  26. package/build/esm/utils/decorators.utils.js +312 -0
  27. package/build/esm/utils/decorators.utils.js.map +1 -0
  28. package/build/esm/utils/dir.utils.d.ts +122 -1
  29. package/build/esm/utils/dir.utils.js +578 -3
  30. package/build/esm/utils/dir.utils.js.map +1 -1
  31. package/build/esm/utils/env.utils.d.ts +83 -0
  32. package/build/esm/utils/env.utils.js +235 -6
  33. package/build/esm/utils/env.utils.js.map +1 -1
  34. package/build/esm/utils/exception.utils.d.ts +117 -1
  35. package/build/esm/utils/exception.utils.js +331 -12
  36. package/build/esm/utils/exception.utils.js.map +1 -1
  37. package/build/esm/utils/fs.utils.d.ts +132 -0
  38. package/build/esm/utils/fs.utils.js +421 -4
  39. package/build/esm/utils/fs.utils.js.map +1 -1
  40. package/build/esm/utils/http-status-codes.d.ts +87 -178
  41. package/build/esm/utils/http-status-codes.js +92 -178
  42. package/build/esm/utils/http-status-codes.js.map +1 -1
  43. package/build/esm/utils/id.utils.d.ts +11 -10
  44. package/build/esm/utils/id.utils.js +30 -21
  45. package/build/esm/utils/id.utils.js.map +1 -1
  46. package/build/esm/utils/logger.utils.d.ts +35 -2
  47. package/build/esm/utils/logger.utils.js +68 -14
  48. package/build/esm/utils/logger.utils.js.map +1 -1
  49. package/build/esm/utils/middleware.utils.d.ts +73 -0
  50. package/build/esm/utils/middleware.utils.js +158 -0
  51. package/build/esm/utils/middleware.utils.js.map +1 -0
  52. package/build/esm/utils/obj.utils.d.ts +65 -3
  53. package/build/esm/utils/obj.utils.js +206 -18
  54. package/build/esm/utils/obj.utils.js.map +1 -1
  55. package/build/esm/utils/response.utils.d.ts +103 -2
  56. package/build/esm/utils/response.utils.js +156 -3
  57. package/build/esm/utils/response.utils.js.map +1 -1
  58. package/build/esm/utils/string.utils.d.ts +61 -5
  59. package/build/esm/utils/string.utils.js +109 -19
  60. package/build/esm/utils/string.utils.js.map +1 -1
  61. package/build/esm/utils/url.utils.d.ts +117 -0
  62. package/build/esm/utils/url.utils.js +287 -2
  63. package/build/esm/utils/url.utils.js.map +1 -1
  64. package/build/esm/utils/validate.utils.d.ts +110 -0
  65. package/build/esm/utils/validate.utils.js +190 -8
  66. package/build/esm/utils/validate.utils.js.map +1 -1
  67. package/build/esnext/config.d.ts +13 -1
  68. package/build/esnext/config.js +16 -4
  69. package/build/esnext/config.js.map +1 -1
  70. package/build/esnext/index.d.ts +20 -18
  71. package/build/esnext/index.js +20 -18
  72. package/build/esnext/index.js.map +1 -1
  73. package/build/esnext/types/api-response.d.ts +83 -1
  74. package/build/esnext/types/api-response.js.map +1 -1
  75. package/build/esnext/utils/array.utils.d.ts +65 -2
  76. package/build/esnext/utils/array.utils.js +140 -21
  77. package/build/esnext/utils/array.utils.js.map +1 -1
  78. package/build/esnext/utils/async.utils.d.ts +56 -1
  79. package/build/esnext/utils/async.utils.js +130 -14
  80. package/build/esnext/utils/async.utils.js.map +1 -1
  81. package/build/esnext/utils/cache.utils.d.ts +67 -4
  82. package/build/esnext/utils/cache.utils.js +137 -9
  83. package/build/esnext/utils/cache.utils.js.map +1 -1
  84. package/build/esnext/utils/context-store.utils.d.ts +102 -1
  85. package/build/esnext/utils/context-store.utils.js +171 -3
  86. package/build/esnext/utils/context-store.utils.js.map +1 -1
  87. package/build/esnext/utils/crypto.utils.d.ts +110 -8
  88. package/build/esnext/utils/crypto.utils.js +199 -19
  89. package/build/esnext/utils/crypto.utils.js.map +1 -1
  90. package/build/esnext/utils/decorators.utils.d.ts +40 -0
  91. package/build/esnext/utils/decorators.utils.js +155 -0
  92. package/build/esnext/utils/decorators.utils.js.map +1 -0
  93. package/build/esnext/utils/dir.utils.d.ts +122 -1
  94. package/build/esnext/utils/dir.utils.js +307 -3
  95. package/build/esnext/utils/dir.utils.js.map +1 -1
  96. package/build/esnext/utils/env.utils.d.ts +83 -0
  97. package/build/esnext/utils/env.utils.js +191 -8
  98. package/build/esnext/utils/env.utils.js.map +1 -1
  99. package/build/esnext/utils/exception.utils.d.ts +117 -1
  100. package/build/esnext/utils/exception.utils.js +222 -12
  101. package/build/esnext/utils/exception.utils.js.map +1 -1
  102. package/build/esnext/utils/fs.utils.d.ts +132 -0
  103. package/build/esnext/utils/fs.utils.js +268 -4
  104. package/build/esnext/utils/fs.utils.js.map +1 -1
  105. package/build/esnext/utils/http-status-codes.d.ts +87 -178
  106. package/build/esnext/utils/http-status-codes.js +92 -178
  107. package/build/esnext/utils/http-status-codes.js.map +1 -1
  108. package/build/esnext/utils/id.utils.d.ts +11 -10
  109. package/build/esnext/utils/id.utils.js +28 -20
  110. package/build/esnext/utils/id.utils.js.map +1 -1
  111. package/build/esnext/utils/logger.utils.d.ts +35 -2
  112. package/build/esnext/utils/logger.utils.js +56 -14
  113. package/build/esnext/utils/logger.utils.js.map +1 -1
  114. package/build/esnext/utils/middleware.utils.d.ts +73 -0
  115. package/build/esnext/utils/middleware.utils.js +157 -0
  116. package/build/esnext/utils/middleware.utils.js.map +1 -0
  117. package/build/esnext/utils/obj.utils.d.ts +65 -3
  118. package/build/esnext/utils/obj.utils.js +169 -14
  119. package/build/esnext/utils/obj.utils.js.map +1 -1
  120. package/build/esnext/utils/response.utils.d.ts +103 -2
  121. package/build/esnext/utils/response.utils.js +141 -3
  122. package/build/esnext/utils/response.utils.js.map +1 -1
  123. package/build/esnext/utils/string.utils.d.ts +61 -5
  124. package/build/esnext/utils/string.utils.js +110 -14
  125. package/build/esnext/utils/string.utils.js.map +1 -1
  126. package/build/esnext/utils/url.utils.d.ts +117 -0
  127. package/build/esnext/utils/url.utils.js +248 -2
  128. package/build/esnext/utils/url.utils.js.map +1 -1
  129. package/build/esnext/utils/validate.utils.d.ts +110 -0
  130. package/build/esnext/utils/validate.utils.js +190 -8
  131. package/build/esnext/utils/validate.utils.js.map +1 -1
  132. package/build/src/config.d.ts +13 -1
  133. package/build/src/config.js +15 -3
  134. package/build/src/config.js.map +1 -1
  135. package/build/src/index.d.ts +20 -18
  136. package/build/src/index.js +2 -0
  137. package/build/src/index.js.map +1 -1
  138. package/build/src/types/api-response.d.ts +83 -1
  139. package/build/src/types/api-response.js.map +1 -1
  140. package/build/src/utils/array.utils.d.ts +65 -2
  141. package/build/src/utils/array.utils.js +147 -22
  142. package/build/src/utils/array.utils.js.map +1 -1
  143. package/build/src/utils/async.utils.d.ts +56 -1
  144. package/build/src/utils/async.utils.js +137 -17
  145. package/build/src/utils/async.utils.js.map +1 -1
  146. package/build/src/utils/cache.utils.d.ts +67 -4
  147. package/build/src/utils/cache.utils.js +137 -9
  148. package/build/src/utils/cache.utils.js.map +1 -1
  149. package/build/src/utils/context-store.utils.d.ts +102 -1
  150. package/build/src/utils/context-store.utils.js +173 -3
  151. package/build/src/utils/context-store.utils.js.map +1 -1
  152. package/build/src/utils/crypto.utils.d.ts +110 -8
  153. package/build/src/utils/crypto.utils.js +214 -27
  154. package/build/src/utils/crypto.utils.js.map +1 -1
  155. package/build/src/utils/decorators.utils.d.ts +40 -0
  156. package/build/src/utils/decorators.utils.js +165 -0
  157. package/build/src/utils/decorators.utils.js.map +1 -0
  158. package/build/src/utils/dir.utils.d.ts +122 -1
  159. package/build/src/utils/dir.utils.js +314 -0
  160. package/build/src/utils/dir.utils.js.map +1 -1
  161. package/build/src/utils/env.utils.d.ts +83 -0
  162. package/build/src/utils/env.utils.js +192 -9
  163. package/build/src/utils/env.utils.js.map +1 -1
  164. package/build/src/utils/exception.utils.d.ts +117 -1
  165. package/build/src/utils/exception.utils.js +233 -11
  166. package/build/src/utils/exception.utils.js.map +1 -1
  167. package/build/src/utils/fs.utils.d.ts +132 -0
  168. package/build/src/utils/fs.utils.js +281 -3
  169. package/build/src/utils/fs.utils.js.map +1 -1
  170. package/build/src/utils/http-status-codes.d.ts +87 -178
  171. package/build/src/utils/http-status-codes.js +92 -178
  172. package/build/src/utils/http-status-codes.js.map +1 -1
  173. package/build/src/utils/id.utils.d.ts +11 -10
  174. package/build/src/utils/id.utils.js +28 -20
  175. package/build/src/utils/id.utils.js.map +1 -1
  176. package/build/src/utils/logger.utils.d.ts +35 -2
  177. package/build/src/utils/logger.utils.js +56 -11
  178. package/build/src/utils/logger.utils.js.map +1 -1
  179. package/build/src/utils/middleware.utils.d.ts +73 -0
  180. package/build/src/utils/middleware.utils.js +163 -0
  181. package/build/src/utils/middleware.utils.js.map +1 -0
  182. package/build/src/utils/obj.utils.d.ts +65 -3
  183. package/build/src/utils/obj.utils.js +179 -18
  184. package/build/src/utils/obj.utils.js.map +1 -1
  185. package/build/src/utils/response.utils.d.ts +103 -2
  186. package/build/src/utils/response.utils.js +147 -2
  187. package/build/src/utils/response.utils.js.map +1 -1
  188. package/build/src/utils/string.utils.d.ts +61 -5
  189. package/build/src/utils/string.utils.js +122 -20
  190. package/build/src/utils/string.utils.js.map +1 -1
  191. package/build/src/utils/url.utils.d.ts +117 -0
  192. package/build/src/utils/url.utils.js +256 -1
  193. package/build/src/utils/url.utils.js.map +1 -1
  194. package/build/src/utils/validate.utils.d.ts +110 -0
  195. package/build/src/utils/validate.utils.js +204 -8
  196. package/build/src/utils/validate.utils.js.map +1 -1
  197. package/package.json +20 -12
@@ -1,13 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.uuid = uuid;
4
- exports.ulidString = ulidString;
5
4
  exports.nanoId = nanoId;
6
5
  exports.randomHex = randomHex;
7
6
  exports.randomInt = randomInt;
7
+ exports.randomBase64 = randomBase64;
8
8
  const crypto_1 = require("crypto");
9
- const ulid_1 = require("ulid");
10
- const nanoid_1 = require("nanoid");
11
9
  /**
12
10
  * Generates a UUID v4 string (RFC 4122).
13
11
  *
@@ -17,21 +15,21 @@ function uuid() {
17
15
  return (0, crypto_1.randomUUID)();
18
16
  }
19
17
  /**
20
- * Generates a ULID (Universally Unique Lexicographically Sortable Identifier).
18
+ * Generates a nanoid-style random ID (URL-safe, customizable length).
21
19
  *
22
- * @returns {string} ULID string (26 chars, Crockford Base32, e.g., '01H7ZXS9FJKPX06P1AYZKCGHQF').
20
+ * @param {number} length - Length of the ID (default: 21).
21
+ * @returns {string} Nanoid-style random string.
23
22
  */
24
- function ulidString() {
25
- return (0, ulid_1.ulid)();
26
- }
27
- /**
28
- * Generates a nanoid string (URL-friendly, collision-resistant, customizable size).
29
- *
30
- * @param {number} [size=21] - Number of characters for the ID (default: 21).
31
- * @returns {string} nanoid string.
32
- */
33
- function nanoId(size = 21) {
34
- return (0, nanoid_1.nanoid)(size);
23
+ function nanoId(length = 21) {
24
+ if (length <= 0)
25
+ return '';
26
+ let id = '';
27
+ while (id.length < length) {
28
+ id += (0, crypto_1.randomBytes)(Math.ceil((length * 3) / 4))
29
+ .toString('base64url')
30
+ .replace(/[+/=]/g, '');
31
+ }
32
+ return id.slice(0, length);
35
33
  }
36
34
  /**
37
35
  * Generates a cryptographically strong random hex string.
@@ -40,10 +38,11 @@ function nanoId(size = 21) {
40
38
  * @returns {string} Random hex string.
41
39
  */
42
40
  function randomHex(byteLength = 16) {
43
- // Node: crypto.getRandomValues is not available; use randomBytes if needed.
44
- // If using browser target, replace this impl accordingly.
45
- return Buffer.from(crypto.getRandomValues(new Uint8Array(byteLength)))
46
- .toString("hex")
41
+ // Use Node.js crypto for both Node and browser compatibility
42
+ // Prefer randomBytes if available (Node), fallback to getRandomValues for browser (not used here)
43
+ return (0, crypto_1.randomBytes)(byteLength)
44
+ .toString('hex')
45
+ .padStart(byteLength * 2, '0')
47
46
  .slice(0, byteLength * 2);
48
47
  }
49
48
  /**
@@ -57,4 +56,13 @@ function randomInt(min, max) {
57
56
  const range = max - min + 1;
58
57
  return Math.floor(Math.random() * range) + min;
59
58
  }
59
+ /**
60
+ * Generates a cryptographically strong random base64 string.
61
+ *
62
+ * @param {number} byteLength - Number of random bytes (default: 16).
63
+ * @returns {string} Random base64 string (URL-safe, no padding).
64
+ */
65
+ function randomBase64(byteLength = 16) {
66
+ return (0, crypto_1.randomBytes)(byteLength).toString('base64url');
67
+ }
60
68
  //# sourceMappingURL=id.utils.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"id.utils.js","sourceRoot":"","sources":["../../../src/utils/id.utils.ts"],"names":[],"mappings":";;AASA,oBAEC;AAOD,gCAEC;AAQD,wBAEC;AAQD,8BAMC;AASD,8BAGC;AAxDD,mCAAoC;AACpC,+BAA4B;AAC5B,mCAAgC;AAEhC;;;;GAIG;AACH,SAAgB,IAAI;IAClB,OAAO,IAAA,mBAAU,GAAE,CAAC;AACtB,CAAC;AAED;;;;GAIG;AACH,SAAgB,UAAU;IACxB,OAAO,IAAA,WAAI,GAAE,CAAC;AAChB,CAAC;AAED;;;;;GAKG;AACH,SAAgB,MAAM,CAAC,OAAe,EAAE;IACtC,OAAO,IAAA,eAAM,EAAC,IAAI,CAAC,CAAC;AACtB,CAAC;AAED;;;;;GAKG;AACH,SAAgB,SAAS,CAAC,aAAqB,EAAE;IAC/C,4EAA4E;IAC5E,0DAA0D;IAC1D,OAAO,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,eAAe,CAAC,IAAI,UAAU,CAAC,UAAU,CAAC,CAAC,CAAC;SACnE,QAAQ,CAAC,KAAK,CAAC;SACf,KAAK,CAAC,CAAC,EAAE,UAAU,GAAG,CAAC,CAAC,CAAC;AAC9B,CAAC;AAED;;;;;;GAMG;AACH,SAAgB,SAAS,CAAC,GAAW,EAAE,GAAW;IAChD,MAAM,KAAK,GAAG,GAAG,GAAG,GAAG,GAAG,CAAC,CAAC;IAC5B,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,KAAK,CAAC,GAAG,GAAG,CAAC;AACjD,CAAC","sourcesContent":["import { randomUUID } from \"crypto\";\nimport { ulid } from \"ulid\";\nimport { nanoid } from \"nanoid\";\n\n/**\n * Generates a UUID v4 string (RFC 4122).\n *\n * @returns {string} UUID v4 (e.g., 'c0de1234-5678-9abc-def0-123456789abc')\n */\nexport function uuid(): string {\n return randomUUID();\n}\n\n/**\n * Generates a ULID (Universally Unique Lexicographically Sortable Identifier).\n *\n * @returns {string} ULID string (26 chars, Crockford Base32, e.g., '01H7ZXS9FJKPX06P1AYZKCGHQF').\n */\nexport function ulidString(): string {\n return ulid();\n}\n\n/**\n * Generates a nanoid string (URL-friendly, collision-resistant, customizable size).\n *\n * @param {number} [size=21] - Number of characters for the ID (default: 21).\n * @returns {string} nanoid string.\n */\nexport function nanoId(size: number = 21): string {\n return nanoid(size);\n}\n\n/**\n * Generates a cryptographically strong random hex string.\n *\n * @param {number} byteLength - Number of random bytes (default: 16 → 32 hex chars).\n * @returns {string} Random hex string.\n */\nexport function randomHex(byteLength: number = 16): string {\n // Node: crypto.getRandomValues is not available; use randomBytes if needed.\n // If using browser target, replace this impl accordingly.\n return Buffer.from(crypto.getRandomValues(new Uint8Array(byteLength)))\n .toString(\"hex\")\n .slice(0, byteLength * 2);\n}\n\n/**\n * Generates a random integer between min (inclusive) and max (inclusive).\n *\n * @param {number} min - Minimum value.\n * @param {number} max - Maximum value.\n * @returns {number} Random integer in range.\n */\nexport function randomInt(min: number, max: number): number {\n const range = max - min + 1;\n return Math.floor(Math.random() * range) + min;\n}\n"]}
1
+ {"version":3,"file":"id.utils.js","sourceRoot":"","sources":["../../../src/utils/id.utils.ts"],"names":[],"mappings":";;AAOA,oBAEC;AAQD,wBASC;AAQD,8BAOC;AASD,8BAGC;AAQD,oCAEC;AA/DD,mCAAiD;AAEjD;;;;GAIG;AACH,SAAgB,IAAI;IAClB,OAAO,IAAA,mBAAU,GAAE,CAAC;AACtB,CAAC;AAED;;;;;GAKG;AACH,SAAgB,MAAM,CAAC,SAAiB,EAAE;IACxC,IAAI,MAAM,IAAI,CAAC;QAAE,OAAO,EAAE,CAAC;IAC3B,IAAI,EAAE,GAAG,EAAE,CAAC;IACZ,OAAO,EAAE,CAAC,MAAM,GAAG,MAAM,EAAE,CAAC;QAC1B,EAAE,IAAI,IAAA,oBAAW,EAAC,IAAI,CAAC,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;aAC3C,QAAQ,CAAC,WAAW,CAAC;aACrB,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;IAC3B,CAAC;IACD,OAAO,EAAE,CAAC,KAAK,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;AAC7B,CAAC;AAED;;;;;GAKG;AACH,SAAgB,SAAS,CAAC,aAAqB,EAAE;IAC/C,6DAA6D;IAC7D,kGAAkG;IAClG,OAAO,IAAA,oBAAW,EAAC,UAAU,CAAC;SAC3B,QAAQ,CAAC,KAAK,CAAC;SACf,QAAQ,CAAC,UAAU,GAAG,CAAC,EAAE,GAAG,CAAC;SAC7B,KAAK,CAAC,CAAC,EAAE,UAAU,GAAG,CAAC,CAAC,CAAC;AAC9B,CAAC;AAED;;;;;;GAMG;AACH,SAAgB,SAAS,CAAC,GAAW,EAAE,GAAW;IAChD,MAAM,KAAK,GAAG,GAAG,GAAG,GAAG,GAAG,CAAC,CAAC;IAC5B,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,KAAK,CAAC,GAAG,GAAG,CAAC;AACjD,CAAC;AAED;;;;;GAKG;AACH,SAAgB,YAAY,CAAC,aAAqB,EAAE;IAClD,OAAO,IAAA,oBAAW,EAAC,UAAU,CAAC,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC;AACvD,CAAC","sourcesContent":["import { randomUUID, randomBytes } from 'crypto';\n\n/**\n * Generates a UUID v4 string (RFC 4122).\n *\n * @returns {string} UUID v4 (e.g., 'c0de1234-5678-9abc-def0-123456789abc')\n */\nexport function uuid(): string {\n return randomUUID();\n}\n\n/**\n * Generates a nanoid-style random ID (URL-safe, customizable length).\n *\n * @param {number} length - Length of the ID (default: 21).\n * @returns {string} Nanoid-style random string.\n */\nexport function nanoId(length: number = 21): string {\n if (length <= 0) return '';\n let id = '';\n while (id.length < length) {\n id += randomBytes(Math.ceil((length * 3) / 4))\n .toString('base64url')\n .replace(/[+/=]/g, '');\n }\n return id.slice(0, length);\n}\n\n/**\n * Generates a cryptographically strong random hex string.\n *\n * @param {number} byteLength - Number of random bytes (default: 16 → 32 hex chars).\n * @returns {string} Random hex string.\n */\nexport function randomHex(byteLength: number = 16): string {\n // Use Node.js crypto for both Node and browser compatibility\n // Prefer randomBytes if available (Node), fallback to getRandomValues for browser (not used here)\n return randomBytes(byteLength)\n .toString('hex')\n .padStart(byteLength * 2, '0')\n .slice(0, byteLength * 2);\n}\n\n/**\n * Generates a random integer between min (inclusive) and max (inclusive).\n *\n * @param {number} min - Minimum value.\n * @param {number} max - Maximum value.\n * @returns {number} Random integer in range.\n */\nexport function randomInt(min: number, max: number): number {\n const range = max - min + 1;\n return Math.floor(Math.random() * range) + min;\n}\n\n/**\n * Generates a cryptographically strong random base64 string.\n *\n * @param {number} byteLength - Number of random bytes (default: 16).\n * @returns {string} Random base64 string (URL-safe, no padding).\n */\nexport function randomBase64(byteLength: number = 16): string {\n return randomBytes(byteLength).toString('base64url');\n}\n"]}
@@ -1,4 +1,13 @@
1
- import type { Logger } from "pino";
1
+ import pino from 'pino';
2
+ import type { Logger as PinoLogger } from 'pino';
3
+ /**
4
+ * Logger type for application-wide logging.
5
+ */
6
+ export type Logger = pino.Logger;
7
+ /**
8
+ * Logger levels for application-wide logging.
9
+ */
10
+ export type LoggerLevels = pino.Level;
2
11
  /**
3
12
  * Use an object compatible with either modern or legacy global scopes.
4
13
  */
@@ -11,5 +20,29 @@ export declare const _globalThis: typeof globalThis;
11
20
  *
12
21
  * @returns {Logger} The logger instance (request-bound or global root logger)
13
22
  */
14
- export declare function getLogger(): Logger;
23
+ export declare function getLogger(): PinoLogger;
24
+ /**
25
+ * Creates a child logger with additional context.
26
+ *
27
+ * @param {Record<string, any>} bindings - Properties to attach to all log records
28
+ * @param {Logger} [parentLogger] - Parent logger (defaults to current context logger or global)
29
+ * @returns {Logger} Child logger with merged context
30
+ */
31
+ export declare function createChildLogger(bindings: Record<string, any>, parentLogger?: PinoLogger): PinoLogger;
32
+ /**
33
+ * Creates a request-scoped logger with request ID and stores it in context
34
+ *
35
+ * @param {string} requestId - Unique request identifier
36
+ * @param {object} [additionalContext] - Additional context to include in logs
37
+ * @returns {Logger} Request-scoped logger instance
38
+ */
39
+ export declare function createRequestLogger(requestId: string, additionalContext?: Record<string, any>): PinoLogger;
40
+ /**
41
+ * Utility to safely log errors with proper stack trace extraction
42
+ *
43
+ * @param {Error|unknown} error - Error object to log
44
+ * @param {string} [message] - Optional message to include
45
+ * @param {Record<string, any>} [context] - Additional context properties
46
+ */
47
+ export declare function logError(error: Error | unknown, message?: string, context?: Record<string, any>): void;
15
48
  //# sourceMappingURL=logger.utils.d.ts.map
@@ -35,17 +35,20 @@ var __importStar = (this && this.__importStar) || (function () {
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports._globalThis = void 0;
37
37
  exports.getLogger = getLogger;
38
+ exports.createChildLogger = createChildLogger;
39
+ exports.createRequestLogger = createRequestLogger;
40
+ exports.logError = logError;
38
41
  const pino_1 = __importStar(require("pino"));
39
42
  const config_1 = require("../config");
40
43
  const context_store_utils_1 = require("./context-store.utils");
41
44
  /**
42
45
  * Symbol used to store the root logger in the Node.js global object.
43
46
  */
44
- const GLOBAL_LOGGER_KEY = Symbol.for("logger");
47
+ const GLOBAL_LOGGER_KEY = Symbol.for('logger');
45
48
  /**
46
49
  * Use an object compatible with either modern or legacy global scopes.
47
50
  */
48
- exports._globalThis = typeof globalThis === "object" ? globalThis : global;
51
+ exports._globalThis = typeof globalThis === 'object' ? globalThis : global;
49
52
  const _global = exports._globalThis;
50
53
  /**
51
54
  * Initializes the global root logger according to app configuration.
@@ -58,23 +61,23 @@ function setupLogger() {
58
61
  name: config_1.Config.Logger.name,
59
62
  level: config_1.Config.Logger.level,
60
63
  redact: {
61
- paths: ["req.authorization", "url"],
64
+ paths: ['req.authorization', 'url'],
62
65
  censor(value, path) {
63
- if (path[0] === "url") {
64
- return value.replace(/access_token=[a-zA-Z0-9_-]*/, "access_token=***");
66
+ if (path[0] === 'url') {
67
+ return value.replace(/access_token=[a-zA-Z0-9_-]*/, 'access_token=***');
65
68
  }
66
- else if (path[1] === "authorization") {
67
- return value.replace(/\s+(\S+)$/, " ***");
69
+ else if (path[1] === 'authorization') {
70
+ return value.replace(/\s+(\S+)$/, ' ***');
68
71
  }
69
- return "***";
70
- },
71
- },
72
+ return '***';
73
+ }
74
+ }
72
75
  };
73
76
  if (config_1.Config.Logger.isoTimestamp) {
74
77
  logParams.timestamp = pino_1.stdTimeFunctions.isoTime;
75
78
  }
76
79
  _global[GLOBAL_LOGGER_KEY] = (0, pino_1.default)(logParams);
77
- _global[GLOBAL_LOGGER_KEY].debug("Logger initialized");
80
+ _global[GLOBAL_LOGGER_KEY].debug('Logger initialized');
78
81
  }
79
82
  /**
80
83
  * Retrieves the current logger instance:
@@ -93,4 +96,46 @@ function getLogger() {
93
96
  }
94
97
  return _global[GLOBAL_LOGGER_KEY];
95
98
  }
99
+ /**
100
+ * Creates a child logger with additional context.
101
+ *
102
+ * @param {Record<string, any>} bindings - Properties to attach to all log records
103
+ * @param {Logger} [parentLogger] - Parent logger (defaults to current context logger or global)
104
+ * @returns {Logger} Child logger with merged context
105
+ */
106
+ function createChildLogger(bindings, parentLogger) {
107
+ const logger = parentLogger || getLogger();
108
+ return logger.child(bindings);
109
+ }
110
+ /**
111
+ * Creates a request-scoped logger with request ID and stores it in context
112
+ *
113
+ * @param {string} requestId - Unique request identifier
114
+ * @param {object} [additionalContext] - Additional context to include in logs
115
+ * @returns {Logger} Request-scoped logger instance
116
+ */
117
+ function createRequestLogger(requestId, additionalContext = {}) {
118
+ const logger = createChildLogger(Object.assign({ requestId }, additionalContext));
119
+ try {
120
+ context_store_utils_1.ContextStore.set(context_store_utils_1.StoreKeys.LOGGER, logger);
121
+ }
122
+ catch (_a) {
123
+ // Context not initialized, can't store logger
124
+ logger.debug('Failed to store logger in context - AsyncLocalStorage not initialized');
125
+ }
126
+ return logger;
127
+ }
128
+ /**
129
+ * Utility to safely log errors with proper stack trace extraction
130
+ *
131
+ * @param {Error|unknown} error - Error object to log
132
+ * @param {string} [message] - Optional message to include
133
+ * @param {Record<string, any>} [context] - Additional context properties
134
+ */
135
+ function logError(error, message, context) {
136
+ const logger = getLogger();
137
+ const errObj = error instanceof Error ? error : new Error(String(error));
138
+ const logContext = Object.assign(Object.assign({}, context), { err: errObj });
139
+ logger.error(logContext, message || errObj.message);
140
+ }
96
141
  //# sourceMappingURL=logger.utils.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"logger.utils.js","sourceRoot":"","sources":["../../../src/utils/logger.utils.ts"],"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AC;AAED;;;;;;;GAOG;AACH,SAAgB,SAAS;IACvB,MAAM,MAAM,GAAG,kCAAY,CAAC,GAAG,CAAS,+BAAS,CAAC,MAAM,CAAC,CAAC;IAC1D,IAAI,MAAM;QAAE,OAAO,MAAM,CAAC;IAE1B,IAAI,CAAC,OAAO,CAAC,iBAAiB,CAAC,EAAE,CAAC;QAChC,WAAW,EAAE,CAAC;IAChB,CAAC;IAED,OAAO,OAAO,CAAC,iBAAiB,CAAC,CAAC;AACpC,CAAC","sourcesContent":["import pino, { LoggerOptions, stdTimeFunctions } from \"pino\";\nimport type { Logger } from \"pino\"; // Type-only import\nimport { Config } from \"../config\";\nimport { ContextStore, StoreKeys } from \"./context-store.utils\";\n\n/**\n * Symbol used to store the root logger in the Node.js global object.\n */\nconst GLOBAL_LOGGER_KEY = Symbol.for(\"logger\");\n\n/**\n * Use an object compatible with either modern or legacy global scopes.\n */\nexport const _globalThis = typeof globalThis === \"object\" ? globalThis : global;\nconst _global = _globalThis as unknown as { [GLOBAL_LOGGER_KEY]: Logger };\n\n/**\n * Initializes the global root logger according to app configuration.\n *\n * - Sets log name, level, timestamp, and redaction for sensitive fields.\n * - Uses singleton in global symbol registry.\n */\nfunction setupLogger(): void {\n const logParams: LoggerOptions = {\n name: Config.Logger.name,\n level: Config.Logger.level,\n redact: {\n paths: [\"req.authorization\", \"url\"],\n censor(value, path) {\n if (path[0] === \"url\") {\n return value.replace(\n /access_token=[a-zA-Z0-9_-]*/,\n \"access_token=***\",\n );\n } else if (path[1] === \"authorization\") {\n return value.replace(/\\s+(\\S+)$/, \" ***\");\n }\n return \"***\";\n },\n },\n };\n\n if (Config.Logger.isoTimestamp) {\n logParams.timestamp = stdTimeFunctions.isoTime;\n }\n\n _global[GLOBAL_LOGGER_KEY] = pino(logParams);\n _global[GLOBAL_LOGGER_KEY].debug(\"Logger initialized\");\n}\n\n/**\n * Retrieves the current logger instance:\n * - Returns a request-scoped logger from AsyncLocalStorage if available\n * - Falls back to the global (singleton) logger\n * - Initializes the global logger if not created yet\n *\n * @returns {Logger} The logger instance (request-bound or global root logger)\n */\nexport function getLogger(): Logger {\n const logger = ContextStore.get<Logger>(StoreKeys.LOGGER);\n if (logger) return logger;\n\n if (!_global[GLOBAL_LOGGER_KEY]) {\n setupLogger();\n }\n\n return _global[GLOBAL_LOGGER_KEY];\n}\n"]}
1
+ {"version":3,"file":"logger.utils.js","sourceRoot":"","sources":["../../../src/utils/logger.utils.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiEA,8BASC;AASD,8CAGC;AASD,kDAcC;AASD,4BAUC;AAhID,6CAA6D;AAE7D,sCAAmC;AACnC,+DAAgE;AAEhE;;GAEG;AACH,MAAM,iBAAiB,GAAG,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;AAY/C;;GAEG;AACU,QAAA,WAAW,GAAG,OAAO,UAAU,KAAK,QAAQ,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,MAAM,CAAC;AAChF,MAAM,OAAO,GAAG,mBAA6D,CAAC;AAE9E;;;;;GAKG;AACH,SAAS,WAAW;IAClB,MAAM,SAAS,GAAkB;QAC/B,IAAI,EAAE,eAAM,CAAC,MAAM,CAAC,IAAI;QACxB,KAAK,EAAE,eAAM,CAAC,MAAM,CAAC,KAAK;QAC1B,MAAM,EAAE;YACN,KAAK,EAAE,CAAC,mBAAmB,EAAE,KAAK,CAAC;YACnC,MAAM,CAAC,KAAK,EAAE,IAAI;gBAChB,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,KAAK,EAAE,CAAC;oBACtB,OAAO,KAAK,CAAC,OAAO,CAAC,6BAA6B,EAAE,kBAAkB,CAAC,CAAC;gBAC1E,CAAC;qBAAM,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,eAAe,EAAE,CAAC;oBACvC,OAAO,KAAK,CAAC,OAAO,CAAC,WAAW,EAAE,MAAM,CAAC,CAAC;gBAC5C,CAAC;gBACD,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Q,CAAC,KAAsB,EAAE,OAAgB,EAAE,OAA6B;IAC9F,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;IAE3B,MAAM,MAAM,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IACzE,MAAM,UAAU,mCACX,OAAO,KACV,GAAG,EAAE,MAAM,GACZ,CAAC;IAEF,MAAM,CAAC,KAAK,CAAC,UAAU,EAAE,OAAO,IAAI,MAAM,CAAC,OAAO,CAAC,CAAC;AACtD,CAAC","sourcesContent":["import pino, { LoggerOptions, stdTimeFunctions } from 'pino';\nimport type { Logger as PinoLogger } from 'pino'; // Type-only import\nimport { Config } from '../config';\nimport { ContextStore, StoreKeys } from './context-store.utils';\n\n/**\n * Symbol used to store the root logger in the Node.js global object.\n */\nconst GLOBAL_LOGGER_KEY = Symbol.for('logger');\n\n/**\n * Logger type for application-wide logging.\n */\nexport type Logger = pino.Logger;\n\n/**\n * Logger levels for application-wide logging.\n */\nexport type LoggerLevels = pino.Level;\n\n/**\n * Use an object compatible with either modern or legacy global scopes.\n */\nexport const _globalThis = typeof globalThis === 'object' ? globalThis : global;\nconst _global = _globalThis as unknown as { [GLOBAL_LOGGER_KEY]: PinoLogger };\n\n/**\n * Initializes the global root logger according to app configuration.\n *\n * - Sets log name, level, timestamp, and redaction for sensitive fields.\n * - Uses singleton in global symbol registry.\n */\nfunction setupLogger(): void {\n const logParams: LoggerOptions = {\n name: Config.Logger.name,\n level: Config.Logger.level,\n redact: {\n paths: ['req.authorization', 'url'],\n censor(value, path) {\n if (path[0] === 'url') {\n return value.replace(/access_token=[a-zA-Z0-9_-]*/, 'access_token=***');\n } else if (path[1] === 'authorization') {\n return value.replace(/\\s+(\\S+)$/, ' ***');\n }\n return '***';\n }\n }\n };\n\n if (Config.Logger.isoTimestamp) {\n logParams.timestamp = stdTimeFunctions.isoTime;\n }\n\n _global[GLOBAL_LOGGER_KEY] = pino(logParams);\n _global[GLOBAL_LOGGER_KEY].debug('Logger initialized');\n}\n\n/**\n * Retrieves the current logger instance:\n * - Returns a request-scoped logger from AsyncLocalStorage if available\n * - Falls back to the global (singleton) logger\n * - Initializes the global logger if not created yet\n *\n * @returns {Logger} The logger instance (request-bound or global root logger)\n */\nexport function getLogger(): PinoLogger {\n const logger = ContextStore.get<PinoLogger>(StoreKeys.LOGGER);\n if (logger) return logger;\n\n if (!_global[GLOBAL_LOGGER_KEY]) {\n setupLogger();\n }\n\n return _global[GLOBAL_LOGGER_KEY];\n}\n\n/**\n * Creates a child logger with additional context.\n *\n * @param {Record<string, any>} bindings - Properties to attach to all log records\n * @param {Logger} [parentLogger] - Parent logger (defaults to current context logger or global)\n * @returns {Logger} Child logger with merged context\n */\nexport function createChildLogger(bindings: Record<string, any>, parentLogger?: PinoLogger): PinoLogger {\n const logger = parentLogger || getLogger();\n return logger.child(bindings);\n}\n\n/**\n * Creates a request-scoped logger with request ID and stores it in context\n *\n * @param {string} requestId - Unique request identifier\n * @param {object} [additionalContext] - Additional context to include in logs\n * @returns {Logger} Request-scoped logger instance\n */\nexport function createRequestLogger(requestId: string, additionalContext: Record<string, any> = {}): PinoLogger {\n const logger = createChildLogger({\n requestId,\n ...additionalContext\n });\n\n try {\n ContextStore.set(StoreKeys.LOGGER, logger);\n } catch {\n // Context not initialized, can't store logger\n logger.debug('Failed to store logger in context - AsyncLocalStorage not initialized');\n }\n\n return logger;\n}\n\n/**\n * Utility to safely log errors with proper stack trace extraction\n *\n * @param {Error|unknown} error - Error object to log\n * @param {string} [message] - Optional message to include\n * @param {Record<string, any>} [context] - Additional context properties\n */\nexport function logError(error: Error | unknown, message?: string, context?: Record<string, any>): void {\n const logger = getLogger();\n\n const errObj = error instanceof Error ? error : new Error(String(error));\n const logContext = {\n ...context,\n err: errObj\n };\n\n logger.error(logContext, message || errObj.message);\n}\n"]}
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Type definitions for Express-compatible middleware
3
+ */
4
+ type Request = {
5
+ headers: Record<string, string | string[] | undefined>;
6
+ method: string;
7
+ url: string;
8
+ ip?: string;
9
+ body?: any;
10
+ query?: Record<string, any>;
11
+ params?: Record<string, any>;
12
+ [key: string]: any;
13
+ };
14
+ type Response = {
15
+ status: (code: number) => Response;
16
+ json: (data: any) => void;
17
+ send: (data: any) => void;
18
+ setHeader: (name: string, value: string | string[]) => void;
19
+ end: (data?: any) => void;
20
+ on: (event: string, callback: (...args: any[]) => void) => void;
21
+ [key: string]: any;
22
+ };
23
+ type NextFunction = (err?: Error | any) => void;
24
+ type Middleware = (req: Request, res: Response, next: NextFunction) => void | Promise<void>;
25
+ /**
26
+ * Attaches a unique request ID to each request.
27
+ * Useful for request tracing and correlation between logs.
28
+ *
29
+ * @param {object} [options] - Configuration options
30
+ * @param {string} [options.headerName='X-Request-ID'] - Header name for request ID
31
+ * @param {boolean} [options.exposeHeader=true] - Whether to expose the header in response
32
+ * @returns {Middleware} Express-compatible middleware
33
+ */
34
+ export declare function requestId(options?: {
35
+ headerName?: string;
36
+ exposeHeader?: boolean;
37
+ }): Middleware;
38
+ /**
39
+ * Measures request processing time and logs or adds it to response headers.
40
+ *
41
+ * @param {object} [options] - Configuration options
42
+ * @param {boolean} [options.addHeader=true] - Whether to add X-Response-Time header
43
+ * @param {boolean} [options.logOnComplete=false] - Whether to log timing info
44
+ * @returns {Middleware} Express-compatible middleware
45
+ */
46
+ export declare function responseTime(options?: {
47
+ addHeader?: boolean;
48
+ logOnComplete?: boolean;
49
+ }): Middleware;
50
+ /**
51
+ * Request timeout middleware.
52
+ * Aborts requests that take too long to process.
53
+ *
54
+ * @param {number} [timeoutMs=30000] - Timeout in milliseconds
55
+ * @returns {Middleware} Express-compatible middleware
56
+ */
57
+ export declare function timeout(timeoutMs?: number): Middleware;
58
+ /**
59
+ * Global error handling middleware with enhanced features.
60
+ *
61
+ * @param {object} [options] - Error handler options
62
+ * @param {boolean} [options.logErrors=true] - Whether to log errors
63
+ * @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production
64
+ * @param {Function} [options.logger=getLogger().error] - Custom logging function
65
+ * @returns {(err: any, req: Request, res: Response, next: NextFunction) => void} Error middleware
66
+ */
67
+ export declare function errorHandler(options?: {
68
+ logErrors?: boolean;
69
+ includeDetails?: boolean;
70
+ logger?: (message: string, error: any) => void;
71
+ }): (err: any, req: Request, res: Response, _next: NextFunction) => void;
72
+ export {};
73
+ //# sourceMappingURL=middleware.utils.d.ts.map
@@ -0,0 +1,163 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.requestId = requestId;
4
+ exports.responseTime = responseTime;
5
+ exports.timeout = timeout;
6
+ exports.errorHandler = errorHandler;
7
+ const crypto_1 = require("crypto");
8
+ const config_1 = require("../config");
9
+ const id_utils_1 = require("./id.utils");
10
+ const http_status_codes_1 = require("./http-status-codes");
11
+ const response_utils_1 = require("./response.utils");
12
+ const env_utils_1 = require("./env.utils");
13
+ const logger_utils_1 = require("./logger.utils");
14
+ /**
15
+ * Attaches a unique request ID to each request.
16
+ * Useful for request tracing and correlation between logs.
17
+ *
18
+ * @param {object} [options] - Configuration options
19
+ * @param {string} [options.headerName='X-Request-ID'] - Header name for request ID
20
+ * @param {boolean} [options.exposeHeader=true] - Whether to expose the header in response
21
+ * @returns {Middleware} Express-compatible middleware
22
+ */
23
+ function requestId(options) {
24
+ const headerName = (options === null || options === void 0 ? void 0 : options.headerName) || 'X-Request-ID';
25
+ const exposeHeader = (options === null || options === void 0 ? void 0 : options.exposeHeader) !== false;
26
+ return (req, res, next) => {
27
+ // Use existing request ID from header or generate a new one
28
+ const existingId = req.headers[headerName.toLowerCase()];
29
+ const id = existingId || (0, crypto_1.randomUUID)();
30
+ // Attach ID to request object
31
+ req.id = id;
32
+ // Add ID to response headers
33
+ if (exposeHeader) {
34
+ res.setHeader(headerName, id);
35
+ }
36
+ next();
37
+ };
38
+ }
39
+ /**
40
+ * Measures request processing time and logs or adds it to response headers.
41
+ *
42
+ * @param {object} [options] - Configuration options
43
+ * @param {boolean} [options.addHeader=true] - Whether to add X-Response-Time header
44
+ * @param {boolean} [options.logOnComplete=false] - Whether to log timing info
45
+ * @returns {Middleware} Express-compatible middleware
46
+ */
47
+ function responseTime(options) {
48
+ const addHeader = (options === null || options === void 0 ? void 0 : options.addHeader) !== false;
49
+ const logOnComplete = (options === null || options === void 0 ? void 0 : options.logOnComplete) === true;
50
+ return (req, res, next) => {
51
+ const start = process.hrtime();
52
+ // Function to calculate elapsed time
53
+ const calculateDuration = () => {
54
+ const diff = process.hrtime(start);
55
+ return diff[0] * 1e3 + diff[1] * 1e-6; // Convert to ms
56
+ };
57
+ // Handle response completion
58
+ res.on('finish', () => {
59
+ const duration = calculateDuration();
60
+ if (addHeader) {
61
+ res.setHeader('X-Response-Time', `${duration.toFixed(2)}ms`);
62
+ }
63
+ if (logOnComplete) {
64
+ const { method, url } = req;
65
+ (0, logger_utils_1.getLogger)().info(`${method} ${url} - ${duration.toFixed(2)}ms`);
66
+ }
67
+ });
68
+ next();
69
+ };
70
+ }
71
+ /**
72
+ * Request timeout middleware.
73
+ * Aborts requests that take too long to process.
74
+ *
75
+ * @param {number} [timeoutMs=30000] - Timeout in milliseconds
76
+ * @returns {Middleware} Express-compatible middleware
77
+ */
78
+ function timeout(timeoutMs = config_1.Config.Http.timeout) {
79
+ return (req, res, next) => {
80
+ // Set timeout for the request
81
+ const timer = setTimeout(() => {
82
+ res.status(408).json({
83
+ error: true,
84
+ message: 'Request timeout',
85
+ status: 408,
86
+ timestamp: new Date().toISOString()
87
+ });
88
+ }, timeoutMs);
89
+ // Clear timeout when response is sent
90
+ res.on('finish', () => {
91
+ clearTimeout(timer);
92
+ });
93
+ next();
94
+ };
95
+ }
96
+ /**
97
+ * Creates a standardized error response object for API errors.
98
+ *
99
+ * @param {string} message - Error message
100
+ * @param {Request} req - Express request object
101
+ * @param {any} error - Original error object
102
+ * @param {object} [options] - Additional options
103
+ * @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production
104
+ * @returns {object} Formatted error response
105
+ */
106
+ const createErrorResponse = (message, req, error, options) => {
107
+ const isDev = env_utils_1.Env.isDev();
108
+ const includeDetails = (options === null || options === void 0 ? void 0 : options.includeDetails) && isDev;
109
+ const response = {
110
+ error: true,
111
+ message,
112
+ timestamp: new Date().toISOString(),
113
+ requestId: (error === null || error === void 0 ? void 0 : error.requestId) || req.id || (0, id_utils_1.uuid)(),
114
+ path: req.originalUrl || req.url
115
+ };
116
+ // Include error code if present
117
+ if (error === null || error === void 0 ? void 0 : error.code) {
118
+ response.code = error.code;
119
+ }
120
+ // Include stack trace in development mode if requested
121
+ if (includeDetails && (error === null || error === void 0 ? void 0 : error.stack)) {
122
+ response.stack = error.stack.split('\n').map((line) => line.trim());
123
+ }
124
+ return response;
125
+ };
126
+ /**
127
+ * Global error handling middleware with enhanced features.
128
+ *
129
+ * @param {object} [options] - Error handler options
130
+ * @param {boolean} [options.logErrors=true] - Whether to log errors
131
+ * @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production
132
+ * @param {Function} [options.logger=getLogger().error] - Custom logging function
133
+ * @returns {(err: any, req: Request, res: Response, next: NextFunction) => void} Error middleware
134
+ */
135
+ function errorHandler(options) {
136
+ const logErrors = (options === null || options === void 0 ? void 0 : options.logErrors) !== false;
137
+ const includeDetails = (options === null || options === void 0 ? void 0 : options.includeDetails) === true;
138
+ const logger = (options === null || options === void 0 ? void 0 : options.logger) || (0, logger_utils_1.getLogger)().error;
139
+ return (err, req, res, _next) => {
140
+ // Determine status code
141
+ const status = (err === null || err === void 0 ? void 0 : err.status) || (err === null || err === void 0 ? void 0 : err.statusCode) || http_status_codes_1.HttpStatusCodes.INTERNAL_SERVER_ERROR;
142
+ // Log error if enabled
143
+ if (logErrors) {
144
+ const logMessage = `[ERROR] ${req.method} ${req.originalUrl || req.url}: ${err.message || 'Unknown error'}`;
145
+ logger(logMessage, err);
146
+ }
147
+ // Handle ErrorResponse instances (our custom error class)
148
+ if (err instanceof response_utils_1.ErrorResponse) {
149
+ return res.status(status).json({
150
+ error: err.error,
151
+ message: err.message,
152
+ timestamp: err.timestamp,
153
+ requestId: err.requestId || req.id || (0, id_utils_1.uuid)(),
154
+ path: req.originalUrl || req.url
155
+ });
156
+ }
157
+ // Handle any other errors
158
+ return res.status(status).json(createErrorResponse((err === null || err === void 0 ? void 0 : err.message) || 'Internal Server Error', req, err, {
159
+ includeDetails
160
+ }));
161
+ };
162
+ }
163
+ //# sourceMappingURL=middleware.utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"middleware.utils.js","sourceRoot":"","sources":["../../../src/utils/middleware.utils.ts"],"names":[],"mappings":";;AA6CA,8BAmBC;AAUD,oCA6BC;AASD,0BAmBC;AA8CD,oCAqCC;AAtND,mCAAoC;AACpC,sCAAmC;AACnC,yCAAkC;AAClC,2DAAsD;AACtD,qDAAiD;AACjD,2CAAkC;AAClC,iDAA2C;AA8B3C;;;;;;;;GAQG;AACH,SAAgB,SAAS,CAAC,OAAyD;IACjF,MAAM,UAAU,GAAG,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,UAAU,KAAI,cAAc,CAAC;IACzD,MAAM,YAAY,GAAG,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,YAAY,MAAK,KAAK,CAAC;IAErD,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QACxB,4DAA4D;QAC5D,MAAM,UAAU,GAAG,GAAG,CAAC,OAAO,CAAC,UAAU,CAAC,WAAW,EAAE,CAAC,CAAC;QACzD,MAAM,EAAE,GAAI,UAAqB,IAAI,IAAA,mBAAU,GAAE,CAAC;QAElD,8BAA8B;QAC9B,GAAG,CAAC,EAAE,GAAG,EAAE,CAAC;QAEZ,6BAA6B;QAC7B,IAAI,YAAY,EAAE,CAAC;YACjB,GAAG,CAAC,SAAS,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC;QACh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CAAC,UAAU,EAAE,GAAG,CAAC,CAAC;QAC1B,CAAC;QAED,0DAA0D;QAC1D,IAAI,GAAG,YAAY,8BAAa,EAAE,CAAC;YACjC,OAAO,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC;gBAC7B,KAAK,EAAE,GAAG,CAAC,KAAK;gBAChB,OAAO,EAAE,GAAG,CAAC,OAAO;gBACpB,SAAS,EAAE,GAAG,CAAC,SAAS;gBACxB,SAAS,EAAE,GAAG,CAAC,SAAS,IAAI,GAAG,CAAC,EAAE,IAAI,IAAA,eAAI,GAAE;gBAC5C,IAAI,EAAE,GAAG,CAAC,WAAW,IAAI,GAAG,CAAC,GAAG;aACjC,CAAC,CAAC;QACL,CAAC;QAED,0BAA0B;QAC1B,OAAO,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAC5B,mBAAmB,CAAC,CAAA,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,OAAO,KAAI,uBAAuB,EAAE,GAAG,EAAE,GAAG,EAAE;YACrE,cAAc;SACf,CAAC,CACH,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { randomUUID } from 'crypto';\nimport { Config } from '../config';\nimport { uuid } from './id.utils';\nimport { HttpStatusCodes } from './http-status-codes';\nimport { ErrorResponse } from './response.utils';\nimport { Env } from './env.utils';\nimport { getLogger } from './logger.utils';\n\n/**\n * Type definitions for Express-compatible middleware\n */\ntype Request = {\n headers: Record<string, string | string[] | undefined>;\n method: string;\n url: string;\n ip?: string;\n body?: any;\n query?: Record<string, any>;\n params?: Record<string, any>;\n [key: string]: any;\n};\n\ntype Response = {\n status: (code: number) => Response;\n json: (data: any) => void;\n send: (data: any) => void;\n setHeader: (name: string, value: string | string[]) => void;\n end: (data?: any) => void;\n on: (event: string, callback: (...args: any[]) => void) => void;\n [key: string]: any;\n};\n\ntype NextFunction = (err?: Error | any) => void;\n\ntype Middleware = (req: Request, res: Response, next: NextFunction) => void | Promise<void>;\n\n/**\n * Attaches a unique request ID to each request.\n * Useful for request tracing and correlation between logs.\n *\n * @param {object} [options] - Configuration options\n * @param {string} [options.headerName='X-Request-ID'] - Header name for request ID\n * @param {boolean} [options.exposeHeader=true] - Whether to expose the header in response\n * @returns {Middleware} Express-compatible middleware\n */\nexport function requestId(options?: { headerName?: string; exposeHeader?: boolean }): Middleware {\n const headerName = options?.headerName || 'X-Request-ID';\n const exposeHeader = options?.exposeHeader !== false;\n\n return (req, res, next) => {\n // Use existing request ID from header or generate a new one\n const existingId = req.headers[headerName.toLowerCase()];\n const id = (existingId as string) || randomUUID();\n\n // Attach ID to request object\n req.id = id;\n\n // Add ID to response headers\n if (exposeHeader) {\n res.setHeader(headerName, id);\n }\n\n next();\n };\n}\n\n/**\n * Measures request processing time and logs or adds it to response headers.\n *\n * @param {object} [options] - Configuration options\n * @param {boolean} [options.addHeader=true] - Whether to add X-Response-Time header\n * @param {boolean} [options.logOnComplete=false] - Whether to log timing info\n * @returns {Middleware} Express-compatible middleware\n */\nexport function responseTime(options?: { addHeader?: boolean; logOnComplete?: boolean }): Middleware {\n const addHeader = options?.addHeader !== false;\n const logOnComplete = options?.logOnComplete === true;\n\n return (req, res, next) => {\n const start = process.hrtime();\n\n // Function to calculate elapsed time\n const calculateDuration = (): number => {\n const diff = process.hrtime(start);\n return diff[0] * 1e3 + diff[1] * 1e-6; // Convert to ms\n };\n\n // Handle response completion\n res.on('finish', () => {\n const duration = calculateDuration();\n\n if (addHeader) {\n res.setHeader('X-Response-Time', `${duration.toFixed(2)}ms`);\n }\n\n if (logOnComplete) {\n const { method, url } = req;\n getLogger().info(`${method} ${url} - ${duration.toFixed(2)}ms`);\n }\n });\n\n next();\n };\n}\n\n/**\n * Request timeout middleware.\n * Aborts requests that take too long to process.\n *\n * @param {number} [timeoutMs=30000] - Timeout in milliseconds\n * @returns {Middleware} Express-compatible middleware\n */\nexport function timeout(timeoutMs: number = Config.Http.timeout): Middleware {\n return (req, res, next) => {\n // Set timeout for the request\n const timer = setTimeout(() => {\n res.status(408).json({\n error: true,\n message: 'Request timeout',\n status: 408,\n timestamp: new Date().toISOString()\n });\n }, timeoutMs);\n\n // Clear timeout when response is sent\n res.on('finish', () => {\n clearTimeout(timer);\n });\n\n next();\n };\n}\n\n/**\n * Creates a standardized error response object for API errors.\n *\n * @param {string} message - Error message\n * @param {Request} req - Express request object\n * @param {any} error - Original error object\n * @param {object} [options] - Additional options\n * @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production\n * @returns {object} Formatted error response\n */\nconst createErrorResponse = (message: string, req: Request, error: any, options?: { includeDetails?: boolean }) => {\n const isDev = Env.isDev();\n const includeDetails = options?.includeDetails && isDev;\n\n const response: Record<string, any> = {\n error: true,\n message,\n timestamp: new Date().toISOString(),\n requestId: error?.requestId || req.id || uuid(),\n path: req.originalUrl || req.url\n };\n\n // Include error code if present\n if (error?.code) {\n response.code = error.code;\n }\n\n // Include stack trace in development mode if requested\n if (includeDetails && error?.stack) {\n response.stack = error.stack.split('\\n').map((line: string) => line.trim());\n }\n\n return response;\n};\n\n/**\n * Global error handling middleware with enhanced features.\n *\n * @param {object} [options] - Error handler options\n * @param {boolean} [options.logErrors=true] - Whether to log errors\n * @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production\n * @param {Function} [options.logger=getLogger().error] - Custom logging function\n * @returns {(err: any, req: Request, res: Response, next: NextFunction) => void} Error middleware\n */\nexport function errorHandler(options?: {\n logErrors?: boolean;\n includeDetails?: boolean;\n logger?: (message: string, error: any) => void;\n}) {\n const logErrors = options?.logErrors !== false;\n const includeDetails = options?.includeDetails === true;\n const logger = options?.logger || getLogger().error;\n\n return (err: any, req: Request, res: Response, _next: NextFunction) => {\n // Determine status code\n const status = err?.status || err?.statusCode || HttpStatusCodes.INTERNAL_SERVER_ERROR;\n\n // Log error if enabled\n if (logErrors) {\n const logMessage = `[ERROR] ${req.method} ${req.originalUrl || req.url}: ${err.message || 'Unknown error'}`;\n logger(logMessage, err);\n }\n\n // Handle ErrorResponse instances (our custom error class)\n if (err instanceof ErrorResponse) {\n return res.status(status).json({\n error: err.error,\n message: err.message,\n timestamp: err.timestamp,\n requestId: err.requestId || req.id || uuid(),\n path: req.originalUrl || req.url\n });\n }\n\n // Handle any other errors\n return res.status(status).json(\n createErrorResponse(err?.message || 'Internal Server Error', req, err, {\n includeDetails\n })\n );\n };\n}\n"]}
@@ -4,7 +4,7 @@
4
4
  * @param {Record<any, any>} obj - The object to check.
5
5
  * @returns {boolean} True if the object is empty, false otherwise.
6
6
  */
7
- export declare const isObjEmpty: (obj: Record<any, any>) => boolean;
7
+ export declare function isObjEmpty(obj: Record<any, any>): boolean;
8
8
  /**
9
9
  * Returns a new object with only the specified keys picked.
10
10
  *
@@ -14,7 +14,7 @@ export declare const isObjEmpty: (obj: Record<any, any>) => boolean;
14
14
  * @param {K[]} keys - Keys to pick from the object.
15
15
  * @returns {Pick<T, K>} New object with picked keys.
16
16
  */
17
- export declare const pick: <T extends object, K extends keyof T>(obj: T, keys: K[]) => Pick<T, K>;
17
+ export declare function pick<T extends object, K extends keyof T>(obj: T, keys: K[]): Pick<T, K>;
18
18
  /**
19
19
  * Returns a new object with the specified keys omitted.
20
20
  *
@@ -24,7 +24,7 @@ export declare const pick: <T extends object, K extends keyof T>(obj: T, keys: K
24
24
  * @param {K[]} keys - Keys to omit from the object.
25
25
  * @returns {Omit<T, K>} New object without omitted keys.
26
26
  */
27
- export declare const omit: <T extends object, K extends keyof T>(obj: T, keys: K[]) => Omit<T, K>;
27
+ export declare function omit<T extends object, K extends keyof T>(obj: T, keys: K[]): Omit<T, K>;
28
28
  /**
29
29
  * Deeply merges two objects (mutates and returns the target object, not pure).
30
30
  *
@@ -52,4 +52,66 @@ export declare function flattenObject<T extends Record<string, any>>(obj: T, pre
52
52
  * @returns {any} The value at the given path, or undefined if not found.
53
53
  */
54
54
  export declare function getValueByPath<T extends object>(obj: T, path: string): any;
55
+ /**
56
+ * Sets a value at a deeply nested key in an object using dot/bracket notation path.
57
+ * Creates intermediate objects and arrays as needed.
58
+ *
59
+ * @template T
60
+ * @param {T} obj - The object to modify.
61
+ * @param {string} path - String path using dot and/or bracket notation (e.g., 'user.friends[0].name').
62
+ * @param {any} value - The value to set at the path.
63
+ * @returns {T} The modified object.
64
+ */
65
+ export declare function setValueByPath<T extends object>(obj: T, path: string, value: any): T;
66
+ /**
67
+ * Performs a deep equality check between two objects.
68
+ *
69
+ * @param {any} a - First value to compare.
70
+ * @param {any} b - Second value to compare.
71
+ * @returns {boolean} True if values are deeply equal.
72
+ */
73
+ export declare function isEqual(a: any, b: any): boolean;
74
+ /**
75
+ * Filters object properties based on a predicate function.
76
+ *
77
+ * @template T
78
+ * @param {T} obj - The source object.
79
+ * @param {(value: any, key: string, obj: T) => boolean} predicate - Filter function.
80
+ * @returns {Partial<T>} New object with filtered properties.
81
+ */
82
+ export declare function filterObject<T extends object>(obj: T, predicate: (value: any, key: string, obj: T) => boolean): Partial<T>;
83
+ /**
84
+ * Maps object values to new values using a mapping function.
85
+ *
86
+ * @template T
87
+ * @template U
88
+ * @param {T} obj - The source object.
89
+ * @param {(value: any, key: string, obj: T) => U} mapFn - Mapping function.
90
+ * @returns {Record<keyof T, U>} New object with mapped values.
91
+ */
92
+ export declare function mapObject<T extends object, U>(obj: T, mapFn: (value: any, key: string, obj: T) => U): Record<keyof T, U>;
93
+ /**
94
+ * Recursively freezes an object and all its properties.
95
+ * Makes an object immutable.
96
+ *
97
+ * @template T
98
+ * @param {T} obj - The object to freeze.
99
+ * @returns {Readonly<T>} The frozen object.
100
+ */
101
+ export declare function deepFreeze<T extends object>(obj: T): Readonly<T>;
102
+ /**
103
+ * Safely checks if a value is an object (not null, not array).
104
+ *
105
+ * @param {unknown} value - Value to check.
106
+ * @returns {boolean} True if value is a non-null, non-array object.
107
+ */
108
+ export declare function isObject(value: unknown): value is Record<string, any>;
109
+ /**
110
+ * Gets all paths in an object using dot notation.
111
+ *
112
+ * @param {Record<string, any>} obj - Object to analyze.
113
+ * @param {string} [parentPath=""] - Internal param for recursion.
114
+ * @returns {string[]} Array of all paths in dot notation.
115
+ */
116
+ export declare function getAllPaths(obj: Record<string, any>, parentPath?: string): string[];
55
117
  //# sourceMappingURL=obj.utils.d.ts.map