@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,11 +1,15 @@
1
- import { AsyncLocalStorage } from "async_hooks";
1
+ import { AsyncLocalStorage } from 'async_hooks';
2
2
  /**
3
3
  * Predefined symbols used as keys in AsyncLocalStorage.
4
4
  * Add new symbols here to avoid duplication.
5
5
  */
6
6
  export const StoreKeys = {
7
- LOGGER: Symbol("logger"),
8
- REQUEST_ID: Symbol("requestId"),
7
+ LOGGER: Symbol('logger'),
8
+ REQUEST_ID: Symbol('requestId'),
9
+ USER_ID: Symbol('userId'),
10
+ TENANT_ID: Symbol('tenantId'),
11
+ TRACE_ID: Symbol('traceId'),
12
+ CORRELATION_ID: Symbol('correlationId')
9
13
  };
10
14
  /**
11
15
  * Retrieves the current request ID from the async context, if available.
@@ -15,6 +19,15 @@ export const StoreKeys = {
15
19
  export function getRequestId() {
16
20
  return ContextStore.get(StoreKeys.REQUEST_ID);
17
21
  }
22
+ /**
23
+ * Type-safe getter for common context values.
24
+ *
25
+ * @param key The store key symbol
26
+ * @returns The typed value from the store
27
+ */
28
+ export function getFromContext(key) {
29
+ return ContextStore.get(key);
30
+ }
18
31
  /**
19
32
  * ContextStore manages per-request scoped context using AsyncLocalStorage.
20
33
  * It allows storing and retrieving data across async calls (e.g., request ID, logger).
@@ -86,10 +99,165 @@ export class ContextStore {
86
99
  static run(store, callback) {
87
100
  return this.storage.run(store, callback);
88
101
  }
102
+ /**
103
+ * Checks if a key exists in the current context store.
104
+ *
105
+ * @param {symbol} key - The symbol key to check.
106
+ * @returns {boolean} True if the key exists, false otherwise.
107
+ */
108
+ static has(key) {
109
+ const store = this.storage.getStore();
110
+ return store !== undefined && key in store;
111
+ }
112
+ /**
113
+ * Removes a value from the current context store by symbol key.
114
+ *
115
+ * @param {symbol} key - The symbol key to delete.
116
+ * @returns {boolean} True if the key was deleted, false if the key wasn't found or no active context.
117
+ * @throws {Error} If called outside an active context.
118
+ */
119
+ static delete(key) {
120
+ const store = this.storage.getStore();
121
+ if (!store) {
122
+ throw new Error(`Failed to delete ${String(key)}: AsyncLocalStorage store is not initialized.`);
123
+ }
124
+ return delete store[key];
125
+ }
126
+ /**
127
+ * Updates multiple values in the current context store at once.
128
+ *
129
+ * @param {Partial<Record<symbol, unknown>>} values - Object containing symbol keys and values to update.
130
+ * @throws {Error} If called outside an active context.
131
+ */
132
+ static patch(values) {
133
+ const store = this.storage.getStore();
134
+ if (!store) {
135
+ throw new Error('Failed to patch: AsyncLocalStorage store is not initialized.');
136
+ }
137
+ Object.getOwnPropertySymbols(values).forEach(key => {
138
+ store[key] = values[key];
139
+ });
140
+ }
141
+ /**
142
+ * Executes a callback with a temporary store value that only exists during execution.
143
+ * Original store is restored after callback completes.
144
+ *
145
+ * @typeParam T - The callback's return type.
146
+ * @param {symbol} key - The symbol key to temporarily set.
147
+ * @param {unknown} value - The temporary value.
148
+ * @param {() => T} callback - The function to execute with the temporary value.
149
+ * @returns {T} The result of the callback function.
150
+ * @throws {Error} If called outside an active context.
151
+ */
152
+ static withValue(key, value, callback) {
153
+ const store = this.storage.getStore();
154
+ if (!store) {
155
+ throw new Error(`Failed to set temporary value: AsyncLocalStorage store is not initialized.`);
156
+ }
157
+ // Save original value
158
+ const hasOriginal = key in store;
159
+ const originalValue = store[key];
160
+ // Set temporary value
161
+ store[key] = value;
162
+ try {
163
+ // Run callback
164
+ return callback();
165
+ }
166
+ finally {
167
+ // Restore original value
168
+ if (hasOriginal) {
169
+ store[key] = originalValue;
170
+ }
171
+ else {
172
+ delete store[key];
173
+ }
174
+ }
175
+ }
176
+ /**
177
+ * Creates a new context that inherits values from the current context.
178
+ *
179
+ * @typeParam T - The callback's return type.
180
+ * @param {Partial<Record<symbol, unknown>>} newValues - New values to add to or override in the context.
181
+ * @param {() => T} callback - The function to execute in the new context.
182
+ * @returns {T} The result of the callback function.
183
+ */
184
+ static extend(newValues, callback) {
185
+ const currentStore = this.storage.getStore() || {};
186
+ // Create new store with current values plus new ones
187
+ const newStore = Object.assign({}, currentStore);
188
+ // Add new values
189
+ Object.getOwnPropertySymbols(newValues).forEach(key => {
190
+ newStore[key] = newValues[key];
191
+ });
192
+ // Run with extended store
193
+ return this.storage.run(newStore, callback);
194
+ }
195
+ /**
196
+ * Creates Express middleware that initializes a context for each request.
197
+ *
198
+ * @param {(req: any) => Partial<Record<symbol, unknown>>} initialValuesFactory - Function that returns initial context values.
199
+ * @returns Express middleware function.
200
+ */
201
+ static createExpressMiddleware(initialValuesFactory = () => ({})) {
202
+ return (req, res, next) => {
203
+ const initialValues = initialValuesFactory(req);
204
+ ContextStore.run(initialValues, next);
205
+ };
206
+ }
89
207
  }
