@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 +1 @@
1
- {"version":3,"file":"cache.utils.js","sourceRoot":"","sources":["../../../src/utils/cache.utils.ts"],"names":[],"mappings":";;;AAQA;;;;;;;;;;GAUG;AACH,MAAa,QAAQ;IAGnB;;OAEG;IACH,YAAoB,QAAgB,CAAC,GAAG,EAAE,GAAG,IAAI;QAA7B,UAAK,GAAL,KAAK,CAAwB;QALzC,UAAK,GAAG,IAAI,GAAG,EAAoB,CAAC;IAKQ,CAAC;IAErD;;;;;OAKG;IACH,GAAG,CAAC,GAAM,EAAE,KAAQ;QAClB,MAAM,SAAS,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC;QAC1C,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC;IAC5C,CAAC;IAED;;;;;;OAMG;IACH,UAAU,CAAC,GAAM,EAAE,KAAQ,EAAE,KAAa;QACxC,MAAM,SAAS,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC;QACrC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC;IAC5C,CAAC;IAED;;;;;OAKG;IACH,GAAG,CAAC,GAAM;QACR,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAClC,IAAI,CAAC,KAAK;YAAE,OAAO,SAAS,CAAC;Q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;gBAClC,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;YAC3B,CAAC;QACH,CAAC;IACH,CAAC;IAED;;;;OAIG;IACH,CAAC,IAAI;QACH,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,EAAE,CAAC;YAChD,IAAI,IAAI,CAAC,GAAG,EAAE,IAAI,KAAK,CAAC,SAAS,EAAE,CAAC;gBAClC,MAAM,GAAG,CAAC;YACZ,CAAC;QACH,CAAC;IACH,CAAC;IAED;;;;OAIG;IACH,CAAC,MAAM;QACL,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,EAAE,CAAC;YACxC,IAAI,IAAI,CAAC,GAAG,EAAE,IAAI,KAAK,CAAC,SAAS,EAAE,CAAC;gBAClC,MAAM,KAAK,CAAC,KAAK,CAAC;YACpB,CAAC;QACH,CAAC;IACH,CAAC;CACF;AA1ID,4BA0IC","sourcesContent":["/**\n * Represents a cached entry with a value and an expiration timestamp.\n */\ntype CacheEntry<T> = {\n value: T;\n expiresAt: number;\n};\n\n/**\n * An in-memory cache with time-to-live (TTL) support for each entry.\n *\n * @typeParam K - Type of the key.\n * @typeParam V - Type of the value.\n *\n * @example\n * const cache = new TTLCache<string, number>(1000);\n * cache.set(\"x\", 123);\n * const value = cache.get(\"x\"); // 123\n */\nexport class TTLCache<K, V> {\n private cache = new Map<K, CacheEntry<V>>();\n\n /**\n * @param ttlMs - Default time-to-live in milliseconds for cache entries.\n */\n constructor(private ttlMs: number = 5 * 60 * 1000) {}\n\n /**\n * Sets a key-value pair in the cache with the default TTL.\n *\n * @param key - The key to set.\n * @param value - The value to associate with the key.\n */\n set(key: K, value: V): void {\n const expiresAt = Date.now() + this.ttlMs;\n this.cache.set(key, { value, expiresAt });\n }\n\n /**\n * Sets a key-value pair in the cache with a custom TTL.\n *\n * @param key - The key to set.\n * @param value - The value to associate with the key.\n * @param ttlMs - Time-to-live in milliseconds.\n */\n setWithTTL(key: K, value: V, ttlMs: number): void {\n const expiresAt = Date.now() + ttlMs;\n this.cache.set(key, { value, expiresAt });\n }\n\n /**\n * Retrieves the value for a given key if it hasn't expired.\n *\n * @param key - The key to retrieve.\n * @returns The cached value, or undefined if not found or expired.\n */\n get(key: K): V | undefined {\n const entry = this.cache.get(key);\n if (!entry) return undefined;\n if (Date.now() > entry.expiresAt) {\n this.cache.delete(key);\n return undefined;\n }\n return entry.value;\n }\n\n /**\n * Checks if the key exists and hasn't expired.\n *\n * @param key - The key to check.\n * @returns `true` if key exists and is valid, otherwise `false`.\n */\n has(key: K): boolean {\n return this.get(key) !== undefined;\n }\n\n /**\n * Deletes a key from the cache.\n *\n * @param key - The key to delete.\n * @returns `true` if the key existed and was removed, `false` otherwise.\n */\n delete(key: K): boolean {\n return this.cache.delete(key);\n }\n\n /**\n * Clears all entries from the cache.\n */\n clear(): void {\n this.cache.clear();\n }\n\n /**\n * Returns the number of entries currently in the cache (includes expired entries until next access/cleanup).\n *\n * @returns Number of items in the cache (may include expired keys).\n */\n size(): number {\n return this.cache.size;\n }\n\n /**\n * Removes all expired entries from the cache.\n *\n * @returns Number of entries removed.\n */\n cleanup(): number {\n let removed = 0;\n const now = Date.now();\n for (const [key, entry] of this.cache.entries()) {\n if (now > entry.expiresAt) {\n this.cache.delete(key);\n removed++;\n }\n }\n return removed;\n }\n\n /**\n * Returns an iterator of all current valid [key, value] pairs.\n *\n * @returns IterableIterator<[K, V]>\n */\n *entries(): IterableIterator<[K, V]> {\n for (const [key, entry] of this.cache.entries()) {\n if (Date.now() <= entry.expiresAt) {\n yield [key, entry.value];\n }\n }\n }\n\n /**\n * Returns an iterator of all current valid keys.\n *\n * @returns IterableIterator<K>\n */\n *keys(): IterableIterator<K> {\n for (const [key, entry] of this.cache.entries()) {\n if (Date.now() <= entry.expiresAt) {\n yield key;\n }\n }\n }\n\n /**\n * Returns an iterator of all current valid values.\n *\n * @returns IterableIterator<V>\n */\n *values(): IterableIterator<V> {\n for (const entry of this.cache.values()) {\n if (Date.now() <= entry.expiresAt) {\n yield entry.value;\n }\n }\n }\n}\n"]}
1
+ {"version":3,"file":"cache.utils.js","sourceRoot":"","sources":["../../../src/utils/cache.utils.ts"],"names":[],"mappings":";;;AAAA,sCAAmC;AAuBnC;;;;;;;;;;GAUG;AACH,MAAa,QAAQ;IAMnB;;OAEG;IACH,YAAY,UAA2B,EAAE;;QARjC,UAAK,GAAG,IAAI,GAAG,EAAoB,CAAC;QAS1C,IAAI,CAAC,KAAK,GAAG,MAAA,OAAO,CAAC,KAAK,mCAAI,eAAM,CAAC,KAAK,CAAC,UAAU,CAAC;QACtD,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;QAE/B,gCAAgC;QAChC,MAAM,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC;QAC5C,IAAI,aAAa,IAAI,aAAa,GAAG,CAAC,EAAE,CAAC;YACvC,IAAI,CAAC,eAAe,GAAG,WAAW,CAAC,GAAG,EAAE;gBACtC,IAAI,CAAC,OAAO,EAAE,CAAC;YACjB,CAAC,EAAE,aAAa,CAAC,CAAC;QACpB,CAAC;IACH,CAAC;IAED;;;;;OAKG;IACH,GAAG,CAAC,GAAM,EAAE,KAAQ;QAClB,IAAI,CAAC,UAAU,CAAC,GAAG,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC;IAC1C,CAAC;IAED;;;;;;OAMG;IACH,UAAU,CAAC,GAAM,EAAE,KAAQ,EAAE,KAAa;QACxC,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QACvB,MAAM,SAAS,GAAG,GAAG,GAAG,KAAK,CAAC;QAC9B,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,YAAY,EAAE,GAAG,EAAE,CAAC,CAAC;QAE7D,uCAAuC;QACvC,IAAI,IAAI,CAAC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SAAS,CAAC,CAAC;QAC/B,CAAC;IACH,CAAC;CACF;AA7RD,4BA6RC","sourcesContent":["import { Config } from '../config';\n\n/**\n * Represents a cached entry with a value and an expiration timestamp.\n */\ntype CacheEntry<T> = {\n value: T;\n expiresAt: number;\n lastAccessed?: number; // Track last access time for LRU functionality\n};\n\n/**\n * Options for configuring a TTLCache instance.\n */\nexport interface TTLCacheOptions {\n /** Default time-to-live in milliseconds for cache entries */\n ttlMs?: number;\n /** Maximum number of entries to keep in cache (uses LRU eviction policy) */\n maxSize?: number;\n /** Auto-cleanup interval in milliseconds (disabled if 0 or negative) */\n autoCleanupMs?: number;\n}\n\n/**\n * An in-memory cache with time-to-live (TTL) support for each entry.\n *\n * @typeParam K - Type of the key.\n * @typeParam V - Type of the value.\n *\n * @example\n * const cache = new TTLCache<string, number>({ ttlMs: 1000 });\n * cache.set(\"x\", 123);\n * const value = cache.get(\"x\"); // 123\n */\nexport class TTLCache<K, V> {\n private cache = new Map<K, CacheEntry<V>>();\n private ttlMs: number;\n private maxSize?: number;\n private cleanupInterval?: NodeJS.Timeout;\n\n /**\n * @param options - Configuration options for the cache\n */\n constructor(options: TTLCacheOptions = {}) {\n this.ttlMs = options.ttlMs ?? Config.Cache.defaultTtl;\n this.maxSize = options.maxSize;\n\n // Setup auto-cleanup if enabled\n const autoCleanupMs = options.autoCleanupMs;\n if (autoCleanupMs && autoCleanupMs > 0) {\n this.cleanupInterval = setInterval(() => {\n this.cleanup();\n }, autoCleanupMs);\n }\n }\n\n /**\n * Sets a key-value pair in the cache with the default TTL.\n *\n * @param key - The key to set.\n * @param value - The value to associate with the key.\n */\n set(key: K, value: V): void {\n this.setWithTTL(key, value, this.ttlMs);\n }\n\n /**\n * Sets a key-value pair in the cache with a custom TTL.\n *\n * @param key - The key to set.\n * @param value - The value to associate with the key.\n * @param ttlMs - Time-to-live in milliseconds.\n */\n setWithTTL(key: K, value: V, ttlMs: number): void {\n const now = Date.now();\n const expiresAt = now + ttlMs;\n this.cache.set(key, { value, expiresAt, lastAccessed: now });\n\n // Enforce max size limit if configured\n if (this.maxSize && this.cache.size > this.maxSize) {\n this.evictLRU();\n }\n }\n\n /**\n * Retrieves the value for a given key if it hasn't expired.\n *\n * @param key - The key to retrieve.\n * @returns The cached value, or undefined if not found or expired.\n */\n get(key: K): V | undefined {\n const entry = this.cache.get(key);\n if (!entry) return undefined;\n\n const now = Date.now();\n if (now > entry.expiresAt) {\n this.cache.delete(key);\n return undefined;\n }\n\n // Update last access time for LRU tracking\n entry.lastAccessed = now;\n return entry.value;\n }\n\n /**\n * Retrieves or computes a value if it's not in the cache or has expired.\n *\n * @param key - The key to retrieve\n * @param producer - Function to generate the value if not cached\n * @param ttlMs - Optional custom TTL for the computed value\n * @returns The cached or computed value\n */\n async getOrCompute(key: K, producer: () => Promise<V>, ttlMs?: number): Promise<V> {\n const value = this.get(key);\n if (value !== undefined) return value;\n\n const newValue = await producer();\n this.setWithTTL(key, newValue, ttlMs ?? this.ttlMs);\n return newValue;\n }\n\n /**\n * Checks if the key exists and hasn't expired.\n *\n * @param key - The key to check.\n * @returns `true` if key exists and is valid, otherwise `false`.\n */\n has(key: K): boolean {\n return this.get(key) !== undefined;\n }\n\n /**\n * Deletes a key from the cache.\n *\n * @param key - The key to delete.\n * @returns `true` if the key existed and was removed, `false` otherwise.\n */\n delete(key: K): boolean {\n return this.cache.delete(key);\n }\n\n /**\n * Clears all entries from the cache.\n */\n clear(): void {\n this.cache.clear();\n }\n\n /**\n * Returns the number of entries currently in the cache (includes expired entries until next access/cleanup).\n *\n * @returns Number of items in the cache (may include expired keys).\n */\n size(): number {\n return this.cache.size;\n }\n\n /**\n * Set multiple key-value pairs at once with the default TTL.\n *\n * @param entries - Array of [key, value] tuples to set\n */\n setMany(entries: [K, V][]): void {\n for (const [key, value] of entries) {\n this.set(key, value);\n }\n }\n\n /**\n * Get multiple values at once.\n *\n * @param keys - Array of keys to retrieve\n * @returns Array of values (undefined for keys that don't exist or expired)\n */\n getMany(keys: K[]): (V | undefined)[] {\n return keys.map(key => this.get(key));\n }\n\n /**\n * Removes all expired entries from the cache.\n *\n * @returns Number of entries removed.\n */\n cleanup(): number {\n let removed = 0;\n const now = Date.now();\n for (const [key, entry] of this.cache.entries()) {\n if (now > entry.expiresAt) {\n this.cache.delete(key);\n removed++;\n }\n }\n return removed;\n }\n\n /**\n * Returns an iterator of all current valid [key, value] pairs.\n *\n * @returns IterableIterator<[K, V]>\n */\n *entries(): IterableIterator<[K, V]> {\n for (const [key, entry] of this.cache.entries()) {\n if (Date.now() <= entry.expiresAt) {\n yield [key, entry.value];\n }\n }\n }\n\n /**\n * Returns an iterator of all current valid keys.\n *\n * @returns IterableIterator<K>\n */\n *keys(): IterableIterator<K> {\n for (const [key, entry] of this.cache.entries()) {\n if (Date.now() <= entry.expiresAt) {\n yield key;\n }\n }\n }\n\n /**\n * Returns an iterator of all current valid values.\n *\n * @returns IterableIterator<V>\n */\n *values(): IterableIterator<V> {\n for (const entry of this.cache.values()) {\n if (Date.now() <= entry.expiresAt) {\n yield entry.value;\n }\n }\n }\n\n /**\n * Extends the expiration of a key by the specified time or default TTL.\n *\n * @param key - The key to refresh\n * @param ttlMs - Optional new TTL in milliseconds (uses default if not specified)\n * @returns true if the key was found and refreshed, false otherwise\n */\n refresh(key: K, ttlMs?: number): boolean {\n const entry = this.cache.get(key);\n if (!entry) return false;\n\n const now = Date.now();\n if (now > entry.expiresAt) {\n this.cache.delete(key);\n return false;\n }\n\n entry.expiresAt = now + (ttlMs ?? this.ttlMs);\n entry.lastAccessed = now;\n return true;\n }\n\n /**\n * Returns a snapshot of cache stats.\n *\n * @returns Object containing cache statistics\n */\n stats() {\n const now = Date.now();\n let expired = 0;\n let valid = 0;\n\n for (const entry of this.cache.values()) {\n if (now > entry.expiresAt) {\n expired++;\n } else {\n valid++;\n }\n }\n\n return {\n size: this.cache.size,\n validEntries: valid,\n expiredEntries: expired,\n maxSize: this.maxSize\n };\n }\n\n /**\n * Stop the auto-cleanup interval if it's running.\n */\n destroy() {\n if (this.cleanupInterval) {\n clearInterval(this.cleanupInterval);\n this.cleanupInterval = undefined;\n }\n }\n\n /**\n * Evict the least recently used entry from the cache.\n * @private\n */\n private evictLRU(): void {\n let oldestKey: K | undefined;\n let oldestAccess = Infinity;\n\n for (const [key, entry] of this.cache.entries()) {\n // Skip entries that are already expired\n if (Date.now() > entry.expiresAt) {\n this.cache.delete(key);\n return;\n }\n\n // Find the oldest accessed entry\n if (entry.lastAccessed && entry.lastAccessed < oldestAccess) {\n oldestAccess = entry.lastAccessed;\n oldestKey = key;\n }\n }\n\n if (oldestKey) {\n this.cache.delete(oldestKey);\n }\n }\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { AsyncLocalStorage } from "async_hooks";
1
+ import { AsyncLocalStorage } from 'async_hooks';
2
2
  /**
3
3
  * Type representing the store object used in AsyncLocalStorage.
4
4
  * Keys must be unique symbols to ensure isolation and prevent collisions.
@@ -13,6 +13,10 @@ export interface Store {
13
13
  export declare const StoreKeys: {
14
14
  LOGGER: symbol;
15
15
  REQUEST_ID: symbol;
16
+ USER_ID: symbol;
17
+ TENANT_ID: symbol;
18
+ TRACE_ID: symbol;
19
+ CORRELATION_ID: symbol;
16
20
  };
17
21
  /**
18
22
  * Retrieves the current request ID from the async context, if available.
@@ -20,6 +24,13 @@ export declare const StoreKeys: {
20
24
  * @returns {string | undefined} The request ID string or undefined if not present in the current context.
21
25
  */
22
26
  export declare function getRequestId(): string | undefined;
27
+ /**
28
+ * Type-safe getter for common context values.
29
+ *
30
+ * @param key The store key symbol
31
+ * @returns The typed value from the store
32
+ */
33
+ export declare function getFromContext<T>(key: symbol): T | undefined;
23
34
  /**
24
35
  * ContextStore manages per-request scoped context using AsyncLocalStorage.
25
36
  * It allows storing and retrieving data across async calls (e.g., request ID, logger).
@@ -81,5 +92,95 @@ export declare class ContextStore {
81
92
  * @returns {T} The result of the callback function.
82
93
  */
83
94
  static run<T>(store: Store, callback: () => T): T;
95
+ /**
96
+ * Checks if a key exists in the current context store.
97
+ *
98
+ * @param {symbol} key - The symbol key to check.
99
+ * @returns {boolean} True if the key exists, false otherwise.
100
+ */
101
+ static has(key: symbol): boolean;
102
+ /**
103
+ * Removes a value from the current context store by symbol key.
104
+ *
105
+ * @param {symbol} key - The symbol key to delete.
106
+ * @returns {boolean} True if the key was deleted, false if the key wasn't found or no active context.
107
+ * @throws {Error} If called outside an active context.
108
+ */
109
+ static delete(key: symbol): boolean;
110
+ /**
111
+ * Updates multiple values in the current context store at once.
112
+ *
113
+ * @param {Partial<Record<symbol, unknown>>} values - Object containing symbol keys and values to update.
114
+ * @throws {Error} If called outside an active context.
115
+ */
116
+ static patch(values: Partial<Record<symbol, unknown>>): void;
117
+ /**
118
+ * Executes a callback with a temporary store value that only exists during execution.
119
+ * Original store is restored after callback completes.
120
+ *
121
+ * @typeParam T - The callback's return type.
122
+ * @param {symbol} key - The symbol key to temporarily set.
123
+ * @param {unknown} value - The temporary value.
124
+ * @param {() => T} callback - The function to execute with the temporary value.
125
+ * @returns {T} The result of the callback function.
126
+ * @throws {Error} If called outside an active context.
127
+ */
128
+ static withValue<T>(key: symbol, value: unknown, callback: () => T): T;
129
+ /**
130
+ * Creates a new context that inherits values from the current context.
131
+ *
132
+ * @typeParam T - The callback's return type.
133
+ * @param {Partial<Record<symbol, unknown>>} newValues - New values to add to or override in the context.
134
+ * @param {() => T} callback - The function to execute in the new context.
135
+ * @returns {T} The result of the callback function.
136
+ */
137
+ static extend<T>(newValues: Partial<Record<symbol, unknown>>, callback: () => T): T;
138
+ /**
139
+ * Creates Express middleware that initializes a context for each request.
140
+ *
141
+ * @param {(req: any) => Partial<Record<symbol, unknown>>} initialValuesFactory - Function that returns initial context values.
142
+ * @returns Express middleware function.
143
+ */
144
+ static createExpressMiddleware(initialValuesFactory?: (req: any) => Partial<Record<symbol, unknown>>): (req: any, res: any, next: any) => void;
145
+ }
146
+ /**
147
+ * Type-safe wrapper for accessing and modifying context values with specific types.
148
+ *
149
+ * @typeParam T - The value type.
150
+ */
151
+ export declare class TypedContextKey<T> {
152
+ private symbol;
153
+ private defaultValue?;
154
+ /**
155
+ * Creates a new typed context key.
156
+ *
157
+ * @param symbol - The unique symbol for this key
158
+ * @param defaultValue - Optional default value if key is not found
159
+ */
160
+ constructor(symbol: symbol, defaultValue?: T | undefined);
161
+ /**
162
+ * Gets the current value for this key.
163
+ *
164
+ * @returns The value or defaultValue if not found
165
+ */
166
+ get(): T | undefined;
167
+ /**
168
+ * Sets the value for this key.
169
+ *
170
+ * @param value The value to set
171
+ */
172
+ set(value: T): void;
173
+ /**
174
+ * Checks if this key exists in the context.
175
+ *
176
+ * @returns True if the key exists
177
+ */
178
+ exists(): boolean;
179
+ /**
180
+ * Deletes this key from the context.
181
+ *
182
+ * @returns True if the key was deleted
183
+ */
184
+ delete(): boolean;
84
185
  }
85
186
  //# sourceMappingURL=context-store.utils.d.ts.map
@@ -1,15 +1,20 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ContextStore = exports.StoreKeys = void 0;
3
+ exports.TypedContextKey = exports.ContextStore = exports.StoreKeys = void 0;
4
4
  exports.getRequestId = getRequestId;
5
+ exports.getFromContext = getFromContext;
5
6
  const async_hooks_1 = require("async_hooks");
6
7
  /**
7
8
  * Predefined symbols used as keys in AsyncLocalStorage.
8
9
  * Add new symbols here to avoid duplication.
9
10
  */
10
11
  exports.StoreKeys = {
11
- LOGGER: Symbol("logger"),
12
- REQUEST_ID: Symbol("requestId"),
12
+ LOGGER: Symbol('logger'),
13
+ REQUEST_ID: Symbol('requestId'),
14
+ USER_ID: Symbol('userId'),
15
+ TENANT_ID: Symbol('tenantId'),
16
+ TRACE_ID: Symbol('traceId'),
17
+ CORRELATION_ID: Symbol('correlationId')
13
18
  };
14
19
  /**
15
20
  * Retrieves the current request ID from the async context, if available.
@@ -19,6 +24,15 @@ exports.StoreKeys = {
19
24
  function getRequestId() {
20
25
  return ContextStore.get(exports.StoreKeys.REQUEST_ID);
21
26
  }
27
+ /**
28
+ * Type-safe getter for common context values.
29
+ *
30
+ * @param key The store key symbol
31
+ * @returns The typed value from the store
32
+ */
33
+ function getFromContext(key) {
34
+ return ContextStore.get(key);
35
+ }
22
36
  /**
23
37
  * ContextStore manages per-request scoped context using AsyncLocalStorage.
24
38
  * It allows storing and retrieving data across async calls (e.g., request ID, logger).
@@ -90,6 +104,111 @@ class ContextStore {
90
104
  static run(store, callback) {
91
105
  return this.storage.run(store, callback);
92
106
  }
107
+ /**
108
+ * Checks if a key exists in the current context store.
109
+ *
110
+ * @param {symbol} key - The symbol key to check.
111
+ * @returns {boolean} True if the key exists, false otherwise.
112
+ */
113
+ static has(key) {
114
+ const store = this.storage.getStore();
115
+ return store !== undefined && key in store;
116
+ }
117
+ /**
118
+ * Removes a value from the current context store by symbol key.
119
+ *
120
+ * @param {symbol} key - The symbol key to delete.
121
+ * @returns {boolean} True if the key was deleted, false if the key wasn't found or no active context.
122
+ * @throws {Error} If called outside an active context.
123
+ */
124
+ static delete(key) {
125
+ const store = this.storage.getStore();
126
+ if (!store) {
127
+ throw new Error(`Failed to delete ${String(key)}: AsyncLocalStorage store is not initialized.`);
128
+ }
129
+ return delete store[key];
130
+ }
131
+ /**
132
+ * Updates multiple values in the current context store at once.
133
+ *
134
+ * @param {Partial<Record<symbol, unknown>>} values - Object containing symbol keys and values to update.
135
+ * @throws {Error} If called outside an active context.
136
+ */
137
+ static patch(values) {
138
+ const store = this.storage.getStore();
139
+ if (!store) {
140
+ throw new Error('Failed to patch: AsyncLocalStorage store is not initialized.');
141
+ }
142
+ Object.getOwnPropertySymbols(values).forEach(key => {
143
+ store[key] = values[key];
144
+ });
145
+ }
146
+ /**
147
+ * Executes a callback with a temporary store value that only exists during execution.
148
+ * Original store is restored after callback completes.
149
+ *
150
+ * @typeParam T - The callback's return type.
151
+ * @param {symbol} key - The symbol key to temporarily set.
152
+ * @param {unknown} value - The temporary value.
153
+ * @param {() => T} callback - The function to execute with the temporary value.
154
+ * @returns {T} The result of the callback function.
155
+ * @throws {Error} If called outside an active context.
156
+ */
157
+ static withValue(key, value, callback) {
158
+ const store = this.storage.getStore();
159
+ if (!store) {
160
+ throw new Error(`Failed to set temporary value: AsyncLocalStorage store is not initialized.`);
161
+ }
162
+ // Save original value
163
+ const hasOriginal = key in store;
164
+ const originalValue = store[key];
165
+ // Set temporary value
166
+ store[key] = value;
167
+ try {
168
+ // Run callback
169
+ return callback();
170
+ }
171
+ finally {
172
+ // Restore original value
173
+ if (hasOriginal) {
174
+ store[key] = originalValue;
175
+ }
176
+ else {
177
+ delete store[key];
178
+ }
179
+ }
180
+ }
181
+ /**
182
+ * Creates a new context that inherits values from the current context.
183
+ *
184
+ * @typeParam T - The callback's return type.
185
+ * @param {Partial<Record<symbol, unknown>>} newValues - New values to add to or override in the context.
186
+ * @param {() => T} callback - The function to execute in the new context.
187
+ * @returns {T} The result of the callback function.
188
+ */
189
+ static extend(newValues, callback) {
190
+ const currentStore = this.storage.getStore() || {};
191
+ // Create new store with current values plus new ones
192
+ const newStore = Object.assign({}, currentStore);
193
+ // Add new values
194
+ Object.getOwnPropertySymbols(newValues).forEach(key => {
195
+ newStore[key] = newValues[key];
196
+ });
197
+ // Run with extended store
198
+ return this.storage.run(newStore, callback);
199
+ }
200
+ /**
201
+ * Creates Express middleware that initializes a context for each request.
202
+ *
203
+ * @param {(req: any) => Partial<Record<symbol, unknown>>} initialValuesFactory - Function that returns initial context values.
204
+ * @returns Express middleware function.
205
+ */
206
+ static createExpressMiddleware(initialValuesFactory = () => ({})) {
207
+ return (req, res, next) => {
208
+ const initialValues = initialValuesFactory(req);
209
+ ContextStore.run(initialValues, next);
210
+ };
211
+ }
93
212
  }
