@catbee/utils 0.0.5 → 0.0.7

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 (246) hide show
  1. package/LICENSE +21 -201
  2. package/README.md +51 -888
  3. package/build/esm/config.d.ts +84 -7
  4. package/build/esm/config.js +89 -5
  5. package/build/esm/config.js.map +1 -1
  6. package/build/esm/index.d.ts +4 -0
  7. package/build/esm/index.js +27 -0
  8. package/build/esm/index.js.map +1 -1
  9. package/build/esm/servers/server.builder.d.ts +508 -0
  10. package/build/esm/servers/server.builder.js +702 -0
  11. package/build/esm/servers/server.builder.js.map +1 -0
  12. package/build/esm/servers/server.d.ts +256 -0
  13. package/build/esm/servers/server.js +1201 -0
  14. package/build/esm/servers/server.js.map +1 -0
  15. package/build/esm/types/api-response.d.ts +33 -7
  16. package/build/esm/types/api-response.js +33 -1
  17. package/build/esm/types/api-response.js.map +1 -1
  18. package/build/esm/types/index.d.ts +125 -0
  19. package/build/esm/types/index.js +25 -0
  20. package/build/esm/types/index.js.map +1 -0
  21. package/build/esm/types/server.d.ts +268 -0
  22. package/build/esm/types/server.js +25 -0
  23. package/build/esm/types/server.js.map +1 -0
  24. package/build/esm/utils/array.utils.js +23 -0
  25. package/build/esm/utils/array.utils.js.map +1 -1
  26. package/build/esm/utils/async.utils.d.ts +91 -0
  27. package/build/esm/utils/async.utils.js +267 -0
  28. package/build/esm/utils/async.utils.js.map +1 -1
  29. package/build/esm/utils/cache.utils.js +23 -0
  30. package/build/esm/utils/cache.utils.js.map +1 -1
  31. package/build/esm/utils/context-store.utils.d.ts +3 -0
  32. package/build/esm/utils/context-store.utils.js +32 -6
  33. package/build/esm/utils/context-store.utils.js.map +1 -1
  34. package/build/esm/utils/crypto.utils.js +23 -0
  35. package/build/esm/utils/crypto.utils.js.map +1 -1
  36. package/build/esm/utils/date.utils.d.ts +159 -0
  37. package/build/esm/utils/date.utils.js +389 -0
  38. package/build/esm/utils/date.utils.js.map +1 -0
  39. package/build/esm/utils/decorators.utils.js +23 -1
  40. package/build/esm/utils/decorators.utils.js.map +1 -1
  41. package/build/esm/utils/dir.utils.js +23 -0
  42. package/build/esm/utils/dir.utils.js.map +1 -1
  43. package/build/esm/utils/env.utils.js +23 -0
  44. package/build/esm/utils/env.utils.js.map +1 -1
  45. package/build/esm/utils/exception.utils.js +31 -8
  46. package/build/esm/utils/exception.utils.js.map +1 -1
  47. package/build/esm/utils/fs.utils.js +23 -0
  48. package/build/esm/utils/fs.utils.js.map +1 -1
  49. package/build/esm/utils/http-status-codes.js +23 -0
  50. package/build/esm/utils/http-status-codes.js.map +1 -1
  51. package/build/esm/utils/id.utils.js +23 -0
  52. package/build/esm/utils/id.utils.js.map +1 -1
  53. package/build/esm/utils/logger.utils.d.ts +5 -0
  54. package/build/esm/utils/logger.utils.js +40 -3
  55. package/build/esm/utils/logger.utils.js.map +1 -1
  56. package/build/esm/utils/middleware.utils.d.ts +2 -0
  57. package/build/esm/utils/middleware.utils.js +61 -50
  58. package/build/esm/utils/middleware.utils.js.map +1 -1
  59. package/build/esm/utils/obj.utils.d.ts +10 -3
  60. package/build/esm/utils/obj.utils.js +225 -15
  61. package/build/esm/utils/obj.utils.js.map +1 -1
  62. package/build/esm/utils/performance.utils.d.ts +136 -0
  63. package/build/esm/utils/performance.utils.js +376 -0
  64. package/build/esm/utils/performance.utils.js.map +1 -0
  65. package/build/esm/utils/request.utils.d.ts +9 -0
  66. package/build/esm/utils/request.utils.js +55 -5
  67. package/build/esm/utils/request.utils.js.map +1 -1
  68. package/build/esm/utils/response.utils.d.ts +15 -1
  69. package/build/esm/utils/response.utils.js +51 -0
  70. package/build/esm/utils/response.utils.js.map +1 -1
  71. package/build/esm/utils/stream.utils.d.ts +88 -0
  72. package/build/esm/utils/stream.utils.js +284 -0
  73. package/build/esm/utils/stream.utils.js.map +1 -0
  74. package/build/esm/utils/string.utils.js +23 -0
  75. package/build/esm/utils/string.utils.js.map +1 -1
  76. package/build/esm/utils/type.utils.d.ts +90 -0
  77. package/build/esm/utils/type.utils.js +190 -0
  78. package/build/esm/utils/type.utils.js.map +1 -0
  79. package/build/esm/utils/url.utils.js +23 -0
  80. package/build/esm/utils/url.utils.js.map +1 -1
  81. package/build/esm/utils/validate.utils.d.ts +7 -0
  82. package/build/esm/utils/validate.utils.js +35 -2
  83. package/build/esm/utils/validate.utils.js.map +1 -1
  84. package/build/esnext/config.d.ts +84 -7
  85. package/build/esnext/config.js +89 -5
  86. package/build/esnext/config.js.map +1 -1
  87. package/build/esnext/index.d.ts +4 -0
  88. package/build/esnext/index.js +27 -0
  89. package/build/esnext/index.js.map +1 -1
  90. package/build/esnext/servers/server.builder.d.ts +508 -0
  91. package/build/esnext/servers/server.builder.js +657 -0
  92. package/build/esnext/servers/server.builder.js.map +1 -0
  93. package/build/esnext/servers/server.d.ts +256 -0
  94. package/build/esnext/servers/server.js +908 -0
  95. package/build/esnext/servers/server.js.map +1 -0
  96. package/build/esnext/types/api-response.d.ts +33 -7
  97. package/build/esnext/types/api-response.js +33 -1
  98. package/build/esnext/types/api-response.js.map +1 -1
  99. package/build/esnext/types/index.d.ts +125 -0
  100. package/build/esnext/types/index.js +25 -0
  101. package/build/esnext/types/index.js.map +1 -0
  102. package/build/esnext/types/server.d.ts +268 -0
  103. package/build/esnext/types/server.js +25 -0
  104. package/build/esnext/types/server.js.map +1 -0
  105. package/build/esnext/utils/array.utils.js +23 -0
  106. package/build/esnext/utils/array.utils.js.map +1 -1
  107. package/build/esnext/utils/async.utils.d.ts +91 -0
  108. package/build/esnext/utils/async.utils.js +213 -0
  109. package/build/esnext/utils/async.utils.js.map +1 -1
  110. package/build/esnext/utils/cache.utils.js +23 -0
  111. package/build/esnext/utils/cache.utils.js.map +1 -1
  112. package/build/esnext/utils/context-store.utils.d.ts +3 -0
  113. package/build/esnext/utils/context-store.utils.js +32 -6
  114. package/build/esnext/utils/context-store.utils.js.map +1 -1
  115. package/build/esnext/utils/crypto.utils.js +23 -0
  116. package/build/esnext/utils/crypto.utils.js.map +1 -1
  117. package/build/esnext/utils/date.utils.d.ts +159 -0
  118. package/build/esnext/utils/date.utils.js +384 -0
  119. package/build/esnext/utils/date.utils.js.map +1 -0
  120. package/build/esnext/utils/decorators.utils.js +23 -1
  121. package/build/esnext/utils/decorators.utils.js.map +1 -1
  122. package/build/esnext/utils/dir.utils.js +23 -0
  123. package/build/esnext/utils/dir.utils.js.map +1 -1
  124. package/build/esnext/utils/env.utils.js +23 -0
  125. package/build/esnext/utils/env.utils.js.map +1 -1
  126. package/build/esnext/utils/exception.utils.js +30 -7
  127. package/build/esnext/utils/exception.utils.js.map +1 -1
  128. package/build/esnext/utils/fs.utils.js +23 -0
  129. package/build/esnext/utils/fs.utils.js.map +1 -1
  130. package/build/esnext/utils/http-status-codes.js +23 -0
  131. package/build/esnext/utils/http-status-codes.js.map +1 -1
  132. package/build/esnext/utils/id.utils.js +23 -0
  133. package/build/esnext/utils/id.utils.js.map +1 -1
  134. package/build/esnext/utils/logger.utils.d.ts +5 -0
  135. package/build/esnext/utils/logger.utils.js +40 -3
  136. package/build/esnext/utils/logger.utils.js.map +1 -1
  137. package/build/esnext/utils/middleware.utils.d.ts +2 -0
  138. package/build/esnext/utils/middleware.utils.js +57 -50
  139. package/build/esnext/utils/middleware.utils.js.map +1 -1
  140. package/build/esnext/utils/obj.utils.d.ts +10 -3
  141. package/build/esnext/utils/obj.utils.js +176 -12
  142. package/build/esnext/utils/obj.utils.js.map +1 -1
  143. package/build/esnext/utils/performance.utils.d.ts +136 -0
  144. package/build/esnext/utils/performance.utils.js +271 -0
  145. package/build/esnext/utils/performance.utils.js.map +1 -0
  146. package/build/esnext/utils/request.utils.d.ts +9 -0
  147. package/build/esnext/utils/request.utils.js +46 -5
  148. package/build/esnext/utils/request.utils.js.map +1 -1
  149. package/build/esnext/utils/response.utils.d.ts +15 -1
  150. package/build/esnext/utils/response.utils.js +51 -0
  151. package/build/esnext/utils/response.utils.js.map +1 -1
  152. package/build/esnext/utils/stream.utils.d.ts +88 -0
  153. package/build/esnext/utils/stream.utils.js +210 -0
  154. package/build/esnext/utils/stream.utils.js.map +1 -0
  155. package/build/esnext/utils/string.utils.js +23 -0
  156. package/build/esnext/utils/string.utils.js.map +1 -1
  157. package/build/esnext/utils/type.utils.d.ts +90 -0
  158. package/build/esnext/utils/type.utils.js +187 -0
  159. package/build/esnext/utils/type.utils.js.map +1 -0
  160. package/build/esnext/utils/url.utils.js +23 -0
  161. package/build/esnext/utils/url.utils.js.map +1 -1
  162. package/build/esnext/utils/validate.utils.d.ts +7 -0
  163. package/build/esnext/utils/validate.utils.js +33 -0
  164. package/build/esnext/utils/validate.utils.js.map +1 -1
  165. package/build/src/config.d.ts +84 -7
  166. package/build/src/config.js +90 -6
  167. package/build/src/config.js.map +1 -1
  168. package/build/src/index.d.ts +4 -0
  169. package/build/src/index.js +27 -0
  170. package/build/src/index.js.map +1 -1
  171. package/build/src/servers/server.builder.d.ts +508 -0
  172. package/build/src/servers/server.builder.js +661 -0
  173. package/build/src/servers/server.builder.js.map +1 -0
  174. package/build/src/servers/server.d.ts +256 -0
  175. package/build/src/servers/server.js +948 -0
  176. package/build/src/servers/server.js.map +1 -0
  177. package/build/src/types/api-response.d.ts +33 -7
  178. package/build/src/types/api-response.js +34 -0
  179. package/build/src/types/api-response.js.map +1 -1
  180. package/build/src/types/index.d.ts +125 -0
  181. package/build/src/types/index.js +26 -0
  182. package/build/src/types/index.js.map +1 -0
  183. package/build/src/types/server.d.ts +268 -0
  184. package/build/src/types/server.js +26 -0
  185. package/build/src/types/server.js.map +1 -0
  186. package/build/src/utils/array.utils.js +23 -0
  187. package/build/src/utils/array.utils.js.map +1 -1
  188. package/build/src/utils/async.utils.d.ts +91 -0
  189. package/build/src/utils/async.utils.js +217 -0
  190. package/build/src/utils/async.utils.js.map +1 -1
  191. package/build/src/utils/cache.utils.js +23 -0
  192. package/build/src/utils/cache.utils.js.map +1 -1
  193. package/build/src/utils/context-store.utils.d.ts +3 -0
  194. package/build/src/utils/context-store.utils.js +32 -6
  195. package/build/src/utils/context-store.utils.js.map +1 -1
  196. package/build/src/utils/crypto.utils.js +23 -0
  197. package/build/src/utils/crypto.utils.js.map +1 -1
  198. package/build/src/utils/date.utils.d.ts +159 -0
  199. package/build/src/utils/date.utils.js +396 -0
  200. package/build/src/utils/date.utils.js.map +1 -0
  201. package/build/src/utils/decorators.utils.js +23 -1
  202. package/build/src/utils/decorators.utils.js.map +1 -1
  203. package/build/src/utils/dir.utils.js +23 -0
  204. package/build/src/utils/dir.utils.js.map +1 -1
  205. package/build/src/utils/env.utils.js +23 -0
  206. package/build/src/utils/env.utils.js.map +1 -1
  207. package/build/src/utils/exception.utils.js +30 -7
  208. package/build/src/utils/exception.utils.js.map +1 -1
  209. package/build/src/utils/fs.utils.js +23 -0
  210. package/build/src/utils/fs.utils.js.map +1 -1
  211. package/build/src/utils/http-status-codes.js +23 -0
  212. package/build/src/utils/http-status-codes.js.map +1 -1
  213. package/build/src/utils/id.utils.js +23 -0
  214. package/build/src/utils/id.utils.js.map +1 -1
  215. package/build/src/utils/logger.utils.d.ts +5 -0
  216. package/build/src/utils/logger.utils.js +41 -4
  217. package/build/src/utils/logger.utils.js.map +1 -1
  218. package/build/src/utils/middleware.utils.d.ts +2 -0
  219. package/build/src/utils/middleware.utils.js +56 -49
  220. package/build/src/utils/middleware.utils.js.map +1 -1
  221. package/build/src/utils/obj.utils.d.ts +10 -3
  222. package/build/src/utils/obj.utils.js +177 -12
  223. package/build/src/utils/obj.utils.js.map +1 -1
  224. package/build/src/utils/performance.utils.d.ts +136 -0
  225. package/build/src/utils/performance.utils.js +278 -0
  226. package/build/src/utils/performance.utils.js.map +1 -0
  227. package/build/src/utils/request.utils.d.ts +9 -0
  228. package/build/src/utils/request.utils.js +48 -5
  229. package/build/src/utils/request.utils.js.map +1 -1
  230. package/build/src/utils/response.utils.d.ts +15 -1
  231. package/build/src/utils/response.utils.js +52 -0
  232. package/build/src/utils/response.utils.js.map +1 -1
  233. package/build/src/utils/stream.utils.d.ts +88 -0
  234. package/build/src/utils/stream.utils.js +218 -0
  235. package/build/src/utils/stream.utils.js.map +1 -0
  236. package/build/src/utils/string.utils.js +23 -0
  237. package/build/src/utils/string.utils.js.map +1 -1
  238. package/build/src/utils/type.utils.d.ts +90 -0
  239. package/build/src/utils/type.utils.js +196 -0
  240. package/build/src/utils/type.utils.js.map +1 -0
  241. package/build/src/utils/url.utils.js +23 -0
  242. package/build/src/utils/url.utils.js.map +1 -1
  243. package/build/src/utils/validate.utils.d.ts +7 -0
  244. package/build/src/utils/validate.utils.js +36 -2
  245. package/build/src/utils/validate.utils.js.map +1 -1
  246. package/package.json +39 -9
