@catbee/utils 0.0.2 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/build/esm/config.d.ts +1 -1
  2. package/build/esm/config.js +7 -7
  3. package/build/esm/config.js.map +1 -1
  4. package/build/esm/index.d.ts +20 -19
  5. package/build/esm/index.js +20 -19
  6. package/build/esm/index.js.map +1 -1
  7. package/build/esm/types/api-response.d.ts +2 -2
  8. package/build/esm/types/api-response.js.map +1 -1
  9. package/build/esm/utils/array.utils.d.ts +1 -1
  10. package/build/esm/utils/array.utils.js +17 -27
  11. package/build/esm/utils/array.utils.js.map +1 -1
  12. package/build/esm/utils/async.utils.d.ts +1 -5
  13. package/build/esm/utils/async.utils.js +17 -20
  14. package/build/esm/utils/async.utils.js.map +1 -1
  15. package/build/esm/utils/cache.utils.js +2 -2
  16. package/build/esm/utils/cache.utils.js.map +1 -1
  17. package/build/esm/utils/context-store.utils.d.ts +1 -1
  18. package/build/esm/utils/context-store.utils.js +8 -8
  19. package/build/esm/utils/context-store.utils.js.map +1 -1
  20. package/build/esm/utils/crypto.utils.d.ts +2 -2
  21. package/build/esm/utils/crypto.utils.js +37 -45
  22. package/build/esm/utils/crypto.utils.js.map +1 -1
  23. package/build/esm/utils/decorators.utils.d.ts +7 -7
  24. package/build/esm/utils/decorators.utils.js +31 -31
  25. package/build/esm/utils/decorators.utils.js.map +1 -1
  26. package/build/esm/utils/dir.utils.d.ts +4 -4
  27. package/build/esm/utils/dir.utils.js +18 -20
  28. package/build/esm/utils/dir.utils.js.map +1 -1
  29. package/build/esm/utils/env.utils.js +22 -26
  30. package/build/esm/utils/env.utils.js.map +1 -1
  31. package/build/esm/utils/exception.utils.d.ts +1 -1
  32. package/build/esm/utils/exception.utils.js +26 -29
  33. package/build/esm/utils/exception.utils.js.map +1 -1
  34. package/build/esm/utils/fs.utils.d.ts +3 -3
  35. package/build/esm/utils/fs.utils.js +19 -23
  36. package/build/esm/utils/fs.utils.js.map +1 -1
  37. package/build/esm/utils/http-status-codes.js.map +1 -1
  38. package/build/esm/utils/id.utils.js +8 -8
  39. package/build/esm/utils/id.utils.js.map +1 -1
  40. package/build/esm/utils/logger.utils.d.ts +13 -4
  41. package/build/esm/utils/logger.utils.js +15 -15
  42. package/build/esm/utils/logger.utils.js.map +1 -1
  43. package/build/esm/utils/middleware.utils.d.ts +5 -4
  44. package/build/esm/utils/middleware.utils.js +19 -19
  45. package/build/esm/utils/middleware.utils.js.map +1 -1
  46. package/build/esm/utils/obj.utils.js +16 -27
  47. package/build/esm/utils/obj.utils.js.map +1 -1
  48. package/build/esm/utils/response.utils.d.ts +2 -2
  49. package/build/esm/utils/response.utils.js +11 -11
  50. package/build/esm/utils/response.utils.js.map +1 -1
  51. package/build/esm/utils/string.utils.js +17 -17
  52. package/build/esm/utils/string.utils.js.map +1 -1
  53. package/build/esm/utils/url.utils.js +20 -22
  54. package/build/esm/utils/url.utils.js.map +1 -1
  55. package/build/esm/utils/validate.utils.js +11 -15
  56. package/build/esm/utils/validate.utils.js.map +1 -1
  57. package/build/esnext/config.d.ts +1 -1
  58. package/build/esnext/config.js +7 -7
  59. package/build/esnext/config.js.map +1 -1
  60. package/build/esnext/index.d.ts +20 -19
  61. package/build/esnext/index.js +20 -19
  62. package/build/esnext/index.js.map +1 -1
  63. package/build/esnext/types/api-response.d.ts +2 -2
  64. package/build/esnext/types/api-response.js.map +1 -1
  65. package/build/esnext/utils/array.utils.d.ts +1 -1
  66. package/build/esnext/utils/array.utils.js +23 -31
  67. package/build/esnext/utils/array.utils.js.map +1 -1
  68. package/build/esnext/utils/async.utils.d.ts +1 -5
  69. package/build/esnext/utils/async.utils.js +22 -22
  70. package/build/esnext/utils/async.utils.js.map +1 -1
  71. package/build/esnext/utils/cache.utils.js +3 -3
  72. package/build/esnext/utils/cache.utils.js.map +1 -1
  73. package/build/esnext/utils/context-store.utils.d.ts +1 -1
  74. package/build/esnext/utils/context-store.utils.js +10 -10
  75. package/build/esnext/utils/context-store.utils.js.map +1 -1
  76. package/build/esnext/utils/crypto.utils.d.ts +2 -2
  77. package/build/esnext/utils/crypto.utils.js +37 -47
  78. package/build/esnext/utils/crypto.utils.js.map +1 -1
  79. package/build/esnext/utils/decorators.utils.d.ts +7 -7
  80. package/build/esnext/utils/decorators.utils.js +33 -33
  81. package/build/esnext/utils/decorators.utils.js.map +1 -1
  82. package/build/esnext/utils/dir.utils.d.ts +4 -4
  83. package/build/esnext/utils/dir.utils.js +22 -24
  84. package/build/esnext/utils/dir.utils.js.map +1 -1
  85. package/build/esnext/utils/env.utils.js +24 -26
  86. package/build/esnext/utils/env.utils.js.map +1 -1
  87. package/build/esnext/utils/exception.utils.d.ts +1 -1
  88. package/build/esnext/utils/exception.utils.js +26 -29
  89. package/build/esnext/utils/exception.utils.js.map +1 -1
  90. package/build/esnext/utils/fs.utils.d.ts +3 -3
  91. package/build/esnext/utils/fs.utils.js +21 -25
  92. package/build/esnext/utils/fs.utils.js.map +1 -1
  93. package/build/esnext/utils/http-status-codes.js.map +1 -1
  94. package/build/esnext/utils/id.utils.js +8 -8
  95. package/build/esnext/utils/id.utils.js.map +1 -1
  96. package/build/esnext/utils/logger.utils.d.ts +13 -4
  97. package/build/esnext/utils/logger.utils.js +15 -15
  98. package/build/esnext/utils/logger.utils.js.map +1 -1
  99. package/build/esnext/utils/middleware.utils.d.ts +5 -4
  100. package/build/esnext/utils/middleware.utils.js +19 -19
  101. package/build/esnext/utils/middleware.utils.js.map +1 -1
  102. package/build/esnext/utils/obj.utils.js +17 -26
  103. package/build/esnext/utils/obj.utils.js.map +1 -1
  104. package/build/esnext/utils/response.utils.d.ts +2 -2
  105. package/build/esnext/utils/response.utils.js +11 -11
  106. package/build/esnext/utils/response.utils.js.map +1 -1
  107. package/build/esnext/utils/string.utils.js +17 -17
  108. package/build/esnext/utils/string.utils.js.map +1 -1
  109. package/build/esnext/utils/url.utils.js +21 -23
  110. package/build/esnext/utils/url.utils.js.map +1 -1
  111. package/build/esnext/utils/validate.utils.js +14 -16
  112. package/build/esnext/utils/validate.utils.js.map +1 -1
  113. package/build/src/config.d.ts +1 -1
  114. package/build/src/config.js +6 -6
  115. package/build/src/config.js.map +1 -1
  116. package/build/src/index.d.ts +20 -19
  117. package/build/src/index.js +1 -0
  118. package/build/src/index.js.map +1 -1
  119. package/build/src/types/api-response.d.ts +2 -2
  120. package/build/src/types/api-response.js.map +1 -1
  121. package/build/src/utils/array.utils.d.ts +1 -1
  122. package/build/src/utils/array.utils.js +22 -30
  123. package/build/src/utils/array.utils.js.map +1 -1
  124. package/build/src/utils/async.utils.d.ts +1 -5
  125. package/build/src/utils/async.utils.js +22 -22
  126. package/build/src/utils/async.utils.js.map +1 -1
  127. package/build/src/utils/cache.utils.js +2 -2
  128. package/build/src/utils/cache.utils.js.map +1 -1
  129. package/build/src/utils/context-store.utils.d.ts +1 -1
  130. package/build/src/utils/context-store.utils.js +9 -9
  131. package/build/src/utils/context-store.utils.js.map +1 -1
  132. package/build/src/utils/crypto.utils.d.ts +2 -2
  133. package/build/src/utils/crypto.utils.js +35 -45
  134. package/build/src/utils/crypto.utils.js.map +1 -1
  135. package/build/src/utils/decorators.utils.d.ts +7 -7
  136. package/build/src/utils/decorators.utils.js +32 -32
  137. package/build/src/utils/decorators.utils.js.map +1 -1
  138. package/build/src/utils/dir.utils.d.ts +4 -4
  139. package/build/src/utils/dir.utils.js +16 -18
  140. package/build/src/utils/dir.utils.js.map +1 -1
  141. package/build/src/utils/env.utils.js +22 -24
  142. package/build/src/utils/env.utils.js.map +1 -1
  143. package/build/src/utils/exception.utils.d.ts +1 -1
  144. package/build/src/utils/exception.utils.js +23 -26
  145. package/build/src/utils/exception.utils.js.map +1 -1
  146. package/build/src/utils/fs.utils.d.ts +3 -3
  147. package/build/src/utils/fs.utils.js +15 -19
  148. package/build/src/utils/fs.utils.js.map +1 -1
  149. package/build/src/utils/http-status-codes.js.map +1 -1
  150. package/build/src/utils/id.utils.js +7 -7
  151. package/build/src/utils/id.utils.js.map +1 -1
  152. package/build/src/utils/logger.utils.d.ts +13 -4
  153. package/build/src/utils/logger.utils.js +12 -12
  154. package/build/src/utils/logger.utils.js.map +1 -1
  155. package/build/src/utils/middleware.utils.d.ts +5 -4
  156. package/build/src/utils/middleware.utils.js +12 -12
  157. package/build/src/utils/middleware.utils.js.map +1 -1
  158. package/build/src/utils/obj.utils.js +17 -26
  159. package/build/src/utils/obj.utils.js.map +1 -1
  160. package/build/src/utils/response.utils.d.ts +2 -2
  161. package/build/src/utils/response.utils.js +9 -9
  162. package/build/src/utils/response.utils.js.map +1 -1
  163. package/build/src/utils/string.utils.js +17 -17
  164. package/build/src/utils/string.utils.js.map +1 -1
  165. package/build/src/utils/url.utils.js +20 -22
  166. package/build/src/utils/url.utils.js.map +1 -1
  167. package/build/src/utils/validate.utils.js +14 -16
  168. package/build/src/utils/validate.utils.js.map +1 -1
  169. package/package.json +1 -1