94
213
  exports.ContextStore = ContextStore;
95
214
  /**
@@ -97,4 +216,55 @@ exports.ContextStore = ContextStore;
97
216
  * @private
98
217
  */
99
218
  ContextStore.storage = new async_hooks_1.AsyncLocalStorage();
219
+ /**
220
+ * Type-safe wrapper for accessing and modifying context values with specific types.
221
+ *
222
+ * @typeParam T - The value type.
223
+ */
224
+ class TypedContextKey {
225
+ /**
226
+ * Creates a new typed context key.
227
+ *
228
+ * @param symbol - The unique symbol for this key
229
+ * @param defaultValue - Optional default value if key is not found
230
+ */
231
+ constructor(symbol, defaultValue) {
232
+ this.symbol = symbol;
233
+ this.defaultValue = defaultValue;
234
+ }
235
+ /**
236
+ * Gets the current value for this key.
237
+ *
238
+ * @returns The value or defaultValue if not found
239
+ */
240
+ get() {
241
+ const value = ContextStore.get(this.symbol);
242
+ return value !== undefined ? value : this.defaultValue;
243
+ }
244
+ /**
245
+ * Sets the value for this key.
246
+ *
247
+ * @param value The value to set
248
+ */
249
+ set(value) {
250
+ ContextStore.set(this.symbol, value);
251
+ }
252
+ /**
253
+ * Checks if this key exists in the context.
254
+ *
255
+ * @returns True if the key exists
256
+ */
257
+ exists() {
258
+ return ContextStore.has(this.symbol);
259
+ }
260
+ /**
261
+ * Deletes this key from the context.
262
+ *
263
+ * @returns True if the key was deleted
264
+ */
265
+ delete() {
266
+ return ContextStore.delete(this.symbol);
267
+ }
268
+ }
269
+ exports.TypedContextKey = TypedContextKey;
100
270
  //# sourceMappingURL=context-store.utils.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"context-store.utils.js","sourceRoot":"","sources":["../../../src/utils/context-store.utils.ts"],"names":[],"mappings":";;;AAwBA,oCAEC;AA1BD,6CAAgD;AAUhD;;;GAGG;AACU,QAAA,SAAS,GAAG;IACvB,MAAM,EAAE,MAAM,CAAC,QAAQ,CAAC;IACxB,UAAU,EAAE,MAAM,CAAC,WAAW,CAAC;CAChC,CAAC;AAEF;;;;GAIG;AACH,SAAgB,YAAY;IAC1B,OAAO,YAAY,CAAC,GAAG,CAAS,iBAAS,CAAC,UAAU,CAAC,CAAC;AACxD,CAAC;AAED;;;;;;;;;;;;;;;GAeG;AACH,MAAa,YAAY;IAOvB;;;;OAIG;IACH,MAAM,CAAC,WAAW;QAChB,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;IAED;;;;;;OAMG;IACH,MAAM,CAAC,GAAG,CAAI,GAAW;QACvB,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC;QACtC,OAAO,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAG,GAAG,CAAkB,CAAC;IACvC,CAAC;IAED;;;;;;;OAOG;IACH,MAAM,CAAC,GAAG,CAAI,GAAW,EAAE,KAAQ;QACjC,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC;QACtC,IAAI,CAAC,KAAK,EAAE,CAAC;YACX,MAAM,IAAI,KAAK,CACb,iBAAiB,MAAM,CAAC,GAAG,CAAC,+CAA+C,CAC5E,CAAC;QACJ,CAAC;QACD,KAAK,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;IACrB,CAAC;IAED;;;;OAIG;IACH,MAAM,CAAC,MAAM;QACX,OAAO,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC;IACjC,CAAC;IAED;;;;;;;;OAQG;IACH,MAAM,CAAC,GAAG,CAAI,KAAY,EAAE,QAAiB;QAC3C,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;IAC3C,CAAC;;AAlEH,oCAmEC;AAlEC;;;GAGG;AACqB,oBAAO,GAAG,IAAI,+BAAiB,EAAS,CAAC","sourcesContent":["import { AsyncLocalStorage } from \"async_hooks\";\n\n/**\n * Type representing the store object used in AsyncLocalStorage.\n * Keys must be unique symbols to ensure isolation and prevent collisions.\n */\nexport interface Store {\n [key: symbol]: unknown;\n}\n\n/**\n * Predefined symbols used as keys in AsyncLocalStorage.\n * Add new symbols here to avoid duplication.\n */\nexport const StoreKeys = {\n LOGGER: Symbol(\"logger\"),\n REQUEST_ID: Symbol(\"requestId\"),\n};\n\n/**\n * Retrieves the current request ID from the async context, if available.\n *\n * @returns {string | undefined} The request ID string or undefined if not present in the current context.\n */\nexport function getRequestId(): string | undefined {\n return ContextStore.get<string>(StoreKeys.REQUEST_ID);\n}\n\n/**\n * ContextStore manages per-request scoped context using AsyncLocalStorage.\n * It allows storing and retrieving data across async calls (e.g., request ID, logger).\n *\n * Example (Express middleware):\n * ```\n * // Middleware to initialize context and logger\n * app.use((req, res, next) => {\n * const requestId = req.headers[\"x-request-id\"]?.toString() || crypto.randomUUID();\n * ContextStore.run({ [StoreKeys.REQUEST_ID]: requestId }, () => {\n * ContextStore.set(StoreKeys.LOGGER, getLogger().child({ reqId: requestId }));\n * next();\n * });\n * });\n * ```\n */\nexport class ContextStore {\n /**\n * The underlying AsyncLocalStorage instance for context.\n * @private\n */\n private static readonly storage = new AsyncLocalStorage<Store>();\n\n /**\n * Returns the raw AsyncLocalStorage instance for advanced access.\n *\n * @returns {AsyncLocalStorage<Store>} The AsyncLocalStorage instance.\n */\n static getInstance(): AsyncLocalStorage<Store> {\n return this.storage;\n }\n\n /**\n * Retrieves a value from the async context store by symbol key.\n *\n * @typeParam T - The expected return type of the value.\n * @param {symbol} key - Unique symbol used as the store key.\n * @returns {T | undefined} The value found (typed) or undefined if not present.\n */\n static get<T>(key: symbol): T | undefined {\n const store = this.storage.getStore();\n return store?.[key] as T | undefined;\n }\n\n /**\n * Sets a value in the current context store by symbol key.\n *\n * @typeParam T - The value type to set.\n * @param {symbol} key - Unique symbol key.\n * @param {T} value - Value to set in context.\n * @throws {Error} If called outside an active context (not within a .run call or in the wrong async boundaries).\n */\n static set<T>(key: symbol, value: T): void {\n const store = this.storage.getStore();\n if (!store) {\n throw new Error(\n `Failed to set ${String(key)}: AsyncLocalStorage store is not initialized.`,\n );\n }\n store[key] = value;\n }\n\n /**\n * Retrieves the entire context store object for the current async context.\n *\n * @returns {Store | undefined} The current store object or undefined if called outside a context.\n */\n static getAll(): Store | undefined {\n return this.storage.getStore();\n }\n\n /**\n * Initializes a new async context and executes a callback within it.\n * This must be called at the beginning of a request or logical async flow.\n *\n * @typeParam T - The callback's return type.\n * @param {Store} store - The initial key-value store object.\n * @param {() => T} callback - The function to run within the new context.\n * @returns {T} The result of the callback function.\n */\n static run<T>(store: Store, callback: () => T): T {\n return this.storage.run(store, callback);\n }\n}\n"]}
