@catbee/utils 1.0.5 → 2.0.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +27 -27
  3. package/array/array.utils.d.ts +191 -0
  4. package/array/index.cjs +246 -0
  5. package/array/index.d.ts +25 -0
  6. package/array/index.mjs +228 -0
  7. package/async/async.utils.d.ts +296 -0
  8. package/async/index.cjs +428 -0
  9. package/async/index.d.ts +25 -0
  10. package/async/index.mjs +407 -0
  11. package/cache/cache.utils.d.ts +176 -0
  12. package/cache/index.cjs +292 -0
  13. package/cache/index.d.ts +25 -0
  14. package/cache/index.mjs +290 -0
  15. package/config/config.d.ts +57 -0
  16. package/config/index.cjs +136 -0
  17. package/config/index.d.ts +26 -0
  18. package/config/index.mjs +131 -0
  19. package/context-store/context-store.utils.d.ts +212 -0
  20. package/context-store/index.cjs +267 -0
  21. package/context-store/index.d.ts +25 -0
  22. package/context-store/index.mjs +261 -0
  23. package/crypto/crypto.utils.d.ts +183 -0
  24. package/crypto/index.cjs +182 -0
  25. package/crypto/index.d.ts +25 -0
  26. package/crypto/index.mjs +166 -0
  27. package/date/date.utils.d.ts +190 -0
  28. package/date/index.cjs +295 -0
  29. package/date/index.d.ts +25 -0
  30. package/date/index.mjs +283 -0
  31. package/decorators/decorators.utils.d.ts +705 -0
  32. package/decorators/index.cjs +913 -0
  33. package/decorators/index.d.ts +25 -0
  34. package/decorators/index.mjs +872 -0
  35. package/dir/dir.utils.d.ts +216 -0
  36. package/dir/index.cjs +416 -0
  37. package/dir/index.d.ts +25 -0
  38. package/dir/index.mjs +389 -0
  39. package/env/env.utils.d.ts +400 -0
  40. package/env/index.cjs +761 -0
  41. package/env/index.d.ts +25 -0
  42. package/env/index.mjs +758 -0
  43. package/exception/exception.utils.d.ts +253 -0
  44. package/exception/index.cjs +362 -0
  45. package/exception/index.d.ts +25 -0
  46. package/exception/index.mjs +338 -0
  47. package/fs/fs.utils.d.ts +196 -0
  48. package/fs/index.cjs +253 -0
  49. package/fs/index.d.ts +25 -0
  50. package/fs/index.mjs +228 -0
  51. package/http-status-codes/http-status-codes.d.ts +289 -0
  52. package/http-status-codes/index.cjs +96 -0
  53. package/http-status-codes/index.d.ts +25 -0
  54. package/http-status-codes/index.mjs +94 -0
  55. package/id/id.utils.d.ts +59 -0
  56. package/id/index.cjs +62 -0
  57. package/id/index.d.ts +25 -0
  58. package/id/index.mjs +56 -0
  59. package/index.cjs +218 -0
  60. package/index.d.ts +51 -0
  61. package/index.mjs +51 -0
  62. package/logger/index.cjs +334 -0
  63. package/logger/index.d.ts +25 -0
  64. package/logger/index.mjs +313 -0
  65. package/logger/logger.utils.d.ts +210 -0
  66. package/middleware/index.cjs +177 -0
  67. package/middleware/index.d.ts +25 -0
  68. package/middleware/index.mjs +170 -0
  69. package/middleware/middleware.utils.d.ts +123 -0
  70. package/obj/index.cjs +317 -0
  71. package/obj/index.d.ts +25 -0
  72. package/obj/index.mjs +301 -0
  73. package/obj/obj.utils.d.ts +156 -0
  74. package/package.json +172 -20
  75. package/performance/index.cjs +231 -0
  76. package/performance/index.d.ts +25 -0
  77. package/performance/index.mjs +225 -0
  78. package/performance/performance.utils.d.ts +159 -0
  79. package/request/index.cjs +202 -0
  80. package/request/index.d.ts +26 -0
  81. package/request/index.mjs +194 -0
  82. package/request/request.utils.d.ts +109 -0
  83. package/response/index.cjs +234 -0
  84. package/response/index.d.ts +26 -0
  85. package/response/index.mjs +222 -0
  86. package/response/response.utils.d.ts +186 -0
  87. package/server/index.cjs +1627 -0
  88. package/server/index.d.ts +28 -0
  89. package/server/index.mjs +1617 -0
  90. package/server/server.builder.d.ts +531 -0
  91. package/server/server.d.ts +303 -0
  92. package/stream/index.cjs +151 -0
  93. package/stream/index.d.ts +25 -0
  94. package/stream/index.mjs +144 -0
  95. package/stream/stream.utils.d.ts +111 -0
  96. package/string/index.cjs +109 -0
  97. package/string/index.d.ts +25 -0
  98. package/string/index.mjs +95 -0
  99. package/string/string.utils.d.ts +124 -0
  100. package/type/index.cjs +129 -0
  101. package/type/index.d.ts +25 -0
  102. package/type/index.mjs +119 -0
  103. package/type/type.utils.d.ts +129 -0
  104. package/types/api-response.d.ts +175 -0
  105. package/types/common.d.ts +148 -0
  106. package/types/config.d.ts +88 -0
  107. package/types/index.cjs +34 -0
  108. package/types/index.d.ts +28 -0
  109. package/types/index.mjs +32 -0
  110. package/types/server.d.ts +291 -0
  111. package/url/index.cjs +201 -0
  112. package/url/index.d.ts +25 -0
  113. package/url/index.mjs +189 -0
  114. package/url/url.utils.d.ts +164 -0
  115. package/validate/index.cjs +212 -0
  116. package/validate/index.d.ts +25 -0
  117. package/validate/index.mjs +188 -0
  118. package/validate/validate.utils.d.ts +200 -0
  119. package/build/index.cjs +0 -7579
  120. package/build/index.d.ts +0 -5774
  121. package/build/index.mjs +0 -7274
