@catbee/utils 0.0.6 → 0.0.8-next.0

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 (249) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +77 -1107
  3. package/build/index.cjs +6888 -0
  4. package/build/index.d.ts +5242 -0
  5. package/build/index.mjs +6615 -0
  6. package/package.json +26 -95
  7. package/build/esm/config.d.ts +0 -130
  8. package/build/esm/config.js +0 -145
  9. package/build/esm/config.js.map +0 -1
  10. package/build/esm/index.d.ts +0 -27
  11. package/build/esm/index.js +0 -50
  12. package/build/esm/index.js.map +0 -1
  13. package/build/esm/servers/server.builder.d.ts +0 -625
  14. package/build/esm/servers/server.builder.js +0 -722
  15. package/build/esm/servers/server.builder.js.map +0 -1
  16. package/build/esm/servers/server.d.ts +0 -256
  17. package/build/esm/servers/server.js +0 -1211
  18. package/build/esm/servers/server.js.map +0 -1
  19. package/build/esm/types/api-response.d.ts +0 -124
  20. package/build/esm/types/api-response.js +0 -25
  21. package/build/esm/types/api-response.js.map +0 -1
  22. package/build/esm/types/index.d.ts +0 -125
  23. package/build/esm/types/index.js +0 -25
  24. package/build/esm/types/index.js.map +0 -1
  25. package/build/esm/types/server.d.ts +0 -285
  26. package/build/esm/types/server.js +0 -25
  27. package/build/esm/types/server.js.map +0 -1
  28. package/build/esm/utils/array.utils.d.ts +0 -168
  29. package/build/esm/utils/array.utils.js +0 -382
  30. package/build/esm/utils/array.utils.js.map +0 -1
  31. package/build/esm/utils/async.utils.d.ts +0 -174
  32. package/build/esm/utils/async.utils.js +0 -652
  33. package/build/esm/utils/async.utils.js.map +0 -1
  34. package/build/esm/utils/cache.utils.d.ts +0 -153
  35. package/build/esm/utils/cache.utils.js +0 -499
  36. package/build/esm/utils/cache.utils.js.map +0 -1
  37. package/build/esm/utils/context-store.utils.d.ts +0 -186
  38. package/build/esm/utils/context-store.utils.js +0 -304
  39. package/build/esm/utils/context-store.utils.js.map +0 -1
  40. package/build/esm/utils/crypto.utils.d.ts +0 -160
  41. package/build/esm/utils/crypto.utils.js +0 -375
  42. package/build/esm/utils/crypto.utils.js.map +0 -1
  43. package/build/esm/utils/decorators.utils.d.ts +0 -315
  44. package/build/esm/utils/decorators.utils.js +0 -666
  45. package/build/esm/utils/decorators.utils.js.map +0 -1
  46. package/build/esm/utils/dir.utils.d.ts +0 -196
  47. package/build/esm/utils/dir.utils.js +0 -998
  48. package/build/esm/utils/dir.utils.js.map +0 -1
  49. package/build/esm/utils/env.utils.d.ts +0 -377
  50. package/build/esm/utils/env.utils.js +0 -873
  51. package/build/esm/utils/env.utils.js.map +0 -1
  52. package/build/esm/utils/exception.utils.d.ts +0 -230
  53. package/build/esm/utils/exception.utils.js +0 -559
  54. package/build/esm/utils/exception.utils.js.map +0 -1
  55. package/build/esm/utils/fs.utils.d.ts +0 -164
  56. package/build/esm/utils/fs.utils.js +0 -580
  57. package/build/esm/utils/fs.utils.js.map +0 -1
  58. package/build/esm/utils/http-status-codes.d.ts +0 -266
  59. package/build/esm/utils/http-status-codes.js +0 -295
  60. package/build/esm/utils/http-status-codes.js.map +0 -1
  61. package/build/esm/utils/id.utils.d.ts +0 -36
  62. package/build/esm/utils/id.utils.js +0 -87
  63. package/build/esm/utils/id.utils.js.map +0 -1
  64. package/build/esm/utils/logger.utils.d.ts +0 -166
  65. package/build/esm/utils/logger.utils.js +0 -347
  66. package/build/esm/utils/logger.utils.js.map +0 -1
  67. package/build/esm/utils/middleware.utils.d.ts +0 -83
  68. package/build/esm/utils/middleware.utils.js +0 -205
  69. package/build/esm/utils/middleware.utils.js.map +0 -1
  70. package/build/esm/utils/obj.utils.d.ts +0 -124
  71. package/build/esm/utils/obj.utils.js +0 -519
  72. package/build/esm/utils/obj.utils.js.map +0 -1
  73. package/build/esm/utils/request.utils.d.ts +0 -77
  74. package/build/esm/utils/request.utils.js +0 -196
  75. package/build/esm/utils/request.utils.js.map +0 -1
  76. package/build/esm/utils/response.utils.d.ts +0 -163
  77. package/build/esm/utils/response.utils.js +0 -284
  78. package/build/esm/utils/response.utils.js.map +0 -1
  79. package/build/esm/utils/string.utils.d.ts +0 -93
  80. package/build/esm/utils/string.utils.js +0 -169
  81. package/build/esm/utils/string.utils.js.map +0 -1
  82. package/build/esm/utils/url.utils.d.ts +0 -141
  83. package/build/esm/utils/url.utils.js +0 -381
  84. package/build/esm/utils/url.utils.js.map +0 -1
  85. package/build/esm/utils/validate.utils.d.ts +0 -177
  86. package/build/esm/utils/validate.utils.js +0 -336
  87. package/build/esm/utils/validate.utils.js.map +0 -1
  88. package/build/esnext/config.d.ts +0 -130
  89. package/build/esnext/config.js +0 -145
  90. package/build/esnext/config.js.map +0 -1
  91. package/build/esnext/index.d.ts +0 -27
  92. package/build/esnext/index.js +0 -50
  93. package/build/esnext/index.js.map +0 -1
  94. package/build/esnext/servers/server.builder.d.ts +0 -625
  95. package/build/esnext/servers/server.builder.js +0 -677
  96. package/build/esnext/servers/server.builder.js.map +0 -1
  97. package/build/esnext/servers/server.d.ts +0 -256
  98. package/build/esnext/servers/server.js +0 -918
  99. package/build/esnext/servers/server.js.map +0 -1
  100. package/build/esnext/types/api-response.d.ts +0 -124
  101. package/build/esnext/types/api-response.js +0 -25
  102. package/build/esnext/types/api-response.js.map +0 -1
  103. package/build/esnext/types/index.d.ts +0 -125
  104. package/build/esnext/types/index.js +0 -25
  105. package/build/esnext/types/index.js.map +0 -1
  106. package/build/esnext/types/server.d.ts +0 -285
  107. package/build/esnext/types/server.js +0 -25
  108. package/build/esnext/types/server.js.map +0 -1
  109. package/build/esnext/utils/array.utils.d.ts +0 -168
  110. package/build/esnext/utils/array.utils.js +0 -345
  111. package/build/esnext/utils/array.utils.js.map +0 -1
  112. package/build/esnext/utils/async.utils.d.ts +0 -174
  113. package/build/esnext/utils/async.utils.js +0 -430
  114. package/build/esnext/utils/async.utils.js.map +0 -1
  115. package/build/esnext/utils/cache.utils.d.ts +0 -153
  116. package/build/esnext/utils/cache.utils.js +0 -293
  117. package/build/esnext/utils/cache.utils.js.map +0 -1
  118. package/build/esnext/utils/context-store.utils.d.ts +0 -186
  119. package/build/esnext/utils/context-store.utils.js +0 -286
  120. package/build/esnext/utils/context-store.utils.js.map +0 -1
  121. package/build/esnext/utils/crypto.utils.d.ts +0 -160
  122. package/build/esnext/utils/crypto.utils.js +0 -276
  123. package/build/esnext/utils/crypto.utils.js.map +0 -1
  124. package/build/esnext/utils/decorators.utils.d.ts +0 -315
  125. package/build/esnext/utils/decorators.utils.js +0 -504
  126. package/build/esnext/utils/decorators.utils.js.map +0 -1
  127. package/build/esnext/utils/dir.utils.d.ts +0 -196
  128. package/build/esnext/utils/dir.utils.js +0 -477
  129. package/build/esnext/utils/dir.utils.js.map +0 -1
  130. package/build/esnext/utils/env.utils.d.ts +0 -377
  131. package/build/esnext/utils/env.utils.js +0 -785
  132. package/build/esnext/utils/env.utils.js.map +0 -1
  133. package/build/esnext/utils/exception.utils.d.ts +0 -230
  134. package/build/esnext/utils/exception.utils.js +0 -381
  135. package/build/esnext/utils/exception.utils.js.map +0 -1
  136. package/build/esnext/utils/fs.utils.d.ts +0 -164
  137. package/build/esnext/utils/fs.utils.js +0 -349
  138. package/build/esnext/utils/fs.utils.js.map +0 -1
  139. package/build/esnext/utils/http-status-codes.d.ts +0 -266
  140. package/build/esnext/utils/http-status-codes.js +0 -295
  141. package/build/esnext/utils/http-status-codes.js.map +0 -1
  142. package/build/esnext/utils/id.utils.d.ts +0 -36
  143. package/build/esnext/utils/id.utils.js +0 -84
  144. package/build/esnext/utils/id.utils.js.map +0 -1
  145. package/build/esnext/utils/logger.utils.d.ts +0 -166
  146. package/build/esnext/utils/logger.utils.js +0 -306
  147. package/build/esnext/utils/logger.utils.js.map +0 -1
  148. package/build/esnext/utils/middleware.utils.d.ts +0 -83
  149. package/build/esnext/utils/middleware.utils.js +0 -198
  150. package/build/esnext/utils/middleware.utils.js.map +0 -1
  151. package/build/esnext/utils/obj.utils.d.ts +0 -124
  152. package/build/esnext/utils/obj.utils.js +0 -413
  153. package/build/esnext/utils/obj.utils.js.map +0 -1
  154. package/build/esnext/utils/request.utils.d.ts +0 -77
  155. package/build/esnext/utils/request.utils.js +0 -168
  156. package/build/esnext/utils/request.utils.js.map +0 -1
  157. package/build/esnext/utils/response.utils.d.ts +0 -163
  158. package/build/esnext/utils/response.utils.js +0 -247
  159. package/build/esnext/utils/response.utils.js.map +0 -1
  160. package/build/esnext/utils/string.utils.d.ts +0 -93
  161. package/build/esnext/utils/string.utils.js +0 -165
  162. package/build/esnext/utils/string.utils.js.map +0 -1
  163. package/build/esnext/utils/url.utils.d.ts +0 -141
  164. package/build/esnext/utils/url.utils.js +0 -304
  165. package/build/esnext/utils/url.utils.js.map +0 -1
  166. package/build/esnext/utils/validate.utils.d.ts +0 -177
  167. package/build/esnext/utils/validate.utils.js +0 -320
  168. package/build/esnext/utils/validate.utils.js.map +0 -1
  169. package/build/src/config.d.ts +0 -130
  170. package/build/src/config.js +0 -150
  171. package/build/src/config.js.map +0 -1
  172. package/build/src/index.d.ts +0 -27
  173. package/build/src/index.js +0 -69
  174. package/build/src/index.js.map +0 -1
  175. package/build/src/servers/server.builder.d.ts +0 -625
  176. package/build/src/servers/server.builder.js +0 -681
  177. package/build/src/servers/server.builder.js.map +0 -1
  178. package/build/src/servers/server.d.ts +0 -256
  179. package/build/src/servers/server.js +0 -958
  180. package/build/src/servers/server.js.map +0 -1
  181. package/build/src/types/api-response.d.ts +0 -124
  182. package/build/src/types/api-response.js +0 -26
  183. package/build/src/types/api-response.js.map +0 -1
  184. package/build/src/types/index.d.ts +0 -125
  185. package/build/src/types/index.js +0 -26
  186. package/build/src/types/index.js.map +0 -1
  187. package/build/src/types/server.d.ts +0 -285
  188. package/build/src/types/server.js +0 -26
  189. package/build/src/types/server.js.map +0 -1
  190. package/build/src/utils/array.utils.d.ts +0 -168
  191. package/build/src/utils/array.utils.js +0 -364
  192. package/build/src/utils/array.utils.js.map +0 -1
  193. package/build/src/utils/async.utils.d.ts +0 -174
  194. package/build/src/utils/async.utils.js +0 -447
  195. package/build/src/utils/async.utils.js.map +0 -1
  196. package/build/src/utils/cache.utils.d.ts +0 -153
  197. package/build/src/utils/cache.utils.js +0 -297
  198. package/build/src/utils/cache.utils.js.map +0 -1
  199. package/build/src/utils/context-store.utils.d.ts +0 -186
  200. package/build/src/utils/context-store.utils.js +0 -293
  201. package/build/src/utils/context-store.utils.js.map +0 -1
  202. package/build/src/utils/crypto.utils.d.ts +0 -160
  203. package/build/src/utils/crypto.utils.js +0 -293
  204. package/build/src/utils/crypto.utils.js.map +0 -1
  205. package/build/src/utils/decorators.utils.d.ts +0 -315
  206. package/build/src/utils/decorators.utils.js +0 -516
  207. package/build/src/utils/decorators.utils.js.map +0 -1
  208. package/build/src/utils/dir.utils.d.ts +0 -196
  209. package/build/src/utils/dir.utils.js +0 -501
  210. package/build/src/utils/dir.utils.js.map +0 -1
  211. package/build/src/utils/env.utils.d.ts +0 -377
  212. package/build/src/utils/env.utils.js +0 -789
  213. package/build/src/utils/env.utils.js.map +0 -1
  214. package/build/src/utils/exception.utils.d.ts +0 -230
  215. package/build/src/utils/exception.utils.js +0 -407
  216. package/build/src/utils/exception.utils.js.map +0 -1
  217. package/build/src/utils/fs.utils.d.ts +0 -164
  218. package/build/src/utils/fs.utils.js +0 -372
  219. package/build/src/utils/fs.utils.js.map +0 -1
  220. package/build/src/utils/http-status-codes.d.ts +0 -266
  221. package/build/src/utils/http-status-codes.js +0 -298
  222. package/build/src/utils/http-status-codes.js.map +0 -1
  223. package/build/src/utils/id.utils.d.ts +0 -36
  224. package/build/src/utils/id.utils.js +0 -91
  225. package/build/src/utils/id.utils.js.map +0 -1
  226. package/build/src/utils/logger.utils.d.ts +0 -166
  227. package/build/src/utils/logger.utils.js +0 -352
  228. package/build/src/utils/logger.utils.js.map +0 -1
  229. package/build/src/utils/middleware.utils.d.ts +0 -83
  230. package/build/src/utils/middleware.utils.js +0 -205
  231. package/build/src/utils/middleware.utils.js.map +0 -1
  232. package/build/src/utils/obj.utils.d.ts +0 -124
  233. package/build/src/utils/obj.utils.js +0 -429
  234. package/build/src/utils/obj.utils.js.map +0 -1
  235. package/build/src/utils/request.utils.d.ts +0 -77
  236. package/build/src/utils/request.utils.js +0 -175
  237. package/build/src/utils/request.utils.js.map +0 -1
  238. package/build/src/utils/response.utils.d.ts +0 -163
  239. package/build/src/utils/response.utils.js +0 -260
  240. package/build/src/utils/response.utils.js.map +0 -1
  241. package/build/src/utils/string.utils.d.ts +0 -93
  242. package/build/src/utils/string.utils.js +0 -179
  243. package/build/src/utils/string.utils.js.map +0 -1
  244. package/build/src/utils/url.utils.d.ts +0 -141
  245. package/build/src/utils/url.utils.js +0 -317
  246. package/build/src/utils/url.utils.js.map +0 -1
  247. package/build/src/utils/validate.utils.d.ts +0 -177
  248. package/build/src/utils/validate.utils.js +0 -345
  249. package/build/src/utils/validate.utils.js.map +0 -1