90
208
  /**
91
209
  * The underlying AsyncLocalStorage instance for context.
92
210
  * @private
93
211
  */
94
212
  ContextStore.storage = new AsyncLocalStorage();
213
+ /**
214
+ * Type-safe wrapper for accessing and modifying context values with specific types.
215
+ *
216
+ * @typeParam T - The value type.
217
+ */
218
+ export class TypedContextKey {
219
+ /**
220
+ * Creates a new typed context key.
221
+ *
222
+ * @param symbol - The unique symbol for this key
223
+ * @param defaultValue - Optional default value if key is not found
224
+ */
225
+ constructor(symbol, defaultValue) {
226
+ this.symbol = symbol;
227
+ this.defaultValue = defaultValue;
228
+ }
229
+ /**
230
+ * Gets the current value for this key.
231
+ *
232
+ * @returns The value or defaultValue if not found
233
+ */
234
+ get() {
235
+ const value = ContextStore.get(this.symbol);
236
+ return value !== undefined ? value : this.defaultValue;
237
+ }
238
+ /**
239
+ * Sets the value for this key.
240
+ *
241
+ * @param value The value to set
242
+ */
243
+ set(value) {
244
+ ContextStore.set(this.symbol, value);
245
+ }
246
+ /**
247
+ * Checks if this key exists in the context.
248
+ *
249
+ * @returns True if the key exists
250
+ */
251
+ exists() {
252
+ return ContextStore.has(this.symbol);
253
+ }
254
+ /**
255
+ * Deletes this key from the context.
256
+ *
257
+ * @returns True if the key was deleted
258
+ */
259
+ delete() {
260
+ return ContextStore.delete(this.symbol);
261
+ }
262
+ }
95
263
  //# 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":"AAAA,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,WAAW,CAAC;CAChC,CAAC;AAEF;;;;GAIG;AACH,MAAM,UAAU,YAAY;IAC1B,OAAO,YAAY,CAAC,GAAG,CAAS,SAAS,CAAC,UAAU,CAAC,CAAC;AACxD,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,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;;AAjED;;;GAGG;AACqB,oBAAO,GAAG,IAAI,iBAAiB,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":"AAAA,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,WAAW,CAAC;IAC/B,OAAO,EAAE,MAAM,CAAC,QAAQ,CAAC;IAC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,CAAC;IACJ,CAAC;;AAjLD;;;GAGG;AACqB,oBAAO,GAAG,IAAI,iBAAiB,EAAS,CAAC;AAgLnE;;;;GAIG;AACH,MAAM,OAAO,eAAe;IAC1B;;;;;OAKG;IACH,YACU,MAAc,EACd,YAAgB;QADhB,WAAM,GAAN,MAAM,CAAQ;QACd,iBAAY,GAAZ,YAAY,CAAI;IACvB,CAAC;IAEJ;;;;OAIG;IACH,GAAG;QACD,MAAM,KAAK,GAAG,YAAY,CAAC,GAAG,CAAI,IAAI,CAAC,MAAM,CAAC,CAAC;QAC/C,OAAO,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,YAAY,CAAC;IACzD,CAAC;IAED;;;;OAIG;IACH,GAAG,CAAC,KAAQ;QACV,YAAY,CAAC,GAAG,CAAI,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IAC1C,CAAC;IAED;;;;OAIG;IACH,MAAM;QACJ,OAAO,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACvC,CAAC;IAED;;;;OAIG;IACH,MAAM;QACJ,OAAO,YAAY,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAC1C,CAAC;CACF","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