@@ -0,0 +1,1627 @@
1
+ /*
2
+ * The MIT License
3
+ *
4
+ * Copyright (c) 2025 Catbee Technologies. https://catbee.in/license
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+
25
+ 'use strict';
26
+
27
+ var express = require('express');
28
+ var https = require('https');
29
+ var httpStatusCodes = require('@catbee/utils/http-status-codes');
30
+ var response = require('@catbee/utils/response');
31
+ var middleware = require('@catbee/utils/middleware');
32
+ var env = require('@catbee/utils/env');
33
+ var logger = require('@catbee/utils/logger');
34
+ var exception = require('@catbee/utils/exception');
35
+ var fs$1 = require('fs');
36
+ var config = require('@catbee/utils/config');
37
+ var obj = require('@catbee/utils/obj');
38
+ var fs = require('@catbee/utils/fs');
39
+ var validate = require('@catbee/utils/validate');
40
+ var async = require('@catbee/utils/async');
41
+
42
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
43
+
44
+ var express__default = /*#__PURE__*/_interopDefault(express);
45
+ var https__default = /*#__PURE__*/_interopDefault(https);
46
+ var fs__default = /*#__PURE__*/_interopDefault(fs$1);
47
+
48
+ var __defProp = Object.defineProperty;
49
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
50
+ var BUILD_MARKER = Symbol.for("catbee.express.server.build");
51
+ var ServerConfigBuilder = class {
52
+ static {
53
+ __name(this, "ServerConfigBuilder");
54
+ }
55
+ config = {};
56
+ /**
57
+ * Validates that a port number is valid and usable.
58
+ *
59
+ * @private
60
+ * @param port - The port number to validate
61
+ * @throws {Error} If port is not an integer or is outside the valid range (1-65535)
62
+ */
63
+ validatePort(port) {
64
+ if (!validate.isPort(port)) {
65
+ throw new Error(`Port must be a valid number between 1 and 65535, got: ${port}`);
66
+ }
67
+ }
68
+ /**
69
+ * Sets the port the server will listen on.
70
+ *
71
+ * @param port - The port number (1-65535)
72
+ * @returns The builder instance for chaining
73
+ * @throws {Error} If port is invalid
74
+ * @default 3000 (can be overridden via PORT env variable)
75
+ *
76
+ * @example
77
+ * ```typescript
78
+ * builder.withPort(3000)
79
+ * ```
80
+ */
81
+ withPort(port) {
82
+ this.validatePort(port);
83
+ this.config.port = port;
84
+ return this;
85
+ }
86
+ /**
87
+ * Sets the hostname the server will bind to.
88
+ *
89
+ * @param host - The hostname (e.g., 'localhost', '0.0.0.0', '127.0.0.1')
90
+ * @returns The builder instance for chaining
91
+ * @default '0.0.0.0' (can be overridden via HOST env variable)
92
+ *
93
+ * @example
94
+ * ```typescript
95
+ * builder.withHost('0.0.0.0') // Listen on all interfaces
96
+ * ```
97
+ */
98
+ withHost(host) {
99
+ this.config.host = host;
100
+ return this;
101
+ }
102
+ /**
103
+ * Configures Cross-Origin Resource Sharing (CORS) for the server.
104
+ *
105
+ * @param opts - CORS options object or boolean (true to enable with defaults, false to disable)
106
+ * @returns The builder instance for chaining
107
+ * @default false (CORS is disabled by default)
108
+ *
109
+ * @example
110
+ * ```typescript
111
+ * // Enable CORS with default options
112
+ * builder.withCors(true)
113
+ *
114
+ * // Configure CORS with specific options
115
+ * builder.withCors({
116
+ * origin: ['https://example.com'],
117
+ * methods: ['GET', 'POST']
118
+ * })
119
+ * ```
120
+ */
121
+ withCors(opts) {
122
+ this.config.cors = opts;
123
+ return this;
124
+ }
125
+ /**
126
+ * Enables CORS with default settings
127
+ *
128
+ * @returns The builder instance for chaining
129
+ */
130
+ enableCors() {
131
+ return this.withCors(true);
132
+ }
133
+ /**
134
+ * Disables CORS
135
+ *
136
+ * @returns The builder instance for chaining
137
+ */
138
+ disableCors() {
139
+ return this.withCors(false);
140
+ }
141
+ /**
142
+ * Configures the Helmet middleware for setting HTTP security headers.
143
+ *
144
+ * @param opts - Helmet options object or boolean (true to enable with defaults, false to disable)
145
+ * @returns The builder instance for chaining
146
+ * @default false (Helmet is disabled by default)
147
+ *
148
+ * @example
149
+ * ```typescript
150
+ * // Enable Helmet with default settings
151
+ * builder.withHelmet(true)
152
+ *
153
+ * // Configure Helmet with specific options
154
+ * builder.withHelmet({
155
+ * contentSecurityPolicy: false,
156
+ * xssFilter: true
157
+ * })
158
+ * ```
159
+ */
160
+ withHelmet(opts) {
161
+ this.config.helmet = opts;
162
+ return this;
163
+ }
164
+ /**
165
+ * Enables Helmet with default settings
166
+ *
167
+ * @returns The builder instance for chaining
168
+ */
169
+ enableHelmet() {
170
+ return this.withHelmet(true);
171
+ }
172
+ /**
173
+ * Disables Helmet
174
+ *
175
+ * @returns The builder instance for chaining
176
+ */
177
+ disableHelmet() {
178
+ return this.withHelmet(false);
179
+ }
180
+ /**
181
+ * Configures response compression middleware.
182
+ *
183
+ * @param opts - Compression options object or boolean (true to enable with defaults, false to disable)
184
+ * @returns The builder instance for chaining
185
+ * @default false (Compression is disabled by default)
186
+ *
187
+ * @example
188
+ * ```typescript
189
+ * // Enable compression with default settings
190
+ * builder.withCompression(true)
191
+ *
192
+ * // Configure compression with specific options
193
+ * builder.withCompression({
194
+ * level: 6,
195
+ * threshold: 1024
196
+ * })
197
+ * ```
198
+ */
199
+ withCompression(opts) {
200
+ this.config.compression = opts;
201
+ return this;
202
+ }
203
+ /**
204
+ * Enables compression with default settings
205
+ *
206
+ * @returns The builder instance for chaining
207
+ */
208
+ enableCompression() {
209
+ return this.withCompression(true);
210
+ }
211
+ /**
212
+ * Disables compression
213
+ *
214
+ * @returns The builder instance for chaining
215
+ */
216
+ disableCompression() {
217
+ return this.withCompression(false);
218
+ }
219
+ /**
220
+ * Configures rate limiting to protect against brute-force attacks.
221
+ *
222
+ * @param opts - Rate limit configuration options
223
+ * @returns The builder instance for chaining
224
+ * @default - { enable: false, windowMs: 15 * 60 * 1000, max: 100, message: 'Too many requests', standardHeaders: true, legacyHeaders: false }
225
+ *
226
+ * @example
227
+ * ```typescript
228
+ * builder.withRateLimit({
229
+ * enable: true,
230
+ * windowMs: 15 * 60 * 1000, // 15 minutes
231
+ * max: 100 // limit each IP to 100 requests per windowMs
232
+ * })
233
+ * ```
234
+ */
235
+ withRateLimit(opts) {
236
+ this.mergeConfig("rateLimit", opts);
237
+ return this;
238
+ }
239
+ /**
240
+ * Enables rate limiting with default or custom settings
241
+ *
242
+ * @param opts - Optional rate limit configuration (max requests, window, etc.)
243
+ * @returns The builder instance for chaining
244
+ */
245
+ enableRateLimit(opts = {}) {
246
+ return this.setEnabled("rateLimit", true, opts);
247
+ }
248
+ /**
249
+ * Disables rate limiting
250
+ *
251
+ * @returns The builder instance for chaining
252
+ */
253
+ disableRateLimit() {
254
+ return this.setEnabled("rateLimit", false);
255
+ }
256
+ /**
257
+ * Configures HTTP request logging middleware.
258
+ *
259
+ * @param opts - Request logging configuration options
260
+ * @returns The builder instance for chaining
261
+ * @default - { enable: true in dev/false in prod, ignorePaths: ['/healthz', '/favicon.ico', '/metrics', '/docs', '/.well-known'], skipNotFoundRoutes: false }
262
+ *
263
+ * @example
264
+ * ```typescript
265
+ * builder.withRequestLogging({
266
+ * enable: true,
267
+ * ignorePaths: ['/health', '/metrics'],
268
+ * skipNotFoundRoutes: true
269
+ * })
270
+ * ```
271
+ */
272
+ withRequestLogging(opts) {
273
+ this.mergeConfig("requestLogging", opts);
274
+ return this;
275
+ }
276
+ /**
277
+ * Enables request logging with default or custom settings
278
+ *
279
+ * @param opts - Optional request logging configuration
280
+ * @returns The builder instance for chaining
281
+ */
282
+ enableRequestLogging(opts = {}) {
283
+ return this.setEnabled("requestLogging", true, opts);
284
+ }
285
+ /**
286
+ * Disables request logging
287
+ *
288
+ * @returns The builder instance for chaining
289
+ */
290
+ disableRequestLogging() {
291
+ return this.setEnabled("requestLogging", false);
292
+ }
293
+ /**
294
+ * Configures server metrics collection and endpoints.
295
+ *
296
+ * @param opts - Metrics configuration options
297
+ * @returns The builder instance for chaining
298
+ * @default - { enable: false, path: '/metrics', withGlobalPrefix: false }
299
+ *
300
+ * @example
301
+ * ```typescript
302
+ * builder.withMetrics({
303
+ * enable: true,
304
+ * path: '/metrics'
305
+ * })
306
+ * ```
307
+ */
308
+ withMetrics(opts) {
309
+ this.mergeConfig("metrics", opts);
310
+ return this;
311
+ }
312
+ /**
313
+ * Enables Prometheus metrics collection and endpoint
314
+ *
315
+ * @param opts - Optional metrics configuration
316
+ * @returns The builder instance for chaining
317
+ */
318
+ enableMetrics(opts = {}) {
319
+ return this.setEnabled("metrics", true, opts);
320
+ }
321
+ /**
322
+ * Disables Prometheus metrics
323
+ *
324
+ * @returns The builder instance for chaining
325
+ */
326
+ disableMetrics() {
327
+ return this.setEnabled("metrics", false);
328
+ }
329
+ /**
330
+ * Configures server health check endpoint.
331
+ *
332
+ * @param opts - Health check configuration options
333
+ * @returns The builder instance for chaining
334
+ * @default - { path: '/healthz', detailed: true, withGlobalPrefix: false }
335
+ *
336
+ * @example
337
+ * ```typescript
338
+ * builder.withHealthCheck({
339
+ * path: '/health',
340
+ * detailed: true
341
+ * })
342
+ * ```
343
+ */
344
+ withHealthCheck(opts) {
345
+ this.mergeConfig("healthCheck", opts);
346
+ return this;
347
+ }
348
+ /**
349
+ * Configures OpenAPI/Swagger documentation for the API.
350
+ *
351
+ * @param opts - OpenAPI configuration options
352
+ * @returns The builder instance for chaining
353
+ * @default - { enable: false, mountPath: '/docs', verbose: false, withGlobalPrefix: false }
354
+ *
355
+ * @example
356
+ * ```typescript
357
+ * builder.withOpenApi({
358
+ * enable: true,
359
+ * path: '/api-docs',
360
+ * filePath: './openapi.yaml'
361
+ * })
362
+ * ```
363
+ */
364
+ withOpenApi(opts) {
365
+ this.mergeConfig("openApi", opts);
366
+ return this;
367
+ }
368
+ /**
369
+ * Enables OpenAPI documentation with required file path
370
+ *
371
+ * @param filePath - Path to OpenAPI specification file (required)
372
+ * @param opts - Optional OpenAPI configuration
373
+ * @returns The builder instance for chaining
374
+ */
375
+ enableOpenApi(filePath, opts = {}) {
376
+ this.setEnabled("openApi", true, {
377
+ filePath,
378
+ ...opts
379
+ });
380
+ return this;
381
+ }
382
+ /**
383
+ * Disables OpenAPI documentation
384
+ *
385
+ * @returns The builder instance for chaining
386
+ */
387
+ disableOpenApi() {
388
+ return this.setEnabled("openApi", false);
389
+ }
390
+ /**
391
+ * Configures the server as a microservice with versioning.
392
+ *
393
+ * @param opts - Microservice configuration options including app name and service version
394
+ * @returns The builder instance for chaining
395
+ * @default - { isMicroservice: false, appName: 'express_app' }
396
+ *
397
+ * @example
398
+ * ```typescript
399
+ * builder.withMicroService({
400
+ * appName: 'user-service',
401
+ * serviceVersion: {
402
+ * enable: true,
403
+ * version: '1.2.3'
404
+ * }
405
+ * })
406
+ * ```
407
+ */
408
+ withMicroService(opts) {
409
+ this.config.isMicroservice = true;
410
+ this.config.appName = opts.appName;
411
+ this.mergeConfig("serviceVersion", opts.serviceVersion);
412
+ return this;
413
+ }
414
+ /**
415
+ * Configures the trust proxy settings to determine if X-Forwarded-* headers should be trusted.
416
+ *
417
+ * @param opts - Trust proxy configuration options
418
+ * @returns The builder instance for chaining
419
+ * @default false
420
+ *
421
+ * @example
422
+ * ```typescript
423
+ * // Trust proxy headers (useful when behind a load balancer)
424
+ * builder.withTrustProxy(true)
425
+ * ```
426
+ */
427
+ withTrustProxy(opts) {
428
+ this.config.trustProxy = opts;
429
+ return this;
430
+ }
431
+ /**
432
+ * Configures the request ID middleware for tracing requests across services.
433
+ *
434
+ * @param opts - Request ID configuration options
435
+ * @returns The builder instance for chaining
436
+ * @default - { headerName: 'x-request-id', exposeHeader: true }
437
+ *
438
+ * @example
439
+ * ```typescript
440
+ * builder.withRequestId({
441
+ * headerName: 'X-Request-Id',
442
+ * generator: () => crypto.randomUUID()
443
+ * })
444
+ * ```
445
+ */
446
+ withRequestId(opts) {
447
+ this.mergeConfig("requestId", opts);
448
+ return this;
449
+ }
450
+ /**
451
+ * Configures the response time middleware for measuring request processing times.
452
+ *
453
+ * @param opts - Response time configuration options
454
+ * @returns The builder instance for chaining
455
+ * @default - { enable: false, addHeader: true, logOnComplete: false }
456
+ *
457
+ * @example
458
+ * ```typescript
459
+ * builder.withResponseTime({
460
+ * enable: true,
461
+ * addHeader: true,
462
+ * logOnComplete: true
463
+ * })
464
+ * ```
465
+ */
466
+ withResponseTime(opts) {
467
+ this.mergeConfig("responseTime", opts);
468
+ return this;
469
+ }
470
+ /**
471
+ * Enables response time tracking with default or custom settings
472
+ *
473
+ * @param opts - Optional response time configuration
474
+ * @returns The builder instance for chaining
475
+ */
476
+ enableResponseTime(opts = {}) {
477
+ this.setEnabled("responseTime", true, opts);
478
+ return this;
479
+ }
480
+ /**
481
+ * Disables response time tracking
482
+ *
483
+ * @returns The builder instance for chaining
484
+ */
485
+ disableResponseTime() {
486
+ return this.setEnabled("responseTime", false);
487
+ }
488
+ /**
489
+ * Configures the body parser middleware options for parsing request bodies.
490
+ *
491
+ * @param opts - Body parser configuration options
492
+ * @returns The builder instance for chaining
493
+ * @default - { json: { limit: '1mb' }, urlencoded: { extended: true, limit: '1mb' } }
494
+ *
495
+ * @example
496
+ * ```typescript
497
+ * builder.withBodyParser({
498
+ * json: {
499
+ * limit: '1mb'
500
+ * },
501
+ * urlencoded: {
502
+ * extended: true,
503
+ * limit: '1mb'
504
+ * }
505
+ * })
506
+ * ```
507
+ */
508
+ withBodyParser(opts) {
509
+ this.config.bodyParser = obj.deepObjMerge({}, this.config.bodyParser ?? {}, opts);
510
+ return this;
511
+ }
512
+ /**
513
+ * Configures cookie parsing middleware.
514
+ *
515
+ * @param opts - Cookie parser options or boolean (true to enable with defaults, false to disable)
516
+ * @returns The builder instance for chaining
517
+ * @default false
518
+ *
519
+ * @example
520
+ * ```typescript
521
+ * // Enable cookie parsing with default options
522
+ * builder.withCookies(true)
523
+ *
524
+ * // Enable cookie parsing with specific options
525
+ * builder.withCookies({
526
+ * secret: 'your-secret-key',
527
+ * secure: true
528
+ * })
529
+ * ```
530
+ */
531
+ withCookies(opts) {
532
+ this.config.cookieParser = opts;
533
+ return this;
534
+ }
535
+ /**
536
+ * Adds a static folder to serve files from.
537
+ *
538
+ * @param folder - Static folder configuration
539
+ * @returns The builder instance for chaining
540
+ *
541
+ * @example
542
+ * ```typescript
543
+ * builder.withStaticFolder({
544
+ * path: '/assets',
545
+ * directory: './public',
546
+ * options: { maxAge: '1d' }
547
+ * })
548
+ * ```
549
+ */
550
+ withStaticFolder(folder) {
551
+ if (!folder.path) throw new Error("Static folder requires a path");
552
+ const folders = [
553
+ ...this.config.staticFolders ?? [],
554
+ folder
555
+ ];
556
+ this.config.staticFolders = Array.from(new Map(folders.map((f) => [
557
+ f.path,
558
+ f
559
+ ])).values());
560
+ return this;
561
+ }
562
+ /**
563
+ * Sets global headers to be included in all responses.
564
+ *
565
+ * @param headers - Object containing header name/value pairs or functions that return values
566
+ * @returns The builder instance for chaining
567
+ * @default - {}
568
+ *
569
+ * @example
570
+ * ```typescript
571
+ * builder.withGlobalHeaders({
572
+ * 'X-Powered-By': 'Catbee',
573
+ * 'Server-Time': () => new Date().toISOString()
574
+ * })
575
+ * ```
576
+ */
577
+ withGlobalHeaders(headers) {
578
+ this.mergeConfig("globalHeaders", headers);
579
+ return this;
580
+ }
581
+ /**
582
+ * Sets a global prefix for all routes.
583
+ *
584
+ * @param prefix - The prefix to prepend to all routes (e.g., '/api/v1')
585
+ * @returns The builder instance for chaining
586
+ * @default '/'
587
+ *
588
+ * @example
589
+ * ```typescript
590
+ * builder.withGlobalPrefix('/api/v1')
591
+ * ```
592
+ */
593
+ withGlobalPrefix(prefix) {
594
+ this.config.globalPrefix = prefix;
595
+ return this;
596
+ }
597
+ /**
598
+ * Applies custom configuration overrides directly.
599
+ *
600
+ * @param overrides - Custom configuration options to merge
601
+ * @returns The builder instance for chaining
602
+ *
603
+ * @example
604
+ * ```typescript
605
+ * builder.withCustom({
606
+ * port: 8080,
607
+ * customMiddleware: myMiddlewareFunction
608
+ * })
609
+ * ```
610
+ */
611
+ withCustom(overrides) {
612
+ this.config = obj.deepObjMerge({}, this.config, overrides);
613
+ return this;
614
+ }
615
+ /**
616
+ * Configures HTTPS server options.
617
+ *
618
+ * @param opts - HTTPS configuration (key, cert, ca, passphrase, etc.)
619
+ * @returns The builder instance for chaining
620
+ *
621
+ * @example
622
+ * ```typescript
623
+ * builder.withHttps({
624
+ * key: './localhost-key.pem',
625
+ * cert: './localhost-cert.pem'
626
+ * })
627
+ * ```
628
+ */
629
+ withHttps(opts) {
630
+ this.config.https = opts;
631
+ return this;
632
+ }
633
+ /**
634
+ * Builds and returns the final server configuration.
635
+ *
636
+ * This method merges the user-specified configuration with default values,
637
+ * ensures all sections with 'enable' flags are properly structured, and
638
+ * produces the final configuration to be used by the server.
639
+ *
640
+ * @returns The complete ServerConfig object
641
+ *
642
+ * @example
643
+ * ```typescript
644
+ * const config = new ServerConfigBuilder()
645
+ * .withPort(3000)
646
+ * .withHost('localhost')
647
+ * .withCors(true)
648
+ * .build();
649
+ * ```
650
+ */
651
+ build() {
652
+ const config$1 = obj.deepObjMerge({}, config.defaultServerConfig, this.config);
653
+ if (config$1.openApi?.enable && !config$1.openApi.filePath) {
654
+ throw new Error("OpenAPI is enabled but no filePath is specified");
655
+ }
656
+ return Object.freeze({
657
+ ...config$1,
658
+ [BUILD_MARKER]: true
659
+ });
660
+ }
661
+ mergeConfig(key, value) {
662
+ const current = typeof this.config[key] === "object" && this.config[key] !== null ? this.config[key] : {};
663
+ this.config[key] = obj.deepObjMerge({}, current, value);
664
+ }
665
+ setEnabled(key, enable, overrides = {}) {
666
+ this.mergeConfig(key, {
667
+ ...overrides,
668
+ enable
669
+ });
670
+ return this;
671
+ }
672
+ };
673
+
674
+ // src/server/server.ts
675
+ var getDependencyErrorMessage = /* @__PURE__ */ __name((packageName, x) => `Missing required dependency ${x ? `for ${x}` : ""}: ${packageName}. Please install it to proceed.`, "getDependencyErrorMessage");
676
+ var DependencyErrors = {
677
+ express: getDependencyErrorMessage("express"),
678
+ helmet: getDependencyErrorMessage("helmet"),
679
+ cors: getDependencyErrorMessage("cors"),
680
+ compression: getDependencyErrorMessage("compression"),
681
+ "express-rate-limit": getDependencyErrorMessage("express-rate-limit"),
682
+ "cookie-parser": getDependencyErrorMessage("cookie-parser"),
683
+ "@scalar/express-api-reference": getDependencyErrorMessage("@scalar/express-api-reference"),
684
+ "prom-client": getDependencyErrorMessage("prom-client")
685
+ };
686
+ var ExpressServer = class {
687
+ static {
688
+ __name(this, "ExpressServer");
689
+ }
690
+ /** Prometheus client registry for metrics collection */
691
+ register = null;
692
+ /** HTTP server instance (null when not running) */
693
+ server = null;
694
+ /** Merged configuration with defaults applied */
695
+ config;
696
+ /** User-defined lifecycle hooks */
697
+ hooks;
698
+ /** Global API prefix (from config) */
699
+ globalPrefix;
700
+ /** Internal fallback router */
701
+ rootRouter;
702
+ /** User-supplied router */
703
+ externalRouter;
704
+ /** Internal Express app instance */
705
+ app;
706
+ /** Set of active WebSocket connections */
707
+ connections = /* @__PURE__ */ new Set();
708
+ /** Flag indicating if the server is shutting down */
709
+ isShuttingDown = false;
710
+ /**
711
+ * Collection of registered health check functions.
712
+ * These are executed when the health check endpoint is accessed.
713
+ */
714
+ healthChecks = [];
715
+ /** Prometheus metrics for monitoring */
716
+ requestCounter;
717
+ routeTimings;
718
+ requestSizes;
719
+ clientIPs;
720
+ /** Promise that resolves when initialization (middleware + routes) is complete */
721
+ initPromise;
722
+ /**
723
+ * Initializes server with intelligent defaults and security best practices.
724
+ * All settings can be customized via config and hooks.
725
+ *
726
+ * Default Security:
727
+ * - Secure headers (Helmet)
728
+ * - Rate limiting
729
+ * - Request timeouts
730
+ * - Body size limits
731
+ * - CORS protection
732
+ *
733
+ * Default Monitoring:
734
+ * - Request/Response logging
735
+ * - Prometheus metrics
736
+ * - Health checks
737
+ * - Request tracing
738
+ */
739
+ constructor(config$1, hooks = {}) {
740
+ if (this.isBuiltServerConfig(config$1)) {
741
+ this.config = config$1;
742
+ } else {
743
+ this.config = obj.deepObjMerge({}, config.defaultServerConfig, config$1);
744
+ }
745
+ if (!validate.isPort(this.config.port)) {
746
+ const msg = `Port must be a valid number between 1 and 65535, got: ${this.config.port}`;
747
+ logger.getLogger().error(msg);
748
+ throw new Error(msg);
749
+ }
750
+ const safeAppName = (this.config.appName || "express_app").toLowerCase().replace(/[^a-z0-9_]/g, "_");
751
+ if (this.config.metrics?.enable) {
752
+ const client = async.optionalRequire("prom-client");
753
+ if (!client) {
754
+ this.throwDependancyError("prom-client");
755
+ }
756
+ this.register = new client.Registry();
757
+ this.requestCounter = new client.Counter({
758
+ name: `${safeAppName}_http_requests_total`,
759
+ help: "Total HTTP requests",
760
+ labelNames: [
761
+ "method",
762
+ "route",
763
+ "status"
764
+ ],
765
+ registers: [
766
+ this.register
767
+ ]
768
+ });
769
+ this.routeTimings = new client.Histogram({
770
+ name: `${safeAppName}_http_request_duration_seconds`,
771
+ help: "Duration of HTTP requests by route",
772
+ labelNames: [
773
+ "method",
774
+ "route",
775
+ "status"
776
+ ],
777
+ buckets: [
778
+ 0.1,
779
+ 0.3,
780
+ 0.5,
781
+ 0.7,
782
+ 1,
783
+ 3,
784
+ 5,
785
+ 7,
786
+ 10
787
+ ],
788
+ registers: [
789
+ this.register
790
+ ]
791
+ });
792
+ this.requestSizes = new client.Histogram({
793
+ name: `${safeAppName}_http_request_size_bytes`,
794
+ help: "Size of HTTP request bodies",
795
+ labelNames: [
796
+ "method",
797
+ "route"
798
+ ],
799
+ buckets: [
800
+ 100,
801
+ 1e3,
802
+ 1e4,
803
+ 1e5,
804
+ 1e6
805
+ ],
806
+ registers: [
807
+ this.register
808
+ ]
809
+ });
810
+ this.clientIPs = new client.Counter({
811
+ name: `${safeAppName}_http_client_ip_total`,
812
+ help: "Client IP request counter",
813
+ labelNames: [
814
+ "ip",
815
+ "method"
816
+ ],
817
+ registers: [
818
+ this.register
819
+ ]
820
+ });
821
+ client.collectDefaultMetrics({
822
+ register: this.register,
823
+ prefix: `${safeAppName}_`
824
+ });
825
+ }
826
+ if (config$1?.healthCheck?.checks) {
827
+ this.healthChecks.push(...config$1.healthCheck.checks);
828
+ }
829
+ this.globalPrefix = this.normalizePath(this.config.globalPrefix ?? "", false);
830
+ this.hooks = hooks;
831
+ this.app = express__default.default();
832
+ this.rootRouter = express__default.default.Router();
833
+ this.initPromise = this.initialize();
834
+ }
835
+ /**
836
+ * Execute a lifecycle hook safely with comprehensive error handling.
837
+ * Prevents hook failures from crashing the server while logging issues.
838
+ *
839
+ * @param hook Name of the lifecycle hook to execute
840
+ * @param args Arguments to pass to the hook function
841
+ */
842
+ async runHook(hook, ...args) {
843
+ try {
844
+ const fn = this.hooks[hook];
845
+ if (fn) await fn.apply(null, args);
846
+ } catch (err) {
847
+ logger.getLogger().error({
848
+ err,
849
+ hook
850
+ }, `Error executing ${hook} hook:`);
851
+ }
852
+ }
853
+ /**
854
+ * Initialize the Express server with middleware and routes.
855
+ */
856
+ async initialize() {
857
+ await this.runHook("beforeInit", this);
858
+ await this.setupMiddleware();
859
+ await this.setupRoutes();
860
+ await this.runHook("afterInit", this);
861
+ }
862
+ /**
863
+ * Configure and register all middlewares in the optimal order.
864
+ *
865
+ * Middleware Order (CRITICAL - don't change without understanding implications):
866
+ * 1. Basic server configuration (trust proxy, x-powered-by)
867
+ * 2. Request ID generation (for tracing)
868
+ * 3. Request context setup (for logging correlation)
869
+ * 4. Timeout protection (prevents hanging requests)
870
+ * 5. Response time tracking (for performance monitoring)
871
+ * 6. Request logging (after ID/context setup)
872
+ * 7. Custom request hooks
873
+ * 8. Security middleware (rate limiting, CORS, Helmet)
874
+ * 9. Response compression
875
+ * 10. Static file serving
876
+ * 11. Request parsing (body parsing, cookies)
877
+ * 12. API documentation (OpenAPI)
878
+ * 13. Global headers
879
+ * 14. Custom response hooks
880
+ */
881
+ async setupMiddleware() {
882
+ if (this.config.https) {
883
+ await this.validateHttpsFiles();
884
+ }
885
+ this.app.disable("x-powered-by");
886
+ if (this.config.trustProxy) {
887
+ this.app.set("trust proxy", true);
888
+ }
889
+ this.app.use(middleware.requestId({
890
+ headerName: this.config.requestId?.headerName,
891
+ exposeHeader: this.config.requestId?.exposeHeader,
892
+ generator: this.config.requestId?.generator
893
+ }));
894
+ this.app.use(middleware.setupRequestContext({
895
+ headerName: this.config.requestId?.headerName,
896
+ autoLog: false
897
+ }));
898
+ this.app.use((_req, res, next) => {
899
+ if (this.isShuttingDown) {
900
+ res.setHeader("Connection", "close");
901
+ return res.status(httpStatusCodes.HttpStatusCodes.SERVICE_UNAVAILABLE).json(new exception.ServiceUnavailableException("Server is shutting down"));
902
+ }
903
+ next();
904
+ return;
905
+ });
906
+ if (this.config.helmet) {
907
+ const helmet = async.optionalRequire("helmet");
908
+ if (!helmet) {
909
+ this.throwDependancyError("helmet");
910
+ }
911
+ if (typeof this.config.helmet === "object") {
912
+ this.app.use(helmet(this.config.helmet));
913
+ } else {
914
+ this.app.use(helmet());
915
+ }
916
+ }
917
+ if (this.config.cors) {
918
+ const cors = async.optionalRequire("cors");
919
+ if (!cors) {
920
+ this.throwDependancyError("cors");
921
+ }
922
+ this.app.use(cors(this.config.cors === true ? {} : this.config.cors));
923
+ }
924
+ this.app.use((_req, res, next) => {
925
+ if (this.config.globalHeaders) {
926
+ for (const key in this.config.globalHeaders) {
927
+ const value = this.config.globalHeaders[key];
928
+ res.setHeader(key, typeof value === "function" ? value() : value);
929
+ }
930
+ }
931
+ if (this.config.isMicroservice) {
932
+ res.setHeader("X-Microservice", this.config.appName || "express_app");
933
+ }
934
+ if (this.config.serviceVersion?.enable) {
935
+ const version = typeof this.config.serviceVersion?.version === "function" ? this.config.serviceVersion.version() : this.config.serviceVersion?.version;
936
+ res.setHeader(this.config.serviceVersion?.headerName || "x-service-version", version || "0.0.0");
937
+ }
938
+ next();
939
+ });
940
+ if (this.config.requestTimeout) {
941
+ this.app.use(middleware.timeout(this.config.requestTimeout));
942
+ }
943
+ if (this.config.responseTime?.enable) {
944
+ this.app.use(middleware.responseTime({
945
+ addHeader: this.config.responseTime.addHeader,
946
+ logOnComplete: this.config.responseTime.logOnComplete
947
+ }));
948
+ }
949
+ if (this.config.rateLimit?.enable) {
950
+ const rateLimit = async.optionalRequire("express-rate-limit");
951
+ if (!rateLimit) {
952
+ this.throwDependancyError("express-rate-limit");
953
+ }
954
+ this.app.use(rateLimit({
955
+ windowMs: this.config.rateLimit.windowMs ?? 15 * 60 * 1e3,
956
+ max: this.config.rateLimit.max ?? 100,
957
+ handler: /* @__PURE__ */ __name((req, res) => {
958
+ const status = httpStatusCodes.HttpStatusCodes.TOO_MANY_REQUESTS;
959
+ const response$1 = response.createFinalErrorResponse(req, status, this.config.rateLimit?.message || "Too many requests");
960
+ res.status(status).json(response$1);
961
+ }, "handler"),
962
+ standardHeaders: this.config.rateLimit.standardHeaders ?? true,
963
+ legacyHeaders: this.config.rateLimit.legacyHeaders ?? false
964
+ }));
965
+ }
966
+ if (this.config.requestLogging?.enable) {
967
+ this.app.use((req, res, next) => {
968
+ if (typeof this.config.requestLogging?.ignorePaths === "function") {
969
+ const skip = this.config.requestLogging?.ignorePaths?.(req, res);
970
+ if (skip) return next();
971
+ } else if (Array.isArray(this.config.requestLogging?.ignorePaths)) {
972
+ const skip = this.config.requestLogging?.ignorePaths?.some((path) => req.path.startsWith(path));
973
+ if (skip) return next();
974
+ }
975
+ const logger$1 = logger.getLogger();
976
+ const incomingRequestMetaData = {
977
+ requestId: req.id,
978
+ method: req.method,
979
+ url: req.originalUrl || req.url,
980
+ ip: req.ip
981
+ };
982
+ logger$1.info(incomingRequestMetaData, "Incoming Request");
983
+ next();
984
+ });
985
+ }
986
+ if (this.hooks.onRequest) {
987
+ this.app.use(this.hooks.onRequest);
988
+ }
989
+ if (this.config.compression) {
990
+ const compression = async.optionalRequire("compression");
991
+ if (!compression) {
992
+ this.throwDependancyError("compression");
993
+ }
994
+ if (typeof this.config.compression === "object") {
995
+ this.app.use(compression(this.config.compression));
996
+ } else {
997
+ this.app.use(compression());
998
+ }
999
+ }
1000
+ if (this.config.staticFolders) {
1001
+ this.config.staticFolders.forEach((folder) => {
1002
+ this.app.use(this.normalizePath(folder.path ?? "/"), express__default.default.static(folder.directory, {
1003
+ maxAge: folder.maxAge || 0,
1004
+ etag: folder.etag !== false,
1005
+ immutable: folder.immutable === true,
1006
+ lastModified: folder.lastModified !== false,
1007
+ cacheControl: folder.cacheControl !== false
1008
+ }));
1009
+ logger.getLogger().info(`Serving static folder: ${folder.directory} at path ${folder.path || "/"}`);
1010
+ });
1011
+ }
1012
+ if (this.config.bodyParser) {
1013
+ if (this.config.bodyParser.json) {
1014
+ this.app.use(express__default.default.json(this.config.bodyParser.json));
1015
+ }
1016
+ if (this.config.bodyParser.urlencoded) {
1017
+ this.app.use(express__default.default.urlencoded(this.config.bodyParser.urlencoded));
1018
+ }
1019
+ }
1020
+ if (this.config.cookieParser) {
1021
+ const cookieParser = async.optionalRequire("cookie-parser");
1022
+ if (!cookieParser) {
1023
+ this.throwDependancyError("cookie-parser");
1024
+ }
1025
+ if (typeof this.config.cookieParser === "object") {
1026
+ this.app.use(cookieParser(void 0, this.config.cookieParser));
1027
+ } else {
1028
+ this.app.use(cookieParser());
1029
+ }
1030
+ }
1031
+ if (this.config.openApi?.enable) {
1032
+ try {
1033
+ const openApiMountPath = this.normalizePath(this.config.openApi.mountPath ?? "/docs", this.config.openApi.withGlobalPrefix);
1034
+ const openApiFilePath = this.config.openApi.filePath;
1035
+ if (!openApiFilePath) {
1036
+ const msg = "OpenAPI file path is required";
1037
+ logger.getLogger().error(msg);
1038
+ throw new Error(msg);
1039
+ }
1040
+ const isOpenApiFilePathExists = await fs.fileExists(openApiFilePath);
1041
+ if (!isOpenApiFilePathExists) {
1042
+ const msg = `OpenAPI spec file not found at ${openApiFilePath}`;
1043
+ logger.getLogger().error(msg);
1044
+ throw new Error(msg);
1045
+ }
1046
+ if (this.config.openApi?.verbose) {
1047
+ logger.getLogger().info(`Mounting OpenAPI docs at ${openApiMountPath}`);
1048
+ logger.getLogger().info(`Using OpenAPI spec file at ${openApiFilePath}`);
1049
+ }
1050
+ const apiReference = async.optionalRequire("@scalar/express-api-reference")?.apiReference;
1051
+ if (!apiReference) {
1052
+ this.throwDependancyError("@scalar/express-api-reference", getDependencyErrorMessage("@scalar/express-api-reference", "OpenAPI docs"));
1053
+ }
1054
+ this.app.use(openApiMountPath, apiReference({
1055
+ spec: {
1056
+ content: await fs__default.default.promises.readFile(openApiFilePath, "utf8")
1057
+ }
1058
+ }));
1059
+ if (this.config.openApi?.verbose) {
1060
+ logger.getLogger().info(`Mounted OpenAPI docs at ${openApiMountPath}`);
1061
+ }
1062
+ } catch (err) {
1063
+ logger.getLogger().error({
1064
+ err
1065
+ }, "Failed to mount OpenAPI docs");
1066
+ }
1067
+ }
1068
+ if (this.hooks.onResponse) {
1069
+ this.app.use(this.globalPrefix, this.hooks.onResponse);
1070
+ }
1071
+ if (this.config.metrics?.enable) {
1072
+ this.app.use((req, res, next) => {
1073
+ const start = process.hrtime();
1074
+ this.clientIPs?.inc({
1075
+ ip: req.ip,
1076
+ method: req.method
1077
+ });
1078
+ const cl = req.headers["content-length"];
1079
+ if (cl) {
1080
+ const size = Number(cl);
1081
+ if (!Number.isNaN(size) && size >= 0) {
1082
+ const route = this.normalizeRouteForMetrics(req, res);
1083
+ this.requestSizes?.observe({
1084
+ method: req.method,
1085
+ route
1086
+ }, size);
1087
+ }
1088
+ }
1089
+ res.once("finish", () => {
1090
+ const [seconds, nanoseconds] = process.hrtime(start);
1091
+ const finalRoute = this.normalizeRouteForMetrics(req, res);
1092
+ this.requestCounter?.inc({
1093
+ method: req.method,
1094
+ route: finalRoute,
1095
+ status: res.statusCode.toString()
1096
+ });
1097
+ this.routeTimings?.observe({
1098
+ method: req.method,
1099
+ route: finalRoute,
1100
+ status: res.statusCode.toString()
1101
+ }, seconds + nanoseconds / 1e9);
1102
+ });
1103
+ next();
1104
+ });
1105
+ }
1106
+ }
1107
+ /**
1108
+ * Configure server routes and error handling.
1109
+ * Sets up in following order:
1110
+ *
1111
+ * 1. Built-in routes (health, metrics)
1112
+ * 2. Application routes
1113
+ * 3. 404 handler
1114
+ * 4. Error handler
1115
+ */
1116
+ async setupRoutes() {
1117
+ const healthCheckPath = this.normalizePath(this.config.healthCheck?.path || "/healthz", this.config.healthCheck?.withGlobalPrefix);
1118
+ this.app.get(healthCheckPath, async (_req, res) => {
1119
+ try {
1120
+ if (!this.healthChecks.length || config.defaultCatbeeConfig.server.skipHealthz) {
1121
+ return res.status(httpStatusCodes.HttpStatusCodes.OK).json(new response.SuccessResponse("OK"));
1122
+ }
1123
+ const checkResults = await Promise.allSettled(this.healthChecks.map(async ({ name, check }) => {
1124
+ try {
1125
+ const status2 = await Promise.resolve(check());
1126
+ return {
1127
+ name,
1128
+ status: status2,
1129
+ error: null
1130
+ };
1131
+ } catch (error) {
1132
+ return {
1133
+ name,
1134
+ status: false,
1135
+ error: error.message
1136
+ };
1137
+ }
1138
+ }));
1139
+ const results = checkResults.map((result) => {
1140
+ if (result.status === "fulfilled") return result.value;
1141
+ return {
1142
+ name: "unknown",
1143
+ status: false,
1144
+ error: result.reason
1145
+ };
1146
+ });
1147
+ const allOk = results.every((r) => r.status);
1148
+ const status = allOk ? httpStatusCodes.HttpStatusCodes.OK : httpStatusCodes.HttpStatusCodes.SERVICE_UNAVAILABLE;
1149
+ const response$1 = new response.SuccessResponse(allOk ? "OK" : "Service unavailable");
1150
+ if (!allOk) response$1.error = true;
1151
+ if (this.config.healthCheck?.detailed) response$1.data = {
1152
+ checks: results
1153
+ };
1154
+ return res.status(status).json(response$1);
1155
+ } catch {
1156
+ return res.status(httpStatusCodes.HttpStatusCodes.INTERNAL_SERVER_ERROR).json(new exception.InternalServerErrorException("Health check failed"));
1157
+ }
1158
+ });
1159
+ if (this.config.metrics?.enable) {
1160
+ const metricsPath = this.normalizePath(this.config.metrics.path ?? "/metrics", this.config.metrics?.withGlobalPrefix);
1161
+ this.app.get(metricsPath, async (_req, res) => {
1162
+ res.set("Content-Type", this.register.contentType);
1163
+ res.end(await this.register.metrics());
1164
+ });
1165
+ }
1166
+ const routerToUse = this.externalRouter || this.rootRouter;
1167
+ this.app.use(this.globalPrefix, routerToUse);
1168
+ this.app.use((req, res) => {
1169
+ const status = httpStatusCodes.HttpStatusCodes.NOT_FOUND;
1170
+ const response$1 = response.createFinalErrorResponse(req, status, `Route ${req.method.toUpperCase()} ${req.path} not found`);
1171
+ res.status(status).json(response$1);
1172
+ });
1173
+ this.app.use((err, req, res, next) => {
1174
+ const isNotFoundError = err instanceof exception.NotFoundException;
1175
+ const shouldSkipLogging = !this.hooks.onError && isNotFoundError && this.config.requestLogging?.enable && this.config.requestLogging.skipNotFoundRoutes === true;
1176
+ if (this.hooks.onError) {
1177
+ this.hooks.onError(err, req, res, next);
1178
+ } else {
1179
+ const errorHandlerMiddleware = middleware.errorHandler({
1180
+ logErrors: !shouldSkipLogging,
1181
+ includeDetails: env.Env.isDev()
1182
+ // Only show stack traces in development
1183
+ });
1184
+ errorHandlerMiddleware(err, req, res, next);
1185
+ }
1186
+ });
1187
+ }
1188
+ /**
1189
+ * Register a new health check function for monitoring service dependencies.
1190
+ *
1191
+ * Health checks are executed when the health endpoint is accessed and
1192
+ * help determine if the service is ready to handle requests.
1193
+ *
1194
+ * Examples:
1195
+ * - Database connectivity
1196
+ * - External service availability
1197
+ * - File system access
1198
+ * - Memory/CPU usage checks
1199
+ *
1200
+ * @param name Unique identifier for the check (used in detailed responses)
1201
+ * @param check Function returning boolean or Promise<boolean> indicating health
1202
+ * @returns This instance for method chaining
1203
+ */
1204
+ registerHealthCheck(name, check) {
1205
+ this.healthChecks.push({
1206
+ name,
1207
+ check
1208
+ });
1209
+ return this;
1210
+ }
1211
+ /**
1212
+ * Run registered health checks and return whether the service is ready.
1213
+ * Useful for readiness probes in deployment tooling.
1214
+ *
1215
+ * @returns Promise resolving to `true` when all checks pass, otherwise `false`.
1216
+ */
1217
+ async ready() {
1218
+ try {
1219
+ if (!this.healthChecks.length || config.defaultCatbeeConfig.server.skipHealthz) return true;
1220
+ const checkResults = await Promise.allSettled(this.healthChecks.map(async ({ name, check }) => {
1221
+ try {
1222
+ const status = await Promise.resolve(check());
1223
+ return {
1224
+ name,
1225
+ status,
1226
+ error: null
1227
+ };
1228
+ } catch (error) {
1229
+ return {
1230
+ name,
1231
+ status: false,
1232
+ error: error.message
1233
+ };
1234
+ }
1235
+ }));
1236
+ const results = checkResults.map((result) => result.status === "fulfilled" ? result.value : {
1237
+ name: "unknown",
1238
+ status: false,
1239
+ error: result.reason
1240
+ });
1241
+ return results.every((r) => r.status === true);
1242
+ } catch (err) {
1243
+ logger.getLogger().error({
1244
+ err
1245
+ }, "Error while running readiness checks");
1246
+ return false;
1247
+ }
1248
+ }
1249
+ /**
1250
+ * Get the underlying Express application instance.
1251
+ * Use this for advanced Express features not exposed by this wrapper.
1252
+ *
1253
+ * @returns The raw Express app instance
1254
+ */
1255
+ getApp() {
1256
+ return this.app;
1257
+ }
1258
+ /**
1259
+ * Get the active HTTP/HTTPS server instance.
1260
+ * Returns null if the server is not currently running.
1261
+ *
1262
+ * @returns The HTTP/HTTPS server instance or null
1263
+ */
1264
+ getServer() {
1265
+ return this.server;
1266
+ }
1267
+ /**
1268
+ * Start the HTTP server and begin listening for requests.
1269
+ *
1270
+ * This method:
1271
+ * - Executes beforeStart hooks
1272
+ * - Binds to the configured host/port
1273
+ * - Sets up error handling for startup failures
1274
+ * - Executes afterStart hooks on success
1275
+ * - Logs startup information
1276
+ *
1277
+ * @returns Promise resolving to the running HTTP server instance
1278
+ * @throws Error if server fails to start or port is already in use
1279
+ */
1280
+ async start() {
1281
+ await this.initPromise;
1282
+ await this.runHook("beforeStart", this.app);
1283
+ return new Promise((resolve, reject) => {
1284
+ try {
1285
+ const listenArgs = [
1286
+ this.config.port,
1287
+ this.config.host,
1288
+ async () => {
1289
+ const protocol = this.config.https ? "https" : "http";
1290
+ const url = `${protocol}://${this.config.host}:${this.config.port}`;
1291
+ logger.getLogger().info(`Server running on ${url}`);
1292
+ if (this.config.healthCheck?.path) {
1293
+ logger.getLogger().info(`Health check available at ${url}${this.normalizePath(this.config.healthCheck.path, this.config.healthCheck.withGlobalPrefix)}`);
1294
+ }
1295
+ if (this.config.metrics?.enable && this.config.metrics.path) {
1296
+ logger.getLogger().info(`Metrics available at ${url}${this.normalizePath(this.config.metrics.path, this.config.metrics.withGlobalPrefix)}`);
1297
+ }
1298
+ if (this.config.openApi?.enable) {
1299
+ logger.getLogger().info(`API docs available at ${url}${this.normalizePath(this.config.openApi.mountPath, this.config.openApi.withGlobalPrefix)}`);
1300
+ }
1301
+ if (this.server) await this.runHook("afterStart", this.server);
1302
+ resolve(this.server);
1303
+ }
1304
+ ];
1305
+ if (this.config.https) {
1306
+ const httpsOptions = {
1307
+ ...this.config.https,
1308
+ key: fs__default.default.readFileSync(this.config.https.key),
1309
+ cert: fs__default.default.readFileSync(this.config.https.cert)
1310
+ };
1311
+ if (this.config.https.ca) {
1312
+ httpsOptions.ca = fs__default.default.readFileSync(this.config.https.ca);
1313
+ }
1314
+ if (this.config.https.passphrase) {
1315
+ httpsOptions.passphrase = this.config.https.passphrase;
1316
+ }
1317
+ this.server = https__default.default.createServer(httpsOptions, this.app).listen(...listenArgs);
1318
+ } else {
1319
+ this.server = this.app.listen(...listenArgs);
1320
+ }
1321
+ this.server.on("connection", (conn) => {
1322
+ this.connections.add(conn);
1323
+ conn.on("close", () => this.connections.delete(conn));
1324
+ });
1325
+ this.server.on("error", (err) => {
1326
+ logger.getLogger().error({
1327
+ err
1328
+ }, "Server failed to start");
1329
+ reject(err);
1330
+ });
1331
+ } catch (error) {
1332
+ reject(error);
1333
+ }
1334
+ });
1335
+ }
1336
+ /**
1337
+ * Stop the HTTP server gracefully.
1338
+ *
1339
+ * This method:
1340
+ * - Executes beforeStop hooks
1341
+ * - Stops accepting new connections
1342
+ * - Waits for existing connections to finish
1343
+ * - Closes the server
1344
+ * - Executes afterStop hooks
1345
+ * - Logs shutdown information
1346
+ *
1347
+ * Graceful shutdown ensures:
1348
+ * - No requests are dropped
1349
+ * - Resources are properly cleaned up
1350
+ * - Monitoring systems are notified
1351
+ */
1352
+ async stop(force = false) {
1353
+ if (!this.server) {
1354
+ logger.getLogger().warn("Stop called but server is not running");
1355
+ return;
1356
+ }
1357
+ if (this.isShuttingDown) {
1358
+ logger.getLogger().warn("Stop called while shutdown is already in progress");
1359
+ return;
1360
+ }
1361
+ this.isShuttingDown = true;
1362
+ await this.runHook("beforeStop", this.server);
1363
+ const shutdownTimeout = 1e4;
1364
+ const serverClosePromise = new Promise((resolve, reject) => {
1365
+ this.server.close(async (err) => {
1366
+ if (err) {
1367
+ logger.getLogger().error({
1368
+ err
1369
+ }, "Error while closing server");
1370
+ reject(err);
1371
+ return;
1372
+ }
1373
+ this.server = null;
1374
+ this.isShuttingDown = false;
1375
+ logger.getLogger().info("Server stopped gracefully");
1376
+ await this.runHook("afterStop");
1377
+ resolve();
1378
+ });
1379
+ });
1380
+ const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(new Error("Shutdown timeout")), shutdownTimeout));
1381
+ try {
1382
+ await Promise.race([
1383
+ serverClosePromise,
1384
+ timeoutPromise
1385
+ ]);
1386
+ } catch (err) {
1387
+ logger.getLogger().error({
1388
+ err
1389
+ }, "Graceful shutdown timed out");
1390
+ if (force) {
1391
+ logger.getLogger().warn("Forcing connection destroy due to shutdown timeout");
1392
+ }
1393
+ } finally {
1394
+ await this.destroyConnections();
1395
+ }
1396
+ }
1397
+ /**
1398
+ * Enable graceful shutdown on OS signals for production deployment.
1399
+ *
1400
+ * This is essential for:
1401
+ * - Container orchestration (Docker, Kubernetes)
1402
+ * - Process managers (PM2, systemd)
1403
+ * - Load balancer health checks
1404
+ * - Zero-downtime deployments
1405
+ *
1406
+ * @param signals Array of process signals to listen for (default: SIGINT, SIGTERM)
1407
+ */
1408
+ enableGracefulShutdown(signals = [
1409
+ "SIGINT",
1410
+ "SIGTERM"
1411
+ ]) {
1412
+ signals.forEach((signal) => {
1413
+ process.on(signal, async () => {
1414
+ logger.getLogger().info(`Received ${signal}, initiating graceful shutdown...`);
1415
+ try {
1416
+ await this.stop();
1417
+ process.exit(0);
1418
+ } catch (err) {
1419
+ logger.getLogger().error({
1420
+ err
1421
+ }, "Error during graceful shutdown, forcing stop...");
1422
+ try {
1423
+ await this.stop(true);
1424
+ process.exit(1);
1425
+ } catch (forceError) {
1426
+ logger.getLogger().fatal({
1427
+ forceError
1428
+ }, "Forced shutdown failed, exiting hard");
1429
+ process.exit(1);
1430
+ }
1431
+ }
1432
+ });
1433
+ });
1434
+ return this;
1435
+ }
1436
+ /**
1437
+ * Set an externally created base router.
1438
+ * This will override the internal rootRouter.
1439
+ */
1440
+ setBaseRouter(router) {
1441
+ this.externalRouter = router;
1442
+ return this;
1443
+ }
1444
+ /**
1445
+ * Create and register a new router (only used if not injecting one externally - use `setBaseRouter` instead).
1446
+ */
1447
+ createRouter(prefix = "") {
1448
+ const router = express__default.default.Router();
1449
+ const path = this.normalizePath(prefix, true);
1450
+ this.rootRouter.use(path, router);
1451
+ return router;
1452
+ }
1453
+ /**
1454
+ * Register a new route handler with support for multiple HTTP methods.
1455
+ * The route is automatically registered under the globalPrefix if set.
1456
+ *
1457
+ * @param methods Array of HTTP methods (get, post, put, delete, etc.)
1458
+ * @param path Route path with Express path patterns support
1459
+ * @param handlers One or more Express request handlers (middleware + final handler)
1460
+ * @returns This instance for method chaining
1461
+ */
1462
+ registerRoute(methods, path, ...handlers) {
1463
+ const fullPath = this.normalizePath(path, true);
1464
+ const methodMap = {
1465
+ get: this.app.get.bind(this.app),
1466
+ post: this.app.post.bind(this.app),
1467
+ put: this.app.put.bind(this.app),
1468
+ delete: this.app.delete.bind(this.app),
1469
+ patch: this.app.patch.bind(this.app),
1470
+ options: this.app.options.bind(this.app),
1471
+ head: this.app.head.bind(this.app)
1472
+ };
1473
+ methods.forEach((m) => {
1474
+ const fn = methodMap[m];
1475
+ if (fn) {
1476
+ fn(fullPath, ...handlers);
1477
+ } else {
1478
+ throw new Error(`Unsupported HTTP method: ${m}`);
1479
+ }
1480
+ });
1481
+ return this;
1482
+ }
1483
+ /**
1484
+ * Register custom middleware with optional path restriction.
1485
+ *
1486
+ * Use this for:
1487
+ * - Adding authentication to specific routes
1488
+ * - Custom logging or validation
1489
+ * - Request transformation
1490
+ * - Third-party middleware integration
1491
+ *
1492
+ * @param path Optional path prefix or middleware function if no path
1493
+ * @param middleware Middleware handler (required if path is provided)
1494
+ * @returns This instance for method chaining
1495
+ */
1496
+ registerMiddleware(path, middleware) {
1497
+ if (typeof path === "string") {
1498
+ const normalizedPath = this.normalizePath(path);
1499
+ if (normalizedPath) {
1500
+ this.app.use(normalizedPath, middleware);
1501
+ } else {
1502
+ this.app.use(middleware);
1503
+ }
1504
+ } else {
1505
+ this.app.use(path);
1506
+ }
1507
+ return this;
1508
+ }
1509
+ /**
1510
+ * Register one or more middleware functions to be applied globally.
1511
+ * This is a simpler alternative to registerMiddleware when you just want
1512
+ * to add middleware without path restrictions.
1513
+ *
1514
+ * @param middlewares One or more Express middleware functions
1515
+ * @returns This instance for method chaining
1516
+ */
1517
+ useMiddleware(...middlewares) {
1518
+ middlewares.forEach((middleware) => {
1519
+ this.app.use(middleware);
1520
+ });
1521
+ return this;
1522
+ }
1523
+ /**
1524
+ * Get Prometheus registry (to add custom counters/histograms)
1525
+ *
1526
+ * @return {*} {client.Registry}
1527
+ */
1528
+ getMetricsRegistry() {
1529
+ if (!this.config.metrics?.enable) {
1530
+ logger.getLogger().warn("Metrics are not enabled in the server configuration \nPlease enable metrics to use this feature.");
1531
+ }
1532
+ return this.register;
1533
+ }
1534
+ /**
1535
+ * Get server configuration
1536
+ *
1537
+ * @return {*} {ServerConfig}
1538
+ */
1539
+ getConfig() {
1540
+ return this.config;
1541
+ }
1542
+ /**
1543
+ * Wait until server initialization (middleware + routes) has completed.
1544
+ * Useful for integration tests that inspect app before starting.
1545
+ */
1546
+ async waitUntilReady() {
1547
+ await this.initPromise;
1548
+ }
1549
+ normalizePath(path, withGlobalPrefix = false) {
1550
+ const sanitize = /* @__PURE__ */ __name((p) => {
1551
+ return "/" + p.trim().replace(/^\/+/, "").replace(/\/{2,}/g, "/").replace(/\/+$/, "");
1552
+ }, "sanitize");
1553
+ const prefix = withGlobalPrefix && this.globalPrefix ? sanitize(this.globalPrefix) : "";
1554
+ if (typeof path !== "string" || !path.trim()) {
1555
+ return prefix || "/";
1556
+ }
1557
+ return sanitize(prefix + "/" + path);
1558
+ }
1559
+ normalizeRouteForMetrics(req, res) {
1560
+ if (req?.route?.path) {
1561
+ return req.route.path;
1562
+ }
1563
+ if (res.statusCode === 404) return "/404";
1564
+ const path = (req.path || "unknown").split("?")[0];
1565
+ return path.replace(/\/[0-9]+/g, "/:id").replace(/\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g, "/:uuid");
1566
+ }
1567
+ /**
1568
+ * Destroy all active connections (gracefully if possible).
1569
+ * If a connection does not close cleanly, it will be force-destroyed.
1570
+ */
1571
+ async destroyConnections() {
1572
+ const total = this.connections.size;
1573
+ if (total === 0) {
1574
+ logger.getLogger().debug("No active connections to close");
1575
+ return;
1576
+ }
1577
+ const timeoutMs = 5e3;
1578
+ await Promise.race([
1579
+ Promise.all(Array.from(this.connections).map((conn) => new Promise((resolve) => {
1580
+ conn.end(() => {
1581
+ if (!conn.destroyed) conn.destroy();
1582
+ resolve();
1583
+ });
1584
+ conn.on("error", () => {
1585
+ conn.destroy();
1586
+ resolve();
1587
+ });
1588
+ }))),
1589
+ new Promise((resolve) => setTimeout(resolve, timeoutMs))
1590
+ ]);
1591
+ this.connections.clear();
1592
+ logger.getLogger().info(`Closed ${total} active connections`);
1593
+ }
1594
+ async validateHttpsFiles() {
1595
+ if (!await fs.fileExists(this.config.https.key)) {
1596
+ const msg = `HTTPS key file not found: ${this.config.https.key}`;
1597
+ logger.getLogger().error(msg);
1598
+ throw new Error(msg);
1599
+ }
1600
+ if (!await fs.fileExists(this.config.https.cert)) {
1601
+ const msg = `HTTPS cert file not found: ${this.config.https.cert}`;
1602
+ logger.getLogger().error(msg);
1603
+ throw new Error(msg);
1604
+ }
1605
+ if (this.config.https.ca && !await fs.fileExists(this.config.https.ca)) {
1606
+ const msg = `HTTPS CA file not found: ${this.config.https.ca}`;
1607
+ logger.getLogger().error(msg);
1608
+ throw new Error(msg);
1609
+ }
1610
+ }
1611
+ isBuiltServerConfig(config) {
1612
+ if (config?.[BUILD_MARKER]) {
1613
+ return true;
1614
+ }
1615
+ return false;
1616
+ }
1617
+ throwDependancyError(packageName, msg) {
1618
+ logger.getLogger().error({
1619
+ command: `npm install ${packageName}`
1620
+ }, msg || DependencyErrors[packageName]);
1621
+ throw new Error(msg || DependencyErrors[packageName]);
1622
+ }
1623
+ };
1624
+
1625
+ exports.DependencyErrors = DependencyErrors;
1626
+ exports.ExpressServer = ExpressServer;
1627
+ exports.ServerConfigBuilder = ServerConfigBuilder;