@catbee/utils 0.0.8-rc.3 → 1.0.1

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 (129) hide show
  1. package/README.md +3 -2
  2. package/build/index.cjs +6912 -0
  3. package/build/index.d.ts +5284 -0
  4. package/build/index.mjs +6635 -0
  5. package/package.json +13 -292
  6. package/build/cjs/config.d.ts +0 -121
  7. package/build/cjs/config.js +0 -137
  8. package/build/cjs/index.d.ts +0 -26
  9. package/build/cjs/index.js +0 -68
  10. package/build/cjs/servers/server.builder.d.ts +0 -507
  11. package/build/cjs/servers/server.builder.js +0 -658
  12. package/build/cjs/servers/server.d.ts +0 -255
  13. package/build/cjs/servers/server.js +0 -970
  14. package/build/cjs/types/api-response.d.ts +0 -151
  15. package/build/cjs/types/api-response.js +0 -36
  16. package/build/cjs/types/index.d.ts +0 -124
  17. package/build/cjs/types/index.js +0 -25
  18. package/build/cjs/types/server.d.ts +0 -267
  19. package/build/cjs/types/server.js +0 -25
  20. package/build/cjs/utils/array.utils.d.ts +0 -167
  21. package/build/cjs/utils/array.utils.js +0 -363
  22. package/build/cjs/utils/async.utils.d.ts +0 -264
  23. package/build/cjs/utils/async.utils.js +0 -640
  24. package/build/cjs/utils/cache.utils.d.ts +0 -152
  25. package/build/cjs/utils/cache.utils.js +0 -298
  26. package/build/cjs/utils/context-store.utils.d.ts +0 -188
  27. package/build/cjs/utils/context-store.utils.js +0 -297
  28. package/build/cjs/utils/crypto.utils.d.ts +0 -159
  29. package/build/cjs/utils/crypto.utils.js +0 -295
  30. package/build/cjs/utils/date.utils.d.ts +0 -158
  31. package/build/cjs/utils/date.utils.js +0 -395
  32. package/build/cjs/utils/decorators.utils.d.ts +0 -511
  33. package/build/cjs/utils/decorators.utils.js +0 -1035
  34. package/build/cjs/utils/dir.utils.d.ts +0 -195
  35. package/build/cjs/utils/dir.utils.js +0 -500
  36. package/build/cjs/utils/env.utils.d.ts +0 -376
  37. package/build/cjs/utils/env.utils.js +0 -786
  38. package/build/cjs/utils/exception.utils.d.ts +0 -229
  39. package/build/cjs/utils/exception.utils.js +0 -408
  40. package/build/cjs/utils/fs.utils.d.ts +0 -163
  41. package/build/cjs/utils/fs.utils.js +0 -371
  42. package/build/cjs/utils/http-status-codes.d.ts +0 -265
  43. package/build/cjs/utils/http-status-codes.js +0 -297
  44. package/build/cjs/utils/id.utils.d.ts +0 -35
  45. package/build/cjs/utils/id.utils.js +0 -90
  46. package/build/cjs/utils/logger.utils.d.ts +0 -159
  47. package/build/cjs/utils/logger.utils.js +0 -350
  48. package/build/cjs/utils/middleware.utils.d.ts +0 -99
  49. package/build/cjs/utils/middleware.utils.js +0 -243
  50. package/build/cjs/utils/obj.utils.d.ts +0 -123
  51. package/build/cjs/utils/obj.utils.js +0 -428
  52. package/build/cjs/utils/performance.utils.d.ts +0 -135
  53. package/build/cjs/utils/performance.utils.js +0 -280
  54. package/build/cjs/utils/request.utils.d.ts +0 -85
  55. package/build/cjs/utils/request.utils.js +0 -199
  56. package/build/cjs/utils/response.utils.d.ts +0 -162
  57. package/build/cjs/utils/response.utils.js +0 -274
  58. package/build/cjs/utils/stream.utils.d.ts +0 -87
  59. package/build/cjs/utils/stream.utils.js +0 -217
  60. package/build/cjs/utils/string.utils.d.ts +0 -92
  61. package/build/cjs/utils/string.utils.js +0 -178
  62. package/build/cjs/utils/type.utils.d.ts +0 -89
  63. package/build/cjs/utils/type.utils.js +0 -195
  64. package/build/cjs/utils/url.utils.d.ts +0 -140
  65. package/build/cjs/utils/url.utils.js +0 -316
  66. package/build/cjs/utils/validate.utils.d.ts +0 -176
  67. package/build/cjs/utils/validate.utils.js +0 -344
  68. package/build/esm/config.d.ts +0 -121
  69. package/build/esm/config.js +0 -132
  70. package/build/esm/index.d.ts +0 -26
  71. package/build/esm/index.js +0 -49
  72. package/build/esm/servers/server.builder.d.ts +0 -507
  73. package/build/esm/servers/server.builder.js +0 -654
  74. package/build/esm/servers/server.d.ts +0 -255
  75. package/build/esm/servers/server.js +0 -963
  76. package/build/esm/types/api-response.d.ts +0 -151
  77. package/build/esm/types/api-response.js +0 -33
  78. package/build/esm/types/index.d.ts +0 -124
  79. package/build/esm/types/index.js +0 -24
  80. package/build/esm/types/server.d.ts +0 -267
  81. package/build/esm/types/server.js +0 -24
  82. package/build/esm/utils/array.utils.d.ts +0 -167
  83. package/build/esm/utils/array.utils.js +0 -344
  84. package/build/esm/utils/async.utils.d.ts +0 -264
  85. package/build/esm/utils/async.utils.js +0 -619
  86. package/build/esm/utils/cache.utils.d.ts +0 -152
  87. package/build/esm/utils/cache.utils.js +0 -294
  88. package/build/esm/utils/context-store.utils.d.ts +0 -188
  89. package/build/esm/utils/context-store.utils.js +0 -290
  90. package/build/esm/utils/crypto.utils.d.ts +0 -159
  91. package/build/esm/utils/crypto.utils.js +0 -278
  92. package/build/esm/utils/date.utils.d.ts +0 -158
  93. package/build/esm/utils/date.utils.js +0 -383
  94. package/build/esm/utils/decorators.utils.d.ts +0 -511
  95. package/build/esm/utils/decorators.utils.js +0 -1013
  96. package/build/esm/utils/dir.utils.d.ts +0 -195
  97. package/build/esm/utils/dir.utils.js +0 -476
  98. package/build/esm/utils/env.utils.d.ts +0 -376
  99. package/build/esm/utils/env.utils.js +0 -782
  100. package/build/esm/utils/exception.utils.d.ts +0 -229
  101. package/build/esm/utils/exception.utils.js +0 -382
  102. package/build/esm/utils/fs.utils.d.ts +0 -163
  103. package/build/esm/utils/fs.utils.js +0 -348
  104. package/build/esm/utils/http-status-codes.d.ts +0 -265
  105. package/build/esm/utils/http-status-codes.js +0 -294
  106. package/build/esm/utils/id.utils.d.ts +0 -35
  107. package/build/esm/utils/id.utils.js +0 -83
  108. package/build/esm/utils/logger.utils.d.ts +0 -159
  109. package/build/esm/utils/logger.utils.js +0 -304
  110. package/build/esm/utils/middleware.utils.d.ts +0 -99
  111. package/build/esm/utils/middleware.utils.js +0 -235
  112. package/build/esm/utils/obj.utils.d.ts +0 -123
  113. package/build/esm/utils/obj.utils.js +0 -412
  114. package/build/esm/utils/performance.utils.d.ts +0 -135
  115. package/build/esm/utils/performance.utils.js +0 -273
  116. package/build/esm/utils/request.utils.d.ts +0 -85
  117. package/build/esm/utils/request.utils.js +0 -190
  118. package/build/esm/utils/response.utils.d.ts +0 -162
  119. package/build/esm/utils/response.utils.js +0 -261
  120. package/build/esm/utils/stream.utils.d.ts +0 -87
  121. package/build/esm/utils/stream.utils.js +0 -209
  122. package/build/esm/utils/string.utils.d.ts +0 -92
  123. package/build/esm/utils/string.utils.js +0 -164
  124. package/build/esm/utils/type.utils.d.ts +0 -89
  125. package/build/esm/utils/type.utils.js +0 -186
  126. package/build/esm/utils/url.utils.d.ts +0 -140
  127. package/build/esm/utils/url.utils.js +0 -303
  128. package/build/esm/utils/validate.utils.d.ts +0 -176
  129. package/build/esm/utils/validate.utils.js +0 -319