@@ -1,4 +1,5 @@
1
- import { createHmac, createHash, randomUUID, } from "crypto";
1
+ import { createHmac, createHash, randomUUID, randomBytes, createCipheriv, createDecipheriv, scrypt, timingSafeEqual } from 'crypto';
2
+ import { promisify } from 'util';
2
3
  /**
3
4
  * Generates an HMAC digest using the specified algorithm and secret key.
4
5
  *
@@ -8,9 +9,9 @@ import { createHmac, createHash, randomUUID, } 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 const hmac = (algorithm, input, secret, encoding = "hex") => {
12
+ export function hmac(algorithm, input, secret, encoding = 'hex') {
12
13
  return createHmac(algorithm, secret).update(input).digest(encoding);
13
- };
14
+ }
14
15
  /**
15
16
  * Generates a hash digest using the specified algorithm.
16
17
  *
@@ -19,9 +20,9 @@ export const hmac = (algorithm, input, secret, encoding = "hex") => {
19
20
  * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).
20
21
  * @returns {string} Hash digest as a string.
21
22
  */
22
- export const hash = (algorithm, input, encoding = "hex") => {
23
+ export function hash(algorithm, input, encoding = 'hex') {
23
24
  return createHash(algorithm).update(input).digest(encoding);
24
- };
25
+ }
25
26
  /**
26
27
  * Generates an HMAC-SHA256 digest.
27
28
  *
@@ -29,9 +30,9 @@ export const hash = (algorithm, input, encoding = "hex") => {
29
30
  * @param {string} secret - The secret key.
30
31
  * @returns {string} SHA-256 HMAC digest as a string.
31
32
  */
32
- export const sha256Hmac = (input, secret) => {
33
- return hmac("sha256", input, secret);
34
- };
33
+ export function sha256Hmac(input, secret) {
34
+ return hmac('sha256', input, secret);
35
+ }
35
36
  /**
36
37
  * Generates a SHA1 hash digest.
37
38
  *
@@ -39,9 +40,9 @@ export const sha256Hmac = (input, secret) => {
39
40
  * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
40
41
  * @returns {string} SHA-1 hash as a string.
41
42
  */
42
- export const sha1 = (input, encoding = "hex") => {
43
- return hash("sha1", input, encoding);
44
- };
43
+ export function sha1(input, encoding = 'hex') {
44
+ return hash('sha1', input, encoding);
45
+ }
45
46
  /**
46
47
  * Generates a SHA256 hash digest.
47
48
  *
@@ -49,24 +50,203 @@ export const sha1 = (input, encoding = "hex") => {
49
50
  * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
50
51
  * @returns {string} SHA-256 hash as a string.
51
52
  */
52
- export const sha256 = (input, encoding = "hex") => {
53
- return hash("sha256", input, encoding);
54
- };
53
+ export function sha256(input, encoding = 'hex') {
54
+ return hash('sha256', input, encoding);
55
+ }
55
56
  /**
56
57
  * Generates an MD5 hash digest.
57
58
  *
58
59
  * @param {string} input - The string to hash.
59
60
  * @returns {string} MD5 hash as a string.
60
61
  */
61
- export const md5 = (input) => {
62
- return hash("md5", input);
63
- };
62
+ export function md5(input) {
63
+ return hash('md5', input);
64
+ }
64
65
  /**
65
66
  * Generates a cryptographically strong random string by hashing a random UUID with SHA-256.
66
67
  *
67
68
  * @returns {string} Random string hashed with SHA-256 (hex encoding).
68
69
  */
