@catbee/utils 1.0.5 → 2.0.0-next.0
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 +27 -27
- package/array/array.utils.d.ts +191 -0
- package/array/index.cjs +246 -0
- package/array/index.d.ts +25 -0
- package/array/index.mjs +228 -0
- package/async/async.utils.d.ts +296 -0
- package/async/index.cjs +428 -0
- package/async/index.d.ts +25 -0
- package/async/index.mjs +407 -0
- package/cache/cache.utils.d.ts +176 -0
- package/cache/index.cjs +292 -0
- package/cache/index.d.ts +25 -0
- package/cache/index.mjs +290 -0
- package/config/config.d.ts +57 -0
- package/config/index.cjs +136 -0
- package/config/index.d.ts +26 -0
- package/config/index.mjs +131 -0
- package/context-store/context-store.utils.d.ts +212 -0
- package/context-store/index.cjs +267 -0
- package/context-store/index.d.ts +25 -0
- package/context-store/index.mjs +261 -0
- package/crypto/crypto.utils.d.ts +183 -0
- package/crypto/index.cjs +182 -0
- package/crypto/index.d.ts +25 -0
- package/crypto/index.mjs +166 -0
- package/date/date.utils.d.ts +190 -0
- package/date/index.cjs +295 -0
- package/date/index.d.ts +25 -0
- package/date/index.mjs +283 -0
- package/decorators/decorators.utils.d.ts +705 -0
- package/decorators/index.cjs +913 -0
- package/decorators/index.d.ts +25 -0
- package/decorators/index.mjs +872 -0
- package/dir/dir.utils.d.ts +216 -0
- package/dir/index.cjs +416 -0
- package/dir/index.d.ts +25 -0
- package/dir/index.mjs +389 -0
- package/env/env.utils.d.ts +400 -0
- package/env/index.cjs +761 -0
- package/env/index.d.ts +25 -0
- package/env/index.mjs +758 -0
- package/exception/exception.utils.d.ts +253 -0
- package/exception/index.cjs +362 -0
- package/exception/index.d.ts +25 -0
- package/exception/index.mjs +338 -0
- package/fs/fs.utils.d.ts +196 -0
- package/fs/index.cjs +253 -0
- package/fs/index.d.ts +25 -0
- package/fs/index.mjs +228 -0
- package/http-status-codes/http-status-codes.d.ts +289 -0
- package/http-status-codes/index.cjs +96 -0
- package/http-status-codes/index.d.ts +25 -0
- package/http-status-codes/index.mjs +94 -0
- package/id/id.utils.d.ts +59 -0
- package/id/index.cjs +62 -0
- package/id/index.d.ts +25 -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 +25 -0
- package/logger/index.mjs +313 -0
- package/logger/logger.utils.d.ts +210 -0
- package/middleware/index.cjs +177 -0
- package/middleware/index.d.ts +25 -0
- package/middleware/index.mjs +170 -0
- package/middleware/middleware.utils.d.ts +123 -0
- package/obj/index.cjs +317 -0
- package/obj/index.d.ts +25 -0
- package/obj/index.mjs +301 -0
- package/obj/obj.utils.d.ts +156 -0
- package/package.json +172 -20
- package/performance/index.cjs +231 -0
- package/performance/index.d.ts +25 -0
- package/performance/index.mjs +225 -0
- package/performance/performance.utils.d.ts +159 -0
- package/request/index.cjs +202 -0
- package/request/index.d.ts +26 -0
- package/request/index.mjs +194 -0
- package/request/request.utils.d.ts +109 -0
- package/response/index.cjs +234 -0
- package/response/index.d.ts +26 -0
- package/response/index.mjs +222 -0
- package/response/response.utils.d.ts +186 -0
- package/server/index.cjs +1627 -0
- package/server/index.d.ts +28 -0
- package/server/index.mjs +1617 -0
- package/server/server.builder.d.ts +531 -0
- package/server/server.d.ts +303 -0
- package/stream/index.cjs +151 -0
- package/stream/index.d.ts +25 -0
- package/stream/index.mjs +144 -0
- package/stream/stream.utils.d.ts +111 -0
- package/string/index.cjs +109 -0
- package/string/index.d.ts +25 -0
- package/string/index.mjs +95 -0
- package/string/string.utils.d.ts +124 -0
- package/type/index.cjs +129 -0
- package/type/index.d.ts +25 -0
- package/type/index.mjs +119 -0
- package/type/type.utils.d.ts +129 -0
- package/types/api-response.d.ts +175 -0
- package/types/common.d.ts +148 -0
- package/types/config.d.ts +88 -0
- package/types/index.cjs +34 -0
- package/types/index.d.ts +28 -0
- package/types/index.mjs +32 -0
- package/types/server.d.ts +291 -0
- package/url/index.cjs +201 -0
- package/url/index.d.ts +25 -0
- package/url/index.mjs +189 -0
- package/url/url.utils.d.ts +164 -0
- package/validate/index.cjs +212 -0
- package/validate/index.d.ts +25 -0
- package/validate/index.mjs +188 -0
- package/validate/validate.utils.d.ts +200 -0
- package/build/index.cjs +0 -7579
- package/build/index.d.ts +0 -5774
- package/build/index.mjs +0 -7274
|
@@ -0,0 +1,210 @@
|
|
|
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 from 'pino';
|
|
26
|
+
import type { Logger as PinoLogger } from 'pino';
|
|
27
|
+
/**
|
|
28
|
+
* Logger type for application-wide logging.
|
|
29
|
+
*/
|
|
30
|
+
export type Logger = PinoLogger;
|
|
31
|
+
/**
|
|
32
|
+
* Logger levels for application-wide logging.
|
|
33
|
+
*/
|
|
34
|
+
export type LoggerLevels = pino.Level;
|
|
35
|
+
export 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
|
+
export 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
|
+
export 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
|
+
export 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
|
+
export 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
|
+
export 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
|
+
export 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
|
+
export declare function addSensitiveFields(fields: string[]): void;
|
|
153
|
+
/**
|
|
154
|
+
* Use an object compatible with either modern or legacy global scopes.
|
|
155
|
+
*/
|
|
156
|
+
export 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
|
+
export declare function getLogger(newInstance?: boolean): PinoLogger;
|
|
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
|
+
export declare function createChildLogger(bindings: Record<string, any>, parentLogger?: PinoLogger): PinoLogger;
|
|
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
|
+
export declare function createRequestLogger(requestId: string, additionalContext?: Record<string, any>): PinoLogger;
|
|
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
|
+
export 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
|
+
export 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
|
+
export 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
|
+
export declare function generateDeepPaths(field: string, depth: number): string[];
|
|
@@ -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;
|
|
@@ -0,0 +1,25 @@
|
|
|
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
|
+
export * from './middleware.utils';
|
|
@@ -0,0 +1,170 @@
|
|
|
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 { uuid } from '@catbee/utils/id';
|
|
26
|
+
import { HttpStatusCodes } from '@catbee/utils/http-status-codes';
|
|
27
|
+
import { ErrorResponse, createFinalErrorResponse } from '@catbee/utils/response';
|
|
28
|
+
import { getLogger } from '@catbee/utils/logger';
|
|
29
|
+
import { ContextStore, StoreKeys } from '@catbee/utils/context-store';
|
|
30
|
+
import { RequestTimeoutException } from '@catbee/utils/exception';
|
|
31
|
+
|
|
32
|
+
var __defProp = Object.defineProperty;
|
|
33
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
34
|
+
function requestId(options) {
|
|
35
|
+
const headerName = options?.headerName || "X-Request-ID";
|
|
36
|
+
const exposeHeader = options?.exposeHeader !== false;
|
|
37
|
+
const generateId = options?.generator || uuid;
|
|
38
|
+
return (req, res, next) => {
|
|
39
|
+
const existingId = req.headers[headerName.toLowerCase()];
|
|
40
|
+
const id = existingId || generateId();
|
|
41
|
+
req.id = id;
|
|
42
|
+
if (exposeHeader) {
|
|
43
|
+
res.setHeader(headerName, id);
|
|
44
|
+
}
|
|
45
|
+
next();
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
__name(requestId, "requestId");
|
|
49
|
+
function responseTime(options) {
|
|
50
|
+
const addHeader = options?.addHeader !== false;
|
|
51
|
+
const logOnComplete = options?.logOnComplete === true;
|
|
52
|
+
return (req, res, next) => {
|
|
53
|
+
const start = process.hrtime();
|
|
54
|
+
const getDuration = /* @__PURE__ */ __name(() => {
|
|
55
|
+
const diff = process.hrtime(start);
|
|
56
|
+
return (diff[0] * 1e3 + diff[1] * 1e-6).toFixed(2);
|
|
57
|
+
}, "getDuration");
|
|
58
|
+
if (addHeader) {
|
|
59
|
+
const originalWriteHead = res.writeHead;
|
|
60
|
+
res.writeHead = function(...args) {
|
|
61
|
+
res.setHeader("X-Response-Time", `${getDuration()}ms`);
|
|
62
|
+
return originalWriteHead.apply(this, args);
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
if (logOnComplete) {
|
|
66
|
+
res.on("finish", () => {
|
|
67
|
+
getLogger().info(`${req.method} ${req.url} - ${getDuration()}ms`);
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
next();
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
__name(responseTime, "responseTime");
|
|
74
|
+
function timeout(timeoutMs = 3e4) {
|
|
75
|
+
return (_req, res, next) => {
|
|
76
|
+
const timer = setTimeout(() => {
|
|
77
|
+
const response = new RequestTimeoutException("Request timed out");
|
|
78
|
+
res.status(HttpStatusCodes.REQUEST_TIMEOUT).json(response);
|
|
79
|
+
}, timeoutMs);
|
|
80
|
+
res.on("finish", () => {
|
|
81
|
+
clearTimeout(timer);
|
|
82
|
+
});
|
|
83
|
+
next();
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
__name(timeout, "timeout");
|
|
87
|
+
function setupRequestContext(options = {}) {
|
|
88
|
+
const { headerName = "x-request-id", autoLog = true } = options;
|
|
89
|
+
return (req, _res, next) => {
|
|
90
|
+
const requestId2 = req.headers[headerName] || req?.["id"] || uuid();
|
|
91
|
+
ContextStore.run({
|
|
92
|
+
[StoreKeys.REQUEST_ID]: requestId2
|
|
93
|
+
}, () => {
|
|
94
|
+
const childLogger = getLogger().child({
|
|
95
|
+
requestId: requestId2,
|
|
96
|
+
method: req.method,
|
|
97
|
+
url: req.originalUrl || req.url
|
|
98
|
+
});
|
|
99
|
+
req.logger = childLogger;
|
|
100
|
+
ContextStore.set(StoreKeys.LOGGER, childLogger);
|
|
101
|
+
if (autoLog) {
|
|
102
|
+
req.logger.info("Request context initialized");
|
|
103
|
+
}
|
|
104
|
+
next();
|
|
105
|
+
});
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
__name(setupRequestContext, "setupRequestContext");
|
|
109
|
+
function errorHandler(options) {
|
|
110
|
+
const logErrors = options?.logErrors !== false;
|
|
111
|
+
const includeDetails = options?.includeDetails === true;
|
|
112
|
+
return (err, req, res, _next) => {
|
|
113
|
+
const status = err?.status || err?.statusCode || HttpStatusCodes.INTERNAL_SERVER_ERROR;
|
|
114
|
+
if (logErrors) {
|
|
115
|
+
getLogger().error({
|
|
116
|
+
err
|
|
117
|
+
}, `${err.message || "Unknown error"}`);
|
|
118
|
+
}
|
|
119
|
+
if (err instanceof ErrorResponse) {
|
|
120
|
+
const result = {
|
|
121
|
+
error: true,
|
|
122
|
+
message: err.message,
|
|
123
|
+
timestamp: err.timestamp,
|
|
124
|
+
requestId: err?.requestId || req?.id || uuid(),
|
|
125
|
+
status,
|
|
126
|
+
path: req.originalUrl || req.url
|
|
127
|
+
};
|
|
128
|
+
if (includeDetails && err?.stack) {
|
|
129
|
+
result.stack = err.stack.split("\n").map((line) => line.trim());
|
|
130
|
+
}
|
|
131
|
+
return res.status(status).json(result);
|
|
132
|
+
}
|
|
133
|
+
return res.status(status).json(createFinalErrorResponse(req, status, err?.message || "Internal Server Error", err, {
|
|
134
|
+
includeDetails
|
|
135
|
+
}));
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
__name(errorHandler, "errorHandler");
|
|
139
|
+
function healthCheck(options) {
|
|
140
|
+
const path = options?.path || "/healthz";
|
|
141
|
+
const checks = options?.checks || [];
|
|
142
|
+
const detailed = options?.detailed !== false;
|
|
143
|
+
return async (req, res, next) => {
|
|
144
|
+
if (req.path !== path) return next();
|
|
145
|
+
const results = {};
|
|
146
|
+
let allHealthy = true;
|
|
147
|
+
for (const check of checks) {
|
|
148
|
+
try {
|
|
149
|
+
const result = await Promise.resolve(check.check());
|
|
150
|
+
results[check.name] = !!result;
|
|
151
|
+
if (!result) allHealthy = false;
|
|
152
|
+
} catch {
|
|
153
|
+
results[check.name] = false;
|
|
154
|
+
allHealthy = false;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
const status = allHealthy ? HttpStatusCodes.OK : HttpStatusCodes.SERVICE_UNAVAILABLE;
|
|
158
|
+
const response = detailed ? {
|
|
159
|
+
status: allHealthy ? "ok" : "unhealthy",
|
|
160
|
+
checks: results,
|
|
161
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
162
|
+
} : {
|
|
163
|
+
status: allHealthy ? "ok" : "unhealthy"
|
|
164
|
+
};
|
|
165
|
+
res.status(status).json(response);
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
__name(healthCheck, "healthCheck");
|
|
169
|
+
|
|
170
|
+
export { errorHandler, healthCheck, requestId, responseTime, setupRequestContext, timeout };
|