1
+ {"version":3,"file":"context-store.utils.js","sourceRoot":"","sources":["../../../src/utils/context-store.utils.ts"],"names":[],"mappings":";;;AA4BA,oCAEC;AAQD,wCAEC;AAxCD,6CAAgD;AAUhD;;;GAGG;AACU,QAAA,SAAS,GAAG;IACvB,MAAM,EAAE,MAAM,CAAC,QAAQ,CAAC;IACxB,UAAU,EAAE,MAAM,CAAC,WAAW,CAAC;IAC/B,OAAO,EAAE,MAAM,CAAC,QAAQ,CAAC;IACzB,SAAS,EAAE,MAAM,CAAC,UAAU,CAAC;IAC7B,QAAQ,EAAE,MAAM,CAAC,SAAS,CAAC;IAC3B,cAAc,EAAE,MAAM,CAAC,eAAe,CAAC;CACxC,CAAC;AAEF;;;;GAIG;AACH,SAAgB,YAAY;IAC1B,OAAO,YAAY,CAAC,GAAG,CAAS,iBAAS,CAAC,UAAU,CAAC,CAAC;AACxD,CAAC;AAED;;;;;GAKG;AACH,SAAgB,cAAc,CAAI,GAAW;IAC3C,OAAO,YAAY,CAAC,GAAG,CAAI,GAAG,CAAC,CAAC;AAClC,CAAC;AAED;;;;;;;;;;;;;;;GAeG;AACH,MAAa,YAAY;IAOvB;;;;OAIG;IACH,MAAM,CAAC,WAAW;QAChB,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;IAED;;;;;;OAMG;IACH,MAAM,CAAC,GAAG,CAAI,GAAW;QACvB,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC;QACtC,OAAO,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAG,GAAG,CAAkB,CAAC;IACvC,CAAC;IAED;;;;;;;OAOG;IACH,MAAM,CAAC,GAAG,CAAI,GAAW,EAAE,KAAQ;QACjC,MAAM,KAAK,GAAG,IA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DD,0CAgDC","sourcesContent":["import { AsyncLocalStorage } from 'async_hooks';\n\n/**\n * Type representing the store object used in AsyncLocalStorage.\n * Keys must be unique symbols to ensure isolation and prevent collisions.\n */\nexport interface Store {\n [key: symbol]: unknown;\n}\n\n/**\n * Predefined symbols used as keys in AsyncLocalStorage.\n * Add new symbols here to avoid duplication.\n */\nexport const StoreKeys = {\n LOGGER: Symbol('logger'),\n REQUEST_ID: Symbol('requestId'),\n USER_ID: Symbol('userId'),\n TENANT_ID: Symbol('tenantId'),\n TRACE_ID: Symbol('traceId'),\n CORRELATION_ID: Symbol('correlationId')\n};\n\n/**\n * Retrieves the current request ID from the async context, if available.\n *\n * @returns {string | undefined} The request ID string or undefined if not present in the current context.\n */\nexport function getRequestId(): string | undefined {\n return ContextStore.get<string>(StoreKeys.REQUEST_ID);\n}\n\n/**\n * Type-safe getter for common context values.\n *\n * @param key The store key symbol\n * @returns The typed value from the store\n */\nexport function getFromContext<T>(key: symbol): T | undefined {\n return ContextStore.get<T>(key);\n}\n\n/**\n * ContextStore manages per-request scoped context using AsyncLocalStorage.\n * It allows storing and retrieving data across async calls (e.g., request ID, logger).\n *\n * Example (Express middleware):\n * ```\n * // Middleware to initialize context and logger\n * app.use((req, res, next) => {\n * const requestId = req.headers[\"x-request-id\"]?.toString() || crypto.randomUUID();\n * ContextStore.run({ [StoreKeys.REQUEST_ID]: requestId }, () => {\n * ContextStore.set(StoreKeys.LOGGER, getLogger().child({ reqId: requestId }));\n * next();\n * });\n * });\n * ```\n */\nexport class ContextStore {\n /**\n * The underlying AsyncLocalStorage instance for context.\n * @private\n */\n private static readonly storage = new AsyncLocalStorage<Store>();\n\n /**\n * Returns the raw AsyncLocalStorage instance for advanced access.\n *\n * @returns {AsyncLocalStorage<Store>} The AsyncLocalStorage instance.\n */\n static getInstance(): AsyncLocalStorage<Store> {\n return this.storage;\n }\n\n /**\n * Retrieves a value from the async context store by symbol key.\n *\n * @typeParam T - The expected return type of the value.\n * @param {symbol} key - Unique symbol used as the store key.\n * @returns {T | undefined} The value found (typed) or undefined if not present.\n */\n static get<T>(key: symbol): T | undefined {\n const store = this.storage.getStore();\n return store?.[key] as T | undefined;\n }\n\n /**\n * Sets a value in the current context store by symbol key.\n *\n * @typeParam T - The value type to set.\n * @param {symbol} key - Unique symbol key.\n * @param {T} value - Value to set in context.\n * @throws {Error} If called outside an active context (not within a .run call or in the wrong async boundaries).\n */\n static set<T>(key: symbol, value: T): void {\n const store = this.storage.getStore();\n if (!store) {\n throw new Error(`Failed to set ${String(key)}: AsyncLocalStorage store is not initialized.`);\n }\n store[key] = value;\n }\n\n /**\n * Retrieves the entire context store object for the current async context.\n *\n * @returns {Store | undefined} The current store object or undefined if called outside a context.\n */\n static getAll(): Store | undefined {\n return this.storage.getStore();\n }\n\n /**\n * Initializes a new async context and executes a callback within it.\n * This must be called at the beginning of a request or logical async flow.\n *\n * @typeParam T - The callback's return type.\n * @param {Store} store - The initial key-value store object.\n * @param {() => T} callback - The function to run within the new context.\n * @returns {T} The result of the callback function.\n */\n static run<T>(store: Store, callback: () => T): T {\n return this.storage.run(store, callback);\n }\n\n /**\n * Checks if a key exists in the current context store.\n *\n * @param {symbol} key - The symbol key to check.\n * @returns {boolean} True if the key exists, false otherwise.\n */\n static has(key: symbol): boolean {\n const store = this.storage.getStore();\n return store !== undefined && key in store;\n }\n\n /**\n * Removes a value from the current context store by symbol key.\n *\n * @param {symbol} key - The symbol key to delete.\n * @returns {boolean} True if the key was deleted, false if the key wasn't found or no active context.\n * @throws {Error} If called outside an active context.\n */\n static delete(key: symbol): boolean {\n const store = this.storage.getStore();\n if (!store) {\n throw new Error(`Failed to delete ${String(key)}: AsyncLocalStorage store is not initialized.`);\n }\n return delete store[key];\n }\n\n /**\n * Updates multiple values in the current context store at once.\n *\n * @param {Partial<Record<symbol, unknown>>} values - Object containing symbol keys and values to update.\n * @throws {Error} If called outside an active context.\n */\n static patch(values: Partial<Record<symbol, unknown>>): void {\n const store = this.storage.getStore();\n if (!store) {\n throw new Error('Failed to patch: AsyncLocalStorage store is not initialized.');\n }\n Object.getOwnPropertySymbols(values).forEach(key => {\n store[key] = values[key];\n });\n }\n /**\n * Executes a callback with a temporary store value that only exists during execution.\n * Original store is restored after callback completes.\n *\n * @typeParam T - The callback's return type.\n * @param {symbol} key - The symbol key to temporarily set.\n * @param {unknown} value - The temporary value.\n * @param {() => T} callback - The function to execute with the temporary value.\n * @returns {T} The result of the callback function.\n * @throws {Error} If called outside an active context.\n */\n static withValue<T>(key: symbol, value: unknown, callback: () => T): T {\n const store = this.storage.getStore();\n if (!store) {\n throw new Error(`Failed to set temporary value: AsyncLocalStorage store is not initialized.`);\n }\n\n // Save original value\n const hasOriginal = key in store;\n const originalValue = store[key];\n\n // Set temporary value\n store[key] = value;\n\n try {\n // Run callback\n return callback();\n } finally {\n // Restore original value\n if (hasOriginal) {\n store[key] = originalValue;\n } else {\n delete store[key];\n }\n }\n }\n\n /**\n * Creates a new context that inherits values from the current context.\n *\n * @typeParam T - The callback's return type.\n * @param {Partial<Record<symbol, unknown>>} newValues - New values to add to or override in the context.\n * @param {() => T} callback - The function to execute in the new context.\n * @returns {T} The result of the callback function.\n */\n static extend<T>(newValues: Partial<Record<symbol, unknown>>, callback: () => T): T {\n const currentStore = this.storage.getStore() || {};\n\n // Create new store with current values plus new ones\n const newStore: Store = { ...currentStore };\n\n // Add new values\n Object.getOwnPropertySymbols(newValues).forEach(key => {\n newStore[key] = newValues[key];\n });\n\n // Run with extended store\n return this.storage.run(newStore, callback);\n }\n\n /**\n * Creates Express middleware that initializes a context for each request.\n *\n * @param {(req: any) => Partial<Record<symbol, unknown>>} initialValuesFactory - Function that returns initial context values.\n * @returns Express middleware function.\n */\n static createExpressMiddleware(initialValuesFactory: (req: any) => Partial<Record<symbol, unknown>> = () => ({})) {\n return (req: any, res: any, next: any) => {\n const initialValues = initialValuesFactory(req);\n ContextStore.run(initialValues as Store, next);\n };\n }\n}\n\n/**\n * Type-safe wrapper for accessing and modifying context values with specific types.\n *\n * @typeParam T - The value type.\n */\nexport class TypedContextKey<T> {\n /**\n * Creates a new typed context key.\n *\n * @param symbol - The unique symbol for this key\n * @param defaultValue - Optional default value if key is not found\n */\n constructor(\n private symbol: symbol,\n private defaultValue?: T\n ) {}\n\n /**\n * Gets the current value for this key.\n *\n * @returns The value or defaultValue if not found\n */\n get(): T | undefined {\n const value = ContextStore.get<T>(this.symbol);\n return value !== undefined ? value : this.defaultValue;\n }\n\n /**\n * Sets the value for this key.\n *\n * @param value The value to set\n */\n set(value: T): void {\n ContextStore.set<T>(this.symbol, value);\n }\n\n /**\n * Checks if this key exists in the context.\n *\n * @returns True if the key exists\n */\n exists(): boolean {\n return ContextStore.has(this.symbol);\n }\n\n /**\n * Deletes this key from the context.\n *\n * @returns True if the key was deleted\n */\n delete(): boolean {\n return ContextStore.delete(this.symbol);\n }\n}\n"]}
@@ -1,4 +1,5 @@
1
- import { BinaryToTextEncoding } from "crypto";
1
+ import { BinaryToTextEncoding, CipherGCMTypes } from 'crypto';
2
+ export type BufferEncoding = 'ascii' | 'utf8' | 'utf-8' | 'utf16le' | 'utf-16le' | 'ucs2' | 'ucs-2' | 'base64' | 'base64url' | 'latin1' | 'binary' | 'hex';
2
3
  /**
3
4
  * Generates an HMAC digest using the specified algorithm and secret key.
4
5
  *
@@ -8,7 +9,7 @@ import { BinaryToTextEncoding } from "crypto";
8
9
  * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).
9
10
  * @returns {string} HMAC digest as a string.
10
11
  */
