@catbee/utils 0.0.8-next.0 → 0.0.8-rc.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.
- package/README.md +1 -2
- package/build/esm/config.d.ts +122 -0
- package/build/esm/config.js +133 -0
- package/build/esm/config.js.map +1 -0
- package/build/esm/index.d.ts +27 -0
- package/build/esm/index.js +50 -0
- package/build/esm/index.js.map +1 -0
- package/build/esm/servers/server.builder.d.ts +508 -0
- package/build/esm/servers/server.builder.js +702 -0
- package/build/esm/servers/server.builder.js.map +1 -0
- package/build/esm/servers/server.d.ts +256 -0
- package/build/esm/servers/server.js +1248 -0
- package/build/esm/servers/server.js.map +1 -0
- package/build/esm/types/api-response.d.ts +152 -0
- package/build/esm/types/api-response.js +34 -0
- package/build/esm/types/api-response.js.map +1 -0
- package/build/esm/types/index.d.ts +125 -0
- package/build/esm/types/index.js +25 -0
- package/build/esm/types/index.js.map +1 -0
- package/build/esm/types/server.d.ts +268 -0
- package/build/esm/types/server.js +25 -0
- package/build/esm/types/server.js.map +1 -0
- package/build/esm/utils/array.utils.d.ts +168 -0
- package/build/esm/utils/array.utils.js +382 -0
- package/build/esm/utils/array.utils.js.map +1 -0
- package/build/esm/utils/async.utils.d.ts +265 -0
- package/build/esm/utils/async.utils.js +896 -0
- package/build/esm/utils/async.utils.js.map +1 -0
- package/build/esm/utils/cache.utils.d.ts +153 -0
- package/build/esm/utils/cache.utils.js +499 -0
- package/build/esm/utils/cache.utils.js.map +1 -0
- package/build/esm/utils/context-store.utils.d.ts +189 -0
- package/build/esm/utils/context-store.utils.js +307 -0
- package/build/esm/utils/context-store.utils.js.map +1 -0
- package/build/esm/utils/crypto.utils.d.ts +160 -0
- package/build/esm/utils/crypto.utils.js +375 -0
- package/build/esm/utils/crypto.utils.js.map +1 -0
- package/build/esm/utils/date.utils.d.ts +159 -0
- package/build/esm/utils/date.utils.js +389 -0
- package/build/esm/utils/date.utils.js.map +1 -0
- package/build/esm/utils/decorators.utils.d.ts +508 -0
- package/build/esm/utils/decorators.utils.js +1057 -0
- package/build/esm/utils/decorators.utils.js.map +1 -0
- package/build/esm/utils/dir.utils.d.ts +196 -0
- package/build/esm/utils/dir.utils.js +998 -0
- package/build/esm/utils/dir.utils.js.map +1 -0
- package/build/esm/utils/env.utils.d.ts +377 -0
- package/build/esm/utils/env.utils.js +873 -0
- package/build/esm/utils/env.utils.js.map +1 -0
- package/build/esm/utils/exception.utils.d.ts +230 -0
- package/build/esm/utils/exception.utils.js +559 -0
- package/build/esm/utils/exception.utils.js.map +1 -0
- package/build/esm/utils/fs.utils.d.ts +164 -0
- package/build/esm/utils/fs.utils.js +580 -0
- package/build/esm/utils/fs.utils.js.map +1 -0
- package/build/esm/utils/http-status-codes.d.ts +266 -0
- package/build/esm/utils/http-status-codes.js +295 -0
- package/build/esm/utils/http-status-codes.js.map +1 -0
- package/build/esm/utils/id.utils.d.ts +36 -0
- package/build/esm/utils/id.utils.js +87 -0
- package/build/esm/utils/id.utils.js.map +1 -0
- package/build/esm/utils/logger.utils.d.ts +160 -0
- package/build/esm/utils/logger.utils.js +341 -0
- package/build/esm/utils/logger.utils.js.map +1 -0
- package/build/esm/utils/middleware.utils.d.ts +100 -0
- package/build/esm/utils/middleware.utils.js +325 -0
- package/build/esm/utils/middleware.utils.js.map +1 -0
- package/build/esm/utils/obj.utils.d.ts +124 -0
- package/build/esm/utils/obj.utils.js +519 -0
- package/build/esm/utils/obj.utils.js.map +1 -0
- package/build/esm/utils/performance.utils.d.ts +136 -0
- package/build/esm/utils/performance.utils.js +376 -0
- package/build/esm/utils/performance.utils.js.map +1 -0
- package/build/esm/utils/request.utils.d.ts +86 -0
- package/build/esm/utils/request.utils.js +223 -0
- package/build/esm/utils/request.utils.js.map +1 -0
- package/build/esm/utils/response.utils.d.ts +163 -0
- package/build/esm/utils/response.utils.js +284 -0
- package/build/esm/utils/response.utils.js.map +1 -0
- package/build/esm/utils/stream.utils.d.ts +88 -0
- package/build/esm/utils/stream.utils.js +284 -0
- package/build/esm/utils/stream.utils.js.map +1 -0
- package/build/esm/utils/string.utils.d.ts +93 -0
- package/build/esm/utils/string.utils.js +169 -0
- package/build/esm/utils/string.utils.js.map +1 -0
- package/build/esm/utils/type.utils.d.ts +90 -0
- package/build/esm/utils/type.utils.js +190 -0
- package/build/esm/utils/type.utils.js.map +1 -0
- package/build/esm/utils/url.utils.d.ts +141 -0
- package/build/esm/utils/url.utils.js +381 -0
- package/build/esm/utils/url.utils.js.map +1 -0
- package/build/esm/utils/validate.utils.d.ts +177 -0
- package/build/esm/utils/validate.utils.js +336 -0
- package/build/esm/utils/validate.utils.js.map +1 -0
- package/build/esnext/config.d.ts +122 -0
- package/build/esnext/config.js +133 -0
- package/build/esnext/config.js.map +1 -0
- package/build/esnext/index.d.ts +27 -0
- package/build/esnext/index.js +50 -0
- package/build/esnext/index.js.map +1 -0
- package/build/esnext/servers/server.builder.d.ts +508 -0
- package/build/esnext/servers/server.builder.js +657 -0
- package/build/esnext/servers/server.builder.js.map +1 -0
- package/build/esnext/servers/server.d.ts +256 -0
- package/build/esnext/servers/server.js +955 -0
- package/build/esnext/servers/server.js.map +1 -0
- package/build/esnext/types/api-response.d.ts +152 -0
- package/build/esnext/types/api-response.js +34 -0
- package/build/esnext/types/api-response.js.map +1 -0
- package/build/esnext/types/index.d.ts +125 -0
- package/build/esnext/types/index.js +25 -0
- package/build/esnext/types/index.js.map +1 -0
- package/build/esnext/types/server.d.ts +268 -0
- package/build/esnext/types/server.js +25 -0
- package/build/esnext/types/server.js.map +1 -0
- package/build/esnext/utils/array.utils.d.ts +168 -0
- package/build/esnext/utils/array.utils.js +345 -0
- package/build/esnext/utils/array.utils.js.map +1 -0
- package/build/esnext/utils/async.utils.d.ts +265 -0
- package/build/esnext/utils/async.utils.js +620 -0
- package/build/esnext/utils/async.utils.js.map +1 -0
- package/build/esnext/utils/cache.utils.d.ts +153 -0
- package/build/esnext/utils/cache.utils.js +293 -0
- package/build/esnext/utils/cache.utils.js.map +1 -0
- package/build/esnext/utils/context-store.utils.d.ts +189 -0
- package/build/esnext/utils/context-store.utils.js +289 -0
- package/build/esnext/utils/context-store.utils.js.map +1 -0
- package/build/esnext/utils/crypto.utils.d.ts +160 -0
- package/build/esnext/utils/crypto.utils.js +276 -0
- package/build/esnext/utils/crypto.utils.js.map +1 -0
- package/build/esnext/utils/date.utils.d.ts +159 -0
- package/build/esnext/utils/date.utils.js +384 -0
- package/build/esnext/utils/date.utils.js.map +1 -0
- package/build/esnext/utils/decorators.utils.d.ts +508 -0
- package/build/esnext/utils/decorators.utils.js +877 -0
- package/build/esnext/utils/decorators.utils.js.map +1 -0
- package/build/esnext/utils/dir.utils.d.ts +196 -0
- package/build/esnext/utils/dir.utils.js +477 -0
- package/build/esnext/utils/dir.utils.js.map +1 -0
- package/build/esnext/utils/env.utils.d.ts +377 -0
- package/build/esnext/utils/env.utils.js +785 -0
- package/build/esnext/utils/env.utils.js.map +1 -0
- package/build/esnext/utils/exception.utils.d.ts +230 -0
- package/build/esnext/utils/exception.utils.js +381 -0
- package/build/esnext/utils/exception.utils.js.map +1 -0
- package/build/esnext/utils/fs.utils.d.ts +164 -0
- package/build/esnext/utils/fs.utils.js +349 -0
- package/build/esnext/utils/fs.utils.js.map +1 -0
- package/build/esnext/utils/http-status-codes.d.ts +266 -0
- package/build/esnext/utils/http-status-codes.js +295 -0
- package/build/esnext/utils/http-status-codes.js.map +1 -0
- package/build/esnext/utils/id.utils.d.ts +36 -0
- package/build/esnext/utils/id.utils.js +84 -0
- package/build/esnext/utils/id.utils.js.map +1 -0
- package/build/esnext/utils/logger.utils.d.ts +160 -0
- package/build/esnext/utils/logger.utils.js +300 -0
- package/build/esnext/utils/logger.utils.js.map +1 -0
- package/build/esnext/utils/middleware.utils.d.ts +100 -0
- package/build/esnext/utils/middleware.utils.js +236 -0
- package/build/esnext/utils/middleware.utils.js.map +1 -0
- package/build/esnext/utils/obj.utils.d.ts +124 -0
- package/build/esnext/utils/obj.utils.js +413 -0
- package/build/esnext/utils/obj.utils.js.map +1 -0
- package/build/esnext/utils/performance.utils.d.ts +136 -0
- package/build/esnext/utils/performance.utils.js +271 -0
- package/build/esnext/utils/performance.utils.js.map +1 -0
- package/build/esnext/utils/request.utils.d.ts +86 -0
- package/build/esnext/utils/request.utils.js +186 -0
- package/build/esnext/utils/request.utils.js.map +1 -0
- package/build/esnext/utils/response.utils.d.ts +163 -0
- package/build/esnext/utils/response.utils.js +247 -0
- package/build/esnext/utils/response.utils.js.map +1 -0
- package/build/esnext/utils/stream.utils.d.ts +88 -0
- package/build/esnext/utils/stream.utils.js +210 -0
- package/build/esnext/utils/stream.utils.js.map +1 -0
- package/build/esnext/utils/string.utils.d.ts +93 -0
- package/build/esnext/utils/string.utils.js +165 -0
- package/build/esnext/utils/string.utils.js.map +1 -0
- package/build/esnext/utils/type.utils.d.ts +90 -0
- package/build/esnext/utils/type.utils.js +187 -0
- package/build/esnext/utils/type.utils.js.map +1 -0
- package/build/esnext/utils/url.utils.d.ts +141 -0
- package/build/esnext/utils/url.utils.js +304 -0
- package/build/esnext/utils/url.utils.js.map +1 -0
- package/build/esnext/utils/validate.utils.d.ts +177 -0
- package/build/esnext/utils/validate.utils.js +320 -0
- package/build/esnext/utils/validate.utils.js.map +1 -0
- package/build/src/config.d.ts +122 -0
- package/build/src/config.js +138 -0
- package/build/src/config.js.map +1 -0
- package/build/src/index.d.ts +27 -0
- package/build/src/index.js +69 -0
- package/build/src/index.js.map +1 -0
- package/build/src/servers/server.builder.d.ts +508 -0
- package/build/src/servers/server.builder.js +661 -0
- package/build/src/servers/server.builder.js.map +1 -0
- package/build/src/servers/server.d.ts +256 -0
- package/build/src/servers/server.js +962 -0
- package/build/src/servers/server.js.map +1 -0
- package/build/src/types/api-response.d.ts +152 -0
- package/build/src/types/api-response.js +37 -0
- package/build/src/types/api-response.js.map +1 -0
- package/build/src/types/index.d.ts +125 -0
- package/build/src/types/index.js +26 -0
- package/build/src/types/index.js.map +1 -0
- package/build/src/types/server.d.ts +268 -0
- package/build/src/types/server.js +26 -0
- package/build/src/types/server.js.map +1 -0
- package/build/src/utils/array.utils.d.ts +168 -0
- package/build/src/utils/array.utils.js +364 -0
- package/build/src/utils/array.utils.js.map +1 -0
- package/build/src/utils/async.utils.d.ts +265 -0
- package/build/src/utils/async.utils.js +641 -0
- package/build/src/utils/async.utils.js.map +1 -0
- package/build/src/utils/cache.utils.d.ts +153 -0
- package/build/src/utils/cache.utils.js +297 -0
- package/build/src/utils/cache.utils.js.map +1 -0
- package/build/src/utils/context-store.utils.d.ts +189 -0
- package/build/src/utils/context-store.utils.js +296 -0
- package/build/src/utils/context-store.utils.js.map +1 -0
- package/build/src/utils/crypto.utils.d.ts +160 -0
- package/build/src/utils/crypto.utils.js +293 -0
- package/build/src/utils/crypto.utils.js.map +1 -0
- package/build/src/utils/date.utils.d.ts +159 -0
- package/build/src/utils/date.utils.js +396 -0
- package/build/src/utils/date.utils.js.map +1 -0
- package/build/src/utils/decorators.utils.d.ts +508 -0
- package/build/src/utils/decorators.utils.js +896 -0
- package/build/src/utils/decorators.utils.js.map +1 -0
- package/build/src/utils/dir.utils.d.ts +196 -0
- package/build/src/utils/dir.utils.js +501 -0
- package/build/src/utils/dir.utils.js.map +1 -0
- package/build/src/utils/env.utils.d.ts +377 -0
- package/build/src/utils/env.utils.js +789 -0
- package/build/src/utils/env.utils.js.map +1 -0
- package/build/src/utils/exception.utils.d.ts +230 -0
- package/build/src/utils/exception.utils.js +407 -0
- package/build/src/utils/exception.utils.js.map +1 -0
- package/build/src/utils/fs.utils.d.ts +164 -0
- package/build/src/utils/fs.utils.js +372 -0
- package/build/src/utils/fs.utils.js.map +1 -0
- package/build/src/utils/http-status-codes.d.ts +266 -0
- package/build/src/utils/http-status-codes.js +298 -0
- package/build/src/utils/http-status-codes.js.map +1 -0
- package/build/src/utils/id.utils.d.ts +36 -0
- package/build/src/utils/id.utils.js +91 -0
- package/build/src/utils/id.utils.js.map +1 -0
- package/build/src/utils/logger.utils.d.ts +160 -0
- package/build/src/utils/logger.utils.js +346 -0
- package/build/src/utils/logger.utils.js.map +1 -0
- package/build/src/utils/middleware.utils.d.ts +100 -0
- package/build/src/utils/middleware.utils.js +244 -0
- package/build/src/utils/middleware.utils.js.map +1 -0
- package/build/src/utils/obj.utils.d.ts +124 -0
- package/build/src/utils/obj.utils.js +429 -0
- package/build/src/utils/obj.utils.js.map +1 -0
- package/build/src/utils/performance.utils.d.ts +136 -0
- package/build/src/utils/performance.utils.js +278 -0
- package/build/src/utils/performance.utils.js.map +1 -0
- package/build/src/utils/request.utils.d.ts +86 -0
- package/build/src/utils/request.utils.js +195 -0
- package/build/src/utils/request.utils.js.map +1 -0
- package/build/src/utils/response.utils.d.ts +163 -0
- package/build/src/utils/response.utils.js +260 -0
- package/build/src/utils/response.utils.js.map +1 -0
- package/build/src/utils/stream.utils.d.ts +88 -0
- package/build/src/utils/stream.utils.js +218 -0
- package/build/src/utils/stream.utils.js.map +1 -0
- package/build/src/utils/string.utils.d.ts +93 -0
- package/build/src/utils/string.utils.js +179 -0
- package/build/src/utils/string.utils.js.map +1 -0
- package/build/src/utils/type.utils.d.ts +90 -0
- package/build/src/utils/type.utils.js +196 -0
- package/build/src/utils/type.utils.js.map +1 -0
- package/build/src/utils/url.utils.d.ts +141 -0
- package/build/src/utils/url.utils.js +317 -0
- package/build/src/utils/url.utils.js.map +1 -0
- package/build/src/utils/validate.utils.d.ts +177 -0
- package/build/src/utils/validate.utils.js +345 -0
- package/build/src/utils/validate.utils.js.map +1 -0
- package/package.json +66 -12
- package/build/index.cjs +0 -6888
- package/build/index.d.ts +0 -5242
- package/build/index.mjs +0 -6615
|
@@ -0,0 +1,300 @@
|
|
|
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
|
+
var _a;
|
|
204
|
+
const logParams = {
|
|
205
|
+
name: config.logger.name || '@catbee/utils',
|
|
206
|
+
level: config.logger.level || 'info',
|
|
207
|
+
redact: {
|
|
208
|
+
paths: ['req.authorization', 'res.authorization', 'url', 'headers.authorization', 'headers.cookies'],
|
|
209
|
+
censor: (value, path) => redact(value, path)
|
|
210
|
+
},
|
|
211
|
+
// serializers: {
|
|
212
|
+
// req: pino.stdSerializers.req,
|
|
213
|
+
// request: pino.stdSerializers.req,
|
|
214
|
+
// res: pino.stdSerializers.res,
|
|
215
|
+
// response: pino.stdSerializers.res,
|
|
216
|
+
// err: pino.stdSerializers.err,
|
|
217
|
+
// error: pino.stdSerializers.err
|
|
218
|
+
// },
|
|
219
|
+
timestamp: stdTimeFunctions.isoTime
|
|
220
|
+
};
|
|
221
|
+
const logger = config.logger.pretty && Env.isDev()
|
|
222
|
+
? pino(logParams, pino.transport({
|
|
223
|
+
target: 'pino-pretty',
|
|
224
|
+
options: {
|
|
225
|
+
colorize: true,
|
|
226
|
+
translateTime: 'SYS:standard',
|
|
227
|
+
ignore: 'pid,hostname',
|
|
228
|
+
singleLine: config.logger.singleLine,
|
|
229
|
+
levelFirst: true
|
|
230
|
+
}
|
|
231
|
+
}))
|
|
232
|
+
: pino(logParams);
|
|
233
|
+
_global[GLOBAL_LOGGER_KEY] = logger;
|
|
234
|
+
(_a = _global[GLOBAL_LOGGER_KEY]) === null || _a === void 0 ? void 0 : _a.debug('Logger initialized');
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Retrieves the current logger instance:
|
|
238
|
+
* - Returns a request-scoped logger from AsyncLocalStorage if available
|
|
239
|
+
* - Falls back to the global (singleton) logger
|
|
240
|
+
* - Initializes the global logger if not created yet
|
|
241
|
+
*
|
|
242
|
+
* @returns {Logger} The logger instance (request-bound or global root logger)
|
|
243
|
+
*/
|
|
244
|
+
export function getLogger() {
|
|
245
|
+
const logger = ContextStore.get(StoreKeys.LOGGER);
|
|
246
|
+
if (logger)
|
|
247
|
+
return logger;
|
|
248
|
+
if (!_global[GLOBAL_LOGGER_KEY]) {
|
|
249
|
+
setupLogger();
|
|
250
|
+
}
|
|
251
|
+
return _global[GLOBAL_LOGGER_KEY];
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* Logger instance for the global context.
|
|
255
|
+
* This logger is used for logging messages that are not tied to a specific request.
|
|
256
|
+
*/
|
|
257
|
+
export const logger = getLogger();
|
|
258
|
+
/**
|
|
259
|
+
* Creates a child logger with additional context.
|
|
260
|
+
*
|
|
261
|
+
* @param {Record<string, any>} bindings - Properties to attach to all log records
|
|
262
|
+
* @param {Logger} [parentLogger] - Parent logger (defaults to current context logger or global)
|
|
263
|
+
* @returns {Logger} Child logger with merged context
|
|
264
|
+
*/
|
|
265
|
+
export function createChildLogger(bindings, parentLogger) {
|
|
266
|
+
const logger = parentLogger || getLogger();
|
|
267
|
+
return logger.child(bindings);
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* Creates a request-scoped logger with request ID and stores it in context
|
|
271
|
+
*
|
|
272
|
+
* @param {string} requestId - Unique request identifier
|
|
273
|
+
* @param {object} [additionalContext] - Additional context to include in logs
|
|
274
|
+
* @returns {Logger} Request-scoped logger instance
|
|
275
|
+
*/
|
|
276
|
+
export function createRequestLogger(requestId, additionalContext = {}) {
|
|
277
|
+
const logger = createChildLogger(Object.assign({ requestId }, additionalContext));
|
|
278
|
+
try {
|
|
279
|
+
ContextStore.set(StoreKeys.LOGGER, logger);
|
|
280
|
+
}
|
|
281
|
+
catch (_a) {
|
|
282
|
+
// Context not initialized, can't store logger
|
|
283
|
+
logger.debug('Failed to store logger in context - AsyncLocalStorage not initialized');
|
|
284
|
+
}
|
|
285
|
+
return logger;
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* Utility to safely log errors with proper stack trace extraction
|
|
289
|
+
*
|
|
290
|
+
* @param {Error|unknown} error - Error object to log
|
|
291
|
+
* @param {string} [message] - Optional message to include
|
|
292
|
+
* @param {Record<string, any>} [context] - Additional context properties
|
|
293
|
+
*/
|
|
294
|
+
export function logError(error, message, context) {
|
|
295
|
+
const logger = getLogger();
|
|
296
|
+
const errObj = error instanceof Error ? error : new Error(String(error));
|
|
297
|
+
const logContext = Object.assign(Object.assign({}, context), { error: errObj });
|
|
298
|
+
logger.error(logContext, message || errObj.message);
|
|
299
|
+
}
|
|
300
|
+
//# sourceMappingURL=logger.utils.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"logger.utils.js","sourceRoot":"","sources":["../../../src/utils/logger.utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,IAAI,EAAE,EAAiB,gBAAgB,EAAE,MAAM,MAAM,CAAC;AAE7D,OAAO,EAAE,MAAM,EAAE,MAAM,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AC,CAAC;IAC7C,CAAC;IAAC,WAAM,CAAC;QACP,8CAA8C;QAC9C,MAAM,CAAC,KAAK,CAAC,uEAAuE,CAAC,CAAC;IACxF,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,QAAQ,CAAC,KAAsB,EAAE,OAAgB,EAAE,OAA6B;IAC9F,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;IAE3B,MAAM,MAAM,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IACzE,MAAM,UAAU,mCACX,OAAO,KACV,KAAK,EAAE,MAAM,GACd,CAAC;IAEF,MAAM,CAAC,KAAK,CAAC,UAAU,EAAE,OAAO,IAAI,MAAM,CAAC,OAAO,CAAC,CAAC;AACtD,CAAC","sourcesContent":["/*\n * The MIT License\n *\n * Copyright (c) 2025 Catbee Technologies. https://catbee-utils.npm.hprasath.com/license\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 pino, { LoggerOptions, stdTimeFunctions } from 'pino';\nimport type { Logger as PinoLogger } from 'pino'; // Type-only import\nimport { config } from '../config';\nimport { ContextStore, StoreKeys } from './context-store.utils';\nimport { Env } from './env.utils';\n\n/**\n * Symbol used to store the root logger in the Node.js global object.\n */\nconst GLOBAL_LOGGER_KEY = Symbol.for('logger');\n\n/**\n * Logger type for application-wide logging.\n */\nexport type Logger = pino.Logger;\n\n/**\n * Logger levels for application-wide logging.\n */\nexport type LoggerLevels = pino.Level;\n\n// Default sensitive fields\nexport const defaultSensitiveFields = [\n 'password',\n 'secret',\n 'token',\n 'apiKey',\n 'api_key',\n 'auth',\n 'jwt',\n 'access_token',\n 'client_secret',\n 'session_token',\n 'refresh_token'\n];\n\n/**\n * The global censor function used by the logger.\n */\nlet globalRedactCensor: (value: unknown, path: string[], sensitiveFields?: string[]) => string = (\n value,\n path,\n sensitiveFields = defaultSensitiveFields\n) => {\n if (typeof value !== 'string') return '***';\n\n const lowerPath = path.map(p => p.toLowerCase());\n const lowerSensitiveFields = sensitiveFields.map(f => f.toLowerCase());\n\n if (lowerPath.some(p => lowerSensitiveFields.includes(p))) return '***';\n\n // Redact URLs\n if (lowerPath[0] === 'url') {\n return value.replace(new RegExp(`([?&](${lowerSensitiveFields.join('|')})=)[^&#]*`, 'gi'), '$1***');\n }\n\n if (lowerPath.some(p => p.includes('authorization') || p.includes('auth'))) {\n return value.replace(/^(\\S+)\\s+.+$/, '$1 ***') || '***';\n }\n\n // Redact sensitive fields - check each path segment against each sensitive field\n if (lowerPath.some(pathPart => lowerSensitiveFields.some(field => pathPart.includes(field)))) {\n return '***';\n }\n\n if (path.length > 0 && !['req', 'res', 'headers'].includes(lowerPath[0])) {\n return value;\n }\n\n return value;\n};\n\n/**\n * Sets the global redaction censor function used throughout the application for log redaction.\n *\n * Use this function to customize how sensitive data is redacted in logs. The provided function\n * will replace the default censor implementation.\n *\n * @example\n * ```typescript\n * // Custom censor that redacts only specific values\n * setRedactCensor((value, path, sensitiveFields) => {\n * if (path.includes('password')) return '***';\n * return value;\n * });\n * ```\n *\n * @param fn - The redaction censor function to use globally. This function receives:\n * - value: The data value to potentially redact\n * - path: Array of strings representing the path to the value in the object\n * - sensitiveFields: Optional array of field names to consider sensitive\n * @returns void\n */\nexport function setRedactCensor(fn: (value: unknown, path: string[], sensitiveFields?: string[]) => string) {\n globalRedactCensor = fn;\n}\n\n/**\n * Gets the current global redaction censor function used for log redaction.\n *\n * This function is called internally by the logger when determining how to redact\n * sensitive information. It can also be used to access the current censor implementation\n * for composition or extension.\n *\n * @example\n * ```typescript\n * const currentCensor = getRedactCensor();\n * // Create an enhanced censor that extends the current one\n * setRedactCensor((value, path, fields) => {\n * // Add custom logic before delegating to current censor\n * if (someCondition) return customHandling();\n * return currentCensor(value, path, fields);\n * });\n * ```\n *\n * @returns The current redaction censor function\n */\nexport function getRedactCensor() {\n return globalRedactCensor;\n}\n\n/**\n * Convenience function to redact sensitive data using the current global redact censor.\n *\n * This is a direct wrapper around the global censor function that simplifies usage\n * in application code without needing to access the censor function directly.\n *\n * @example\n * ```typescript\n * // Redact a potential sensitive value\n * const safeValue = redact(value, ['user', 'apiKey']);\n * ```\n *\n * @param value - The value to potentially redact\n * @param path - Array of strings representing the path to the value in the object\n * @param sensitiveFields - Optional array of field names to consider sensitive\n * @returns The redacted string value or \"***\" for redacted content\n */\nexport function redact(value: unknown, path: string[], sensitiveFields?: string[]) {\n return globalRedactCensor(value, path, sensitiveFields);\n}\n\n/**\n * Extends the current redaction function with additional fields to redact.\n *\n * This function wraps the existing censor while adding more fields to be considered\n * sensitive without replacing the entire redaction logic.\n *\n * @example\n * ```typescript\n * // Add custom fields to be redacted in all future redaction operations\n * addRedactFields(['customerId', 'accountNumber']);\n * ```\n *\n * @param fields - Array of additional field names to redact\n */\nexport function addRedactFields(fields: string[]) {\n const prev = globalRedactCensor;\n globalRedactCensor = (value, path, sensitiveFields = defaultSensitiveFields) =>\n prev(value, path, [...(sensitiveFields || []), ...fields]);\n}\n\n/**\n * Replaces the default list of sensitive fields with a new list.\n *\n * This is useful when you want complete control over what fields are considered\n * sensitive by default, rather than using the library's built-in list.\n *\n * @example\n * ```typescript\n * // Replace default sensitive fields with a custom list\n * setSensitiveFields(['password', 'ssn', 'creditCard']);\n * ```\n *\n * @param fields - Array of field names to set as the new default sensitive fields\n */\nexport function setSensitiveFields(fields: string[]) {\n defaultSensitiveFields.splice(0, defaultSensitiveFields.length, ...fields);\n}\n\n/**\n * Adds additional field names to the default sensitive fields list.\n *\n * This preserves the existing sensitive fields while adding new ones for\n * application-specific sensitive data.\n *\n * @example\n * ```typescript\n * // Add domain-specific sensitive fields to the default list\n * addSensitiveFields(['socialSecurityNumber', 'medicalRecordNumber']);\n * ```\n *\n * @param fields - Array of additional field names to add to the sensitive fields list\n */\nexport function addSensitiveFields(fields: string[]) {\n defaultSensitiveFields.push(...fields);\n}\n\n/**\n * Use an object compatible with either modern or legacy global scopes.\n */\nexport const _globalThis = typeof globalThis === 'object' ? globalThis : global;\nconst _global = _globalThis as unknown as { [GLOBAL_LOGGER_KEY]: PinoLogger };\n\n/**\n * Initializes the global root logger according to app configuration.\n *\n * - Sets log name, level, timestamp, and redaction for sensitive fields.\n * - Uses singleton in global symbol registry.\n */\nfunction setupLogger(): void {\n const logParams: LoggerOptions = {\n name: config.logger.name || '@catbee/utils',\n level: config.logger.level || 'info',\n redact: {\n paths: ['req.authorization', 'res.authorization', 'url', 'headers.authorization', 'headers.cookies'],\n censor: (value, path) => redact(value, path)\n },\n // serializers: {\n // req: pino.stdSerializers.req,\n // request: pino.stdSerializers.req,\n // res: pino.stdSerializers.res,\n // response: pino.stdSerializers.res,\n // err: pino.stdSerializers.err,\n // error: pino.stdSerializers.err\n // },\n timestamp: stdTimeFunctions.isoTime\n };\n\n const logger =\n config.logger.pretty && Env.isDev()\n ? pino(\n logParams,\n pino.transport({\n target: 'pino-pretty',\n options: {\n colorize: true,\n translateTime: 'SYS:standard',\n ignore: 'pid,hostname',\n singleLine: config.logger.singleLine,\n levelFirst: true\n }\n })\n )\n : pino(logParams);\n\n _global[GLOBAL_LOGGER_KEY] = logger;\n _global[GLOBAL_LOGGER_KEY]?.debug('Logger initialized');\n}\n\n/**\n * Retrieves the current logger instance:\n * - Returns a request-scoped logger from AsyncLocalStorage if available\n * - Falls back to the global (singleton) logger\n * - Initializes the global logger if not created yet\n *\n * @returns {Logger} The logger instance (request-bound or global root logger)\n */\nexport function getLogger(): PinoLogger {\n const logger = ContextStore.get<PinoLogger>(StoreKeys.LOGGER);\n if (logger) return logger;\n\n if (!_global[GLOBAL_LOGGER_KEY]) {\n setupLogger();\n }\n\n return _global[GLOBAL_LOGGER_KEY];\n}\n\n/**\n * Logger instance for the global context.\n * This logger is used for logging messages that are not tied to a specific request.\n */\nexport const logger = getLogger();\n\n/**\n * Creates a child logger with additional context.\n *\n * @param {Record<string, any>} bindings - Properties to attach to all log records\n * @param {Logger} [parentLogger] - Parent logger (defaults to current context logger or global)\n * @returns {Logger} Child logger with merged context\n */\nexport function createChildLogger(bindings: Record<string, any>, parentLogger?: PinoLogger): PinoLogger {\n const logger = parentLogger || getLogger();\n return logger.child(bindings);\n}\n\n/**\n * Creates a request-scoped logger with request ID and stores it in context\n *\n * @param {string} requestId - Unique request identifier\n * @param {object} [additionalContext] - Additional context to include in logs\n * @returns {Logger} Request-scoped logger instance\n */\nexport function createRequestLogger(requestId: string, additionalContext: Record<string, any> = {}): PinoLogger {\n const logger = createChildLogger({\n requestId,\n ...additionalContext\n });\n\n try {\n ContextStore.set(StoreKeys.LOGGER, logger);\n } catch {\n // Context not initialized, can't store logger\n logger.debug('Failed to store logger in context - AsyncLocalStorage not initialized');\n }\n\n return logger;\n}\n\n/**\n * Utility to safely log errors with proper stack trace extraction\n *\n * @param {Error|unknown} error - Error object to log\n * @param {string} [message] - Optional message to include\n * @param {Record<string, any>} [context] - Additional context properties\n */\nexport function logError(error: Error | unknown, message?: string, context?: Record<string, any>): void {\n const logger = getLogger();\n\n const errObj = error instanceof Error ? error : new Error(String(error));\n const logContext = {\n ...context,\n error: errObj\n };\n\n logger.error(logContext, message || errObj.message);\n}\n"]}
|
|
@@ -0,0 +1,100 @@
|
|
|
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;
|
|
100
|
+
//# sourceMappingURL=middleware.utils.d.ts.map
|
|
@@ -0,0 +1,236 @@
|
|
|
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 { uuid } from './id.utils';
|
|
25
|
+
import { HttpStatusCodes } from './http-status-codes';
|
|
26
|
+
import { createFinalErrorResponse, ErrorResponse } from './response.utils';
|
|
27
|
+
import { getLogger } from './logger.utils';
|
|
28
|
+
import { ContextStore, StoreKeys } from './context-store.utils';
|
|
29
|
+
import { RequestTimeoutException } from './exception.utils';
|
|
30
|
+
/**
|
|
31
|
+
* Attaches a unique request ID to each request.
|
|
32
|
+
* Useful for request tracing and correlation between logs.
|
|
33
|
+
*
|
|
34
|
+
* @param {object} [options] - Configuration options
|
|
35
|
+
* @param {string} [options.headerName='X-Request-ID'] - Header name for request ID
|
|
36
|
+
* @param {boolean} [options.exposeHeader=true] - Whether to expose the header in response
|
|
37
|
+
* @param {() => string} [options.generator] - Custom ID generator function
|
|
38
|
+
* @returns {Middleware} Express-compatible middleware
|
|
39
|
+
*/
|
|
40
|
+
export function requestId(options) {
|
|
41
|
+
const headerName = (options === null || options === void 0 ? void 0 : options.headerName) || 'X-Request-ID';
|
|
42
|
+
const exposeHeader = (options === null || options === void 0 ? void 0 : options.exposeHeader) !== false;
|
|
43
|
+
const generateId = (options === null || options === void 0 ? void 0 : options.generator) || uuid;
|
|
44
|
+
return (req, res, next) => {
|
|
45
|
+
// Use existing request ID from header or generate a new one
|
|
46
|
+
const existingId = req.headers[headerName.toLowerCase()];
|
|
47
|
+
const id = existingId || generateId();
|
|
48
|
+
// Attach ID to request object
|
|
49
|
+
req.id = id;
|
|
50
|
+
// Add ID to response headers
|
|
51
|
+
if (exposeHeader) {
|
|
52
|
+
res.setHeader(headerName, id);
|
|
53
|
+
}
|
|
54
|
+
next();
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Measures request processing time and logs or adds it to response headers.
|
|
59
|
+
*
|
|
60
|
+
* @param {object} [options] - Configuration options
|
|
61
|
+
* @param {boolean} [options.addHeader=true] - Whether to add X-Response-Time header
|
|
62
|
+
* @param {boolean} [options.logOnComplete=false] - Whether to log timing info
|
|
63
|
+
* @returns {Middleware} Express-compatible middleware
|
|
64
|
+
*/
|
|
65
|
+
export function responseTime(options) {
|
|
66
|
+
const addHeader = (options === null || options === void 0 ? void 0 : options.addHeader) !== false;
|
|
67
|
+
const logOnComplete = (options === null || options === void 0 ? void 0 : options.logOnComplete) === true;
|
|
68
|
+
return (req, res, next) => {
|
|
69
|
+
const start = process.hrtime();
|
|
70
|
+
// Function to calculate duration
|
|
71
|
+
const getDuration = () => {
|
|
72
|
+
const diff = process.hrtime(start);
|
|
73
|
+
return (diff[0] * 1e3 + diff[1] * 1e-6).toFixed(2);
|
|
74
|
+
};
|
|
75
|
+
if (addHeader) {
|
|
76
|
+
// Ensure header is set before response is sent
|
|
77
|
+
const originalWriteHead = res.writeHead;
|
|
78
|
+
res.writeHead = function (...args) {
|
|
79
|
+
res.setHeader('X-Response-Time', `${getDuration()}ms`);
|
|
80
|
+
return originalWriteHead.apply(this, args);
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
if (logOnComplete) {
|
|
84
|
+
res.on('finish', () => {
|
|
85
|
+
getLogger().info(`${req.method} ${req.url} - ${getDuration()}ms`);
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
next();
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Request timeout middleware.
|
|
93
|
+
* Aborts requests that take too long to process.
|
|
94
|
+
*
|
|
95
|
+
* @param {number} [timeoutMs=30000] - Timeout in milliseconds
|
|
96
|
+
* @returns {Middleware} Express-compatible middleware
|
|
97
|
+
*/
|
|
98
|
+
export function timeout(timeoutMs = 30000) {
|
|
99
|
+
return (_req, res, next) => {
|
|
100
|
+
// Set timeout for the request
|
|
101
|
+
const timer = setTimeout(() => {
|
|
102
|
+
const response = new RequestTimeoutException('Request timed out');
|
|
103
|
+
res.status(HttpStatusCodes.REQUEST_TIMEOUT).json(response);
|
|
104
|
+
}, timeoutMs);
|
|
105
|
+
// Clear timeout when response is sent
|
|
106
|
+
res.on('finish', () => {
|
|
107
|
+
clearTimeout(timer);
|
|
108
|
+
});
|
|
109
|
+
next();
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Creates an Express middleware that initializes a per-request context.
|
|
114
|
+
*
|
|
115
|
+
* @param {object} [options] - Optional configuration
|
|
116
|
+
* @param {string} [options.headerName='x-request-id'] - Header to look for request ID
|
|
117
|
+
* @param {boolean} [options.autoLog=true] - Whether to log automatically when context is initialized
|
|
118
|
+
* @returns {(req: Request, res: Response, next: NextFunction) => void} Express middleware function
|
|
119
|
+
*/
|
|
120
|
+
export function setupRequestContext(options = {}) {
|
|
121
|
+
const { headerName = 'x-request-id', autoLog = true } = options;
|
|
122
|
+
return (req, _res, next) => {
|
|
123
|
+
// Generate or use existing request ID
|
|
124
|
+
const requestId = req.headers[headerName] || (req === null || req === void 0 ? void 0 : req['id']) || uuid();
|
|
125
|
+
ContextStore.run({ [StoreKeys.REQUEST_ID]: requestId }, () => {
|
|
126
|
+
// Create a child logger for this request
|
|
127
|
+
const childLogger = getLogger().child({
|
|
128
|
+
requestId,
|
|
129
|
+
method: req.method,
|
|
130
|
+
url: req.originalUrl || req.url
|
|
131
|
+
});
|
|
132
|
+
req.logger = childLogger;
|
|
133
|
+
// Store logger in context
|
|
134
|
+
ContextStore.set(StoreKeys.LOGGER, childLogger);
|
|
135
|
+
if (autoLog) {
|
|
136
|
+
req.logger.info('Request context initialized');
|
|
137
|
+
}
|
|
138
|
+
next();
|
|
139
|
+
});
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Global error handling middleware with enhanced features.
|
|
144
|
+
*
|
|
145
|
+
* @param {ErrorHandlerOptions} options - Error handler options
|
|
146
|
+
* @param {boolean} [options.logErrors=true] - Whether to log errors
|
|
147
|
+
* @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production
|
|
148
|
+
* @returns Error middleware
|
|
149
|
+
*
|
|
150
|
+
* @example
|
|
151
|
+
* import express from 'express';
|
|
152
|
+
* import { errorHandler } from '@catbee/utils';
|
|
153
|
+
*
|
|
154
|
+
* const app = express();
|
|
155
|
+
*
|
|
156
|
+
* // Your routes
|
|
157
|
+
* app.get('/ping', (req, res) => {
|
|
158
|
+
* throw new Error('Something went wrong');
|
|
159
|
+
* });
|
|
160
|
+
*
|
|
161
|
+
* // Error handler (must be last middleware)
|
|
162
|
+
* app.use(errorHandler({ includeDetails: true }));
|
|
163
|
+
*
|
|
164
|
+
* app.listen(3000, () => {
|
|
165
|
+
* console.log('Server running on port 3000');
|
|
166
|
+
* });
|
|
167
|
+
*/
|
|
168
|
+
export function errorHandler(options) {
|
|
169
|
+
const logErrors = (options === null || options === void 0 ? void 0 : options.logErrors) !== false;
|
|
170
|
+
const includeDetails = (options === null || options === void 0 ? void 0 : options.includeDetails) === true;
|
|
171
|
+
return (err, req, res, _next) => {
|
|
172
|
+
// Determine status code
|
|
173
|
+
const status = (err === null || err === void 0 ? void 0 : err.status) || (err === null || err === void 0 ? void 0 : err.statusCode) || HttpStatusCodes.INTERNAL_SERVER_ERROR;
|
|
174
|
+
// Log error if enabled
|
|
175
|
+
if (logErrors) {
|
|
176
|
+
getLogger().error({ err }, `${err.message || 'Unknown error'}`);
|
|
177
|
+
}
|
|
178
|
+
// Handle ErrorResponse instances (our custom error class)
|
|
179
|
+
if (err instanceof ErrorResponse) {
|
|
180
|
+
const result = {
|
|
181
|
+
error: true,
|
|
182
|
+
message: err.message,
|
|
183
|
+
timestamp: err.timestamp,
|
|
184
|
+
requestId: (err === null || err === void 0 ? void 0 : err.requestId) || (req === null || req === void 0 ? void 0 : req.id) || uuid(),
|
|
185
|
+
status,
|
|
186
|
+
path: req.originalUrl || req.url
|
|
187
|
+
};
|
|
188
|
+
if (includeDetails && (err === null || err === void 0 ? void 0 : err.stack)) {
|
|
189
|
+
result.stack = err.stack.split('\n').map((line) => line.trim());
|
|
190
|
+
}
|
|
191
|
+
return res.status(status).json(result);
|
|
192
|
+
}
|
|
193
|
+
// Handle any other errors
|
|
194
|
+
return res
|
|
195
|
+
.status(status)
|
|
196
|
+
.json(createFinalErrorResponse(req, status, (err === null || err === void 0 ? void 0 : err.message) || 'Internal Server Error', err, { includeDetails }));
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Health check middleware for service status and custom checks.
|
|
201
|
+
*
|
|
202
|
+
* @param {object} [options] - Health check options
|
|
203
|
+
* @param {string} [options.path='/healthz'] - Health check endpoint path
|
|
204
|
+
* @param {Array<{name: string; check: () => Promise<boolean> | boolean}>} [options.checks] - Custom health checks
|
|
205
|
+
* @param {boolean} [options.detailed=true] - Show detailed check results
|
|
206
|
+
* @returns {Middleware} Express-compatible middleware
|
|
207
|
+
*/
|
|
208
|
+
export function healthCheck(options) {
|
|
209
|
+
const path = (options === null || options === void 0 ? void 0 : options.path) || '/healthz';
|
|
210
|
+
const checks = (options === null || options === void 0 ? void 0 : options.checks) || [];
|
|
211
|
+
const detailed = (options === null || options === void 0 ? void 0 : options.detailed) !== false;
|
|
212
|
+
return async (req, res, next) => {
|
|
213
|
+
if (req.path !== path)
|
|
214
|
+
return next();
|
|
215
|
+
const results = {};
|
|
216
|
+
let allHealthy = true;
|
|
217
|
+
for (const check of checks) {
|
|
218
|
+
try {
|
|
219
|
+
const result = await Promise.resolve(check.check());
|
|
220
|
+
results[check.name] = !!result;
|
|
221
|
+
if (!result)
|
|
222
|
+
allHealthy = false;
|
|
223
|
+
}
|
|
224
|
+
catch (_a) {
|
|
225
|
+
results[check.name] = false;
|
|
226
|
+
allHealthy = false;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
const status = allHealthy ? HttpStatusCodes.OK : HttpStatusCodes.SERVICE_UNAVAILABLE;
|
|
230
|
+
const response = detailed
|
|
231
|
+
? { status: allHealthy ? 'ok' : 'unhealthy', checks: results, timestamp: new Date().toISOString() }
|
|
232
|
+
: { status: allHealthy ? 'ok' : 'unhealthy' };
|
|
233
|
+
res.status(status).json(response);
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
//# sourceMappingURL=middleware.utils.js.map
|