@catbee/utils 0.0.5 → 0.0.7

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