@@ -1,159 +0,0 @@
1
- import pino from 'pino';
2
- import type { Logger as PinoLogger } from 'pino';
3
- /**
4
- * Logger type for application-wide logging.
5
- */
6
- export type Logger = pino.Logger;
7
- /**
8
- * Logger levels for application-wide logging.
9
- */
10
- export type LoggerLevels = pino.Level;
11
- export declare const defaultSensitiveFields: string[];
12
- /**
13
- * Sets the global redaction censor function used throughout the application for log redaction.
14
- *
15
- * Use this function to customize how sensitive data is redacted in logs. The provided function
16
- * will replace the default censor implementation.
17
- *
18
- * @example
19
- * ```typescript
20
- * // Custom censor that redacts only specific values
21
- * setRedactCensor((value, path, sensitiveFields) => {
22
- * if (path.includes('password')) return '***';
23
- * return value;
24
- * });
25
- * ```
26
- *
27
- * @param fn - The redaction censor function to use globally. This function receives:
28
- * - value: The data value to potentially redact
29
- * - path: Array of strings representing the path to the value in the object
30
- * - sensitiveFields: Optional array of field names to consider sensitive
31
- * @returns void
32
- */
33
- export declare function setRedactCensor(fn: (value: unknown, path: string[], sensitiveFields?: string[]) => string): void;
34
- /**
35
- * Gets the current global redaction censor function used for log redaction.
36
- *
37
- * This function is called internally by the logger when determining how to redact
38
- * sensitive information. It can also be used to access the current censor implementation
39
- * for composition or extension.
40
- *
41
- * @example
42
- * ```typescript
43
- * const currentCensor = getRedactCensor();
44
- * // Create an enhanced censor that extends the current one
45
- * setRedactCensor((value, path, fields) => {
46
- * // Add custom logic before delegating to current censor
47
- * if (someCondition) return customHandling();
48
- * return currentCensor(value, path, fields);
49
- * });
50
- * ```
51
- *
52
- * @returns The current redaction censor function
53
- */
54
- export declare function getRedactCensor(): (value: unknown, path: string[], sensitiveFields?: string[]) => string;
55
- /**
56
- * Convenience function to redact sensitive data using the current global redact censor.
57
- *
58
- * This is a direct wrapper around the global censor function that simplifies usage
59
- * in application code without needing to access the censor function directly.
60
- *
61
- * @example
62
- * ```typescript
63
- * // Redact a potential sensitive value
64
- * const safeValue = redact(value, ['user', 'apiKey']);
65
- * ```
66
- *
67
- * @param value - The value to potentially redact
68
- * @param path - Array of strings representing the path to the value in the object
69
- * @param sensitiveFields - Optional array of field names to consider sensitive
70
- * @returns The redacted string value or "***" for redacted content
71
- */
72
- export declare function redact(value: unknown, path: string[], sensitiveFields?: string[]): string;
73
- /**
74
- * Extends the current redaction function with additional fields to redact.
75
- *
76
- * This function wraps the existing censor while adding more fields to be considered
77
- * sensitive without replacing the entire redaction logic.
78
- *
79
- * @example
80
- * ```typescript
81
- * // Add custom fields to be redacted in all future redaction operations
82
- * addRedactFields(['customerId', 'accountNumber']);
83
- * ```
84
- *
85
- * @param fields - Array of additional field names to redact
86
- */
87
- export declare function addRedactFields(fields: string[]): void;
88
- /**
89
- * Replaces the default list of sensitive fields with a new list.
90
- *
91
- * This is useful when you want complete control over what fields are considered
92
- * sensitive by default, rather than using the library's built-in list.
93
- *
94
- * @example
95
- * ```typescript
96
- * // Replace default sensitive fields with a custom list
97
- * setSensitiveFields(['password', 'ssn', 'creditCard']);
98
- * ```
99
- *
100
- * @param fields - Array of field names to set as the new default sensitive fields
101
- */
102
- export declare function setSensitiveFields(fields: string[]): void;
103
- /**
104
- * Adds additional field names to the default sensitive fields list.
105
- *
106
- * This preserves the existing sensitive fields while adding new ones for
107
- * application-specific sensitive data.
108
- *
109
- * @example
110
- * ```typescript
111
- * // Add domain-specific sensitive fields to the default list
112
- * addSensitiveFields(['socialSecurityNumber', 'medicalRecordNumber']);
113
- * ```
114
- *
115
- * @param fields - Array of additional field names to add to the sensitive fields list
116
- */
117
- export declare function addSensitiveFields(fields: string[]): void;
118
- /**
119
- * Use an object compatible with either modern or legacy global scopes.
120
- */
121
- export declare const _globalThis: typeof globalThis;
122
- /**
123
- * Retrieves the current logger instance:
124
- * - Returns a request-scoped logger from AsyncLocalStorage if available
125
- * - Falls back to the global (singleton) logger
126
- * - Initializes the global logger if not created yet
127
- *
128
- * @returns {Logger} The logger instance (request-bound or global root logger)
129
- */
130
- export declare function getLogger(): PinoLogger;
131
- /**
132
- * Logger instance for the global context.
133
- * This logger is used for logging messages that are not tied to a specific request.
134
- */
135
- export declare const logger: pino.Logger;
136
- /**
137
- * Creates a child logger with additional context.
138
- *
139
- * @param {Record<string, any>} bindings - Properties to attach to all log records
140
- * @param {Logger} [parentLogger] - Parent logger (defaults to current context logger or global)
141
- * @returns {Logger} Child logger with merged context
142
- */
143
- export declare function createChildLogger(bindings: Record<string, any>, parentLogger?: PinoLogger): PinoLogger;
144
- /**
145
- * Creates a request-scoped logger with request ID and stores it in context
146
- *
147
- * @param {string} requestId - Unique request identifier
148
- * @param {object} [additionalContext] - Additional context to include in logs
149
- * @returns {Logger} Request-scoped logger instance
150
- */
151
- export declare function createRequestLogger(requestId: string, additionalContext?: Record<string, any>): PinoLogger;
152
- /**
153
- * Utility to safely log errors with proper stack trace extraction
154
- *
155
- * @param {Error|unknown} error - Error object to log
156
- * @param {string} [message] - Optional message to include
157
- * @param {Record<string, any>} [context] - Additional context properties
158
- */
159
- export declare function logError(error: Error | unknown, message?: string, context?: Record<string, any>): void;
@@ -1,304 +0,0 @@
1
- /*
2
- * The MIT License
3
- *
4
- * Copyright (c) 2025 Catbee Technologies. https://catbee-utils.npm.hprasath.com/license
5
- *
6
- * Permission is hereby granted, free of charge, to any person obtaining a copy
7
- * of this software and associated documentation files (the "Software"), to deal
8
- * in the Software without restriction, including without limitation the rights
9
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
- * copies of the Software, and to permit persons to whom the Software is
11
- * furnished to do so, subject to the following conditions:
12
- *
13
- * The above copyright notice and this permission notice shall be included in all
14
- * copies or substantial portions of the Software.
15
- *
16
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
- * SOFTWARE.
23
- */
24
- import pino, { stdTimeFunctions } from 'pino';
25
- import { config } from '../config';
26
- import { ContextStore, StoreKeys } from './context-store.utils';
27
- import { Env } from './env.utils';
28
- /**
29
- * Symbol used to store the root logger in the Node.js global object.
30
- */
31
- const GLOBAL_LOGGER_KEY = Symbol.for('logger');
32
- // Default sensitive fields
33
- export const defaultSensitiveFields = [
34
- 'password',
35
- 'secret',
36
- 'token',
37
- 'apiKey',
38
- 'api_key',
39
- 'auth',
40
- 'jwt',
41
- 'access_token',
42
- 'client_secret',
43
- 'session_token',
44
- 'refresh_token'
45
- ];
46
- /**
47
- * The global censor function used by the logger.
48
- */
49
- let globalRedactCensor = (value, path, sensitiveFields = defaultSensitiveFields) => {
50
- if (typeof value !== 'string')
51
- return '***';
52
- const lowerPath = path.map(p => p.toLowerCase());
53
- const lowerSensitiveFields = sensitiveFields.map(f => f.toLowerCase());
54
- if (lowerPath.some(p => lowerSensitiveFields.includes(p)))
55
- return '***';
56
- // Redact URLs
57
- if (lowerPath[0] === 'url') {
58
- return value.replace(new RegExp(`([?&](${lowerSensitiveFields.join('|')})=)[^&#]*`, 'gi'), '$1***');
59
- }
60
- if (lowerPath.some(p => p.includes('authorization') || p.includes('auth'))) {
61
- return value.replace(/^(\S+)\s+.+$/, '$1 ***') || '***';
62
- }
63
- // Redact sensitive fields - check each path segment against each sensitive field
64
- if (lowerPath.some(pathPart => lowerSensitiveFields.some(field => pathPart.includes(field)))) {
65
- return '***';
66
- }
67
- if (path.length > 0 && !['req', 'res', 'headers'].includes(lowerPath[0])) {
68
- return value;
69
- }
70
- return value;
71
- };
72
- /**
73
- * Sets the global redaction censor function used throughout the application for log redaction.
74
- *
75
- * Use this function to customize how sensitive data is redacted in logs. The provided function
76
- * will replace the default censor implementation.
77
- *
78
- * @example
79
- * ```typescript
80
- * // Custom censor that redacts only specific values
81
- * setRedactCensor((value, path, sensitiveFields) => {
82
- * if (path.includes('password')) return '***';
83
- * return value;
84
- * });
85
- * ```
86
- *
87
- * @param fn - The redaction censor function to use globally. This function receives:
88
- * - value: The data value to potentially redact
89
- * - path: Array of strings representing the path to the value in the object
90
- * - sensitiveFields: Optional array of field names to consider sensitive
91
- * @returns void
92
- */
93
- export function setRedactCensor(fn) {
94
- globalRedactCensor = fn;
95
- }
96
- /**
97
- * Gets the current global redaction censor function used for log redaction.
98
- *
99
- * This function is called internally by the logger when determining how to redact
100
- * sensitive information. It can also be used to access the current censor implementation
101
- * for composition or extension.
102
- *
103
- * @example
104
- * ```typescript
105
- * const currentCensor = getRedactCensor();
106
- * // Create an enhanced censor that extends the current one
107
- * setRedactCensor((value, path, fields) => {
108
- * // Add custom logic before delegating to current censor
109
- * if (someCondition) return customHandling();
110
- * return currentCensor(value, path, fields);
111
- * });
112
- * ```
113
- *
114
- * @returns The current redaction censor function
115
- */
116
- export function getRedactCensor() {
117
- return globalRedactCensor;
118
- }
119
- /**
120
- * Convenience function to redact sensitive data using the current global redact censor.
121
- *
122
- * This is a direct wrapper around the global censor function that simplifies usage
123
- * in application code without needing to access the censor function directly.
124
- *
125
- * @example
126
- * ```typescript
127
- * // Redact a potential sensitive value
128
- * const safeValue = redact(value, ['user', 'apiKey']);
129
- * ```
130
- *
131
- * @param value - The value to potentially redact
132
- * @param path - Array of strings representing the path to the value in the object
133
- * @param sensitiveFields - Optional array of field names to consider sensitive
134
- * @returns The redacted string value or "***" for redacted content
135
- */
136
- export function redact(value, path, sensitiveFields) {
137
- return globalRedactCensor(value, path, sensitiveFields);
138
- }
139
- /**
140
- * Extends the current redaction function with additional fields to redact.
141
- *
142
- * This function wraps the existing censor while adding more fields to be considered
143
- * sensitive without replacing the entire redaction logic.
144
- *
145
- * @example
146
- * ```typescript
147
- * // Add custom fields to be redacted in all future redaction operations
148
- * addRedactFields(['customerId', 'accountNumber']);
149
- * ```
150
- *
151
- * @param fields - Array of additional field names to redact
152
- */
153
- export function addRedactFields(fields) {
154
- const prev = globalRedactCensor;
155
- globalRedactCensor = (value, path, sensitiveFields = defaultSensitiveFields) => prev(value, path, [...(sensitiveFields || []), ...fields]);
156
- }
157
- /**
158
- * Replaces the default list of sensitive fields with a new list.
159
- *
160
- * This is useful when you want complete control over what fields are considered
161
- * sensitive by default, rather than using the library's built-in list.
162
- *
163
- * @example
164
- * ```typescript
165
- * // Replace default sensitive fields with a custom list
166
- * setSensitiveFields(['password', 'ssn', 'creditCard']);
167
- * ```
168
- *
169
- * @param fields - Array of field names to set as the new default sensitive fields
170
- */
171
- export function setSensitiveFields(fields) {
172
- defaultSensitiveFields.splice(0, defaultSensitiveFields.length, ...fields);
173
- }
174
- /**
175
- * Adds additional field names to the default sensitive fields list.
176
- *
177
- * This preserves the existing sensitive fields while adding new ones for
178
- * application-specific sensitive data.
179
- *
180
- * @example
181
- * ```typescript
182
- * // Add domain-specific sensitive fields to the default list
183
- * addSensitiveFields(['socialSecurityNumber', 'medicalRecordNumber']);
184
- * ```
185
- *
186
- * @param fields - Array of additional field names to add to the sensitive fields list
187
- */
188
- export function addSensitiveFields(fields) {
189
- defaultSensitiveFields.push(...fields);
190
- }
191
- /**
192
- * Use an object compatible with either modern or legacy global scopes.
193
- */
194
- export const _globalThis = typeof globalThis === 'object' ? globalThis : global;
195
- const _global = _globalThis;
196
- /**
197
- * Initializes the global root logger according to app configuration.
198
- *
199
- * - Sets log name, level, timestamp, and redaction for sensitive fields.
200
- * - Uses singleton in global symbol registry.
201
- */
202
- function setupLogger() {
203
- const logParams = {
204
- name: config.logger.name || '@catbee/utils',
205
- level: config.logger.level || 'info',
206
- redact: {
207
- paths: ['req.authorization', 'res.authorization', 'url', 'headers.authorization', 'headers.cookies'],
208
- censor: (value, path) => redact(value, path)
209
- },
210
- // serializers: {
211
- // req: pino.stdSerializers.req,
212
- // request: pino.stdSerializers.req,
213
- // res: pino.stdSerializers.res,
214
- // response: pino.stdSerializers.res,
215
- // err: pino.stdSerializers.err,
216
- // error: pino.stdSerializers.err
217
- // },
218
- timestamp: stdTimeFunctions.isoTime
219
- };
220
- const logger = config.logger.pretty && Env.isDev()
221
- ? pino(logParams, pino.transport({
222
- target: 'pino-pretty',
223
- options: {
224
- colorize: true,
225
- translateTime: 'SYS:standard',
226
- ignore: 'pid,hostname',
227
- singleLine: config.logger.singleLine,
228
- levelFirst: true
229
- }
230
- }))
231
- : pino(logParams);
232
- _global[GLOBAL_LOGGER_KEY] = logger;
233
- _global[GLOBAL_LOGGER_KEY]?.debug('Logger initialized');
234
- }
235
- /**
236
- * Retrieves the current logger instance:
237
- * - Returns a request-scoped logger from AsyncLocalStorage if available
238
- * - Falls back to the global (singleton) logger
239
- * - Initializes the global logger if not created yet
240
- *
241
- * @returns {Logger} The logger instance (request-bound or global root logger)
242
- */
243
- export function getLogger() {
244
- const logger = ContextStore.get(StoreKeys.LOGGER);
245
- if (logger)
246
- return logger;
247
- if (!_global[GLOBAL_LOGGER_KEY]) {
248
- setupLogger();
249
- }
250
- return _global[GLOBAL_LOGGER_KEY];
251
- }
252
- /**
253
- * Logger instance for the global context.
254
- * This logger is used for logging messages that are not tied to a specific request.
255
- */
256
- export const logger = getLogger();
257
- /**
258
- * Creates a child logger with additional context.
259
- *
260
- * @param {Record<string, any>} bindings - Properties to attach to all log records
261
- * @param {Logger} [parentLogger] - Parent logger (defaults to current context logger or global)
262
- * @returns {Logger} Child logger with merged context
263
- */
264
- export function createChildLogger(bindings, parentLogger) {
265
- const logger = parentLogger || getLogger();
266
- return logger.child(bindings);
267
- }
268
- /**
269
- * Creates a request-scoped logger with request ID and stores it in context
270
- *
271
- * @param {string} requestId - Unique request identifier
272
- * @param {object} [additionalContext] - Additional context to include in logs
273
- * @returns {Logger} Request-scoped logger instance
274
- */
275
- export function createRequestLogger(requestId, additionalContext = {}) {
276
- const logger = createChildLogger({
277
- requestId,
278
- ...additionalContext
279
- });
280
- try {
281
- ContextStore.set(StoreKeys.LOGGER, logger);
282
- }
283
- catch {
284
- // Context not initialized, can't store logger
285
- logger.debug('Failed to store logger in context - AsyncLocalStorage not initialized');
286
- }
287
- return logger;
288
- }
289
- /**
290
- * Utility to safely log errors with proper stack trace extraction
291
- *
292
- * @param {Error|unknown} error - Error object to log
293
- * @param {string} [message] - Optional message to include
294
- * @param {Record<string, any>} [context] - Additional context properties
295
- */
296
- export function logError(error, message, context) {
297
- const logger = getLogger();
298
- const errObj = error instanceof Error ? error : new Error(String(error));
299
- const logContext = {
300
- ...context,
301
- error: errObj
302
- };
303
- logger.error(logContext, message || errObj.message);
304
- }
@@ -1,99 +0,0 @@
1
- import type { Request, Response, NextFunction } from 'express';
2
- export type Middleware = (req: Request, res: Response, next: NextFunction) => void | Promise<void>;
3
- /**
4
- * Attaches a unique request ID to each request.
5
- * Useful for request tracing and correlation between logs.
6
- *
7
- * @param {object} [options] - Configuration options
8
- * @param {string} [options.headerName='X-Request-ID'] - Header name for request ID
9
- * @param {boolean} [options.exposeHeader=true] - Whether to expose the header in response
10
- * @param {() => string} [options.generator] - Custom ID generator function
11
- * @returns {Middleware} Express-compatible middleware
12
- */
13
- export declare function requestId(options?: {
14
- headerName?: string;
15
- exposeHeader?: boolean;
16
- generator?: () => string;
17
- }): Middleware;
18
- /**
19
- * Measures request processing time and logs or adds it to response headers.
20
- *
21
- * @param {object} [options] - Configuration options
22
- * @param {boolean} [options.addHeader=true] - Whether to add X-Response-Time header
23
- * @param {boolean} [options.logOnComplete=false] - Whether to log timing info
24
- * @returns {Middleware} Express-compatible middleware
25
- */
26
- export declare function responseTime(options?: {
27
- addHeader?: boolean;
28
- logOnComplete?: boolean;
29
- }): (req: Request, res: Response, next: NextFunction) => void;
30
- /**
31
- * Request timeout middleware.
32
- * Aborts requests that take too long to process.
33
- *
34
- * @param {number} [timeoutMs=30000] - Timeout in milliseconds
35
- * @returns {Middleware} Express-compatible middleware
36
- */
37
- export declare function timeout(timeoutMs?: number): Middleware;
38
- /**
39
- * Creates an Express middleware that initializes a per-request context.
40
- *
41
- * @param {object} [options] - Optional configuration
42
- * @param {string} [options.headerName='x-request-id'] - Header to look for request ID
43
- * @param {boolean} [options.autoLog=true] - Whether to log automatically when context is initialized
44
- * @returns {(req: Request, res: Response, next: NextFunction) => void} Express middleware function
45
- */
46
- export declare function setupRequestContext(options?: {
47
- headerName?: string;
48
- autoLog?: boolean;
49
- }): Middleware;
50
- export interface ErrorHandlerOptions {
51
- /** Whether to log errors (default: true) */
52
- logErrors?: boolean;
53
- /** Whether to include error details in non-production (default: false) */
54
- includeDetails?: boolean;
55
- }
56
- /**
57
- * Global error handling middleware with enhanced features.
58
- *
59
- * @param {ErrorHandlerOptions} options - Error handler options
60
- * @param {boolean} [options.logErrors=true] - Whether to log errors
61
- * @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production
62
- * @returns Error middleware
63
- *
64
- * @example
65
- * import express from 'express';
66
- * import { errorHandler } from '@catbee/utils';
67
- *
68
- * const app = express();
69
- *
70
- * // Your routes
71
- * app.get('/ping', (req, res) => {
72
- * throw new Error('Something went wrong');
73
- * });
74
- *
75
- * // Error handler (must be last middleware)
76
- * app.use(errorHandler({ includeDetails: true }));
77
- *
78
- * app.listen(3000, () => {
79
- * console.log('Server running on port 3000');
80
- * });
81
- */
82
- export declare function errorHandler(options?: ErrorHandlerOptions): (err: any, req: Request, res: Response, _next: NextFunction) => Response<any, Record<string, any>>;
83
- /**
84
- * Health check middleware for service status and custom checks.
85
- *
86
- * @param {object} [options] - Health check options
87
- * @param {string} [options.path='/healthz'] - Health check endpoint path
88
- * @param {Array<{name: string; check: () => Promise<boolean> | boolean}>} [options.checks] - Custom health checks
89
- * @param {boolean} [options.detailed=true] - Show detailed check results
90
- * @returns {Middleware} Express-compatible middleware
91
- */
92
- export declare function healthCheck(options?: {
93
- path?: string;
94
- checks?: Array<{
95
- name: string;
96
- check: () => Promise<boolean> | boolean;
97
- }>;
98
- detailed?: boolean;
99
- }): Middleware;