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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (280) hide show
  1. package/build/{esnext → cjs}/config.d.ts +0 -1
  2. package/build/{src → cjs}/config.js +0 -1
  3. package/build/{esnext → cjs}/index.d.ts +0 -1
  4. package/build/{src → cjs}/index.js +0 -1
  5. package/build/{esnext → cjs}/servers/server.builder.d.ts +0 -1
  6. package/build/{src → cjs}/servers/server.builder.js +10 -13
  7. package/build/{src → cjs}/servers/server.d.ts +0 -1
  8. package/build/{src → cjs}/servers/server.js +83 -75
  9. package/build/{src → cjs}/types/api-response.d.ts +0 -1
  10. package/build/{src → cjs}/types/api-response.js +0 -1
  11. package/build/{src → cjs}/types/index.d.ts +0 -1
  12. package/build/{src → cjs}/types/index.js +0 -1
  13. package/build/{src → cjs}/types/server.d.ts +0 -1
  14. package/build/{src → cjs}/types/server.js +0 -1
  15. package/build/{src → cjs}/utils/array.utils.d.ts +0 -1
  16. package/build/{src → cjs}/utils/array.utils.js +0 -1
  17. package/build/{src → cjs}/utils/async.utils.d.ts +0 -1
  18. package/build/{src → cjs}/utils/async.utils.js +2 -3
  19. package/build/{esnext → cjs}/utils/cache.utils.d.ts +0 -1
  20. package/build/{src → cjs}/utils/cache.utils.js +7 -6
  21. package/build/{esnext → cjs}/utils/context-store.utils.d.ts +1 -2
  22. package/build/{src → cjs}/utils/context-store.utils.js +10 -9
  23. package/build/{esnext → cjs}/utils/crypto.utils.d.ts +0 -1
  24. package/build/{src → cjs}/utils/crypto.utils.js +5 -3
  25. package/build/{src → cjs}/utils/date.utils.d.ts +0 -1
  26. package/build/{src → cjs}/utils/date.utils.js +1 -2
  27. package/build/{src → cjs}/utils/decorators.utils.d.ts +30 -27
  28. package/build/{src → cjs}/utils/decorators.utils.js +169 -30
  29. package/build/{esnext → cjs}/utils/dir.utils.d.ts +0 -1
  30. package/build/{src → cjs}/utils/dir.utils.js +6 -7
  31. package/build/{esnext → cjs}/utils/env.utils.d.ts +0 -1
  32. package/build/{src → cjs}/utils/env.utils.js +5 -8
  33. package/build/{src → cjs}/utils/exception.utils.d.ts +0 -1
  34. package/build/{src → cjs}/utils/exception.utils.js +2 -1
  35. package/build/{src → cjs}/utils/fs.utils.d.ts +0 -1
  36. package/build/{src → cjs}/utils/fs.utils.js +12 -13
  37. package/build/{esnext → cjs}/utils/http-status-codes.d.ts +0 -1
  38. package/build/{src → cjs}/utils/http-status-codes.js +0 -1
  39. package/build/{esnext → cjs}/utils/id.utils.d.ts +0 -1
  40. package/build/{src → cjs}/utils/id.utils.js +0 -1
  41. package/build/{src → cjs}/utils/logger.utils.d.ts +0 -1
  42. package/build/{src → cjs}/utils/logger.utils.js +10 -6
  43. package/build/{esnext → cjs}/utils/middleware.utils.d.ts +0 -1
  44. package/build/{src → cjs}/utils/middleware.utils.js +16 -17
  45. package/build/{esnext → cjs}/utils/obj.utils.d.ts +0 -1
  46. package/build/{src → cjs}/utils/obj.utils.js +1 -2
  47. package/build/{src → cjs}/utils/performance.utils.d.ts +0 -1
  48. package/build/{src → cjs}/utils/performance.utils.js +6 -4
  49. package/build/{esnext → cjs}/utils/request.utils.d.ts +0 -1
  50. package/build/{src → cjs}/utils/request.utils.js +7 -3
  51. package/build/{esnext → cjs}/utils/response.utils.d.ts +0 -1
  52. package/build/{src → cjs}/utils/response.utils.js +42 -28
  53. package/build/{esnext → cjs}/utils/stream.utils.d.ts +0 -1
  54. package/build/{src → cjs}/utils/stream.utils.js +0 -1
  55. package/build/{esnext → cjs}/utils/string.utils.d.ts +0 -1
  56. package/build/{src → cjs}/utils/string.utils.js +0 -1
  57. package/build/{src → cjs}/utils/type.utils.d.ts +0 -1
  58. package/build/{src → cjs}/utils/type.utils.js +2 -3
  59. package/build/{src → cjs}/utils/url.utils.d.ts +0 -1
  60. package/build/{src → cjs}/utils/url.utils.js +8 -9
  61. package/build/{src → cjs}/utils/validate.utils.d.ts +0 -1
  62. package/build/{src → cjs}/utils/validate.utils.js +2 -3
  63. package/build/esm/config.d.ts +0 -1
  64. package/build/esm/config.js +6 -7
  65. package/build/esm/index.d.ts +0 -1
  66. package/build/esm/index.js +0 -1
  67. package/build/esm/servers/server.builder.d.ts +0 -1
  68. package/build/esm/servers/server.builder.js +99 -147
  69. package/build/esm/servers/server.d.ts +0 -1
  70. package/build/esm/servers/server.js +591 -876
  71. package/build/esm/types/api-response.d.ts +0 -1
  72. package/build/esm/types/api-response.js +0 -1
  73. package/build/esm/types/index.d.ts +0 -1
  74. package/build/esm/types/index.js +0 -1
  75. package/build/esm/types/server.d.ts +0 -1
  76. package/build/esm/types/server.js +0 -1
  77. package/build/esm/utils/array.utils.d.ts +0 -1
  78. package/build/esm/utils/array.utils.js +48 -86
  79. package/build/esm/utils/async.utils.d.ts +0 -1
  80. package/build/esm/utils/async.utils.js +247 -524
  81. package/build/esm/utils/cache.utils.d.ts +0 -1
  82. package/build/esm/utils/cache.utils.js +96 -301
  83. package/build/esm/utils/context-store.utils.d.ts +1 -2
  84. package/build/esm/utils/context-store.utils.js +62 -79
  85. package/build/esm/utils/crypto.utils.d.ts +0 -1
  86. package/build/esm/utils/crypto.utils.js +78 -175
  87. package/build/esm/utils/date.utils.d.ts +0 -1
  88. package/build/esm/utils/date.utils.js +47 -53
  89. package/build/esm/utils/decorators.utils.d.ts +30 -27
  90. package/build/esm/utils/decorators.utils.js +417 -461
  91. package/build/esm/utils/dir.utils.d.ts +0 -1
  92. package/build/esm/utils/dir.utils.js +264 -786
  93. package/build/esm/utils/env.utils.d.ts +0 -1
  94. package/build/esm/utils/env.utils.js +180 -271
  95. package/build/esm/utils/exception.utils.d.ts +0 -1
  96. package/build/esm/utils/exception.utils.js +112 -289
  97. package/build/esm/utils/fs.utils.d.ts +0 -1
  98. package/build/esm/utils/fs.utils.js +169 -401
  99. package/build/esm/utils/http-status-codes.d.ts +0 -1
  100. package/build/esm/utils/http-status-codes.js +0 -1
  101. package/build/esm/utils/id.utils.d.ts +0 -1
  102. package/build/esm/utils/id.utils.js +5 -9
  103. package/build/esm/utils/logger.utils.d.ts +0 -1
  104. package/build/esm/utils/logger.utils.js +34 -71
  105. package/build/esm/utils/middleware.utils.d.ts +0 -1
  106. package/build/esm/utils/middleware.utils.js +65 -155
  107. package/build/esm/utils/obj.utils.d.ts +0 -1
  108. package/build/esm/utils/obj.utils.js +69 -176
  109. package/build/esm/utils/performance.utils.d.ts +0 -1
  110. package/build/esm/utils/performance.utils.js +92 -195
  111. package/build/esm/utils/request.utils.d.ts +0 -1
  112. package/build/esm/utils/request.utils.js +41 -74
  113. package/build/esm/utils/response.utils.d.ts +0 -1
  114. package/build/esm/utils/response.utils.js +84 -107
  115. package/build/esm/utils/stream.utils.d.ts +0 -1
  116. package/build/esm/utils/stream.utils.js +38 -113
  117. package/build/esm/utils/string.utils.d.ts +0 -1
  118. package/build/esm/utils/string.utils.js +6 -11
  119. package/build/esm/utils/type.utils.d.ts +0 -1
  120. package/build/esm/utils/type.utils.js +8 -12
  121. package/build/esm/utils/url.utils.d.ts +0 -1
  122. package/build/esm/utils/url.utils.js +49 -127
  123. package/build/esm/utils/validate.utils.d.ts +0 -1
  124. package/build/esm/utils/validate.utils.js +23 -40
  125. package/package.json +288 -63
  126. package/build/esm/config.js.map +0 -1
  127. package/build/esm/index.js.map +0 -1
  128. package/build/esm/servers/server.builder.js.map +0 -1
  129. package/build/esm/servers/server.js.map +0 -1
  130. package/build/esm/types/api-response.js.map +0 -1
  131. package/build/esm/types/index.js.map +0 -1
  132. package/build/esm/types/server.js.map +0 -1
  133. package/build/esm/utils/array.utils.js.map +0 -1
  134. package/build/esm/utils/async.utils.js.map +0 -1
  135. package/build/esm/utils/cache.utils.js.map +0 -1
  136. package/build/esm/utils/context-store.utils.js.map +0 -1
  137. package/build/esm/utils/crypto.utils.js.map +0 -1
  138. package/build/esm/utils/date.utils.js.map +0 -1
  139. package/build/esm/utils/decorators.utils.js.map +0 -1
  140. package/build/esm/utils/dir.utils.js.map +0 -1
  141. package/build/esm/utils/env.utils.js.map +0 -1
  142. package/build/esm/utils/exception.utils.js.map +0 -1
  143. package/build/esm/utils/fs.utils.js.map +0 -1
  144. package/build/esm/utils/http-status-codes.js.map +0 -1
  145. package/build/esm/utils/id.utils.js.map +0 -1
  146. package/build/esm/utils/logger.utils.js.map +0 -1
  147. package/build/esm/utils/middleware.utils.js.map +0 -1
  148. package/build/esm/utils/obj.utils.js.map +0 -1
  149. package/build/esm/utils/performance.utils.js.map +0 -1
  150. package/build/esm/utils/request.utils.js.map +0 -1
  151. package/build/esm/utils/response.utils.js.map +0 -1
  152. package/build/esm/utils/stream.utils.js.map +0 -1
  153. package/build/esm/utils/string.utils.js.map +0 -1
  154. package/build/esm/utils/type.utils.js.map +0 -1
  155. package/build/esm/utils/url.utils.js.map +0 -1
  156. package/build/esm/utils/validate.utils.js.map +0 -1
  157. package/build/esnext/config.js +0 -133
  158. package/build/esnext/config.js.map +0 -1
  159. package/build/esnext/index.js +0 -50
  160. package/build/esnext/index.js.map +0 -1
  161. package/build/esnext/servers/server.builder.js +0 -657
  162. package/build/esnext/servers/server.builder.js.map +0 -1
  163. package/build/esnext/servers/server.d.ts +0 -256
  164. package/build/esnext/servers/server.js +0 -955
  165. package/build/esnext/servers/server.js.map +0 -1
  166. package/build/esnext/types/api-response.d.ts +0 -152
  167. package/build/esnext/types/api-response.js +0 -34
  168. package/build/esnext/types/api-response.js.map +0 -1
  169. package/build/esnext/types/index.d.ts +0 -125
  170. package/build/esnext/types/index.js +0 -25
  171. package/build/esnext/types/index.js.map +0 -1
  172. package/build/esnext/types/server.d.ts +0 -268
  173. package/build/esnext/types/server.js +0 -25
  174. package/build/esnext/types/server.js.map +0 -1
  175. package/build/esnext/utils/array.utils.d.ts +0 -168
  176. package/build/esnext/utils/array.utils.js +0 -345
  177. package/build/esnext/utils/array.utils.js.map +0 -1
  178. package/build/esnext/utils/async.utils.d.ts +0 -265
  179. package/build/esnext/utils/async.utils.js +0 -620
  180. package/build/esnext/utils/async.utils.js.map +0 -1
  181. package/build/esnext/utils/cache.utils.js +0 -293
  182. package/build/esnext/utils/cache.utils.js.map +0 -1
  183. package/build/esnext/utils/context-store.utils.js +0 -289
  184. package/build/esnext/utils/context-store.utils.js.map +0 -1
  185. package/build/esnext/utils/crypto.utils.js +0 -276
  186. package/build/esnext/utils/crypto.utils.js.map +0 -1
  187. package/build/esnext/utils/date.utils.d.ts +0 -159
  188. package/build/esnext/utils/date.utils.js +0 -384
  189. package/build/esnext/utils/date.utils.js.map +0 -1
  190. package/build/esnext/utils/decorators.utils.d.ts +0 -508
  191. package/build/esnext/utils/decorators.utils.js +0 -877
  192. package/build/esnext/utils/decorators.utils.js.map +0 -1
  193. package/build/esnext/utils/dir.utils.js +0 -477
  194. package/build/esnext/utils/dir.utils.js.map +0 -1
  195. package/build/esnext/utils/env.utils.js +0 -785
  196. package/build/esnext/utils/env.utils.js.map +0 -1
  197. package/build/esnext/utils/exception.utils.d.ts +0 -230
  198. package/build/esnext/utils/exception.utils.js +0 -381
  199. package/build/esnext/utils/exception.utils.js.map +0 -1
  200. package/build/esnext/utils/fs.utils.d.ts +0 -164
  201. package/build/esnext/utils/fs.utils.js +0 -349
  202. package/build/esnext/utils/fs.utils.js.map +0 -1
  203. package/build/esnext/utils/http-status-codes.js +0 -295
  204. package/build/esnext/utils/http-status-codes.js.map +0 -1
  205. package/build/esnext/utils/id.utils.js +0 -84
  206. package/build/esnext/utils/id.utils.js.map +0 -1
  207. package/build/esnext/utils/logger.utils.d.ts +0 -160
  208. package/build/esnext/utils/logger.utils.js +0 -300
  209. package/build/esnext/utils/logger.utils.js.map +0 -1
  210. package/build/esnext/utils/middleware.utils.js +0 -236
  211. package/build/esnext/utils/middleware.utils.js.map +0 -1
  212. package/build/esnext/utils/obj.utils.js +0 -413
  213. package/build/esnext/utils/obj.utils.js.map +0 -1
  214. package/build/esnext/utils/performance.utils.d.ts +0 -136
  215. package/build/esnext/utils/performance.utils.js +0 -271
  216. package/build/esnext/utils/performance.utils.js.map +0 -1
  217. package/build/esnext/utils/request.utils.js +0 -186
  218. package/build/esnext/utils/request.utils.js.map +0 -1
  219. package/build/esnext/utils/response.utils.js +0 -247
  220. package/build/esnext/utils/response.utils.js.map +0 -1
  221. package/build/esnext/utils/stream.utils.js +0 -210
  222. package/build/esnext/utils/stream.utils.js.map +0 -1
  223. package/build/esnext/utils/string.utils.js +0 -165
  224. package/build/esnext/utils/string.utils.js.map +0 -1
  225. package/build/esnext/utils/type.utils.d.ts +0 -90
  226. package/build/esnext/utils/type.utils.js +0 -187
  227. package/build/esnext/utils/type.utils.js.map +0 -1
  228. package/build/esnext/utils/url.utils.d.ts +0 -141
  229. package/build/esnext/utils/url.utils.js +0 -304
  230. package/build/esnext/utils/url.utils.js.map +0 -1
  231. package/build/esnext/utils/validate.utils.d.ts +0 -177
  232. package/build/esnext/utils/validate.utils.js +0 -320
  233. package/build/esnext/utils/validate.utils.js.map +0 -1
  234. package/build/src/config.d.ts +0 -122
  235. package/build/src/config.js.map +0 -1
  236. package/build/src/index.d.ts +0 -27
  237. package/build/src/index.js.map +0 -1
  238. package/build/src/servers/server.builder.d.ts +0 -508
  239. package/build/src/servers/server.builder.js.map +0 -1
  240. package/build/src/servers/server.js.map +0 -1
  241. package/build/src/types/api-response.js.map +0 -1
  242. package/build/src/types/index.js.map +0 -1
  243. package/build/src/types/server.js.map +0 -1
  244. package/build/src/utils/array.utils.js.map +0 -1
  245. package/build/src/utils/async.utils.js.map +0 -1
  246. package/build/src/utils/cache.utils.d.ts +0 -153
  247. package/build/src/utils/cache.utils.js.map +0 -1
  248. package/build/src/utils/context-store.utils.d.ts +0 -189
  249. package/build/src/utils/context-store.utils.js.map +0 -1
  250. package/build/src/utils/crypto.utils.d.ts +0 -160
  251. package/build/src/utils/crypto.utils.js.map +0 -1
  252. package/build/src/utils/date.utils.js.map +0 -1
  253. package/build/src/utils/decorators.utils.js.map +0 -1
  254. package/build/src/utils/dir.utils.d.ts +0 -196
  255. package/build/src/utils/dir.utils.js.map +0 -1
  256. package/build/src/utils/env.utils.d.ts +0 -377
  257. package/build/src/utils/env.utils.js.map +0 -1
  258. package/build/src/utils/exception.utils.js.map +0 -1
  259. package/build/src/utils/fs.utils.js.map +0 -1
  260. package/build/src/utils/http-status-codes.d.ts +0 -266
  261. package/build/src/utils/http-status-codes.js.map +0 -1
  262. package/build/src/utils/id.utils.d.ts +0 -36
  263. package/build/src/utils/id.utils.js.map +0 -1
  264. package/build/src/utils/logger.utils.js.map +0 -1
  265. package/build/src/utils/middleware.utils.d.ts +0 -100
  266. package/build/src/utils/middleware.utils.js.map +0 -1
  267. package/build/src/utils/obj.utils.d.ts +0 -124
  268. package/build/src/utils/obj.utils.js.map +0 -1
  269. package/build/src/utils/performance.utils.js.map +0 -1
  270. package/build/src/utils/request.utils.d.ts +0 -86
  271. package/build/src/utils/request.utils.js.map +0 -1
  272. package/build/src/utils/response.utils.d.ts +0 -163
  273. package/build/src/utils/response.utils.js.map +0 -1
  274. package/build/src/utils/stream.utils.d.ts +0 -88
  275. package/build/src/utils/stream.utils.js.map +0 -1
  276. package/build/src/utils/string.utils.d.ts +0 -93
  277. package/build/src/utils/string.utils.js.map +0 -1
  278. package/build/src/utils/type.utils.js.map +0 -1
  279. package/build/src/utils/url.utils.js.map +0 -1
  280. package/build/src/utils/validate.utils.js.map +0 -1
