@catbee/utils 0.0.4 → 0.0.6
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 +21 -201
- package/README.md +911 -242
- package/build/esm/config.d.ts +108 -8
- package/build/esm/config.js +122 -6
- package/build/esm/config.js.map +1 -1
- package/build/esm/index.d.ts +6 -0
- package/build/esm/index.js +29 -0
- package/build/esm/index.js.map +1 -1
- package/build/esm/servers/server.builder.d.ts +625 -0
- package/build/esm/servers/server.builder.js +722 -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 +1211 -0
- package/build/esm/servers/server.js.map +1 -0
- package/build/esm/types/api-response.d.ts +5 -7
- package/build/esm/types/api-response.js +23 -0
- package/build/esm/types/api-response.js.map +1 -1
- 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 +285 -0
- package/build/esm/types/server.js +25 -0
- package/build/esm/types/server.js.map +1 -0
- package/build/esm/utils/array.utils.js +23 -0
- package/build/esm/utils/array.utils.js.map +1 -1
- package/build/esm/utils/async.utils.js +23 -0
- package/build/esm/utils/async.utils.js.map +1 -1
- package/build/esm/utils/cache.utils.js +39 -16
- package/build/esm/utils/cache.utils.js.map +1 -1
- package/build/esm/utils/context-store.utils.d.ts +1 -1
- package/build/esm/utils/context-store.utils.js +24 -1
- package/build/esm/utils/context-store.utils.js.map +1 -1
- package/build/esm/utils/crypto.utils.js +26 -2
- package/build/esm/utils/crypto.utils.js.map +1 -1
- package/build/esm/utils/decorators.utils.d.ts +291 -0
- package/build/esm/utils/decorators.utils.js +395 -41
- package/build/esm/utils/decorators.utils.js.map +1 -1
- package/build/esm/utils/dir.utils.js +23 -0
- package/build/esm/utils/dir.utils.js.map +1 -1
- package/build/esm/utils/env.utils.d.ts +186 -23
- package/build/esm/utils/env.utils.js +517 -91
- package/build/esm/utils/env.utils.js.map +1 -1
- package/build/esm/utils/exception.utils.js +31 -8
- package/build/esm/utils/exception.utils.js.map +1 -1
- package/build/esm/utils/fs.utils.js +23 -0
- package/build/esm/utils/fs.utils.js.map +1 -1
- package/build/esm/utils/http-status-codes.js +23 -0
- package/build/esm/utils/http-status-codes.js.map +1 -1
- package/build/esm/utils/id.utils.js +23 -0
- package/build/esm/utils/id.utils.js.map +1 -1
- package/build/esm/utils/logger.utils.d.ts +118 -0
- package/build/esm/utils/logger.utils.js +251 -15
- package/build/esm/utils/logger.utils.js.map +1 -1
- package/build/esm/utils/middleware.utils.d.ts +29 -7
- package/build/esm/utils/middleware.utils.js +81 -55
- package/build/esm/utils/middleware.utils.js.map +1 -1
- package/build/esm/utils/obj.utils.d.ts +10 -3
- package/build/esm/utils/obj.utils.js +225 -15
- package/build/esm/utils/obj.utils.js.map +1 -1
- package/build/esm/utils/request.utils.d.ts +77 -0
- package/build/esm/utils/request.utils.js +196 -0
- package/build/esm/utils/request.utils.js.map +1 -0
- package/build/esm/utils/response.utils.d.ts +15 -1
- package/build/esm/utils/response.utils.js +55 -4
- package/build/esm/utils/response.utils.js.map +1 -1
- package/build/esm/utils/string.utils.js +23 -0
- package/build/esm/utils/string.utils.js.map +1 -1
- package/build/esm/utils/url.utils.js +23 -0
- package/build/esm/utils/url.utils.js.map +1 -1
- package/build/esm/utils/validate.utils.d.ts +7 -0
- package/build/esm/utils/validate.utils.js +35 -2
- package/build/esm/utils/validate.utils.js.map +1 -1
- package/build/esnext/config.d.ts +108 -8
- package/build/esnext/config.js +122 -6
- package/build/esnext/config.js.map +1 -1
- package/build/esnext/index.d.ts +6 -0
- package/build/esnext/index.js +29 -0
- package/build/esnext/index.js.map +1 -1
- package/build/esnext/servers/server.builder.d.ts +625 -0
- package/build/esnext/servers/server.builder.js +677 -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 +918 -0
- package/build/esnext/servers/server.js.map +1 -0
- package/build/esnext/types/api-response.d.ts +5 -7
- package/build/esnext/types/api-response.js +23 -0
- package/build/esnext/types/api-response.js.map +1 -1
- 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 +285 -0
- package/build/esnext/types/server.js +25 -0
- package/build/esnext/types/server.js.map +1 -0
- package/build/esnext/utils/array.utils.js +23 -0
- package/build/esnext/utils/array.utils.js.map +1 -1
- package/build/esnext/utils/async.utils.js +23 -0
- package/build/esnext/utils/async.utils.js.map +1 -1
- package/build/esnext/utils/cache.utils.js +39 -16
- package/build/esnext/utils/cache.utils.js.map +1 -1
- package/build/esnext/utils/context-store.utils.d.ts +1 -1
- package/build/esnext/utils/context-store.utils.js +24 -1
- package/build/esnext/utils/context-store.utils.js.map +1 -1
- package/build/esnext/utils/crypto.utils.js +26 -2
- package/build/esnext/utils/crypto.utils.js.map +1 -1
- package/build/esnext/utils/decorators.utils.d.ts +291 -0
- package/build/esnext/utils/decorators.utils.js +371 -22
- package/build/esnext/utils/decorators.utils.js.map +1 -1
- package/build/esnext/utils/dir.utils.js +23 -0
- package/build/esnext/utils/dir.utils.js.map +1 -1
- package/build/esnext/utils/env.utils.d.ts +186 -23
- package/build/esnext/utils/env.utils.js +468 -77
- package/build/esnext/utils/env.utils.js.map +1 -1
- package/build/esnext/utils/exception.utils.js +30 -7
- package/build/esnext/utils/exception.utils.js.map +1 -1
- package/build/esnext/utils/fs.utils.js +23 -0
- package/build/esnext/utils/fs.utils.js.map +1 -1
- package/build/esnext/utils/http-status-codes.js +23 -0
- package/build/esnext/utils/http-status-codes.js.map +1 -1
- package/build/esnext/utils/id.utils.js +23 -0
- package/build/esnext/utils/id.utils.js.map +1 -1
- package/build/esnext/utils/logger.utils.d.ts +118 -0
- package/build/esnext/utils/logger.utils.js +222 -15
- package/build/esnext/utils/logger.utils.js.map +1 -1
- package/build/esnext/utils/middleware.utils.d.ts +29 -7
- package/build/esnext/utils/middleware.utils.js +77 -55
- package/build/esnext/utils/middleware.utils.js.map +1 -1
- package/build/esnext/utils/obj.utils.d.ts +10 -3
- package/build/esnext/utils/obj.utils.js +176 -12
- package/build/esnext/utils/obj.utils.js.map +1 -1
- package/build/esnext/utils/request.utils.d.ts +77 -0
- package/build/esnext/utils/request.utils.js +168 -0
- package/build/esnext/utils/request.utils.js.map +1 -0
- package/build/esnext/utils/response.utils.d.ts +15 -1
- package/build/esnext/utils/response.utils.js +55 -4
- package/build/esnext/utils/response.utils.js.map +1 -1
- package/build/esnext/utils/string.utils.js +23 -0
- package/build/esnext/utils/string.utils.js.map +1 -1
- package/build/esnext/utils/url.utils.js +23 -0
- package/build/esnext/utils/url.utils.js.map +1 -1
- package/build/esnext/utils/validate.utils.d.ts +7 -0
- package/build/esnext/utils/validate.utils.js +33 -0
- package/build/esnext/utils/validate.utils.js.map +1 -1
- package/build/src/config.d.ts +108 -8
- package/build/src/config.js +125 -7
- package/build/src/config.js.map +1 -1
- package/build/src/index.d.ts +6 -0
- package/build/src/index.js +32 -0
- package/build/src/index.js.map +1 -1
- package/build/src/servers/server.builder.d.ts +625 -0
- package/build/src/servers/server.builder.js +681 -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 +958 -0
- package/build/src/servers/server.js.map +1 -0
- package/build/src/types/api-response.d.ts +5 -7
- package/build/src/types/api-response.js +23 -0
- package/build/src/types/api-response.js.map +1 -1
- 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 +285 -0
- package/build/src/types/server.js +26 -0
- package/build/src/types/server.js.map +1 -0
- package/build/src/utils/array.utils.js +23 -0
- package/build/src/utils/array.utils.js.map +1 -1
- package/build/src/utils/async.utils.js +23 -0
- package/build/src/utils/async.utils.js.map +1 -1
- package/build/src/utils/cache.utils.js +38 -15
- package/build/src/utils/cache.utils.js.map +1 -1
- package/build/src/utils/context-store.utils.d.ts +1 -1
- package/build/src/utils/context-store.utils.js +24 -1
- package/build/src/utils/context-store.utils.js.map +1 -1
- package/build/src/utils/crypto.utils.js +25 -1
- package/build/src/utils/crypto.utils.js.map +1 -1
- package/build/src/utils/decorators.utils.d.ts +291 -0
- package/build/src/utils/decorators.utils.js +373 -22
- package/build/src/utils/decorators.utils.js.map +1 -1
- package/build/src/utils/dir.utils.js +23 -0
- package/build/src/utils/dir.utils.js.map +1 -1
- package/build/src/utils/env.utils.d.ts +186 -23
- package/build/src/utils/env.utils.js +467 -76
- package/build/src/utils/env.utils.js.map +1 -1
- package/build/src/utils/exception.utils.js +30 -7
- package/build/src/utils/exception.utils.js.map +1 -1
- package/build/src/utils/fs.utils.js +23 -0
- package/build/src/utils/fs.utils.js.map +1 -1
- package/build/src/utils/http-status-codes.js +23 -0
- package/build/src/utils/http-status-codes.js.map +1 -1
- package/build/src/utils/id.utils.js +23 -0
- package/build/src/utils/id.utils.js.map +1 -1
- package/build/src/utils/logger.utils.d.ts +118 -0
- package/build/src/utils/logger.utils.js +228 -15
- package/build/src/utils/logger.utils.js.map +1 -1
- package/build/src/utils/middleware.utils.d.ts +29 -7
- package/build/src/utils/middleware.utils.js +76 -54
- package/build/src/utils/middleware.utils.js.map +1 -1
- package/build/src/utils/obj.utils.d.ts +10 -3
- package/build/src/utils/obj.utils.js +177 -12
- package/build/src/utils/obj.utils.js.map +1 -1
- package/build/src/utils/request.utils.d.ts +77 -0
- package/build/src/utils/request.utils.js +175 -0
- package/build/src/utils/request.utils.js.map +1 -0
- package/build/src/utils/response.utils.d.ts +15 -1
- package/build/src/utils/response.utils.js +56 -4
- package/build/src/utils/response.utils.js.map +1 -1
- package/build/src/utils/string.utils.js +23 -0
- package/build/src/utils/string.utils.js.map +1 -1
- package/build/src/utils/url.utils.js +23 -0
- package/build/src/utils/url.utils.js.map +1 -1
- package/build/src/utils/validate.utils.d.ts +7 -0
- package/build/src/utils/validate.utils.js +36 -2
- package/build/src/utils/validate.utils.js.map +1 -1
- package/package.json +40 -9
|
@@ -1,11 +1,32 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
/*
|
|
2
|
+
* The MIT License
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) 2025 Catbee Technologies
|
|
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
|
+
*/
|
|
3
24
|
import { uuid } from './id.utils';
|
|
4
25
|
import { HttpStatusCodes } from './http-status-codes';
|
|
5
|
-
import { ErrorResponse } from './response.utils';
|
|
6
|
-
import { Env } from './env.utils';
|
|
26
|
+
import { createFinalErrorResponse, ErrorResponse } from './response.utils';
|
|
7
27
|
import { getLogger } from './logger.utils';
|
|
8
28
|
import { ContextStore, StoreKeys } from './context-store.utils';
|
|
29
|
+
import { RequestTimeoutException } from './exception.utils';
|
|
9
30
|
/**
|
|
10
31
|
* Attaches a unique request ID to each request.
|
|
11
32
|
* Useful for request tracing and correlation between logs.
|
|
@@ -13,15 +34,17 @@ import { ContextStore, StoreKeys } from './context-store.utils';
|
|
|
13
34
|
* @param {object} [options] - Configuration options
|
|
14
35
|
* @param {string} [options.headerName='X-Request-ID'] - Header name for request ID
|
|
15
36
|
* @param {boolean} [options.exposeHeader=true] - Whether to expose the header in response
|
|
37
|
+
* @param {() => string} [options.generator] - Custom ID generator function
|
|
16
38
|
* @returns {Middleware} Express-compatible middleware
|
|
17
39
|
*/
|
|
18
40
|
export function requestId(options) {
|
|
19
41
|
var headerName = (options === null || options === void 0 ? void 0 : options.headerName) || 'X-Request-ID';
|
|
20
42
|
var exposeHeader = (options === null || options === void 0 ? void 0 : options.exposeHeader) !== false;
|
|
43
|
+
var generateId = (options === null || options === void 0 ? void 0 : options.generator) || uuid;
|
|
21
44
|
return function (req, res, next) {
|
|
22
45
|
// Use existing request ID from header or generate a new one
|
|
23
46
|
var existingId = req.headers[headerName.toLowerCase()];
|
|
24
|
-
var id = existingId ||
|
|
47
|
+
var id = existingId || generateId();
|
|
25
48
|
// Attach ID to request object
|
|
26
49
|
req.id = id;
|
|
27
50
|
// Add ID to response headers
|
|
@@ -44,21 +67,26 @@ export function responseTime(options) {
|
|
|
44
67
|
var logOnComplete = (options === null || options === void 0 ? void 0 : options.logOnComplete) === true;
|
|
45
68
|
return function (req, res, next) {
|
|
46
69
|
var start = process.hrtime();
|
|
70
|
+
// Function to calculate duration
|
|
71
|
+
var getDuration = function () {
|
|
72
|
+
var diff = process.hrtime(start);
|
|
73
|
+
return (diff[0] * 1e3 + diff[1] * 1e-6).toFixed(2);
|
|
74
|
+
};
|
|
47
75
|
if (addHeader) {
|
|
48
|
-
//
|
|
49
|
-
var
|
|
50
|
-
res.
|
|
51
|
-
var
|
|
52
|
-
var
|
|
53
|
-
|
|
54
|
-
|
|
76
|
+
// Ensure header is set before response is sent
|
|
77
|
+
var originalWriteHead_1 = res.writeHead;
|
|
78
|
+
res.writeHead = function () {
|
|
79
|
+
var args = [];
|
|
80
|
+
for (var _i = 0; _i < arguments.length; _i++) {
|
|
81
|
+
args[_i] = arguments[_i];
|
|
82
|
+
}
|
|
83
|
+
res.setHeader('X-Response-Time', "".concat(getDuration(), "ms"));
|
|
84
|
+
return originalWriteHead_1.apply(this, args);
|
|
55
85
|
};
|
|
56
86
|
}
|
|
57
87
|
if (logOnComplete) {
|
|
58
88
|
res.on('finish', function () {
|
|
59
|
-
|
|
60
|
-
var duration = diff[0] * 1e3 + diff[1] * 1e-6;
|
|
61
|
-
getLogger().info("".concat(req.method, " ").concat(req.url, " - ").concat(duration.toFixed(2), "ms"));
|
|
89
|
+
getLogger().info("".concat(req.method, " ").concat(req.url, " - ").concat(getDuration(), "ms"));
|
|
62
90
|
});
|
|
63
91
|
}
|
|
64
92
|
next();
|
|
@@ -72,16 +100,12 @@ export function responseTime(options) {
|
|
|
72
100
|
* @returns {Middleware} Express-compatible middleware
|
|
73
101
|
*/
|
|
74
102
|
export function timeout(timeoutMs) {
|
|
75
|
-
if (timeoutMs === void 0) { timeoutMs =
|
|
76
|
-
return function (
|
|
103
|
+
if (timeoutMs === void 0) { timeoutMs = 30000; }
|
|
104
|
+
return function (_req, res, next) {
|
|
77
105
|
// Set timeout for the request
|
|
78
106
|
var timer = setTimeout(function () {
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
message: 'Request timeout',
|
|
82
|
-
status: 408,
|
|
83
|
-
timestamp: new Date().toISOString()
|
|
84
|
-
});
|
|
107
|
+
var response = new RequestTimeoutException('Request timed out');
|
|
108
|
+
res.status(HttpStatusCodes.REQUEST_TIMEOUT).json(response);
|
|
85
109
|
}, timeoutMs);
|
|
86
110
|
// Clear timeout when response is sent
|
|
87
111
|
res.on('finish', function () {
|
|
@@ -104,11 +128,11 @@ export function setupRequestContext(options) {
|
|
|
104
128
|
return function (req, _res, next) {
|
|
105
129
|
var _a;
|
|
106
130
|
// Generate or use existing request ID
|
|
107
|
-
var requestId = req.headers[headerName] || (req === null || req === void 0 ? void 0 : req['id']) ||
|
|
131
|
+
var requestId = req.headers[headerName] || (req === null || req === void 0 ? void 0 : req['id']) || uuid();
|
|
108
132
|
ContextStore.run((_a = {}, _a[StoreKeys.REQUEST_ID] = requestId, _a), function () {
|
|
109
133
|
// Create a child logger for this request
|
|
110
134
|
var childLogger = getLogger().child({
|
|
111
|
-
|
|
135
|
+
requestId: requestId,
|
|
112
136
|
method: req.method,
|
|
113
137
|
url: req.originalUrl || req.url
|
|
114
138
|
});
|
|
@@ -124,11 +148,28 @@ export function setupRequestContext(options) {
|
|
|
124
148
|
/**
|
|
125
149
|
* Global error handling middleware with enhanced features.
|
|
126
150
|
*
|
|
127
|
-
* @param {
|
|
151
|
+
* @param {ErrorHandlerOptions} options - Error handler options
|
|
128
152
|
* @param {boolean} [options.logErrors=true] - Whether to log errors
|
|
129
153
|
* @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production
|
|
130
|
-
* @
|
|
131
|
-
*
|
|
154
|
+
* @returns Error middleware
|
|
155
|
+
*
|
|
156
|
+
* @example
|
|
157
|
+
* import express from 'express';
|
|
158
|
+
* import { errorHandler } from '@catbee/utils';
|
|
159
|
+
*
|
|
160
|
+
* const app = express();
|
|
161
|
+
*
|
|
162
|
+
* // Your routes
|
|
163
|
+
* app.get('/ping', (req, res) => {
|
|
164
|
+
* throw new Error('Something went wrong');
|
|
165
|
+
* });
|
|
166
|
+
*
|
|
167
|
+
* // Error handler (must be last middleware)
|
|
168
|
+
* app.use(errorHandler({ includeDetails: true }));
|
|
169
|
+
*
|
|
170
|
+
* app.listen(3000, () => {
|
|
171
|
+
* console.log('Server running on port 3000');
|
|
172
|
+
* });
|
|
132
173
|
*/
|
|
133
174
|
export function errorHandler(options) {
|
|
134
175
|
var logErrors = (options === null || options === void 0 ? void 0 : options.logErrors) !== false;
|
|
@@ -138,42 +179,27 @@ export function errorHandler(options) {
|
|
|
138
179
|
var status = (err === null || err === void 0 ? void 0 : err.status) || (err === null || err === void 0 ? void 0 : err.statusCode) || HttpStatusCodes.INTERNAL_SERVER_ERROR;
|
|
139
180
|
// Log error if enabled
|
|
140
181
|
if (logErrors) {
|
|
141
|
-
getLogger().error({
|
|
182
|
+
getLogger().error({ err: err }, "".concat(err.message || 'Unknown error'));
|
|
142
183
|
}
|
|
143
184
|
// Handle ErrorResponse instances (our custom error class)
|
|
144
185
|
if (err instanceof ErrorResponse) {
|
|
145
|
-
|
|
146
|
-
error:
|
|
186
|
+
var result = {
|
|
187
|
+
error: true,
|
|
147
188
|
message: err.message,
|
|
148
189
|
timestamp: err.timestamp,
|
|
149
|
-
requestId: err.requestId || req.id || uuid(),
|
|
150
|
-
|
|
151
|
-
});
|
|
152
|
-
}
|
|
153
|
-
var createErrorResponse = function (message, req, error, options) {
|
|
154
|
-
var isDev = Env.isDev();
|
|
155
|
-
var includeDetails = (options === null || options === void 0 ? void 0 : options.includeDetails) && isDev;
|
|
156
|
-
var response = {
|
|
157
|
-
error: true,
|
|
158
|
-
message: message,
|
|
159
|
-
timestamp: new Date().toISOString(),
|
|
160
|
-
requestId: (error === null || error === void 0 ? void 0 : error.requestId) || req.id || uuid(),
|
|
190
|
+
requestId: (err === null || err === void 0 ? void 0 : err.requestId) || (req === null || req === void 0 ? void 0 : req.id) || uuid(),
|
|
191
|
+
status: status,
|
|
161
192
|
path: req.originalUrl || req.url
|
|
162
193
|
};
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
response.code = error.code;
|
|
166
|
-
}
|
|
167
|
-
// Include stack trace in development mode if requested
|
|
168
|
-
if (includeDetails && (error === null || error === void 0 ? void 0 : error.stack)) {
|
|
169
|
-
response.stack = error.stack.split('\n').map(function (line) { return line.trim(); });
|
|
194
|
+
if (includeDetails && (err === null || err === void 0 ? void 0 : err.stack)) {
|
|
195
|
+
result.stack = err.stack.split('\n').map(function (line) { return line.trim(); });
|
|
170
196
|
}
|
|
171
|
-
return
|
|
172
|
-
}
|
|
197
|
+
return res.status(status).json(result);
|
|
198
|
+
}
|
|
173
199
|
// Handle any other errors
|
|
174
|
-
return res
|
|
175
|
-
|
|
176
|
-
|
|
200
|
+
return res
|
|
201
|
+
.status(status)
|
|
202
|
+
.json(createFinalErrorResponse(req, status, (err === null || err === void 0 ? void 0 : err.message) || 'Internal Server Error', err, { includeDetails: includeDetails }));
|
|
177
203
|
};
|
|
178
204
|
}
|
|
179
205
|
//# sourceMappingURL=middleware.utils.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"middleware.utils.js","sourceRoot":"","sources":["../../../src/utils/middleware.utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AACpC,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACnC,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAClC,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAClC,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAE3C,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAIhE;;;;;;;;GAQG;AACH,MAAM,UAAU,SAAS,CAAC,OAAyD;IACjF,IAAM,UAAU,GAAG,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,UAAU,KAAI,cAAc,CAAC;IACzD,IAAM,YAAY,GAAG,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,YAAY,MAAK,KAAK,CAAC;IAErD,OAAO,UAAC,GAAG,EAAE,GAAG,EAAE,IAAI;QACpB,4DAA4D;QAC5D,IAAM,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,CAAC,GAAG;aACjC,CAAC;YAEF,gCAAgC;YAChC,IAAI,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,IAAI,EAAE,CAAC;gBAChB,QAAQ,CAAC,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC;YAC7B,CAAC;YAED,uDAAuD;YACvD,IAAI,cAAc,KAAI,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,KAAK,CAAA,EAAE,CAAC;gBACnC,QAAQ,CAAC,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,UAAC,IAAY,IAAK,OAAA,IAAI,CAAC,IAAI,EAAE,EAAX,CAAW,CAAC,CAAC;YAC9E,CAAC;YAED,OAAO,QAAQ,CAAC;QAClB,CAAC,CAAC;QAEF,0BAA0B;QAC1B,OAAO,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAC5B,mBAAmB,CAAC,CAAA,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,OAAO,KAAI,uBAAuB,EAAE,GAAG,EAAE,GAAG,EAAE;YACrE,cAAc,gBAAA;SACf,CAAC,CACH,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { randomUUID } from 'crypto';\nimport { Config } from '../config';\nimport { uuid } from './id.utils';\nimport { HttpStatusCodes } from './http-status-codes';\nimport { ErrorResponse } from './response.utils';\nimport { Env } from './env.utils';\nimport { getLogger } from './logger.utils';\nimport type { Request, Response, NextFunction } from 'express';\nimport { ContextStore, StoreKeys } from './context-store.utils';\n\nexport type Middleware = (req: Request, res: Response, next: NextFunction) => void | Promise<void>;\n\n/**\n * Attaches a unique request ID to each request.\n * Useful for request tracing and correlation between logs.\n *\n * @param {object} [options] - Configuration options\n * @param {string} [options.headerName='X-Request-ID'] - Header name for request ID\n * @param {boolean} [options.exposeHeader=true] - Whether to expose the header in response\n * @returns {Middleware} Express-compatible middleware\n */\nexport function requestId(options?: { headerName?: string; exposeHeader?: boolean }): Middleware {\n const headerName = options?.headerName || 'X-Request-ID';\n const exposeHeader = options?.exposeHeader !== false;\n\n return (req, res, next) => {\n // Use existing request ID from header or generate a new one\n const existingId = req.headers[headerName.toLowerCase()];\n const id = (existingId as string) || randomUUID();\n\n // Attach ID to request object\n (req as any).id = id;\n\n // Add ID to response headers\n if (exposeHeader) {\n res.setHeader(headerName, id);\n }\n\n next();\n };\n}\n\n/**\n * Measures request processing time and logs or adds it to response headers.\n *\n * @param {object} [options] - Configuration options\n * @param {boolean} [options.addHeader=true] - Whether to add X-Response-Time header\n * @param {boolean} [options.logOnComplete=false] - Whether to log timing info\n * @returns {Middleware} Express-compatible middleware\n */\nexport function responseTime(options?: { addHeader?: boolean; logOnComplete?: boolean }) {\n const addHeader = options?.addHeader !== false;\n const logOnComplete = options?.logOnComplete === true;\n\n return (req: Request, res: Response, next: NextFunction) => {\n const start = process.hrtime();\n\n if (addHeader) {\n // Wrap res.end to set header just before sending response\n const originalEnd = res.end;\n res.end = function (chunk?: any, encoding?: any, cb?: any) {\n const diff = process.hrtime(start);\n const duration = diff[0] * 1e3 + diff[1] * 1e-6;\n res.setHeader('X-Response-Time', `${duration.toFixed(2)}ms`);\n return originalEnd.call(this, chunk, encoding, cb);\n };\n }\n\n if (logOnComplete) {\n res.on('finish', () => {\n const diff = process.hrtime(start);\n const duration = diff[0] * 1e3 + diff[1] * 1e-6;\n getLogger().info(`${req.method} ${req.url} - ${duration.toFixed(2)}ms`);\n });\n }\n\n next();\n };\n}\n\n/**\n * Request timeout middleware.\n * Aborts requests that take too long to process.\n *\n * @param {number} [timeoutMs=30000] - Timeout in milliseconds\n * @returns {Middleware} Express-compatible middleware\n */\nexport function timeout(timeoutMs: number = Config.Http.timeout): Middleware {\n return (req, res, next) => {\n // Set timeout for the request\n const timer = setTimeout(() => {\n res.status(408).json({\n error: true,\n message: 'Request timeout',\n status: 408,\n timestamp: new Date().toISOString()\n });\n }, timeoutMs);\n\n // Clear timeout when response is sent\n res.on('finish', () => {\n clearTimeout(timer);\n });\n\n next();\n };\n}\n\n/**\n * Creates an Express middleware that initializes a per-request context.\n *\n * @param {object} [options] - Optional configuration\n * @param {string} [options.headerName='x-request-id'] - Header to look for request ID\n * @param {boolean} [options.autoLog=true] - Whether to log automatically when context is initialized\n * @returns {(req: Request, res: Response, next: NextFunction) => void} Express middleware function\n */\nexport function setupRequestContext(options: { headerName?: string; autoLog?: boolean } = {}): Middleware {\n const { headerName = 'x-request-id', autoLog = true } = options;\n return (req, _res, next) => {\n // Generate or use existing request ID\n const requestId = (req.headers[headerName] as string) || req?.['id'] || crypto.randomUUID();\n\n ContextStore.run({ [StoreKeys.REQUEST_ID]: requestId }, () => {\n // Create a child logger for this request\n const childLogger = getLogger().child({\n reqId: requestId,\n method: req.method,\n url: req.originalUrl || req.url\n });\n\n // Store logger in context\n ContextStore.set(StoreKeys.LOGGER, childLogger);\n\n if (autoLog) {\n childLogger.info('Request context initialized');\n }\n\n next();\n });\n };\n}\n\n/**\n * Global error handling middleware with enhanced features.\n *\n * @param {object} [options] - Error handler options\n * @param {boolean} [options.logErrors=true] - Whether to log errors\n * @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production\n * @param {Function} [options.logger=getLogger().error] - Custom logging function\n * @returns {(err: any, req: Request, res: Response, next: NextFunction) => void} Error middleware\n */\nexport function errorHandler(options?: { logErrors?: boolean; includeDetails?: boolean }) {\n const logErrors = options?.logErrors !== false;\n const includeDetails = options?.includeDetails === true;\n\n return (err: any, req: Request, res: Response, _next: NextFunction) => {\n // Determine status code\n const status = err?.status || err?.statusCode || HttpStatusCodes.INTERNAL_SERVER_ERROR;\n\n // Log error if enabled\n if (logErrors) {\n getLogger().error({ error: err }, `${err.message || 'Unknown error'}`);\n }\n\n // Handle ErrorResponse instances (our custom error class)\n if (err instanceof ErrorResponse) {\n return res.status(status).json({\n error: err.error,\n message: err.message,\n timestamp: err.timestamp,\n requestId: err.requestId || (req as any).id || uuid(),\n path: req.originalUrl || req.url\n });\n }\n\n const createErrorResponse = (message: string, req: Request, error: any, options?: { includeDetails?: boolean }) => {\n const isDev = Env.isDev();\n const includeDetails = options?.includeDetails && isDev;\n\n const response: Record<string, any> = {\n error: true,\n message,\n timestamp: new Date().toISOString(),\n requestId: error?.requestId || (req as any).id || uuid(),\n path: req.originalUrl || req.url\n };\n\n // Include error code if present\n if (error?.code) {\n response.code = error.code;\n }\n\n // Include stack trace in development mode if requested\n if (includeDetails && error?.stack) {\n response.stack = error.stack.split('\\n').map((line: string) => line.trim());\n }\n\n return response;\n };\n\n // Handle any other errors\n return res.status(status).json(\n createErrorResponse(err?.message || 'Internal Server Error', req, err, {\n includeDetails\n })\n );\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"middleware.utils.js","sourceRoot":"","sources":["../../../src/utils/middleware.utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAClC,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,wBAAwB,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAC3E,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAE3C,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAChE,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAK5D;;;;;;;;;GASG;AACH,MAAM,UAAU,SAAS,CAAC,OAIzB;IACC,IAAM,UAAU,GAAG,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,UAAU,KAAI,cAAc,CAAC;IACzD,IAAM,YAAY,GAAG,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,YAAY,MAAK,KAAK,CAAC;IACrD,IAAM,UAAU,GAAG,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,SAAS,KAAI,IAAI,CAAC;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esContent":["/*\n * The MIT License\n *\n * Copyright (c) 2025 Catbee Technologies\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { uuid } from './id.utils';\nimport { HttpStatusCodes } from './http-status-codes';\nimport { createFinalErrorResponse, ErrorResponse } from './response.utils';\nimport { getLogger } from './logger.utils';\nimport type { Request, Response, NextFunction } from 'express';\nimport { ContextStore, StoreKeys } from './context-store.utils';\nimport { RequestTimeoutException } from './exception.utils';\nimport { ApiErrorResponse } from '../types/api-response';\n\nexport type Middleware = (req: Request, res: Response, next: NextFunction) => void | Promise<void>;\n\n/**\n * Attaches a unique request ID to each request.\n * Useful for request tracing and correlation between logs.\n *\n * @param {object} [options] - Configuration options\n * @param {string} [options.headerName='X-Request-ID'] - Header name for request ID\n * @param {boolean} [options.exposeHeader=true] - Whether to expose the header in response\n * @param {() => string} [options.generator] - Custom ID generator function\n * @returns {Middleware} Express-compatible middleware\n */\nexport function requestId(options?: {\n headerName?: string;\n exposeHeader?: boolean;\n generator?: () => string;\n}): Middleware {\n const headerName = options?.headerName || 'X-Request-ID';\n const exposeHeader = options?.exposeHeader !== false;\n const generateId = options?.generator || uuid;\n\n return (req, res, next) => {\n // Use existing request ID from header or generate a new one\n const existingId = req.headers[headerName.toLowerCase()];\n const id = (existingId as string) || generateId();\n\n // Attach ID to request object\n req.id = id;\n\n // Add ID to response headers\n if (exposeHeader) {\n res.setHeader(headerName, id);\n }\n\n next();\n };\n}\n\n/**\n * Measures request processing time and logs or adds it to response headers.\n *\n * @param {object} [options] - Configuration options\n * @param {boolean} [options.addHeader=true] - Whether to add X-Response-Time header\n * @param {boolean} [options.logOnComplete=false] - Whether to log timing info\n * @returns {Middleware} Express-compatible middleware\n */\nexport function responseTime(options?: { addHeader?: boolean; logOnComplete?: boolean }) {\n const addHeader = options?.addHeader !== false;\n const logOnComplete = options?.logOnComplete === true;\n\n return (req: Request, res: Response, next: NextFunction) => {\n const start = process.hrtime();\n\n // Function to calculate duration\n const getDuration = () => {\n const diff = process.hrtime(start);\n return (diff[0] * 1e3 + diff[1] * 1e-6).toFixed(2);\n };\n\n if (addHeader) {\n // Ensure header is set before response is sent\n const originalWriteHead = res.writeHead;\n res.writeHead = function (...args: any[]) {\n res.setHeader('X-Response-Time', `${getDuration()}ms`);\n return originalWriteHead.apply(this, args as any);\n };\n }\n\n if (logOnComplete) {\n res.on('finish', () => {\n getLogger().info(`${req.method} ${req.url} - ${getDuration()}ms`);\n });\n }\n\n next();\n };\n}\n\n/**\n * Request timeout middleware.\n * Aborts requests that take too long to process.\n *\n * @param {number} [timeoutMs=30000] - Timeout in milliseconds\n * @returns {Middleware} Express-compatible middleware\n */\nexport function timeout(timeoutMs: number = 30000): Middleware {\n return (_req, res, next) => {\n // Set timeout for the request\n const timer = setTimeout(() => {\n const response = new RequestTimeoutException('Request timed out');\n res.status(HttpStatusCodes.REQUEST_TIMEOUT).json(response);\n }, timeoutMs);\n\n // Clear timeout when response is sent\n res.on('finish', () => {\n clearTimeout(timer);\n });\n\n next();\n };\n}\n\n/**\n * Creates an Express middleware that initializes a per-request context.\n *\n * @param {object} [options] - Optional configuration\n * @param {string} [options.headerName='x-request-id'] - Header to look for request ID\n * @param {boolean} [options.autoLog=true] - Whether to log automatically when context is initialized\n * @returns {(req: Request, res: Response, next: NextFunction) => void} Express middleware function\n */\nexport function setupRequestContext(options: { headerName?: string; autoLog?: boolean } = {}): Middleware {\n const { headerName = 'x-request-id', autoLog = true } = options;\n return (req, _res, next) => {\n // Generate or use existing request ID\n const requestId = (req.headers[headerName] as string) || req?.['id'] || uuid();\n\n ContextStore.run({ [StoreKeys.REQUEST_ID]: requestId }, () => {\n // Create a child logger for this request\n const childLogger = getLogger().child({\n requestId,\n method: req.method,\n url: req.originalUrl || req.url\n });\n\n // Store logger in context\n ContextStore.set(StoreKeys.LOGGER, childLogger);\n\n if (autoLog) {\n childLogger.info('Request context initialized');\n }\n\n next();\n });\n };\n}\n\nexport interface ErrorHandlerOptions {\n /** Whether to log errors (default: true) */\n logErrors?: boolean;\n /** Whether to include error details in non-production (default: false) */\n includeDetails?: boolean;\n}\n\n/**\n * Global error handling middleware with enhanced features.\n *\n * @param {ErrorHandlerOptions} options - Error handler options\n * @param {boolean} [options.logErrors=true] - Whether to log errors\n * @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production\n * @returns Error middleware\n *\n * @example\n * import express from 'express';\n * import { errorHandler } from '@catbee/utils';\n *\n * const app = express();\n *\n * // Your routes\n * app.get('/ping', (req, res) => {\n * throw new Error('Something went wrong');\n * });\n *\n * // Error handler (must be last middleware)\n * app.use(errorHandler({ includeDetails: true }));\n *\n * app.listen(3000, () => {\n * console.log('Server running on port 3000');\n * });\n */\nexport function errorHandler(options?: ErrorHandlerOptions) {\n const logErrors = options?.logErrors !== false;\n const includeDetails = options?.includeDetails === true;\n\n return (err: any, req: Request, res: Response, _next: NextFunction) => {\n // Determine status code\n const status = err?.status || err?.statusCode || HttpStatusCodes.INTERNAL_SERVER_ERROR;\n\n // Log error if enabled\n if (logErrors) {\n getLogger().error({ err }, `${err.message || 'Unknown error'}`);\n }\n\n // Handle ErrorResponse instances (our custom error class)\n if (err instanceof ErrorResponse) {\n const result: ApiErrorResponse = {\n error: true,\n message: err.message,\n timestamp: err.timestamp,\n requestId: err?.requestId || req?.id || uuid(),\n status,\n path: req.originalUrl || req.url\n };\n\n if (includeDetails && err?.stack) {\n result.stack = err.stack.split('\\n').map((line: string) => line.trim());\n }\n return res.status(status).json(result);\n }\n\n // Handle any other errors\n return res\n .status(status)\n .json(createFinalErrorResponse(req, status, err?.message || 'Internal Server Error', err, { includeDetails }));\n };\n}\n"]}
|
|
@@ -26,14 +26,21 @@ export declare function pick<T extends object, K extends keyof T>(obj: T, keys:
|
|
|
26
26
|
*/
|
|
27
27
|
export declare function omit<T extends object, K extends keyof T>(obj: T, keys: K[]): Omit<T, K>;
|
|
28
28
|
/**
|
|
29
|
-
* Deeply merges
|
|
29
|
+
* Deeply merges multiple objects into the target object (mutates and returns the target object, not pure).
|
|
30
30
|
*
|
|
31
31
|
* @template T
|
|
32
32
|
* @param {T} target - The object to merge into (will be mutated).
|
|
33
|
-
* @param {
|
|
33
|
+
* @param {...any[]} sources - The objects to merge from.
|
|
34
34
|
* @returns {T} The merged object (same as target).
|
|
35
35
|
*/
|
|
36
|
-
export declare function deepObjMerge<T extends
|
|
36
|
+
export declare function deepObjMerge<T extends object>(target: T, ...sources: any[]): T;
|
|
37
|
+
/**
|
|
38
|
+
* Checks if a value is a plain object (i.e., not an array, null, or a built-in object).
|
|
39
|
+
*
|
|
40
|
+
* @param value - The value to check.
|
|
41
|
+
* @returns True if the value is a plain object, false otherwise.
|
|
42
|
+
*/
|
|
43
|
+
export declare function isPlainObject(value: any): value is Record<string, any>;
|
|
37
44
|
/**
|
|
38
45
|
* Flattens a nested object using dot notation for keys (e.g., `{a: {b: 1}}` → `{ "a.b": 1 }`).
|
|
39
46
|
*
|
|
@@ -1,3 +1,26 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* The MIT License
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) 2025 Catbee Technologies
|
|
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
|
+
*/
|
|
1
24
|
var __read = (this && this.__read) || function (o, n) {
|
|
2
25
|
var m = typeof Symbol === "function" && o[Symbol.iterator];
|
|
3
26
|
if (!m) return o;
|
|
@@ -71,29 +94,216 @@ export function omit(obj, keys) {
|
|
|
71
94
|
}));
|
|
72
95
|
}
|
|
73
96
|
/**
|
|
74
|
-
* Deeply merges
|
|
97
|
+
* Deeply merges multiple objects into the target object (mutates and returns the target object, not pure).
|
|
75
98
|
*
|
|
76
99
|
* @template T
|
|
77
100
|
* @param {T} target - The object to merge into (will be mutated).
|
|
78
|
-
* @param {
|
|
101
|
+
* @param {...any[]} sources - The objects to merge from.
|
|
79
102
|
* @returns {T} The merged object (same as target).
|
|
80
103
|
*/
|
|
81
|
-
export function deepObjMerge(target
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
104
|
+
export function deepObjMerge(target) {
|
|
105
|
+
var e_1, _a, e_2, _b, e_3, _c;
|
|
106
|
+
var sources = [];
|
|
107
|
+
for (var _i = 1; _i < arguments.length; _i++) {
|
|
108
|
+
sources[_i - 1] = arguments[_i];
|
|
109
|
+
}
|
|
110
|
+
if (!sources.length)
|
|
111
|
+
return target;
|
|
112
|
+
var seen = new WeakMap();
|
|
113
|
+
seen.set(target, target);
|
|
114
|
+
try {
|
|
115
|
+
for (var sources_1 = __values(sources), sources_1_1 = sources_1.next(); !sources_1_1.done; sources_1_1 = sources_1.next()) {
|
|
116
|
+
var s = sources_1_1.value;
|
|
117
|
+
if (s && typeof s === 'object') {
|
|
118
|
+
seen.set(s, target);
|
|
88
119
|
}
|
|
89
|
-
deepObjMerge(target[key], sourceVal);
|
|
90
120
|
}
|
|
91
|
-
|
|
92
|
-
|
|
121
|
+
}
|
|
122
|
+
catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
|
123
|
+
finally {
|
|
124
|
+
try {
|
|
125
|
+
if (sources_1_1 && !sources_1_1.done && (_a = sources_1.return)) _a.call(sources_1);
|
|
126
|
+
}
|
|
127
|
+
finally { if (e_1) throw e_1.error; }
|
|
128
|
+
}
|
|
129
|
+
function deepClone(value) {
|
|
130
|
+
if (value === null || typeof value !== 'object')
|
|
131
|
+
return value;
|
|
132
|
+
if (seen.has(value))
|
|
133
|
+
return seen.get(value);
|
|
134
|
+
// Date
|
|
135
|
+
if (value instanceof Date) {
|
|
136
|
+
return new Date(value.getTime());
|
|
137
|
+
}
|
|
138
|
+
// Array
|
|
139
|
+
if (Array.isArray(value)) {
|
|
140
|
+
var clone_1 = [];
|
|
141
|
+
seen.set(value, clone_1);
|
|
142
|
+
value.forEach(function (item, i) { return (clone_1[i] = deepClone(item)); });
|
|
143
|
+
return clone_1;
|
|
144
|
+
}
|
|
145
|
+
// Set
|
|
146
|
+
if (value instanceof Set) {
|
|
147
|
+
var clone_2 = new Set();
|
|
148
|
+
seen.set(value, clone_2);
|
|
149
|
+
value.forEach(function (item) { return clone_2.add(deepClone(item)); });
|
|
150
|
+
return clone_2;
|
|
151
|
+
}
|
|
152
|
+
// Map
|
|
153
|
+
if (value instanceof Map) {
|
|
154
|
+
var clone_3 = new Map();
|
|
155
|
+
seen.set(value, clone_3);
|
|
156
|
+
value.forEach(function (val, key) { return clone_3.set(key, deepClone(val)); });
|
|
157
|
+
return clone_3;
|
|
158
|
+
}
|
|
159
|
+
// RegExp
|
|
160
|
+
if (value instanceof RegExp) {
|
|
161
|
+
return new RegExp(value.source, value.flags);
|
|
162
|
+
}
|
|
163
|
+
// ArrayBuffer
|
|
164
|
+
if (value instanceof ArrayBuffer) {
|
|
165
|
+
return value.slice(0);
|
|
166
|
+
}
|
|
167
|
+
// TypedArrays
|
|
168
|
+
if (ArrayBuffer.isView(value) && !(value instanceof DataView)) {
|
|
169
|
+
var typed = value; // cast for TS
|
|
170
|
+
var ctor = typed.constructor;
|
|
171
|
+
// List of standard TypedArray constructors
|
|
172
|
+
var typedArrayCtors = [
|
|
173
|
+
Int8Array,
|
|
174
|
+
Uint8Array,
|
|
175
|
+
Uint8ClampedArray,
|
|
176
|
+
Int16Array,
|
|
177
|
+
Uint16Array,
|
|
178
|
+
Int32Array,
|
|
179
|
+
Uint32Array,
|
|
180
|
+
Float32Array,
|
|
181
|
+
Float64Array,
|
|
182
|
+
BigInt64Array,
|
|
183
|
+
BigUint64Array
|
|
184
|
+
].filter(Boolean); // filter out undefined (for environments without BigInt)
|
|
185
|
+
var typedArrayCtorSet = new Set(typedArrayCtors);
|
|
186
|
+
if (typeof ctor === 'function' && typedArrayCtorSet.has(ctor)) {
|
|
187
|
+
// Defensive: ensure buffer is an ArrayBuffer and slice is available
|
|
188
|
+
var buffer = typed.buffer && typeof typed.buffer.slice === 'function' ? typed.buffer.slice(0) : typed.buffer;
|
|
189
|
+
var clone_4 = new ctor(buffer, typed.byteOffset, typed.length);
|
|
190
|
+
seen.set(value, clone_4);
|
|
191
|
+
return clone_4;
|
|
192
|
+
}
|
|
193
|
+
else if (typeof typed.slice === 'function') {
|
|
194
|
+
// Fallback: try using slice if available (e.g., Node.js Buffer)
|
|
195
|
+
var clone_5 = typed.slice();
|
|
196
|
+
seen.set(value, clone_5);
|
|
197
|
+
return clone_5;
|
|
198
|
+
}
|
|
199
|
+
else {
|
|
200
|
+
// Could not safely clone, throw an error for better debugging
|
|
201
|
+
throw new Error('Cannot deep clone unknown TypedArray type: ' + (typed && typed.constructor && typed.constructor.name));
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
var clone = Object.create(Object.getPrototypeOf(value));
|
|
205
|
+
seen.set(value, clone);
|
|
206
|
+
Reflect.ownKeys(value).forEach(function (key) {
|
|
207
|
+
var descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
208
|
+
if (descriptor.get || descriptor.set) {
|
|
209
|
+
Object.defineProperty(clone, key, descriptor);
|
|
210
|
+
}
|
|
211
|
+
else {
|
|
212
|
+
clone[key] = deepClone(value[key]);
|
|
213
|
+
}
|
|
214
|
+
});
|
|
215
|
+
return clone;
|
|
216
|
+
}
|
|
217
|
+
function mergeProp(target, source, key) {
|
|
218
|
+
var e_4, _a;
|
|
219
|
+
var targetValue = target[key];
|
|
220
|
+
var sourceValue = source[key];
|
|
221
|
+
// Ignore undefined in source
|
|
222
|
+
if (sourceValue === undefined)
|
|
223
|
+
return;
|
|
224
|
+
// Primitives → overwrite directly
|
|
225
|
+
if (sourceValue === null || typeof sourceValue !== 'object') {
|
|
226
|
+
target[key] = sourceValue;
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
// Arrays → replace (lodash behavior)
|
|
230
|
+
if (Array.isArray(sourceValue)) {
|
|
231
|
+
target[key] = deepClone(sourceValue);
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
// Special cloneable objects
|
|
235
|
+
if (sourceValue instanceof Date ||
|
|
236
|
+
sourceValue instanceof RegExp ||
|
|
237
|
+
sourceValue instanceof Set ||
|
|
238
|
+
sourceValue instanceof Map ||
|
|
239
|
+
sourceValue instanceof ArrayBuffer ||
|
|
240
|
+
(ArrayBuffer.isView(sourceValue) && !(sourceValue instanceof DataView))) {
|
|
241
|
+
target[key] = deepClone(sourceValue);
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
// Plain objects → recursive merge
|
|
245
|
+
if (isPlainObject(sourceValue) && isPlainObject(targetValue)) {
|
|
246
|
+
try {
|
|
247
|
+
for (var _b = __values(Reflect.ownKeys(sourceValue)), _c = _b.next(); !_c.done; _c = _b.next()) {
|
|
248
|
+
var k = _c.value;
|
|
249
|
+
mergeProp(targetValue, sourceValue, k);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
catch (e_4_1) { e_4 = { error: e_4_1 }; }
|
|
253
|
+
finally {
|
|
254
|
+
try {
|
|
255
|
+
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
|
|
256
|
+
}
|
|
257
|
+
finally { if (e_4) throw e_4.error; }
|
|
258
|
+
}
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
// Default → overwrite with clone
|
|
262
|
+
target[key] = deepClone(sourceValue);
|
|
263
|
+
}
|
|
264
|
+
try {
|
|
265
|
+
for (var sources_2 = __values(sources), sources_2_1 = sources_2.next(); !sources_2_1.done; sources_2_1 = sources_2.next()) {
|
|
266
|
+
var source = sources_2_1.value;
|
|
267
|
+
if (source == null)
|
|
268
|
+
continue;
|
|
269
|
+
try {
|
|
270
|
+
for (var _d = (e_3 = void 0, __values(Reflect.ownKeys(source))), _e = _d.next(); !_e.done; _e = _d.next()) {
|
|
271
|
+
var key = _e.value;
|
|
272
|
+
mergeProp(target, source, key);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
catch (e_3_1) { e_3 = { error: e_3_1 }; }
|
|
276
|
+
finally {
|
|
277
|
+
try {
|
|
278
|
+
if (_e && !_e.done && (_c = _d.return)) _c.call(_d);
|
|
279
|
+
}
|
|
280
|
+
finally { if (e_3) throw e_3.error; }
|
|
281
|
+
}
|
|
93
282
|
}
|
|
94
283
|
}
|
|
284
|
+
catch (e_2_1) { e_2 = { error: e_2_1 }; }
|
|
285
|
+
finally {
|
|
286
|
+
try {
|
|
287
|
+
if (sources_2_1 && !sources_2_1.done && (_b = sources_2.return)) _b.call(sources_2);
|
|
288
|
+
}
|
|
289
|
+
finally { if (e_2) throw e_2.error; }
|
|
290
|
+
}
|
|
95
291
|
return target;
|
|
96
292
|
}
|
|
293
|
+
/**
|
|
294
|
+
* Checks if a value is a plain object (i.e., not an array, null, or a built-in object).
|
|
295
|
+
*
|
|
296
|
+
* @param value - The value to check.
|
|
297
|
+
* @returns True if the value is a plain object, false otherwise.
|
|
298
|
+
*/
|
|
299
|
+
export function isPlainObject(value) {
|
|
300
|
+
if (typeof value !== 'object' || value === null)
|
|
301
|
+
return false;
|
|
302
|
+
if (Array.isArray(value))
|
|
303
|
+
return false;
|
|
304
|
+
var proto = Object.getPrototypeOf(value);
|
|
305
|
+
return proto === Object.prototype || proto === null;
|
|
306
|
+
}
|
|
97
307
|
/**
|
|
98
308
|
* Flattens a nested object using dot notation for keys (e.g., `{a: {b: 1}}` → `{ "a.b": 1 }`).
|
|
99
309
|
*
|
|
@@ -255,7 +465,7 @@ export function mapObject(obj, mapFn) {
|
|
|
255
465
|
* @returns {Readonly<T>} The frozen object.
|
|
256
466
|
*/
|
|
257
467
|
export function deepFreeze(obj) {
|
|
258
|
-
var
|
|
468
|
+
var e_5, _a;
|
|
259
469
|
// Freeze primitive properties
|
|
260
470
|
Object.freeze(obj);
|
|
261
471
|
try {
|
|
@@ -268,12 +478,12 @@ export function deepFreeze(obj) {
|
|
|
268
478
|
}
|
|
269
479
|
}
|
|
270
480
|
}
|
|
271
|
-
catch (
|
|
481
|
+
catch (e_5_1) { e_5 = { error: e_5_1 }; }
|
|
272
482
|
finally {
|
|
273
483
|
try {
|
|
274
484
|
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
|
|
275
485
|
}
|
|
276
|
-
finally { if (
|
|
486
|
+
finally { if (e_5) throw e_5.error; }
|
|
277
487
|
}
|
|
278
488
|
return obj;
|
|
279
489
|
}
|