@@ -0,0 +1,278 @@
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.timeSync = timeSync;
27
+ exports.timeAsync = timeAsync;
28
+ exports.timed = timed;
29
+ exports.memoize = memoize;
30
+ exports.trackMemoryUsage = trackMemoryUsage;
31
+ const cache_utils_1 = require("./cache.utils");
32
+ const logger_utils_1 = require("./logger.utils");
33
+ /**
34
+ * Measure the execution time of a synchronous function.
35
+ *
36
+ * @param fn - Function to measure
37
+ * @param options - Timing options
38
+ * @returns Result containing the return value and timing information
39
+ *
40
+ * @example
41
+ * ```typescript
42
+ * const { result, timing } = timeSync(() => {
43
+ * // Some expensive operation
44
+ * return computeResult();
45
+ * }, { label: 'Computation', log: true });
46
+ *
47
+ * console.log(`Result: ${result}, took ${timing.durationMs}ms`);
48
+ * ```
49
+ */
50
+ function timeSync(fn, options = {}) {
51
+ const { label = fn.name || 'anonymous function', log = false, logLevel = 'debug' } = options;
52
+ const startTime = performance.now();
53
+ const result = fn();
54
+ const endTime = performance.now();
55
+ const durationMs = endTime - startTime;
56
+ const durationSec = durationMs / 1000;
57
+ const timing = {
58
+ durationMs,
59
+ durationSec,
60
+ startTime,
61
+ endTime,
62
+ label
63
+ };
64
+ if (log) {
65
+ const logger = (0, logger_utils_1.getLogger)();
66
+ const message = `${label} completed in ${durationMs.toFixed(2)}ms`;
67
+ switch (logLevel) {
68
+ case 'trace':
69
+ logger.trace({ timing }, message);
70
+ break;
71
+ case 'debug':
72
+ logger.debug({ timing }, message);
73
+ break;
74
+ case 'info':
75
+ logger.info({ timing }, message);
76
+ break;
77
+ case 'warn':
78
+ logger.warn({ timing }, message);
79
+ break;
80
+ case 'error':
81
+ logger.error({ timing }, message);
82
+ break;
83
+ default:
84
+ logger.debug({ timing }, message);
85
+ break;
86
+ }
87
+ }
88
+ return { result, timing };
89
+ }
90
+ /**
91
+ * Measure the execution time of an asynchronous function.
92
+ *
93
+ * @param fn - Async function to measure
94
+ * @param options - Timing options
95
+ * @returns Promise resolving to result and timing information
96
+ *
97
+ * @example
98
+ * ```typescript
99
+ * const { result, timing } = await timeAsync(async () => {
100
+ * // Some expensive async operation
101
+ * const data = await fetchData();
102
+ * return processData(data);
103
+ * }, { label: 'API Request', log: true });
104
+ *
105
+ * console.log(`Fetched ${result.length} items in ${timing.durationSec.toFixed(2)}s`);
106
+ * ```
107
+ */
108
+ async function timeAsync(fn, options = {}) {
109
+ const { label = fn.name || 'anonymous async function', log = false, logLevel = 'debug' } = options;
110
+ const startTime = performance.now();
111
+ const result = await fn();
112
+ const endTime = performance.now();
113
+ const durationMs = endTime - startTime;
114
+ const durationSec = durationMs / 1000;
115
+ const timing = {
116
+ durationMs,
117
+ durationSec,
118
+ startTime,
119
+ endTime,
120
+ label
121
+ };
122
+ if (log) {
123
+ const logger = (0, logger_utils_1.getLogger)();
124
+ const message = `${label} completed in ${durationMs.toFixed(2)}ms`;
125
+ switch (logLevel) {
126
+ case 'trace':
127
+ logger.trace({ timing }, message);
128
+ break;
129
+ case 'debug':
130
+ logger.debug({ timing }, message);
131
+ break;
132
+ case 'info':
133
+ logger.info({ timing }, message);
134
+ break;
135
+ case 'warn':
136
+ logger.warn({ timing }, message);
137
+ break;
138
+ case 'error':
139
+ logger.error({ timing }, message);
140
+ break;
141
+ default:
142
+ logger.debug({ timing }, message);
143
+ break;
144
+ }
145
+ }
146
+ return { result, timing };
147
+ }
148
+ /**
149
+ * Create a timing decorator for class methods.
150
+ *
151
+ * @param options - Timing options
152
+ * @returns Method decorator
153
+ *
154
+ * @example
155
+ * ```typescript
156
+ * class DataService {
157
+ * @timed({ log: true, logLevel: 'info' })
158
+ * async fetchData() {
159
+ * // ...implementation
160
+ * }
161
+ * }
162
+ * ```
163
+ */
164
+ function timed(options = {}) {
165
+ return function (target, propertyKeyOrContext, descriptor) {
166
+ let propertyKey;
167
+ let actualDescriptor;
168
+ // ESNext decorator: second argument is context object
169
+ if (typeof propertyKeyOrContext === 'object' && propertyKeyOrContext !== null && 'name' in propertyKeyOrContext) {
170
+ propertyKey = propertyKeyOrContext.name;
171
+ actualDescriptor = descriptor !== null && descriptor !== void 0 ? descriptor : Object.getOwnPropertyDescriptor(target, propertyKey);
172
+ }
173
+ else {
174
+ // Legacy decorator: second argument is property key
175
+ propertyKey = propertyKeyOrContext;
176
+ actualDescriptor = descriptor !== null && descriptor !== void 0 ? descriptor : Object.getOwnPropertyDescriptor(target, propertyKey);
177
+ }
178
+ const originalMethod = actualDescriptor.value;
179
+ actualDescriptor.value = function (...args) {
180
+ const methodOptions = Object.assign(Object.assign({}, options), { label: options.label || `${target.constructor.name}.${String(propertyKey)}` });
181
+ if (originalMethod.constructor.name === 'AsyncFunction') {
182
+ return timeAsync(() => originalMethod.apply(this, args), methodOptions).then(({ result }) => result);
183
+ }
184
+ else {
185
+ return timeSync(() => originalMethod.apply(this, args), methodOptions).result;
186
+ }
187
+ };
188
+ // For legacy decorators, assign the new descriptor
189
+ if (descriptor) {
190
+ descriptor.value = actualDescriptor.value;
191
+ }
192
+ else {
193
+ Object.defineProperty(target, propertyKey, actualDescriptor);
194
+ }
195
+ // No return needed for method decorators
196
+ };
197
+ }
198
+ /**
199
+ * Memoize function results with optional TTL and max cache size.
200
+ *
201
+ * @param fn - Function to memoize
202
+ * @param options - Memoization options
203
+ * @returns Memoized function
204
+ *
205
+ * @example
206
+ * ```typescript
207
+ * // Cache results for 30 seconds, with a maximum of 100 entries
208
+ * const cachedFetch = memoize(
209
+ * async (url) => {
210
+ * const response = await fetch(url);
211
+ * return response.json();
212
+ * },
213
+ * { ttl: 30000, maxSize: 100, cacheKey: (url) => url }
214
+ * );
215
+ * ```
216
+ */
217
+ function memoize(fn, options = {}) {
218
+ const { ttl, maxSize, autoCleanupMs, cacheKey = (...args) => JSON.stringify(args) } = options;
219
+ // Create a properly configured TTLCache instance
220
+ const cache = new cache_utils_1.TTLCache({
221
+ ttlMs: ttl,
222
+ maxSize: maxSize,
223
+ autoCleanupMs: autoCleanupMs
224
+ });
225
+ return function (...args) {
226
+ const key = cacheKey(...args);
227
+ // Try to get from cache first - TTLCache handles expiration internally
228
+ const cachedValue = cache.get(key);
229
+ if (cachedValue !== undefined) {
230
+ return cachedValue;
231
+ }
232
+ // Calculate the value and store in cache with configured TTL
233
+ const value = fn(...args);
234
+ cache.set(key, value);
235
+ return value;
236
+ };
237
+ }
238
+ /**
239
+ * Track memory usage for a function execution.
240
+ *
241
+ * @param fn - Function to track
242
+ * @param options - Memory tracking options
243
+ * @returns Result and memory usage information
244
+ */
245
+ function trackMemoryUsage(fn, options = {}) {
246
+ const { log = false, label = fn.name || 'anonymous function' } = options;
247
+ // Collect garbage before measuring (optional)
248
+ if (global.gc) {
249
+ global.gc();
250
+ }
251
+ const beforeMemory = process.memoryUsage();
252
+ const result = fn();
253
+ const afterMemory = process.memoryUsage();
254
+ // Calculate differences
255
+ const diff = {};
256
+ for (const key in afterMemory) {
257
+ if (Object.prototype.hasOwnProperty.call(afterMemory, key)) {
258
+ diff[key] = afterMemory[key] - beforeMemory[key];
259
+ }
260
+ }
261
+ if (log) {
262
+ (0, logger_utils_1.getLogger)().info({
263
+ label,
264
+ memoryBefore: beforeMemory,
265
+ memoryAfter: afterMemory,
266
+ memoryDiff: diff
267
+ }, `Memory usage for ${label}`);
268
+ }
269
+ return {
270
+ result,
271
+ memoryUsage: {
272
+ before: beforeMemory,
273
+ after: afterMemory,
274
+ diff
275
+ }
276
+ };
277
+ }
278
+ //# sourceMappingURL=performance.utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"performance.utils.js","sourceRoot":"","sources":["../../../src/utils/performance.utils.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;;AAkDH,4BA6CC;AAoBD,8BAgDC;AAkBD,sBAsCC;AAqBD,0BAoCC;AASD,4CAgDC;AA3UD,+CAAyC;AACzC,iDAA2C;AA8B3C;;;;;;;;;;;;;;;;GAgBG;AACH,SAAgB,QAAQ,CAAI,EAAW,EAAE,UAAyB,EAAE;IAClE,MAAM,EAAE,KAAK,GAAG,EAAE,CAAC,I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C5B,CAAC;IACJ,CAAC;IAED,OAAO;QACL,MAAM;QACN,WAAW,EAAE;YACX,MAAM,EAAE,YAAY;YACpB,KAAK,EAAE,WAAW;YAClB,IAAI;SACL;KACF,CAAC;AACJ,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 { TTLCache } from './cache.utils';\nimport { getLogger } from './logger.utils';\n\n/**\n * Options for timing function execution.\n */\nexport interface TimingOptions {\n /** Optional label for the timing (defaults to function name) */\n label?: string;\n /** Whether to log the timing (default: false) */\n log?: boolean;\n /** Log level to use if logging is enabled (default: 'debug') */\n logLevel?: 'trace' | 'debug' | 'info' | 'warn' | 'error';\n}\n\n/**\n * Result of a timing operation.\n */\nexport interface TimingResult {\n /** Duration in milliseconds */\n durationMs: number;\n /** Duration in seconds */\n durationSec: number;\n /** Start timestamp */\n startTime: number;\n /** End timestamp */\n endTime: number;\n /** Label used for the timing */\n label: string;\n}\n\n/**\n * Measure the execution time of a synchronous function.\n *\n * @param fn - Function to measure\n * @param options - Timing options\n * @returns Result containing the return value and timing information\n *\n * @example\n * ```typescript\n * const { result, timing } = timeSync(() => {\n * // Some expensive operation\n * return computeResult();\n * }, { label: 'Computation', log: true });\n *\n * console.log(`Result: ${result}, took ${timing.durationMs}ms`);\n * ```\n */\nexport function timeSync<T>(fn: () => T, options: TimingOptions = {}): { result: T; timing: TimingResult } {\n const { label = fn.name || 'anonymous function', log = false, logLevel = 'debug' } = options;\n\n const startTime = performance.now();\n const result = fn();\n const endTime = performance.now();\n\n const durationMs = endTime - startTime;\n const durationSec = durationMs / 1000;\n\n const timing: TimingResult = {\n durationMs,\n durationSec,\n startTime,\n endTime,\n label\n };\n\n if (log) {\n const logger = getLogger();\n const message = `${label} completed in ${durationMs.toFixed(2)}ms`;\n\n switch (logLevel) {\n case 'trace':\n logger.trace({ timing }, message);\n break;\n case 'debug':\n logger.debug({ timing }, message);\n break;\n case 'info':\n logger.info({ timing }, message);\n break;\n case 'warn':\n logger.warn({ timing }, message);\n break;\n case 'error':\n logger.error({ timing }, message);\n break;\n default:\n logger.debug({ timing }, message);\n break;\n }\n }\n\n return { result, timing };\n}\n\n/**\n * Measure the execution time of an asynchronous function.\n *\n * @param fn - Async function to measure\n * @param options - Timing options\n * @returns Promise resolving to result and timing information\n *\n * @example\n * ```typescript\n * const { result, timing } = await timeAsync(async () => {\n * // Some expensive async operation\n * const data = await fetchData();\n * return processData(data);\n * }, { label: 'API Request', log: true });\n *\n * console.log(`Fetched ${result.length} items in ${timing.durationSec.toFixed(2)}s`);\n * ```\n */\nexport async function timeAsync<T>(\n fn: () => Promise<T>,\n options: TimingOptions = {}\n): Promise<{ result: T; timing: TimingResult }> {\n const { label = fn.name || 'anonymous async function', log = false, logLevel = 'debug' } = options;\n\n const startTime = performance.now();\n const result = await fn();\n const endTime = performance.now();\n\n const durationMs = endTime - startTime;\n const durationSec = durationMs / 1000;\n\n const timing: TimingResult = {\n durationMs,\n durationSec,\n startTime,\n endTime,\n label\n };\n\n if (log) {\n const logger = getLogger();\n const message = `${label} completed in ${durationMs.toFixed(2)}ms`;\n\n switch (logLevel) {\n case 'trace':\n logger.trace({ timing }, message);\n break;\n case 'debug':\n logger.debug({ timing }, message);\n break;\n case 'info':\n logger.info({ timing }, message);\n break;\n case 'warn':\n logger.warn({ timing }, message);\n break;\n case 'error':\n logger.error({ timing }, message);\n break;\n default:\n logger.debug({ timing }, message);\n break;\n }\n }\n\n return { result, timing };\n}\n\n/**\n * Create a timing decorator for class methods.\n *\n * @param options - Timing options\n * @returns Method decorator\n *\n * @example\n * ```typescript\n * class DataService {\n * @timed({ log: true, logLevel: 'info' })\n * async fetchData() {\n * // ...implementation\n * }\n * }\n * ```\n */\nexport function timed(options: TimingOptions = {}) {\n return function (target: any, propertyKeyOrContext: string | symbol | any, descriptor?: PropertyDescriptor): void {\n let propertyKey: string | symbol;\n let actualDescriptor: PropertyDescriptor;\n\n // ESNext decorator: second argument is context object\n if (typeof propertyKeyOrContext === 'object' && propertyKeyOrContext !== null && 'name' in propertyKeyOrContext) {\n propertyKey = propertyKeyOrContext.name;\n actualDescriptor = descriptor ?? Object.getOwnPropertyDescriptor(target, propertyKey)!;\n } else {\n // Legacy decorator: second argument is property key\n propertyKey = propertyKeyOrContext;\n actualDescriptor = descriptor ?? Object.getOwnPropertyDescriptor(target, propertyKey)!;\n }\n\n const originalMethod = actualDescriptor.value;\n\n actualDescriptor.value = function (...args: any[]) {\n const methodOptions = {\n ...options,\n label: options.label || `${target.constructor.name}.${String(propertyKey)}`\n };\n\n if (originalMethod.constructor.name === 'AsyncFunction') {\n return timeAsync(() => originalMethod.apply(this, args), methodOptions).then(({ result }) => result);\n } else {\n return timeSync(() => originalMethod.apply(this, args), methodOptions).result;\n }\n };\n\n // For legacy decorators, assign the new descriptor\n if (descriptor) {\n descriptor.value = actualDescriptor.value;\n } else {\n Object.defineProperty(target, propertyKey, actualDescriptor);\n }\n // No return needed for method decorators\n };\n}\n\n/**\n * Memoize function results with optional TTL and max cache size.\n *\n * @param fn - Function to memoize\n * @param options - Memoization options\n * @returns Memoized function\n *\n * @example\n * ```typescript\n * // Cache results for 30 seconds, with a maximum of 100 entries\n * const cachedFetch = memoize(\n * async (url) => {\n * const response = await fetch(url);\n * return response.json();\n * },\n * { ttl: 30000, maxSize: 100, cacheKey: (url) => url }\n * );\n * ```\n */\nexport function memoize<T, Args extends any[]>(\n fn: (...args: Args) => T,\n options: {\n /** Time-to-live in milliseconds (default: indefinite) */\n ttl?: number;\n /** Maximum cache size (default: unlimited) */\n maxSize?: number;\n /** Function to generate a cache key from arguments */\n cacheKey?: (...args: Args) => string;\n /** Auto-cleanup interval in milliseconds (default: disabled) */\n autoCleanupMs?: number;\n } = {}\n) {\n const { ttl, maxSize, autoCleanupMs, cacheKey = (...args) => JSON.stringify(args) } = options;\n\n // Create a properly configured TTLCache instance\n const cache = new TTLCache<string, T>({\n ttlMs: ttl,\n maxSize: maxSize,\n autoCleanupMs: autoCleanupMs\n });\n\n return function (...args: Args): T {\n const key = cacheKey(...args);\n\n // Try to get from cache first - TTLCache handles expiration internally\n const cachedValue = cache.get(key);\n if (cachedValue !== undefined) {\n return cachedValue;\n }\n\n // Calculate the value and store in cache with configured TTL\n const value = fn(...args);\n cache.set(key, value);\n return value;\n };\n}\n\n/**\n * Track memory usage for a function execution.\n *\n * @param fn - Function to track\n * @param options - Memory tracking options\n * @returns Result and memory usage information\n */\nexport function trackMemoryUsage<T>(\n fn: () => T,\n options: {\n /** Whether to log the memory usage (default: false) */\n log?: boolean;\n /** Label for the memory tracking (default: function name) */\n label?: string;\n } = {}\n): { result: T; memoryUsage: { before: NodeJS.MemoryUsage; after: NodeJS.MemoryUsage; diff: Record<string, number> } } {\n const { log = false, label = fn.name || 'anonymous function' } = options;\n\n // Collect garbage before measuring (optional)\n if (global.gc) {\n global.gc();\n }\n\n const beforeMemory = process.memoryUsage();\n const result = fn();\n const afterMemory = process.memoryUsage();\n\n // Calculate differences\n const diff: Record<string, number> = {};\n for (const key in afterMemory) {\n if (Object.prototype.hasOwnProperty.call(afterMemory, key)) {\n diff[key] = (afterMemory as any)[key] - (beforeMemory as any)[key];\n }\n }\n\n if (log) {\n getLogger().info(\n {\n label,\n memoryBefore: beforeMemory,\n memoryAfter: afterMemory,\n memoryDiff: diff\n },\n `Memory usage for ${label}`\n );\n }\n\n return {\n result,\n memoryUsage: {\n before: beforeMemory,\n after: afterMemory,\n diff\n }\n };\n}\n"]}
@@ -1,3 +1,5 @@
1
+ import { Request } from 'express';
2
+ import { WithPagination } from '../types/api-response';
1
3
  /**
2
4
  * Options for parsing and validating request parameters.
3
5
  */
