@catbee/utils 1.1.0 → 2.0.0-next.1

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