@catbee/utils 0.0.4 → 0.0.6

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