@catbee/utils 0.0.8-next.0 → 0.0.8-rc.0

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