@catbee/utils 0.0.6 → 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 (122) hide show
  1. package/README.md +51 -1106
  2. package/build/esm/config.d.ts +5 -13
  3. package/build/esm/config.js +0 -12
  4. package/build/esm/config.js.map +1 -1
  5. package/build/esm/servers/server.builder.d.ts +1 -118
  6. package/build/esm/servers/server.builder.js +0 -20
  7. package/build/esm/servers/server.builder.js.map +1 -1
  8. package/build/esm/servers/server.d.ts +2 -2
  9. package/build/esm/servers/server.js +3 -13
  10. package/build/esm/servers/server.js.map +1 -1
  11. package/build/esm/types/api-response.d.ts +28 -0
  12. package/build/esm/types/api-response.js +10 -1
  13. package/build/esm/types/api-response.js.map +1 -1
  14. package/build/esm/types/server.d.ts +0 -17
  15. package/build/esm/types/server.js.map +1 -1
  16. package/build/esm/utils/async.utils.d.ts +91 -0
  17. package/build/esm/utils/async.utils.js +244 -0
  18. package/build/esm/utils/async.utils.js.map +1 -1
  19. package/build/esm/utils/context-store.utils.d.ts +3 -0
  20. package/build/esm/utils/context-store.utils.js +9 -6
  21. package/build/esm/utils/context-store.utils.js.map +1 -1
  22. package/build/esm/utils/date.utils.d.ts +159 -0
  23. package/build/esm/utils/date.utils.js +389 -0
  24. package/build/esm/utils/date.utils.js.map +1 -0
  25. package/build/esm/utils/logger.utils.d.ts +3 -9
  26. package/build/esm/utils/logger.utils.js +3 -9
  27. package/build/esm/utils/logger.utils.js.map +1 -1
  28. package/build/esm/utils/middleware.utils.js +2 -1
  29. package/build/esm/utils/middleware.utils.js.map +1 -1
  30. package/build/esm/utils/performance.utils.d.ts +136 -0
  31. package/build/esm/utils/performance.utils.js +376 -0
  32. package/build/esm/utils/performance.utils.js.map +1 -0
  33. package/build/esm/utils/request.utils.d.ts +9 -0
  34. package/build/esm/utils/request.utils.js +32 -5
  35. package/build/esm/utils/request.utils.js.map +1 -1
  36. package/build/esm/utils/stream.utils.d.ts +88 -0
  37. package/build/esm/utils/stream.utils.js +284 -0
  38. package/build/esm/utils/stream.utils.js.map +1 -0
  39. package/build/esm/utils/type.utils.d.ts +90 -0
  40. package/build/esm/utils/type.utils.js +190 -0
  41. package/build/esm/utils/type.utils.js.map +1 -0
  42. package/build/esnext/config.d.ts +5 -13
  43. package/build/esnext/config.js +0 -12
  44. package/build/esnext/config.js.map +1 -1
  45. package/build/esnext/servers/server.builder.d.ts +1 -118
  46. package/build/esnext/servers/server.builder.js +0 -20
  47. package/build/esnext/servers/server.builder.js.map +1 -1
  48. package/build/esnext/servers/server.d.ts +2 -2
  49. package/build/esnext/servers/server.js +3 -13
  50. package/build/esnext/servers/server.js.map +1 -1
  51. package/build/esnext/types/api-response.d.ts +28 -0
  52. package/build/esnext/types/api-response.js +10 -1
  53. package/build/esnext/types/api-response.js.map +1 -1
  54. package/build/esnext/types/server.d.ts +0 -17
  55. package/build/esnext/types/server.js.map +1 -1
  56. package/build/esnext/utils/async.utils.d.ts +91 -0
  57. package/build/esnext/utils/async.utils.js +190 -0
  58. package/build/esnext/utils/async.utils.js.map +1 -1
  59. package/build/esnext/utils/context-store.utils.d.ts +3 -0
  60. package/build/esnext/utils/context-store.utils.js +9 -6
  61. package/build/esnext/utils/context-store.utils.js.map +1 -1
  62. package/build/esnext/utils/date.utils.d.ts +159 -0
  63. package/build/esnext/utils/date.utils.js +384 -0
  64. package/build/esnext/utils/date.utils.js.map +1 -0
  65. package/build/esnext/utils/logger.utils.d.ts +3 -9
  66. package/build/esnext/utils/logger.utils.js +3 -9
  67. package/build/esnext/utils/logger.utils.js.map +1 -1
  68. package/build/esnext/utils/middleware.utils.js +2 -1
  69. package/build/esnext/utils/middleware.utils.js.map +1 -1
  70. package/build/esnext/utils/performance.utils.d.ts +136 -0
  71. package/build/esnext/utils/performance.utils.js +271 -0
  72. package/build/esnext/utils/performance.utils.js.map +1 -0
  73. package/build/esnext/utils/request.utils.d.ts +9 -0
  74. package/build/esnext/utils/request.utils.js +23 -5
  75. package/build/esnext/utils/request.utils.js.map +1 -1
  76. package/build/esnext/utils/stream.utils.d.ts +88 -0
  77. package/build/esnext/utils/stream.utils.js +210 -0
  78. package/build/esnext/utils/stream.utils.js.map +1 -0
  79. package/build/esnext/utils/type.utils.d.ts +90 -0
  80. package/build/esnext/utils/type.utils.js +187 -0
  81. package/build/esnext/utils/type.utils.js.map +1 -0
  82. package/build/src/config.d.ts +5 -13
  83. package/build/src/config.js +0 -12
  84. package/build/src/config.js.map +1 -1
  85. package/build/src/servers/server.builder.d.ts +1 -118
  86. package/build/src/servers/server.builder.js +0 -20
  87. package/build/src/servers/server.builder.js.map +1 -1
  88. package/build/src/servers/server.d.ts +2 -2
  89. package/build/src/servers/server.js +2 -12
  90. package/build/src/servers/server.js.map +1 -1
  91. package/build/src/types/api-response.d.ts +28 -0
  92. package/build/src/types/api-response.js +11 -0
  93. package/build/src/types/api-response.js.map +1 -1
  94. package/build/src/types/server.d.ts +0 -17
  95. package/build/src/types/server.js.map +1 -1
  96. package/build/src/utils/async.utils.d.ts +91 -0
  97. package/build/src/utils/async.utils.js +194 -0
  98. package/build/src/utils/async.utils.js.map +1 -1
  99. package/build/src/utils/context-store.utils.d.ts +3 -0
  100. package/build/src/utils/context-store.utils.js +9 -6
  101. package/build/src/utils/context-store.utils.js.map +1 -1
  102. package/build/src/utils/date.utils.d.ts +159 -0
  103. package/build/src/utils/date.utils.js +396 -0
  104. package/build/src/utils/date.utils.js.map +1 -0
  105. package/build/src/utils/logger.utils.d.ts +3 -9
  106. package/build/src/utils/logger.utils.js +4 -10
  107. package/build/src/utils/logger.utils.js.map +1 -1
  108. package/build/src/utils/middleware.utils.js +2 -1
  109. package/build/src/utils/middleware.utils.js.map +1 -1
  110. package/build/src/utils/performance.utils.d.ts +136 -0
  111. package/build/src/utils/performance.utils.js +278 -0
  112. package/build/src/utils/performance.utils.js.map +1 -0
  113. package/build/src/utils/request.utils.d.ts +9 -0
  114. package/build/src/utils/request.utils.js +25 -5
  115. package/build/src/utils/request.utils.js.map +1 -1
  116. package/build/src/utils/stream.utils.d.ts +88 -0
  117. package/build/src/utils/stream.utils.js +218 -0
  118. package/build/src/utils/stream.utils.js.map +1 -0
  119. package/build/src/utils/type.utils.d.ts +90 -0
  120. package/build/src/utils/type.utils.js +196 -0
  121. package/build/src/utils/type.utils.js.map +1 -0
  122. package/package.json +6 -2