11
- export declare const hmac: (algorithm: string, input: string, secret: string, encoding?: BinaryToTextEncoding) => string;
12
+ export declare function hmac(algorithm: string, input: string, secret: string, encoding?: BinaryToTextEncoding): string;
12
13
  /**
13
14
  * Generates a hash digest using the specified algorithm.
14
15
  *
@@ -17,7 +18,7 @@ export declare const hmac: (algorithm: string, input: string, secret: string, en
17
18
  * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).
18
19
  * @returns {string} Hash digest as a string.
19
20
  */
20
- export declare const hash: (algorithm: string, input: string, encoding?: BinaryToTextEncoding) => string;
21
+ export declare function hash(algorithm: string, input: string, encoding?: BinaryToTextEncoding): string;
21
22
  /**
22
23
  * Generates an HMAC-SHA256 digest.
23
24
  *
@@ -25,7 +26,7 @@ export declare const hash: (algorithm: string, input: string, encoding?: BinaryT
25
26
  * @param {string} secret - The secret key.
26
27
  * @returns {string} SHA-256 HMAC digest as a string.
27
28
  */
28
- export declare const sha256Hmac: (input: string, secret: string) => string;
29
+ export declare function sha256Hmac(input: string, secret: string): string;
29
30
  /**
30
31
  * Generates a SHA1 hash digest.
31
32
  *
@@ -33,7 +34,7 @@ export declare const sha256Hmac: (input: string, secret: string) => string;
33
34
  * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
34
35
  * @returns {string} SHA-1 hash as a string.
35
36
  */