@@ -22,6 +24,13 @@ export interface ValidationResult<T> {
22
24
  /** Error message if validation failed */
23
25
  error?: string;
24
26
  }
27
+ /**
28
+ * Extracts pagination, sorting, and optional search params from a request.
29
+ *
30
+ * @param req - Express request
31
+ * @returns Object containing validated pagination, sorting, and additional query params
32
+ */
33
+ export declare const getPaginationParams: <T = {}>(req: Request) => WithPagination<T>;
25
34
  /**
26
35
  * Safely parses a string parameter to a number.
27
36
  *
@@ -1,10 +1,53 @@
1
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
+ */
2
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.getPaginationParams = void 0;
3
27
  exports.parseNumberParam = parseNumberParam;
4
28
  exports.parseBooleanParam = parseBooleanParam;
5
29
  exports.extractPaginationParams = extractPaginationParams;
6
30
  exports.extractSortParams = extractSortParams;
7
31
  exports.extractFilterParams = extractFilterParams;
32
+ const exception_utils_1 = require("./exception.utils");
33
+ /**
34
+ * Extracts pagination, sorting, and optional search params from a request.
35
+ *
36
+ * @param req - Express request
37
+ * @returns Object containing validated pagination, sorting, and additional query params
38
+ */
39
+ const getPaginationParams = (req) => {
40
+ const query = req.query;
41
+ // Extract page & limit
42
+ const { page, limit } = extractPaginationParams(query, 1, 20, 100);
43
+ const { sortBy, sortOrder } = extractSortParams(query, []);
44
+ // Optional search param
45
+ const search = typeof query.search === 'string' ? query.search : undefined;
46
+ return Object.assign(Object.assign({}, query), { page,
47
+ limit,
48
+ sortBy, sortOrder: sortOrder, search });
49
+ };
50
+ exports.getPaginationParams = getPaginationParams;
8
51
  /**
9
52
  * Safely parses a string parameter to a number.
10
53
  *
@@ -19,7 +62,7 @@ function parseNumberParam(value, options = {}) {
19
62
  if (required) {
20
63
  const error = `Required number parameter is missing`;
21
64
  if (throwOnError)
22
- throw new Error(error);
65
+ throw new exception_utils_1.BadRequestException(error);
23
66
  return { isValid: false, value: null, error };
24
67
  }
25
68
  return {
@@ -32,7 +75,7 @@ function parseNumberParam(value, options = {}) {
32
75
  const num = Number(value);
33
76
  if (isNaN(num)) {
34
77
  if (throwOnError)
35
- throw new Error(errorMessage);
78
+ throw new exception_utils_1.BadRequestException(errorMessage);
36
79
  return { isValid: false, value: null, error: errorMessage };
37
80
  }
38
81
  return { isValid: true, value: num };
@@ -51,7 +94,7 @@ function parseBooleanParam(value, options = {}) {
51
94
  if (required) {
52
95
  const error = `Required boolean parameter is missing`;
53
96
  if (throwOnError)
54
- throw new Error(error);
97
+ throw new exception_utils_1.BadRequestException(error);
55
98
  return { isValid: false, value: null, error };
56
99
  }
57
100
  return {
@@ -69,7 +112,7 @@ function parseBooleanParam(value, options = {}) {
69
112
  return { isValid: true, value: false };
70
113
  }
71
114
  if (throwOnError)
72
- throw new Error(errorMessage);
115
+ throw new exception_utils_1.BadRequestException(errorMessage);
73
116
  return { isValid: false, value: null, error: errorMessage };
74
117
  }
75
118
  /**
@@ -127,7 +170,7 @@ function extractSortParams(query, allowedFields, defaultSort = { sortBy: 'create
127
170
  }
128
171
  }
129
172
  // Validate field
130
- if (!allowedFields.includes(sortBy)) {
173
+ if (allowedFields.length && !allowedFields.includes(sortBy)) {
131
174
  sortBy = defaultSort.sortBy;
132
175
  }
133
176
  return { sortBy, sortOrder };
@@ -1 +1 @@
1
- {"version":3,"file":"request.utils.js","sourceRoot":"","sources":["../../../src/utils/request.utils.ts"],"names":[],"mappings":";;AAsCA,4CA0BC;AASD,8CAiCC;AAWD,0DAoBC;AAUD,8CAmCC;AASD,kDAcC;AA9KD;;;;;;GAMG;AACH,SAAgB,gBAAgB,CAAC,KAAyB,EAAE,UAA6B,EAAE;IACzF,MAAM,EAAE,YAAY,GAAG,KAAK,EAAE,YAAY,GAAG,0BAA0B,EAAE,YAAY,EAAE,QAAQ,GAAG,KAAK,EAAE,GAAG,OAAO,CAAC;IAEpH,wBAAwB;IACxB,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;QACxB,IAAI,QAAQ,EAAE,CAAC;YACb,MAAM,KAAK,GAAG,sCAAsC,CAAC;YACrD,IAAI,YAAY;gBAAE,MAAM,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC;YACzC,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AwB;IAExB,MAAM,OAAO,GAAsC,EAAE,CAAC;IAEtD,sCAAsC;IACtC,KAAK,MAAM,KAAK,IAAI,cAAc,EAAE,CAAC;QACnC,IAAI,KAAK,IAAI,KAAK,EAAE,CAAC;YACnB,OAAO,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC;QAChC,CAAC;IACH,CAAC;IAED,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["/**\n * Options for parsing and validating request parameters.\n */\nexport interface ValidationOptions {\n /** Whether to throw an error on validation failure */\n throwOnError?: boolean;\n\n /** Custom error message for validation failures */\n errorMessage?: string;\n\n /** Default value to use if parameter is missing */\n defaultValue?: any;\n\n /** Whether the parameter is required */\n required?: boolean;\n}\n\n/**\n * Result of a parameter validation operation.\n */\nexport interface ValidationResult<T> {\n /** Whether validation was successful */\n isValid: boolean;\n\n /** The validated and potentially transformed value */\n value: T | null;\n\n /** Error message if validation failed */\n error?: string;\n}\n\n/**\n * Safely parses a string parameter to a number.\n *\n * @param value - String value to parse\n * @param options - Validation options\n * @returns Validation result containing the parsed number or error\n */\nexport function parseNumberParam(value: string | undefined, options: ValidationOptions = {}): ValidationResult<number> {\n const { throwOnError = false, errorMessage = 'Invalid number parameter', defaultValue, required = false } = options;\n\n // Handle undefined case\n if (value === undefined) {\n if (required) {\n const error = `Required number parameter is missing`;\n if (throwOnError) throw new Error(error);\n return { isValid: false, value: null, error };\n }\n\n return {\n isValid: defaultValue !== undefined,\n value: defaultValue !== undefined ? defaultValue : null,\n error: defaultValue === undefined ? 'Missing parameter with no default' : undefined\n };\n }\n\n // Parse and validate the number\n const num = Number(value);\n if (isNaN(num)) {\n if (throwOnError) throw new Error(errorMessage);\n return { isValid: false, value: null, error: errorMessage };\n }\n\n return { isValid: true, value: num };\n}\n\n/**\n * Safely parses a string parameter to a boolean.\n *\n * @param value - String value to parse\n * @param options - Validation options\n * @returns Validation result containing the parsed boolean or error\n */\nexport function parseBooleanParam(\n value: string | undefined,\n options: ValidationOptions = {}\n): ValidationResult<boolean> {\n const { throwOnError = false, errorMessage = 'Invalid boolean parameter', defaultValue, required = false } = options;\n\n // Handle undefined case\n if (value === undefined) {\n if (required) {\n const error = `Required boolean parameter is missing`;\n if (throwOnError) throw new Error(error);\n return { isValid: false, value: null, error };\n }\n\n return {\n isValid: defaultValue !== undefined,\n value: defaultValue !== undefined ? defaultValue : null,\n error: defaultValue === undefined ? 'Missing parameter with no default' : undefined\n };\n }\n\n // Parse the boolean value with various allowed formats\n const lowercaseValue = value.toLowerCase();\n if (['true', 't', 'yes', 'y', '1'].includes(lowercaseValue)) {\n return { isValid: true, value: true };\n }\n\n if (['false', 'f', 'no', 'n', '0'].includes(lowercaseValue)) {\n return { isValid: true, value: false };\n }\n\n if (throwOnError) throw new Error(errorMessage);\n return { isValid: false, value: null, error: errorMessage };\n}\n\n/**\n * Extracts pagination parameters from request query parameters.\n *\n * @param query - Query parameters object\n * @param defaultPage - Default page number if not specified (defaults to 1)\n * @param defaultLimit - Default per page size if not specified (defaults to 20)\n * @param maxLimitSize - Maximum allowed per page size (defaults to 100)\n * @returns Object containing validated page and limit\n */\nexport function extractPaginationParams(\n query: Record<string, string | string[]>,\n defaultPage: number = 1,\n defaultLimit: number = 20,\n maxLimitSize: number = 100\n): { page: number; limit: number } {\n // Parse page parameter\n const pageParam = typeof query.page === 'string' ? query.page : undefined;\n const pageResult = parseNumberParam(pageParam, { defaultValue: defaultPage });\n\n // Parse limit parameter\n const limitParam = typeof query.limit === 'string' ? query.limit : undefined;\n const limitResult = parseNumberParam(limitParam, { defaultValue: defaultLimit });\n\n // Ensure valid values (handle 0 → fallback to default)\n const page = pageResult.value && pageResult.value > 0 ? pageResult.value : defaultPage;\n\n const limit = limitResult.value && limitResult.value > 0 ? Math.min(limitResult.value, maxLimitSize) : defaultLimit;\n\n return { page, limit };\n}\n\n/**\n * Extracts sorting parameters from request query parameters.\n *\n * @param query - Query parameters object\n * @param allowedFields - Array of field names that are allowed to be sorted\n * @param defaultSort - Default sort configuration if not specified\n * @returns Object containing sort field and direction\n */\nexport function extractSortParams(\n query: Record<string, string | string[]>,\n allowedFields: string[],\n defaultSort: { sortBy: string; sortOrder: 'asc' | 'desc' } = { sortBy: 'createdAt', sortOrder: 'desc' }\n): { sortBy: string; sortOrder: 'asc' | 'desc' } {\n let sortBy = defaultSort.sortBy;\n let sortOrder: 'asc' | 'desc' = defaultSort.sortOrder;\n\n // Extract from `sortBy` or `sort`\n if (typeof query.sortBy === 'string') {\n sortBy = query.sortBy;\n } else if (Array.isArray(query.sortBy)) {\n sortBy = query.sortBy[0];\n } else if (typeof query.sort === 'string') {\n sortBy = query.sort.startsWith('-') ? query.sort.slice(1) : query.sort;\n sortOrder = query.sort.startsWith('-') ? 'desc' : 'asc';\n } else if (Array.isArray(query.sort)) {\n sortBy = query.sort[0].startsWith('-') ? query.sort[0].slice(1) : query.sort[0];\n sortOrder = query.sort[0].startsWith('-') ? 'desc' : 'asc';\n }\n\n // Explicit sortOrder (overrides inferred one if valid)\n if (typeof query.sortOrder === 'string') {\n const order = query.sortOrder.toLowerCase();\n if (order === 'asc' || order === 'desc') {\n sortOrder = order;\n }\n }\n\n // Validate field\n if (!allowedFields.includes(sortBy)) {\n sortBy = defaultSort.sortBy;\n }\n\n return { sortBy, sortOrder };\n}\n\n/**\n * Extracts filter parameters from query parameters based on allowed filter fields.\n *\n * @param query - Query parameters object\n * @param allowedFilters - Array of field names that are allowed to be used as filters\n * @returns Object containing the filters as key-value pairs\n */\nexport function extractFilterParams(\n query: Record<string, string | string[]>,\n allowedFilters: string[]\n): Record<string, string | string[]> {\n const filters: Record<string, string | string[]> = {};\n\n // Find filter parameters in the query\n for (const field of allowedFilters) {\n if (field in query) {\n filters[field] = query[field];\n }\n }\n\n return filters;\n}\n"]}
1
+ {"version":3,"file":"request.utils.js","sourceRoot":"","sources":["../../../src/utils/request.utils.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;;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IAAI,cAAc,EAAE,CAAC;QACnC,IAAI,KAAK,IAAI,KAAK,EAAE,CAAC;YACnB,OAAO,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC;QAChC,CAAC;IACH,CAAC;IAED,OAAO,OAAO,CAAC;AACjB,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 { Request } from 'express';\nimport { SortDirection, WithPagination } from '../types/api-response';\nimport { BadRequestException } from './exception.utils';\n\n/**\n * Options for parsing and validating request parameters.\n */\nexport interface ValidationOptions {\n /** Whether to throw an error on validation failure */\n throwOnError?: boolean;\n\n /** Custom error message for validation failures */\n errorMessage?: string;\n\n /** Default value to use if parameter is missing */\n defaultValue?: any;\n\n /** Whether the parameter is required */\n required?: boolean;\n}\n\n/**\n * Result of a parameter validation operation.\n */\nexport interface ValidationResult<T> {\n /** Whether validation was successful */\n isValid: boolean;\n\n /** The validated and potentially transformed value */\n value: T | null;\n\n /** Error message if validation failed */\n error?: string;\n}\n\n/**\n * Extracts pagination, sorting, and optional search params from a request.\n *\n * @param req - Express request\n * @returns Object containing validated pagination, sorting, and additional query params\n */\nexport const getPaginationParams = <T = {}>(req: Request): WithPagination<T> => {\n const query = req.query as Record<string, string | string[]>;\n\n // Extract page & limit\n const { page, limit } = extractPaginationParams(query, 1, 20, 100);\n const { sortBy, sortOrder } = extractSortParams(query, []);\n\n // Optional search param\n const search = typeof query.search === 'string' ? query.search : undefined;\n\n return {\n ...(query as T),\n page,\n limit,\n sortBy,\n sortOrder: sortOrder as SortDirection,\n search\n };\n};\n\n/**\n * Safely parses a string parameter to a number.\n *\n * @param value - String value to parse\n * @param options - Validation options\n * @returns Validation result containing the parsed number or error\n */\nexport function parseNumberParam(value: string | undefined, options: ValidationOptions = {}): ValidationResult<number> {\n const { throwOnError = false, errorMessage = 'Invalid number parameter', defaultValue, required = false } = options;\n\n // Handle undefined case\n if (value === undefined) {\n if (required) {\n const error = `Required number parameter is missing`;\n if (throwOnError) throw new BadRequestException(error);\n return { isValid: false, value: null, error };\n }\n\n return {\n isValid: defaultValue !== undefined,\n value: defaultValue !== undefined ? defaultValue : null,\n error: defaultValue === undefined ? 'Missing parameter with no default' : undefined\n };\n }\n\n // Parse and validate the number\n const num = Number(value);\n if (isNaN(num)) {\n if (throwOnError) throw new BadRequestException(errorMessage);\n return { isValid: false, value: null, error: errorMessage };\n }\n\n return { isValid: true, value: num };\n}\n\n/**\n * Safely parses a string parameter to a boolean.\n *\n * @param value - String value to parse\n * @param options - Validation options\n * @returns Validation result containing the parsed boolean or error\n */\nexport function parseBooleanParam(\n value: string | undefined,\n options: ValidationOptions = {}\n): ValidationResult<boolean> {\n const { throwOnError = false, errorMessage = 'Invalid boolean parameter', defaultValue, required = false } = options;\n\n // Handle undefined case\n if (value === undefined) {\n if (required) {\n const error = `Required boolean parameter is missing`;\n if (throwOnError) throw new BadRequestException(error);\n return { isValid: false, value: null, error };\n }\n\n return {\n isValid: defaultValue !== undefined,\n value: defaultValue !== undefined ? defaultValue : null,\n error: defaultValue === undefined ? 'Missing parameter with no default' : undefined\n };\n }\n\n // Parse the boolean value with various allowed formats\n const lowercaseValue = value.toLowerCase();\n if (['true', 't', 'yes', 'y', '1'].includes(lowercaseValue)) {\n return { isValid: true, value: true };\n }\n\n if (['false', 'f', 'no', 'n', '0'].includes(lowercaseValue)) {\n return { isValid: true, value: false };\n }\n\n if (throwOnError) throw new BadRequestException(errorMessage);\n return { isValid: false, value: null, error: errorMessage };\n}\n\n/**\n * Extracts pagination parameters from request query parameters.\n *\n * @param query - Query parameters object\n * @param defaultPage - Default page number if not specified (defaults to 1)\n * @param defaultLimit - Default per page size if not specified (defaults to 20)\n * @param maxLimitSize - Maximum allowed per page size (defaults to 100)\n * @returns Object containing validated page and limit\n */\nexport function extractPaginationParams(\n query: Record<string, string | string[]>,\n defaultPage: number = 1,\n defaultLimit: number = 20,\n maxLimitSize: number = 100\n): { page: number; limit: number } {\n // Parse page parameter\n const pageParam = typeof query.page === 'string' ? query.page : undefined;\n const pageResult = parseNumberParam(pageParam, { defaultValue: defaultPage });\n\n // Parse limit parameter\n const limitParam = typeof query.limit === 'string' ? query.limit : undefined;\n const limitResult = parseNumberParam(limitParam, { defaultValue: defaultLimit });\n\n // Ensure valid values (handle 0 → fallback to default)\n const page = pageResult.value && pageResult.value > 0 ? pageResult.value : defaultPage;\n\n const limit = limitResult.value && limitResult.value > 0 ? Math.min(limitResult.value, maxLimitSize) : defaultLimit;\n\n return { page, limit };\n}\n\n/**\n * Extracts sorting parameters from request query parameters.\n *\n * @param query - Query parameters object\n * @param allowedFields - Array of field names that are allowed to be sorted\n * @param defaultSort - Default sort configuration if not specified\n * @returns Object containing sort field and direction\n */\nexport function extractSortParams(\n query: Record<string, string | string[]>,\n allowedFields: string[],\n defaultSort: { sortBy: string; sortOrder: 'asc' | 'desc' } = { sortBy: 'createdAt', sortOrder: 'desc' }\n): { sortBy: string; sortOrder: 'asc' | 'desc' } {\n let sortBy = defaultSort.sortBy;\n let sortOrder: 'asc' | 'desc' = defaultSort.sortOrder;\n\n // Extract from `sortBy` or `sort`\n if (typeof query.sortBy === 'string') {\n sortBy = query.sortBy;\n } else if (Array.isArray(query.sortBy)) {\n sortBy = query.sortBy[0];\n } else if (typeof query.sort === 'string') {\n sortBy = query.sort.startsWith('-') ? query.sort.slice(1) : query.sort;\n sortOrder = query.sort.startsWith('-') ? 'desc' : 'asc';\n } else if (Array.isArray(query.sort)) {\n sortBy = query.sort[0].startsWith('-') ? query.sort[0].slice(1) : query.sort[0];\n sortOrder = query.sort[0].startsWith('-') ? 'desc' : 'asc';\n }\n\n // Explicit sortOrder (overrides inferred one if valid)\n if (typeof query.sortOrder === 'string') {\n const order = query.sortOrder.toLowerCase();\n if (order === 'asc' || order === 'desc') {\n sortOrder = order;\n }\n }\n\n // Validate field\n if (allowedFields.length && !allowedFields.includes(sortBy)) {\n sortBy = defaultSort.sortBy;\n }\n\n return { sortBy, sortOrder };\n}\n\n/**\n * Extracts filter parameters from query parameters based on allowed filter fields.\n *\n * @param query - Query parameters object\n * @param allowedFilters - Array of field names that are allowed to be used as filters\n * @returns Object containing the filters as key-value pairs\n */\nexport function extractFilterParams(\n query: Record<string, string | string[]>,\n allowedFilters: string[]\n): Record<string, string | string[]> {\n const filters: Record<string, string | string[]> = {};\n\n // Find filter parameters in the query\n for (const field of allowedFilters) {\n if (field in query) {\n filters[field] = query[field];\n }\n }\n\n return filters;\n}\n"]}
@@ -1,4 +1,5 @@
1
- import { ApiResponse } from '../types/api-response';
1
+ import { Request } from 'express';
2
+ import { ApiErrorResponse, ApiResponse } from '../types/api-response';
2
3
  /**
3
4
  * Standard HTTP response wrapper for successful responses.
4
5
  * Implements the `ApiResponse<T>` interface and sets default values.
@@ -128,6 +129,19 @@ export declare function createSuccessResponse<T>(data: T, message?: string): Suc
128
129
  * @returns {ErrorResponse} A properly formatted error response.
129
130
  */
130
131
  export declare function createErrorResponse(message: string, statusCode?: number): ErrorResponse;
132
+ /**
133
+ * Creates a final error response with request information.
134
+ *
135
+ * @param req - The original request object.
136
+ * @param status - The HTTP status code.
137
+ * @param message - The error message.
138
+ * @param error - The original error object (optional).
139
+ * @param options - Additional options for the response (optional).
140
+ * @returns A properly formatted final error response.
141
+ */
142
+ export declare function createFinalErrorResponse(req: Request, status: number, message: string, error?: any, options?: {
143
+ includeDetails?: boolean;
144
+ }): ApiErrorResponse;
131
145
  /**
132
146
  * Creates a paginated response from array data.
133
147
  *
@@ -1,11 +1,36 @@
1
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
+ */
2
25
  Object.defineProperty(exports, "__esModule", { value: true });
3
26
  exports.RedirectResponse = exports.NoContentResponse = exports.PaginatedResponse = exports.ErrorResponse = exports.SuccessResponse = void 0;
4
27
  exports.createSuccessResponse = createSuccessResponse;
5
28
  exports.createErrorResponse = createErrorResponse;
29
+ exports.createFinalErrorResponse = createFinalErrorResponse;
6
30
  exports.createPaginatedResponse = createPaginatedResponse;
7
31
  exports.sendResponse = sendResponse;
8
32
  const context_store_utils_1 = require("./context-store.utils");
33
+ const env_utils_1 = require("./env.utils");
9
34
  const id_utils_1 = require("./id.utils");
10
35
  /**
11
36
  * Standard HTTP response wrapper for successful responses.
@@ -148,6 +173,33 @@ function createSuccessResponse(data, message = 'Success') {
148
173
  function createErrorResponse(message, statusCode = 500) {
149
174
  return new ErrorResponse(message, statusCode);
150
175
  }
176
+ /**
177
+ * Creates a final error response with request information.
178
+ *
179
+ * @param req - The original request object.
180
+ * @param status - The HTTP status code.
181
+ * @param message - The error message.
182
+ * @param error - The original error object (optional).
183
+ * @param options - Additional options for the response (optional).
184
+ * @returns A properly formatted final error response.
185
+ */
186
+ function createFinalErrorResponse(req, status, message, error, options) {
187
+ const isDev = env_utils_1.Env.isDev();
188
+ const includeDetails = (options === null || options === void 0 ? void 0 : options.includeDetails) && isDev;
189
+ const response = {
190
+ error: true,
191
+ message,
192
+ timestamp: new Date().toISOString(),
193
+ requestId: (error === null || error === void 0 ? void 0 : error.requestId) || (req === null || req === void 0 ? void 0 : req.id) || (0, id_utils_1.uuid)(),
194
+ status,
195
+ path: req.originalUrl || req.url
196
+ };
197
+ // Include stack trace in development mode if requested
198
+ if (includeDetails && (error === null || error === void 0 ? void 0 : error.stack)) {
199
+ response.stack = error.stack.split('\n').map((line) => line.trim());
200
+ }
201
+ return response;
202
+ }
151
203
  /**
152
204
  * Creates a paginated response from array data.
153
205
  *