@@ -1,289 +0,0 @@
1
- /*
2
- * The MIT License
3
- *
4
- * Copyright (c) 2025 Catbee Technologies. https://catbee-utils.npm.hprasath.com/license
5
- *
6
- * Permission is hereby granted, free of charge, to any person obtaining a copy
7
- * of this software and associated documentation files (the "Software"), to deal
8
- * in the Software without restriction, including without limitation the rights
9
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
- * copies of the Software, and to permit persons to whom the Software is
11
- * furnished to do so, subject to the following conditions:
12
- *
13
- * The above copyright notice and this permission notice shall be included in all
14
- * copies or substantial portions of the Software.
15
- *
16
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
- * SOFTWARE.
23
- */
24
- import { AsyncLocalStorage } from 'async_hooks';
25
- /**
26
- * Predefined symbols used as keys in AsyncLocalStorage.
27
- * Add new symbols here to avoid duplication.
28
- */
29
- export const StoreKeys = {
30
- LOGGER: Symbol('LOGGER'),
31
- REQUEST_ID: Symbol('REQUEST_ID'),
32
- USER: Symbol('USER'),
33
- SESSION: Symbol('SESSION'),
34
- TRANSACTION_ID: Symbol('TRANSACTION_ID'),
35
- USER_ID: Symbol('USER_ID'),
36
- TENANT_ID: Symbol('TENANT_ID'),
37
- TRACE_ID: Symbol('TRACE_ID'),
38
- CORRELATION_ID: Symbol('CORRELATION_ID')
39
- };
40
- /**
41
- * Retrieves the current request ID from the async context, if available.
42
- *
43
- * @returns {string | undefined} The request ID string or undefined if not present in the current context.
44
- */
45
- export function getRequestId() {
46
- return ContextStore.get(StoreKeys.REQUEST_ID);
47
- }
48
- /**
49
- * Type-safe getter for common context values.
50
- *
51
- * @param key The store key symbol
52
- * @returns The typed value from the store
53
- */
54
- export function getFromContext(key) {
55
- return ContextStore.get(key);
56
- }
57
- /**
58
- * ContextStore manages per-request scoped context using AsyncLocalStorage.
59
- * It allows storing and retrieving data across async calls (e.g., request ID, logger).
60
- *
61
- * Example (Express middleware):
62
- * ```
63
- * // Middleware to initialize context and logger
64
- * app.use((req, res, next) => {
65
- * const requestId = req.headers["x-request-id"]?.toString() || crypto.randomUUID();
66
- * ContextStore.run({ [StoreKeys.REQUEST_ID]: requestId }, () => {
67
- * ContextStore.set(StoreKeys.LOGGER, getLogger().child({ requestId }));
68
- * next();
69
- * });
70
- * });
71
- * ```
72
- */
73
- export class ContextStore {
74
- /**
75
- * Returns the raw AsyncLocalStorage instance for advanced access.
76
- *
77
- * @returns {AsyncLocalStorage<Store>} The AsyncLocalStorage instance.
78
- */
79
- static getInstance() {
80
- return this.storage;
81
- }
82
- /**
83
- * Retrieves a value from the async context store by symbol key.
84
- *
85
- * @typeParam T - The expected return type of the value.
86
- * @param {symbol} key - Unique symbol used as the store key.
87
- * @returns {T | undefined} The value found (typed) or undefined if not present.
88
- */
89
- static get(key) {
90
- const store = this.storage.getStore();
91
- return store === null || store === void 0 ? void 0 : store[key];
92
- }
93
- /**
94
- * Sets a value in the current context store by symbol key.
95
- *
96
- * @typeParam T - The value type to set.
97
- * @param {symbol} key - Unique symbol key.
98
- * @param {T} value - Value to set in context.
99
- * @throws {Error} If called outside an active context (not within a .run call or in the wrong async boundaries).
100
- */
101
- static set(key, value) {
102
- const store = this.storage.getStore();
103
- if (!store) {
104
- throw new Error(`Failed to set ${String(key)}: AsyncLocalStorage store is not initialized.`);
105
- }
106
- store[key] = value;
107
- }
108
- /**
109
- * Retrieves the entire context store object for the current async context.
110
- *
111
- * @returns {Store | undefined} The current store object or undefined if called outside a context.
112
- */
113
- static getAll() {
114
- return this.storage.getStore();
115
- }
116
- /**
117
- * Initializes a new async context and executes a callback within it.
118
- * This must be called at the beginning of a request or logical async flow.
119
- *
120
- * @typeParam T - The callback's return type.
121
- * @param {Store} store - The initial key-value store object.
122
- * @param {() => T} callback - The function to run within the new context.
123
- * @returns {T} The result of the callback function.
124
- */
125
- static run(store, callback) {
126
- return this.storage.run(store, callback);
127
- }
128
- /**
129
- * Checks if a key exists in the current context store.
130
- *
131
- * @param {symbol} key - The symbol key to check.
132
- * @returns {boolean} True if the key exists, false otherwise.
133
- */
134
- static has(key) {
135
- const store = this.storage.getStore();
136
- return store !== undefined && key in store;
137
- }
138
- /**
139
- * Removes a value from the current context store by symbol key.
140
- *
141
- * @param {symbol} key - The symbol key to delete.
142
- * @returns {boolean} True if the key was deleted, false if the key wasn't found or no active context.
143
- * @throws {Error} If called outside an active context.
144
- */
145
- static delete(key) {
146
- const store = this.storage.getStore();
147
- if (!store) {
148
- throw new Error(`Failed to delete ${String(key)}: AsyncLocalStorage store is not initialized.`);
149
- }
150
- return delete store[key];
151
- }
152
- /**
153
- * Updates multiple values in the current context store at once.
154
- *
155
- * @param {Partial<Record<symbol, unknown>>} values - Object containing symbol keys and values to update.
156
- * @throws {Error} If called outside an active context.
157
- */
158
- static patch(values) {
159
- const store = this.storage.getStore();
160
- if (!store) {
161
- throw new Error('Failed to patch: AsyncLocalStorage store is not initialized.');
162
- }
163
- Object.getOwnPropertySymbols(values).forEach(key => {
164
- store[key] = values[key];
165
- });
166
- }
167
- /**
168
- * Executes a callback with a temporary store value that only exists during execution.
169
- * Original store is restored after callback completes.
170
- *
171
- * @typeParam T - The callback's return type.
172
- * @param {symbol} key - The symbol key to temporarily set.
173
- * @param {unknown} value - The temporary value.
174
- * @param {() => T} callback - The function to execute with the temporary value.
175
- * @returns {T} The result of the callback function.
176
- * @throws {Error} If called outside an active context.
177
- */
178
- static withValue(key, value, callback) {
179
- const store = this.storage.getStore();
180
- if (!store) {
181
- throw new Error(`Failed to set temporary value: AsyncLocalStorage store is not initialized.`);
182
- }
183
- // Save original value
184
- const hasOriginal = key in store;
185
- const originalValue = store[key];
186
- // Set temporary value
187
- store[key] = value;
188
- try {
189
- // Run callback
190
- return callback();
191
- }
192
- finally {
193
- // Restore original value
194
- if (hasOriginal) {
195
- store[key] = originalValue;
196
- }
197
- else {
198
- delete store[key];
199
- }
200
- }
201
- }
202
- /**
203
- * Creates a new context that inherits values from the current context.
204
- *
205
- * @typeParam T - The callback's return type.
206
- * @param {Partial<Record<symbol, unknown>>} newValues - New values to add to or override in the context.
207
- * @param {() => T} callback - The function to execute in the new context.
208
- * @returns {T} The result of the callback function.
209
- */
210
- static extend(newValues, callback) {
211
- const currentStore = this.storage.getStore() || {};
212
- // Create new store with current values plus new ones
213
- const newStore = Object.assign({}, currentStore);
214
- // Add new values
215
- Object.getOwnPropertySymbols(newValues).forEach(key => {
216
- newStore[key] = newValues[key];
217
- });
218
- // Run with extended store
219
- return this.storage.run(newStore, callback);
220
- }
221
- /**
222
- * Creates Express middleware that initializes a context for each request.
223
- *
224
- * @param {(req: any) => Partial<Record<symbol, unknown>>} initialValuesFactory - Function that returns initial context values.
225
- * @returns Express middleware function.
226
- */
227
- static createExpressMiddleware(initialValuesFactory = () => ({})) {
228
- return (req, res, next) => {
229
- const initialValues = initialValuesFactory(req);
230
- ContextStore.run(initialValues, next);
231
- };
232
- }
233
- }
234
- /**
235
- * The underlying AsyncLocalStorage instance for context.
236
- * @private
237
- */
238
- ContextStore.storage = new AsyncLocalStorage();
239
- /**
240
- * Type-safe wrapper for accessing and modifying context values with specific types.
241
- *
242
- * @typeParam T - The value type.
243
- */
244
- export class TypedContextKey {
245
- /**
246
- * Creates a new typed context key.
247
- *
248
- * @param symbol - The unique symbol for this key
249
- * @param defaultValue - Optional default value if key is not found
250
- */
251
- constructor(symbol, defaultValue) {
252
- this.symbol = symbol;
253
- this.defaultValue = defaultValue;
254
- }
255
- /**
256
- * Gets the current value for this key.
257
- *
258
- * @returns The value or defaultValue if not found
259
- */
260
- get() {
261
- const value = ContextStore.get(this.symbol);
262
- return value !== undefined ? value : this.defaultValue;
263
- }
264
- /**
265
- * Sets the value for this key.
266
- *
267
- * @param value The value to set
268
- */
269
- set(value) {
270
- ContextStore.set(this.symbol, value);
271
- }
272
- /**
273
- * Checks if this key exists in the context.
274
- *
275
- * @returns True if the key exists
276
- */
277
- exists() {
278
- return ContextStore.has(this.symbol);
279
- }
280
- /**
281
- * Deletes this key from the context.
282
- *
283
- * @returns True if the key was deleted
284
- */
285
- delete() {
286
- return ContextStore.delete(this.symbol);
287
- }
288
- }
289
- //# sourceMappingURL=context-store.utils.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"context-store.utils.js","sourceRoot":"","sources":["../../../src/utils/context-store.utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAUhD;;;GAGG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG;IACvB,MAAM,EAAE,MAAM,CAAC,QAAQ,CAAC;IACxB,UAAU,EAAE,MAAM,CAAC,YAAY,CAAC;IAChC,IAAI,EAAE,MAAM,CAAC,MAAM,CAAC;IACpB,OAAO,EAAE,MAAM,CAAC,SAAS,CAAC;IAC1B,cAAc,EAAE,MAAM,CAAC,gBAAgB,CAAC;IACxC,OAAO,EAAE,MAAM,CAAC,SAAS,CAAC;IAC1B,SAAS,EAAE,MAAM,CAAC,WAAW,CAAC;IAC9B,QAAQ,EAAE,MAAM,CAAC,UAAU,CAAC;IAC5B,cAAc,EAAE,MAAM,CAAC,gBAAgB,CAAC;CACzC,CAAC;AAEF;;;;GAIG;AACH,MAAM,UAAU,YAAY;IAC1B,OAAO,YAAY,CAAC,GAAG,CAAS,SAAS,CAAC,UAAU,CAAC,CAAC;AACxD,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,cAAc,CAAI,GAAW;IAC3C,OAAO,YAAY,CAAC,GAAG,CAAI,GAAG,CAAC,CAAC;AAClC,CAAC;AAED;;;;;;;;;;;;;;;GAeG;AACH,MAAM,OAAO,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,KAA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vC,CAAC;IAED;;;;OAIG;IACH,MAAM;QACJ,OAAO,YAAY,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAC1C,CAAC;CACF","sourcesContent":["/*\n * The MIT License\n *\n * Copyright (c) 2025 Catbee Technologies. https://catbee-utils.npm.hprasath.com/license\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { 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('REQUEST_ID'),\n USER: Symbol('USER'),\n SESSION: Symbol('SESSION'),\n TRANSACTION_ID: Symbol('TRANSACTION_ID'),\n USER_ID: Symbol('USER_ID'),\n TENANT_ID: Symbol('TENANT_ID'),\n TRACE_ID: Symbol('TRACE_ID'),\n CORRELATION_ID: Symbol('CORRELATION_ID')\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({ 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,276 +0,0 @@
1
- /*
2
- * The MIT License
3
- *
4
- * Copyright (c) 2025 Catbee Technologies. https://catbee-utils.npm.hprasath.com/license
5
- *
6
- * Permission is hereby granted, free of charge, to any person obtaining a copy
7
- * of this software and associated documentation files (the "Software"), to deal
8
- * in the Software without restriction, including without limitation the rights
9
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
- * copies of the Software, and to permit persons to whom the Software is
11
- * furnished to do so, subject to the following conditions:
12
- *
13
- * The above copyright notice and this permission notice shall be included in all
14
- * copies or substantial portions of the Software.
15
- *
16
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
- * SOFTWARE.
23
- */
24
- import { createHmac, createHash, randomBytes, createCipheriv, createDecipheriv, scrypt, timingSafeEqual } from 'crypto';
25
- import { promisify } from 'util';
26
- import { uuid } from './id.utils';
27
- /**
28
- * Generates an HMAC digest using the specified algorithm and secret key.
29
- *
30
- * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'sha1').
31
- * @param {string} input - The string to hash.
32
- * @param {string} secret - The secret key for HMAC.
33
- * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).
34
- * @returns {string} HMAC digest as a string.
35
- */
36
- export function hmac(algorithm, input, secret, encoding = 'hex') {
37
- return createHmac(algorithm, secret).update(input).digest(encoding);
38
- }
39
- /**
40
- * Generates a hash digest using the specified algorithm.
41
- *
42
- * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'md5').
43
- * @param {string} input - The string to hash.
44
- * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).
45
- * @returns {string} Hash digest as a string.
46
- */
47
- export function hash(algorithm, input, encoding = 'hex') {
48
- return createHash(algorithm).update(input).digest(encoding);
49
- }
50
- /**
51
- * Generates an HMAC-SHA256 digest.
52
- *
53
- * @param {string} input - The string to hash.
54
- * @param {string} secret - The secret key.
55
- * @returns {string} SHA-256 HMAC digest as a string.
56
- */
57
- export function sha256Hmac(input, secret) {
58
- return hmac('sha256', input, secret);
59
- }
60
- /**
61
- * Generates a SHA1 hash digest.
62
- *
63
- * @param {string} input - The string to hash.
64
- * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
65
- * @returns {string} SHA-1 hash as a string.
66
- */
67
- export function sha1(input, encoding = 'hex') {
68
- return hash('sha1', input, encoding);
69
- }
70
- /**
71
- * Generates a SHA256 hash digest.
72
- *
73
- * @param {string} input - The string to hash.
74
- * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
75
- * @returns {string} SHA-256 hash as a string.
76
- */
77
- export function sha256(input, encoding = 'hex') {
78
- return hash('sha256', input, encoding);
79
- }
80
- /**
81
- * Generates an MD5 hash digest.
82
- *
83
- * @param {string} input - The string to hash.
84
- * @returns {string} MD5 hash as a string.
85
- */
86
- export function md5(input) {
87
- return hash('md5', input);
88
- }
89
- /**
90
- * Generates a cryptographically strong random string by hashing a random UUID with SHA-256.
91
- *
92
- * @returns {string} Random string hashed with SHA-256 (hex encoding).
93
- */
94
- export function randomString() {
95
- return sha256(uuid());
96
- }
97
- /**
98
- * Generates a secure random buffer of specified byte length.
99
- *
100
- * @param {number} [byteLength=32] - Number of random bytes to generate.
101
- * @returns {Buffer} Buffer containing random bytes.
102
- */
103
- export function generateRandomBytes(byteLength = 32) {
104
- return randomBytes(byteLength);
105
- }
106
- /**
107
- * Generates a secure random string of specified byte length with specified encoding.
108
- *
109
- * @param {number} [byteLength=32] - Number of random bytes to generate.
110
- * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
111
- * @returns {string} Random string in specified encoding.
112
- */
113
- export function generateRandomBytesAsString(byteLength = 32, encoding = 'hex') {
114
- return randomBytes(byteLength).toString(encoding);
115
- }
116
- /**
117
- * Generates a secure API key with a specified format.
118
- *
119
- * @param {string} [prefix=''] - Optional prefix for the key.
120
- * @param {number} [byteLength=24] - Number of random bytes to generate.
121
- * @returns {string} Formatted API key.
122
- */
123
- export function generateApiKey(prefix = '', byteLength = 24) {
124
- const randomString = generateRandomBytesAsString(byteLength, 'base64');
125
- const key = randomString
126
- .replace(/[+/=]/g, '') // Remove non-URL-safe characters
127
- .substring(0, 32); // Limit length
128
- return prefix ? `${prefix}_${key}` : key;
129
- }
130
- /**
131
- * Compares two strings, arrays, or buffers in constant time to prevent timing attacks.
132
- *
133
- * @param {string | Buffer | Uint8Array} a - First value to compare
134
- * @param {string | Buffer | Uint8Array} b - Second value to compare
135
- * @returns {boolean} True if values are equal
136
- */
137
- export function safeCompare(a, b) {
138
- if (typeof a === 'string' && typeof b === 'string') {
139
- // Convert strings to buffers
140
- const bufA = Buffer.from(a);
141
- const bufB = Buffer.from(b);
142
- // Compare lengths first (not constant time, but prevents timing attack on contents)
143
- if (bufA.length !== bufB.length)
144
- return false;
145
- return timingSafeEqual(bufA, bufB);
146
- }
147
- else if ((a instanceof Buffer || a instanceof Uint8Array) && (b instanceof Buffer || b instanceof Uint8Array)) {
148
- // Compare lengths first
149
- if (a.length !== b.length)
150
- return false;
151
- return timingSafeEqual(a instanceof Buffer ? a : Buffer.from(a), b instanceof Buffer ? b : Buffer.from(b));
152
- }
153
- throw new Error('Cannot compare: inputs must be strings, Buffers, or Uint8Arrays');
154
- }
155
- // Promisified version of scrypt for key derivation
156
- const scryptAsync = promisify(scrypt);
157
- /**
158
- * Encrypts data using a symmetric key with secure defaults (AES-256-GCM).
159
- *
160
- * @param {string | Buffer} data - Data to encrypt
161
- * @param {string | Buffer} key - Encryption key or passphrase
162
- * @param {EncryptionOptions} [options] - Encryption options
163
- * @returns {Promise<EncryptionResult>} Encrypted data with metadata
164
- */
165
- export async function encrypt(data, key, options = {}) {
166
- const algorithm = options.algorithm || 'aes-256-gcm';
167
- const inputEncoding = options.inputEncoding || 'utf8';
168
- const outputEncoding = options.outputEncoding || 'hex';
169
- // Generate a random IV
170
- const iv = randomBytes(16);
171
- // Derive key using scrypt if key is a string (passphrase)
172
- const derivedKey = typeof key === 'string' ? await scryptAsync(key, iv.slice(0, 8), 32) : key;
173
- // Create cipher
174
- const cipher = createCipheriv(algorithm, derivedKey, iv);
175
- // Encrypt the data
176
- let ciphertext;
177
- if (typeof data === 'string') {
178
- ciphertext = cipher.update(data, inputEncoding, outputEncoding);
179
- ciphertext += cipher.final(outputEncoding);
180
- }
181
- else {
182
- const encrypted = Buffer.concat([cipher.update(data), cipher.final()]);
183
- ciphertext = outputEncoding ? encrypted.toString(outputEncoding) : encrypted;
184
- }
185
- // Get authentication tag if using GCM mode
186
- const authTag = algorithm.includes('gcm') ? cipher.getAuthTag() : undefined;
187
- return {
188
- ciphertext,
189
- iv,
190
- authTag,
191
- algorithm
192
- };
193
- }
194
- /**
195
- * Decrypts data that was encrypted with the encrypt function.
196
- *
197
- * @param {EncryptionResult} encryptedData - The encrypted data and metadata
198
- * @param {string | Buffer} key - Decryption key or passphrase
199
- * @param {DecryptionOptions} [options] - Decryption options
200
- * @returns {Promise<string | Buffer>} Decrypted data
201
- */
202
- export async function decrypt(encryptedData, key, options = {}) {
203
- const algorithm = options.algorithm || encryptedData.algorithm || 'aes-256-gcm';
204
- const inputEncoding = options.inputEncoding || 'hex';
205
- const outputEncoding = options.outputEncoding || 'utf8';
206
- // Derive key using scrypt if key is a string (passphrase)
207
- const derivedKey = typeof key === 'string' ? await scryptAsync(key, encryptedData.iv.slice(0, 8), 32) : key;
208
- // Create decipher
209
- const decipher = createDecipheriv(algorithm, derivedKey, encryptedData.iv);
210
- // Set auth tag if using GCM mode
211
- if (encryptedData.authTag && algorithm.includes('gcm')) {
212
- decipher.setAuthTag(encryptedData.authTag);
213
- }
214
- // Decrypt the data
215
- let decrypted;
216
- if (typeof encryptedData.ciphertext === 'string') {
217
- decrypted = decipher.update(encryptedData.ciphertext, inputEncoding, outputEncoding);
218
- decrypted += decipher.final(outputEncoding);
219
- }
220
- else {
221
- const result = Buffer.concat([decipher.update(encryptedData.ciphertext), decipher.final()]);
222
- decrypted = outputEncoding ? result.toString(outputEncoding) : result;
223
- }
224
- return decrypted;
225
- }
226
- /**
227
- * Creates a signed token with an expiration time and payload.
228
- *
229
- * @param {object} payload - Data to include in the token
230
- * @param {string} secret - Secret key for signing
231
- * @param {number} [expiresInSeconds=3600] - Token expiration in seconds
232
- * @returns {string} Signed token string
233
- */
234
- export function createSignedToken(payload, secret, expiresInSeconds = 3600) {
235
- // Create payload with expiration
236
- const tokenPayload = Object.assign(Object.assign({}, payload), { exp: Math.floor(Date.now() / 1000) + expiresInSeconds });
237
- // Convert to string
238
- const payloadStr = JSON.stringify(tokenPayload);
239
- // Base64 encode the payload
240
- const base64Payload = Buffer.from(payloadStr).toString('base64url');
241
- // Create signature
242
- const signature = hmac('sha256', base64Payload, secret, 'base64url');
243
- // Combine payload and signature
244
- return `${base64Payload}.${signature}`;
245
- }
246
- /**
247
- * Verifies and decodes a signed token.
248
- *
249
- * @param {string} token - The token to verify
250
- * @param {string} secret - Secret key for verification
251
- * @returns {object | null} Decoded payload if valid, null if invalid
252
- */
253
- export function verifySignedToken(token, secret) {
254
- try {
255
- // Split token into parts
256
- const [payloadB64, signature] = token.split('.');
257
- if (!payloadB64 || !signature)
258
- return null;
259
- // Verify signature
260
- const expectedSignature = hmac('sha256', payloadB64, secret, 'base64url');
261
- if (!safeCompare(signature, expectedSignature))
262
- return null;
263
- // Decode payload
264
- const payloadStr = Buffer.from(payloadB64, 'base64url').toString('utf8');
265
- const payload = JSON.parse(payloadStr);
266
- // Check expiration
267
- if (payload.exp && payload.exp < Math.floor(Date.now() / 1000)) {
268
- return null;
269
- }
270
- return payload;
271
- }
272
- catch (_a) {
273
- return null;
274
- }
275
- }
276
- //# sourceMappingURL=crypto.utils.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"crypto.utils.js","sourceRoot":"","sources":["../../../src/utils/crypto.utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EACL,UAAU,EACV,UAAU,EAEV,WAAW,EACX,cAAc,EACd,gBAAgB,EAChB,MAAM,EACN,eAAe,EAEhB,MAAM,QAAQ,CAAC;AAChB,OAAO,EAAE,SAAS,EAAE,MAAM,MAAM,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAgBlC;;;;;;;;GAQG;AACH,MAAM,UAAU,IAAI,CAAC,SAAiB,EAAE,KAAa,EAAE,MAAc,EAAE,WAAiC,KAAK;IAC3G,OAAO,UAAU,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AACtE,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,IAAI,CAAC,SAAiB,EAAE,KAAa,EAAE,WAAiC,KAAK;IAC3F,OAAO,UAAU,CAAC,SAAS,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AAC9D,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,UAAU,CAAC,KAAa,EAAE,MAAc;IACtD,OAAO,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I,CAAC,WAAW,CAAC,SAAS,EAAE,iBAAiB,CAAC;YAAE,OAAO,IAAI,CAAC;QAE5D,iBAAiB;QACjB,MAAM,UAAU,GAAG,MAAM,CAAC,IAAI,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;QACzE,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;QAEvC,mBAAmB;QACnB,IAAI,OAAO,CAAC,GAAG,IAAI,OAAO,CAAC,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,EAAE,CAAC;YAC/D,OAAO,IAAI,CAAC;QACd,CAAC;QAED,OAAO,OAAO,CAAC;IACjB,CAAC;IAAC,WAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["/*\n * The MIT License\n *\n * Copyright (c) 2025 Catbee Technologies. https://catbee-utils.npm.hprasath.com/license\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport {\n createHmac,\n createHash,\n BinaryToTextEncoding,\n randomBytes,\n createCipheriv,\n createDecipheriv,\n scrypt,\n timingSafeEqual,\n CipherGCMTypes\n} from 'crypto';\nimport { promisify } from 'util';\nimport { uuid } from './id.utils';\n\nexport type BufferEncoding =\n | 'ascii'\n | 'utf8'\n | 'utf-8'\n | 'utf16le'\n | 'utf-16le'\n | 'ucs2'\n | 'ucs-2'\n | 'base64'\n | 'base64url'\n | 'latin1'\n | 'binary'\n | 'hex';\n\n/**\n * Generates an HMAC digest using the specified algorithm and secret key.\n *\n * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'sha1').\n * @param {string} input - The string to hash.\n * @param {string} secret - The secret key for HMAC.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).\n * @returns {string} HMAC digest as a string.\n */\nexport function hmac(algorithm: string, input: string, secret: string, encoding: BinaryToTextEncoding = 'hex'): string {\n return createHmac(algorithm, secret).update(input).digest(encoding);\n}\n\n/**\n * Generates a hash digest using the specified algorithm.\n *\n * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'md5').\n * @param {string} input - The string to hash.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).\n * @returns {string} Hash digest as a string.\n */\nexport function hash(algorithm: string, input: string, encoding: BinaryToTextEncoding = 'hex'): string {\n return createHash(algorithm).update(input).digest(encoding);\n}\n\n/**\n * Generates an HMAC-SHA256 digest.\n *\n * @param {string} input - The string to hash.\n * @param {string} secret - The secret key.\n * @returns {string} SHA-256 HMAC digest as a string.\n */\nexport function sha256Hmac(input: string, secret: string): string {\n return hmac('sha256', input, secret);\n}\n\n/**\n * Generates a SHA1 hash digest.\n *\n * @param {string} input - The string to hash.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.\n * @returns {string} SHA-1 hash as a string.\n */\nexport function sha1(input: string, encoding: BinaryToTextEncoding = 'hex'): string {\n return hash('sha1', input, encoding);\n}\n\n/**\n * Generates a SHA256 hash digest.\n *\n * @param {string} input - The string to hash.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.\n * @returns {string} SHA-256 hash as a string.\n */\nexport function sha256(input: string, encoding: BinaryToTextEncoding = 'hex'): string {\n return hash('sha256', input, encoding);\n}\n\n/**\n * Generates an MD5 hash digest.\n *\n * @param {string} input - The string to hash.\n * @returns {string} MD5 hash as a string.\n */\nexport function md5(input: string): string {\n return hash('md5', input);\n}\n\n/**\n * Generates a cryptographically strong random string by hashing a random UUID with SHA-256.\n *\n * @returns {string} Random string hashed with SHA-256 (hex encoding).\n */\nexport function randomString(): string {\n return sha256(uuid());\n}\n\n/**\n * Generates a secure random buffer of specified byte length.\n *\n * @param {number} [byteLength=32] - Number of random bytes to generate.\n * @returns {Buffer} Buffer containing random bytes.\n */\nexport function generateRandomBytes(byteLength: number = 32): Buffer {\n return randomBytes(byteLength);\n}\n\n/**\n * Generates a secure random string of specified byte length with specified encoding.\n *\n * @param {number} [byteLength=32] - Number of random bytes to generate.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.\n * @returns {string} Random string in specified encoding.\n */\nexport function generateRandomBytesAsString(byteLength: number = 32, encoding: BinaryToTextEncoding = 'hex'): string {\n return randomBytes(byteLength).toString(encoding);\n}\n\n/**\n * Generates a secure API key with a specified format.\n *\n * @param {string} [prefix=''] - Optional prefix for the key.\n * @param {number} [byteLength=24] - Number of random bytes to generate.\n * @returns {string} Formatted API key.\n */\nexport function generateApiKey(prefix: string = '', byteLength: number = 24): string {\n const randomString = generateRandomBytesAsString(byteLength, 'base64');\n const key = randomString\n .replace(/[+/=]/g, '') // Remove non-URL-safe characters\n .substring(0, 32); // Limit length\n\n return prefix ? `${prefix}_${key}` : key;\n}\n\n/**\n * Compares two strings, arrays, or buffers in constant time to prevent timing attacks.\n *\n * @param {string | Buffer | Uint8Array} a - First value to compare\n * @param {string | Buffer | Uint8Array} b - Second value to compare\n * @returns {boolean} True if values are equal\n */\nexport function safeCompare(a: string | Buffer | Uint8Array, b: string | Buffer | Uint8Array): boolean {\n if (typeof a === 'string' && typeof b === 'string') {\n // Convert strings to buffers\n const bufA = Buffer.from(a);\n const bufB = Buffer.from(b);\n\n // Compare lengths first (not constant time, but prevents timing attack on contents)\n if (bufA.length !== bufB.length) return false;\n\n return timingSafeEqual(bufA, bufB);\n } else if ((a instanceof Buffer || a instanceof Uint8Array) && (b instanceof Buffer || b instanceof Uint8Array)) {\n // Compare lengths first\n if (a.length !== b.length) return false;\n\n return timingSafeEqual(a instanceof Buffer ? a : Buffer.from(a), b instanceof Buffer ? b : Buffer.from(b));\n }\n\n throw new Error('Cannot compare: inputs must be strings, Buffers, or Uint8Arrays');\n}\n\n/**\n * Interface for encryption options\n */\nexport interface EncryptionOptions {\n /** Algorithm to use (default: aes-256-gcm) */\n algorithm?: CipherGCMTypes;\n /** Input encoding for plaintext if string (default: utf8) */\n inputEncoding?: BufferEncoding;\n /** Output encoding for ciphertext (default: hex) */\n outputEncoding?: BinaryToTextEncoding;\n}\n\n/**\n * Interface for decryption options\n */\nexport interface DecryptionOptions {\n /** Algorithm to use (default: aes-256-gcm) */\n algorithm?: CipherGCMTypes;\n /** Input encoding for ciphertext if string (default: hex) */\n inputEncoding?: BinaryToTextEncoding;\n /** Output encoding for plaintext (default: utf8) */\n outputEncoding?: BufferEncoding;\n}\n\n/**\n * Result of encryption operation including all data needed for decryption\n */\nexport interface EncryptionResult {\n /** Encrypted data (string or Buffer based on options) */\n ciphertext: string | Buffer;\n /** Initialization vector */\n iv: Buffer;\n /** Authentication tag (for GCM mode) */\n authTag?: Buffer;\n /** Algorithm used */\n algorithm: string;\n}\n\n// Promisified version of scrypt for key derivation\nconst scryptAsync = promisify<string | Buffer, string | Buffer, number, Buffer>(scrypt);\n\n/**\n * Encrypts data using a symmetric key with secure defaults (AES-256-GCM).\n *\n * @param {string | Buffer} data - Data to encrypt\n * @param {string | Buffer} key - Encryption key or passphrase\n * @param {EncryptionOptions} [options] - Encryption options\n * @returns {Promise<EncryptionResult>} Encrypted data with metadata\n */\nexport async function encrypt(\n data: string | Buffer,\n key: string | Buffer,\n options: EncryptionOptions = {}\n): Promise<EncryptionResult> {\n const algorithm = options.algorithm || 'aes-256-gcm';\n const inputEncoding = options.inputEncoding || 'utf8';\n const outputEncoding = options.outputEncoding || 'hex';\n\n // Generate a random IV\n const iv = randomBytes(16);\n\n // Derive key using scrypt if key is a string (passphrase)\n const derivedKey = typeof key === 'string' ? await scryptAsync(key, iv.slice(0, 8), 32) : key;\n\n // Create cipher\n const cipher = createCipheriv(algorithm, derivedKey, iv);\n\n // Encrypt the data\n let ciphertext: string | Buffer;\n\n if (typeof data === 'string') {\n ciphertext = cipher.update(data, inputEncoding, outputEncoding as BufferEncoding);\n ciphertext += cipher.final(outputEncoding as BufferEncoding);\n } else {\n const encrypted = Buffer.concat([cipher.update(data), cipher.final()]);\n ciphertext = outputEncoding ? encrypted.toString(outputEncoding) : encrypted;\n }\n\n // Get authentication tag if using GCM mode\n const authTag = algorithm.includes('gcm') ? (cipher as any).getAuthTag() : undefined;\n\n return {\n ciphertext,\n iv,\n authTag,\n algorithm\n };\n}\n\n/**\n * Decrypts data that was encrypted with the encrypt function.\n *\n * @param {EncryptionResult} encryptedData - The encrypted data and metadata\n * @param {string | Buffer} key - Decryption key or passphrase\n * @param {DecryptionOptions} [options] - Decryption options\n * @returns {Promise<string | Buffer>} Decrypted data\n */\nexport async function decrypt(\n encryptedData: EncryptionResult,\n key: string | Buffer,\n options: DecryptionOptions = {}\n): Promise<string | Buffer> {\n const algorithm = options.algorithm || encryptedData.algorithm || 'aes-256-gcm';\n const inputEncoding = options.inputEncoding || 'hex';\n const outputEncoding = options.outputEncoding || 'utf8';\n\n // Derive key using scrypt if key is a string (passphrase)\n const derivedKey = typeof key === 'string' ? await scryptAsync(key, encryptedData.iv.slice(0, 8), 32) : key;\n\n // Create decipher\n const decipher = createDecipheriv(algorithm, derivedKey, encryptedData.iv);\n\n // Set auth tag if using GCM mode\n if (encryptedData.authTag && algorithm.includes('gcm')) {\n (decipher as any).setAuthTag(encryptedData.authTag);\n }\n\n // Decrypt the data\n let decrypted: string | Buffer;\n\n if (typeof encryptedData.ciphertext === 'string') {\n decrypted = decipher.update(encryptedData.ciphertext, inputEncoding as BufferEncoding, outputEncoding);\n decrypted += decipher.final(outputEncoding);\n } else {\n const result = Buffer.concat([decipher.update(encryptedData.ciphertext), decipher.final()]);\n decrypted = outputEncoding ? result.toString(outputEncoding) : result;\n }\n\n return decrypted;\n}\n\n/**\n * Creates a signed token with an expiration time and payload.\n *\n * @param {object} payload - Data to include in the token\n * @param {string} secret - Secret key for signing\n * @param {number} [expiresInSeconds=3600] - Token expiration in seconds\n * @returns {string} Signed token string\n */\nexport function createSignedToken(\n payload: Record<string, any>,\n secret: string,\n expiresInSeconds: number = 3600\n): string {\n // Create payload with expiration\n const tokenPayload = {\n ...payload,\n exp: Math.floor(Date.now() / 1000) + expiresInSeconds\n };\n\n // Convert to string\n const payloadStr = JSON.stringify(tokenPayload);\n\n // Base64 encode the payload\n const base64Payload = Buffer.from(payloadStr).toString('base64url');\n\n // Create signature\n const signature = hmac('sha256', base64Payload, secret, 'base64url');\n\n // Combine payload and signature\n return `${base64Payload}.${signature}`;\n}\n\n/**\n * Verifies and decodes a signed token.\n *\n * @param {string} token - The token to verify\n * @param {string} secret - Secret key for verification\n * @returns {object | null} Decoded payload if valid, null if invalid\n */\nexport function verifySignedToken(token: string, secret: string): Record<string, any> | null {\n try {\n // Split token into parts\n const [payloadB64, signature] = token.split('.');\n\n if (!payloadB64 || !signature) return null;\n\n // Verify signature\n const expectedSignature = hmac('sha256', payloadB64, secret, 'base64url');\n if (!safeCompare(signature, expectedSignature)) return null;\n\n // Decode payload\n const payloadStr = Buffer.from(payloadB64, 'base64url').toString('utf8');\n const payload = JSON.parse(payloadStr);\n\n // Check expiration\n if (payload.exp && payload.exp < Math.floor(Date.now() / 1000)) {\n return null;\n }\n\n return payload;\n } catch {\n return null;\n }\n}\n"]}