@catbee/utils 1.1.0 → 2.0.0-next.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/LICENSE +1 -1
- package/README.md +79 -43
- package/array/index.cjs +355 -0
- package/array/index.d.ts +317 -0
- package/array/index.mjs +327 -0
- package/async/index.cjs +484 -0
- package/async/index.d.ts +299 -0
- package/async/index.mjs +463 -0
- package/cache/index.cjs +292 -0
- package/cache/index.d.ts +179 -0
- package/cache/index.mjs +290 -0
- package/config/index.cjs +150 -0
- package/config/index.d.ts +88 -0
- package/config/index.mjs +143 -0
- package/context-store/index.cjs +267 -0
- package/context-store/index.d.ts +216 -0
- package/context-store/index.mjs +261 -0
- package/crypto/index.cjs +182 -0
- package/crypto/index.d.ts +187 -0
- package/crypto/index.mjs +166 -0
- package/date/index.cjs +340 -0
- package/date/index.d.ts +214 -0
- package/date/index.mjs +326 -0
- package/decorators/index.cjs +2051 -0
- package/decorators/index.d.ts +708 -0
- package/decorators/index.mjs +2010 -0
- package/dir/index.cjs +417 -0
- package/dir/index.d.ts +219 -0
- package/dir/index.mjs +390 -0
- package/env/index.cjs +745 -0
- package/env/index.d.ts +403 -0
- package/env/index.mjs +742 -0
- package/exception/index.cjs +362 -0
- package/exception/index.d.ts +256 -0
- package/exception/index.mjs +338 -0
- package/fs/index.cjs +287 -0
- package/fs/index.d.ts +229 -0
- package/fs/index.mjs +258 -0
- package/http-status-codes/index.cjs +96 -0
- package/http-status-codes/index.d.ts +291 -0
- package/http-status-codes/index.mjs +94 -0
- package/id/index.cjs +62 -0
- package/id/index.d.ts +61 -0
- package/id/index.mjs +56 -0
- package/index.cjs +218 -0
- package/index.d.ts +51 -0
- package/index.mjs +51 -0
- package/logger/index.cjs +334 -0
- package/logger/index.d.ts +213 -0
- package/logger/index.mjs +313 -0
- package/middleware/index.cjs +177 -0
- package/middleware/index.d.ts +127 -0
- package/middleware/index.mjs +170 -0
- package/obj/index.cjs +305 -0
- package/obj/index.d.ts +160 -0
- package/obj/index.mjs +289 -0
- package/package.json +172 -20
- package/performance/index.cjs +231 -0
- package/performance/index.d.ts +162 -0
- package/performance/index.mjs +225 -0
- package/request/index.cjs +202 -0
- package/request/index.d.ts +265 -0
- package/request/index.mjs +194 -0
- package/response/index.cjs +234 -0
- package/response/index.d.ts +342 -0
- package/response/index.mjs +222 -0
- package/server/index.cjs +1631 -0
- package/server/index.d.ts +809 -0
- package/server/index.mjs +1622 -0
- package/stream/index.cjs +151 -0
- package/stream/index.d.ts +114 -0
- package/stream/index.mjs +144 -0
- package/string/index.cjs +109 -0
- package/string/index.d.ts +126 -0
- package/string/index.mjs +95 -0
- package/type/index.cjs +129 -0
- package/type/index.d.ts +131 -0
- package/type/index.mjs +119 -0
- package/types/index.cjs +34 -0
- package/types/index.d.ts +798 -0
- package/types/index.mjs +32 -0
- package/url/index.cjs +199 -0
- package/url/index.d.ts +166 -0
- package/url/index.mjs +187 -0
- package/validation/index.cjs +259 -0
- package/validation/index.d.ts +209 -0
- package/validation/index.mjs +231 -0
- package/build/index.cjs +0 -7694
- package/build/index.d.ts +0 -5792
- package/build/index.mjs +0 -7386
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* The MIT License
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) 2025 Catbee Technologies. https://catbee.in/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
|
+
|
|
25
|
+
import pino, { Logger as Logger$1 } from 'pino';
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Logger type for application-wide logging.
|
|
29
|
+
*/
|
|
30
|
+
type Logger = Logger$1;
|
|
31
|
+
/**
|
|
32
|
+
* Logger levels for application-wide logging.
|
|
33
|
+
*/
|
|
34
|
+
type LoggerLevels = pino.Level;
|
|
35
|
+
declare const defaultSensitiveFields: string[];
|
|
36
|
+
/**
|
|
37
|
+
* Sets the global redaction censor function used throughout the application for log redaction.
|
|
38
|
+
*
|
|
39
|
+
* Use this function to customize how sensitive data is redacted in logs. The provided function
|
|
40
|
+
* will replace the default censor implementation.
|
|
41
|
+
*
|
|
42
|
+
* @example
|
|
43
|
+
* ```typescript
|
|
44
|
+
* // Custom censor that redacts only specific values
|
|
45
|
+
* setRedactCensor((value, path, sensitiveFields) => {
|
|
46
|
+
* if (path.includes('password')) return '***';
|
|
47
|
+
* return value;
|
|
48
|
+
* });
|
|
49
|
+
* ```
|
|
50
|
+
*
|
|
51
|
+
* @param fn - The redaction censor function to use globally. This function receives:
|
|
52
|
+
* - value: The data value to potentially redact
|
|
53
|
+
* - path: Array of strings representing the path to the value in the object
|
|
54
|
+
* - sensitiveFields: Optional array of field names to consider sensitive
|
|
55
|
+
* @returns void
|
|
56
|
+
*/
|
|
57
|
+
declare function setRedactCensor(fn: (value: unknown, path: string[], sensitiveFields?: string[]) => string): void;
|
|
58
|
+
/**
|
|
59
|
+
* Gets the current global redaction censor function used for log redaction.
|
|
60
|
+
*
|
|
61
|
+
* This function is called internally by the logger when determining how to redact
|
|
62
|
+
* sensitive information. It can also be used to access the current censor implementation
|
|
63
|
+
* for composition or extension.
|
|
64
|
+
*
|
|
65
|
+
* @example
|
|
66
|
+
* ```typescript
|
|
67
|
+
* const currentCensor = getRedactCensor();
|
|
68
|
+
* // Create an enhanced censor that extends the current one
|
|
69
|
+
* setRedactCensor((value, path, fields) => {
|
|
70
|
+
* // Add custom logic before delegating to current censor
|
|
71
|
+
* if (someCondition) return customHandling();
|
|
72
|
+
* return currentCensor(value, path, fields);
|
|
73
|
+
* });
|
|
74
|
+
* ```
|
|
75
|
+
*
|
|
76
|
+
* @returns The current redaction censor function
|
|
77
|
+
*/
|
|
78
|
+
declare function getRedactCensor(): (value: unknown, path: string[], sensitiveFields?: string[]) => string;
|
|
79
|
+
/**
|
|
80
|
+
* Convenience function to redact sensitive data using the current global redact censor.
|
|
81
|
+
*
|
|
82
|
+
* This is a direct wrapper around the global censor function that simplifies usage
|
|
83
|
+
* in application code without needing to access the censor function directly.
|
|
84
|
+
*
|
|
85
|
+
* @example
|
|
86
|
+
* ```typescript
|
|
87
|
+
* // Redact a potential sensitive value
|
|
88
|
+
* const safeValue = redact(value, ['user', 'apiKey']);
|
|
89
|
+
* ```
|
|
90
|
+
*
|
|
91
|
+
* @param value - The value to potentially redact
|
|
92
|
+
* @param path - Array of strings representing the path to the value in the object
|
|
93
|
+
* @param sensitiveFields - Optional array of field names to consider sensitive
|
|
94
|
+
* @returns The redacted string value or "***" for redacted content
|
|
95
|
+
*/
|
|
96
|
+
declare function redact(value: unknown, path: string[], sensitiveFields?: string[]): string;
|
|
97
|
+
/**
|
|
98
|
+
* @deprecated Use addSensitiveFields instead.
|
|
99
|
+
*
|
|
100
|
+
* Extends the current redaction function with additional fields to redact.
|
|
101
|
+
*
|
|
102
|
+
* This function wraps the existing censor while adding more fields to be considered
|
|
103
|
+
* sensitive without replacing the entire redaction logic.
|
|
104
|
+
*
|
|
105
|
+
* @example
|
|
106
|
+
* ```typescript
|
|
107
|
+
* // Add custom fields to be redacted in all future redaction operations
|
|
108
|
+
* addRedactFields(['customerId', 'accountNumber']);
|
|
109
|
+
* ```
|
|
110
|
+
*
|
|
111
|
+
* @param fields - Array of additional field names to redact
|
|
112
|
+
*/
|
|
113
|
+
declare function addRedactFields(fields: string[]): void;
|
|
114
|
+
/**
|
|
115
|
+
* Retrieves the expanded list of sensitive fields.
|
|
116
|
+
*
|
|
117
|
+
* This function expands the default sensitive fields into their various naming
|
|
118
|
+
* conventions (e.g., camelCase, snake_case) and caches the result for efficiency.
|
|
119
|
+
*
|
|
120
|
+
* @returns Array of expanded sensitive field names
|
|
121
|
+
*/
|
|
122
|
+
declare function getExpandedSensitiveFields(): string[];
|
|
123
|
+
/**
|
|
124
|
+
* Replaces the default list of sensitive fields with a new list.
|
|
125
|
+
*
|
|
126
|
+
* This is useful when you want complete control over what fields are considered
|
|
127
|
+
* sensitive by default, rather than using the library's built-in list.
|
|
128
|
+
*
|
|
129
|
+
* @example
|
|
130
|
+
* ```typescript
|
|
131
|
+
* // Replace default sensitive fields with a custom list
|
|
132
|
+
* setSensitiveFields(['password', 'ssn', 'creditCard']);
|
|
133
|
+
* ```
|
|
134
|
+
*
|
|
135
|
+
* @param fields - Array of field names to set as the new default sensitive fields
|
|
136
|
+
*/
|
|
137
|
+
declare function setSensitiveFields(fields: string[]): void;
|
|
138
|
+
/**
|
|
139
|
+
* Adds additional field names to the default sensitive fields list.
|
|
140
|
+
*
|
|
141
|
+
* This preserves the existing sensitive fields while adding new ones for
|
|
142
|
+
* application-specific sensitive data.
|
|
143
|
+
*
|
|
144
|
+
* @example
|
|
145
|
+
* ```typescript
|
|
146
|
+
* // Add domain-specific sensitive fields to the default list
|
|
147
|
+
* addSensitiveFields(['socialSecurityNumber', 'medicalRecordNumber']);
|
|
148
|
+
* ```
|
|
149
|
+
*
|
|
150
|
+
* @param fields - Array of additional field names to add to the sensitive fields list
|
|
151
|
+
*/
|
|
152
|
+
declare function addSensitiveFields(fields: string[]): void;
|
|
153
|
+
/**
|
|
154
|
+
* Use an object compatible with either modern or legacy global scopes.
|
|
155
|
+
*/
|
|
156
|
+
declare const _globalThis: typeof globalThis;
|
|
157
|
+
/**
|
|
158
|
+
* Retrieves the current logger instance:
|
|
159
|
+
* - Returns a request-scoped logger from AsyncLocalStorage if available
|
|
160
|
+
* - Falls back to the global (singleton) logger
|
|
161
|
+
* - Initializes the global logger if not created yet
|
|
162
|
+
* - If newInstance is true, returns a fresh logger without any context
|
|
163
|
+
*
|
|
164
|
+
* @param {boolean} newInstance - If true, returns a fresh logger without any context
|
|
165
|
+
* @returns {Logger} The logger instance (request-bound or global root logger or fresh instance)
|
|
166
|
+
*/
|
|
167
|
+
declare function getLogger(newInstance?: boolean): Logger$1;
|
|
168
|
+
/**
|
|
169
|
+
* Creates a child logger with additional context.
|
|
170
|
+
*
|
|
171
|
+
* @param {Record<string, any>} bindings - Properties to attach to all log records
|
|
172
|
+
* @param {Logger} [parentLogger] - Parent logger (defaults to current context logger or global)
|
|
173
|
+
* @returns {Logger} Child logger with merged context
|
|
174
|
+
*/
|
|
175
|
+
declare function createChildLogger(bindings: Record<string, any>, parentLogger?: Logger$1): Logger$1;
|
|
176
|
+
/**
|
|
177
|
+
* Creates a request-scoped logger with request ID and stores it in context
|
|
178
|
+
*
|
|
179
|
+
* @param {string} requestId - Unique request identifier
|
|
180
|
+
* @param {object} [additionalContext] - Additional context to include in logs
|
|
181
|
+
* @returns {Logger} Request-scoped logger instance
|
|
182
|
+
*/
|
|
183
|
+
declare function createRequestLogger(requestId: string, additionalContext?: Record<string, any>): Logger$1;
|
|
184
|
+
/**
|
|
185
|
+
* Utility to safely log errors with proper stack trace extraction
|
|
186
|
+
*
|
|
187
|
+
* @param {Error|unknown} error - Error object to log
|
|
188
|
+
* @param {string} [message] - Optional message to include
|
|
189
|
+
* @param {Record<string, any>} [context] - Additional context properties
|
|
190
|
+
*/
|
|
191
|
+
declare function logError(error: Error | unknown, message?: string, context?: Record<string, any>): void;
|
|
192
|
+
/**
|
|
193
|
+
* Expands multiple sensitive field names into their variants.
|
|
194
|
+
* Useful to match fields like `api_key`, `apiKey`, `apikey`, `APIKEY`, etc.
|
|
195
|
+
*/
|
|
196
|
+
declare function expandSensitiveFields(fields: string[]): string[];
|
|
197
|
+
/**
|
|
198
|
+
* Generates multiple variants of a sensitive field name.
|
|
199
|
+
* Useful to match fields like `api_key`, `apiKey`, `apikey`, `APIKEY`, etc.
|
|
200
|
+
*/
|
|
201
|
+
declare function expandSensitiveField(field: string): string[];
|
|
202
|
+
/**
|
|
203
|
+
* Generates wildcard paths up to the given depth.
|
|
204
|
+
*
|
|
205
|
+
* depth = 2 ->
|
|
206
|
+
* password
|
|
207
|
+
* *.password
|
|
208
|
+
* *.*.password
|
|
209
|
+
*/
|
|
210
|
+
declare function generateDeepPaths(field: string, depth: number): string[];
|
|
211
|
+
|
|
212
|
+
export { _globalThis, addRedactFields, addSensitiveFields, createChildLogger, createRequestLogger, defaultSensitiveFields, expandSensitiveField, expandSensitiveFields, generateDeepPaths, getExpandedSensitiveFields, getLogger, getRedactCensor, logError, redact, setRedactCensor, setSensitiveFields };
|
|
213
|
+
export type { Logger, LoggerLevels };
|
package/logger/index.mjs
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* The MIT License
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) 2025 Catbee Technologies. https://catbee.in/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
|
+
|
|
25
|
+
import pino, { stdTimeFunctions } from 'pino';
|
|
26
|
+
import { getCatbeeGlobalConfig } from '@catbee/utils/config';
|
|
27
|
+
import { ContextStore, StoreKeys } from '@catbee/utils/context-store';
|
|
28
|
+
|
|
29
|
+
var __defProp = Object.defineProperty;
|
|
30
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
31
|
+
var GLOBAL_LOGGER_KEY = Symbol.for("logger");
|
|
32
|
+
var defaultSensitiveFields = [
|
|
33
|
+
"password",
|
|
34
|
+
"secret",
|
|
35
|
+
"token",
|
|
36
|
+
"api_key",
|
|
37
|
+
"auth",
|
|
38
|
+
"private_key",
|
|
39
|
+
"public_key",
|
|
40
|
+
"jwt",
|
|
41
|
+
"access_token",
|
|
42
|
+
"refresh_token",
|
|
43
|
+
"session_token",
|
|
44
|
+
"csrf_token",
|
|
45
|
+
"authorization",
|
|
46
|
+
"bearer",
|
|
47
|
+
"x-api-key",
|
|
48
|
+
"x-auth-token",
|
|
49
|
+
"x-access-token",
|
|
50
|
+
"client_secret",
|
|
51
|
+
"passphrase",
|
|
52
|
+
"otp",
|
|
53
|
+
"api_secret",
|
|
54
|
+
"token_secret"
|
|
55
|
+
];
|
|
56
|
+
var defaultRedactPaths = [
|
|
57
|
+
"req.authorization",
|
|
58
|
+
"req.headers.authorization",
|
|
59
|
+
"req.headers.cookie",
|
|
60
|
+
'req.headers["x-api-key"]',
|
|
61
|
+
'req.headers["x-auth-token"]',
|
|
62
|
+
'req.headers["x-access-token"]',
|
|
63
|
+
"req.body.password",
|
|
64
|
+
"req.body.token",
|
|
65
|
+
"req.body.secret",
|
|
66
|
+
"req.query.token",
|
|
67
|
+
"req.query.api_key",
|
|
68
|
+
"req.query.apiKey",
|
|
69
|
+
"res.authorization",
|
|
70
|
+
"res.headers.authorization",
|
|
71
|
+
'res.headers["set-cookie"]',
|
|
72
|
+
"headers.authorization",
|
|
73
|
+
"headers.cookies",
|
|
74
|
+
'headers["set-cookie"]',
|
|
75
|
+
'headers["x-api-key"]',
|
|
76
|
+
'headers["x-auth-token"]',
|
|
77
|
+
'headers["x-access-token"]',
|
|
78
|
+
"url",
|
|
79
|
+
"uri",
|
|
80
|
+
"href",
|
|
81
|
+
"redirect_uri",
|
|
82
|
+
"redirectUri"
|
|
83
|
+
];
|
|
84
|
+
var globalRedactCensor = /* @__PURE__ */ __name((value, path, sensitiveFields = getExpandedSensitiveFields()) => {
|
|
85
|
+
if (typeof value !== "string") return "***";
|
|
86
|
+
const lowerPath = path.filter((p) => typeof p === "string").map((p) => p.toLowerCase());
|
|
87
|
+
const lowerSensitiveFields = sensitiveFields.map((f) => f.toLowerCase());
|
|
88
|
+
if (lowerPath.some((p) => lowerSensitiveFields.includes(p))) return "***";
|
|
89
|
+
if (lowerPath[0] === "url" || lowerPath[0] === "uri" || lowerPath[0] === "href" || lowerPath.includes("redirect_uri") || lowerPath.includes("redirecturi")) {
|
|
90
|
+
return value.replace(new RegExp(`([?&](${lowerSensitiveFields.join("|")})=)[^&#]*`, "gi"), "$1***");
|
|
91
|
+
}
|
|
92
|
+
if (lowerPath.some((p) => p.includes("authorization") || p.includes("auth"))) {
|
|
93
|
+
return value.replace(/^(\S+)\s+.+$/, "$1 ***") || "***";
|
|
94
|
+
}
|
|
95
|
+
if (lowerPath.some((p) => lowerSensitiveFields.some((f) => p.includes(f)))) {
|
|
96
|
+
return "***";
|
|
97
|
+
}
|
|
98
|
+
if (path.length > 0 && ![
|
|
99
|
+
"req",
|
|
100
|
+
"res",
|
|
101
|
+
"headers"
|
|
102
|
+
].includes(lowerPath[0])) {
|
|
103
|
+
return value;
|
|
104
|
+
}
|
|
105
|
+
return value;
|
|
106
|
+
}, "globalRedactCensor");
|
|
107
|
+
function setRedactCensor(fn) {
|
|
108
|
+
globalRedactCensor = fn;
|
|
109
|
+
}
|
|
110
|
+
__name(setRedactCensor, "setRedactCensor");
|
|
111
|
+
function getRedactCensor() {
|
|
112
|
+
return globalRedactCensor;
|
|
113
|
+
}
|
|
114
|
+
__name(getRedactCensor, "getRedactCensor");
|
|
115
|
+
function redact(value, path, sensitiveFields) {
|
|
116
|
+
return globalRedactCensor(value, path, sensitiveFields);
|
|
117
|
+
}
|
|
118
|
+
__name(redact, "redact");
|
|
119
|
+
function addRedactFields(fields) {
|
|
120
|
+
const prev = globalRedactCensor;
|
|
121
|
+
globalRedactCensor = /* @__PURE__ */ __name((value, path, sensitiveFields = getExpandedSensitiveFields()) => prev(value, path, [
|
|
122
|
+
...sensitiveFields || [],
|
|
123
|
+
...fields
|
|
124
|
+
]), "globalRedactCensor");
|
|
125
|
+
cachedExpandedFields = null;
|
|
126
|
+
}
|
|
127
|
+
__name(addRedactFields, "addRedactFields");
|
|
128
|
+
var cachedExpandedFields = null;
|
|
129
|
+
function getExpandedSensitiveFields() {
|
|
130
|
+
if (!cachedExpandedFields) {
|
|
131
|
+
cachedExpandedFields = expandSensitiveFields(defaultSensitiveFields);
|
|
132
|
+
}
|
|
133
|
+
return cachedExpandedFields;
|
|
134
|
+
}
|
|
135
|
+
__name(getExpandedSensitiveFields, "getExpandedSensitiveFields");
|
|
136
|
+
function setSensitiveFields(fields) {
|
|
137
|
+
defaultSensitiveFields.splice(0, defaultSensitiveFields.length, ...fields);
|
|
138
|
+
cachedExpandedFields = null;
|
|
139
|
+
}
|
|
140
|
+
__name(setSensitiveFields, "setSensitiveFields");
|
|
141
|
+
function addSensitiveFields(fields) {
|
|
142
|
+
defaultSensitiveFields.push(...fields);
|
|
143
|
+
cachedExpandedFields = null;
|
|
144
|
+
}
|
|
145
|
+
__name(addSensitiveFields, "addSensitiveFields");
|
|
146
|
+
var _globalThis = typeof globalThis === "object" ? globalThis : global;
|
|
147
|
+
var _global = _globalThis;
|
|
148
|
+
function setupLogger(isGlobal = true) {
|
|
149
|
+
const sensitiveFields = getExpandedSensitiveFields();
|
|
150
|
+
const paths = /* @__PURE__ */ new Set([
|
|
151
|
+
...defaultRedactPaths,
|
|
152
|
+
...sensitiveFields.flatMap((field) => generateDeepPaths(field, 2))
|
|
153
|
+
]);
|
|
154
|
+
const logParams = {
|
|
155
|
+
name: getCatbeeGlobalConfig().logger?.name || "@catbee/utils",
|
|
156
|
+
level: getCatbeeGlobalConfig().logger?.level || "info",
|
|
157
|
+
redact: {
|
|
158
|
+
paths: Array.from(paths),
|
|
159
|
+
censor: /* @__PURE__ */ __name((value, path) => redact(value, path), "censor")
|
|
160
|
+
},
|
|
161
|
+
serializers: {
|
|
162
|
+
req: pino.stdSerializers.req,
|
|
163
|
+
request: pino.stdSerializers.req,
|
|
164
|
+
res: pino.stdSerializers.res,
|
|
165
|
+
response: pino.stdSerializers.res,
|
|
166
|
+
err: pino.stdSerializers.err,
|
|
167
|
+
error: pino.stdSerializers.err
|
|
168
|
+
},
|
|
169
|
+
timestamp: stdTimeFunctions.isoTime
|
|
170
|
+
};
|
|
171
|
+
let logger;
|
|
172
|
+
const logDir = getCatbeeGlobalConfig().logger?.dir?.trim();
|
|
173
|
+
const hasFileLogging = Boolean(logDir);
|
|
174
|
+
if (hasFileLogging && getCatbeeGlobalConfig().logger?.pretty) {
|
|
175
|
+
logger = pino(logParams, pino.transport({
|
|
176
|
+
targets: [
|
|
177
|
+
{
|
|
178
|
+
target: "pino-pretty",
|
|
179
|
+
level: getCatbeeGlobalConfig().logger?.level ?? "info",
|
|
180
|
+
options: {
|
|
181
|
+
colorize: getCatbeeGlobalConfig().logger?.colorize,
|
|
182
|
+
translateTime: "SYS:standard",
|
|
183
|
+
ignore: "pid,hostname",
|
|
184
|
+
singleLine: getCatbeeGlobalConfig().logger?.singleLine,
|
|
185
|
+
levelFirst: true
|
|
186
|
+
}
|
|
187
|
+
},
|
|
188
|
+
{
|
|
189
|
+
target: "pino/file",
|
|
190
|
+
level: getCatbeeGlobalConfig().logger?.level ?? "info",
|
|
191
|
+
options: {
|
|
192
|
+
destination: `${logDir}/app.log`,
|
|
193
|
+
mkdir: true
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
]
|
|
197
|
+
}));
|
|
198
|
+
} else if (hasFileLogging) {
|
|
199
|
+
logger = pino(logParams, pino.transport({
|
|
200
|
+
target: "pino/file",
|
|
201
|
+
options: {
|
|
202
|
+
destination: `${logDir}/app.log`,
|
|
203
|
+
mkdir: true
|
|
204
|
+
}
|
|
205
|
+
}));
|
|
206
|
+
} else if (getCatbeeGlobalConfig().logger?.pretty) {
|
|
207
|
+
logger = pino(logParams, pino.transport({
|
|
208
|
+
target: "pino-pretty",
|
|
209
|
+
options: {
|
|
210
|
+
colorize: getCatbeeGlobalConfig().logger?.colorize,
|
|
211
|
+
translateTime: "SYS:standard",
|
|
212
|
+
ignore: "pid,hostname",
|
|
213
|
+
singleLine: getCatbeeGlobalConfig().logger?.singleLine,
|
|
214
|
+
levelFirst: true
|
|
215
|
+
}
|
|
216
|
+
}));
|
|
217
|
+
} else {
|
|
218
|
+
logger = pino(logParams);
|
|
219
|
+
}
|
|
220
|
+
if (isGlobal) {
|
|
221
|
+
_global[GLOBAL_LOGGER_KEY] = logger;
|
|
222
|
+
_global[GLOBAL_LOGGER_KEY]?.debug({
|
|
223
|
+
logDir: logDir || "none"
|
|
224
|
+
}, "Global Logger Initialized");
|
|
225
|
+
}
|
|
226
|
+
return logger;
|
|
227
|
+
}
|
|
228
|
+
__name(setupLogger, "setupLogger");
|
|
229
|
+
function getLogger(newInstance = false) {
|
|
230
|
+
if (newInstance) {
|
|
231
|
+
return setupLogger(false);
|
|
232
|
+
}
|
|
233
|
+
const logger = ContextStore.get(StoreKeys.LOGGER);
|
|
234
|
+
if (logger) return logger;
|
|
235
|
+
if (!_global[GLOBAL_LOGGER_KEY]) {
|
|
236
|
+
setupLogger();
|
|
237
|
+
}
|
|
238
|
+
return _global[GLOBAL_LOGGER_KEY];
|
|
239
|
+
}
|
|
240
|
+
__name(getLogger, "getLogger");
|
|
241
|
+
function createChildLogger(bindings, parentLogger) {
|
|
242
|
+
const logger = parentLogger || getLogger();
|
|
243
|
+
return logger.child(bindings);
|
|
244
|
+
}
|
|
245
|
+
__name(createChildLogger, "createChildLogger");
|
|
246
|
+
function createRequestLogger(requestId, additionalContext = {}) {
|
|
247
|
+
const logger = createChildLogger({
|
|
248
|
+
requestId,
|
|
249
|
+
...additionalContext
|
|
250
|
+
});
|
|
251
|
+
try {
|
|
252
|
+
ContextStore.set(StoreKeys.LOGGER, logger);
|
|
253
|
+
} catch {
|
|
254
|
+
logger.debug("Failed to store logger in context - AsyncLocalStorage not initialized");
|
|
255
|
+
}
|
|
256
|
+
return logger;
|
|
257
|
+
}
|
|
258
|
+
__name(createRequestLogger, "createRequestLogger");
|
|
259
|
+
function logError(error, message, context) {
|
|
260
|
+
const logger = getLogger();
|
|
261
|
+
const errObj = error instanceof Error ? error : new Error(String(error));
|
|
262
|
+
const logContext = {
|
|
263
|
+
...context,
|
|
264
|
+
error: errObj
|
|
265
|
+
};
|
|
266
|
+
logger.error(logContext, message || errObj.message);
|
|
267
|
+
}
|
|
268
|
+
__name(logError, "logError");
|
|
269
|
+
function expandSensitiveFields(fields) {
|
|
270
|
+
const set = /* @__PURE__ */ new Set();
|
|
271
|
+
for (const field of fields) {
|
|
272
|
+
for (const v of expandSensitiveField(field)) {
|
|
273
|
+
set.add(v);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
return Array.from(set);
|
|
277
|
+
}
|
|
278
|
+
__name(expandSensitiveFields, "expandSensitiveFields");
|
|
279
|
+
function expandSensitiveField(field) {
|
|
280
|
+
const parts = field.split(/[_-]/g).filter(Boolean);
|
|
281
|
+
const camel = parts[0].toLowerCase() + parts.slice(1).map((p) => p.charAt(0).toUpperCase() + p.slice(1).toLowerCase()).join("");
|
|
282
|
+
const mergedLower = parts.join("").toLowerCase();
|
|
283
|
+
const mergedUpper = parts.join("").toUpperCase();
|
|
284
|
+
const kebab = parts.map((p) => p.toLowerCase()).join("-");
|
|
285
|
+
const snakeLower = parts.map((p) => p.toLowerCase()).join("_");
|
|
286
|
+
const snakeUpper = parts.map((p) => p.toUpperCase()).join("_");
|
|
287
|
+
return Array.from(/* @__PURE__ */ new Set([
|
|
288
|
+
field,
|
|
289
|
+
camel,
|
|
290
|
+
mergedLower,
|
|
291
|
+
mergedUpper,
|
|
292
|
+
kebab,
|
|
293
|
+
snakeLower,
|
|
294
|
+
snakeUpper
|
|
295
|
+
]));
|
|
296
|
+
}
|
|
297
|
+
__name(expandSensitiveField, "expandSensitiveField");
|
|
298
|
+
function generateDeepPaths(field, depth) {
|
|
299
|
+
const set = /* @__PURE__ */ new Set([
|
|
300
|
+
field
|
|
301
|
+
]);
|
|
302
|
+
let prefix = "";
|
|
303
|
+
for (let i = 1; i <= depth; i++) {
|
|
304
|
+
prefix = prefix ? `${prefix}.*` : "*";
|
|
305
|
+
set.add(`${prefix}.${field}`);
|
|
306
|
+
}
|
|
307
|
+
return [
|
|
308
|
+
...set
|
|
309
|
+
];
|
|
310
|
+
}
|
|
311
|
+
__name(generateDeepPaths, "generateDeepPaths");
|
|
312
|
+
|
|
313
|
+
export { _globalThis, addRedactFields, addSensitiveFields, createChildLogger, createRequestLogger, defaultSensitiveFields, expandSensitiveField, expandSensitiveFields, generateDeepPaths, getExpandedSensitiveFields, getLogger, getRedactCensor, logError, redact, setRedactCensor, setSensitiveFields };
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* The MIT License
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) 2025 Catbee Technologies. https://catbee.in/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
|
+
|
|
25
|
+
'use strict';
|
|
26
|
+
|
|
27
|
+
var id = require('@catbee/utils/id');
|
|
28
|
+
var httpStatusCodes = require('@catbee/utils/http-status-codes');
|
|
29
|
+
var response = require('@catbee/utils/response');
|
|
30
|
+
var logger = require('@catbee/utils/logger');
|
|
31
|
+
var contextStore = require('@catbee/utils/context-store');
|
|
32
|
+
var exception = require('@catbee/utils/exception');
|
|
33
|
+
|
|
34
|
+
var __defProp = Object.defineProperty;
|
|
35
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
36
|
+
function requestId(options) {
|
|
37
|
+
const headerName = options?.headerName || "X-Request-ID";
|
|
38
|
+
const exposeHeader = options?.exposeHeader !== false;
|
|
39
|
+
const generateId = options?.generator || id.uuid;
|
|
40
|
+
return (req, res, next) => {
|
|
41
|
+
const existingId = req.headers[headerName.toLowerCase()];
|
|
42
|
+
const id = existingId || generateId();
|
|
43
|
+
req.id = id;
|
|
44
|
+
if (exposeHeader) {
|
|
45
|
+
res.setHeader(headerName, id);
|
|
46
|
+
}
|
|
47
|
+
next();
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
__name(requestId, "requestId");
|
|
51
|
+
function responseTime(options) {
|
|
52
|
+
const addHeader = options?.addHeader !== false;
|
|
53
|
+
const logOnComplete = options?.logOnComplete === true;
|
|
54
|
+
return (req, res, next) => {
|
|
55
|
+
const start = process.hrtime();
|
|
56
|
+
const getDuration = /* @__PURE__ */ __name(() => {
|
|
57
|
+
const diff = process.hrtime(start);
|
|
58
|
+
return (diff[0] * 1e3 + diff[1] * 1e-6).toFixed(2);
|
|
59
|
+
}, "getDuration");
|
|
60
|
+
if (addHeader) {
|
|
61
|
+
const originalWriteHead = res.writeHead;
|
|
62
|
+
res.writeHead = function(...args) {
|
|
63
|
+
res.setHeader("X-Response-Time", `${getDuration()}ms`);
|
|
64
|
+
return originalWriteHead.apply(this, args);
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
if (logOnComplete) {
|
|
68
|
+
res.on("finish", () => {
|
|
69
|
+
logger.getLogger().info(`${req.method} ${req.url} - ${getDuration()}ms`);
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
next();
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
__name(responseTime, "responseTime");
|
|
76
|
+
function timeout(timeoutMs = 3e4) {
|
|
77
|
+
return (_req, res, next) => {
|
|
78
|
+
const timer = setTimeout(() => {
|
|
79
|
+
const response = new exception.RequestTimeoutException("Request timed out");
|
|
80
|
+
res.status(httpStatusCodes.HttpStatusCodes.REQUEST_TIMEOUT).json(response);
|
|
81
|
+
}, timeoutMs);
|
|
82
|
+
res.on("finish", () => {
|
|
83
|
+
clearTimeout(timer);
|
|
84
|
+
});
|
|
85
|
+
next();
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
__name(timeout, "timeout");
|
|
89
|
+
function setupRequestContext(options = {}) {
|
|
90
|
+
const { headerName = "x-request-id", autoLog = true } = options;
|
|
91
|
+
return (req, _res, next) => {
|
|
92
|
+
const requestId2 = req.headers[headerName] || req?.["id"] || id.uuid();
|
|
93
|
+
contextStore.ContextStore.run({
|
|
94
|
+
[contextStore.StoreKeys.REQUEST_ID]: requestId2
|
|
95
|
+
}, () => {
|
|
96
|
+
const childLogger = logger.getLogger().child({
|
|
97
|
+
requestId: requestId2,
|
|
98
|
+
method: req.method,
|
|
99
|
+
url: req.originalUrl || req.url
|
|
100
|
+
});
|
|
101
|
+
req.logger = childLogger;
|
|
102
|
+
contextStore.ContextStore.set(contextStore.StoreKeys.LOGGER, childLogger);
|
|
103
|
+
if (autoLog) {
|
|
104
|
+
req.logger.info("Request context initialized");
|
|
105
|
+
}
|
|
106
|
+
next();
|
|
107
|
+
});
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
__name(setupRequestContext, "setupRequestContext");
|
|
111
|
+
function errorHandler(options) {
|
|
112
|
+
const logErrors = options?.logErrors !== false;
|
|
113
|
+
const includeDetails = options?.includeDetails === true;
|
|
114
|
+
return (err, req, res, _next) => {
|
|
115
|
+
const status = err?.status || err?.statusCode || httpStatusCodes.HttpStatusCodes.INTERNAL_SERVER_ERROR;
|
|
116
|
+
if (logErrors) {
|
|
117
|
+
logger.getLogger().error({
|
|
118
|
+
err
|
|
119
|
+
}, `${err.message || "Unknown error"}`);
|
|
120
|
+
}
|
|
121
|
+
if (err instanceof response.ErrorResponse) {
|
|
122
|
+
const result = {
|
|
123
|
+
error: true,
|
|
124
|
+
message: err.message,
|
|
125
|
+
timestamp: err.timestamp,
|
|
126
|
+
requestId: err?.requestId || req?.id || id.uuid(),
|
|
127
|
+
status,
|
|
128
|
+
path: req.originalUrl || req.url
|
|
129
|
+
};
|
|
130
|
+
if (includeDetails && err?.stack) {
|
|
131
|
+
result.stack = err.stack.split("\n").map((line) => line.trim());
|
|
132
|
+
}
|
|
133
|
+
return res.status(status).json(result);
|
|
134
|
+
}
|
|
135
|
+
return res.status(status).json(response.createFinalErrorResponse(req, status, err?.message || "Internal Server Error", err, {
|
|
136
|
+
includeDetails
|
|
137
|
+
}));
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
__name(errorHandler, "errorHandler");
|
|
141
|
+
function healthCheck(options) {
|
|
142
|
+
const path = options?.path || "/healthz";
|
|
143
|
+
const checks = options?.checks || [];
|
|
144
|
+
const detailed = options?.detailed !== false;
|
|
145
|
+
return async (req, res, next) => {
|
|
146
|
+
if (req.path !== path) return next();
|
|
147
|
+
const results = {};
|
|
148
|
+
let allHealthy = true;
|
|
149
|
+
for (const check of checks) {
|
|
150
|
+
try {
|
|
151
|
+
const result = await Promise.resolve(check.check());
|
|
152
|
+
results[check.name] = !!result;
|
|
153
|
+
if (!result) allHealthy = false;
|
|
154
|
+
} catch {
|
|
155
|
+
results[check.name] = false;
|
|
156
|
+
allHealthy = false;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
const status = allHealthy ? httpStatusCodes.HttpStatusCodes.OK : httpStatusCodes.HttpStatusCodes.SERVICE_UNAVAILABLE;
|
|
160
|
+
const response = detailed ? {
|
|
161
|
+
status: allHealthy ? "ok" : "unhealthy",
|
|
162
|
+
checks: results,
|
|
163
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
164
|
+
} : {
|
|
165
|
+
status: allHealthy ? "ok" : "unhealthy"
|
|
166
|
+
};
|
|
167
|
+
res.status(status).json(response);
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
__name(healthCheck, "healthCheck");
|
|
171
|
+
|
|
172
|
+
exports.errorHandler = errorHandler;
|
|
173
|
+
exports.healthCheck = healthCheck;
|
|
174
|
+
exports.requestId = requestId;
|
|
175
|
+
exports.responseTime = responseTime;
|
|
176
|
+
exports.setupRequestContext = setupRequestContext;
|
|
177
|
+
exports.timeout = timeout;
|