@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
|
@@ -0,0 +1,958 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/*
|
|
3
|
+
* The MIT License
|
|
4
|
+
*
|
|
5
|
+
* Copyright (c) 2025 Catbee Technologies
|
|
6
|
+
*
|
|
7
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
8
|
+
* of this software and associated documentation files (the "Software"), to deal
|
|
9
|
+
* in the Software without restriction, including without limitation the rights
|
|
10
|
+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
11
|
+
* copies of the Software, and to permit persons to whom the Software is
|
|
12
|
+
* furnished to do so, subject to the following conditions:
|
|
13
|
+
*
|
|
14
|
+
* The above copyright notice and this permission notice shall be included in all
|
|
15
|
+
* copies or substantial portions of the Software.
|
|
16
|
+
*
|
|
17
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
18
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
19
|
+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
20
|
+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
21
|
+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
22
|
+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
23
|
+
* SOFTWARE.
|
|
24
|
+
*/
|
|
25
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
26
|
+
if (k2 === undefined) k2 = k;
|
|
27
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
28
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
29
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
30
|
+
}
|
|
31
|
+
Object.defineProperty(o, k2, desc);
|
|
32
|
+
}) : (function(o, m, k, k2) {
|
|
33
|
+
if (k2 === undefined) k2 = k;
|
|
34
|
+
o[k2] = m[k];
|
|
35
|
+
}));
|
|
36
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
37
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
38
|
+
}) : function(o, v) {
|
|
39
|
+
o["default"] = v;
|
|
40
|
+
});
|
|
41
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
42
|
+
var ownKeys = function(o) {
|
|
43
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
44
|
+
var ar = [];
|
|
45
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
46
|
+
return ar;
|
|
47
|
+
};
|
|
48
|
+
return ownKeys(o);
|
|
49
|
+
};
|
|
50
|
+
return function (mod) {
|
|
51
|
+
if (mod && mod.__esModule) return mod;
|
|
52
|
+
var result = {};
|
|
53
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
54
|
+
__setModuleDefault(result, mod);
|
|
55
|
+
return result;
|
|
56
|
+
};
|
|
57
|
+
})();
|
|
58
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
59
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
60
|
+
};
|
|
61
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
62
|
+
exports.ExpressServer = void 0;
|
|
63
|
+
const express_1 = __importDefault(require("express"));
|
|
64
|
+
const https_1 = __importDefault(require("https"));
|
|
65
|
+
const cors_1 = __importDefault(require("cors"));
|
|
66
|
+
const helmet_1 = __importDefault(require("helmet"));
|
|
67
|
+
const compression_1 = __importDefault(require("compression"));
|
|
68
|
+
const cookie_parser_1 = __importDefault(require("cookie-parser"));
|
|
69
|
+
const express_rate_limit_1 = __importDefault(require("express-rate-limit"));
|
|
70
|
+
const http_status_codes_1 = require("../utils/http-status-codes");
|
|
71
|
+
const response_utils_1 = require("../utils/response.utils");
|
|
72
|
+
const middleware_utils_1 = require("../utils/middleware.utils");
|
|
73
|
+
const env_utils_1 = require("../utils/env.utils");
|
|
74
|
+
const logger_utils_1 = require("../utils/logger.utils");
|
|
75
|
+
const exception_utils_1 = require("../utils/exception.utils");
|
|
76
|
+
const prom_client_1 = __importStar(require("prom-client"));
|
|
77
|
+
const exception_utils_2 = require("../utils/exception.utils");
|
|
78
|
+
const fs_1 = __importDefault(require("fs"));
|
|
79
|
+
const express_api_reference_1 = require("@scalar/express-api-reference");
|
|
80
|
+
const config_1 = require("../config");
|
|
81
|
+
const obj_utils_1 = require("../utils/obj.utils");
|
|
82
|
+
const fs_utils_1 = require("../utils/fs.utils");
|
|
83
|
+
const server_builder_1 = require("./server.builder");
|
|
84
|
+
const validate_utils_1 = require("../utils/validate.utils");
|
|
85
|
+
/**
|
|
86
|
+
* Production-ready Express server with enterprise features.
|
|
87
|
+
*
|
|
88
|
+
* Core Features:
|
|
89
|
+
* - Security: Helmet, CORS, rate limiting, timeouts
|
|
90
|
+
* - Monitoring: Request logs, metrics, health checks
|
|
91
|
+
* - Performance: Compression, caching, static files
|
|
92
|
+
* - Reliability: Graceful shutdown, error handling
|
|
93
|
+
* - Developer UX: OpenAPI docs, debugging tools
|
|
94
|
+
* - Extensibility: Hooks, middleware, custom routes
|
|
95
|
+
*
|
|
96
|
+
* Designed for microservices and production workloads.
|
|
97
|
+
* Includes K8s readiness probes and zero-downtime support.
|
|
98
|
+
*/
|
|
99
|
+
class ExpressServer {
|
|
100
|
+
/**
|
|
101
|
+
* Initializes server with intelligent defaults and security best practices.
|
|
102
|
+
* All settings can be customized via config and hooks.
|
|
103
|
+
*
|
|
104
|
+
* Default Security:
|
|
105
|
+
* - Secure headers (Helmet)
|
|
106
|
+
* - Rate limiting
|
|
107
|
+
* - Request timeouts
|
|
108
|
+
* - Body size limits
|
|
109
|
+
* - CORS protection
|
|
110
|
+
*
|
|
111
|
+
* Default Monitoring:
|
|
112
|
+
* - Request/Response logging
|
|
113
|
+
* - Prometheus metrics
|
|
114
|
+
* - Health checks
|
|
115
|
+
* - Request tracing
|
|
116
|
+
*/
|
|
117
|
+
constructor(config, hooks = {}) {
|
|
118
|
+
var _a, _b, _c;
|
|
119
|
+
/** Prometheus client registry for metrics collection */
|
|
120
|
+
this.register = new prom_client_1.default.Registry();
|
|
121
|
+
/** HTTP server instance (null when not running) */
|
|
122
|
+
this.server = null;
|
|
123
|
+
/** Set of active WebSocket connections */
|
|
124
|
+
this.connections = new Set();
|
|
125
|
+
/** Flag indicating if the server is shutting down */
|
|
126
|
+
this.isShuttingDown = false;
|
|
127
|
+
/**
|
|
128
|
+
* Collection of registered health check functions.
|
|
129
|
+
* These are executed when the health check endpoint is accessed.
|
|
130
|
+
*/
|
|
131
|
+
this.healthChecks = [];
|
|
132
|
+
if (ExpressServer.isBuiltServerConfig(config)) {
|
|
133
|
+
this.config = config;
|
|
134
|
+
}
|
|
135
|
+
else {
|
|
136
|
+
// Deep merge config with user overrides
|
|
137
|
+
this.config = (0, obj_utils_1.deepObjMerge)({}, config_1.defaultServerConfig, config);
|
|
138
|
+
}
|
|
139
|
+
if (!(0, validate_utils_1.isPort)(this.config.port)) {
|
|
140
|
+
throw new Error(`Port must be a valid number between 1 and 65535, got: ${this.config.port}`);
|
|
141
|
+
}
|
|
142
|
+
// Sanitize app name for metrics (replace invalid characters with underscore)
|
|
143
|
+
const safeAppName = (this.config.appName || 'express_app').toLowerCase().replace(/[^a-z0-9_]/g, '_');
|
|
144
|
+
if ((_a = this.config.metrics) === null || _a === void 0 ? void 0 : _a.enable) {
|
|
145
|
+
// Initialize Prometheus metrics with sanitized names
|
|
146
|
+
this.requestCounter = new prom_client_1.Counter({
|
|
147
|
+
name: `${safeAppName}_http_requests_total`,
|
|
148
|
+
help: 'Total HTTP requests',
|
|
149
|
+
labelNames: ['method', 'route', 'status'],
|
|
150
|
+
registers: [this.register]
|
|
151
|
+
});
|
|
152
|
+
this.routeTimings = new prom_client_1.Histogram({
|
|
153
|
+
name: `${safeAppName}_http_request_duration_seconds`,
|
|
154
|
+
help: 'Duration of HTTP requests by route',
|
|
155
|
+
labelNames: ['method', 'route', 'status'],
|
|
156
|
+
buckets: [0.1, 0.3, 0.5, 0.7, 1, 3, 5, 7, 10],
|
|
157
|
+
registers: [this.register]
|
|
158
|
+
});
|
|
159
|
+
this.requestSizes = new prom_client_1.Histogram({
|
|
160
|
+
name: `${safeAppName}_http_request_size_bytes`,
|
|
161
|
+
help: 'Size of HTTP request bodies',
|
|
162
|
+
labelNames: ['method', 'route'],
|
|
163
|
+
buckets: [100, 1000, 10000, 100000, 1000000],
|
|
164
|
+
registers: [this.register]
|
|
165
|
+
});
|
|
166
|
+
this.clientIPs = new prom_client_1.Counter({
|
|
167
|
+
name: `${safeAppName}_http_client_ip_total`,
|
|
168
|
+
help: 'Client IP request counter',
|
|
169
|
+
labelNames: ['ip', 'method'],
|
|
170
|
+
registers: [this.register]
|
|
171
|
+
});
|
|
172
|
+
// Default system metrics (CPU, memory, event loop lag, etc.)
|
|
173
|
+
prom_client_1.default.collectDefaultMetrics({
|
|
174
|
+
register: this.register,
|
|
175
|
+
prefix: `${safeAppName}_`
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
// Health checks
|
|
179
|
+
if ((_b = config.healthCheck) === null || _b === void 0 ? void 0 : _b.checks) {
|
|
180
|
+
this.healthChecks.push(...config.healthCheck.checks);
|
|
181
|
+
}
|
|
182
|
+
// Logger
|
|
183
|
+
if (this.config.logger) {
|
|
184
|
+
const { name, level, prettyPrint: pretty, singleLine } = this.config.logger;
|
|
185
|
+
(0, config_1.setConfig)({
|
|
186
|
+
logger: {
|
|
187
|
+
name: name !== null && name !== void 0 ? name : 'express_app',
|
|
188
|
+
level: level !== null && level !== void 0 ? level : 'info',
|
|
189
|
+
pretty: pretty !== null && pretty !== void 0 ? pretty : env_utils_1.Env.isDev(),
|
|
190
|
+
singleLine: singleLine !== null && singleLine !== void 0 ? singleLine : false
|
|
191
|
+
}
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
// Set global prefix (normalize to empty string or "/prefix" without trailing slash)
|
|
195
|
+
this.globalPrefix = this.normalizePath((_c = this.config.globalPrefix) !== null && _c !== void 0 ? _c : '', false);
|
|
196
|
+
this.hooks = hooks;
|
|
197
|
+
this.app = (0, express_1.default)();
|
|
198
|
+
this.rootRouter = express_1.default.Router();
|
|
199
|
+
// Store initialization promise to prevent race conditions with start()
|
|
200
|
+
this.initPromise = this.initialize();
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Execute a lifecycle hook safely with comprehensive error handling.
|
|
204
|
+
* Prevents hook failures from crashing the server while logging issues.
|
|
205
|
+
*
|
|
206
|
+
* @param hook Name of the lifecycle hook to execute
|
|
207
|
+
* @param args Arguments to pass to the hook function
|
|
208
|
+
*/
|
|
209
|
+
async runHook(hook, ...args) {
|
|
210
|
+
try {
|
|
211
|
+
const fn = this.hooks[hook];
|
|
212
|
+
if (fn)
|
|
213
|
+
await fn.apply(null, args);
|
|
214
|
+
}
|
|
215
|
+
catch (err) {
|
|
216
|
+
(0, logger_utils_1.getLogger)().error({ err, hook }, `Error executing ${hook} hook:`);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* Initialize the Express server with middleware and routes.
|
|
221
|
+
*/
|
|
222
|
+
async initialize() {
|
|
223
|
+
await this.runHook('beforeInit', this);
|
|
224
|
+
// Set up middleware stack (order is critical)
|
|
225
|
+
await this.setupMiddleware();
|
|
226
|
+
// Set up default routes and error handling
|
|
227
|
+
await this.setupRoutes();
|
|
228
|
+
await this.runHook('afterInit', this);
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* Configure and register all middlewares in the optimal order.
|
|
232
|
+
*
|
|
233
|
+
* Middleware Order (CRITICAL - don't change without understanding implications):
|
|
234
|
+
* 1. Basic server configuration (trust proxy, x-powered-by)
|
|
235
|
+
* 2. Request ID generation (for tracing)
|
|
236
|
+
* 3. Request context setup (for logging correlation)
|
|
237
|
+
* 4. Timeout protection (prevents hanging requests)
|
|
238
|
+
* 5. Response time tracking (for performance monitoring)
|
|
239
|
+
* 6. Request logging (after ID/context setup)
|
|
240
|
+
* 7. Custom request hooks
|
|
241
|
+
* 8. Security middleware (rate limiting, CORS, Helmet)
|
|
242
|
+
* 9. Response compression
|
|
243
|
+
* 10. Static file serving
|
|
244
|
+
* 11. Request parsing (body parsing, cookies)
|
|
245
|
+
* 12. API documentation (OpenAPI)
|
|
246
|
+
* 13. Global headers
|
|
247
|
+
* 14. Custom response hooks
|
|
248
|
+
*/
|
|
249
|
+
async setupMiddleware() {
|
|
250
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
|
|
251
|
+
if (this.config.https) {
|
|
252
|
+
await this.validateHttpsFiles();
|
|
253
|
+
}
|
|
254
|
+
// Basic middleware should be first
|
|
255
|
+
this.app.disable('x-powered-by');
|
|
256
|
+
if (this.config.trustProxy) {
|
|
257
|
+
this.app.set('trust proxy', true);
|
|
258
|
+
}
|
|
259
|
+
// Request ID generation - must be first for proper tracing
|
|
260
|
+
this.app.use((0, middleware_utils_1.requestId)({
|
|
261
|
+
headerName: (_a = this.config.requestId) === null || _a === void 0 ? void 0 : _a.headerName,
|
|
262
|
+
exposeHeader: (_b = this.config.requestId) === null || _b === void 0 ? void 0 : _b.exposeHeader,
|
|
263
|
+
generator: (_c = this.config.requestId) === null || _c === void 0 ? void 0 : _c.generator
|
|
264
|
+
}));
|
|
265
|
+
// Request context setup for logging correlation
|
|
266
|
+
this.app.use((0, middleware_utils_1.setupRequestContext)({
|
|
267
|
+
headerName: (_d = this.config.requestId) === null || _d === void 0 ? void 0 : _d.headerName,
|
|
268
|
+
autoLog: false
|
|
269
|
+
}));
|
|
270
|
+
// Early shutdown-awareness middleware (lets load balancers drain connections gracefully)
|
|
271
|
+
this.app.use((_req, res, next) => {
|
|
272
|
+
if (this.isShuttingDown) {
|
|
273
|
+
res.setHeader('Connection', 'close');
|
|
274
|
+
return res
|
|
275
|
+
.status(http_status_codes_1.HttpStatusCodes.SERVICE_UNAVAILABLE)
|
|
276
|
+
.json(new exception_utils_1.ServiceUnavailableException('Server is shutting down'));
|
|
277
|
+
}
|
|
278
|
+
next();
|
|
279
|
+
return;
|
|
280
|
+
});
|
|
281
|
+
// Security middleware should come early
|
|
282
|
+
if (this.config.helmet) {
|
|
283
|
+
if (typeof this.config.helmet === 'object') {
|
|
284
|
+
this.app.use((0, helmet_1.default)(this.config.helmet));
|
|
285
|
+
}
|
|
286
|
+
else {
|
|
287
|
+
this.app.use((0, helmet_1.default)());
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
// CORS middleware should be early
|
|
291
|
+
if (this.config.cors) {
|
|
292
|
+
this.app.use((0, cors_1.default)(this.config.cors === true ? {} : this.config.cors));
|
|
293
|
+
}
|
|
294
|
+
// Global headers
|
|
295
|
+
this.app.use((_req, res, next) => {
|
|
296
|
+
var _a, _b, _c, _d;
|
|
297
|
+
if (this.config.globalHeaders) {
|
|
298
|
+
for (const key in this.config.globalHeaders) {
|
|
299
|
+
const value = this.config.globalHeaders[key];
|
|
300
|
+
res.setHeader(key, typeof value === 'function' ? value() : value);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
if (this.config.isMicroservice) {
|
|
304
|
+
res.setHeader('X-Microservice', this.config.appName || 'express_app');
|
|
305
|
+
}
|
|
306
|
+
if ((_a = this.config.serviceVersion) === null || _a === void 0 ? void 0 : _a.enable) {
|
|
307
|
+
const version = typeof ((_b = this.config.serviceVersion) === null || _b === void 0 ? void 0 : _b.version) === 'function'
|
|
308
|
+
? this.config.serviceVersion.version()
|
|
309
|
+
: (_c = this.config.serviceVersion) === null || _c === void 0 ? void 0 : _c.version;
|
|
310
|
+
res.setHeader(((_d = this.config.serviceVersion) === null || _d === void 0 ? void 0 : _d.headerName) || 'x-service-version', version || '0.0.0');
|
|
311
|
+
}
|
|
312
|
+
next();
|
|
313
|
+
});
|
|
314
|
+
// Global request timeout protection
|
|
315
|
+
if (this.config.requestTimeout) {
|
|
316
|
+
this.app.use((0, middleware_utils_1.timeout)(this.config.requestTimeout));
|
|
317
|
+
}
|
|
318
|
+
// Response time tracking for performance monitoring
|
|
319
|
+
if ((_e = this.config.responseTime) === null || _e === void 0 ? void 0 : _e.enable) {
|
|
320
|
+
this.app.use((0, middleware_utils_1.responseTime)({
|
|
321
|
+
addHeader: this.config.responseTime.addHeader,
|
|
322
|
+
logOnComplete: this.config.responseTime.logOnComplete
|
|
323
|
+
}));
|
|
324
|
+
}
|
|
325
|
+
// Rate limiting should be early to prevent unnecessary processing
|
|
326
|
+
if ((_f = this.config.rateLimit) === null || _f === void 0 ? void 0 : _f.enable) {
|
|
327
|
+
this.app.use((0, express_rate_limit_1.default)({
|
|
328
|
+
windowMs: (_g = this.config.rateLimit.windowMs) !== null && _g !== void 0 ? _g : 15 * 60 * 1000,
|
|
329
|
+
max: (_h = this.config.rateLimit.max) !== null && _h !== void 0 ? _h : 100,
|
|
330
|
+
handler: (req, res) => {
|
|
331
|
+
var _a;
|
|
332
|
+
const status = http_status_codes_1.HttpStatusCodes.TOO_MANY_REQUESTS;
|
|
333
|
+
const response = (0, response_utils_1.createFinalErrorResponse)(req, status, ((_a = this.config.rateLimit) === null || _a === void 0 ? void 0 : _a.message) || 'Too many requests');
|
|
334
|
+
res.status(status).json(response);
|
|
335
|
+
},
|
|
336
|
+
standardHeaders: (_j = this.config.rateLimit.standardHeaders) !== null && _j !== void 0 ? _j : true,
|
|
337
|
+
legacyHeaders: (_k = this.config.rateLimit.legacyHeaders) !== null && _k !== void 0 ? _k : false
|
|
338
|
+
}));
|
|
339
|
+
}
|
|
340
|
+
// Request logging with filtering
|
|
341
|
+
if ((_l = this.config.requestLogging) === null || _l === void 0 ? void 0 : _l.enable) {
|
|
342
|
+
this.app.use((req, res, next) => {
|
|
343
|
+
var _a, _b, _c, _d, _e, _f;
|
|
344
|
+
if (typeof ((_a = this.config.requestLogging) === null || _a === void 0 ? void 0 : _a.ignorePaths) === 'function') {
|
|
345
|
+
const skip = (_c = (_b = this.config.requestLogging) === null || _b === void 0 ? void 0 : _b.ignorePaths) === null || _c === void 0 ? void 0 : _c.call(_b, req, res);
|
|
346
|
+
if (skip)
|
|
347
|
+
return next();
|
|
348
|
+
}
|
|
349
|
+
else if (Array.isArray((_d = this.config.requestLogging) === null || _d === void 0 ? void 0 : _d.ignorePaths)) {
|
|
350
|
+
const skip = (_f = (_e = this.config.requestLogging) === null || _e === void 0 ? void 0 : _e.ignorePaths) === null || _f === void 0 ? void 0 : _f.includes(req.path);
|
|
351
|
+
if (skip)
|
|
352
|
+
return next();
|
|
353
|
+
}
|
|
354
|
+
const logger = (0, logger_utils_1.getLogger)();
|
|
355
|
+
const incomingRequestMetaData = {
|
|
356
|
+
requestId: req.id,
|
|
357
|
+
method: req.method,
|
|
358
|
+
url: req.originalUrl || req.url,
|
|
359
|
+
ip: req.ip
|
|
360
|
+
};
|
|
361
|
+
logger.info(incomingRequestMetaData, 'Incoming Request');
|
|
362
|
+
next();
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
// Custom request preprocessing hook
|
|
366
|
+
if (this.hooks.onRequest) {
|
|
367
|
+
this.app.use(this.hooks.onRequest);
|
|
368
|
+
}
|
|
369
|
+
// Response compression for better performance
|
|
370
|
+
if (this.config.compression) {
|
|
371
|
+
if (typeof this.config.compression === 'object') {
|
|
372
|
+
this.app.use((0, compression_1.default)(this.config.compression));
|
|
373
|
+
}
|
|
374
|
+
else {
|
|
375
|
+
this.app.use((0, compression_1.default)());
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
// Static file serving (do NOT normalize filesystem path; only normalize route)
|
|
379
|
+
if (this.config.staticFolders) {
|
|
380
|
+
this.config.staticFolders.forEach(folder => {
|
|
381
|
+
var _a;
|
|
382
|
+
this.app.use(this.normalizePath((_a = folder.path) !== null && _a !== void 0 ? _a : '/'), express_1.default.static(folder.directory, {
|
|
383
|
+
maxAge: folder.maxAge || 0,
|
|
384
|
+
etag: folder.etag !== false,
|
|
385
|
+
immutable: folder.immutable === true,
|
|
386
|
+
lastModified: folder.lastModified !== false,
|
|
387
|
+
cacheControl: folder.cacheControl !== false
|
|
388
|
+
}));
|
|
389
|
+
(0, logger_utils_1.getLogger)().info(`Serving static folder: ${folder.directory} at path ${folder.path || '/'}`);
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
// Request body parsing with size limits
|
|
393
|
+
if (this.config.bodyParser) {
|
|
394
|
+
if (this.config.bodyParser.json) {
|
|
395
|
+
this.app.use(express_1.default.json(this.config.bodyParser.json));
|
|
396
|
+
}
|
|
397
|
+
if (this.config.bodyParser.urlencoded) {
|
|
398
|
+
this.app.use(express_1.default.urlencoded(this.config.bodyParser.urlencoded));
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
// Cookie parser middleware
|
|
402
|
+
if (this.config.cookieParser) {
|
|
403
|
+
if (typeof this.config.cookieParser === 'object') {
|
|
404
|
+
this.app.use((0, cookie_parser_1.default)(undefined, this.config.cookieParser));
|
|
405
|
+
}
|
|
406
|
+
else {
|
|
407
|
+
this.app.use((0, cookie_parser_1.default)());
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
// OpenAPI docs via @scalar/express-api-reference
|
|
411
|
+
if ((_m = this.config.openApi) === null || _m === void 0 ? void 0 : _m.enable) {
|
|
412
|
+
try {
|
|
413
|
+
const openApiMountPath = this.normalizePath((_o = this.config.openApi.mountPath) !== null && _o !== void 0 ? _o : '/docs', this.config.openApi.withGlobalPrefix);
|
|
414
|
+
const openApiFilePath = this.config.openApi.filePath;
|
|
415
|
+
if (!openApiFilePath) {
|
|
416
|
+
throw new Error('OpenAPI file path is required');
|
|
417
|
+
}
|
|
418
|
+
const isOpenApiFilePathExists = await (0, fs_utils_1.fileExists)(openApiFilePath);
|
|
419
|
+
if (!isOpenApiFilePathExists) {
|
|
420
|
+
throw new Error(`OpenAPI spec file not found at ${openApiFilePath}`);
|
|
421
|
+
}
|
|
422
|
+
if ((_p = this.config.openApi) === null || _p === void 0 ? void 0 : _p.verbose) {
|
|
423
|
+
(0, logger_utils_1.getLogger)().info(`Mounting OpenAPI docs at ${openApiMountPath}`);
|
|
424
|
+
(0, logger_utils_1.getLogger)().info(`Using OpenAPI spec file at ${openApiFilePath}`);
|
|
425
|
+
}
|
|
426
|
+
this.app.use(openApiMountPath, (0, express_api_reference_1.apiReference)({
|
|
427
|
+
spec: {
|
|
428
|
+
content: await fs_1.default.promises.readFile(openApiFilePath, 'utf8')
|
|
429
|
+
}
|
|
430
|
+
}));
|
|
431
|
+
if ((_q = this.config.openApi) === null || _q === void 0 ? void 0 : _q.verbose) {
|
|
432
|
+
(0, logger_utils_1.getLogger)().info(`Mounted OpenAPI docs at ${openApiMountPath}`);
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
catch (err) {
|
|
436
|
+
(0, logger_utils_1.getLogger)().error({ err }, 'Failed to mount OpenAPI docs');
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
// Custom response preprocessing hook (apply global prefix if set)
|
|
440
|
+
if (this.hooks.onResponse) {
|
|
441
|
+
this.app.use(this.globalPrefix, this.hooks.onResponse);
|
|
442
|
+
}
|
|
443
|
+
if ((_r = this.config.metrics) === null || _r === void 0 ? void 0 : _r.enable) {
|
|
444
|
+
// Add metrics tracking middleware
|
|
445
|
+
this.app.use((req, res, next) => {
|
|
446
|
+
var _a, _b;
|
|
447
|
+
const start = process.hrtime();
|
|
448
|
+
// Track client IPs
|
|
449
|
+
(_a = this.clientIPs) === null || _a === void 0 ? void 0 : _a.inc({ ip: req.ip, method: req.method });
|
|
450
|
+
// Track request sizes (parse safely)
|
|
451
|
+
const cl = req.headers['content-length'];
|
|
452
|
+
if (cl) {
|
|
453
|
+
const size = Number(cl);
|
|
454
|
+
if (!Number.isNaN(size) && size >= 0) {
|
|
455
|
+
const route = this.normalizeRouteForMetrics(req, res);
|
|
456
|
+
(_b = this.requestSizes) === null || _b === void 0 ? void 0 : _b.observe({ method: req.method, route }, size);
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
res.once('finish', () => {
|
|
460
|
+
var _a, _b;
|
|
461
|
+
const [seconds, nanoseconds] = process.hrtime(start);
|
|
462
|
+
const finalRoute = this.normalizeRouteForMetrics(req, res);
|
|
463
|
+
(_a = this.requestCounter) === null || _a === void 0 ? void 0 : _a.inc({
|
|
464
|
+
method: req.method,
|
|
465
|
+
route: finalRoute,
|
|
466
|
+
status: res.statusCode.toString()
|
|
467
|
+
});
|
|
468
|
+
(_b = this.routeTimings) === null || _b === void 0 ? void 0 : _b.observe({
|
|
469
|
+
method: req.method,
|
|
470
|
+
route: finalRoute,
|
|
471
|
+
status: res.statusCode.toString()
|
|
472
|
+
}, seconds + nanoseconds / 1e9);
|
|
473
|
+
});
|
|
474
|
+
next();
|
|
475
|
+
});
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
/**
|
|
479
|
+
* Configure server routes and error handling.
|
|
480
|
+
* Sets up in following order:
|
|
481
|
+
*
|
|
482
|
+
* 1. Built-in routes (health, metrics)
|
|
483
|
+
* 2. Application routes
|
|
484
|
+
* 3. 404 handler
|
|
485
|
+
* 4. Error handler
|
|
486
|
+
*/
|
|
487
|
+
async setupRoutes() {
|
|
488
|
+
var _a, _b, _c, _d, _e;
|
|
489
|
+
// Health check endpoint
|
|
490
|
+
const healthCheckPath = this.normalizePath(((_a = this.config.healthCheck) === null || _a === void 0 ? void 0 : _a.path) || '/healthz', (_b = this.config.healthCheck) === null || _b === void 0 ? void 0 : _b.withGlobalPrefix);
|
|
491
|
+
this.app.get(healthCheckPath, async (_req, res) => {
|
|
492
|
+
var _a;
|
|
493
|
+
try {
|
|
494
|
+
if (!this.healthChecks.length) {
|
|
495
|
+
return res.status(http_status_codes_1.HttpStatusCodes.OK).json(new response_utils_1.SuccessResponse('OK'));
|
|
496
|
+
}
|
|
497
|
+
const checkResults = await Promise.allSettled(this.healthChecks.map(async ({ name, check }) => {
|
|
498
|
+
try {
|
|
499
|
+
const status = await Promise.resolve(check());
|
|
500
|
+
return { name, status, error: null };
|
|
501
|
+
}
|
|
502
|
+
catch (error) {
|
|
503
|
+
return { name, status: false, error: error.message };
|
|
504
|
+
}
|
|
505
|
+
}));
|
|
506
|
+
const results = checkResults.map(result => {
|
|
507
|
+
if (result.status === 'fulfilled')
|
|
508
|
+
return result.value;
|
|
509
|
+
return { name: 'unknown', status: false, error: result.reason };
|
|
510
|
+
});
|
|
511
|
+
const allOk = results.every(r => r.status);
|
|
512
|
+
const status = allOk ? http_status_codes_1.HttpStatusCodes.OK : http_status_codes_1.HttpStatusCodes.SERVICE_UNAVAILABLE;
|
|
513
|
+
const response = new response_utils_1.SuccessResponse(allOk ? 'OK' : 'Service unavailable');
|
|
514
|
+
if (!allOk)
|
|
515
|
+
response.error = true;
|
|
516
|
+
if ((_a = this.config.healthCheck) === null || _a === void 0 ? void 0 : _a.detailed)
|
|
517
|
+
response.data = { checks: results };
|
|
518
|
+
return res.status(status).json(response);
|
|
519
|
+
}
|
|
520
|
+
catch (_b) {
|
|
521
|
+
return res
|
|
522
|
+
.status(http_status_codes_1.HttpStatusCodes.INTERNAL_SERVER_ERROR)
|
|
523
|
+
.json(new exception_utils_1.InternalServerErrorException('Health check failed'));
|
|
524
|
+
}
|
|
525
|
+
});
|
|
526
|
+
// Metrics endpoint
|
|
527
|
+
if ((_c = this.config.metrics) === null || _c === void 0 ? void 0 : _c.enable) {
|
|
528
|
+
const metricsPath = this.normalizePath((_d = this.config.metrics.path) !== null && _d !== void 0 ? _d : '/metrics', (_e = this.config.metrics) === null || _e === void 0 ? void 0 : _e.withGlobalPrefix);
|
|
529
|
+
this.app.get(metricsPath, async (_req, res) => {
|
|
530
|
+
res.set('Content-Type', this.register.contentType);
|
|
531
|
+
res.end(await this.register.metrics());
|
|
532
|
+
});
|
|
533
|
+
}
|
|
534
|
+
// Application routes
|
|
535
|
+
const routerToUse = this.externalRouter || this.rootRouter;
|
|
536
|
+
this.app.use(this.globalPrefix, routerToUse);
|
|
537
|
+
// 404 handler (must be after all other routes)
|
|
538
|
+
this.app.use((req, res) => {
|
|
539
|
+
const status = http_status_codes_1.HttpStatusCodes.NOT_FOUND;
|
|
540
|
+
const response = (0, response_utils_1.createFinalErrorResponse)(req, status, `Route ${req.method.toUpperCase()} ${req.path} not found`);
|
|
541
|
+
res.status(status).json(response);
|
|
542
|
+
});
|
|
543
|
+
// Global error handler (must be the last middleware)
|
|
544
|
+
this.app.use((err, req, res, next) => {
|
|
545
|
+
var _a;
|
|
546
|
+
// Check if this is a 404 error that should be handled with special logging rules
|
|
547
|
+
const isNotFoundError = err instanceof exception_utils_2.NotFoundException;
|
|
548
|
+
const shouldSkipLogging = !this.hooks.onError &&
|
|
549
|
+
isNotFoundError &&
|
|
550
|
+
((_a = this.config.requestLogging) === null || _a === void 0 ? void 0 : _a.enable) &&
|
|
551
|
+
this.config.requestLogging.skipNotFoundRoutes === true;
|
|
552
|
+
if (this.hooks.onError) {
|
|
553
|
+
// Use custom error handler if provided
|
|
554
|
+
this.hooks.onError(err, req, res, next);
|
|
555
|
+
}
|
|
556
|
+
else {
|
|
557
|
+
// Default error handler with logging
|
|
558
|
+
const errorHandlerMiddleware = (0, middleware_utils_1.errorHandler)({
|
|
559
|
+
logErrors: !shouldSkipLogging,
|
|
560
|
+
includeDetails: env_utils_1.Env.isDev() // Only show stack traces in development
|
|
561
|
+
});
|
|
562
|
+
errorHandlerMiddleware(err, req, res, next);
|
|
563
|
+
}
|
|
564
|
+
});
|
|
565
|
+
}
|
|
566
|
+
/**
|
|
567
|
+
* Register a new health check function for monitoring service dependencies.
|
|
568
|
+
*
|
|
569
|
+
* Health checks are executed when the health endpoint is accessed and
|
|
570
|
+
* help determine if the service is ready to handle requests.
|
|
571
|
+
*
|
|
572
|
+
* Examples:
|
|
573
|
+
* - Database connectivity
|
|
574
|
+
* - External service availability
|
|
575
|
+
* - File system access
|
|
576
|
+
* - Memory/CPU usage checks
|
|
577
|
+
*
|
|
578
|
+
* @param name Unique identifier for the check (used in detailed responses)
|
|
579
|
+
* @param check Function returning boolean or Promise<boolean> indicating health
|
|
580
|
+
* @returns This instance for method chaining
|
|
581
|
+
*/
|
|
582
|
+
registerHealthCheck(name, check) {
|
|
583
|
+
this.healthChecks.push({ name, check });
|
|
584
|
+
return this;
|
|
585
|
+
}
|
|
586
|
+
/**
|
|
587
|
+
* Get the underlying Express application instance.
|
|
588
|
+
* Use this for advanced Express features not exposed by this wrapper.
|
|
589
|
+
*
|
|
590
|
+
* @returns The raw Express app instance
|
|
591
|
+
*/
|
|
592
|
+
getApp() {
|
|
593
|
+
return this.app;
|
|
594
|
+
}
|
|
595
|
+
/**
|
|
596
|
+
* Get the active HTTP/HTTPS server instance.
|
|
597
|
+
* Returns null if the server is not currently running.
|
|
598
|
+
*
|
|
599
|
+
* @returns The HTTP/HTTPS server instance or null
|
|
600
|
+
*/
|
|
601
|
+
getServer() {
|
|
602
|
+
return this.server;
|
|
603
|
+
}
|
|
604
|
+
/**
|
|
605
|
+
* Start the HTTP server and begin listening for requests.
|
|
606
|
+
*
|
|
607
|
+
* This method:
|
|
608
|
+
* - Executes beforeStart hooks
|
|
609
|
+
* - Binds to the configured host/port
|
|
610
|
+
* - Sets up error handling for startup failures
|
|
611
|
+
* - Executes afterStart hooks on success
|
|
612
|
+
* - Logs startup information
|
|
613
|
+
*
|
|
614
|
+
* @returns Promise resolving to the running HTTP server instance
|
|
615
|
+
* @throws Error if server fails to start or port is already in use
|
|
616
|
+
*/
|
|
617
|
+
async start() {
|
|
618
|
+
// Ensure initialization (middleware + routes) completed before starting
|
|
619
|
+
await this.initPromise;
|
|
620
|
+
await this.runHook('beforeStart', this.app);
|
|
621
|
+
return new Promise((resolve, reject) => {
|
|
622
|
+
try {
|
|
623
|
+
// Prepare listen arguments with optional host parameter
|
|
624
|
+
const listenArgs = [
|
|
625
|
+
this.config.port,
|
|
626
|
+
this.config.host,
|
|
627
|
+
async () => {
|
|
628
|
+
var _a, _b, _c;
|
|
629
|
+
const protocol = this.config.https ? 'https' : 'http';
|
|
630
|
+
const url = `${protocol}://${this.config.host}:${this.config.port}`;
|
|
631
|
+
(0, logger_utils_1.getLogger)().info(`Server running on ${url}`);
|
|
632
|
+
if ((_a = this.config.healthCheck) === null || _a === void 0 ? void 0 : _a.path) {
|
|
633
|
+
(0, logger_utils_1.getLogger)().info(`Health check available at ${url}${this.normalizePath(this.config.healthCheck.path, this.config.healthCheck.withGlobalPrefix)}`);
|
|
634
|
+
}
|
|
635
|
+
if (((_b = this.config.metrics) === null || _b === void 0 ? void 0 : _b.enable) && this.config.metrics.path) {
|
|
636
|
+
(0, logger_utils_1.getLogger)().info(`Metrics available at ${url}${this.normalizePath(this.config.metrics.path, this.config.metrics.withGlobalPrefix)}`);
|
|
637
|
+
}
|
|
638
|
+
if ((_c = this.config.openApi) === null || _c === void 0 ? void 0 : _c.enable) {
|
|
639
|
+
(0, logger_utils_1.getLogger)().info(`API docs available at ${url}${this.normalizePath(this.config.openApi.mountPath, this.config.openApi.withGlobalPrefix)}`);
|
|
640
|
+
}
|
|
641
|
+
if (this.server)
|
|
642
|
+
await this.runHook('afterStart', this.server);
|
|
643
|
+
resolve(this.server);
|
|
644
|
+
}
|
|
645
|
+
];
|
|
646
|
+
if (this.config.https) {
|
|
647
|
+
const httpsOptions = Object.assign(Object.assign({}, this.config.https), { key: fs_1.default.readFileSync(this.config.https.key), cert: fs_1.default.readFileSync(this.config.https.cert) });
|
|
648
|
+
if (this.config.https.ca) {
|
|
649
|
+
httpsOptions.ca = fs_1.default.readFileSync(this.config.https.ca);
|
|
650
|
+
}
|
|
651
|
+
if (this.config.https.passphrase) {
|
|
652
|
+
httpsOptions.passphrase = this.config.https.passphrase;
|
|
653
|
+
}
|
|
654
|
+
this.server = https_1.default.createServer(httpsOptions, this.app).listen(...listenArgs);
|
|
655
|
+
}
|
|
656
|
+
else {
|
|
657
|
+
// Start the HTTP server
|
|
658
|
+
this.server = this.app.listen(...listenArgs);
|
|
659
|
+
}
|
|
660
|
+
// Track connections
|
|
661
|
+
this.server.on('connection', (conn) => {
|
|
662
|
+
this.connections.add(conn);
|
|
663
|
+
conn.on('close', () => this.connections.delete(conn));
|
|
664
|
+
});
|
|
665
|
+
// Handle server startup errors (port in use, permission denied, etc.)
|
|
666
|
+
this.server.on('error', err => {
|
|
667
|
+
(0, logger_utils_1.getLogger)().error({ err }, 'Server failed to start');
|
|
668
|
+
reject(err);
|
|
669
|
+
});
|
|
670
|
+
}
|
|
671
|
+
catch (error) {
|
|
672
|
+
reject(error);
|
|
673
|
+
}
|
|
674
|
+
});
|
|
675
|
+
}
|
|
676
|
+
/**
|
|
677
|
+
* Stop the HTTP server gracefully.
|
|
678
|
+
*
|
|
679
|
+
* This method:
|
|
680
|
+
* - Executes beforeStop hooks
|
|
681
|
+
* - Stops accepting new connections
|
|
682
|
+
* - Waits for existing connections to finish
|
|
683
|
+
* - Closes the server
|
|
684
|
+
* - Executes afterStop hooks
|
|
685
|
+
* - Logs shutdown information
|
|
686
|
+
*
|
|
687
|
+
* Graceful shutdown ensures:
|
|
688
|
+
* - No requests are dropped
|
|
689
|
+
* - Resources are properly cleaned up
|
|
690
|
+
* - Monitoring systems are notified
|
|
691
|
+
*/
|
|
692
|
+
async stop(force = false) {
|
|
693
|
+
if (!this.server) {
|
|
694
|
+
(0, logger_utils_1.getLogger)().warn('Stop called but server is not running');
|
|
695
|
+
return;
|
|
696
|
+
}
|
|
697
|
+
if (this.isShuttingDown) {
|
|
698
|
+
(0, logger_utils_1.getLogger)().warn('Stop called while shutdown is already in progress');
|
|
699
|
+
return;
|
|
700
|
+
}
|
|
701
|
+
this.isShuttingDown = true;
|
|
702
|
+
await this.runHook('beforeStop', this.server);
|
|
703
|
+
const shutdownTimeout = 10000; // 10s max wait
|
|
704
|
+
const serverClosePromise = new Promise((resolve, reject) => {
|
|
705
|
+
this.server.close(async (err) => {
|
|
706
|
+
if (err) {
|
|
707
|
+
(0, logger_utils_1.getLogger)().error({ err }, 'Error while closing server');
|
|
708
|
+
reject(err);
|
|
709
|
+
return;
|
|
710
|
+
}
|
|
711
|
+
this.server = null;
|
|
712
|
+
this.isShuttingDown = false;
|
|
713
|
+
(0, logger_utils_1.getLogger)().info('Server stopped gracefully');
|
|
714
|
+
await this.runHook('afterStop');
|
|
715
|
+
resolve();
|
|
716
|
+
});
|
|
717
|
+
});
|
|
718
|
+
const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(new Error('Shutdown timeout')), shutdownTimeout));
|
|
719
|
+
try {
|
|
720
|
+
await Promise.race([serverClosePromise, timeoutPromise]);
|
|
721
|
+
}
|
|
722
|
+
catch (err) {
|
|
723
|
+
(0, logger_utils_1.getLogger)().error({ err }, 'Graceful shutdown timed out');
|
|
724
|
+
if (force) {
|
|
725
|
+
(0, logger_utils_1.getLogger)().warn('Forcing connection destroy due to shutdown timeout');
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
finally {
|
|
729
|
+
// Always clean up connections
|
|
730
|
+
await this.destroyConnections();
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
/**
|
|
734
|
+
* Enable graceful shutdown on OS signals for production deployment.
|
|
735
|
+
*
|
|
736
|
+
* This is essential for:
|
|
737
|
+
* - Container orchestration (Docker, Kubernetes)
|
|
738
|
+
* - Process managers (PM2, systemd)
|
|
739
|
+
* - Load balancer health checks
|
|
740
|
+
* - Zero-downtime deployments
|
|
741
|
+
*
|
|
742
|
+
* @param signals Array of process signals to listen for (default: SIGINT, SIGTERM)
|
|
743
|
+
*/
|
|
744
|
+
enableGracefulShutdown(signals = ['SIGINT', 'SIGTERM']) {
|
|
745
|
+
signals.forEach(signal => {
|
|
746
|
+
process.on(signal, async () => {
|
|
747
|
+
(0, logger_utils_1.getLogger)().info(`Received ${signal}, initiating graceful shutdown...`);
|
|
748
|
+
try {
|
|
749
|
+
await this.stop();
|
|
750
|
+
process.exit(0);
|
|
751
|
+
}
|
|
752
|
+
catch (err) {
|
|
753
|
+
(0, logger_utils_1.getLogger)().error({ err }, 'Error during graceful shutdown, forcing stop...');
|
|
754
|
+
try {
|
|
755
|
+
await this.stop(true); // fallback to forced shutdown
|
|
756
|
+
process.exit(1);
|
|
757
|
+
}
|
|
758
|
+
catch (forceError) {
|
|
759
|
+
(0, logger_utils_1.getLogger)().fatal({ forceError }, 'Forced shutdown failed, exiting hard');
|
|
760
|
+
process.exit(1);
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
});
|
|
764
|
+
});
|
|
765
|
+
}
|
|
766
|
+
/**
|
|
767
|
+
* Set an externally created base router.
|
|
768
|
+
* This will override the internal rootRouter.
|
|
769
|
+
*/
|
|
770
|
+
setBaseRouter(router) {
|
|
771
|
+
this.externalRouter = router;
|
|
772
|
+
}
|
|
773
|
+
/**
|
|
774
|
+
* Create and register a new router (only used if not injecting one externally - use `setBaseRouter` instead).
|
|
775
|
+
*/
|
|
776
|
+
createRouter(prefix = '') {
|
|
777
|
+
const router = express_1.default.Router();
|
|
778
|
+
const path = this.normalizePath(prefix, true);
|
|
779
|
+
this.rootRouter.use(path, router);
|
|
780
|
+
return router;
|
|
781
|
+
}
|
|
782
|
+
/**
|
|
783
|
+
* Register a new route handler with support for multiple HTTP methods.
|
|
784
|
+
* The route is automatically registered under the globalPrefix if set.
|
|
785
|
+
*
|
|
786
|
+
* @param methods Array of HTTP methods (get, post, put, delete, etc.)
|
|
787
|
+
* @param path Route path with Express path patterns support
|
|
788
|
+
* @param handlers One or more Express request handlers (middleware + final handler)
|
|
789
|
+
* @returns This instance for method chaining
|
|
790
|
+
*/
|
|
791
|
+
registerRoute(methods, path, ...handlers) {
|
|
792
|
+
const fullPath = this.normalizePath(path, true);
|
|
793
|
+
const methodMap = {
|
|
794
|
+
get: this.app.get.bind(this.app),
|
|
795
|
+
post: this.app.post.bind(this.app),
|
|
796
|
+
put: this.app.put.bind(this.app),
|
|
797
|
+
delete: this.app.delete.bind(this.app),
|
|
798
|
+
patch: this.app.patch.bind(this.app),
|
|
799
|
+
options: this.app.options.bind(this.app),
|
|
800
|
+
head: this.app.head.bind(this.app)
|
|
801
|
+
};
|
|
802
|
+
methods.forEach(m => {
|
|
803
|
+
const fn = methodMap[m];
|
|
804
|
+
if (fn) {
|
|
805
|
+
fn(fullPath, ...handlers);
|
|
806
|
+
}
|
|
807
|
+
else {
|
|
808
|
+
throw new Error(`Unsupported HTTP method: ${m}`);
|
|
809
|
+
}
|
|
810
|
+
});
|
|
811
|
+
return this;
|
|
812
|
+
}
|
|
813
|
+
/**
|
|
814
|
+
* Register custom middleware with optional path restriction.
|
|
815
|
+
*
|
|
816
|
+
* Use this for:
|
|
817
|
+
* - Adding authentication to specific routes
|
|
818
|
+
* - Custom logging or validation
|
|
819
|
+
* - Request transformation
|
|
820
|
+
* - Third-party middleware integration
|
|
821
|
+
*
|
|
822
|
+
* @param path Optional path prefix or middleware function if no path
|
|
823
|
+
* @param middleware Middleware handler (required if path is provided)
|
|
824
|
+
* @returns This instance for method chaining
|
|
825
|
+
*/
|
|
826
|
+
registerMiddleware(path, middleware) {
|
|
827
|
+
if (typeof path === 'string') {
|
|
828
|
+
const normalizedPath = this.normalizePath(path);
|
|
829
|
+
if (normalizedPath) {
|
|
830
|
+
this.app.use(normalizedPath, middleware);
|
|
831
|
+
}
|
|
832
|
+
else {
|
|
833
|
+
this.app.use(middleware);
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
else {
|
|
837
|
+
this.app.use(path);
|
|
838
|
+
}
|
|
839
|
+
return this;
|
|
840
|
+
}
|
|
841
|
+
/**
|
|
842
|
+
* Register one or more middleware functions to be applied globally.
|
|
843
|
+
* This is a simpler alternative to registerMiddleware when you just want
|
|
844
|
+
* to add middleware without path restrictions.
|
|
845
|
+
*
|
|
846
|
+
* @param middlewares One or more Express middleware functions
|
|
847
|
+
* @returns This instance for method chaining
|
|
848
|
+
*/
|
|
849
|
+
useMiddleware(...middlewares) {
|
|
850
|
+
middlewares.forEach(middleware => {
|
|
851
|
+
this.app.use(middleware);
|
|
852
|
+
});
|
|
853
|
+
return this;
|
|
854
|
+
}
|
|
855
|
+
/**
|
|
856
|
+
* Get Prometheus registry (to add custom counters/histograms)
|
|
857
|
+
*
|
|
858
|
+
* @return {*} {client.Registry}
|
|
859
|
+
*/
|
|
860
|
+
getMetricsRegistry() {
|
|
861
|
+
return this.register;
|
|
862
|
+
}
|
|
863
|
+
/**
|
|
864
|
+
* Get server configuration
|
|
865
|
+
*
|
|
866
|
+
* @return {*} {ServerConfig}
|
|
867
|
+
*/
|
|
868
|
+
getConfig() {
|
|
869
|
+
return this.config;
|
|
870
|
+
}
|
|
871
|
+
/**
|
|
872
|
+
* Wait until server initialization (middleware + routes) has completed.
|
|
873
|
+
* Useful for integration tests that inspect app before starting.
|
|
874
|
+
*/
|
|
875
|
+
async waitUntilReady() {
|
|
876
|
+
await this.initPromise;
|
|
877
|
+
}
|
|
878
|
+
normalizePath(path, withGlobalPrefix = false) {
|
|
879
|
+
const sanitize = (p) => {
|
|
880
|
+
return ('/' +
|
|
881
|
+
p
|
|
882
|
+
.trim()
|
|
883
|
+
.replace(/^\/+/, '') // remove leading slashes
|
|
884
|
+
.replace(/\/{2,}/g, '/') // collapse multiple slashes
|
|
885
|
+
.replace(/\/+$/, '')); // remove trailing slash
|
|
886
|
+
};
|
|
887
|
+
// Resolve global prefix if enabled
|
|
888
|
+
const prefix = withGlobalPrefix && this.globalPrefix ? sanitize(this.globalPrefix) : '';
|
|
889
|
+
// If path is invalid, default to prefix or root
|
|
890
|
+
if (typeof path !== 'string' || !path.trim()) {
|
|
891
|
+
return prefix || '/';
|
|
892
|
+
}
|
|
893
|
+
return sanitize(prefix + '/' + path);
|
|
894
|
+
}
|
|
895
|
+
normalizeRouteForMetrics(req, res) {
|
|
896
|
+
var _a;
|
|
897
|
+
// Prevent high cardinality metrics by normalizing routes
|
|
898
|
+
if ((_a = req === null || req === void 0 ? void 0 : req.route) === null || _a === void 0 ? void 0 : _a.path) {
|
|
899
|
+
// Use Express route pattern instead of actual URL
|
|
900
|
+
return req.route.path;
|
|
901
|
+
}
|
|
902
|
+
// Group common patterns
|
|
903
|
+
if (res.statusCode === 404)
|
|
904
|
+
return '/404';
|
|
905
|
+
const path = (req.path || 'unknown').split('?')[0];
|
|
906
|
+
// Replace IDs and UUIDs with placeholders
|
|
907
|
+
return path
|
|
908
|
+
.replace(/\/[0-9]+/g, '/:id')
|
|
909
|
+
.replace(/\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g, '/:uuid');
|
|
910
|
+
}
|
|
911
|
+
/**
|
|
912
|
+
* Destroy all active connections (gracefully if possible).
|
|
913
|
+
* If a connection does not close cleanly, it will be force-destroyed.
|
|
914
|
+
*/
|
|
915
|
+
async destroyConnections() {
|
|
916
|
+
const total = this.connections.size;
|
|
917
|
+
if (total === 0) {
|
|
918
|
+
(0, logger_utils_1.getLogger)().debug('No active connections to close');
|
|
919
|
+
return;
|
|
920
|
+
}
|
|
921
|
+
const timeoutMs = 5000;
|
|
922
|
+
await Promise.race([
|
|
923
|
+
Promise.all(Array.from(this.connections).map(conn => new Promise(resolve => {
|
|
924
|
+
conn.end(() => {
|
|
925
|
+
if (!conn.destroyed)
|
|
926
|
+
conn.destroy();
|
|
927
|
+
resolve();
|
|
928
|
+
});
|
|
929
|
+
conn.on('error', () => {
|
|
930
|
+
conn.destroy();
|
|
931
|
+
resolve();
|
|
932
|
+
});
|
|
933
|
+
}))),
|
|
934
|
+
new Promise(resolve => setTimeout(resolve, timeoutMs))
|
|
935
|
+
]);
|
|
936
|
+
this.connections.clear();
|
|
937
|
+
(0, logger_utils_1.getLogger)().info(`Closed ${total} active connections`);
|
|
938
|
+
}
|
|
939
|
+
async validateHttpsFiles() {
|
|
940
|
+
if (!(await (0, fs_utils_1.fileExists)(this.config.https.key))) {
|
|
941
|
+
throw new Error(`HTTPS key file not found: ${this.config.https.key}`);
|
|
942
|
+
}
|
|
943
|
+
if (!(await (0, fs_utils_1.fileExists)(this.config.https.cert))) {
|
|
944
|
+
throw new Error(`HTTPS cert file not found: ${this.config.https.cert}`);
|
|
945
|
+
}
|
|
946
|
+
if (this.config.https.ca && !(await (0, fs_utils_1.fileExists)(this.config.https.ca))) {
|
|
947
|
+
throw new Error(`HTTPS CA file not found: ${this.config.https.ca}`);
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
static isBuiltServerConfig(config) {
|
|
951
|
+
if (config[server_builder_1.BUILD_MARKER]) {
|
|
952
|
+
return true;
|
|
953
|
+
}
|
|
954
|
+
return false;
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
exports.ExpressServer = ExpressServer;
|
|
958
|
+
//# sourceMappingURL=server.js.map
|