@catbee/utils 0.0.5 → 0.0.7

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