69
- export const randomString = () => {
70
+ export function randomString() {
70
71
  return sha256(randomUUID());
71
- };
72
+ }
73
+ /**
74
+ * Generates a secure random buffer of specified byte length.
75
+ *
76
+ * @param {number} [byteLength=32] - Number of random bytes to generate.
77
+ * @returns {Buffer} Buffer containing random bytes.
78
+ */
79
+ export function generateRandomBytes(byteLength = 32) {
80
+ return randomBytes(byteLength);
81
+ }
82
+ /**
83
+ * Generates a secure random string of specified byte length with specified encoding.
84
+ *
85
+ * @param {number} [byteLength=32] - Number of random bytes to generate.
86
+ * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
87
+ * @returns {string} Random string in specified encoding.
88
+ */
89
+ export function generateRandomBytesAsString(byteLength = 32, encoding = 'hex') {
90
+ return randomBytes(byteLength).toString(encoding);
91
+ }
92
+ /**
93
+ * Generates a secure API key with a specified format.
94
+ *
95
+ * @param {string} [prefix=''] - Optional prefix for the key.
96
+ * @param {number} [byteLength=24] - Number of random bytes to generate.
97
+ * @returns {string} Formatted API key.
98
+ */
99
+ export function generateApiKey(prefix = '', byteLength = 24) {
100
+ const randomString = generateRandomBytesAsString(byteLength, 'base64');
101
+ const key = randomString
102
+ .replace(/[+/=]/g, '') // Remove non-URL-safe characters
103
+ .substring(0, 32); // Limit length
104
+ return prefix ? `${prefix}_${key}` : key;
105
+ }
106
+ /**
107
+ * Compares two strings, arrays, or buffers in constant time to prevent timing attacks.
108
+ *
109
+ * @param {string | Buffer | Uint8Array} a - First value to compare
110
+ * @param {string | Buffer | Uint8Array} b - Second value to compare
111
+ * @returns {boolean} True if values are equal
112
+ */
113
+ export function safeCompare(a, b) {
114
+ if (typeof a === 'string' && typeof b === 'string') {
115
+ // Convert strings to buffers
116
+ const bufA = Buffer.from(a);
117
+ const bufB = Buffer.from(b);
118
+ // Compare lengths first (not constant time, but prevents timing attack on contents)
119
+ if (bufA.length !== bufB.length)
120
+ return false;
121
+ return timingSafeEqual(bufA, bufB);
122
+ }
123
+ else if ((a instanceof Buffer || a instanceof Uint8Array) && (b instanceof Buffer || b instanceof Uint8Array)) {
124
+ // Compare lengths first
125
+ if (a.length !== b.length)
126
+ return false;
127
+ return timingSafeEqual(a instanceof Buffer ? a : Buffer.from(a), b instanceof Buffer ? b : Buffer.from(b));
128
+ }
129
+ throw new Error('Cannot compare: inputs must be strings, Buffers, or Uint8Arrays');
130
+ }
131
+ // Promisified version of scrypt for key derivation
132
+ const scryptAsync = promisify(scrypt);
133
+ /**
134
+ * Encrypts data using a symmetric key with secure defaults (AES-256-GCM).
135
+ *
136
+ * @param {string | Buffer} data - Data to encrypt
137
+ * @param {string | Buffer} key - Encryption key or passphrase
138
+ * @param {EncryptionOptions} [options] - Encryption options
139
+ * @returns {Promise<EncryptionResult>} Encrypted data with metadata
140
+ */
141
+ export async function encrypt(data, key, options = {}) {
142
+ const algorithm = options.algorithm || 'aes-256-gcm';
143
+ const inputEncoding = options.inputEncoding || 'utf8';
144
+ const outputEncoding = options.outputEncoding || 'hex';
145
+ // Generate a random IV
146
+ const iv = randomBytes(16);
147
+ // Derive key using scrypt if key is a string (passphrase)
148
+ const derivedKey = typeof key === 'string' ? await scryptAsync(key, iv.slice(0, 8), 32) : key;
149
+ // Create cipher
150
+ const cipher = createCipheriv(algorithm, derivedKey, iv);
151
+ // Encrypt the data
152
+ let ciphertext;
153
+ if (typeof data === 'string') {
154
+ ciphertext = cipher.update(data, inputEncoding, outputEncoding);
155
+ ciphertext += cipher.final(outputEncoding);
156
+ }
157
+ else {
158
+ const encrypted = Buffer.concat([cipher.update(data), cipher.final()]);
159
+ ciphertext = outputEncoding ? encrypted.toString(outputEncoding) : encrypted;
160
+ }
161
+ // Get authentication tag if using GCM mode
162
+ const authTag = algorithm.includes('gcm') ? cipher.getAuthTag() : undefined;
163
+ return {
164
+ ciphertext,
165
+ iv,
166
+ authTag,
167
+ algorithm
168
+ };
169
+ }
170
+ /**
171
+ * Decrypts data that was encrypted with the encrypt function.
172
+ *
173
+ * @param {EncryptionResult} encryptedData - The encrypted data and metadata
174
+ * @param {string | Buffer} key - Decryption key or passphrase
175
+ * @param {DecryptionOptions} [options] - Decryption options
176
+ * @returns {Promise<string | Buffer>} Decrypted data
177
+ */
178
+ export async function decrypt(encryptedData, key, options = {}) {
179
+ const algorithm = options.algorithm || encryptedData.algorithm || 'aes-256-gcm';
180
+ const inputEncoding = options.inputEncoding || 'hex';
181
+ const outputEncoding = options.outputEncoding || 'utf8';
182
+ // Derive key using scrypt if key is a string (passphrase)
183
+ const derivedKey = typeof key === 'string' ? await scryptAsync(key, encryptedData.iv.slice(0, 8), 32) : key;
184
+ // Create decipher
185
+ const decipher = createDecipheriv(algorithm, derivedKey, encryptedData.iv);
186
+ // Set auth tag if using GCM mode
187
+ if (encryptedData.authTag && algorithm.includes('gcm')) {
188
+ decipher.setAuthTag(encryptedData.authTag);
189
+ }
190
+ // Decrypt the data
191
+ let decrypted;
192
+ if (typeof encryptedData.ciphertext === 'string') {
193
+ decrypted = decipher.update(encryptedData.ciphertext, inputEncoding, outputEncoding);
194
+ decrypted += decipher.final(outputEncoding);
195
+ }
196
+ else {
197
+ const result = Buffer.concat([decipher.update(encryptedData.ciphertext), decipher.final()]);
198
+ decrypted = outputEncoding ? result.toString(outputEncoding) : result;
199
+ }
200
+ return decrypted;
201
+ }
202
+ /**
203
+ * Creates a signed token with an expiration time and payload.
204
+ *
205
+ * @param {object} payload - Data to include in the token
206
+ * @param {string} secret - Secret key for signing
207
+ * @param {number} [expiresInSeconds=3600] - Token expiration in seconds
208
+ * @returns {string} Signed token string
209
+ */
210
+ export function createSignedToken(payload, secret, expiresInSeconds = 3600) {
211
+ // Create payload with expiration
212
+ const tokenPayload = Object.assign(Object.assign({}, payload), { exp: Math.floor(Date.now() / 1000) + expiresInSeconds });
213
+ // Convert to string
214
+ const payloadStr = JSON.stringify(tokenPayload);
215
+ // Base64 encode the payload
216
+ const base64Payload = Buffer.from(payloadStr).toString('base64url');
217
+ // Create signature
218
+ const signature = hmac('sha256', base64Payload, secret, 'base64url');
219
+ // Combine payload and signature
220
+ return `${base64Payload}.${signature}`;
221
+ }
222
+ /**
223
+ * Verifies and decodes a signed token.
224
+ *
225
+ * @param {string} token - The token to verify
226
+ * @param {string} secret - Secret key for verification
227
+ * @returns {object | null} Decoded payload if valid, null if invalid
228
+ */
229
+ export function verifySignedToken(token, secret) {
230
+ try {
231
+ // Split token into parts
232
+ const [payloadB64, signature] = token.split('.');
233
+ if (!payloadB64 || !signature)
234
+ return null;
235
+ // Verify signature
236
+ const expectedSignature = hmac('sha256', payloadB64, secret, 'base64url');
237
+ if (!safeCompare(signature, expectedSignature))
238
+ return null;
239
+ // Decode payload
240
+ const payloadStr = Buffer.from(payloadB64, 'base64url').toString('utf8');
241
+ const payload = JSON.parse(payloadStr);
242
+ // Check expiration
243
+ if (payload.exp && payload.exp < Math.floor(Date.now() / 1000)) {
244
+ return null;
245
+ }
246
+ return payload;
247
+ }
248
+ catch (_a) {
249
+ return null;
250
+ }
251
+ }
72
252
  //# sourceMappingURL=crypto.utils.js.map