@@ -1 +1 @@
1
- {"version":3,"file":"middleware.utils.js","sourceRoot":"","sources":["../../../src/utils/middleware.utils.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;;AAuBH,8BAwBC;AAUD,oCA8BC;AASD,0BAeC;AAUD,kDAwBC;AAmCD,oCAmCC;AArND,yCAAkC;AAClC,2DAAsD;AACtD,qDAA2E;AAC3E,iDAA2C;AAE3C,+DAAgE;AAChE,uDAA4D;AAK5D;;;;;;;;;GASG;AACH,SAAgB,SAAS,CAAC,OAIzB;IACC,MAAM,UAAU,GAAG,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,UAAU,KAAI,cAAc,CAAC;IACzD,MAAM,YAAY,GAAG,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,YAAY,MAAK,KAAK,CAAC;IACrD,MAAM,UAAU,GAAG,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,SAAS,KAAI,eAAI,CAAC;IAE9C,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QACxB,4DAA4D;QAC5D,MAAM,UAAU,GAAG,GAAG,CAAC,OAAO,CAAC,UAAU,CAAC,WAAW,EAAE,CAAC,CAAC;QACzD,MAAM,EAAE,GAAI,UAAqB,IAAI,UAAU,EAAE,CAAC;QAElD,8BAA8B;QAC9B,GAAG,CAAC,EAAE,GAAG,EAAE,CAAC;QAEZ,6BAA6B;QAC7B,IAAI,YAAY,EAAE,CAAC;YACjB,GAAG,CAAC,SAAS,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC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EAAE,CAAA,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,SAAS,MAAI,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,EAAE,CAAA,IAAI,IAAA,eAAI,GAAE;gBAC9C,MAAM;gBACN,IAAI,EAAE,GAAG,CAAC,WAAW,IAAI,GAAG,CAAC,GAAG;aACjC,CAAC;YAEF,IAAI,cAAc,KAAI,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,KAAK,CAAA,EAAE,CAAC;gBACjC,MAAM,CAAC,KAAK,GAAG,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,IAAY,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;YAC1E,CAAC;YACD,OAAO,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACzC,CAAC;QAED,0BAA0B;QAC1B,OAAO,GAAG;aACP,MAAM,CAAC,MAAM,CAAC;aACd,IAAI,CAAC,IAAA,yCAAwB,EAAC,GAAG,EAAE,MAAM,EAAE,CAAA,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,OAAO,KAAI,uBAAuB,EAAE,GAAG,EAAE,EAAE,cAAc,EAAE,CAAC,CAAC,CAAC;IACnH,CAAC,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 { uuid } from './id.utils';\nimport { HttpStatusCodes } from './http-status-codes';\nimport { createFinalErrorResponse, ErrorResponse } from './response.utils';\nimport { getLogger } from './logger.utils';\nimport type { Request, Response, NextFunction } from 'express';\nimport { ContextStore, StoreKeys } from './context-store.utils';\nimport { RequestTimeoutException } from './exception.utils';\nimport { ApiErrorResponse } from '../types/api-response';\n\nexport type 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 * @param {() => string} [options.generator] - Custom ID generator function\n * @returns {Middleware} Express-compatible middleware\n */\nexport function requestId(options?: {\n headerName?: string;\n exposeHeader?: boolean;\n generator?: () => string;\n}): Middleware {\n const headerName = options?.headerName || 'X-Request-ID';\n const exposeHeader = options?.exposeHeader !== false;\n const generateId = options?.generator || uuid;\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) || generateId();\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 }) {\n const addHeader = options?.addHeader !== false;\n const logOnComplete = options?.logOnComplete === true;\n\n return (req: Request, res: Response, next: NextFunction) => {\n const start = process.hrtime();\n\n // Function to calculate duration\n const getDuration = () => {\n const diff = process.hrtime(start);\n return (diff[0] * 1e3 + diff[1] * 1e-6).toFixed(2);\n };\n\n if (addHeader) {\n // Ensure header is set before response is sent\n const originalWriteHead = res.writeHead;\n res.writeHead = function (...args: any[]) {\n res.setHeader('X-Response-Time', `${getDuration()}ms`);\n return originalWriteHead.apply(this, args as any);\n };\n }\n\n if (logOnComplete) {\n res.on('finish', () => {\n getLogger().info(`${req.method} ${req.url} - ${getDuration()}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 = 30000): Middleware {\n return (_req, res, next) => {\n // Set timeout for the request\n const timer = setTimeout(() => {\n const response = new RequestTimeoutException('Request timed out');\n res.status(HttpStatusCodes.REQUEST_TIMEOUT).json(response);\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 an Express middleware that initializes a per-request context.\n *\n * @param {object} [options] - Optional configuration\n * @param {string} [options.headerName='x-request-id'] - Header to look for request ID\n * @param {boolean} [options.autoLog=true] - Whether to log automatically when context is initialized\n * @returns {(req: Request, res: Response, next: NextFunction) => void} Express middleware function\n */\nexport function setupRequestContext(options: { headerName?: string; autoLog?: boolean } = {}): Middleware {\n const { headerName = 'x-request-id', autoLog = true } = options;\n return (req, _res, next) => {\n // Generate or use existing request ID\n const requestId = (req.headers[headerName] as string) || req?.['id'] || uuid();\n\n ContextStore.run({ [StoreKeys.REQUEST_ID]: requestId }, () => {\n // Create a child logger for this request\n const childLogger = getLogger().child({\n requestId,\n method: req.method,\n url: req.originalUrl || req.url\n });\n\n // Store logger in context\n ContextStore.set(StoreKeys.LOGGER, childLogger);\n\n if (autoLog) {\n childLogger.info('Request context initialized');\n }\n\n next();\n });\n };\n}\n\nexport interface ErrorHandlerOptions {\n /** Whether to log errors (default: true) */\n logErrors?: boolean;\n /** Whether to include error details in non-production (default: false) */\n includeDetails?: boolean;\n}\n\n/**\n * Global error handling middleware with enhanced features.\n *\n * @param {ErrorHandlerOptions} 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 * @returns Error middleware\n *\n * @example\n * import express from 'express';\n * import { errorHandler } from '@catbee/utils';\n *\n * const app = express();\n *\n * // Your routes\n * app.get('/ping', (req, res) => {\n * throw new Error('Something went wrong');\n * });\n *\n * // Error handler (must be last middleware)\n * app.use(errorHandler({ includeDetails: true }));\n *\n * app.listen(3000, () => {\n * console.log('Server running on port 3000');\n * });\n */\nexport function errorHandler(options?: ErrorHandlerOptions) {\n const logErrors = options?.logErrors !== false;\n const includeDetails = options?.includeDetails === true;\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 getLogger().error({ err }, `${err.message || 'Unknown error'}`);\n }\n\n // Handle ErrorResponse instances (our custom error class)\n if (err instanceof ErrorResponse) {\n const result: ApiErrorResponse = {\n error: true,\n message: err.message,\n timestamp: err.timestamp,\n requestId: err?.requestId || req?.id || uuid(),\n status,\n path: req.originalUrl || req.url\n };\n\n if (includeDetails && err?.stack) {\n result.stack = err.stack.split('\\n').map((line: string) => line.trim());\n }\n return res.status(status).json(result);\n }\n\n // Handle any other errors\n return res\n .status(status)\n .json(createFinalErrorResponse(req, status, err?.message || 'Internal Server Error', err, { includeDetails }));\n };\n}\n"]}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I,GAAG,CAAC,GAAG;aACjC,CAAC;YAEF,IAAI,cAAc,KAAI,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,KAAK,CAAA,EAAE,CAAC;gBACjC,MAAM,CAAC,KAAK,GAAG,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,IAAY,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;YAC1E,CAAC;YACD,OAAO,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACzC,CAAC;QAED,0BAA0B;QAC1B,OAAO,GAAG;aACP,MAAM,CAAC,MAAM,CAAC;aACd,IAAI,CAAC,IAAA,yCAAwB,EAAC,GAAG,EAAE,MAAM,EAAE,CAAA,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,OAAO,KAAI,uBAAuB,EAAE,GAAG,EAAE,EAAE,cAAc,EAAE,CAAC,CAAC,CAAC;IACnH,CAAC,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 { uuid } from './id.utils';\nimport { HttpStatusCodes } from './http-status-codes';\nimport { createFinalErrorResponse, ErrorResponse } from './response.utils';\nimport { getLogger } from './logger.utils';\nimport type { Request, Response, NextFunction } from 'express';\nimport { ContextStore, StoreKeys } from './context-store.utils';\nimport { RequestTimeoutException } from './exception.utils';\nimport { ApiErrorResponse } from '../types/api-response';\n\nexport type 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 * @param {() => string} [options.generator] - Custom ID generator function\n * @returns {Middleware} Express-compatible middleware\n */\nexport function requestId(options?: {\n headerName?: string;\n exposeHeader?: boolean;\n generator?: () => string;\n}): Middleware {\n const headerName = options?.headerName || 'X-Request-ID';\n const exposeHeader = options?.exposeHeader !== false;\n const generateId = options?.generator || uuid;\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) || generateId();\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 }) {\n const addHeader = options?.addHeader !== false;\n const logOnComplete = options?.logOnComplete === true;\n\n return (req: Request, res: Response, next: NextFunction) => {\n const start = process.hrtime();\n\n // Function to calculate duration\n const getDuration = () => {\n const diff = process.hrtime(start);\n return (diff[0] * 1e3 + diff[1] * 1e-6).toFixed(2);\n };\n\n if (addHeader) {\n // Ensure header is set before response is sent\n const originalWriteHead = res.writeHead;\n res.writeHead = function (...args: any[]) {\n res.setHeader('X-Response-Time', `${getDuration()}ms`);\n return originalWriteHead.apply(this, args as any);\n };\n }\n\n if (logOnComplete) {\n res.on('finish', () => {\n getLogger().info(`${req.method} ${req.url} - ${getDuration()}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 = 30000): Middleware {\n return (_req, res, next) => {\n // Set timeout for the request\n const timer = setTimeout(() => {\n const response = new RequestTimeoutException('Request timed out');\n res.status(HttpStatusCodes.REQUEST_TIMEOUT).json(response);\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 an Express middleware that initializes a per-request context.\n *\n * @param {object} [options] - Optional configuration\n * @param {string} [options.headerName='x-request-id'] - Header to look for request ID\n * @param {boolean} [options.autoLog=true] - Whether to log automatically when context is initialized\n * @returns {(req: Request, res: Response, next: NextFunction) => void} Express middleware function\n */\nexport function setupRequestContext(options: { headerName?: string; autoLog?: boolean } = {}): Middleware {\n const { headerName = 'x-request-id', autoLog = true } = options;\n return (req, _res, next) => {\n // Generate or use existing request ID\n const requestId = (req.headers[headerName] as string) || req?.['id'] || uuid();\n\n ContextStore.run({ [StoreKeys.REQUEST_ID]: requestId }, () => {\n // Create a child logger for this request\n const childLogger = getLogger().child({\n requestId,\n method: req.method,\n url: req.originalUrl || req.url\n });\n\n req.logger = childLogger;\n\n // Store logger in context\n ContextStore.set(StoreKeys.LOGGER, childLogger);\n\n if (autoLog) {\n req.logger.info('Request context initialized');\n }\n\n next();\n });\n };\n}\n\nexport interface ErrorHandlerOptions {\n /** Whether to log errors (default: true) */\n logErrors?: boolean;\n /** Whether to include error details in non-production (default: false) */\n includeDetails?: boolean;\n}\n\n/**\n * Global error handling middleware with enhanced features.\n *\n * @param {ErrorHandlerOptions} 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 * @returns Error middleware\n *\n * @example\n * import express from 'express';\n * import { errorHandler } from '@catbee/utils';\n *\n * const app = express();\n *\n * // Your routes\n * app.get('/ping', (req, res) => {\n * throw new Error('Something went wrong');\n * });\n *\n * // Error handler (must be last middleware)\n * app.use(errorHandler({ includeDetails: true }));\n *\n * app.listen(3000, () => {\n * console.log('Server running on port 3000');\n * });\n */\nexport function errorHandler(options?: ErrorHandlerOptions) {\n const logErrors = options?.logErrors !== false;\n const includeDetails = options?.includeDetails === true;\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 getLogger().error({ err }, `${err.message || 'Unknown error'}`);\n }\n\n // Handle ErrorResponse instances (our custom error class)\n if (err instanceof ErrorResponse) {\n const result: ApiErrorResponse = {\n error: true,\n message: err.message,\n timestamp: err.timestamp,\n requestId: err?.requestId || req?.id || uuid(),\n status,\n path: req.originalUrl || req.url\n };\n\n if (includeDetails && err?.stack) {\n result.stack = err.stack.split('\\n').map((line: string) => line.trim());\n }\n return res.status(status).json(result);\n }\n\n // Handle any other errors\n return res\n .status(status)\n .json(createFinalErrorResponse(req, status, err?.message || 'Internal Server Error', err, { includeDetails }));\n };\n}\n"]}
@@ -0,0 +1,136 @@
1
+ /**
2
+ * Options for timing function execution.
3
+ */
4
+ export interface TimingOptions {
5
+ /** Optional label for the timing (defaults to function name) */
6
+ label?: string;
7
+ /** Whether to log the timing (default: false) */
8
+ log?: boolean;
9
+ /** Log level to use if logging is enabled (default: 'debug') */
10
+ logLevel?: 'trace' | 'debug' | 'info' | 'warn' | 'error';
11
+ }
12
+ /**
13
+ * Result of a timing operation.
14
+ */
15
+ export interface TimingResult {
16
+ /** Duration in milliseconds */
17
+ durationMs: number;
18
+ /** Duration in seconds */
19
+ durationSec: number;
20
+ /** Start timestamp */
21
+ startTime: number;
22
+ /** End timestamp */
23
+ endTime: number;
24
+ /** Label used for the timing */
25
+ label: string;
26
+ }
27
+ /**
28
+ * Measure the execution time of a synchronous function.
29
+ *
30
+ * @param fn - Function to measure
31
+ * @param options - Timing options
32
+ * @returns Result containing the return value and timing information
33
+ *
34
+ * @example
35
+ * ```typescript
36
+ * const { result, timing } = timeSync(() => {
37
+ * // Some expensive operation
38
+ * return computeResult();
39
+ * }, { label: 'Computation', log: true });
40
+ *
41
+ * console.log(`Result: ${result}, took ${timing.durationMs}ms`);
42
+ * ```
43
+ */
44
+ export declare function timeSync<T>(fn: () => T, options?: TimingOptions): {
45
+ result: T;
46
+ timing: TimingResult;
47
+ };
48
+ /**
49
+ * Measure the execution time of an asynchronous function.
50
+ *
51
+ * @param fn - Async function to measure
52
+ * @param options - Timing options
53
+ * @returns Promise resolving to result and timing information
54
+ *
55
+ * @example
56
+ * ```typescript
57
+ * const { result, timing } = await timeAsync(async () => {
58
+ * // Some expensive async operation
59
+ * const data = await fetchData();
60
+ * return processData(data);
61
+ * }, { label: 'API Request', log: true });
62
+ *
63
+ * console.log(`Fetched ${result.length} items in ${timing.durationSec.toFixed(2)}s`);
64
+ * ```
65
+ */
66
+ export declare function timeAsync<T>(fn: () => Promise<T>, options?: TimingOptions): Promise<{
67
+ result: T;
68
+ timing: TimingResult;
69
+ }>;
70
+ /**
71
+ * Create a timing decorator for class methods.
72
+ *
73
+ * @param options - Timing options
74
+ * @returns Method decorator
75
+ *
76
+ * @example
77
+ * ```typescript
78
+ * class DataService {
79
+ * @timed({ log: true, logLevel: 'info' })
80
+ * async fetchData() {
81
+ * // ...implementation
82
+ * }
83
+ * }
84
+ * ```
85
+ */
86
+ export declare function timed(options?: TimingOptions): (target: any, propertyKeyOrContext: string | symbol | any, descriptor?: PropertyDescriptor) => void;
87
+ /**
88
+ * Memoize function results with optional TTL and max cache size.
89
+ *
90
+ * @param fn - Function to memoize
91
+ * @param options - Memoization options
92
+ * @returns Memoized function
93
+ *
94
+ * @example
95
+ * ```typescript
96
+ * // Cache results for 30 seconds, with a maximum of 100 entries
97
+ * const cachedFetch = memoize(
98
+ * async (url) => {
99
+ * const response = await fetch(url);
100
+ * return response.json();
101
+ * },
102
+ * { ttl: 30000, maxSize: 100, cacheKey: (url) => url }
103
+ * );
104
+ * ```
105
+ */
106
+ export declare function memoize<T, Args extends any[]>(fn: (...args: Args) => T, options?: {
107
+ /** Time-to-live in milliseconds (default: indefinite) */
108
+ ttl?: number;
109
+ /** Maximum cache size (default: unlimited) */
110
+ maxSize?: number;
111
+ /** Function to generate a cache key from arguments */
112
+ cacheKey?: (...args: Args) => string;
113
+ /** Auto-cleanup interval in milliseconds (default: disabled) */
114
+ autoCleanupMs?: number;
115
+ }): (...args: Args) => T;
116
+ /**
117
+ * Track memory usage for a function execution.
118
+ *
119
+ * @param fn - Function to track
120
+ * @param options - Memory tracking options
121
+ * @returns Result and memory usage information
122
+ */
123
+ export declare function trackMemoryUsage<T>(fn: () => T, options?: {
124
+ /** Whether to log the memory usage (default: false) */
125
+ log?: boolean;
126
+ /** Label for the memory tracking (default: function name) */
127
+ label?: string;
128
+ }): {
129
+ result: T;
130
+ memoryUsage: {
131
+ before: NodeJS.MemoryUsage;
132
+ after: NodeJS.MemoryUsage;
133
+ diff: Record<string, number>;
134
+ };
135
+ };
136
+ //# sourceMappingURL=performance.utils.d.ts.map
@@ -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,IAAI,IAAI,oBAAoB,EAAE,GAAG,GAAG,KAAK,EAAE,QAAQ,GAAG,OAAO,EAAE,GAAG,OAAO,CAAC;IAE7F,MAAM,SAAS,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC;IACpC,MAAM,MAAM,GAAG,EAAE,EAAE,CAAC;IACpB,MAAM,OAAO,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC;IAElC,MAAM,UAAU,GAAG,OAAO,GAAG,SAAS,CAAC;IACvC,MAAM,WAAW,GAAG,UAAU,GAAG,IAAI,CAAC;IAEtC,MAAM,MAAM,GAAiB;QAC3B,UAAU;QACV,WAAW;QACX,SAAS;QACT,OAAO;QACP,KAAK;KACN,CAAC;IAEF,IAAI,GAAG,EAAE,CAAC;QACR,MAAM,MAAM,GAAG,IAAA,wBAAS,GAAE,CAAC;QAC3B,MAAM,OAAO,GAAG,GAAG,KAAK,iBAAiB,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC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AG,OAAO,CAAC,WAAW,EAAE,CAAC;IAC3C,MAAM,MAAM,GAAG,EAAE,EAAE,CAAC;IACpB,MAAM,WAAW,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC;IAE1C,wBAAwB;IACxB,MAAM,IAAI,GAA2B,EAAE,CAAC;IACxC,KAAK,MAAM,GAAG,IAAI,WAAW,EAAE,CAAC;QAC9B,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,WAAW,EAAE,GAAG,CAAC,EAAE,CAAC;YAC3D,IAAI,CAAC,GAAG,CAAC,GAAI,WAAmB,CAAC,GAAG,CAAC,GAAI,YAAoB,CAAC,GAAG,CAAC,CAAC;QACrE,CAAC;IACH,CAAC;IAED,IAAI,GAAG,EAAE,CAAC;QACR,IAAA,wBAAS,GAAE,CAAC,IAAI,CACd;YACE,KAAK;YACL,YAAY,EAAE,YAAY;YAC1B,WAAW,EAAE,WAAW;YACxB,UAAU,EAAE,IAAI;SACjB,EACD,oBAAoB,KAAK,EAAE,CAC5B,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
  *
@@ -23,11 +23,31 @@
23
23
  * SOFTWARE.
24
24
  */
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.getPaginationParams = void 0;
26
27
  exports.parseNumberParam = parseNumberParam;
27
28
  exports.parseBooleanParam = parseBooleanParam;
28
29
  exports.extractPaginationParams = extractPaginationParams;
29
30
  exports.extractSortParams = extractSortParams;
30
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;
31
51
  /**
32
52
  * Safely parses a string parameter to a number.
33
53
  *
@@ -42,7 +62,7 @@ function parseNumberParam(value, options = {}) {
42
62
  if (required) {
43
63
  const error = `Required number parameter is missing`;
44
64
  if (throwOnError)
45
- throw new Error(error);
65
+ throw new exception_utils_1.BadRequestException(error);
46
66
  return { isValid: false, value: null, error };
47
67
  }
48
68
  return {
@@ -55,7 +75,7 @@ function parseNumberParam(value, options = {}) {
55
75
  const num = Number(value);
56
76
  if (isNaN(num)) {
57
77
  if (throwOnError)
58
- throw new Error(errorMessage);
78
+ throw new exception_utils_1.BadRequestException(errorMessage);
59
79
  return { isValid: false, value: null, error: errorMessage };
60
80
  }
61
81
  return { isValid: true, value: num };
@@ -74,7 +94,7 @@ function parseBooleanParam(value, options = {}) {
74
94
  if (required) {
75
95
  const error = `Required boolean parameter is missing`;
76
96
  if (throwOnError)
77
- throw new Error(error);
97
+ throw new exception_utils_1.BadRequestException(error);
78
98
  return { isValid: false, value: null, error };
79
99
  }
80
100
  return {
@@ -92,7 +112,7 @@ function parseBooleanParam(value, options = {}) {
92
112
  return { isValid: true, value: false };
93
113
  }
94
114
  if (throwOnError)
95
- throw new Error(errorMessage);
115
+ throw new exception_utils_1.BadRequestException(errorMessage);
96
116
  return { isValid: false, value: null, error: errorMessage };
97
117
  }
98
118
  /**
@@ -150,7 +170,7 @@ function extractSortParams(query, allowedFields, defaultSort = { sortBy: 'create
150
170
  }
151
171
  }
152
172
  // Validate field
153
- if (!allowedFields.includes(sortBy)) {
173
+ if (allowedFields.length && !allowedFields.includes(sortBy)) {
154
174
  sortBy = defaultSort.sortBy;
155
175
  }
156
176
  return { sortBy, sortOrder };