@@ -1,10 +1,10 @@
1
- import { randomUUID } from "crypto";
2
- import { Config } from "../config";
3
- import { uuid } from "./id.utils";
4
- import { HttpStatusCodes } from "./http-status-codes";
5
- import { ErrorResponse } from "./response.utils";
6
- import { Env } from "./env.utils";
7
- import { getLogger } from "./logger.utils";
1
+ import { randomUUID } from 'crypto';
2
+ import { Config } from '../config';
3
+ import { uuid } from './id.utils';
4
+ import { HttpStatusCodes } from './http-status-codes';
5
+ import { ErrorResponse } from './response.utils';
6
+ import { Env } from './env.utils';
7
+ import { getLogger } from './logger.utils';
8
8
  /**
9
9
  * Attaches a unique request ID to each request.
10
10
  * Useful for request tracing and correlation between logs.
@@ -15,7 +15,7 @@ import { getLogger } from "./logger.utils";
15
15
  * @returns {Middleware} Express-compatible middleware
16
16
  */
17
17
  export function requestId(options) {
18
- const headerName = (options === null || options === void 0 ? void 0 : options.headerName) || "X-Request-ID";
18
+ const headerName = (options === null || options === void 0 ? void 0 : options.headerName) || 'X-Request-ID';
19
19
  const exposeHeader = (options === null || options === void 0 ? void 0 : options.exposeHeader) !== false;
20
20
  return (req, res, next) => {
21
21
  // Use existing request ID from header or generate a new one
@@ -49,10 +49,10 @@ export function responseTime(options) {
49
49
  return diff[0] * 1e3 + diff[1] * 1e-6; // Convert to ms
50
50
  };
51
51
  // Handle response completion
52
- res.on("finish", () => {
52
+ res.on('finish', () => {
53
53
  const duration = calculateDuration();
54
54
  if (addHeader) {
55
- res.setHeader("X-Response-Time", `${duration.toFixed(2)}ms`);
55
+ res.setHeader('X-Response-Time', `${duration.toFixed(2)}ms`);
56
56
  }
57
57
  if (logOnComplete) {
58
58
  const { method, url } = req;
@@ -75,13 +75,13 @@ export function timeout(timeoutMs = Config.Http.timeout) {
75
75
  const timer = setTimeout(() => {
76
76
  res.status(408).json({
77
77
  error: true,
78
- message: "Request timeout",
78
+ message: 'Request timeout',
79
79
  status: 408,
80
- timestamp: new Date().toISOString(),
80
+ timestamp: new Date().toISOString()
81
81
  });
82
82
  }, timeoutMs);
83
83
  // Clear timeout when response is sent
84
- res.on("finish", () => {
84
+ res.on('finish', () => {
85
85
  clearTimeout(timer);
86
86
  });
87
87
  next();
@@ -105,7 +105,7 @@ const createErrorResponse = (message, req, error, options) => {
105
105
  message,
106
106
  timestamp: new Date().toISOString(),
107
107
  requestId: (error === null || error === void 0 ? void 0 : error.requestId) || req.id || uuid(),
108
- path: req.originalUrl || req.url,
108
+ path: req.originalUrl || req.url
109
109
  };
110
110
  // Include error code if present
111
111
  if (error === null || error === void 0 ? void 0 : error.code) {
@@ -113,7 +113,7 @@ const createErrorResponse = (message, req, error, options) => {
113
113
  }
114
114
  // Include stack trace in development mode if requested
115
115
  if (includeDetails && (error === null || error === void 0 ? void 0 : error.stack)) {
116
- response.stack = error.stack.split("\n").map((line) => line.trim());
116
+ response.stack = error.stack.split('\n').map((line) => line.trim());
117
117
  }
118
118
  return response;
119
119
  };
@@ -135,7 +135,7 @@ export function errorHandler(options) {
135
135
  const status = (err === null || err === void 0 ? void 0 : err.status) || (err === null || err === void 0 ? void 0 : err.statusCode) || HttpStatusCodes.INTERNAL_SERVER_ERROR;
136
136
  // Log error if enabled
137
137
  if (logErrors) {
138
- const logMessage = `[ERROR] ${req.method} ${req.originalUrl || req.url}: ${err.message || "Unknown error"}`;
138
+ const logMessage = `[ERROR] ${req.method} ${req.originalUrl || req.url}: ${err.message || 'Unknown error'}`;
139
139
  logger(logMessage, err);
140
140
  }
141
141
  // Handle ErrorResponse instances (our custom error class)
@@ -145,12 +145,12 @@ export function errorHandler(options) {
145
145
  message: err.message,
146
146
  timestamp: err.timestamp,
147
147
  requestId: err.requestId || req.id || uuid(),
148
- path: req.originalUrl || req.url,
148
+ path: req.originalUrl || req.url
149
149
  });
150
150
  }
151
151
  // Handle any other errors
152
- return res.status(status).json(createErrorResponse((err === null || err === void 0 ? void 0 : err.message) || "Internal Server Error", req, err, {
153
- includeDetails,
152
+ return res.status(status).json(createErrorResponse((err === null || err === void 0 ? void 0 : err.message) || 'Internal Server Error', req, err, {
153
+ includeDetails
154
154
  }));
155
155
  };
156
156
  }
@@ -1 +1 @@
1
- {"version":3,"file":"middleware.utils.js","sourceRoot":"","sources":["../../../src/utils/middleware.utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AACpC,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACnC,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAClC,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAClC,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAkC3C;;;;;;;;GAQG;AACH,MAAM,UAAU,SAAS,CAAC,OAGzB;IACC,MAAM,UAAU,GAAG,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,UAAU,KAAI,cAAc,CAAC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from \"./id.utils\";\nimport { HttpStatusCodes } from \"./http-status-codes\";\nimport { ErrorResponse } from \"./response.utils\";\nimport { Env } from \"./env.utils\";\nimport { getLogger } from \"./logger.utils\";\n\n/**\n * Type definitions for Express-compatible middleware\n */\nexport type Request = {\n headers: Record<string, string | string[] | undefined>;\n method: string;\n url: string;\n ip?: string;\n body?: any;\n query?: Record<string, any>;\n params?: Record<string, any>;\n [key: string]: any;\n};\n\nexport type Response = {\n status: (code: number) => Response;\n json: (data: any) => void;\n send: (data: any) => void;\n setHeader: (name: string, value: string | string[]) => void;\n end: (data?: any) => void;\n on: (event: string, callback: (...args: any[]) => void) => void;\n [key: string]: any;\n};\n\nexport type NextFunction = (err?: Error | any) => void;\n\nexport type Middleware = (\n req: Request,\n res: Response,\n next: NextFunction,\n) => void | Promise<void>;\n\n/**\n * Attaches a unique request ID to each request.\n * Useful for request tracing and correlation between logs.\n *\n * @param {object} [options] - Configuration options\n * @param {string} [options.headerName='X-Request-ID'] - Header name for request ID\n * @param {boolean} [options.exposeHeader=true] - Whether to expose the header in response\n * @returns {Middleware} Express-compatible middleware\n */\nexport function requestId(options?: {\n headerName?: string;\n exposeHeader?: boolean;\n}): Middleware {\n const headerName = options?.headerName || \"X-Request-ID\";\n const exposeHeader = options?.exposeHeader !== false;\n\n return (req, res, next) => {\n // Use existing request ID from header or generate a new one\n const existingId = req.headers[headerName.toLowerCase()];\n const id = (existingId as string) || randomUUID();\n\n // Attach ID to request object\n req.id = id;\n\n // Add ID to response headers\n if (exposeHeader) {\n res.setHeader(headerName, id);\n }\n\n next();\n };\n}\n\n/**\n * Measures request processing time and logs or adds it to response headers.\n *\n * @param {object} [options] - Configuration options\n * @param {boolean} [options.addHeader=true] - Whether to add X-Response-Time header\n * @param {boolean} [options.logOnComplete=false] - Whether to log timing info\n * @returns {Middleware} Express-compatible middleware\n */\nexport function responseTime(options?: {\n addHeader?: boolean;\n logOnComplete?: boolean;\n}): Middleware {\n const addHeader = options?.addHeader !== false;\n const logOnComplete = options?.logOnComplete === true;\n\n return (req, res, next) => {\n const start = process.hrtime();\n\n // Function to calculate elapsed time\n const calculateDuration = (): number => {\n const diff = process.hrtime(start);\n return diff[0] * 1e3 + diff[1] * 1e-6; // Convert to ms\n };\n\n // Handle response completion\n res.on(\"finish\", () => {\n const duration = calculateDuration();\n\n if (addHeader) {\n res.setHeader(\"X-Response-Time\", `${duration.toFixed(2)}ms`);\n }\n\n if (logOnComplete) {\n const { method, url } = req;\n getLogger().info(`${method} ${url} - ${duration.toFixed(2)}ms`);\n }\n });\n\n next();\n };\n}\n\n/**\n * Request timeout middleware.\n * Aborts requests that take too long to process.\n *\n * @param {number} [timeoutMs=30000] - Timeout in milliseconds\n * @returns {Middleware} Express-compatible middleware\n */\nexport function timeout(timeoutMs: number = Config.Http.timeout): Middleware {\n return (req, res, next) => {\n // Set timeout for the request\n const timer = setTimeout(() => {\n res.status(408).json({\n error: true,\n message: \"Request timeout\",\n status: 408,\n timestamp: new Date().toISOString(),\n });\n }, timeoutMs);\n\n // Clear timeout when response is sent\n res.on(\"finish\", () => {\n clearTimeout(timer);\n });\n\n next();\n };\n}\n\n/**\n * Creates a standardized error response object for API errors.\n *\n * @param {string} message - Error message\n * @param {Request} req - Express request object\n * @param {any} error - Original error object\n * @param {object} [options] - Additional options\n * @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production\n * @returns {object} Formatted error response\n */\nconst createErrorResponse = (\n message: string,\n req: Request,\n error: any,\n options?: { includeDetails?: boolean },\n) => {\n const isDev = Env.isDev();\n const includeDetails = options?.includeDetails && isDev;\n\n const response: Record<string, any> = {\n error: true,\n message,\n timestamp: new Date().toISOString(),\n requestId: error?.requestId || req.id || uuid(),\n path: req.originalUrl || req.url,\n };\n\n // Include error code if present\n if (error?.code) {\n response.code = error.code;\n }\n\n // Include stack trace in development mode if requested\n if (includeDetails && error?.stack) {\n response.stack = error.stack.split(\"\\n\").map((line: string) => line.trim());\n }\n\n return response;\n};\n\n/**\n * Global error handling middleware with enhanced features.\n *\n * @param {object} [options] - Error handler options\n * @param {boolean} [options.logErrors=true] - Whether to log errors\n * @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production\n * @param {Function} [options.logger=getLogger().error] - Custom logging function\n * @returns {(err: any, req: Request, res: Response, next: NextFunction) => void} Error middleware\n */\nexport function errorHandler(options?: {\n logErrors?: boolean;\n includeDetails?: boolean;\n logger?: (message: string, error: any) => void;\n}) {\n const logErrors = options?.logErrors !== false;\n const includeDetails = options?.includeDetails === true;\n const logger = options?.logger || getLogger().error;\n\n return (err: any, req: Request, res: Response, _next: NextFunction) => {\n // Determine status code\n const status =\n err?.status || err?.statusCode || HttpStatusCodes.INTERNAL_SERVER_ERROR;\n\n // Log error if enabled\n if (logErrors) {\n const logMessage = `[ERROR] ${req.method} ${req.originalUrl || req.url}: ${err.message || \"Unknown error\"}`;\n logger(logMessage, err);\n }\n\n // Handle ErrorResponse instances (our custom error class)\n if (err instanceof ErrorResponse) {\n return res.status(status).json({\n error: err.error,\n message: err.message,\n timestamp: err.timestamp,\n requestId: err.requestId || req.id || uuid(),\n path: req.originalUrl || req.url,\n });\n }\n\n // Handle any other errors\n return res.status(status).json(\n createErrorResponse(err?.message || \"Internal Server Error\", req, err, {\n includeDetails,\n }),\n );\n };\n}\n"]}
1
+ {"version":3,"file":"middleware.utils.js","sourceRoot":"","sources":["../../../src/utils/middleware.utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AACpC,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACnC,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAClC,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAClC,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AA8B3C;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GAAG,EAAE,GAAG,EAAE;YACrE,cAAc;SACf,CAAC,CACH,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { randomUUID } from 'crypto';\nimport { Config } from '../config';\nimport { uuid } from './id.utils';\nimport { HttpStatusCodes } from './http-status-codes';\nimport { ErrorResponse } from './response.utils';\nimport { Env } from './env.utils';\nimport { getLogger } from './logger.utils';\n\n/**\n * Type definitions for Express-compatible middleware\n */\ntype Request = {\n headers: Record<string, string | string[] | undefined>;\n method: string;\n url: string;\n ip?: string;\n body?: any;\n query?: Record<string, any>;\n params?: Record<string, any>;\n [key: string]: any;\n};\n\ntype Response = {\n status: (code: number) => Response;\n json: (data: any) => void;\n send: (data: any) => void;\n setHeader: (name: string, value: string | string[]) => void;\n end: (data?: any) => void;\n on: (event: string, callback: (...args: any[]) => void) => void;\n [key: string]: any;\n};\n\ntype NextFunction = (err?: Error | any) => void;\n\ntype Middleware = (req: Request, res: Response, next: NextFunction) => void | Promise<void>;\n\n/**\n * Attaches a unique request ID to each request.\n * Useful for request tracing and correlation between logs.\n *\n * @param {object} [options] - Configuration options\n * @param {string} [options.headerName='X-Request-ID'] - Header name for request ID\n * @param {boolean} [options.exposeHeader=true] - Whether to expose the header in response\n * @returns {Middleware} Express-compatible middleware\n */\nexport function requestId(options?: { headerName?: string; exposeHeader?: boolean }): Middleware {\n const headerName = options?.headerName || 'X-Request-ID';\n const exposeHeader = options?.exposeHeader !== false;\n\n return (req, res, next) => {\n // Use existing request ID from header or generate a new one\n const existingId = req.headers[headerName.toLowerCase()];\n const id = (existingId as string) || randomUUID();\n\n // Attach ID to request object\n req.id = id;\n\n // Add ID to response headers\n if (exposeHeader) {\n res.setHeader(headerName, id);\n }\n\n next();\n };\n}\n\n/**\n * Measures request processing time and logs or adds it to response headers.\n *\n * @param {object} [options] - Configuration options\n * @param {boolean} [options.addHeader=true] - Whether to add X-Response-Time header\n * @param {boolean} [options.logOnComplete=false] - Whether to log timing info\n * @returns {Middleware} Express-compatible middleware\n */\nexport function responseTime(options?: { addHeader?: boolean; logOnComplete?: boolean }): Middleware {\n const addHeader = options?.addHeader !== false;\n const logOnComplete = options?.logOnComplete === true;\n\n return (req, res, next) => {\n const start = process.hrtime();\n\n // Function to calculate elapsed time\n const calculateDuration = (): number => {\n const diff = process.hrtime(start);\n return diff[0] * 1e3 + diff[1] * 1e-6; // Convert to ms\n };\n\n // Handle response completion\n res.on('finish', () => {\n const duration = calculateDuration();\n\n if (addHeader) {\n res.setHeader('X-Response-Time', `${duration.toFixed(2)}ms`);\n }\n\n if (logOnComplete) {\n const { method, url } = req;\n getLogger().info(`${method} ${url} - ${duration.toFixed(2)}ms`);\n }\n });\n\n next();\n };\n}\n\n/**\n * Request timeout middleware.\n * Aborts requests that take too long to process.\n *\n * @param {number} [timeoutMs=30000] - Timeout in milliseconds\n * @returns {Middleware} Express-compatible middleware\n */\nexport function timeout(timeoutMs: number = Config.Http.timeout): Middleware {\n return (req, res, next) => {\n // Set timeout for the request\n const timer = setTimeout(() => {\n res.status(408).json({\n error: true,\n message: 'Request timeout',\n status: 408,\n timestamp: new Date().toISOString()\n });\n }, timeoutMs);\n\n // Clear timeout when response is sent\n res.on('finish', () => {\n clearTimeout(timer);\n });\n\n next();\n };\n}\n\n/**\n * Creates a standardized error response object for API errors.\n *\n * @param {string} message - Error message\n * @param {Request} req - Express request object\n * @param {any} error - Original error object\n * @param {object} [options] - Additional options\n * @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production\n * @returns {object} Formatted error response\n */\nconst createErrorResponse = (message: string, req: Request, error: any, options?: { includeDetails?: boolean }) => {\n const isDev = Env.isDev();\n const includeDetails = options?.includeDetails && isDev;\n\n const response: Record<string, any> = {\n error: true,\n message,\n timestamp: new Date().toISOString(),\n requestId: error?.requestId || req.id || uuid(),\n path: req.originalUrl || req.url\n };\n\n // Include error code if present\n if (error?.code) {\n response.code = error.code;\n }\n\n // Include stack trace in development mode if requested\n if (includeDetails && error?.stack) {\n response.stack = error.stack.split('\\n').map((line: string) => line.trim());\n }\n\n return response;\n};\n\n/**\n * Global error handling middleware with enhanced features.\n *\n * @param {object} [options] - Error handler options\n * @param {boolean} [options.logErrors=true] - Whether to log errors\n * @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production\n * @param {Function} [options.logger=getLogger().error] - Custom logging function\n * @returns {(err: any, req: Request, res: Response, next: NextFunction) => void} Error middleware\n */\nexport function errorHandler(options?: {\n logErrors?: boolean;\n includeDetails?: boolean;\n logger?: (message: string, error: any) => void;\n}) {\n const logErrors = options?.logErrors !== false;\n const includeDetails = options?.includeDetails === true;\n const logger = options?.logger || getLogger().error;\n\n return (err: any, req: Request, res: Response, _next: NextFunction) => {\n // Determine status code\n const status = err?.status || err?.statusCode || HttpStatusCodes.INTERNAL_SERVER_ERROR;\n\n // Log error if enabled\n if (logErrors) {\n const logMessage = `[ERROR] ${req.method} ${req.originalUrl || req.url}: ${err.message || 'Unknown error'}`;\n logger(logMessage, err);\n }\n\n // Handle ErrorResponse instances (our custom error class)\n if (err instanceof ErrorResponse) {\n return res.status(status).json({\n error: err.error,\n message: err.message,\n timestamp: err.timestamp,\n requestId: err.requestId || req.id || uuid(),\n path: req.originalUrl || req.url\n });\n }\n\n // Handle any other errors\n return res.status(status).json(\n createErrorResponse(err?.message || 'Internal Server Error', req, err, {\n includeDetails\n })\n );\n };\n}\n"]}
@@ -5,7 +5,7 @@
5
5
  * @returns {boolean} True if the object is empty, false otherwise.
6
6
  */
7
7
  export function isObjEmpty(obj) {
8
- return !!obj && typeof obj === "object" && Object.keys(obj).length === 0;
8
+ return !!obj && typeof obj === 'object' && Object.keys(obj).length === 0;
9
9
  }
10
10
  /**
11
11
  * Returns a new object with only the specified keys picked.
@@ -17,7 +17,7 @@ export function isObjEmpty(obj) {
17
17
  * @returns {Pick<T, K>} New object with picked keys.
18
18
  */
19
19
  export function pick(obj, keys) {
20
- return Object.fromEntries(keys.map((key) => [key, obj[key]]));
20
+ return Object.fromEntries(keys.map(key => [key, obj[key]]));
21
21
  }
22
22
  /**
23
23
  * Returns a new object with the specified keys omitted.
@@ -43,12 +43,8 @@ export function deepObjMerge(target, source) {
43
43
  for (const key in source) {
44
44
  const sourceVal = source[key];
45
45
  const targetVal = target[key];
46
- if (sourceVal &&
47
- typeof sourceVal === "object" &&
48
- !Array.isArray(sourceVal)) {
49
- if (!targetVal ||
50
- typeof targetVal !== "object" ||
51
- Array.isArray(targetVal)) {
46
+ if (sourceVal && typeof sourceVal === 'object' && !Array.isArray(sourceVal)) {
47
+ if (!targetVal || typeof targetVal !== 'object' || Array.isArray(targetVal)) {
52
48
  target[key] = {};
53
49
  }
54
50
  deepObjMerge(target[key], sourceVal);
@@ -67,10 +63,10 @@ export function deepObjMerge(target, source) {
67
63
  * @param {string} [prefix=""] - Optional prefix for nested keys (used internally).
68
64
  * @returns {Record<string, any>} A new object with flattened keys.
69
65
  */
70
- export function flattenObject(obj, prefix = "") {
66
+ export function flattenObject(obj, prefix = '') {
71
67
  return Object.entries(obj).reduce((acc, [key, value]) => {
72
68
  const newKey = prefix ? `${prefix}.${key}` : key;
73
- if (value && typeof value === "object" && !Array.isArray(value)) {
69
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
74
70
  Object.assign(acc, flattenObject(value, newKey));
75
71
  }
76
72
  else {
@@ -88,12 +84,12 @@ export function flattenObject(obj, prefix = "") {
88
84
  * @returns {any} The value at the given path, or undefined if not found.
89
85
  */
90
86
  export function getValueByPath(obj, path) {
91
- if (!obj || typeof obj !== "object")
87
+ if (!obj || typeof obj !== 'object')
92
88
  return undefined;
93
89
  // Convert path like "a.b[0].c" into ["a", "b", "0", "c"]
94
90
  const parts = path
95
- .replace(/\[(\d+)\]/g, ".$1") // convert [0] to .0
96
- .split(".")
91
+ .replace(/\[(\d+)\]/g, '.$1') // convert [0] to .0
92
+ .split('.')
97
93
  .filter(Boolean); // remove empty strings
98
94
  return parts.reduce((acc, key) => acc === null || acc === void 0 ? void 0 : acc[key], obj);
99
95
  }
@@ -108,12 +104,12 @@ export function getValueByPath(obj, path) {
108
104
  * @returns {T} The modified object.
109
105
  */
110
106
  export function setValueByPath(obj, path, value) {
111
- if (!obj || typeof obj !== "object")
107
+ if (!obj || typeof obj !== 'object')
112
108
  return obj;
113
109
  // Convert path like "a.b[0].c" into ["a", "b", "0", "c"]
114
110
  const parts = path
115
- .replace(/\[(\d+)\]/g, ".$1") // convert [0] to .0
116
- .split(".")
111
+ .replace(/\[(\d+)\]/g, '.$1') // convert [0] to .0
112
+ .split('.')
117
113
  .filter(Boolean); // remove empty strings
118
114
  // Handle empty path
119
115
  if (parts.length === 0)
@@ -146,10 +142,7 @@ export function isEqual(a, b) {
146
142
  if (a === b)
147
143
  return true;
148
144
  // Check if either is null/undefined or not an object
149
- if (a == null ||
150
- b == null ||
151
- typeof a !== "object" ||
152
- typeof b !== "object") {
145
+ if (a == null || b == null || typeof a !== 'object' || typeof b !== 'object') {
153
146
  return false;
154
147
  }
155
148
  // Handle Date objects
@@ -181,7 +174,7 @@ export function isEqual(a, b) {
181
174
  if (keysA.length !== keysB.length)
182
175
  return false;
183
176
  // Check if every key in A exists in B and has the same value
184
- return keysA.every((key) => Object.prototype.hasOwnProperty.call(b, key) && isEqual(a[key], b[key]));
177
+ return keysA.every(key => Object.prototype.hasOwnProperty.call(b, key) && isEqual(a[key], b[key]));
185
178
  }
186
179
  /**
187
180
  * Filters object properties based on a predicate function.
@@ -220,9 +213,7 @@ export function deepFreeze(obj) {
220
213
  // Recursively freeze nested objects
221
214
  for (const prop of Object.getOwnPropertyNames(obj)) {
222
215
  const value = obj[prop];
223
- if (value !== null &&
224
- typeof value === "object" &&
225
- !Object.isFrozen(value)) {
216
+ if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {
226
217
  deepFreeze(value);
227
218
  }
228
219
  }
@@ -235,7 +226,7 @@ export function deepFreeze(obj) {
235
226
  * @returns {boolean} True if value is a non-null, non-array object.
236
227
  */
237
228
  export function isObject(value) {
238
- return value !== null && typeof value === "object" && !Array.isArray(value);
229
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
239
230
  }
240
231
  /**
241
232
  * Gets all paths in an object using dot notation.
@@ -244,7 +235,7 @@ export function isObject(value) {
244
235
  * @param {string} [parentPath=""] - Internal param for recursion.
245
236
  * @returns {string[]} Array of all paths in dot notation.
246
237
  */
247
- export function getAllPaths(obj, parentPath = "") {
238
+ export function getAllPaths(obj, parentPath = '') {
248
239
  if (!isObject(obj))
249
240
  return [];
250
241
  return Object.entries(obj).flatMap(([key, value]) => {
@@ -1 +1 @@
1
- {"version":3,"file":"obj.utils.js","sourceRoot":"","sources":["../../../src/utils/obj.utils.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,MAAM,UAAU,UAAU,CAAC,GAAqB;IAC9C,OAAO,CAAC,CAAC,GAAG,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC;AAC3E,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,IAAI,CAClB,GAAM,EACN,IAAS;IAET,OAAO,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,GAAG,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAe,CAAC;AAC9E,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,IAAI,CAClB,GAAM,EACN,IAAS;IAET,OAAO,MAAM,CAAC,WAAW,CACvB,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAQ,CAAC,CAAC,CAClD,CAAC;AAClB,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,YAAY,CAC1B,MAAS,EACT,MAAkB;IAElB,KAAK,MAAM,GAAG,IAAI,MAAM,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AAW,GAAG,UAAU,CAAC,CAAC,CAAC,GAAG,UAAU,IAAI,GAAG,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC;QAE9D,IAAI,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;YACpB,OAAO,CAAC,WAAW,EAAE,GAAG,WAAW,CAAC,KAAK,EAAE,WAAW,CAAC,CAAC,CAAC;QAC3D,CAAC;QAED,OAAO,CAAC,WAAW,CAAC,CAAC;IACvB,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * Checks whether the object has no own enumerable properties.\n *\n * @param {Record<any, any>} obj - The object to check.\n * @returns {boolean} True if the object is empty, false otherwise.\n */\nexport function isObjEmpty(obj: Record<any, any>): boolean {\n return !!obj && typeof obj === \"object\" && Object.keys(obj).length === 0;\n}\n\n/**\n * Returns a new object with only the specified keys picked.\n *\n * @template T\n * @template K\n * @param {T} obj - The source object.\n * @param {K[]} keys - Keys to pick from the object.\n * @returns {Pick<T, K>} New object with picked keys.\n */\nexport function pick<T extends object, K extends keyof T>(\n obj: T,\n keys: K[],\n): Pick<T, K> {\n return Object.fromEntries(keys.map((key) => [key, obj[key]])) as Pick<T, K>;\n}\n\n/**\n * Returns a new object with the specified keys omitted.\n *\n * @template T\n * @template K\n * @param {T} obj - The source object.\n * @param {K[]} keys - Keys to omit from the object.\n * @returns {Omit<T, K>} New object without omitted keys.\n */\nexport function omit<T extends object, K extends keyof T>(\n obj: T,\n keys: K[],\n): Omit<T, K> {\n return Object.fromEntries(\n Object.entries(obj).filter(([key]) => !keys.includes(key as K)),\n ) as Omit<T, K>;\n}\n\n/**\n * Deeply merges two objects (mutates and returns the target object, not pure).\n *\n * @template T\n * @param {T} target - The object to merge into (will be mutated).\n * @param {Partial<T>} source - The object to merge from.\n * @returns {T} The merged object (same as target).\n */\nexport function deepObjMerge<T extends Record<string, any>>(\n target: T,\n source: Partial<T>,\n): T {\n for (const key in source) {\n const sourceVal = source[key];\n const targetVal = target[key];\n\n if (\n sourceVal &&\n typeof sourceVal === \"object\" &&\n !Array.isArray(sourceVal)\n ) {\n if (\n !targetVal ||\n typeof targetVal !== \"object\" ||\n Array.isArray(targetVal)\n ) {\n target[key] = {} as any;\n }\n deepObjMerge(target[key], sourceVal as any);\n } else {\n target[key] = sourceVal as T[Extract<keyof T, string>];\n }\n }\n return target;\n}\n\n/**\n * Flattens a nested object using dot notation for keys (e.g., `{a: {b: 1}}` → `{ \"a.b\": 1 }`).\n *\n * @template T\n * @param {T} obj - The object to flatten.\n * @param {string} [prefix=\"\"] - Optional prefix for nested keys (used internally).\n * @returns {Record<string, any>} A new object with flattened keys.\n */\nexport function flattenObject<T extends Record<string, any>>(\n obj: T,\n prefix = \"\",\n): Record<string, any> {\n return Object.entries(obj).reduce(\n (acc: Record<string, any>, [key, value]) => {\n const newKey = prefix ? `${prefix}.${key}` : key;\n\n if (value && typeof value === \"object\" && !Array.isArray(value)) {\n Object.assign(acc, flattenObject(value, newKey));\n } else {\n acc[newKey] = value;\n }\n\n return acc;\n },\n {},\n );\n}\n\n/**\n * Safely gets the value of a deeply nested key in an object using dot/bracket notation path.\n *\n * @template T\n * @param {T} obj - The object to extract from.\n * @param {string} path - String path using dot and/or bracket notation (e.g., 'user.friends[0].name').\n * @returns {any} The value at the given path, or undefined if not found.\n */\nexport function getValueByPath<T extends object>(obj: T, path: string) {\n if (!obj || typeof obj !== \"object\") return undefined;\n\n // Convert path like \"a.b[0].c\" into [\"a\", \"b\", \"0\", \"c\"]\n const parts = path\n .replace(/\\[(\\d+)\\]/g, \".$1\") // convert [0] to .0\n .split(\".\")\n .filter(Boolean); // remove empty strings\n\n return parts.reduce((acc: any, key: string) => acc?.[key], obj);\n}\n\n/**\n * Sets a value at a deeply nested key in an object using dot/bracket notation path.\n * Creates intermediate objects and arrays as needed.\n *\n * @template T\n * @param {T} obj - The object to modify.\n * @param {string} path - String path using dot and/or bracket notation (e.g., 'user.friends[0].name').\n * @param {any} value - The value to set at the path.\n * @returns {T} The modified object.\n */\nexport function setValueByPath<T extends object>(\n obj: T,\n path: string,\n value: any,\n): T {\n if (!obj || typeof obj !== \"object\") return obj;\n\n // Convert path like \"a.b[0].c\" into [\"a\", \"b\", \"0\", \"c\"]\n const parts = path\n .replace(/\\[(\\d+)\\]/g, \".$1\") // convert [0] to .0\n .split(\".\")\n .filter(Boolean); // remove empty strings\n\n // Handle empty path\n if (parts.length === 0) return obj;\n\n let current: any = obj;\n\n // Navigate to the parent of the target property\n for (let i = 0; i < parts.length - 1; i++) {\n const key = parts[i];\n const isArrayIndex = !isNaN(Number(parts[i + 1]));\n\n if (current[key] === undefined) {\n // Create intermediate object or array based on next key type\n current[key] = isArrayIndex ? [] : {};\n }\n\n current = current[key];\n }\n\n // Set the value at the final key\n const finalKey = parts[parts.length - 1];\n current[finalKey] = value;\n\n return obj;\n}\n\n/**\n * Performs a deep equality check between two objects.\n *\n * @param {any} a - First value to compare.\n * @param {any} b - Second value to compare.\n * @returns {boolean} True if values are deeply equal.\n */\nexport function isEqual(a: any, b: any): boolean {\n // Check if primitives or references to the same object\n if (a === b) return true;\n\n // Check if either is null/undefined or not an object\n if (\n a == null ||\n b == null ||\n typeof a !== \"object\" ||\n typeof b !== \"object\"\n ) {\n return false;\n }\n\n // Handle Date objects\n if (a instanceof Date && b instanceof Date) {\n return a.getTime() === b.getTime();\n }\n\n // If one is Date but the other isn't\n if (a instanceof Date || b instanceof Date) {\n return false;\n }\n\n // Handle arrays\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false;\n\n // Check each element\n for (let i = 0; i < a.length; i++) {\n if (!isEqual(a[i], b[i])) return false;\n }\n\n return true;\n }\n\n // If one is Array but the other isn't\n if (Array.isArray(a) || Array.isArray(b)) {\n return false;\n }\n\n // Compare object keys\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) return false;\n\n // Check if every key in A exists in B and has the same value\n return keysA.every(\n (key) =>\n Object.prototype.hasOwnProperty.call(b, key) && isEqual(a[key], b[key]),\n );\n}\n\n/**\n * Filters object properties based on a predicate function.\n *\n * @template T\n * @param {T} obj - The source object.\n * @param {(value: any, key: string, obj: T) => boolean} predicate - Filter function.\n * @returns {Partial<T>} New object with filtered properties.\n */\nexport function filterObject<T extends object>(\n obj: T,\n predicate: (value: any, key: string, obj: T) => boolean,\n): Partial<T> {\n return Object.fromEntries(\n Object.entries(obj).filter(([key, value]) => predicate(value, key, obj)),\n ) as Partial<T>;\n}\n\n/**\n * Maps object values to new values using a mapping function.\n *\n * @template T\n * @template U\n * @param {T} obj - The source object.\n * @param {(value: any, key: string, obj: T) => U} mapFn - Mapping function.\n * @returns {Record<keyof T, U>} New object with mapped values.\n */\nexport function mapObject<T extends object, U>(\n obj: T,\n mapFn: (value: any, key: string, obj: T) => U,\n): Record<keyof T, U> {\n return Object.fromEntries(\n Object.entries(obj).map(([key, value]) => [key, mapFn(value, key, obj)]),\n ) as Record<keyof T, U>;\n}\n\n/**\n * Recursively freezes an object and all its properties.\n * Makes an object immutable.\n *\n * @template T\n * @param {T} obj - The object to freeze.\n * @returns {Readonly<T>} The frozen object.\n */\nexport function deepFreeze<T extends object>(obj: T): Readonly<T> {\n // Freeze primitive properties\n Object.freeze(obj);\n\n // Recursively freeze nested objects\n for (const prop of Object.getOwnPropertyNames(obj)) {\n const value = (obj as any)[prop];\n if (\n value !== null &&\n typeof value === \"object\" &&\n !Object.isFrozen(value)\n ) {\n deepFreeze(value);\n }\n }\n\n return obj;\n}\n\n/**\n * Safely checks if a value is an object (not null, not array).\n *\n * @param {unknown} value - Value to check.\n * @returns {boolean} True if value is a non-null, non-array object.\n */\nexport function isObject(value: unknown): value is Record<string, any> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\n/**\n * Gets all paths in an object using dot notation.\n *\n * @param {Record<string, any>} obj - Object to analyze.\n * @param {string} [parentPath=\"\"] - Internal param for recursion.\n * @returns {string[]} Array of all paths in dot notation.\n */\nexport function getAllPaths(\n obj: Record<string, any>,\n parentPath: string = \"\",\n): string[] {\n if (!isObject(obj)) return [];\n\n return Object.entries(obj).flatMap(([key, value]) => {\n const currentPath = parentPath ? `${parentPath}.${key}` : key;\n\n if (isObject(value)) {\n return [currentPath, ...getAllPaths(value, currentPath)];\n }\n\n return [currentPath];\n });\n}\n"]}
1
+ {"version":3,"file":"obj.utils.js","sourceRoot":"","sources":["../../../src/utils/obj.utils.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,MAAM,UAAU,UAAU,CAAC,GAAqB;IAC9C,OAAO,CAAC,CAAC,GAAG,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC;AAC3E,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,IAAI,CAAsC,GAAM,EAAE,IAAS;IACzE,OAAO,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,GAAG,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAe,CAAC;AAC5E,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,IAAI,CAAsC,GAAM,EAAE,IAAS;IACzE,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAQ,CAAC,CAAC,CAAe,CAAC;AAC3G,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,YAAY,CAAgC,MAAS,EAAE,MAAkB;IACvF,KAAK,MAAM,GAAG,IAAI,MAAM,EAAE,CAAC;QACzB,MAAM,SAAS,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;QAC9B,MAAM,SAAS,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;QAE9B,IAAI,SAAS,IAAI,OAAO,S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CAAC;YACpB,OAAO,CAAC,WAAW,EAAE,GAAG,WAAW,CAAC,KAAK,EAAE,WAAW,CAAC,CAAC,CAAC;QAC3D,CAAC;QAED,OAAO,CAAC,WAAW,CAAC,CAAC;IACvB,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * Checks whether the object has no own enumerable properties.\n *\n * @param {Record<any, any>} obj - The object to check.\n * @returns {boolean} True if the object is empty, false otherwise.\n */\nexport function isObjEmpty(obj: Record<any, any>): boolean {\n return !!obj && typeof obj === 'object' && Object.keys(obj).length === 0;\n}\n\n/**\n * Returns a new object with only the specified keys picked.\n *\n * @template T\n * @template K\n * @param {T} obj - The source object.\n * @param {K[]} keys - Keys to pick from the object.\n * @returns {Pick<T, K>} New object with picked keys.\n */\nexport function pick<T extends object, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> {\n return Object.fromEntries(keys.map(key => [key, obj[key]])) as Pick<T, K>;\n}\n\n/**\n * Returns a new object with the specified keys omitted.\n *\n * @template T\n * @template K\n * @param {T} obj - The source object.\n * @param {K[]} keys - Keys to omit from the object.\n * @returns {Omit<T, K>} New object without omitted keys.\n */\nexport function omit<T extends object, K extends keyof T>(obj: T, keys: K[]): Omit<T, K> {\n return Object.fromEntries(Object.entries(obj).filter(([key]) => !keys.includes(key as K))) as Omit<T, K>;\n}\n\n/**\n * Deeply merges two objects (mutates and returns the target object, not pure).\n *\n * @template T\n * @param {T} target - The object to merge into (will be mutated).\n * @param {Partial<T>} source - The object to merge from.\n * @returns {T} The merged object (same as target).\n */\nexport function deepObjMerge<T extends Record<string, any>>(target: T, source: Partial<T>): T {\n for (const key in source) {\n const sourceVal = source[key];\n const targetVal = target[key];\n\n if (sourceVal && typeof sourceVal === 'object' && !Array.isArray(sourceVal)) {\n if (!targetVal || typeof targetVal !== 'object' || Array.isArray(targetVal)) {\n target[key] = {} as any;\n }\n deepObjMerge(target[key], sourceVal as any);\n } else {\n target[key] = sourceVal as T[Extract<keyof T, string>];\n }\n }\n return target;\n}\n\n/**\n * Flattens a nested object using dot notation for keys (e.g., `{a: {b: 1}}` → `{ \"a.b\": 1 }`).\n *\n * @template T\n * @param {T} obj - The object to flatten.\n * @param {string} [prefix=\"\"] - Optional prefix for nested keys (used internally).\n * @returns {Record<string, any>} A new object with flattened keys.\n */\nexport function flattenObject<T extends Record<string, any>>(obj: T, prefix = ''): Record<string, any> {\n return Object.entries(obj).reduce((acc: Record<string, any>, [key, value]) => {\n const newKey = prefix ? `${prefix}.${key}` : key;\n\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n Object.assign(acc, flattenObject(value, newKey));\n } else {\n acc[newKey] = value;\n }\n\n return acc;\n }, {});\n}\n\n/**\n * Safely gets the value of a deeply nested key in an object using dot/bracket notation path.\n *\n * @template T\n * @param {T} obj - The object to extract from.\n * @param {string} path - String path using dot and/or bracket notation (e.g., 'user.friends[0].name').\n * @returns {any} The value at the given path, or undefined if not found.\n */\nexport function getValueByPath<T extends object>(obj: T, path: string) {\n if (!obj || typeof obj !== 'object') return undefined;\n\n // Convert path like \"a.b[0].c\" into [\"a\", \"b\", \"0\", \"c\"]\n const parts = path\n .replace(/\\[(\\d+)\\]/g, '.$1') // convert [0] to .0\n .split('.')\n .filter(Boolean); // remove empty strings\n\n return parts.reduce((acc: any, key: string) => acc?.[key], obj);\n}\n\n/**\n * Sets a value at a deeply nested key in an object using dot/bracket notation path.\n * Creates intermediate objects and arrays as needed.\n *\n * @template T\n * @param {T} obj - The object to modify.\n * @param {string} path - String path using dot and/or bracket notation (e.g., 'user.friends[0].name').\n * @param {any} value - The value to set at the path.\n * @returns {T} The modified object.\n */\nexport function setValueByPath<T extends object>(obj: T, path: string, value: any): T {\n if (!obj || typeof obj !== 'object') return obj;\n\n // Convert path like \"a.b[0].c\" into [\"a\", \"b\", \"0\", \"c\"]\n const parts = path\n .replace(/\\[(\\d+)\\]/g, '.$1') // convert [0] to .0\n .split('.')\n .filter(Boolean); // remove empty strings\n\n // Handle empty path\n if (parts.length === 0) return obj;\n\n let current: any = obj;\n\n // Navigate to the parent of the target property\n for (let i = 0; i < parts.length - 1; i++) {\n const key = parts[i];\n const isArrayIndex = !isNaN(Number(parts[i + 1]));\n\n if (current[key] === undefined) {\n // Create intermediate object or array based on next key type\n current[key] = isArrayIndex ? [] : {};\n }\n\n current = current[key];\n }\n\n // Set the value at the final key\n const finalKey = parts[parts.length - 1];\n current[finalKey] = value;\n\n return obj;\n}\n\n/**\n * Performs a deep equality check between two objects.\n *\n * @param {any} a - First value to compare.\n * @param {any} b - Second value to compare.\n * @returns {boolean} True if values are deeply equal.\n */\nexport function isEqual(a: any, b: any): boolean {\n // Check if primitives or references to the same object\n if (a === b) return true;\n\n // Check if either is null/undefined or not an object\n if (a == null || b == null || typeof a !== 'object' || typeof b !== 'object') {\n return false;\n }\n\n // Handle Date objects\n if (a instanceof Date && b instanceof Date) {\n return a.getTime() === b.getTime();\n }\n\n // If one is Date but the other isn't\n if (a instanceof Date || b instanceof Date) {\n return false;\n }\n\n // Handle arrays\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false;\n\n // Check each element\n for (let i = 0; i < a.length; i++) {\n if (!isEqual(a[i], b[i])) return false;\n }\n\n return true;\n }\n\n // If one is Array but the other isn't\n if (Array.isArray(a) || Array.isArray(b)) {\n return false;\n }\n\n // Compare object keys\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) return false;\n\n // Check if every key in A exists in B and has the same value\n return keysA.every(key => Object.prototype.hasOwnProperty.call(b, key) && isEqual(a[key], b[key]));\n}\n\n/**\n * Filters object properties based on a predicate function.\n *\n * @template T\n * @param {T} obj - The source object.\n * @param {(value: any, key: string, obj: T) => boolean} predicate - Filter function.\n * @returns {Partial<T>} New object with filtered properties.\n */\nexport function filterObject<T extends object>(\n obj: T,\n predicate: (value: any, key: string, obj: T) => boolean\n): Partial<T> {\n return Object.fromEntries(Object.entries(obj).filter(([key, value]) => predicate(value, key, obj))) as Partial<T>;\n}\n\n/**\n * Maps object values to new values using a mapping function.\n *\n * @template T\n * @template U\n * @param {T} obj - The source object.\n * @param {(value: any, key: string, obj: T) => U} mapFn - Mapping function.\n * @returns {Record<keyof T, U>} New object with mapped values.\n */\nexport function mapObject<T extends object, U>(\n obj: T,\n mapFn: (value: any, key: string, obj: T) => U\n): Record<keyof T, U> {\n return Object.fromEntries(Object.entries(obj).map(([key, value]) => [key, mapFn(value, key, obj)])) as Record<\n keyof T,\n U\n >;\n}\n\n/**\n * Recursively freezes an object and all its properties.\n * Makes an object immutable.\n *\n * @template T\n * @param {T} obj - The object to freeze.\n * @returns {Readonly<T>} The frozen object.\n */\nexport function deepFreeze<T extends object>(obj: T): Readonly<T> {\n // Freeze primitive properties\n Object.freeze(obj);\n\n // Recursively freeze nested objects\n for (const prop of Object.getOwnPropertyNames(obj)) {\n const value = (obj as any)[prop];\n if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {\n deepFreeze(value);\n }\n }\n\n return obj;\n}\n\n/**\n * Safely checks if a value is an object (not null, not array).\n *\n * @param {unknown} value - Value to check.\n * @returns {boolean} True if value is a non-null, non-array object.\n */\nexport function isObject(value: unknown): value is Record<string, any> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/**\n * Gets all paths in an object using dot notation.\n *\n * @param {Record<string, any>} obj - Object to analyze.\n * @param {string} [parentPath=\"\"] - Internal param for recursion.\n * @returns {string[]} Array of all paths in dot notation.\n */\nexport function getAllPaths(obj: Record<string, any>, parentPath: string = ''): string[] {\n if (!isObject(obj)) return [];\n\n return Object.entries(obj).flatMap(([key, value]) => {\n const currentPath = parentPath ? `${parentPath}.${key}` : key;\n\n if (isObject(value)) {\n return [currentPath, ...getAllPaths(value, currentPath)];\n }\n\n return [currentPath];\n });\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { ApiResponse } from "../types/api-response";
1
+ import { ApiResponse } from '../types/api-response';
2
2
  /**
3
3
  * Standard HTTP response wrapper for successful responses.
4
4
  * Implements the `ApiResponse<T>` interface and sets default values.
@@ -28,7 +28,7 @@ export declare class SuccessResponse<T> implements ApiResponse<T> {
28
28
  * Wrapper for error responses that extends the native `Error` object.
29
29
  * Implements `ApiResponse` but omits the `data` field (which should not be present in errors).
30
30
  */
31
- export declare class ErrorResponse extends Error implements Omit<ApiResponse<never>, "data"> {
31
+ export declare class ErrorResponse extends Error implements Omit<ApiResponse<never>, 'data'> {
32
32
  /** HTTP status code associated with the error (e.g., 404, 500). */
33
33
  status: number;
34
34
  /** Indicates that this is an error. Always true. */
@@ -1,5 +1,5 @@
1
- import { randomUUID } from "crypto";
2
- import { getRequestId } from "./context-store.utils";
1
+ import { randomUUID } from 'crypto';
2
+ import { getRequestId } from './context-store.utils';
3
3
  /**
4
4
  * Standard HTTP response wrapper for successful responses.
5
5
  * Implements the `ApiResponse<T>` interface and sets default values.
@@ -16,7 +16,7 @@ export class SuccessResponse {
16
16
  constructor(message, data) {
17
17
  var _a;
18
18
  /** Message describing the result of the operation. */
19
- this.message = "Success";
19
+ this.message = 'Success';
20
20
  /** Whether the response is an error. Always false in success responses. */
21
21
  this.error = false;
22
22
  /** The payload returned from the API. */
@@ -72,7 +72,7 @@ export class PaginatedResponse extends SuccessResponse {
72
72
  * @param {number} pagination.pageSize - Number of items per page.
73
73
  * @param {string} [message="Success"] - Optional custom message.
74
74
  */
75
- constructor(items, pagination, message = "Success") {
75
+ constructor(items, pagination, message = 'Success') {
76
76
  super(message, items);
77
77
  this.total = pagination.total;
78
78
  this.page = pagination.page;
@@ -91,7 +91,7 @@ export class NoContentResponse extends SuccessResponse {
91
91
  *
92
92
  * @param {string} [message="Operation completed successfully"] - Optional custom message.
93
93
  */
94
- constructor(message = "Operation completed successfully") {
94
+ constructor(message = 'Operation completed successfully') {
95
95
  super(message, null);
96
96
  }
97
97
  }
@@ -123,7 +123,7 @@ export class RedirectResponse {
123
123
  * @param {string} [message="Success"] - Optional custom message.
124
124
  * @returns {SuccessResponse<T>} A properly formatted success response.
125
125
  */
126
- export function createSuccessResponse(data, message = "Success") {
126
+ export function createSuccessResponse(data, message = 'Success') {
127
127
  return new SuccessResponse(message, data);
128
128
  }
129
129
  /**
@@ -146,7 +146,7 @@ export function createErrorResponse(message, statusCode = 500) {
146
146
  * @param {string} [message="Success"] - Optional custom message.
147
147
  * @returns {PaginatedResponse<T>} A properly formatted paginated response.
148
148
  */
149
- export function createPaginatedResponse(allItems, page, pageSize, message = "Success") {
149
+ export function createPaginatedResponse(allItems, page, pageSize, message = 'Success') {
150
150
  // Ensure valid pagination parameters
151
151
  const validPage = Math.max(1, page);
152
152
  const validPageSize = Math.max(1, pageSize);
@@ -158,7 +158,7 @@ export function createPaginatedResponse(allItems, page, pageSize, message = "Suc
158
158
  return new PaginatedResponse(pageItems, {
159
159
  total: allItems.length,
160
160
  page: validPage,
161
- pageSize: validPageSize,
161
+ pageSize: validPageSize
162
162
  }, message);
163
163
  }
164
164
  /**
@@ -169,18 +169,18 @@ export function createPaginatedResponse(allItems, page, pageSize, message = "Suc
169
169
  */
170
170
  export function sendResponse(res, apiResponse) {
171
171
  // Handle redirects
172
- if ("redirectUrl" in apiResponse) {
172
+ if ('redirectUrl' in apiResponse) {
173
173
  res.redirect(apiResponse.statusCode, apiResponse.redirectUrl);
174
174
  return;
175
175
  }
176
176
  // Handle errors
177
- if ("error" in apiResponse && apiResponse.error) {
177
+ if ('error' in apiResponse && apiResponse.error) {
178
178
  const errorResponse = apiResponse;
179
179
  res.status(errorResponse.status).json({
180
180
  error: true,
181
181
  message: errorResponse.message,
182
182
  timestamp: errorResponse.timestamp,
183
- requestId: errorResponse.requestId,
183
+ requestId: errorResponse.requestId
184
184
  });
185
185
  return;
186
186
  }
@@ -1 +1 @@
1
- {"version":3,"file":"response.utils.js","sourceRoot":"","sources":["../../../src/utils/response.utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AAEpC,OAAO,EAAE,YAAY,EAAE,MAAM,uBA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Aa,CAAC,SAAS;SACnC,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IAED,2BAA2B;IAC3B,MAAM,eAAe,GAAG,WAAmC,CAAC;IAE5D,2CAA2C;IAC3C,IAAI,eAAe,YAAY,iBAAiB,EAAE,CAAC;QACjD,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,CAAC;QACtB,OAAO;IACT,CAAC;IAED,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;AACxC,CAAC","sourcesContent":["import { randomUUID } from \"crypto\";\nimport { ApiResponse } from \"../types/api-response\";\nimport { getRequestId } from \"./context-store.utils\";\n\n/**\n * Standard HTTP response wrapper for successful responses.\n * Implements the `ApiResponse<T>` interface and sets default values.\n *\n * @typeParam T - The shape of the data returned in the response.\n */\nexport class SuccessResponse<T> implements ApiResponse<T> {\n /** Message describing the result of the operation. */\n message: string = \"Success\";\n\n /** Whether the response is an error. Always false in success responses. */\n error: boolean = false;\n\n /** The payload returned from the API. */\n data: T | null = null;\n\n /** Timestamp when the response was generated, in ISO format. */\n timestamp: string = new Date().toISOString();\n\n /** Unique identifier for this response, useful for request tracing. */\n requestId: string = getRequestId() ?? randomUUID();\n\n /**\n * Constructs a new success response.\n *\n * @param {string} message - Optional message to override the default.\n * @param {T} [data] - Optional data payload.\n */\n constructor(message: string, data?: T) {\n if (message) this.message = message;\n this.data = data ?? null;\n }\n}\n\n/**\n * Wrapper for error responses that extends the native `Error` object.\n * Implements `ApiResponse` but omits the `data` field (which should not be present in errors).\n */\nexport class ErrorResponse\n extends Error\n implements Omit<ApiResponse<never>, \"data\">\n{\n /** HTTP status code associated with the error (e.g., 404, 500). */\n status: number;\n\n /** Indicates that this is an error. Always true. */\n error: boolean = true;\n\n /** Timestamp when the error occurred, in ISO format. */\n timestamp: string = new Date().toISOString();\n\n /** Unique identifier for this error instance. */\n requestId: string = getRequestId() ?? randomUUID();\n\n /**\n * Constructs a new error response.\n *\n * @param {string} message - The error message to display or log.\n * @param {number} [status=500] - Optional HTTP status code (defaults to 500).\n */\n constructor(message: string, status: number = 500) {\n super(message);\n this.status = status;\n this.name = this.constructor.name;\n Error.captureStackTrace(this, this.constructor);\n }\n}\n\n/**\n * Response with paginated data extending the standard success response.\n * Useful for APIs that return large collections of data.\n *\n * @typeParam T - The shape of each item in the paginated collection.\n */\nexport class PaginatedResponse<T> extends SuccessResponse<T[]> {\n /** Total number of items across all pages */\n total: number;\n\n /** Current page number (1-based) */\n page: number;\n\n /** Number of items per page */\n pageSize: number;\n\n /** Total number of pages */\n totalPages: number;\n\n /** Whether there's a next page available */\n hasNext: boolean;\n\n /** Whether there's a previous page available */\n hasPrevious: boolean;\n\n /**\n * Constructs a new paginated response.\n *\n * @param {T[]} items - The current page of items.\n * @param {Object} pagination - Pagination information.\n * @param {number} pagination.total - Total number of items across all pages.\n * @param {number} pagination.page - Current page number (1-based).\n * @param {number} pagination.pageSize - Number of items per page.\n * @param {string} [message=\"Success\"] - Optional custom message.\n */\n constructor(\n items: T[],\n pagination: { total: number; page: number; pageSize: number },\n message: string = \"Success\",\n ) {\n super(message, items);\n\n this.total = pagination.total;\n this.page = pagination.page;\n this.pageSize = pagination.pageSize;\n\n this.totalPages = Math.ceil(this.total / this.pageSize);\n this.hasNext = this.page < this.totalPages;\n this.hasPrevious = this.page > 1;\n }\n}\n\n/**\n * Specialized response for operations that don't return data (HTTP 204).\n */\nexport class NoContentResponse extends SuccessResponse<null> {\n /**\n * Constructs a new no-content response.\n *\n * @param {string} [message=\"Operation completed successfully\"] - Optional custom message.\n */\n constructor(message: string = \"Operation completed successfully\") {\n super(message, null);\n }\n}\n\n/**\n * Specialized response for redirects.\n */\nexport class RedirectResponse {\n /** The URL to redirect to */\n redirectUrl: string;\n\n /** HTTP status code for the redirect (301, 302, 303, 307, 308) */\n statusCode: number;\n\n /** Whether the response is a redirect */\n isRedirect: boolean = true;\n\n /** Unique identifier for this response */\n requestId: string = getRequestId() ?? randomUUID();\n\n /**\n * Constructs a new redirect response.\n *\n * @param {string} url - The URL to redirect to.\n * @param {number} [statusCode=302] - HTTP status code for the redirect.\n */\n constructor(url: string, statusCode: number = 302) {\n this.redirectUrl = url;\n this.statusCode = statusCode;\n }\n}\n\n/**\n * Creates a standard success response.\n *\n * @typeParam T - The shape of the data returned in the response.\n * @param {T} data - The data to include in the response.\n * @param {string} [message=\"Success\"] - Optional custom message.\n * @returns {SuccessResponse<T>} A properly formatted success response.\n */\nexport function createSuccessResponse<T>(\n data: T,\n message: string = \"Success\",\n): SuccessResponse<T> {\n return new SuccessResponse<T>(message, data);\n}\n\n/**\n * Creates a standard error response.\n *\n * @param {string} message - The error message.\n * @param {number} [statusCode=500] - HTTP status code for the error.\n * @returns {ErrorResponse} A properly formatted error response.\n */\nexport function createErrorResponse(\n message: string,\n statusCode: number = 500,\n): ErrorResponse {\n return new ErrorResponse(message, statusCode);\n}\n\n/**\n * Creates a paginated response from array data.\n *\n * @typeParam T - The shape of each item in the collection.\n * @param {T[]} allItems - The complete array of items to paginate.\n * @param {number} page - The requested page (1-based).\n * @param {number} pageSize - The number of items per page.\n * @param {string} [message=\"Success\"] - Optional custom message.\n * @returns {PaginatedResponse<T>} A properly formatted paginated response.\n */\nexport function createPaginatedResponse<T>(\n allItems: T[],\n page: number,\n pageSize: number,\n message: string = \"Success\",\n): PaginatedResponse<T> {\n // Ensure valid pagination parameters\n const validPage = Math.max(1, page);\n const validPageSize = Math.max(1, pageSize);\n\n // Calculate slice indices\n const startIndex = (validPage - 1) * validPageSize;\n const endIndex = startIndex + validPageSize;\n\n // Get current page items\n const pageItems = allItems.slice(startIndex, endIndex);\n\n return new PaginatedResponse<T>(\n pageItems,\n {\n total: allItems.length,\n page: validPage,\n pageSize: validPageSize,\n },\n message,\n );\n}\n\n/**\n * Adapter to convert API responses to Express.js response format.\n *\n * @param {any} res - Express response object.\n * @param {SuccessResponse<any> | ErrorResponse | RedirectResponse} apiResponse - API response instance.\n */\nexport function sendResponse(\n res: any,\n apiResponse: SuccessResponse<any> | ErrorResponse | RedirectResponse,\n): void {\n // Handle redirects\n if (\"redirectUrl\" in apiResponse) {\n res.redirect(apiResponse.statusCode, apiResponse.redirectUrl);\n return;\n }\n\n // Handle errors\n if (\"error\" in apiResponse && apiResponse.error) {\n const errorResponse = apiResponse as ErrorResponse;\n res.status(errorResponse.status).json({\n error: true,\n message: errorResponse.message,\n timestamp: errorResponse.timestamp,\n requestId: errorResponse.requestId,\n });\n return;\n }\n\n // Handle success responses\n const successResponse = apiResponse as SuccessResponse<any>;\n\n // No content (204) shouldn't return a body\n if (successResponse instanceof NoContentResponse) {\n res.status(204).end();\n return;\n }\n\n res.status(200).json(successResponse);\n}\n"]}
1
+ {"version":3,"file":"response.utils.js","sourceRoot":"","sources":["../../../src/utils/response.utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AAEpC,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAErD;;;;;GAKG;AACH,MAAM,OAAO,eAAe;IAgB1B;;;;;OAKG;IACH,YAAY,OAAe,EAAE,IAAQ;;QArBrC,sDAAsD;QACtD,YAAO,GAAW,SAAS,CAAC;QAE5B,2EAA2E;QAC3E,UAAK,GAAY,KAAK,CAAC;QAEvB,yCAAyC;QACzC,SAAI,GAAa,IAAI,CAAC;QAEtB,gEAAgE;QAChE,cAAS,GAAW,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;QAE7C,uEAAuE;QACvE,cAAS,GAAW,MAAA,YAAY,EAAE,mCAAI,UAAU,EAAE,CAAC;QASjD,IAAI,OAAO;YAAE,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACpC,IAAI,CAAC,IAAI,GAAG,IAAI,aAAJ,IAAI,cAAJ,IAAI,GAAI,IAAI,CAAC;IAC3B,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,OAAO,aAAc,SAAQ,KAAK;IAatC;;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AM;QACtB,IAAI,EAAE,SAAS;QACf,QAAQ,EAAE,aAAa;KACxB,EACD,OAAO,CACR,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,YAAY,CAAC,GAAQ,EAAE,WAAoE;IACzG,mBAAmB;IACnB,IAAI,aAAa,IAAI,WAAW,EAAE,CAAC;QACjC,GAAG,CAAC,QAAQ,CAAC,WAAW,CAAC,UAAU,EAAE,WAAW,CAAC,WAAW,CAAC,CAAC;QAC9D,OAAO;IACT,CAAC;IAED,gBAAgB;IAChB,IAAI,OAAO,IAAI,WAAW,IAAI,WAAW,CAAC,KAAK,EAAE,CAAC;QAChD,MAAM,aAAa,GAAG,WAA4B,CAAC;QACnD,GAAG,CAAC,MAAM,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC;YACpC,KAAK,EAAE,IAAI;YACX,OAAO,EAAE,aAAa,CAAC,OAAO;YAC9B,SAAS,EAAE,aAAa,CAAC,SAAS;YAClC,SAAS,EAAE,aAAa,CAAC,SAAS;SACnC,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IAED,2BAA2B;IAC3B,MAAM,eAAe,GAAG,WAAmC,CAAC;IAE5D,2CAA2C;IAC3C,IAAI,eAAe,YAAY,iBAAiB,EAAE,CAAC;QACjD,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,CAAC;QACtB,OAAO;IACT,CAAC;IAED,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;AACxC,CAAC","sourcesContent":["import { randomUUID } from 'crypto';\nimport { ApiResponse } from '../types/api-response';\nimport { getRequestId } from './context-store.utils';\n\n/**\n * Standard HTTP response wrapper for successful responses.\n * Implements the `ApiResponse<T>` interface and sets default values.\n *\n * @typeParam T - The shape of the data returned in the response.\n */\nexport class SuccessResponse<T> implements ApiResponse<T> {\n /** Message describing the result of the operation. */\n message: string = 'Success';\n\n /** Whether the response is an error. Always false in success responses. */\n error: boolean = false;\n\n /** The payload returned from the API. */\n data: T | null = null;\n\n /** Timestamp when the response was generated, in ISO format. */\n timestamp: string = new Date().toISOString();\n\n /** Unique identifier for this response, useful for request tracing. */\n requestId: string = getRequestId() ?? randomUUID();\n\n /**\n * Constructs a new success response.\n *\n * @param {string} message - Optional message to override the default.\n * @param {T} [data] - Optional data payload.\n */\n constructor(message: string, data?: T) {\n if (message) this.message = message;\n this.data = data ?? null;\n }\n}\n\n/**\n * Wrapper for error responses that extends the native `Error` object.\n * Implements `ApiResponse` but omits the `data` field (which should not be present in errors).\n */\nexport class ErrorResponse extends Error implements Omit<ApiResponse<never>, 'data'> {\n /** HTTP status code associated with the error (e.g., 404, 500). */\n status: number;\n\n /** Indicates that this is an error. Always true. */\n error: boolean = true;\n\n /** Timestamp when the error occurred, in ISO format. */\n timestamp: string = new Date().toISOString();\n\n /** Unique identifier for this error instance. */\n requestId: string = getRequestId() ?? randomUUID();\n\n /**\n * Constructs a new error response.\n *\n * @param {string} message - The error message to display or log.\n * @param {number} [status=500] - Optional HTTP status code (defaults to 500).\n */\n constructor(message: string, status: number = 500) {\n super(message);\n this.status = status;\n this.name = this.constructor.name;\n Error.captureStackTrace(this, this.constructor);\n }\n}\n\n/**\n * Response with paginated data extending the standard success response.\n * Useful for APIs that return large collections of data.\n *\n * @typeParam T - The shape of each item in the paginated collection.\n */\nexport class PaginatedResponse<T> extends SuccessResponse<T[]> {\n /** Total number of items across all pages */\n total: number;\n\n /** Current page number (1-based) */\n page: number;\n\n /** Number of items per page */\n pageSize: number;\n\n /** Total number of pages */\n totalPages: number;\n\n /** Whether there's a next page available */\n hasNext: boolean;\n\n /** Whether there's a previous page available */\n hasPrevious: boolean;\n\n /**\n * Constructs a new paginated response.\n *\n * @param {T[]} items - The current page of items.\n * @param {Object} pagination - Pagination information.\n * @param {number} pagination.total - Total number of items across all pages.\n * @param {number} pagination.page - Current page number (1-based).\n * @param {number} pagination.pageSize - Number of items per page.\n * @param {string} [message=\"Success\"] - Optional custom message.\n */\n constructor(items: T[], pagination: { total: number; page: number; pageSize: number }, message: string = 'Success') {\n super(message, items);\n\n this.total = pagination.total;\n this.page = pagination.page;\n this.pageSize = pagination.pageSize;\n\n this.totalPages = Math.ceil(this.total / this.pageSize);\n this.hasNext = this.page < this.totalPages;\n this.hasPrevious = this.page > 1;\n }\n}\n\n/**\n * Specialized response for operations that don't return data (HTTP 204).\n */\nexport class NoContentResponse extends SuccessResponse<null> {\n /**\n * Constructs a new no-content response.\n *\n * @param {string} [message=\"Operation completed successfully\"] - Optional custom message.\n */\n constructor(message: string = 'Operation completed successfully') {\n super(message, null);\n }\n}\n\n/**\n * Specialized response for redirects.\n */\nexport class RedirectResponse {\n /** The URL to redirect to */\n redirectUrl: string;\n\n /** HTTP status code for the redirect (301, 302, 303, 307, 308) */\n statusCode: number;\n\n /** Whether the response is a redirect */\n isRedirect: boolean = true;\n\n /** Unique identifier for this response */\n requestId: string = getRequestId() ?? randomUUID();\n\n /**\n * Constructs a new redirect response.\n *\n * @param {string} url - The URL to redirect to.\n * @param {number} [statusCode=302] - HTTP status code for the redirect.\n */\n constructor(url: string, statusCode: number = 302) {\n this.redirectUrl = url;\n this.statusCode = statusCode;\n }\n}\n\n/**\n * Creates a standard success response.\n *\n * @typeParam T - The shape of the data returned in the response.\n * @param {T} data - The data to include in the response.\n * @param {string} [message=\"Success\"] - Optional custom message.\n * @returns {SuccessResponse<T>} A properly formatted success response.\n */\nexport function createSuccessResponse<T>(data: T, message: string = 'Success'): SuccessResponse<T> {\n return new SuccessResponse<T>(message, data);\n}\n\n/**\n * Creates a standard error response.\n *\n * @param {string} message - The error message.\n * @param {number} [statusCode=500] - HTTP status code for the error.\n * @returns {ErrorResponse} A properly formatted error response.\n */\nexport function createErrorResponse(message: string, statusCode: number = 500): ErrorResponse {\n return new ErrorResponse(message, statusCode);\n}\n\n/**\n * Creates a paginated response from array data.\n *\n * @typeParam T - The shape of each item in the collection.\n * @param {T[]} allItems - The complete array of items to paginate.\n * @param {number} page - The requested page (1-based).\n * @param {number} pageSize - The number of items per page.\n * @param {string} [message=\"Success\"] - Optional custom message.\n * @returns {PaginatedResponse<T>} A properly formatted paginated response.\n */\nexport function createPaginatedResponse<T>(\n allItems: T[],\n page: number,\n pageSize: number,\n message: string = 'Success'\n): PaginatedResponse<T> {\n // Ensure valid pagination parameters\n const validPage = Math.max(1, page);\n const validPageSize = Math.max(1, pageSize);\n\n // Calculate slice indices\n const startIndex = (validPage - 1) * validPageSize;\n const endIndex = startIndex + validPageSize;\n\n // Get current page items\n const pageItems = allItems.slice(startIndex, endIndex);\n\n return new PaginatedResponse<T>(\n pageItems,\n {\n total: allItems.length,\n page: validPage,\n pageSize: validPageSize\n },\n message\n );\n}\n\n/**\n * Adapter to convert API responses to Express.js response format.\n *\n * @param {any} res - Express response object.\n * @param {SuccessResponse<any> | ErrorResponse | RedirectResponse} apiResponse - API response instance.\n */\nexport function sendResponse(res: any, apiResponse: SuccessResponse<any> | ErrorResponse | RedirectResponse): void {\n // Handle redirects\n if ('redirectUrl' in apiResponse) {\n res.redirect(apiResponse.statusCode, apiResponse.redirectUrl);\n return;\n }\n\n // Handle errors\n if ('error' in apiResponse && apiResponse.error) {\n const errorResponse = apiResponse as ErrorResponse;\n res.status(errorResponse.status).json({\n error: true,\n message: errorResponse.message,\n timestamp: errorResponse.timestamp,\n requestId: errorResponse.requestId\n });\n return;\n }\n\n // Handle success responses\n const successResponse = apiResponse as SuccessResponse<any>;\n\n // No content (204) shouldn't return a body\n if (successResponse instanceof NoContentResponse) {\n res.status(204).end();\n return;\n }\n\n res.status(200).json(successResponse);\n}\n"]}
@@ -5,7 +5,7 @@
5
5
  * @returns {string} The string with the first character in uppercase.
6
6
  */
7
7
  export function capitalize(str) {
8
- return str.length === 0 ? "" : str.charAt(0).toUpperCase() + str.slice(1);
8
+ return str.length === 0 ? '' : str.charAt(0).toUpperCase() + str.slice(1);
9
9
  }
10
10
  /**
11
11
  * Converts a string to kebab-case (e.g., "FooBar test" → "foo-bar-test").
@@ -15,9 +15,9 @@ export function capitalize(str) {
15
15
  */
16
16
  export function toKebabCase(str) {
17
17
  return str
18
- .replace(/([a-z])([A-Z])/g, "$1-$2") // camelCase -> camel-Case
19
- .replace(/\s+/g, "-") // spaces to dash
20
- .replace(/_+/g, "-") // underscores to dash
18
+ .replace(/([a-z])([A-Z])/g, '$1-$2') // camelCase -> camel-Case
19
+ .replace(/\s+/g, '-') // spaces to dash
20
+ .replace(/_+/g, '-') // underscores to dash
21
21
  .toLowerCase();
22
22
  }
23
23
  /**
@@ -38,10 +38,10 @@ export function toCamelCase(str) {
38
38
  export function slugify(str) {
39
39
  return str
40
40
  .toLowerCase()
41
- .replace(/[^\w\s-]/g, "") // remove non-word
42
- .replace(/\s+/g, "-") // spaces to dash
43
- .replace(/-+/g, "-") // multiple dashes to one
44
- .replace(/^-+|-+$/g, ""); // trim leading/trailing dashes
41
+ .replace(/[^\w\s-]/g, '') // remove non-word
42
+ .replace(/\s+/g, '-') // spaces to dash
43
+ .replace(/-+/g, '-') // multiple dashes to one
44
+ .replace(/^-+|-+$/g, ''); // trim leading/trailing dashes
45
45
  }
46
46
  /**
47
47
  * Truncates a string to a specific length, appending '...' if truncated.
@@ -51,7 +51,7 @@ export function slugify(str) {
51
51
  * @returns {string} The truncated string.
52
52
  */
53
53
  export function truncate(str, len) {
54
- return str.length > len ? str.slice(0, len) + "..." : str;
54
+ return str.length > len ? str.slice(0, len) + '...' : str;
55
55
  }
56
56
  /**
57
57
  * Converts a string to PascalCase (e.g., "foo-bar" → "FooBar").
@@ -71,9 +71,9 @@ export function toPascalCase(str) {
71
71
  export function toSnakeCase(str) {
72
72
  return str
73
73
  .trim()
74
- .replace(/([a-z])([A-Z])/g, "$1_$2") // camelCase -> camel_Case
75
- .replace(/\s+/g, "_") // spaces to underscore
76
- .replace(/-+/g, "_") // dashes to underscore
74
+ .replace(/([a-z])([A-Z])/g, '$1_$2') // camelCase -> camel_Case
75
+ .replace(/\s+/g, '_') // spaces to underscore
76
+ .replace(/-+/g, '_') // dashes to underscore
77
77
  .toLowerCase();
78
78
  }
79
79
  /**
@@ -86,13 +86,13 @@ export function toSnakeCase(str) {
86
86
  * @param {string} [maskChar="*"] - Character to use for masking.
87
87
  * @returns {string} The masked string.
88
88
  */
89
- export function mask(str, visibleStart = 0, visibleEnd = 0, maskChar = "*") {
89
+ export function mask(str, visibleStart = 0, visibleEnd = 0, maskChar = '*') {
90
90
  if (!str || str.length === 0)
91
- return "";
91
+ return '';
92
92
  if (visibleStart >= str.length)
93
93
  return str;
94
94
  const start = str.slice(0, visibleStart);
95
- const end = visibleEnd > 0 ? str.slice(-visibleEnd) : "";
95
+ const end = visibleEnd > 0 ? str.slice(-visibleEnd) : '';
96
96
  const masked = maskChar.repeat(Math.max(0, str.length - visibleStart - visibleEnd));
97
97
  return start + masked + end;
98
98
  }
@@ -103,7 +103,7 @@ export function mask(str, visibleStart = 0, visibleEnd = 0, maskChar = "*") {
103
103
  * @returns {string} The string with HTML tags removed.
104
104
  */
105
105
  export function stripHtml(str) {
106
- return str.replace(/<[^>]*>/g, "");
106
+ return str.replace(/<[^>]*>/g, '');
107
107
  }
108
108
  /**
109
109
  * Performs case-insensitive string comparison.
@@ -122,7 +122,7 @@ export function equalsIgnoreCase(a, b) {
122
122
  * @returns {string} The reversed string.
123
123
  */
124
124
  export function reverse(str) {
125
- return str.split("").reverse().join("");
125
+ return str.split('').reverse().join('');
126
126
  }
127
127
  /**
128
128
  * Counts occurrences of a substring within a string.