36
- export declare const sha1: (input: string, encoding?: BinaryToTextEncoding) => string;
37
+ export declare function sha1(input: string, encoding?: BinaryToTextEncoding): string;
37
38
  /**
38
39
  * Generates a SHA256 hash digest.
39
40
  *
@@ -41,18 +42,119 @@ export declare const sha1: (input: string, encoding?: BinaryToTextEncoding) => s
41
42
  * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
42
43
  * @returns {string} SHA-256 hash as a string.
43
44
  */
44
- export declare const sha256: (input: string, encoding?: BinaryToTextEncoding) => string;
45
+ export declare function sha256(input: string, encoding?: BinaryToTextEncoding): string;
45
46
  /**
46
47
  * Generates an MD5 hash digest.
47
48
  *
48
49
  * @param {string} input - The string to hash.
49
50
  * @returns {string} MD5 hash as a string.
50
51
  */
51
- export declare const md5: (input: string) => string;
52
+ export declare function md5(input: string): string;
52
53
  /**
53
54
  * Generates a cryptographically strong random string by hashing a random UUID with SHA-256.
54
55
  *
55
56
  * @returns {string} Random string hashed with SHA-256 (hex encoding).
56
57
  */
57
- export declare const randomString: () => string;
58
+ export declare function randomString(): string;
59
+ /**
60
+ * Generates a secure random buffer of specified byte length.
61
+ *
62
+ * @param {number} [byteLength=32] - Number of random bytes to generate.
63
+ * @returns {Buffer} Buffer containing random bytes.
64
+ */
65
+ export declare function generateRandomBytes(byteLength?: number): Buffer;
66
+ /**
67
+ * Generates a secure random string of specified byte length with specified encoding.
68
+ *
69
+ * @param {number} [byteLength=32] - Number of random bytes to generate.
70
+ * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
71
+ * @returns {string} Random string in specified encoding.
72
+ */
73
+ export declare function generateRandomBytesAsString(byteLength?: number, encoding?: BinaryToTextEncoding): string;
74
+ /**
75
+ * Generates a secure API key with a specified format.
76
+ *
77
+ * @param {string} [prefix=''] - Optional prefix for the key.
78
+ * @param {number} [byteLength=24] - Number of random bytes to generate.
79
+ * @returns {string} Formatted API key.
80
+ */
81
+ export declare function generateApiKey(prefix?: string, byteLength?: number): string;
82
+ /**
83
+ * Compares two strings, arrays, or buffers in constant time to prevent timing attacks.
84
+ *
85
+ * @param {string | Buffer | Uint8Array} a - First value to compare
86
+ * @param {string | Buffer | Uint8Array} b - Second value to compare
87
+ * @returns {boolean} True if values are equal
88
+ */
89
+ export declare function safeCompare(a: string | Buffer | Uint8Array, b: string | Buffer | Uint8Array): boolean;
90
+ /**
91
+ * Interface for encryption options
92
+ */
93
+ export interface EncryptionOptions {
94
+ /** Algorithm to use (default: aes-256-gcm) */
95
+ algorithm?: CipherGCMTypes;
96
+ /** Input encoding for plaintext if string (default: utf8) */
97
+ inputEncoding?: BufferEncoding;
98
+ /** Output encoding for ciphertext (default: hex) */
99
+ outputEncoding?: BinaryToTextEncoding;
100
+ }
101
+ /**
102
+ * Interface for decryption options
103
+ */
104
+ export interface DecryptionOptions {
105
+ /** Algorithm to use (default: aes-256-gcm) */
106
+ algorithm?: CipherGCMTypes;
107
+ /** Input encoding for ciphertext if string (default: hex) */
108
+ inputEncoding?: BinaryToTextEncoding;
109
+ /** Output encoding for plaintext (default: utf8) */
110
+ outputEncoding?: BufferEncoding;
111
+ }
112
+ /**
113
+ * Result of encryption operation including all data needed for decryption
114
+ */
115
+ export interface EncryptionResult {
116
+ /** Encrypted data (string or Buffer based on options) */
117
+ ciphertext: string | Buffer;
118
+ /** Initialization vector */
119
+ iv: Buffer;
120
+ /** Authentication tag (for GCM mode) */
121
+ authTag?: Buffer;
122
+ /** Algorithm used */
123
+ algorithm: string;
124
+ }
125
+ /**
126
+ * Encrypts data using a symmetric key with secure defaults (AES-256-GCM).
127
+ *
128
+ * @param {string | Buffer} data - Data to encrypt
129
+ * @param {string | Buffer} key - Encryption key or passphrase
130
+ * @param {EncryptionOptions} [options] - Encryption options
131
+ * @returns {Promise<EncryptionResult>} Encrypted data with metadata
132
+ */
133
+ export declare function encrypt(data: string | Buffer, key: string | Buffer, options?: EncryptionOptions): Promise<EncryptionResult>;
134
+ /**
135
+ * Decrypts data that was encrypted with the encrypt function.
136
+ *
137
+ * @param {EncryptionResult} encryptedData - The encrypted data and metadata
138
+ * @param {string | Buffer} key - Decryption key or passphrase
139
+ * @param {DecryptionOptions} [options] - Decryption options
140
+ * @returns {Promise<string | Buffer>} Decrypted data
141
+ */
142
+ export declare function decrypt(encryptedData: EncryptionResult, key: string | Buffer, options?: DecryptionOptions): Promise<string | Buffer>;
143
+ /**
144
+ * Creates a signed token with an expiration time and payload.
145
+ *
146
+ * @param {object} payload - Data to include in the token
147
+ * @param {string} secret - Secret key for signing
148
+ * @param {number} [expiresInSeconds=3600] - Token expiration in seconds
149
+ * @returns {string} Signed token string
150
+ */
151
+ export declare function createSignedToken(payload: Record<string, any>, secret: string, expiresInSeconds?: number): string;
152
+ /**
153
+ * Verifies and decodes a signed token.
154
+ *
155
+ * @param {string} token - The token to verify
156
+ * @param {string} secret - Secret key for verification
157
+ * @returns {object | null} Decoded payload if valid, null if invalid
158
+ */
159
+ export declare function verifySignedToken(token: string, secret: string): Record<string, any> | null;
58
160
  //# sourceMappingURL=crypto.utils.d.ts.map