@@ -1,293 +0,0 @@
1
- "use strict";
2
- /*
3
- * The MIT License
4
- *
5
- * Copyright (c) 2025 Catbee Technologies
6
- *
7
- * Permission is hereby granted, free of charge, to any person obtaining a copy
8
- * of this software and associated documentation files (the "Software"), to deal
9
- * in the Software without restriction, including without limitation the rights
10
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
- * copies of the Software, and to permit persons to whom the Software is
12
- * furnished to do so, subject to the following conditions:
13
- *
14
- * The above copyright notice and this permission notice shall be included in all
15
- * copies or substantial portions of the Software.
16
- *
17
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
- * SOFTWARE.
24
- */
25
- Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.hmac = hmac;
27
- exports.hash = hash;
28
- exports.sha256Hmac = sha256Hmac;
29
- exports.sha1 = sha1;
30
- exports.sha256 = sha256;
31
- exports.md5 = md5;
32
- exports.randomString = randomString;
33
- exports.generateRandomBytes = generateRandomBytes;
34
- exports.generateRandomBytesAsString = generateRandomBytesAsString;
35
- exports.generateApiKey = generateApiKey;
36
- exports.safeCompare = safeCompare;
37
- exports.encrypt = encrypt;
38
- exports.decrypt = decrypt;
39
- exports.createSignedToken = createSignedToken;
40
- exports.verifySignedToken = verifySignedToken;
41
- const crypto_1 = require("crypto");
42
- const util_1 = require("util");
43
- const id_utils_1 = require("./id.utils");
44
- /**
45
- * Generates an HMAC digest using the specified algorithm and secret key.
46
- *
47
- * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'sha1').
48
- * @param {string} input - The string to hash.
49
- * @param {string} secret - The secret key for HMAC.
50
- * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).
51
- * @returns {string} HMAC digest as a string.
52
- */
53
- function hmac(algorithm, input, secret, encoding = 'hex') {
54
- return (0, crypto_1.createHmac)(algorithm, secret).update(input).digest(encoding);
55
- }
56
- /**
57
- * Generates a hash digest using the specified algorithm.
58
- *
59
- * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'md5').
60
- * @param {string} input - The string to hash.
61
- * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).
62
- * @returns {string} Hash digest as a string.
63
- */
64
- function hash(algorithm, input, encoding = 'hex') {
65
- return (0, crypto_1.createHash)(algorithm).update(input).digest(encoding);
66
- }
67
- /**
68
- * Generates an HMAC-SHA256 digest.
69
- *
70
- * @param {string} input - The string to hash.
71
- * @param {string} secret - The secret key.
72
- * @returns {string} SHA-256 HMAC digest as a string.
73
- */
74
- function sha256Hmac(input, secret) {
75
- return hmac('sha256', input, secret);
76
- }
77
- /**
78
- * Generates a SHA1 hash digest.
79
- *
80
- * @param {string} input - The string to hash.
81
- * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
82
- * @returns {string} SHA-1 hash as a string.
83
- */
84
- function sha1(input, encoding = 'hex') {
85
- return hash('sha1', input, encoding);
86
- }
87
- /**
88
- * Generates a SHA256 hash digest.
89
- *
90
- * @param {string} input - The string to hash.
91
- * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
92
- * @returns {string} SHA-256 hash as a string.
93
- */
94
- function sha256(input, encoding = 'hex') {
95
- return hash('sha256', input, encoding);
96
- }
97
- /**
98
- * Generates an MD5 hash digest.
99
- *
100
- * @param {string} input - The string to hash.
101
- * @returns {string} MD5 hash as a string.
102
- */
103
- function md5(input) {
104
- return hash('md5', input);
105
- }
106
- /**
107
- * Generates a cryptographically strong random string by hashing a random UUID with SHA-256.
108
- *
109
- * @returns {string} Random string hashed with SHA-256 (hex encoding).
110
- */
111
- function randomString() {
112
- return sha256((0, id_utils_1.uuid)());
113
- }
114
- /**
115
- * Generates a secure random buffer of specified byte length.
116
- *
117
- * @param {number} [byteLength=32] - Number of random bytes to generate.
118
- * @returns {Buffer} Buffer containing random bytes.
119
- */
120
- function generateRandomBytes(byteLength = 32) {
121
- return (0, crypto_1.randomBytes)(byteLength);
122
- }
123
- /**
124
- * Generates a secure random string of specified byte length with specified encoding.
125
- *
126
- * @param {number} [byteLength=32] - Number of random bytes to generate.
127
- * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
128
- * @returns {string} Random string in specified encoding.
129
- */
130
- function generateRandomBytesAsString(byteLength = 32, encoding = 'hex') {
131
- return (0, crypto_1.randomBytes)(byteLength).toString(encoding);
132
- }
133
- /**
134
- * Generates a secure API key with a specified format.
135
- *
136
- * @param {string} [prefix=''] - Optional prefix for the key.
137
- * @param {number} [byteLength=24] - Number of random bytes to generate.
138
- * @returns {string} Formatted API key.
139
- */
140
- function generateApiKey(prefix = '', byteLength = 24) {
141
- const randomString = generateRandomBytesAsString(byteLength, 'base64');
142
- const key = randomString
143
- .replace(/[+/=]/g, '') // Remove non-URL-safe characters
144
- .substring(0, 32); // Limit length
145
- return prefix ? `${prefix}_${key}` : key;
146
- }
147
- /**
148
- * Compares two strings, arrays, or buffers in constant time to prevent timing attacks.
149
- *
150
- * @param {string | Buffer | Uint8Array} a - First value to compare
151
- * @param {string | Buffer | Uint8Array} b - Second value to compare
152
- * @returns {boolean} True if values are equal
153
- */
154
- function safeCompare(a, b) {
155
- if (typeof a === 'string' && typeof b === 'string') {
156
- // Convert strings to buffers
157
- const bufA = Buffer.from(a);
158
- const bufB = Buffer.from(b);
159
- // Compare lengths first (not constant time, but prevents timing attack on contents)
160
- if (bufA.length !== bufB.length)
161
- return false;
162
- return (0, crypto_1.timingSafeEqual)(bufA, bufB);
163
- }
164
- else if ((a instanceof Buffer || a instanceof Uint8Array) && (b instanceof Buffer || b instanceof Uint8Array)) {
165
- // Compare lengths first
166
- if (a.length !== b.length)
167
- return false;
168
- return (0, crypto_1.timingSafeEqual)(a instanceof Buffer ? a : Buffer.from(a), b instanceof Buffer ? b : Buffer.from(b));
169
- }
170
- throw new Error('Cannot compare: inputs must be strings, Buffers, or Uint8Arrays');
171
- }
172
- // Promisified version of scrypt for key derivation
173
- const scryptAsync = (0, util_1.promisify)(crypto_1.scrypt);
174
- /**
175
- * Encrypts data using a symmetric key with secure defaults (AES-256-GCM).
176
- *
177
- * @param {string | Buffer} data - Data to encrypt
178
- * @param {string | Buffer} key - Encryption key or passphrase
179
- * @param {EncryptionOptions} [options] - Encryption options
180
- * @returns {Promise<EncryptionResult>} Encrypted data with metadata
181
- */
182
- async function encrypt(data, key, options = {}) {
183
- const algorithm = options.algorithm || 'aes-256-gcm';
184
- const inputEncoding = options.inputEncoding || 'utf8';
185
- const outputEncoding = options.outputEncoding || 'hex';
186
- // Generate a random IV
187
- const iv = (0, crypto_1.randomBytes)(16);
188
- // Derive key using scrypt if key is a string (passphrase)
189
- const derivedKey = typeof key === 'string' ? await scryptAsync(key, iv.slice(0, 8), 32) : key;
190
- // Create cipher
191
- const cipher = (0, crypto_1.createCipheriv)(algorithm, derivedKey, iv);
192
- // Encrypt the data
193
- let ciphertext;
194
- if (typeof data === 'string') {
195
- ciphertext = cipher.update(data, inputEncoding, outputEncoding);
196
- ciphertext += cipher.final(outputEncoding);
197
- }
198
- else {
199
- const encrypted = Buffer.concat([cipher.update(data), cipher.final()]);
200
- ciphertext = outputEncoding ? encrypted.toString(outputEncoding) : encrypted;
201
- }
202
- // Get authentication tag if using GCM mode
203
- const authTag = algorithm.includes('gcm') ? cipher.getAuthTag() : undefined;
204
- return {
205
- ciphertext,
206
- iv,
207
- authTag,
208
- algorithm
209
- };
210
- }
211
- /**
212
- * Decrypts data that was encrypted with the encrypt function.
213
- *
214
- * @param {EncryptionResult} encryptedData - The encrypted data and metadata
215
- * @param {string | Buffer} key - Decryption key or passphrase
216
- * @param {DecryptionOptions} [options] - Decryption options
217
- * @returns {Promise<string | Buffer>} Decrypted data
218
- */
219
- async function decrypt(encryptedData, key, options = {}) {
220
- const algorithm = options.algorithm || encryptedData.algorithm || 'aes-256-gcm';
221
- const inputEncoding = options.inputEncoding || 'hex';
222
- const outputEncoding = options.outputEncoding || 'utf8';
223
- // Derive key using scrypt if key is a string (passphrase)
224
- const derivedKey = typeof key === 'string' ? await scryptAsync(key, encryptedData.iv.slice(0, 8), 32) : key;
225
- // Create decipher
226
- const decipher = (0, crypto_1.createDecipheriv)(algorithm, derivedKey, encryptedData.iv);
227
- // Set auth tag if using GCM mode
228
- if (encryptedData.authTag && algorithm.includes('gcm')) {
229
- decipher.setAuthTag(encryptedData.authTag);
230
- }
231
- // Decrypt the data
232
- let decrypted;
233
- if (typeof encryptedData.ciphertext === 'string') {
234
- decrypted = decipher.update(encryptedData.ciphertext, inputEncoding, outputEncoding);
235
- decrypted += decipher.final(outputEncoding);
236
- }
237
- else {
238
- const result = Buffer.concat([decipher.update(encryptedData.ciphertext), decipher.final()]);
239
- decrypted = outputEncoding ? result.toString(outputEncoding) : result;
240
- }
241
- return decrypted;
242
- }
243
- /**
244
- * Creates a signed token with an expiration time and payload.
245
- *
246
- * @param {object} payload - Data to include in the token
247
- * @param {string} secret - Secret key for signing
248
- * @param {number} [expiresInSeconds=3600] - Token expiration in seconds
249
- * @returns {string} Signed token string
250
- */
251
- function createSignedToken(payload, secret, expiresInSeconds = 3600) {
252
- // Create payload with expiration
253
- const tokenPayload = Object.assign(Object.assign({}, payload), { exp: Math.floor(Date.now() / 1000) + expiresInSeconds });
254
- // Convert to string
255
- const payloadStr = JSON.stringify(tokenPayload);
256
- // Base64 encode the payload
257
- const base64Payload = Buffer.from(payloadStr).toString('base64url');
258
- // Create signature
259
- const signature = hmac('sha256', base64Payload, secret, 'base64url');
260
- // Combine payload and signature
261
- return `${base64Payload}.${signature}`;
262
- }
263
- /**
264
- * Verifies and decodes a signed token.
265
- *
266
- * @param {string} token - The token to verify
267
- * @param {string} secret - Secret key for verification
268
- * @returns {object | null} Decoded payload if valid, null if invalid
269
- */
270
- function verifySignedToken(token, secret) {
271
- try {
272
- // Split token into parts
273
- const [payloadB64, signature] = token.split('.');
274
- if (!payloadB64 || !signature)
275
- return null;
276
- // Verify signature
277
- const expectedSignature = hmac('sha256', payloadB64, secret, 'base64url');
278
- if (!safeCompare(signature, expectedSignature))
279
- return null;
280
- // Decode payload
281
- const payloadStr = Buffer.from(payloadB64, 'base64url').toString('utf8');
282
- const payload = JSON.parse(payloadStr);
283
- // Check expiration
284
- if (payload.exp && payload.exp < Math.floor(Date.now() / 1000)) {
285
- return null;
286
- }
287
- return payload;
288
- }
289
- catch (_a) {
290
- return null;
291
- }
292
- }
293
- //# sourceMappingURL=crypto.utils.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"crypto.utils.js","sourceRoot":"","sources":["../../../src/utils/crypto.utils.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AAI,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\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"]}
@@ -1,315 +0,0 @@
1
- import type { RequestHandler, Router } from 'express';
2
- import 'reflect-metadata';
3
- /**
4
- * Decorator for GET HTTP method routes.
5
- *
6
- * @param path - URL path for the route
7
- * @returns Method decorator
8
- *
9
- * @example
10
- * ```ts
11
- * @Get('/users')
12
- * getUsers() {
13
- * return this.userService.findAll();
14
- * }
15
- * ```
16
- */
17
- export declare const Get: (path: string) => MethodDecorator;
18
- /**
19
- * Decorator for POST HTTP method routes.
20
- *
21
- * @param path - URL path for the route
22
- * @returns Method decorator
23
- *
24
- * @example
25
- * ```ts
26
- * @Post('/users')
27
- * createUser(@Body() userData: any) {
28
- * return this.userService.create(userData);
29
- * }
30
- * ```
31
- */
32
- export declare const Post: (path: string) => MethodDecorator;
33
- /**
34
- * Decorator for PUT HTTP method routes.
35
- *
36
- * @param path - URL path for the route
37
- * @returns Method decorator
38
- */
39
- export declare const Put: (path: string) => MethodDecorator;
40
- /**
41
- * Decorator for PATCH HTTP method routes.
42
- *
43
- * @param path - URL path for the route
44
- * @returns Method decorator
45
- */
46
- export declare const Patch: (path: string) => MethodDecorator;
47
- /**
48
- * Decorator for DELETE HTTP method routes.
49
- *
50
- * @param path - URL path for the route
51
- * @returns Method decorator
52
- */
53
- export declare const Delete: (path: string) => MethodDecorator;
54
- /**
55
- * Decorator for OPTIONS HTTP method routes.
56
- *
57
- * @param path - URL path for the route
58
- * @returns Method decorator
59
- */
60
- export declare const Options: (path: string) => MethodDecorator;
61
- /**
62
- * Decorator for HEAD HTTP method routes.
63
- *
64
- * @param path - URL path for the route
65
- * @returns Method decorator
66
- */
67
- export declare const Head: (path: string) => MethodDecorator;
68
- /**
69
- * Decorator for TRACE HTTP method routes.
70
- *
71
- * @param path - URL path for the route
72
- * @returns Method decorator
73
- */
74
- export declare const Trace: (path: string) => MethodDecorator;
75
- /**
76
- * Decorator for CONNECT HTTP method routes.
77
- *
78
- * @param path - URL path for the route
79
- * @returns Method decorator
80
- */
81
- export declare const Connect: (path: string) => MethodDecorator;
82
- /**
83
- * Decorator that marks a class as a controller with a base path.
84
- * Used as the entry point for routing configuration.
85
- *
86
- * @param basePath - Base URL path for all routes in this controller
87
- * @returns Class decorator
88
- *
89
- * @example
90
- * ```ts
91
- * @Controller('/api/users')
92
- * class UserController {
93
- * // Controller methods...
94
- * }
95
- * ```
96
- */
97
- export declare function Controller(basePath: string): ClassDecorator;
98
- /**
99
- * Decorator that applies middleware to a controller method.
100
- * Multiple middlewares can be applied and will execute in order.
101
- *
102
- * @param middlewares - Express middleware functions to apply
103
- * @returns Method decorator
104
- *
105
- * @example
106
- * ```ts
107
- * @Get('/protected')
108
- * @Use(authMiddleware, loggingMiddleware)
109
- * getProtectedResource() {
110
- * // This route is protected by auth middleware
111
- * }
112
- * ```
113
- */
114
- export declare function Use(...middlewares: RequestHandler[]): MethodDecorator;
115
- /**
116
- * Decorator that extracts query parameters from request.
117
- *
118
- * @param paramKey - Optional key to extract specific query parameter
119
- * @returns Parameter decorator
120
- *
121
- * @example
122
- * ```ts
123
- * @Get('/search')
124
- * search(@Query('term') searchTerm: string) {
125
- * // searchTerm will contain the value of req.query.term
126
- * }
127
- * ```
128
- */
129
- export declare const Query: (paramKey?: string) => ParameterDecorator;
130
- /**
131
- * Decorator that extracts route parameters from request.
132
- *
133
- * @param paramKey - Optional key to extract specific route parameter
134
- * @returns Parameter decorator
135
- *
136
- * @example
137
- * ```ts
138
- * @Get('/users/:id')
139
- * getUser(@Param('id') userId: string) {
140
- * // userId will contain the value of req.params.id
141
- * }
142
- * ```
143
- */
144
- export declare const Param: (paramKey?: string) => ParameterDecorator;
145
- /**
146
- * Decorator that extracts body or body property from request.
147
- *
148
- * @param paramKey - Optional key to extract specific body property
149
- * @returns Parameter decorator
150
- *
151
- * @example
152
- * ```ts
153
- * @Post('/users')
154
- * createUser(@Body() userData: any) {
155
- * // userData will contain the entire req.body
156
- * }
157
- *
158
- * @Post('/update')
159
- * updateName(@Body('name') name: string) {
160
- * // name will contain the value of req.body.name
161
- * }
162
- * ```
163
- */
164
- export declare const Body: (paramKey?: string) => ParameterDecorator;
165
- /**
166
- * Decorator that injects the entire request object.
167
- *
168
- * @returns Parameter decorator
169
- *
170
- * @example
171
- * ```ts
172
- * @Get('/complex')
173
- * complex(@Req() req: Request) {
174
- * // Access the full request object
175
- * console.log(req.headers);
176
- * }
177
- * ```
178
- */
179
- export declare const Req: (paramKey?: string) => ParameterDecorator;
180
- /**
181
- * Decorator that injects the response object.
182
- *
183
- * @returns Parameter decorator
184
- *
185
- * @example
186
- * ```ts
187
- * @Get('/custom')
188
- * custom(@Res() res: Response) {
189
- * // Direct access to response object
190
- * return res.status(201).send('Created');
191
- * }
192
- * ```
193
- */
194
- export declare const Res: (paramKey?: string) => ParameterDecorator;
195
- /**
196
- * Decorator that sets a custom HTTP status code for a response.
197
- *
198
- * @param status - HTTP status code to use
199
- * @returns Method decorator
200
- *
201
- * @example
202
- * ```ts
203
- * @Post('/users')
204
- * @HttpCode(201)
205
- * createUser(@Body() userData: any) {
206
- * // Response will have 201 Created status code
207
- * return { id: '123', ...userData };
208
- * }
209
- * ```
210
- */
211
- export declare function HttpCode(status: number): MethodDecorator;
212
- /**
213
- * Decorator that adds a custom HTTP header to the response.
214
- *
215
- * @param name - Header name
216
- * @param value - Header value
217
- * @returns Method decorator
218
- *
219
- * @example
220
- * ```ts
221
- * @Get('/data')
222
- * @Header('Cache-Control', 'max-age=60')
223
- * getData() {
224
- * // Response will include the Cache-Control header
225
- * return { data: '...' };
226
- * }
227
- * ```
228
- */
229
- export declare function Header(name: string, value: string): MethodDecorator;
230
- /**
231
- * Decorator that registers a function to run before route handler execution.
232
- * Useful for pre-processing or logging.
233
- *
234
- * @param fn - Function to execute before the handler
235
- * @returns Method decorator
236
- *
237
- * @example
238
- * ```ts
239
- * @Get('/users/:id')
240
- * @Before((req, res) => console.log(`Accessing user ${req.params.id}`))
241
- * getUser(@Param('id') id: string) {
242
- * // Function will log before this handler runs
243
- * }
244
- * ```
245
- */
246
- export declare function Before(fn: Function): MethodDecorator;
247
- /**
248
- * Decorator that registers a function to run after route handler execution.
249
- * Can access the handler's result.
250
- *
251
- * @param fn - Function to execute after the handler
252
- * @returns Method decorator
253
- *
254
- * @example
255
- * ```ts
256
- * @Get('/users/:id')
257
- * @After((req, res, result) => console.log(`User data sent: ${JSON.stringify(result)}`))
258
- * getUser(@Param('id') id: string) {
259
- * // After this handler, the function will log the returned data
260
- * return { id, name: 'Example' };
261
- * }
262
- * ```
263
- */
264
- export declare function After(fn: Function): MethodDecorator;
265
- /**
266
- * Decorator that requires specific roles for accessing a route.
267
- * Must be used with authentication middleware.
268
- *
269
- * @param roles - List of roles that can access this route
270
- * @returns Method decorator
271
- *
272
- * @example
273
- * ```ts
274
- * @Get('/admin/settings')
275
- * @Roles('admin', 'superuser')
276
- * getSettings() {
277
- * // Only admins and superusers can access
278
- * return { settings: [...] };
279
- * }
280
- * ```
281
- */
282
- export declare function Roles(...roles: string[]): MethodDecorator;
283
- /**
284
- * Decorator that redirects to another URL.
285
- *
286
- * @param url - URL to redirect to (can be absolute or relative)
287
- * @param statusCode - HTTP status code for redirect (default: 302)
288
- * @returns Method decorator
289
- *
290
- * @example
291
- * ```ts
292
- * @Get('/old-path')
293
- * @Redirect('/new-path', 301)
294
- * redirectToNewPath() {
295
- * // This method won't be executed; automatic redirect happens
296
- * }
297
- *
298
- * @Get('/dynamic-redirect')
299
- * @Redirect()
300
- * getDynamicRedirect() {
301
- * // Return an object with url and optionally statusCode
302
- * return { url: '/calculated-path', statusCode: 307 };
303
- * }
304
- * ```
305
- */
306
- export declare function Redirect(url?: string, statusCode?: number): MethodDecorator;
307
- /**
308
- * Registers all controller classes with the provided router.
309
- * This function processes all decorators and sets up the Express routes.
310
- *
311
- * @param router - Express router instance
312
- * @param controllers - Array of controller classes
313
- */
314
- export declare function registerControllers(router: Router, controllers: any[]): void;
315
- //# sourceMappingURL=decorators.utils.d.ts.map